Software

How to Write an Object to a Memory-Mapped File with Oracle JDK

import static java.nio.channels.FileChannel.MapMode.READ_WRITE;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class JdkSample {

  public static void main(String[] args) throws Exception {
    RandomAccessFile f = new RandomAccessFile("sample.out", "rw");

    FileChannel fc = f.getChannel();

    ByteBuffer map = fc.map(READ_WRITE, 0, 20);

    ByteArrayOutputStream baos = new ByteArrayOutputStream(20);

    ObjectOutputStream oos = new ObjectOutputStream(baos);

    oos.writeObject("Simples Assim");

    map.put(baos.toByteArray());

    oos.close();

    f.close();
  }

}
Software

How to Read an Object from a Memory-Mapped File with Oracle JDK

import static java.lang.System.out;
import static java.nio.channels.FileChannel.MapMode.READ_ONLY;

import java.io.ByteArrayInputStream;

import java.io.ObjectInputStream;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class JdkSample {

  public static void main(String[] args) throws Exception {
    RandomAccessFile f = new RandomAccessFile("sample.out", "r");

    FileChannel fc = f.getChannel();

    MappedByteBuffer map = chan.map(READ_ONLY, 0, 20);

    byte[] buf = new byte[20];

    map.get(buf);

    final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(buf));

    out.println(ois.readObject());

    ois.close();

    f.close();
  }

}
Software

How to Write an Object to Direct Memory with Oracle JDK

W/ ByteBuffer

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.nio.ByteBuffer;

public class JdkSample {

  public static void main(String[] args) throws Exception {
    ByteBuffer buf = ByteBuffer.allocateDirect(20);

    ByteArrayOutputStream baos = new ByteArrayOutputStream(20);

    ObjectOutputStream oos = new ObjectOutputStream(baos);

    oos.writeObject("Simples Assim");

    buf.put(baos.toByteArray());

    oos.close();
  }

}

W/ Unsafe

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;

import sun.misc.Unsafe;

public class JdkSample {

  public static void main(String[] args) throws Exception {
    Unsafe unsafe = Unsafe.getUnsafe();

    ByteArrayOutputStream baos = new ByteArrayOutputStream(20);

    ObjectOutputStream oos = new ObjectOutputStream(baos);

    oos.writeObject("Simples Assim");

    byte[] buf = baos.toByteArray();

    oos.close();

    long address = unsafe.allocateMemory(buf.length);

    for (int i = 0; i < buf.length; i++)
      unsafe.putByte(address + i, buf[i]);

    unsafe.freeMemory(address);
  }

}
Software

How to Create an Multicast Client/Server with Oracle JDK

Client

import static java.lang.System.out;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

public class JdkClient {

  public static void main(String[] args) throws Exception {
    MulticastSocket client = new MulticastSocket(45588);

    client.joinGroup(InetAddress.getByName("224.0.1.0")); // 224.0.0.XXX is reserved

    DatagramPacket packet = new DatagramPacket(new byte[13], 13);

    client.receive(packet);

    out.write(packet.getData());

    client.close();
  }

}

Server

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

public class JdkServer {

  public static void main(String[] args) throws Exception {
    MulticastSocket server = new MulticastSocket();

    DatagramPacket packet = new DatagramPacket("Simples Assim".getBytes(), 13, InetAddress.getByName("224.0.1.0"), 45588);

    while (true)
      server.send(packet);

  }

}
Software

How to Create an IP Unicast Client/Server with Oracle JDK

Client

import static java.lang.System.out;

import java.io.InputStream;
import java.net.Socket;

public class JdkClient {

  public static void main(String[] args) throws Exception {
    Socket client = new Socket("localhost", 8080);

    InputStream in = client.getInputStream();

    byte[] msg = new byte[13];

    in.read(msg);

    out.println(new String(msg));

    in.close();

    client.close();
  }

}

Server

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class JdkServer {

  public static void main(String[] args) throws Exception {
    ServerSocket server = new ServerSocket(8080);

    Socket client = server.accept();

    while (client != null) {
      OutputStream out = client.getOutputStream();

      byte[] msg = "Simples Assim".getBytes();

      Thread t = new Thread(new Runnable() {

        public void run() {

          try {
            out.write(msg);
          } catch (IOException e) {
            ...
          } finally {

            if (out != null) {

              try {
                out.close();
              } catch (IOException e) {
                e.printStackTrace();
              }

            }

          }

        }

      });

      t.start();

      client = server.accept();
    }

    server.close();
  }

}
Software

How to Make a HTTP POST Call with Basic Authentication with Oracle JDK

import static java.lang.System.out;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.URL;

public class HttpSample {

  public static void main(String[] args) throws Exception {
    Authenticator.setDefault(new Authenticator() {

      public PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("user", "password".toCharArray());
      }

    });

    URL url = new URL("http://host/");

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    conn.setDoOutput(true);

    conn.setRequestMethod("POST");

    OutputStream out = conn.getOutputStream();

    out.write("param1=value&param2=value".getBytes()); // urlencode when needed

    out.close();

    int responseCode = conn.getResponseCode();

    if (responseCode < 207) {
      InputStream in = conn.getInputStream();

      int i = in.read();

      while (i != -1) {
        out.print((char)i);

        i = in.read();
      }

      in.close();
    } else {
      InputStream err = conn.getErrorStream();

      int i = err.read();

      while (i != -1) {
        out.print((char)i);

        i = err.read();
      }

      err.close();
    }

    conn.disconnect();
  }

}
Software

How to Make a HTTP GET Call with Basic Authentication with Oracle JDK

import static java.lang.System.out;

import java.io.InputStream;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.URL;

public class HttpSample {

  public static void main(String[] args) throws Exception {
    Authenticator.setDefault(new Authenticator() {

      public PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("user", "password".toCharArray());
      }

    });

    URL url = new URL("http://host/"); // If there are parameters, just concatenate them to the URL

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    int responseCode = conn.getResponseCode();

    InputStream in = conn.getInputStream();

    if (responseCode == 200) { // OK
      int i = in.read();

      while (i != -1) {
        out.print((char)i);

        i = in.read();
      }

      in.close();
    } else {
      out.println(responseCode + " " + conn.getResponseMessage());
    }

    conn.disconnect();
  }

}
Software

How to Create a Runnable Object with Oracle JDK

JDK 8

import static java.lang.System.out;

public class JdkSample {

  public static void main(String[] args) {
    Thread t = new Thread(() -> out.println("Simples Assim"));

    t.start();
  }

}

JDK 7

import static java.lang.System.out;

public class JdkSample {

  public static void main(String[] args) {
    Thread t = new Thread(new Runnable() {

      public void run() {
        out.println("Simples Assim");
      }

    });

    t.start();
  }

}
Software

How to Compare Objects with Oracle JDK

JDK 8

import static java.lang.System.out;

import java.util.Arrays;

public class JdkSample {

  public static void main(String[] args) {
    String[] names = { "Fernando", "Kusuma", "Karina", "Melissa" };

    Arrays.sort(names, (o1, o2) -> o1.compareTo(o2));

    for (int i = 0; i < names.length; i++)
      out.println(names[i]);

  }

}

JDK 7

import static java.lang.System.out;

import java.util.Arrays;
import java.util.Comparator;

public class JdkSample {

  public static void main(String[] args) {
    String[] names = { "Fernando", "Kusuma", "Karina", "Melissa" };

    Arrays.sort(names, new Comparator<String>() {

      public int compare(String o1, String o2) {
        return o1.compareTo(o2);
      }

    });

    for (int i = 0; i < names.length; i++)
      out.println(names[i]);

  }

}