junit test with Eclipse - testing

Hi i am trying to use junit and it does not work s well.
Here is my code.
package safe;
import java.lang.reflect.*;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import safe.SafetyException;
public class SafetyInspector {
public static boolean isSafe(Class<?> clazz) throws SafetyException{
if (clazz.equals(Object.class)) return true;
if (clazz == null ) {
throw new SafetyException();
}
Field fields[] = clazz.getDeclaredFields();
for(Field f: fields){
f.setAccessible(true);
int mod = f.getModifiers();
if (Modifier.isFinal(mod)){
continue;
}
else if (Modifier.isPrivate(mod)){
Class<?> typeArray[] = new Class<?>[1] ;
typeArray[0] = f.getType();
try {
Method mSet = clazz.getMethod("set" + f.getName().substring(0, 0).toUpperCase() + f.getName().substring(1),typeArray );
int modMet = mSet.getModifiers();
if(!Modifier.isPublic(modMet)) return false;
if(!mSet.getReturnType().equals(void.class)) return false;
}
catch (SecurityException e) {
throw new SafetyException();
}
catch (NoSuchMethodException e) {
return false;
}
try {
Class<?> typeArray2[] = new Class<?>[1] ;
Method mGet = clazz.getMethod("get" + f.getName().substring(0, 0).toUpperCase() + f.getName().substring(1),typeArray2);
int modMet2 = mGet.getModifiers();
if(!Modifier.isPublic(modMet2)) return false;
if(!mGet.getReturnType().equals(f.getType())) return false;
}
catch (SecurityException e) {
throw new SafetyException() ;
}
catch (NoSuchMethodException e) {
return false;
}
}
}
return isSafe(clazz.getSuperclass());
}
public static void sort(List<Class<?>> classes) throws SafetyException{
for (int i = 1; i < classes.size(); i++) {
for (int j = 0; j < classes.size() - i; j++) {
if (compare(classes.get(j), classes.get(j + 1)) > 0) {
swap(classes, j);
}
}
}
}
public static void reset(Object object) throws SafetyException{
Class c = object.getClass();
Field fields[] = c.getDeclaredFields();
for(Field f :fields ){
if (!isSafe(f.getClass()))
{
f.setAccessible(true);
try{
if(!f.getClass().isPrimitive()){
}
else if(f.getClass().equals(boolean.class)){
f.setBoolean(object, false);
}
else{
f.set(object, 0);
}
}
catch(Exception e)
{
throw new SafetyException();
}
}
}
}
private static int compare(Class<?> o1, Class<?> o2) throws SafetyException {
Field[] fields1 = o1.getDeclaredFields();
int count1 = 0;
for (Field f : fields1){
if (isSafe(f.getClass())) count1++;
}
Field[] fields2 = o2.getDeclaredFields();
int count2 = 0;
for (Field f : fields2){
if (isSafe(f.getClass())) count2++;
}
if (count1 == count2)
return o1.getName().compareTo(o2.getName());
else return count1- count2;
}
private static void swap(List<Class<?>> list, int j) {
Class<?> temp = list.get(j);
list.set(j, list.get(j+1));
list.set(j + 1, temp);
}
};
and here is the code junit test that they gave me.
package test;
import static org.junit.Assert.assertEquals;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import org.junit.Test;
import safe.SafetyException;
import safe.SafetyInspector;
public class SafetyInspectorTest {
#Test
public void testIsSafeEmployee() throws SafetyException {
assertEquals(false, SafetyInspector.isSafe(Employee.class));
}
#Test
public void testResetEmployee() throws SafetyException {
Employee e = new Employee(123,3000);
SafetyInspector.reset(e);
assertEquals(0, e.id);
assertEquals(3000, e.getSalary());
}
#Test
public void testSort() throws SafetyException {
List<Class<?>> sortedClasses = new LinkedList<Class<?>>();
sortedClasses.add(Employee.class);
List<Class<?>> classes = new LinkedList<Class<?>>(sortedClasses);
Collections.shuffle(classes);
SafetyInspector.sort(classes);
assertEquals(sortedClasses, classes);
}
}
and when I run the safetyInspectorTest as a junitTESTCLASS i get an initialization error. I work with eclipse if it helps and I put Junit as a library of the project.

An initialization error in JUnit is generally caused by a bad classpath. See this related question which also suffered from initialization error:
Eclipse JUnit - possible causes of seeing "initializationError" in Eclipse window
The most likely cause is as that question addressed, you are using a version of JUnit 4 which requires the hamcrest jar to be added. Instead of adding the junit and hamcrest jars you should be able to add the JUnit 4 library on your project's Java Build Path.
Your imports largely look benign but you should confirm safe.SafetyException is on your classpath.
Finally, the initialization error could be caused by a static initialization failure in code that loads before your test runs. The code you've posted looks safe but SafetyException class could possibly have an initialization block to check.

Related

C3P0, rawConnectionOperation() & java.lang.IllegalArgumentException

I am attempting to use a non-standard method, getServerJobIdentifier(), that is part of the IBM Java Tool Box (jt400.jar) and class com.ibm.as400.access.AS400JDBCConnection with C3P0 & rawConnectionOperation(). I am getting "java.lang.IllegalArgumentException: object is not an instance of declaring class". I have tried numerous options but have not stumbled upon the correct parameters to pass. I am using C3P0 0.9.5.4. Code snippet follows:
// The method I want to call.
// getServerJobIdentifier, public abstract java.lang.String com.ibm.as400.access.AS400JDBCConnection.getServerJobIdentifier()
String driverClassName = "com.ibm.as400.access.AS400JDBCDriver";
String m_DatabaseConnectionString = "jdbc:db2:*local;naming=sql;extended metadata=true";
Connection m_dbConnection;
ComboPooledDataSource m_cpds;
m_cpds = new ComboPooledDataSource();
try {
m_cpds.setDriverClass(driverClassName); //loads the jdbc driver
}
catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
m_cpds.setJdbcUrl(m_DatabaseConnectionString);
m_dbConnection = m_cpds.getConnection();
String qualifiedName = "";
C3P0ProxyConnection castCon = (C3P0ProxyConnection)m_dbConnection;
Method m = AS400JDBCConnection.class.getDeclaredMethod("getServerJobIdentifier");
// This does return what I want. getServerJobIdentified() has no parameters.
System.out.println("method=" + m.toString());
Object[] args = new Object[] {};
System.out.println("calling rawConnectionOperation");
qualifiedName = (String) castCon.rawConnectionOperation(m, C3P0ProxyConnection.RAW_CONNECTION, args);
// never gets here
System.out.println("qualifiedName=" + qualifiedName);
I know I'm that close or I think I am. Thanks!
import java.util.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import com.mchange.v2.c3p0.*;
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400JDBCConnection;
import com.ibm.as400.access.AS400SecurityException;
import com.ibm.db2.jdbc.app.DB2Connection;
// javac -cp :./c3p0-0.9.5.4.jar:./mchange-commons-java-0.2.15.jar:./jt400.jar C3P0Main.java
// /QIBM/ProdData/OS400/jt400/lib/jt400Native.jar
// java -cp :./c3p0-0.9.5.4.jar:./mchange-commons-java-0.2.15.jar:./jt400.jar C3P0Main
// or
// java -cp :./c3p0-0.9.5.4.jar:./mchange-commons-java-0.2.15.jar:/QIBM/ProdData/OS400/jt400/lib/jt400Native.jar C3P0Main
// c3p0.acquireRetryAttempts=0
// c3p0.acquireRetryDelay=5000
// c3p0.breakAfterAcquireFailure=false
// c3p0.maxConnectionAge=10800
// c3p0.maxIdleTime=3600
// c3p0.maxIdleTimeExcessConnections=600
// c3p0.automaticTestTable=c3p0test
// c3p0.idleConnectionTestPeriod=600
// c3p0.testConnectionOnCheckout=true
// java -cp :./c3p0-0.9.5.4.jar:./mchange-commons-java-0.2.15.jar:./jt400.jar -Dc3p0.acquireRetryAttempts=0 -Dc3p0.acquireRetryDelay=5000 -Dc3p0.breakAfterAcquireFailure=false -Dc3p0.maxConnectionAge=10800 -Dc3p0.maxIdleTime=3600 -Dc3p0.maxIdleTimeExcessConnections=600 -Dc3p0.automaticTestTable=c3p0test -Dc3p0.idleConnectionTestPeriod=600 -Dc3p0.testConnectionOnCheckout=true C3P0Main
public class C3P0Main {
private Connection m_dbConnection;
private ComboPooledDataSource m_cpds;
private String driverClassName = "com.ibm.as400.access.AS400JDBCDriver";
//private String m_DatabaseConnectionString = "jdbc:as400:BNADEV;naming=sql;extended metadata=true;user=beak;password=roatan12";
private String m_DatabaseConnectionString = "jdbc:as400:BNADEV;naming=sql;extended metadata=true";
private String m_databaseServerJobID;
public C3P0Main() throws SQLException
{
m_cpds = new ComboPooledDataSource();
try {
m_cpds.setDriverClass(driverClassName); //loads the jdbc driver
}
catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
m_cpds.setJdbcUrl(m_DatabaseConnectionString);
}
public void run(String[] args) throws Exception
{
m_dbConnection = m_cpds.getConnection();
System.out.println("m_dbConnection=" + m_dbConnection.toString());
String qualifiedName = "";
try {
// To use it, first cast the returned Connection to a C3P0ProxyConnection.
// Then call the method rawConnectionOperation, supplying the java.lang.reflect.Method object
// for the non-standard method you wish to call as an argument. The Method you supply will
// be invoked on the target you provide on the second argument (null for static methods),
// and using the arguments you supply in the third argument to that function. For the target,
// and for any of the method arguments, you can supply the special token
// C3P0ProxyConnection.RAW_CONNECTION, which will be replaced with the
// underlying vendor-specific Connection object before the Method is invoked.
//
// C3P0ProxyConnection castCon = (C3P0ProxyConnection) c3p0DataSource.getConnection();
// Method m = CLOB.class.getMethod("createTemporary", new Class[]{Connection.class, boolean.class, int.class});
// Object[] args = new Object[] {C3P0ProxyConnection.RAW_CONNECTION, Boolean.valueOf( true ), new Integer( 10 )};
// CLOB oracleCLOB = (CLOB) castCon.rawConnectionOperation(m, null, args);
// getServerJobIdentifier, public abstract java.lang.String com.ibm.as400.access.AS400JDBCConnection.getServerJobIdentifier()
System.out.println("Is a wrapper for DB2Connection=" + m_dbConnection.isWrapperFor(com.ibm.db2.jdbc.app.DB2Connection.class));
System.out.println("Is a wrapper for AS400JDBCConnection=" + m_dbConnection.isWrapperFor(AS400JDBCConnection.class));
C3P0ProxyConnection castCon = (C3P0ProxyConnection)m_dbConnection;
System.out.println("C3P0ProxyConnection.RAW_CONNECTION=" + C3P0ProxyConnection.RAW_CONNECTION.getClass().getName());
Method method = AS400JDBCConnection.class.getMethod("getServerJobIdentifier");
System.out.println("method=" + method.toString());
Object[] method_args = new Object[] {};
System.out.println("calling rawConnectionOperation");
try {
qualifiedName = (String) castCon.rawConnectionOperation(method, m_dbConnection, method_args);
System.out.println("qualifiedName=" + qualifiedName);
}
catch (IllegalArgumentException | SQLException | InvocationTargetException | IllegalAccessException e) {
System.out.println(e);
System.out.println("oh well #1.");
}
try {
Object[] method_args = new Object[] {};
qualifiedName = (String) castCon.rawConnectionOperation(method, m_dbConnection, method_args);
System.out.println("qualifiedName=" + qualifiedName);
}
catch (IllegalArgumentException | SQLException | InvocationTargetException | IllegalAccessException e) {
System.out.println(e);
System.out.println("oh well #2.");
}
if (castCon instanceof AS400JDBCConnection) {
System.out.println("YES");
qualifiedName = ((AS400JDBCConnection)C3P0ProxyConnection.RAW_CONNECTION).getServerJobIdentifier();
String jobName = qualifiedName.substring(0, 10).trim();
String jobUser = qualifiedName.substring(10, 20).trim();
String jobNumber = qualifiedName.substring(20).trim();
m_databaseServerJobID = jobNumber + '/' + jobUser + '/' + jobName;
System.out.println("SQL Server Job ID: " + m_databaseServerJobID);
}
else {
System.out.println("m_dbConnection is not an instance of DB2Connection.");
}
}
catch (IllegalArgumentException | SQLException | NoSuchMethodException e) {
System.out.println(e);
System.out.println("oh well.");
}
}
public static void main(java.lang.String args[])
{
try {
C3P0Main app = new C3P0Main();
app.run(args);
}
catch (Exception e) {
e.printStackTrace();
}
}
}

How can I decide if the game I coded using JavaFX uses adequate system resources?

I have coded a simple card game (using IntelliJ 3.3) that updates gui each second and contains many nodes in game which are used to display game events and animation. People who have tried the game said that their system slows down and memory and cpu usage goes up (I was shocked when I saw from one of my friend's screen that it used around 1.4 GB ram) is this supposed to happen?
I have checked some questions related to javaFX memory usage problems but could not relate to my matter. In one article, I read that using many nodes in a JavaFX game might result in high memory usage.
in a short runtime:
minimum memory usage is around 100-250 MB
maximum memory usage is around 800-1200 MB
average memory usage is around 500-700 MB
IMPORTANT:
THERE ARE 100 BUTTONS IN A 10X10 GRIDPANE WHICH DO NOT HAVE FX IDS
in gameButtonClicked matches are found buttons.indexOf(event.getSource())
UML DIAGRAM
Main.java
IMPORTS:
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
public class Main extends Application {
static boolean isMuted;
static Stage window;
static MediaPlayer mediaPlayerBGM;
static MediaPlayer mediaPlayerSFX;
private static HashMap<String, Media> sounds;
private static ArrayList<Long> usage;
private final String[] SOUND_LIST = {"bgm_credits.mp3", "bgm_game.mp3", "bgm_game_1.mp3", "bgm_game_2.mp3", "bgm_game_3.mp3",
"bgm_how_to.mp3", "bgm_menu.mp3", "bgm_victory.mp3", "sfx_button_clicked.wav",
"sfx_card_unfold.wav", "sfx_toggle.wav"
};
public static void main(String[] args) {
launch(args);
AtomicLong sum = new AtomicLong();
usage.forEach(sum::addAndGet);
long average = sum.get() / usage.size();
System.out.printf("minimum usage: %d, maximum usage: %d, average usage: %d",
Collections.min(usage), Collections.max(usage), average);
}
static void playBGM(String key) {
mediaPlayerBGM.stop();
mediaPlayerBGM.setStartTime(Duration.ZERO);
if (key.equals("bgm_game")) {
String[] suffix = {"", "_1", "_2", "_3"};
Random random = new Random();
mediaPlayerBGM = new MediaPlayer(sounds.get(key + suffix[random.nextInt(4)]));
} else {
mediaPlayerBGM = new MediaPlayer(sounds.get(key));
}
mediaPlayerBGM.setCycleCount(MediaPlayer.INDEFINITE);
if (isMuted) {
mediaPlayerBGM.setVolume(0.0);
}
mediaPlayerBGM.play();
}
static void playSFX(String key) {
if (mediaPlayerSFX != null) {
mediaPlayerSFX.stop();
}
mediaPlayerSFX = new MediaPlayer(sounds.get(key));
if (isMuted) {
mediaPlayerSFX.setVolume(0.0);
}
mediaPlayerSFX.play();
}
#Override
public void start(Stage primaryStage) throws Exception {
sounds = new HashMap<>();
usage = new ArrayList<>();
isMuted = false;
for (String soundName :
SOUND_LIST) {
URL resource = getClass().getResource("/" + soundName);
System.out.println(soundName);
System.out.println(resource.toString());
sounds.put(soundName.substring(0, soundName.lastIndexOf('.')), new Media(resource.toString()));
}
mediaPlayerBGM = new MediaPlayer(sounds.get("bgm_menu"));
mediaPlayerBGM.setCycleCount(MediaPlayer.INDEFINITE);
mediaPlayerBGM.play();
window = primaryStage;
Parent root = FXMLLoader.load(getClass().getResource("menu.fxml"));
// long running operation runs on different thread
Thread thread = new Thread(() -> {
Runnable updater = () -> {
if (!Game.isGameIsOver() && Game.getScore() != 0 && window.getTitle().equals("The Main Pick") &&
Game.firstClickHappened()) {
Game.scoreCalculator();
}
};
while (true) {
try {
usage.add(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
System.out.printf("Used memory: %d\n", Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
Thread.sleep(1000);
} catch (InterruptedException ex) {
System.out.println("Interrupted");
}
// UI update is run on the Application thread
Platform.runLater(updater);
}
});
// don't let thread prevent JVM shutdown
thread.setDaemon(true);
thread.start();
window.setTitle("Main Menu");
window.setScene(new Scene(root, 600, 600));
window.setResizable(false);
window.show();
}
}
Controller.java
IMPORTS:
package com.sample;
import javafx.animation.FadeTransition;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
importjavafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.layout.GridPane;
import javafx.util.Duration;
import java.io.IOException;
public class Controller
{
#FXML
public RadioButton musicOnOff;
#FXML
public Button newGame;
#FXML
public Button howTo;
#FXML
public Button credits;
#FXML
public Button exit;
#FXML
public Button menu;
#FXML
public GridPane pane;
#FXML
public Label score;
#FXML
public Label time;
#FXML
public Label tries;
private boolean animating;
public void initialize() {
if (score != null && time != null && tries != null) {
score.textProperty().bind(Game.scoreProperty);
time.textProperty().bind(Game.timeProperty);
tries.textProperty().bind(Game.triesProperty);
animating=false;
}
if (musicOnOff!=null){
if(Main.isMuted){
musicOnOff.setSelected(true);
}
}
}
public void newGameButtonClicked() {
try {
Main.playSFX("sfx_button_clicked");
new Game();
Main.window.hide();
Main.window.setScene(getScene("game"));
Main.window.setTitle("The Main Pick");
Main.window.setMaximized(true);
Main.playBGM("bgm_game");
Main.window.show();
} catch (IOException e) {
System.out.println("could not change the scene to: game");
}
}
public void menuButtonClicked() {
try {
Main.playSFX("sfx_button_clicked");
Main.playBGM("bgm_menu");
if (Main.window.getTitle().equals("The Main Pick")) {
Main.window.hide();
Game.setGameOver();
Main.window.setScene(getScene("menu"));
Main.window.setMaximized(false);
Main.window.show();
} else {
Main.window.setScene(getScene("menu"));
}
Main.window.setTitle("Main Menu");
} catch (IOException e) {
System.out.println("could not change the scene to: game");
}
}
public void gameButtonClicked(ActionEvent event) {
ObservableList<Node> buttons = pane.getChildren();
int index = buttons.indexOf(event.getSource());
int column = index % 10;
int row = (index - index % 10) / 10;
if (!((Button) event.getSource()).getStyleClass().toString().equals("button button-treasure") &&
!((Button) event.getSource()).getStyleClass().toString().equals("button button-uncovered"))
{
FadeTransition transition = new FadeTransition();
transition.setNode((Button) event.getSource());
transition.setDuration(new Duration(500));
transition.setFromValue(1.0);
transition.setToValue(0.0);
transition.setCycleCount(1);
transition.setOnFinished(actionEvent -> {
if (((Button) event.getSource()).getStyleClass().toString().equals("button button-treasure")) {
loadVictoryScene();
}
if (!((Button) event.getSource()).getStyleClass().toString().equals("button button-treasure") &&
!((Button) event.getSource()).getStyleClass().toString().equals("button button-uncovered"))
{
transition.setFromValue(0.0);
transition.setToValue(1.0);
System.out.println(((Button) event.getSource()).getStyleClass().toString());
((Button) event.getSource()).getStyleClass().remove("button-covered");
((Button) event.getSource()).getStyleClass().add(Game.click(row, column));
transition.play();
transition.setOnFinished(ActionEvent->animating=false);
}
});
System.out.println(animating);
if(!animating){
animating=true;
transition.play();
Main.playSFX("sfx_card_unfold");}
}
System.out.printf("button index:%d,row:%d,column:%d\n", index, row, column);
}
public void howToPlayButtonClicked() {
try {
Main.playSFX("sfx_button_clicked");
Main.playBGM("bgm_how_to");
Main.window.setScene(getScene("howTo"));
Main.window.setTitle("How to Play");
} catch (IOException e) {
System.out.println("could not change the scene to: how to play");
}
}
public void creditsButtonClicked() {
try {
Main.playSFX("sfx_button_clicked");
Main.playBGM("bgm_credits");
Main.window.setScene(getScene("credits"));
Main.window.setTitle("Credits");
} catch (IOException e) {
System.out.println("could not change the scene to: credits");
}
}
public void exitButtonClicked() {
Main.playSFX("sfx_button_clicked");
Main.window.close();
}
public void musicOnOffRadioButtonChecked() {
Main.playSFX("sfx_toggle");
if (musicOnOff.isSelected()) {
Main.isMuted=true;
Main.mediaPlayerBGM.setVolume(0.0);
Main.mediaPlayerSFX.setVolume(0.0);
System.out.println("now selected");
} else {
Main.isMuted=false;
Main.mediaPlayerBGM.setVolume(1.0);
Main.mediaPlayerSFX.setVolume(1.0);
System.out.println("unselected");
}
}
private void loadVictoryScene() {
try {
Main.window.hide();
Main.playBGM("bgm_victory");
Main.window.setScene(getScene("victory"));
Main.window.setTitle("Victory");
Main.window.setMaximized(false);
Main.window.show();
} catch (IOException e) {
System.out.println("could not change the scene to: victory");
}
}
private Scene getScene(String name) throws IOException {
Parent root = FXMLLoader.load(getClass().getResource(name + ".fxml"));
if (name.equals("game")) {
return new Scene(root, 800, 800);
}
return new Scene(root, 600, 600);
}
}
Game.java
IMPORTS:
package com.sample;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import java.util.Random;
public class Game {
static StringProperty scoreProperty;
static StringProperty timeProperty;
static StringProperty triesProperty;
private static int time;
private static int score;
private static int tries;
private static int[][] tiles;
private static boolean gameIsOver;
private static boolean firstClick;
public Game() {
System.out.println("Game created...");
tries = 0;
score = 100000;
time = 0;
gameIsOver = false;
firstClick = false;
scoreProperty = new SimpleStringProperty("" + score);
timeProperty = new SimpleStringProperty("0");
triesProperty = new SimpleStringProperty("0");
tiles = new int[10][10];
Random random = new Random();
int treasureColumn = random.nextInt(10);
int treasureRow = random.nextInt(10);
tiles[treasureRow][treasureColumn] = 1;
}
static boolean firstClickHappened() {
return firstClick;
}
static void setGameOver() {
gameIsOver = true;
}
static boolean isGameIsOver() {
return gameIsOver;
}
static int getScore() {
return score;
}
static void scoreCalculator() {
time++;
if (time < 10) {
score = score - 100;
} else if (time < 20) {
score = score - 200;
} else if (time < 30) {
score = score - 300;
} else if (time < 50) {
score = score - 500;
} else {
score = score - 1000;
}
if (score < 0) {
score = 0;
}
scoreProperty.setValue("" + score);
timeProperty.setValue("" + time);
triesProperty.setValue("" + tries);
System.out.printf("Score:%s,Time:%s,Tries%s\n", scoreProperty.getValue(), timeProperty.getValue(), triesProperty.getValue());
}
static String click(int row, int column) {
if (!firstClickHappened()) firstClick = true;
System.out.println(row + "," + column);
int clickValue = tiles[row][column];
System.out.println(clickValue);
if (clickValue == 0) {
tries++;
score -= 1000;
} else {
setGameOver();
}
return (clickValue == 1) ? "button-treasure" : "button-uncovered";
}
}

CannotCompileException while Instrumenting Java code with using Java Assist, cannot find class

I'm trying create a generic Java Agent to instrument any Java application's methods.
I've followed this tutorial https://javapapers.com/core-java/java-instrumentation/ and created a java agent.
The java agent is supposed to look for a particular class ( I'm restricting it to one class now since it's not working for me)
Once the class is found, I'm using JavaAssist API to add a local variable to the beginning of each method and capture the current time. In the end of the method I'd like to simply print the time it took for the method to execute. (Pretty much following all the typical examples about Java agent.
I run my test application ( a web server using Vert.x ) with --javaagent flag pointing to the Java agent jar file I created ( the code is down below).
This works just fine for methods that either don't have return value and no parameters or return/take a primitive type.
However when a method is returning or taking a parameter that is an object from a another class (that has not been loaded yet I think) I get a CannotCompileException exception with the message that that class which is in the parameters list or in the return statement is not found.
For example the instrumentation for this method works:
#Override
public void start() throws Exception {
logger.debug("started thread {}", Thread.currentThread().getName());
for (int port : ports) {
HttpServer httpServer = getVertx().createHttpServer(httpServerOptions);
Router router = setupRoutes();
httpServer.requestHandler(router::accept);
logger.info("Listening on port {}", port);
httpServer.listen(port);
}
}
However for this method that returns io.vertx.ext.web.Router:
private Router setupRoutes() {
Router router = Router.router(getVertx());
router.get(STATUS_PATH).handler(this::statusHandler);
router.route().handler(BodyHandler.create());
router.post().handler(this::handleBidRequest);
router.put().handler(this::handleBidRequest);
router.get(SLEEP_CONTROLLER_PATH).handler(this::sleepControllerHandler);
return router;
}
I get an exception and the output of my java agent is :
Instrumenting method rubiconproject.com.WebServerVerticle.setupRoutes()
Could not instrument method setupRoutes error: cannot find io.vertx.ext.web.Router
This the code for my java agent:
import java.lang.instrument.Instrumentation;
import transformers.TimeMeasuringTransformer;
public class TimeCapturerAgent {
public static void premain(String agentArgs, Instrumentation inst) {
System.out.println(TimeCapturerAgent.class.getCanonicalName() + " is loaded...... ");
inst.addTransformer(new TimeMeasuringTransformer());
}}
package transformers;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
public class TimeMeasuringTransformer implements ClassFileTransformer {
public TimeMeasuringTransformer() {
System.out.println("TimeMeasuringTransformer added ");
}
#Override
public byte[] transform(ClassLoader loader,
String className,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] classfileBuffer) throws IllegalClassFormatException {
if(className != null && className.contains("WebServerVerticle")) {
System.out.println("Instrumenting class " + className);
return modifyClass(classfileBuffer);
}
return null;
}
private byte[] modifyClass(byte[] originalClassfileBuffer) {
ClassPool classPool = ClassPool.getDefault();
CtClass compiledClass;
try {
compiledClass = classPool.makeClass(new ByteArrayInputStream(originalClassfileBuffer));
System.out.println("Created new compiled Class " + compiledClass.getName());
} catch (IOException e) {
e.printStackTrace();
return null;
}
instrumentMethods(compiledClass);
byte [] newClassByteCode = createNewClassByteArray(compiledClass);
compiledClass.detach();
return newClassByteCode;
}
private byte[] createNewClassByteArray(CtClass compiledClass) {
byte[] newClassByteArray = null;
try {
newClassByteArray = compiledClass.toBytecode();
} catch (IOException e) {
e.printStackTrace();
} catch (CannotCompileException e) {
e.printStackTrace();
} finally {
return newClassByteArray;
}
}
private void instrumentMethods(CtClass compiledClass) {
CtMethod[] methods = compiledClass.getDeclaredMethods();
System.out.println("Class has " + methods.length + " methods");
for (CtMethod method : methods) {
try {
System.out.println("Instrumenting method " + method.getLongName());
method.addLocalVariable("startTime", CtClass.longType);
method.insertBefore("startTime = System.nanoTime();");
method.insertAfter("System.out.println(\"Execution Duration "
+ "(nano sec): \"+ (System.nanoTime() - startTime) );");
} catch (CannotCompileException e) {
System.out.println("Could not instrument method " + method.getName()+" error: " + e.getMessage());
continue;
}
}
}}

Ignite dataStreamer is not working

I am exploring Ignite dataStreamer with the following code.
But the output is:
For MessageKey0001, the output all displays data is null.
For MessageKey0003, the output also all displays data is null
For MessageKey0002, the output shows nothing, looks that receiver code is not run
When I change
dataStreamer.addData(i, "data-" + i);
to
IgniteFuture future = dataStreamer.addData(i, "data-" + i);
future.get();
The future.get() doesn't return, looks addData doesn't finish anyway?
I am not sure where the problem is, can someone take a look? Thanks!
package ignite.streamer;
import org.apache.ignite.*;
import org.apache.ignite.cache.query.annotations.QuerySqlField;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.stream.StreamReceiver;
import javax.cache.Cache;
import java.io.Serializable;
import java.util.Collection;
import java.util.Map;
class IgniteDataStreamer_Person implements Serializable {
#QuerySqlField(index = true)
private String name;
#QuerySqlField(index = true)
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class IgniteDataStreamerTest {
public static void main(String[] args) {
String configPath = "D:/Software/apache-ignite-fabric-1.7.0-bin/apache-ignite-fabric-1.7.0-bin/config/default-config.xml";
Ignite ignite = Ignition.start(configPath);
CacheConfiguration<Integer, String> cfg = new CacheConfiguration<Integer, String>();
String cacheName = "stream_cache";
cfg.setName(cacheName);
cfg.setIndexedTypes(Integer.class, IgniteDataStreamer_Person.class);
Cache cache = ignite.getOrCreateCache(cfg);
IgniteDataStreamer<Integer, String> dataStreamer = ignite.dataStreamer(cacheName);
for (int i = 0; i < 3; i++) {
dataStreamer.addData(i, "data-" + i);
}
//null is got from cache
for (int i = 0; i < 3; i++) {
System.out.println(String.format("0001: data is %s ", cache.get(i)));
}
dataStreamer.receiver(new StreamReceiver<Integer, String>() {
public void receive(IgniteCache<Integer, String> cache, Collection<Map.Entry<Integer, String>> entries) throws IgniteException {
//nothing is printed to console
for (Map.Entry<Integer, String> entry : entries) {
System.out.println(String.format("0002: key is: %s, value is: %s", entry.getKey(), entry.getValue()));
}
}
});
//null is got from cache
for (int i = 0; i < 3; i++) {
System.out.println(String.format("0003: data is %s ", cache.get(i)));
}
ignite.close();
}
}
DataStreamer uses batches in order to provide good performance. You should flush data in your case (use flush() method) before block on future.get() method.
Please, see IgniteDataStreamer javadocs for details.

J2ME connect localhost nullpointerexception 0

I am trying to connect localhost and insert data into database through j2me application.but when I am connecting the server it shows there is a nullpointerexception 0 error.
this is midlet code
import java.io.DataOutputStream;
import java.io.InputStream;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.midlet.*;
public class Midlet_1 extends MIDlet implements CommandListener {
Display mdDisplay;
Form mForm;
StringItem messageitem;
Command exit, connectCommand;
public Midlet_1() {
mForm = new Form("My Counter midlet");
messageitem = new StringItem(null, "");
exit = new Command("Exit", Command.EXIT, 0);
connectCommand = new Command("Connect", Command.SCREEN, 0);
mForm.append(messageitem);
mForm.addCommand(exit);
mForm.addCommand(connectCommand);
mForm.setCommandListener(this);
}
public void startApp() {
mdDisplay = Display.getDisplay(this);
mdDisplay.setCurrent(mForm);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable d) {
if (c == exit) {
notifyDestroyed();
} else if (c == connectCommand) {
Form waitform = new Form("Waiting");
mdDisplay.setCurrent(waitform);
Thread t = new Thread() {
public void run() {
connect();
}
};
t.start();
}
}
private void connect() {
try {
HttpConnection hs = null;
InputStream in = null;
String url = "localhost:8080/testweb/src/save";
hs.setRequestProperty("User-Agent", "Profile/MIDP-2.0,Configuration/CLDC-2.0");
hs.setRequestProperty("Content-Language", "en-US");
hs.setRequestMethod(HttpConnection.POST);
DataOutputStream ds = hs.openDataOutputStream();
ds.writeUTF("nam56");
ds.writeUTF("67");
ds.writeUTF("0716522549");
ds.flush();
ds.close();
in = hs.openInputStream();
int connectlength = (int) hs.getLength();
byte[] raw = new byte[connectlength];
int length = in.read(raw);
// int ch;
// StringBuffer sb=new StringBuffer();
// while((ch=in.read())!=-1){
// sb.append((char)ch);
// }
in.close();
hs.close();
String s = new String(raw, 0, length);
messageitem.setText(s);
} catch (Exception e) {
messageitem.setText(e.toString());
System.out.println(e);
}
mdDisplay.setCurrent(mForm);
}
}
and this is servlet code
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ClassNotFoundException, SQLException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
DataInputStream in=new DataInputStream(request.getInputStream());
String name=in.readUTF();
String id=in.readUTF();
String contt=in.readUTF();
Connection c=DBcon.setconConnection();
Statement s=c.createStatement();
s.executeUpdate("insert into details values('"+id+"','"+name+"''"+contt+"')");
out.print("successfullllll");
} finally {
out.close();
}
}
please check this out.....
This might work only if you are running an emulator on the same machine as the server. Try to replace locahost by 127.0.0.1.
In your connect() method, I can see that you initialized hs as null then you called setRequestProperty. Try to initialize hs properly before calling its methods.