I have an Applet whose method gets called from a JavaScript function within a browser. This method will eventually send a file to an Amazon S3 bucket. When this method attempts to create the AmazonS3Client however, the method fails without displaying any errors.
The relevant snippet of the code within the method is:
InputStream input = DigitalLive.class.getResourceAsStream("AwsCredentials.properties");
System.out.println("File loaded into Input Stream.");
PropertiesCredentials theCredentials = new PropertiesCredentials(input);
System.out.println("Credentials created.");
System.out.println("AccessKey is:" + theCredentials.getAWSAccessKeyId());
System.out.println("SecretKey is:" + theCredentials.getAWSSecretKey());
//All of the above strings print to the console with the correct AccessKey and SecretKey
try{
AmazonS3 s3Client = new AmazonS3Client(theCredentials);
//This message never prints
System.out.println("Client created.");
} catch(Exception e) {
//This message never prints
System.err.println("Error creating AmazonClient: " + e.getMessage());
}
None of the messages within the try/catch block ever print. None of the rest of the method's code (not shown here for brevity) gets fired either.
The jar file compiles without error. I'm using jdk 1.7.0_51 and the amazon aws-java-sdk-1.7.1. I'm using Eclipse as the IDE and am building the jar with a build file using ANT.
I'm not really sure what else to try other than wrapping the code in a try/catch block.
Is there a different/better way for me to debug the Java code to learn why the AmazonS3Client is not created? Or perhaps a more obvious reason why it might fail given the code snippet above?
EDIT: I added a try/catch block in the JavaScript code that calls the Java method and it throws an error:
Error calling method on NPObject
Error: java.lang.reflect.InvocationTargetException
I think what this tells me that the Java Applet is in fact throwing an error. I'm just not sure how to figure out which one and how to solve it. I've attempted to put try/catch blocks around the AmazonS3 s3Client = new AmazonS3Client(theCredentials); but the IDE tells me Unreachable catch block for InvocationTargetException. This exception is never thrown from the try statement body.
As it turns out, the error message was not being written to the console when the method in question was called from within JavaScript. I modified the Applet so that the method could be called from within the Applet, and the error was displayed in the console as expected.
The Applet was missing an Apache class, so that was added and all is well.
Related
I have a problem with Eclipse and one of my apps. Eclipse ONLY hits breakpoints when I throw an exception but not when it runs other lines of code "normally".
I am running the project in
C:\.....SmashDataServiceExternal\processor\bin
While my source code is under a different directory:
C:\.......\SmashDataProcessorExternal\...
When I try to run my app, it does not hit any of lines of code normally, but if I break on an Exception and I make my App throw an exception, then Eclipse breaks on the correct line in the correct source file.
i.e:
System.out.println("HISTORIC DATA: " + historicData.getDatasetId());
System.out.println("HISTORIC DATA TYPE: " + historicData.getReplayEventTypeId());
outputInputRequest(outputEvent);
logger.info("Sent BatchJobRequest for batchId {}, sessionId {} for byTime request", outputEvent.getBatchId(batchIdFlyweight), outputEvent.getSessionId(sessionIdFlyweight) );
if (1==1) {
throw new NullPointerException();
}
I set break point on every single line above, my app actually prints out the statements but does not break until nullpointer gets thrown.
https://imgur.com/a/8f306
I would appreciate any advise on how to get Eclipse to break properly.
Thank you.
So we want to use the bog-standard keytool utility that ships with a JRE. But rather than going through the trouble of finding the correct path and executable extension, spawning a subprocess, and running the executable, we collectively had the bright idea ("remember, none of us is as dumb as all of us!") to just call KeyTool's main() directly. It's implemented in Java code and also shipped with the JRE, and contains the standard "classpath" exception to the GPL so we can link against it.
Looking at the KeyTool source, there's even some provision made for this sort of thing: there are comments like "if you're calling KeyTool.main() directly in your own Java program, then [helpful reminder]" and the top-level main() is capable of propagating exceptions to calling code instead of just dying with System.exit(). Being able to just build the same command-line argument array and run KeyTool.main(stuff) instead of having to mess with platform differences seems like a very Java-esque thing to do, right?
In practice, weird things happen and we don't know why.
We want to capture any output from running KeyTool, which starts off like this:
// jdk/src/share/classes/sun/security/tools/KeyTool.java, line 331:
public static void main(String[] args) throws Exception {
KeyTool kt = new KeyTool();
kt.run(args, System.out);
}
private void run(String[] args, PrintStream out) throws Exception {
// real code here, sends to 'out'
}
The KeyTool entry points don't allow us to pass a PrintStream, it's hardcoded to use System.out. That should be okay thanks to System.setOut. We have an OutputStream subclass which feeds to a JTextComponent, but for initial coding, redirecting to a text file is fine. So our code does
PrintStream orig = System.out;
try {
System.out.println("This is the last visible console line");
System.setOut(new PrintStream("redirect_test.txt"));
System.out.println("This is now redirected!");
KeyTool.main(keytool_argv); // "-help" and "-debug" for now
}
catch all the myriad ways things might go wrong { ... }
finally {
System.setOut(orig);
System.out.println("Back to normal console output");
}
But when we run the code, the redirect_test.txt file contains only "This is now redirected!". The output from keytool's "-help" still shows up on the console, along with the before-and-after println calls.
There are some other oddities in calling KeyTool directly, like the package and class name has changed between Java 7 and Java 8, but that's easy to deal with via reflection. (The comments in the KeyTool source in Java 8 still refer to the Java 7 name, heh.) The only thing just freaky weird is how its "System.out" is strangely not affected by the same redirection that works everywhere else. (No, there are no weird import statements bringing in a special System replacement.)
Here's an online copy of Java 7's KeyTool.java if you don't happen to have OpenJDK sitting around.
You just need to redirect both System.out and System.err, since the usage instructions get printed to the standard error stream instead of the standard output stream. Try this:
PrintStream original = System.out;
PrintStream redirected = new PrintStream("redirect_test.txt")
try {
System.out.println("This is the last visible console line");
System.setOut(redirected);
System.setErr(redirected);
System.out.println("This is now redirected!");
KeyTool.main(keytool_argv); // "-help" and "-debug" for now
}
catch all the myriad ways things might go wrong { ... }
finally {
System.setOut(original);
System.setErr(original);
System.out.println("Back to normal console output");
}
I am a new java student currently working on File I/O. My professor has asked us to create a very simple "DC universe" game using interfaces and classes and has asked us in the current lab I am working on, to create an instance of an object and then save the file to a directory in our C drive. My problem, is that even after all my constant 2 hours of digging through past topics I still cannot find a proper explanation as to how I create a directory and THEN create a file and write to a file in that directory because it appears whenever I run my code to not be able to do both tasks simultaneously. The code below also contains an error at the "Print Writer" line and asks to add a throw clause for "file not found exception"
Any and all help is vastly appreciated
package runtime;
import java.io.*;
import java.util.*;
import model.hero.*;
public class Gameplay {
public static void main(String[] args) {
File x = new File("C://prog24178//dcheroes.dat");
if(!x.exists()){
x.mkdir();
}
PrintWriter output = new PrintWriter(x);
// 1. Create a save file called dcheroes.dat in {$root}\prog24178
// 2. Create a hero
// 3. Save hero to file
}
}
Two errors I see:
x.mkdir() will try to create C:\prog24178\dcheroes.dat as a directory. Use x.getParent().mkdir() to create C:\prog24178.
the PrintWriter error is Java complaining about you not catching a potential error. Your code is fine, it's just Java being demanding. Surround your code with a try { ... } catch (FileNotFoundException ex) { ... } block. Every function call that could potentionally throw an Exception needs to have that exception caught, or the containing function needs to be marked to also be a potential source of the exception (and you can't do the latter on main).
I am writing a simple java console application where program will prompt the user to type something in and then the program control will wait for the user input and do something with that input.
Issue is : while typing on the console , the user can not see what he is typing. What should I do differently so the user can see what he is typing?(user can see what he has typed after he hits 'enter').
I created a java standalone project and built and ran the project using netbean's ant command from command line:
ant run
Below is the whole code that I have.OS is Windows 7. jdk version: 1.6
Below is the code I am using to get user-input from console.
import java.io.*;
public class StatLibraryTest {
public static void main(String[] args) {
String CurLine = ""; // Line read from standard in
try{
while (!(CurLine.equals("quit"))){
System.out.println("Enter: " );
CurLine = readLine();
if (!(CurLine.equals("quit"))){
System.out.println("You typed: " + CurLine);
}
}
}catch(Exception e){
System.out.println(e.getMessage());
}
}
public static String readLine()
{
String s = "";
try {
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
s = in.readLine();
} catch (Exception e) {
System.out.println("Error! Exception: "+e);
}
return s;
}
}
Character echoing is normal taken care of by the operating system's terminal driver or (in modern systems) the terminal emulator. It happens independently of Java ... or whatever else the application is written in ... unless the application has turned character echoing off or something.
So ...
We need you to explain how you've run the application that is causing the console connected to System.in to get into "no echo" mode.
I don't know if this is the cause of your problem, but your readLine method is incorrect. Each time you call readLine it creates a new InputStreamReader and BufferedReader for System.in. This is inefficient. But worse than that, it is liable to lose input. You see, when in.readLine() is called, the input stack will make a read call on System.in to read all input that is currently available. If more than one line is available (because the user has typed ahead ... or because the application has been called with standard input redirected from a file), you can end up with multiple lines in the BufferedReader's buffer. The readLine() call returns the first line ... but the rest get thrown away.
There is also a bug in the way that you handle EOF. The in.readLine call will return a null when it sees EOF, but you are not dealing with it.
I suspect that the reason you are not getting echoing is something to do with the way you are running the program ... using Ant. Try running your program directly from the command line instead; i.e. run java StatLibraryTest.
Finally, there are some style problems with your code:
You've got an identifier (CurrLine) which violates the Java identifier name rules.
The indentation is inconsistent
Your use of embedded whitespace is inconsistent
Catching Exception is generally a bad idea. Catch the specific exceptions that you are expecting (e.g. IOException).
It is better to let an exception propagate if your code cannot do something sensible with it. Specifically, if readLine catches an exception, the caller will get an empty String. It can't distinguish that from valid input; e.g. the user entering an empty line. You should declare readLine as throws IOException.
Im am currently developing an automated "test" class (running several individual tests on other classes in the same package). The aim of the test file is to show whether each test either passed or failed. Some of the files being tested are not written correctly creating an ArrayOutOfBoundsException when running the test, that produces my test file to crash and not carry on until the end performing other tests. I am not in the position to modify code to fix the errors on the project being tested.
-> how to stop an exception from halting program execution in Java without creating any new classes
Thank for all your help, advice and sharing.
Best way to stop it happening: fix the code to perform appropriate checking.
If you can't fix the code which is actually failing, you could catch the exception explicitly at an "outer" level, log a warning and continue with the next file:
try
{
operationWhichMightThrow();
}
catch (ArrayIndexOutOfBoundsException e)
{
log.warning("Failed file " + filename, e);
// Do whatever you need to continue to the next file.
}
Catch the exception and log it as a test failure.