Netty 4 Beta 3 issue - java

I just started going trough the Netty 4 examples to see what is new and how to use it in an application. I started with the Discard Server tutorial. I wrote it and run and it worked. I could check via the telnet command. However based upon what is on the netty site I should be able to see something written on the console. But I could not see that though the app is running.
Also I have this warning message : WARNING: Your platform does not provide complete low-level API for accessing direct buffers reliably. Unless explicitly requested, heap buffer will always be preferred to avoid potential risk of getting OutOfMemoryError.
This is the code I have written:
/**
*
*/
package com.smsgh.Discard;
import java.net.InetSocketAddress;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
/**
* #author Arsene
*
*/
public class DiscardServer {
/**
*
*/
public DiscardServer() {
}
public static void main(String[] args){
// Instance of the Server bootstrap
ServerBootstrap bootstrap = new ServerBootstrap();
try{
// Bootstrap group is used to handle incoming connections and handle the I/O of
// those connections
bootstrap.group(new NioEventLoopGroup(), new NioEventLoopGroup());
// Set the factory
bootstrap.channel(NioServerSocketChannel.class);
// Add a child channel handler
bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
#Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new DiscardServerHandler());
}
});
// add the options
bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture future = bootstrap.bind(new InetSocketAddress(8889)).sync();
future.channel().closeFuture().sync();
}
catch(Exception ex){
ex.printStackTrace();
}
finally{
bootstrap.shutdown();
}
}
}
and this is the server handler code:
/**
*
*/
package com.smsgh.Discard;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundByteHandlerAdapter;
/**
* #author Arsene
*
*/
public class DiscardServerHandler extends ChannelInboundByteHandlerAdapter {
/**
*
*/
public DiscardServerHandler() {
}
/*
* (non-Javadoc)
*
* #see
* io.netty.channel.ChannelInboundByteHandlerAdapter#inboundBufferUpdated
* (io.netty.channel.ChannelHandlerContext, io.netty.buffer.ByteBuf)
*/
#Override
protected void inboundBufferUpdated(ChannelHandlerContext ctx, ByteBuf in)
throws Exception {
// Here we manipulate the data received
while(in.isReadable()){
System.out.println((char)in.readByte());
System.out.flush();
}
in.clear();
}
#Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
Can anyone tell me what went wrong? Thanx

I saw the issue. I did not add any encoder nor decoder of message coming in the pipeline.

Related

How do I properly set up a BrowserMobProxy/Selenium Proxy with RemoteWebDriver/Sauce Labs/Sauce Connect?

I've been looking everywhere and have not found any good documentation on how to properly set up a proxy to run a script on Sauce labs and extract the HAR file. I'm using BMP in an embedded mode https://github.com/lightbody/browsermob-proxy#using-with-selenium, along with https://wiki.saucelabs.com/display/DOCS/Sauce+Connect+Proxy. I found Sauce's documentation on setting up and running scripts through a BMP manually https://wiki.saucelabs.com/display/DOCS/Sauce+Connect+Proxy+with+an+Additional+Proxy+Setup, however their documentation does not show how to set it up in an embedded mode only via standalone mode. Here is my setup:
My PAC file
function FindProxyForURL(url, host) {
if (shExpMatch(host, "*.miso.saucelabs.com") ||
shExpMatch(host, "saucelabs.com")) {
// KGP and REST connections. Another proxy can also be specified.
return "DIRECT";
}
// Test HTTP traffic, route it through the local BrowserMob proxy.
return "PROXY localhost:9091";
}
BMP Set up
package com.grainger.Framework;
import java.io.File;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.UnknownHostException;
import org.apache.log4j.Logger;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import com.grainger.Automation.Utilities;
import com.grainger.Build.BuildVariables;
import net.lightbody.bmp.BrowserMobProxy;
import net.lightbody.bmp.BrowserMobProxyServer;
import net.lightbody.bmp.client.ClientUtil;
import net.lightbody.bmp.core.har.Har;
import net.lightbody.bmp.proxy.CaptureType;
public class BrowserMobProxyImpl {
public static Logger log = Logger.getLogger(BrowserMobProxyImpl.class.getName());
private static BrowserMobProxy MOB_PROXY_SERVER;
private static Proxy SELENIUM_PROXY;
/**
* #author xsxg091
* #return
*/
public static void startBrowserMobProxyServer(){
// start the proxy
MOB_PROXY_SERVER = getProxyServer();
// get the Selenium proxy object
SELENIUM_PROXY = getSeleniumProxy(MOB_PROXY_SERVER);
}
/**
* #author xsxg091
* #return
*/
public static BrowserMobProxy getProxyServer() {
BrowserMobProxy proxy = new BrowserMobProxyServer();
proxy.setTrustAllServers(true);
proxy.start(9090);
return proxy;
}
/**
* #author xsxg091
* #param proxyServer
* #return
*/
public static Proxy getSeleniumProxy(BrowserMobProxy proxyServer) {
Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxyServer);;
try {
String hostIp = Inet4Address.getLocalHost().getHostAddress();
seleniumProxy.setHttpProxy(hostIp + ":" + Integer.toString(9091));
seleniumProxy.setSslProxy(hostIp + ":" + Integer.toString(9091));
seleniumProxy.setAutodetect(false);
} catch (UnknownHostException e) {
log.error("Error initializing Selenium Proxy");
}
return seleniumProxy;
}
/**
* #author xsxg091
* #param tcName
* #param capabilities
*/
public static void setSeleniumProxy(DesiredCapabilities capabilities){
if(BuildVariables.amICapturingNetworkTraffic()){
capabilities.setCapability(CapabilityType.PROXY, SELENIUM_PROXY);
}
}
/**
* #author xsxg091
* #param tcName
* #param capabilities
*/
public static void stopBrowserMobProxyServer(){
MOB_PROXY_SERVER.stop();
}
/**
* #author xsxg091
* #return
*/
public static void getHarFile(String fileName) {
// enable more detailed HAR capture, if desired (see CaptureType for the complete list)
MOB_PROXY_SERVER.enableHarCaptureTypes(CaptureType.REQUEST_CONTENT, CaptureType.RESPONSE_CONTENT);
MOB_PROXY_SERVER.newHar(fileName);
try {
// get the HAR data
Har pageHarFile = MOB_PROXY_SERVER.getHar();
File harFile = new File(Utilities.getWorkSpace()+"//"+fileName+".har");
pageHarFile.writeTo(harFile);
} catch (IOException e) {
log.error("Unable to store Har File");
}
}
}
Here is the command I use to kick off my Sauce Tunnel
bin/sc -u ****** -k *********** -i Tunnel_Testing -v --pac file:///<path-to-pac-file>/BrowserMobProxy/browserMob.js
When I run lsof, I can port 9090 is actively listening, but I don't see 9091 in embedded mode. However, when I run it in standalone mode I can see both ports and everything works perfectly on Sauce labs. I see this when I run in embedded mode:
What am I doing wrong? Any help would be greatly appreciated. If anything is unclear, please let me know!
Thanks in advance.
I figured it out. Turns out it was a bug in version 2.1.4. When I upgraded to version 2.1.5, everything worked as it is supposed to.

Android Handler is null during testing with junit

I'm trying to test my network module. When I run this on simulator or device, handler is ok, but when I'm trying to do it from tests, handler = null and callback doesn't get called. How can I solve this problem?
public void performCall(Call callToPerform){
callToPerform.call.enqueue(new okhttp3.Callback() {
Handler handler = new Handler();
#Override
public void onFailure(okhttp3.Call call, IOException e) {
handler.post(() -> {
for (Callback callback : callToPerform.callbacks) {
callback.onFailure(callToPerform, e);
}
});
}
#Override
public void onResponse(okhttp3.Call call, final okhttp3.Response response){
handler.post(() -> {
for (Callback callback : callToPerform.callbacks) {
try {
callback.onResponse(callToPerform, new Response(response.body().bytes(), response.headers().toMultimap()));
} catch (IOException e) {
callback.onFailure(call, e);
}
}
});
}
});
}
My graddle app file contains this params.
testOptions {
unitTests.returnDefaultValues = true
}
Ok, after a few hours of research I've found solution and it's similar to this:
package com.dpmedeiros.androidtestsupportlibrary;
import android.os.Handler;
import android.os.Looper;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import static org.mockito.Mockito.*;
/**
* Utility methods that unit tests can use to do common android library mocking that might be needed.
*/
public class AndroidMockUtil {
private AndroidMockUtil() {}
/**
* Mocks main thread handler post() and postDelayed() for use in Android unit tests
*
* To use this:
* <ol>
* <li>Call this method in an {#literal #}Before method of your test.</li>
* <li>Place Looper.class in the {#literal #}PrepareForTest annotation before your test class.</li>
* <li>any class under test that needs to call {#code new Handler(Looper.getMainLooper())} should be placed
* in the {#literal #}PrepareForTest annotation as well.</li>
* </ol>
*
* #throws Exception
*/
public static void mockMainThreadHandler() throws Exception {
PowerMockito.mockStatic(Looper.class);
Looper mockMainThreadLooper = mock(Looper.class);
when(Looper.getMainLooper()).thenReturn(mockMainThreadLooper);
Handler mockMainThreadHandler = mock(Handler.class);
Answer<Boolean> handlerPostAnswer = new Answer<Boolean>() {
#Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
Runnable runnable = invocation.getArgumentAt(0, Runnable.class);
Long delay = 0L;
if (invocation.getArguments().length > 1) {
delay = invocation.getArgumentAt(1, Long.class);
}
if (runnable != null) {
mainThread.schedule(runnable, delay, TimeUnit.MILLISECONDS);
}
return true;
}
};
doAnswer(handlerPostAnswer).when(mockMainThreadHandler).post(any(Runnable.class));
doAnswer(handlerPostAnswer).when(mockMainThreadHandler).postDelayed(any(Runnable.class), anyLong());
PowerMockito.whenNew(Handler.class).withArguments(mockMainThreadLooper).thenReturn(mockMainThreadHandler);
}
private final static ScheduledExecutorService mainThread = Executors.newSingleThreadScheduledExecutor();
}
If you run this sample code on JUnit, this will not work because JUnit tests are running on a JVM, and Instrumented tests are running on a Simulator or Real Device
You can take a look at this link, it explains why :
Instrumented tests or Local tests

Instance "Main" Method Not Running When Called from Another Class

I'm learning Java and experimenting with Javafx in netbeans.
I am running the sqlite tutorial here: http://www.tutorialspoint.com/sqlite/sqlite_java.htm
When set up as a lone-file it works fine of course.
I'm setting it up in a test project "testDB" and for some reason when I initiate the class the class itself is recognized, but main() is not running.
Here is the testdb file itself:
testDB.java:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sqlitetest;
import java.sql.*;
/**
*
*/
public class testDB {
public static void main(String args[]) {
//THESE STEPS ARE ON NOT RUNNING (compiles without errors)
System.out.println("testing");
Connection c = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Opened database successfully");
}
public void makeStuff(){
}
}
sqlitetest.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sqlitetest;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
/**
*
*/
public class Sqlitetest extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
testDB test = new testDB();
test.makeStuff();
launch(args);
}
}
I think you are getting confused between a constructor and a main method.
A main method is only invoked when you start the JVM, running that specific class (or if you invoke it explicitly elsewhere).
A constructor is invoked when you create an instance of the class, like you are doing here.
In testdb, change:
public static void main(String args[]) {
to
public testdb() {
Alternatively, invoke testdb.main(args) (or with some other parameter) in Sqlitetest.main.

running a simple task example

Hi I've been trying all night to run this example and have had no luck what so ever, I cannot find a solution. I have two file.
First is Worker.java and here is its contents
import javafx.application.Application;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author brett
*/
public class Worker {
/**
* #param args the command line arguments
* #throws java.lang.Exception
*/
/**
*
* #param args
* #throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO code application logic here
doit();
}
private static void doit(){
try {
IteratingTask mytask = new IteratingTask(800000);
mytask.call();
System.out.println(mytask.getValue());
int pro = (int) mytask.getProgress();
System.out.println(pro);
} catch (Exception ex) {
Logger.getLogger(Worker.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Next is the IteratingTask.java file and its contents
//import javafx.concurrent.Task;
import javafx.application.Application;
import javafx.concurrent.Task;
/**
*
* #author brett
*/
public class IteratingTask extends Task<Integer> {
private final int totalIterations;
public IteratingTask(int totalIterations) {
this.totalIterations = totalIterations;
}
#Override protected Integer call() throws Exception {
int iterations;
// iterations = 0;
for (iterations = 0; iterations < totalIterations; iterations++) {
if (isCancelled()) {
updateMessage("Cancelled");
break;
}
updateMessage("Iteration " + iterations);
updateProgress(iterations, totalIterations);
}
return iterations;
}
}
I know I'm doing something very wrong but... I just cant see it.
Here is the error it get
run:
Jan 31, 2015 11:56:38 PM Worker doit
SEVERE: null
java.lang.IllegalStateException: Toolkit not initialized
at com.sun.javafx.application.PlatformImpl.runLater(PlatformImpl.java:270)
at com.sun.javafx.application.PlatformImpl.runLater(PlatformImpl.java:265)
at javafx.application.Platform.runLater(Platform.java:81)
at javafx.concurrent.Task.runLater(Task.java:1211)
at javafx.concurrent.Task.updateMessage(Task.java:1129)
at IteratingTask.call(IteratingTask.java:24)
at Worker.doit(Worker.java:38)
at Worker.main(Worker.java:31)
BUILD SUCCESSFUL (total time: 0 seconds)
It builds ok.... any advice would be awesome.
The problem is that the FX Toolkit, and in particular the FX Application Thread have not been started. The update...(...) methods in Task update various state on the FX Application Thread, so your calls to those methods cause an IllegalStateException as there is no such thread running.
If you embed this code in an actual FX Application, it will run fine. Calling launch() causes the FX toolkit to be started.
Also, note that while this will run, Tasks are generally intended to be run in a background thread, as below:
import javafx.application.Application;
import javafx.scene.Scene ;
import javafx.scene.layout.StackPane ;
import javafx.scene.control.Label ;
import javafx.stage.Stage ;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Worker extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
StackPane root = new StackPane(new Label("Hello World"));
Scene scene = new Scene(root, 350, 75);
primaryStage.setScene(scene);
primaryStage.show();
doit();
}
public static void main(String[] args) throws Exception {
launch(args);
}
private void doit(){
try {
IteratingTask mytask = new IteratingTask(800000);
// mytask.call();
Thread backgroundThread = new Thread(mytask);
backgroundThread.start(); // will return immediately, task runs in background
System.out.println(mytask.getValue());
int pro = (int) mytask.getProgress();
System.out.println(pro);
} catch (Exception ex) {
Logger.getLogger(Worker.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

Problem while executing simple quartz scheduler

I am learning quartz scheduler framework and as a base I have started with "Hello World" thats prints at regular Intervals.
This is my SampleScheduler
public class SampleScheduler {
public static void main(String arfs[]) {
try {
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.start();
System.out.println("Scheduler Started...");
JobDetail job = new JobDetail("job1","group1",SampleJobInter.class);
Trigger trigger = new SimpleTrigger("trigger1",Scheduler.DEFAULT_GROUP,new Date(),null,SimpleTrigger.REPEAT_INDEFINITELY,60L*1000L);
scheduler.scheduleJob(job, trigger);
scheduler.shutdown();
System.out.println("Scheduler Stopped..");
} catch(SchedulerException e) {
}
}
}
Here is my SampleJobInter.class
public class SampleJobInter implements Job {
SampleJobInter(){}
#Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {
// TODO Auto-generated method stub
System.out.println("Hello World at "+new Date());
}
}
The output am getting is
Scheduler Started...
Scheduler Stopped..
I am not getting the desired output. I am running it in the console. Do I need to do any configurations or what?. Please Help me in this
just put scheduler.start() after you have scheduled a job to run - scheduler.scheduleJob...
UPDATE: I stand corrected by org.life.java. The order of statements won't make much of a difference. The source of your troubles is the shutdown() invocation. A scheduler's contract [javadoc] is to keep running as long as an explicit shutdown command is not issued on it. if you remove that line from your code, it works fine.
I have created it from scratch and it works well.!!
I would suggest you to compare your code with this ans also log exception in catch so that you will have good idea.
JobRunner
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.life.java.so.questions;
/**
*
* #author Jigar
*/
import java.util.Date;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;
public class HelloSchedule {
public HelloSchedule() throws Exception {
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sched = sf.getScheduler();
sched.start();
JobDetail jd = new JobDetail("myjob", sched.DEFAULT_GROUP, SampleJobInter.class);
SimpleTrigger st = new SimpleTrigger("mytrigger", sched.DEFAULT_GROUP, new Date(),
null, SimpleTrigger.REPEAT_INDEFINITELY, 100L);
sched.scheduleJob(jd, st);
}
public static void main(String args[]) {
try {
new HelloSchedule();
} catch (Exception e) {
}
}
}
Job
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.life.java.so.questions;
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
/**
*
* #author Jigar
*/
public class SampleJobInter implements Job {
public SampleJobInter() {
}
public void execute(JobExecutionContext arg0) throws JobExecutionException {
System.out.println("Hello World at " + new Date());
}
}

Categories

Resources