running a simple task example - java

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);
}
}
}

Related

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.

Handle on launched JavaFX Application

How do I get a handle on a JavaFX application started using the following code?
CPUUsageChart.launch(CPUUsageChart.class);
CPUUsageChart extends Application from JavaFX and I am launching it from a main method of a simple Java project.
What I ultimately want to achieve is, that I can start the App and use its methods in the simple Java code, so that I do not have to do the calling in the Constructor of the Application extending class. I only want to use JavaFX's abilities for drawing charts and save them to HDD, for later usage, but I do not need to see any GUI made in JavaFX.
Proposed Solution
You can only launch an application once, so there will only ever be a single instance of your application class.
Because there is only a single instance of the application, you can store a reference to the instance in a static variable of the application when the application is started and you can get the instance as required from a static method (a kind of singleton pattern).
Caveats
Care must be taken to ensure:
The instance is available before you try to use it.
That threading rules are appropriately observed.
That the JavaFX Platform is appropriately shutdown when it is no longer required.
Sample Solution
The sample code below uses a lock and a condition to ensure that the application instance is available before you try to use it. It will also require explicit shutdown of the JavaFX platform when it is no longer required.
Thanks to StackOverflow user James-D for some edit assistance with this code.
import javafx.application.Application;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.stage.Stage;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class CPUUsageChart extends Application {
private static CPUUsageChart appInstance;
private static final Lock lock = new ReentrantLock();
private static final Condition appStarted = lock.newCondition();
/**
* Starts the application and records the instance.
* Sets the JavaFX platform not to exit implicitly.
* (e.g. an explicit call to Platform.exit() is required
* to exit the JavaFX Platform).
*/
#Override
public void start(Stage primaryStage) {
lock.lock();
try {
Platform.setImplicitExit(false);
appInstance = this;
appStarted.signalAll();
} finally {
lock.unlock();
}
}
/**
* Get an instance of the application.
* If the application has not already been launched it will be launched.
* This method will block the calling thread until the
* start method of the application has been invoked and the instance set.
* #return application instance (will not return null).
*/
public static CPUUsageChart getInstance() throws InterruptedException {
lock.lock();
try {
if (appInstance == null) {
Thread launchThread = new Thread(
() -> launch(CPUUsageChart.class),
"chart-launcher"
);
launchThread.setDaemon(true);
launchThread.start();
appStarted.await();
}
} finally {
lock.unlock();
}
return appInstance;
}
/**
* Public method which can be called to perform the main operation
* for this application.
* (render a chart and store the chart image to disk).
* This method can safely be called from any thread.
* Once this method is invoked, the data list should not be modified
* off of the JavaFX application thread.
*/
public void renderChart(
ObservableList<XYChart.Data<Number, Number>> data
) {
// ensure chart is rendered on the JavaFX application thread.
if (!Platform.isFxApplicationThread()) {
Platform.runLater(() -> this.renderChartImpl(data));
} else {
this.renderChartImpl(data);
}
}
/**
* Private method which can be called to perform the main operation
* for this application.
* (render a chart and store the chart image to disk).
* This method must be invoked on the JavaFX application thread.
*/
private void renderChartImpl(
ObservableList<XYChart.Data<Number, Number>> data
) {
LineChart<Number, Number> chart = new LineChart<>(
new NumberAxis(),
new NumberAxis(0, 100, 10)
);
chart.setAnimated(false);
chart.getData().add(
new XYChart.Series<>("CPU Usage", data)
);
Scene scene = new Scene(chart);
try {
LocalDateTime now = LocalDateTime.now();
File file = Paths.get(
System.getProperty("user.dir"),
"cpu-usage-chart-" + now + ".png"
).toFile();
ImageIO.write(
SwingFXUtils.fromFXImage(
chart.snapshot(null, null),
null
),
"png",
file
);
System.out.println("Chart saved as: " + file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
To use this (from any thread):
try {
// get chartApp instance, blocking until it is available.
CPUUsageChart chartApp = CPUUsageChart.getInstance();
// call render chart as many times as you want
chartApp.renderChart(cpuUsageData);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
// note your program should only ever exit the platform once.
Platform.exit();
}
Complete sample application which creates five graphs of cpu usage data with ten samples in each chart, each sample spaced by 100 milliseconds. As the sample invokes the chart application to render the charts, it will create chart png image files in the current java working directory and the file names will be output to the system console. No JavaFX stage or window is displayed.
Code to sample CPU usage copied from: How to get percentage of CPU usage of OS from java
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.chart.XYChart;
import javax.management.*;
import java.lang.management.ManagementFactory;
public class ChartTest {
public static void main(String[] args) {
try {
CPUUsageChart chart = CPUUsageChart.getInstance();
for (int i = 0; i < 5; i++) {
ObservableList<XYChart.Data<Number, Number>> cpuUsageData = FXCollections.observableArrayList();
for (int j = 0; j < 10; j++) {
cpuUsageData.add(
new XYChart.Data<>(
j / 10.0,
getSystemCpuLoad()
)
);
Thread.sleep(100);
}
chart.renderChart(cpuUsageData);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (MalformedObjectNameException | ReflectionException | InstanceNotFoundException e) {
e.printStackTrace();
} finally {
Platform.exit();
}
}
public static double getSystemCpuLoad() throws MalformedObjectNameException, ReflectionException, InstanceNotFoundException {
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName name = ObjectName.getInstance("java.lang:type=OperatingSystem");
AttributeList list = mbs.getAttributes(name, new String[]{ "SystemCpuLoad" });
if (list.isEmpty()) return Double.NaN;
Attribute att = (Attribute)list.get(0);
Double value = (Double)att.getValue();
if (value == -1.0) return Double.NaN; // usually takes a couple of seconds before we get real values
return ((int)(value * 1000) / 10.0); // returns a percentage value with 1 decimal point precision
}
}
Sample output (percentage CPU usage on the Y axis, and time in tenth of second sample spacing on the X axis).
Background Information
Application javadoc to further understand the JavaFX application lifecycle.
Related question: How do I start again an external JavaFX program? Launch prevents this, even if the JavaFX program ended with Platform.Exit
Alternate Implementations
You could use a JFXPanel rather than a class which extends Application. Though, then your application would also have a dependency on Swing.
You could make the main class of your application extend Application, so the application is automatically launched when your application is started rather than having a separate Application just for your usage chart.
If you have lots and lots of charts to render you could look a this off screen chart renderer implementation.

Netty 4 Beta 3 issue

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.

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