List of usage examples for java.io DataOutputStream DataOutputStream
public DataOutputStream(OutputStream out)
From source file:cacheservice.CacheServer.java
/** * @param args the command line arguments *//*from www . j a va 2 s . c o m*/ public static void main(String[] args) { // COMUNICACIN CON EL CLIENTE ServerSocket serverSocket; Socket socketCliente; DataInputStream in; //Flujo de datos de entrada DataOutputStream out; //Flujo de datos de salida String mensaje; int laTengoenCache = 0; //COMUNICACIN CON EL INDEX ServerSocket serverSocketIndex; Socket socketIndex; DataOutputStream outIndex; ObjectInputStream inIndex; String mensajeIndex; try { serverSocket = new ServerSocket(4444); System.out.print("SERVIDOR CACHE ACTIVO a la espera de peticiones"); //MIENTRAS PERMANEZCA ACTIVO EL SERVIDOR CACHE ESPERAR? POR PETICIONES DE LOS CLIENTES while (true) { socketCliente = serverSocket.accept(); in = new DataInputStream(socketCliente.getInputStream()); //Entrada de los mensajes del cliente mensaje = in.readUTF(); //Leo el mensaje enviado por el cliente System.out.println("\nHe recibido del cliente: " + mensaje); //Muestro el mensaje recibido por el cliente //int particionBuscada = seleccionarParticion(mensaje, tamanoCache, numeroParticiones); //Busco la particin //double tamanoParticion = Math.ceil( (double)tamanoCache / (double)numeroParticiones); //Thread hilo = new Hilo(mensaje,particionBuscada,cache.GetTable(),(int) tamanoParticion); //hilo.start(); //RESPUESTA DEL SERVIDOR CACHE AL CLIENTE out = new DataOutputStream(socketCliente.getOutputStream()); String respuesta = "Respuesta para " + mensaje; if (laTengoenCache == 1) { out.writeUTF(respuesta); System.out.println("\nTengo la respuesta. He respondido al cliente: " + respuesta); } else { out.writeUTF("miss"); out.close(); in.close(); socketCliente.close(); System.out.println("\nNo tengo la respuesta."); //LEER RESPUESTA DEL SERVIDOR INDEX serverSocketIndex = new ServerSocket(6666); socketIndex = serverSocketIndex.accept(); inIndex = new ObjectInputStream(socketIndex.getInputStream()); JSONObject mensajeRecibidoIndex = (JSONObject) inIndex.readObject(); System.out.println("He recibido del SERVIDOR INDEX: " + mensajeRecibidoIndex); //outIndex.close(); inIndex.close(); socketIndex.close(); } } } catch (Exception e) { System.out.print(e.getMessage()); } }
From source file:DataIODemo.java
public static void main(String[] args) throws IOException { // write the data out DataOutputStream out = new DataOutputStream(new FileOutputStream("invoice1.txt")); double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 }; int[] units = { 12, 8, 13, 29, 50 }; String[] descs = { "Java T-shirt", "Java Mug", "Duke Juggling Dolls", "Java Pin", "Java Key Chain" }; for (int i = 0; i < prices.length; i++) { out.writeDouble(prices[i]);/*ww w. j a v a 2 s. co m*/ out.writeChar('\t'); out.writeInt(units[i]); out.writeChar('\t'); out.writeChars(descs[i]); out.writeChar('\n'); } out.close(); // read it in again DataInputStream in = new DataInputStream(new FileInputStream("invoice1.txt")); double price; int unit; StringBuffer desc; double total = 0.0; try { while (true) { price = in.readDouble(); in.readChar(); // throws out the tab unit = in.readInt(); in.readChar(); // throws out the tab char chr; desc = new StringBuffer(20); char lineSep = System.getProperty("line.separator").charAt(0); while ((chr = in.readChar()) != lineSep) desc.append(chr); System.out.println("You've ordered " + unit + " units of " + desc + " at $" + price); total = total + unit * price; } } catch (EOFException e) { } System.out.println("For a TOTAL of: $" + total); in.close(); }
From source file:Naive.java
public static void main(String[] args) throws Exception { // Basic access authentication setup String key = "CHANGEME: YOUR_API_KEY"; String secret = "CHANGEME: YOUR_API_SECRET"; String version = "preview1"; // CHANGEME: the API version to use String practiceid = "000000"; // CHANGEME: the practice ID to use // Find the authentication path Map<String, String> auth_prefix = new HashMap<String, String>(); auth_prefix.put("v1", "oauth"); auth_prefix.put("preview1", "oauthpreview"); auth_prefix.put("openpreview1", "oauthopenpreview"); URL authurl = new URL("https://api.athenahealth.com/" + auth_prefix.get(version) + "/token"); HttpURLConnection conn = (HttpURLConnection) authurl.openConnection(); conn.setRequestMethod("POST"); // Set the Authorization request header String auth = Base64.encodeBase64String((key + ':' + secret).getBytes()); conn.setRequestProperty("Authorization", "Basic " + auth); // Since this is a POST, the parameters go in the body conn.setDoOutput(true);//from ww w . j av a2 s . co m String contents = "grant_type=client_credentials"; DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(contents); wr.flush(); wr.close(); // Read the response BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); // Decode from JSON and save the token for later String response = sb.toString(); JSONObject authorization = new JSONObject(response); String token = authorization.get("access_token").toString(); // GET /departments HashMap<String, String> params = new HashMap<String, String>(); params.put("limit", "1"); // Set up the URL, method, and Authorization header URL url = new URL("https://api.athenahealth.com/" + version + "/" + practiceid + "/departments" + "?" + urlencode(params)); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Authorization", "Bearer " + token); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); sb = new StringBuilder(); while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); response = sb.toString(); JSONObject departments = new JSONObject(response); System.out.println(departments.toString()); // POST /appointments/{appointmentid}/notes params = new HashMap<String, String>(); params.put("notetext", "Hello from Java!"); url = new URL("https://api.athenahealth.com/" + version + "/" + practiceid + "/appointments/1/notes"); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Authorization", "Bearer " + token); // POST parameters go in the body conn.setDoOutput(true); contents = urlencode(params); wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(contents); wr.flush(); wr.close(); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); sb = new StringBuilder(); while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); response = sb.toString(); JSONObject note = new JSONObject(response); System.out.println(note.toString()); }
From source file:org.wso2.charon3.samples.group.sample01.CreateGroupSample.java
public static void main(String[] args) { try {/*from w w w. j av a 2s . c om*/ String url = "http://localhost:8080/scim/v2/Groups"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // Setting basic post request con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/scim+json"); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(createRequestBody); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); BufferedReader in; if (responseCode == HttpURLConnection.HTTP_CREATED) { // success in = new BufferedReader(new InputStreamReader(con.getInputStream())); } else { in = new BufferedReader(new InputStreamReader(con.getErrorStream())); } String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //printing result from response System.out.println("Response Code : " + responseCode); System.out.println("Response Message : " + con.getResponseMessage()); System.out.println("Response Content : " + response.toString()); } catch (ProtocolException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:SecurityManagerTest.java
public static void main(String[] args) throws Exception { try {/*from w w w . j a va 2 s . c o m*/ System.setSecurityManager(new PasswordSecurityManager("Booga Booga")); } catch (SecurityException se) { System.err.println("SecurityManager already set!"); } DataInputStream in = new DataInputStream(new FileInputStream("inputtext.txt")); DataOutputStream out = new DataOutputStream(new FileOutputStream("outputtext.txt")); String inputString; while ((inputString = in.readLine()) != null) { out.writeBytes(inputString); out.writeByte('\n'); } in.close(); out.close(); }
From source file:Ch7_Images.java
public static void main(String[] args) { int numRows = 6, numCols = 11, pix = 20; PaletteData pd = new PaletteData( new RGB[] { new RGB(0x00, 0x00, 0x00), new RGB(0x80, 0x80, 0x80), new RGB(0xFF, 0xFF, 0xFF) }); ImageData[] flagArray = new ImageData[3]; for (int frame = 0; frame < flagArray.length; frame++) { flagArray[frame] = new ImageData(pix * numCols, pix * numRows, 4, pd); flagArray[frame].delayTime = 10; for (int x = 0; x < pix * numCols; x++) { for (int y = 0; y < pix * numRows; y++) { int value = (((x / pix) % 3) + (3 - ((y / pix) % 3)) + frame) % 3; flagArray[frame].setPixel(x, y, value); }// w ww . j ava 2 s .c o m } } ImageLoader gifloader = new ImageLoader(); ByteArrayOutputStream flagByte[] = new ByteArrayOutputStream[3]; byte[][] gifarray = new byte[3][]; gifloader.data = flagArray; for (int i = 0; i < 3; i++) { flagByte[i] = new ByteArrayOutputStream(); flagArray[0] = flagArray[i]; gifloader.save(flagByte[i], SWT.IMAGE_GIF); gifarray[i] = flagByte[i].toByteArray(); } byte[] gif = new byte[4628]; System.arraycopy(gifarray[0], 0, gif, 0, 61); System.arraycopy(new byte[] { 33, (byte) 255, 11 }, 0, gif, 61, 3); System.arraycopy("NETSCAPE2.0".getBytes(), 0, gif, 64, 11); System.arraycopy(new byte[] { 3, 1, -24, 3, 0, 33, -7, 4, -24 }, 0, gif, 75, 9); System.arraycopy(gifarray[0], 65, gif, 84, 1512); for (int i = 1; i < 3; i++) { System.arraycopy(gifarray[i], 61, gif, 1516 * i + 80, 3); gif[1516 * i + 83] = (byte) -24; System.arraycopy(gifarray[i], 65, gif, 1516 * i + 84, 1512); } try { DataOutputStream in = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(new File("FlagGIF.gif")))); in.write(gif, 0, gif.length); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.tc.simple.apn.quicktests.Test.java
/** * @param args/* ww w . j a v a 2 s . co m*/ */ public static void main(String[] args) { SSLSocket socket = null; try { String host = "gateway.sandbox.push.apple.com"; int port = 2195; String token = "de7f197546e41a76684f8e2d89f397ed165298d7772f4bd9b0f39c674b185b0f"; System.out.println(token.toCharArray().length); //String token = "8cebc7c08f79fa62f0994eb4298387ff930857ff8d14a50de431559cf476b223"; KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(Test.class.getResourceAsStream("egram-dev-apn.p12"), "xxxxxxxxx".toCharArray()); KeyManagerFactory keyMgrFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyMgrFactory.init(keyStore, "xxxxxxxxx".toCharArray()); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyMgrFactory.getKeyManagers(), null, null); SSLSocketFactory socketFactory = sslContext.getSocketFactory(); socket = (SSLSocket) socketFactory.createSocket(host, port); String[] cipherSuites = socket.getSupportedCipherSuites(); socket.setEnabledCipherSuites(cipherSuites); socket.startHandshake(); char[] t = token.toCharArray(); byte[] b = Hex.decodeHex(t); OutputStream outputstream = socket.getOutputStream(); String payload = "{\"aps\":{\"alert\":\"yabadabadooo\"}}"; int expiry = (int) ((System.currentTimeMillis() / 1000L) + 7200); ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bout); //command dos.writeByte(1); //id dos.writeInt(900); //expiry dos.writeInt(expiry); //token length. dos.writeShort(b.length); //token dos.write(b); //payload length dos.writeShort(payload.length()); //payload. dos.write(payload.getBytes()); byte[] byteMe = bout.toByteArray(); socket.getOutputStream().write(byteMe); socket.setSoTimeout(900); InputStream in = socket.getInputStream(); System.out.println(APNErrors.getError(in.read())); in.close(); outputstream.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
From source file:RSATest.java
public static void main(String[] args) { try {//from w ww . jav a 2 s . co m if (args[0].equals("-genkey")) { KeyPairGenerator pairgen = KeyPairGenerator.getInstance("RSA"); SecureRandom random = new SecureRandom(); pairgen.initialize(KEYSIZE, random); KeyPair keyPair = pairgen.generateKeyPair(); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(args[1])); out.writeObject(keyPair.getPublic()); out.close(); out = new ObjectOutputStream(new FileOutputStream(args[2])); out.writeObject(keyPair.getPrivate()); out.close(); } else if (args[0].equals("-encrypt")) { KeyGenerator keygen = KeyGenerator.getInstance("AES"); SecureRandom random = new SecureRandom(); keygen.init(random); SecretKey key = keygen.generateKey(); // wrap with RSA public key ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3])); Key publicKey = (Key) keyIn.readObject(); keyIn.close(); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.WRAP_MODE, publicKey); byte[] wrappedKey = cipher.wrap(key); DataOutputStream out = new DataOutputStream(new FileOutputStream(args[2])); out.writeInt(wrappedKey.length); out.write(wrappedKey); InputStream in = new FileInputStream(args[1]); cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, key); crypt(in, out, cipher); in.close(); out.close(); } else { DataInputStream in = new DataInputStream(new FileInputStream(args[1])); int length = in.readInt(); byte[] wrappedKey = new byte[length]; in.read(wrappedKey, 0, length); // unwrap with RSA private key ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3])); Key privateKey = (Key) keyIn.readObject(); keyIn.close(); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.UNWRAP_MODE, privateKey); Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY); OutputStream out = new FileOutputStream(args[2]); cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, key); crypt(in, out, cipher); in.close(); out.close(); } } catch (IOException e) { e.printStackTrace(); } catch (GeneralSecurityException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
From source file:SignatureTest.java
public static void main(String[] args) { try {/*from w ww .j a v a2 s . c om*/ if (args[0].equals("-genkeypair")) { KeyPairGenerator pairgen = KeyPairGenerator.getInstance("DSA"); SecureRandom random = new SecureRandom(); pairgen.initialize(KEYSIZE, random); KeyPair keyPair = pairgen.generateKeyPair(); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(args[1])); out.writeObject(keyPair.getPublic()); out.close(); out = new ObjectOutputStream(new FileOutputStream(args[2])); out.writeObject(keyPair.getPrivate()); out.close(); } else if (args[0].equals("-sign")) { ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3])); PrivateKey privkey = (PrivateKey) keyIn.readObject(); keyIn.close(); Signature signalg = Signature.getInstance("DSA"); signalg.initSign(privkey); File infile = new File(args[1]); InputStream in = new FileInputStream(infile); int length = (int) infile.length(); byte[] message = new byte[length]; in.read(message, 0, length); in.close(); signalg.update(message); byte[] signature = signalg.sign(); DataOutputStream out = new DataOutputStream(new FileOutputStream(args[2])); int signlength = signature.length; out.writeInt(signlength); out.write(signature, 0, signlength); out.write(message, 0, length); out.close(); } else if (args[0].equals("-verify")) { ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[2])); PublicKey pubkey = (PublicKey) keyIn.readObject(); keyIn.close(); Signature verifyalg = Signature.getInstance("DSA"); verifyalg.initVerify(pubkey); File infile = new File(args[1]); DataInputStream in = new DataInputStream(new FileInputStream(infile)); int signlength = in.readInt(); byte[] signature = new byte[signlength]; in.read(signature, 0, signlength); int length = (int) infile.length() - signlength - 4; byte[] message = new byte[length]; in.read(message, 0, length); in.close(); verifyalg.update(message); if (!verifyalg.verify(signature)) System.out.print("not "); System.out.println("verified"); } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.linkedin.pinot.perf.MultiValueReaderWriterBenchmark.java
public static void main(String[] args) throws Exception { List<String> lines = IOUtils.readLines(new FileReader(new File(args[0]))); int totalDocs = lines.size(); int max = Integer.MIN_VALUE; int maxNumberOfMultiValues = Integer.MIN_VALUE; int totalNumValues = 0; int data[][] = new int[totalDocs][]; for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); String[] split = line.split(","); totalNumValues = totalNumValues + split.length; if (split.length > maxNumberOfMultiValues) { maxNumberOfMultiValues = split.length; }// ww w . j a v a 2s .c o m data[i] = new int[split.length]; for (int j = 0; j < split.length; j++) { String token = split[j]; int val = Integer.parseInt(token); data[i][j] = val; if (val > max) { max = val; } } } int maxBitsNeeded = (int) Math.ceil(Math.log(max) / Math.log(2)); int size = 2048; int[] offsets = new int[size]; int bitMapSize = 0; File outputFile = new File("output.mv.fwd"); FixedBitSkipListSCMVWriter fixedBitSkipListSCMVWriter = new FixedBitSkipListSCMVWriter(outputFile, totalDocs, totalNumValues, maxBitsNeeded); for (int i = 0; i < totalDocs; i++) { fixedBitSkipListSCMVWriter.setIntArray(i, data[i]); if (i % size == size - 1) { MutableRoaringBitmap rr1 = MutableRoaringBitmap.bitmapOf(offsets); ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); rr1.serialize(dos); dos.close(); //System.out.println("Chunk " + i / size + " bitmap size:" + bos.size()); bitMapSize += bos.size(); } else if (i == totalDocs - 1) { MutableRoaringBitmap rr1 = MutableRoaringBitmap.bitmapOf(Arrays.copyOf(offsets, i % size)); ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); rr1.serialize(dos); dos.close(); //System.out.println("Chunk " + i / size + " bitmap size:" + bos.size()); bitMapSize += bos.size(); } } fixedBitSkipListSCMVWriter.close(); System.out.println("Output file size:" + outputFile.length()); System.out.println("totalNumberOfDoc\t\t\t:" + totalDocs); System.out.println("totalNumberOfValues\t\t\t:" + totalNumValues); System.out.println("chunk size\t\t\t\t:" + size); System.out.println("Num chunks\t\t\t\t:" + totalDocs / size); int numChunks = totalDocs / size + 1; int totalBits = (totalNumValues * maxBitsNeeded); int dataSizeinBytes = (totalBits + 7) / 8; System.out.println("Raw data size with fixed bit encoding\t:" + dataSizeinBytes); System.out.println("\nPer encoding size"); System.out.println(); System.out.println("size (offset + length)\t\t\t:" + ((totalDocs * (4 + 4)) + dataSizeinBytes)); System.out.println(); System.out.println("size (offset only)\t\t\t:" + ((totalDocs * (4)) + dataSizeinBytes)); System.out.println(); System.out.println("bitMapSize\t\t\t\t:" + bitMapSize); System.out.println("size (with bitmap)\t\t\t:" + (bitMapSize + (numChunks * 4) + dataSizeinBytes)); System.out.println(); System.out.println("Custom Bitset\t\t\t\t:" + (totalNumValues + 7) / 8); System.out.println("size (with custom bitset)\t\t\t:" + (((totalNumValues + 7) / 8) + (numChunks * 4) + dataSizeinBytes)); }