Java low level networking project (#770)

* made changes to java reflection

* removed redundant method makeSound in Animal abstract class

* added project for play-framework article

* added project for regex

* changed regex project from own model to core-java

* added project for routing in play

* made changes to regex project

* refactored code for REST API with Play project

* refactored student store indexing to zero base

* added unit tests, removed bad names

* added NIO Selector project under core-java module

* requested changes made
This commit is contained in:
Egima profile 2016-10-25 17:42:03 +03:00 committed by Grzegorz Piwowarek
parent 4bae45370d
commit 89b50437be
9 changed files with 485 additions and 8 deletions

View File

@ -0,0 +1,56 @@
package com.baeldung.java.networking.cookies;
import java.net.*;
import java.util.List;
public class PersistentCookieStore implements CookieStore, Runnable {
CookieStore store;
public PersistentCookieStore() {
store = new CookieManager().getCookieStore();
// deserialize cookies into store
Runtime.getRuntime().addShutdownHook(new Thread(this));
}
@Override
public void run() {
// serialize cookies to persistent storage
}
@Override
public void add(URI uri, HttpCookie cookie) {
store.add(uri, cookie);
}
@Override
public List<HttpCookie> get(URI uri) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<HttpCookie> getCookies() {
// TODO Auto-generated method stub
return null;
}
@Override
public List<URI> getURIs() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean remove(URI uri, HttpCookie cookie) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean removeAll() {
// TODO Auto-generated method stub
return false;
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.java.networking.cookies;
import java.net.*;
public class ProxyAcceptCookiePolicy implements CookiePolicy {
String acceptedProxy;
public ProxyAcceptCookiePolicy(String acceptedProxy) {
this.acceptedProxy = acceptedProxy;
}
public boolean shouldAccept(URI uri, HttpCookie cookie) {
String host;
try {
host = InetAddress.getByName(uri.getHost()).getCanonicalHostName();
} catch (UnknownHostException e) {
host = uri.getHost();
}
if (!HttpCookie.domainMatches(acceptedProxy, host)) {
return false;
}
return CookiePolicy.ACCEPT_ORIGINAL_SERVER.shouldAccept(uri, cookie);
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.java.networking.udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class EchoClient {
private DatagramSocket socket;
private InetAddress address;
private byte[] buf;
public EchoClient() {
try {
socket = new DatagramSocket();
address = InetAddress.getByName("localhost");
} catch (IOException e) {
e.printStackTrace();
}
}
public String sendEcho(String msg) {
DatagramPacket packet = null;
try {
buf=msg.getBytes();
packet = new DatagramPacket(buf, buf.length, address, 4445);
socket.send(packet);
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
} catch (IOException e) {
e.printStackTrace();
}
String received = new String(packet.getData(), 0, packet.getLength());
return received;
}
public void close() {
socket.close();
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.java.networking.udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class EchoServer extends Thread {
protected DatagramSocket socket = null;
protected boolean running;
protected byte[] buf = new byte[256];
public EchoServer() throws IOException {
socket = new DatagramSocket(4445);
}
public void run() {
running = true;
while (running) {
try {
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(buf, buf.length, address, port);
String received = new String(packet.getData(), 0, packet.getLength());
if (received.equals("end")) {
running = false;
continue;
}
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
running = false;
}
}
socket.close();
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.java.networking.udp;
import static org.junit.Assert.*;
import java.io.IOException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class UDPTest {
EchoClient client = null;
@Before
public void setup() throws IOException {
new EchoServer().start();
client = new EchoClient();
}
@Test
public void whenCanSendAndReceivePacket_thenCorrect1() {
String echo = client.sendEcho("hello server");
assertEquals("hello server", echo);
echo = client.sendEcho("server is working");
assertFalse(echo.equals("hello server"));
}
@After
public void tearDown() {
client.sendEcho("end");
client.close();
}
}

View File

@ -1,15 +1,15 @@
package com.baeldung.java.nio.selector; package com.baeldung.java.nio.selector;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel; import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel; import java.nio.channels.SocketChannel;
import java.util.Iterator; import java.nio.channels.Selector;
import java.nio.channels.SelectionKey;
import java.nio.ByteBuffer;
import java.io.IOException;
import java.util.Set; import java.util.Set;
import java.util.Iterator;
import java.net.InetSocketAddress;
import java.io.File;
public class EchoServer { public class EchoServer {
@ -49,6 +49,7 @@ public class EchoServer {
} }
} }
public static Process start() throws IOException, InterruptedException { public static Process start() throws IOException, InterruptedException {
String javaHome = System.getProperty("java.home"); String javaHome = System.getProperty("java.home");
String javaBin = javaHome + File.separator + "bin" + File.separator + "java"; String javaBin = javaHome + File.separator + "bin" + File.separator + "java";

View File

@ -0,0 +1,104 @@
package com.baeldung.java.networking.url;
import static org.junit.Assert.assertEquals;
import java.net.MalformedURLException;
import java.net.URL;
import org.junit.Test;
public class UrlTest {
@Test
public void givenUrl_whenCanIdentifyProtocol_thenCorrect() throws MalformedURLException {
URL url = new URL("http://baeldung.com");
assertEquals("http", url.getProtocol());
}
@Test
public void givenUrl_whenCanGetHost_thenCorrect() throws MalformedURLException {
URL url = new URL("http://baeldung.com");
assertEquals("baeldung.com", url.getHost());
}
@Test
public void givenUrl_whenCanGetFileName_thenCorrect2() throws MalformedURLException {
URL url = new URL("http://baeldung.com/articles?topic=java&version=8");
assertEquals("/articles?topic=java&version=8", url.getFile());
}
@Test
public void givenUrl_whenCanGetFileName_thenCorrect1() throws MalformedURLException {
URL url = new URL("http://baeldung.com/guidelines.txt");
assertEquals("/guidelines.txt", url.getFile());
}
@Test
public void givenUrl_whenCanGetPathParams_thenCorrect() throws MalformedURLException {
URL url = new URL("http://baeldung.com/articles?topic=java&version=8");
assertEquals("/articles", url.getPath());
}
@Test
public void givenUrl_whenCanGetQueryParams_thenCorrect() throws MalformedURLException {
URL url = new URL("http://baeldung.com/articles?topic=java");
assertEquals("topic=java", url.getQuery());
}
@Test
public void givenUrl_whenGetsDefaultPort_thenCorrect() throws MalformedURLException {
URL url = new URL("http://baeldung.com");
assertEquals(-1, url.getPort());
assertEquals(80, url.getDefaultPort());
}
@Test
public void givenUrl_whenGetsPort_thenCorrect() throws MalformedURLException {
URL url = new URL("http://baeldung.com:8090");
assertEquals(8090, url.getPort());
assertEquals(80, url.getDefaultPort());
}
@Test
public void givenBaseUrl_whenCreatesRelativeUrl_thenCorrect() throws MalformedURLException {
URL baseUrl = new URL("http://baeldung.com");
URL relativeUrl = new URL(baseUrl, "a-guide-to-java-sockets");
assertEquals("http://baeldung.com/a-guide-to-java-sockets", relativeUrl.toString());
}
@Test
public void givenAbsoluteUrl_whenIgnoresBaseUrl_thenCorrect() throws MalformedURLException {
URL baseUrl = new URL("http://baeldung.com");
URL relativeUrl = new URL(baseUrl, "http://baeldung.com/a-guide-to-java-sockets");
assertEquals("http://baeldung.com/a-guide-to-java-sockets", relativeUrl.toString());
}
@Test
public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException {
String protocol = "http";
String host = "baeldung.com";
String file = "/guidelines.txt";
URL url = new URL(protocol, host, file);
assertEquals("http://baeldung.com/guidelines.txt", url.toString());
}
@Test
public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect2() throws MalformedURLException {
String protocol = "http";
String host = "baeldung.com";
String file = "/articles?topic=java&version=8";
URL url = new URL(protocol, host, file);
assertEquals("http://baeldung.com/guidelines.txt", url.toString());
}
@Test
public void givenUrlComponentsWithPort_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException {
String protocol = "http";
String host = "baeldung.com";
int port = 9000;
String file = "/guidelines.txt";
URL url = new URL(protocol, host, port, file);
assertEquals("http://baeldung.com:9000/guidelines.txt", url.toString());
}
}

View File

@ -16,6 +16,7 @@ public class EchoTest {
String resp2 = client.sendMessage("world"); String resp2 = client.sendMessage("world");
assertEquals("hello", resp1); assertEquals("hello", resp1);
assertEquals("world", resp2); assertEquals("world", resp2);
process.destroy(); process.destroy();
} }
} }

View File

@ -0,0 +1,172 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import model.Student;
import play.test.*;
import static play.test.Helpers.*;
public class ApplicationTest{
private static final String BASE_URL = "http://localhost:9000";
@Test
public void testInServer() throws Exception {
TestServer server = testServer(3333);
running(server, () -> {
try {
WSClient ws = play.libs.ws.WS.newClient(3333);
CompletionStage<WSResponse> completionStage = ws.url("/").get();
WSResponse response = completionStage.toCompletableFuture().get();
ws.close();
assertEquals(OK, response.getStatus());
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
});
}
@Test
public void whenCreatesRecord_thenCorrect() {
Student student = new Student("jody", "west", 50);
JSONObject obj = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student)));
assertTrue(obj.getBoolean("isSuccessfull"));
JSONObject body = obj.getJSONObject("body");
assertEquals(student.getAge(), body.getInt("age"));
assertEquals(student.getFirstName(), body.getString("firstName"));
assertEquals(student.getLastName(), body.getString("lastName"));
}
@Test
public void whenDeletesCreatedRecord_thenCorrect() {
Student student = new Student("Usain", "Bolt", 25);
JSONObject ob1 = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student))).getJSONObject("body");
int id = ob1.getInt("id");
JSONObject obj1 = new JSONObject(makeRequest(BASE_URL + "/" + id, "POST", new JSONObject()));
assertTrue(obj1.getBoolean("isSuccessfull"));
makeRequest(BASE_URL + "/" + id, "DELETE", null);
JSONObject obj2 = new JSONObject(makeRequest(BASE_URL + "/" + id, "POST", new JSONObject()));
assertFalse(obj2.getBoolean("isSuccessfull"));
}
@Test
public void whenUpdatesCreatedRecord_thenCorrect() {
Student student = new Student("john", "doe", 50);
JSONObject body1 = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student))).getJSONObject("body");
assertEquals(student.getAge(), body1.getInt("age"));
int newAge = 60;
body1.put("age", newAge);
JSONObject body2 = new JSONObject(makeRequest(BASE_URL, "PUT", body1)).getJSONObject("body");
assertFalse(student.getAge() == body2.getInt("age"));
assertTrue(newAge == body2.getInt("age"));
}
@Test
public void whenGetsAllRecords_thenCorrect() {
Student student1 = new Student("jane", "daisy", 50);
Student student2 = new Student("john", "daniel", 60);
Student student3 = new Student("don", "mason", 55);
Student student4 = new Student("scarlet", "ohara", 90);
makeRequest(BASE_URL, "POST", new JSONObject(student1));
makeRequest(BASE_URL, "POST", new JSONObject(student2));
makeRequest(BASE_URL, "POST", new JSONObject(student3));
makeRequest(BASE_URL, "POST", new JSONObject(student4));
JSONObject objects = new JSONObject(makeRequest(BASE_URL, "GET", null));
assertTrue(objects.getBoolean("isSuccessfull"));
JSONArray array = objects.getJSONArray("body");
assertTrue(array.length() >= 4);
}
public static String makeRequest(String myUrl, String httpMethod, JSONObject parameters) {
URL url = null;
try {
url = new URL(myUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
conn.setDoInput(true);
conn.setReadTimeout(10000);
conn.setRequestProperty("Content-Type", "application/json");
DataOutputStream dos = null;
int respCode = 0;
String inputString = null;
try {
conn.setRequestMethod(httpMethod);
if (Arrays.asList("POST", "PUT").contains(httpMethod)) {
String params = parameters.toString();
conn.setDoOutput(true);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(params);
dos.flush();
dos.close();
}
respCode = conn.getResponseCode();
if (respCode != 200 && respCode != 201) {
String error = inputStreamToString(conn.getErrorStream());
return error;
}
inputString = inputStreamToString(conn.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
return inputString;
}
public static String inputStreamToString(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
}