List of usage examples for java.lang Thread start
public synchronized void start()
From source file:io.seldon.importer.articles.GeneralItemAttributesImporter.java
/** * @param args/*from w w w . ja v a 2s . c om*/ * @throws InterruptedException * @throws FileNotFoundException */ public static void main(String[] args) throws InterruptedException, FileNotFoundException { FailFast failFast = new FailFast(Thread.currentThread()); { // Fail Fast thread Thread fail_fast_thread = new Thread(failFast); fail_fast_thread.setName("fail_fast_thread"); fail_fast_thread.start(); } try { Args.parse(GeneralItemAttributesImporter.class, args); UrlFetcher urlFetcher = null; { // setup the correct UrlFetcher if (jsSupport) { urlFetcher = new JsSupporedUrlFetcher(httpGetTimeout); } else { urlFetcher = new SimpleUrlFetcher(httpGetTimeout); } } { // Determine opMode by checking for urlFile if (urlFile != null) { opMode = OperationMode.OPERATION_MODE_FILE_IMPORTER; } } { // setup the attribute_detail_list attribute_detail_list = getAttributeDetailList(attributesConfigFile); } if (testUrl != null) { test_url_and_exit(urlFetcher, testUrl); } DefaultApiClient client = new DefaultApiClient(apiUrl, consumerKey, consumerSecret, API_TIMEOUT); GeneralItemAttributesImporter fixer = new GeneralItemAttributesImporter(client); fixer.setFailFast(failFast); fixer.run(urlFetcher); } catch (IllegalArgumentException e) { e.printStackTrace(); Args.usage(GeneralItemAttributesImporter.class); } catch (Exception e) { e.printStackTrace(); Args.usage(GeneralItemAttributesImporter.class); } }
From source file:ffx.numerics.fft.Complex3DCuda.java
/** * <p>/* w w w. j a v a 2s . co m*/ * main</p> * * @param args an array of {@link java.lang.String} objects. * @throws java.lang.Exception if any. */ public static void main(String[] args) throws Exception { int dimNotFinal = 64; int reps = 10; if (args != null) { try { dimNotFinal = Integer.parseInt(args[0]); if (dimNotFinal < 1) { dimNotFinal = 64; } reps = Integer.parseInt(args[1]); if (reps < 1) { reps = 10; } } catch (Exception e) { } } final int dim = dimNotFinal; System.out.println(String.format( " Initializing a %d cubed grid.\n" + " The best timing out of %d repititions will be used.", dim, reps)); final int dimCubed = dim * dim * dim; /** * Create an array to save the initial input and result. */ double orig[] = new double[dimCubed]; double answer[] = new double[dimCubed]; double data[] = new double[dimCubed * 2]; double recip[] = new double[dimCubed]; Random random = new Random(1); int index = 0; for (int k = 0; k < dim; k++) { for (int j = 0; j < dim; j++) { for (int i = 0; i < dim; i++) { orig[index] = random.nextDouble(); //recip[index] = orig[index]; recip[index] = 1.0; index++; } } } Complex3D complex3D = new Complex3D(dim, dim, dim); Complex3DParallel complex3DParallel = new Complex3DParallel(dim, dim, dim, new ParallelTeam(), IntegerSchedule.fixed()); complex3DParallel.setRecip(recip); Complex3DCuda complex3DCUDA = new Complex3DCuda(dim, dim, dim); Thread cudaThread = new Thread(complex3DCUDA); cudaThread.setPriority(Thread.MAX_PRIORITY); cudaThread.start(); complex3DCUDA.setRecip(recip); double toSeconds = 0.000000001; long parTime = Long.MAX_VALUE; long seqTime = Long.MAX_VALUE; long clTime = Long.MAX_VALUE; complex3D.setRecip(recip); for (int i = 0; i < reps; i++) { for (int j = 0; j < dimCubed; j++) { data[j * 2] = orig[j]; data[j * 2 + 1] = 0.0; } long time = System.nanoTime(); //complex3D.convolution(data); complex3D.fft(data); time = (System.nanoTime() - time); System.out.println(String.format(" %2d Sequential: %8.3f", i + 1, toSeconds * time)); if (time < seqTime) { seqTime = time; } } for (int j = 0; j < dimCubed; j++) { answer[j] = data[j * 2]; } for (int i = 0; i < reps; i++) { for (int j = 0; j < dimCubed; j++) { data[j * 2] = orig[j]; data[j * 2 + 1] = 0.0; } long time = System.nanoTime(); //complex3DParallel.convolution(data); complex3DParallel.fft(data); time = (System.nanoTime() - time); System.out.println(String.format(" %2d Parallel: %8.3f", i + 1, toSeconds * time)); if (time < parTime) { parTime = time; } } double maxError = Double.MIN_VALUE; double rmse = 0.0; for (int i = 0; i < dimCubed; i++) { double error = Math.abs(answer[i] - data[2 * i]); if (error > maxError) { maxError = error; } rmse += error * error; } rmse /= dimCubed; rmse = Math.sqrt(rmse); logger.info(String.format(" Parallel RMSE: %12.10f, Max: %12.10f", rmse, maxError)); DoubleBuffer cudaBuffer = complex3DCUDA.getDoubleBuffer(); for (int i = 0; i < reps; i++) { for (int j = 0; j < dimCubed; j++) { // data[j * 2] = orig[j]; // data[j * 2 + 1] = 0.0; cudaBuffer.put(j * 2, orig[j]); cudaBuffer.put(j * 2 + 1, 0.0); } long time = System.nanoTime(); //complex3DCUDA.convolution(data); complex3DCUDA.fft(data); time = (System.nanoTime() - time); System.out.println(String.format(" %2d CUDA: %8.3f", i + 1, toSeconds * time)); if (time < clTime) { clTime = time; } } maxError = Double.MIN_VALUE; double avg = 0.0; rmse = 0.0; for (int i = 0; i < dimCubed; i++) { double error = Math.abs(answer[i] - cudaBuffer.get(2 * i)); // double error = Math.abs(answer[i] / dimCubed - data[2 * i]); avg += error; if (error > maxError) { maxError = error; } rmse += error * error; } rmse /= dimCubed; avg /= dimCubed; rmse = Math.sqrt(rmse); logger.info(String.format(" CUDA RMSE: %12.10f, Max: %12.10f, Avg: %12.10f", rmse, maxError, avg)); complex3DCUDA.free(); complex3DCUDA = null; System.out.println(String.format(" Best Sequential Time: %8.3f", toSeconds * seqTime)); System.out.println(String.format(" Best Parallel Time: %8.3f", toSeconds * parTime)); System.out.println(String.format(" Best CUDA Time: %8.3f", toSeconds * clTime)); System.out.println(String.format(" Parallel Speedup: %15.5f", (double) seqTime / parTime)); System.out.println(String.format(" CUDA Speedup: %15.5f", (double) seqTime / clTime)); }
From source file:com.cic.datacrawl.ui.Main.java
/** * Main entry point. Creates a debugger attached to a Rhino * {@link com.cic.datacrawl.ui.shell.Shell} shell session. *///w w w . j a v a2 s. c o m public static void main(final String[] args) { if (System.getProperties().get("os.name").toString().toLowerCase().indexOf("linux") >= 0) System.setProperty("sun.awt.xembedserver", "true"); try { String path = null; boolean reflash = true; if (args != null && args.length > 0) { if (args[0].equalsIgnoreCase("-h")) { System.out.println("Command Format: \n" + "\t%JAVA_HOME%\\BIN\\JAVA -jar homepageCatcher.jar " + "[-d config path]\n" + "\t%JAVA_HOME%\\BIN\\JAVA -jar homepageCatcher.jar " + "[-d config path_1;path_2;....;path_n]\n"); } int pathIndex = ArrayUtils.indexOf(args, "-d"); if (pathIndex >= 0) { try { path = args[pathIndex + 1]; File f = new File(path); if (!f.exists()) { LOG.warn("Invalid path of configuration. " + "Using default configuration."); } } catch (Throwable e) { LOG.warn("Invalid path of configuration. " + "Using default configuration."); } } // int reflashIndex = ArrayUtils.indexOf(args, "-r"); // // reflash = new Boolean(args[reflashIndex + 1]).booleanValue(); } if (path == null || path.trim().length() == 0) path = Config.INSTALL_PATH + File.separator + "config" + File.separator + "beans"; LOG.debug("Config Path: \"" + path + "\""); // ?IOC // ???? // ? ApplicationContext.initialiaze(path, reflash); System.setProperty(ApplicationContext.CONFIG_PATH, path); // js??? InitializerRegister.getInstance().execute(); // ??? //VerifyCodeInputDialog.init(); // ?? //initTestData(); // ?GUI Thread thread = new Thread(new Runnable() { @Override public void run() { startupGUI(args); } }); thread.setName("UI_Thread"); thread.start(); } catch (Throwable e) { LOG.error(e.getMessage(), e); } }
From source file:SyncExecExample.java
public static void main(String[] args) { final Display display = new Display(); Shell shell = new Shell(display); final Runnable print = new Runnable() { public void run() { System.out.println("Print from thread: \t" + Thread.currentThread().getName()); }//from www . j a v a 2s . c o m }; final Thread applicationThread = new Thread("applicationThread") { public void run() { System.out.println("Hello from thread: \t" + Thread.currentThread().getName()); display.syncExec(print); System.out.println("Bye from thread: \t" + Thread.currentThread().getName()); } }; shell.setText("syncExec Example"); shell.setSize(300, 100); Button button = new Button(shell, SWT.CENTER); button.setText("Click to start"); button.setBounds(shell.getClientArea()); button.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { } public void widgetSelected(SelectionEvent e) { applicationThread.start(); } }); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) {// If no more entries in event queue display.sleep(); } } display.dispose(); }
From source file:com.weibo.wesync.client.NHttpClient2.java
public static void main(String[] args) throws Exception { RSAPublicKey publicKey = RSAEncrypt.loadPublicKey("D:\\weibo\\meyou_gw\\conf\\public.pem"); // /*from w w w . j av a 2 s.c o m*/ byte[] cipher = RSAEncrypt.encrypt(publicKey, password.getBytes()); password = RSAEncrypt.toHexString(cipher); // HTTP parameters for the client HttpParams params = new SyncBasicHttpParams(); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000) .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true); // Create HTTP protocol processing chain HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Use standard client-side protocol interceptors new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); // Create client-side HTTP protocol handler HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor(); // Create client-side I/O event dispatch final IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler, params); // Create client-side I/O reactor IOReactorConfig config = new IOReactorConfig(); config.setIoThreadCount(1); final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(config); // Create HTTP connection pool BasicNIOConnPool pool = new BasicNIOConnPool(ioReactor, params); // Limit total number of connections to just two pool.setDefaultMaxPerRoute(2); pool.setMaxTotal(1); // Run the I/O reactor in a separate thread Thread t = new Thread(new Runnable() { public void run() { try { // Ready to go! ioReactor.execute(ioEventDispatch); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException e) { System.err.println("I/O error: " + e.getMessage()); } System.out.println("Shutdown"); } }); // Start the client thread t.start(); // Create HTTP requester // HttpAsyncRequester requester = new HttpAsyncRequester( // httpproc, new DefaultConnectionReuseStrategy(), params); // Execute HTTP GETs to the following hosts and HttpHost[] targets = new HttpHost[] { // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), new HttpHost("123.125.106.28", 8082, "http") }; final CountDownLatch latch = new CountDownLatch(targets.length); int callbackId = 0; for (int i = 0; i < 1; i++) { for (final HttpHost target : targets) { BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/wesync"); // String usrpwd = Base64.encodeBase64String((username + ":" + password).getBytes()); // request.setHeader("authorization", "Basic " + usrpwd); request.setHeader("uid", "2565640713"); Meyou.MeyouPacket packet = null; if (callbackId == 0) { packet = Meyou.MeyouPacket.newBuilder().setCallbackId(String.valueOf(callbackId++)) .setSort(MeyouSort.notice).build(); } else { packet = Meyou.MeyouPacket.newBuilder().setCallbackId(String.valueOf(callbackId++)) .setSort(MeyouSort.wesync).build(); } ByteArrayEntity entity = new ByteArrayEntity(packet.toByteArray()); request.setEntity(entity); // BasicHttpRequest request = new BasicHttpRequest("GET", "/test.html"); System.out.println("send ..."); HttpAsyncRequester requester = new HttpAsyncRequester(httpproc, new DefaultConnectionReuseStrategy(), params); requester.execute(new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(), pool, new BasicHttpContext(), // Handle HTTP response from a callback new FutureCallback<HttpResponse>() { public void completed(final HttpResponse response) { StatusLine status = response.getStatusLine(); int code = status.getStatusCode(); if (code == 200) { try { latch.countDown(); DataInputStream in; in = new DataInputStream(response.getEntity().getContent()); int packetLength = in.readInt(); int start = 0; while (packetLength > 0) { ByteArrayOutputStream outstream = new ByteArrayOutputStream( packetLength); byte[] buffer = new byte[1024]; int len = 0; while (start < packetLength && (len = in.read(buffer, start, packetLength)) > 0) { outstream.write(buffer, 0, len); start += len; } Meyou.MeyouPacket packet0 = Meyou.MeyouPacket .parseFrom(outstream.toByteArray()); System.out.println(target + "->" + packet0); if ((len = in.read(buffer, start, 4)) > 0) { packetLength = Util.readPacketLength(buffer); } else { break; } } } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { System.out.println("error code=" + code + "|" + status.getReasonPhrase()); } } public void failed(final Exception ex) { latch.countDown(); System.out.println(target + "->" + ex); } public void cancelled() { latch.countDown(); System.out.println(target + " cancelled"); } }); Thread.sleep((long) (Math.random() * 10000)); } } // latch.await(); // System.out.println("Shutting down I/O reactor"); // ioReactor.shutdown(); // System.out.println("Done"); }
From source file:com.griddynamics.jagger.JaggerLauncher.java
public static void main(String[] args) throws Exception { Thread memoryMonitorThread = new Thread("memory-monitor") { @Override/*from w w w .ja v a2 s . c om*/ public void run() { for (;;) { try { log.info("Memory info: totalMemory={}, freeMemory={}", Runtime.getRuntime().totalMemory(), Runtime.getRuntime().freeMemory()); Thread.sleep(60000); } catch (InterruptedException e) { throw new RuntimeException(e); } } } }; memoryMonitorThread.setDaemon(true); memoryMonitorThread.start(); String pid = ManagementFactory.getRuntimeMXBean().getName(); System.out.println(String.format("PID:%s", pid)); Properties props = System.getProperties(); for (Map.Entry<Object, Object> prop : props.entrySet()) { log.info("{}: '{}'", prop.getKey(), prop.getValue()); } log.info(""); URL directory = new URL("file:" + System.getProperty("user.dir") + "/"); loadBootProperties(directory, args[0], environmentProperties); log.debug("Bootstrap properties:"); for (String propName : environmentProperties.stringPropertyNames()) { log.debug(" {}={}", propName, environmentProperties.getProperty(propName)); } String[] roles = environmentProperties.getProperty(ROLES).split(","); Set<String> rolesSet = Sets.newHashSet(roles); if (rolesSet.contains(Role.COORDINATION_SERVER.toString())) { launchCoordinationServer(directory); } if (rolesSet.contains(Role.HTTP_COORDINATION_SERVER.toString())) { launchCometdCoordinationServer(directory); } if (rolesSet.contains(Role.RDB_SERVER.toString())) { launchRdbServer(directory); } if (rolesSet.contains(Role.MASTER.toString())) { launchMaster(directory); } if (rolesSet.contains(Role.KERNEL.toString())) { launchKernel(directory); } if (rolesSet.contains(Role.REPORTER.toString())) { launchReporter(directory); } LaunchManager launchManager = builder.build(); int result = launchManager.launch(); System.exit(result); }
From source file:collabedit.Telnet.java
/*** * Main for the TelnetClientExample./*from w ww.j av a 2 s . co m*/ ***/ public static void main(String[] args) throws Exception { FileOutputStream fout = null; String remoteip = "23.102.136.121"; int remoteport = 8888; try { fout = new FileOutputStream("spy.log", true); } catch (IOException e) { System.err.println("Exception while opening the spy file: " + e.getMessage()); } tc = new TelnetClient(); TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false); EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false); SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true); try { tc.addOptionHandler(ttopt); tc.addOptionHandler(echoopt); tc.addOptionHandler(gaopt); } catch (InvalidTelnetOptionException e) { System.err.println("Error registering option handlers: " + e.getMessage()); } try { tc.connect(remoteip, remoteport); Thread reader = new Thread(new Telnet()); tc.registerNotifHandler(new Telnet()); System.out.println("TelnetClientExample"); System.out.println("Type AYT to send an AYT telnet command"); System.out.println("Type OPT to print a report of status of options (0-24)"); System.out.println("Type REGISTER to register a new SimpleOptionHandler"); System.out.println("Type UNREGISTER to unregister an OptionHandler"); System.out.println("Type SPY to register the spy (connect to port 3333 to spy)"); System.out.println("Type UNSPY to stop spying the connection"); reader.start(); OutputStream outstr = tc.getOutputStream(); byte[] buff = new byte[1024]; int ret_read = 0; /* * do { try { ret_read = System.in.read(buff); if (ret_read > 0) { * if ((new String(buff, 0, ret_read)) .startsWith("AYT")) { try { * System.out.println("Sending AYT"); * * System.out.println("AYT response:" + tc.sendAYT(5000)); } catch * (IOException e) { System.err * .println("Exception waiting AYT response: " + e.getMessage()); } * } else if ((new String(buff, 0, ret_read)) .startsWith("OPT")) { * System.out.println("Status of options:"); for (int ii = 0; ii < * 25; ii++) { System.out.println("Local Option " + ii + ":" + * tc.getLocalOptionState(ii) + " Remote Option " + ii + ":" + * tc.getRemoteOptionState(ii)); } } else if ((new String(buff, 0, * ret_read)) .startsWith("REGISTER")) { StringTokenizer st = new * StringTokenizer( new String(buff)); try { st.nextToken(); int * opcode = Integer.parseInt(st .nextToken()); boolean initlocal = * Boolean.parseBoolean(st .nextToken()); boolean initremote = * Boolean .parseBoolean(st.nextToken()); boolean acceptlocal = * Boolean .parseBoolean(st.nextToken()); boolean acceptremote = * Boolean .parseBoolean(st.nextToken()); SimpleOptionHandler * opthand = new SimpleOptionHandler( opcode, initlocal, initremote, * acceptlocal, acceptremote); tc.addOptionHandler(opthand); } catch * (Exception e) { if (e instanceof InvalidTelnetOptionException) { * System.err .println("Error registering option: " + * e.getMessage()); } else { System.err * .println("Invalid REGISTER command."); System.err .println( * "Use REGISTER optcode initlocal initremote acceptlocal acceptremote" * ); System.err .println("(optcode is an integer.)"); System.err * .println * ("(initlocal, initremote, acceptlocal, acceptremote are boolean)" * ); } } } else if ((new String(buff, 0, ret_read)) * .startsWith("UNREGISTER")) { StringTokenizer st = new * StringTokenizer( new String(buff)); try { st.nextToken(); int * opcode = (new Integer(st.nextToken())) .intValue(); * tc.deleteOptionHandler(opcode); } catch (Exception e) { if (e * instanceof InvalidTelnetOptionException) { System.err * .println("Error unregistering option: " + e.getMessage()); } else * { System.err .println("Invalid UNREGISTER command."); System.err * .println("Use UNREGISTER optcode"); System.err * .println("(optcode is an integer)"); } } } else if ((new * String(buff, 0, ret_read)) .startsWith("SPY")) { * tc.registerSpyStream(fout); } else if ((new String(buff, 0, * ret_read)) .startsWith("UNSPY")) { tc.stopSpyStream(); } else { * post("hi"); } } } catch (IOException e) { * System.err.println("Exception while reading keyboard:" + * e.getMessage()); end_loop = true; } } while ((ret_read > 0) && * (end_loop == false)); */ } catch (IOException e) { System.err.println("Exception while connecting:" + e.getMessage()); System.exit(1); } }
From source file:com.groupC1.control.network.TelnetClientExample.java
/*** * Main for the TelnetClient.//from w ww .jav a 2s . co m ***/ public static void main(String[] args) throws Exception { args = new String[] { "169.254.0.10", "10001" }; FileOutputStream fout = null; if (args.length < 1) { System.err.println("Usage: TelnetClientExample1 <remote-ip> [<remote-port>]"); System.exit(1); } String remoteip = args[0]; int remoteport; if (args.length > 1) { remoteport = (new Integer(args[1])).intValue(); } else { remoteport = 23; } try { fout = new FileOutputStream("spy.log", true); } catch (IOException e) { System.err.println("Exception while opening the spy file: " + e.getMessage()); } tc = new org.apache.commons.net.telnet.TelnetClient(); TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false); EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false); SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true); try { tc.addOptionHandler(ttopt); tc.addOptionHandler(echoopt); tc.addOptionHandler(gaopt); } catch (InvalidTelnetOptionException e) { System.err.println("Error registering option handlers: " + e.getMessage()); } while (true) { boolean end_loop = false; try { tc.connect(remoteip, remoteport); Thread reader = new Thread(new TelnetClientExample()); tc.registerNotifHandler(new TelnetClientExample()); System.out.println("TelnetClient"); System.out.println("Type AYT to send an AYT telnet command"); System.out.println("Type OPT to print a report of status of options (0-24)"); System.out.println("Type REGISTER to register a new SimpleOptionHandler"); System.out.println("Type UNREGISTER to unregister an OptionHandler"); System.out.println("Type SPY to register the spy (connect to port 3333 to spy)"); System.out.println("Type UNSPY to stop spying the connection"); reader.start(); OutputStream outstr = tc.getOutputStream(); byte[] buff = new byte[1024]; int ret_read = 0; do { try { ret_read = System.in.read(buff); if (ret_read > 0) { if ((new String(buff, 0, ret_read)).startsWith("AYT")) { try { System.out.println("Sending AYT"); System.out.println("AYT response:" + tc.sendAYT(5000)); } catch (IOException e) { System.err.println("Exception waiting AYT response: " + e.getMessage()); } } else if ((new String(buff, 0, ret_read)).startsWith("OPT")) { System.out.println("Status of options:"); for (int ii = 0; ii < 25; ii++) { System.out.println("Local Option " + ii + ":" + tc.getLocalOptionState(ii) + " Remote Option " + ii + ":" + tc.getRemoteOptionState(ii)); } } else if ((new String(buff, 0, ret_read)).startsWith("REGISTER")) { StringTokenizer st = new StringTokenizer(new String(buff)); try { st.nextToken(); int opcode = Integer.parseInt(st.nextToken()); boolean initlocal = Boolean.parseBoolean(st.nextToken()); boolean initremote = Boolean.parseBoolean(st.nextToken()); boolean acceptlocal = Boolean.parseBoolean(st.nextToken()); boolean acceptremote = Boolean.parseBoolean(st.nextToken()); SimpleOptionHandler opthand = new SimpleOptionHandler(opcode, initlocal, initremote, acceptlocal, acceptremote); tc.addOptionHandler(opthand); } catch (Exception e) { if (e instanceof InvalidTelnetOptionException) { System.err.println("Error registering option: " + e.getMessage()); } else { System.err.println("Invalid REGISTER command."); System.err.println( "Use REGISTER optcode initlocal initremote acceptlocal acceptremote"); System.err.println("(optcode is an integer.)"); System.err.println( "(initlocal, initremote, acceptlocal, acceptremote are boolean)"); } } } else if ((new String(buff, 0, ret_read)).startsWith("UNREGISTER")) { StringTokenizer st = new StringTokenizer(new String(buff)); try { st.nextToken(); int opcode = (new Integer(st.nextToken())).intValue(); tc.deleteOptionHandler(opcode); } catch (Exception e) { if (e instanceof InvalidTelnetOptionException) { System.err.println("Error unregistering option: " + e.getMessage()); } else { System.err.println("Invalid UNREGISTER command."); System.err.println("Use UNREGISTER optcode"); System.err.println("(optcode is an integer)"); } } } else if ((new String(buff, 0, ret_read)).startsWith("SPY")) { tc.registerSpyStream(fout); } else if ((new String(buff, 0, ret_read)).startsWith("UNSPY")) { tc.stopSpyStream(); } else { try { outstr.write(buff, 0, ret_read); outstr.flush(); } catch (IOException e) { end_loop = true; } } } } catch (IOException e) { System.err.println("Exception while reading keyboard:" + e.getMessage()); end_loop = true; } } while ((ret_read > 0) && (end_loop == false)); try { tc.disconnect(); } catch (IOException e) { System.err.println("Exception while connecting:" + e.getMessage()); } } catch (IOException e) { System.err.println("Exception while connecting:" + e.getMessage()); System.exit(1); } } }
From source file:fr.bmartel.protocol.google.main.LaunchOauthApiServer.java
/** * The main method./*w ww . ja va 2 s . c om*/ * * @param args the arguments */ public static void main(String[] args) { webPath = ""; clientId = ""; clientSecret = ""; if (args.length == 3) { for (int i = 0; i < 3; i++) { if (args[i].toLowerCase().startsWith("webpath=")) webPath = args[i].substring(args[i].indexOf("webpath=") + "webpath=".length() + 1, args[i].length()); if (args[i].toLowerCase().startsWith("clientid=")) clientId = args[i].substring(args[i].indexOf("clientid=") + "clientid=".length() + 1, args[i].length()); if (args[i].toLowerCase().startsWith("clientsecret=")) clientSecret = args[i].substring( args[i].indexOf("clientsecret=") + "clientsecret=".length() + 1, args[i].length()); } if (webPath.equals("")) { printHelp("Error web path is missing"); return; } else if (clientId.equals("")) { printHelp("Error client Id is missing"); return; } else if (clientSecret.equals("")) { printHelp("Error client secret is missing"); return; } } else { printHelp(""); return; } // start http server HttpServer server = new HttpServer(SERVER_PORT); websocketServer = new WebsocketServer(WEBSOCKET_SERVER_PORT); websocketServer.addServerEventListener(new IClientEventListener() { @SuppressWarnings("unchecked") @Override public void onMessageReceivedFromClient(final IWebsocketClient client, String message) { JSONObject obj = (JSONObject) JSONValue.parse(message); if (obj != null && obj.containsKey(JsonConstants.API_ACTION)) { System.out.println("[API] > " + obj.toJSONString()); String action = obj.get(JsonConstants.API_ACTION).toString(); if (action != null) { if (action.equals(JsonConstants.API_REGISTRATION_STATE)) { JSONObject registrationResponse = new JSONObject(); if (calendarNotifManager != null && calendarNotifManager.getOauthRegistration() != null) { registrationResponse.put(JsonConstants.GOOGLE_OAUTH_DEVICE_CODE, calendarNotifManager.getOauthRegistration().getDeviceCode()); registrationResponse.put(JsonConstants.GOOGLE_OAUTH_EXPIRING_BEFORE, calendarNotifManager.getOauthRegistration().getExpiringBefore()); registrationResponse.put(JsonConstants.GOOGLE_OAUTH_INTERVAL, calendarNotifManager.getOauthRegistration().getInterval()); registrationResponse.put(JsonConstants.GOOGLE_OAUTH_USERCODE, calendarNotifManager.getOauthRegistration().getUserCode()); registrationResponse.put(JsonConstants.GOOGLE_OAUTH_VERIFICATION_URL, calendarNotifManager.getOauthRegistration().getVerificationUrl()); } System.out.println("[API] < " + registrationResponse.toJSONString()); client.sendMessage(registrationResponse.toJSONString()); } else if (action.equals(JsonConstants.API_TOKEN_STATE)) { JSONObject requestTokenResponse = new JSONObject(); if (calendarNotifManager != null && calendarNotifManager.getCurrentToken() != null) { requestTokenResponse.put(JsonConstants.GOOGLE_OAUTH_ACCESS_TOKEN, calendarNotifManager.getCurrentToken().getAccessToken()); requestTokenResponse.put(JsonConstants.GOOGLE_OAUTH_TOKEN_TYPE, calendarNotifManager.getCurrentToken().getTokenType()); requestTokenResponse.put(JsonConstants.GOOGLE_OAUTH_EXPIRE_IN, calendarNotifManager.getCurrentToken().getExpiresIn()); } System.out.println("[API] < " + requestTokenResponse.toJSONString()); client.sendMessage(requestTokenResponse.toJSONString()); } else if (action.equals(JsonConstants.API_REGISTRATION)) { calendarNotifManager = new CalendarNotifManager(clientId, clientSecret); calendarNotifManager.requestDeviceAuth(new IOauthDeviceResponseListener() { @Override public void onResponseReceived(OauthForDeviceResponse response) { if (response != null) { JSONObject registrationResponse = new JSONObject(); registrationResponse.put(JsonConstants.GOOGLE_OAUTH_DEVICE_CODE, response.getDeviceCode()); registrationResponse.put(JsonConstants.GOOGLE_OAUTH_EXPIRING_BEFORE, response.getExpiringBefore()); registrationResponse.put(JsonConstants.GOOGLE_OAUTH_INTERVAL, response.getInterval()); registrationResponse.put(JsonConstants.GOOGLE_OAUTH_USERCODE, response.getUserCode()); registrationResponse.put(JsonConstants.GOOGLE_OAUTH_VERIFICATION_URL, response.getVerificationUrl()); System.out.println("[API] < " + registrationResponse.toJSONString()); client.sendMessage(registrationResponse.toJSONString()); } } }); } else if (action.equals(JsonConstants.API_REQUEST_TOKEN)) { if (calendarNotifManager != null) { calendarNotifManager.requestToken(new IRequestTokenListener() { @Override public void onRequestTokenReceived(OauthToken token) { if (token != null) { JSONObject requestTokenResponse = new JSONObject(); requestTokenResponse.put(JsonConstants.GOOGLE_OAUTH_ACCESS_TOKEN, token.getAccessToken()); requestTokenResponse.put(JsonConstants.GOOGLE_OAUTH_TOKEN_TYPE, token.getTokenType()); requestTokenResponse.put(JsonConstants.GOOGLE_OAUTH_EXPIRE_IN, token.getExpiresIn()); System.out.println("[API] < " + requestTokenResponse.toJSONString()); client.sendMessage(requestTokenResponse.toJSONString()); } } @Override public void onRequestTokenError(String description) { String response = "{\"error\":\"request token error\",\"error_description\":\"" + description + "\"}"; System.out.println("[API] < " + response); client.sendMessage(response); } }); } } else if (action.equals(JsonConstants.API_REVOKE_TOKEN)) { if (calendarNotifManager != null) { calendarNotifManager.revokeToken(new IRevokeTokenListener() { @Override public void onSuccess() { System.out.println("[API] < " + "{\"revokeToken\":\"success\"}"); client.sendMessage("{\"revokeToken\":\"success\"}"); } @Override public void onError(String description) { String response = "{\"error\":\"request token error\",\"error_description\":\"" + description + "\"}"; System.out.println("[API] < " + response); client.sendMessage(response); } }); } } else if (action.equals(JsonConstants.API_USER_PROFILE)) { if (calendarNotifManager != null) { calendarNotifManager.getUserProfileManager() .getUserProfile(new IUserProfileListener() { @Override public void onSuccess(UserProfile userProfile) { if (userProfile != null) { JSONObject userProfileResponse = new JSONObject(); userProfileResponse.put(JsonConstants.GOOGLE_API_PROFILE_GENDER, userProfile.getGender()); userProfileResponse.put( JsonConstants.GOOGLE_API_PROFILE_DISPLAY_NAME, userProfile.getDisplayName()); userProfileResponse.put( JsonConstants.GOOGLE_API_PROFILE_FAMILY_NAME, userProfile.getFamilyName()); userProfileResponse.put( JsonConstants.GOOGLE_API_PROFILE_GIVEN_NAME, userProfile.getGivenName()); userProfileResponse.put( JsonConstants.GOOGLE_API_PROFILE_LANGUAGE, userProfile.getLanguage()); System.out.println( "[API] < " + userProfileResponse.toJSONString()); client.sendMessage(userProfileResponse.toJSONString()); } } @Override public void onError(String description) { String response = "{\"error\":\"request token error\",\"error_description\":\"" + description + "\"}"; System.out.println("[API] < " + response); client.sendMessage(response); } }); } } else if (action.equals(JsonConstants.API_CREATE_EVENT) && obj.containsKey(JsonConstants.API_DATE_BEGIN) && obj.containsKey(JsonConstants.API_DATE_END) && obj.containsKey(JsonConstants.API_SUMMARY)) { String dateBegin = obj.get(JsonConstants.API_DATE_BEGIN).toString(); String dateEnd = obj.get(JsonConstants.API_DATE_END).toString(); String summary = obj.get(JsonConstants.API_SUMMARY).toString(); if (calendarNotifManager != null) { calendarNotifManager.getCalendarManager().createEvent(dateBegin, dateEnd, summary, new ICreateEventListener() { @Override public void onError(String description) { String response = "{\"error\":\"request token error\",\"error_description\":\"" + description + "\"}"; System.out.println("[API] < " + response); client.sendMessage( "{\"error\":\"request token error\",\"error_description\":\"" + description + "\"}"); } @Override public void onCreateSuccess(String id) { String response = "{\"createEvent\":\"success\",\"eventId\":\"" + id + "\"}"; System.out.println("[API] < " + response); client.sendMessage(response); } }); } } else if (action.equals(JsonConstants.API_DELETE_EVENT) && obj.containsKey(JsonConstants.API_EVENT_ID)) { final String eventId = obj.get(JsonConstants.API_EVENT_ID).toString(); calendarNotifManager.getCalendarManager().deleteEvent(eventId, new IDeleteEventListener() { @Override public void onSuccess() { String response = "{\"deleteEvent\":\"success\",\"eventId\":\"" + eventId + "\"}"; System.out.println("[API] < " + response); client.sendMessage(response); } @Override public void onError(String description) { String response = "{\"error\":\"request token error\",\"error_description\":\"" + description + "\"}"; System.out.println("[API] < " + response); client.sendMessage(response); } }); } else if (action.equals(JsonConstants.API_GET_EVENTS) && obj.containsKey(JsonConstants.API_DATE_BEGIN) && obj.containsKey(JsonConstants.API_DATE_END) && obj.containsKey("searchText") && calendarNotifManager != null) { String dateBegin = obj.get(JsonConstants.API_DATE_BEGIN).toString(); String dateEnd = obj.get(JsonConstants.API_DATE_END).toString(); String searchText = obj.get(JsonConstants.API_SEARCH_TEXT).toString(); calendarNotifManager.getCalendarManager().getEventList(dateBegin, dateEnd, searchText, new IEventListListener() { @Override public void onEventListReceived(List<CalendarEvents> calendarEventList) { String response = "{\"eventList\":" + CalendarUtils .convertCalendarListToJsonArray(calendarEventList) .toJSONString() + "}"; System.out.println("[API] < " + response); client.sendMessage(response); } @Override public void onError(String description) { String response = "{\"error\":\"request token error\",\"error_description\":\"" + description + "\"}"; System.out.println("[API] < " + response); client.sendMessage(response); } }); } else if (action.equals(JsonConstants.API_SUBSCRIBE_EVENT) && obj.containsKey(JsonConstants.API_EVENT_ID) && obj.containsKey(JsonConstants.API_TIME_ABOUT_TO_START)) { String eventId = obj.get(JsonConstants.API_EVENT_ID).toString(); int timeAboutToStart = Integer .parseInt(obj.get(JsonConstants.API_TIME_ABOUT_TO_START).toString()); calendarNotifManager.getNotificationManager().subscribeEvent(eventId, timeAboutToStart, new IEventListener() { @Override public void onEventStart(String eventId, String summary) { String response = "{\"subscribedEvent\":\"" + eventId + "\",\"eventType\":\"started\",\"summary\":\"" + summary + "\"}"; System.out.println("[API] < " + response); client.sendMessage(response); } @Override public void onEventAboutToStart(String eventId, String summary) { String response = "{\"subscribedEvent\":\"" + eventId + "\",\"eventType\":\"aboutToStart\",\"summary\":\"" + summary + "\"}"; System.out.println("[API] < " + response); client.sendMessage(response); } }); } else if (action.equals(JsonConstants.API_UNSUBSCRIBE_EVENT) && obj.containsKey(JsonConstants.API_EVENT_ID)) { String eventId = obj.get(JsonConstants.API_EVENT_ID).toString(); calendarNotifManager.getNotificationManager().unsubscribeEvent(eventId); } else { System.out.println("[API] Error api target is inconsistent"); } } } } @Override public void onClientConnection(IWebsocketClient client) { System.out.println("Websocket client connected"); } @Override public void onClientClose(IWebsocketClient client) { System.out.println("Websocket client disconnected"); } }); Runnable websocketTask = new Runnable() { @Override public void run() { websocketServer.start(); } }; Thread thread = new Thread(websocketTask, "WEBSOCKET_THREAD"); thread.start(); server.addServerEventListener(new IHttpServerEventListener() { @Override public void onHttpFrameReceived(IHttpFrame httpFrame, HttpStates receptionStates, IHttpStream httpStream) { // check if http frame is OK if (receptionStates == HttpStates.HTTP_FRAME_OK) { // you can check here http frame type (response or request // frame) if (httpFrame.isHttpRequestFrame()) { // we want to send a message to client for http GET // request on page with uri /index if (httpFrame.getMethod().equals("GET") && httpFrame.getUri().equals("/gcalendar")) { String defaultPage = ""; try { defaultPage = FileUtils.readFile(webPath + "/index.html", "UTF-8"); } catch (IOException e) { e.printStackTrace(); } // return default html page for this HTTP Server httpStream.writeHttpFrame(new HttpResponseFrame(StatusCodeList.OK, new HttpVersion(1, 1), new HashMap<String, String>(), defaultPage.getBytes()) .toString().getBytes()); } else if (httpFrame.getMethod().equals("GET") && (httpFrame.getUri().endsWith(".css") || httpFrame.getUri().endsWith(".js"))) { String defaultPage = ""; try { defaultPage = FileUtils.readFile(webPath + httpFrame.getUri(), "UTF-8"); } catch (IOException e) { e.printStackTrace(); } // return default html page for this HTTP Server httpStream.writeHttpFrame(new HttpResponseFrame(StatusCodeList.OK, new HttpVersion(1, 1), new HashMap<String, String>(), defaultPage.getBytes()) .toString().getBytes()); } } } } }); server.start(); thread.interrupt(); }
From source file:examples.TelnetClientExample.java
/*** * Main for the TelnetClientExample./*from w ww . j a v a 2 s. co m*/ ***/ public static void main(String[] args) throws IOException { FileOutputStream fout = null; if (args.length < 1) { System.err.println("Usage: TelnetClientExample1 <remote-ip> [<remote-port>]"); System.exit(1); } String remoteip = args[0]; int remoteport; if (args.length > 1) { remoteport = (new Integer(args[1])).intValue(); } else { remoteport = 23; } try { fout = new FileOutputStream("spy.log", true); } catch (Exception e) { System.err.println("Exception while opening the spy file: " + e.getMessage()); } tc = new TelnetClient(); TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false); EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false); SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true); try { tc.addOptionHandler(ttopt); tc.addOptionHandler(echoopt); tc.addOptionHandler(gaopt); } catch (InvalidTelnetOptionException e) { System.err.println("Error registering option handlers: " + e.getMessage()); } while (true) { boolean end_loop = false; try { tc.connect(remoteip, remoteport); Thread reader = new Thread(new TelnetClientExample()); tc.registerNotifHandler(new TelnetClientExample()); System.out.println("TelnetClientExample"); System.out.println("Type AYT to send an AYT telnet command"); System.out.println("Type OPT to print a report of status of options (0-24)"); System.out.println("Type REGISTER to register a new SimpleOptionHandler"); System.out.println("Type UNREGISTER to unregister an OptionHandler"); System.out.println("Type SPY to register the spy (connect to port 3333 to spy)"); System.out.println("Type UNSPY to stop spying the connection"); reader.start(); OutputStream outstr = tc.getOutputStream(); byte[] buff = new byte[1024]; int ret_read = 0; do { try { ret_read = System.in.read(buff); if (ret_read > 0) { if ((new String(buff, 0, ret_read)).startsWith("AYT")) { try { System.out.println("Sending AYT"); System.out.println("AYT response:" + tc.sendAYT(5000)); } catch (Exception e) { System.err.println("Exception waiting AYT response: " + e.getMessage()); } } else if ((new String(buff, 0, ret_read)).startsWith("OPT")) { System.out.println("Status of options:"); for (int ii = 0; ii < 25; ii++) System.out.println("Local Option " + ii + ":" + tc.getLocalOptionState(ii) + " Remote Option " + ii + ":" + tc.getRemoteOptionState(ii)); } else if ((new String(buff, 0, ret_read)).startsWith("REGISTER")) { StringTokenizer st = new StringTokenizer(new String(buff)); try { st.nextToken(); int opcode = (new Integer(st.nextToken())).intValue(); boolean initlocal = (new Boolean(st.nextToken())).booleanValue(); boolean initremote = (new Boolean(st.nextToken())).booleanValue(); boolean acceptlocal = (new Boolean(st.nextToken())).booleanValue(); boolean acceptremote = (new Boolean(st.nextToken())).booleanValue(); SimpleOptionHandler opthand = new SimpleOptionHandler(opcode, initlocal, initremote, acceptlocal, acceptremote); tc.addOptionHandler(opthand); } catch (Exception e) { if (e instanceof InvalidTelnetOptionException) { System.err.println("Error registering option: " + e.getMessage()); } else { System.err.println("Invalid REGISTER command."); System.err.println( "Use REGISTER optcode initlocal initremote acceptlocal acceptremote"); System.err.println("(optcode is an integer.)"); System.err.println( "(initlocal, initremote, acceptlocal, acceptremote are boolean)"); } } } else if ((new String(buff, 0, ret_read)).startsWith("UNREGISTER")) { StringTokenizer st = new StringTokenizer(new String(buff)); try { st.nextToken(); int opcode = (new Integer(st.nextToken())).intValue(); tc.deleteOptionHandler(opcode); } catch (Exception e) { if (e instanceof InvalidTelnetOptionException) { System.err.println("Error unregistering option: " + e.getMessage()); } else { System.err.println("Invalid UNREGISTER command."); System.err.println("Use UNREGISTER optcode"); System.err.println("(optcode is an integer)"); } } } else if ((new String(buff, 0, ret_read)).startsWith("SPY")) { try { tc.registerSpyStream(fout); } catch (Exception e) { System.err.println("Error registering the spy"); } } else if ((new String(buff, 0, ret_read)).startsWith("UNSPY")) { tc.stopSpyStream(); } else { try { outstr.write(buff, 0, ret_read); outstr.flush(); } catch (Exception e) { end_loop = true; } } } } catch (Exception e) { System.err.println("Exception while reading keyboard:" + e.getMessage()); end_loop = true; } } while ((ret_read > 0) && (end_loop == false)); try { tc.disconnect(); } catch (Exception e) { System.err.println("Exception while connecting:" + e.getMessage()); } } catch (Exception e) { System.err.println("Exception while connecting:" + e.getMessage()); System.exit(1); } } }