android java is not enclosing class - java

this is my class
public class mm {
public class MessageHandler {
public HashMap<String, Command> commandMap;
public MessageHandler() {
this.commandMap = new HashMap<>();
commandMap.put("init", new CreateOfferCommand());
commandMap.put("offer", new CreateAnswerCommand());
commandMap.put("answer", new SetRemoteSDPCommand());
commandMap.put("candidate", new AddIceCandidateCommand());
}
public Emitter.Listener onMessage = new Emitter.Listener() {
#Override
public void call(Object... args) {
JSONObject data = (JSONObject) args[0];
try {
String from = data.getString("from");
String type = data.getString("type");
JSONObject payload = null;
if(!type.equals("init")) {
payload = data.getJSONObject("payload");
}
// if peer is unknown, try to add him
if(!peers.containsKey(from)) {
// if MAX_PEER is reach, ignore the call
int endPoint = findEndPoint();
if(endPoint != MAX_PEER) {
Peer peer = addPeer(from, endPoint);
peer.pc.addStream(localMS);
commandMap.get(type).execute(from, payload);
}
} else {
commandMap.get(type).execute(from, payload);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
public Emitter.Listener onId = new Emitter.Listener() {
#Override
public void call(Object... args) {
String id = (String) args[0];
mListener.onCallReady(id);
}
};
public Emitter.Listener onCall = new Emitter.Listener() {
#Override
public void call(Object... args) {
String id = (String) args[0];
mListener.onCalling(id);
}
};
}
......................
.........
}
and when i call the inner class from another class its give me an enclosing class
mm.MessageHandler messageHandler = new mm.MessageHandler();
when i make inner class messageHandler a static the error gone but its shown anothe error inside inner class so can i call the inner class without make it static ?

mm n = new mm();
mm.MessageHandler messageHandler = n.new MessageHandler();
or use static in your inner class
hope that's help

Related

Creating a chain of Vertx handler executions

From the start, sorry for bad English, I am working on it.
My goal is to create http methods in vert.x. Each method consists of steps, which can be blocked by other steps. For simplifying one step can be blocked by exactly one another.
I decided to create an AsyncMethodHandler which inside of handle method call, create exemplars of AsyncStepHandlers. Method handler also creates a map of steps futures, and try to create a compose handler for them to join.
here's the code AsyncMethodHandler:
public abstract class AsyncMethodHandler<T extends BaseChannelResponse> implements Handler<RoutingContext> {
private static final String CONTENT_TYPE_JSON = "application/json; charset=utf-8";
private final List<Class<? extends AsyncStepHandler>> steplist;
private final HttpMethod methodType;
private final String endpointName;
private final HttpEndpointName endpoint;
private String responseEndpoint;
public AsyncMethodHandler(HttpEndpointName endpoint, String endpointName, HttpMethod methodType, List<Class<? extends AsyncStepHandler>> steplist) {
this.steplist = steplist;
this.endpoint = endpoint;
this.endpointName = endpointName;
this.methodType = methodType;
}
#Override
public void handle(RoutingContext event) {
try {
Map<Class<? extends AsyncStepHandler>, Future> mapOfExecution = new ConcurrentHashMap<>(steplist.size());
List<AsyncStepHandler> handlers = new ArrayList<>(steplist.size());
for (Class<? extends AsyncStepHandler> stepClass : this.steplist) {
AsyncStepHandler stepHandler = stepClass.getConstructor(RoutingContext.class).newInstance(event);
mapOfExecution.put(stepClass, stepHandler.getStepFuture());
handlers.add(stepHandler);
}
for (AsyncStepHandler stepHandler : handlers) {
stepHandler.before(mapOfExecution).setHandler(stepHandler.makeHandler(mapOfExecution));
}
CompositeFuture.join(new ArrayList<>(mapOfExecution.values())).setHandler(handleResult(event, mapOfExecution));
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
e.printStackTrace();
}
}
private Handler<AsyncResult<CompositeFuture>> handleResult(RoutingContext event, Map<Class<? extends AsyncStepHandler>, Future> mapOfExecution) {
return result -> {
if (result.succeeded()) {
succeeded(event.response(), generateResponse(mapOfExecution));
} else {
ChannelAPIException error = ChannelAPIException.createFrom(result.cause());
errored(event.response(), error.getCode(), error.getMessage());
}
};
}
protected abstract T generateResponse(Map<Class<? extends AsyncStepHandler>, Future> mapOfExecution);
private void errored(HttpServerResponse response, int code, String message) {
response.putHeader(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE_JSON)
.setStatusCode(code)
.end(message);
CAPIMetricFactory.incBotResponseError(this.responseEndpoint, code);
}
private void succeeded(HttpServerResponse response, T result) {
response.putHeader(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE_JSON)
.setStatusCode(200)
.end(Serializer.toPrettyJson(result));
CAPIMetricFactory.incBotResponse(this.responseEndpoint);
}
public String getEndpointName() {
return endpointName;
}
public HttpMethod getMethodType() {
return methodType;
}
public HttpEndpointName getEndpoint() {
return endpoint;
}
public void setResponseEndpoint(String responseEndpoint) {
this.responseEndpoint = responseEndpoint;
}
}
here's the code AsyncStepHandlers:
public abstract class AsyncStepHandler<T> {
private final Future stepFuture;
private final RoutingContext context;
private final Class<? extends AsyncStepHandler> before;
public AsyncStepHandler(RoutingContext context) {
this(Future.future(), context, null);
}
public AsyncStepHandler(RoutingContext context, Class<? extends AsyncStepHandler> before) {
this(Future.future(), context, before);
}
private AsyncStepHandler(Future stepFuture, RoutingContext context, Class<? extends AsyncStepHandler> before) {
this.stepFuture = stepFuture;
this.context = context;
this.before = before;
}
public static <T> T getResultFromMap(Map<Class<? extends AsyncStepHandler>, Future> mapOfExecution, Class<? extends AsyncStepHandler> key) {
return (T) mapOfExecution.get(key).result();
}
public final Future getStepFuture() {
return stepFuture;
}
public RoutingContext getContext() {
return context;
}
public Buffer getContextBody() {
return context.getBody();
}
public String getContextBodyAsString() {
return context.getBodyAsString();
}
public Future before(Map<Class<? extends AsyncStepHandler>, Future> mapOfExecution) {
if (before != null) {
return mapOfExecution.get(before);
} else {
return Future.succeededFuture();
}
}
public abstract Future<T> execute(Map<Class<? extends AsyncStepHandler>, Future> mapOfExecution);
public Handler<AsyncResult> makeHandler(Map<Class<? extends AsyncStepHandler>, Future> mapOfExecution) {
return result -> {
if (result.succeeded()) {
this.execute(mapOfExecution).setHandler(this.finish());
} else {
stepFuture.fail(result.cause());
}
};
}
private Handler<AsyncResult<T>> finish() {
return result -> {
if (result.succeeded()) {
stepFuture.complete(result.result());
} else {
stepFuture.fail(result.cause());
}
};
}
}
So then, I try to create some actual methods and steps. For example:
create parameters object from the request body
from created earlier parameters get token and try to authorize
from an authorized object from the previous step consider validating the status of the request.
So here's the code:
public class SimpleTestMethod extends AsyncMethodHandler<TestData> {
public SimpleTestMethod(String endpoint) {
super(
CHANNEL_API_SEND_TEXT,
endpoint,
POST,
new ArrayList<Class<? extends AsyncStepHandler>>(){{
add(ParametersStep.class);
}{
add(AuthorizationStep.class);
}{
add(ValidateStep.class);
}}
);
}
#Override
protected TestData generateResponse(Map<Class<? extends AsyncStepHandler>, Future> mapOfExecution) {
System.out.println("End");
SendMessageParameters response = (SendMessageParameters) mapOfExecution.get(ParametersStep.class).result();
ValidationResult validationResult = (ValidationResult) mapOfExecution.get(ValidateStep.class).result();
return new TestData(response.toString(),0l);
}
}
First if for example steps will be like this:
public class ParametersStep extends AsyncStepHandler<SendMessageParameters> {
public ParametersStep(RoutingContext context) {
super(context);
}
#Override
public Future<SendMessageParameters> execute(Map<Class<? extends AsyncStepHandler>, Future> mapOfExecution) {
System.out.println("ParametersStep");
SendMessageParameters parameters = parseJson(this.getContextBodyAsString(), SendMessageParameters.class);
return Future.succeededFuture(parameters);
}
}
Execution will be expectable. But if I will add some additional awaiting for some step, then the next after that step will never start.
For example:
public class AuthorizationStep extends AsyncStepHandler<AuthResponse> {
public AuthorizationStep(RoutingContext context) {
super(context, ParametersStep.class);
}
#Override
public Future<AuthResponse> execute(Map<Class<? extends AsyncStepHandler>, Future> mapOfExecution) {
System.out.println("AuthorizationStep");
final Future<AuthResponse> authorization = Future.future();
SendMessageParameters parameters = getResultFromMap(mapOfExecution, ParametersStep.class);
AuthResponse response = new AuthResponse(new ChannelTokenData(0l,parameters.getToken(),true,0l,0l,null));
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
authorization.complete(response);
}
});
t.start();
return authorization;
}
}
Then no steps, that awaits of authorization step ending will be called. I reading the official doc, and tried to find some information about this case, but did not succeed. I tried different technics setHandler, compose but get's the same result.
Can anybody help me with understanding why next step won't start and solving this issue because the next part is to use CompositeFuture =)
P.S.:
What is the most interesting, if for example AuthorizationStep is second in 3 steps method - execution will stop on second step. But if I do this:
#Override
public void handle(RoutingContext event) {
try {
Map<Class<? extends AsyncStepHandler>, Future> mapOfExecution = new ConcurrentHashMap<>(steplist.size());
List<AsyncStepHandler> handlers = new ArrayList<>(steplist.size());
CountDownLatch latch = new CountDownLatch(steplist.size());
for (Class<? extends AsyncStepHandler> stepClass : this.steplist) {
AsyncStepHandler stepHandler = stepClass.getConstructor(RoutingContext.class).newInstance(event);
mapOfExecution.put(stepClass, stepHandler.getStepFuture());
handlers.add(stepHandler);
stepHandler.setLatch(latch);
}
for (AsyncStepHandler stepHandler : handlers) {
stepHandler.before(mapOfExecution).setHandler(stepHandler.makeHandler(mapOfExecution));
}
latch.await();
CompositeFuture.join(new ArrayList<>(mapOfExecution.values())).setHandler(handleResult(event, mapOfExecution));
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
And this in AsyncStepHandler:
private Handler<AsyncResult<T>> finish() {
return result -> {
System.out.println("finish");
if (result.succeeded()) {
latch.countDown();
stepFuture.complete(result.result());
} else {
stepFuture.fail(result.cause());
}
};
}
Everything starts to work. If I add countdown latch, and add await before Composite future join, all will be fine.

Decorate a method with ByteBuddy

How can I define a method and then decorate it (multiple times) with ByteBuddy ?
This is my example
Builder<Object> builder = new ByteBuddy().subclass(Object.class).name("Dynamic");
builder = builder.defineMethod("method", void.class, Visibility.PUBLIC)
.intercept(MethodDelegation.to(new Object(){
#RuntimeType
public void intercept(#This Object o) {
System.out.println("Executing code...");
}
}));
builder = builder.method(ElementMatchers.named("method")).
intercept(MethodDelegation.to(new Object(){
#RuntimeType
public void intercept(#This Object o) {
System.out.println("Executing other code...");
}
}));
try {
Class cls = builder.make()
.load(StructClassBuilder.class.getClassLoader())
.getLoaded();
Object obj = cls.newInstance();
cls.getDeclaredMethod("method").invoke(obj, args);
} catch (Exception e1) {
e1.printStackTrace();
}
The output is
Executing other code...
I would like that the output is
Executing code...
Executing other code...
Thanks
One option is to chain Your interceptors using MethodDelegation.to(...).addThen(...) methods.
public class ByteBuddyTest {
public static void main(String[] args) throws Exception {
DynamicType.Builder<Object> builder = new ByteBuddy().subclass(Object.class).name("Dynamic");
builder = builder
.defineMethod("method", void.class, Visibility.PUBLIC)
.intercept(MethodDelegation.to(Interceptor1.class).andThen(MethodDelegation.to(Interceptor2.class)));
try {
Class<?> clazz = builder.make().include().load(ByteBuddyTest.class.getClassLoader()).getLoaded();
Object obj = clazz.newInstance();
clazz.getDeclaredMethod("method").invoke(obj, args);
} catch (Exception e1) {
e1.printStackTrace();
}
}
public static class Interceptor1 {
public static void intercept() {
System.out.println("Executing code...");
}
}
public static class Interceptor2 {
public static void intercept() {
System.out.println("Executing other code...");
}
}
}
I'll use decorator pattern to decorate the Interceptor, now it works as expected.
I share my solution:
private static interface Interceptor{
public void intercept(#This Object o);
}
private abstract static class InterceptorDecorator implements Interceptor{
protected Interceptor interceptor;
public InterceptorDecorator(Interceptor interceptor){
this.interceptor = interceptor;
}
public void intercept(#This Object o) {
if(interceptor!=null){
interceptor.intercept(o);
}
}
}
private static class Interceptor1 extends InterceptorDecorator{
public Interceptor1(Interceptor interceptor) {
super(interceptor);
}
public void intercept(#This Object o) {
super.intercept(o);
System.out.println("Executing code...");
}
}
private static class Interceptor2 extends InterceptorDecorator{
public Interceptor2(Interceptor interceptor) {
super(interceptor);
}
public void intercept(#This Object o) {
super.intercept(o);
System.out.println("Executing other code...");
}
}
public static void main(String[] args) {
Interceptor interceptor = new Interceptor1(null);
interceptor = new Interceptor2(interceptor);
Builder<Object> builder = new ByteBuddy().subclass(Object.class).name("Dynamic");
builder = builder.defineMethod("method", void.class, Visibility.PUBLIC)
.intercept(MethodDelegation.to(interceptor));
try {
Class cls = builder.make()
.load(StructClassBuilder.class.getClassLoader())
.getLoaded();
Object obj = cls.newInstance();
cls.getDeclaredMethod("method").invoke(obj, args);
} catch (Exception e1) {
e1.printStackTrace();
}
}

AIDL ERROR while trying to return custom class object

I am trying to pass 'Response' class object using IPC in AIDL. I have made the class parcelable:
public class Response implements Parcelable{
private long id;
private String speechString;
private List<String> responseString = new ArrayList<String>();
//set
...
}
//get
...
public Response(Parcel in) {
id = in.readLong();
speechString = in.readString();
if (in.readByte() == 0x01) {
responseString = new ArrayList<String>();
in.readList(responseString, String.class.getClassLoader());
} else {
responseString = null;
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(id);
dest.writeString(speechString);
if (responseString == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(responseString);
}
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Response createFromParcel(Parcel in) {
return new Response(in);
}
public Response[] newArray(int size) {
return new Response[size];
}
};
}
Defined Response.aidl:
package com.example;
parcelable Response;
IappMain.aidl is used for IPC and is defined as following:
package com.example;
// Declare any non-default types here with import statements
import com.example.Response;
interface IOizuuMain {
int app(String aString);
Response getResponseByString(String string);
}
but upon building the project, it gives me the following error in IappMain.java:
"error: incompatible types: Object cannot be converted to Response" at this line:
_result = com.example.Response.CREATOR.createFromParcel(_reply);
The error is being caused by this line:
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
Type parameters need to be added to both the return type and the object being created. The change to add type parameters is this:
public static final Parcelable.Creator<Response> CREATOR =
new Parcelable.Creator<Response>() {
try to add
public Response()
{}
above to the below mentioned code.
public Response(Parcel in) { .....
....
}
so it should look like
public Response(){}
public Response(Parcel in) { .....
....
}

Try catch not being forced

I have this Exception:
public class ErrorException extends Exception
{
private static final long serialVersionUID = 1L;
private String errorMessage = "";
private int errorCode = 0;
private String errorLevel = "";
private Window errorSource = null;
public String getErrorMessage()
{
return errorMessage;
}
public int getErrorCode()
{
return errorCode;
}
public String getErrorLevel()
{
return errorLevel;
}
public Window getErrorSource()
{
return errorSource;
}
public ErrorException(String message, int code, int level, Window source)
{
super();
errorMessage = message;
errorCode = code;
switch (level)
{
case 0:
{
errorLevel = "benignError";
}
case 1:
{
errorLevel = "criticalError";
}
case 2:
{
errorLevel = "terminalError";
}
}
errorSource = source;
}
}
And I have this method:
public static Element check(final Document document) throws ErrorException
{
try
{
chapter.resetLatch();
final SecondaryLoop loop = Toolkit.getDefaultToolkit().getSystemEventQueue().createSecondaryLoop();
new Thread()
{
#Override
public void run()
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
answer.getPreviousElement().takeFocus();
question.removeAnswer(answer);
question.rewriteLetters();
Utils.update(chapter);
loop.exit();
}
});
}
}.start();
loop.enter();
chapter.getLatch().await();
}
catch (InterruptedException e)
{
throw new ErrorException("blankElementDialogError", 8, 1, Main.getGui().getMasterWindow());
}
return new Element();
}
And I use it in this constructor code:
public ConfirmCloseDialog(final Document document, final int postOperation)
{
final CustomJButton doSave = new CustomJButton(Main.getString("doSave"), false);
doSave.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent arg0)
{
getConfirmCloseDialog().dispose();
new Thread()
{
#Override
public void run()
{
/*this method is the one above -->*/Element problem = BlankElementDialog.check(document);
if (problem == null)
{
new SaveChooser(document, postOperation);
}
else
{
new BlankElementDialog(problem);
}
}
}.start();
}
});
}
The code for the second part is not full, but there are no special constructs in the rest of the code (just some GUi objects being constructed and there is no try catch anywhere in the constructor).
However, Eclipse isn't forcing me to encapsulate the method call into try catch block, despite the fact that the method throws an Exception (ErorrException subclasses Exception).
And I know that Exception is checked exception, so it should force it, right?
Why?
What do I have to do so it would force it?
Even without any details Eclipse should notify, look at this:
Just restart the Eclipse should solve the issue.
public class TestClass {
public static void main(String[] args) {
method(2);//Notification here!
}
static void method(int a) throws myException {
}
}
class myException extends Exception {
}

How to manage different TwitterStream from different Thread

i'm trying to execute different Thread using different TwitterStream object with an single authentication:
public class Support {
private static final String accessToken = "xxxxxxx";
private static final String accessTokenSecret = "xxxxxxx";
public static final AccessToken token = new AccessToken(accessToken, accessTokenSecret);
private static final String consumerKey = "xxxxxxx";
private static final String consumerSecret = "xxxxxxx";
private static final Configuration conf = new ConfigurationBuilder().setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret).build();
public static TwitterStreamFactory factory = new TwitterStreamFactory(conf);
}
In every Thread i do:
public MyThread1(){
this.twitterStream = Support.factory.getInstance(Support.token);
}
public void run(){
StatusListener listener = ... ;
twitterStream.addListener(listener);
FilterQuery fq = new FilterQuery();
fq.track(new String[]{"hashtag1","hashtag2"});
twitterStream.filter(fq);
}
public MyThread2(){
this.twitterStream = Support.factory.getInstance(Support.token);
}
public void run(){
StatusListener listener = ... ;
twitterStream.addListener(listener);
FilterQuery fq = new FilterQuery();
fq.track(new String[]{"hashtag3","hashtag4"});
twitterStream.filter(fq);
}
But it gives me authentication error.. multiple request of the same authentication. How can i solve?
Here is how I did it:
public class MyTwitterApp implements {
private Twitter twitter;
private Query query;
public MyTwitterApp (){
twitter = TwitterFactory.getSingleton();
}
public static void main(String[] args) {
MyTwitterApp twitterApp = new MyTwitterApp();
twitterApp.getStreamingTweets();
}
public void getStreamingTweets(){
StatusListener listener = new StatusListener(){
public void onStatus(Status status) {
handleStatus(status);
}
public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {}
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {}
public void onException(Exception ex) {ex.printStackTrace(); }
public void onScrubGeo(long arg0, long arg1) {}
public void onStallWarning(StallWarning arg0) {}
};
twitter.addListener(listener);
FilterQuery fq = new FilterQuery();
fq.count(0);
fq.track(new String[]{"#MyHashTag"});
twitter.filter(fq);
}
protected void handleStatus(Status tweet) {
if(tweet.isRetweet()){
return;
}
if(isMyHashTagTweet(tweet)){
//do something with tweet here
}
}
private boolean isMyHashTagTweet(Status tweet) {
HashtagEntity[] htes = tweet.getHashtagEntities();
for(HashtagEntity hte : htes){
if(hte.getText().equalsIgnoreCase("myhashtag")) {
return true;
}
}
return false;
}
}
Each thread will contain something like this.
twitter = TwitterFactory.getSingleton();
Will make sure you are reusing the same connection each time.
twitter.addListener(listener);
Will add a listener so that you will get called back to this thread (but you will get called back from every query added)
twitter.filter(fq);
Will add a new search query to follow.
isMyHashTagTweet(tweet)
Will check to make sure that the tweet returned by all queries live in your twitterStream are relevant for your current thread

Categories

Resources