I am trying to send an EXCEPTION from a Web Server to a Client using JAX-WS ...
When the exception is thrown by the server the client does catch it ... but the contents are not the expected message...
Server.java
package pck;
#WebService()
public class Server
{
#WebMethod()
public function() throws UserException
{
throw new UserException(“Something”);
}
}
Exception.java
import javax.xml.ws.WebFault;
#WebFault()
public class UserException
extends Exception
{
private String ErrMessage;
public UserException(String message)
{
this.ErrMessage = message;
}
public String ErrorMessage()
{
return this.ErrMessage;
}
}
Client.java
public class Client
{
public static void main(String[] args) throws Exception
{
try
{
Server.function();
}
catch (UserException ex)
{
System.out.println("User Exception: " + ex.ErrorMessage());
}
}
}
Now, as I mentioned, when the exception is thrown by the server the client does catch it, but ex.ErrorMessage() returns the string “pck.UserException” instead of “Something” which it was created with in the Server... any clues as to why?
Also, when I run my WebService I keep getting the following messages in the output:
com.sun.xml.internal.ws.model.RuntimeModeler getExceptionBeanClass
INFO: Dynamically creating exception bean Class pck.jaxws.UserExceptionBean
Any clues or help would be much appreciated.
Thanks,
Not sure, but your custom exception looks odd. You should in fact super the message:
public UserException(String message) {
super(message);
}
This way you can get it by e.getMessage(). See if it helps.
Related
I cant fix problem with my spring boot application, where I tried to create my own Telegram bot.
After Spring container created and app start, I see at logs same error :
Error logs
2019-06-17 23:26:33.117 ERROR 3340 --- [gram Connection] Telegram Bots Api : BOTSESSION
Bot Impl :
public TelegramBot(BotProperties botProperties) {
this.botProperties = botProperties;
}
#PostConstruct
public void init() {
TelegramBotsApi telegramBotsApi = new TelegramBotsApi();
try {
telegramBotsApi.registerBot(new TelegramBot(botProperties));
logger.info("bot successfully register");
} catch (TelegramApiException e) {
logger.error(e.getMessage(), e);
}
}
#Override
public void onUpdateReceived(Update update) {
if (update.hasMessage()) {
System.out.println(update.getMessage().getText());
}
}
#Override
public String getBotUsername() {
return botProperties.getBotName();
}
#Override
public String getBotToken() {
return botProperties.getBotToken();
}
}
Main class :
public class TelegramApplication {
public static void main(String[] args) {
ApiContextInitializer.init();
SpringApplication.run(TelegramApplication.class, args);
}
}
Verify that at a time only one server if accessing the bot . The telegram bot address can only be accessed by one server at a time.If you are having one in local and one server running in another ,it will throw this same when you try connecting it in local.
If you are using the devtools to rebuild the code without restarting, try to stop the application and restart it.It should work.
I am trying to write a simple Client Server application using netty.
I followed this tutorial, and specifically the time server model along with the POJO model. My problem is with the ByteToMessageDecoder : it runs more times than it has to, meaning instead of stopping when it reads a null ByteBuf it reads one more time and for some reason, that I cannot understand, it finds the previous message that my client has sent! I am certain that the client only sends said message only once!
So the idea is this : a simple Client Server model where the Client sends a "DataPacket" with a "hello world" message in it and the server responds with a "DataPacket" with an "ACK". I am using the DataPacket type because in the future I want to pass more things in it, add a header and built something a bit more complicated...But for starters I need to see what am I doing wrong in this one...
The ERROR :
As you can see the Server starts normally, my Client (Transceiver) sends the message, the encoder activates and converts it from DataPacket to ByteBuf, the message is sent and received from the server, the Decoder from the Server activates and converts it from ByteBuf to DataPacket and then the Server handles it accordingly... It should sent the ACK and repeat the same backwards but this is were things go wrong and I cannot understand why.
I have read some posts here and already tried a LengthFieldBasedFrameDecoder, it did not work and I also want to see what is wrong with this one if possible and not use something else...
Code:
Encoder and Decoder class :
package org.client_server;
import java.util.List;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.CharsetUtil;
public class EncoderDecoder {
public static class NettyEncoder extends MessageToByteEncoder<DataPacket> {
#Override
protected void encode(ChannelHandlerContext ctx, DataPacket msg, ByteBuf out)
throws Exception {
System.out.println("Encode: "+msg.getData());
out.writeBytes(msg.convertData());
}
}
public static class NettyDecoder extends ByteToMessageDecoder{
#Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in,
List<Object> out) throws Exception {
if((in.readableBytes() < 4) ) {
return;
}
String msg = in.toString(CharsetUtil.UTF_8);
System.out.println("Decode:"+msg);
out.add(new DataPacket(msg));
}
}
}
Server handler :
class DataAvroHandler extends ChannelInboundHandlerAdapter {
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
try {
DataPacket in = (DataPacket)msg;
System.out.println("[Server]: Message received..."+in.getData());
}finally {
ReferenceCountUtil.release(msg);
//ctx.close();
}
}
#Override
public void channelReadComplete(ChannelHandlerContext ctx)
throws Exception {
System.out.println("[Server]: Read Complete...");
DataPacket pkt = new DataPacket("ACK!");
//pkt.setData(Unpooled.copiedBuffer("ACK", CharsetUtil.UTF_8));
ctx.writeAndFlush(pkt);
}
#Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
serverLog.warning("[Server]: Error..." + cause.toString());
ctx.close();
}
The Client handler :
class DataAvroHandlerCl extends ChannelInboundHandlerAdapter {
#Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("[Transceiver]: Channel Active!!!");
DataPacket pkt = new DataPacket("Hello World!");
ChannelFuture f = ctx.writeAndFlush(pkt);
//f.addListener(ChannelFutureListener.CLOSE);
}
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
try {
DataPacket in = (DataPacket)msg;
System.out.println("[Transceiver]: Message received..."+in.getData());
}finally {
ReferenceCountUtil.release(msg);
//ctx.close();
}
}
#Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
transLog.warning("[Transceiver] : Error..." + cause.getMessage());
ctx.close();
}
}
The Server and Client pipelines :
ch.pipeline().addLast("Decoder", new EncoderDecoder.NettyDecoder());
ch.pipeline().addLast("Encoder", new EncoderDecoder.NettyEncoder());
ch.pipeline().addLast("DataAvroHandler", new DataAvroHandler());
Your problem arises from using the toString() method of the ByteBuf in in your NettyDecoder.
Quoting from the javadoc (http://netty.io/4.0/api/io/netty/buffer/ByteBuf.html#toString%28java.nio.charset.Charset%29):
This method does not modify readerIndex or writerIndex of this buffer.
Now, the ByteToMessageDecoder doesn't know how many bytes you have actually decoded! It looks like you decoded 0 bytes, because the buffer's readerIndex was not modified and therefore you also get the error messages in your console.
You have to modify the readerIndex manually:
String msg = in.toString(CharsetUtil.UTF_8);
in.readerIndex(in.readerIndex() + in.readableBytes());
System.out.println("Decode:"+msg);
i need to perform the all operation like the creating the quartz-2 scheduler and deleting on only one Apache camel context
using restful service. when i try using following code .each time its creating the new context object. i do not know how to fix it or where i need to initiate the apache camel context object.
this is my code
this is my java restful services which is call to the quartz scheduler.
java Rest Services.
#Path("/remainder")
public class RemainderResource {
private static org.apache.log4j.Logger log = Logger.getLogger(RemainderResource.class);
RemainderScheduler remainderScheduler=new RemainderScheduler();
CamelContext context = new DefaultCamelContext();
#POST
#Path("/beforeday/{day}")
public void create(#PathParam("day") int day,final String userdata)
{
log.debug("the starting process of the creating the Remainder");
JSONObject data=(JSONObject) JSONSerializer.toJSON(userdata);
String cronExp=data.getString("cronExp");
remainderScheduler.create(cronExp,day,context);
}
}
This is my java class which is schedule job .
public class RemainderScheduler {
private static org.apache.log4j.Logger log = Logger.getLogger(RemainderScheduler.class);
public void sendRemainder(int day)
{
log.debug("the starting of the sending the Remainder to user");
}
public RouteBuilder createMyRoutes(final String cronExp,final int day)
{
return new RouteBuilder()
{
#Override
public void configure() throws Exception {
log.debug("Before set schedulling");
from("quartz2://RemainderGroup/Remainder? cron="+cronExp+"&deleteJob=true&job.name='RemainderServices'").bean(new RemainderScheduler(), "sendRemainder('"+day+"')").routeId("Remainder")
.process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
}
})
;
log.debug("after set schedulling");
}
};
}
public void stopService(CamelContext context)
{
log.debug("this is going to be stop the route");
try {
context.stopRoute("Remainder");
context.removeRoute("Remainder");
} catch (Exception e) {
e.printStackTrace();
}
}
public void create(final String cronExp,final int day,CamelContext context)
{
try
{
//this for if all ready exist then stop it.
if(context.getRoute("Remainder")!=null)
stopService(context);
log.debug("the starting of the process for creating the Remaider Services");
context.addRoutes(createMyRoutes(cronExp, day));
context.start();
log.debug("the status for removing the services is"+context.removeRoute("Remainder"));
}
catch(Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
}
}
}
if i execute the above code then the each java Restful request create the new context object.
and its will start the job scheduling on new apache camel context object. and if send request for stop the route then also its creating the new apache context object so i am not able to reset or stop the quartz-2 scheduler.
It is not a good practise to create a camel context per request.
I suggest you to use camel-restlet or camel-cxfrs to delegate the request of create and delete scheduler to another camel context.
I'm trying to make an Mbeans which can change a few parameters in runtime but when trying to invoke an operation the following error occurs:
java.rmi.UnmarshalException: Error unmarshaling return; nested exception is: java.lang.ClassNotFoundException: weblogic.management.NoAccessRuntimeException > (no security manager: RMI class loader disabled)
I am using weblogic y jconsole.
code:
public class MyMBeanListener extends ApplicationLifecycleListener {
public void postStart(weblogic.application.ApplicationLifecycleEvent p1) {
try {
ObjectName mymbean =
new ObjectName("monitor:Name=MyMonitor,Type=MyMonitorMBean");
InitialContext ctx = new InitialContext();
MBeanServer server = (MBeanServer)ctx.lookup("java:comp/jmx/runtime");
MyMonitor monitor = new MyMonitor();
server.registerMBean(monitor, mymbean);
System.out.println(" MBean registered successfully!");
} catch (Exception e) {
e.printStackTrace();
}
}
public interface MyMonitorMBean {
public void setMessage(String msg);
}
public class MyMonitor implements MyMonitorMBean {
private String _con;
#Override
public synchronized void setMessage(String msg) {
_con = msg;
}
}
If you put Weblogic's JARs in your classpath it should work or at least you will get rid of the ClassNotFoundException
I would put weblogic.jar or wlfullclient.jar (if you have it), try running JConsole in a way similar to this:
jconsole -J-Djava.class.path="Weblogic Lib Folder\weblogic.jar"
I would like to be aware of the connection state in a camel/netty environment.
To do so, I tried something like this:
specified my camel route
from("direct:in").marshal().serialization()
.to("netty:tcp://localhost:42123?clientPipelineFactory=#cpf&sync=false");
implemented my pipeline factory
public class ConnectionStatusPipelineFactory extends ClientPipelineFactory {
#Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline cp = Channels.pipeline();
cp.addLast("statusHandler", new ConnectionStatusHandler());
return cp;
}
#Override
public ClientPipelineFactory createPipelineFactory(NettyProducer producer) {
return new ConnectionStatusPipelineFactory();
}
}
implemented my connection status handler
public class ConnectionStatusHandler extends SimpleChannelUpstreamHandler {
#Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception {
System.out.println("Event: " + e);
super.channelConnected(ctx, e);
}
#Override
public void channelDisconnected(ChannelHandlerContext ctx,
ChannelStateEvent e) throws Exception {
System.out.println("Event: " + e);
super.channelDisconnected(ctx, e);
}
}
And finally bound "ConnectionStatusPipelineFactory" to "cpf" in my camel registry.
But the following exception occured:
java.lang.IllegalArgumentException: unsupported message type: class [B
Remarks:
"channelConnected" and "channelDisconnected" methods are called as expected.
When I disable this, everything works (message marshalling, connection, remote process...).
Questions are:
what's wrong with that ?
is it the good way to know the connection status (connected or not) ?
Try using the decoder option instead and not the entire client pipeline factory.
eg use option decoder=#myConnectionStatusHandler. And then register your ConnectionStatusHandler in the registry with the name myConnectionStatusHandler.
If you use the pipeline factory then you need to add all the others that Camel add out of the box.