How do I stop a webservice endpoint? - java

I understand that I need to call the stop() method using the endpoint.
But I am not sure how to call it.
Here's my code
public class Publish {
public static void main(String[] args) {
String address = "http://localhost:8483/cal";
Object implementor = new CalWebserviceImpl();
Endpoint endpoint = Endpoint.publish(address, implementor);
System.out.println(endpoint.isPublished());
endpoint.stop();
} // main
}
And this is the error I get:
Exception in thread "main" com.sun.xml.internal.ws.server.ServerRtException: Server Runtime Error: java.net.BindException: Address already in use: bind
at com.sun.xml.internal.ws.transport.http.server.ServerMgr.createContext(ServerMgr.java:117)
I assume that I am getting the error message because I am trying to (re-)publish the endpoint before stopping it.
I tried to create a new endpoint reference and use it to stop it.
Endpoint ep = Endpoint.create(implementor);
ep.stop();
But I am getting the same error message.
I am just unclear how to call the stop() the service. Please advise. Thank you!
Edit:
Here's another unsuccessful attempt:
package com.website.test;
import javax.xml.ws.Endpoint;
public class Unpublish {
Endpoint ep = null;
public static void main(String[] args) {
Unpublish up = new Unpublish();
up.run();
} // main
public void run(){
String address = "http://localhost:8483/cal";
Object implementor = new CalWebserviceImpl();
// my service is already running, I believe it's publish here that's causing the issue
ep = Endpoint.publish(address, implementor);
startWebService();
}
private void startWebService() {
if(ep.isPublished()){
System.out.println("Endpoint webservice is running!");
}
else{
ep.stop();
System.out.println("Endpoint webservice stopped!");
}
}
}

Related

NetworkManager is APSupported

I want to consume a service. I am 100% sure that this service works correctly.
Service call
public void add(User user) {
ConnectionRequest con = new ConnectionRequest();
String url="http://localhost/NY/untitled/web/app_dev.php/user/new"
+ "?Fonctionuser="+user.getUserFunction()
+"&Fullname="+user.getUserName()
+"&Imageproduit="+user.getUserImage()
+"&Latitude="+user.getLatitude()
+"&Longitude="+user.getLongitude()
+"&State="+user.getUserState();
System.out.println(user.getUserState());
con.setUrl(url);
NetworkManager.getInstance().addToQueue(con);
}
Error
Exception in thread "main" java.lang.NullPointerException
at com.codename1.io.NetworkManager.isAPSupported(NetworkManager.java:866)
at com.codename1.io.ConnectionRequest.<init>(ConnectionRequest.java:330)
at Services.UserServices.add(UserServices.java:18)
at Services.Main.main(Main.java:30)
Main method
public static void main(String[] args) {
User user = new User();
user.setLatitude(111);
user.setLongitude(111);
user.setUserFunction( UserFunction.Client.ordinal());
user.setUserImage("uezfniez");
user.setUserState((int)UserState.Hold.ordinal());
user.setUserName("jamel");
UserServices userServices = new UserServices();
userServices.add(user);
}
It seems you nedd to write your code in an Action Listener
registerButton.addActionListener(e -> {
con.setUrl("http://localhost/NY/untitled/web/app_dev.php/user/"
+ "new?Fonctionuser=2&Fullname=jamel&Imageproduit=uezfniez&Latitude=111&Longitude=111&State=2");
NetworkManager.getInstance().addToQueue(con);
});
I'm guessing that you invoked that code from the constructor or a static initializer which means the implementation of Codename One didn't finish initializing. No code that relies on implementation should be executed before the init(Object) method is invoked.
Action listeners happen well after that point and would thus work well in this case.

Grpc.Core.RpcException method is unimplemented with C# client and Java Server

I am having trouble finding the source of this error. I implemented a simple service using protobuf:
syntax = "proto3";
package tourism;
service RemoteService {
rpc Login(LoginUserDTO) returns (Response) {}
}
message AgencyDTO{
int32 id=1;
string name=2;
string email=3;
string password=4;
}
message LoginUserDTO{
string password=1;
string email=2;
}
message SearchAttractionsDTO{
string name=1;
int32 start_hour=2;
int32 start_minute=3;
int32 stop_hour=4;
int32 stop_minute=5;
AgencyDTO loggedUser=6;
}
message AttractionDTO{
int32 id=1;
string name=2;
string agency=3;
int32 hour=4;
int32 minute=5;
int32 seats=6;
int32 price=7;
}
message ReservationDTO{
int32 id=1;
string first_name=2;
string last_name=3;
string phone=4;
int32 seats=5;
AttractionDTO attraction=6;
AgencyDTO agency=7;
}
message Response{
enum ResponseType{
OK=0;
NOT_LOGGED_ID=1;
SERVER_ERROR=2;
VALIDATOR_ERROR=3;
}
ResponseType type=1;
AgencyDTO user=2;
string message=3;
}
When using a java client everything works fine, the server receives the request and responds appropriately. When using C# with the same .proto file for generating sources at the client.Login() I get the following errror: Grpc.Core.RpcException Status(StatusCode=Unimplemented, Detail="Method tourism.RemoteService/Login is unimplemented"). The server receives the request but does not have time to respond and throws:
INFO: Request from ex#ex.com
May 22, 2017 12:28:58 AM io.grpc.internal.SerializingExecutor run
SEVERE: Exception while executing runnable io.grpc.internal.ServerImpl$JumpToApplicationThreadServerStreamListener$2#4be43082
java.lang.IllegalStateException: call is closed
at com.google.common.base.Preconditions.checkState(Preconditions.java:174)
at io.grpc.internal.ServerCallImpl.sendHeaders(ServerCallImpl.java:103)
at io.grpc.stub.ServerCalls$ServerCallStreamObserverImpl.onNext(ServerCalls.java:282)
at ServiceImp.login(ServiceImp.java:20)
at tourism.RemoteServiceGrpc$MethodHandlers.invoke(RemoteServiceGrpc.java:187)
at io.grpc.stub.ServerCalls$1$1.onHalfClose(ServerCalls.java:148)
at io.grpc.internal.ServerCallImpl$ServerStreamListenerImpl.halfClosed(ServerCallImpl.java:262)
at io.grpc.internal.ServerImpl$JumpToApplicationThreadServerStreamListener$2.runInContext(ServerImpl.java:572)
at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:52)
at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:117)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Java server:
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import tourism.RemoteServiceGrpc;
import tourism.Service;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Created by Andu on 21/05/2017.
*/
public class ServerGrpc {
Logger logger= Logger.getLogger(ServerGrpc.class.getName());
private final Server server;
private final int port;
public ServerGrpc(int p){
port=p;
server= ServerBuilder.forPort(port).addService(new ServiceImp()).build();
}
public void start() throws IOException {
server.start();
logger.info("Server started, listening on " + port);
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
// Use stderr here since the logger may has been reset by its JVM shutdown hook.
System.err.println("*** shutting down gRPC server since JVM is shutting down");
ServerGrpc.this.stop();
System.err.println("*** server shut down");
}
});
}
public void stop() {
if (server != null) {
server.shutdown();
}
}
void blockUntilShutdown() throws InterruptedException {
if (server != null) {
server.awaitTermination();
}
}
private class ServiceImp extends RemoteServiceGrpc.RemoteServiceImplBase {
Logger log=Logger.getLogger(ServiceImp.class.getName());
#Override
public void login(Service.LoginUserDTO request, StreamObserver<Service.Response> responseStreamObserver){
super.login(request,responseStreamObserver);
log.log(Level.INFO,"Request from "+request.getEmail());
Service.Response response= Service.Response.newBuilder().setMessage("Hello "+request.getEmail()+", I know your password: "+request.getPassword()).build();
responseStreamObserver.onNext(response);
responseStreamObserver.onCompleted();
}
}
}
C# Client:
namespace testGrpc2
{
class MainClass
{
public static void Main(string[] args)
{
var channel = new Channel("127.0.0.1:61666",ChannelCredentials.Insecure);
var client = new RemoteService.RemoteServiceClient(channel);
Response response=client.Login(new LoginUserDTO{Email="ex#ex.com",Password="notmypassword"});
Console.WriteLine(response);
Console.ReadKey();
}
}
}
I managed to find the source of the problem. For anyone else having this problem:
Make sure your .proto file is identical for both client and server and it has the same package. When the client calls a method on the remote server, it uses the full name of the remote class and the package.
However this was not the reason why the method appeared as unimplemented to the client. It was this:
super.login(request,responseStreamObserver);
Calling the super method login sends an async UNIMPLEMENTED error code back to the client. This is the login() method in the generated class:
public void login(LoginUserDTO request,StreamObserver<Response> responseObserver) {
asyncUnimplementedUnaryCall(METHOD_LOGIN, responseObserver);
}
So make sure in the implementation of your service methods you don't call the super method as it will appear to the client as UNIMPLEMENTED. If you generate #Override methods using IntelliJ IDEA it will add the super method call. Make sure to delete it.
For me it was that I forget adding endpoint of gRpc service in startup class.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGrpcService<GreeterService>();
//Add your endpoint here like this
endpoints.MapGrpcService<YourProtoService>();
});
For me, using the C# client, the problem was that I wasn't overriding the generated service method.
Thanks to Alexandru - this helped solve my problem with Akka gRPC client and Python grPC server. In my case, I had same packages and preamble in .proto file but had eliminated message classes and gRPC functions not needed for this specific use case in the Python gRPC server. When I made the .proto files identical, everything worked and I no longer received UNIMPLEMENTED errors. This is needed for languages beyond the C#/Java example cited. Thanks again.
My server and client were both java, and the problem was removed after closing and opening the project in IntelliJ!!

Standalone Apache Camel application doesn' run

I'm on this problem: can't get my apache camel batch run. Here is the code:
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;
public class Launch {
private Main main;
public static void main(String[] args) {
Launch l = new Launch();
System.out.println(System.getProperty("from") +" -> "+System.getProperty("to"));
try {
l.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
public void execute() throws Exception {
main = new Main();
main.enableHangupSupport();
main.addRouteBuilder(new FromFileToFile());
main.run();
}
private static class FromFileToFile extends RouteBuilder {
#Override
public void configure() throws Exception {
onException(Exception.class).handled(true).process(new Processor() {
public void process(Exchange arg0) throws Exception {
arg0.getException().printStackTrace();
}
});
from(System.getProperty("from") + "")
.filter(body().contains("DOTHIS"))
.process(new Processor() {
public void process(Exchange arg0) throws Exception {
System.out.println(arg0.getIn().getBody()
.toString());
}
}).to(System.getProperty("to"))
.to(System.getProperty("to") + ".BAK");
}
}
}
I don't want to use the Thread.sleep(...) workaround. I simply copied and modified the source stuff posted on this official docs page. When I run my dummy program using Eclipse, application simply hangs. I can't figure out what's wrong.
Your application doesn't probably hang, it just won't do anything. :)
You have defined filter that checks if Camel Message body contains word "DOTHIS". When you consume file with File consumer the body will be of type GenericFile. Then when your filter checks for that string it surely won't find it since the body is not string.
Solution: Convert file body to string first and then your filter will work and you get the result you were expecting. Conversion can be done like this
from(System.getProperty("from") + "")
.convertBodyTo(String.class, "UTF-8")
.filter(body().contains("DOTHIS"))
You might also want to increase logging level so you can get the grasp of what's going on in your route.
It was a problem about path. I passed arguments as options like this:
file://Users/francesco/..
As I'm using windows I must specify uri like this
file:///C:/Users/francesco/..
The batch doesn't hangs, it continues to poll directory for new files to consumes.

Apache camel send a simple message

I have a simply camel MINA server using the JAVA DSL, and I am running like the example documented here:
Running Camel standalone and have it keep running in JAVA
MINA 2 Component
I am trying to create a sample application hosted at "mina:tcp://localhost:9991" (aka MyApp_B) that sends a very simple message to a server hosted at "mina:tcp://localhost:9990" (aka MyApp_A).
I want is to send a simple message containing a String in the header (which is "Hellow World!") and with the address in the body.
public class MyApp_B extends Main{
public static final String MINA_HOST = "mina:tcp://localhost:9991";
public static void main(String... args) throws Exception {
MyApp_B main = new MyApp_B();
main.enableHangupSupport();
main.addRouteBuilder(
new RouteBuilder(){
#Override
public void configure() throws Exception {
from("direct:start")
.setHeader("order", constant("Hello World!"))
.setBody(constant(MINA_HOST))
.to("mina:tcp://localhost:9990");
}
}
);
System.out.println("Starting Camel MyApp_B. Use ctrl + c to terminate the JVM.\n");
main.run();
}
}
public class MainApp_A {
public static void main(String... args) throws Exception {
Main main = new Main();
main.enableHangupSupport();
main.addRouteBuilder(new RouteBuilder(){
#Override
public void configure() throws Exception {
from("mina:tcp://localhost:9990").bean(MyRecipientListBean.class,
"updateServers").to("direct:debug");
from("direct:debug").process(new Processor() {
public void process(Exchange exchange) throws Exception {
System.out.println("Received order: " +
exchange.getIn().getBody());
}
});
}
});
main.run(args);
}
}
Bean used by MyApp_A:
public class MyRecipientListBean {
public final static String REMOVE_SERVER = "remove";
public final static String ADD_SERVER = "add";
private Set<String> servers = new HashSet<String>();
public void updateServers(#Body String serverURI,
#Header("order") String order){
System.out.println("===============================================\n");
System.out.println("Received " + order + "request from server " + serverURI + "\n");
System.out.println("===============================================\n");
if(order.equals(ADD_SERVER))
servers.add(serverURI);
else if(order.equals(REMOVE_SERVER))
servers.remove(serverURI);
}
}
I have done this code, however, the servers on the other side don't seem to receive anything. Therefore I have 2 questions:
Am I doing something wrong?
Is there a better way to send simple message using Camel?
MyApp_A does NOT send any messages. You need to send a message to the direct endpoint to start the route.
You can also change direct to a timer component to have it trigger every X second etc.
Added latest comment as requested:
yes and the direct route is also running. Its just that to send a
message to direct, you need to do that using Camel. direct is an
internal Camel component for sending messages between its endpoint
(routes). To send a message to it, you can use the producer template.
See chapter 7, section 7.7 in the Camel in Action book.

Problem with Apache's Java XMLRPC library

So i'm trying to get my Apache xmlrpc client/server implementation to play ball. Everything works fine except for one crucial issue:
my handler class (mapped through the properties file org.apache.xmlrpc.webserver.XmlRpcServlet.properties) reacts as it should but it's constructor is called at every method invocation. It would seem that the handler class is instantiated at each call which is bad because I have data stored in instance variables that I need to save between calls.
How do I save a reference to the instantiated handler so that I can access it's instance variables?
So, for anyone else who still wants to use XMLRPC here's how I fixed this issue:
http://xmlrpc.sourceforge.net/
far superior to apache xmlrpc, in my opinion.
This is standard behaviour of Apache XMLRPC 3.x. http://ws.apache.org/xmlrpc/handlerCreation.html:
By default, Apache XML-RPC creates a new object for processing each
request received at the server side.
However, you can emulate the behaviour of XMLRPC 2.x, where you registered handler objects instead of handler classes, using a RequestProcessorFactoryFactory. I have written a custom RequestProcessorFactoryFactory that you can use:
public class CustomHandler implements RequestProcessorFactoryFactory {
Map<Class<?>, RequestProcessorFactory> handlers =
Collections.synchronizedMap(
new HashMap<Class<?>, RequestProcessorFactory>());
#Override
public RequestProcessorFactory getRequestProcessorFactory(Class pClass)
throws XmlRpcException {
return handlers.get(pClass);
}
public void addHandler(final Object handler) {
handlers.put(handler.getClass(), new RequestProcessorFactory() {
#Override
public Object getRequestProcessor(XmlRpcRequest pRequest)
throws XmlRpcException {
return handler;
}
});
}
}
This can then be used with e.g. a XMLRPC WebServer like this
WebServer server = ...
PropertyHandlerMapping phm = new PropertyHandlerMapping();
server.getXmlRpcServer().setHandlerMapping(phm);
Custom sh = new CustomHandler();
phm.setRequestProcessorFactoryFactory(sh);
Object handler = ... /** The object you want to expose via XMLRPC */
sh.addHandler(handler);
phm.addHandler(serverName, handler.getClass());
Maybe something to do with javax.xml.rpc.session.maintain set to true?
I know this is a really old post but I managed to solve the problem with Apache's Java XML-RPC.
First, I thought this could be solved with singleton class in Java but it doesn't work and throws "illegal access exception".
These are what I have done:
public class XmlRpcServer {
private static JFrame frame = new JFrame();
private static JPanel pane = new JPanel();
public static XmlRpcServer singleton_inst = new XmlRpcServer();
public XmlRpcServer() {
// I kept the constructor empty.
}
public static void main(String[] args) throws XmlRpcException, IOException {
// In my case, I put the constructor code here.
// Then stuff for XML-RPC server
// Server Part
WebServer ws = new WebServer(8741);
PropertyHandlerMapping mapping = new PropertyHandlerMapping();
mapping.addHandler("SERVER", singleton_inst.getClass());
ws.getXmlRpcServer().setHandlerMapping(mapping);
ws.start();
////
}
// I called doTheJob() from python via XML-RPC
public String doTheJob(String s) throws XmlRpcException {
loop();
return s;
}
// It executed loop() forever
private static void loop() throws XmlRpcException {
// Actual work is here
}
But metaspace increases gradually:
I worked too much on this metaspace issue when looping forever in Java but I couldn't figure out a solution.

Categories