Route file to Queue Apache Camel - java

I have a requirement to read a file from a folder and place it on a queue.
Here is the code I have:
import java.io.File;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.LoggingLevel;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
public class FileMove{
public static void main(final String[] arguments) {
final CamelContext camelContext = new DefaultCamelContext();
try {
camelContext.addRoutes(new RouteBuilder() {
#Override
public void configure() throws Exception {
from("file://E:/TestingWatch1/input?preMove=staging&move=.completed&scheduler=quartz2&scheduler.cron=00+*/1+*+1/1+*+?+*")
.routeId("testRoute").process(new Processor() {
#Override
public void process(Exchange msg) throws Exception {
File file = msg.getIn().getBody(File.class);
String file1 = msg.getIn().getBody(String.class);
System.out.println("" + file + file1);
}
}).
to("file://E:/TestingWatch1/output");
}
});
camelContext.start();
// Thread.sleep(10*60*1000);
// camelContext.stop();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
I am able to read the file and file contents, but I need to place it on the queue.
How do I move the file or file contents to queue using the Java DSL?

Thanks, I found the solution: Here is the code
import java.io.File;
import javax.jms.ConnectionFactory;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.LoggingLevel;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.jms.JmsComponent;
import org.apache.camel.impl.DefaultCamelContext;
public class CopyTest {
public static void main(final String[] arguments) {
final CamelContext camelContext = new DefaultCamelContext();
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "admin",
ActiveMQConnection.DEFAULT_BROKER_URL);
camelContext.addComponent("test-jms", JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));
try {
camelContext.addRoutes(new RouteBuilder() {
#Override
public void configure() throws Exception {
from("file://E:/TestingWatch1/input?preMove=staging&move=.completed&scheduler=quartz2&scheduler.cron=00+*/1+*+1/1+*+?+*")
.routeId("testRoute").process(new Processor() {
#Override
public void process(Exchange msg) throws Exception {
File file = msg.getIn().getBody(File.class);
String file1 = msg.getIn().getBody(String.class);
System.out.println("" + file + file1);
}
}).to("test-jms:queue:testMQDestination").
to("file://E:/TestingWatch1/output");
}
});
camelContext.start();
// Thread.sleep(10*60*1000);
// camelContext.stop();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

Related

Dockerize rmi application

I'm new to Docker and I would like to put my rmi server on docker and to access it using the client which is local, on the laptop. When the server is not on docker the application works, however when it is on docker, I get a "Connection Refused" error. Below is the code for the server:
import org.modelmapper.ModelMapper;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.validation.annotation.Validated;
import ro.tuc.ds2020.services.MedicationPlanService;
import ro.tuc.ds2020.servinterface.IMedicationService;
import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.*;
#SpringBootApplication
#Validated
public class Ds2020Application extends SpringBootServletInitializer {
private int port;
// private Registry registry;
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Ds2020Application.class);
}
public Ds2020Application() throws RemoteException{
this.port = 8889;
Registry registry = null;
try {
registry = LocateRegistry.createRegistry(this.port);
} catch (RemoteException e) {
e.printStackTrace();
}
try {
//MedicationPlanService is the stub // "name",stub
registry.bind(IMedicationService.class.getSimpleName(), new MedicationPlanService());
} catch (RemoteException e) {
e.printStackTrace();
} catch (AlreadyBoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
try {
SpringApplication.run(Ds2020Application.class, args);
System.out.println("The server has started.");
} catch (Exception e) {
e.printStackTrace();
}
}
#Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
}
and client:
package ro.tuc.ds2020.controller;
import ro.tuc.ds2020.DTO.DrugPlanDTO;
import ro.tuc.ds2020.servinterface.IMedicationService;
import ro.tuc.ds2020.view.DisplayTable;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
public class ClientController {
private static IMedicationService iMedicationService;
private Registry registry;
private String serverAddress;
private int serverPort;
private DisplayTable displayTable;
public ClientController() throws RemoteException, NotBoundException, SQLException, ParseException {
this.serverAddress = "localhost";
this.serverPort = 8889;
String patientID="334975ea-c90d-4fd2-9a0b-9e2c9f0e4cb9";
//obtain the stub for the registry
registry = LocateRegistry.getRegistry(serverAddress, serverPort);
//obtain stub for remote object from server registry
iMedicationService = (IMedicationService) (registry.lookup(IMedicationService.class.getSimpleName()));
ArrayList<DrugPlanDTO> dto= iMedicationService.getAllMedicationPlans(patientID);
for (DrugPlanDTO drugplans:
dto) {
System.out.println((String)drugplans.getBegin_time());
}
this.displayTable=new DisplayTable(dto,patientID);
System.out.println("Finished");
}
public static void sendMessage(String drugPlanID,String patientID,String medicationName,String begin_time,String end_time) throws RemoteException, SQLException {
if (iMedicationService != null) {
iMedicationService.savePillTakenLog(drugPlanID,patientID,medicationName,begin_time,end_time);
System.out.println("Finished send message"+ patientID);
}
}
}
Im not sure how to bind the client to the server when dockerizing the application.
Docker compose:
version: '3'
services:
tomcat-db-api:
image: ds_a3
ports:
- "8889:8889"
rabbitmq-container:
image: rabbitmq:management
ports:
- 5672:5672
- 15672:15672
Try setting the: this.serverAddress="tomcat-db-api;" at your client.

NullPointer exception while init of WebSocketClient

I am getting nullpointer exception on Connecting to a secured websocket.
PFB the exception:
Exception in thread "main" java.lang.NullPointerException
at org.eclipse.jetty.websocket.common.extensions.AbstractExtension.getName(AbstractExtension.java:90)
at org.eclipse.jetty.websocket.api.extensions.ExtensionFactory.<init>(ExtensionFactory.java:37)
at org.eclipse.jetty.websocket.common.extensions.WebSocketExtensionFactory.<init>(WebSocketExtensionFactory.java:40)
at org.eclipse.jetty.websocket.client.WebSocketClient.<init>(WebSocketClient.java:90)
at com.service.SecureClientSocket.main(SecureClientSocket.java:26)
PFB my code:
package com.service;
import java.net.URI;
import java.util.concurrent.Future;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketError;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;
import org.eclipse.jetty.websocket.client.WebSocketClient;
#WebSocket
public class SecureClientSocket {
public static void main(String []args){
String url = "wss://qa.sockets.stackexchange.com/";
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setTrustAll(true); // The magic
WebSocketClient client = new WebSocketClient(sslContextFactory);
try
{
client.start();
SecureClientSocket socket = new SecureClientSocket();
Future<Session> fut = client.connect(socket,URI.create(url));
Session session = fut.get();
session.getRemote().sendString("Hello");
session.getRemote().sendString("155-questions-active");
}
catch (Throwable t)
{
System.out.println(t.getMessage());
}
}
#OnWebSocketConnect
public void onConnect(Session sess)
{
System.out.println("onConnect({})"+sess);
}
#OnWebSocketClose
public void onClose(int statusCode, String reason)
{
System.out.println("onClose({}, {})"+ statusCode+ reason);
}
#OnWebSocketError
public void onError(Throwable cause)
{
System.out.println(cause);
}
#OnWebSocketMessage
public void onMessage(String msg)
{
System.out.println("onMessage() - {}"+ msg);
}
}

Java WatchService unexpectedly stops working

I have a recursive watch service that I'm using to monitor directories while the application is running. For an unknown reason, the watchservice appears stop working after about a day. At that point I can add a new file to a monitored directory and get no log statements and my observers are not notified.
I thought Spring might be destroying the bean, so I added a log statement to the #pre-destroy section of the class, but that log statement doesn't show up after the watchservice stops working, so it seems that bean still exists, it's just not functioning as expected. The class is as follows
import com.sun.nio.file.SensitivityWatchEventModifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Consumer;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
#Service
public class DirectoryMonitor {
private static final Logger logger = LoggerFactory.getLogger(DirectoryMonitor.class);
private WatchService watcher;
private ExecutorService executor;
private List<DirectoryMonitorObserver> observerList = new ArrayList<>();
private final Map<WatchKey, Path> keys = new HashMap<>();
public void addObserver(DirectoryMonitorObserver observer){
observerList.add(observer);
}
private void notifyObservers(){
observerList.forEach(DirectoryMonitorObserver::directoryModified);
}
#PostConstruct
public void init() throws IOException {
watcher = FileSystems.getDefault().newWatchService();
executor = Executors.newSingleThreadExecutor();
}
#PreDestroy
public void cleanup() {
try {
logger.info("Stopping directory monitor");
watcher.close();
} catch (IOException e) {
logger.error("Error closing watcher service", e);
}
executor.shutdown();
}
#SuppressWarnings("unchecked")
public void startRecursiveWatcher(String pathToMonitor) {
logger.info("Starting Recursive Watcher");
Consumer<Path> register = p -> {
if (!p.toFile().exists() || !p.toFile().isDirectory())
throw new RuntimeException("folder " + p + " does not exist or is not a directory");
try {
Files.walkFileTree(p, new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
logger.info("registering " + dir + " in watcher service");
WatchKey watchKey = dir.register(watcher, new WatchEvent.Kind[]{ENTRY_CREATE, ENTRY_DELETE}, SensitivityWatchEventModifier.HIGH);
keys.put(watchKey, dir);
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
throw new RuntimeException("Error registering path " + p);
}
};
register.accept(Paths.get(pathToMonitor));
executor.submit(() -> {
while (true) {
final WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException ex) {
logger.error(ex.toString());
continue;
}
final Path dir = keys.get(key);
key.pollEvents().stream()
.map(e -> ((WatchEvent<Path>) e).context())
.forEach(p -> {
final Path absPath = dir.resolve(p);
if (absPath.toFile().isDirectory()) {
register.accept(absPath);
} else {
final File f = absPath.toFile();
logger.info("Detected new file " + f.getAbsolutePath());
}
});
notifyObservers();
key.reset();
}
});
}
}
This is where I'm creating the monitor bean..
#Component
public class MovieInfoFacade {
#Value("${media.path}")
private String mediaPath;
private MovieInfoControl movieInfoControl;
private DirectoryMonitor directoryMonitor;
private FileListProvider fileListProvider;
#Autowired
public MovieInfoFacade(MovieInfoControl movieInfoControl, DirectoryMonitor directoryMonitor, FileListProvider fileListProvider){
this.movieInfoControl = movieInfoControl;
this.directoryMonitor = directoryMonitor;
this.fileListProvider = fileListProvider;
}
#PostConstruct
public void startDirectoryMonitor(){
if(!mediaPath.equalsIgnoreCase("none")) {
directoryMonitor.addObserver(fileListProvider);
directoryMonitor.startRecursiveWatcher(mediaPath);
}
}
public int loadMovieListLength(String directoryPath){
return fileListProvider.listFiles(directoryPath).length;
}
public List<MovieInfo> loadMovieList(MovieSearchCriteria searchCriteria) {
List<File> files = Arrays.asList(fileListProvider.listFiles(searchCriteria.getPath()));
return files.parallelStream()
.sorted()
.skip(searchCriteria.getPage() * searchCriteria.getItemsPerPage())
.limit(searchCriteria.getItemsPerPage())
.map(file -> movieInfoControl.loadMovieInfoFromCache(file.getAbsolutePath()))
.collect(Collectors.toList());
}
public MovieInfo loadSingleMovie(String filePath) {
return movieInfoControl.loadMovieInfoFromCache(filePath);
}
}
It appears that the error was in my exception handling. After removing the throw statements (and replacing them with logs) I have not had any issues.

ISSUES with Monitor folder, consume WebService and send files via FTP Outbound channel

I'm having bad time dealing with a simple application that must monitor a folder for new files, take each file and consume RESTful service ( one of my other apps) and send the response files using spring integration FTP Outbound channel adapter
It has following structure:
Initializer:
package com.ftpoutbound;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import com.ftpoutbound.client.FtpoutboundApp;
public class ServletInitializer extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(FtpoutboundApp.class);
}
}
I define beans in FtpoutboundApp:
package com.ftpoutbound.client;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.context.ApplicationContext;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.expression.common.LiteralExpression;
import org.springframework.integration.annotation.Gateway;
import org.springframework.integration.annotation.IntegrationComponentScan;
import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.file.FileNameGenerator;
import org.springframework.integration.file.remote.session.CachingSessionFactory;
import org.springframework.integration.file.remote.session.SessionFactory;
import org.springframework.integration.ftp.outbound.FtpMessageHandler;
import org.springframework.integration.ftp.session.DefaultFtpSessionFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.client.RestTemplate;
import com.ftpoutbound.monitor.MonitorDirectory;
#Configuration
#SpringBootApplication
#ComponentScan({ "com.ftpoutbound" })
#IntegrationComponentScan
#EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class })
#EnableScheduling
public class FtpoutboundApp implements ApplicationContextAware {
final static Logger logger = Logger.getLogger(FtpoutboundApp.class);
#Autowired
private MonitorDirectory monitor;
#Autowired
MyGateway gateway;
#Value("${remotedirectory}")
private String remotedirectory;
#Value("${remotehost}")
private String remotehost;
#Value("${remoteport}")
private int remoteport;
#Value("${remoteuser}")
private String remoteuser;
#Value("${remotepassword}")
private String remotepassword;
#Value("${outbound214sname}")
private String outbound214sname;
public static void main(String[] args) {
SpringApplication.run(FtpoutboundApp.class, args);
}
public void createGateway(File file214) {
try {
gateway.sendToFtp(file214);
file214.delete();
} catch (Exception e) {
logger.error("ERROR APP OUTBOUND\n");
logger.error(e);
}
}
#Bean
public SessionFactory<FTPFile> ftpSessionFactory() {
DefaultFtpSessionFactory sf = new DefaultFtpSessionFactory();
sf.setHost(remotehost);
sf.setPort(remoteport);
sf.setUsername(remoteuser);
sf.setPassword(remotepassword);
return new CachingSessionFactory<FTPFile>(sf);
}
#Bean
#ServiceActivator(inputChannel = "ftpChannel")
public MessageHandler handler() {
FtpMessageHandler handler = new FtpMessageHandler(ftpSessionFactory());
handler.setRemoteDirectoryExpression(new LiteralExpression(remotedirectory));
handler.setFileNameGenerator(new FileNameGenerator() {
#Override
public String generateFileName(Message<?> message) {
String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
String time = new SimpleDateFormat("HHmmssssssss").format(new Date());
return outbound214sname + "." + date + time;
}
});
return handler;
}
#MessagingGateway
public interface MyGateway {
#Gateway(requestChannel = "ftpChannel")
void sendToFtp(File file);
}
#EventListener
public void afterApplicationReady(ApplicationReadyEvent event) {
try {
logger.info("INICIO DE MONITOREO DE ARCHIVOS HG");
monitor.startMonitoring();
} catch (IOException e) {
logger.error("ERROR EN MONITOREO DE FOLDER ENTRADA ARCHIVOS HG:\n" + e);
} catch (InterruptedException e) {
logger.error("INTERRUPCIƓN EN MONITOREO DE FOLDER ENTRADA ARCHIVOS HG:\n" + e);
}
}
#Bean
RestTemplate restTemplate() {
return new RestTemplate();
}
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
}
}
The monitor started from the FtpoutboundApp:
I'm using SCHEDULED annotation since Watchservice was not working either
package com.ftpoutbound.monitor;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.ClosedWatchServiceException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.ftpoutbound.client.FtpoutboundApp;
import com.ftpoutbound.restfulclient.httpPost;
#Component
public class MonitorDirectory {
final static Logger logger = Logger.getLogger(MonitorDirectory.class);
#Autowired
private httpPost httppost;
#Value("${inboundhgfilesfolder}")
private String inboundhgfilesfolder;
#Value("${inboundhgfilesfolderbak}")
private String inboundhgfilesfolderbak;
#Value("${hglin}")
private String hglin;
#Scheduled(fixedRate = 10000)
public void startMonitoring() throws IOException, InterruptedException {
try {
listFiles();
} catch (Exception e) {
logger.error("ERROR MONITOREANDO FOLDER");
logger.error(e);
}
}
public void listFiles() throws Exception {
File directory = new File(inboundhgfilesfolder);
File[] fList = directory.listFiles();
for (File file : fList) {
String fileName = file.getName();
if (file.isFile()) {
readFile(fileName);
Thread.sleep(1000);
}
}
}
public void readFile(String fileName) throws IOException {
String hgFile = fileName.substring(0, 7);
if (hgFile.equals(hglin)) {
InputStream input = new FileInputStream(inboundhgfilesfolder + fileName);
StringBuilder builder = new StringBuilder();
int ch;
while ((ch = input.read()) != -1) {
builder.append((char) ch);
}
try {
httppost.get214fromRestful(builder.toString());
} catch (Exception e) {
logger.error("ERROR EN POST REQUEST DESDE APP OUTBOUND:\n" + e);
}
}
moveFile(fileName);
}
public void moveFile(String fileName) {
Path source = Paths.get(inboundhgfilesfolder + fileName);
Path newdir = Paths.get(inboundhgfilesfolderbak + fileName);
try {
Files.move(source, newdir);
} catch (IOException e) {
logger.error("ERROR MOVIENDO ARCHIVO:\n" + e);
}
}
}
And the HTTPclient that consumes the RESTful app
package com.ftpoutbound.restfulclient;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import com.ftpoutbound.client.FtpoutboundApp;
#Component
public class httpPost {
final static Logger logger = Logger.getLogger(httpPost.class);
#Value("${restful214url}")
private String restful214url;
#Value("${outbound214sfolder}")
private String outbound214sfolder;
#Autowired
private FtpoutboundApp ftpoutbound;
public void get214fromRestful(String hgfile) throws Exception {
logger.info("OBTENIENDO 214");
logger.info("DIRECCION" + restful214url);
logger.info("ARCHIVO" + hgfile);
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.postForObject(restful214url, hgfile, String.class);
File file = createFile214local(result.toString());
logger.info("RESULTADO DE POST:");
logger.info(result.toString());
ftpoutbound.createGateway(file);
}
private File createFile214local(String hgfile) {
logger.info("ESCRIBIENDO 214");
File file = new File(outbound214sfolder + "214.tmp");
try {
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(hgfile);
bw.close();
} catch (IOException e) {
logger.error("ERROR ESCRIBIENDO FILE:\n->" + e);
}
return file;
}
}
but the app seems not working, it freezes before consuming the RESTful in:
logger.info("OBTENIENDO 214");
logger.info("DIRECCION" + restful214url);
logger.info("ARCHIVO" + hgfile);
I noticed these lines are printed twice in the log, still not sure if this is a threads issue or what causes the APP to not even finish the deployment in the server, I have another similar App (except that one doesn't consume RESTful) and it works OK, another FTPInbound channel Adapter and it works OK, but I have some days figuring what I'm missing or What's the best way to do this.
Believe me, Help will be extremely appreciated.
The issue was that
my outbound channel configuration class was implementing ApplicationContextAware and it was causing the RestTemplate to freezes the App when consuming my Microservices App, so I changed to extend SpringBootServletInitializer and implement WebApplicationInitializerand it worked.

Why my websocket example isn't working?

I have two files server.java and client.java. Basically there is no error or message like Client Connected, Connected to server, Message:..., etc.
But if i change localhost to something else client.java does give an error but if it's correct no error or response.
server.java has this:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.ArrayList;
import javax.json.Json;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.glassfish.tyrus.server.*;
#ServerEndpoint("/game")
public class socketServer{
public static void main(String[] args) {
new socketServer();
}
public socketServer() {
runServer();
}
public static void runServer() {
Server s = new Server("localhost", 8025, "/websockets", null, socketServer.class);
try {
s.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
#OnMessage
public String onMessage(String message, Session s) throws IOException {
System.out.println("User input: " + message);
s.getBasicRemote().sendText("Hello world Mr. " + message);
return message;
}
#OnOpen
public void onOpen(Session s) throws IOException {
System.out.println("Client connected");
s.getBasicRemote().sendText("wtf");
}
#OnClose
public void onClose() {System.out.println("Connection closed");}
#OnError
public void handleError(Throwable t) {t.printStackTrace();}
}
client.java has this:
import java.net.URI;
import java.net.URISyntaxException;
import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.ClientEndpoint;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.DeploymentException;
import org.glassfish.tyrus.client.ClientManager;
#ClientEndpoint
public class clientServer {
public static void main(String[] args) {
new clientServer();
}
public clientServer() {
ClientManager client = ClientManager.createClient();
try {
client.connectToServer(clientServer.class, new URI("ws://localhost:8025/websockets/game"));
} catch (Exception e) {
e.printStackTrace();
}
}
#OnOpen
public void onOpen(Session session) {
System.out.println("connected to server");
try {
session.getBasicRemote().sendText("start");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
#OnMessage
public String onMessage(String message, Session session) {
return message;
}
#OnClose
public void onClose(Session session, CloseReason closeReason) {
System.out.println("Client: closed");
}
}
I guess server.java and client.java have to use the same host name. If you change the URI in client.java, for example, from "ws://localhost:8025/websockets/game" to "ws://myhost:8025/websockets/game", try to change the first argument of the constructor of Server from "localhost" to "myhost".

Categories

Resources