Merge branch 'master' into master

This commit is contained in:
binary-joe
2019-09-14 18:33:59 +02:00
committed by GitHub
1623 changed files with 248849 additions and 8250 deletions

View File

@@ -0,0 +1,29 @@
package com.baeldung.curltojava;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
public class JavaCurlExamples {
public static String inputStreamToString(InputStream inputStream) {
final int bufferSize = 8 * 1024;
byte[] buffer = new byte[bufferSize];
final StringBuilder builder = new StringBuilder();
try (BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream, bufferSize)) {
while (bufferedInputStream.read(buffer) != -1) {
builder.append(new String(buffer));
}
} catch (IOException ex) {
Logger.getLogger(JavaCurlExamples.class.getName()).log(Level.SEVERE, null, ex);
}
return builder.toString();
}
public static void consumeInputStream(InputStream inputStream) {
inputStreamToString(inputStream);
}
}

View File

@@ -0,0 +1,65 @@
package com.baeldung.httprequest;
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();
}
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.httprequest;
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;
}
}

View File

@@ -0,0 +1,77 @@
package com.baeldung.mail;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.util.Properties;
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");
}
}

View File

@@ -0,0 +1,46 @@
package com.baeldung.urlconnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class PostJSONWithHttpURLConnection {
public static void main (String []args) throws IOException{
//Change the URL with any other publicly accessible POST resource, which accepts JSON request body
URL url = new URL ("https://reqres.in/api/users");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
//JSON String need to be constructed for the specific resource.
//We may construct complex JSON using any third-party JSON libraries such as jackson or org.json
String jsonInputString = "{\"name\": \"Upendra\", \"job\": \"Programmer\"}";
try(OutputStream os = con.getOutputStream()){
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
int code = con.getResponseCode();
System.out.println(code);
try(BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))){
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
}
}

View File

@@ -0,0 +1,50 @@
package com.baeldung.curltojava;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Assert;
import org.junit.Test;
public class JavaCurlExamplesLiveTest {
@Test
public void givenCommand_whenCalled_thenProduceZeroExitCode() throws IOException {
String command = "curl -X GET https://postman-echo.com/get?foo1=bar1&foo2=bar2";
ProcessBuilder processBuilder = new ProcessBuilder(command.split(" "));
processBuilder.directory(new File("/home/"));
Process process = processBuilder.start();
InputStream inputStream = process.getInputStream();
// Consume the inputStream so the process can exit
JavaCurlExamples.consumeInputStream(inputStream);
int exitCode = process.exitValue();
Assert.assertEquals(0, exitCode);
}
@Test
public void givenNewCommands_whenCalled_thenCheckIfIsAlive() throws IOException {
String command = "curl -X GET https://postman-echo.com/get?foo1=bar1&foo2=bar2";
ProcessBuilder processBuilder = new ProcessBuilder(command.split(" "));
processBuilder.directory(new File("/home/"));
Process process = processBuilder.start();
// Re-use processBuilder
processBuilder.command(new String[]{"newCommand", "arguments"});
Assert.assertEquals(true, process.isAlive());
}
@Test
public void whenRequestPost_thenCheckIfReturnContent() throws IOException {
String command = "curl -X POST https://postman-echo.com/post --data foo1=bar1&foo2=bar2";
Process process = Runtime.getRuntime().exec(command);
// Get the POST result
String content = JavaCurlExamples.inputStreamToString(process.getInputStream());
Assert.assertTrue(null != content && !content.isEmpty());
}
}

View File

@@ -0,0 +1,184 @@
package com.baeldung.httprequest;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import java.io.*;
import java.net.CookieManager;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class HttpRequestLiveTest {
@Test
public void whenGetRequest_thenOk() throws IOException {
URL url = new URL("http://example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
Map<String, String> parameters = new HashMap<>();
parameters.put("param1", "val");
con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.writeBytes(ParameterStringBuilder.getParamsString(parameters));
out.flush();
out.close();
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
assertEquals("status code incorrect", status, 200);
assertTrue("content incorrect", content.toString()
.contains("Example Domain"));
}
@Test
public void whenPostRequest_thenOk() throws IOException {
URL url = new URL("http://example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
Map<String, String> parameters = new HashMap<>();
parameters.put("param1", "val");
con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.writeBytes(ParameterStringBuilder.getParamsString(parameters));
out.flush();
out.close();
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
assertEquals("status code incorrect", status, 200);
}
@Test
public void whenGetCookies_thenOk() throws IOException {
URL url = new URL("http://example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
CookieManager cookieManager = new CookieManager();
String cookiesHeader = con.getHeaderField("Set-Cookie");
Optional<HttpCookie> usernameCookie = null;
if (cookiesHeader != null) {
List<HttpCookie> cookies = HttpCookie.parse(cookiesHeader);
cookies.forEach(cookie -> cookieManager.getCookieStore()
.add(null, cookie));
usernameCookie = cookies.stream()
.findAny()
.filter(cookie -> cookie.getName()
.equals("username"));
}
if (usernameCookie == null) {
cookieManager.getCookieStore()
.add(null, new HttpCookie("username", "john"));
}
con.disconnect();
con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Cookie", StringUtils.join(cookieManager.getCookieStore()
.getCookies(), ";"));
int status = con.getResponseCode();
assertEquals("status code incorrect", status, 200);
}
@Test
public void whenRedirect_thenOk() throws IOException {
URL url = new URL("http://example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setInstanceFollowRedirects(true);
int status = con.getResponseCode();
if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM) {
String location = con.getHeaderField("Location");
URL newUrl = new URL(location);
con = (HttpURLConnection) newUrl.openConnection();
}
assertEquals("status code incorrect", con.getResponseCode(), 200);
}
@Test
public void whenFailedRequest_thenOk() throws IOException {
URL url = new URL("http://example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
int status = con.getResponseCode();
Reader streamReader = null;
if (status > 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();
con.disconnect();
assertEquals("status code incorrect", status, 411);
assertTrue("error content", content.toString()
.contains("411 - Length Required"));
}
@Test
public void whenGetRequestFullResponse_thenOk() throws IOException {
URL url = new URL("http://example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
String fullResponse = FullResponseBuilder.getFullResponse(con);
con.disconnect();
assertEquals("status code incorrect", con.getResponseCode(), 200);
assertTrue("header incorrect", fullResponse.contains("Content-Type: text/html; charset=UTF-8"));
assertTrue("response incorrect", fullResponse.contains("<!doctype html><html><head>"));
}
}