commit
b8592c463c
|
@ -5,29 +5,37 @@ import org.apache.avro.io.DatumReader;
|
|||
import org.apache.avro.io.Decoder;
|
||||
import org.apache.avro.io.DecoderFactory;
|
||||
import org.apache.avro.specific.SpecificDatumReader;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class AvroDeSerealizer {
|
||||
|
||||
public AvroHttpRequest deSerealizeAvroHttpRequestJSON(byte[] data){
|
||||
DatumReader<AvroHttpRequest> reader = new SpecificDatumReader<>(AvroHttpRequest.class);
|
||||
Decoder decoder = null;
|
||||
try {
|
||||
decoder = DecoderFactory.get().jsonDecoder(AvroHttpRequest.getClassSchema(), new String(data));
|
||||
return reader.read(null, decoder);
|
||||
} catch (IOException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
private static Logger logger = LoggerFactory.getLogger(AvroDeSerealizer.class);
|
||||
|
||||
public AvroHttpRequest deSerealizeAvroHttpRequestBinary(byte[] data){
|
||||
DatumReader<AvroHttpRequest> employeeReader = new SpecificDatumReader<>(AvroHttpRequest.class);
|
||||
Decoder decoder = DecoderFactory.get().binaryDecoder(data, null);
|
||||
try {
|
||||
return employeeReader.read(null, decoder);
|
||||
} catch (IOException e) {
|
||||
public AvroHttpRequest deSerealizeAvroHttpRequestJSON(byte[] data) {
|
||||
DatumReader<AvroHttpRequest> reader = new SpecificDatumReader<>(AvroHttpRequest.class);
|
||||
Decoder decoder = null;
|
||||
try {
|
||||
decoder = DecoderFactory.get()
|
||||
.jsonDecoder(AvroHttpRequest.getClassSchema(), new String(data));
|
||||
return reader.read(null, decoder);
|
||||
} catch (IOException e) {
|
||||
logger.error("Deserialization error" + e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public AvroHttpRequest deSerealizeAvroHttpRequestBinary(byte[] data) {
|
||||
DatumReader<AvroHttpRequest> employeeReader = new SpecificDatumReader<>(AvroHttpRequest.class);
|
||||
Decoder decoder = DecoderFactory.get()
|
||||
.binaryDecoder(data, null);
|
||||
try {
|
||||
return employeeReader.read(null, decoder);
|
||||
} catch (IOException e) {
|
||||
logger.error("Deserialization error" + e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -3,42 +3,48 @@ package com.baeldung.avro.util.serealization;
|
|||
import com.baeldung.avro.util.model.AvroHttpRequest;
|
||||
import org.apache.avro.io.*;
|
||||
import org.apache.avro.specific.SpecificDatumWriter;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
|
||||
public class AvroSerealizer {
|
||||
|
||||
public byte[] serealizeAvroHttpRequestJSON(AvroHttpRequest request){
|
||||
DatumWriter<AvroHttpRequest> writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
|
||||
byte[] data = new byte[0];
|
||||
ByteArrayOutputStream stream = new ByteArrayOutputStream();
|
||||
Encoder jsonEncoder = null;
|
||||
try {
|
||||
jsonEncoder = EncoderFactory.get().jsonEncoder(AvroHttpRequest.getClassSchema(), stream);
|
||||
writer.write(request, jsonEncoder);
|
||||
jsonEncoder.flush();
|
||||
data = stream.toByteArray();
|
||||
} catch (IOException e) {
|
||||
data =null;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
private static final Logger logger = LoggerFactory.getLogger(AvroSerealizer.class);
|
||||
|
||||
public byte[] serealizeAvroHttpRequestBinary(AvroHttpRequest request){
|
||||
DatumWriter<AvroHttpRequest> writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
|
||||
byte[] data = new byte[0];
|
||||
ByteArrayOutputStream stream = new ByteArrayOutputStream();
|
||||
Encoder jsonEncoder = EncoderFactory.get().binaryEncoder(stream,null);
|
||||
try {
|
||||
writer.write(request, jsonEncoder);
|
||||
jsonEncoder.flush();
|
||||
data = stream.toByteArray();
|
||||
} catch (IOException e) {
|
||||
data = null;
|
||||
public byte[] serealizeAvroHttpRequestJSON(AvroHttpRequest request) {
|
||||
DatumWriter<AvroHttpRequest> writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
|
||||
byte[] data = new byte[0];
|
||||
ByteArrayOutputStream stream = new ByteArrayOutputStream();
|
||||
Encoder jsonEncoder = null;
|
||||
try {
|
||||
jsonEncoder = EncoderFactory.get()
|
||||
.jsonEncoder(AvroHttpRequest.getClassSchema(), stream);
|
||||
writer.write(request, jsonEncoder);
|
||||
jsonEncoder.flush();
|
||||
data = stream.toByteArray();
|
||||
} catch (IOException e) {
|
||||
logger.error("Serialization error " + e.getMessage());
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
public byte[] serealizeAvroHttpRequestBinary(AvroHttpRequest request) {
|
||||
DatumWriter<AvroHttpRequest> writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
|
||||
byte[] data = new byte[0];
|
||||
ByteArrayOutputStream stream = new ByteArrayOutputStream();
|
||||
Encoder jsonEncoder = EncoderFactory.get()
|
||||
.binaryEncoder(stream, null);
|
||||
try {
|
||||
writer.write(request, jsonEncoder);
|
||||
jsonEncoder.flush();
|
||||
data = stream.toByteArray();
|
||||
} catch (IOException e) {
|
||||
logger.error("Serialization error " + e.getMessage());
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -24,8 +24,10 @@ public class AvroSerealizerDeSerealizerTest {
|
|||
serealizer = new AvroSerealizer();
|
||||
deSerealizer = new AvroDeSerealizer();
|
||||
|
||||
ClientIdentifier clientIdentifier = ClientIdentifier.newBuilder().
|
||||
setHostName("localhost").setIpAddress("255.255.255.0").build();
|
||||
ClientIdentifier clientIdentifier = ClientIdentifier.newBuilder()
|
||||
.setHostName("localhost")
|
||||
.setIpAddress("255.255.255.0")
|
||||
.build();
|
||||
|
||||
List<CharSequence> employees = new ArrayList();
|
||||
employees.add("James");
|
||||
|
@ -33,43 +35,49 @@ public class AvroSerealizerDeSerealizerTest {
|
|||
employees.add("David");
|
||||
employees.add("Han");
|
||||
|
||||
request = AvroHttpRequest.newBuilder().setRequestTime(01l)
|
||||
.setActive(Active.YES).setClientIdentifier(clientIdentifier)
|
||||
.setEmployeeNames(employees).build();
|
||||
request = AvroHttpRequest.newBuilder()
|
||||
.setRequestTime(01l)
|
||||
.setActive(Active.YES)
|
||||
.setClientIdentifier(clientIdentifier)
|
||||
.setEmployeeNames(employees)
|
||||
.build();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void WhenSerialized_UsingJSONEncoder_ObjectGetsSerialized(){
|
||||
byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
|
||||
assertTrue(Objects.nonNull(data));
|
||||
assertTrue(data.length > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void WhenSerialized_UsingBinaryEncoder_ObjectGetsSerialized(){
|
||||
byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
|
||||
assertTrue(Objects.nonNull(data));
|
||||
assertTrue(data.length > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void WhenDeserialize_UsingJSONDecoder_ActualAndExpectedObjectsAreEqual(){
|
||||
byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
|
||||
AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestJSON(data);
|
||||
assertEquals(actualRequest,request);
|
||||
assertTrue(actualRequest.getRequestTime().equals(request.getRequestTime()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void WhenDeserialize_UsingBinaryecoder_ActualAndExpectedObjectsAreEqual(){
|
||||
byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
|
||||
AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestBinary(data);
|
||||
assertEquals(actualRequest,request);
|
||||
assertTrue(actualRequest.getRequestTime().equals(request.getRequestTime()));
|
||||
}
|
||||
@Test
|
||||
public void WhenSerializedUsingJSONEncoder_thenObjectGetsSerialized() {
|
||||
byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
|
||||
assertTrue(Objects.nonNull(data));
|
||||
assertTrue(data.length > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void WhenSerializedUsingBinaryEncoder_thenObjectGetsSerialized() {
|
||||
byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
|
||||
assertTrue(Objects.nonNull(data));
|
||||
assertTrue(data.length > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void WhenDeserializeUsingJSONDecoder_thenActualAndExpectedObjectsAreEqual() {
|
||||
byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
|
||||
AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestJSON(data);
|
||||
assertEquals(actualRequest, request);
|
||||
assertTrue(actualRequest.getRequestTime()
|
||||
.equals(request.getRequestTime()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void WhenDeserializeUsingBinaryecoder_thenActualAndExpectedObjectsAreEqual() {
|
||||
byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
|
||||
AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestBinary(data);
|
||||
assertEquals(actualRequest, request);
|
||||
assertTrue(actualRequest.getRequestTime()
|
||||
.equals(request.getRequestTime()));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
<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">
|
||||
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>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-cxf</artifactId>
|
||||
|
@ -17,6 +17,7 @@
|
|||
<module>cxf-spring</module>
|
||||
<module>cxf-jaxrs-implementation</module>
|
||||
<module>cxf-aegis</module>
|
||||
<module>sse-jaxrs</module>
|
||||
</modules>
|
||||
|
||||
<build>
|
||||
|
|
|
@ -0,0 +1,21 @@
|
|||
<?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">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>sse-jaxrs</artifactId>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-cxf</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<modules>
|
||||
<module>sse-jaxrs-server</module>
|
||||
<module>sse-jaxrs-client</module>
|
||||
</modules>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,62 @@
|
|||
<?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">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>sse-jaxrs</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>sse-jaxrs-client</artifactId>
|
||||
|
||||
<properties>
|
||||
<cxf-version>3.2.0</cxf-version>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>1.6.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>singleEvent</id>
|
||||
<goals>
|
||||
<goal>java</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<mainClass>com.baeldung.sse.jaxrs.client.SseClientApp</mainClass>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>broadcast</id>
|
||||
<goals>
|
||||
<goal>java</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<mainClass>com.baeldung.sse.jaxrs.client.SseClientBroadcastApp</mainClass>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-rs-client</artifactId>
|
||||
<version>${cxf-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-rs-sse</artifactId>
|
||||
<version>${cxf-version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,48 @@
|
|||
package com.baeldung.sse.jaxrs.client;
|
||||
|
||||
import javax.ws.rs.client.Client;
|
||||
import javax.ws.rs.client.ClientBuilder;
|
||||
import javax.ws.rs.client.WebTarget;
|
||||
import javax.ws.rs.sse.InboundSseEvent;
|
||||
import javax.ws.rs.sse.SseEventSource;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class SseClientApp {
|
||||
|
||||
private static final String url = "http://127.0.0.1:9080/sse-jaxrs-server/sse/stock/prices";
|
||||
|
||||
public static void main(String... args) throws Exception {
|
||||
|
||||
Client client = ClientBuilder.newClient();
|
||||
WebTarget target = client.target(url);
|
||||
try (SseEventSource eventSource = SseEventSource.target(target).build()) {
|
||||
|
||||
eventSource.register(onEvent, onError, onComplete);
|
||||
eventSource.open();
|
||||
|
||||
//Consuming events for one hour
|
||||
Thread.sleep(60 * 60 * 1000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
client.close();
|
||||
System.out.println("End");
|
||||
}
|
||||
|
||||
// A new event is received
|
||||
private static Consumer<InboundSseEvent> onEvent = (inboundSseEvent) -> {
|
||||
String data = inboundSseEvent.readData();
|
||||
System.out.println(data);
|
||||
};
|
||||
|
||||
//Error
|
||||
private static Consumer<Throwable> onError = (throwable) -> {
|
||||
throwable.printStackTrace();
|
||||
};
|
||||
|
||||
//Connection close and there is nothing to receive
|
||||
private static Runnable onComplete = () -> {
|
||||
System.out.println("Done!");
|
||||
};
|
||||
|
||||
}
|
|
@ -0,0 +1,52 @@
|
|||
package com.baeldung.sse.jaxrs.client;
|
||||
|
||||
import javax.ws.rs.client.Client;
|
||||
import javax.ws.rs.client.ClientBuilder;
|
||||
import javax.ws.rs.client.WebTarget;
|
||||
import javax.ws.rs.sse.InboundSseEvent;
|
||||
import javax.ws.rs.sse.SseEventSource;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class SseClientBroadcastApp {
|
||||
|
||||
private static final String subscribeUrl = "http://localhost:9080/sse-jaxrs-server/sse/stock/subscribe";
|
||||
|
||||
|
||||
public static void main(String... args) throws Exception {
|
||||
|
||||
Client client = ClientBuilder.newClient();
|
||||
WebTarget target = client.target(subscribeUrl);
|
||||
try (final SseEventSource eventSource = SseEventSource.target(target)
|
||||
.reconnectingEvery(5, TimeUnit.SECONDS)
|
||||
.build()) {
|
||||
eventSource.register(onEvent, onError, onComplete);
|
||||
eventSource.open();
|
||||
System.out.println("Wainting for incoming event ...");
|
||||
|
||||
//Consuming events for one hour
|
||||
Thread.sleep(60 * 60 * 1000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
client.close();
|
||||
System.out.println("End");
|
||||
}
|
||||
|
||||
// A new event is received
|
||||
private static Consumer<InboundSseEvent> onEvent = (inboundSseEvent) -> {
|
||||
String data = inboundSseEvent.readData();
|
||||
System.out.println(data);
|
||||
};
|
||||
|
||||
//Error
|
||||
private static Consumer<Throwable> onError = (throwable) -> {
|
||||
throwable.printStackTrace();
|
||||
};
|
||||
|
||||
//Connection close and there is nothing to receive
|
||||
private static Runnable onComplete = () -> {
|
||||
System.out.println("Done!");
|
||||
};
|
||||
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
<?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>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
|
@ -0,0 +1,85 @@
|
|||
<?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">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>sse-jaxrs</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>sse-jaxrs-server</artifactId>
|
||||
<packaging>war</packaging>
|
||||
|
||||
<properties>
|
||||
<liberty-maven-plugin.version>2.4.2</liberty-maven-plugin.version>
|
||||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||
<openliberty-version>18.0.0.2</openliberty-version>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
<finalName>${artifactId}</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>net.wasdev.wlp.maven.plugins</groupId>
|
||||
<artifactId>liberty-maven-plugin</artifactId>
|
||||
<version>${liberty-maven-plugin.version}</version>
|
||||
<configuration>
|
||||
<assemblyArtifact>
|
||||
<groupId>io.openliberty</groupId>
|
||||
<artifactId>openliberty-webProfile8</artifactId>
|
||||
<version>${openliberty-version}</version>
|
||||
<type>zip</type>
|
||||
</assemblyArtifact>
|
||||
<installAppPackages>project</installAppPackages>
|
||||
<looseApplication>true</looseApplication>
|
||||
<configFile>src/main/liberty/config/server.xml</configFile>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>install-server</id>
|
||||
<phase>prepare-package</phase>
|
||||
<goals>
|
||||
<goal>install-server</goal>
|
||||
<goal>create-server</goal>
|
||||
<goal>install-feature</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>install-apps</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>install-apps</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.ws.rs</groupId>
|
||||
<artifactId>javax.ws.rs-api</artifactId>
|
||||
<version>2.1</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.enterprise</groupId>
|
||||
<artifactId>cdi-api</artifactId>
|
||||
<version>2.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.json.bind</groupId>
|
||||
<artifactId>javax.json.bind-api</artifactId>
|
||||
<version>1.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung.sse.jaxrs;
|
||||
|
||||
import javax.ws.rs.ApplicationPath;
|
||||
import javax.ws.rs.core.Application;
|
||||
|
||||
@ApplicationPath("sse")
|
||||
public class AppConfig extends Application {
|
||||
}
|
|
@ -0,0 +1,119 @@
|
|||
package com.baeldung.sse.jaxrs;
|
||||
|
||||
import javax.enterprise.context.ApplicationScoped;
|
||||
import javax.inject.Inject;
|
||||
import javax.ws.rs.*;
|
||||
import javax.ws.rs.core.Context;
|
||||
import javax.ws.rs.core.HttpHeaders;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.sse.OutboundSseEvent;
|
||||
import javax.ws.rs.sse.Sse;
|
||||
import javax.ws.rs.sse.SseBroadcaster;
|
||||
import javax.ws.rs.sse.SseEventSink;
|
||||
|
||||
@ApplicationScoped
|
||||
@Path("stock")
|
||||
public class SseResource {
|
||||
|
||||
@Inject
|
||||
private StockService stockService;
|
||||
|
||||
private Sse sse;
|
||||
private SseBroadcaster sseBroadcaster;
|
||||
private OutboundSseEvent.Builder eventBuilder;
|
||||
|
||||
@Context
|
||||
public void setSse(Sse sse) {
|
||||
this.sse = sse;
|
||||
this.eventBuilder = sse.newEventBuilder();
|
||||
this.sseBroadcaster = sse.newBroadcaster();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("prices")
|
||||
@Produces("text/event-stream")
|
||||
public void getStockPrices(@Context SseEventSink sseEventSink,
|
||||
@HeaderParam(HttpHeaders.LAST_EVENT_ID_HEADER) @DefaultValue("-1") int lastReceivedId) {
|
||||
|
||||
int lastEventId = 1;
|
||||
if (lastReceivedId != -1) {
|
||||
lastEventId = ++lastReceivedId;
|
||||
}
|
||||
boolean running = true;
|
||||
while (running) {
|
||||
Stock stock = stockService.getNextTransaction(lastEventId);
|
||||
if (stock != null) {
|
||||
OutboundSseEvent sseEvent = this.eventBuilder
|
||||
.name("stock")
|
||||
.id(String.valueOf(lastEventId))
|
||||
.mediaType(MediaType.APPLICATION_JSON_TYPE)
|
||||
.data(Stock.class, stock)
|
||||
.reconnectDelay(3000)
|
||||
.comment("price change")
|
||||
.build();
|
||||
sseEventSink.send(sseEvent);
|
||||
lastEventId++;
|
||||
}
|
||||
//Simulate connection close
|
||||
if (lastEventId % 5 == 0) {
|
||||
sseEventSink.close();
|
||||
break;
|
||||
}
|
||||
|
||||
try {
|
||||
//Wait 5 seconds
|
||||
Thread.sleep(5 * 1000);
|
||||
} catch (InterruptedException ex) {
|
||||
// ...
|
||||
}
|
||||
//Simulatae a while boucle break
|
||||
running = lastEventId <= 2000;
|
||||
}
|
||||
sseEventSink.close();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("subscribe")
|
||||
@Produces(MediaType.SERVER_SENT_EVENTS)
|
||||
public void listen(@Context SseEventSink sseEventSink) {
|
||||
sseEventSink.send(sse.newEvent("Welcome !"));
|
||||
this.sseBroadcaster.register(sseEventSink);
|
||||
sseEventSink.send(sse.newEvent("You are registred !"));
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("publish")
|
||||
public void broadcast() {
|
||||
Runnable r = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
int lastEventId = 0;
|
||||
boolean running = true;
|
||||
while (running) {
|
||||
lastEventId++;
|
||||
Stock stock = stockService.getNextTransaction(lastEventId);
|
||||
if (stock != null) {
|
||||
OutboundSseEvent sseEvent = eventBuilder
|
||||
.name("stock")
|
||||
.id(String.valueOf(lastEventId))
|
||||
.mediaType(MediaType.APPLICATION_JSON_TYPE)
|
||||
.data(Stock.class, stock)
|
||||
.reconnectDelay(3000)
|
||||
.comment("price change")
|
||||
.build();
|
||||
sseBroadcaster.broadcast(sseEvent);
|
||||
}
|
||||
try {
|
||||
//Wait 5 seconds
|
||||
Thread.currentThread().sleep(5 * 1000);
|
||||
} catch (InterruptedException ex) {
|
||||
// ...
|
||||
}
|
||||
//Simulatae a while boucle break
|
||||
running = lastEventId <= 2000;
|
||||
}
|
||||
}
|
||||
};
|
||||
new Thread(r).start();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
package com.baeldung.sse.jaxrs;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public class Stock {
|
||||
private Integer id;
|
||||
private String name;
|
||||
private BigDecimal price;
|
||||
LocalDateTime dateTime;
|
||||
|
||||
public Stock(Integer id, String name, BigDecimal price, LocalDateTime dateTime) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.price = price;
|
||||
this.dateTime = dateTime;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public BigDecimal getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(BigDecimal price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public LocalDateTime getDateTime() {
|
||||
return dateTime;
|
||||
}
|
||||
|
||||
public void setDateTime(LocalDateTime dateTime) {
|
||||
this.dateTime = dateTime;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,78 @@
|
|||
package com.baeldung.sse.jaxrs;
|
||||
|
||||
import javax.enterprise.context.ApplicationScoped;
|
||||
import javax.enterprise.context.Initialized;
|
||||
import javax.enterprise.event.Event;
|
||||
import javax.enterprise.event.Observes;
|
||||
import javax.inject.Inject;
|
||||
import javax.inject.Named;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
@ApplicationScoped
|
||||
@Named
|
||||
public class StockService {
|
||||
|
||||
private static final BigDecimal UP = BigDecimal.valueOf(1.05f);
|
||||
private static final BigDecimal DOWN = BigDecimal.valueOf(0.95f);
|
||||
|
||||
List<String> stockNames = Arrays.asList("GOOG", "IBM", "MS", "GOOG", "YAHO");
|
||||
List<Stock> stocksDB = new ArrayList<>();
|
||||
private AtomicInteger counter = new AtomicInteger(0);
|
||||
|
||||
public void init(@Observes @Initialized(ApplicationScoped.class) Object init) {
|
||||
//Open price
|
||||
System.out.println("@Start Init ...");
|
||||
stockNames.forEach(stockName -> {
|
||||
stocksDB.add(new Stock(counter.incrementAndGet(), stockName, generateOpenPrice(), LocalDateTime.now()));
|
||||
});
|
||||
|
||||
Runnable runnable = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
//Simulate Change price and put every x seconds
|
||||
while (true) {
|
||||
int indx = new Random().nextInt(stockNames.size());
|
||||
String stockName = stockNames.get(indx);
|
||||
BigDecimal price = getLastPrice(stockName);
|
||||
BigDecimal newprice = changePrice(price);
|
||||
Stock stock = new Stock(counter.incrementAndGet(), stockName, newprice, LocalDateTime.now());
|
||||
stocksDB.add(stock);
|
||||
|
||||
int r = new Random().nextInt(30);
|
||||
try {
|
||||
Thread.currentThread().sleep(r*1000);
|
||||
} catch (InterruptedException ex) {
|
||||
// ...
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
new Thread(runnable).start();
|
||||
System.out.println("@End Init ...");
|
||||
}
|
||||
|
||||
public Stock getNextTransaction(Integer lastEventId) {
|
||||
return stocksDB.stream().filter(s -> s.getId().equals(lastEventId)).findFirst().orElse(null);
|
||||
}
|
||||
|
||||
BigDecimal generateOpenPrice() {
|
||||
float min = 70;
|
||||
float max = 120;
|
||||
return BigDecimal.valueOf(min + new Random().nextFloat() * (max - min)).setScale(4,RoundingMode.CEILING);
|
||||
}
|
||||
|
||||
BigDecimal changePrice(BigDecimal price) {
|
||||
return Math.random() >= 0.5 ? price.multiply(UP).setScale(4,RoundingMode.CEILING) : price.multiply(DOWN).setScale(4,RoundingMode.CEILING);
|
||||
}
|
||||
|
||||
private BigDecimal getLastPrice(String stockName) {
|
||||
return stocksDB.stream().filter(stock -> stock.getName().equals(stockName)).findFirst().get().getPrice();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
<server description="OpenLiberty Server">
|
||||
<featureManager>
|
||||
<feature>jaxrs-2.1</feature>
|
||||
<feature>cdi-2.0</feature>
|
||||
</featureManager>
|
||||
<httpEndpoint httpPort="9080" httpsPort="9443" id="defaultHttpEndpoint" host="*"/>
|
||||
</server>
|
|
@ -0,0 +1,6 @@
|
|||
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
|
||||
http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"
|
||||
bean-discovery-mode="all">
|
||||
</beans>
|
|
@ -0,0 +1,13 @@
|
|||
<?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>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
|
@ -0,0 +1,11 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
|
||||
version="4.0">
|
||||
<display-name>Hello Servlet</display-name>
|
||||
|
||||
<welcome-file-list>
|
||||
<welcome-file>index.html</welcome-file>
|
||||
</welcome-file-list>
|
||||
|
||||
</web-app>
|
|
@ -0,0 +1 @@
|
|||
index
|
|
@ -0,0 +1,38 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Server-Sent Event Broadcasting</title>
|
||||
</head>
|
||||
<body>
|
||||
<h2>Stock prices :</h2>
|
||||
<div>
|
||||
<ul id="data">
|
||||
</ul>
|
||||
</div>
|
||||
<script>
|
||||
|
||||
var source = new EventSource('sse/stock/subscribe');
|
||||
source.onopen = function(event) {
|
||||
console.log(event);
|
||||
};
|
||||
source.addEventListener("stock", function(event) {
|
||||
append(event.data);
|
||||
}, false);
|
||||
|
||||
source.onmessage = function(event) {
|
||||
append(event.data);
|
||||
};
|
||||
source.onerror = function(event) {
|
||||
console.log(event);
|
||||
};
|
||||
|
||||
function append(data) {
|
||||
var ul = document.getElementById("data");
|
||||
var li = document.createElement("li");
|
||||
li.appendChild(document.createTextNode(data));
|
||||
ul.insertBefore(li, ul.childNodes[0]);
|
||||
};
|
||||
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,38 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Server-Sent Event</title>
|
||||
</head>
|
||||
<body>
|
||||
<h2>Stock prices :</h2>
|
||||
<div>
|
||||
<ul id="data">
|
||||
</ul>
|
||||
</div>
|
||||
<script>
|
||||
|
||||
var source = new EventSource('sse/stock/prices');
|
||||
source.onopen = function(event) {
|
||||
console.log(event);
|
||||
};
|
||||
source.addEventListener("stock", function(event) {
|
||||
append(event.data);
|
||||
}, false);
|
||||
|
||||
source.onmessage = function(event) {
|
||||
append(event.data);
|
||||
};
|
||||
source.onerror = function(event) {
|
||||
console.log(event);
|
||||
};
|
||||
|
||||
function append(data) {
|
||||
var ul = document.getElementById("data");
|
||||
var li = document.createElement("li");
|
||||
li.appendChild(document.createTextNode(data));
|
||||
ul.insertBefore(li, ul.childNodes[0]);
|
||||
};
|
||||
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
|
@ -137,7 +137,7 @@
|
|||
<aws-lambda-java-core.version>1.1.0</aws-lambda-java-core.version>
|
||||
<gson.version>2.8.0</gson.version>
|
||||
<aws-java-sdk.version>1.11.290</aws-java-sdk.version>
|
||||
<mockito-core.version>2.8.9</mockito-core.version>
|
||||
<mockito-core.version>2.21.0</mockito-core.version>
|
||||
<assertj-core.version>3.8.0</assertj-core.version>
|
||||
<dynamodblocal.version>1.11.86</dynamodblocal.version>
|
||||
<dynamodblocal.repository.url>https://s3-us-west-2.amazonaws.com/dynamodb-local/release</dynamodblocal.repository.url>
|
||||
|
|
|
@ -14,7 +14,6 @@
|
|||
- [Guide to Java 8 groupingBy Collector](http://www.baeldung.com/java-groupingby-collector)
|
||||
- [Strategy Design Pattern in Java 8](http://www.baeldung.com/java-strategy-pattern)
|
||||
- [Java 8 and Infinite Streams](http://www.baeldung.com/java-inifinite-streams)
|
||||
- [String Operations with Java Streams](http://www.baeldung.com/java-stream-operations-on-strings)
|
||||
- [Exceptions in Java 8 Lambda Expressions](http://www.baeldung.com/java-lambda-exceptions)
|
||||
- [Java 8 Stream findFirst() vs. findAny()](http://www.baeldung.com/java-stream-findfirst-vs-findany)
|
||||
- [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing)
|
||||
|
@ -34,13 +33,11 @@
|
|||
- [Copy a File with Java](http://www.baeldung.com/java-copy-file)
|
||||
- [Static and Default Methods in Interfaces in Java](http://www.baeldung.com/java-static-default-methods)
|
||||
- [Iterable to Stream in Java](http://www.baeldung.com/java-iterable-to-stream)
|
||||
- [Converting String to Stream of chars](http://www.baeldung.com/java-string-to-stream)
|
||||
- [How to Iterate Over a Stream With Indices](http://www.baeldung.com/java-stream-indices)
|
||||
- [Efficient Word Frequency Calculator in Java](http://www.baeldung.com/java-word-frequency)
|
||||
- [Primitive Type Streams in Java 8](http://www.baeldung.com/java-8-primitive-streams)
|
||||
- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
|
||||
- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection)
|
||||
- [Java 8 StringJoiner](http://www.baeldung.com/java-string-joiner)
|
||||
- [Introduction to Spliterator in Java](http://www.baeldung.com/java-spliterator)
|
||||
- [Java 8 Math New Methods](http://www.baeldung.com/java-8-math)
|
||||
- [Overview of Java Built-in Annotations](http://www.baeldung.com/java-default-annotations)
|
||||
|
@ -54,7 +51,6 @@
|
|||
- [Java 8 Unsigned Arithmetic Support](http://www.baeldung.com/java-unsigned-arithmetic)
|
||||
- [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end)
|
||||
- [Generalized Target-Type Inference in Java](http://www.baeldung.com/java-generalized-target-type-inference)
|
||||
- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string)
|
||||
- [Calculate Age in Java](http://www.baeldung.com/java-get-age)
|
||||
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
|
||||
- [Increment Date in Java](http://www.baeldung.com/java-increment-date)
|
||||
|
|
|
@ -17,7 +17,6 @@
|
|||
- [Java 9 Reactive Streams](http://www.baeldung.com/java-9-reactive-streams)
|
||||
- [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates)
|
||||
- [Java 9 java.util.Objects Additions](http://www.baeldung.com/java-9-objects-new)
|
||||
- [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string)
|
||||
- [Convert Date to LocalDate or LocalDateTime and Back](http://www.baeldung.com/java-date-to-localdate-and-localdatetime)
|
||||
- [Java 9 Variable Handles Demistyfied](http://www.baeldung.com/java-variable-handles)
|
||||
- [Exploring the New HTTP Client in Java 9](http://www.baeldung.com/java-9-http-client)
|
||||
|
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.java9.rangedates;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Date;
|
||||
|
||||
public class DatesCollectionIteration {
|
||||
|
||||
public void iteratingRangeOfDatesJava7(Collection<Date> dates) {
|
||||
|
||||
for (Date date : dates) {
|
||||
processDate(date);
|
||||
}
|
||||
}
|
||||
|
||||
public void iteratingRangeOfDatesJava8(Collection<Date> dates) {
|
||||
dates.stream()
|
||||
.forEach(this::processDate);
|
||||
}
|
||||
|
||||
private void processDate(Date date) {
|
||||
System.out.println(date);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package com.baeldung.java9.rangedates;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
public class RangeDatesIteration {
|
||||
|
||||
public void iterateBetweenDatesJava9(LocalDate startDate, LocalDate endDate) {
|
||||
|
||||
startDate.datesUntil(endDate)
|
||||
.forEach(this::processDate);
|
||||
}
|
||||
|
||||
public void iterateBetweenDatesJava8(LocalDate start, LocalDate end) {
|
||||
for (LocalDate date = start; date.isBefore(end); date = date.plusDays(1)) {
|
||||
processDate(date);
|
||||
}
|
||||
}
|
||||
|
||||
public void iterateBetweenDatesJava7(Date start, Date end) {
|
||||
Date current = start;
|
||||
|
||||
while (current.before(end)) {
|
||||
processDate(current);
|
||||
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(current);
|
||||
|
||||
calendar.add(Calendar.DATE, 1);
|
||||
|
||||
current = calendar.getTime();
|
||||
}
|
||||
}
|
||||
|
||||
private void processDate(LocalDate date) {
|
||||
System.out.println(date);
|
||||
}
|
||||
|
||||
private void processDate(Date date) {
|
||||
System.out.println(date);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,61 @@
|
|||
package com.baeldung.java9.rangedates;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Calendar;
|
||||
import java.util.Collection;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class DatesCollectionIterationUnitTest {
|
||||
|
||||
private Collection<LocalDate> localDates = LocalDate.now()
|
||||
.datesUntil(LocalDate.now()
|
||||
.plus(10L, ChronoUnit.DAYS))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
private Collection<Date> dates = localDates.stream()
|
||||
.map(localDate -> Date.from(localDate.atStartOfDay(ZoneId.systemDefault())
|
||||
.toInstant()))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
@Test
|
||||
public void givenIteratingListOfDatesJava7_WhenStartTodayAndEnding10DaysAhead() {
|
||||
DatesCollectionIteration iterateInColleciton = new DatesCollectionIteration();
|
||||
Calendar today = Calendar.getInstance();
|
||||
Calendar next10Ahead = (Calendar) today.clone();
|
||||
next10Ahead.add(Calendar.DATE, 10);
|
||||
|
||||
iterateInColleciton.iteratingRangeOfDatesJava7(createRangeDates(today.getTime(), next10Ahead.getTime()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIteratingListOfDatesJava8_WhenStartTodayAndEnd10DaysAhead() {
|
||||
DatesCollectionIteration iterateInColleciton = new DatesCollectionIteration();
|
||||
|
||||
iterateInColleciton.iteratingRangeOfDatesJava8(dates);
|
||||
}
|
||||
|
||||
private List<Date> createRangeDates(Date start, Date end) {
|
||||
|
||||
List<Date> dates = new ArrayList<>();
|
||||
Date current = start;
|
||||
|
||||
while (current.before(end)) {
|
||||
dates.add(current);
|
||||
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(current);
|
||||
calendar.add(Calendar.DATE, 1);
|
||||
|
||||
current = calendar.getTime();
|
||||
}
|
||||
|
||||
return dates;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,48 @@
|
|||
package com.baeldung.java9.rangedates;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class RangeDatesIterationUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenIterateBetweenDatesJava9_WhenStartDateAsTodayAndEndDateAs10DaysAhead() {
|
||||
LocalDate start = LocalDate.now();
|
||||
LocalDate end = start.plus(10L, ChronoUnit.DAYS);
|
||||
|
||||
RangeDatesIteration iteration = new RangeDatesIteration();
|
||||
|
||||
iteration.iterateBetweenDatesJava9(start, end);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIterateBetweenDatesJava8_WhenStartDateAsTodayAndEndDateAs10DaysAhead() {
|
||||
LocalDate start = LocalDate.now();
|
||||
LocalDate end = start.plus(10L, ChronoUnit.DAYS);
|
||||
|
||||
RangeDatesIteration iteration = new RangeDatesIteration();
|
||||
|
||||
iteration.iterateBetweenDatesJava8(start, end);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIterateBetweenDatesJava7_WhenStartDateAsTodayAndEndDateAs10DaysAhead() {
|
||||
Calendar today = Calendar.getInstance();
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.clear();
|
||||
calendar.set(today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DATE));
|
||||
Date start = calendar.getTime();
|
||||
|
||||
calendar.add(Calendar.DATE, 10);
|
||||
Date end = calendar.getTime();
|
||||
|
||||
RangeDatesIteration iteration = new RangeDatesIteration();
|
||||
|
||||
iteration.iterateBetweenDatesJava7(start, end);
|
||||
}
|
||||
|
||||
}
|
|
@ -36,3 +36,4 @@
|
|||
- [Remove the First Element from a List](http://www.baeldung.com/java-remove-first-element-from-list)
|
||||
- [How to Convert List to Map in Java](http://www.baeldung.com/java-list-to-map)
|
||||
- [Initializing HashSet at the Time of Construction](http://www.baeldung.com/java-initialize-hashset)
|
||||
- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element)
|
||||
|
|
|
@ -53,15 +53,27 @@
|
|||
<version>${junit.platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${openjdk.jmh.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${openjdk.jmh.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
<properties>
|
||||
<openjdk.jmh.version>1.19</openjdk.jmh.version>
|
||||
<junit.platform.version>1.2.0</junit.platform.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<collections-generic.version>4.01</collections-generic.version>
|
||||
<avaitility.version>1.7.0</avaitility.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<eclipse.collections.version>9.2.0</eclipse.collections.version>
|
||||
<eclipse.collections.version>7.1.0</eclipse.collections.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,59 @@
|
|||
package com.baeldung.performance;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
@Warmup(iterations = 5)
|
||||
public class CollectionsBenchmark {
|
||||
|
||||
@State(Scope.Thread)
|
||||
public static class MyState {
|
||||
private Set<Employee> employeeSet = new HashSet<>();
|
||||
private List<Employee> employeeList = new ArrayList<>();
|
||||
|
||||
private long iterations = 10000;
|
||||
|
||||
private Employee employee = new Employee(100L, "Harry");
|
||||
|
||||
@Setup(Level.Trial)
|
||||
public void setUp() {
|
||||
|
||||
for (long i = 0; i < iterations; i++) {
|
||||
employeeSet.add(new Employee(i, "John"));
|
||||
employeeList.add(new Employee(i, "John"));
|
||||
}
|
||||
|
||||
employeeList.add(employee);
|
||||
employeeSet.add(employee);
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean testArrayList(MyState state) {
|
||||
return state.employeeList.contains(state.employee);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean testHashSet(MyState state) {
|
||||
return state.employeeSet.contains(state.employee);
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Options options = new OptionsBuilder()
|
||||
.include(CollectionsBenchmark.class.getSimpleName()).threads(1)
|
||||
.forks(1).shouldFailOnError(true)
|
||||
.shouldDoGC(true)
|
||||
.jvmArgs("-server").build();
|
||||
new Runner(options).run();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
package com.baeldung.performance;
|
||||
|
||||
public class Employee {
|
||||
|
||||
private Long id;
|
||||
private String name;
|
||||
|
||||
public Employee(Long id, String name) {
|
||||
this.name = name;
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
|
||||
Employee employee = (Employee) o;
|
||||
|
||||
if (!id.equals(employee.id)) return false;
|
||||
return name.equals(employee.name);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = id.hashCode();
|
||||
result = 31 * result + name.hashCode();
|
||||
return result;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
package com.baeldung.collection;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class CollectionsEmpty {
|
||||
|
||||
@Test
|
||||
public void givenArrayList_whenAddingElement_addsNewElement() {
|
||||
ArrayList<String> mutableList = new ArrayList<>();
|
||||
mutableList.add("test");
|
||||
|
||||
Assert.assertEquals(mutableList.size(), 1);
|
||||
Assert.assertEquals(mutableList.get(0), "test");
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void givenCollectionsEmptyList_whenAddingElement_throwsUnsupportedOperationException() {
|
||||
List<String> immutableList = Collections.emptyList();
|
||||
immutableList.add("test");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,78 @@
|
|||
package com.baeldung.collection;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class StreamOperateAndRemoveUnitTest {
|
||||
|
||||
private List<Item> itemList;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
|
||||
itemList = new ArrayList<>();
|
||||
for (int i = 0; i < 10; i++) {
|
||||
itemList.add(new Item(i));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOf10Items_whenFilteredForQualifiedItems_thenFilteredListContains5Items() {
|
||||
|
||||
final List<Item> filteredList = itemList.stream().filter(item -> item.isQualified())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
Assert.assertEquals(5, filteredList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOf10Items_whenOperateAndRemoveQualifiedItemsUsingRemoveIf_thenListContains5Items() {
|
||||
|
||||
itemList.stream().filter(item -> item.isQualified()).forEach(item -> item.operate());
|
||||
itemList.removeIf(item -> item.isQualified());
|
||||
|
||||
Assert.assertEquals(5, itemList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOf10Items_whenOperateAndRemoveQualifiedItemsUsingRemoveAll_thenListContains5Items() {
|
||||
|
||||
final List<Item> operatedList = new ArrayList<>();
|
||||
itemList.stream().filter(item -> item.isQualified()).forEach(item -> {
|
||||
item.operate();
|
||||
operatedList.add(item);
|
||||
});
|
||||
itemList.removeAll(operatedList);
|
||||
|
||||
Assert.assertEquals(5, itemList.size());
|
||||
}
|
||||
|
||||
class Item {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
|
||||
|
||||
private final int value;
|
||||
|
||||
public Item(final int value) {
|
||||
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public boolean isQualified() {
|
||||
|
||||
return value % 2 == 0;
|
||||
}
|
||||
|
||||
public void operate() {
|
||||
|
||||
logger.info("Even Number: " + this.value);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -4,6 +4,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
|
|||
import static org.hamcrest.Matchers.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
|
@ -48,4 +49,14 @@ public class RemoveFirstElementUnitTest {
|
|||
assertThat(linkedList, not(contains("cat")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringArray_whenRemovingFirstElement_thenArrayIsSmallerAndElementRemoved() {
|
||||
String[] stringArray = {"foo", "bar", "baz"};
|
||||
|
||||
String[] modifiedArray = Arrays.copyOfRange(stringArray, 1, stringArray.length);
|
||||
|
||||
assertThat(modifiedArray.length, is(2));
|
||||
assertThat(modifiedArray[0], is("bar"));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -0,0 +1,26 @@
|
|||
package org.baeldung.java.collections;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
class CollectionsEmpty {
|
||||
|
||||
@Test
|
||||
public void givenArrayList_whenAddingElement_addsNewElement() {
|
||||
ArrayList<String> mutableList = new ArrayList<>();
|
||||
mutableList.add("test");
|
||||
|
||||
Assert.assertEquals(mutableList.size(), 1);
|
||||
Assert.assertEquals(mutableList.get(0), "test");
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void givenCollectionsEmptyList_whenAddingElement_throwsUnsupportedOperationException() {
|
||||
List<String> immutableList = Collections.emptyList();
|
||||
immutableList.add("test");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
*.class
|
||||
|
||||
0.*
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
.resourceCache
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
|
||||
# Files generated by integration tests
|
||||
*.txt
|
||||
backup-pom.xml
|
||||
/bin/
|
||||
/temp
|
||||
|
||||
#IntelliJ specific
|
||||
.idea/
|
||||
*.iml
|
|
@ -0,0 +1,15 @@
|
|||
=========
|
||||
|
||||
## Core Java Concurrency Collections Examples
|
||||
|
||||
### Relevant Articles:
|
||||
- [Guide to java.util.concurrent.BlockingQueue](http://www.baeldung.com/java-blocking-queue)
|
||||
- [A Guide to ConcurrentMap](http://www.baeldung.com/java-concurrent-map)
|
||||
- [Guide to PriorityBlockingQueue in Java](http://www.baeldung.com/java-priority-blocking-queue)
|
||||
- [Avoiding the ConcurrentModificationException in Java](http://www.baeldung.com/java-concurrentmodificationexception)
|
||||
- [Custom Thread Pools In Java 8 Parallel Streams](http://www.baeldung.com/java-8-parallel-streams-custom-threadpool)
|
||||
- [Guide to DelayQueue](http://www.baeldung.com/java-delay-queue)
|
||||
- [A Guide to Java SynchronousQueue](http://www.baeldung.com/java-synchronous-queue)
|
||||
- [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue)
|
||||
- [Guide to the ConcurrentSkipListMap](http://www.baeldung.com/java-concurrent-skip-list-map)
|
||||
- [Guide to CopyOnWriteArrayList](http://www.baeldung.com/java-copy-on-write-arraylist)
|
|
@ -0,0 +1,94 @@
|
|||
<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">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>core-java-concurrency-collections</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>core-java-concurrency-collections</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>${commons-io.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-math3</artifactId>
|
||||
<version>${commons-math3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.jayway.awaitility</groupId>
|
||||
<artifactId>awaitility</artifactId>
|
||||
<version>${avaitility.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-concurrency-collections</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy-dependencies</id>
|
||||
<phase>prepare-package</phase>
|
||||
<goals>
|
||||
<goal>copy-dependencies</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<outputDirectory>${project.build.directory}/libs</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- util -->
|
||||
<guava.version>21.0</guava.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<commons-math3.version>3.6.1</commons-math3.version>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<collections-generic.version>4.01</collections-generic.version>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<avaitility.version>1.7.0</avaitility.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -10,15 +10,18 @@ public class BlockingQueueUsage {
|
|||
int N_CONSUMERS = Runtime.getRuntime().availableProcessors();
|
||||
int poisonPill = Integer.MAX_VALUE;
|
||||
int poisonPillPerProducer = N_CONSUMERS / N_PRODUCERS;
|
||||
|
||||
int mod = N_CONSUMERS % N_PRODUCERS;
|
||||
BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(BOUND);
|
||||
|
||||
for (int i = 0; i < N_PRODUCERS; i++) {
|
||||
for (int i = 1; i < N_PRODUCERS; i++) {
|
||||
new Thread(new NumbersProducer(queue, poisonPill, poisonPillPerProducer)).start();
|
||||
}
|
||||
|
||||
for (int j = 0; j < N_CONSUMERS; j++) {
|
||||
new Thread(new NumbersConsumer(queue, poisonPill)).start();
|
||||
}
|
||||
|
||||
new Thread(new NumbersProducer(queue, poisonPill, poisonPillPerProducer+mod)).start();
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>web - %date [%thread] %-5level %logger{36} - %message%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>
|
|
@ -0,0 +1,13 @@
|
|||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
|
@ -7,22 +7,12 @@
|
|||
- [A Guide to the Java ExecutorService](http://www.baeldung.com/java-executor-service-tutorial)
|
||||
- [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava)
|
||||
- [Guide to java.util.concurrent.Future](http://www.baeldung.com/java-future)
|
||||
- [Guide to java.util.concurrent.BlockingQueue](http://www.baeldung.com/java-blocking-queue)
|
||||
- [Guide to CountDownLatch in Java](http://www.baeldung.com/java-countdown-latch)
|
||||
- [A Guide to ConcurrentMap](http://www.baeldung.com/java-concurrent-map)
|
||||
- [Guide to PriorityBlockingQueue in Java](http://www.baeldung.com/java-priority-blocking-queue)
|
||||
- [Avoiding the ConcurrentModificationException in Java](http://www.baeldung.com/java-concurrentmodificationexception)
|
||||
- [Custom Thread Pools In Java 8 Parallel Streams](http://www.baeldung.com/java-8-parallel-streams-custom-threadpool)
|
||||
- [Guide to java.util.concurrent.Locks](http://www.baeldung.com/java-concurrent-locks)
|
||||
- [An Introduction to ThreadLocal in Java](http://www.baeldung.com/java-threadlocal)
|
||||
- [Guide to DelayQueue](http://www.baeldung.com/java-delay-queue)
|
||||
- [A Guide to Java SynchronousQueue](http://www.baeldung.com/java-synchronous-queue)
|
||||
- [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue)
|
||||
- [Guide to the ConcurrentSkipListMap](http://www.baeldung.com/java-concurrent-skip-list-map)
|
||||
- [Difference Between Wait and Sleep in Java](http://www.baeldung.com/java-wait-and-sleep)
|
||||
- [LongAdder and LongAccumulator in Java](http://www.baeldung.com/java-longadder-and-longaccumulator)
|
||||
- [The Dining Philosophers Problem in Java](http://www.baeldung.com/java-dining-philoshophers)
|
||||
- [Guide to CopyOnWriteArrayList](http://www.baeldung.com/java-copy-on-write-arraylist)
|
||||
- [Guide to the Java Phaser](http://www.baeldung.com/java-phaser)
|
||||
- [Guide to Synchronized Keyword in Java](http://www.baeldung.com/java-synchronized)
|
||||
- [An Introduction to Atomic Variables in Java](http://www.baeldung.com/java-atomic-variables)
|
||||
|
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.fileparser;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class BufferedReaderExample {
|
||||
|
||||
protected static ArrayList<String> generateArrayListFromFile(String filename) throws IOException {
|
||||
|
||||
ArrayList<String> result = new ArrayList<>();
|
||||
|
||||
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
|
||||
|
||||
while (br.ready()) {
|
||||
result.add(br.readLine());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
package com.baeldung.fileparser;
|
||||
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class FileReaderExample {
|
||||
|
||||
protected static ArrayList<String> generateArrayListFromFile(String filename) throws IOException {
|
||||
|
||||
ArrayList<String> result = new ArrayList<>();
|
||||
|
||||
try (FileReader f = new FileReader(filename)) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
while (f.ready()) {
|
||||
char c = (char) f.read();
|
||||
if (c == '\n') {
|
||||
result.add(sb.toString());
|
||||
sb = new StringBuffer();
|
||||
} else {
|
||||
sb.append(c);
|
||||
}
|
||||
}
|
||||
if (sb.length() > 0) {
|
||||
result.add(sb.toString());
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.fileparser;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class FilesReadLinesExample {
|
||||
|
||||
protected static ArrayList<String> generateArrayListFromFile(String filename) throws IOException {
|
||||
|
||||
List<String> result = Files.readAllLines(Paths.get(filename));
|
||||
|
||||
return (ArrayList<String>) result;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.fileparser;
|
||||
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class ScannerIntExample {
|
||||
|
||||
protected static ArrayList<Integer> generateArrayListFromFile(String filename) throws IOException {
|
||||
|
||||
ArrayList<Integer> result = new ArrayList<>();
|
||||
|
||||
try (Scanner s = new Scanner(new FileReader(filename))) {
|
||||
|
||||
while (s.hasNext()) {
|
||||
result.add(s.nextInt());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.fileparser;
|
||||
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class ScannerStringExample {
|
||||
|
||||
protected static ArrayList<String> generateArrayListFromFile(String filename) throws IOException {
|
||||
|
||||
ArrayList<String> result = new ArrayList<>();
|
||||
|
||||
try (Scanner s = new Scanner(new FileReader(filename))) {
|
||||
|
||||
while (s.hasNext()) {
|
||||
result.add(s.nextLine());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -18,7 +18,7 @@ public class FilenameFilterManualTest {
|
|||
@BeforeClass
|
||||
public static void setupClass() {
|
||||
directory = new File(FilenameFilterManualTest.class.getClassLoader()
|
||||
.getResource("testFolder")
|
||||
.getResource("fileNameFilterManualTestFolder")
|
||||
.getFile());
|
||||
}
|
||||
|
||||
|
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.fileparser;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class BufferedReaderUnitTest {
|
||||
|
||||
protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
|
||||
|
||||
@Test
|
||||
public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
|
||||
List<String> lines = BufferedReaderExample.generateArrayListFromFile(TEXT_FILENAME);
|
||||
assertTrue("File does not has 2 lines", lines.size() == 2);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.fileparser;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FileReaderUnitTest {
|
||||
|
||||
protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
|
||||
|
||||
@Test
|
||||
public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
|
||||
List<String> lines = FileReaderExample.generateArrayListFromFile(TEXT_FILENAME);
|
||||
assertTrue("File does not has 2 lines", lines.size() == 2);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.fileparser;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FilesReadAllLinesUnitTest {
|
||||
|
||||
protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
|
||||
|
||||
@Test
|
||||
public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
|
||||
List<String> lines = FilesReadLinesExample.generateArrayListFromFile(TEXT_FILENAME);
|
||||
assertTrue("File does not has 2 lines", lines.size() == 2);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.fileparser;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ScannerIntUnitTest {
|
||||
|
||||
protected static final String NUMBER_FILENAME = "src/test/resources/sampleNumberFile.txt";
|
||||
|
||||
@Test
|
||||
public void whenParsingExistingTextFile_thenGetIntArrayList() throws IOException {
|
||||
List<Integer> numbers = ScannerIntExample.generateArrayListFromFile(NUMBER_FILENAME);
|
||||
assertTrue("File does not has 2 lines", numbers.size() == 2);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.fileparser;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ScannerStringUnitTest {
|
||||
|
||||
protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
|
||||
|
||||
@Test
|
||||
public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
|
||||
List<String> lines = ScannerStringExample.generateArrayListFromFile(TEXT_FILENAME);
|
||||
assertTrue("File does not has 2 lines", lines.size() == 2);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,2 @@
|
|||
111
|
||||
222
|
|
@ -0,0 +1,2 @@
|
|||
Hello
|
||||
World
|
|
@ -0,0 +1,8 @@
|
|||
=========
|
||||
|
||||
## Core Java Persistence Examples
|
||||
|
||||
### Relevant Articles:
|
||||
- [Introduction to JDBC](http://www.baeldung.com/java-jdbc)
|
||||
- [Batch Processing in JDBC](http://www.baeldung.com/jdbc-batch-processing)
|
||||
- [Introduction to the JDBC RowSet Interface in Java](http://www.baeldung.com/java-jdbc-rowset)
|
|
@ -39,6 +39,16 @@
|
|||
<artifactId>c3p0</artifactId>
|
||||
<version>${c3p0.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
<version>${springframework.spring-web.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
<version>${springframework.boot.spring-boot-starter.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<finalName>core-java-persistence</finalName>
|
||||
|
@ -55,5 +65,7 @@
|
|||
<commons-dbcp2.version>2.4.0</commons-dbcp2.version>
|
||||
<HikariCP.version>3.2.0</HikariCP.version>
|
||||
<c3p0.version>0.9.5.2</c3p0.version>
|
||||
<springframework.boot.spring-boot-starter.version>1.5.8.RELEASE</springframework.boot.spring-boot-starter.version>
|
||||
<springframework.spring-web.version>4.3.4.RELEASE</springframework.spring-web.version>
|
||||
</properties>
|
||||
</project>
|
|
@ -303,7 +303,7 @@
|
|||
<avaitility.version>1.7.0</avaitility.version>
|
||||
|
||||
<!-- maven plugins -->
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
|
||||
<sun-tools.version>1.8.0</sun-tools.version>
|
||||
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
|
||||
</properties>
|
||||
|
|
|
@ -3,18 +3,14 @@
|
|||
## Core Java Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
- [Java – Generate Random String](http://www.baeldung.com/java-random-string)
|
||||
- [Java Timer](http://www.baeldung.com/java-timer-and-timertask)
|
||||
- [How to Run a Shell Command in Java](http://www.baeldung.com/run-shell-command-in-java)
|
||||
- [MD5 Hashing in Java](http://www.baeldung.com/java-md5)
|
||||
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
|
||||
- [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets)
|
||||
- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string)
|
||||
- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer)
|
||||
- [Java – Try with Resources](http://www.baeldung.com/java-try-with-resources)
|
||||
- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join)
|
||||
- [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java)
|
||||
- [How to Convert String to different data types in Java](http://www.baeldung.com/java-string-conversions)
|
||||
- [Introduction to Java Generics](http://www.baeldung.com/java-generics)
|
||||
- [Generate equals() and hashCode() with Eclipse](http://www.baeldung.com/java-eclipse-equals-and-hashcode)
|
||||
- [A Guide To Java Regular Expressions API](http://www.baeldung.com/regular-expressions-java)
|
||||
|
@ -37,8 +33,6 @@
|
|||
- [A Quick JUnit vs TestNG Comparison](http://www.baeldung.com/junit-vs-testng)
|
||||
- [Java Primitive Conversions](http://www.baeldung.com/java-primitive-conversions)
|
||||
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
|
||||
- [Converting Strings to Enums in Java](http://www.baeldung.com/java-string-to-enum)
|
||||
- [Quick Guide to the Java StringTokenizer](http://www.baeldung.com/java-stringtokenizer)
|
||||
- [JVM Log Forging](http://www.baeldung.com/jvm-log-forging)
|
||||
- [Guide to sun.misc.Unsafe](http://www.baeldung.com/java-unsafe)
|
||||
- [How to Perform a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request)
|
||||
|
@ -53,36 +47,28 @@
|
|||
- [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method)
|
||||
- [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies)
|
||||
- [How to Copy an Array in Java](http://www.baeldung.com/java-array-copy)
|
||||
- [Introduction to JDBC](http://www.baeldung.com/java-jdbc)
|
||||
- [Period and Duration in Java](http://www.baeldung.com/java-period-duration)
|
||||
- [Converting a Stack Trace to a String in Java](http://www.baeldung.com/java-stacktrace-to-string)
|
||||
- [Count Occurrences of a Char in a String](http://www.baeldung.com/java-count-chars)
|
||||
- [Java Double Brace Initialization](http://www.baeldung.com/java-double-brace-initialization)
|
||||
- [The StackOverflowError in Java](http://www.baeldung.com/java-stack-overflow-error)
|
||||
- [Split a String in Java](http://www.baeldung.com/java-split-string)
|
||||
- [Introduction to Java Serialization](http://www.baeldung.com/java-serialization)
|
||||
- [How to Remove the Last Character of a String?](http://www.baeldung.com/java-remove-last-character-of-string)
|
||||
- [ClassNotFoundException vs NoClassDefFoundError](http://www.baeldung.com/java-classnotfoundexception-and-noclassdeffounderror)
|
||||
- [Guide to UUID in Java](http://www.baeldung.com/java-uuid)
|
||||
- [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char)
|
||||
- [Guide to hashCode() in Java](http://www.baeldung.com/java-hashcode)
|
||||
- [Difference between URL and URI](http://www.baeldung.com/java-url-vs-uri)
|
||||
- [Broadcasting and Multicasting in Java](http://www.baeldung.com/java-broadcast-multicast)
|
||||
- [CharSequence vs. String in Java](http://www.baeldung.com/java-char-sequence-string)
|
||||
- [Period and Duration in Java](http://www.baeldung.com/java-period-duration)
|
||||
- [Guide to the Diamond Operator in Java](http://www.baeldung.com/java-diamond-operator)
|
||||
- [“Sneaky Throws” in Java](http://www.baeldung.com/java-sneaky-throws)
|
||||
- [OutOfMemoryError: GC Overhead Limit Exceeded](http://www.baeldung.com/java-gc-overhead-limit-exceeded)
|
||||
- [StringBuilder and StringBuffer in Java](http://www.baeldung.com/java-string-builder-string-buffer)
|
||||
- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin)
|
||||
- [A Guide to the Static Keyword in Java](http://www.baeldung.com/java-static)
|
||||
- [Initializing Arrays in Java](http://www.baeldung.com/java-initialize-array)
|
||||
- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool)
|
||||
- [Quick Example - Comparator vs Comparable in Java](http://www.baeldung.com/java-comparator-comparable)
|
||||
- [Quick Guide to Java Stack](http://www.baeldung.com/java-stack)
|
||||
- [The Java continue and break Keywords](http://www.baeldung.com/java-continue-and-break)
|
||||
- [Guide to java.util.Formatter](http://www.baeldung.com/java-string-formatter)
|
||||
- [Batch Processing in JDBC](http://www.baeldung.com/jdbc-batch-processing)
|
||||
- [Check if a Java Array Contains a Value](http://www.baeldung.com/java-array-contains-value)
|
||||
- [How to Invert an Array in Java](http://www.baeldung.com/java-invert-array)
|
||||
- [Guide to the Cipher Class](http://www.baeldung.com/java-cipher-class)
|
||||
|
@ -90,7 +76,6 @@
|
|||
- [Implementing a Binary Tree in Java](http://www.baeldung.com/java-binary-tree)
|
||||
- [A Guide to ThreadLocalRandom in Java](http://www.baeldung.com/java-thread-local-random)
|
||||
- [RegEx for matching Date Pattern in Java](http://www.baeldung.com/java-date-regular-expressions)
|
||||
- [Introduction to the JDBC RowSet Interface in Java](http://www.baeldung.com/java-jdbc-rowset)
|
||||
- [Nested Classes in Java](http://www.baeldung.com/java-nested-classes)
|
||||
- [A Guide to Java Loops](http://www.baeldung.com/java-loops)
|
||||
- [Varargs in Java](http://www.baeldung.com/java-varargs)
|
||||
|
@ -105,15 +90,12 @@
|
|||
- [The Trie Data Structure in Java](http://www.baeldung.com/trie-java)
|
||||
- [Introduction to Javadoc](http://www.baeldung.com/javadoc)
|
||||
- [How to Make a Deep Copy of an Object in Java](http://www.baeldung.com/java-deep-copy)
|
||||
- [Check if a String is a Palindrome](http://www.baeldung.com/java-palindrome)
|
||||
- [Comparing Strings in Java](http://www.baeldung.com/java-compare-strings)
|
||||
- [Guide to Inheritance in Java](http://www.baeldung.com/java-inheritance)
|
||||
- [Guide to Externalizable Interface in Java](http://www.baeldung.com/java-externalizable)
|
||||
- [Object Type Casting in Java](http://www.baeldung.com/java-type-casting)
|
||||
- [A Practical Guide to DecimalFormat](http://www.baeldung.com/java-decimalformat)
|
||||
- [How to Detect the OS Using Java](http://www.baeldung.com/java-detect-os)
|
||||
- [ASCII Art in Java](http://www.baeldung.com/ascii-art-in-java)
|
||||
- [An Advanced Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging-advanced)
|
||||
- [Handling Daylight Savings Time in Java](http://www.baeldung.com/java-daylight-savings)
|
||||
- [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition)
|
||||
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
|
||||
|
@ -139,11 +121,9 @@
|
|||
- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java)
|
||||
- [Using Java Assertions](http://www.baeldung.com/java-assert)
|
||||
- [Pass-By-Value as a Parameter Passing Mechanism in Java](http://www.baeldung.com/java-pass-by-value-or-pass-by-reference)
|
||||
- [Check If a String Is Numeric in Java](http://www.baeldung.com/java-check-string-number)
|
||||
- [Variable and Method Hiding in Java](http://www.baeldung.com/java-variable-method-hiding)
|
||||
- [Access Modifiers in Java](http://www.baeldung.com/java-access-modifiers)
|
||||
- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java)
|
||||
- [Why Use char[] Array Over a String for Storing Passwords in Java?](http://www.baeldung.com/java-storing-passwords)
|
||||
- [Introduction to Creational Design Patterns](http://www.baeldung.com/creational-design-patterns)
|
||||
- [Proxy, Decorator, Adapter and Bridge Patterns](http://www.baeldung.com/java-structural-design-patterns)
|
||||
- [Singletons in Java](http://www.baeldung.com/java-singleton)
|
||||
|
@ -157,7 +137,6 @@
|
|||
- [Importance of Main Manifest Attribute in a Self-Executing JAR](http://www.baeldung.com/java-jar-executable-manifest-main-class)
|
||||
- [Extracting Year, Month and Day from Date in Java](http://www.baeldung.com/java-year-month-day)
|
||||
- [Get Date Without Time in Java](http://www.baeldung.com/java-date-without-time)
|
||||
- [Convert a String to Title Case](http://www.baeldung.com/java-string-title-case)
|
||||
- [How to Get the File Extension of a File in Java](http://www.baeldung.com/java-file-extension)
|
||||
- [Immutable Objects in Java](http://www.baeldung.com/java-immutable-object)
|
||||
- [Console I/O in Java](http://www.baeldung.com/java-console-input-output)
|
||||
|
@ -171,3 +150,4 @@
|
|||
- [Guide to Java Instrumentation](http://www.baeldung.com/java-instrumentation)
|
||||
- [Getting a File’s Mime Type in Java](http://www.baeldung.com/java-file-mime-type)
|
||||
- [Common Java Exceptions](http://www.baeldung.com/java-common-exceptions)
|
||||
- [Java Constructors vs Static Factory Methods](https://www.baeldung.com/java-constructors-vs-static-factory-methods)
|
||||
|
|
|
@ -127,11 +127,6 @@
|
|||
<artifactId>spring-web</artifactId>
|
||||
<version>${springframework.spring-web.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
<version>${springframework.boot.spring-boot-starter.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
|
@ -142,11 +137,6 @@
|
|||
<artifactId>mail</artifactId>
|
||||
<version>${javax.mail.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.ibm.icu</groupId>
|
||||
<artifactId>icu4j</artifactId>
|
||||
<version>${icu4j.version}</version>
|
||||
</dependency>
|
||||
<!-- Mime Type Resolution Libraries -->
|
||||
<dependency>
|
||||
<groupId>org.apache.tika</groupId>
|
||||
|
@ -530,9 +520,8 @@
|
|||
<assertj-core.version>3.10.0</assertj-core.version>
|
||||
|
||||
<!-- maven plugins -->
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
|
||||
<springframework.spring-web.version>4.3.4.RELEASE</springframework.spring-web.version>
|
||||
<springframework.boot.spring-boot-starter.version>1.5.8.RELEASE</springframework.boot.spring-boot-starter.version>
|
||||
|
||||
<javamoney.moneta.version>1.1</javamoney.moneta.version>
|
||||
<h2database.version>1.4.197</h2database.version>
|
||||
|
|
|
@ -0,0 +1,23 @@
|
|||
package com.baeldung.binding;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Created by madhumita.g on 25-07-2018.
|
||||
*/
|
||||
public class Animal {
|
||||
|
||||
final static Logger logger = LoggerFactory.getLogger(Animal.class);
|
||||
|
||||
public void makeNoise() {
|
||||
logger.info("generic animal noise");
|
||||
}
|
||||
|
||||
public void makeNoise(Integer repetitions) {
|
||||
while(repetitions != 0) {
|
||||
logger.info("generic animal noise countdown " + repetitions);
|
||||
repetitions -= 1;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package com.baeldung.binding;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Created by madhumita.g on 25-07-2018.
|
||||
*/
|
||||
public class AnimalActivity {
|
||||
|
||||
final static Logger logger = LoggerFactory.getLogger(AnimalActivity.class);
|
||||
|
||||
|
||||
public static void sleep(Animal animal) {
|
||||
logger.info("Animal is sleeping");
|
||||
}
|
||||
|
||||
public static void sleep(Cat cat) {
|
||||
logger.info("Cat is sleeping");
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
Animal animal = new Animal();
|
||||
|
||||
//calling methods of animal object
|
||||
animal.makeNoise();
|
||||
|
||||
animal.makeNoise(3);
|
||||
|
||||
|
||||
//assigning a dog object to reference of type Animal
|
||||
Animal catAnimal = new Cat();
|
||||
|
||||
catAnimal.makeNoise();
|
||||
|
||||
// calling static function
|
||||
AnimalActivity.sleep(catAnimal);
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.binding;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Created by madhumita.g on 25-07-2018.
|
||||
*/
|
||||
public class Cat extends Animal {
|
||||
|
||||
final static Logger logger = LoggerFactory.getLogger(Cat.class);
|
||||
|
||||
public void makeNoise() {
|
||||
|
||||
logger.info("meow");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung.constructorsstaticfactorymethods.application;
|
||||
|
||||
import com.baeldung.constructorsstaticfactorymethods.entities.User;
|
||||
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
User user1 = User.createWithDefaultCountry("John", "john@domain.com");
|
||||
User user2 = User.createWithLoggedInstantiationTime("John", "john@domain.com", "Argentina");
|
||||
User user3 = User.getSingletonInstance("John", "john@domain.com", "Argentina");
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue