Merge branch 'eugenp:master' into master
This commit is contained in:
@@ -10,7 +10,7 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
|
||||
- [Converting Between Roman and Arabic Numerals in Java](https://www.baeldung.com/java-convert-roman-arabic)
|
||||
- [Practical Java Examples of the Big O Notation](https://www.baeldung.com/java-algorithm-complexity)
|
||||
- [Checking If a List Is Sorted in Java](https://www.baeldung.com/java-check-if-list-sorted)
|
||||
- [Checking if a Java Graph has a Cycle](https://www.baeldung.com/java-graph-has-a-cycle)
|
||||
- [Checking if a Java Graph Has a Cycle](https://www.baeldung.com/java-graph-has-a-cycle)
|
||||
- [A Guide to the Folding Technique in Java](https://www.baeldung.com/folding-hashing-technique)
|
||||
- [Creating a Triangle with for Loops in Java](https://www.baeldung.com/java-print-triangle)
|
||||
- [The K-Means Clustering Algorithm in Java](https://www.baeldung.com/java-k-means-clustering-algorithm)
|
||||
|
||||
@@ -5,10 +5,10 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
|
||||
### Relevant articles:
|
||||
|
||||
- [Multi-Swarm Optimization Algorithm in Java](https://www.baeldung.com/java-multi-swarm-algorithm)
|
||||
- [Check If a String Contains All The Letters of The Alphabet with Java](https://www.baeldung.com/java-string-contains-all-letters)
|
||||
- [Check if a String Contains All the Letters of the Alphabet With Java](https://www.baeldung.com/java-string-contains-all-letters)
|
||||
- [Find the Middle Element of a Linked List in Java](https://www.baeldung.com/java-linked-list-middle-element)
|
||||
- [Find Substrings That Are Palindromes in Java](https://www.baeldung.com/java-palindrome-substrings)
|
||||
- [Find the Longest Substring without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters)
|
||||
- [Find the Longest Substring Without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters)
|
||||
- [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations)
|
||||
- [Find the Smallest Missing Integer in an Array](https://www.baeldung.com/java-smallest-missing-integer-in-array)
|
||||
- [Permutations of a String in Java](https://www.baeldung.com/java-string-permutations)
|
||||
|
||||
@@ -9,7 +9,7 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
|
||||
- [Reversing a Binary Tree in Java](https://www.baeldung.com/java-reversing-a-binary-tree)
|
||||
- [Find If Two Numbers Are Relatively Prime in Java](https://www.baeldung.com/java-two-relatively-prime-numbers)
|
||||
- [Knapsack Problem Implementation in Java](https://www.baeldung.com/java-knapsack)
|
||||
- [How to Determine if a Binary Tree is Balanced in Java](https://www.baeldung.com/java-balanced-binary-tree)
|
||||
- [How to Determine if a Binary Tree Is Balanced in Java](https://www.baeldung.com/java-balanced-binary-tree)
|
||||
- [Overview of Combinatorial Problems in Java](https://www.baeldung.com/java-combinatorial-algorithms)
|
||||
- [Prim’s Algorithm with a Java Implementation](https://www.baeldung.com/java-prim-algorithm)
|
||||
- [Maximum Subarray Problem in Java](https://www.baeldung.com/java-maximum-subarray)
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
### Relevant Articles:
|
||||
|
||||
- [Server-Sent Events (SSE) In JAX-RS](https://www.baeldung.com/java-ee-jax-rs-sse)
|
||||
- [Server-Sent Events (SSE) in JAX-RS](https://www.baeldung.com/java-ee-jax-rs-sse)
|
||||
|
||||
@@ -90,6 +90,12 @@
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mock-server</groupId>
|
||||
<artifactId>mockserver-netty</artifactId>
|
||||
<version>${mockserver.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.github.tomakehurst</groupId>
|
||||
<artifactId>wiremock</artifactId>
|
||||
@@ -112,6 +118,7 @@
|
||||
<!-- util -->
|
||||
<httpasyncclient.version>4.1.4</httpasyncclient.version>
|
||||
<!-- testing -->
|
||||
<mockserver.version>5.6.1</mockserver.version>
|
||||
<wiremock.version>2.5.1</wiremock.version>
|
||||
<httpclient.version>4.5.8</httpclient.version> <!-- 4.3.6 --> <!-- 4.4-beta1 -->
|
||||
<!-- http client & core 5 -->
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.baeldung.httpclient;
|
||||
|
||||
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
|
||||
import static org.mockserver.matchers.Times.exactly;
|
||||
import static org.mockserver.model.HttpRequest.request;
|
||||
import static org.mockserver.model.HttpResponse.response;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.URISyntaxException;
|
||||
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.mockserver.client.MockServerClient;
|
||||
import org.mockserver.integration.ClientAndServer;
|
||||
|
||||
public class GetRequestMockServer {
|
||||
|
||||
public static ClientAndServer mockServer;
|
||||
public static String serviceOneUrl;
|
||||
public static String serviceTwoUrl;
|
||||
|
||||
public static int serverPort;
|
||||
|
||||
public static final String SERVER_ADDRESS = "127.0.0.1";
|
||||
public static final String PATH_ONE = "/test1";
|
||||
public static final String PATH_TWO = "/test2";
|
||||
public static final String METHOD = "GET";
|
||||
|
||||
@BeforeAll
|
||||
static void startServer() throws IOException {
|
||||
serverPort = getFreePort();
|
||||
System.out.println("Free port "+serverPort);
|
||||
serviceOneUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_ONE;
|
||||
serviceTwoUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_TWO;
|
||||
mockServer = startClientAndServer(serverPort);
|
||||
mockGetRequest();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void stopServer() {
|
||||
mockServer.stop();
|
||||
}
|
||||
|
||||
private static void mockGetRequest() {
|
||||
new MockServerClient(SERVER_ADDRESS, serverPort)
|
||||
.when(
|
||||
request()
|
||||
.withPath(PATH_ONE)
|
||||
.withMethod(METHOD),
|
||||
exactly(5)
|
||||
)
|
||||
.respond(
|
||||
response()
|
||||
.withStatusCode(HttpStatus.SC_OK)
|
||||
.withBody("{\"status\":\"ok\"}")
|
||||
);
|
||||
new MockServerClient(SERVER_ADDRESS, serverPort)
|
||||
.when(
|
||||
request()
|
||||
.withPath(PATH_TWO)
|
||||
.withMethod(METHOD),
|
||||
exactly(1)
|
||||
)
|
||||
.respond(
|
||||
response()
|
||||
.withStatusCode(HttpStatus.SC_OK)
|
||||
.withBody("{\"status\":\"ok\"}")
|
||||
);
|
||||
}
|
||||
|
||||
private static int getFreePort () throws IOException {
|
||||
try (ServerSocket serverSocket = new ServerSocket(0)) {
|
||||
return serverSocket.getLocalPort();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+11
-25
@@ -9,6 +9,7 @@ import java.util.concurrent.Future;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
|
||||
import org.apache.hc.client5.http.impl.routing.DefaultProxyRoutePlanner;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
|
||||
@@ -38,7 +39,7 @@ import org.apache.hc.core5.ssl.SSLContexts;
|
||||
import org.apache.hc.core5.ssl.TrustStrategy;
|
||||
|
||||
|
||||
class HttpAsyncClientLiveTest {
|
||||
class HttpAsyncClientLiveTest extends GetRequestMockServer {
|
||||
|
||||
private static final String HOST = "http://www.google.com";
|
||||
private static final String HOST_WITH_SSL = "https://mms.nw.ru/";
|
||||
@@ -55,12 +56,12 @@ class HttpAsyncClientLiveTest {
|
||||
|
||||
@Test
|
||||
void whenUseHttpAsyncClient_thenCorrect() throws InterruptedException, ExecutionException, IOException {
|
||||
final HttpHost target = new HttpHost(HOST);
|
||||
final HttpHost target = new HttpHost(HOST_WITH_COOKIE);
|
||||
final SimpleHttpRequest request = SimpleRequestBuilder.get()
|
||||
.setHttpHost(target)
|
||||
.build();
|
||||
|
||||
final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
|
||||
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().build();
|
||||
client.start();
|
||||
|
||||
|
||||
@@ -102,30 +103,15 @@ class HttpAsyncClientLiveTest {
|
||||
|
||||
@Test
|
||||
void whenUseProxyWithHttpClient_thenCorrect() throws Exception {
|
||||
final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
|
||||
final HttpHost proxy = new HttpHost("127.0.0.1", GetRequestMockServer.serverPort);
|
||||
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
|
||||
final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
|
||||
.setRoutePlanner(routePlanner)
|
||||
.build();
|
||||
client.start();
|
||||
final HttpHost proxy = new HttpHost("127.0.0.1", 8080);
|
||||
final RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
|
||||
|
||||
final SimpleHttpRequest request = new SimpleHttpRequest("GET" ,HOST_WITH_PROXY);
|
||||
request.setConfig(config);
|
||||
final Future<SimpleHttpResponse> future = client.execute(request, new FutureCallback<>(){
|
||||
@Override
|
||||
public void completed(SimpleHttpResponse response) {
|
||||
|
||||
System.out.println("responseData");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void failed(Exception ex) {
|
||||
System.out.println("Error executing HTTP request: " + ex.getMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancelled() {
|
||||
System.out.println("HTTP request execution cancelled");
|
||||
}
|
||||
});
|
||||
|
||||
final Future<SimpleHttpResponse> future = client.execute(request, null);
|
||||
final HttpResponse response = future.get();
|
||||
assertThat(response.getCode(), equalTo(200));
|
||||
client.close();
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.baeldung.httpclient;
|
||||
|
||||
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
|
||||
import static org.mockserver.matchers.Times.exactly;
|
||||
import static org.mockserver.model.HttpRequest.request;
|
||||
import static org.mockserver.model.HttpResponse.response;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.URISyntaxException;
|
||||
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.mockserver.client.MockServerClient;
|
||||
import org.mockserver.integration.ClientAndServer;
|
||||
|
||||
public class GetRequestMockServer {
|
||||
|
||||
public static ClientAndServer mockServer;
|
||||
public static String serviceOneUrl;
|
||||
public static String serviceTwoUrl;
|
||||
|
||||
public static int serverPort;
|
||||
|
||||
public static final String SERVER_ADDRESS = "127.0.0.1";
|
||||
public static final String PATH_ONE = "/test1";
|
||||
public static final String PATH_TWO = "/test2";
|
||||
public static final String METHOD = "GET";
|
||||
|
||||
@BeforeAll
|
||||
static void startServer() throws IOException, URISyntaxException {
|
||||
serverPort = getFreePort();
|
||||
serviceOneUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_ONE;
|
||||
serviceTwoUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_TWO;
|
||||
mockServer = startClientAndServer(serverPort);
|
||||
mockGetRequest();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void stopServer() {
|
||||
mockServer.stop();
|
||||
}
|
||||
|
||||
private static void mockGetRequest() {
|
||||
new MockServerClient(SERVER_ADDRESS, serverPort)
|
||||
.when(
|
||||
request()
|
||||
.withPath(PATH_ONE)
|
||||
.withMethod(METHOD),
|
||||
exactly(5)
|
||||
)
|
||||
.respond(
|
||||
response()
|
||||
.withStatusCode(HttpStatus.SC_OK)
|
||||
.withBody("{\"status\":\"ok\"}")
|
||||
);
|
||||
new MockServerClient(SERVER_ADDRESS, serverPort)
|
||||
.when(
|
||||
request()
|
||||
.withPath(PATH_TWO)
|
||||
.withMethod(METHOD),
|
||||
exactly(1)
|
||||
)
|
||||
.respond(
|
||||
response()
|
||||
.withStatusCode(HttpStatus.SC_OK)
|
||||
.withBody("{\"status\":\"ok\"}")
|
||||
);
|
||||
}
|
||||
|
||||
private static int getFreePort () throws IOException {
|
||||
try (ServerSocket serverSocket = new ServerSocket(0)) {
|
||||
return serverSocket.getLocalPort();
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -31,7 +31,8 @@ import org.apache.http.protocol.HttpContext;
|
||||
import org.apache.http.ssl.SSLContexts;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class HttpAsyncClientV4LiveTest {
|
||||
|
||||
class HttpAsyncClientV4LiveTest extends GetRequestMockServer {
|
||||
|
||||
private static final String HOST = "http://www.google.com";
|
||||
private static final String HOST_WITH_SSL = "https://mms.nw.ru/";
|
||||
@@ -87,7 +88,7 @@ class HttpAsyncClientV4LiveTest {
|
||||
void whenUseProxyWithHttpClient_thenCorrect() throws Exception {
|
||||
final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
|
||||
client.start();
|
||||
final HttpHost proxy = new HttpHost("127.0.0.1", 8080);
|
||||
final HttpHost proxy = new HttpHost("127.0.0.1", GetRequestMockServer.serverPort);
|
||||
final RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
|
||||
final HttpGet request = new HttpGet(HOST_WITH_PROXY);
|
||||
request.setConfig(config);
|
||||
|
||||
@@ -9,3 +9,5 @@ You can build the project from the command line using: *mvn clean install*, or i
|
||||
- [Guide to Check if Apache Kafka Server Is Running](https://www.baeldung.com/apache-kafka-check-server-is-running)
|
||||
- [Add Custom Headers to a Kafka Message](https://www.baeldung.com/java-kafka-custom-headers)
|
||||
- [Get Last N Messages in Apache Kafka Topic](https://www.baeldung.com/java-apache-kafka-get-last-n-messages)
|
||||
- [Is a Key Required as Part of Sending Messages to Kafka?](https://www.baeldung.com/java-kafka-message-key)
|
||||
- [Read Data From the Beginning Using Kafka Consumer API](https://www.baeldung.com/java-kafka-consumer-api-read)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>apache-poi-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
@@ -19,10 +19,15 @@
|
||||
<artifactId>poi-ooxml</artifactId>
|
||||
<version>${poi.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.poi</groupId>
|
||||
<artifactId>poi-scratchpad</artifactId>
|
||||
<version>${poi.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<poi.version>5.2.0</poi.version>
|
||||
<poi.version>5.2.3</poi.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.poi.replacevariables;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import org.apache.poi.hwpf.HWPFDocument;
|
||||
import org.apache.poi.hwpf.usermodel.Range;
|
||||
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
|
||||
|
||||
public class DocTextReplacer {
|
||||
|
||||
public void replaceText() throws IOException {
|
||||
String filePath = getClass().getClassLoader()
|
||||
.getResource("baeldung.doc")
|
||||
.getPath();
|
||||
try (InputStream inputStream = new FileInputStream(filePath); POIFSFileSystem fileSystem = new POIFSFileSystem(inputStream)) {
|
||||
HWPFDocument doc = new HWPFDocument(fileSystem);
|
||||
doc = replaceText(doc, "Baeldung", "Hello");
|
||||
saveFile(filePath, doc);
|
||||
doc.close();
|
||||
}
|
||||
}
|
||||
|
||||
private HWPFDocument replaceText(HWPFDocument doc, String originalText, String updatedText) {
|
||||
Range range = doc.getRange();
|
||||
range.replaceText(originalText, updatedText);
|
||||
return doc;
|
||||
}
|
||||
|
||||
private void saveFile(String filePath, HWPFDocument doc) throws IOException {
|
||||
try (FileOutputStream out = new FileOutputStream(filePath)) {
|
||||
doc.write(out);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package com.baeldung.poi.replacevariables;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.poi.xwpf.usermodel.XWPFDocument;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFRun;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFTable;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
|
||||
|
||||
public class DocxNaiveTextReplacer {
|
||||
|
||||
public void replaceText() throws IOException {
|
||||
String filePath = getClass().getClassLoader()
|
||||
.getResource("baeldung-copy.docx")
|
||||
.getPath();
|
||||
try (InputStream inputStream = new FileInputStream(filePath)) {
|
||||
XWPFDocument doc = new XWPFDocument(inputStream);
|
||||
doc = replaceText(doc, "Baeldung", "Hello");
|
||||
saveFile(filePath, doc);
|
||||
doc.close();
|
||||
}
|
||||
}
|
||||
|
||||
private XWPFDocument replaceText(XWPFDocument doc, String originalText, String updatedText) {
|
||||
replaceTextInParagraphs(doc.getParagraphs(), originalText, updatedText);
|
||||
for (XWPFTable tbl : doc.getTables()) {
|
||||
for (XWPFTableRow row : tbl.getRows()) {
|
||||
for (XWPFTableCell cell : row.getTableCells()) {
|
||||
replaceTextInParagraphs(cell.getParagraphs(), originalText, updatedText);
|
||||
}
|
||||
}
|
||||
}
|
||||
return doc;
|
||||
}
|
||||
|
||||
private void replaceTextInParagraphs(List<XWPFParagraph> paragraphs, String originalText, String updatedText) {
|
||||
paragraphs.forEach(paragraph -> replaceTextInParagraph(paragraph, originalText, updatedText));
|
||||
}
|
||||
|
||||
private void replaceTextInParagraph(XWPFParagraph paragraph, String originalText, String updatedText) {
|
||||
List<XWPFRun> runs = paragraph.getRuns();
|
||||
for (XWPFRun run : runs) {
|
||||
String text = run.getText(0);
|
||||
if (text != null && text.contains(originalText)) {
|
||||
String updatedRunText = text.replace(originalText, updatedText);
|
||||
run.setText(updatedRunText, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void saveFile(String filePath, XWPFDocument doc) throws IOException {
|
||||
try (FileOutputStream out = new FileOutputStream(filePath)) {
|
||||
doc.write(out);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.baeldung.poi.replacevariables;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
import org.apache.poi.xwpf.usermodel.XWPFDocument;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFRun;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFTable;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
|
||||
|
||||
public class DocxTextReplacer {
|
||||
|
||||
public void replaceText() throws IOException {
|
||||
String filePath = getClass().getClassLoader()
|
||||
.getResource("baeldung.docx")
|
||||
.getPath();
|
||||
try (InputStream inputStream = new FileInputStream(filePath)) {
|
||||
XWPFDocument doc = new XWPFDocument(inputStream);
|
||||
doc = replaceText(doc, "Baeldung", "Hello");
|
||||
saveFile(filePath, doc);
|
||||
doc.close();
|
||||
}
|
||||
}
|
||||
|
||||
private XWPFDocument replaceText(XWPFDocument doc, String originalText, String updatedText) {
|
||||
replaceTextInParagraphs(doc.getParagraphs(), originalText, updatedText);
|
||||
for (XWPFTable tbl : doc.getTables()) {
|
||||
for (XWPFTableRow row : tbl.getRows()) {
|
||||
for (XWPFTableCell cell : row.getTableCells()) {
|
||||
replaceTextInParagraphs(cell.getParagraphs(), originalText, updatedText);
|
||||
}
|
||||
}
|
||||
}
|
||||
return doc;
|
||||
}
|
||||
|
||||
private void replaceTextInParagraphs(List<XWPFParagraph> paragraphs, String originalText, String updatedText) {
|
||||
paragraphs.forEach(paragraph -> replaceTextInParagraph(paragraph, originalText, updatedText));
|
||||
}
|
||||
|
||||
private void replaceTextInParagraph(XWPFParagraph paragraph, String originalText, String updatedText) {
|
||||
String paragraphText = paragraph.getParagraphText();
|
||||
if (paragraphText.contains(originalText)) {
|
||||
String updatedParagraphText = paragraphText.replace(originalText, updatedText);
|
||||
while (paragraph.getRuns().size() > 0) {
|
||||
paragraph.removeRun(0);
|
||||
}
|
||||
XWPFRun newRun = paragraph.createRun();
|
||||
newRun.setText(updatedParagraphText);
|
||||
}
|
||||
}
|
||||
|
||||
private void saveFile(String filePath, XWPFDocument doc) throws IOException {
|
||||
try (FileOutputStream out = new FileOutputStream(filePath)) {
|
||||
doc.write(out);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
+31
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.poi.replacevariables;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.apache.poi.hwpf.HWPFDocument;
|
||||
import org.apache.poi.hwpf.extractor.WordExtractor;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class DocTextReplacerUnitTest {
|
||||
|
||||
@Test
|
||||
void whenReplaceText_ThenTextReplaced() throws IOException {
|
||||
new DocTextReplacer().replaceText();
|
||||
|
||||
String filePath = getClass().getClassLoader()
|
||||
.getResource("baeldung.doc")
|
||||
.getPath();
|
||||
try (FileInputStream fis = new FileInputStream(filePath); HWPFDocument document = new HWPFDocument(fis); WordExtractor extractor = new WordExtractor(document)) {
|
||||
long occurrencesOfHello = Arrays.stream(extractor.getText()
|
||||
.split("\\s+"))
|
||||
.filter(s -> s.contains("Hello"))
|
||||
.count();
|
||||
assertEquals(5, occurrencesOfHello);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.poi.replacevariables;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFDocument;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class DocxNaiveTextReplacerUnitTest {
|
||||
|
||||
@Test
|
||||
void whenReplaceText_ThenTextReplaced() throws IOException {
|
||||
new DocxNaiveTextReplacer().replaceText();
|
||||
|
||||
String filePath = getClass().getClassLoader()
|
||||
.getResource("baeldung-copy.docx")
|
||||
.getPath();
|
||||
try (FileInputStream fis = new FileInputStream(filePath); XWPFDocument document = new XWPFDocument(fis); XWPFWordExtractor extractor = new XWPFWordExtractor(document)) {
|
||||
long occurrencesOfHello = Arrays.stream(extractor.getText()
|
||||
.split("\\s+"))
|
||||
.filter(s -> s.contains("Hello"))
|
||||
.count();
|
||||
assertTrue(occurrencesOfHello < 5);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.poi.replacevariables;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFDocument;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class DocxTestReplacerUnitTest {
|
||||
|
||||
@Test
|
||||
void whenReplaceText_ThenTextReplaced() throws IOException {
|
||||
new DocxTextReplacer().replaceText();
|
||||
|
||||
String filePath = getClass().getClassLoader()
|
||||
.getResource("baeldung.docx")
|
||||
.getPath();
|
||||
try (FileInputStream fis = new FileInputStream(filePath); XWPFDocument document = new XWPFDocument(fis); XWPFWordExtractor extractor = new XWPFWordExtractor(document)) {
|
||||
long occurrencesOfHello = Arrays.stream(extractor.getText()
|
||||
.split("\\s+"))
|
||||
.filter(s -> s.contains("Hello"))
|
||||
.count();
|
||||
assertEquals(5, occurrencesOfHello);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -5,7 +5,7 @@ This module contains complete guides about arrays in Java
|
||||
### Relevant Articles:
|
||||
- [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide)
|
||||
- [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays)
|
||||
- [What is [Ljava.lang.Object;?](https://www.baeldung.com/java-tostring-array)
|
||||
- [What Is [Ljava.lang.Object;?](https://www.baeldung.com/java-tostring-array)
|
||||
- [Guide to ArrayStoreException](https://www.baeldung.com/java-arraystoreexception)
|
||||
- [Creating a Generic Array in Java](https://www.baeldung.com/java-generic-array)
|
||||
- [Maximum Size of Java Arrays](https://www.baeldung.com/java-arrays-max-size)
|
||||
|
||||
@@ -3,5 +3,5 @@
|
||||
This module contains articles about multidimensional arrays in Java
|
||||
|
||||
### Relevant Articles:
|
||||
- [Multi-Dimensional Arrays In Java](https://www.baeldung.com/java-jagged-arrays)
|
||||
- [Looping Diagonally Through a 2d Java Array](https://www.baeldung.com/java-loop-diagonal-array)
|
||||
- [Multi-Dimensional Arrays in Java](https://www.baeldung.com/java-jagged-arrays)
|
||||
- [Looping Diagonally Through a 2d Java Array](https://www.baeldung.com/java-loop-diagonal-array)
|
||||
|
||||
@@ -7,7 +7,7 @@ This module contains articles about advanced operations on arrays in Java. They
|
||||
- [How to Copy an Array in Java](https://www.baeldung.com/java-array-copy)
|
||||
- [Arrays.deepEquals](https://www.baeldung.com/java-arrays-deepequals)
|
||||
- [Find Sum and Average in a Java Array](https://www.baeldung.com/java-array-sum-average)
|
||||
- [Intersection Between two Integer Arrays](https://www.baeldung.com/java-array-intersection)
|
||||
- [Intersection Between Two Integer Arrays](https://www.baeldung.com/java-array-intersection)
|
||||
- [Comparing Arrays in Java](https://www.baeldung.com/java-comparing-arrays)
|
||||
- [Concatenate Two Arrays in Java](https://www.baeldung.com/java-concatenate-arrays)
|
||||
- [Performance of System.arraycopy() vs. Arrays.copyOf()](https://www.baeldung.com/java-system-arraycopy-arrays-copyof-performance)
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
- [Join and Split Arrays and Collections in Java](https://www.baeldung.com/java-join-and-split)
|
||||
- [Java – Combine Multiple Collections](https://www.baeldung.com/java-combine-multiple-collections)
|
||||
- [Combining Different Types of Collections in Java](https://www.baeldung.com/java-combine-collections)
|
||||
- [Shuffling Collections In Java](https://www.baeldung.com/java-shuffle-collection)
|
||||
- [Shuffling Collections in Java](https://www.baeldung.com/java-shuffle-collection)
|
||||
- [Sorting in Java](https://www.baeldung.com/java-sorting)
|
||||
- [Getting the Size of an Iterable in Java](https://www.baeldung.com/java-iterable-size)
|
||||
- [Java Null-Safe Streams from Collections](https://www.baeldung.com/java-null-safe-streams-from-collections)
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
This module contains articles about conversions among Collection types and arrays in Java.
|
||||
|
||||
### Relevant Articles:
|
||||
- [Converting between an Array and a List in Java](https://www.baeldung.com/convert-array-to-list-and-list-to-array)
|
||||
- [Converting Between an Array and a List in Java](https://www.baeldung.com/convert-array-to-list-and-list-to-array)
|
||||
- [Converting Between an Array and a Set in Java](https://www.baeldung.com/convert-array-to-set-and-set-to-array)
|
||||
- [Convert a Map to an Array, List or Set in Java](https://www.baeldung.com/convert-map-values-to-array-list-set)
|
||||
- [Converting a List to String in Java](https://www.baeldung.com/java-list-to-string)
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
This module contains articles about the Java List collection
|
||||
|
||||
### Relevant Articles:
|
||||
- [Check If Two Lists are Equal in Java](https://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
|
||||
- [Java 8 Streams: Find Items From One List Based On Values From Another List](https://www.baeldung.com/java-streams-find-list-items)
|
||||
- [Check if Two Lists Are Equal in Java](https://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
|
||||
- [Java 8 Streams: Find Items From One List Based on Values From Another List](https://www.baeldung.com/java-streams-find-list-items)
|
||||
- [A Guide to the Java LinkedList](https://www.baeldung.com/java-linkedlist)
|
||||
- [Java List UnsupportedOperationException](https://www.baeldung.com/java-list-unsupported-operation-exception)
|
||||
- [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line)
|
||||
|
||||
@@ -7,3 +7,5 @@ This module contains articles about the Java List collection
|
||||
- [Finding All Duplicates in a List in Java](https://www.baeldung.com/java-list-find-duplicates)
|
||||
- [Moving Items Around in an Arraylist](https://www.baeldung.com/java-arraylist-move-items)
|
||||
- [Check if a List Contains an Element From Another List in Java](https://www.baeldung.com/java-check-elements-between-lists)
|
||||
- [Array vs. List Performance in Java](https://www.baeldung.com/java-array-vs-list-performance)
|
||||
- [Set Default Value for Elements in List](https://www.baeldung.com/java-list-set-default-values)
|
||||
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.java.uniqueelements;
|
||||
|
||||
import static java.util.stream.Collectors.toList;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class UniqueElementsInListUnitTest {
|
||||
// @formatter:off
|
||||
private static final List<String> MY_LIST = Arrays.asList(new String[]{
|
||||
"Microsoft Windows",
|
||||
"Mac OS",
|
||||
"GNU Linux",
|
||||
"Free BSD",
|
||||
"GNU Linux",
|
||||
"Mac OS"});
|
||||
// @formatter:on
|
||||
|
||||
@Test
|
||||
void whenConvertToSet_thenGetExpectedResult() {
|
||||
List<String> result = new ArrayList<>(new HashSet<>(MY_LIST));
|
||||
assertThat(result).containsExactlyInAnyOrder("Free BSD", "Microsoft Windows", "Mac OS", "GNU Linux");
|
||||
|
||||
result = new ArrayList<>(new LinkedHashSet<>(MY_LIST));
|
||||
assertThat(result).containsExactly("Microsoft Windows", "Mac OS", "GNU Linux", "Free BSD");
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingStream_thenGetExpectedResult() {
|
||||
List<String> result = MY_LIST.stream()
|
||||
.distinct()
|
||||
.collect(toList());
|
||||
assertThat(result).containsExactly("Microsoft Windows", "Mac OS", "GNU Linux", "Free BSD");
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,8 @@ This module contains articles about the Java List collection
|
||||
|
||||
### Relevant Articles:
|
||||
- [Java – Get Random Item/Element From a List](http://www.baeldung.com/java-random-list-element)
|
||||
- [Removing all Nulls from a List in Java](http://www.baeldung.com/java-remove-nulls-from-list)
|
||||
- [Removing all duplicates from a List in Java](http://www.baeldung.com/java-remove-duplicates-from-list)
|
||||
- [Removing All Nulls From a List in Java](https://www.baeldung.com/java-remove-nulls-from-list)
|
||||
- [Removing All Duplicates From a List in Java](https://www.baeldung.com/java-remove-duplicates-from-list)
|
||||
- [How to TDD a List Implementation in Java](http://www.baeldung.com/java-test-driven-list)
|
||||
- [Iterating Backward Through a List](http://www.baeldung.com/java-list-iterate-backwards)
|
||||
- [Remove the First Element from a List](http://www.baeldung.com/java-remove-first-element-from-list)
|
||||
|
||||
@@ -8,7 +8,7 @@ This module contains articles about Map data structures in Java.
|
||||
- [A Guide to Java HashMap](https://www.baeldung.com/java-hashmap)
|
||||
- [Guide to WeakHashMap in Java](https://www.baeldung.com/java-weakhashmap)
|
||||
- [Map to String Conversion in Java](https://www.baeldung.com/java-map-to-string-conversion)
|
||||
- [Iterate over a Map in Java](https://www.baeldung.com/java-iterate-map)
|
||||
- [Iterate Over a Map in Java](https://www.baeldung.com/java-iterate-map)
|
||||
- [Merging Two Maps with Java 8](https://www.baeldung.com/java-merge-maps)
|
||||
- [Sort a HashMap in Java](https://www.baeldung.com/java-hashmap-sort)
|
||||
- [Finding the Highest Value in a Java Map](https://www.baeldung.com/java-find-map-max)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user