j2me HttpConnection - java-me

am creating a J2ME application which connects/accesses some php Files in a remote server using j2me(HttpConnection). due to some network problems at times the connection block for a long period of time. how would i create a thread to try the connection given a timeout of 10seconds. if the connection doesnt respond within the 10seconds the thread waits for another 5 seconds and retries again. the maximum number of retries should be 3 before the user is alerted that there is not network connection available.

You can use TimerTask class in either way, to check the Timeout interval of 10 seconds as follows,
// First do your HttpConnection and open your URL
HttpConnection httpConnection = (HttpConnection) Connector.open(URL);
responseCode = httpConnection.getResponseCode(); // responseCode is class variable
// Now create a timertask that invokes after 10 seconds,
Timer timer = new Timer();
timer.schedule ( new TimeoutTask(), 10 * 1000 );
...
private class TimeOutTask extends TimerTask
{
public void run()
{
// check reponseCode's value here, if it is not 200 then there is problem in network connection.
}
}

Related

WCF ChannelFactory use in multithread request timeout

I have a problem using WCF ChannelFactory in multi threading environment. When I call the a method from the ChannelFactory, I keep geting timeout on my calls.
private static ChannelFactory<Foo> factory = null;
private static object lockObj = new object();
...
in my thread method:
Foo obj
lock(lockObj)
{
if(factory == null)
{
factory = new ChannelFactory<Foo>(basicBinding, New EndpointAddress(New Uri(u)));
}
obj = factory.CreateChannel();
}
obj.doSomething();
obj.close()
...
When the code execute the obj.doSomething(), I get a timeout exception and I don't understand why. And worst, some times, the call pass witought problems and I ged expected results.
I also noted that there are only 2 call made when the program execute.
Ok, I do not understand why, but it seem that the backgroundWorker that we use to manage the threads cap the number of connection to 2. The Thread class though does not block the connections

Can i set remoteTimeOut to Infinity on TcpOutBoundgateway

I am using CachingClientConnectionFactory, How can i keep the connections alive, its closing out after default remoteTimeOut elapses, Can I set the remoteTimeOut to LONG.MAX_VALUE?
Thanks
#Bean
public AbstractClientConnectionFactory clientConnectionFactory() {
TcpNioClientConnectionFactory tcpNioClientConnectionFactory = new TcpNioClientConnectionFactory(host, port);
tcpNioClientConnectionFactory.setUsingDirectBuffers(true);
tcpNioClientConnectionFactory.setApplicationEventPublisher(applicationEventPublisher);
return new CachingClientConnectionFactory(tcpNioClientConnectionFactory, connectionPoolSize);
}
#Bean
public MessageChannel outboundChannel() {
return new DirectChannel();
}
#Bean
#ServiceActivator(inputChannel = "outboundChannel")
public MessageHandler outboundGateway(AbstractClientConnectionFactory clientConnectionFactory) {
TcpOutboundGateway tcpOutboundGateway = new TcpOutboundGateway();
tcpOutboundGateway.setConnectionFactory(clientConnectionFactory);
tcpOutboundGateway.setRemoteTimeout(Long.MAX_VALUE);
tcpOutboundGateway.setRequestTimeout(5_000);
return tcpOutboundGateway;
}
Yes I want it to single thread, I want concurrent send to be blocked until the socket is available;
Yes; with that configuration, it will be single-threaded; concurrent requests will wait for up to requestTimeout to get access to the shared socket.
https://github.com/spring-projects/spring-integration/blob/4484c4da753096094e5b376411b94ac4ba2834c6/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/TcpOutboundGateway.java#L217
try {
haveSemaphore = acquireSemaphoreIfNeeded(requestMessage);
connection = this.connectionFactory.getConnection();
...
The request that gets access to the socket then waits for up to replyTimeout for a reply. If it times out, the socket is closed, to avoid the next request getting this request's reply. The next request will get a new socket.
tcpOutboundGateway.setRemoteTimeout(Long.MAX_VALUE);
That should be reduced to something more reasonable otherwise you could block forever if, for some reason, the server doesn't reply (but keeps the socket open).

Netty OrderedMemoryAwareThreadPoolExecutor not creating multiple threads

I use Netty for a multithreaded TCP server and a single client persistent connection.
The client sends many binary messages (10000 in my use case) and is supposed to receive an answer for each message. I added an OrderedMemoryAwareThreadPoolExecutor to the pipeline to handle the execution of DB calls on multiple threads.
If I run a DB call in the method messageReceived() (or simulate it with Thread.currentThread().sleep(50)) then all events are handled by a single thread.
5 count of {main}
1 count of {New
10000 count of {pool-3-thread-4}
For a simple implementation of messageReceived() the server creates many executor threads as expected.
How should I configure the ExecutionHandler to get multiple threads executors for the business logic, please?
Here is my code:
public class MyServer {
public void run() {
OrderedMemoryAwareThreadPoolExecutor eventExecutor = new OrderedMemoryAwareThreadPoolExecutor(16, 1048576L, 1048576L, 1000, TimeUnit.MILLISECONDS, Executors.defaultThreadFactory());
ExecutionHandler executionHandler = new ExecutionHandler(eventExecutor);
bootstrap.setPipelineFactory(new ServerChannelPipelineFactory(executionHandler));
}
}
public class ServerChannelPipelineFactory implements ChannelPipelineFactory {
public ChannelPipeline getPipeline() throws Exception {
pipeline.addLast("encoder", new MyProtocolEncoder());
pipeline.addLast("decoder", new MyProtocolDecoder());
pipeline.addLast("executor", executionHandler);
pipeline.addLast("myHandler", new MyServerHandler(dataSource));
}
}
public class MyServerHandler extends SimpleChannelHandler {
public void messageReceived(ChannelHandlerContext ctx, final MessageEvent e) throws DBException {
// long running DB call simulation
try {
Thread.currentThread().sleep(50);
} catch (InterruptedException ex) {
}
// a simple message
final MyMessage answerMsg = new MyMessage();
if (e.getChannel().isWritable()) {
e.getChannel().write(answerMsg);
}
}
}
OrderedMemoryAwareThreadPoolExecutor guarantees that events from a single channel are processed in order. You can think of it as binding a channel to a specific thread in the pool and then processing all events on that thread - although it's a bit more complex than that, so don't depend on a channel always being processed by the same thread.
If you start up a second client you'll see it (most likely) being processed on another thread from the pool. If you really can process a single client's requests in parallel then you probably want MemoryAwareThreadPoolExecutor but be aware that this offers no guarantees on the order of channel events.

SimpleChannelUpstreamHandler await*() in I/O thread causes a dead lock

In my Netty SimpleChannelUpstreamHandler when I receive a message I need to start up a connection to another Netty Server and forward the message on. However, when starting up this second connection I use:
ChannelFuture channelFuture = clientBootstrap.connect(new InetSocketAddress(host, port));
hannelFuture.awaitUninterruptibly();
Which results in the following error:
java.lang.IllegalStateException: await*() in I/O thread causes a dead lock or sudden performance drop. Use addListener() instead or call await*() from a different thread.
at org.jboss.netty.channel.DefaultChannelFuture.checkDeadLock(DefaultChannelFuture.java:314)
at org.jboss.netty.channel.DefaultChannelFuture.awaitUninterruptibly(DefaultChannelFuture.java:226)
at com.my.NettyClient.start(NettyClient.java:204)
....
at com.my.MyChannelUpstreamHandler.messageReceived(MyChannelUpstreamHandler.java:52)
Whats the best way to start this second connection? Should I do the following?:
#Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.submit(new Runnable() {
#Override
public void run() {
// Connect to another Netty Server...
// Forward on message...
}
});
executorService.shutdown();
...
Is this wasteful to start a new thread on each message recieved?
Checkout the proxy example to see how you can do it without blocking:
http://netty.io/docs/stable/xref/org/jboss/netty/example/proxy/HexDumpProxyInboundHandler.html

log4j - DailyRollingFileAppender, file not roll hourly

I have the following simple Test class for DailyRollingFileAppender to rolls the log file every hour. The problem I am facing is that, it doesn't seem to roll over to new log file every hour even though I have set that to '.'yyyy-MM-dd-HH. Any idea where in the code I did wrongly?
public class Test {
static Logger logger = Logger.getLogger(Test.class);
public static void main(String args[]) throws Exception {
String pattern = "%-20d{dd MMM yyyy HH:mm:ss} [%-5p] - %m%n";
PatternLayout patternLayout = new PatternLayout(pattern);
//CREATE APPENDER.
DailyRollingFileAppender myAppender = new DailyRollingFileAppender(patternLayout, "TestOrig.log", "'.'yyyy-MM-dd-HH");
//ADD APPENDER & LEVEL.
logger.addAppender(myAppender);
logger.setLevel ((Level) Level.DEBUG);
//WRITE MESSAGES.
logger.debug("Successful");
logger.info ("Failed" );
logger.warn ("Failed" );
logger.error("Successful");
logger.fatal("Failed");
while(true)
{
Thread.sleep(1000);
}
}
}
Use #Singleton and #Schedule to create an ejb cron like schedule for your timer service.
import javax.ejb.Schedule;
import javax.ejb.Singleton;
#Singleton
public class Cron {
static Logger logger = Logger.getLogger(Test.class);
#Schedule(second="0", minute="0", hour="0", dayOfWeek="*", persistent=false)
public void rollLogs() {
logger.info("midnight");
}
}
I don't see any error here. I could see this is creating files when I tried for minutes.
DailyRollingFileAppender myAppender = new DailyRollingFileAppender(patternLayout, "TestOrig.log", "'.'yyyy-MM-dd-HH-mm");
Did you see any error on the console??
Possible reason of error for you could be , you are trying to run the same program multiple times, without ending the previously started program and that is resulting in file access permission issue.
Mike, you are correct in your comment above. You will not get a new file unless there is logging activity during that time. If you are required to force the issue, you'll need to start a thread with a runnable that posts a line to the log after the start of each new hour.
The goal is to make one post to your log every 59.5 minutes, starting from minute 1.
Basic standard knowledge of how to use Runnable and Thread are required for his solution. I am assuming you are running a standard application and not within a managed server environment
create a class that implements Runnable
overwrite the run() method with a while loop to a true boolean variable (isAlive) your app can set to false when your app shuts down.
during the loop call the .info("Logger Text") method of a static Logger logger = Logger.getLogger(YourClassName.class); with a loop wait time of 60 minutes.
Toss the Runnable into a new Thread() object at application start-up
make one info() post to your log at startup.
start the thread object when you start your app.
run() method of Runnable can be
public void run() {
while (isAlive) { // isAlive is a global-level (static, even) boolean
// you declared earlier as true, your app should set it to false
// if your app decides to exit
try {
logger.info("Rollover Log Text");
Thread.currentThread().sleep(1000 * 60 * 60); // 60 minutes
} catch (InterruptedException ignore) {
}
}
}
Remember to set isAlive to true before you start your Thread, set it to false on shutdown or error/exception close, and call the the interrupt() method of your thread after setting to false. This should log one time an hour.

Resources