RubyNoMethodError - call a ruby method from Java - java

I have this ruby class :
require 'stringio'
require 'hirb'
class Engine
def initialize()
#binding = Kernel.binding
end
def run(code)
# run something
stdout_id = $stdout.to_i
$stdout = StringIO.new
cmd = <<-EOF
$SAFE = 3
$stdout = StringIO.new
begin
#{code}
end
EOF
begin
result = Thread.new { Kernel.eval(cmd, #binding) }.value
rescue SecurityError
return "illegal"
rescue Exception => e
return e
ensure
output = get_stdout
$stdout = IO.new(stdout_id)
end
return output
end
private
def get_stdout
raise TypeError, "$stdout is a #{$stdout.class}" unless $stdout.is_a? StringIO
$stdout.rewind
$stdout.read
end
end
The "run" method should call an IRB's function and to capture the output (string format).
I want to call this function from a Java class but it can't find the IRB methods, even they are loaded (require 'hirb').
My java class looks like this :
public class MyClass {
private final static String jrubyhome = "/usr/lib/jruby/";
private String rubySources;
private String hirbSource;
private String myEngine;
private boolean loaded = false;
private void loadPaths() {
String userDir;
userDir = System.getProperty("user.dir");
rubySources = userDir + "/../ruby";
hirbSource = userDir + "/hirb.rb";
myEngine = rubySources + "/engine.rb";
System.setProperty("jruby.home", jrubyhome);
System.setProperty("org.jruby.embed.class.path", rubySources+":"+hirbSource);
System.setProperty("hbase.ruby.sources", rubySources+":"+hirbSource);
}
private String commandResponse(String command)
throws FileNotFoundException
{
String response;
loadPaths();
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("jruby");
ScriptingContainer container = new ScriptingContainer();
Reader reader = new FileReader(myEngine);
try {
Object receiver = engine.eval(reader);
String method = "run";
Object ob = container.callMethod(receiver,method,command);
response = ob.getClass().toString();
return response;
} catch (ScriptException e) {
System.out.println("exception");
}
return "FAILED";
}
public static void main(String args[])
throws IOException {
MyClass my = new MyClass();
System.out.println(my.commandResponse(args[0]));
}
}
Do you know what could be the problem?
[EDITED] After I extended the Kernel module and added the commands it worked.

Related

How to write junit test case for method have args parameter

Here is my code for junit test case
public class HelptextValidation {
#Test
public void test() {
CLIReaderTest cli=new CLIReaderTest();
String Output="Test Execution";
assertEquals(cli.readCommandLineParameters(new String[]{"-h"}) , Output);
}
}
And is the class method for which test case is prepared
public class CLIReaderTest {
private String user = "";
private String password = "";
private String serverUrl = "";
private boolean spit_everythingtoLog = false;
public boolean readCommandLineParameters(String[] args) {
Logger log = Logger.getLogger(CLIReader.class);
Options options = new Options();
Option helpOpt = Option.builder("h").longOpt("help").desc("Usage Help").build();
options.addOption(helpOpt);
Option serverurl = Option.builder("url").longOpt("server url").desc("Server url").required().hasArg().argName("url").build();
options.addOption(serverurl);
Option userOpt = Option.builder("u").longOpt("user").desc("User Name").hasArg().argName("user").required().build();
options.addOption(userOpt);
Option pwdOpt = Option.builder("p").longOpt("password").desc("user password").hasArg().argName("password").required().build();
options.addOption(pwdOpt);
try {
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args, true);
if(cmd.hasOption("v")) {
spit_everythingtoLog = true;
}
serverUrl = cmd.getOptionValue("url");
user = cmd.getOptionValue("u");
password = cmd.getOptionValue("p");
streamName = cmd.getOptionValue("s");
compList = cmd.getOptionValue("c");
}
catch (Exception e) {
String temp1="--help";
String temp2="[--help]";
String temp3="[-h]";
String temp4="-h";
if(temp1.equals(args[0]) || temp2.equals(args[0]))
{
System.out.println("Test Execution");
System.exit(1);
}
}
Here when user passes java -jar abc.jar -h in command line the output is "Test Execution"
The same i want to do with my test case but i am unable to pass the cmd argument and compare it with string. Can anyone please help me out in this?

How read JSON file in Play framework using Java

I am trying to read JSON file from test/resources package in my play application. I am getting com.couchbase.client.java.error.DocumentDoesNotExistException. I believe my path is not correct, can anyone suggest how to take absolute path?
public class AppControllerTest extends WithApplication {
#Inject
AppDaoServiceImpl appDaoServiceImpl;
private CouchbaseEnvironment env;
private static Cluster cluster = null;
private static Bucket bucket = null;
private String testResources = System.getProperty("java.class.path") + "/test/resources/";
private static final ALogger logger = Logger.of(AppControllerTest.class);
#Rule
public ExpectedException thrown = ExpectedException.none();
#Override
protected Application provideApplication() {
return new GuiceApplicationBuilder().build();
}
#Before
public void init() {
env = DefaultCouchbaseEnvironment.create();
cluster = CouchbaseCluster.create(env, "127.0.0.1:8091");
bucket = cluster.openBucket("CLUSTER", "admin123");
try {
String docId = "ABEBV_common";
File testResource = new File(testResources + "ABEBV_common.json");
FileInputStream is = new FileInputStream(testResource);
JsonNode testData = Json.parse(is);
RawJsonDocument rawJsonDocument = RawJsonDocument.create(docId, testData.asText());
bucket.upsert(rawJsonDocument);
} catch (Exception e) {
}
}
#Test
public void testGenericData() {
Http.RequestBuilder request = new Http.RequestBuilder().method(GET).uri("/app/ms/genericdata/ABEBV")
.header("client_id", "chase");
Result result = route(app, request);
assertEquals(OK, result.status());
assertEquals("application/json", result.contentType().get());
assertTrue(contentAsString(result).contains("141-GYCVZY"));
}
#After
public void deleteDocuments() {
bucket.remove("ABEBV_common");
bucket.close();
cluster.disconnect();
}
}
Yes your path is not correct, System.getProperty("java.class.path") will return all the java class path the jvm is referring to You have to, instead use "user.dir".
private String testResources = System.getProperty("user.dir") + "/test/resources/";

"Scanner closed" message after running

I have a program that creates a webgraph from text files. Every Time I run it I get the same message that says "Scanner Closed."
//constant final variables
public static final String PAGES_FILE = "pages.txt";
public static final String LINKS_FILE = "links.txt";
// webgraph object var
private WebGraph web;
// searchEngine constructor.
public SearchEngine() throws FileNotFoundException {
web = WebGraph.buildFromFiles(PAGES_FILE, LINKS_FILE);
}
Scanner Portion
try {
System.out.println("Loading WebGraph data...");
SearchEngine engine = new SearchEngine();
System.out.println("Success!");
Scanner scanner = new Scanner(System.in);
I have the scanner.close() right after the try block which contains all the possible user inputs. I have also attached an image of what should be happening once I run the program. Any ideas what could be going wrong? If any other code is needed I can provide that.Sample Program
Here is the image of what I am getting My Run
This is the code for the "buildFromFiles"
public static WebGraph buildFromFiles(String pagesFile, String linksFile)
throws IllegalArgumentException, FileNotFoundException {
WebGraph webGraph = new WebGraph();
File filePages = new File(pagesFile);
File fileLinks = new File(linksFile);
if (filePages.exists() && fileLinks.exists() && filePages.isFile() && fileLinks.isFile()) {
Scanner pageScanner = new Scanner(filePages);
while (pageScanner.hasNextLine()) {
String[] pageData = pageScanner.nextLine().split("\\s+");
String url = pageData[0];
ArrayList<String> keywords = new ArrayList<String>();
for (int i = 1; i < pageData.length; i++) {
keywords.add(pageData[i]);
}
webGraph.addPage(url, keywords);
}
pageScanner.close();
Scanner linkScanner = new Scanner(fileLinks);
while (linkScanner.hasNextLine()) {
String[] linkData = pageScanner.nextLine().split("\\s+");
webGraph.addLink(linkData[0], linkData[1]);
}
linkScanner.close();
} else {
throw new IllegalArgumentException();
}
return webGraph;
}

Get ID lexemes in lexer class ANTLR3 that implemented to a jTable

I am building a java clone code detector in swing that implemented the ANTLR. This is the Screenshot :
https://www.dropbox.com/s/wnumgsjmpps33v5/SemogaYaAllah.png
if you see the screenshot, there are a main file that compared to another files. The way that I do is compared thats token main file to another file. The problem is, I am failed to get the ID Lexemes or tokens from my lexer class.
This is my ANTLR3JavaLexer
public class Antlr3JavaLexer extends Lexer {
public static final int PACKAGE=84;
public static final int EXPONENT=173;
public static final int STAR=49;
public static final int WHILE=103;
public static final int MOD=32;
public static final int MOD_ASSIGN=33;
public static final int CASE=58;
public static final int CHAR=60;
I ve created a JavaParser.class like this to use that lexer:
public final class JavaParser extends AParser { //Parser is my Abstract Class
JavaParser() {
}
#Override
protected boolean parseFile(JCCDFile f, final ASTManager treeContainer)throws ParseException, IOException {
BufferedReader in = new BufferedReader(new FileReader(f.getFile()));
String filePath = f.getNama(); // getName of file
final Antlr3JavaLexer lexer = new Antlr3JavaLexer();
lexer.preserveWhitespacesAndComments = false;
try {
lexer.setCharStream(new ANTLRReaderStream(in));
} catch (IOException e) {
e.printStackTrace();
return false;
}
//This is the problem
//When I am activated this code pieces, I get the output like this
https://www.dropbox.com/s/80uyva56mk1r5xy/Bismillah2.png
/*
StringBuilder sbu = new StringBuilder();
while (true) {
org.antlr.runtime.Token token = lexer.nextToken();
if (token.getType() == Antlr3JavaLexer.EOF) {
break;
}
sbu.append(token.getType());
System.out.println(token.getType() + ": :" + token.getText());
}*/
final CommonTokenStream tokens = new CommonTokenStream();
tokens.setTokenSource(lexer);
tokens.LT(10); // force load
// Create the parser
Antlr3JavaParser parser = new Antlr3JavaParser(tokens);
StringBuffer sb = new StringBuffer();
sb.append(tokens.toString());
DefaultTableModel model = (DefaultTableModel) Main_Menu.jTable2.getModel();
List<final_tugas_akhir.Report2> theListData = new ArrayList<Report2>();
final_tugas_akhir.Report2 theResult = new final_tugas_akhir.Report2();
theResult.setFile(filePath);
theResult.setId(sb.toString());
theResult.setNum(sbu.toString());
theListData.add(theResult);
for (Report2 report : theListData) {
System.out.println(report.getFile());
System.out.println(report.getId());
model.addRow(new Object[]{
report.getFile(),
report.getId(),
report.getNum(),
});
}
// in CompilationUnit
CommonTree tree;
try {
tree = (CommonTree) parser.compilationUnit().getTree();
DOTTreeGenerator gen = new DOTTreeGenerator();
StringTemplate st = gen.toDOT(tree);
} catch (RecognitionException e) {
e.printStackTrace();
return false;
}
walkThroughChildren(tree, treeContainer, parser.getTokenStream()); //this is my method to check the similiar tokens
in.close();
this.posisiFix(treeContainer); //fix position
return true;
}
Once again, this is the error code my java program link: https://www.dropbox.com/s/80uyva56mk1r5xy/Bismillah2.png.
The tokens always give me a null value.

Receiving null output for tdd url test

When I run junit tests on my project I receive the following error when trying to test that my project can build a url correctly. I am not sure what I am doing wrong below is the trace of the failed test run as well as the distancematrixconnection class and test class. It is producing a blank output when trying to compile the url string.
org.junit.ComparisonFailure: expected:<[http://maps.googleapis.com/maps/api/distancematrix/xml?origins=albany&destinations=albany%20in&language=en-EN&sensor=false&language=en-EN&units=imperial]> but was:<[]>
at org.junit.Assert.assertEquals(Assert.java:115)
at org.junit.Assert.assertEquals(Assert.java:144)
at edu.bsu.cs222.gascalculator.tests.GoogleUrlTests.testAlbanyNYtoAlbanyINURL(GoogleUrlTests.java:26)
public class GoogleDistanceMatrixConnection
{
String startLocation;
String endLocation;
final String urlString = "http://maps.googleapis.com/maps/api/distancematrix/xml?origins=" + startLocation +"&destinations=" + endLocation +"&language=en-EN&sensor=false&language=en-EN&units=imperial";
private static String XMLFile;
public String makeXMLFile(String start, String end) throws IOException
{
startLocation = start;
endLocation = end;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
connection.connect();
BufferedReader reader = new BufferedReader( new InputStreamReader(
connection.getInputStream()));
for(String line = reader.readLine(); line != null; line =
reader.readLine())
{
setXMLFile(line);
}
return getXMLFile();
}
// public static void main(String[] args) throws IOException{
// GoogleDistanceMatrixConnection c = new GoogleDistanceMatrixConnection();
// }
public static String getXMLFile() {
return XMLFile;
}
public static void setXMLFile(String xMLFile) {
XMLFile = xMLFile;
}
public boolean doesPageExist() {
if(XMLFile == null)
return true;
else
return false;
}
}
public class GoogleUrlTests {
private GoogleDistanceMatrixConnection urlString = new GoogleDistanceMatrixConnection();
private String generatedUrl = "";
private String actualUrl = "";
#Test
public void testAlbanyNYtoAlbanyINURL() throws IOException {
generatedUrl = urlString.makeXMLFile("albany", "albany+in");
actualUrl = "http://maps.googleapis.com/maps/api/distancematrix/xml?origins=albany&destinations=albany%20in&language=en-EN&sensor=false&language=en-EN&units=imperial";
Assert.assertEquals(actualUrl, generatedUrl);
}
#Test
public void testLosAngelesToNewYorkURL() throws IOException {
generatedUrl = urlString.makeXMLFile("losangeles", "newyork");
actualUrl = "http://maps.googleapis.com/maps/api/distancematrix/xml?origins=losangeles&destinations=newyork&language=en-EN&sensor=false&language=en-EN&units=imperial";
Assert.assertEquals(actualUrl, generatedUrl);
}
}
Comparing your test cases and your code in makeXMLFile, I'm confused of what you are really trying to do here.
If you want to pass you tests, then I think this code will do that for you. You can use URLEncoder to properly encode your URL string.
public class GoogleDistanceMatrixConnection
{
public String makeXMLFile(String start, String end) throws IOException
{
return "http://maps.googleapis.com/maps/api/distancematrix/xml?origins=" + URLEncoder.encode(start) +"&destinations=" + URLEncoder.encode(end) +"&language=en-EN&sensor=false&language=en-EN&units=imperial";
}
}
Otherwise, you need to clarify your question.

Categories

Resources