I am 100% new to Java and I'm trying to add Crashlytics to my React Native project. The only code snippet I could find on the internet is retrolambda syntax.
I realize I could add that particular "library" or whatever, so it works, but considering it's the only place used in my project I'd rather just convert it to the 'older format' rather than adding a library just to do one function.
public final class AppReactPackage implements ReactPackage {
#Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
addExceptionHandler(reactContext);
}
private void addExceptionHandler(ReactApplicationContext reactContext) {
// Fyi, this is using Retrolambda for Java 8 syntax
reactContext.setNativeModuleCallExceptionHandler(e -> {
if (e instanceof JavascriptException) {
Crashlytics.log(e.getMessage());
} else {
Crashlytics.logException(e);
}
});
}
}
Searching your syntax I found these two links:
React
NativeModuleCallExceptionHandler
By using those, it should look something like this: (untested)
private void addExceptionHandler(ReactApplicationContext reactContext) {
reactContext.setNativeModuleCallExceptionHandler(new NativeModuleCallExceptionHandler() {
#Override
public void onHandleException(Exception e) {
if (e instanceof JavascriptException) {
Crashlytics.log(e.getMessage());
} else {
Crashlytics.logException(e);
}
}
});
}
Related
I'm trying to write a generic code. Here is my scenario.
class AEvent {
public void onAEventCreate( A event){
//do something
}
}
class BEvent {
public void onBEventCreate (B event) {
//do something
}
}
I want to have some generic class which could do the operation of method onAEventCreate and onBEventCreate on one single method. Now the catch is I do not want to change the classes AEvent and BEvent . Is there a way I can listen to the two methods? or is there some kind of design pattern maybe like observer which can help me achieve this.
There are a lot of ways to do this, if you want to use the Observe Pattern an example would be :
You create an ObserverEvent class
class EventObserver {
private AEvent aEvent;
private BEvent bEvent;
public EventObserver(AEvent aEvent, BEvent bEvent) {
this.aEvent = aEvent;
this.bEvent = bEvent;
aEvent.setObserver(this);
bEvent.setObserver(this);
}
public void onEventCreated() {
if (aEvent.isAEventCreated && bEvent.isBEventCreated) {
onBothEventsCreated();
}
}
public void onBothEventsCreated() {
//this method will be called when both events are created
}
}
Then you need to adapt your classes to this :
class BEvent {
private boolean isBEventCreated = false;
private EventObserver observer;
public void setObserver(EventObserver observer) {
this.observer = observer;
}
public void onBEventCreated() {
this.isBEventCreated = true;
observer.onEventCreated();
}
}
And the same with AEvent.
I'm building a GUI application in Java using an application framework (Netbeans Platform) which requires a large amount of nearly identical classes to implement extremely similar Action classes. I've spent a lot of time attempting to generate these actions programmatically. Although I'm able to generate the Actions, the framework utilizes annotations during compile time to generate other internal cache/data files which I've been unable to reproduce using a programmatic approach.
I'm wondering if code generation tools are a better solution, or perhaps some custom annotations which wrap the framework annotations. Perhaps something like Lombok, or maybe a maven plugin. But don't know where to start and am not sure if this is even a good path to explore. Ideally, I think it would be great to define the actions in a data file and generate the java code at compile time.
The project is open source, and a number of other actions are on github. Here is an example of what the template might look like, the pieces I would need to inject replaced with {{string}}, {{code}} and {{int}}:
// imports omitted
#ActionID(
category = {{string}},
id = {{string}})
#ActionRegistration(
iconBase = {{string}},
displayName = "resources.MessagesBundle#" + {{string}},
lazy = false)
#ActionReferences({
#ActionReference(
path = {{string}},
position = {{int}})
})
public final class {{string}} extends AbstractAction implements UGSEventListener {
public static final String ICON_BASE = {{string}};
private BackendAPI backend;
public SoftResetAction() {
this.backend = CentralLookup.getDefault().lookup(BackendAPI.class);
this.backend.addUGSEventListener(this);
putValue("iconBase", ICON_BASE);
putValue(SMALL_ICON, ImageUtilities.loadImageIcon(ICON_BASE, false));
putValue("menuText", {{string}});
putValue(NAME, {{string}});
}
#Override
public void UGSEvent(UGSEvent cse) {
java.awt.EventQueue.invokeLater(() -> setEnabled(isEnabled()));
}
#Override
public boolean isEnabled() {
{{code}}
}
#Override
public void actionPerformed(ActionEvent e) {
{{code}}
}
}
You should try a code generator like Telosys ( http://www.telosys.org/ )
This tool is designed for this kind of situation, you just have to create a template for each type of repetitive class and launch the generation.
For more information see the templating principles : http://www.telosys.org/templates.html
Everything is free and open source, so you can reuse existing templates and adapt them according to your needs.
Some interresting posts about this tool :
https://modeling-languages.com/telosys-tools-the-concept-of-lightweight-model-for-code-generation/
https://dzone.com/articles/telosys-a-code-generation-tool-by-laurent-guerin
You can design a public Action class for common using just like blow. This is only a section of sample code. If some modules has its own biz logical, you can implements this PubAction to any subclass.
import java.awt.event.ActionEvent;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.swing.AbstractAction;
public abstract class PubAction
extends AbstractAction
implements AppEventListener
{
protected ActionInterceptor interceptor;
protected IExceptionHandler exceptionHandler;
protected IActionStatusJudge actionStatusJudge = null;
public static final String TOOLBAR_SHOWNAME_KEY = "TOOLBAR_SHOWNAME_KEY";
public PubAction()
{
setShowNameInToolbar(false);
}
public String getBtnName() {
return (String)getValue("Name");
}
public void setBtnName(String btnName) {
putValue("Name", btnName);
}
public void setCode(String code)
{
putValue("Code", code);
}
public void handleEvent(AppEvent event)
{
updateStatus();
}
public void updateStatus()
{
boolean isEnable = isActionEnable();
setEnabled(getActionStatusJudge() == null ? isEnable : getActionStatusJudge().isActionEnable(this, isEnable));
}
protected boolean isActionEnable() {
return true;
}
public void setShowNameInToolbar(boolean isShow)
{
putValue("TOOLBAR_SHOWNAME_KEY", isShow ? Boolean.TRUE : Boolean.FALSE);
}
public void actionPerformed(ActionEvent e) {
Logger.debug("Entering " + getClass().toString() + ".actionPerformed");
beforeDoAction();
try
{
if ((interceptor == null) || (interceptor.beforeDoAction(this, e)))
{
try
{
doAction(e);
if (interceptor != null) {
interceptor.afterDoActionSuccessed(this, e);
}
} catch (Exception ex) {
if ((interceptor == null) || (interceptor.afterDoActionFailed(this, e, ex)))
{
if (getExceptionHandler() != null)
{
processExceptionHandler(ex);
}
else if ((ex instanceof RuntimeException))
{
throw ((RuntimeException)ex);
}
throw new RuntimeException(ex);
}
}
}
}
finally
{
Logger.debug("Leaving " + getClass().toString() + ".actionPerformed");
}
}
protected void processExceptionHandler(Exception ex)
{
new ExceptionHandlerUtil().processErrorMsg4SpecialAction(this, getExceptionHandler(), ex);
}
protected void beforeDoAction()
{
Method[] ms = getClass().getMethods();
for (Method m : ms)
{
Class<?> clazz = m.getReturnType();
if (AbstractUIAppModel.class.isAssignableFrom(clazz)) {
try
{
AbstractUIAppModel model = (AbstractUIAppModel)m.invoke(this, null);
if (model == null)
return;
LoginContext ctx = model.getContext();
if (ctx == null)
break;
ShowStatusBarMsgUtil.showStatusBarMsg("", ctx);
} catch (IllegalArgumentException e) {
Logger.debug(e.getMessage());
} catch (IllegalAccessException e) {
Logger.debug(e.getMessage());
} catch (InvocationTargetException e) {
Logger.debug(e.getMessage());
}
}
}
}
public abstract void doAction(ActionEvent paramActionEvent) throws Exception;
public ActionInterceptor getInterceptor()
{
return interceptor;
}
public void setInterceptor(ActionInterceptor interceptor) {
this.interceptor = interceptor;
}
public IExceptionHandler getExceptionHandler() {
return exceptionHandler;
}
public void setExceptionHandler(IExceptionHandler exceptionHandler) {
this.exceptionHandler = exceptionHandler;
}
public IActionStatusJudge getActionStatusJudge() {
return actionStatusJudge;
}
public void setActionStatusJudge(IActionStatusJudge actionStatusJudge) {
this.actionStatusJudge = actionStatusJudge;
}
}
For some reason I need to rewrite groovy code to java. It's gradle plugin if it matters. But I don't understand some code. Could you please explain it step-by-step, probably with java code?
class DeployPlugin implements Plugin<Project> {
#Override
void apply(Project project) {
project.with {
apply plugin: 'org.hidetake.ssh'
ssh.settings {
identity = file(ssh_file)
knownHosts = allowAnyHosts
passphrase = ssh_passphrase
}
...
As far as I understand project.with{ } means methods (which?) inside are called for project instance.
apply plugin: 'org.hidetake.ssh' - can it be expressed with project.getPlugins() .apply("org.hidetake.ssh") ?
ssh.settings - what is ssh here? If it is a variable, how can I get it's instance in java?
ssh.settings {someExpressions} - what are curly braces used for in this context?
The code will probably look something like this in Java:
public class DeployPlugin implements Plugin<Project> {
#Override
public void apply(Project project) {
project.getPlugins().apply("org.hidetake.ssh");
org.hidetake.groovy.ssh.core.Service ssh = project.getExtensions().getByType(org.hidetake.groovy.ssh.core.Service.class);
ssh.settings(new MethodClosure(this, "configureSettingsClosure"));
}
private void configureSettingsClosure(org.hidetake.groovy.ssh.core.settings.GlobalSettings settings) {
settings.setIdentity(ssh_file);
settings.setKnownHosts(settings.getAllowAnyHosts());
settings.setPassphrase("p#ssw0rd");
}
or if you want to not depend on groovy-ssh probably something like this, but I'd not recommend it:
public class DeployPlugin implements Plugin<Project> {
#Override
public void apply(Project project) {
project.getPlugins().apply("org.hidetake.ssh");
Object ssh = project.getExtensions().getByName("ssh");
try {
Method settings = ssh.getClass().getDeclaredMethod("settings", Closure.class);
settings.invoke(ssh, new MethodClosure(this, "configureSettingsClosure"));
} catch (IllegalAccessException | NoSuchMethodException e) {
throw new AssertionError("Should not happen except by using a different groovy-ssh version that changed incompatibly", e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private void configureSettingsClosure(Object settings) throws InvocationTargetException {
try {
Method setIdentity = settings.getClass().getDeclaredMethod("setIdentity", Object.class);
setIdentity.invoke(settings, ssh_file);
Method getAllowAnyHosts = settings.getClass().getDeclaredMethod("getAllowAnyHosts");
Method setKnownHosts = settings.getClass().getDeclaredMethod("setKnownHosts", File.class);
setKnownHosts.invoke(settings, getAllowAnyHosts.invoke(settings));
Method setPassphrase = settings.getClass().getDeclaredMethod("setPassphrase", String.class);
setPassphrase.invoke(settings, "p#ssw0rd");
} catch (NoSuchMethodException | IllegalAccessException e) {
throw new AssertionError("Should not happen except by using a different groovy-ssh version that changed incompatibly", e);
}
}
I created an Android Binding Library for my Xamarin project, using an AAR.
I am now trying to implement that library.
Here is the java snippet of code using the library:
The java code:
new AsyncOperation.CompletionHandler<RouteManager>(){
#Override
public void success(RouteManager result){
result.subscribe(ACCEL_DATA, new RouteManager.MessageHandler(){
#Override
public void process(Message message){
Log.i(LOG_TAG,message)
}
}
}
I am trying to port this code to C#.
My C# code, from C# wrapper created from binding library:
class AsyncOperationHandler : AsyncOperationCompletionHandler
{
public override unsafe void Success(Object p0)
{
try
{
var routeManger = (IRouteManager)p0;
routeManger.Subscribe(ACCEL_DATA, new RouteMessageHandler());
}
catch (Exception)
{
Log.Error(LOG_TAG, "Error");
}
}
}
class RouteMessageHandler : IRouteManagerMessageHandler
{
public void Dispose()
{
throw new NotImplementedException();
}
public IntPtr Handle { get; }
public void Process(Message p0)
{
var message = p0;
Log.Info(LOG_TAG, message);
}
}
I am getting an error in the C# wrapper on the routeManger.Subscribe line.
When the RouteManagerMessageHandler gets initialized, it gets the Handle, then throws a null pointer exception inside the Binding Library.
Is this the correct way to port a Java Interface to C#?
If you implement a Java Interface, you have to derive from Java.Lang.Object.
class RouteMessageHandler : Java.Lang.Object, IRouteManagerMessageHandler
{
public void Process(Message p0)
{
var message = p0;
Log.Info(LOG_TAG, message);
}
}
There should be something on the compile output.
Type 'AppXYZ.RouteMessageHandler' implements IRouteManagerMessageHandler but does not inherit from Java.Lang.Object. It is not supported.
My application have several execution modes, and in 1 mode it is normal that some of my tests will throw a concrete exception. I need to annotate this methods with something like #SkipOnFail that will set method as skipped if exception was thrown.
thanks in advance!
#Edit(for my question to be more clear)
#Test(expected=ConcreteException.class)
does not work for me because i need my tests to pass even if ConcreteException.class was not thrown(expected tag in junit will mark my test as failed if this exception won't be thrown), and to be skipped otherwise. In all other cases it should work as always.
#Solution that worked for me(junit v4.7) thx to #axtavt
#Rule
public MethodRule skipRule = new MethodRule() {
public Statement apply(final Statement base, FrameworkMethod method, Object target) {
if(method.getAnnotation(SkipOnFail.class) == null) return base;
return new Statement() {
#Override
public void evaluate() throws Throwable {
try{
base.evaluate();
} catch (ConcreteException e) {
Assume.assumeTrue(false);
}
}
};
}
};
#Thx
I don't think that such a feature is available out of the box, but it should be pretty easy to implement with custom TestRule and Assume, something like this:
#Rule
public TestRule skipRule = new TestRule() {
public Statement apply(final Statement base, Description desc) {
if (desc.getAnnotation(SkipOnFail.class) == null) return base;
return new Statement() {
public void evaluate() throws Throwable {
try {
base.evaluate();
} catch (MyExceptoion ex) {
Assume.assumeTrue(false);
}
}
};
}
};
What about using JUnit Extensions?
The following example is taken from their Tutorial.
It provides aditional annotations for Prerequisites (#Prerequisite): Ignore tests based on conditions.
The required approach would be to check this during running tests. So you can simply add a #Prerequisite(requires="") annotation.
public class TestFillDatabase {
#Prerequisite(requires = "databaseIsAvailable")
#Test public void fillData() {
// ...
}
public boolean databaseIsAvailable() {
boolean isAvailable = ...;
return isAvailable;
}
}
public class TestFillDatabase {
#Prerequisite(requires = "databaseIsAvailable")
#Test public void fillData() {
// ...
}
public boolean databaseIsAvailable() {
boolean isAvailable = ...;
return isAvailable ;
}
}
This specified methods with #Prerequisite(requires = "databaseIsAvailable") must be a public method, returning a boolean or Boolean value.
If these methods will be consolidated in helper classes, you can also specify static methods within a class to be called using #Prerequisite(requires = "databaseIsAvailable", callee="DBHelper").
public class TestFillDatabase {
#Prerequisite(requires = "databaseIsAvailable", callee="DBHelper")
#Test public void fillData() {
// ...
}
}
public class DBHelper {
public static boolean databaseIsAvailable() {
boolean isAvailable = ...;
return isAvailable ;
}
}
Also using the Assume class (since jUnit 4.4), you can use assumeNoException():
try{
base.evaluate();
} catch (ConcreteException e) {
Assume.assumeNoException("Concrete exception: skipping test", e);
}
I searched for the docs about JUnit and it appears that from version 4.9 they have introduced what they call test rules (see TestRule). You may start from this.
The ExpectedException class marked as #Rule could be of some help in order to check for exceptions thrown but not mandatory for the test to pass.
For more advanced usage I cannot say for the moment as I've just discovered it.