From 11110cb4618b5c7bb6a2346060ca84a0f153bd13 Mon Sep 17 00:00:00 2001 From: Markus Date: Sun, 22 Feb 2015 14:07:06 +0100 Subject: [PATCH 01/10] prepared Logger, probably too many methods --- EventBus/src/de/greenrobot/event/Logger.java | 239 +++++++++++++++++++ 1 file changed, 239 insertions(+) create mode 100644 EventBus/src/de/greenrobot/event/Logger.java diff --git a/EventBus/src/de/greenrobot/event/Logger.java b/EventBus/src/de/greenrobot/event/Logger.java new file mode 100644 index 00000000..9d7cba85 --- /dev/null +++ b/EventBus/src/de/greenrobot/event/Logger.java @@ -0,0 +1,239 @@ +package de.greenrobot.event; + +import android.annotation.TargetApi; +import android.os.Build; +import android.util.Log; + +import java.util.logging.Level; + +public abstract class Logger { + private static final boolean useAndroidLog; + private static volatile Logger DEFAULT_LOGGER; + + + static { + boolean android = false; + try { + android = Class.forName("android.util.Log") != null; + } catch (ClassNotFoundException e) { + // OK + } + useAndroidLog = android; + } + + + public static synchronized Logger initDefaultLogger(String tag) { + if (DEFAULT_LOGGER != null) { + throw new IllegalStateException("Default logger already set up"); + } + DEFAULT_LOGGER = create(tag); + return DEFAULT_LOGGER; + } + + public static Logger get() { + if (DEFAULT_LOGGER == null) { + throw new IllegalStateException("Default logger must be initialized before"); + } + return DEFAULT_LOGGER; + } + + public static Logger create(String tag) { + if (useAndroidLog) { + return new AndroidLogger(tag); + } else { + return new JavaLogger(tag); + } + } + + + public abstract boolean isLoggable(int level); + + public abstract void v(String msg); + + public abstract void v(String msg, Throwable th); + + public abstract void d(String msg); + + public abstract void d(String msg, Throwable th); + + public abstract void i(String msg); + + public abstract void i(String msg, Throwable th); + + public abstract void w(String msg); + + public abstract void w(String msg, Throwable th); + + public abstract void w(Throwable th); + + public abstract void e(String msg); + + public abstract void e(String msg, Throwable th); + + public abstract void wtf(String msg); + + public abstract void wtf(String msg, Throwable th); + + public static class AndroidLogger extends Logger { + public static final int VERBOSE = 2; + public static final int DEBUG = 3; + public static final int INFO = 4; + public static final int WARN = 5; + public static final int ERROR = 6; + public static final int ASSERT = 7; + + private final String tag; + + public AndroidLogger(String tag) { + this.tag = tag; + } + + public boolean isLoggable(int level) { + return Log.isLoggable(tag, level); + } + + public void v(String msg) { + Log.v(tag, msg); + } + + public void v(String msg, Throwable th) { + Log.v(tag, msg, th); + } + + public void d(String msg) { + Log.d(tag, msg); + } + + public void d(String msg, Throwable th) { + Log.d(tag, msg, th); + } + + public void i(String msg) { + Log.i(tag, msg); + } + + public void i(String msg, Throwable th) { + Log.i(tag, msg, th); + } + + public void w(String msg) { + Log.w(tag, msg); + } + + public void w(String msg, Throwable th) { + Log.w(tag, msg, th); + } + + public void w(Throwable th) { + Log.w(tag, th); + } + + public void e(String msg) { + Log.e(tag, msg); + } + + public void e(String msg, Throwable th) { + Log.e(tag, msg, th); + } + + @TargetApi(Build.VERSION_CODES.FROYO) + @Override + public void wtf(String msg) { + Log.wtf(tag, msg); + } + + @TargetApi(Build.VERSION_CODES.FROYO) + @Override + public void wtf(String msg, Throwable th) { + Log.wtf(tag, msg, th); + } + } + + public static class JavaLogger extends Logger { + private static final Level[] LEVEL_MAP = { + Level.OFF, Level.OFF, Level.OFF, // Unused + Level.FINEST, // VERBOSE = 2 + Level.FINE, //DEBUG = 3 + Level.INFO, // INFO = 4 + Level.WARNING, // WARN = 5 + Level.SEVERE, //ERROR = 6 + Level.SEVERE, //ASSERT = 7 + }; + + java.util.logging.Logger logger = java.util.logging.Logger.getLogger(""); + + public JavaLogger(String tag) { + logger = java.util.logging.Logger.getLogger(tag); + } + + @Override + public boolean isLoggable(int level) { + return logger.isLoggable(LEVEL_MAP[level]); + } + + @Override + public void v(String msg) { + logger.finest(msg); + } + + @Override + public void v(String msg, Throwable th) { + logger.log(Level.FINEST, msg, th); + } + + @Override + public void d(String msg) { + logger.fine(msg); + } + + @Override + public void d(String msg, Throwable th) { + logger.log(Level.FINE, msg, th); + } + + @Override + public void i(String msg) { + logger.info(msg); + } + + @Override + public void i(String msg, Throwable th) { + logger.log(Level.INFO, msg, th); + } + + @Override + public void w(String msg) { + logger.warning(msg); + } + + @Override + public void w(String msg, Throwable th) { + logger.log(Level.WARNING, msg, th); + } + + @Override + public void w(Throwable th) { + logger.log(Level.WARNING, null, th); + } + + @Override + public void e(String msg) { + logger.severe(msg); + } + + @Override + public void e(String msg, Throwable th) { + logger.log(Level.SEVERE, msg, th); + } + + @Override + public void wtf(String msg) { + logger.severe(msg); + } + + @Override + public void wtf(String msg, Throwable th) { + logger.log(Level.SEVERE, msg, th); + } + } +} From 1558ebf894dc9d8cac5db8b0676cfcd2c259418a Mon Sep 17 00:00:00 2001 From: William Ferguson Date: Sun, 31 Jan 2016 00:49:47 +1000 Subject: [PATCH 02/10] Providing mechanisms to allow non Android use of the library. --- .../org/greenrobot/eventbus/AsyncPoster.java | 2 +- .../greenrobot/eventbus/BackgroundPoster.java | 6 +- .../src/org/greenrobot/eventbus/EventBus.java | 35 ++++-- .../greenrobot/eventbus/EventBusBuilder.java | 20 ++++ .../greenrobot/eventbus/HandlerPoster.java | 8 +- .../src/org/greenrobot/eventbus/Poster.java | 32 ++++++ .../org/greenrobot/eventbus/SyncPoster.java | 35 ++++++ .../greenrobot/eventbus/log/AndroidLog.java | 95 ++++++++++++++++ .../org/greenrobot/eventbus/log/EBLog.java | 79 ++++++++++++++ .../greenrobot/eventbus/log/GenericLog.java | 39 +++++++ .../greenrobot/eventbus/log/SystemOutLog.java | 103 ++++++++++++++++++ .../eventbus/util/AndroidMTCalculator.java | 16 +++ .../eventbus/util/AsyncExecutor.java | 8 +- .../util/ExceptionToResourceMapping.java | 8 +- .../eventbus/util/MainThreadCalculator.java | 14 +++ .../eventbus/util/NonAndroidMTCalculator.java | 12 ++ 16 files changed, 482 insertions(+), 30 deletions(-) create mode 100644 EventBus/src/org/greenrobot/eventbus/Poster.java create mode 100644 EventBus/src/org/greenrobot/eventbus/SyncPoster.java create mode 100644 EventBus/src/org/greenrobot/eventbus/log/AndroidLog.java create mode 100644 EventBus/src/org/greenrobot/eventbus/log/EBLog.java create mode 100644 EventBus/src/org/greenrobot/eventbus/log/GenericLog.java create mode 100644 EventBus/src/org/greenrobot/eventbus/log/SystemOutLog.java create mode 100644 EventBus/src/org/greenrobot/eventbus/util/AndroidMTCalculator.java create mode 100644 EventBus/src/org/greenrobot/eventbus/util/MainThreadCalculator.java create mode 100644 EventBus/src/org/greenrobot/eventbus/util/NonAndroidMTCalculator.java diff --git a/EventBus/src/org/greenrobot/eventbus/AsyncPoster.java b/EventBus/src/org/greenrobot/eventbus/AsyncPoster.java index a56f4ebf..90a30d1e 100644 --- a/EventBus/src/org/greenrobot/eventbus/AsyncPoster.java +++ b/EventBus/src/org/greenrobot/eventbus/AsyncPoster.java @@ -21,7 +21,7 @@ * * @author Markus */ -class AsyncPoster implements Runnable { +class AsyncPoster implements Runnable, Poster { private final PendingPostQueue queue; private final EventBus eventBus; diff --git a/EventBus/src/org/greenrobot/eventbus/BackgroundPoster.java b/EventBus/src/org/greenrobot/eventbus/BackgroundPoster.java index 2a5319d0..d2e5dcfb 100644 --- a/EventBus/src/org/greenrobot/eventbus/BackgroundPoster.java +++ b/EventBus/src/org/greenrobot/eventbus/BackgroundPoster.java @@ -15,14 +15,14 @@ */ package org.greenrobot.eventbus; -import android.util.Log; +import org.greenrobot.eventbus.log.EBLog; /** * Posts events in background. * * @author Markus */ -final class BackgroundPoster implements Runnable { +final class BackgroundPoster implements Runnable, Poster { private final PendingPostQueue queue; private final EventBus eventBus; @@ -64,7 +64,7 @@ public void run() { eventBus.invokeSubscriber(pendingPost); } } catch (InterruptedException e) { - Log.w("Event", Thread.currentThread().getName() + " was interruppted", e); + EBLog.w(Thread.currentThread().getName() + " was interruppted", e); } } finally { executorRunning = false; diff --git a/EventBus/src/org/greenrobot/eventbus/EventBus.java b/EventBus/src/org/greenrobot/eventbus/EventBus.java index 1cd57e32..ae2b5834 100644 --- a/EventBus/src/org/greenrobot/eventbus/EventBus.java +++ b/EventBus/src/org/greenrobot/eventbus/EventBus.java @@ -15,8 +15,12 @@ */ package org.greenrobot.eventbus; -import android.os.Looper; -import android.util.Log; +import org.greenrobot.eventbus.log.AndroidLog; +import org.greenrobot.eventbus.log.EBLog; +import org.greenrobot.eventbus.log.SystemOutLog; +import org.greenrobot.eventbus.util.AndroidMTCalculator; +import org.greenrobot.eventbus.util.MainThreadCalculator; +import org.greenrobot.eventbus.util.NonAndroidMTCalculator; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; @@ -59,11 +63,12 @@ protected PostingThreadState initialValue() { } }; - private final HandlerPoster mainThreadPoster; + private final Poster mainThreadPoster; private final BackgroundPoster backgroundPoster; private final AsyncPoster asyncPoster; private final SubscriberMethodFinder subscriberMethodFinder; private final ExecutorService executorService; + private final MainThreadCalculator mtCalculator; private final boolean throwSubscriberException; private final boolean logSubscriberExceptions; @@ -105,10 +110,15 @@ public EventBus() { } EventBus(EventBusBuilder builder) { + if (builder.logTarget == null) { + EBLog.setLogTarget(builder.nonAndroidEnvironment ? new SystemOutLog() : new AndroidLog(TAG)); + } else { + EBLog.setLogTarget(builder.logTarget); + } subscriptionsByEventType = new HashMap<>(); typesBySubscriber = new HashMap<>(); stickyEvents = new ConcurrentHashMap<>(); - mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10); + mainThreadPoster = (builder.nonAndroidEnvironment ? new SyncPoster(this) : new HandlerPoster(this, 10)); backgroundPoster = new BackgroundPoster(this); asyncPoster = new AsyncPoster(this); indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0; @@ -121,6 +131,7 @@ public EventBus() { throwSubscriberException = builder.throwSubscriberException; eventInheritance = builder.eventInheritance; executorService = builder.executorService; + mtCalculator = (builder.nonAndroidEnvironment ? new NonAndroidMTCalculator() : new AndroidMTCalculator()); } /** @@ -196,7 +207,7 @@ private void checkPostStickyEventToSubscription(Subscription newSubscription, Ob if (stickyEvent != null) { // If the subscriber is trying to abort the event, it will fail (event is not tracked in posting state) // --> Strange corner case, which we don't take care of here. - postToSubscription(newSubscription, stickyEvent, Looper.getMainLooper() == Looper.myLooper()); + postToSubscription(newSubscription, stickyEvent, mtCalculator.isMainThread()); } } @@ -230,7 +241,7 @@ public synchronized void unregister(Object subscriber) { } typesBySubscriber.remove(subscriber); } else { - Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass()); + EBLog.w("Subscriber to unregister was not registered before: " + subscriber.getClass()); } } @@ -241,7 +252,7 @@ public void post(Object event) { eventQueue.add(event); if (!postingState.isPosting) { - postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper(); + postingState.isMainThread = mtCalculator.isMainThread(); postingState.isPosting = true; if (postingState.canceled) { throw new EventBusException("Internal error. Abort state was not reset"); @@ -374,7 +385,7 @@ private void postSingleEvent(Object event, PostingThreadState postingState) thro } if (!subscriptionFound) { if (logNoSubscriberMessages) { - Log.d(TAG, "No subscribers registered for event " + eventClass); + EBLog.d("No subscribers registered for event " + eventClass); } if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class && eventClass != SubscriberExceptionEvent.class) { @@ -494,10 +505,10 @@ private void handleSubscriberException(Subscription subscription, Object event, if (event instanceof SubscriberExceptionEvent) { if (logSubscriberExceptions) { // Don't send another SubscriberExceptionEvent to avoid infinite event recursion, just log - Log.e(TAG, "SubscriberExceptionEvent subscriber " + subscription.subscriber.getClass() + EBLog.e("SubscriberExceptionEvent subscriber " + subscription.subscriber.getClass() + " threw an exception", cause); SubscriberExceptionEvent exEvent = (SubscriberExceptionEvent) event; - Log.e(TAG, "Initial event " + exEvent.causingEvent + " caused exception in " + EBLog.e("Initial event " + exEvent.causingEvent + " caused exception in " + exEvent.causingSubscriber, exEvent.throwable); } } else { @@ -505,7 +516,7 @@ private void handleSubscriberException(Subscription subscription, Object event, throw new EventBusException("Invoking subscriber failed", cause); } if (logSubscriberExceptions) { - Log.e(TAG, "Could not dispatch event: " + event.getClass() + " to subscribing class " + EBLog.e("Could not dispatch event: " + event.getClass() + " to subscribing class " + subscription.subscriber.getClass(), cause); } if (sendSubscriberExceptionEvent) { @@ -518,7 +529,7 @@ private void handleSubscriberException(Subscription subscription, Object event, /** For ThreadLocal, much faster to set (and get multiple values). */ final static class PostingThreadState { - final List eventQueue = new ArrayList(); + final List eventQueue = new ArrayList<>(); boolean isPosting; boolean isMainThread; Subscription subscription; diff --git a/EventBus/src/org/greenrobot/eventbus/EventBusBuilder.java b/EventBus/src/org/greenrobot/eventbus/EventBusBuilder.java index e212750e..3a899a21 100644 --- a/EventBus/src/org/greenrobot/eventbus/EventBusBuilder.java +++ b/EventBus/src/org/greenrobot/eventbus/EventBusBuilder.java @@ -17,6 +17,8 @@ import org.greenrobot.eventbus.meta.SubscriberInfoIndex; +import org.greenrobot.eventbus.log.GenericLog; + import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; @@ -40,6 +42,8 @@ public class EventBusBuilder { ExecutorService executorService = DEFAULT_EXECUTOR_SERVICE; List> skipMethodVerificationForClasses; List subscriberInfoIndexes; + GenericLog logTarget; + boolean nonAndroidEnvironment; EventBusBuilder() { } @@ -137,6 +141,22 @@ public EventBusBuilder addIndex(SubscriberInfoIndex index) { return this; } + /** + * Set a specific log handler for all EventBus logging. + * + * By default all logging is via {@link android.util.Log} but if you want to use EventBus + * outside the Android environment then you will need to provide another log target. + */ + public EventBusBuilder logger(GenericLog logTarget) { + this.logTarget = logTarget; + return this; + } + + public EventBusBuilder nonAndroidEnvironment(boolean nonAndroidEnvironment) { + this.nonAndroidEnvironment = nonAndroidEnvironment; + return this; + } + /** * Installs the default EventBus returned by {@link EventBus#getDefault()} using this builders' values. Must be * done only once before the first usage of the default EventBus. diff --git a/EventBus/src/org/greenrobot/eventbus/HandlerPoster.java b/EventBus/src/org/greenrobot/eventbus/HandlerPoster.java index 3247be53..3596c47a 100644 --- a/EventBus/src/org/greenrobot/eventbus/HandlerPoster.java +++ b/EventBus/src/org/greenrobot/eventbus/HandlerPoster.java @@ -20,21 +20,21 @@ import android.os.Message; import android.os.SystemClock; -final class HandlerPoster extends Handler { +final class HandlerPoster extends Handler implements Poster { private final PendingPostQueue queue; private final int maxMillisInsideHandleMessage; private final EventBus eventBus; private boolean handlerActive; - HandlerPoster(EventBus eventBus, Looper looper, int maxMillisInsideHandleMessage) { - super(looper); + HandlerPoster(EventBus eventBus, int maxMillisInsideHandleMessage) { + super(Looper.getMainLooper()); this.eventBus = eventBus; this.maxMillisInsideHandleMessage = maxMillisInsideHandleMessage; queue = new PendingPostQueue(); } - void enqueue(Subscription subscription, Object event) { + public void enqueue(Subscription subscription, Object event) { PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event); synchronized (this) { queue.enqueue(pendingPost); diff --git a/EventBus/src/org/greenrobot/eventbus/Poster.java b/EventBus/src/org/greenrobot/eventbus/Poster.java new file mode 100644 index 00000000..3ebe24f4 --- /dev/null +++ b/EventBus/src/org/greenrobot/eventbus/Poster.java @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2012 Markus Junginger, greenrobot (http://greenrobot.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.greenrobot.eventbus; + +/** + * Posts events. + * + * @author William Ferguson + */ +interface Poster { + + /** + * Enqueue an event to be posted for a particular subscription. + * + * @param subscription Subscription which will receive the event. + * @param event Event that will be posted to subscribers. + */ + void enqueue(Subscription subscription, Object event); +} diff --git a/EventBus/src/org/greenrobot/eventbus/SyncPoster.java b/EventBus/src/org/greenrobot/eventbus/SyncPoster.java new file mode 100644 index 00000000..29e5c0cf --- /dev/null +++ b/EventBus/src/org/greenrobot/eventbus/SyncPoster.java @@ -0,0 +1,35 @@ +/* + * Copyright (C) 2012 Markus Junginger, greenrobot (http://greenrobot.de) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.greenrobot.eventbus; + + +/** + * Posts events in the current Thread. + * + * @author William Ferguson + */ +class SyncPoster implements Poster { + + private final EventBus eventBus; + + SyncPoster(EventBus eventBus) { + this.eventBus = eventBus; + } + + public void enqueue(Subscription subscription, Object event) { + eventBus.invokeSubscriber(subscription, event); + } +} diff --git a/EventBus/src/org/greenrobot/eventbus/log/AndroidLog.java b/EventBus/src/org/greenrobot/eventbus/log/AndroidLog.java new file mode 100644 index 00000000..c15def5a --- /dev/null +++ b/EventBus/src/org/greenrobot/eventbus/log/AndroidLog.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) Xandar IP 2013. + * + * All Rights Reserved + * No part of this application may be reproduced, copied, modified or adapted, without the prior written consent + * of the author, unless otherwise indicated for stand-alone materials. + * + * Contact support@xandar.com.au for copyright requests. + */ + +package org.greenrobot.eventbus.log; + +import android.util.Log; + +/** + * Logs to the Android log. + */ +public final class AndroidLog implements GenericLog { + + private final String tag; + + public AndroidLog(String tag) { + this.tag = tag; + } + + @Override + public void v(String msg) { + Log.v(tag, msg); + } + + @Override + public void v(String msg, Throwable tr) { + Log.v(tag, msg, tr); + } + + @Override + public void d(String msg) { + Log.d(tag, msg); + } + + @Override + public void d(String msg, Throwable tr) { + Log.d(tag, msg, tr); + } + + @Override + public void i(String msg) { + Log.i(tag, msg); + } + + @Override + public void i(String msg, Throwable tr) { + Log.i(tag, msg, tr); + } + + @Override + public void w(String msg) { + Log.w(tag, msg); + } + + @Override + public void w(String msg, Throwable tr) { + Log.w(tag, msg, tr); + } + + @Override + public void w(Throwable tr) { + Log.w(tag, tr); + } + + @Override + public void e(String msg) { + Log.e(tag, msg); + } + + @Override + public void e(String msg, Throwable tr) { + Log.e(tag, msg, tr); + } + + @Override + public void wtf(String msg) { + Log.wtf(tag, msg); + } + + @Override + public void wtf(Throwable tr) { + Log.wtf(tag, tr); + } + + @Override + public void wtf(String msg, Throwable tr) { + Log.wtf(tag, msg, tr); + } +} diff --git a/EventBus/src/org/greenrobot/eventbus/log/EBLog.java b/EventBus/src/org/greenrobot/eventbus/log/EBLog.java new file mode 100644 index 00000000..a321c9e5 --- /dev/null +++ b/EventBus/src/org/greenrobot/eventbus/log/EBLog.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) Xandar IP 2013. + * + * All Rights Reserved + * No part of this application may be reproduced, copied, modified or adapted, without the prior written consent + * of the author, unless otherwise indicated for stand-alone materials. + * + * Contact support@xandar.com.au for copyright requests. + */ + +package org.greenrobot.eventbus.log; + +/** + * Provides a platform neutral logging target for all EVentBus logging.. + */ +public final class EBLog { + + private static GenericLog log; + + public static void setLogTarget(GenericLog logTarget) { + log = logTarget; + } + + public static void v(String msg) { + log.v(msg); + } + + public static void v(String msg, Throwable tr) { + log.v(msg, tr); + } + + public static void d(String msg) { + log.d(msg); + } + + public static void d(String msg, Throwable tr) { + log.d(msg, tr); + } + + public static void i(String msg) { + log.i(msg); + } + + public static void i(String msg, Throwable tr) { + log.i(msg, tr); + } + + public static void w(String msg) { + log.w(msg); + } + + public static void w(String msg, Throwable tr) { + log.w(msg, tr); + } + + public static void w(Throwable tr) { + log.w(tr); + } + + public static void e(String msg) { + log.e(msg); + } + + public static void e(String msg, Throwable tr) { + log.e(msg, tr); + } + + public static void wtf(String msg) { + log.wtf(msg); + } + + public static void wtf(Throwable tr) { + log.wtf(tr); + } + + public static void wtf(String msg, Throwable tr) { + log.wtf(msg, tr); + } +} diff --git a/EventBus/src/org/greenrobot/eventbus/log/GenericLog.java b/EventBus/src/org/greenrobot/eventbus/log/GenericLog.java new file mode 100644 index 00000000..8ad08177 --- /dev/null +++ b/EventBus/src/org/greenrobot/eventbus/log/GenericLog.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) Xandar IP 2013. + * + * All Rights Reserved + * No part of this application may be reproduced, copied, modified or adapted, without the prior written consent + * of the author, unless otherwise indicated for stand-alone materials. + * + * Contact support@xandar.com.au for copyright requests. + */ + +package org.greenrobot.eventbus.log; + +/** + * Means of logging regardless of what platform you are on. + * + * @author William Ferguson + */ +public interface GenericLog { + + void v(String msg); + void v(String msg, Throwable tr); + + void d(String msg); + void d(String msg, Throwable tr); + + void i(String msg); + void i(String msg, Throwable tr); + + void w(String msg); + void w(String msg, Throwable tr); + void w(Throwable tr); + + void e(String msg); + void e(String msg, Throwable tr); + + void wtf(String msg); + void wtf(Throwable tr); + void wtf(String msg, Throwable tr); +} diff --git a/EventBus/src/org/greenrobot/eventbus/log/SystemOutLog.java b/EventBus/src/org/greenrobot/eventbus/log/SystemOutLog.java new file mode 100644 index 00000000..096af53f --- /dev/null +++ b/EventBus/src/org/greenrobot/eventbus/log/SystemOutLog.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) Xandar IP 2013. + * + * All Rights Reserved + * No part of this application may be reproduced, copied, modified or adapted, without the prior written consent + * of the author, unless otherwise indicated for stand-alone materials. + * + * Contact support@xandar.com.au for copyright requests. + */ + +package org.greenrobot.eventbus.log; + +/** + * Logs to SystemOut. + * + * @author William Ferguson + */ +public final class SystemOutLog implements GenericLog { + + @Override + public void v(String msg) { + System.out.println("VERBOSE: " + msg); + } + + @Override + public void v(String msg, Throwable tr) { + System.out.println("VERBOSE: " + msg); + System.out.println("VERBOSE: " + tr.getMessage()); + tr.printStackTrace(System.out); + } + + @Override + public void d(String msg) { + System.out.println("DEBUG: " + msg); + } + + @Override + public void d(String msg, Throwable tr) { + System.out.println("DEBUG: " + msg); + System.out.println("DEBUG: " + tr.getMessage()); + tr.printStackTrace(System.out); + } + + @Override + public void i(String msg) { + System.out.println("INFO: " + msg); + } + + @Override + public void i(String msg, Throwable tr) { + System.out.println("INFO: " + msg); + System.out.println("INFO: " + tr.getMessage()); + tr.printStackTrace(System.out); + } + + @Override + public void w(String msg) { + System.out.println("WARN: " + msg); + } + + @Override + public void w(String msg, Throwable tr) { + System.out.println("WARN: " + msg); + System.out.println("WARN: " + tr.getMessage()); + tr.printStackTrace(System.out); + } + + @Override + public void w(Throwable tr) { + System.out.println("WARN: " + tr.getMessage()); + tr.printStackTrace(System.out); + } + + @Override + public void e(String msg) { + System.out.println("ERROR: " + msg); + } + + @Override + public void e(String msg, Throwable tr) { + System.out.println("ERROR: " + msg); + System.out.println("ERROR: " + tr.getMessage()); + tr.printStackTrace(System.out); + } + + @Override + public void wtf(String msg) { + System.out.println("WTF: " + msg); + } + + @Override + public void wtf(Throwable tr) { + System.out.println("WTF: " + tr.getMessage()); + tr.printStackTrace(System.out); + } + + @Override + public void wtf(String msg, Throwable tr) { + System.out.println("WTF: " + msg); + System.out.println("WTF: " + tr.getMessage()); + tr.printStackTrace(System.out); + } +} diff --git a/EventBus/src/org/greenrobot/eventbus/util/AndroidMTCalculator.java b/EventBus/src/org/greenrobot/eventbus/util/AndroidMTCalculator.java new file mode 100644 index 00000000..23ce5753 --- /dev/null +++ b/EventBus/src/org/greenrobot/eventbus/util/AndroidMTCalculator.java @@ -0,0 +1,16 @@ +package org.greenrobot.eventbus.util; + +import android.os.Looper; + +/** + * Returns true if the current Thread is the Android Main Looper Thread. + * + * @author William Ferguson + */ +public class AndroidMTCalculator implements MainThreadCalculator { + + @Override + public boolean isMainThread() { + return Looper.getMainLooper() == Looper.myLooper(); + } +} diff --git a/EventBus/src/org/greenrobot/eventbus/util/AsyncExecutor.java b/EventBus/src/org/greenrobot/eventbus/util/AsyncExecutor.java index c44c1366..d989b361 100644 --- a/EventBus/src/org/greenrobot/eventbus/util/AsyncExecutor.java +++ b/EventBus/src/org/greenrobot/eventbus/util/AsyncExecutor.java @@ -15,10 +15,8 @@ */ package org.greenrobot.eventbus.util; -import android.app.Activity; -import android.util.Log; - import org.greenrobot.eventbus.EventBus; +import org.greenrobot.eventbus.log.EBLog; import java.lang.reflect.Constructor; import java.util.concurrent.Executor; @@ -59,7 +57,7 @@ public AsyncExecutor build() { return buildForScope(null); } - public AsyncExecutor buildForActivityScope(Activity activity) { + public AsyncExecutor buildForActivityScope(Object activity) { return buildForScope(activity.getClass()); } @@ -119,7 +117,7 @@ public void run() { try { event = failureEventConstructor.newInstance(e); } catch (Exception e1) { - Log.e(EventBus.TAG, "Original exception:", e); + EBLog.e("Original exception:", e); throw new RuntimeException("Could not create failure event", e1); } if (event instanceof HasExecutionScope) { diff --git a/EventBus/src/org/greenrobot/eventbus/util/ExceptionToResourceMapping.java b/EventBus/src/org/greenrobot/eventbus/util/ExceptionToResourceMapping.java index 9ab0d006..b334c13c 100644 --- a/EventBus/src/org/greenrobot/eventbus/util/ExceptionToResourceMapping.java +++ b/EventBus/src/org/greenrobot/eventbus/util/ExceptionToResourceMapping.java @@ -16,9 +16,7 @@ package org.greenrobot.eventbus.util; -import android.util.Log; - -import org.greenrobot.eventbus.EventBus; +import org.greenrobot.eventbus.log.EBLog; import java.util.HashMap; import java.util.Map; @@ -36,7 +34,7 @@ public class ExceptionToResourceMapping { public final Map, Integer> throwableToMsgIdMap; public ExceptionToResourceMapping() { - throwableToMsgIdMap = new HashMap, Integer>(); + throwableToMsgIdMap = new HashMap<>(); } /** Looks at the exception and its causes trying to find an ID. */ @@ -52,7 +50,7 @@ public Integer mapThrowable(final Throwable throwable) { throwableToCheck = throwableToCheck.getCause(); depthToGo--; if (depthToGo <= 0 || throwableToCheck == throwable || throwableToCheck == null) { - Log.d(EventBus.TAG, "No specific message ressource ID found for " + throwable); + EBLog.d("No specific message resource ID found for " + throwable); // return config.defaultErrorMsgId; return null; } diff --git a/EventBus/src/org/greenrobot/eventbus/util/MainThreadCalculator.java b/EventBus/src/org/greenrobot/eventbus/util/MainThreadCalculator.java new file mode 100644 index 00000000..6feeb21d --- /dev/null +++ b/EventBus/src/org/greenrobot/eventbus/util/MainThreadCalculator.java @@ -0,0 +1,14 @@ +package org.greenrobot.eventbus.util; + +/** + * Determines whether the current Thread is the Android Main Looper Thread. + * + * @author William Ferguson + */ +public interface MainThreadCalculator { + + /** + * @return true if the current Thread is the Android Main Looper Thread. + */ + boolean isMainThread(); +} diff --git a/EventBus/src/org/greenrobot/eventbus/util/NonAndroidMTCalculator.java b/EventBus/src/org/greenrobot/eventbus/util/NonAndroidMTCalculator.java new file mode 100644 index 00000000..2a7897ee --- /dev/null +++ b/EventBus/src/org/greenrobot/eventbus/util/NonAndroidMTCalculator.java @@ -0,0 +1,12 @@ +package org.greenrobot.eventbus.util; + +/** + * Always returns false as the Main Looper Thread only occurs within Android. + */ +public class NonAndroidMTCalculator implements MainThreadCalculator { + + @Override + public boolean isMainThread() { + return false; + } +} From 0a5acfb37b6d57913b730a214c2ff8cf89634757 Mon Sep 17 00:00:00 2001 From: Markus Date: Fri, 5 Feb 2016 19:24:14 +0100 Subject: [PATCH 03/10] simplified Logger to use java.util.logging.Level --- EventBus/src/de/greenrobot/event/Logger.java | 213 +++++-------------- 1 file changed, 50 insertions(+), 163 deletions(-) diff --git a/EventBus/src/de/greenrobot/event/Logger.java b/EventBus/src/de/greenrobot/event/Logger.java index 9d7cba85..b2af3d40 100644 --- a/EventBus/src/de/greenrobot/event/Logger.java +++ b/EventBus/src/de/greenrobot/event/Logger.java @@ -1,7 +1,5 @@ package de.greenrobot.event; -import android.annotation.TargetApi; -import android.os.Build; import android.util.Log; import java.util.logging.Level; @@ -45,195 +43,84 @@ public static Logger create(String tag) { } } + public abstract boolean isLoggable(Level level); - public abstract boolean isLoggable(int level); + public abstract void log(Level level, String msg); - public abstract void v(String msg); - - public abstract void v(String msg, Throwable th); - - public abstract void d(String msg); - - public abstract void d(String msg, Throwable th); - - public abstract void i(String msg); - - public abstract void i(String msg, Throwable th); - - public abstract void w(String msg); - - public abstract void w(String msg, Throwable th); - - public abstract void w(Throwable th); - - public abstract void e(String msg); - - public abstract void e(String msg, Throwable th); - - public abstract void wtf(String msg); - - public abstract void wtf(String msg, Throwable th); + public abstract void log(Level level, String msg, Throwable th); public static class AndroidLogger extends Logger { - public static final int VERBOSE = 2; - public static final int DEBUG = 3; - public static final int INFO = 4; - public static final int WARN = 5; - public static final int ERROR = 6; - public static final int ASSERT = 7; - private final String tag; public AndroidLogger(String tag) { this.tag = tag; } - public boolean isLoggable(int level) { - return Log.isLoggable(tag, level); - } - - public void v(String msg) { - Log.v(tag, msg); - } - - public void v(String msg, Throwable th) { - Log.v(tag, msg, th); - } - - public void d(String msg) { - Log.d(tag, msg); - } - - public void d(String msg, Throwable th) { - Log.d(tag, msg, th); - } - - public void i(String msg) { - Log.i(tag, msg); - } - - public void i(String msg, Throwable th) { - Log.i(tag, msg, th); - } - - public void w(String msg) { - Log.w(tag, msg); - } - - public void w(String msg, Throwable th) { - Log.w(tag, msg, th); - } - - public void w(Throwable th) { - Log.w(tag, th); - } - - public void e(String msg) { - Log.e(tag, msg); - } - - public void e(String msg, Throwable th) { - Log.e(tag, msg, th); - } - - @TargetApi(Build.VERSION_CODES.FROYO) - @Override - public void wtf(String msg) { - Log.wtf(tag, msg); + public boolean isLoggable(Level level) { + if (level == Level.OFF) { + return false; + } else { + return Log.isLoggable(tag, mapLevel(level)); + } + } + + public void log(Level level, String msg) { + if (level != Level.OFF) { + Log.println(mapLevel(level), tag, msg); + } + } + + public void log(Level level, String msg, Throwable th) { + if (level != Level.OFF) { + // That's how Log does it internally + Log.println(mapLevel(level), tag, msg + "\n" + Log.getStackTraceString(th)); + } + } + + protected int mapLevel(Level level) { + if (level == Level.OFF) { + return 0; + } else if (level == Level.FINEST || level == Level.FINER) { + return Log.VERBOSE; + } else if (level == Level.FINE || level == Level.CONFIG) { + return Log.DEBUG; + } else if (level == Level.INFO) { + return Log.INFO; + } else if (level == Level.WARNING) { + return Log.WARN; + } else if (level == Level.SEVERE) { + return Log.ERROR; + } else if (level == Level.ALL) { + // Hmm, well.. + return Log.ASSERT; + } else { + throw new IllegalArgumentException("Unexpected level: " + level); + } } - @TargetApi(Build.VERSION_CODES.FROYO) - @Override - public void wtf(String msg, Throwable th) { - Log.wtf(tag, msg, th); - } } public static class JavaLogger extends Logger { - private static final Level[] LEVEL_MAP = { - Level.OFF, Level.OFF, Level.OFF, // Unused - Level.FINEST, // VERBOSE = 2 - Level.FINE, //DEBUG = 3 - Level.INFO, // INFO = 4 - Level.WARNING, // WARN = 5 - Level.SEVERE, //ERROR = 6 - Level.SEVERE, //ASSERT = 7 - }; - - java.util.logging.Logger logger = java.util.logging.Logger.getLogger(""); + protected final java.util.logging.Logger logger; public JavaLogger(String tag) { logger = java.util.logging.Logger.getLogger(tag); } @Override - public boolean isLoggable(int level) { - return logger.isLoggable(LEVEL_MAP[level]); - } - - @Override - public void v(String msg) { - logger.finest(msg); - } - - @Override - public void v(String msg, Throwable th) { - logger.log(Level.FINEST, msg, th); - } - - @Override - public void d(String msg) { - logger.fine(msg); - } - - @Override - public void d(String msg, Throwable th) { - logger.log(Level.FINE, msg, th); - } - - @Override - public void i(String msg) { - logger.info(msg); - } - - @Override - public void i(String msg, Throwable th) { - logger.log(Level.INFO, msg, th); - } - - @Override - public void w(String msg) { - logger.warning(msg); - } - - @Override - public void w(String msg, Throwable th) { - logger.log(Level.WARNING, msg, th); + public boolean isLoggable(Level level) { + return logger.isLoggable(level); } @Override - public void w(Throwable th) { - logger.log(Level.WARNING, null, th); + public void log(Level level, String msg) { + logger.log(level, msg); } @Override - public void e(String msg) { - logger.severe(msg); + public void log(Level level, String msg, Throwable th) { + logger.log(level, msg, th); } - @Override - public void e(String msg, Throwable th) { - logger.log(Level.SEVERE, msg, th); - } - - @Override - public void wtf(String msg) { - logger.severe(msg); - } - - @Override - public void wtf(String msg, Throwable th) { - logger.log(Level.SEVERE, msg, th); - } } } From fcc5eda79f434aec508e760acf30f3e10582c25d Mon Sep 17 00:00:00 2001 From: Markus Date: Mon, 8 Feb 2016 18:19:56 +0100 Subject: [PATCH 04/10] remove DEFAULT_LOGGER, map level based on intValue --- EventBus/src/de/greenrobot/event/Logger.java | 43 +++++--------------- 1 file changed, 10 insertions(+), 33 deletions(-) diff --git a/EventBus/src/de/greenrobot/event/Logger.java b/EventBus/src/de/greenrobot/event/Logger.java index b2af3d40..10a11970 100644 --- a/EventBus/src/de/greenrobot/event/Logger.java +++ b/EventBus/src/de/greenrobot/event/Logger.java @@ -6,8 +6,6 @@ public abstract class Logger { private static final boolean useAndroidLog; - private static volatile Logger DEFAULT_LOGGER; - static { boolean android = false; @@ -19,22 +17,6 @@ public abstract class Logger { useAndroidLog = android; } - - public static synchronized Logger initDefaultLogger(String tag) { - if (DEFAULT_LOGGER != null) { - throw new IllegalStateException("Default logger already set up"); - } - DEFAULT_LOGGER = create(tag); - return DEFAULT_LOGGER; - } - - public static Logger get() { - if (DEFAULT_LOGGER == null) { - throw new IllegalStateException("Default logger must be initialized before"); - } - return DEFAULT_LOGGER; - } - public static Logger create(String tag) { if (useAndroidLog) { return new AndroidLogger(tag); @@ -78,26 +60,21 @@ public void log(Level level, String msg, Throwable th) { } protected int mapLevel(Level level) { - if (level == Level.OFF) { - return 0; - } else if (level == Level.FINEST || level == Level.FINER) { - return Log.VERBOSE; - } else if (level == Level.FINE || level == Level.CONFIG) { - return Log.DEBUG; - } else if (level == Level.INFO) { + int value = level.intValue(); + if (value < 800) { // below INFO + if (value < 500) { // below FINE + return Log.VERBOSE; + } else { + return Log.DEBUG; + } + } else if (value < 900) { // below WARNING return Log.INFO; - } else if (level == Level.WARNING) { + } else if (value < 1000) { // below ERROR return Log.WARN; - } else if (level == Level.SEVERE) { - return Log.ERROR; - } else if (level == Level.ALL) { - // Hmm, well.. - return Log.ASSERT; } else { - throw new IllegalArgumentException("Unexpected level: " + level); + return Log.ERROR; } } - } public static class JavaLogger extends Logger { From d1a3ab3b559ad3606cd8dc90ecca805481d855d6 Mon Sep 17 00:00:00 2001 From: Markus Date: Mon, 15 Feb 2016 19:03:25 +0100 Subject: [PATCH 05/10] SystemOutLogger etc. --- EventBus/src/de/greenrobot/event/Logger.java | 35 +++++++++++++++++--- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/EventBus/src/de/greenrobot/event/Logger.java b/EventBus/src/de/greenrobot/event/Logger.java index 10a11970..897d437b 100644 --- a/EventBus/src/de/greenrobot/event/Logger.java +++ b/EventBus/src/de/greenrobot/event/Logger.java @@ -5,7 +5,7 @@ import java.util.logging.Level; public abstract class Logger { - private static final boolean useAndroidLog; + private static final boolean ANDROID_LOG_AVAILABLE; static { boolean android = false; @@ -14,14 +14,18 @@ public abstract class Logger { } catch (ClassNotFoundException e) { // OK } - useAndroidLog = android; + ANDROID_LOG_AVAILABLE = android; + } + + public static boolean isAndroidLogAvailable() { + return ANDROID_LOG_AVAILABLE; } public static Logger create(String tag) { - if (useAndroidLog) { + if (ANDROID_LOG_AVAILABLE) { return new AndroidLogger(tag); } else { - return new JavaLogger(tag); + return new SystemOutLogger(); } } @@ -91,13 +95,36 @@ public boolean isLoggable(Level level) { @Override public void log(Level level, String msg) { + // TODO Replace logged method with caller method logger.log(level, msg); } @Override public void log(Level level, String msg, Throwable th) { + // TODO Replace logged method with caller method logger.log(level, msg, th); } } + + public static class SystemOutLogger extends Logger { + + @Override + public boolean isLoggable(Level level) { + return true; + } + + @Override + public void log(Level level, String msg) { + System.out.println("[" + level + "] " + msg); + } + + @Override + public void log(Level level, String msg, Throwable th) { + System.out.println("[" + level + "] " + msg); + th.printStackTrace(System.out); + } + + } + } From 95bbdc005bd0ea8eca8e39745148d488e48b03a3 Mon Sep 17 00:00:00 2001 From: Markus Date: Thu, 25 Feb 2016 23:58:58 +0100 Subject: [PATCH 06/10] replaced logging with smaller Logger --- .../greenrobot/eventbus/BackgroundPoster.java | 6 +- .../src/org/greenrobot/eventbus/EventBus.java | 28 ++--- .../greenrobot/eventbus/EventBusBuilder.java | 22 ++-- .../greenrobot/eventbus}/Logger.java | 66 ++++------- .../greenrobot/eventbus/log/AndroidLog.java | 95 ---------------- .../org/greenrobot/eventbus/log/EBLog.java | 79 -------------- .../greenrobot/eventbus/log/GenericLog.java | 39 ------- .../greenrobot/eventbus/log/SystemOutLog.java | 103 ------------------ .../eventbus/util/AsyncExecutor.java | 4 +- .../util/ExceptionToResourceMapping.java | 4 +- 10 files changed, 54 insertions(+), 392 deletions(-) rename EventBus/src/{de/greenrobot/event => org/greenrobot/eventbus}/Logger.java (59%) delete mode 100644 EventBus/src/org/greenrobot/eventbus/log/AndroidLog.java delete mode 100644 EventBus/src/org/greenrobot/eventbus/log/EBLog.java delete mode 100644 EventBus/src/org/greenrobot/eventbus/log/GenericLog.java delete mode 100644 EventBus/src/org/greenrobot/eventbus/log/SystemOutLog.java diff --git a/EventBus/src/org/greenrobot/eventbus/BackgroundPoster.java b/EventBus/src/org/greenrobot/eventbus/BackgroundPoster.java index d2e5dcfb..624ddf6d 100644 --- a/EventBus/src/org/greenrobot/eventbus/BackgroundPoster.java +++ b/EventBus/src/org/greenrobot/eventbus/BackgroundPoster.java @@ -15,11 +15,11 @@ */ package org.greenrobot.eventbus; -import org.greenrobot.eventbus.log.EBLog; +import java.util.logging.Level; /** * Posts events in background. - * + * * @author Markus */ final class BackgroundPoster implements Runnable, Poster { @@ -64,7 +64,7 @@ public void run() { eventBus.invokeSubscriber(pendingPost); } } catch (InterruptedException e) { - EBLog.w(Thread.currentThread().getName() + " was interruppted", e); + eventBus.getLogger().log(Level.WARNING, Thread.currentThread().getName() + " was interruppted", e); } } finally { executorRunning = false; diff --git a/EventBus/src/org/greenrobot/eventbus/EventBus.java b/EventBus/src/org/greenrobot/eventbus/EventBus.java index ae2b5834..8312a983 100644 --- a/EventBus/src/org/greenrobot/eventbus/EventBus.java +++ b/EventBus/src/org/greenrobot/eventbus/EventBus.java @@ -15,9 +15,6 @@ */ package org.greenrobot.eventbus; -import org.greenrobot.eventbus.log.AndroidLog; -import org.greenrobot.eventbus.log.EBLog; -import org.greenrobot.eventbus.log.SystemOutLog; import org.greenrobot.eventbus.util.AndroidMTCalculator; import org.greenrobot.eventbus.util.MainThreadCalculator; import org.greenrobot.eventbus.util.NonAndroidMTCalculator; @@ -31,6 +28,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutorService; +import java.util.logging.Level; /** * EventBus is a central publish/subscribe event system for Android. Events are posted ({@link #post(Object)}) to the @@ -78,6 +76,7 @@ protected PostingThreadState initialValue() { private final boolean eventInheritance; private final int indexCount; + private final Logger logger; /** Convenience singleton for apps using a process-wide EventBus instance. */ public static EventBus getDefault() { @@ -110,11 +109,7 @@ public EventBus() { } EventBus(EventBusBuilder builder) { - if (builder.logTarget == null) { - EBLog.setLogTarget(builder.nonAndroidEnvironment ? new SystemOutLog() : new AndroidLog(TAG)); - } else { - EBLog.setLogTarget(builder.logTarget); - } + logger = builder.initLogger(); subscriptionsByEventType = new HashMap<>(); typesBySubscriber = new HashMap<>(); stickyEvents = new ConcurrentHashMap<>(); @@ -241,7 +236,7 @@ public synchronized void unregister(Object subscriber) { } typesBySubscriber.remove(subscriber); } else { - EBLog.w("Subscriber to unregister was not registered before: " + subscriber.getClass()); + logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass()); } } @@ -385,7 +380,7 @@ private void postSingleEvent(Object event, PostingThreadState postingState) thro } if (!subscriptionFound) { if (logNoSubscriberMessages) { - EBLog.d("No subscribers registered for event " + eventClass); + logger.log(Level.FINE, "No subscribers registered for event " + eventClass); } if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class && eventClass != SubscriberExceptionEvent.class) { @@ -505,10 +500,10 @@ private void handleSubscriberException(Subscription subscription, Object event, if (event instanceof SubscriberExceptionEvent) { if (logSubscriberExceptions) { // Don't send another SubscriberExceptionEvent to avoid infinite event recursion, just log - EBLog.e("SubscriberExceptionEvent subscriber " + subscription.subscriber.getClass() + logger.log(Level.SEVERE, "SubscriberExceptionEvent subscriber " + subscription.subscriber.getClass() + " threw an exception", cause); SubscriberExceptionEvent exEvent = (SubscriberExceptionEvent) event; - EBLog.e("Initial event " + exEvent.causingEvent + " caused exception in " + logger.log(Level.SEVERE, "Initial event " + exEvent.causingEvent + " caused exception in " + exEvent.causingSubscriber, exEvent.throwable); } } else { @@ -516,7 +511,7 @@ private void handleSubscriberException(Subscription subscription, Object event, throw new EventBusException("Invoking subscriber failed", cause); } if (logSubscriberExceptions) { - EBLog.e("Could not dispatch event: " + event.getClass() + " to subscribing class " + logger.log(Level.SEVERE, "Could not dispatch event: " + event.getClass() + " to subscribing class " + subscription.subscriber.getClass(), cause); } if (sendSubscriberExceptionEvent) { @@ -541,6 +536,13 @@ ExecutorService getExecutorService() { return executorService; } + /** + * For internal use only. + */ + public Logger getLogger() { + return logger; + } + // Just an idea: we could provide a callback to post() to be notified, an alternative would be events, of course... /* public */interface PostCallback { void onPostCompleted(List exceptionEvents); diff --git a/EventBus/src/org/greenrobot/eventbus/EventBusBuilder.java b/EventBus/src/org/greenrobot/eventbus/EventBusBuilder.java index 3a899a21..b12a7f38 100644 --- a/EventBus/src/org/greenrobot/eventbus/EventBusBuilder.java +++ b/EventBus/src/org/greenrobot/eventbus/EventBusBuilder.java @@ -17,8 +17,6 @@ import org.greenrobot.eventbus.meta.SubscriberInfoIndex; -import org.greenrobot.eventbus.log.GenericLog; - import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; @@ -42,7 +40,7 @@ public class EventBusBuilder { ExecutorService executorService = DEFAULT_EXECUTOR_SERVICE; List> skipMethodVerificationForClasses; List subscriberInfoIndexes; - GenericLog logTarget; + Logger logger; boolean nonAndroidEnvironment; EventBusBuilder() { @@ -134,7 +132,7 @@ public EventBusBuilder strictMethodVerification(boolean strictMethodVerification /** Adds an index generated by EventBus' annotation preprocessor. */ public EventBusBuilder addIndex(SubscriberInfoIndex index) { - if(subscriberInfoIndexes == null) { + if (subscriberInfoIndexes == null) { subscriberInfoIndexes = new ArrayList<>(); } subscriberInfoIndexes.add(index); @@ -143,18 +141,22 @@ public EventBusBuilder addIndex(SubscriberInfoIndex index) { /** * Set a specific log handler for all EventBus logging. - * + *

* By default all logging is via {@link android.util.Log} but if you want to use EventBus * outside the Android environment then you will need to provide another log target. */ - public EventBusBuilder logger(GenericLog logTarget) { - this.logTarget = logTarget; + public EventBusBuilder logger(Logger logger) { + this.logger = logger; return this; } - public EventBusBuilder nonAndroidEnvironment(boolean nonAndroidEnvironment) { - this.nonAndroidEnvironment = nonAndroidEnvironment; - return this; + Logger initLogger() { + if (logger != null) { + return logger; + } else { + return Logger.AndroidLogger.isAndroidLogAvailable() ? new Logger.AndroidLogger("EventBus") : + new Logger.SystemOutLogger(); + } } /** diff --git a/EventBus/src/de/greenrobot/event/Logger.java b/EventBus/src/org/greenrobot/eventbus/Logger.java similarity index 59% rename from EventBus/src/de/greenrobot/event/Logger.java rename to EventBus/src/org/greenrobot/eventbus/Logger.java index 897d437b..7a1ad232 100644 --- a/EventBus/src/de/greenrobot/event/Logger.java +++ b/EventBus/src/org/greenrobot/eventbus/Logger.java @@ -1,55 +1,39 @@ -package de.greenrobot.event; +package org.greenrobot.eventbus; import android.util.Log; import java.util.logging.Level; -public abstract class Logger { - private static final boolean ANDROID_LOG_AVAILABLE; +public interface Logger { - static { - boolean android = false; - try { - android = Class.forName("android.util.Log") != null; - } catch (ClassNotFoundException e) { - // OK - } - ANDROID_LOG_AVAILABLE = android; - } + void log(Level level, String msg); - public static boolean isAndroidLogAvailable() { - return ANDROID_LOG_AVAILABLE; - } + void log(Level level, String msg, Throwable th); - public static Logger create(String tag) { - if (ANDROID_LOG_AVAILABLE) { - return new AndroidLogger(tag); - } else { - return new SystemOutLogger(); - } - } + public static class AndroidLogger implements Logger { + static final boolean ANDROID_LOG_AVAILABLE; - public abstract boolean isLoggable(Level level); + static { + boolean android = false; + try { + android = Class.forName("android.util.Log") != null; + } catch (ClassNotFoundException e) { + // OK + } + ANDROID_LOG_AVAILABLE = android; + } - public abstract void log(Level level, String msg); + public static boolean isAndroidLogAvailable() { + return ANDROID_LOG_AVAILABLE; + } - public abstract void log(Level level, String msg, Throwable th); - public static class AndroidLogger extends Logger { private final String tag; public AndroidLogger(String tag) { this.tag = tag; } - public boolean isLoggable(Level level) { - if (level == Level.OFF) { - return false; - } else { - return Log.isLoggable(tag, mapLevel(level)); - } - } - public void log(Level level, String msg) { if (level != Level.OFF) { Log.println(mapLevel(level), tag, msg); @@ -81,18 +65,13 @@ protected int mapLevel(Level level) { } } - public static class JavaLogger extends Logger { + public static class JavaLogger implements Logger { protected final java.util.logging.Logger logger; public JavaLogger(String tag) { logger = java.util.logging.Logger.getLogger(tag); } - @Override - public boolean isLoggable(Level level) { - return logger.isLoggable(level); - } - @Override public void log(Level level, String msg) { // TODO Replace logged method with caller method @@ -107,12 +86,7 @@ public void log(Level level, String msg, Throwable th) { } - public static class SystemOutLogger extends Logger { - - @Override - public boolean isLoggable(Level level) { - return true; - } + public static class SystemOutLogger implements Logger { @Override public void log(Level level, String msg) { diff --git a/EventBus/src/org/greenrobot/eventbus/log/AndroidLog.java b/EventBus/src/org/greenrobot/eventbus/log/AndroidLog.java deleted file mode 100644 index c15def5a..00000000 --- a/EventBus/src/org/greenrobot/eventbus/log/AndroidLog.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) Xandar IP 2013. - * - * All Rights Reserved - * No part of this application may be reproduced, copied, modified or adapted, without the prior written consent - * of the author, unless otherwise indicated for stand-alone materials. - * - * Contact support@xandar.com.au for copyright requests. - */ - -package org.greenrobot.eventbus.log; - -import android.util.Log; - -/** - * Logs to the Android log. - */ -public final class AndroidLog implements GenericLog { - - private final String tag; - - public AndroidLog(String tag) { - this.tag = tag; - } - - @Override - public void v(String msg) { - Log.v(tag, msg); - } - - @Override - public void v(String msg, Throwable tr) { - Log.v(tag, msg, tr); - } - - @Override - public void d(String msg) { - Log.d(tag, msg); - } - - @Override - public void d(String msg, Throwable tr) { - Log.d(tag, msg, tr); - } - - @Override - public void i(String msg) { - Log.i(tag, msg); - } - - @Override - public void i(String msg, Throwable tr) { - Log.i(tag, msg, tr); - } - - @Override - public void w(String msg) { - Log.w(tag, msg); - } - - @Override - public void w(String msg, Throwable tr) { - Log.w(tag, msg, tr); - } - - @Override - public void w(Throwable tr) { - Log.w(tag, tr); - } - - @Override - public void e(String msg) { - Log.e(tag, msg); - } - - @Override - public void e(String msg, Throwable tr) { - Log.e(tag, msg, tr); - } - - @Override - public void wtf(String msg) { - Log.wtf(tag, msg); - } - - @Override - public void wtf(Throwable tr) { - Log.wtf(tag, tr); - } - - @Override - public void wtf(String msg, Throwable tr) { - Log.wtf(tag, msg, tr); - } -} diff --git a/EventBus/src/org/greenrobot/eventbus/log/EBLog.java b/EventBus/src/org/greenrobot/eventbus/log/EBLog.java deleted file mode 100644 index a321c9e5..00000000 --- a/EventBus/src/org/greenrobot/eventbus/log/EBLog.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) Xandar IP 2013. - * - * All Rights Reserved - * No part of this application may be reproduced, copied, modified or adapted, without the prior written consent - * of the author, unless otherwise indicated for stand-alone materials. - * - * Contact support@xandar.com.au for copyright requests. - */ - -package org.greenrobot.eventbus.log; - -/** - * Provides a platform neutral logging target for all EVentBus logging.. - */ -public final class EBLog { - - private static GenericLog log; - - public static void setLogTarget(GenericLog logTarget) { - log = logTarget; - } - - public static void v(String msg) { - log.v(msg); - } - - public static void v(String msg, Throwable tr) { - log.v(msg, tr); - } - - public static void d(String msg) { - log.d(msg); - } - - public static void d(String msg, Throwable tr) { - log.d(msg, tr); - } - - public static void i(String msg) { - log.i(msg); - } - - public static void i(String msg, Throwable tr) { - log.i(msg, tr); - } - - public static void w(String msg) { - log.w(msg); - } - - public static void w(String msg, Throwable tr) { - log.w(msg, tr); - } - - public static void w(Throwable tr) { - log.w(tr); - } - - public static void e(String msg) { - log.e(msg); - } - - public static void e(String msg, Throwable tr) { - log.e(msg, tr); - } - - public static void wtf(String msg) { - log.wtf(msg); - } - - public static void wtf(Throwable tr) { - log.wtf(tr); - } - - public static void wtf(String msg, Throwable tr) { - log.wtf(msg, tr); - } -} diff --git a/EventBus/src/org/greenrobot/eventbus/log/GenericLog.java b/EventBus/src/org/greenrobot/eventbus/log/GenericLog.java deleted file mode 100644 index 8ad08177..00000000 --- a/EventBus/src/org/greenrobot/eventbus/log/GenericLog.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) Xandar IP 2013. - * - * All Rights Reserved - * No part of this application may be reproduced, copied, modified or adapted, without the prior written consent - * of the author, unless otherwise indicated for stand-alone materials. - * - * Contact support@xandar.com.au for copyright requests. - */ - -package org.greenrobot.eventbus.log; - -/** - * Means of logging regardless of what platform you are on. - * - * @author William Ferguson - */ -public interface GenericLog { - - void v(String msg); - void v(String msg, Throwable tr); - - void d(String msg); - void d(String msg, Throwable tr); - - void i(String msg); - void i(String msg, Throwable tr); - - void w(String msg); - void w(String msg, Throwable tr); - void w(Throwable tr); - - void e(String msg); - void e(String msg, Throwable tr); - - void wtf(String msg); - void wtf(Throwable tr); - void wtf(String msg, Throwable tr); -} diff --git a/EventBus/src/org/greenrobot/eventbus/log/SystemOutLog.java b/EventBus/src/org/greenrobot/eventbus/log/SystemOutLog.java deleted file mode 100644 index 096af53f..00000000 --- a/EventBus/src/org/greenrobot/eventbus/log/SystemOutLog.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (c) Xandar IP 2013. - * - * All Rights Reserved - * No part of this application may be reproduced, copied, modified or adapted, without the prior written consent - * of the author, unless otherwise indicated for stand-alone materials. - * - * Contact support@xandar.com.au for copyright requests. - */ - -package org.greenrobot.eventbus.log; - -/** - * Logs to SystemOut. - * - * @author William Ferguson - */ -public final class SystemOutLog implements GenericLog { - - @Override - public void v(String msg) { - System.out.println("VERBOSE: " + msg); - } - - @Override - public void v(String msg, Throwable tr) { - System.out.println("VERBOSE: " + msg); - System.out.println("VERBOSE: " + tr.getMessage()); - tr.printStackTrace(System.out); - } - - @Override - public void d(String msg) { - System.out.println("DEBUG: " + msg); - } - - @Override - public void d(String msg, Throwable tr) { - System.out.println("DEBUG: " + msg); - System.out.println("DEBUG: " + tr.getMessage()); - tr.printStackTrace(System.out); - } - - @Override - public void i(String msg) { - System.out.println("INFO: " + msg); - } - - @Override - public void i(String msg, Throwable tr) { - System.out.println("INFO: " + msg); - System.out.println("INFO: " + tr.getMessage()); - tr.printStackTrace(System.out); - } - - @Override - public void w(String msg) { - System.out.println("WARN: " + msg); - } - - @Override - public void w(String msg, Throwable tr) { - System.out.println("WARN: " + msg); - System.out.println("WARN: " + tr.getMessage()); - tr.printStackTrace(System.out); - } - - @Override - public void w(Throwable tr) { - System.out.println("WARN: " + tr.getMessage()); - tr.printStackTrace(System.out); - } - - @Override - public void e(String msg) { - System.out.println("ERROR: " + msg); - } - - @Override - public void e(String msg, Throwable tr) { - System.out.println("ERROR: " + msg); - System.out.println("ERROR: " + tr.getMessage()); - tr.printStackTrace(System.out); - } - - @Override - public void wtf(String msg) { - System.out.println("WTF: " + msg); - } - - @Override - public void wtf(Throwable tr) { - System.out.println("WTF: " + tr.getMessage()); - tr.printStackTrace(System.out); - } - - @Override - public void wtf(String msg, Throwable tr) { - System.out.println("WTF: " + msg); - System.out.println("WTF: " + tr.getMessage()); - tr.printStackTrace(System.out); - } -} diff --git a/EventBus/src/org/greenrobot/eventbus/util/AsyncExecutor.java b/EventBus/src/org/greenrobot/eventbus/util/AsyncExecutor.java index d989b361..ba5f263d 100644 --- a/EventBus/src/org/greenrobot/eventbus/util/AsyncExecutor.java +++ b/EventBus/src/org/greenrobot/eventbus/util/AsyncExecutor.java @@ -16,11 +16,11 @@ package org.greenrobot.eventbus.util; import org.greenrobot.eventbus.EventBus; -import org.greenrobot.eventbus.log.EBLog; import java.lang.reflect.Constructor; import java.util.concurrent.Executor; import java.util.concurrent.Executors; +import java.util.logging.Level; /** * Executes an {@link RunnableEx} using a thread pool. Thrown exceptions are propagated by posting failure events of any @@ -117,7 +117,7 @@ public void run() { try { event = failureEventConstructor.newInstance(e); } catch (Exception e1) { - EBLog.e("Original exception:", e); + eventBus.getLogger().log(Level.SEVERE, "Original exception:", e); throw new RuntimeException("Could not create failure event", e1); } if (event instanceof HasExecutionScope) { diff --git a/EventBus/src/org/greenrobot/eventbus/util/ExceptionToResourceMapping.java b/EventBus/src/org/greenrobot/eventbus/util/ExceptionToResourceMapping.java index b334c13c..a3bb67f3 100644 --- a/EventBus/src/org/greenrobot/eventbus/util/ExceptionToResourceMapping.java +++ b/EventBus/src/org/greenrobot/eventbus/util/ExceptionToResourceMapping.java @@ -16,7 +16,7 @@ package org.greenrobot.eventbus.util; -import org.greenrobot.eventbus.log.EBLog; +import android.util.Log; import java.util.HashMap; import java.util.Map; @@ -50,7 +50,7 @@ public Integer mapThrowable(final Throwable throwable) { throwableToCheck = throwableToCheck.getCause(); depthToGo--; if (depthToGo <= 0 || throwableToCheck == throwable || throwableToCheck == null) { - EBLog.d("No specific message resource ID found for " + throwable); + Log.d("EventBus", "No specific message resource ID found for " + throwable); // return config.defaultErrorMsgId; return null; } From 850615d492c2b292b791d796be39998dece117c1 Mon Sep 17 00:00:00 2001 From: Markus Date: Mon, 29 Feb 2016 18:17:06 +0100 Subject: [PATCH 07/10] MainThreadSupport interface as a single place for main thread support --- .../src/org/greenrobot/eventbus/EventBus.java | 28 ++++++++++----- .../greenrobot/eventbus/EventBusBuilder.java | 2 +- .../greenrobot/eventbus/HandlerPoster.java | 6 ++-- .../eventbus/MainThreadSupport.java | 33 +++++++++++++++++ .../org/greenrobot/eventbus/SyncPoster.java | 35 ------------------- .../eventbus/util/AndroidMTCalculator.java | 16 --------- .../eventbus/util/MainThreadCalculator.java | 14 -------- .../eventbus/util/NonAndroidMTCalculator.java | 12 ------- 8 files changed, 57 insertions(+), 89 deletions(-) create mode 100644 EventBus/src/org/greenrobot/eventbus/MainThreadSupport.java delete mode 100644 EventBus/src/org/greenrobot/eventbus/SyncPoster.java delete mode 100644 EventBus/src/org/greenrobot/eventbus/util/AndroidMTCalculator.java delete mode 100644 EventBus/src/org/greenrobot/eventbus/util/MainThreadCalculator.java delete mode 100644 EventBus/src/org/greenrobot/eventbus/util/NonAndroidMTCalculator.java diff --git a/EventBus/src/org/greenrobot/eventbus/EventBus.java b/EventBus/src/org/greenrobot/eventbus/EventBus.java index 8312a983..2518946b 100644 --- a/EventBus/src/org/greenrobot/eventbus/EventBus.java +++ b/EventBus/src/org/greenrobot/eventbus/EventBus.java @@ -15,9 +15,7 @@ */ package org.greenrobot.eventbus; -import org.greenrobot.eventbus.util.AndroidMTCalculator; -import org.greenrobot.eventbus.util.MainThreadCalculator; -import org.greenrobot.eventbus.util.NonAndroidMTCalculator; +import android.os.Looper; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; @@ -61,12 +59,14 @@ protected PostingThreadState initialValue() { } }; + // @Nullable + private final MainThreadSupport mainThreadSupport; + // @Nullable private final Poster mainThreadPoster; private final BackgroundPoster backgroundPoster; private final AsyncPoster asyncPoster; private final SubscriberMethodFinder subscriberMethodFinder; private final ExecutorService executorService; - private final MainThreadCalculator mtCalculator; private final boolean throwSubscriberException; private final boolean logSubscriberExceptions; @@ -113,7 +113,10 @@ public EventBus() { subscriptionsByEventType = new HashMap<>(); typesBySubscriber = new HashMap<>(); stickyEvents = new ConcurrentHashMap<>(); - mainThreadPoster = (builder.nonAndroidEnvironment ? new SyncPoster(this) : new HandlerPoster(this, 10)); + mainThreadSupport = builder.mainThreadSupport != null ? builder.mainThreadSupport : + Logger.AndroidLogger.isAndroidLogAvailable() ? + new MainThreadSupport.AndroidHandlerMainThreadSupport(Looper.getMainLooper()) : null; + mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null; backgroundPoster = new BackgroundPoster(this); asyncPoster = new AsyncPoster(this); indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0; @@ -126,7 +129,6 @@ public EventBus() { throwSubscriberException = builder.throwSubscriberException; eventInheritance = builder.eventInheritance; executorService = builder.executorService; - mtCalculator = (builder.nonAndroidEnvironment ? new NonAndroidMTCalculator() : new AndroidMTCalculator()); } /** @@ -202,10 +204,20 @@ private void checkPostStickyEventToSubscription(Subscription newSubscription, Ob if (stickyEvent != null) { // If the subscriber is trying to abort the event, it will fail (event is not tracked in posting state) // --> Strange corner case, which we don't take care of here. - postToSubscription(newSubscription, stickyEvent, mtCalculator.isMainThread()); + postToSubscription(newSubscription, stickyEvent, isMainThread()); } } + /** + * Checks if the current thread is running in the main thread. + * If there is no main thread support (e.g. non-Android), "true" is always returned. In that case MAIN thread + * subscribers are always called in posting thread, and BACKGROUND subscribers are always called from a background + * poster. + */ + private boolean isMainThread() { + return mainThreadSupport != null? mainThreadSupport.isMainThread(): true; + } + public synchronized boolean isRegistered(Object subscriber) { return typesBySubscriber.containsKey(subscriber); } @@ -247,7 +259,7 @@ public void post(Object event) { eventQueue.add(event); if (!postingState.isPosting) { - postingState.isMainThread = mtCalculator.isMainThread(); + postingState.isMainThread = isMainThread(); postingState.isPosting = true; if (postingState.canceled) { throw new EventBusException("Internal error. Abort state was not reset"); diff --git a/EventBus/src/org/greenrobot/eventbus/EventBusBuilder.java b/EventBus/src/org/greenrobot/eventbus/EventBusBuilder.java index b12a7f38..90e53eb0 100644 --- a/EventBus/src/org/greenrobot/eventbus/EventBusBuilder.java +++ b/EventBus/src/org/greenrobot/eventbus/EventBusBuilder.java @@ -41,7 +41,7 @@ public class EventBusBuilder { List> skipMethodVerificationForClasses; List subscriberInfoIndexes; Logger logger; - boolean nonAndroidEnvironment; + MainThreadSupport mainThreadSupport; EventBusBuilder() { } diff --git a/EventBus/src/org/greenrobot/eventbus/HandlerPoster.java b/EventBus/src/org/greenrobot/eventbus/HandlerPoster.java index 3596c47a..95309547 100644 --- a/EventBus/src/org/greenrobot/eventbus/HandlerPoster.java +++ b/EventBus/src/org/greenrobot/eventbus/HandlerPoster.java @@ -20,15 +20,15 @@ import android.os.Message; import android.os.SystemClock; -final class HandlerPoster extends Handler implements Poster { +public class HandlerPoster extends Handler implements Poster { private final PendingPostQueue queue; private final int maxMillisInsideHandleMessage; private final EventBus eventBus; private boolean handlerActive; - HandlerPoster(EventBus eventBus, int maxMillisInsideHandleMessage) { - super(Looper.getMainLooper()); + protected HandlerPoster(EventBus eventBus, Looper looper, int maxMillisInsideHandleMessage) { + super(looper); this.eventBus = eventBus; this.maxMillisInsideHandleMessage = maxMillisInsideHandleMessage; queue = new PendingPostQueue(); diff --git a/EventBus/src/org/greenrobot/eventbus/MainThreadSupport.java b/EventBus/src/org/greenrobot/eventbus/MainThreadSupport.java new file mode 100644 index 00000000..6c77fde8 --- /dev/null +++ b/EventBus/src/org/greenrobot/eventbus/MainThreadSupport.java @@ -0,0 +1,33 @@ +package org.greenrobot.eventbus; + +import android.os.Looper; + +/** + * Interface to the "main" thread, which can be whatever you like. Typically on Android, Android's main thread is used. + */ +public interface MainThreadSupport { + + boolean isMainThread(); + + Poster createPoster(EventBus eventBus); + + class AndroidHandlerMainThreadSupport implements MainThreadSupport { + + private final Looper looper; + + public AndroidHandlerMainThreadSupport(Looper looper) { + this.looper = looper; + } + + @Override + public boolean isMainThread() { + return looper == Looper.myLooper(); + } + + @Override + public Poster createPoster(EventBus eventBus) { + return new HandlerPoster(eventBus, looper, 10); + } + } + +} diff --git a/EventBus/src/org/greenrobot/eventbus/SyncPoster.java b/EventBus/src/org/greenrobot/eventbus/SyncPoster.java deleted file mode 100644 index 29e5c0cf..00000000 --- a/EventBus/src/org/greenrobot/eventbus/SyncPoster.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) 2012 Markus Junginger, greenrobot (http://greenrobot.de) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.greenrobot.eventbus; - - -/** - * Posts events in the current Thread. - * - * @author William Ferguson - */ -class SyncPoster implements Poster { - - private final EventBus eventBus; - - SyncPoster(EventBus eventBus) { - this.eventBus = eventBus; - } - - public void enqueue(Subscription subscription, Object event) { - eventBus.invokeSubscriber(subscription, event); - } -} diff --git a/EventBus/src/org/greenrobot/eventbus/util/AndroidMTCalculator.java b/EventBus/src/org/greenrobot/eventbus/util/AndroidMTCalculator.java deleted file mode 100644 index 23ce5753..00000000 --- a/EventBus/src/org/greenrobot/eventbus/util/AndroidMTCalculator.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.greenrobot.eventbus.util; - -import android.os.Looper; - -/** - * Returns true if the current Thread is the Android Main Looper Thread. - * - * @author William Ferguson - */ -public class AndroidMTCalculator implements MainThreadCalculator { - - @Override - public boolean isMainThread() { - return Looper.getMainLooper() == Looper.myLooper(); - } -} diff --git a/EventBus/src/org/greenrobot/eventbus/util/MainThreadCalculator.java b/EventBus/src/org/greenrobot/eventbus/util/MainThreadCalculator.java deleted file mode 100644 index 6feeb21d..00000000 --- a/EventBus/src/org/greenrobot/eventbus/util/MainThreadCalculator.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.greenrobot.eventbus.util; - -/** - * Determines whether the current Thread is the Android Main Looper Thread. - * - * @author William Ferguson - */ -public interface MainThreadCalculator { - - /** - * @return true if the current Thread is the Android Main Looper Thread. - */ - boolean isMainThread(); -} diff --git a/EventBus/src/org/greenrobot/eventbus/util/NonAndroidMTCalculator.java b/EventBus/src/org/greenrobot/eventbus/util/NonAndroidMTCalculator.java deleted file mode 100644 index 2a7897ee..00000000 --- a/EventBus/src/org/greenrobot/eventbus/util/NonAndroidMTCalculator.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.greenrobot.eventbus.util; - -/** - * Always returns false as the Main Looper Thread only occurs within Android. - */ -public class NonAndroidMTCalculator implements MainThreadCalculator { - - @Override - public boolean isMainThread() { - return false; - } -} From b7f78faa6ee235473782e3113293b316bdd59ff4 Mon Sep 17 00:00:00 2001 From: Markus Date: Mon, 29 Feb 2016 20:11:32 +0100 Subject: [PATCH 08/10] update copyright header --- EventBus/src/org/greenrobot/eventbus/Logger.java | 15 +++++++++++++++ .../greenrobot/eventbus/MainThreadSupport.java | 15 +++++++++++++++ EventBus/src/org/greenrobot/eventbus/Poster.java | 8 ++++---- 3 files changed, 34 insertions(+), 4 deletions(-) diff --git a/EventBus/src/org/greenrobot/eventbus/Logger.java b/EventBus/src/org/greenrobot/eventbus/Logger.java index 7a1ad232..6609b61b 100644 --- a/EventBus/src/org/greenrobot/eventbus/Logger.java +++ b/EventBus/src/org/greenrobot/eventbus/Logger.java @@ -1,3 +1,18 @@ +/* + * Copyright (C) 2012-2016 Markus Junginger, greenrobot (http://greenrobot.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.greenrobot.eventbus; import android.util.Log; diff --git a/EventBus/src/org/greenrobot/eventbus/MainThreadSupport.java b/EventBus/src/org/greenrobot/eventbus/MainThreadSupport.java index 6c77fde8..d5655533 100644 --- a/EventBus/src/org/greenrobot/eventbus/MainThreadSupport.java +++ b/EventBus/src/org/greenrobot/eventbus/MainThreadSupport.java @@ -1,3 +1,18 @@ +/* + * Copyright (C) 2012-2016 Markus Junginger, greenrobot (http://greenrobot.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.greenrobot.eventbus; import android.os.Looper; diff --git a/EventBus/src/org/greenrobot/eventbus/Poster.java b/EventBus/src/org/greenrobot/eventbus/Poster.java index 3ebe24f4..a69a078d 100644 --- a/EventBus/src/org/greenrobot/eventbus/Poster.java +++ b/EventBus/src/org/greenrobot/eventbus/Poster.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Markus Junginger, greenrobot (http://greenrobot.de) + * Copyright (C) 2012-2016 Markus Junginger, greenrobot (http://greenrobot.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ /** * Posts events. - * + * * @author William Ferguson */ interface Poster { @@ -25,8 +25,8 @@ interface Poster { /** * Enqueue an event to be posted for a particular subscription. * - * @param subscription Subscription which will receive the event. - * @param event Event that will be posted to subscribers. + * @param subscription Subscription which will receive the event. + * @param event Event that will be posted to subscribers. */ void enqueue(Subscription subscription, Object event); } From f236762ab957f7bb945ead44c9fb7fae1797505e Mon Sep 17 00:00:00 2001 From: Markus Date: Mon, 29 Feb 2016 21:45:18 +0100 Subject: [PATCH 09/10] remove AsyncExecutor.buildForActivityScope --- EventBus/src/org/greenrobot/eventbus/util/AsyncExecutor.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/EventBus/src/org/greenrobot/eventbus/util/AsyncExecutor.java b/EventBus/src/org/greenrobot/eventbus/util/AsyncExecutor.java index ba5f263d..9c0433e8 100644 --- a/EventBus/src/org/greenrobot/eventbus/util/AsyncExecutor.java +++ b/EventBus/src/org/greenrobot/eventbus/util/AsyncExecutor.java @@ -57,10 +57,6 @@ public AsyncExecutor build() { return buildForScope(null); } - public AsyncExecutor buildForActivityScope(Object activity) { - return buildForScope(activity.getClass()); - } - public AsyncExecutor buildForScope(Object executionContext) { if (eventBus == null) { eventBus = EventBus.getDefault(); From 598e4a1bf7ace60697808b631bb704cde79d39f6 Mon Sep 17 00:00:00 2001 From: Markus Date: Mon, 29 Feb 2016 21:45:43 +0100 Subject: [PATCH 10/10] remove error dialog and mapping classes --- .../eventbus/util/ErrorDialogConfig.java | 82 ------ .../util/ErrorDialogFragmentFactory.java | 114 -------- .../eventbus/util/ErrorDialogFragments.java | 91 ------ .../eventbus/util/ErrorDialogManager.java | 262 ------------------ .../util/ExceptionToResourceMapping.java | 88 ------ 5 files changed, 637 deletions(-) delete mode 100644 EventBus/src/org/greenrobot/eventbus/util/ErrorDialogConfig.java delete mode 100644 EventBus/src/org/greenrobot/eventbus/util/ErrorDialogFragmentFactory.java delete mode 100644 EventBus/src/org/greenrobot/eventbus/util/ErrorDialogFragments.java delete mode 100644 EventBus/src/org/greenrobot/eventbus/util/ErrorDialogManager.java delete mode 100644 EventBus/src/org/greenrobot/eventbus/util/ExceptionToResourceMapping.java diff --git a/EventBus/src/org/greenrobot/eventbus/util/ErrorDialogConfig.java b/EventBus/src/org/greenrobot/eventbus/util/ErrorDialogConfig.java deleted file mode 100644 index 95e84c72..00000000 --- a/EventBus/src/org/greenrobot/eventbus/util/ErrorDialogConfig.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2012-2016 Markus Junginger, greenrobot (http://greenrobot.org) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.greenrobot.eventbus.util; - -import android.content.res.Resources; -import android.util.Log; - -import org.greenrobot.eventbus.EventBus; - -public class ErrorDialogConfig { - final Resources resources; - final int defaultTitleId; - final int defaultErrorMsgId; - final ExceptionToResourceMapping mapping; - - EventBus eventBus; - boolean logExceptions = true; - String tagForLoggingExceptions; - int defaultDialogIconId; - Class defaultEventTypeOnDialogClosed; - - public ErrorDialogConfig(Resources resources, int defaultTitleId, int defaultMsgId) { - this.resources = resources; - this.defaultTitleId = defaultTitleId; - this.defaultErrorMsgId = defaultMsgId; - mapping = new ExceptionToResourceMapping(); - } - - public ErrorDialogConfig addMapping(Class clazz, int msgId) { - mapping.addMapping(clazz, msgId); - return this; - } - - public int getMessageIdForThrowable(final Throwable throwable) { - Integer resId = mapping.mapThrowable(throwable); - if (resId != null) { - return resId; - } else { - Log.d(EventBus.TAG, "No specific message ressource ID found for " + throwable); - return defaultErrorMsgId; - } - } - - public void setDefaultDialogIconId(int defaultDialogIconId) { - this.defaultDialogIconId = defaultDialogIconId; - } - - public void setDefaultEventTypeOnDialogClosed(Class defaultEventTypeOnDialogClosed) { - this.defaultEventTypeOnDialogClosed = defaultEventTypeOnDialogClosed; - } - - public void disableExceptionLogging() { - logExceptions = false; - } - - public void setTagForLoggingExceptions(String tagForLoggingExceptions) { - this.tagForLoggingExceptions = tagForLoggingExceptions; - } - - public void setEventBus(EventBus eventBus) { - this.eventBus = eventBus; - } - - /** eventBus!=null ? eventBus: EventBus.getDefault() */ - EventBus getEventBus() { - return eventBus!=null ? eventBus: EventBus.getDefault(); - } -} \ No newline at end of file diff --git a/EventBus/src/org/greenrobot/eventbus/util/ErrorDialogFragmentFactory.java b/EventBus/src/org/greenrobot/eventbus/util/ErrorDialogFragmentFactory.java deleted file mode 100644 index 27ab963d..00000000 --- a/EventBus/src/org/greenrobot/eventbus/util/ErrorDialogFragmentFactory.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (C) 2012-2016 Markus Junginger, greenrobot (http://greenrobot.org) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.greenrobot.eventbus.util; - -import android.annotation.TargetApi; -import android.os.Build; -import android.os.Bundle; -import android.support.v4.app.Fragment; - -/** - * Factory to allow injecting a more complex exception mapping; typically you would subclass one of {@link Honeycomb} or - * {@link Support}. - */ -public abstract class ErrorDialogFragmentFactory { - protected final ErrorDialogConfig config; - - protected ErrorDialogFragmentFactory(ErrorDialogConfig config) { - this.config = config; - } - - /** - * Prepares the fragment's arguments and creates the fragment. May be overridden to provide custom error fragments. - */ - protected T prepareErrorFragment(ThrowableFailureEvent event, boolean finishAfterDialog, - Bundle argumentsForErrorDialog) { - if (event.isSuppressErrorUi()) { - // Show nothing by default - return null; - } - Bundle bundle; - if (argumentsForErrorDialog != null) { - bundle = (Bundle) argumentsForErrorDialog.clone(); - } else { - bundle = new Bundle(); - } - - if (!bundle.containsKey(ErrorDialogManager.KEY_TITLE)) { - String title = getTitleFor(event, bundle); - bundle.putString(ErrorDialogManager.KEY_TITLE, title); - } - if (!bundle.containsKey(ErrorDialogManager.KEY_MESSAGE)) { - String message = getMessageFor(event, bundle); - bundle.putString(ErrorDialogManager.KEY_MESSAGE, message); - } - if (!bundle.containsKey(ErrorDialogManager.KEY_FINISH_AFTER_DIALOG)) { - bundle.putBoolean(ErrorDialogManager.KEY_FINISH_AFTER_DIALOG, finishAfterDialog); - } - if (!bundle.containsKey(ErrorDialogManager.KEY_EVENT_TYPE_ON_CLOSE) - && config.defaultEventTypeOnDialogClosed != null) { - bundle.putSerializable(ErrorDialogManager.KEY_EVENT_TYPE_ON_CLOSE, config.defaultEventTypeOnDialogClosed); - } - if (!bundle.containsKey(ErrorDialogManager.KEY_ICON_ID) && config.defaultDialogIconId != 0) { - bundle.putInt(ErrorDialogManager.KEY_ICON_ID, config.defaultDialogIconId); - } - return createErrorFragment(event, bundle); - } - - /** Returns either a new Honeycomb+ or a new support library DialogFragment. */ - protected abstract T createErrorFragment(ThrowableFailureEvent event, Bundle arguments); - - /** May be overridden to provide custom error title. */ - protected String getTitleFor(ThrowableFailureEvent event, Bundle arguments) { - return config.resources.getString(config.defaultTitleId); - } - - /** May be overridden to provide custom error messages. */ - protected String getMessageFor(ThrowableFailureEvent event, Bundle arguments) { - int msgResId = config.getMessageIdForThrowable(event.throwable); - return config.resources.getString(msgResId); - } - - public static class Support extends ErrorDialogFragmentFactory { - - public Support(ErrorDialogConfig config) { - super(config); - } - - protected Fragment createErrorFragment(ThrowableFailureEvent event, Bundle arguments) { - ErrorDialogFragments.Support errorFragment = new ErrorDialogFragments.Support(); - errorFragment.setArguments(arguments); - return errorFragment; - } - - } - - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - public static class Honeycomb extends ErrorDialogFragmentFactory { - - public Honeycomb(ErrorDialogConfig config) { - super(config); - } - - protected android.app.Fragment createErrorFragment(ThrowableFailureEvent event, Bundle arguments) { - ErrorDialogFragments.Honeycomb errorFragment = new ErrorDialogFragments.Honeycomb(); - errorFragment.setArguments(arguments); - return errorFragment; - } - - } -} \ No newline at end of file diff --git a/EventBus/src/org/greenrobot/eventbus/util/ErrorDialogFragments.java b/EventBus/src/org/greenrobot/eventbus/util/ErrorDialogFragments.java deleted file mode 100644 index 49174766..00000000 --- a/EventBus/src/org/greenrobot/eventbus/util/ErrorDialogFragments.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (C) 2012-2016 Markus Junginger, greenrobot (http://greenrobot.org) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.greenrobot.eventbus.util; - -import android.annotation.TargetApi; -import android.app.Activity; -import android.app.AlertDialog; -import android.app.Dialog; -import android.content.Context; -import android.content.DialogInterface; -import android.content.DialogInterface.OnClickListener; -import android.os.Build; -import android.os.Bundle; -import android.support.v4.app.DialogFragment; - -import org.greenrobot.eventbus.EventBus; - -public class ErrorDialogFragments { - /** TODO Use config: Icon res ID to use for all error dialogs. May be configured by each app (optional). */ - public static int ERROR_DIALOG_ICON = 0; - - /** TODO Use config: Event class to be fired on dismissing the dialog by the user. May be configured by each app. */ - public static Class EVENT_TYPE_ON_CLICK; - - public static Dialog createDialog(Context context, Bundle arguments, OnClickListener onClickListener) { - AlertDialog.Builder builder = new AlertDialog.Builder(context); - builder.setTitle(arguments.getString(ErrorDialogManager.KEY_TITLE)); - builder.setMessage(arguments.getString(ErrorDialogManager.KEY_MESSAGE)); - if (ERROR_DIALOG_ICON != 0) { - builder.setIcon(ERROR_DIALOG_ICON); - } - builder.setPositiveButton(android.R.string.ok, onClickListener); - return builder.create(); - } - - public static void handleOnClick(DialogInterface dialog, int which, Activity activity, Bundle arguments) { - if (EVENT_TYPE_ON_CLICK != null) { - Object event; - try { - event = EVENT_TYPE_ON_CLICK.newInstance(); - } catch (Exception e) { - throw new RuntimeException("Event cannot be constructed", e); - } - EventBus eventBus = ErrorDialogManager.factory.config.getEventBus(); - eventBus.post(event); - } - boolean finish = arguments.getBoolean(ErrorDialogManager.KEY_FINISH_AFTER_DIALOG, false); - if (finish && activity != null) { - activity.finish(); - } - } - - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - public static class Honeycomb extends android.app.DialogFragment implements OnClickListener { - @Override - public Dialog onCreateDialog(Bundle savedInstanceState) { - return createDialog(getActivity(), getArguments(), this); - } - - @Override - public void onClick(DialogInterface dialog, int which) { - handleOnClick(dialog, which, getActivity(), getArguments()); - } - } - - public static class Support extends DialogFragment implements OnClickListener { - @Override - public Dialog onCreateDialog(Bundle savedInstanceState) { - return createDialog(getActivity(), getArguments(), this); - } - - @Override - public void onClick(DialogInterface dialog, int which) { - handleOnClick(dialog, which, getActivity(), getArguments()); - } - } -} diff --git a/EventBus/src/org/greenrobot/eventbus/util/ErrorDialogManager.java b/EventBus/src/org/greenrobot/eventbus/util/ErrorDialogManager.java deleted file mode 100644 index 9d5ccf2c..00000000 --- a/EventBus/src/org/greenrobot/eventbus/util/ErrorDialogManager.java +++ /dev/null @@ -1,262 +0,0 @@ -/* - * Copyright (C) 2012-2016 Markus Junginger, greenrobot (http://greenrobot.org) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.greenrobot.eventbus.util; - -import android.annotation.TargetApi; -import android.app.Activity; -import android.app.Application; -import android.os.Build; -import android.os.Bundle; -import android.support.v4.app.DialogFragment; -import android.support.v4.app.Fragment; -import android.support.v4.app.FragmentActivity; -import android.support.v4.app.FragmentManager; -import android.util.Log; - -import org.greenrobot.eventbus.EventBus; - -/** - * Central class for app that want to use event based error dialogs.
- *
- * How to use: - *

    - *
  1. Set the {@link #factory} to configure dialogs for your app, typically in {@link Application#onCreate()}
  2. - *
  3. Use one of {@link #attachTo(Activity)}, {@link #attachTo(Activity, boolean)} or - * {@link #attachTo(Activity, boolean, Bundle)} in your Activity, typically in onCreate.
  4. - *
- * - * For more complex mappings, you can supply your own {@link ErrorDialogFragmentFactory}. - * - * @author Markus - */ -public class ErrorDialogManager { - - public static class SupportManagerFragment extends Fragment { - protected boolean finishAfterDialog; - protected Bundle argumentsForErrorDialog; - private EventBus eventBus; - private boolean skipRegisterOnNextResume; - private Object executionScope; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - eventBus = ErrorDialogManager.factory.config.getEventBus(); - eventBus.register(this); - skipRegisterOnNextResume = true; - } - - @Override - public void onResume() { - super.onResume(); - if (skipRegisterOnNextResume) { - // registered in onCreate, skip registration in this run - skipRegisterOnNextResume = false; - } else { - eventBus = ErrorDialogManager.factory.config.getEventBus(); - eventBus.register(this); - } - } - - @Override - public void onPause() { - eventBus.unregister(this); - super.onPause(); - } - - public void onEventMainThread(ThrowableFailureEvent event) { - if (!isInExecutionScope(executionScope, event)) { - return; - } - checkLogException(event); - // Execute pending commits before finding to avoid multiple error fragments being shown - FragmentManager fm = getFragmentManager(); - fm.executePendingTransactions(); - - DialogFragment existingFragment = (DialogFragment) fm.findFragmentByTag(TAG_ERROR_DIALOG); - if (existingFragment != null) { - // Just show the latest error - existingFragment.dismiss(); - } - - android.support.v4.app.DialogFragment errorFragment = (android.support.v4.app.DialogFragment) factory - .prepareErrorFragment(event, finishAfterDialog, argumentsForErrorDialog); - if (errorFragment != null) { - errorFragment.show(fm, TAG_ERROR_DIALOG); - } - } - - public static void attachTo(Activity activity, Object executionScope, boolean finishAfterDialog, - Bundle argumentsForErrorDialog) { - FragmentManager fm = ((FragmentActivity) activity).getSupportFragmentManager(); - SupportManagerFragment fragment = (SupportManagerFragment) fm.findFragmentByTag(TAG_ERROR_DIALOG_MANAGER); - if (fragment == null) { - fragment = new SupportManagerFragment(); - fm.beginTransaction().add(fragment, TAG_ERROR_DIALOG_MANAGER).commit(); - fm.executePendingTransactions(); - } - fragment.finishAfterDialog = finishAfterDialog; - fragment.argumentsForErrorDialog = argumentsForErrorDialog; - fragment.executionScope = executionScope; - } - } - - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - public static class HoneycombManagerFragment extends android.app.Fragment { - protected boolean finishAfterDialog; - protected Bundle argumentsForErrorDialog; - private EventBus eventBus; - private Object executionScope; - - @Override - public void onResume() { - super.onResume(); - eventBus = ErrorDialogManager.factory.config.getEventBus(); - eventBus.register(this); - } - - @Override - public void onPause() { - eventBus.unregister(this); - super.onPause(); - } - - public void onEventMainThread(ThrowableFailureEvent event) { - if (!isInExecutionScope(executionScope, event)) { - return; - } - checkLogException(event); - - // Execute pending commits before finding to avoid multiple error fragments being shown - android.app.FragmentManager fm = getFragmentManager(); - fm.executePendingTransactions(); - - android.app.DialogFragment existingFragment = (android.app.DialogFragment) fm - .findFragmentByTag(TAG_ERROR_DIALOG); - if (existingFragment != null) { - // Just show the latest error - existingFragment.dismiss(); - } - - android.app.DialogFragment errorFragment = (android.app.DialogFragment) factory.prepareErrorFragment(event, - finishAfterDialog, argumentsForErrorDialog); - if (errorFragment != null) { - errorFragment.show(fm, TAG_ERROR_DIALOG); - } - } - - public static void attachTo(Activity activity, Object executionScope, boolean finishAfterDialog, Bundle argumentsForErrorDialog) { - android.app.FragmentManager fm = activity.getFragmentManager(); - HoneycombManagerFragment fragment = (HoneycombManagerFragment) fm - .findFragmentByTag(TAG_ERROR_DIALOG_MANAGER); - if (fragment == null) { - fragment = new HoneycombManagerFragment(); - fm.beginTransaction().add(fragment, TAG_ERROR_DIALOG_MANAGER).commit(); - fm.executePendingTransactions(); - } - fragment.finishAfterDialog = finishAfterDialog; - fragment.argumentsForErrorDialog = argumentsForErrorDialog; - fragment.executionScope = executionScope; - } - } - - /** Must be set by the application. */ - public static ErrorDialogFragmentFactory factory; - - protected static final String TAG_ERROR_DIALOG = "de.greenrobot.eventbus.error_dialog"; - protected static final String TAG_ERROR_DIALOG_MANAGER = "de.greenrobot.eventbus.error_dialog_manager"; - - public static final String KEY_TITLE = "de.greenrobot.eventbus.errordialog.title"; - public static final String KEY_MESSAGE = "de.greenrobot.eventbus.errordialog.message"; - public static final String KEY_FINISH_AFTER_DIALOG = "de.greenrobot.eventbus.errordialog.finish_after_dialog"; - public static final String KEY_ICON_ID = "de.greenrobot.eventbus.errordialog.icon_id"; - public static final String KEY_EVENT_TYPE_ON_CLOSE = "de.greenrobot.eventbus.errordialog.event_type_on_close"; - - /** Scope is limited to the activity's class. */ - public static void attachTo(Activity activity) { - attachTo(activity, false, null); - } - - /** Scope is limited to the activity's class. */ - public static void attachTo(Activity activity, boolean finishAfterDialog) { - attachTo(activity, finishAfterDialog, null); - } - - /** Scope is limited to the activity's class. */ - public static void attachTo(Activity activity, boolean finishAfterDialog, Bundle argumentsForErrorDialog) { - Object executionScope = activity.getClass(); - attachTo(activity, executionScope, finishAfterDialog, argumentsForErrorDialog); - } - - public static void attachTo(Activity activity, Object executionScope, boolean finishAfterDialog, Bundle argumentsForErrorDialog) { - if (factory == null) { - throw new RuntimeException("You must set the static factory field to configure error dialogs for your app."); - } - if (isSupportActivity(activity)) { - SupportManagerFragment.attachTo(activity, executionScope, finishAfterDialog, argumentsForErrorDialog); - } else { - HoneycombManagerFragment.attachTo(activity, executionScope, finishAfterDialog, argumentsForErrorDialog); - } - } - - private static boolean isSupportActivity(Activity activity) { - boolean isSupport = false; - for (Class c = activity.getClass().getSuperclass();; c = c.getSuperclass()) { - if (c == null) { - throw new RuntimeException("Illegal activity type: " + activity.getClass()); - } - String name = c.getName(); - if (name.equals("android.support.v4.app.FragmentActivity")) { - isSupport = true; - break; - } else if (name.startsWith("com.actionbarsherlock.app") - && (name.endsWith(".SherlockActivity") || name.endsWith(".SherlockListActivity") || name - .endsWith(".SherlockPreferenceActivity"))) { - throw new RuntimeException("Please use SherlockFragmentActivity. Illegal activity: " + name); - } else if (name.equals("android.app.Activity")) { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { - throw new RuntimeException( - "Illegal activity without fragment support. Either use Android 3.0+ or android.support.v4.app.FragmentActivity."); - } - break; - } - } - return isSupport; - } - - protected static void checkLogException(ThrowableFailureEvent event) { - if (factory.config.logExceptions) { - String tag = factory.config.tagForLoggingExceptions; - if (tag == null) { - tag = EventBus.TAG; - } - Log.i(tag, "Error dialog manager received exception", event.throwable); - } - } - - private static boolean isInExecutionScope(Object executionScope, ThrowableFailureEvent event) { - if (event != null) { - Object eventExecutionScope = event.getExecutionScope(); - if (eventExecutionScope != null && !eventExecutionScope.equals(executionScope)) { - // Event not in our scope, do nothing - return false; - } - } - return true; - } - -} diff --git a/EventBus/src/org/greenrobot/eventbus/util/ExceptionToResourceMapping.java b/EventBus/src/org/greenrobot/eventbus/util/ExceptionToResourceMapping.java deleted file mode 100644 index a3bb67f3..00000000 --- a/EventBus/src/org/greenrobot/eventbus/util/ExceptionToResourceMapping.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (C) 2012-2016 Markus Junginger, greenrobot (http://greenrobot.org) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.greenrobot.eventbus.util; - -import android.util.Log; - -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - - -/** - * Maps throwables to texts for error dialogs. Use Config to configure the mapping. - * - * @author Markus - */ -public class ExceptionToResourceMapping { - - public final Map, Integer> throwableToMsgIdMap; - - public ExceptionToResourceMapping() { - throwableToMsgIdMap = new HashMap<>(); - } - - /** Looks at the exception and its causes trying to find an ID. */ - public Integer mapThrowable(final Throwable throwable) { - Throwable throwableToCheck = throwable; - int depthToGo = 20; - - while (true) { - Integer resId = mapThrowableFlat(throwableToCheck); - if (resId != null) { - return resId; - } else { - throwableToCheck = throwableToCheck.getCause(); - depthToGo--; - if (depthToGo <= 0 || throwableToCheck == throwable || throwableToCheck == null) { - Log.d("EventBus", "No specific message resource ID found for " + throwable); - // return config.defaultErrorMsgId; - return null; - } - } - } - - } - - /** Mapping without checking the cause (done in mapThrowable). */ - protected Integer mapThrowableFlat(Throwable throwable) { - Class throwableClass = throwable.getClass(); - Integer resId = throwableToMsgIdMap.get(throwableClass); - if (resId == null) { - Class closestClass = null; - Set, Integer>> mappings = throwableToMsgIdMap.entrySet(); - for (Entry, Integer> mapping : mappings) { - Class candidate = mapping.getKey(); - if (candidate.isAssignableFrom(throwableClass)) { - if (closestClass == null || closestClass.isAssignableFrom(candidate)) { - closestClass = candidate; - resId = mapping.getValue(); - } - } - } - - } - return resId; - } - - public ExceptionToResourceMapping addMapping(Class clazz, int msgId) { - throwableToMsgIdMap.put(clazz, msgId); - return this; - } - -}