Turn a stack trace into a string? - gwt

Is it possible to print a stack trace to a string in GWT? The usual methods of using the classes in java.io won't work I think, because the java.io package is not available clientside (and Writer, PrintWriter, etc are in that package)
Thank you

I'm not sure if StackTraceElement is emulated, but if it is you can run something like
for (StackTraceElement element : exception.getStackTrace()) {
string += element + "\n";
}

Here is the method I'm using to retrieve a full stack trace as a String in GWT :
private static String getMessage (Throwable throwable) {
String ret="";
while (throwable!=null) {
if (throwable instanceof com.google.gwt.event.shared.UmbrellaException){
for (Throwable thr2 :((com.google.gwt.event.shared.UmbrellaException)throwable).getCauses()){
if (ret != "")
ret += "\nCaused by: ";
ret += thr2.toString();
ret += "\n at "+getMessage(thr2);
}
} else if (throwable instanceof com.google.web.bindery.event.shared.UmbrellaException){
for (Throwable thr2 :((com.google.web.bindery.event.shared.UmbrellaException)throwable).getCauses()){
if (ret != "")
ret += "\nCaused by: ";
ret += thr2.toString();
ret += "\n at "+getMessage(thr2);
}
} else {
if (ret != "")
ret += "\nCaused by: ";
ret += throwable.toString();
for (StackTraceElement sTE : throwable.getStackTrace())
ret += "\n at "+sTE;
}
throwable = throwable.getCause();
}
return ret;
}

I would not recommend trying to display error stack trace in a GUI label.
1) They are not readable after GWT Obfuscation. They just look like bunch of tab aligned characters over new lines.
2) They are not in I18N format.
3) The correct way is the just show user a well formed error "Message" . exception.getMessage() will give you a single line of non-obf information which should provide the necessary UX interaction to user.
4) If you are looking for well formed exception stacktrace helpful for debugging ( not for user ) you should use GWT's well documented logging feature with web mode exceptions -
a) https://developers.google.com/web-toolkit/doc/latest/DevGuideLogging
b) Also read on http://code.google.com/p/google-web-toolkit/wiki/WebModeExceptions

Use com.google.gwt.logging.impl.StackTracePrintStream
Throwable t = ...;
StringBuilder message = new StringBuilder();
StackTracePrintStream ps = new StackTracePrintStream(message);
t.printStackTrace(ps);
ps.flush();

Related

Why won't BufferedWriter write URL content to text file?

I'm trying to write the text from the URL to a text file in batches of 35 lines, pushing enter to continue to the next batch of 35 lines. If I don't try and write to the file in batches of 35 lines it works great and writes all of the content to the text file. But when I try and use the if statement to print in batches of 35 it won't print to the file unless I push enter around 15 times. And even then it doesn't print everything. I seems like it has something to do with the if statement but I can't figure it out.
String urlString = "https://www.gutenberg.org/files/46768/46768-0.txt";
try {
URL url = new URL(urlString);
try(Scanner input = new Scanner(System.in);
InputStream stream = url.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\Users\\mattj\\Documents\\JuliusCeasar.txt"));) {
String line;
int PAGE_LENGTH = 35;
int lineCount = 0;
while ((line = reader.readLine()) != null) {
System.out.println(line);
writer.write(line + "\n");
lineCount++;
if (lineCount == PAGE_LENGTH){
System.out.println();
System.out.println("- - - Press enter to continue - - -");
input.nextLine();
lineCount = 0;
}
}
}
} catch (MalformedURLException e) {
System.out.println("We encountered a problem regarding the following URL:\n"
+ urlString + "\nEither no legal protocol could be found or the "
+ "string could not be parsed.");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Attempting to open a stream from the following URL:\n"
+ urlString + "\ncaused a problem.");
e.printStackTrace();
}
I don't know Java, but there's very similar concepts in .NET. I think there's a couple of things to consider here.
BufferWriter will not write to the file immediately, it acts - as the name suggests - as a buffer, collecting up write requests over time then doing it in batch. BufferWriter has a flush method to flush the 'queued' up writes to the file immediately - so I'd do this when you hit your 35 (never flush on every write).
Also, BufferedReader and BufferedWriter are closable, so ensure to wrap them in a try statement to make sure resources are properly unlocked/cleared.

Using a Beakerx Custom Magic

I've created a custom Magic command with the intention of generating a spark query programatically. Here's the relevant part of my class that implements the MagicCommandFunctionality:
MagicCommandOutcomeItem execute(MagicCommandExecutionParam magicCommandExecutionParam) {
// get the string that was entered:
String input = magicCommandExecutionParam.command.substring(MAGIC.length())
// use the input to generate a query
String generatedQuery = Interpreter.interpret(input)
MIMEContainer result = Text(generatedQuery);
return new MagicCommandOutput(MagicCommandOutcomeItem.Status.OK, result.getData().toString());
}
This works splendidly. It returns the command that I generated. (As text)
My question is -- how do I coerce the notebook into evaluating that value in the cell? My guess is that a SimpleEvaluationObject and TryResult are involved, but I can't find any examples of their use
Rather than creating the MagicCommandOutput I probably want the Kernel to create one for me. I see that the KernelMagicCommand has an execute method that would do that. Anyone have any ideas?
Okay, I found one way to do it. Here's my solution:
You can ask the current kernelManager for the kernel you're interested in,
then call PythonEntryPoint.evaluate. It seems to do the job!
#Override
MagicCommandOutcomeItem execute(MagicCommandExecutionParam magicCommandExecutionParam) {
String input = magicCommandExecutionParam.command.substring(MAGIC.length() + 1)
// this is the Scala code I want to evaluate:
String codeToExecute = <your code here>
KernelFunctionality kernel = KernelManager.get()
PythonEntryPoint pep = kernel.getPythonEntryPoint(SCALA_KERNEL)
pep.evaluate(codeToExecute)
pep.getShellMsg()
List<Message> messages = new ArrayList<>()
//until there are messages on iopub channel available collect them into response
while (true) {
String iopubMsg = pep.getIopubMsg()
if (iopubMsg == "null") break
try {
Message msg = parseMessage(iopubMsg) //(I didn't show this part)
messages.add(msg)
String commId = (String) msg.getContent().get("comm_id")
if (commId != null) {
kernel.addCommIdManagerMapping(commId, SCALA_KERNEL)
}
} catch (IOException e) {
log.error("There was an error: ${e.getMessage()}")
return new MagicKernelResponse(MagicCommandOutcomeItem.Status.ERROR, messages)
}
}
return new MagicKernelResponse(MagicCommandOutcomeItem.Status.OK, messages)
}

Inserting block/braces in If-else statements using JDT

I'm creating an Eclipse plugin that should insert block to one line if-else statements.
[Just like Eclipse facilitates via setting a preference for editor on Save-action]
for e.g.
if (isFormed)
if (i == 1)
System.out.println("i is 1");
else
System.out.println("i is undefined");
should be replaced with
if (isFormed)
{
if (i == 1)
{
System.out.println("i is 1");
}
else
{
System.out.println("i is undefined");
}
}
Here is how I'm visiting & replacing the statement inside AST
node.accept(new ASTVisitor() {
#Override
public boolean visit(IfStatement ifStatement) {
//Add Block in case of IfStatemnet if it is not there.
if(ifStatement != null){
Statement thenStatement = ifStatement.getThenStatement();
Statement elseStatement = ifStatement.getElseStatement();
String codeToReplace = "if("+ifStatement.getExpression()+")";
if(thenStatement instanceof Block)
codeToReplace += "\n"+ thenStatement + "";
else
codeToReplace += "{\n"+ thenStatement + "\n}";
if(elseStatement != null){
if(elseStatement instanceof Block)
codeToReplace += "else" + elseStatement +"\n";
else
codeToReplace += "else{\n" + elseStatement +"\n}";
}
replaceStatment(rewriter, getBlockInstence(ifStatement), codeToReplace , ifStatement);
}
return super.visit(ifStatement);
}
});
& once it's whole visited I commit the working copy.
This adds block to the outer if-else, & not to the inner ones.
I also tried replacing the document & committing it while visit like below:
IDocument document = new org.eclipse.jface.text.Document(iCompilationUnit.getSource());
TextEdit edits = mCompilationUnit.rewrite(document, null);
document.replace(ifStatement.getStartPosition(), ifStatement.getLength(), codeToReplace);
edits.apply(document);
iCompilationUnit.getBuffer().setContents(document.get());
iCompilationUnit.commitWorkingCopy(true, new NullProgressMonitor());
But this adds braces at wrong places for inner if-else & whole code gets messed up as IT DOES NOT HAVE UPDATED "offset" & "length" FOR THE CODE TO BE REPLACED & hence it keeps replacing at wrong places & messes up.
//void org.eclipse.jface.text.IDocument.replace(int offset, int length, String textTobeReplaced)
I also tried getting how eclipse is doing it. But couldn't reach that point.
Can anyone help solving this? Or any sort of plugin code I should refer? Even if I can get which eclipse plugin does this I can try de-compiling it.
I had the same problem that through changes the offset of expressions was changed and not updated. As a workaround I first collected all expressions that should be replaced, then reversed the collection and so started the changes at the end of the code. So the offset did not changed and I could change all expressions.
It's no good solution, but this worked for me.

Need some eclipse search/replace regex help to speed things up

So I have had an issue for a while now and thought it was worth the time to ask the more experienced regex guys if there was a way to fix this issue with a quick search and replace.
So i use a tool which generates java code(not written in java or I would manually fix the cause directly), however, it has an issue calling variables before an object is created.
This always occurs only once per object, but not for every object, the object name is unknown, and the error is always the line directly before the constructor is called. This is the format the error is always in:
this.unknownObjectName.mirror = true;
this.unknownObjectName = new Model(unknown, parameter, values);
I know there should be a trick to fix this, as a simple string replace simply will not work since 'unknownObjectName' is unknown.
Would this even be possible with regex, if so, please enlighten me :)
This is how the code SHOULD read:
this.unknownObjectName = new Model(unknown, parameter, values);
this.unknownObjectName.mirror = true;
For complex models, this error may happen hundreds of times, so this will indeed save a lot of time. That and I would rather walk on hot coals then do mindless busy work like fixing all these manually :)
Edit:
I through together a java app that does the job.
public static void main(String args[]){
File file = new File(args[0]);
File file2 = new File(file.getParentFile(), "fixed-" + file.getName());
try {
if(file2.exists()) {
file2 = new File(file.getParentFile(), "fixed-" + System.currentTimeMillis() + "-" + file.getName());
}
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file2)));
String line, savedline = null, lastInitVar = "";
while((line = br.readLine()) != null){
if(line.contains("= new ")){
String varname = line.substring(0, line.indexOf("=")).trim();
lastInitVar = varname;
}else if(line.contains(".mirror")){
String varname = line.substring(0, line.indexOf(".mirror")).trim();
if(!lastInitVar.equals(varname)){
savedline = line;
continue;
}
}else if(savedline != null && savedline.contains(lastInitVar)){
bw.write(savedline + "\n");
savedline = null;
}
bw.write(line + "\n");
}
bw.flush();
bw.close();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Over thinking it
Write a program to read line by line and when you see a object access before a constructor don't write it out, write out the next line and then write out the buffered line, rinse repeat.
Some people, when confronted with a problem, think "I know, I'll use
regular expressions." Now they have two problems. - Jamie Zawinski
Regular Expressions are for matching patterns not state based logic.

counting the number of character in a text using FileReader

I am new in this superb place. I got help several times from this site. I have seen many answers regarding my question that was previously discussed but i am facing problem to count the number of characters using FileReader. It's working using Scanner. This is what i tried:
class CountCharacter
{
public static void main(String args[]) throws IOException
{
File f = new File("hello.txt");
int charCount=0;
String c;
//int lineCount=0;
if(!f.exists())
{
f.createNewFile();
}
BufferedReader br = new BufferedReader(new FileReader(f));
while ( (c=br.readLine()) != null) {
String s = br.readLine();
charCount = s.length()-1;
charCount++;
}
System.out.println("NO OF LINE IN THE FILE, NAMED " +f.getName()+ " IS " +charCount);
}
}`
It looks to me that each time you go through the loop, you assign the charCount to be the length of the line that iteration of the loop is concerned with. i.e. instead of
charCount = s.Length() -1;
try
charCount = charCount + s.Length();
EDIT:
If you have say the document with the contents "onlyOneLine"
Then when you first hit the while check the br.readLine() will make the BufferredReader read the first line, during the while's code block however br.readLine() is called again which advances the BufferredReader to the second line of the document, which will return null. As null is assigned to s, and you call length(), then NPE is thrown.
try this for the while block
while ( (c=br.readLine()) != null) {
charCount = charCount + c.Length(); }