Skip to content

Commit 405746a

Browse files
committed
Merge branch 'master' into BAEL-2977-stream-skip-limit
2 parents 17191d0 + 0927be7 commit 405746a

81 files changed

Lines changed: 3055 additions & 35 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
package com.baeldung.folding;
2+
3+
import java.util.stream.Collectors;
4+
import java.util.stream.IntStream;
5+
6+
/**
7+
* Calculate a hash value for the strings using the folding technique.
8+
*
9+
* The implementation serves only to the illustration purposes and is far
10+
* from being the most efficient.
11+
*
12+
* @author A.Shcherbakov
13+
*
14+
*/
15+
public class FoldingHash {
16+
17+
/**
18+
* Calculate the hash value of a given string.
19+
*
20+
* @param str Assume it is not null
21+
* @param groupSize the group size in the folding technique
22+
* @param maxValue defines a max value that the hash may acquire (exclusive)
23+
* @return integer value from 0 (inclusive) to maxValue (exclusive)
24+
*/
25+
public int hash(String str, int groupSize, int maxValue) {
26+
final int[] codes = this.toAsciiCodes(str);
27+
return IntStream.range(0, str.length())
28+
.filter(i -> i % groupSize == 0)
29+
.mapToObj(i -> extract(codes, i, groupSize))
30+
.map(block -> concatenate(block))
31+
.reduce(0, (a, b) -> (a + b) % maxValue);
32+
}
33+
34+
/**
35+
* Returns a new array of given length whose elements are take from
36+
* the original one starting from the offset.
37+
*
38+
* If the original array has not enough elements, the returning array will contain
39+
* element from the offset till the end of the original array.
40+
*
41+
* @param numbers original array. Assume it is not null.
42+
* @param offset index of the element to start from. Assume it is less than the size of the array
43+
* @param length max size of the resulting array
44+
* @return
45+
*/
46+
public int[] extract(int[] numbers, int offset, int length) {
47+
final int defect = numbers.length - (offset + length);
48+
final int s = defect < 0 ? length + defect : length;
49+
int[] result = new int[s];
50+
for (int index = 0; index < s; index++) {
51+
result[index] = numbers[index + offset];
52+
}
53+
return result;
54+
}
55+
56+
/**
57+
* Concatenate the numbers into a single number as if they were strings.
58+
* Assume that the procedure does not suffer from the overflow.
59+
* @param numbers integers to concatenate
60+
* @return
61+
*/
62+
public int concatenate(int[] numbers) {
63+
final String merged = IntStream.of(numbers)
64+
.mapToObj(number -> "" + number)
65+
.collect(Collectors.joining());
66+
return Integer.parseInt(merged, 10);
67+
}
68+
69+
/**
70+
* Convert the string into its characters' ASCII codes.
71+
* @param str input string
72+
* @return
73+
*/
74+
private int[] toAsciiCodes(String str) {
75+
return str.chars()
76+
.toArray();
77+
}
78+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.baeldung.folding;
2+
3+
/**
4+
* Code snippet for article "A Guide to the Folding Technique".
5+
*
6+
* @author A.Shcherbakov
7+
*
8+
*/
9+
public class Main {
10+
11+
public static void main(String... arg) {
12+
FoldingHash hasher = new FoldingHash();
13+
final String str = "Java language";
14+
System.out.println(hasher.hash(str, 2, 100_000));
15+
System.out.println(hasher.hash(str, 3, 1_000));
16+
}
17+
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package com.baeldung.folding;
2+
3+
import static org.junit.Assert.assertArrayEquals;
4+
import static org.junit.Assert.assertEquals;
5+
import static org.junit.Assert.assertTrue;
6+
7+
import org.junit.Test;
8+
9+
public class FoldingHashUnitTest {
10+
11+
@Test
12+
public void givenStringJavaLanguage_whenSize2Capacity100000_then48933() throws Exception {
13+
final FoldingHash hasher = new FoldingHash();
14+
final int value = hasher.hash("Java language", 2, 100_000);
15+
assertEquals(value, 48933);
16+
}
17+
18+
@Test
19+
public void givenStringVaJaLanguage_whenSize2Capacity100000_thenSameAsJavaLanguage() throws Exception {
20+
final FoldingHash hasher = new FoldingHash();
21+
final int java = hasher.hash("Java language", 2, 100_000);
22+
final int vaja = hasher.hash("vaJa language", 2, 100_000);
23+
assertTrue(java == vaja);
24+
}
25+
26+
@Test
27+
public void givenSingleElementArray_whenOffset0Size2_thenSingleElement() throws Exception {
28+
final FoldingHash hasher = new FoldingHash();
29+
final int[] value = hasher.extract(new int[] { 5 }, 0, 2);
30+
assertArrayEquals(new int[] { 5 }, value);
31+
}
32+
33+
@Test
34+
public void givenFiveElementArray_whenOffset0Size3_thenFirstThreeElements() throws Exception {
35+
final FoldingHash hasher = new FoldingHash();
36+
final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 0, 3);
37+
assertArrayEquals(new int[] { 1, 2, 3 }, value);
38+
}
39+
40+
@Test
41+
public void givenFiveElementArray_whenOffset1Size2_thenTwoElements() throws Exception {
42+
final FoldingHash hasher = new FoldingHash();
43+
final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 1, 2);
44+
assertArrayEquals(new int[] { 2, 3 }, value);
45+
}
46+
47+
@Test
48+
public void givenFiveElementArray_whenOffset2SizeTooBig_thenElementsToTheEnd() throws Exception {
49+
final FoldingHash hasher = new FoldingHash();
50+
final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 2, 2000);
51+
assertArrayEquals(new int[] { 3, 4, 5 }, value);
52+
}
53+
54+
}

core-java-modules/core-java-8-2/src/main/java/com/baeldung/delay/Delay.java renamed to core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/delay/Delay.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package com.baeldung.delay;
1+
package com.baeldung.concurrent.delay;
22

33
import java.util.concurrent.Executors;
44
import java.util.concurrent.ScheduledExecutorService;
@@ -61,6 +61,7 @@ private static void delayedServiceTask(Integer delayInSeconds) {
6161

6262
executorService.schedule(Delay::someTask1, delayInSeconds, TimeUnit.SECONDS);
6363

64+
executorService.shutdown();
6465
}
6566

6667
private static void fixedRateServiceTask(Integer delayInSeconds) {
@@ -78,6 +79,7 @@ private static void fixedRateServiceTask(Integer delayInSeconds) {
7879

7980
sf.cancel(true);
8081

82+
executorService.shutdown();
8183
}
8284

8385
private static void someTask1() {

core-java-modules/core-java-lambdas/README.md

Lines changed: 0 additions & 3 deletions
This file was deleted.
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
## Relevant articles:
2+
3+
- [Determine File Creating Date in Java](https://www.baeldung.com/file-creation-date-java)
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package com.baeldung.creationdate;
2+
3+
import java.io.IOException;
4+
import java.nio.file.Files;
5+
import java.nio.file.Path;
6+
import java.nio.file.attribute.BasicFileAttributes;
7+
import java.nio.file.attribute.FileTime;
8+
import java.time.Instant;
9+
import java.util.Optional;
10+
11+
public class CreationDateResolver {
12+
13+
public Instant resolveCreationTimeWithBasicAttributes(Path path) {
14+
try {
15+
final BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
16+
final FileTime fileTime = attr.creationTime();
17+
18+
return fileTime.toInstant();
19+
} catch (IOException ex) {
20+
throw new RuntimeException("An issue occured went wrong when resolving creation time", ex);
21+
}
22+
}
23+
24+
public Optional<Instant> resolveCreationTimeWithAttribute(Path path) {
25+
try {
26+
final FileTime creationTime = (FileTime) Files.getAttribute(path, "creationTime");
27+
28+
return Optional
29+
.ofNullable(creationTime)
30+
.map((FileTime::toInstant));
31+
} catch (IOException ex) {
32+
throw new RuntimeException("An issue occured went wrong when resolving creation time", ex);
33+
}
34+
}
35+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.baeldung.creationdate;
2+
3+
import org.junit.Test;
4+
5+
import java.io.File;
6+
import java.nio.file.Path;
7+
import java.time.Instant;
8+
import java.util.Optional;
9+
10+
import static org.junit.Assert.assertTrue;
11+
12+
public class CreationDateResolverUnitTest {
13+
14+
private final CreationDateResolver creationDateResolver = new CreationDateResolver();
15+
16+
@Test
17+
public void givenFile_whenGettingCreationDateTimeFromBasicAttributes_thenReturnDate() throws Exception {
18+
19+
final File file = File.createTempFile("createdFile", ".txt");
20+
final Path path = file.toPath();
21+
22+
final Instant response = creationDateResolver.resolveCreationTimeWithBasicAttributes(path);
23+
24+
assertTrue(Instant
25+
.now()
26+
.isAfter(response));
27+
28+
}
29+
30+
@Test
31+
public void givenFile_whenGettingCreationDateTimeFromAttribute_thenReturnDate() throws Exception {
32+
33+
final File file = File.createTempFile("createdFile", ".txt");
34+
final Path path = file.toPath();
35+
36+
final Optional<Instant> response = creationDateResolver.resolveCreationTimeWithAttribute(path);
37+
38+
response.ifPresent((value) -> {
39+
assertTrue(Instant
40+
.now()
41+
.isAfter(value));
42+
});
43+
44+
}
45+
}

jackson-2/pom.xml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,13 @@
2828
<artifactId>jackson-dataformat-yaml</artifactId>
2929
<version>2.9.8</version>
3030
</dependency>
31+
32+
<!-- CSV -->
33+
<dependency>
34+
<groupId>com.fasterxml.jackson.dataformat</groupId>
35+
<artifactId>jackson-dataformat-csv</artifactId>
36+
<version>2.9.8</version>
37+
</dependency>
3138

3239
<!-- Allow use of LocalDate -->
3340
<dependency>
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package com.baeldung.jackson.csv;
2+
3+
import java.io.File;
4+
import java.io.IOException;
5+
6+
import com.baeldung.jackson.entities.OrderLine;
7+
import com.baeldung.jackson.mixin.OrderLineForCsv;
8+
import com.fasterxml.jackson.databind.JsonNode;
9+
import com.fasterxml.jackson.databind.MappingIterator;
10+
import com.fasterxml.jackson.databind.ObjectMapper;
11+
import com.fasterxml.jackson.databind.SerializationFeature;
12+
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
13+
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
14+
import com.fasterxml.jackson.dataformat.csv.CsvSchema.Builder;
15+
16+
public class JsonCsvConverter {
17+
18+
public static void JsonToCsv(File jsonFile, File csvFile) throws IOException {
19+
JsonNode jsonTree = new ObjectMapper().readTree(jsonFile);
20+
21+
Builder csvSchemaBuilder = CsvSchema.builder();
22+
JsonNode firstObject = jsonTree.elements().next();
23+
firstObject.fieldNames().forEachRemaining(fieldName -> {csvSchemaBuilder.addColumn(fieldName);} );
24+
CsvSchema csvSchema = csvSchemaBuilder
25+
.build()
26+
.withHeader();
27+
28+
CsvMapper csvMapper = new CsvMapper();
29+
csvMapper.writerFor(JsonNode.class)
30+
.with(csvSchema)
31+
.writeValue(csvFile, jsonTree);
32+
}
33+
34+
public static void csvToJson(File csvFile, File jsonFile) throws IOException {
35+
CsvSchema orderLineSchema = CsvSchema.emptySchema().withHeader();
36+
CsvMapper csvMapper = new CsvMapper();
37+
MappingIterator<OrderLine> orderLines = csvMapper.readerFor(OrderLine.class)
38+
.with(orderLineSchema)
39+
.readValues(csvFile);
40+
41+
new ObjectMapper()
42+
.configure(SerializationFeature.INDENT_OUTPUT, true)
43+
.writeValue(jsonFile, orderLines.readAll());
44+
}
45+
46+
public static void JsonToFormattedCsv(File jsonFile, File csvFile) throws IOException {
47+
CsvMapper csvMapper = new CsvMapper();
48+
CsvSchema csvSchema = csvMapper
49+
.schemaFor(OrderLineForCsv.class)
50+
.withHeader();
51+
csvMapper.addMixIn(OrderLine.class, OrderLineForCsv.class);
52+
53+
OrderLine[] orderLines = new ObjectMapper()
54+
.readValue(jsonFile, OrderLine[].class);
55+
csvMapper.writerFor(OrderLine[].class)
56+
.with(csvSchema)
57+
.writeValue(csvFile, orderLines);
58+
}
59+
}

0 commit comments

Comments
 (0)