Jruby embedded modules and classes - java

I have a ruby file as follows:
module Example
class Myclass
def t_st
"Hello World!"
end
end
end
now if this was just a class I would be able to use the following java code:
ScriptEngine jruby = new ScriptEngineManager().getEngineByName("jruby");
jruby.eval(new BufferedReader(new FileReader("example.rb")));
Object example = jruby.eval("Myclass.new");
However, this class rests inside a module. Calling the same code as above produces the error:
Exception in thread "main" org.jruby.embed.EvalFailedException: uninitialized constant myclass
In addition, calling:
Object example = jruby.eval("Example");
The module returns no error. So one would assume this follows the format for Ruby.
Object example = jruby.eval("Example::myclass.new");
Again however, I get the same error as before.
Can anyone help? As there is little documentation on JRuby?
Thanks

Make sure that you do not have syntax errors. Usually I get those errors when I'm not paying attention to what I write...
Secondly, you cannot write the following:
Object example = jruby.eval("Myclass.new");
The reason being that your class is in a module. Instead, use the this:
Object example = jruby.eval("Example::Myclass.new");
Other than that, I don't know what the problem could be. For myself, I was able to run the following code under Java 1.6 and with jruby-engine.jar and jruby-complete-1.4.0.jar under my classpath.
package test;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class MyJavaClass {
public static void main(String arg[]) throws ScriptException,
FileNotFoundException {
ScriptEngine jruby = new ScriptEngineManager().getEngineByName("jruby");
jruby.eval(new BufferedReader(new FileReader("example.rb")));
Object example = jruby.eval("Example::Myclass.new");
jruby.put("a", example);
System.out.println(jruby.eval("$a.t_st"));
}
}

Related

Access files under a package in java

I have the package structure something like this
src
main
java
com
org
-- Loader.java
resources
schemas
-- a.schema
-- b. schema
Now I want to be able to access the list of schemas under the schema folder which could vary with time from the Loader class. I package it as a jar and in runtime access all the files under the schema folder. How can I do it?
Do this inside Loader.java:
InputStream in = Loader.class.getResourceAsStream("/data/schemas/a.schema");
The leading slash means from starting from the root of classpath (i.e. your JAR file).
Using java 8, you should get it easily. See below code:
import java.util.stream.*;
import java.nio.file.*;
import java.util.*;
import java.io.*;
public class HelloWorld{
public static void main(String []args) throws IOException {
try (Stream<Path> filePathStream = Files.walk(Paths.get("/data/schemas/"))) {
List<File> filesInFolder = filePathStream.filter(Files::isRegularFile)
.map(Path::toFile)
.collect(Collectors.toList());
System.out.println(filesInFolder);
}
}
}
here the try-with-resource constructs ensures that the stream is closed automatically after using.

FileReader is already defined in this compilation unit error Java

So I'm working on reading in a ".txt" file to use it to implement Dijkstra's algorithm, but every time I try to compile it gives me a "FileReader is already defined in this compilation unit" error while highlighting where I imported it in the beginning. If I take this out, however, it throws a constructor error when I'm trying to read in the file that it's of the wrong type. What am I missing here??
Here is my code:
import java.io.BufferedReader;
import java.io.File;
//import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class FileReader
{
public ArrayList main1()
{
System.out.println("got here");
try
{
BufferedReader in = new BufferedReader(new FileReader(new File("input1.txt")));
I can provide more if needed, but this is where all of the errors crop up.
Your class is named the same as FileReader in the java.io package (you have commented out above). Rename your class to something else like TextFileReader or InputFileReader or use the fully qualified class name for java.io.FileReader.
Just rename your class "FileReader" to different toxicity, in order not to be confused.

Method undefined for type Java

Having real trouble figuring out where i'm going wrong on this one. Building a system using WEKA in java to study associations and am trying to implement the Apriori algorithm. Currently this is the code:
package model;
import weka.associations.*;
import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;
public class Apriori {
public static void main(String args[]) throws Exception {
String dataset = "/Users/andrew/workspace/Movies/src/data/tagsfinal.arff";
DataSource dsource = new DataSource(dataset);
Instances dapriori = dsource.getDataSet();
Apriori apriori = new Apriori();
apriori.buildAssociations(dapriori);
System.out.println(apriori);
}
}
From looking at several implementations across the web this seems to be a widely accepted method of doing this however i receive an error on the "apriori.buildAssociations" line telling me that the method is undefined for the type Apriori. Furthermore, the import statement i use for the associations only works as the package type and when trying to extend it to :
import weka.associations.Apriori;
this throws an error message that "The import weka.associations.Apriori conflicts with a type defined in the same file". I have scoured StackOverflow alongside other resources and realize there is a lot of type undefined questions out there however have yet to find a solution to this problem. Any help/pointers would be greatly appreciated.
Your class is also named Apriori, so you are experiencing a name clash.
You should change the name of your own class to a different name (e.g. AprioriTest). In the unprobable case where you would really need your class to be named Apriori, then you would have to refer to the library's implementation by it's full name:
weka.associations.Apriori apriori = new weka.associations.Apriori();
apriori.buildAssociations(dapriori);

How to check if filesystem supports links and symlinks in Java

The Files class introduced in Java 7 has methods for handling links and symlinks but only as optional operations.
Is there any way of determining at runtime if a file system supports these operations before actually invoking the respective methods or do I need to call them and then catch the exception?
Classes like FileSystem or FileStore do not seem to contain anything in that regard (or I overlooked it).
I don't see any general approach that will work without relying on an UnsupportedOperationException or some other exception.
You could use a heuristic that assumes that only subclasses of BasicFileAttributesView support symbolic linking.
Note: The approach below will not work because FileAttributeViews and file attributes are not the same concept:
I did not get isSymbolicLink as one of the supported attributes with the following code on OS X 10.8.4:
package com.mlbam.internal;
import java.nio.file.Files;
import java.nio.file.FileStore;
import java.nio.file.FileSystems;
import java.nio.file.Paths;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MainClass {
private static final Logger LOG = LoggerFactory.getLogger(MainClass.class);
public static void main(String[] args) {
try {
System.out.println("FileStore.supportsFileAttributeView('isSymbolicLink'): "
+ Files.getFileStore(Paths.get("/")).supportsFileAttributeView("isSymbolicLink"));
// Got: FileStore.supportsFileAttributeView('isSymbolicLink'): false
System.out.println(FileSystems.getDefault().supportedFileAttributeViews());
// Got: [basic, owner, unix, posix]
} catch (Exception e) {}
}
}
Original Answer:
If you have an instance of FileStore, you can use FileStore.supportsFileAttributeView("isSymbolicLink")
Or, if you have an instance of FileSystem, you can check that resulting Set<String> from FileSystem.supportedFileAttributeViews() contains the String "isSymbolicLink".
You can get the FileStore associated with a Path using Files.getFileStore(Path)
One way of getting the FileSystem is via FileSystems.getDefault()

Regarding how to use external libraries in eclipse (java)

I'm a complete beginner in Java using eclipse and even after installing those correctly external libraries,(I installed them in to my build path and they come in my referenced library section) which would make my job easy I can't use them for some reason.
import acm.*;
I used this to import all the classes of this library and when I tried to use those classes in my program, It didn't work for some reason.It gives me the following error if I try to use the method print() which is a method of the class IOconsole of this library.
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method print(String) is undefined for the type ShortPrint
at ShortPrint.main(ShortPrint.java:5)
I don't know if I missed any steps but I'm pretty sure I have installed the libraries correctly,Just can't get them to use.
EDIT 1: Heres my program.
import acm.*;
public class ShortPrint {
public static void main(String []args) {
print ("hello");
}
}
You need to have an object of ShortPrint, like so
ShortPrnt sp = new ShortPrint();
sp.print("Hello");
I am guessing you are trying to call print like this:
ShortPrint.print("Hello");
which would only work is print was a static function of ShortPrint
Another possibility is that you do not inherit ShortPrint from IOConsole, this the IOConsole.print is not accessible from ShortPrint
UPDATE: after OP added code on usage, the suggestion is to add the import
import acm.io.*;
as the IOConsole class resides in the acm.io package. Then change the call to
IOConsole cons = new IOConsole();
cons.print("hello");
as print() is not a static member of IOConsole
I believe you should change your import to:
import static acm.IOConsole.*
Since it appears that the print() method is static in IOConsole.

Categories