List of usage examples for java.io OutputStream write
public void write(byte b[], int off, int len) throws IOException
len
bytes from the specified byte array starting at offset off
to this output stream. From source file:com.rest.samples.getReportFromJasperServerWithSeparateAuthFormatURL.java
public static void main(String[] args) { // TODO code application logic here Map<String, String> params = new HashMap<String, String>(); params.put("host", "10.49.28.3"); params.put("port", "8081"); params.put("reportName", "vencimientos"); params.put("parametros", "feini=2016-09-30&fefin=2016-09-30"); StrSubstitutor sub = new StrSubstitutor(params, "{", "}"); String urlTemplate = "http://{host}:{port}/jasperserver/rest_v2/reports/Reportes/{reportName}.pdf?{parametros}"; String url = sub.replace(urlTemplate); try {/*from w w w .ja v a 2 s .c om*/ CredentialsProvider cp = new BasicCredentialsProvider(); cp.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("jasperadmin", "jasperadmin")); CloseableHttpClient hc = HttpClientBuilder.create().setDefaultCredentialsProvider(cp).build(); HttpGet getMethod = new HttpGet(url); getMethod.addHeader("accept", "application/pdf"); HttpResponse res = hc.execute(getMethod); if (res.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Failed : HTTP eror code: " + res.getStatusLine().getStatusCode()); } InputStream is = res.getEntity().getContent(); OutputStream os = new FileOutputStream(new File("vencimientos.pdf")); int read = 0; byte[] bytes = new byte[2048]; while ((read = is.read(bytes)) != -1) { os.write(bytes, 0, read); } is.close(); os.close(); if (Desktop.isDesktopSupported()) { File pdfFile = new File("vencimientos.pdf"); Desktop.getDesktop().open(pdfFile); } } catch (IOException ex) { Logger.getLogger(SamplesUseHttpclient.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.rest.samples.getReportFromJasperServerWithSeparateAuth.java
public static void main(String[] args) { // TODO code application logic here String host = "10.49.28.3"; String port = "8081"; String reportName = "vencimientos"; String params = "feini=2016-09-30&fefin=2016-09-30"; String url = "http://{host}:{port}/jasperserver/rest_v2/reports/Reportes/{reportName}.pdf?{params}"; url = url.replace("{host}", host); url = url.replace("{port}", port); url = url.replace("{reportName}", reportName); url = url.replace("{params}", params); try {//from www . ja v a 2 s.c o m CredentialsProvider cp = new BasicCredentialsProvider(); cp.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("username", "password")); CloseableHttpClient hc = HttpClientBuilder.create().setDefaultCredentialsProvider(cp).build(); HttpGet getMethod = new HttpGet(url); getMethod.addHeader("accept", "application/pdf"); HttpResponse res = hc.execute(getMethod); if (res.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Failed : HTTP eror code: " + res.getStatusLine().getStatusCode()); } InputStream is = res.getEntity().getContent(); OutputStream os = new FileOutputStream(new File("vencimientos.pdf")); int read = 0; byte[] bytes = new byte[2048]; while ((read = is.read(bytes)) != -1) { os.write(bytes, 0, read); } is.close(); os.close(); if (Desktop.isDesktopSupported()) { File pdfFile = new File("vencimientos.pdf"); Desktop.getDesktop().open(pdfFile); } } catch (IOException ex) { Logger.getLogger(SamplesUseHttpclient.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:luisjosediez.Ejercicio2.java
/** * @param args the command line arguments */// w w w . j av a 2 s . c om public static void main(String[] args) { // TODO code application logic here System.out.println("Introduce la direccin de un servidor ftp: "); FTPClient cliente = new FTPClient(); String servFTP = cadena(); String clave = ""; System.out.println("Introduce usuario (vaco para conexin annima): "); String usuario = cadena(); String opcion; if (usuario.equals("")) { clave = ""; } else { System.out.println("Introduce contrasea: "); clave = cadena(); } try { cliente.setPassiveNatWorkaround(false); cliente.connect(servFTP, 21); boolean login = cliente.login(usuario, clave); if (login) { System.out.println("Conexin ok"); } else { System.out.println("Login incorrecto"); cliente.disconnect(); System.exit(1); } do { System.out.println("Orden [exit para salir]: "); opcion = cadena(); if (opcion.equals("ls")) { FTPFile[] files = cliente.listFiles(); String tipos[] = { "Fichero", "Directorio", "Enlace" }; for (int i = 0; i < files.length; i++) { System.out.println("\t" + files[i].getName() + "\t=> " + tipos[files[i].getType()]); } } else if (opcion.startsWith("cd ")) { try { cliente.changeWorkingDirectory(opcion.substring(3)); } catch (IOException e) { } } else if (opcion.equals("help")) { System.out.println( "Puede ejecutar los comandos 'exit', 'ls', 'cd', 'get' y 'upload'. Para ms detalles utilice 'help <comando>'."); } else if (opcion.startsWith("help ")) { if (opcion.endsWith(" get")) { System.out.println( "Permite descargar un archivo concreto. Uso: 'get <rutaArchivoADescargar>'."); } else if (opcion.endsWith(" ls")) { System.out.println("Lista los ficheros y directorios en la ubicacin actual. Uso: 'ls'."); } else if (opcion.endsWith(" cd")) { System.out.println("Permite cambiar la ubicacin actual. Uso: 'cd <rutaDestino>'."); } else if (opcion.endsWith(" put")) { System.out.println( "Permite subir un archivo al directorio actual. Uso: 'put <rutaArchivoASubir>'."); } } else if (opcion.startsWith("get ")) { try { System.out.println("Indique la carpeta de descarga: "); try (FileOutputStream fos = new FileOutputStream(cadena() + opcion.substring(4))) { cliente.retrieveFile(opcion.substring(4), fos); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { } } else if (opcion.startsWith("put ")) { try { try { System.out.println(opcion.substring(4)); File local = new File(opcion.substring(4)); System.out.println(local.getName()); InputStream is = new FileInputStream(opcion.substring(4)); OutputStream os = cliente.storeFileStream(local.getName()); byte[] bytesIn = new byte[4096]; int read = 0; while ((read = is.read(bytesIn)) != -1) { os.write(bytesIn, 0, read); } is.close(); os.close(); boolean completed = cliente.completePendingCommand(); if (completed) { System.out.println("The file is uploaded successfully."); } } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { } } } while (!(opcion.equals("exit"))); boolean logout = cliente.logout(); if (logout) System.out.println("Logout..."); else System.out.println("Logout incorrecto"); cliente.disconnect(); } catch (Exception e) { e.printStackTrace(); } }
From source file:airnowgrib2tojson.AirNowGRIB2toJSON.java
/** * @param args the command line arguments *//*from w w w . j a va 2 s. c o m*/ public static void main(String[] args) { SimpleDateFormat GMT = new SimpleDateFormat("yyMMddHH"); GMT.setTimeZone(TimeZone.getTimeZone("GMT-2")); System.out.println(GMT.format(new Date())); FTPClient ftpClient = new FTPClient(); FileOutputStream fos = null; try { //Connecting to AirNow FTP server to get the fresh AQI data ftpClient.connect("ftp.airnowapi.org"); ftpClient.login("pixelshade", "GZDN8uqduwvk"); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); //downloading .grib2 file File of = new File("US-" + GMT.format(new Date()) + "_combined.grib2"); OutputStream outstr = new BufferedOutputStream(new FileOutputStream(of)); InputStream instr = ftpClient .retrieveFileStream("GRIB2/US-" + GMT.format(new Date()) + "_combined.grib2"); byte[] bytesArray = new byte[4096]; int bytesRead = -1; while ((bytesRead = instr.read(bytesArray)) != -1) { outstr.write(bytesArray, 0, bytesRead); } //Close used resources ftpClient.completePendingCommand(); outstr.close(); instr.close(); // logout the user ftpClient.logout(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { //disconnect from AirNow server ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } try { //Open .grib2 file final File AQIfile = new File("US-" + GMT.format(new Date()) + "_combined.grib2"); final GridDataset gridDS = GridDataset.open(AQIfile.getAbsolutePath()); //The data type needed - AQI; since it isn't defined in GRIB2 standard, //Aerosol type is used instead; look AirNow API documentation for details. GridDatatype AQI = gridDS.findGridDatatype("Aerosol_type_msl"); //Get the coordinate system for selected data type; //cut the rectangle to work with - time and height axes aren't present in these files //and latitude/longitude go "-1", which means all the data provided. GridCoordSystem AQIGCS = AQI.getCoordinateSystem(); List<CoordinateAxis> AQI_XY = AQIGCS.getCoordinateAxes(); Array AQIslice = AQI.readDataSlice(0, 0, -1, -1); //Variables for iterating through coordinates VariableDS var = AQI.getVariable(); Index index = AQIslice.getIndex(); //Variables for counting lat/long from the indices provided double stepX = (AQI_XY.get(2).getMaxValue() - AQI_XY.get(2).getMinValue()) / index.getShape(1); double stepY = (AQI_XY.get(1).getMaxValue() - AQI_XY.get(1).getMinValue()) / index.getShape(0); double curX = AQI_XY.get(2).getMinValue(); double curY = AQI_XY.get(1).getMinValue(); //Output details OutputStream ValLog = new FileOutputStream("USA_AQI.json"); Writer ValWriter = new OutputStreamWriter(ValLog); for (int j = 0; j < index.getShape(0); j++) { for (int i = 0; i < index.getShape(1); i++) { float val = AQIslice.getFloat(index.set(j, i)); //Write the AQI value and its coordinates if it's present by i/j indices if (!Float.isNaN(val)) ValWriter.write("{\r\n\"lat\":" + curX + ",\r\n\"lng\":" + curY + ",\r\n\"AQI\":" + val + ",\r\n},\r\n"); curX += stepX; } curY += stepY; curX = AQI_XY.get(2).getMinValue(); } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.groupC1.control.network.TelnetClientExample.java
/*** * Main for the TelnetClient.//from w ww . j a v a2s. com ***/ 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:com.hzih.sslvpn.servlet.TelnetClientExample.java
/** * Main for the TelnetClientExample.//from w ww . j av a 2 s .c o m * * */ public static void main(String[] args) throws Exception { 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 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 (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:examples.TelnetClientExample.java
/*** * Main for the TelnetClientExample./*from w w w . ja v a2s . c om*/ ***/ 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); } } }
From source file:ch.unizh.ini.jaer.projects.gesture.vlccontrol.TelnetClientExample.java
/*** * Main for the TelnetClientExample./*from ww w . j av a2 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); } } }
From source file:Main.java
public static void writeNetSocketBytes(Socket socket, byte[] buffer, int len) throws Exception { OutputStream os = socket.getOutputStream(); os.write(buffer, 0, len); os.flush();/* ww w . j a v a 2s .com*/ }
From source file:Main.java
public static void sendData(byte[] bytes, BluetoothSocket socket) throws IOException { OutputStream out = socket.getOutputStream(); out.write(bytes, 0, bytes.length); out.flush();/*from w w w . j a v a2s .c o m*/ out.close(); }