JavaFX Update TextField in Loop - java

I have a problem with my application JavaFX.
Image: https://picload.org/image/rlwpwdgi/javafx.png
With the button (1) showing the second window.
With the key (2) start the search in a path.
I need that the TextField (3) update as searching finds files.
In the Controller class of the second window, the button (2) perform this method.
public void startSuchen() {
String text = textFieldPfad.getText();
if (text.length() > 0) {
dateiGef = 0;
dateiGes = 0;
listf(pfad);
textFieldDateiGef.setText(String.valueOf(dateiGef));
textFieldDateiGes.setText(String.valueOf(dateiGes));
}
}
And this is the procedure listf:
private void listf(File directory) {
try {
File[] fileList = directory.listFiles();
for (File file : fileList) {
// Platform.runLater(new Runnable() {
// #Override
// public void run() {
// textFieldDateiGef.setText(String.valueOf(getDateiGef()));
// textFieldDateiGes.setText(String.valueOf(getDateiGes()));
// }
// });
// Thread thrd = new Thread() {
// public void run() {
// Platform.runLater(new Runnable() {
// #Override
// public void run() {
// textFieldDateiGef.setText(String.valueOf(getDateiGef()));
// textFieldDateiGes.setText(String.valueOf(getDateiGes()));
// }
// });
// }
// };
// thrd.start();
if (file.isFile()) {
dateiGes += 1;
String fileName = file.getName().toLowerCase();
String nome = textFieldName.getText().toLowerCase();
Pattern r = Pattern.compile(nome);
Matcher m = r.matcher(fileName);
if (m.find()) {
dateiGef += 1;
}
} else if (file.isDirectory()) {
listf(file);
}
}
} catch (NullPointerException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
The commented lines are my tests to update the GUI, I also tried with the Task, but unfortunately it does not work. Someone please help me understand why?
Here is the solution:
public void startSuchen() {
String text = textFieldPfad.getText();
if (text.length() > 0) {
dateiGef = 0;
dateiGes = 0;
// Solution
new Thread(() -> listf(pfad)).start();
// End Solution
textFieldDateiGef.setText(String.valueOf(dateiGef));
textFieldDateiGes.setText(String.valueOf(dateiGes));
}
}
And this is the procedure listf:
private void listf(File directory) {
try {
File[] fileList = directory.listFiles();
for (File file : fileList) {
// Solution
Platform.runLater(new Runnable() {
#Override
public void run() {
textFieldDateiGef.setText(String.valueOf(getDateiGef()));
textFieldDateiGes.setText(String.valueOf(getDateiGes()));
}
});
// End Solution
if (file.isFile()) {
dateiGes += 1;
String fileName = file.getName().toLowerCase();
String nome = textFieldName.getText().toLowerCase();
Pattern r = Pattern.compile(nome);
Matcher m = r.matcher(fileName);
if (m.find()) {
dateiGef += 1;
}
} else if (file.isDirectory()) {
listf(file);
}
}
} catch (NullPointerException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
Many thanks to James_D

Related

Device Dicovery file of ONVIF library in android studio

I find out a library of JavaWsDiscovery-0.2.jar. It is find out the ONVIF camera on same network, when I simply run the jar file in android studio, it runs successfully.
But when I want to use it in our project, it does not run just because of Private method.
In this library two methods are private those are not accessible to another class.
When i editing in jar file. so, it shows the compilation Error.
So, I need help in this regard, thank you.
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button btn;
ListView values;
List<String> value;
String[] args;
public static int WS_DISCOVERY_TIMEOUT = 4000;
public static int WS_DISCOVERY_PORT = 3702;
public static String WS_DISCOVERY_ADDRESS_IPv4 = "239.255.255.250";
public static String WS_DISCOVERY_ADDRESS_IPv6 = "[FF02::C]";
public static String WS_DISCOVERY_PROBE_MESSAGE = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:wsa=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:tns=\"http://schemas.xmlsoap.org/ws/2005/04/discovery\"><soap:Header><wsa:Action>http://schemas.xmlsoap.org/ws/2005/04/discovery/Probe</wsa:Action><wsa:MessageID>urn:uuid:c032cfdd-c3ca-49dc-820e-ee6696ad63e2</wsa:MessageID><wsa:To>urn:schemas-xmlsoap-org:ws:2005:04:discovery</wsa:To></soap:Header><soap:Body><tns:Probe/></soap:Body></soap:Envelope>";
private static final Random random = new SecureRandom();
String filepath = "/mnt/sdcard/Android/data/com.onvif.camera/com.onvif.javaWsDiscovery-0.2.jar";
static DeviceDiscovery deviceDiscovery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
deviceDiscovery = new DeviceDiscovery();
btn = (Button) findViewById(R.id.button);
values = (ListView) findViewById(R.id.values);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
main(args);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
public static void main(String[] args) throws InterruptedException {
Iterator i$ = discoverWsDevicesAsUrls().iterator();
while(i$.hasNext()) {
URL url = (URL)i$.next();
System.out.println("Device discovered: " + url.toString());
}
}
public static Collection<URL> discoverWsDevicesAsUrls() {
return discoverWsDevicesAsUrls("", "");
}
public static Collection<URL> discoverWsDevicesAsUrls(String regexpProtocol, String regexpPath) {
TreeSet urls = new TreeSet(new Comparator() {
#Override
public int compare(Object o1, Object o2) {
return o1.toString().compareTo(o2.toString());
}
});
Iterator i$ = discoverWsDevices().iterator();
while(i$.hasNext()) {
String key = (String)i$.next();
try {
URL e = new URL(key);
boolean ok = true;
if(regexpProtocol.length() > 0 && !e.getProtocol().matches(regexpProtocol)) {
ok = false;
}
if(regexpPath.length() > 0 && !e.getPath().matches(regexpPath)) {
ok = false;
}
if(ok) {
urls.add(e);
}
} catch (MalformedURLException var7) {
var7.printStackTrace();
}
}
return urls;
}
public static Collection<String> discoverWsDevices() {
final ConcurrentSkipListSet addresses = new ConcurrentSkipListSet();
final CountDownLatch serverStarted = new CountDownLatch(1);
final CountDownLatch serverFinished = new CountDownLatch(1);
ArrayList addressList = new ArrayList();
try {
Enumeration executorService = NetworkInterface.getNetworkInterfaces();
if(executorService != null) {
label45:
while(true) {
NetworkInterface ignored;
do {
if(!executorService.hasMoreElements()) {
break label45;
}
ignored = (NetworkInterface)executorService.nextElement();
} while(ignored.isLoopback());
List address = ignored.getInterfaceAddresses();
Iterator runnable = address.iterator();
while(runnable.hasNext()) {
InterfaceAddress address1 = (InterfaceAddress)runnable.next();
addressList.add(address1.getAddress());
}
}
}
} catch (SocketException var10) {
var10.printStackTrace();
}
ExecutorService executorService1 = Executors.newCachedThreadPool();
Iterator ignored1 = addressList.iterator();
while(ignored1.hasNext()) {
final InetAddress address2 = (InetAddress)ignored1.next();
Runnable runnable1 = new Runnable() {
public void run() {
try {
String e = UUID.randomUUID().toString();
String probe = WS_DISCOVERY_PROBE_MESSAGE.replaceAll("<wsa:MessageID>urn:uuid:.*</wsa:MessageID>", "<wsa:MessageID>urn:uuid:" + e + "</wsa:MessageID>");
int port = random.nextInt(20000) + '鱀';
final DatagramSocket server = new DatagramSocket(port, address2);
(new Thread() {
public void run() {
try {
DatagramPacket e = new DatagramPacket(new byte[4096], 4096);
server.setSoTimeout(WS_DISCOVERY_TIMEOUT);
long timerStarted = System.currentTimeMillis();
while(System.currentTimeMillis() - timerStarted < (long)WS_DISCOVERY_TIMEOUT) {
serverStarted.countDown();
server.receive(e);
Collection collection = deviceDiscovery.parseSoapResponseForUrls(Arrays.copyOf(e.getData(), e.getLength()));
Iterator i$ = collection.iterator();
while(i$.hasNext()) {
String key = (String)i$.next();
addresses.add(key);
}
}
} catch (SocketTimeoutException var11) {
;
} catch (Exception var12) {
var12.printStackTrace();
} finally {
serverFinished.countDown();
server.close();
}
}
}).start();
try {
serverStarted.await(1000L, TimeUnit.MILLISECONDS);
} catch (InterruptedException var7) {
var7.printStackTrace();
}
if(address2 instanceof Inet4Address) {
server.send(new DatagramPacket(probe.getBytes(), probe.length(), InetAddress.getByName(WS_DISCOVERY_ADDRESS_IPv4), WS_DISCOVERY_PORT));
} else {
server.send(new DatagramPacket(probe.getBytes(), probe.length(), InetAddress.getByName(WS_DISCOVERY_ADDRESS_IPv6), WS_DISCOVERY_PORT));
}
} catch (Exception var8) {
var8.printStackTrace();
}
try {
serverFinished.await((long)WS_DISCOVERY_TIMEOUT, TimeUnit.MILLISECONDS);
} catch (InterruptedException var6) {
var6.printStackTrace();
}
}
};
executorService1.submit(runnable1);
}
try {
executorService1.shutdown();
executorService1.awaitTermination((long)(WS_DISCOVERY_TIMEOUT + 2000), TimeUnit.MILLISECONDS);
} catch (InterruptedException var9) {
;
}
return addresses;
}
}
DeviceDiscovery.class
private static Collection<Node> getNodeMatching(Node body, String regexp) {
ArrayList nodes = new ArrayList();
if(body.getNodeName().matches(regexp)) {
nodes.add(body);
}
if(body.getChildNodes().getLength() == 0) {
return nodes;
} else {
NodeList returnList = body.getChildNodes();
for(int k = 0; k < returnList.getLength(); ++k) {
Node node = returnList.item(k);
nodes.addAll(getNodeMatching(node, regexp));
}
return nodes;
}
}
private static Collection<String> parseSoapResponseForUrls(byte[] data) throws SOAPException, IOException {
ArrayList urls = new ArrayList();
MessageFactory factory = MessageFactory.newInstance(WS_DISCOVERY_SOAP_VERSION);
MimeHeaders headers = new MimeHeaders();
headers.addHeader("Content-type", WS_DISCOVERY_CONTENT_TYPE);
SOAPMessage message = factory.createMessage(headers, new ByteArrayInputStream(data));
SOAPBody body = message.getSOAPBody();
Iterator i$ = getNodeMatching(body, ".*:XAddrs").iterator();
while(i$.hasNext()) {
Node node = (Node)i$.next();
if(node.getTextContent().length() > 0) {
urls.addAll(Arrays.asList(node.getTextContent().split(" ")));
}
}
return urls;
}
I want to use both method of DeviceDiscovery.class. But it's not accessible because it's a private method.
I am not able to editing in DeviceDiscovery.class because it's a part of jar file and it's only readable form.
This is the error I have:
(216, 80) error: parseSoapResponseForUrls(byte[]) has private access in DeviceDiscovery

why dont my filechooser open a dialog

I don't know what is wrong with the code. Can you help me figure it out?
private void doOpenFile() {
int result = myFileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
Path path = myFileChooser.getSelectedFile().toPath();
try {
String contentString = "";
for (String s : Files.readAllLines(path, StandardCharsets.UTF_8)) {
contentString += s;
}
jText.setText(contentString);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void doSaveFile() {
int result = myFileChooser.showSaveDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
// We'll be making a mytmp.txt file, write in there, then move it to
// the selected
// file. This takes care of clearing that file, should there be
// content in it.
File targetFile = myFileChooser.getSelectedFile();
try {
if (!targetFile.exists()) {
targetFile.createNewFile();
}
FileWriter fw = new FileWriter(targetFile);
fw.write(jText.getText());
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I'm not sure how do you use your myFileChooser and how do you instantiate them but this code works well :
public class ForTestApplication {
public static void main(String[] args) {
Window window = new Window();
window.setVisible(true);
window.showFileChooser();
}
static class Window extends JFrame {
JFileChooser jFileChooser = new JFileChooser();
public void showFileChooser() {
jFileChooser.showDialog(this, "Just for test");
}
}
}
Here is screenshot :
Please, provide more code to figure out what is going on.

how to read different files in differents runnable threads Java

I need to read all .txt files in a folder with 4 Threads running at the same time. What can I do so each thread reads a different file. Ex: Thread 1 reads file 1, Thread 2 reads file 2... and so on until there's no more files to read.
Thread h;
public Hilo(){
h= new Thread(this,"Hilo 1");
h.start();
}
public void run(){
int contador;
File folder = new File("C:/Users/Jose/Desktop/java");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile()) {
contador=0;
int i=0;
//System.out.println(file.getName());
Scanner scan = null;
try {
scan = new Scanner (file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (scan.hasNext()){
String linea=scan.next();
String[] lineas = linea.split("(?=[,.])|\\s+");
if (Palindrome.is(lineas[i])){
contador++;
}
}
scan.close();
}
}
}
Try it:
1. Create a class ReadFiles:
public class ReadFiles {
public interface IEvents {
void onFile(File file);
}
int maxConcurrentThread = 5;
ThreadPoolExecutor pool = null;
volatile int countFiles = 0;
String folder = "";
IEvents event = null;
public ReadFiles(String folder, int maxConcurrentThread) {
this.folder = folder;
this.maxConcurrentThread = maxConcurrentThread;
}
public void setEvent(IEvents event) {
this.event = event;
}
public void read() {
ThreadPoolExecutor pool = (ThreadPoolExecutor) Executors.newFixedThreadPool(this.maxConcurrentThread);
File ffolder = new File(folder);
File[] listOfFiles = ffolder.listFiles();
for (final File file : listOfFiles) {
if (file.isFile()) {
pool.execute(new Runnable() {
#Override
public void run() {
countFiles++;
event.onFile(file);
}
});
}
}
pool.shutdown();
}
}
How to use:
int maxConcurrentThread = 5;
ReadFiles read = new ReadFiles("C:/Users/Jose/Desktop/java", maxConcurrentThread);
read.setEvent(new ReadFiles.IEvents() {
#Override
public void onFile(File file) {
Scanner scan = null;
try {
scan = new Scanner(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (scan.hasNext()) {
String linea = scan.next();
String[] lineas = linea.split("(?=[,.])|\\s+");
if (Palindrome.is(lineas[i])) {
contador++;
}
}
scan.close();
}
});
read.read();
package z;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test {
public static void main(String[] args) {
ExecutorService exec = Executors.newFixedThreadPool(4);
File folder = new File("C:/Users/Jose/Desktop/java");
File[] files = folder.listFiles();
for(File file : files){
exec.execute(new Worker(file));
}
}
}
class Worker implements Runnable {
private File file;
public Worker(File file) {
this.file = file;
}
#Override
public void run() {
int contador;
if (file.isFile()) {
contador = 0;
int i = 0;
Scanner scan = null;
try {
scan = new Scanner(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (scan.hasNext()) {
String linea = scan.next();
String[] lineas = linea.split("(?=[,.])|\\s+");
if (Palindrome.is(lineas[i])) {
contador++;
}
}
scan.close();
}
}
}
This is the code, without the palindromo method, its not necesary.
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Hilo numero1 = new Hilo();
Hilo numero2 = new Hilo();
Hilo numero3 = new Hilo();
Hilo numero4 = new Hilo();
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Hilo implements Runnable {
Thread h;
public Hilo() {
h = new Thread(this, "Hilo 1");
h.start();
}
public void run() {
int c = 0;
int contador;
File folder = new File("C:/Users/Jose/Desktop/java");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile()) {
contador = 0;
int i = 0;
//System.out.println(file.getName());
Scanner scan = null;
try {
scan = new Scanner(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (scan.hasNext()) {
String linea = scan.next();
String[] lineas = linea.split("(?=[,.])|\\s+");
if (Palindromo.es(lineas[i])) {
contador++;
}
c++;
}
scan.close();
System.out.println("La cantidad de Palindromos en el archivo " + file + " es de: " + contador);
}
}
}
}

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

Run an Applet (inside a JAR) in a new JFrame

I want to run MinecraftApplet.class inside minecraft.jar in a new JFrame.
However, I am asking on how to do this, because my existing code does not work:
This is StartScript which load the jar urls, then updates class path, and finally starts a thread in GameFrame and adds the createApplet.
public class StartScript implements Runnable{
public ClassLoader classLoader;
public boolean natives_loaded;
protected URL[] urlList;
public void run()
{
try
{
String path = (String)AccessController.doPrivileged(new PrivilegedExceptionAction() {
public Object run() throws Exception {
return InfiniLauncherUtils.getWorkingDirectory() + File.separator + "bin" + File.separator;
}});
File dir = new File(path);
if (!dir.exists())
{
dir.mkdirs();
}
loadJarURLs();
updateClassPath(dir);
Thread start = new Thread(new InfiniLauncherGameFrame(createApplet()));
start.start();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public Applet createApplet() throws InstantiationException, IllegalAccessException, ClassNotFoundException
{
Class appletClass = classLoader.loadClass("net.minecraft.client.MinecraftApplet");
return (Applet)appletClass.newInstance();
}
protected void updateClassPath(File dir)throws Exception
{
URL[] urls = new URL[this.urlList.length];
for (int i = 0; i < this.urlList.length; i++) {
urls[i] = new File(dir, getJarName(this.urlList[i])).toURI().toURL();
System.out.println(urlList[i]);
}
if (classLoader == null) {
classLoader = new URLClassLoader(urls) {
protected PermissionCollection getPermissions(CodeSource codesource)
{
PermissionCollection perms = null;
try
{
Method method = SecureClassLoader.class.getDeclaredMethod("getPermissions", new Class[] { CodeSource.class });
method.setAccessible(true);
perms = (PermissionCollection)method.invoke(getClass().getClassLoader(), new Object[] {
codesource });
String host = "www.minecraft.net";
if ((host != null) && (host.length() > 0))
{
perms.add(new SocketPermission(host, "connect,accept"));
} else codesource.getLocation().getProtocol().equals("file");
perms.add(new FilePermission("<<ALL FILES>>", "read"));
}
catch (Exception e)
{
e.printStackTrace();
}
return perms;
}
};
}
String path = dir.getAbsolutePath();
if (!path.endsWith(File.separator)) path = path + File.separator;
unloadNatives(path);
System.setProperty("org.lwjgl.librarypath", path + "natives");
System.setProperty("net.java.games.input.librarypath", path + "natives");
natives_loaded = true;
}
protected void loadJarURLs() throws Exception {
String jarList[] = {"lwjgl.jar", "jinput.jar", "lwjgl_util.jar", LoginScript.mainGameURL};
//StringTokenizer jar = new StringTokenizer(jarList, ", ");
int jarCount = jarList.length+1;
this.urlList = new URL[jarCount];
URL path = new URL("http://s3.amazonaws.com/MinecraftDownload/");
for (int i = 0; i < jarCount - 1; i++) {
this.urlList[i] = new URL(path, jarList[i]);
System.out.println(urlList[i]);
}
String osName = System.getProperty("os.name");
String nativeJar = null;
if (osName.startsWith("Win"))
nativeJar = "windows_natives.jar.lzma";
else if (osName.startsWith("Linux"))
nativeJar = "linux_natives.jar.lzma";
else if (osName.startsWith("Mac"))
nativeJar = "macosx_natives.jar.lzma";
else if ((osName.startsWith("Solaris")) || (osName.startsWith("SunOS")))
nativeJar = "solaris_natives.jar.lzma";
else {
}
if (nativeJar == null) {
} else {
this.urlList[(jarCount - 1)] = new URL(path, nativeJar);
}
}
protected String getJarName(URL url)
{
System.out.println(url);
String fileName = url.toString();
if (fileName.contains("?"))
{
fileName = fileName.substring(0, fileName.indexOf("?"));
}
if (fileName.endsWith(".pack.lzma"))
{
fileName = fileName.replaceAll(".pack.lzma", "");
}
else if (fileName.endsWith(".pack"))
{
fileName = fileName.replaceAll(".pack", "");
}
else if (fileName.endsWith(".lzma"))
{
fileName = fileName.replaceAll(".lzma", "");
}
return fileName.substring(fileName.lastIndexOf('/') + 1);
}
private void unloadNatives(String nativePath)
{
if (!natives_loaded) {
return;
}
try
{
Field field = ClassLoader.class.getDeclaredField("loadedLibraryNames");
field.setAccessible(true);
Vector libs = (Vector)field.get(getClass().getClassLoader());
String path = new File(nativePath).getCanonicalPath();
for (int i = 0; i < libs.size(); i++) {
String s = (String)libs.get(i);
if (s.startsWith(path)) {
libs.remove(i);
i--;
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
GameFrame class
public InfiniLauncherGameFrame(Applet aapplet)
{
applet = aapplet;
System.out.println("ran");
}
public void run()
{
System.out.println("few");
removeAll();
add(applet);
validate();
setVisible(true);
setSize(300, 300);
}
I do not get any errors when I run it, however the new frame is black with a small white box at the top left.
Picture Here: http://imgur.com/rJjqC
I might not be getting errors because I thrown away a couple of exceptions.
Any help is much appreciated.
Maybe a stupid suggestion, but could it be because you didn't explicitly call the repaint() method? That happens to me a lot

Categories