[BAEL-9555] - Created a core-java-modules folder
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
package com.baeldung.http;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.Reader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
public class FullResponseBuilder {
|
||||
public static String getFullResponse(HttpURLConnection con) throws IOException {
|
||||
StringBuilder fullResponseBuilder = new StringBuilder();
|
||||
|
||||
fullResponseBuilder.append(con.getResponseCode())
|
||||
.append(" ")
|
||||
.append(con.getResponseMessage())
|
||||
.append("\n");
|
||||
|
||||
con.getHeaderFields()
|
||||
.entrySet()
|
||||
.stream()
|
||||
.filter(entry -> entry.getKey() != null)
|
||||
.forEach(entry -> {
|
||||
|
||||
fullResponseBuilder.append(entry.getKey())
|
||||
.append(": ");
|
||||
|
||||
List<String> headerValues = entry.getValue();
|
||||
Iterator<String> it = headerValues.iterator();
|
||||
if (it.hasNext()) {
|
||||
fullResponseBuilder.append(it.next());
|
||||
|
||||
while (it.hasNext()) {
|
||||
fullResponseBuilder.append(", ")
|
||||
.append(it.next());
|
||||
}
|
||||
}
|
||||
|
||||
fullResponseBuilder.append("\n");
|
||||
});
|
||||
|
||||
Reader streamReader = null;
|
||||
|
||||
if (con.getResponseCode() > 299) {
|
||||
streamReader = new InputStreamReader(con.getErrorStream());
|
||||
} else {
|
||||
streamReader = new InputStreamReader(con.getInputStream());
|
||||
}
|
||||
|
||||
BufferedReader in = new BufferedReader(streamReader);
|
||||
String inputLine;
|
||||
StringBuilder content = new StringBuilder();
|
||||
while ((inputLine = in.readLine()) != null) {
|
||||
content.append(inputLine);
|
||||
}
|
||||
|
||||
in.close();
|
||||
|
||||
fullResponseBuilder.append("Response: ")
|
||||
.append(content);
|
||||
|
||||
return fullResponseBuilder.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.http;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.Map;
|
||||
|
||||
public class ParameterStringBuilder {
|
||||
public static String getParamsString(Map<String, String> params) throws UnsupportedEncodingException {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
for (Map.Entry<String, String> entry : params.entrySet()) {
|
||||
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
|
||||
result.append("=");
|
||||
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
|
||||
result.append("&");
|
||||
}
|
||||
|
||||
String resultString = result.toString();
|
||||
return resultString.length() > 0 ? resultString.substring(0, resultString.length() - 1) : resultString;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.baeldung.mail;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Properties;
|
||||
import javax.mail.*;
|
||||
import javax.mail.internet.InternetAddress;
|
||||
import javax.mail.internet.MimeBodyPart;
|
||||
import javax.mail.internet.MimeMessage;
|
||||
import javax.mail.internet.MimeMultipart;
|
||||
|
||||
public class EmailService {
|
||||
|
||||
private String host = "";
|
||||
private int port = 0;
|
||||
private String username = "";
|
||||
private String password = "";
|
||||
|
||||
|
||||
public EmailService(String host, int port, String username, String password) {
|
||||
|
||||
this.host = host;
|
||||
this.port = port;
|
||||
this.username = username;
|
||||
this.password = password;
|
||||
|
||||
sendMail();
|
||||
}
|
||||
|
||||
private void sendMail() {
|
||||
|
||||
Properties prop = new Properties();
|
||||
prop.put("mail.smtp.auth", true);
|
||||
prop.put("mail.smtp.starttls.enable", "true");
|
||||
prop.put("mail.smtp.host", host);
|
||||
prop.put("mail.smtp.port", port);
|
||||
prop.put("mail.smtp.ssl.trust", host);
|
||||
|
||||
Session session = Session.getInstance(prop, new Authenticator() {
|
||||
@Override
|
||||
protected PasswordAuthentication getPasswordAuthentication() {
|
||||
return new PasswordAuthentication(username, password);
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
|
||||
Message message = new MimeMessage(session);
|
||||
message.setFrom(new InternetAddress("from@gmail.com"));
|
||||
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@gmail.com"));
|
||||
message.setSubject("Mail Subject");
|
||||
|
||||
String msg = "This is my first email using JavaMailer";
|
||||
|
||||
MimeBodyPart mimeBodyPart = new MimeBodyPart();
|
||||
mimeBodyPart.setContent(msg, "text/html");
|
||||
|
||||
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
|
||||
attachmentBodyPart.attachFile(new File("pom.xml"));
|
||||
|
||||
Multipart multipart = new MimeMultipart();
|
||||
multipart.addBodyPart(mimeBodyPart);
|
||||
multipart.addBodyPart(attachmentBodyPart);
|
||||
|
||||
message.setContent(multipart);
|
||||
|
||||
Transport.send(message);
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String ... args) {
|
||||
new EmailService("smtp.mailtrap.io", 25, "87ba3d9555fae8", "91cb4379af43ed");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.baeldung.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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.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 true;
|
||||
}
|
||||
|
||||
return CookiePolicy.ACCEPT_ORIGINAL_SERVER.shouldAccept(uri, cookie);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.networking.proxies;
|
||||
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
|
||||
public class CommandLineProxyDemo {
|
||||
|
||||
public static final String RESOURCE_URL = "http://www.google.com";
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
URL url = new URL(RESOURCE_URL);
|
||||
URLConnection con = url.openConnection();
|
||||
System.out.println(UrlConnectionUtils.contentAsString(con));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.networking.proxies;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.Proxy;
|
||||
import java.net.URL;
|
||||
|
||||
public class DirectProxyDemo {
|
||||
|
||||
private static final String URL_STRING = "http://www.google.com";
|
||||
|
||||
public static void main(String... args) throws IOException {
|
||||
|
||||
URL weburl = new URL(URL_STRING);
|
||||
HttpURLConnection directConnection
|
||||
= (HttpURLConnection) weburl.openConnection(Proxy.NO_PROXY);
|
||||
System.out.println(UrlConnectionUtils.contentAsString(directConnection));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.networking.proxies;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Proxy;
|
||||
import java.net.Socket;
|
||||
import java.net.URL;
|
||||
|
||||
public class SocksProxyDemo {
|
||||
|
||||
private static final String URL_STRING = "http://www.google.com";
|
||||
private static final String SOCKET_SERVER_HOST = "someserver.baeldung.com";
|
||||
private static final int SOCKET_SERVER_PORT = 1111;
|
||||
|
||||
public static void main(String... args) throws IOException {
|
||||
|
||||
URL weburl = new URL(URL_STRING);
|
||||
Proxy socksProxy
|
||||
= new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("127.0.0.1", 1080));
|
||||
HttpURLConnection socksConnection
|
||||
= (HttpURLConnection) weburl.openConnection(socksProxy);
|
||||
System.out.println(UrlConnectionUtils.contentAsString(socksConnection));
|
||||
|
||||
Socket proxySocket = new Socket(socksProxy);
|
||||
InetSocketAddress socketHost
|
||||
= new InetSocketAddress(SOCKET_SERVER_HOST, SOCKET_SERVER_PORT);
|
||||
proxySocket.connect(socketHost);
|
||||
// do stuff with the socket
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.networking.proxies;
|
||||
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
|
||||
public class SystemPropertyProxyDemo {
|
||||
|
||||
public static final String RESOURCE_URL = "http://www.google.com";
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
System.setProperty("http.proxyHost", "127.0.0.1");
|
||||
System.setProperty("http.proxyPort", "3128");
|
||||
|
||||
URL url = new URL(RESOURCE_URL);
|
||||
URLConnection con = url.openConnection();
|
||||
System.out.println(UrlConnectionUtils.contentAsString(con));
|
||||
|
||||
System.setProperty("http.proxyHost", null);
|
||||
// proxy will no longer be used for http connections
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.networking.proxies;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.URLConnection;
|
||||
|
||||
class UrlConnectionUtils {
|
||||
|
||||
public static String contentAsString(URLConnection con) throws IOException {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
try (BufferedReader reader
|
||||
= new BufferedReader(new InputStreamReader(con.getInputStream()))){
|
||||
while (reader.ready()) {
|
||||
builder.append(reader.readLine());
|
||||
}
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.networking.proxies;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Proxy;
|
||||
import java.net.URL;
|
||||
|
||||
public class WebProxyDemo {
|
||||
|
||||
private static final String URL_STRING = "http://www.google.com";
|
||||
|
||||
public static void main(String... args) throws IOException {
|
||||
|
||||
URL weburl = new URL(URL_STRING);
|
||||
Proxy webProxy
|
||||
= new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 3128));
|
||||
HttpURLConnection webProxyConnection
|
||||
= (HttpURLConnection) weburl.openConnection(webProxy);
|
||||
System.out.println(UrlConnectionUtils.contentAsString(webProxyConnection));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.baeldung.networking.udp.broadcast;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.InetAddress;
|
||||
import java.net.NetworkInterface;
|
||||
import java.net.SocketException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Enumeration;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class BroadcastingClient {
|
||||
private DatagramSocket socket;
|
||||
private InetAddress address;
|
||||
private int expectedServerCount;
|
||||
private byte[] buf;
|
||||
|
||||
public BroadcastingClient(int expectedServerCount) throws Exception {
|
||||
this.expectedServerCount = expectedServerCount;
|
||||
this.address = InetAddress.getByName("255.255.255.255");
|
||||
}
|
||||
|
||||
public int discoverServers(String msg) throws IOException {
|
||||
initializeSocketForBroadcasting();
|
||||
copyMessageOnBuffer(msg);
|
||||
|
||||
// When we want to broadcast not just to local network, call listAllBroadcastAddresses() and execute broadcastPacket for each value.
|
||||
broadcastPacket(address);
|
||||
|
||||
return receivePackets();
|
||||
}
|
||||
|
||||
List<InetAddress> listAllBroadcastAddresses() throws SocketException {
|
||||
List<InetAddress> broadcastList = new ArrayList<>();
|
||||
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
|
||||
while (interfaces.hasMoreElements()) {
|
||||
NetworkInterface networkInterface = interfaces.nextElement();
|
||||
|
||||
if (networkInterface.isLoopback() || !networkInterface.isUp()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
broadcastList.addAll(networkInterface.getInterfaceAddresses()
|
||||
.stream()
|
||||
.filter(address -> address.getBroadcast() != null)
|
||||
.map(address -> address.getBroadcast())
|
||||
.collect(Collectors.toList()));
|
||||
}
|
||||
return broadcastList;
|
||||
}
|
||||
|
||||
private void initializeSocketForBroadcasting() throws SocketException {
|
||||
socket = new DatagramSocket();
|
||||
socket.setBroadcast(true);
|
||||
}
|
||||
|
||||
private void copyMessageOnBuffer(String msg) {
|
||||
buf = msg.getBytes();
|
||||
}
|
||||
|
||||
private void broadcastPacket(InetAddress address) throws IOException {
|
||||
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445);
|
||||
socket.send(packet);
|
||||
}
|
||||
|
||||
private int receivePackets() throws IOException {
|
||||
int serversDiscovered = 0;
|
||||
while (serversDiscovered != expectedServerCount) {
|
||||
receivePacket();
|
||||
serversDiscovered++;
|
||||
}
|
||||
return serversDiscovered;
|
||||
}
|
||||
|
||||
private void receivePacket() throws IOException {
|
||||
DatagramPacket packet = new DatagramPacket(buf, buf.length);
|
||||
socket.receive(packet);
|
||||
}
|
||||
|
||||
public void close() {
|
||||
socket.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.networking.udp.broadcast;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
|
||||
public class BroadcastingEchoServer extends Thread {
|
||||
|
||||
protected DatagramSocket socket = null;
|
||||
protected boolean running;
|
||||
protected byte[] buf = new byte[256];
|
||||
|
||||
public BroadcastingEchoServer() throws IOException {
|
||||
socket = new DatagramSocket(null);
|
||||
socket.setReuseAddress(true);
|
||||
socket.bind(new InetSocketAddress(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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.networking.udp.multicast;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.InetAddress;
|
||||
import java.net.MulticastSocket;
|
||||
|
||||
public class MulticastEchoServer extends Thread {
|
||||
|
||||
protected MulticastSocket socket = null;
|
||||
protected byte[] buf = new byte[256];
|
||||
protected InetAddress group = null;
|
||||
|
||||
public MulticastEchoServer() throws IOException {
|
||||
socket = new MulticastSocket(4446);
|
||||
socket.setReuseAddress(true);
|
||||
group = InetAddress.getByName("230.0.0.0");
|
||||
socket.joinGroup(group);
|
||||
}
|
||||
|
||||
public void run() {
|
||||
try {
|
||||
while (true) {
|
||||
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")) {
|
||||
break;
|
||||
}
|
||||
socket.send(packet);
|
||||
}
|
||||
socket.leaveGroup(group);
|
||||
socket.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.baeldung.networking.udp.multicast;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.InetAddress;
|
||||
|
||||
public class MulticastingClient {
|
||||
private DatagramSocket socket;
|
||||
private InetAddress group;
|
||||
private int expectedServerCount;
|
||||
private byte[] buf;
|
||||
|
||||
public MulticastingClient(int expectedServerCount) throws Exception {
|
||||
this.expectedServerCount = expectedServerCount;
|
||||
this.socket = new DatagramSocket();
|
||||
this.group = InetAddress.getByName("230.0.0.0");
|
||||
}
|
||||
|
||||
public int discoverServers(String msg) throws IOException {
|
||||
copyMessageOnBuffer(msg);
|
||||
multicastPacket();
|
||||
|
||||
return receivePackets();
|
||||
}
|
||||
|
||||
private void copyMessageOnBuffer(String msg) {
|
||||
buf = msg.getBytes();
|
||||
}
|
||||
|
||||
private void multicastPacket() throws IOException {
|
||||
DatagramPacket packet = new DatagramPacket(buf, buf.length, group, 4446);
|
||||
socket.send(packet);
|
||||
}
|
||||
|
||||
private int receivePackets() throws IOException {
|
||||
int serversDiscovered = 0;
|
||||
while (serversDiscovered != expectedServerCount) {
|
||||
receivePacket();
|
||||
serversDiscovered++;
|
||||
}
|
||||
return serversDiscovered;
|
||||
}
|
||||
|
||||
private void receivePacket() throws IOException {
|
||||
DatagramPacket packet = new DatagramPacket(buf, buf.length);
|
||||
socket.receive(packet);
|
||||
}
|
||||
|
||||
public void close() {
|
||||
socket.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.baeldung.networking.uriurl;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class URIDemo {
|
||||
private final Logger logger = LoggerFactory.getLogger(URIDemo.class);
|
||||
|
||||
String URISTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484";
|
||||
// parsed locator
|
||||
String URISCHEME = "https";
|
||||
String URISCHEMESPECIFIC;
|
||||
String URIHOST = "wordpress.org";
|
||||
String URIAUTHORITY = "wordpress.org:443";
|
||||
|
||||
String URIPATH = "/support/topic/page-jumps-within-wordpress/";
|
||||
int URIPORT = 443;
|
||||
String URIQUERY = "replies=3";
|
||||
String URIFRAGMENT = "post-2278484";
|
||||
String URIUSERINFO;
|
||||
String URICOMPOUND = URISCHEME + "://" + URIHOST + ":" + URIPORT + URIPATH + "?" + URIQUERY + "#" + URIFRAGMENT;
|
||||
|
||||
URI uri;
|
||||
URL url;
|
||||
BufferedReader in = null;
|
||||
String URIContent = "";
|
||||
|
||||
private String getParsedPieces(URI uri) {
|
||||
logger.info("*** List of parsed pieces ***");
|
||||
URISCHEME = uri.getScheme();
|
||||
logger.info("URISCHEME: " + URISCHEME);
|
||||
URISCHEMESPECIFIC = uri.getSchemeSpecificPart();
|
||||
logger.info("URISCHEMESPECIFIC: " + URISCHEMESPECIFIC);
|
||||
URIHOST = uri.getHost();
|
||||
URIAUTHORITY = uri.getAuthority();
|
||||
logger.info("URIAUTHORITY: " + URIAUTHORITY);
|
||||
logger.info("URIHOST: " + URIHOST);
|
||||
URIPATH = uri.getPath();
|
||||
logger.info("URIPATH: " + URIPATH);
|
||||
URIPORT = uri.getPort();
|
||||
logger.info("URIPORT: " + URIPORT);
|
||||
URIQUERY = uri.getQuery();
|
||||
logger.info("URIQUERY: " + URIQUERY);
|
||||
URIFRAGMENT = uri.getFragment();
|
||||
logger.info("URIFRAGMENT: " + URIFRAGMENT);
|
||||
|
||||
try {
|
||||
url = uri.toURL();
|
||||
} catch (MalformedURLException e) {
|
||||
logger.info("MalformedURLException thrown: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
} catch (IllegalArgumentException e) {
|
||||
logger.info("IllegalArgumentException thrown: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
public String testURIAsNew(String URIString) {
|
||||
// creating URI object
|
||||
try {
|
||||
uri = new URI(URIString);
|
||||
} catch (URISyntaxException e) {
|
||||
logger.info("URISyntaxException thrown: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
return getParsedPieces(uri);
|
||||
}
|
||||
|
||||
public String testURIAsCreate(String URIString) {
|
||||
// creating URI object
|
||||
uri = URI.create(URIString);
|
||||
return getParsedPieces(uri);
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
URIDemo demo = new URIDemo();
|
||||
String contentCreate = demo.testURIAsCreate(demo.URICOMPOUND);
|
||||
demo.logger.info(contentCreate);
|
||||
String contentNew = demo.testURIAsNew(demo.URICOMPOUND);
|
||||
demo.logger.info(contentNew);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.baeldung.networking.uriurl;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URI;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class URLDemo {
|
||||
private final Logger log = LoggerFactory.getLogger(URLDemo.class);
|
||||
|
||||
String URLSTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484";
|
||||
// parsed locator
|
||||
String URLPROTOCOL = "https";
|
||||
// final static String URLAUTHORITY = "wordpress.org:443";
|
||||
String URLHOST = "wordpress.org";
|
||||
String URLPATH = "/support/topic/page-jumps-within-wordpress/";
|
||||
// final static String URLFILENAME = "/support/topic/page-jumps-within-wordpress/?replies=3";
|
||||
// final static int URLPORT = 443;
|
||||
int URLDEFAULTPORT = 443;
|
||||
String URLQUERY = "replies=3";
|
||||
String URLREFERENCE = "post-2278484";
|
||||
String URLCOMPOUND = URLPROTOCOL + "://" + URLHOST + ":" + URLDEFAULTPORT + URLPATH + "?" + URLQUERY + "#" + URLREFERENCE;
|
||||
|
||||
URL url;
|
||||
URLConnection urlConnection = null;
|
||||
HttpURLConnection connection = null;
|
||||
BufferedReader in = null;
|
||||
String urlContent = "";
|
||||
|
||||
public String testURL(String urlString) throws IOException, IllegalArgumentException {
|
||||
String urlStringCont = "";
|
||||
// comment the if clause if experiment with URL
|
||||
/*if (!URLSTRING.equals(urlString)) {
|
||||
throw new IllegalArgumentException("URL String argument is not proper: " + urlString);
|
||||
}*/
|
||||
// creating URL object
|
||||
url = new URL(urlString);
|
||||
// get URL connection
|
||||
urlConnection = url.openConnection();
|
||||
connection = null;
|
||||
// we can check, if connection is proper type
|
||||
if (urlConnection instanceof HttpURLConnection) {
|
||||
connection = (HttpURLConnection) urlConnection;
|
||||
} else {
|
||||
log.info("Please enter an HTTP URL");
|
||||
throw new IOException("HTTP URL is not correct");
|
||||
}
|
||||
// we can check response code (200 OK is expected)
|
||||
log.info(connection.getResponseCode() + " " + connection.getResponseMessage());
|
||||
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
|
||||
String current;
|
||||
|
||||
while ((current = in.readLine()) != null) {
|
||||
urlStringCont += current;
|
||||
}
|
||||
return urlStringCont;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
URLDemo demo = new URLDemo();
|
||||
String content = demo.testURL(demo.URLCOMPOUND);
|
||||
demo.log.info(content);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.socket;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
|
||||
public class EchoClient {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(EchoClient.class);
|
||||
|
||||
private Socket clientSocket;
|
||||
private PrintWriter out;
|
||||
private BufferedReader in;
|
||||
|
||||
public void startConnection(String ip, int port) {
|
||||
try {
|
||||
clientSocket = new Socket(ip, port);
|
||||
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
||||
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
|
||||
} catch (IOException e) {
|
||||
LOG.debug("Error when initializing connection", e);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public String sendMessage(String msg) {
|
||||
try {
|
||||
out.println(msg);
|
||||
return in.readLine();
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void stopConnection() {
|
||||
try {
|
||||
in.close();
|
||||
out.close();
|
||||
clientSocket.close();
|
||||
} catch (IOException e) {
|
||||
LOG.debug("error when closing", e);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.baeldung.socket;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.net.*;
|
||||
import java.io.*;
|
||||
|
||||
public class EchoMultiServer {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(EchoMultiServer.class);
|
||||
|
||||
private ServerSocket serverSocket;
|
||||
|
||||
public void start(int port) {
|
||||
try {
|
||||
serverSocket = new ServerSocket(port);
|
||||
while (true)
|
||||
new EchoClientHandler(serverSocket.accept()).start();
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
stop();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
try {
|
||||
|
||||
serverSocket.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static class EchoClientHandler extends Thread {
|
||||
private Socket clientSocket;
|
||||
private PrintWriter out;
|
||||
private BufferedReader in;
|
||||
|
||||
public EchoClientHandler(Socket socket) {
|
||||
this.clientSocket = socket;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
try {
|
||||
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
||||
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
|
||||
String inputLine;
|
||||
while ((inputLine = in.readLine()) != null) {
|
||||
if (".".equals(inputLine)) {
|
||||
out.println("bye");
|
||||
break;
|
||||
}
|
||||
out.println(inputLine);
|
||||
}
|
||||
|
||||
in.close();
|
||||
out.close();
|
||||
clientSocket.close();
|
||||
|
||||
} catch (IOException e) {
|
||||
LOG.debug(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
EchoMultiServer server = new EchoMultiServer();
|
||||
server.start(5555);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.baeldung.socket;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.net.*;
|
||||
import java.io.*;
|
||||
|
||||
public class EchoServer {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(EchoServer.class);
|
||||
|
||||
private ServerSocket serverSocket;
|
||||
private Socket clientSocket;
|
||||
private PrintWriter out;
|
||||
private BufferedReader in;
|
||||
|
||||
public void start(int port) {
|
||||
try {
|
||||
serverSocket = new ServerSocket(port);
|
||||
clientSocket = serverSocket.accept();
|
||||
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
||||
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
|
||||
String inputLine;
|
||||
while ((inputLine = in.readLine()) != null) {
|
||||
if (".".equals(inputLine)) {
|
||||
out.println("good bye");
|
||||
break;
|
||||
}
|
||||
out.println(inputLine);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
LOG.debug(e.getMessage());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
try {
|
||||
in.close();
|
||||
out.close();
|
||||
clientSocket.close();
|
||||
serverSocket.close();
|
||||
} catch (IOException e) {
|
||||
LOG.debug(e.getMessage());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
EchoServer server = new EchoServer();
|
||||
server.start(4444);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.socket;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.PrintWriter;
|
||||
import java.net.Socket;
|
||||
|
||||
public class GreetClient {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(EchoMultiServer.class);
|
||||
|
||||
private Socket clientSocket;
|
||||
private PrintWriter out;
|
||||
private BufferedReader in;
|
||||
|
||||
public void startConnection(String ip, int port) {
|
||||
try {
|
||||
clientSocket = new Socket(ip, port);
|
||||
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
||||
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
|
||||
} catch (IOException e) {
|
||||
LOG.debug(e.getMessage());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public String sendMessage(String msg) {
|
||||
try {
|
||||
out.println(msg);
|
||||
return in.readLine();
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void stopConnection() {
|
||||
try {
|
||||
in.close();
|
||||
out.close();
|
||||
clientSocket.close();
|
||||
} catch (IOException e) {
|
||||
LOG.debug(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.socket;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.net.*;
|
||||
import java.io.*;
|
||||
|
||||
public class GreetServer {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(GreetServer.class);
|
||||
|
||||
private ServerSocket serverSocket;
|
||||
private Socket clientSocket;
|
||||
private PrintWriter out;
|
||||
private BufferedReader in;
|
||||
|
||||
public void start(int port) {
|
||||
try {
|
||||
serverSocket = new ServerSocket(port);
|
||||
clientSocket = serverSocket.accept();
|
||||
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
||||
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
|
||||
String greeting = in.readLine();
|
||||
if ("hello server".equals(greeting))
|
||||
out.println("hello client");
|
||||
else
|
||||
out.println("unrecognised greeting");
|
||||
} catch (IOException e) {
|
||||
LOG.debug(e.getMessage());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
try {
|
||||
in.close();
|
||||
out.close();
|
||||
clientSocket.close();
|
||||
serverSocket.close();
|
||||
} catch (IOException e) {
|
||||
LOG.debug(e.getMessage());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
GreetServer server = new GreetServer();
|
||||
server.start(6666);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.socket.read;
|
||||
|
||||
import java.net.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.io.*;
|
||||
|
||||
public class Client {
|
||||
|
||||
public void runClient(String ip, int port) {
|
||||
try {
|
||||
Socket socket = new Socket(ip, port);
|
||||
System.out.println("Connected to server ...");
|
||||
DataInputStream in = new DataInputStream(System.in);
|
||||
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
|
||||
|
||||
char type = 's'; // s for string
|
||||
int length = 29;
|
||||
String data = "This is a string of length 29";
|
||||
byte[] dataInBytes = data.getBytes(StandardCharsets.UTF_8);
|
||||
//Sending data in TLV format
|
||||
out.writeChar(type);
|
||||
out.writeInt(length);
|
||||
out.write(dataInBytes);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.baeldung.socket.read;
|
||||
|
||||
import java.net.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.io.*;
|
||||
|
||||
public class Server {
|
||||
|
||||
public void runServer(int port) {
|
||||
//Start the server and wait for connection
|
||||
try {
|
||||
ServerSocket server = new ServerSocket(port);
|
||||
System.out.println("Server Started. Waiting for connection ...");
|
||||
Socket socket = server.accept();
|
||||
System.out.println("Got connection from client.");
|
||||
//Get input stream from socket variable and convert the same to DataInputStream
|
||||
DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
|
||||
//Read type and length of data
|
||||
char dataType = in.readChar();
|
||||
int length = in.readInt();
|
||||
System.out.println("Type : "+dataType);
|
||||
System.out.println("Lenght :"+length);
|
||||
if(dataType == 's') {
|
||||
//Read String data in bytes
|
||||
byte[] messageByte = new byte[length];
|
||||
boolean end = false;
|
||||
StringBuilder dataString = new StringBuilder(length);
|
||||
int totalBytesRead = 0;
|
||||
//We need to run while loop, to read all data in that stream
|
||||
while(!end) {
|
||||
int currentBytesRead = in.read(messageByte);
|
||||
totalBytesRead = currentBytesRead + totalBytesRead;
|
||||
if(totalBytesRead <= length) {
|
||||
dataString.append(new String(messageByte,0,currentBytesRead,StandardCharsets.UTF_8));
|
||||
} else {
|
||||
dataString.append(new String(messageByte,0,length - totalBytesRead + currentBytesRead,StandardCharsets.UTF_8));
|
||||
}
|
||||
if(dataString.length()>=length) {
|
||||
end = true;
|
||||
}
|
||||
}
|
||||
System.out.println("Read "+length+" bytes of message from client. Message = "+dataString);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<logger name="org.springframework" level="WARN" />
|
||||
<logger name="org.springframework.transaction" level="WARN" />
|
||||
|
||||
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
|
||||
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
Reference in New Issue
Block a user