uso e declaração de namespace Saxon em codigo java - java

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.

Related

CRLF Injection vulnerability while using slf4j LOGGER in Veracode (CWE 117)

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()
}

How to fix "GetStatus Write RFID_API_UNKNOWN_ERROR data(x)- Field can Only Take Word values" Android RFID 8500 Zebra

I am trying to develop and application to read and write to RF tags. Reading is flawless, but I'm having issues with writing. Specifically the error "GetStatus Write RFID_API_UNKNOWN_ERROR data(x)- Field can Only Take Word values"
I have tried reverse-engineering the Zebra RFID API Mobile by obtaining the .apk and decoding it, but the code is obfuscated and I am not able to decypher why that application's Write works and mine doesn't.
I see the error in the https://www.ptsmobile.com/rfd8500/rfd8500-rfid-developer-guide.pdf at page 185, but I have no idea what's causing it.
I've tried forcefully changing the writeData to Hex, before I realized that the API does that on its own, I've tried changing the Length of the writeData as well, but it just gets a null value. I'm so lost.
public boolean WriteTag(String sourceEPC, long Password, MEMORY_BANK memory_bank, String targetData, int offset) {
Log.d(TAG, "WriteTag " + targetData);
try {
TagData tagData = null;
String tagId = sourceEPC;
TagAccess tagAccess = new TagAccess();
tagAccess.getClass();
TagAccess.WriteAccessParams writeAccessParams = tagAccess.new WriteAccessParams();
String writeData = targetData; //write data in string
writeAccessParams.setAccessPassword(Password);
writeAccessParams.setMemoryBank(MEMORY_BANK.MEMORY_BANK_USER);
writeAccessParams.setOffset(offset); // start writing from word offset 0
writeAccessParams.setWriteData(writeData);
// set retries in case of partial write happens
writeAccessParams.setWriteRetries(3);
// data length in words
System.out.println("length: " + writeData.length()/4);
System.out.println("length: " + writeData.length());
writeAccessParams.setWriteDataLength(writeData.length()/4);
// 5th parameter bPrefilter flag is true which means API will apply pre filter internally
// 6th parameter should be true in case of changing EPC ID it self i.e. source and target both is EPC
boolean useTIDfilter = memory_bank == MEMORY_BANK.MEMORY_BANK_EPC;
reader.Actions.TagAccess.writeWait(tagId, writeAccessParams, null, tagData, true, useTIDfilter);
} catch (InvalidUsageException e) {
System.out.println("INVALID USAGE EXCEPTION: " + e.getInfo());
e.printStackTrace();
return false;
} catch (OperationFailureException e) {
//System.out.println("OPERATION FAILURE EXCEPTION");
System.out.println("OPERATION FAILURE EXCEPTION: " + e.getResults().toString());
e.printStackTrace();
return false;
}
return true;
}
With
Password being 00
sourceEPC being the Tag ID obtained after reading
Memory Bank being MEMORY_BANK.MEMORY_BANK_USER
target data being "8426017056458"
offset being 0
It just keeps giving me "GetStatus Write RFID_API_UNKNOWN_ERROR data(x)- Field can Only Take Word values" and I have no idea why this is the case, nor I know what a "Word value" is, and i've searched for it. This is all under the "OperationFailureException", as well. Any help would be appreciated, as there's almost no resources online for this kind of thing.
Even this question is a bit older, I had the same problem so as far as I know this should be the answer.
Your target data "8426017056458" length is 13 and at writeAccessParams.setWriteDataLength(writeData.length()/4)
you are devide it with four. Now if you are trying to write the target data it is longer than the determined WriteDataLength. And this throws the Error.
One 'word' is 4 Hex => 16 Bits long. So your Data have to be filled up first and convert it to Hex.

How to create specific error messages based on parse exceptions in JavaCC

I'm making a JavaCC program to accept a certain language. I've done this but cannot understand how to use a generated ParseException to determine the issue in the input, and customise the output error message.
So far my code looks like:
try {
task parser = new task(System.in);
parser.start();
System.out.println("YES"); // If accepted print YES.
} catch (ParseException e) {
System.out.println("NO"); // If rejected print NO.
switch (e) {
case 1:
System.err.println("Some error case")
case 2:
...
}
}
Some sources I've looked at are the documentation for ParseException and the JavaCC error handling pages. Neither have helped me understand much better.
If anyone could help/hint I would be really thankful.
You can always throw a ParseException with a custom string. For example
void Primary() : {}
{
<INT>
|
"("
|
{throw new ParseException("At "+getCoords()
+" there was \""+ getToken(1).image
+ "\", but the parser expected either"
+ " a \"(\" or an integer literal.");}
}
If you are willing to go to enough effort, it should be possible to create a parser that never throws a ParseException that doesn't have a custom message.

Is it possible to call quickfix solutions(eclipse) for specific(error/s)?

I have a program which scans a Java file for errors. I call the compiler from Eclipse and run a scan on the Java file and get the line numbers, start position and end positon as output. I have written a program to extract the error from the file.
What I want to do is to have access to the quickfix component in eclipse, have a list of possible fixes for the problem, and print that list to the console.
Below is a portion of the program of how I called the compiler and got the details printed on the console:
Iterable fileObjects = fileManager.getJavaFileObjectsFromStrings(
Arrays.asList(fileToCompile));
CompilationTask task = compiler.getTask(null, fileManager, listener, null,
null, fileObjects);
Boolean result = task.call();
if(result == true) {
System.out.println("Compilation has succeeded");
}
myerrors = listener.getlistofErrors();
for (CaptureErrors e : myerrors) {
System.out.println("Code: " + e.getCode());
System.out.println("Kind: " + e.getKind());
System.out.println("Line Number: " + e.getLinenumber());
// System.out.println("Message: "+ e.getMessage(Locale.ENGLISH));
// System.out.println("Source: " + diagnostic.getSource());
System.out.println("End position"+ e.getEndposition());
System.out.println("Position: "+ e.getPosition());
System.out.println("\n");
}
class MyDiagnosticListener implements DiagnosticListener {
List<CaptureErrors> errors = new ArrayList<CaptureErrors>();
public void report(Diagnostic diagnostic) {
CaptureErrors single_error = new CaptureErrors(diagnostic.getCode(),
diagnostic.getKind(), diagnostic.getLineNumber(),
diagnostic.getMessage(Locale.ENGLISH), diagnostic.getPosition(),
diagnostic.getEndPosition());
errors.add(single_error);
}
public List<CaptureErrors> getlistofErrors() {
return errors;
}
}
I also have a program to go to the line numbers and extract the text(error) at specific positions.
How can I call eclipse quickfix solutions for the specific errors that I find?
Yes, it is possible. The exact details are a bit larger than can easily be encompassed in even a StackOverflow answer.
Eclipse is extended through the use of plug-ins. A "Hello World" plugin is detailed here, and after you get through the initial learning curve, you can download other plugins to get a feel for how eclipse works internally.
I imagine that you would do well to examine the current code highlighting capabilities of eclipse and read the source code for those plugins as a guide, but only after you get some idea of how plugin development works.

Java Error Catching Issue

I have a try/catch thing set up where it will catch all exceptions and then display the error.
Here is my code:
try {
//CODE THAT COULD ERROR HERE
} catch (final Exception e) {
System.err.println("Unexpected error: " + e.getStackTrace()[0]);
}
The above code gives me the LAST class that had the error. How do I detect the LAST class of MY PROGRAM that had the error?
Example Output: "Unexpected error: package.ClassName.method(ClassName.java:46)"
I want it to output the line of my program that had the error, not the line of a built-in java class that error-ed because of my program.
e.printStackTrace()
might make you happier. Or print the top of the array of stack trace entries available from the appropriate method.
http://docs.oracle.com/javase/6/docs/api/java/lang/Throwable.html#getStackTrace()
returns them. The first one is what you are asking for.
You can use getStackTrace to get an array of StackTraceElement instances, and filter that based on your package and/or class names (using getClassName for each element, which gives you the fully-qualified class name for that stack trace frame). That would let you winnow it down to your code rather than the JDK class the exception originated in.
try {
//error producing code
} catch (Exception e) {
for (StackTraceElement s : e.getStackTrace()) {
if (!s.getClassName().startsWith("java.")) {
System.out.println("file name: " + s.getFileName());
System.out.println("class name: " + s.getClassName());
System.out.println("method name: " + s.getMethodName());
System.out.println("line number: " + s.getLineNumber());
System.out.println();
//break; // will be the highest non java package...
}
}
}
You of course could switch it to be package specific so if (s.getClassName().startsWith("com.company")) { so it wont return for a third party library or something in the sun package or other non java package.

Categories