Can not print in Text area from same class? - java

I want to print in the text area named arena. I am calling the append method from the same class with no luck so far. How to print a string in a text area??
public class Chat_window extends javax.swing.JFrame implements Runnable {
public static DataInputStream in = null;
public static PrintStream out = null;
private static Socket cs = null;
private static BufferedReader zz;
private static boolean alive = true;
public Chat_window() {
initComponents();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Chat_window w=new Chat_window();
w.setVisible(true);
}
});
try {
cs = new Socket("localhost", 3333);
out = new PrintStream(cs.getOutputStream());
zz = new BufferedReader(new InputStreamReader(System.in));
in = new DataInputStream(cs.getInputStream());
} catch (Exception ex) {
System.out.println(ex);
}
if (cs != null && out != null && in != null) {
try {
new Thread(new Chat_window()).start();
while (alive) {
out.println(zz.readLine().trim());
}
out.close();
in.close();
cs.close();
} catch (Exception error) {
System.out.println(error);
}
}
}
#Override
public void run() {
try {
while ((m = in.readLine()) != null) {
**arena.append(m);** //This line doesnt work
System.out.println(m);
}
} catch (Exception e) {
System.out.println(e);
}
}
// Variables declaration
private java.awt.TextArea arena;
private java.awt.TextArea textArea2;
private java.awt.TextArea usrchat;
// End of variables declaration
}

Try to replace it with arena.setText(arena.getText()+"\n"+m);
Or
arena.setText(arena.getText()+m);
If you don't want to add a new line in between :)

Related

Exception thrown from the UncaughtExceptionHandler

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

Java, javazoom program for playing MP3 files(AdvancedPlayer), event.getFrame() is giving random things

I'm trying to write a program that plays .mp3 files, playing them works perfectly. But pausing is causing some trouble. When I pause the song (stop the song and ask for the frame) I get an incorrect value.
class PauseStartMP3Test {
private static AdvancedPlayer player;
private static int pausedOnFrame = 0;
private static boolean playing = false;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(true) {
String s = in.next();
if(!s.equals("")) {
if(!playing) {
playing = true;
play();
}
else {
player.stop();
}
}
}
}
public static void play() {
File file = null;
file = new File("C:\\Users\\Remco\\Desktop\\Programming\\musictest/throughglass.mp3");
try {
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
try {
player = new AdvancedPlayer(bis);
new Thread() {
public void run() {
try {
if(playing) {
player.setPlayBackListener(new PlaybackListener() {
#Override
public void playbackFinished(PlaybackEvent event) {
pausedOnFrame = event.getFrame();
System.out.println(pausedOnFrame);
playing = false;
}
});
player.play(pausedOnFrame, Integer.MAX_VALUE);
}
else {
player.stop();
}
}
catch (Exception e) {
System.out.println(e);
}
}
}.start();
} catch (JavaLayerException ex) {
System.out.println(ex);
}
} catch (FileNotFoundException ex) {
System.out.println(ex);
}
}

Confused about how to use exchanger in java

As with basically every exchanger task, I have a producer filling up an empty buffer2, a consumer clearing a full buffer1 and when each thread is done, they should exchange their respective buffers.
I am really unsure about where and how to apply the exchange. I defined readyconsumer and readyproducer as booleans, so that a third thread can check whether it's time to exchange the buffers once both are true. This should solve the problem I had doing it with two threads, where the program was stuck with both threads at wait() (which it unfortunately still is).
This is what the code looks like at the moment. Can anyone help me in which class I have to exchange and at what point in the code? Thank you very much in advance!
class Buffer {
static boolean readyconsumer, readyproducer = false;
volatile int count; // number of put actions
static int max = 10;
Buffer() {
count = 0;
}
public synchronized void put() {
if (count == max) {
readyproducer = true;
System.out.println(" wait ");
try {
wait();
} catch (InterruptedException e) {
}
}
count++;
System.out.println("put " + count);
notifyAll();
}
public synchronized void get() {
if (count == 0) {
readyconsumer = true;
System.out.println(" wait");
try {
wait();
} catch (InterruptedException e) {
}
}
count--;
System.out.println("get " + count);
notifyAll();
}
}
class CheckandSwitch extends ProdCon {
public void run() {
while (true) {
if (Buffer.readyconsumer && Buffer.readyproducer) {
try {
ProdCon.buffer2 = exchanger.exchange(ProdCon.buffer1);
ProdCon.buffer1 = exchanger.exchange(ProdCon.buffer2);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Buffer.readyconsumer = false;
Buffer.readyproducer = false;
buffer1.count = 0;
buffer2.count = 10;
notifyAll();
}
}
}
}
class Consumer extends ProdCon {
static Buffer buffer;
Consumer(Buffer b) {
super();
buffer = b;
b.count = 10;
}
public void run() {
while (true) {
consume();
buffer.get();
}
}
private void consume() {
System.out.println("consume");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
}
}
}
class Producer extends ProdCon {
static Buffer buffer;
Producer(Buffer b) {
super();
buffer = b;
b.count = 0;
}
public void run() {
while (true) {
produce();
buffer.put();
}
}
private void produce() {
System.out.println("produce ");
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
}
}
import java.util.concurrent.*;
public class ProdCon extends Thread {
static Exchanger<Buffer> exchanger = new Exchanger<Buffer>();
static Buffer buffer1, buffer2 = null;
public static void main(String[] args) {
buffer1 = new Buffer();
buffer2 = new Buffer();
new Consumer(buffer1).start();
new Producer(buffer2).start();
new CheckandSwitch().start();
}
}
You could use an Exchanger.
Here's the code from the javadoc tweaked into a working example.
class DataBuffer<T> {
T data = null;
public boolean isFull() {
return data != null;
}
public boolean isEmpty() {
return data == null;
}
public T get() {
T d = data;
data = null;
return d;
}
public void put(T data) {
this.data = data;
}
}
class FillAndEmpty {
Exchanger<DataBuffer<Integer>> exchanger = new Exchanger<>();
DataBuffer<Integer> initialEmptyBuffer = new DataBuffer<>();
DataBuffer<Integer> initialFullBuffer = new DataBuffer<>();
int countDown = 10;
class FillingLoop implements Runnable {
#Override
public void run() {
DataBuffer currentBuffer = initialEmptyBuffer;
try {
while (currentBuffer != null && countDown > 0) {
addToBuffer(currentBuffer);
if (currentBuffer.isFull()) {
currentBuffer = exchanger.exchange(currentBuffer);
}
}
} catch (InterruptedException ex) {
}
}
private void addToBuffer(DataBuffer<Integer> currentBuffer) {
currentBuffer.put(countDown--);
}
}
class EmptyingLoop implements Runnable {
#Override
public void run() {
DataBuffer<Integer> currentBuffer = initialFullBuffer;
try {
while (currentBuffer != null) {
takeFromBuffer(currentBuffer);
if (currentBuffer.isEmpty()) {
currentBuffer = exchanger.exchange(currentBuffer);
}
}
} catch (InterruptedException ex) {
}
}
private void takeFromBuffer(DataBuffer<Integer> currentBuffer) {
System.out.println(currentBuffer.get());
}
}
void start() {
new Thread(new FillingLoop()).start();
new Thread(new EmptyingLoop()).start();
}
}
public void test() {
System.out.println("Hello");
new FillAndEmpty().start();
}

Is there a Java equivalent to unputc?

I have a BufferedWriter to which I use to write characters into a PipedInputStream. Based on keyboard events. But I am implementing a backspace handler, but I can see no way of doing so without unputc.
I am almost falling back into using a string to buffer the current line.
Perhaps, I could do a better job using Canvas instead. (God how I hate java!)
public class Console extends JTextArea {
/**
*
*/
private static final long serialVersionUID = 6315506875930497268L;
private PipedInputStream stdin;
private PipedOutputStream stdout;
private PipedOutputStream stderr;
private boolean bounceKey = true;
private class Dispatcher implements Runnable {
InputStream in;
public Dispatcher(InputStream in) {
this.in = in;
}
#Override
public void run() {
Reader input = new BufferedReader(new InputStreamReader(in));
int c;
try {
try {
while ((c = input.read()) >= 0) {
append(String.valueOf((char) c));
}
} finally {
input.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public Console() throws IOException {
stdin = new PipedInputStream();
stdout = new PipedOutputStream();
stderr = new PipedOutputStream();
final Writer kbd = new BufferedWriter(new OutputStreamWriter(
new PipedOutputStream(stdin)));
new Thread(new Dispatcher(new PipedInputStream(stdout))).start();
new Thread(new Dispatcher(new PipedInputStream(stderr))).start();
addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
try {
char ch = e.getKeyChar();
kbd.write(ch);
append(String.valueOf(ch));
if(ch == '\n') kbd.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
#Override
public void keyPressed(KeyEvent e) {
int keycode = e.getKeyCode();
switch(keycode) {
case KeyEvent.VK_BACK_SPACE:
// Erase the last char from buffer and the screen
}
}
#Override
public void keyReleased(KeyEvent e) {
} // DONOTHING
});
setEditable(false);
setFocusable(true);
setBackground(Color.black);
setForeground(Color.lightGray);
setFont(new Font("Monospace", Font.BOLD, 12));
setLineWrap(true);
}
public OutputStream getStderr() {
return stderr;
}
public OutputStream getStdout() {
return stdout;
}
public InputStream getStdin() {
return stdin;
}
public boolean isBounceKey() {
return bounceKey;
}
public void setBounceKey(boolean bounceKey) {
this.bounceKey = bounceKey;
}
}
Yes, see PushbackInputStream.
I am almost falling back into using a string to buffer the current line.
That is the correct way to do it: save up the whole line and don't do anything with it it until the user presses "enter". They might delete the whole thing - what if the process you are communicating with has already taken action?
I.e. what you should be doing is the thing you are for some reason trying to avoid doing! :-)

Swing problem!(problem in showing a frame)

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.

Categories