List of usage examples for java.io OutputStream write
public void write(byte b[]) throws IOException
b.length
bytes from the specified byte array to this output stream. From source file:HTTPServer.java
public static void main(String[] args) throws Exception { ServerSocket sSocket = new ServerSocket(1777); while (true) { System.out.println("Waiting for a client..."); Socket newSocket = sSocket.accept(); System.out.println("accepted the socket"); OutputStream os = newSocket.getOutputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(newSocket.getInputStream())); String inLine = null;/*from www. j av a2s.c o m*/ while (((inLine = br.readLine()) != null) && (!(inLine.equals("")))) { System.out.println(inLine); } System.out.println(""); StringBuffer sb = new StringBuffer(); sb.append("<html>\n"); sb.append("<head>\n"); sb.append("<title>Java \n"); sb.append("</title>\n"); sb.append("</head>\n"); sb.append("<body>\n"); sb.append("<H1>HTTPServer Works!</H1>\n"); sb.append("</body>\n"); sb.append("</html>\n"); String string = sb.toString(); byte[] byteArray = string.getBytes(); os.write("HTTP/1.0 200 OK\n".getBytes()); os.write(new String("Content-Length: " + byteArray.length + "\n").getBytes()); os.write("Content-Type: text/html\n\n".getBytes()); os.write(byteArray); os.flush(); os.close(); br.close(); newSocket.close(); } }
From source file:edu.nyupoly.cs6903.ag3671.FTPClientExample.java
public static void main(String[] args) throws UnknownHostException, Exception { // MY CODE/* w w w .ja v a 2 s. c o m*/ if (crypto(Collections.unmodifiableList(Arrays.asList(args)))) { return; } ; // MY CODE -- END boolean storeFile = false, binaryTransfer = true, error = false, listFiles = false, listNames = false, hidden = false; boolean localActive = false, useEpsvWithIPv4 = false, feat = false, printHash = false; boolean mlst = false, mlsd = false; boolean lenient = false; long keepAliveTimeout = -1; int controlKeepAliveReplyTimeout = -1; int minParams = 5; // listings require 3 params String protocol = null; // SSL protocol String doCommand = null; String trustmgr = null; String proxyHost = null; int proxyPort = 80; String proxyUser = null; String proxyPassword = null; String username = null; String password = null; int base = 0; for (base = 0; base < args.length; base++) { if (args[base].equals("-s")) { storeFile = true; } else if (args[base].equals("-a")) { localActive = true; } else if (args[base].equals("-A")) { username = "anonymous"; password = System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName(); } // Always use binary transfer // else if (args[base].equals("-b")) { // binaryTransfer = true; // } else if (args[base].equals("-c")) { doCommand = args[++base]; minParams = 3; } else if (args[base].equals("-d")) { mlsd = true; minParams = 3; } else if (args[base].equals("-e")) { useEpsvWithIPv4 = true; } else if (args[base].equals("-f")) { feat = true; minParams = 3; } else if (args[base].equals("-h")) { hidden = true; } else if (args[base].equals("-k")) { keepAliveTimeout = Long.parseLong(args[++base]); } else if (args[base].equals("-l")) { listFiles = true; minParams = 3; } else if (args[base].equals("-L")) { lenient = true; } else if (args[base].equals("-n")) { listNames = true; minParams = 3; } else if (args[base].equals("-p")) { protocol = args[++base]; } else if (args[base].equals("-t")) { mlst = true; minParams = 3; } else if (args[base].equals("-w")) { controlKeepAliveReplyTimeout = Integer.parseInt(args[++base]); } else if (args[base].equals("-T")) { trustmgr = args[++base]; } else if (args[base].equals("-PrH")) { proxyHost = args[++base]; String parts[] = proxyHost.split(":"); if (parts.length == 2) { proxyHost = parts[0]; proxyPort = Integer.parseInt(parts[1]); } } else if (args[base].equals("-PrU")) { proxyUser = args[++base]; } else if (args[base].equals("-PrP")) { proxyPassword = args[++base]; } else if (args[base].equals("-#")) { printHash = true; } else { break; } } int remain = args.length - base; if (username != null) { minParams -= 2; } if (remain < minParams) // server, user, pass, remote, local [protocol] { System.err.println(USAGE); System.exit(1); } String server = args[base++]; int port = 0; String parts[] = server.split(":"); if (parts.length == 2) { server = parts[0]; port = Integer.parseInt(parts[1]); } if (username == null) { username = args[base++]; password = args[base++]; } String remote = null; if (args.length - base > 0) { remote = args[base++]; } String local = null; if (args.length - base > 0) { local = args[base++]; } final FTPClient ftp; if (protocol == null) { if (proxyHost != null) { System.out.println("Using HTTP proxy server: " + proxyHost); ftp = new FTPHTTPClient(proxyHost, proxyPort, proxyUser, proxyPassword); } else { ftp = new FTPClient(); } } else { FTPSClient ftps; if (protocol.equals("true")) { ftps = new FTPSClient(true); } else if (protocol.equals("false")) { ftps = new FTPSClient(false); } else { String prot[] = protocol.split(","); if (prot.length == 1) { // Just protocol ftps = new FTPSClient(protocol); } else { // protocol,true|false ftps = new FTPSClient(prot[0], Boolean.parseBoolean(prot[1])); } } ftp = ftps; if ("all".equals(trustmgr)) { ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager()); } else if ("valid".equals(trustmgr)) { ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager()); } else if ("none".equals(trustmgr)) { ftps.setTrustManager(null); } } if (printHash) { ftp.setCopyStreamListener(createListener()); } if (keepAliveTimeout >= 0) { ftp.setControlKeepAliveTimeout(keepAliveTimeout); } if (controlKeepAliveReplyTimeout >= 0) { ftp.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout); } ftp.setListHiddenFiles(hidden); // suppress login details ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true)); try { int reply; if (port > 0) { ftp.connect(server, port); } else { ftp.connect(server); } System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort())); // After connection attempt, you should check the reply code to verify // success. reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); System.exit(1); } } catch (IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { // do nothing } } System.err.println("Could not connect to server."); e.printStackTrace(); System.exit(1); } __main: try { if (!ftp.login(username, password)) { ftp.logout(); error = true; break __main; } System.out.println("Remote system is " + ftp.getSystemType()); if (binaryTransfer) { ftp.setFileType(FTP.BINARY_FILE_TYPE); } else { // in theory this should not be necessary as servers should default to ASCII // but they don't all do so - see NET-500 ftp.setFileType(FTP.ASCII_FILE_TYPE); } // Use passive mode as default because most of us are // behind firewalls these days. if (localActive) { ftp.enterLocalActiveMode(); } else { ftp.enterLocalPassiveMode(); } ftp.setUseEPSVwithIPv4(useEpsvWithIPv4); if (storeFile) { InputStream input; input = new FileInputStream(local); // MY CODE byte[] bytes = IOUtils.toByteArray(input); InputStream encrypted = new ByteArrayInputStream(cryptor.encrypt(bytes)); // MY CODE -- END ftp.storeFile(remote, encrypted); input.close(); } else if (listFiles) { if (lenient) { FTPClientConfig config = new FTPClientConfig(); config.setLenientFutureDates(true); ftp.configure(config); } for (FTPFile f : ftp.listFiles(remote)) { System.out.println(f.getRawListing()); System.out.println(f.toFormattedString()); } } else if (mlsd) { for (FTPFile f : ftp.mlistDir(remote)) { System.out.println(f.getRawListing()); System.out.println(f.toFormattedString()); } } else if (mlst) { FTPFile f = ftp.mlistFile(remote); if (f != null) { System.out.println(f.toFormattedString()); } } else if (listNames) { for (String s : ftp.listNames(remote)) { System.out.println(s); } } else if (feat) { // boolean feature check if (remote != null) { // See if the command is present if (ftp.hasFeature(remote)) { System.out.println("Has feature: " + remote); } else { if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) { System.out.println("FEAT " + remote + " was not detected"); } else { System.out.println("Command failed: " + ftp.getReplyString()); } } // Strings feature check String[] features = ftp.featureValues(remote); if (features != null) { for (String f : features) { System.out.println("FEAT " + remote + "=" + f + "."); } } else { if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) { System.out.println("FEAT " + remote + " is not present"); } else { System.out.println("Command failed: " + ftp.getReplyString()); } } } else { if (ftp.features()) { // Command listener has already printed the output } else { System.out.println("Failed: " + ftp.getReplyString()); } } } else if (doCommand != null) { if (ftp.doCommand(doCommand, remote)) { // Command listener has already printed the output // for(String s : ftp.getReplyStrings()) { // System.out.println(s); // } } else { System.out.println("Failed: " + ftp.getReplyString()); } } else { OutputStream output; output = new FileOutputStream(local); // MY CODE ByteArrayOutputStream remoteFile = new ByteArrayOutputStream(); //InputStream byteIn = new ByteArrayInputStream(buf); ftp.retrieveFile(remote, remoteFile); remoteFile.flush(); Optional<byte[]> opt = cryptor.decrypt(remoteFile.toByteArray()); if (opt.isPresent()) { output.write(opt.get()); } remoteFile.close(); // MY CODE -- END output.close(); } ftp.noop(); // check that control connection is working OK ftp.logout(); } catch (FTPConnectionClosedException e) { error = true; System.err.println("Server closed connection."); e.printStackTrace(); } catch (IOException e) { error = true; e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { // do nothing } } } System.exit(error ? 1 : 0); }
From source file:de.mpg.escidoc.services.common.util.Util.java
/** * Command line transformation.//from ww w . j a va2 s. c om * * @param see usage * @throws Exception Any exception */ public static void main(String[] args) throws Exception { if (args.length < 7) { System.out.println("Usage: "); System.out.println( "Util <srcFile> <srcFormatName> <srcFormatType> <srcFormatEncoding> <trgFormatName> <trgFormatType> <trgFormatEncoding> [<trgFile> [<service>]]"); System.out.println("Example:"); System.out.println( "Util /tmp/source.xml eDoc application/xml UTF-8 eSciDoc application/xml UTF-8 /tmp/target.xml"); } else { // Init Transformation transformation = new TransformationBean(true); Format srcFormat = new Format(args[1], args[2], args[3]); Format trgFormat = new Format(args[4], args[5], args[6]); File srcFile = new File(args[0]); OutputStream trgStream; if (args.length > 7) { trgStream = new FileOutputStream(new File(args[7])); } else { trgStream = System.out; } String service = "eSciDoc"; if (args.length > 8) { service = args[8]; } // Get file content FileInputStream inputStream = new FileInputStream(srcFile); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int read; while ((read = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, read); } byte[] content = outputStream.toByteArray(); // Transform byte[] result = transformation.transform(content, srcFormat, trgFormat, service); // Stream back trgStream.write(result); trgStream.close(); } }
From source file:com.lxf.spider.client.QuickStart.java
public static void main(String[] args) throws Exception { InputStream input = null;//w w w .jav a2 s . c om OutputStream output = null; //httpclient CloseableHttpClient httpclient = HttpClients.createDefault(); try { //get HttpGet httpGet = new HttpGet("http://127.0.0.1:8080/pdqx.jc.web/cen/center.html"); // CloseableHttpResponse response1 = httpclient.execute(httpGet); // The underlying HTTP connection is still held by the response object // to allow the response content to be streamed directly from the network socket. // In order to ensure correct deallocation of system resources // the user MUST call CloseableHttpResponse#close() from a finally clause. // Please note that if response content is not fully consumed the underlying // connection cannot be safely re-used and will be shut down and discarded // by the connection manager. try { //??? int statusCode = response1.getStatusLine().getStatusCode(); //??200? if (statusCode == HttpStatus.SC_OK) { // input = httpGet.getRequestLine(); System.out.println(response1.getStatusLine()); // HttpEntity entity1 = response1.getEntity(); // do something useful with the response body // and ensure it is fully consumed input = entity1.getContent(); output = new FileOutputStream("d:/lxf.data"); //? int tempByte = -1; while ((tempByte = input.read()) > 0) { output.write(tempByte); } EntityUtils.consume(entity1); //? if (input != null) { input.close(); } if (output != null) { output.close(); } } } finally { response1.close(); } /*HttpPost httpPost = new HttpPost("http://targethost/login"); List <NameValuePair> nvps = new ArrayList <NameValuePair>(); nvps.add(new BasicNameValuePair("username", "vip")); nvps.add(new BasicNameValuePair("password", "secret")); httpPost.setEntity(new UrlEncodedFormEntity(nvps)); CloseableHttpResponse response2 = httpclient.execute(httpPost); try { System.out.println(response2.getStatusLine()); HttpEntity entity2 = response2.getEntity(); // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity2); } finally { response2.close(); }*/ } finally { httpclient.close(); } }
From source file:correospingtelnet.Telnet.java
public static void main(String[] args) throws Exception { FileOutputStream fout = null; String remoteip = "64.62.142.154"; int remoteport = 23; try {/*w ww .j a v a 2 s . com*/ 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 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"); System.out.println("Type ^[A-Z] to send the control character; use ^^ to send ^"); 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) { final String line = new String(buff, 0, ret_read); // deliberate use of default charset if (line.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 (line.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 (line.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 (line.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 (line.startsWith("SPY")) { tc.registerSpyStream(fout); } else if (line.startsWith("UNSPY")) { tc.stopSpyStream(); } else if (line.matches("^\\^[A-Z^]\\r?\\n?$")) { byte toSend = buff[1]; if (toSend == '^') { outstr.write(toSend); } else { outstr.write(toSend - 'A' + 1); } outstr.flush(); } 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:Main.java
public static final void writeLong(OutputStream o, long v) throws IOException { OutputStream out = o; out.write((int) (v >>> 56) & 0xFF); out.write((int) (v >>> 48) & 0xFF); out.write((int) (v >>> 40) & 0xFF); out.write((int) (v >>> 32) & 0xFF); out.write((int) (v >>> 24) & 0xFF); out.write((int) (v >>> 16) & 0xFF); out.write((int) (v >>> 8) & 0xFF); out.write((int) (v >>> 0) & 0xFF); }
From source file:Main.java
public static void writeStringToOutputStream(OutputStream out, String str) throws IOException { out.write(str.getBytes("UTF-8")); }
From source file:Main.java
public static void writeUnsignedInt16(OutputStream out, int value) throws IOException { out.write((byte) (value >>> 8)); out.write((byte) value); }
From source file:Main.java
public static void writeUnsignedInt24(OutputStream out, int value) throws IOException { out.write((byte) (value >>> 16)); out.write((byte) (value >>> 8)); out.write((byte) value); }
From source file:Main.java
public static void writeAll(String fileName, byte[] data) throws IOException { OutputStream stream = new FileOutputStream(fileName); stream.write(data); stream.close();//w w w . j a va 2 s . com }