It's a slf4j logger and i have been trying to log error with 2 messages parameters.
catch(ExecutionException executionException) {
LOGGER.error("TimeoutException caught , Error: " + SSG_TIMEOUT.getErrorText()
+ ". Message: " +executionException.getMessage());
}
SSG_TIMEOUT.getErrorText() results to a String "TimeOut error encountered"
Things i used
Manual sanitize code
return entry.replace("\t", "\\t").replace("\b", "\\b").replace("\n",
"\\n").replace("\r", "\\r").replace("\f", "\\f").replace("\u0000",
"\\0").replace("\\a", "\\a").replace("\\v", "\\v").replace("\\e",
"\\e").replaceAll("\\p{Cntrl}", "").replace("'", "\\'").replace("\"",
"\\\"").replace("\\", "\\\\");
StringEscapeUtils.escapeJson(String errorMessage)
String builder to append string + escapeJson(StringBuilder.toString())
Still i see the issue in my veracode report.
Any Suggestions?
First of all first 2 methods of sanitization are correct, its just that there are not supported by Veracode.
Before using a method one should visit About Supported Cleansing Functions in
https://help.veracode.com/r/review_cleansers
So, for the above problem StringUtils.normalizeSpace() worked.
"StringUtils.escapeJava" could also be used but it seems deprecated
Soln:
catch(ExecutionException executionException) {
LOGGER.error("TimeoutException caught , Error: " +
StringUtils.normalizeSpace(SSG_TIMEOUT.getErrorText()
}
Related
I'm trying to use the xQuery API for java s9api, however when I try to declare a namespace and run a simple rule to test it I restore the error "XPST0003: XQuery syntax error in
# ... if (funcJavaDict: CheckString #
Unexpected token "if (" beyond end of query "
Acretido is an easy error to solve, but I'm not getting to the solution,
The Java code snippet is:
//Declara namespace de funções java para usar nas regras
comp.declareNamespace ("funcJavaDict", "java:Rastreamento.retratos.DictionaryTerms");
comp.declareNamespace ("xmi", "http://www.omg.org/XMI");
//compila regra do arquivo
XQueryExecutable exp = null;
try {
exp = comp.compile("return /n"+
"if ( funcJavaDict:CheckString("em andamento","EM Andamento") ) then /n" +
" String("são iguais") /n"
"else /n"+
" String("são diferente") ");
}catch (SaxonApiException e) {
e.printStackTrace();
}
//carrega e executa regra
XQueryEvaluator Eval = exp.load();
XdmValue rs = null;
try {
rs = Eval.evaluate();
} catch (SaxonApiException e) {
e.printStackTrace();
}
the code is very simple is just to check if two string's are equivalent.
Firstly, I'm puzzled by your Java snippet because it won't compile (because of the nested quotes), so I don't see how you get as far as Saxon reporting an XQuery syntax error. Also I imagine that the '/n' should really be '\n'. So let's suppose the Java actually says:
comp.compile("return \n"+
"if ( funcJavaDict:CheckString('em andamento','EM Andamento') ) then \n" +
" String('são iguais') \n"
"else \n"+
" String('são diferente') ");
XQuery keywords are recognized only if they appear in the right context. "return" at the start of an expression is not recognized as a keyword, so it is interpreted as a path expression meaning child::element(return).
(In fact recent Saxon releases will often report a warning if you use a keyword incorrectly like this, but it's not catching this particular case).
So "return" is a complete expression that selects child elements named return, and the only thing that can come after a complete expression is either the end of the input, or an infix operator such as and or union. The keyword if is not either of these things, so the compiler reports a syntax error. The solution is to remove the return keyword.
But that's not the only thing wrong with your query. There is no function named String. You could change it to string and the query would work, but writing string('xyz') is just a long-winded way of writing 'xyz', so better to drop the function call entirely.
First, in case there is a simpler way to solve this problem, here is an outline of what I am trying to accomplish. I want to Annotate my test methods with a KnownIssue annotation (extending AbstractAnnotationDrivenExtension) that takes a defect ID as a parameter and checks the status of the defect before executing the tests. If the defect is fixed, it will continue execution, if it is not fixed I want it to ignore the test, but if it is closed or deleted, I want to induce a test failure with logging stating that the test should be removed or updated and the annotation removed since the defect is now closed or deleted.
I have everything working up until inducing a test failure. What I have tried that doesn't work:
Throwing an exception in the visitFeatureAnnotation method, which causes a failure which causes all tests thereafter not to execute.
Creating a class that extends Spec and including a test method that logs a message and fails, then tried to use feature.featureMethod.setReflection() to set the method to execute to the other method. In this case, I get a java.lang.IllegalArgumentException : object is not an instance of declaring class
I then tried using ExpandoMetaClass to add a method directly to the declaringClass, and point feature.featureMethod.setReflection to point to it, but I still get the same IllegalArgumentException.
Here is what I have inside of my visitFeatureAnnotation method for my latest attempt:
def myMetaClass = feature.getFeatureMethod().getReflection().declaringClass.metaClass
myMetaClass.KnownIssueMethod = { -> return false }
feature.featureMethod.setReflection(myMetaClass.methods[0].getDoCall().getCachedMethod());
Any other ideas on how I could accomplish this, and either induce a test failure, or replace the method with another that will fail?
Ok... I finally came up with a solution. Here is what I got working. Within the visitFeatureAnnotation method I add a CauseFailureInterceptor that I created.
Here is the full source in case anyone is interested, just requires you to extend the KnownIssueExtension and implement the abstract method getDefectStatus:
public abstract class KnownIssueExtension extends AbstractAnnotationDrivenExtension<KnownIssue> {
private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(KnownIssueExtension.class)
public void visitFeatureAnnotation(KnownIssue knownIssue, FeatureInfo feature) {
DefectStatus status = null
try{
status = getDefectStatus(knownIssue.value())
} catch(Exception ex){
LOGGER.warn("Unable to determine defect status for defect ID '{}', test case {}", knownIssue.value(), feature.getName())
// If we can't get info from Defect repository, just skip it, it should not cause failures or cause us not to execute tests.
}
if (status != null){
if(!status.open && !status.fixed){
LOGGER.error("Defect with ID '{}' and title '{}' is no longer in an open status and is not fixed, for test case '{}'. Update or remove test case.", knownIssue.value(), status.defectTitle, feature.getName())
feature.addInterceptor(new CauseFailureInterceptor("Defect with ID '" + knownIssue.value() + "' and title '" + status.defectTitle + "' is no longer in an open status and is not fixed, for test case '" + feature.getName() + "'. Update or remove test case."))
}else if (status.open && !status.fixed){
LOGGER.warn("Defect with ID '{}' and title '{}' is still open and has not been fixed. Not executing test '{}'", knownIssue.value(), status.defectTitle, feature.getName())
feature.setSkipped(true)
}else if (!status.open && status.fixed){
LOGGER.error("Defect with ID '{}' and title '{}' has been fixed and closed. Remove KnownIssue annotation from test '{}'.", knownIssue.value(), status.defectTitle, feature.getName())
feature.addInterceptor(new CauseFailureInterceptor("Defect with ID '" + knownIssue.value() + "' and title '" + status.defectTitle + "' has been fixed and closed. Remove KnownIssue annotation from test '" + feature.getName() + "'."))
}else { // status.open && status.fixed
LOGGER.warn("Defect with ID '{}' and title '{}' has recently been fixed. Remove KnownIssue annotation from test '{}'", knownIssue.value(), status.defectTitle, feature.getName())
}
}
}
public abstract DefectStatus getDefectStatus(String defectId)
}
public class CauseFailureInterceptor extends AbstractMethodInterceptor{
public String failureReason
public CauseFailureInterceptor(String failureReason = ""){
this.failureReason = failureReason
}
#Override
public void interceptFeatureExecution(IMethodInvocation invocation) throws Throwable {
throw new Exception(failureReason)
}
}
class DefectStatus{
boolean open
boolean fixed
String defectTitle
}
Please don't hesitate to edit the question or to ask more details about the questin.
I know I can log the ArithmeticException of the below method using the aspectJ as,
public void afterThrowingAspect(){
System.out.println("This is afterThrowingAspect() !");
int i=2/0;
System.out.println("i value : "+i);
}
The AspectJ class has,
#AfterThrowing(pointcut = "execution(* com.pointel.aop.test1.AopTest.afterThrowingAspect(..))",throwing= "error")
public void logAfterError(JoinPoint joinPoint,Throwable error) {
System.out.println("Hi jacked Method name : " + joinPoint.getSignature().getName());
log.info("Method name : " + joinPoint.getSignature().getName());
log.info("Error report is : " + error);
}
Normally I can handle exception using the TRY and CATCH block and log the errors in the every CATCH block as ,
public void someMehtod(){
try{
int i=2/0;
System.out.println("i value : "+i);
}catch{ArithmeticException err){
log.info("The exception you got is : " + err);
}
}
But I don't like to do the logging like with every single catch block individually in all the java classes of my project like ,
log.info("The exception you got is : " + err);
I would like to do the logging inside CATCH block in my application using the aspectJ class.
Hope you are all understand my question.Thanks.
Its possible to simply remove the try/catch from your code and simply log the exception in your aspect.
public void someMehtod(){
int i=2/0;
System.out.println("i value : "+i);
}
Because you don't re-throw the exception in the aspect then it won't bubble up. Although this is possible I strongly advise you to think more about what you are trying to do here. Why do you need to log the fact that an exception has been thrown? Exceptions aren't necessarily only for errors but can occur in normal code journeys. Simply logging only the exception name is unlikely to help you debug the problem. Therefore, you will probably want a bespoke log message for each catch block. If you do find repetition you could create a method to log out the result.
Hope this helps,
Mark
I believe that most of you would be thinking that this is the same question you have heard multiple times (and answered ) about string concatenation in Java. But trust me, it is different. In fact, so different that I am even hesitant in posting it here. But anyways, here it is. I have some piece of code which goes like:
public void handleSuccess(String result)
{
result = result.trim();
MessageBox.alert("Information","Result after trimming: '" + result + "'");
result = result.substring(result.indexOf('\n') + 1);
MessageBox.alert("Information","Result after substring: '" + result + "'");
String returns = getReturns();
MessageBox.alert("Information","Returns: '" + returns + "'");
String action = getAction();
MessageBox.alert("Information","Action: '" + action + "'");
String finalResult = result + returns + action;
MessageBox.alert("Information","Final result: '" + finalResult + "'");
}
Now the situation here is that, all of these : getReturns(), result and getAction() return non blank values, and in fact the string finalResult contains the concatenated value after the last line is executed.
So, at Line 1, "result" contains "12/03/2013|04-AERTY|". The value of result remains same at end of line 1,2. getReturns() returns value 12.4724. So at end of line 3, finalResult contains "12/03/2013|04-AERTY|12.4724". getAction() returns "expt". So, at end of line 5, finalResult contains "12/03/2013|04-AERTY|12.4724|expt"
This is , when I debug or run the application in eclipse. As soon as build the same application on a UNIX system to generate a "war" file, and deploy the war on a tomcat server, the problem rears it's ugly head. When I run the application on the deployed war, the last line does not contain the concatenated value. So at the end of line 5, finalResult contains just "12/03/2013|04-AERTY|12.4724". I expected it to contain "12/03/2013|04-AERTY|12.4724|expt" as it does while running in eclipse.
I have tried stringbuffer, stringbuilder and the "+" operator as well, but nothing seems to work. I am not even getting an exception.
Can somebody help me in fixing this or at least enlightening me in what I might be doing wrong here?
Just to stress again, the code on eclipse(which is on a windows machine) and UNIX machine are exactly same. I have done a diff on them.
Here is what I get after putting the message-boxes:
Message-box 1: "Result after trimming: '12/03/2013|04-AERTY|'"
Message-box 2: "Result after substring: '12/03/2013|04-AERTY|'"
Message-box 3:"Returns: '12.4724'"
Message-box 4:"Action: '|expt'"
Message-box 5:"Final result: '12/03/2013|04-AERTY|12.4724|expt'"
Message-box 5 output is the one I receive when I execute code using eclipse
When running on deployed war, Message-box 1-4 have the same output as above, but Message-box 5 says: "Final result: '12/03/2013|04-AERTY|12.4724"
It's not clear where the extra "|" is meant to come from - if getAction() just returns expt, the result would be 12/03/2013|04-AERTY|12.4724|expt.
Anyway, I think it's safe to say that string concatenation will be working fine, and something else is wrong. You should add more diagnostics, logging everything:
public void handleSuccess(String result) {
result = result.trim();
log.info("Result after trimming: '" + result + "'");
result = result.substring(result.indexOf('\n') + 1);
log.info("Result after substring: '" + result + "'");
String returns = getReturns();
log.info("Returns: '" + returns + "'");
String action = getAction();
log.info("Action: '" + action + "'");
// It's not clear what this is meant to do. I suggest you remove it and
// use logging instead.
MessageBox.alert("Information", "The selected action is " + action, null);
String finalResult = result + returns + action;
log.info("Final result: '" + finalResult + "'");
I suspect you'll find that action is an empty string in the broken case.
Note that I've added quotes round each of the logged values, very deliberately. That means that if there's some unprintable character at the end of a string which causes problems, you should be able to detect that in the logging.
EDIT: As per the comment thread, when these were turned into message boxes (as it turns out this is running in GWT) it looks like there's something wrong with the early strings, as the closing ' isn't seen in diagnostics, in the broken case. The OP is going to investigate further.
I have a generic function that prints exceptions (using log4j):
private void _showErrorMessage(Exception e) {
log.error(e.getClass() + ": " + e.getMessage() + ": " + e.getCause() + "\n" + e.getStackTrace().toString());
}
Instead of seeing the stack trace I'm seeing:
[Ljava.lang.StackTraceElement;#49af7e68
How can I view the stack trace of the exception properly?
update
log.error(e) <- shows the error, but doesn't show stack trace
Your logging framework should have the ability to log exceptions, so simply passing the exception to the proper .error(Object, Throwable) call should be enough:
log4j can do it
commons logging can do it
java.util.logging can do it
If your logging framework can't do that, or you need the stack trace in a String for any other reason, then it becomes a bit harder. You'll have to create a PrintWriter wrapping a StringWriter and call .printStackTrace() on the Exception:
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();
Have you tried?
private void _showErrorMessage(Exception e) {
log.error("Hey! got an exception", e);
}
I use the ExceptionUtils#getFullStackTrace method of Jakarta Commons Lang
Throwable.getStackTrace returns an array of StackTraceElements, hence the toString method is returning a textual representation of the array itself.
In order to actually retrieve the stack trace information, one would have to go through each StackTraceElement to get more information.
You could also look at the Guava libraries from Google.
Throwables.getStackTraceAsString(Throwable throwable)
The exact answer to your question is that you should call Log4J like this:
private void _showErrorMessage(Exception e) {
log.error(e.getClass() + ": " + e.getMessage() + ": " + e.getCause(), e);
}
Although I would dispense with the call to e.getCause() because the stacktrace will give that to you anyway, so:
private void _showErrorMessage(Exception e) {
log.error(e.getClass() + ": " + e.getMessage(), e);
}
ExceptionUtils is fine if you really need a string of the stacktrace, but since you are using Log4J, you lose a lot by not utilizing its built in exception handling.
Exception Stacktrace logging shows two methods for this purpose, one based on Apache Commons and another using the standard JDK method.