I have two programs for my project. I would like to run program1 via program2 as a thread. I tried extending the Thread class in program1 but, I am getting whole lot of errors:
public void main(String[] args) {
Void is an invalid type for the variable main.
private static void start(Result result) {
Void is an invalid type for the variable start.
Program 1:
public class HelloWorld extends Thread {
private String[] args;
public HelloWorld(String[] args){
this.args = args;
}
int i=1;
String resultText;
try {
URL url;
if (args.length > 0) {
url = new File(args[0]).toURI().toURL();
}
else {
url = HelloWorld.class.getResource("helloworld.config.xml");
}
ConfigurationManager cm = new ConfigurationManager(url);
Recognizer recognizer = (Recognizer) cm.lookup("recognizer");
Microphone microphone = (Microphone) cm.lookup("microphone");
recognizer.allocate();
if (microphone.startRecording()) {
while (true) {
System.out.println("Start speaking. Press Ctrl-C to quit.\n");
Result result = recognizer.recognize();
}
}
else {
System.out.println("Cannot start microphone.");
recognizer.deallocate();
System.exit(1);
}
}
catch (IOException e) {
System.err.println("Problem when loading HelloWorld: " + e);
e.printStackTrace();
}
}
private static void start_recognition(Result result) {
if (result != null)
{
resultText = result.getBestFinalResultNoFiller();
System.out.println("You said: " + resultText + "\n");
if(resultText.equalsIgnoreCase("Command Prompt"))
{
try{
Runtime.getRuntime().exec("cmd /c start cmd");
}
catch(Exception er){
}
}
}
}
}
}
Program 2:
public class App {
public static void main(String[] args) {
HelloWorld obj = new HelloWorld(args);
obj.start();
}
}
How can I run program1 as a thread via program2?
Update of code after suggestions:
public class HelloWorld extends Thread{
public void run() {
int i=1;
String resultText;
try {
URL url;
if (args.length > 0) { // Getting error in this line
args cannot be resolved to a variable.
url = new File(args[0]).toURI().toURL(); // And the same error in this line
}
else {
url = HelloWorld.class.getResource("helloworld.config.xml");
}
ConfigurationManager cm = new ConfigurationManager(url);
Recognizer recognizer = (Recognizer) cm.lookup("recognizer");
Microphone microphone = (Microphone) cm.lookup("microphone");
recognizer.allocate();
if (microphone.startRecording()) {
while (true) {
System.out.println("Start speaking. Press Ctrl-C to quit.\n");
Result result = recognizer.recognize();
start_recognition(result);
}
}
else {
System.out.println("Cannot start microphone.");
recognizer.deallocate();
System.exit(1);
}
}
catch (IOException e) {
System.err.println("Problem when loading HelloWorld: " + e);
e.printStackTrace();
}
}
private void start_recognition(Result result) {
{
if (result != null)
{
String resultText = result.getBestFinalResultNoFiller();
System.out.println("You said: " + resultText + "\n");
if(resultText.equalsIgnoreCase("Command Prompt"))
{
try{
Runtime.getRuntime().exec("cmd /c start cmd");
}
catch(Exception er){
}
}
}
}
}
}
In your class HelloWorld, get rid of public void main(String[] args)
It should look like this:
public class HelloWorld extends Thread {
public void run() {
int i=1;
String resultText;
try {
URL url;
if (args.length > 0) {
url = new File(args[0]).toURI().toURL();
}
else {
url = HelloWorld.class.getResource("helloworld.config.xml");
}
For further information, please refer to this link: Java Class
Related
Using code examples from stockoverflow I made a class to receive data over TCP/IP.
Class code below. It is working OK and I do receive data from other PC.
recPositions Map is build correctly. After transmission is finished I can display all data I received using getRecPositions()
This thread is started in other class that build simple HMI screen.
Thread runs and display data received from other PC.
Problem is I would like to access same data in MainWindow class (HMI)
but it always show that nothing was received.
Class MainWindow below (not all of it since there is lots of useless pushbuttons and so on)
At the very bottom I have pushbutton that should display how many positions were recorded (elements in Map) but it always show 0.
Code snippet from push button update.
System.out.println(dataServer.getRecPositions().size())
So at some point I am doing something wrong.
Thread starts and runs and I can see incoming positions. At some point after I received "EOT" I display received positions stored in Map. But when I tried to display the size of Map in main window it always show 0.
/*
* Simple data server for receiving string data from IIWA robot
*/
public class SimpleDataServer implements Runnable {
Map<Integer, String> recPositions = new HashMap<>();
Server1Connection oneconnection;
ServerSocket echoServer = null;
Socket clientSocket = null;
int port;
boolean reset = false;
public SimpleDataServer( int port ) {
this.port = port;
}
public void stopServer() {
System.out.println( "Simple data server stopped" );
}
public void startServer() {
// Try to open a server socket on the given port
// Note that we can't choose a port less than 1024 if we are not
// privileged users (root)
try {
echoServer = new ServerSocket(port);
}
catch (IOException e) {
System.out.println(e);
}
System.out.println( "Waiting for connections. Only one connection is allowed." );
// Create a socket object from the ServerSocket to listen and accept connections.
// Use Server1Connection to process the connection.
while ( true ) {
try {
clientSocket = echoServer.accept();
oneconnection = new Server1Connection(clientSocket, this);
oneconnection.run();
if(isReset()) {
setReset(false);
System.out.println("Recording finished");
System.out.println("DEBUG:" + this.getRecPositions().size() + " positions recorded: " + this.getRecPositions());
}
}
catch (IOException e) {
System.out.println(e);
}
}
}
#Override
public void run() {
int port = this.port;
SimpleDataServer server = new SimpleDataServer( port );
server.startServer();
}
public Map<Integer, String> getRecPositions() {
return recPositions;
}
public void setRecPositions(Map<Integer, String> recPositions) {
this.recPositions = recPositions;
}
public boolean isReset() {
return reset;
}
public void setReset(boolean reset) {
this.reset = reset;
}
}
class Server1Connection {
BufferedReader is;
PrintStream os;
Socket clientSocket;
SimpleDataServer server;
public Server1Connection(Socket clientSocket, SimpleDataServer server) {
this.clientSocket = clientSocket;
this.server = server;
System.out.println( "Connection established with: " + clientSocket );
try {
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
os = new PrintStream(clientSocket.getOutputStream());
} catch (IOException e) {
System.out.println(e);
}
}
public Map<Integer, String> getPositions() {
return server.getRecPositions();
}
public void run() {
String line; //whole line recevied
String segment = null; //single segment from line using comma delimiter
List<String> stringsList;
try {
boolean serverStop = false;
//server runs here
while (true)
{
line = is.readLine();
System.out.println( "DEBUG Server Received: " + line );
//check is string is not empty
if (line.equals(null)) {
System.err.println("Empty String received");
break;
}
stringsList = new ArrayList<String>(Arrays.asList(line.split(";")));
if (!stringsList.isEmpty()) {
stringsList.set(0, stringsList.get(0).replaceAll("\\s+",""));
stringsList.set((stringsList.size()-1), stringsList.get(stringsList.size()-1).replaceAll("\\s+",""));
String lastSegment = stringsList.get((stringsList.size()-1));
if (lastSegment.equals("ETX") || lastSegment.equals("EOT")) {
switch (stringsList.get(0)) {
case "MSG":
stringsList.remove(0);
stringsList.remove(stringsList.size()-1);
System.out.println("Message: " + stringsList.toString());
break;
case "POS":
// for (String blah : stringsList) {
// System.out.println("DEBUG" + blah);
// }
iiwaPosfromString iiwaPos = new iiwaPosfromString(stringsList.get(1), stringsList.get(2));
System.out.println("DEBUG Position number: " + iiwaPos.posNum + " ; " + iiwaPos.toString());
if (iiwaPos.getPosNum() > 0) {
server.getRecPositions().put(iiwaPos.getPosNum(), iiwaPos.toString());
}
break;
case "EOT":
case "EXT":
//ignore handled later
break;
default:
System.err.println("Ausgebombt!");
break;
}
}
//ETX End Of Text - dump data to screen - close current connection
if(lastSegment.equals("ETX")) {
System.out.println("End of Text received");
break;
}
//EOT End Of Transmission - shuts down server
if(lastSegment.equals("EOT")) {
System.out.println("End of Transmission received");
serverStop = true;
server.setReset(true);
break;
}
System.err.println("No correct end string!");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
} else {
System.out.println("Empty String received");
break;
}
}
System.out.println( "Connection closed." );
is.close();
os.close();
clientSocket.close();
if ( serverStop ) server.stopServer();
} catch (IOException e) {
System.out.println(e);
}
}
public class iiwaPosfromString {
private double posX;
private double posY;
private double posZ;
private double posA;
private double posB;
private double posC;
private int posNum;
public iiwaPosfromString(String posNum, String posString) {
List <String>stringsList = new ArrayList<String>(Arrays.asList(posString.split(" ")));
for (int i = 0; i < stringsList.size(); i++) {
String newElement = stringsList.get(i);
newElement = newElement.replaceAll("[^\\d.]", "");
stringsList.set(i, newElement);
}
this.setPosNum(Integer.parseInt(posNum));
this.setPosX(Double.parseDouble(stringsList.get(1)));
this.setPosY(Double.parseDouble(stringsList.get(2)));
this.setPosZ(Double.parseDouble(stringsList.get(3)));
//this is stupid and don't do that
//from right to left, string to double, change radians to degrees, format to two decimals(string), string to double again
this.setPosA(Double.parseDouble(String.format("%.2f",(Math.toDegrees(Double.parseDouble(stringsList.get(4)))))));
this.setPosB(Double.parseDouble(String.format("%.2f",(Math.toDegrees(Double.parseDouble(stringsList.get(4)))))));
this.setPosC(Double.parseDouble(String.format("%.2f",(Math.toDegrees(Double.parseDouble(stringsList.get(4)))))));
}
public double getPosX() {
return posX;
}
public void setPosX(double posX) {
this.posX = posX;
}
public double getPosY() {
return posY;
}
public void setPosY(double posY) {
this.posY = posY;
}
public double getPosZ() {
return posZ;
}
public void setPosZ(double posZ) {
this.posZ = posZ;
}
public double getPosA() {
return posA;
}
public void setPosA(double posA) {
this.posA = posA;
}
public double getPosB() {
return posB;
}
public void setPosB(double posB) {
this.posB = posB;
}
public double getPosC() {
return posC;
}
public void setPosC(double posC) {
this.posC = posC;
}
#Override
public String toString() {
return "<" +
"X: " + getPosX() + ", " +
"Y: " + getPosY() + ", " +
"Z: " + getPosZ() + ", " +
"A: " + getPosA() + ", " +
"B: " + getPosB() + ", " +
"C: " + getPosC() +
">";
}
public int getPosNum() {
return posNum;
}
public void setPosNum(int posNum) {
this.posNum = posNum;
}
}
}
public class MainWindow {
private Thread dataServerThread;
private SimpleDataServer dataServer;
private XmlParserGlobalVarsRD globalVarPLC, globalVarKRC;
private JFrame frame;
private JTextField simpleWorkingDirStiffness;
private JTextField simpleWorkingDirAdditionalForce;
private JTextField simpleTravelDistance;
private JTextField simpleTravelVelocity;
private JTextField simpleTotalTime;
private JTextField simpleTheoreticalDepth;
private JTextField simpleZProgress;
private JComboBox oscillationMode;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
final JCheckBox emptyScanCycle = new JCheckBox("VRSI Scan Cycle Plain Fasteners");
//set data server thread and start it
dataServer = new SimpleDataServer(30008);
dataServerThread = new Thread(dataServer);
dataServerThread.setDaemon(true);
dataServerThread.start();
...
JButton pbUpdate = new JButton("UPDATE");
pbUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println(dataServer.getRecPositions().size())
}
});
pbUpdate.setBounds(210, 176, 90, 28);
frame.getContentPane().add(pbUpdate);
}
I believe the issue is in your SimpleDataServer.run method. You are creating a separate instance of SimpleDataServer from WITHIN your SimpleDataServer instance. Therefore, all of the communication is taking place in an object that your MainWindow has no direct reference to. I believe your SimpleDataServer.run method should look like this:
#Override
public void run() {
this.startServer();
}
I am trying to create a simple messenger application between two computers, client to server. I have created the necessary port forwards. I have two programs - one for the server and one for the client - when I test them both on my machine from my IDE (Netbeans) they work (the streams are established and I am able to send messages to and fro). But when I run the jar files (again on the same computer) the streams are established between the two programs but then are immediately disconnected since and EOFException is given.
Below please find the code in the Client program and after that the Server program
Client Program
public class ClientGUI extends javax.swing.JFrame {
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private final String serverIP = "46.11.85.22";
private Socket connection;
Sound sound;
int idx;
File[] listOfFiles;
String songs[];
public ClientGUI() {
super("Client");
initComponents();
this.setVisible(true);
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
new Thread() {
#Override
public void run() {
try {
startRunning();
} catch (Exception e) {
System.out.println(e);
}
}
}.start();
}
public void startRunning() {
try {
connectToServer();
setupStreams();
whileChatting();
} catch (EOFException e) {
showMessage("\n " + (jtfUsername.getText()) + " terminated connection");
} catch (IOException IOe) {
IOe.printStackTrace();
} finally {
close();
}
}
private void connectToServer() throws IOException {
showMessage("Attempting Connection... \n");
connection = new Socket(InetAddress.getByName(serverIP), 8080);
showMessage("Connected to: " + connection.getInetAddress().getHostName());
}
private void setupStreams() throws IOException {
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\nStreams Estabished \n");
}
private void whileChatting() throws IOException {
ableToType(true);
do {
try {
message = (String) input.readObject();
File folder = new File("src/Files/");
listOfFiles = folder.listFiles();
songs = new String[listOfFiles.length];
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
songs[i] = listOfFiles[i].getAbsolutePath();
}
}
idx = new Random().nextInt(songs.length);
String clip = (songs[idx]);;
sound = new Sound(clip);
sound.play();
showMessage("\n" + message);
} catch (ClassNotFoundException e) {
showMessage("\n Exception occoured");
}
} while (!message.equals("SERVER - END"));
System.exit(0);
}
private void close() {
showMessage("\n Closing Application");
ableToType(false);
try {
output.close();
input.close();
connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendMessage(String message) {
try {
output.writeObject(jtfUsername.getText() + " - " + message);
output.flush();
showMessage("\n" + jtfUsername.getText() + " - " + message);
} catch (IOException e) {
jtaView.append("\n Exception Occoured");
}
}
private void showMessage(final String m) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
jtaView.append(m);
}
}
);
}
private void ableToType(final boolean tof) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
jtfSend.setEditable(tof);
}
}
);
}
Server Program
public class ServerGUI extends javax.swing.JFrame {
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
Sound sound;
int idx;
File[] listOfFiles;
String songs[];
public ServerGUI() {
super("Server");
this.setVisible(true);
initComponents();
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
new Thread() {
#Override
public void run() {
try {
startRunning();
} catch (Exception e) {
System.out.println(e);
}
}
}.start();
}
public void startRunning() {
try {
server = new ServerSocket(8080, 10);
while (true) {
try {
waitForConnection();
setupStreams();
whileChatting();
} catch (EOFException e) { // End of Stream
showMessage("\n Server ended the connection!");
} finally {
close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void waitForConnection() throws IOException {
showMessage("Waiting for client to connect... \n");
connection = server.accept();
showMessage("Now connected to " + connection.getInetAddress().getHostName());
}
private void setupStreams() throws IOException {
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\nStreams are setup \n");
}
private void whileChatting() throws IOException {
String message = "You are now connected!";
sendMessage(message);
ableToType(true);
do {
try {
message = (String) input.readObject();
File folder = new File("src/Files/");
listOfFiles = folder.listFiles();
songs = new String[listOfFiles.length];
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
songs[i] = listOfFiles[i].getAbsolutePath();
}
}
idx = new Random().nextInt(songs.length);
String clip = (songs[idx]);
sound = new Sound(clip);
sound.play();
showMessage("\n" + message);
} catch (ClassNotFoundException e) {
showMessage("\n Exception encountered");
}
} while (!message.contains("END"));
shutdown();
}
private static void shutdown() throws IOException {
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("shutdown -s -t 30");
System.exit(0);
}
private void close() {
showMessage("\n Closing connections... \n");
ableToType(false);
try {
output.close();
input.close();
connection.close();
} catch (IOException ioE) {
ioE.printStackTrace();
}
}
private void sendMessage(String message) {
try {
output.writeObject("SERVER - " + message);
output.flush();
showMessage("\nSERVER - " + message);
} catch (IOException ioE) {
jtaView.append("\n ERROR Sending");
}
}
private void showMessage(final String text) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
jtaView.append(text);
}
}
);
}
private void ableToType(final boolean tof) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
jtfSend.setEditable(tof);
}
}
);
}
I asked my computing teacher and he told me that it might be the ports that I'm using but it still didn't work with these ports when executing the jar files. Any ideas?
I am writing an apk analysis program. I cannot go deep into details because it's research material. However, the point is that from time to time when I execute the analysis routine, I get the following message:
Exception: java.lang.NullPointerException thrown from the UncaughtExceptionHandler in thread "main"
This happens if I do not override the UncaughtExceptionHandler and also if I do, as you'll see from the code below. Since there is no stacktrace data I cannot know where that exception is coming from and what its cause really is.
I hope you can help me...
This is only the main code. There are three main operation that I have to execute. In order not to disclose particular information, I renamed them to A, B and C
public class MainScannerSequential {
public static void main(String[] args) throws ParserConfigurationException, IOException, InterruptedException {
final File target = new File(args[1]);
final File result = new File(args[2]);
final Options options = new Options(args);
silentMode = options.contains("-s");
noA = options.contains("-nl");
noC = options.contains("-ne");
aStrategy = Factory.createA();
bScanner = Factory.createB();
cDetector = Factory.createcC();
examinedFiles = new PersistentFileList(Globals.EXAMINED_FILES_LIST_FILE);
if (result.exists())
resultsWriter = new BufferedWriter(new FileWriter(result, true));
else {
resultsWriter = new BufferedWriter(new FileWriter(result));
resultsWriter.write("***");
resultsWriter.newLine();
}
if (Globals.PERFORMANCE_FILE.exists())
performancesWriter = new BufferedWriter(new FileWriter(Globals.PERFORMANCE_FILE, true));
else {
performancesWriter = new BufferedWriter(new FileWriter(Globals.PERFORMANCE_FILE));
performancesWriter.write("***");
performancesWriter.newLine();
}
Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread t, Throwable e) {
if ((t != null) && (t.getName() != null))
System.out.println("In thread : " + t.getName());
if ((e != null) && (e.getMessage() != null)) {
System.out.println(e.getClass().getName() + ": " + e.getMessage());
if (e.getStackTrace() != null)
for (StackTraceElement ste : e.getStackTrace())
if (ste != null)
System.out.println(ste.getFileName() + " at line " + ste.getLineNumber());
}
}
});
if (target.isDirectory()) {
enumerateDirectory(target);
} else {
String name = target.getName().toLowerCase();
if (name.endsWith(".apklist"))
readFileList(target);
else if (name.endsWith(".apk"))
checkFile(target);
}
closeWriters();
}
private static void println(String message) {
if (!silentMode)
System.out.println(message);
}
private static void print(String message) {
if (!silentMode)
System.out.print(message);
}
private static void enumerateDirectory(File directory) {
for (File file : directory.listFiles()) {
checkFile(file);
if (file.isDirectory())
enumerateDirectory(file);
}
}
private static void readFileList(File file) {
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while((line = reader.readLine()) != null) {
File readFile = new File(line);
if (readFile.exists())
checkFile(readFile);
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void checkFile(File file) {
if (examinedFiles.contains(file)) {
println("Skipped: " + file.getName());
return;
}
if (!file.getName().toLowerCase().endsWith(".apk")) {
return;
}
final Wrapper<Double> unpackingTime = new Wrapper<Double>(0.0);
final ApplicationData data = unpack(file, unpackingTime);
if (data == null) {
return;
}
scanData(data, unpackingTime.value);
}
private static ApplicationData unpack(final File file, final Wrapper<Double> unpackingTime) {
final Wrapper<ApplicationData> resultWrapper = new Wrapper<ApplicationData>(null);
final Wrapper<Exception> exceptionWrapper = new Wrapper<Exception>(null);
println("Unpacking: " + file.getName());
unpackingTime.value = Stopwatch.time(new Runnable() {
#Override
public void run() {
try {
resultWrapper.value = ApplicationData.open(file);
} catch (Exception e) {
exceptionWrapper.value = e;
}
}
});
if (resultWrapper.value != null)
println("Unpacked: " + file.getName());
else if (exceptionWrapper.value != null)
println("Dropped: " + file.getName() + " : " + exceptionWrapper.value.getMessage());
return resultWrapper.value;
}
private static void scanData(final ApplicationData applicationData, Double unpackingTime) {
String apkName = applicationData.getDecodedPackage().getOriginalApk().getAbsolutePath();
println("Submitted: " + apkName);
examinedFiles.add(applicationData.getDecodedPackage().getOriginalApk());
final Wrapper<Boolean> aDetected = new Wrapper<Boolean>(false);
final Wrapper<Result> bDetected = new Wrapper<Result>(new Result());
final Wrapper<Boolean> cDetected = new Wrapper<Boolean>(false);
final Wrapper<Double> aDetectionTime = new Wrapper<Double>((double)ANALYSIS_TIMEOUT);
final Wrapper<Double> bDetectionTime = new Wrapper<Double>((double)ANALYSIS_TIMEOUT);
final Wrapper<Double> cDetectionTime = new Wrapper<Double>((double)ANALYSIS_TIMEOUT);
ExecutorService executor = Executors.newFixedThreadPool(3);
executor.submit(new Runnable() {
#Override
public void run() {
textDetectionTime.value = Stopwatch.time(new Runnable() {
#Override
public void run() {
bScanner.setUnpackedApkDirectory(applicationData.getDecodedPackage().getDecodedDirectory());
bDetected.value = bScanner.evaluate();
}
});
}
});
if (!noA)
executor.submit(new Runnable() {
#Override
public void run() {
lockDetectionTime.value = Stopwatch.time(new Runnable() {
#Override
public void run() {
aStrategy.setTarget(applicationData.getDecodedPackage());
aDetected.value = aStrategy.detect();
}
});
}
});
if (!noC)
executor.submit(new Runnable() {
#Override
public void run() {
encryptionDetectionTime.value = Stopwatch.time(new Runnable() {
#Override
public void run() {
cDetector.setTarget(applicationData.getDecodedPackage());
cDetected.value = cDetector.detect();
}
});
}
});
boolean timedOut = false;
executor.shutdown();
try {
if (!executor.awaitTermination(ANALYSIS_TIMEOUT, TimeUnit.SECONDS)) {
executor.shutdownNow();
timedOut = true;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
resultsWriter.write(String.format("%s, %b, %b, %f, %b, \"%s\", %b\n",
apkName,
aDetected.value,
bDetected.value.isAccepted(),
bDetected.value.getScore(),
cDetected.value,
bDetected.value.getComment(),
timedOut));
performancesWriter.write(String.format("%s, %f, %f, %f, %f, %d, %dl, %dl\n",
apkName,
aDetectionTime.value,
bDetectionTime.value,
cDetectionTime.value,
unpackingTime,
applicationData.getSmaliLoader().getClassesCount(),
applicationData.getSmaliLoader().getTotalClassesSize(),
applicationData.getDecodedPackage().getOriginalApk().length()));
resultsWriter.flush();
performancesWriter.flush();
} catch (IOException e) { }
// No longer deleting temp files
if (!timedOut)
println("Completed: " + apkName);
else {
print("Timeout");
if (bDetectionTime.value == 0) print(" TextDetection");
if (!noA && (aDetectionTime.value == 0)) print(" LockDetection");
if (!noC && (cDetectionTime.value == 0)) print(" EncryptionDetection");
println(": " + apkName);
}
}
private static void closeWriters() throws IOException {
resultsWriter.close();
performancesWriter.close();
examinedFiles.dispose();
}
private static final int ANALYSIS_TIMEOUT = 40; // seconds
private static Boolean silentMode = false;
private static Boolean noA = false;
private static Boolean noC = false;
private static PersistentFileList examinedFiles;
private static BufferedWriter resultsWriter;
private static BufferedWriter performancesWriter;
private static A aStrategy;
private static B bScanner;
private static C cDetector;
}
I labeled the question as multithread because the same happens in the multithreaded version, which I serialized using this code in order to debug that error. Notice that the NullPointerException is in thread main, not in other Executor-spawned threads.
If you don't have a stack trace, it could mean that there are some crazy exceptions thrown in your code (see Exception without stack trace in Java), but it is more likely that the JVM is re-using exception objects as a performance optimization and the -XX:-OmitStackTraceInFastThrow JVM option would help you.
See this article for details
Aim:
Play video in blackberry device from remote server.
Current Output
Blank screen and this message: "Press space to start/stop/resume playback."
My code
public class MyApp extends UiApplication
{
private Player player;
private VideoControl videoControl;
public static void main(String[] args)
{
MyApp theApp = new MyApp();
theApp.enterEventDispatcher();
}
public MyApp()
{
MainScreen ms = new MainScreen();
public boolean onClose()
{
player.close();
videoControl.setVisible(false);
close();
return true;
}
protected boolean keyChar(char c, int status, int time)
{
boolean retVal = false;
if (c == Characters.SPACE)
{
if (player.getState() == Player.STARTED)
{
//Stop playback.
try
{
player.stop();
}
catch (Exception ex)
{
System.out.println("Exception: " + ex.toString());
}
}
else
{
//Start playback.
try
{
player.start();
}
catch (Exception ex)
{
System.out.println("Exception: " + ex.toString());
}
}
retVal = true;
}
return retVal;
}
};
ms.setTitle(new LabelField("Let's play some video..."));
LabelField lf = new LabelField("Press space to start/stop/resume playback.");
ms.add(lf);
pushScreen(ms);
try
{
player = Manager.createPlayer("http://224.1.2.3:12344:8082/ACSATraffic/blackberry.3gp");
player.realize();
//Create a new VideoControl.
videoControl = (VideoControl)player.getControl("VideoControl");
//Initialize the video mode using a Field.
videoControl.initDisplayMode(VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field");
videoControl.setVisible(true);
}
catch (Exception ex)
{
System.out.println(ex.toString());
}
}
}
}
What am I doing wrong here?
Or else is there any sample for playing video from local and
server? A link would be greatly appreciated.
sorry for posting a lot of code!!I don't know that why my ListFrame doesn't work???
these are the classes.At first I run the MainServer and then I will run the MainFrame in the other package.and then by inserting a correct user name and password ,the Listframe will be shown,BUT I click on menu bar or list or delete button but nothing will happen.why?? please help me.
MainSerevr class :
public class MainServer {
static Socket client = null;
static ServerSocket server = null;
public static void main(String[] args) {
System.out.println("Server is starting...");
System.out.println("Server is listening...");
try {
server = new ServerSocket(5050);
} catch (IOException ex) {
System.out.println("Could not listen on port 5050");
System.exit(-1);
}
try {
client = server.accept();
System.out.println("Client Connected...");
} catch (IOException e) {
System.out.println("Accept failed: 5050");
System.exit(-1);
}
try {
BufferedReader streamIn = new BufferedReader(new InputStreamReader(client.getInputStream()));
boolean done = false;
String line;
while (!done) {
line = streamIn.readLine();
if (line.equalsIgnoreCase(".bye")) {
done = true;
} else {
System.out.println("Client says: " + line);
}
}
streamIn.close();
client.close();
server.close();
} catch (IOException e) {
System.out.println("IO Error in streams " + e);
}
}}
ListFrame:
public class ListFrame extends javax.swing.JFrame implements PersonsModelChangeListener {
private InformationClass client;
private static DefaultListModel model = new DefaultListModel();
private ListSelectionModel moDel;
/** Creates new form ListFrame */
public ListFrame(InformationClass client) {
initComponents();
this.client = client;
jList1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
fillTable();
Manager.addListener(this);
}
private void deleteAPerson() {
int index = jList1.getSelectedIndex();
String yahooId = (String) jList1.getSelectedValue();
model.remove(index);
Manager.removeApersonFromSQL(yahooId);
int size = model.getSize();
if (size == 0) {
jButton1.setEnabled(false);
} else {
if (index == size) {
index--;
}
jList1.setSelectedIndex(index);
jList1.ensureIndexIsVisible(index);
}
}
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {
AddAPerson frame = new AddAPerson(client);
frame.setVisible(true);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
deleteAPerson();
}
private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {
MainClient.setText("");
MainClient.runAClient();
ChatFrame frame = new ChatFrame(client);
frame.setVisible(true);
}
public void fillTable() {
try {
List<InformationClass> list = null;
list = Manager.getClientListFromMySQL();
if (list == null) {
JOptionPane.showMessageDialog(this, "You should add a person to your list", "Information", JOptionPane.OK_OPTION);
return;
} else {
for (int i = 0; i < list.size(); i++) {
InformationClass list1 = list.get(i);
model.add(i, list1.getId());
}
jList1.setModel(model);
}
} catch (SQLException ex) {
Logger.getLogger(ListFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
MainClient class:
public class MainClient {
private static InformationClass info = new InformationClass();
private static Socket c;
private static String text;
public static String getText() {
return text;
}
public static void setText(String text) {
MainClient.text = text;
}
private static PrintWriter os;
private static BufferedReader is;
static boolean closed = false;
/**
* #param args the command line arguments
*/
public static void runAClient() {
try {
c = new Socket("localhost", 5050);
os = new PrintWriter(c.getOutputStream());
is = new BufferedReader(new InputStreamReader(c.getInputStream()));
String teXt = getText();
os.println(teXt);
if(c!=null&& is!=null&&os!=null){
String line = is.readLine();
System.out.println("Text received: " + line);
}
c.close();
is.close();
os.close();
} catch (UnknownHostException ex) {
System.err.println("Don't know about host");
} catch (Exception e) {
System.err.println("IOException: " + e);
}
}
}
EDIT:I have found the problem,which is because of writting MainClient.runAClient() in code ,where should I put it? please help me.
This article contains an sscce that illustrates a simple client-server GUI. You may find it instructive. If so, consider how you would address the bug found in the last line of the Echo(Kind kind) constructor.