Merge branch 'eugenp:master' into danielmcnally285_string_to_long
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
## Java RMI
|
||||
|
||||
This module contains articles about Remote Method Invocation (RMI) in Java.
|
||||
|
||||
### Relevant articles
|
||||
|
||||
- [Getting Started with Java RMI](https://www.baeldung.com/java-rmi)
|
||||
@@ -0,0 +1,17 @@
|
||||
<?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>
|
||||
<groupId>com.baeldung.rmi</groupId>
|
||||
<artifactId>java-rmi</artifactId>
|
||||
<name>java-rmi</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.rmi;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class Message implements Serializable {
|
||||
|
||||
private String messageText;
|
||||
|
||||
private String contentType;
|
||||
|
||||
public Message() {
|
||||
}
|
||||
|
||||
public Message(String messageText, String contentType) {
|
||||
|
||||
this.messageText = messageText;
|
||||
this.contentType = contentType;
|
||||
}
|
||||
|
||||
public String getMessageText() {
|
||||
return messageText;
|
||||
}
|
||||
|
||||
public void setMessageText(String messageText) {
|
||||
this.messageText = messageText;
|
||||
}
|
||||
|
||||
public String getContentType() {
|
||||
return contentType;
|
||||
}
|
||||
|
||||
public void setContentType(String contentType) {
|
||||
this.contentType = contentType;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.rmi;
|
||||
|
||||
import java.rmi.Remote;
|
||||
import java.rmi.RemoteException;
|
||||
|
||||
public interface MessengerService extends Remote {
|
||||
|
||||
public String sendMessage(String clientMessage) throws RemoteException;
|
||||
|
||||
public Message sendMessage(Message clientMessage) throws RemoteException;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.rmi;
|
||||
|
||||
import java.rmi.RemoteException;
|
||||
import java.rmi.registry.LocateRegistry;
|
||||
import java.rmi.registry.Registry;
|
||||
import java.rmi.server.UnicastRemoteObject;
|
||||
|
||||
public class MessengerServiceImpl implements MessengerService {
|
||||
|
||||
public String sendMessage(String clientMessage) {
|
||||
|
||||
String serverMessage = null;
|
||||
if (clientMessage.equals("Client Message")) {
|
||||
serverMessage = "Server Message";
|
||||
}
|
||||
|
||||
return serverMessage;
|
||||
}
|
||||
|
||||
public void createStubAndBind() throws RemoteException {
|
||||
|
||||
MessengerService stub = (MessengerService) UnicastRemoteObject.exportObject((MessengerService) this, 0);
|
||||
Registry registry = LocateRegistry.createRegistry(1099);
|
||||
registry.rebind("MessengerService", stub);
|
||||
}
|
||||
|
||||
public Message sendMessage(Message clientMessage) throws RemoteException {
|
||||
|
||||
Message serverMessage = null;
|
||||
if (clientMessage.getMessageText().equals("Client Message")) {
|
||||
serverMessage = new Message("Server Message", "text/plain");
|
||||
}
|
||||
|
||||
return serverMessage;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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,42 @@
|
||||
package com.baeldung.rmi;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.rmi.NotBoundException;
|
||||
import java.rmi.RemoteException;
|
||||
import java.rmi.registry.LocateRegistry;
|
||||
import java.rmi.registry.Registry;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
public class JavaRMIIntegrationTest {
|
||||
|
||||
private MessengerServiceImpl messengerService;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
try {
|
||||
messengerService = new MessengerServiceImpl();
|
||||
messengerService.createStubAndBind();
|
||||
} catch (RemoteException e) {
|
||||
fail("Exception Occurred: " + e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenClientSendsMessageToServer_thenServerSendsResponseMessage() {
|
||||
try {
|
||||
Registry registry = LocateRegistry.getRegistry();
|
||||
MessengerService server = (MessengerService) registry.lookup("MessengerService");
|
||||
String responseMessage = server.sendMessage("Client Message");
|
||||
|
||||
String expectedMessage = "Server Message";
|
||||
assertEquals(responseMessage, expectedMessage);
|
||||
} catch (RemoteException | NotBoundException e) {
|
||||
fail("Exception Occurred: " + e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
## Java SPI
|
||||
|
||||
This module contains articles about the Service Provider Interface (SPI) in Java.
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Java Service Provider Interface](https://www.baeldung.com/java-spi)
|
||||
@@ -0,0 +1,16 @@
|
||||
<?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>exchange-rate-api</artifactId>
|
||||
<name>exchange-rate-api</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>java-spi</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
</project>
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.rate;
|
||||
|
||||
import com.baeldung.rate.exception.ProviderNotFoundException;
|
||||
import com.baeldung.rate.spi.ExchangeRateProvider;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.ServiceLoader;
|
||||
|
||||
public final class ExchangeRate {
|
||||
|
||||
private static final String DEFAULT_PROVIDER = "com.baeldung.rate.spi.YahooFinanceExchangeRateProvider";
|
||||
|
||||
//All providers
|
||||
public static List<ExchangeRateProvider> providers() {
|
||||
List<ExchangeRateProvider> services = new ArrayList<>();
|
||||
ServiceLoader<ExchangeRateProvider> loader = ServiceLoader.load(ExchangeRateProvider.class);
|
||||
loader.forEach(services::add);
|
||||
return services;
|
||||
}
|
||||
|
||||
//Default provider
|
||||
public static ExchangeRateProvider provider() {
|
||||
return provider(DEFAULT_PROVIDER);
|
||||
}
|
||||
|
||||
//provider by name
|
||||
public static ExchangeRateProvider provider(String providerName) {
|
||||
ServiceLoader<ExchangeRateProvider> loader = ServiceLoader.load(ExchangeRateProvider.class);
|
||||
Iterator<ExchangeRateProvider> it = loader.iterator();
|
||||
while (it.hasNext()) {
|
||||
ExchangeRateProvider provider = it.next();
|
||||
if (providerName.equals(provider.getClass().getName())) {
|
||||
return provider;
|
||||
}
|
||||
}
|
||||
throw new ProviderNotFoundException("Exchange Rate provider " + providerName + " not found");
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package com.baeldung.rate.api;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
|
||||
public class Quote {
|
||||
private String currency;
|
||||
private BigDecimal ask;
|
||||
private BigDecimal bid;
|
||||
private LocalDate date;
|
||||
|
||||
public Quote(String currency, BigDecimal ask, BigDecimal bid) {
|
||||
this.currency = currency;
|
||||
this.ask = ask;
|
||||
this.bid = bid;
|
||||
}
|
||||
|
||||
public String getCurrency() {
|
||||
return currency;
|
||||
}
|
||||
|
||||
public void setCurrency(String currency) {
|
||||
this.currency = currency;
|
||||
}
|
||||
|
||||
public BigDecimal getAsk() {
|
||||
return ask;
|
||||
}
|
||||
|
||||
public void setAsk(BigDecimal ask) {
|
||||
this.ask = ask;
|
||||
}
|
||||
|
||||
public BigDecimal getBid() {
|
||||
return bid;
|
||||
}
|
||||
|
||||
public void setBid(BigDecimal bid) {
|
||||
this.bid = bid;
|
||||
}
|
||||
|
||||
public LocalDate getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
public void setDate(LocalDate date) {
|
||||
this.date = date;
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.rate.api;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
public interface QuoteManager {
|
||||
List<Quote> getQuotes(String baseCurrency, LocalDate date);
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.rate.exception;
|
||||
|
||||
public class ProviderNotFoundException extends RuntimeException {
|
||||
|
||||
public ProviderNotFoundException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public ProviderNotFoundException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.rate.spi;
|
||||
|
||||
import com.baeldung.rate.api.QuoteManager;
|
||||
|
||||
public interface ExchangeRateProvider {
|
||||
QuoteManager create();
|
||||
}
|
||||
@@ -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,28 @@
|
||||
<?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>exchange-rate-app</artifactId>
|
||||
<name>exchange-rate-app</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>java-spi</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>exchange-rate-api</artifactId>
|
||||
<version>${exchange-rate-api.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<exchange-rate-api.version>1.0.0-SNAPSHOT</exchange-rate-api.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.rate.app;
|
||||
|
||||
import com.baeldung.rate.ExchangeRate;
|
||||
import com.baeldung.rate.api.Quote;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
public class MainApp {
|
||||
public static void main(String... args) {
|
||||
ExchangeRate.providers().forEach(provider -> {
|
||||
System.out.println("Retreiving USD quotes from provider :" + provider);
|
||||
List<Quote> quotes = provider.create().getQuotes("USD", LocalDate.now());
|
||||
System.out.println(String.format("%14s%12s|%12s", "","Ask", "Bid"));
|
||||
System.out.println("----------------------------------------");
|
||||
quotes.forEach(quote -> {
|
||||
System.out.println("USD --> " + quote.getCurrency() + " : " + String.format("%12f|%12f", quote.getAsk(), quote.getBid()));
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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,75 @@
|
||||
<?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>exchange-rate-impl</artifactId>
|
||||
<name>exchange-rate-impl</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>java-spi</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>exchange-rate-api</artifactId>
|
||||
<version>${exchange-rate-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp3</groupId>
|
||||
<artifactId>okhttp</artifactId>
|
||||
<version>${okhttp.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.json.bind</groupId>
|
||||
<artifactId>javax.json.bind-api</artifactId>
|
||||
<version>${javax.json.bind-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse</groupId>
|
||||
<artifactId>yasson</artifactId>
|
||||
<version>${yasson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish</groupId>
|
||||
<artifactId>javax.json</artifactId>
|
||||
<version>${javax.json.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<version>${maven-dependency-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy-dependencies</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>copy-dependencies</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<outputDirectory>${project.build.directory}/depends</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<exchange-rate-api.version>1.0.0-SNAPSHOT</exchange-rate-api.version>
|
||||
<okhttp.version>4.12.0</okhttp.version>
|
||||
<javax.json.bind-api.version>1.0</javax.json.bind-api.version>
|
||||
<yasson.version>1.0.1</yasson.version>
|
||||
<javax.json.version>1.1.2</javax.json.version>
|
||||
<maven-dependency-plugin.version>3.1.0</maven-dependency-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.rate.impl;
|
||||
|
||||
import com.baeldung.rate.api.QuoteManager;
|
||||
import com.baeldung.rate.spi.ExchangeRateProvider;
|
||||
|
||||
public class YahooFinanceExchangeRateProvider implements ExchangeRateProvider {
|
||||
|
||||
@Override
|
||||
public QuoteManager create() {
|
||||
return new YahooQuoteManagerImpl();
|
||||
}
|
||||
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
package com.baeldung.rate.impl;
|
||||
|
||||
import com.baeldung.rate.api.Quote;
|
||||
import com.baeldung.rate.api.QuoteManager;
|
||||
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
|
||||
import javax.json.bind.Jsonb;
|
||||
import javax.json.bind.JsonbBuilder;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Currency;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class YahooQuoteManagerImpl implements QuoteManager {
|
||||
|
||||
static final String URL_PROVIDER = "https://query2.finance.yahoo.com/v6/finance/quoteSummary/%s=X?modules=summaryDetail";
|
||||
OkHttpClient client = new OkHttpClient();
|
||||
|
||||
@Override
|
||||
public List<Quote> getQuotes(String baseCurrency, LocalDate date) {
|
||||
|
||||
List<String> currencyQuery = new ArrayList<>();
|
||||
Currency.getAvailableCurrencies().forEach(currency -> {
|
||||
if (!baseCurrency.equals(currency.getCurrencyCode())) {
|
||||
currencyQuery.add(String.format(URL_PROVIDER, baseCurrency + currency.getCurrencyCode()));
|
||||
}
|
||||
});
|
||||
final List<Quote> quotes = new ArrayList<>();
|
||||
for (String url: currencyQuery) {
|
||||
String response = doGetRequest(url);
|
||||
if (response != null) {
|
||||
final Quote map = map(response);
|
||||
if (map != null) {
|
||||
quotes.add(map);
|
||||
}
|
||||
}
|
||||
}
|
||||
return quotes;
|
||||
}
|
||||
|
||||
private Quote map(String response) {
|
||||
try (final Jsonb jsonb = JsonbBuilder.create()) {
|
||||
final Map qrw = jsonb.fromJson(response, Map.class);
|
||||
return parseResult(qrw);
|
||||
} catch (Exception e) {
|
||||
System.out.println("Error while trying to read response");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static Quote parseResult(Map qrw) {
|
||||
Quote quote = null;
|
||||
if (qrw != null) {
|
||||
final Map quoteSummary = (Map) qrw.get("quoteSummary");
|
||||
if (quoteSummary != null) {
|
||||
final List<Map> result = (List<Map>) quoteSummary.get("result");
|
||||
if (result != null) {
|
||||
final Map resultArray = result.get(0);
|
||||
if (resultArray != null) {
|
||||
final Map summaryDetail = (Map) resultArray.get("summaryDetail");
|
||||
if (summaryDetail != null) {
|
||||
quote = constructQuote(summaryDetail);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return quote;
|
||||
}
|
||||
|
||||
private static Quote constructQuote(Map summaryDetail) {
|
||||
final String currency = (String) summaryDetail.get("currency");
|
||||
final Map ask = (Map) summaryDetail.get("ask");
|
||||
final Map bid = (Map) summaryDetail.get("bid");
|
||||
final BigDecimal askPrice = (BigDecimal) ask.get("raw");
|
||||
final BigDecimal bidPrice = (BigDecimal) bid.get("raw");
|
||||
if (askPrice != null && bidPrice != null) {
|
||||
return new Quote(currency, askPrice, bidPrice);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
String doGetRequest(String url) {
|
||||
|
||||
System.out.println(url);
|
||||
Request request = new Request.Builder()
|
||||
.url(url)
|
||||
.build();
|
||||
Response response;
|
||||
try {
|
||||
response = client.newCall(request).execute();
|
||||
return response.body().string();
|
||||
} catch (IOException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
com.baeldung.rate.impl.YahooFinanceExchangeRateProvider
|
||||
@@ -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,22 @@
|
||||
<?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>java-spi</artifactId>
|
||||
<name>java-spi</name>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<modules>
|
||||
<module>exchange-rate-api</module>
|
||||
<module>exchange-rate-impl</module>
|
||||
<module>exchange-rate-app</module>
|
||||
</modules>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,7 @@
|
||||
## Java WebSocket
|
||||
|
||||
This module contains articles about WebSocket in Java.
|
||||
|
||||
### Relevant articles
|
||||
|
||||
- [A Guide to the Java API for WebSocket](https://www.baeldung.com/java-websockets)
|
||||
@@ -0,0 +1,35 @@
|
||||
<?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/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>java-websocket</artifactId>
|
||||
<name>java-websocket</name>
|
||||
<packaging>war</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>javax.websocket</groupId>
|
||||
<artifactId>javax.websocket-api</artifactId>
|
||||
<version>${javax.websocket-api.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
<version>${gson.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<javax.websocket-api.version>1.1</javax.websocket-api.version>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.model;
|
||||
|
||||
public class Message {
|
||||
private String from;
|
||||
private String to;
|
||||
private String content;
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return super.toString();
|
||||
}
|
||||
|
||||
public String getFrom() {
|
||||
return from;
|
||||
}
|
||||
|
||||
public void setFrom(String from) {
|
||||
this.from = from;
|
||||
}
|
||||
|
||||
public String getTo() {
|
||||
return to;
|
||||
}
|
||||
|
||||
public void setTo(String to) {
|
||||
this.to = to;
|
||||
}
|
||||
|
||||
public String getContent() {
|
||||
return content;
|
||||
}
|
||||
|
||||
public void setContent(String content) {
|
||||
this.content = content;
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package com.baeldung.websocket;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CopyOnWriteArraySet;
|
||||
|
||||
import javax.websocket.EncodeException;
|
||||
import javax.websocket.OnClose;
|
||||
import javax.websocket.OnError;
|
||||
import javax.websocket.OnMessage;
|
||||
import javax.websocket.OnOpen;
|
||||
import javax.websocket.Session;
|
||||
import javax.websocket.server.PathParam;
|
||||
import javax.websocket.server.ServerEndpoint;
|
||||
|
||||
import com.baeldung.model.Message;
|
||||
|
||||
@ServerEndpoint(value = "/chat/{username}", decoders = MessageDecoder.class, encoders = MessageEncoder.class)
|
||||
public class ChatEndpoint {
|
||||
private Session session;
|
||||
private static final Set<ChatEndpoint> chatEndpoints = new CopyOnWriteArraySet<>();
|
||||
private static HashMap<String, String> users = new HashMap<>();
|
||||
|
||||
@OnOpen
|
||||
public void onOpen(Session session, @PathParam("username") String username) throws IOException, EncodeException {
|
||||
|
||||
this.session = session;
|
||||
chatEndpoints.add(this);
|
||||
users.put(session.getId(), username);
|
||||
|
||||
Message message = new Message();
|
||||
message.setFrom(username);
|
||||
message.setContent("Connected!");
|
||||
broadcast(message);
|
||||
}
|
||||
|
||||
@OnMessage
|
||||
public void onMessage(Session session, Message message) throws IOException, EncodeException {
|
||||
message.setFrom(users.get(session.getId()));
|
||||
broadcast(message);
|
||||
}
|
||||
|
||||
@OnClose
|
||||
public void onClose(Session session) throws IOException, EncodeException {
|
||||
chatEndpoints.remove(this);
|
||||
Message message = new Message();
|
||||
message.setFrom(users.get(session.getId()));
|
||||
message.setContent("Disconnected!");
|
||||
broadcast(message);
|
||||
}
|
||||
|
||||
@OnError
|
||||
public void onError(Session session, Throwable throwable) {
|
||||
// Do error handling here
|
||||
}
|
||||
|
||||
private static void broadcast(Message message) throws IOException, EncodeException {
|
||||
chatEndpoints.forEach(endpoint -> {
|
||||
synchronized (endpoint) {
|
||||
try {
|
||||
endpoint.session.getBasicRemote()
|
||||
.sendObject(message);
|
||||
} catch (IOException | EncodeException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.websocket;
|
||||
|
||||
import javax.websocket.DecodeException;
|
||||
import javax.websocket.Decoder;
|
||||
import javax.websocket.EndpointConfig;
|
||||
|
||||
import com.baeldung.model.Message;
|
||||
import com.google.gson.Gson;
|
||||
|
||||
public class MessageDecoder implements Decoder.Text<Message> {
|
||||
|
||||
private static Gson gson = new Gson();
|
||||
|
||||
@Override
|
||||
public Message decode(String s) throws DecodeException {
|
||||
Message message = gson.fromJson(s, Message.class);
|
||||
return message;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean willDecode(String s) {
|
||||
return (s != null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(EndpointConfig endpointConfig) {
|
||||
// Custom initialization logic
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
// Close resources
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.websocket;
|
||||
|
||||
import javax.websocket.EncodeException;
|
||||
import javax.websocket.Encoder;
|
||||
import javax.websocket.EndpointConfig;
|
||||
|
||||
import com.baeldung.model.Message;
|
||||
import com.google.gson.Gson;
|
||||
|
||||
public class MessageEncoder implements Encoder.Text<Message> {
|
||||
|
||||
private static Gson gson = new Gson();
|
||||
|
||||
@Override
|
||||
public String encode(Message message) throws EncodeException {
|
||||
String json = gson.toJson(message);
|
||||
return json;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(EndpointConfig endpointConfig) {
|
||||
// Custom initialization logic
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
// Close resources
|
||||
}
|
||||
}
|
||||
@@ -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,5 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://java.sun.com/xml/ns/javaee"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
|
||||
</beans>
|
||||
@@ -0,0 +1,7 @@
|
||||
<!DOCTYPE web-app PUBLIC
|
||||
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
|
||||
"http://java.sun.com/dtd/web-app_2_3.dtd" >
|
||||
|
||||
<web-app>
|
||||
<display-name>Archetype Created Web Application</display-name>
|
||||
</web-app>
|
||||
@@ -0,0 +1,30 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>Chat</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td colspan="2">
|
||||
<input type="text" id="username" placeholder="Username"/>
|
||||
<button type="button" onclick="connect();" >Connect</button>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<textarea readonly="true" rows="10" cols="80" id="log"></textarea>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<input type="text" size="51" id="msg" placeholder="Message"/>
|
||||
<button type="button" onclick="send();" >Send</button>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</body>
|
||||
|
||||
<script src="websocket.js"></script>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,136 @@
|
||||
body {
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
font-size: 80%;
|
||||
background-color: #1f1f1f;
|
||||
}
|
||||
|
||||
#wrapper {
|
||||
width: 960px;
|
||||
margin: auto;
|
||||
text-align: left;
|
||||
color: #d9d9d9;
|
||||
}
|
||||
|
||||
p {
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.button {
|
||||
display: inline;
|
||||
color: #fff;
|
||||
background-color: #f2791d;
|
||||
padding: 8px;
|
||||
margin: auto;
|
||||
border-radius: 8px;
|
||||
-moz-border-radius: 8px;
|
||||
-webkit-border-radius: 8px;
|
||||
box-shadow: none;
|
||||
border: none;
|
||||
}
|
||||
|
||||
.button:hover {
|
||||
background-color: #ffb15e;
|
||||
}
|
||||
.button a, a:visited, a:hover, a:active {
|
||||
color: #fff;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
#addDevice {
|
||||
text-align: center;
|
||||
width: 960px;
|
||||
margin: auto;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
#addDeviceForm {
|
||||
text-align: left;
|
||||
width: 400px;
|
||||
margin: auto;
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
#addDeviceForm span {
|
||||
display: block;
|
||||
}
|
||||
|
||||
#content {
|
||||
margin: auto;
|
||||
width: 960px;
|
||||
}
|
||||
|
||||
.device {
|
||||
width: 180px;
|
||||
height: 110px;
|
||||
margin: 10px;
|
||||
padding: 16px;
|
||||
color: #fff;
|
||||
vertical-align: top;
|
||||
border-radius: 8px;
|
||||
-moz-border-radius: 8px;
|
||||
-webkit-border-radius: 8px;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.device.off {
|
||||
background-color: #c8cccf;
|
||||
}
|
||||
|
||||
.device span {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.deviceName {
|
||||
text-align: center;
|
||||
font-weight: bold;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.removeDevice {
|
||||
margin-top: 12px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.device.Appliance {
|
||||
background-color: #5eb85e;
|
||||
}
|
||||
|
||||
.device.Appliance a:hover {
|
||||
color: #a1ed82;
|
||||
}
|
||||
|
||||
.device.Electronics {
|
||||
background-color: #0f90d1;
|
||||
}
|
||||
|
||||
.device.Electronics a:hover {
|
||||
color: #4badd1;
|
||||
}
|
||||
|
||||
.device.Lights {
|
||||
background-color: #c2a00c;
|
||||
}
|
||||
|
||||
.device.Lights a:hover {
|
||||
color: #fad232;
|
||||
}
|
||||
|
||||
.device.Other {
|
||||
background-color: #db524d;
|
||||
}
|
||||
|
||||
.device.Other a:hover {
|
||||
color: #ff907d;
|
||||
}
|
||||
|
||||
.device a {
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.device a:visited, a:active, a:hover {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.device a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
var ws;
|
||||
|
||||
function connect() {
|
||||
var username = document.getElementById("username").value;
|
||||
|
||||
var host = document.location.host;
|
||||
var pathname = document.location.pathname;
|
||||
|
||||
ws = new WebSocket("ws://" +host + pathname + "chat/" + username);
|
||||
|
||||
ws.onmessage = function(event) {
|
||||
var log = document.getElementById("log");
|
||||
console.log(event.data);
|
||||
var message = JSON.parse(event.data);
|
||||
log.innerHTML += message.from + " : " + message.content + "\n";
|
||||
};
|
||||
}
|
||||
|
||||
function send() {
|
||||
var content = document.getElementById("msg").value;
|
||||
var json = JSON.stringify({
|
||||
"content":content
|
||||
});
|
||||
|
||||
ws.send(json);
|
||||
}
|
||||
@@ -210,6 +210,9 @@
|
||||
<module>core-java-datetime-conversion</module>
|
||||
<module>core-java-httpclient</module>
|
||||
<module>java-native</module>
|
||||
<module>java-rmi</module>
|
||||
<module>java-spi</module>
|
||||
<module>java-websocket</module>
|
||||
</modules>
|
||||
|
||||
<dependencyManagement>
|
||||
|
||||
Reference in New Issue
Block a user