UnitTest (groovy + grails) - Cannot teardown metaclass - java

I'm having a problem when I try to clean the class.
void testFileExists() {
FileObject file = EasyMock.createMock(FileObject.class)
VfsFileSystemManager.metaClass.getFile = {String s, String a ->return file}
FileObject.metaClass.exists = {-> return true}
assertEquals true, siteManagerHelper.fileExists(STRING, STRING)
}
void testFileNotExists() {
FileObject file = EasyMock.createMock(FileObject.class)
VfsFileSystemManager.metaClass.getFile = {String s, String a ->return file}
FileObject.metaClass.exists = {-> return false}
assertEquals false, siteManagerHelper.fileExists(STRING, STRING)
}
When I run one at the time, they work fine, but if I run both at the same time, exists() always return true (if I change the first .metaclass for false, it returns false). So I assume it's not tearing down the metaclass.
The class extends GroovyTestCase, and I checked that I should add:
def remove = GroovySystem.metaClassRegistry.&removeMetaClass
remove FileObject
But it's not working.
Please, help!
EDIT:
I'm using grails 1.3.7 and groovy 1.6.8
private boolean fileExists(String path, String file){
if(path != null && path != ""){
FileObject fileToCheck = fsManager.getFile(path, file)
boolean fileExists = fileToCheck.exists()
logger.debug "File exists? ${fileExists}"
return fileExists
}
logger.debug "The path is null or empty"
return false
}

I faced a similar issue (Grails 2.2.0) and I was able to surmount it by following the below:
Use GroovySystem.metaClassRegistry.removeMetaClass(FileObject.class) in the end of the test method to tear down
Use FileObject.metaClass = null in test class tearDown()
I still wonder why do we need to use both tearDown simultaneously.
Note:- In my case I metaClassed a Groovy Object as compared to a Java Object.

Related

How to invoke a method of a class from another project by Rest Api in Java

I need to call a method from another project in eclipse, I tried to add the project to classpath of the current project (Right click on project -> properties -> java build path -> projects) but I got an error and exception (java.lang.NoClassDefFoundError) and ( java.lang.ClassNotFoundException) and I couldn't fix that. I know there is another way to do this job by using Rest Api. please help me!! Thanks.
I want to call (getSample2) to my current project:
public List<String> getSample2 (String fileName, int minFrequency, int maxFrequency) {
List<SampleMultyFreq> fd = getSamples(fileName, minFrequency, maxFrequency);
List<String> ls = new ArrayList<>();
for(SampleMultyFreq ss: fd) {
ls.add(ss.getFrequencies().toString());
}
return ls;
}
I created this method in the same project with (getsample2) for calling (getSample2) method easy. I don't know it is a right way or not.
#GET
#Path("GET_SAMPLE_API")
public Response getSampleApi (String fileName) {
List<String> ss = new DataReader2NewPods().getSample2(fileName, 1, 9);
return Response.status(Response.Status.OK).entity(ss).build();
}
and Finally I wrote this method in my current project for sending request to get (getSampleApi) like this but I don't know the methods that I used is correct or not I copied another method that was for download a file from AWS cloud by using rest api:
public String getSampleMethdByRest (String fileName) {
if (StringUtils.isNoneBlank(fileName)) {
System.out.println(" print to test 1:");
String url = "http://localhost:8080/project-dev/ss/GET_SAMPLE_API/";
final Response resp = client.target(url).request(MediaType.APPLICATION_OCTET_STREAM).get(Response.class);
if (resp.getStatus() == Response.Status.OK.getStatusCode()) {
System.out.println(" print to test 2:");
InputStream inputStream = (InputStream)resp.getEntity();
}
}
System.out.println(" print to test 3:");
return Constants.root + File.separator +
Config.getInstance().getProperties().getProperty("temp_folder") + File.separator + fileName;
}
and this is the output:
print to test 1:
print to test 3:
C:\home\project\temp_folder\data_98F4ABFB7806_16480262_1595325764285_len_2528.txt
Would you please help me. many thanks in advance.

Why default parser (using commons-cli) does not throw exception when option is not recognized?

I would like to have a printed usage help message, when option which is specified as an program argument is not valid (not available in predefined options list).
CommandLineParser parser = new BasicParser();
try {
CommandLine line = parser.parse(getOptions(), args);
}
catch( ParseException exp ) {
getLogger().info("Invalid command line option name. "+exp.getMessage());
HelpFormatter hf = new HelpFormatter();
hf.printHelp("destDir", getOptions());
return false;
}
return true;
I type as an parameter 'Test' string. I was thinking, that invalid options cause parser to throw ParseException, however it's not. How can I achieve that behaviour ? Is it possible with this library at all ? Now it just ommit paremeters which are not valid.
UPDATE
Actually it throws exception when option has a '-' prefix. So '-Test' cause throwing exception, but 'Test' not. My question anyway is still valid, how to force parser to throw exception on invalid parameter
Command lines have two types of entry other than the program name, Options (which are specified with a - or --) and what I will call parameters (which probably have a better name but I don't know what it is!) which don't have a prefix. For example, for ls:
ls -la foo
The options are -l and -a, and parameter is foo (the directory to list). When you parse a command line with commons-cli it only cares about the options, it ignores everything else. Which is why it doesn't fail if you add Test (not an option) but does if you add -Test.
Although answer provided by adamreeve is really fine and I accept it, I've decided to extend default parser capabilities to prevent typing invalid option even without '-' or '--' symbols. I made my own custom parser :
public class StrictParser extends Parser {
#Override
protected String[] flatten(Options opts, String[] arguments, boolean stopAtNonOption) {
return arguments;
}
#Override
public CommandLine parse(Options options, String[] arguments, boolean stopAtNonOption) throws ParseException {
CommandLine cmd = null;
List<String> tokenList = Arrays.asList(flatten(getOptions(), arguments, stopAtNonOption));
ListIterator<String> iterator = tokenList.listIterator();
boolean eatTheRest = false;
setOptions(options);
cmd = super.parse(options, arguments, stopAtNonOption);
while (iterator.hasNext()) {
String token = (String) iterator.next();
if (!token.startsWith("--") && !token.startsWith("-")) {
if (stopAtNonOption) {
throw new UnrecognizedOptionException("Unrecognized option: " + token +". Every option must start with '--' or '-'", token);
}
} else {
eatTheRest = true;
}
if (eatTheRest) {
iterator.next();
}
}
return cmd;
}
}
In this solution any cli parameters typed without '--' or '-' throw UnrecognizedOptionException. This is no perfect solution, but it show how it can be done, and can be a good starting point to other solutions. For instance we could accept options without '--' and '-' but check if that option is correct. Then we need to change
if (stopAtNonOption) {
throw new UnrecognizedOptionException("Unrecognized option: " + token +". Every option must start with '--' or '-'", token);
}
to
if (stopAtNonOption) {
if(!getOptions().hasOption(token)){
throw new UnrecognizedOptionException(
"Unrecognized option: " + token, token);
}
}
(ignore this ugly three nested ifs ;))
This also accepts only one argument per option,but as I've mentioned it's only starting point to implement other modifications to default parser
Yes you can , you have to create custom Exception like:
public class ParseException extends Exception{
ParseException(String msg){
super(msg);
}
}
And into code :
CommandLineParser parser = new BasicParser();
try {
CommandLine line = parser.parse(getOptions(), args);
}
catch( Exception exp ) {
throw new ParseException("Invalid Arguments");
}
return true;
And above method should throw
throws ParseException
So its caller if pass invalid argument will get ParseException

Java Bukkit/Spigot - Block Specified Commands

i'm trying to make a plugin, it must block a specified commands setted by config. i've maked this but it doesn't block any command.
Code:
#EventHandler(priority = EventPriority.HIGHEST)
public void onPreprocess(PlayerCommandPreprocessEvent event)
{
Player player = event.getPlayer();
String command = event.getMessage();
List<String> bCmds = this.plugin.cfg.getStringList("blocked-commands");
for (String bCmd : bCmds)
{
if(command.equalsIgnoreCase(bCmd))
{
event.setCancelled(true);
}
}
}
Config:
blocked-commands:
- /pl
- /op
- /sp
- /gravityblock
PS: I've tried to use:
String command = event.getMessage().subString(1);
Thanks for Help... :)
Registered events? implemented listner?
Also your code will not work with additional arguments in the command.
If it contains spaces, split it with " " and get the first element to just get the command
if (cmd.contains(" ")) cmd = cmd.split(" ")[0];
As stated by Bukkit's wiiki, the priorities are called in the following order:
EventPriority.LOWEST
EventPriority.LOW
EventPriority.NORMAL
EventPriority.HIGH
EventPriority.HIGHEST
EventPriority.MONITOR
Maybe you could try to use the Lowest priority, so the event gets cancelled before the command is handled.
I also believe that the command might have arguments, so it might not be equal to the string provided, you should also try
String command = event.getMessage();
if (command.toLowerCase().startsWith("/command") ) {
//cancel
}

getResourceAsStream returning null despite called file being in same dir as class getResourceAsStream is called in

I imported an Android sample coded by Amazon involving AWS's DynamoDB which I got from here and was presumably written for Eclipse:
https://github.com/awslabs/aws-sdk-android-samples/tree/master/DynamoDBMapper_UserPreference
Since Android Studio (0.8.1) uses gradle instead of ant, naturally things got auto-moved around in terms of dir structure when importing so (part of) it looks like this:
PropertyLoader gets the TVM credential info it needs to connect to the database DynamoDB from AwsCredentials.properties. Relevant methods:
public class PropertyLoader {
private boolean hasCredentials = false;
private String tokenVendingMachineURL = null;
private boolean useSSL = false;
private String testTableName = null;
private static PropertyLoader instance = null;
public static PropertyLoader getInstance() {
if ( instance == null ) {
instance = new PropertyLoader();
}
return instance;
}
public PropertyLoader() {
try {
Properties properties = new Properties();
properties.load( this.getClass().getResourceAsStream( "AwsCredentials.properties" ) );
this.tokenVendingMachineURL = properties.getProperty( "tokenVendingMachineURL" );
this.useSSL = Boolean.parseBoolean( properties.getProperty( "useSSL" ) );
this.testTableName = properties.getProperty( "testTableName" );
if ( this.tokenVendingMachineURL == null || this.tokenVendingMachineURL.equals( "" ) || this.tokenVendingMachineURL.equals( "CHANGEME" ) || this.testTableName.equals( "" ) ) {
this.tokenVendingMachineURL = null;
this.useSSL = false;
this.hasCredentials = false;
this.testTableName = null;
}
else {
this.hasCredentials = true;
}
}
catch ( Exception exception ) {
Log.e( "PropertyLoader", "Unable to read property file." );
}
}
However the getResourceAsStream line properties.load( this.getClass().getResourceAsStream( "AwsCredentials.properties" ) ); returns null. As you can see in my screenshot, AwsCredentials.properties is in the same dir as PropertyLoader and matches the case, which is all that should be required based on my readings of the method:
http://mindprod.com/jgloss/getresourceasstream.html
getResourceAsStream() is always returning null
I have tried other things such as prefixing "\" (i.e. properties.load( this.getClass().getResourceAsStream( "\AwsCredentials.properties" ) ); and copying the credentials file and placing in the src folder (you can't see it in this screenshot because the explorer sorts by filetype(?) and places 'main' first, but it's there) as per this:
getResourceAsStream returning null
However, that hasn't fixed the issue either. Having tried these options and done research, I'm confused as to why it's returning null. How can I fix this?
Created a dir called resources under /src/main/ and placed AwsCredentials.properties there and used
properties.load( PropertyLoader.class.getClassLoader().getResourceAsStream( "AwsCredentials.properties" ) );
instead of
properties.load( this.getClass().getResourceAsStream("AwsCredentials.properties" ) );
Not as elegant as I would like, but it works.
For up to a day I was struggling with this as well. And finally I was able to resolve this very neatly. The problem is not in the JAVA but in the all project structure. E.g. in Android Studio the whole project is under src/main/java whereas main is a flavour of the project. So if you've file(-s) to read from in source's package (e.g.) com/my/example/app you have to edit the build.gradle file for read (clazz.getResourceAsStream(file)) to work properly. I.e. under android define sourceSets like this:
android {
/* ... Your stuff ... */
sourceSets {
// Lets have two flavours to make it more clear
main {
resources.srcDirs = ['src/main/java']
}
flavourFoo {
resources.srcDirs = ['src/flavourFoo/java']
}
}
}
Hope this helps!

Object doesn't support this method or property error

Hi I created a jni jar and i call the jar using applet in java script. I use the following applet tag to create a object to call jar functions through java script. when i call the function i got the following error Object doesn't support this method or property.
Here is my code.
document.write('<applet code="BiomAPI.Legend.class" width="0" height="0" archive="BiomAPI.jar" id="Obj"></applet>');
function GetTemplateAccurate (sUserID,iFingerID)
{
document.getElementsByName("Enroll")[0].value = "";
document.getElementsByName("Image")[0].value = "";
var lsFeature = null;
var lsImage = null;
Obj.EnableLog(0);
Obj.LocalFilePath("C:\\IMAGE\\");
Obj.EnableEncryption(0);
Obj.SaveImage(1);
Obj.SessionID("abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde");
Obj.GetFeatureAccrual(sUserID,iFingerID);
lsFeature = Obj.Feature();
lsImage = Obj.StringImage();
if (lsFeature != null && lsImage != null )
{
document.getElementsByName("Enroll")[0].value = lsFeature;
document.getElementsByName("Image")[0].value = lsImage;
alert("Scanner Working Properly");
}
else
{
alert("Fingerprint not captured");
}
}
function GetTemplate(sUserID,iFingerID)
{
document.getElementsByName("Verify")[0].value = "";
var lsFeature = null;
Obj.EnableLog(0);
Obj.LocalFilePath("C:\\IMAGE\\");
Obj.EnableEncryption(0);
Obj.SessionID("abcde");
Obj.SaveImage(1);
Obj.GetFeature(sUserID,iFingerID);
lsFeature = Obj.Feature();
lsImage = Obj.StringImage();
if (lsFeature != null)
{
document.getElementsByName("Verify")[0].value = lsFeature;
alert("Scanner Working Properly");
}
else
{
alert("Fingerprint not captured");
}
}
as exception itself is describing:
Object doesn't support this method or property error
the property or method you are trying to access with an object is not supported by that object. Please debug or see on error console the object throwing exception and find whether it support that property you are trying to access.

Categories