Unable to import a Scala object into the Java project - java

I created a Scala object:
package myapp.data
import java.io.File
import myapp.models.NodeViewModel
import com.thoughtworks.xstream.XStream
import com.thoughtworks.xstream.io.xml.DomDriver
object ForumSerializer {
def openFile(file : File) : NodeViewModel = {
// doing something
}
def saveToFile(model : NodeViewModel) : Unit = {
// doing something
}
}
Then I tried to import it in another Java file
import myapp.ForumSerializer;
The error I get is:
Import myapp.ForumSerializer cannot be resolved.
What am I doing wrong?

Import it as ForumSerializer$.
Scala adds a $, so the compiler doesn't get confused with the class, when you have both an object and a class of the same name. You can then access the singleton object using the generated MODULE$.

Related

Android create Toast using class reflection?

I am creating a hook using AndHook to test some functions getting called. I need to show a Toast inside a method without being able to get the context object (I can't directly import MainActivity because I am injecting the script without having the corresponding package when compiling so I can't use MainActivity.this). Here's the code sample:
import andhook.lib.HookHelper;
import android.widget.Toast;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap;
public class AndHookConfig {
#HookHelper.Hook(clazz = BitmapFactory.class)
private static Bitmap decodeFile(BitmapFactory thiz, String path) {
Toast.makeText(Class.forName("com.example.activity.MainActivity").this, "Bitmap.decodeFile("+path+")", Toast.LENGTH_LONG).show();
return (Bitmap)(HookHelper.invokeObjectOrigin(thiz, path));
}
}
I think the only way to do this is using reflection but the code sample doesn't compile and results in an error. Do you have any solutions ?
Thanks in advance.

Using an external Groovy file with Jenkins pipeline

I have two questions here regarding Jenkins pipeline and Groovy methods. Firstly I have multiple build that share common methods so thought best to have all these in a single class and then import the file for each build.
A snippet from my Groovy script looks like
import groovy.json.JsonSlurperClassic;
import groovy.json.JsonSlurper;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.HashSet;
import java.util.Set;
import java.io.Serializable;
Map get_var() {
def gradleVars = readFile "${env.WORKSPACE}/gradle-client/gradle.properties"
Properties properties = new Properties();
InputStream is = new ByteArrayInputStream(gradleVars.getBytes());
properties.load(is)
def sdk_version = "SDKVersion"
def SDK_VERSION = properties."$sdk_version"
return [sdk_version: "$SDK_VERSION"}
}
And in my pipeline script I have
def groovyMethod = load("release_pipeline.groovy")
// Call method
groovyMethod.getVar()
The first problem I have is how do I use ${env.WORKSPACE} within my method, and secondly how do I use readFile within my script as I get the error
hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: Helpers.readFile()
I am really new to Groovy and Java.
Would you please try the below :
def getVar() {
def properties = new Properties()
File propertiesFile = new File("${System.getenv['WORKSPACE']}/gradle-client/gradle.properties")
properties.load(propertiesFile.newDataInputStream())
return [sdk_version: properties.SDKVersion]
}
May be it appears that, you have different method name get_var() and you are trying to use getVar().
And I am not really sure where that error coming from above script
groovy.lang.MissingMethodException: No signature of method: Helpers.readFile()
EDIT: based on OP comment
Please see if the this helps:
def workspace = Thread.currentThread().executable.workspace.toString()

Instantiating object in Python same as Java using jython

In Java I was able to run my code as:
(This are just sample naming)
import com.projectname.api.APIOne;
import com.projectname.api.APITwo;
import com.projectname.api.APIThree;
import com.projectname.api.APIFour;
import com.projectname.api.MainAPI;
public class TestMain {
public static void main(String[] args) {
APIOne a = APIOne.getName();
APITwo b = APIThree.getAddress();
APIFour d = b.getEmail();
MainAPI mainapi = new MainAPI();
mainapi.setEmail(d)
}
}
It is running okay, I tried converting this to Python as:
import com.projectname.api.APIOne as APIOne;
import com.projectname.api.APITwo as APITwo;
import com.projectname.api.APIThree as APIThree;
import com.projectname.api.APIFour as APIFour;
def test():
a = APIOne.getName();
b = APIThree.getAddress();
d = b.getEmail();
mainapi = MainAPI();
mainapi.setEmail(d)
test()
But is this the right way of instantiating? It make me confuse on instantiating.
Hope you could help me.
Importing a class from a java package or python module is normally written as:
from java.lang import Math
Rather than:
import java.lang.Math as Math
But, your code is correct.
I don't understand why you are confused, but this is correct, you could check the Jython documentation about instantiating Java objects using Jython and instantiates the objects the same way as you do.

Error when using ProtocolLibrary PacketAdapter()

I am making a Craftbukkit plugin that has a message in the player count list, Like HIVE-MC or Omega Realm. I am coding in Ecplise and using ProtocolLib v3.2.0 and Craftbukkit 1.7.2 R0.3. I am new to java and don't understand it much. I do know that everything is imported.
So far, here are the imported methods, code, and the error
Methods:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.bukkit.plugin.java.JavaPlugin;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.events.ListenerOptions;
import com.comphenix.protocol.events.ListenerPriority;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.wrappers.WrappedGameProfile;
Code:
private List<WrappedGameProfile> message = new ArrayList<WrappedGameProfile>();
public void onEnable() {
if(!new File(getDataFolder(),"RESET.FILE").exists()){
try {
getConfig().set("PCMessage",
Arrays.asList(new String[]{"First Line", "Second Line"}));
new File(getDataFolder(),"RESET.FILE").createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
saveConfig();
for (String str : getConfig().getStringList("PCMessage"))
message.add(new WrappedGameProfile("1", str));
ProtocolLibrary
.getProtocolManager()
.addPacketListener(
new PacketAdapter(
this,ListenerPriority.NORMAL,
Arrays.asList(new PacketType[] {PacketType.Status.Server.OUT_SERVER_INFO}),
new ListenerOptions[] { ListenerOptions.ASYNC })); {
}
}
Error:
Cannot instantiate the type PacketAdapter
As you will see in the Javadocs for PacketAdapeter, it is declared as:
public abstract class PacketAdapter implements PacketListener
abstract means the class is not a full class, and must be implemented as a full class or anonymous class, it cannot be instantiated. You need to find a subclass of PacketAdapter, or make one yourself.
For more information, see the Java Tutorial for Abstract Methods and Classes.

Run a String through Java using Pig

I have a UDF jar which takes in a String as an input through Pig. This java file works through pig fine as running a 'hard coded' string such as this command
B = foreach f generate URL_UDF.mathUDF('stack.overflow');
Will give me the output I expect
My question is I am trying to get information from a text file and use my UDF with it. I load a file and want to pass data within that file which I have loaded to the UDF.
LoadData = load 'data.csv' using PigStorage(',');
f = foreach LoadData generate $0 as col0, $1 as chararray
$1 is the column I needed and researching data types (http://pig.apache.org/docs/r0.7.0/piglatin_ref2.html#Data+Types) a char array is used.
I then tryed using the following command
B = foreach f generate URL_UDF.mathUDF($1);
to pass the data into the jar which fails stating
java.lang.ClassCastException: org.apache.pig.data.DataByteArray cannot be cast to java.lang.String
If anybody has any solution to this that would be great.
The java code I am running is as follows
package URL_UDF;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.pig.FilterFunc;
import org.apache.pig.data.Tuple;
import org.apache.pig.EvalFunc;
import org.apache.pig.PigWarning;
import org.apache.pig.data.Tuple;
import org.apache.commons.logging.Log;
import org.apache.*;
public class mathUDF extends EvalFunc<String> {
public String exec(Tuple arg0) throws IOException {
// TODO Auto-generated method stub
try{
String urlToCheck = (String) arg0.get(0);
return urlToCheck;
}catch (Exception e) {
// Throwing an exception will cause the task to fail.
throw new IOException("Something bad happened!", e);
}
}
}
Thanks
You can specify the schema with LOAD as follows
LoadData = load 'data.csv' using PigStorage(',') AS (col0: chararray, col1:chararray);
and pass col1 to the UDF.
Or
B = foreach LoadData generate (chararray)$1 AS col1:chararray;
Actually, this is a bug (PIG-2315) in Pig which will be fixed in 0.12.1. The AS clause in foreach does not work as one would expect.

Categories