gwtent reflection java - java

Welcome,
I have a problem with "GWTENT" reflection.
How to create a class using reflection?
I tried this:
try {
ClassType ct = TypeOracle.Instance.getClassType(Klient.class);
ct.invoke(null, "Klient", null);
} catch (ReflectionRequiredException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
`
call the class:
package pl.cba.lukaszbaczek.client.Test;
import com.extjs.gxt.ui.client.widget.Window;
import com.google.gwt.user.client.Element;
import com.gwtent.reflection.client.Reflectable;
import com.gwtent.reflection.client.Reflection;
#Reflectable
public class Klient extends Window implements Reflection {
#Override
protected void onRender(Element parent, int index) {
super.onRender(parent, index);
setHeading("Klient");
setSize(600, 600);
}
public Klient(){
super();
show();
}
}
But fails with the error:
17:30:59.129 [ERROR] [makerbase] Uncaught exception escaped
com.gwtent.reflection.client.NotFoundException: Klient not found or unimplement?

If you are on the client side which is compiled into javascript you cannot use reflection. You can use GWT.create(Clazz.class) but the class signature must be known at compile time. This is a requirement due to the javascript compiler.
Here is a link that uses generators for doing reflection
Can you use Java Reflection api in GWT client

Related

Unable to add a Telegram Bot Library; Beginners fail?

I've just started to go away from tasks of the university and do my own projects.
I want to program a Java Telegram Bot to interact with further classes. Unfortunately I'm not able to add the dependency right or it just cant import all of the functions. I tried to follow multiple tutorials but I got errors in either of them. One of the most promising tutorials was the following: https://github.com/rubenlagus/TelegramBots/wiki/Getting-Started
I followed the instructions (added the library with Maven) and put in the code. After this I imported the needed librarie. However the program isn't able to call the method "execute" and I don't know why.
I hope I specified the topic detailled enough.
Thank you in advance.
Main Class:
import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.generics.LongPollingBot;
public class Main {
public static void main(String[] args) {
ApiContextInitializer.init();
TelegramBotsApi botsApi = new TelegramBotsApi();
try {
botsApi.registerBot((LongPollingBot) new Bot());
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
Bot Class
import org.telegram.telegrambots.api.objects.Update;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
public class Bot extends TelegramLongPollingBot {
#Override
public void onUpdateReceived(Update update) {
// We check if the update has a message and the message has text
if (update.hasMessage() && update.getMessage().hasText()) {
SendMessage message = new SendMessage() // Create a SendMessage object with mandatory fields
.setChatId(update.getMessage().getChatId())
.setText(update.getMessage().getText());
try {
execute(message); // Call method to send the message
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
#Override
public String getBotUsername() {
return null;
}
#Override
public String getBotToken() {
return null;
}
#Override
public void onClosing() {
}
}
Error
Error:(16, 17) java: cannot find symbol
symbol: method execute(org.telegram.telegrambots.meta.api.methods.send.SendMessage)
location: class Bot
in the POM.xml file I added the follow dependency:
<!-- https://mvnrepository.com/artifact/org.telegram/telegrambots -->
<dependency>
<groupId>org.telegram</groupId>
<artifactId>telegrambots</artifactId>
<version>4.9.2</version>
</dependency>
You can also download directly the jar.
You must create and define the bot with BotFather, use a username, take the token and create the class that extends TelegramLongPollingBot.
Your problem is on the token and username that return always null. You must return the configuration created with BothFather.
You must set in the getters botToken and botUsername the token and username of bot.
return "<token>";
return "<username_of_bot>";
at least minimum the token.

Byte Buddy Member Substitution throwing IllegalStateException error

I'm trying to write a java instrumentation agent using byte buddy. My goal is to replace a java standard library method call with a proxy call of my own. I was suggested to use Byte Buddy's MemberSubstitution to achieve this. I used this and this questions from SO for my reference.
I'm using Intellij IDEA for coding. My Agent code is split into multiple files as follows:
MyFirstAgent.java
public class MyFirstAgent {
public static void premain(String agentArgs, Instrumentation inst) {
new AgentBuilder.Default()
.type(ElementMatchers.any())
.transform(new ByteBuddyTransformer())
.with(AgentBuilder.Listener.StreamWriting.toSystemOut())
.with(AgentBuilder.TypeStrategy.Default.REDEFINE)
.installOn(inst);
}
ByteBuddyTransformer.java
public class ByteBuddyTransformer implements AgentBuilder.Transformer {
#Override
public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription,
ClassLoader classLoader, JavaModule javaModule) {
try {
return builder.visit(MemberSubstitution.relaxed()
.method(named("add"))
.replaceWith(MyClass.class.getMethod("printLine"))
.on(any()));
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return builder;
}
}
MyClass.java
public class MyClass {
public boolean printLine(){
System.out.println("This is the proxy!");
return true;
}
}
And the application that I want to instrument is in another Intellij IDEA project with the following:
Main.java
public class Main {
public static void main(String[] args) {
ClassToMonitor classToMonitor = new ClassToMonitor();
classToMonitor.bar();
}
}
ClassToMonitor.java
package com.company;
import java.util.ArrayList;
import java.util.Arrays;
public class ClassToMonitor {
public void bar() {
// create an empty array list with an initial capacity
ArrayList<Integer> arrlist = new ArrayList<Integer>(5);
// use add() method to add elements in the list
arrlist.add(15);
// print all the elements available in list
for (Integer number : arrlist) {
System.out.println("Number = " + number);
}
}
}
When I build the fat jar of my agent and run it with my application, I get the following error:
[Byte Buddy] ERROR com.company.ClassToMonitor [jdk.internal.loader.ClassLoaders$AppClassLoader#2626b418, unnamed module #385e9564, loaded=false]
java.lang.IllegalStateException: Cannot invoke public boolean com.company.MyClass.printLine() on [class java.util.ArrayList, E]
I can provide the full error message if required. Also, I'm new to Java and Instrumentation in general so I might be missing something fundamental here, please kindly excuse me and point it out if that's the case.
For substitution to work, the target method needs to accept the same arguments as the replaced method, in your case an int. Also, since you are calling a member, the implicit first argument of your class needs to be the receiver type, i.e. ArrayList or any super type, even Object. Also, your replacement method needs to be static:
public class MyClass {
public static boolean printLine(Object ignored, int ignored2){
System.out.println("This is the proxy!");
return true;
}
}
MemberSubstitution is still not as flexible as it is supposed to be. You can however already inject custom byte code using the chained step if that is what you want.

Cant instantiate a PUBLIC class, Android studio says it's not public

I want to use the BluetoothA2DPSink service in android,
it's a hidden class but I built a modified SDK and ROM and now Android studio can see it.
The problem is I can't use it, whenever i try
'BluetoothA2DPSink sink = new BluetoothA2DPSink()'
I get this error: "BluetoothA2DPSink() is not public in 'android.bluetooth.BluetoothA2dpSink'. Connot be accesed from outside package".
I verified it and it is in fact public:
"public final class BluetoothA2dpSink implements BluetoothProfile{..."
How can I use its methods?
Any help would be much appreciated.
If you pasted your error message correctly, the problem is not with the class, but with the constructor. Note the parentheses in "BluetoothA2DPSink() is not public in 'android.bluetooth.BluetoothA2dpSink'. Connot be accesed from outside package" — that is a reference to a constructor, not a class. Make sure the zero-argument constructor is public.
Try the below code. It is done using reflection. You can not simply create an object by calling the constructor for BluetoothA2DPSink. You also need to use another class BluetoothProfile.java.
Object mBluetoothA2DPSink;
/**
* This function will connect to A2DPsink profile of the server device to manage audio profile connection
*/
public void getBluetoothA2DPsink() {
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
try {
final int A2DPprofile = BluetoothProfile.class.getField("A2DP_SINK").getInt(null);
BluetoothProfile.ServiceListener mProfileListener1 = new BluetoothProfile.ServiceListener() {
public void onServiceConnected(int profile, BluetoothProfile proxy) {
if (profile == A2DPprofile) {
mBluetoothA2DPSink = proxy;
}
}
public void onServiceDisconnected(int profile) {
if (profile == A2DPprofile) {
mBluetoothA2DPSink = null;
try {
mContext.unregisterReceiver(mA2DPReciever);
} catch (IllegalArgumentException e) {
Log.e(TAG, e.getMessage());
}
}
}
};
// Establish connection to the proxy.
mBluetoothAdapter.getProfileProxy(mContext, mProfileListener1, A2DPprofile);
} catch (NoSuchFieldException | IllegalAccessException e) {
Log.e(TAG, e.getMessage());
}
}

GWT Interface woes : Breaking on exception: TypeError: Cannot read property 'getRestWrapper' of undefined

I am writing a GWT app using Libgdx & having some difficulties loading the correct rest library at runtime.
In my core gradle project, I have defined a "RestWrapper" Interface that grants access to platform specific REST functions (in the case of GWT, RestyGWT). When the HTML5 launcher is run, it passes it's implementation to the LibGDX game class in the Core Project.
However when the HTML5 Project is run this error is raised by the compiled JS:
Breaking on exception: TypeError: Cannot read property 'getRestWrapper' of undefined
The issue appears to be with the first interface (PlatformWrapper).
I understand the GWT compiler is a bit ham-fisted when it comes to interfaces, Should I be taking a different approach to running GWT specific code from my core project?
Calling code (In core Project:)
UserSessionToken token =client.getPlatform().getRestWrapper().getRestLogin().attemptLogin(userNameBox.getText(),passwordBox.getText());
Interfaces (In core Project):
PlaformWrapper
public interface PlatformWrapper {
public RestWrapper getRestWrapper();....
RestWrapper
/* Platform independent wrapper for REST services */
public interface RestWrapper {
public RestLogin getRestLogin();....
Implementations (In HTML5 Project):
PlatformWrapper (Top level)
public class GWTWrapper implements PlatformWrapper {
public RestWrapper gwtRestWrapper;
public GWTWrapper(){
gwtRestWrapper = new GWTRestWrapper();
}
#Override
public RestWrapper getRestWrapper() {
return gwtRestWrapper;
}
GWTRestWrapper:
public class GWTRestWrapper implements RestWrapper {
public RestLogin restLogin;
public RestPortal restPortal;
public RestRegister restRegister;
public GWTRestWrapper(){
restLogin = new GWTRestLogin(); //GWTRest Logic
restRegister = new GWTRestRegister();
restPortal = new GWTRestPortal();
}
#Override
public RestLogin getRestLogin() {
return restLogin;
}
Cheers.
Working change:
public ApplicationListener getApplicationListener () {
setLoadingListener(new LoadingListener(){
#Override
public void beforeSetup() {
// TODO Auto-generated method stub
}
#Override
public void afterSetup() {
// TODO Auto-generated method stub
wrapper = new GWTWrapper();
client.setPlatform(wrapper);
}
});
return client;

Need help For building Testing Framework

Recently I was trying to build a framework like TestNG but struck at Launcher thing(I don't know whether it is Launcher problem or Something else just guessing). So this is what I did.
First I created a Custom annotation named Test
Wrote a implementation class of test annotation with main method(right now I am targeting only one annotation)
In main method of implementation class i wrote code to read xml(so that i can get the class name and using reflection I am checking the method of the class with Test annotation and invoking it).
Now I wrote another class with method having test annotation and mentioned the class name in the xml file. Now when we use testng we get option of running that method/class as TestNG.
But in my case I don't know how to run my Class because there is no main method.
So I am Struck at this Point. Please suggest what I should do. If we need Launcher then please tell how we create launcher or any tutuorial/Book/weblink which contains information about Launcher.
*Note: I know if we use annotation we don't need XML file. But for Simplifying thing I am getting class name from XML later I will discard XML.
Thanks in Advance .
This is My Test Annoatation
package com.annoatation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
#Target(value=ElementType.METHOD)
#Retention(RetentionPolicy.RUNTIME)
public #interface Test {
}
This is my Class Where I am Using Annaotation:
package com.annoatation;
public class TestExample{
#Test
public void sampleMethod()
{
System.out.println("This is sample method");
}
#Test
public void sampleMethod1()
{
System.out.println("This is sample method 1");
}
}
This is my Main Class :
package com.annoatation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) {
TestExample example=new TestExample();
Method[] method=example.getClass().getMethods();
for(Method methods:method)
{
Test test=methods.getAnnotation(com.annoatation.Test.class);
if(test!=null)
{
try {
methods.invoke(example);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
I want when i Click on Run as on My TestExample Class it should Automatically invoke the main Method of main Class.
I am not sure what we say this thing in java (May be Entry point)
Use reflection to create an instance of your class and invoke the annotated method:
Class classDefinition = Class.forName(className);
object = classDefinition.newInstance();
Method method = classDefinition.getMethod("methodName");
method.invoke(object);

Categories