Unable to import java.net.URLEncoder in groovy - java

I'm pretty new in groovy, trying to encode a URL in my first piece of groovy code.
Here is a section of my code:
import java.net.URLEncoder
String url = baseUrl + URLEncoder.encode(parameter);
It looks quite the same as many examples I check online but it throws error as below.
General error during canonicalization: Importing [java.net.URLEncoder] is not allowed
java.lang.SecurityException: Importing [java.net.URLEncoder] is not allowed
I have also tried to use the class directly as illustrated here
String url = baseUrl + java.net.URLEncoder.encode(parameter);
and another version:
String url = baseUrl + URLEncoder.encode(parameter);
both throw me error:
General error during canonicalization: Indirect import checks prevents usage of expression
java.lang.SecurityException: Indirect import checks prevents usage of expression
appreciate if any guru can help clear the doubts.

According to http://groovy.codehaus.org/Differences+from+Java, java.net.* package in Groovy is imported by default, which means java.net.URLEncoder is also imported. Use it without import.
Edit: For me, using this Groovy code:
println URLEncoder.encode("URL encoding fine!")
prints URL+encoding+fine%21

Related

Getting the hash value of String

I am having the following code to get the hash value of String:
package encryption;
import java.security.MessageDigest;
public class MessageDigestExample {
public static void main(String[] args)throws Exception{
String input = "This is a message";
MessageDigest hash = MessageDigest.getInstance("SHA1");
System.out.println("input : " + input);
hash.update(Utils.toByteArray(input));
System.out.println("digest : " + Utils.toHex(hash.digest()));
} }
I am getting this exception at the moment:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Utils cannot be resolved
Utils cannot be resolved
I added apache-storm-1.2.2 lib, but does not work,
Any help, please!
You are using the (class?) name Utils, without ever importing it.
You probably lack some import what.ever.Utils statement here.
Beyond that, you get a runtime exception because you try to run code that did not compile. Although some IDEs, like eclipse, allow for that, it is in generally a bad idea, especially when you are a newbie to Java. You should always fix all compiler errors before you try to run a class.
You should import the Utils library you are using. If I am reading it correctly, add the following line underneath the package section:
import org.apache.storm.utils.Utils;
This should resolve the library Utils for you

JMeter Bean Shell Sampler error "...Static method get( java.lang.String ) not found in class'java.nio.file.Paths" when copying files

I am attempting to copy and rename a file on my local machine (Win 7) using Bean Shell Sampler in JMeter 3.0 (Java v1.8). The idea is to create the new file with a unique name and have the name saved as a variable that can be used in place of the file name in an FTP PUT request.
Here is the code I am using for the copy and rename:
import java.text.*;
import java.nio.file.StandardCopyOption.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
String filename = new SimpleDateFormat("dd-MM-yyyy_hh:mm:ss").format(new Date())+".xlsx";
log.info(filename);
Path source = Paths.get("C:/dropfile/qatp/QATP_GuestRecords.xlsx");
Path target = Paths.get("C:/dropfile/qatp/"+filename);
Files.copy(source, target, REPLACE_EXISTING);
The error I am receiving in the log:
ERROR - jmeter.util.BeanShellInterpreter: Error invoking bsh method:
eval Sourced file: inline evaluation of: ``import java.text.; import
java.nio.file.StandardCopyOption.; import java.io.IO . . . '' : Typed
variable declaration : Error in method invocation: Static method get(
java.lang.String ) not found in class'java.nio.file.Paths'
I have been searching for an answer to this issue and came across a solution where the suggestion was:
"My guess is that the problem is that it's not populating the varargs parameter. Try:
Path target = Paths.get(filename, new String[0]);"
I tried this solution by modifying my code like so:
import java.text.*;
import java.nio.file.StandardCopyOption.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
String filename = new SimpleDateFormat("dd-MM-yyyy_hh:mm:ss").format(new Date())+".xlsx";
log.info(filename);
Path source = Paths.get("C:/dropfile/qatp/QATP_GuestRecords.xlsx", new String[0]);
Path target = Paths.get("C:/dropfile/qatp/"+filename, new String[0]);
Files.copy(source, target, REPLACE_EXISTING);
And received this error:
ERROR - jmeter.util.BeanShellInterpreter: Error invoking bsh method:
eval Sourced file: inline evaluation of: ``import java.text.; import
java.nio.file.StandardCopyOption.; import java.io.IO . . . '' : Typed
variable declaration : Method Invocation Paths.get
Does anyone know why I am hitting this error and how to get around it?
Even in plain old Java this is a misleading use of Paths.get, which takes an URI, or an array of strings (varargs). See javadoc.
In Java what you tried works because the static typing allow the compiler to determine that you are passing an array of a single String. Apparently BeanShell does not and gets confused. The trick suggested in the other answer is not a good one in my opinion: again in Java it would work, by joining the two strings (2nd one is empty, so result is 1st string, which is what you want), but it confuses BeanShell all the same because there is another static get method that takes 2 arguments.
If you already have the path as a single String, try this instead:
Path source = new File("C:/dropfile/qatp/QATP_GuestRecords.xlsx").toPath();
Alternatively, you could use Paths.get like this:
Path source = Paths.get("C:", "dropfile", "qatp", "QATP_GuestRecords.xlsx");
Or like this (varargs is syntaxic sugar to help pass an array):
Path source = Paths.get(new String [] { "C:/dropfile/qatp/QATP_GuestRecords.xlsx" });
It's perfectly valid to pass fragments of path as arguments, or the entire path string as single argument, but that seems to trip BeanShell, so, better avoid Paths.get in BeanShell, unless you pass an array explicitly as in last example.
Beanshell != Java, it doesn't support all the Java features (think about it as about Java 1.5 and amend your code appropriately.
So I would recommend switching to JSR223 Sampler and Groovy language, Groovy is much more Java-compliant and performs much better.
Also be aware that you can use FileUtils.copyFile() method which will work for both Beanshell and/or Groovy
import org.apache.commons.io.FileUtils;
import java.text.SimpleDateFormat;
String filename = new SimpleDateFormat("dd-MM-yyyy_hh:mm:ss").format(new Date()) + ".xlsx";
FileUtils.copyFile(new File("/tmp/QATP_GuestRecords.xlsx"), new File("/tmp/" + filename));
See Groovy is the New Black article for more information on using Groovy language in JMeter test scripts.

Compiling ISO SQL-2003 ANTLR Grammar

I am trying to compile the ISO-SQL 2003 grammar from here
http://www.antlr3.org/grammar/1304304798093/SQL2003_Grammar.zip. All three versions of it can be found here http://www.antlr3.org/grammar/list.html.
These are the steps I followed,
java -jar antlr-3.3-complete.jar -Xmx8G -Xwatchconversion sql2003Lexer.g
java -jar antlr-3.3-complete.jar -Xmx8G -Xwatchconversion sql2003Parser.g
javac ANTLRDemo.java
ANTLRDemo.java file:
import org.antlr.runtime.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class ANTLRDemo {
static String readFile(String path) throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, "UTF-8");
}
public static void main(String[] args) throws Exception {
ANTLRStringStream in = new ANTLRStringStream( readFile(args[0]) );
sql2003Lexer lexer = new sql2003Lexer(in);
CommonTokenStream tokens = new CommonTokenStream(lexer);
sql2003Parser parser = new sql2003Parser(tokens);
parser.eval();
}
}
First two steps work fine, then while compiling my main class I get a lot of errors related to Java syntax like these:
./sql2003Parser.java:96985: error: not a statement
$UnsignedInteger.text == '1'
./sql2003Parser.java:96985: error: ';' expected
$UnsignedInteger.text == '1'
./sql2003Parser.java:102659: error: unclosed character literal
if ( !(((Unsigned_Integer3887!=null?Unsigned_Integer3887.getText():null) == '01')) ) {
Please let me know if I am doing something wrong in setting up the parser. It would be helpful if someone can show me how exactly to setup this grammar using ANTLR.
Edit: After a little more fiddling, I think that these errors are caused by the actions present in lexer and parser rules. Is there a safe way to overcome this?
You are not doing anything wrong, ANTLR has never been able to generate a working Java parser from these grammar files.
According to a post by Douglas Godfrey to antlr-interest in Oct 2011:
I generated a C parser and lexer. they both generate and compile
successfully
on my machine with 8GB heap allocated to Antlr.
...
I don't believe that it will ever be possible to get a working parser in
Java. A C language parser on the other hand is quite possible.
Yes, basically you’re right. The grammar is broken. But also there is an error in your ANTLRDemo.java as there’s no eval() method in Parser class. You should call method with the name of any rule of the parser grammar e.g. query_specification(). In the grammar itself there were some errors looking as a typo, some undefined Java error() method calls, skip() calls in parser that are only suitable in lexer. You see all fixes in this commit. I’ve published my research in this GitHub repository.
I started to fix obvious errors of the grammar, which led to the compilation errors in generated java code. I had the same errors that you posted. Eventually I have fixed all Java syntax errors but faced another one which it impossible to fix directly because it originates from limitation of JVM, the compilation error: code too large. Reading ANTLR mailing list there was a hint to extract some static members of the huge classes into separate interfaces and “implement” them to have a sort of multiple inheritance. With trial and error I ended up with 6 interfaces ”imlemented” by parser in sql2003Parser.java.
But still there are 2 problems:
Wrong start rule. Douglas Godfrey wrote grammar that starts with sql2003Parser rule. Unfortunately if you call parser by this start rule, it won’t parse correctly even simplest select a from b. So I call parser by query_specification rule to parse SELECT clause only.
Some other errors in grammar. I didn’t dig too deep in the grammar but query_specification fails to parse some random complex SQLs.

Jackcess compilation error

i have been searching around for a few days for the answer to this and i just can't seem to get it to work. I have seen exact examples where it is working for them and I try exactly what they do and it is just not working for me.
Basically what i am trying to do is open a local access DB. I have tried numerous methods and this Jackcess seems by far the best library to use, so i am trying to get it to work with that. I have read their cookbook and gone through all of that, and still no luck so i am coming to you guys in the hope of finding a good solution (i have not posted this question anywhere yet). Here is my code (the relevant part)
The only syntax error i am getting is "DatabaseBuilder.Open" and the error is it cannot find the method, even though i have the libraries included for IO
import com.healthmarketscience.jackcess.*;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
Database db = DatabaseBuilder.open(new File("my.mdb"));
try {
Table table = db.getTable("Teams");
} catch (IOException ex) {
Logger.getLogger(Teams.class.getName()).log(Level.SEVERE, null, ex);
}
}
Any help would be greatly appreciated!
The program fails to debug once I have click this buttone the only actual message i can fine is
"Cannot find symbol
Symbol : Method Open(file)
Location : variable.DatabaseBuilder of type Object"
To use Jackcess you must have at least the following items in the build path for your Java project (or on your CLASSPATH):
the Jackcess JAR file itself, and
the JAR files for its two mandatory compile-time dependencies from Apache: commons-lang and commons-logging.
In the Eclipse IDE that will look something like this:

jpype+pdfbox class not found

I'm attempting to use JPype to call Apache Pdfbox from Python, and am having some difficulty actually importing the classes. It doesn't seem to be able to read them from the jar file in the class path.
from jpype import java, startJVM, shutdownJVM, JPackage, JClass, getDefaultJVMPath, nio
import sys, os, codecs
pdfbox_lib = "lib/pdfbox-1.6.0.jar"
classpath = '-Djava.class.path=' + pdfbox_lib + os.pathsep + '.'
startJVM(getDefaultJVMPath(), '-Xmx512m', classpath)
stream = java.io.FileInputStream(java.io.File("test.pdf"))
pdfparser = JPackage('org.apache.pdfbox.pdfparser')
parser = JClass('org.apache.pdfbox.pdfparser.PDFParser')
At this point, the script errors out with the following:
java.lang.ExceptionPyRaisable: java.lang.Exception: Class org.apache.pdfbox.pdfparser.PDFParser not found
I'm running on Linux with Python 2.7, and I know there's nothing wrong with the JPype installation (if there were, the stream declaration would error out). I've also tried various permutations of the class path statement and the JPackage/JClass statements, and nothing seems to matter. Any suggestions would be greatly appreciated!
I figured it out. Three additional jars need to be added to the class path: fontbox-x.x.x.jar, jempbox-x.x.x.jar, and commons-logging.jar.

Categories

Resources