what is the use of MemoryFile in android - java

I want to write some bytes to a shared memory. This is done in my application1. From my another application: application2 I want to access that shared memory to read the written bytes. For this purpose I tried using android's MemoryFile class. I am stuck as how to refer to the same shard memory between two different application. I am also now confused if memoryFile is used for the same purpose or not.
http://developer.android.com/reference/android/os/MemoryFile.html this link I found regarding the topic.
Thanks in advance.
Krishna

If you want some cross-process use with MemoryFile you can use the following fugly method:
import android.os.MemoryFile;
import android.os.ParcelFileDescriptor;
import java.io.FileDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MemoryFileUtil {
private static final Method sMethodGetParcelFileDescriptor;
private static final Method sMethodGetFileDescriptor;
static {
sMethodGetParcelFileDescriptor = get("getParcelFileDescriptor");
sMethodGetFileDescriptor = get("getFileDescriptor");
}
public static ParcelFileDescriptor getParcelFileDescriptor(MemoryFile file) {
try {
return (ParcelFileDescriptor) sMethodGetParcelFileDescriptor.invoke(file);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
public static FileDescriptor getFileDescriptor(MemoryFile file) {
try {
return (FileDescriptor) sMethodGetFileDescriptor.invoke(file);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private static Method get(String name) {
try {
return MemoryFile.class.getDeclaredMethod(name);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
}
What you should be looking at is the #getParcelFileDescriptor(MemoryFile) method which you can return from an implementation of ContentProvider#openFile(Uri, String).

I suspect memory files don't have the getParcelFileDescriptor method. When I commented this getParcelFileDescriptor related methods and use getFileDescriptor. It worked nicely.
import java.io.FileDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.os.MemoryFile;
/**
* Invoke hidden methods using reflection
*
*/
public class MemoryFileUtil {
private static final Method sMethodGetFileDescriptor;
static {
sMethodGetFileDescriptor = get("getFileDescriptor");
}
public static FileDescriptor getFileDescriptor(MemoryFile file) {
try {
return (FileDescriptor) sMethodGetFileDescriptor.invoke(file);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private static Method get(String name) {
try {
return MemoryFile.class.getDeclaredMethod(name);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
}
And created File descriptor from memory file.
FileDescriptor fd = MemoryFileUtil.getFileDescriptor(memFile);

MemoryFile can be used to map to physical memory. The result file descriptor (fd) can be passed to client (memory sharing side). The client can map the same native fd to the same memory region. The memory can then be shared using the native fd, which can be mapped to java layer using InputStream.
Please refer to this link for more details:
Sharing memory using ashem.

Related

Minecraft Fabric Modding, how to get access to private field with help mixin Accessor

i have a problem with Accessor in mixins.
I want to get a private field from the MultiplayerScreen class, for this I use an Accessor, but something is going wrong.
Accessor:
package ru.flexice.mixin;
import net.minecraft.client.gui.screen.multiplayer.MultiplayerScreen;
import net.minecraft.client.network.ServerInfo;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
#Mixin(MultiplayerScreen.class)
public interface MultiplayerScreenAccessor {
#Accessor
ServerInfo getSelectedEntry();
}
Inject to Code
#Inject(at = #At("RETURN"), method = "select")
private void select(CallbackInfo callbackInfo) {
try {
Screen s = MinecraftClient.getInstance().currentScreen;
if (s != null) {
System.out.println(((MultiplayerScreenAccessor) s).getSelectedEntry().address);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
and i just get
Mixin transformation of ru.flexice.mixin.MultiplayerScreenAccessor failed
Use a #Shadow
#Shadow
private ServerInfo selectedEntry;
#Inject(at = #At("TAIL"), method = "select")
public void select(CallbackInfo callbackInfo) {
try {
System.out.println(this.selectedEntry.address);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}

Function Overloading with Subclass Parameters in Java [duplicate]

This question already has answers here:
Overloaded method selection based on the parameter's real type
(7 answers)
Closed 3 years ago.
I have a class that extends another class (In this case, it's an Exception):
public class NewTypeException extends Exception {
private String exceptionField;
public String getExceptionField() {
return exceptionField;
}
public void setExceptionField(String exceptionField) {
this.exceptionField = exceptionField;
}
public NewTypeException(String cause, String reason) {
super(cause);
exceptionField = reason;
}
}
And another class (for sake of example, lets call this PrintUtil) that has two methods with similar signatures, the only difference being the Exception type changes to the subclass:
void doStuff(Exception ex) {
System.out.println(ex.getMessage());
}
void doStuff(NewTypeException ex) {
System.out.println("New Type Exception");
System.out.println(ex.getExceptionField());
System.out.println(ex.getMessage());
}
In a lot of places in my code, I have a bunch of
try {
// code
} catch (Exception ex) {
printUtil.doStuff(ex);
}
After adding this new exception type, I want to have this line call the most specific method it can, depending on the argument. However, it seems when I test this, this will only use the method for Exception even if the runtime type fits another method (e.g. NewTypeException). Is there any way to do this other than replace hundreds of sections of
try {
// code
} catch (Exception ex) {
printUtil.doStuff(ex);
}
with
try {
// code
} catch (NewTypeException ex) {
printUtil.doStuff(ex);
} catch (Exception ex) {
printUtil.doStuff(ex);
}
? This seems like something really basic a OOP language should be able to do...
Not possible the way you're doing it. Method calls check the parameters arguments at compile time taking into account the declared types.
You may move the exception handling code somewhere else, but either you would need to instanceof or catch specific exceptions:
try {
// code
} catch (Exception ex) {
printUtil.handleExceptions(ex);
}
With utility class:
class PrintUtil {
public static handleExceptions(Exception e) {
try {
throw e;
} catch (NewTypeException ex) {
doStuff(ex);
} catch (AnotherTypeException ex) {
doStuff(ex);
}
}
...
}

Java RMI causes "NoSuchObjectException" [duplicate]

This question already has answers here:
java.rmi.NoSuchObjectException: no such object in table
(7 answers)
Closed 7 years ago.
I have a problem with JAVA RMI.
I have a java ee application running, which uses rmi to call specific methods, which have to be implemented specificly for each customer.
The vendor gave me an example RMI interface implementation to show how to get a specific hostinterface running.
The original codefragment looked like posted example1.
The Interface is running but every 2 to 3 days it stops working, without any known reason. The interfaces' log looks like it would be still running.
The glassfish server, which calls the interface, shows log entries like this:
[#|2015-10-01T16:27:53.446+0200|SEVERE|glassfish3.1.2|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=106;_ThreadName=Thread-2;|egatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
...
The application error log shows entries like this:
2015-10-05 08:44:07,819 [http-thread-pool-8080(4)] ERROR medexter.arden.server.engine.DelegatingHostInterface - The method evaluateRead on remote interface does not work correctly.
java.rmi.NoSuchObjectException: no such object in table
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(Unknown Source)
...
I found several threads like this one:
java.rmi.NoSuchObjectException: no such object in table
which tells me the garbage-collection could be responsible and the registry has to be kept statically to prevent the GC from destroying the object.
Meanwhile I tried out diffrent ways. My last one (which somehow shows my desparation - restarting the interface every 24h should not be the golden solution) is posted in example2.
At the moment I generate an executable jar file and start it as an application. I wanted to get it running as a service later on, but first it should work without any mistakes.
Does anybody hava an idea, what the reason for the described behaviour could be?
Any imporovement of the given code apprechiated. I just want to get this stuff working, without loosing connection every few days.
Thank you very much,
Martin
Example 1:
import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class SampleRMIProvider {
private static RmiRegistryThread thr;
public static void main(String[] args) {
SampleRMIProvider prv = new SampleRMIProvider();
prv.init();
}
public void init(){
SampleRMIProvider.thr = new RmiRegistryThread();
thr.start();
}
public class RmiRegistryThread extends Thread {
public boolean run = true;
#Override
public void run() {
System.err.println("thread start");
String name = "RMIHostInterface";
int servicePorti = Integer.parseInt("18989");
try {
RmiHostInterface engine = new RmiHostInterfaceImpl();
RmiHostInterface stub = (RmiHostInterface) UnicastRemoteObject.exportObject(engine, 0);
Registry registry;
try {
registry = LocateRegistry.createRegistry(servicePorti);
} catch (RemoteException e) {
registry = LocateRegistry.getRegistry(servicePorti);
}
registry.bind(name, stub);
} catch (RemoteException e) {
e.printStackTrace();
} catch (AlreadyBoundException e) {
e.printStackTrace();
}
try {
while (this.run) {
Thread.sleep(10000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Example 2:
import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class SampleRMIProvider extends Thread{
private static Registry r = null;
#Override
public void run() {
String name = "RMIHostInterface";
int servicePorti = Integer.parseInt("20002"); //18989
try {
RmiHostInterface engine = new SampleInterfaceImpl();
RmiHostInterface stub = (RmiHostInterface) UnicastRemoteObject.exportObject(engine, 0);
try {
SampleRMIProvider.r = LocateRegistry.createRegistry(servicePorti);
} catch (RemoteException e) {
SampleRMIProvider.r = LocateRegistry.getRegistry(servicePorti);
}
SampleRMIProvider.r.bind(name, stub);
} catch (RemoteException e) {
e.printStackTrace();
} catch (AlreadyBoundException e) {
e.printStackTrace();
}
System.err.println("RMI Interface created...");
try{
while(true){
Thread.sleep(10000);
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
while (true) {
//RMI Interface instanzieren
SampleRMIProvider provider = new SampleRMIProvider();
provider.start();
//Ein Tag pause
Thread.sleep(86400000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
14.10.2015
Finally - this minimal example shows a solution that worked for me. Thanks for the useful advices.
import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class SampleRMIProvider{
private static Registry r = null;
private static SampleHostInterfaceImpl hif = null;
private static RmiHostInterface stub = null;
SampleRMIProvider(){
try{
SampleRMIProvider.r.bind("RMIHostInterface", SampleRMIProvider.stub);
}
catch(RemoteException | AlreadyBoundException e){
e.printStackTrace();
}
}
public static void main(String[] args) {
//setup static references to prevent from beeing collected by GC
try {
SampleRMIProvider.hif = new SampleHostInterfaceImpl();
SampleRMIProvider.stub = (RmiHostInterface) UnicastRemoteObject.exportObject(SampleRMIProvider.hif, 0);
try {
SampleRMIProvider.r = LocateRegistry.createRegistry(20002);
} catch (RemoteException e) {
SampleRMIProvider.r = LocateRegistry.getRegistry(20002);
}
} catch (RemoteException e) {
e.printStackTrace();
}
new SampleRMIProvider();
}
}
I don't know what you mean by 'no known cause', when the cause is documented in the Javadoc of the exception.
You say that you've read that the Registry reference must be static, yet you don't have a static Registry reference anywhere.
Try implementing that.

DRY for Exception Wrapping

I'm working on some server-side code that wraps all exceptions before passing them to the client side, due to this all client facing methods have the following code
try{
DoSomething();
} catch (ExceptionA e) {
throw new CustomException(AType, e);
} catch (ExceptionB e) {
throw new CustomException(BType, e);
} catch (Exception e) {
throw new CustomException(Unexpected, e);
}
to have this repeated in every method seems to violate the DRY principle and I was wondering what the best way to refactor it would be. For instance I was thinking a wrapper method such as:
private void wrapException(Exception e) {
if (e instanceof ExceptionA) {
throw new CustomException(AType, e);
}
etc...
Take a look at AspectJ soften exception.
Also look at Guava's Throwables.
There is also Lamboks sneaky exception.
The other option is to use Anonymous object instances aka closures.
public abstract class Wrapper {
public void execute() {
try {
// do some boiler plate before
this.wrap();
// do some boiler plate after.
} catch (ExceptionA | ExceptionB ex) {
Type t = determineType(ex);
throw new CustomException(t, ex);
}
}
public void abstract wrap();
}
Now in your code you do something like:
new Wrapper() {
public void wrap() {
DoSomething();
}
}.execute()
This is possible in Java7 and up:
http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html
Copy-paste example from above doc:
catch (IOException|SQLException ex) {
logger.log(ex);
throw ex;
}
This is one way to go about it:
Exception caughtEx = null;
String extraInfo = null;
try{
DoSomething();
} catch (ExceptionA e) {
caughtEx = e;
extraInfo = AType;
} catch (ExceptionB e) {
caughtEx = e;
extraInfo = BType;
} catch (Exception e) { // catching Exception is usually a bad idea, just let it bubble up without catching...
caughtEx = e;
extraInfo = Unexpected;
}
if (caughtEx != null) throw new CustomException(extraInfo, caughtEx);

Java Generic Method to Instantiate any Class with any Constructor using Reflection

As we know Java uses erasure, so any Generic class cannot do
T t = new T();
So I was trying out Java reflection to have a class with Static methods, to instantiate any Class with any Constructor. Here is the code.
import java.lang.reflect.*;
public class GenericNewInstance {
public static <T> T createInstance(Class<T> cObj) {
try {
return cObj.newInstance();
} catch (InstantiationException e) {
System.out.println("Instantiation Exception");
return null;
} catch (IllegalAccessException e) {
System.out.println("Illegal Access Exception");
return null;
}
}
public static <T> T createInstanceUsingRelection(Class<T> c, Object... initArgs) {
Constructor<T> cTor = null;
Class<?>[] cObjs = new Class<?>[initArgs.length];
int i = 0;
for(Object o : initArgs) {
cObjs[i++] = o.getClass();
}
try {
cTor = c.getConstructor(cObjs);
} catch (SecurityException e) {
System.out.println("security exception. Cannot get Constructor");
return null;
} catch (NoSuchMethodException e) {
System.out.println("NoSuchMethodException Cannot get constructor");
return null;
}
try {
return cTor.newInstance(initArgs);
} catch (IllegalArgumentException e) {
System.out.println("Illegal Argument Exception");
return null;
} catch (InstantiationException e) {
System.out.println("Instantiation Exception");
return null;
} catch (IllegalAccessException e) {
System.out.println("Illegal Access Exception");
return null;
} catch (InvocationTargetException e) {
System.out.println("Invocation Target Exception");
return null;
}
}
}
Example for using this.
Integer i = GenericNewInstance.createInstanceUsingRelection(Integer.class, "0");
So my questions:
Is this the right way to implement it? (or is it verbose?)
What are the typical use cases of doing this?
Can/Should we avoid using Reflection while using Generics?
Your code will fail at c.getConstructor(cObjs) since this doesn't take into account the type hierarchy. If any argument is a subtype of the constructor's declared param type, this call will not return it. You'll need quite a lot more type juggling to get it working. I advise you to take a look at the code that already solves this problem. Perhaps you can even use that library as-is, your choice. It's the implementation code for Clojure, a JVM-based dynamic language that needs exactly this stuff. The library is available from the Maven central repo.
BTW Your exception handling is redundant. Either just declare throws Exception or catch any Exception and wrap it in a RuntimeException. When something fails, the original exception is the best diagnostic.

Categories

Resources