Rhino API - Access js method using org.mozilla.javascript.Context? - java

How can i access get method in this script:
(function( global ){
var Result;
(Result = function( val ) {
this.tpl = val || '' ;
}).prototype = {
get: function ()
{
return 'text' ;
}
};
global.Result = Result ;
} ( window ) ) ;
I tried in this way:
Create Window class and Result interface:
public interface Result{ public String get(); }
public class Window { public Result Result; }
Call js function:
public void call() {
Context context = Context.enter();
ScriptableObject scope = context.initStandardObjects();
FileReader fileReader = new FileReader("file.js");
Object window = Context.javaToJS(new Window(), scope);
scope.put("window", scope, window);
context.evaluateReader(scope, fileReader, "test", 1, null);
context.evaluateString(scope, "Result = window.Result;", "test", 2, null);
context.evaluateString(scope, "result = Result.get();", "test", 3, null);
Object result = scope.get("result", scope);
System.out.println("\n" + Context.toString(result));
context.exit();
}
but I can't get the return result from get function:

It worked for me:
public class Result extends ScriptableObject{
#Override
public String getClassName() {
// TODO Auto-generated method stub
return "Result";
}
}
public class Window extends ScriptableObject {
private Result Result;
public Result getResult() {
return Result;
}
#Override
public String getClassName() {
return "Window";
}
}
public void call() {
Context context = Context.enter();
ScriptableObject scope = context.initStandardObjects();
FileReader fileReader = new FileReader("file.js");
Window window = new Window();
scope.put("window", scope, window);
scope.put("window.Result", window.getResult());
context.evaluateReader(scope, fileReader, "test", 1, null);
context.evaluateString(scope, "Result = window.Result;", "test", 1, null);
context.evaluateString(scope, "var myResult = new Result();", "test", 1, null);
context.evaluateString(scope, "r = myResult.get();", "test", 1, null);
Object result = scope.get("r", scope);
System.out.println("\n" + Context.toString(result));
context.exit();
}

Related

How to fix API authentication problem in Kotlin Android app?

I developed an API in Laravel for reading some data with authentication. Now in my app I need to send the token in my header for API to respond. Every time i login with app, I'm getting token without problem, but i can't provide token in header and it's returning a null token response. Now every time i reopen my app everything is fine but problem appear only when i login.
Please read my code and say if you found the bug.
This is my (AppServer.kt). I use this for adding the token to my header
class AppServer private constructor(private val client: INetworkClient) : IAppServer {
private val gson = Gson()
companion object {
private var instance: AppServer? = null
fun getInstance(): AppServer {
val token = AppLoggedInUser.getInstance()?.userProfile?.userToken ?: ""
if (instance == null)
instance = AppServer(
MixedNetworkClient(
mHeaders = mutableMapOf(
Headers.CONTENT_TYPE to "application/json",
"X-Requested-With" to "XMLHttpRequest",
"Authorization" to "Bearer $token"
),
mBasePath = "https://myWebsiteURL.com/"
)
)
return instance!!
}
}
override fun getPurchasedItems(): Observable<Pair<ResponseState, List<OrderInfo>?>> {
return Observable.create<Pair<ResponseState, List<OrderInfo>?>> { emitter ->
val (items, statusCode, msg, error) =
client.get(
"api/users/${AppLoggedInUser.getInstance().userProfile.userId}/orders",
{ responseStr ->
try {
val orders = mutableListOf<OrderInfo>()
val jArray = JSONArray(responseStr)
for (i in 0 until jArray.length()) {
val jObject = jArray.getJSONObject(i)
val order =
gson.fromJson<OrderInfo>(jObject.toString(), OrderInfo::class.java)
if (order.isPaymentSuccessful)
orders.add(order)
}
if (orders.isEmpty())
emitter.onNext(pair(empty(), null))
else
emitter.onNext(pair(success(), orders))
} catch (t: Throwable) {
Timber.e(t)
emitter.onNext(pair(ResponseState.internalError(t), null))
}
})
}.attachSchedulers()
}
override fun getDiscountDetailsById(id: Int): Observable<Pair<ResponseState, DiscountDetails?>> {
return Observable.create<Pair<ResponseState, DiscountDetails?>> { emitter ->
try {
client.post("api/post", listOf("post_id" to id.toString())) { responseStr ->
val jObject = JSONObject(responseStr)
var discount: DiscountDetails? = null
if (jObject.has("ID"))
discount =
gson.fromJson<DiscountDetails>(jObject.toString(), DiscountDetails::class.java)
if (discount != null)
emitter.onNext(pair(success(), discount))
else
emitter.onNext(pair(notFound404(), null))
}
} catch (t: Throwable) {
Timber.e(t)
emitter.onNext(pair(ResponseState.internalError(t), null))
}
}.attachSchedulers()
}
}
and this is my (AppLoggedInUser.java) I use it for getting my current user token.
package com.fartaak.gilantakhfif.utilities;
import android.content.Context;
import com.fartaak.gilantakhfif.backend.server.ParsingGSON;
import com.fartaak.gilantakhfif.model.UserProfile;
public class AppLoggedInUser extends AppPreferences {
public static final String NAM_LOGIN_SdPs = "login";
public static final String KEY_USER_TOKEN = "tokenPor";
private static AppLoggedInUser mInstance;
private final String KEY_LOGIN = "prefP";
private boolean isCompletelyRegistered;
public static void init(Context context) {
if (mInstance == null) {
mInstance = new AppLoggedInUser(context);
}
}
public static AppLoggedInUser getInstance() {
if (mInstance != null) {
return mInstance;
} else {
throw new IllegalStateException(
"you should call init to initialize only once per app launch before calling getInstance");
}
}
private AppLoggedInUser(Context context) {
super(NAM_LOGIN_SdPs, context);
}
public String getUserToken() {
return getField(KEY_USER_TOKEN);
}
public void clearUserProfile() {
removeField(KEY_LOGIN);
}
public UserProfile getUserProfile() {
String data = getField(KEY_LOGIN);
if (data == null) {
return null;
}
//return new Gson().fromJson(data, UserProfile.class);
return ParsingGSON.getInstance().getParsingJSONObject(data, UserProfile.class, null);
}
public boolean isRegisterCompleted() {
if (!isCompletelyRegistered) {
UserProfile userProfile = getUserProfile();
if (userProfile.getUserName() == null) {
return false;
} else {
isCompletelyRegistered = true;
}
}
return true;
}
public boolean isUserProfile() {
return isField(KEY_LOGIN);
}
public void setUserProfile(UserProfile userProfile) {
String json = ParsingGSON.getInstance().toJSONObject(userProfile, UserProfile.class, null);
setField(KEY_LOGIN, json);
}
}
I think the problem is with my second class.

VerifyException when adding an if stmt to a method at runtime

Let's say I have a simple
class C$Manipulatables{
public Wrapper get(long v, String f){
if(v == 0){
return new Wrapper(0);
}else{
throw new RuntimeException("unacceptable: v not found");
}
}
}
I now want to redefine the get in C$Manipulatables, s.t. it reads
class C$Manipulatables{
public Wrapper get(long v, String f){
if(v == 1){ return null; }
if(v == 0){
return new Wrapper(0);
}else{
throw new RuntimeException("unacceptable: v not found");
}
}
}
This will trigger a nullpointer exception if I try to use the new value, but that's ok - for now I just want confirmation that the new code is loaded.
We add the code with ASM (I will add the full copy-pastable code at the bottom of this post, so I'm just zooming in on the relevant parts, here):
class AddingMethodVisitor extends MethodVisitor implements Opcodes{
int v;
public AddingMethodVisitor(int v, int api, MethodVisitor mv) {
super(api, mv);
this.v = v;
}
#Override
public void visitCode() {
super.visitCode();
mv.visitVarInsn(LLOAD, 1); //arg 1 of method is version number
/*if arg1 == the new version*/
mv.visitLdcInsn(v);
Label lSkip = new Label();
mv.visitInsn(LCMP);
mv.visitJumpInsn(IFNE, lSkip);
mv.visitInsn(ACONST_NULL);
mv.visitInsn(ARETURN);
/*else*/
mv.visitLabel(lSkip);
mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
}
}
and reload the class with ByteBuddy (again, full code at the bottom of the post):
ClassReader cr;
try {
/*note to self: don't forget the ``.getClassLoader()``*/
cr = new ClassReader(manipsClass.getClassLoader().getResourceAsStream( manipsClass.getName().replace('.','/') + ".class"));
}catch(IOException e){
throw new RuntimeException(e);
}
ClassWriter cw = new ClassWriter(cr, 0);
VersionAdder adder = new VersionAdder(C.latest + 1,Opcodes.ASM5,cw);
cr.accept(adder,0);
System.out.println("reloading C$Manipulatables class");
byte[] bytes = cw.toByteArray();
ClassFileLocator classFileLocator = ClassFileLocator.Simple.of(manipsClass.getName(), bytes);
new ByteBuddy()
.redefine(manipsClass,classFileLocator)
.name(manipsClass.getName())
.make()
.load(C.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent())
;
C.latest++;
System.out.println("RELOADED");
}
}
This fails.
got 0
reloading C$Manipulatables class
Exception in thread "main" java.lang.VerifyError
at sun.instrument.InstrumentationImpl.redefineClasses0(Native Method)
at sun.instrument.InstrumentationImpl.redefineClasses(InstrumentationImpl.java:170)
at net.bytebuddy.dynamic.loading.ClassReloadingStrategy$Strategy$1.apply(ClassReloadingStrategy.java:261)
at net.bytebuddy.dynamic.loading.ClassReloadingStrategy.load(ClassReloadingStrategy.java:171)
at net.bytebuddy.dynamic.TypeResolutionStrategy$Passive.initialize(TypeResolutionStrategy.java:79)
at net.bytebuddy.dynamic.DynamicType$Default$Unloaded.load(DynamicType.java:4456)
at redefineconcept.CInserter.addNext(CInserter.java:60)
at redefineconcept.CInserter.run(CInserter.java:22)
at redefineconcept.CInserter.main(CInserter.java:16)
Process finished with exit code 1
In fact, this even fails when I comment the return null stmt generation (as I have in the full code provided below).
Apparently, java just doesn't like the way I've constructed my IF, even though it's essentially the code I got when I used asmifier on
public class B {
public Object run(long version, String field){
if(version == 2) {
return null;
}
return null;
}
}
which yielded
{
mv = cw.visitMethod(ACC_PUBLIC, "run", "(JLjava/lang/String;)Ljava/lang/Object;", null, null);
mv.visitCode();
mv.visitVarInsn(LLOAD, 1);
mv.visitLdcInsn(new Long(2L));
mv.visitInsn(LCMP);
Label l0 = new Label();
mv.visitJumpInsn(IFNE, l0);
mv.visitInsn(ACONST_NULL);
mv.visitInsn(ARETURN);
mv.visitLabel(l0);
mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
mv.visitInsn(ACONST_NULL);
mv.visitInsn(ARETURN);
mv.visitMaxs(4, 4);
mv.visitEnd();
}
I simply left away everything after
mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
because after that, the already existing part of the method follows.
I really do believe that there's something about that visitFrame that java doesn't like.
Let's say I change my visitCode s.t. it reads
public void visitCode() {
super.visitCode();
mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
mv.visitLdcInsn("Work, you ..!");
mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false);
// mv.visitVarInsn(LLOAD, 1); //arg 1 of method is version number
//
// /*if arg1 == the new version*/
// mv.visitLdcInsn(v);
// Label lSkip = new Label();
//
// mv.visitInsn(LCMP);
// mv.visitJumpInsn(IFNE, lSkip);
//
//// mv.visitInsn(ACONST_NULL);
//// mv.visitInsn(ARETURN);
//
// /*else*/
// mv.visitLabel(lSkip);
// mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
}
Then the redefinition works. I get the expected exception because the code falls through to the original if-else block that cannot handle the new version number, but I do get the output, at least.
got 0
reloading C$Manipulatables class
RELOADED
Work, you ..!
Exception in thread "main" java.lang.RuntimeException: unacceptable: v not found
at redefineconcept.C$Manipulatables.get(C.java:27)
at redefineconcept.C.get(C.java:10)
at redefineconcept.CInserter.run(CInserter.java:23)
at redefineconcept.CInserter.main(CInserter.java:16)
I'd very much appreciate some help in resolving this.
What's the correct way to insert a new if stmt that java will accept?
FULL CODE
C.java
(Note that the class C$Manipulatables is necessary, because ByteBuddy cannot redefine classes that have static initialisers.)
package redefineconcept;
public class C {
public static volatile int latest = 0;
public static final C$Manipulatables manips = new C$Manipulatables();
public int get(){
int v = latest;
return manips.get(v,"").value;
}
}
class Wrapper{
int value;
public Wrapper(int value){
this.value = value;
}
}
class C$Manipulatables{
public Wrapper get(long v, String f){
if(v == 0){
return new Wrapper(0);
}else{
throw new RuntimeException("unacceptable: v not found");
}
}
}
CInserter.java
package redefineconcept;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.dynamic.ClassFileLocator;
import net.bytebuddy.dynamic.loading.ClassReloadingStrategy;
import net.bytebuddy.jar.asm.*;
import java.io.IOException;
public class CInserter {
public static void main(String[] args) {
ByteBuddyAgent.install();
new CInserter().run();
}
private void run(){
C c = new C();
System.out.println("got " + c.get());
addNext();
System.out.println("got " + c.get()); //should trigger nullptr exception
}
private void addNext(){
Object manips;
String manipsFld = "manips";
try {
manips = C.class.getDeclaredField(manipsFld).get(null);
}catch(NoSuchFieldException | IllegalAccessException e){
throw new RuntimeException(e);
}
Class<?> manipsClass = manips.getClass();
assert(manipsClass.getName().equals("redefineconcept.C$Manipulatables"));
ClassReader cr;
try {
/*note to self: don't forget the ``.getClassLoader()``*/
cr = new ClassReader(manipsClass.getClassLoader().getResourceAsStream( manipsClass.getName().replace('.','/') + ".class"));
}catch(IOException e){
throw new RuntimeException(e);
}
ClassWriter cw = new ClassWriter(cr, 0);
VersionAdder adder = new VersionAdder(C.latest + 1,Opcodes.ASM5,cw);
cr.accept(adder,0);
System.out.println("reloading C$Manipulatables class");
byte[] bytes = cw.toByteArray();
ClassFileLocator classFileLocator = ClassFileLocator.Simple.of(manipsClass.getName(), bytes);
new ByteBuddy()
.redefine(manipsClass,classFileLocator)
.name(manipsClass.getName())
.make()
.load(C.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent())
;
C.latest++;
System.out.println("RELOADED");
}
}
class VersionAdder extends ClassVisitor{
private int v;
public VersionAdder(int v, int api, ClassVisitor cv) {
super(api, cv);
this.v = v;
}
#Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);
if(mv != null && name.equals("get")){
return new AddingMethodVisitor(v,Opcodes.ASM5,mv);
}
return mv;
}
class AddingMethodVisitor extends MethodVisitor implements Opcodes{
int v;
public AddingMethodVisitor(int v, int api, MethodVisitor mv) {
super(api, mv);
this.v = v;
}
#Override
public void visitCode() {
super.visitCode();
mv.visitVarInsn(LLOAD, 1); //arg 1 of method is version number
/*if arg1 == the new version*/
mv.visitLdcInsn(v);
Label lSkip = new Label();
mv.visitInsn(LCMP);
mv.visitJumpInsn(IFNE, lSkip);
// mv.visitInsn(ACONST_NULL);
// mv.visitInsn(ARETURN);
/*else*/
mv.visitLabel(lSkip);
mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
}
}
}
One bug I noticed in your code is the following line
mv.visitLdcInsn(v);
The intent of the code is to create and load a long constant, but v has type int, so an integer constant will be created instead, thus creating a type error in the bytecode when you compare it with lcmp on the next line. visitLdcInsn will create a different constant type depending on the type of Object you pass in, so the argument needs to be the exact type you want.
On a side note, you don't need LDC in the first place to create a long constant of value 1, because there is a dedicated bytecode instruction for this, lconst_1. In ASM, this should be something like visitInsn(LCONST_1);

CLI: getOptionValue always return 'null'

public class converter {
public static void main(String [] args) {
Options opt = new Options();
opt.addOption("I", "in", false, "Eingabeformat (2,8,10,16)");
opt.addOption("O", "out", false, "Ausgabeformat (2,8,10,16)");
opt.addOption("V", "value", true, "Zu konvertierende Zahl");
CommandLineParser parser = new DefaultParser();
String value = "0";
String in = "0";
String out = "0";
int inInt = 0;
int outInt = 0;
try {
CommandLine cl = parser.parse(opt, args);
if (cl.hasOption("I")) {
in = cl.getOptionValue("I");
System.out.println(in);
} else if (cl.hasOption("in")) {
in = cl.getOptionValue("in");
inInt = Integer.parseInt(in);
}
if (cl.hasOption("O")) {
out = cl.getOptionValue("O");
outInt = Integer.parseInt(out);
} else if (cl.hasOption("out")) {
out = cl.getOptionValue("out");
outInt = Integer.parseInt(out);
}
if (cl.hasOption("V")) {
value = cl.getOptionValue("V");
} else if (cl.hasOption("value")) {
value = cl.getOptionValue("value");
}
} catch (ParseException e) {
e.printStackTrace();
}
}
Hello, for my classes I have to learn to work with CLI and it looks ok for now. My problem is: the variable 'in' always return null after using cl.getOptionValue("I") on it. Can someone help?
I assume you expect the args I, O and V to have option values, otherwise you would not try to parse them. But you only specify that for the V option by setting the third argument in the call of addOption to true. You should set them all to true if you want to specify option values:
opt.addOption("I", "in", true, "Eingabeformat (2,8,10,16)");
opt.addOption("O", "out", true, "Ausgabeformat (2,8,10,16)");
opt.addOption("V", "value", true, "Zu konvertierende Zahl");
btw you should name your class Converterwith an uppercase 'C', that's Java convention.
public class converter {
public static void main(String [] args) {
Options opt = new Options();
opt.addOption("I", "in", true, "Eingabeformat (2,8,10,16)"); // Bei false gibts spaeter null
opt.addOption("O", "out", true, "Ausgabeformat (2,8,10,16)"); // Bei false gibt spaeter null
opt.addOption("V", "value", true, "Zu konvertierende Zahl");
CommandLineParser parser = new DefaultParser();
String value = "0";
String in, out;
int inInt = 10;
int outInt = 10;
try {
CommandLine cl = parser.parse(opt, args);
if (cl.hasOption("I")) {
in = cl.getOptionValue("I");
inInt = Integer.parseInt(in);
} else if (cl.hasOption("in")) {
in = cl.getOptionValue("in");
inInt = Integer.parseInt(in);
}
if (cl.hasOption("O")) {
out = cl.getOptionValue("O");
outInt = Integer.parseInt(out);
} else if (cl.hasOption("out")) {
out = cl.getOptionValue("out");
outInt = Integer.parseInt(out);
}
if (cl.hasOption("V")) {
value = cl.getOptionValue("V");
System.out.println(convert(value, inInt, outInt));
} else if (cl.hasOption("value")) {
value = cl.getOptionValue("value");
System.out.println(convert(value, inInt, outInt));
} else {
System.out.println("Keinen Wert eingegeben. Erneut Versuchen!");
}
} catch (ParseException e) {
e.printStackTrace();
}
}
public static String convert(String input, int srcRadix, int dstRadix) {
int value = Integer.parseInt(input, srcRadix);
return Integer.toString(value, dstRadix);
}
}

Eclipse Californium CoAP wildcard as url path

I'm working on a CoAP app using Eclipse Californium that will declare explicitly only the root resource path, and the rest of the resources should be served and resolved through a wildcard /root/* just like on REST APIs or servlets.
Is there any way to achieve that ?
Ok I managed to do it.
So after a few hours of digging on their Source code here is what ended up doing.
Note that it works but it's only to show how it could be done, it's still a work on progress (I did this in 3h) as I removed some code like observer etc..
As soon as I have some time, I'll digg onto the Californium Api more and make this generic and optimized I'll create a Github project and link it here.
1 : Create a model class
public class ProxyRes {
public CoapResource coapRes;
public String path;
public ProxyRes () {
}
public CoapResource getCoapRes () {
return coapRes;
}
public void setCoapRes (CoapResource coapRes) {
this.coapRes = coapRes;
}
public String getPath () {
return path;
}
public void setPath (String path) {
this.path = path;
}
}
2 : Create an abstract CoapResource that should inject the Wildcards list
public abstract class AbstractResource extends CoapResource {
private LinkedList<String> wildcards;
protected AbstractResource (String name) {
super (name);
}
protected AbstractResource (String name, boolean visible) {
super (name, visible);
}
public LinkedList<String> getWildcards () {
return wildcards;
}
public void setWildcards (LinkedList<String> wildcards) {
this.wildcards = wildcards;
}
}
3 : Create a Temperature Resource extending AbstractResource
public class TemperatureResource extends AbstractResource {
public TemperatureResource () {
super (ResourceSpecs.House.Sensors.Temperature);
getAttributes ().setTitle ("Temperature resource !");
}
#Override
public void handleGET (CoapExchange exchange) {
String response = "The temperature";
if (getWildcard () != null) {
response += " of the " + getWildcard ().get (0) + " on the " + getWildcard ().get (1);
}
response += " is : 25 degree C";
exchange.respond (response);
}
}
4 : Create a resources directory on the root of my eclipse project, with json conf files of my resources
{
"verb": "get",
"endpoint": "/houses/*/rooms/*/sensors/temperature",
"class": "com.wild.coap.resources.TemperatureResource"
}
5 : Create a Resources Loader (class that will load the specs definition of the resources and instantiate them independently instead of creating a Tree on the server)
public class ResourcesLoader {
private final static String Path = new File (".").getAbsolutePath () + File.separator + "resources";
private List<ProxyRes> resourcesList;
public ResourcesLoader () throws Exception {
resourcesList = new ArrayList<ProxyRes> ();
File resources = new File (Path);
for (String resName : resources.list ()) {
File resFile = new File (resources, resName);
InputStream is = new FileInputStream (resFile);
JsonObject o = new JsonObject (is);
resourcesArr.add (o);
resourcesList.add (buildObject (o));
}
}
private ProxyRes buildObject (JsonObject o) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
ProxyRes r = new ProxyRes ();
r.setPath (o.getString ("endpoint"));
Class<?> clazz = Class.forName (o.getString ("class"));
CoapResource coapRes = (CoapResource)clazz.newInstance ();
r.setCoapRes (coapRes);
return r;
}
public List<ProxyRes> getResourcesList () {
return resourcesList;
}
}
6 : Create a Custom MessageDelieverer
public class DynamicMessageDeliverer implements MessageDeliverer {
private final List<ProxyRes> resources;
public DynamicMessageDeliverer (List<ProxyRes> resources) {
this.resources = resources;
}
public void deliverRequest (final Exchange exchange) {
Request request = exchange.getRequest ();
List<String> path = request.getOptions ().getUriPath ();
final Resource resource = registerResources (path);
if (resource != null) {
executeResource (exchange, resource);
} else {
exchange.sendResponse (new Response (ResponseCode.NOT_FOUND));
throw new RuntimeException ("Did not find resource " + path.toString() + " requested by " + request.getSource()+":"+request.getSourcePort());
}
}
private void executeResource (final Exchange exchange, final Resource resource) {
// Get the executor and let it process the request
Executor executor = resource.getExecutor ();
if (executor != null) {
exchange.setCustomExecutor ();
executor.execute (new Runnable () {
public void run () {
resource.handleRequest (exchange);
}
});
} else {
resource.handleRequest (exchange);
}
}
private Resource registerResources (List<String> list) {
LinkedList<String> path = new LinkedList<String> (list);
String flatRequestedEndpoint = Arrays.toString (path.toArray ());
LinkedList<String> wildcards = new LinkedList <String> ();
ProxyRes retainedResource = null;
for (ProxyRes proxyRes : resources) {
String[] res = proxyRes.getPath ().replaceFirst ("/", "").split ("/");
int length = res.length;
if (length != path.size ()) {
continue;
}
String flatResEndpoint = Arrays.toString (res);
if (flatResEndpoint.equals (flatRequestedEndpoint)) {
retainedResource = proxyRes;
break;
}
boolean match = true;
for (int i = 0; i < length; i ++) {
String str = res[i];
if (str.equals ("*")) {
wildcards.add (path.get (i));
continue;
}
if (!str.equals (path.get (i))) {
match = false;
break;
}
}
if (!match) {
wildcards.clear ();
continue;
}
retainedResource = proxyRes;
break;
}
if (retainedResource == null) {
return null;
}
((AbstractResource)retainedResource.getCoapRes ()).setWildcard (wildcards);
return retainedResource.getCoapRes ();
}
public void deliverResponse (Exchange exchange, Response response) {
if (response == null) throw new NullPointerException();
if (exchange == null) throw new NullPointerException();
if (exchange.getRequest() == null) throw new NullPointerException();
exchange.getRequest().setResponse(response);
Request request = exchange.getRequest ();
List<String> path = request.getOptions ().getUriPath ();
System.out.println ("Path retrieved : " + Arrays.toString (path.toArray ()));
}
}
7 : Create the Server
public class WildCoapServer extends CoapServer {
private static final int COAP_PORT = NetworkConfig.getStandard ().getInt (NetworkConfig.Keys.COAP_PORT);
public WildCoapServer () throws Exception {
// add endpoints on all IP addresses
addEndpoints ();
ResourcesLoader resLoader = new ResourcesLoader ();
List<ProxyRes> resources = resLoader.getResourcesList ();
setMessageDeliverer (new DynamicMessageDeliverer (resources));
}
#Override
protected Resource createRoot () {
return new WildRootResource ();
}
// Add individual endpoints listening on default CoAP port on all IPv4 addresses of all network interfaces.
private void addEndpoints () {
for (InetAddress addr : EndpointManager.getEndpointManager ().getNetworkInterfaces ()) {
// only binds to IPv4 addresses and localhost
if (addr instanceof Inet4Address || addr.isLoopbackAddress ()) {
InetSocketAddress bindToAddress = new InetSocketAddress (addr, COAP_PORT);
addEndpoint (new CoapEndpoint (bindToAddress));
}
}
}
}
8 : Start the server
public class Main {
public static void main (String[] args) {
try {
WildCoapServer server = new WildCoapServer ();
server.start ();
} catch (Exception e) {
throw new RuntimeException (e.getMessage (), e);
}
}
}
9 : Consume the Temperature resource from a client
public class Client {
public static void main (String[] args) {
URI uri = null;
try {
uri = new URI ("coap://192.168.200.1:5683/houses/house1/rooms/kitchen/sensors/temperature");
} catch (URISyntaxException e) {
throw new RuntimeException (e.getMessage (), e);
}
CoapClient client = new CoapClient (uri);
CoapResponse response = client.get ();
if (response != null) {
System.out.println (response.getCode ());
System.out.println (response.getOptions ());
System.out.println (response.getResponseText ());
System.out.println ("\nADVANCED\n");
// access advanced API with access to more details through .advanced ()
System.out.println (Utils.prettyPrint (response));
} else {
System.out.println ("No response received.");
}
}
}
Hope that helps someone.
This is my solution for this problem.
CoapResource wildcard = new CoapResource("*") {
#Override
public void handleGET(CoapExchange exchange) {
...
}
};
CoapResource root = new CoapResource("root") {
#Override
public Resource getChild(String name) {
return wildcard;
}
};

Phonegap FileUpload Java Server

I am trying to upload an Image on Java Server.the File is trnsfering from android device but saving null on server .
Here is server code
public UploadMediaServerResponse uploadFileForFunBoard(#FormDataParam("photoPath") InputStream photoInputStream,
#FormDataParam("photoPath") FormDataContentDisposition photoFileDetail,
#FormDataParam("userId") int userId, #FormDataParam("mediaType") String mediaType,
#FormDataParam("title") String title,#FormDataParam("funBoardId") int funBoardId)
{
MediaContenModel mediaContenModel = new MediaContenModel();
mediaContenModel.setFunBoardId(funBoardId);
mediaContenModel.setMediaType(mediaType);
mediaContenModel.setUserId(userId);
UploadMediaServerResponse uploadMediaServerResponse = new UploadMediaServerResponse();
boolean isMediaProcessedAndUploaded = true;
String mediaProcessingError = "";
if (photoInputStream != null && photoFileDetail != null)
{
uploadMediaServerResponse = mediaService.uploadOnServer(photoInputStream,
photoFileDetail.getFileName(), userId+"");
if (uploadMediaServerResponse != null
&& !uploadMediaServerResponse.getMediaUrl().equalsIgnoreCase("ERROR"))
{
mediaContenModel.setImageUrl(uploadMediaServerResponse.getMediaUrl());
logger.debug("ContentService --> createStroyline --> fearture Image url ::"
+ uploadMediaServerResponse.getMediaUrl());
}
else
{
isMediaProcessedAndUploaded = false;
mediaProcessingError = uploadMediaServerResponse.getMediaUrl();
logger.debug("ContentService --> createStroyline --> mediaProcessingError ::"
+ mediaProcessingError);
}
}
if (isMediaProcessedAndUploaded)
{
UploadMediaServerResponse response = funBoardService.uploadMediaContent(mediaContenModel);
uploadMediaServerResponse.setMediaUrl(response.getMediaUrl());
}
else
{
uploadMediaServerResponse.setError("Task Failed");
uploadMediaServerResponse.setStatus(ServiceAPIStatus.FAILED.getStatus());
}
return uploadMediaServerResponse;
}
here is my phonegap code
var pictureSource;
var destinationType;
function onPhotoURISuccess(imageURI)
{
console.log(imageURI);
var largeImage = document.getElementById('largeImage');
largeImage.style.display = 'block';
largeImage.src = imageURI;
var options = new FileUploadOptions();
options.fileKey="photoPath";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
options.params = {
"userId": 1,
"funBoardId": 3,
"mediaType": 'image'
};
console.log(JSON.stringify(options));
var ft = new FileTransfer();
ft.upload(imageURI, _BaseURL+"mobile/userService/funboard/upload", win, fail, options);
}
function onPhotoDataSuccess(imageURI)
{
var imgProfile = document.getElementById('imgProfile');
imgProfile.src = imageURI;
if(sessionStorage.isprofileimage==1)
{
getLocation();
}
movePic(imageURI);
}
function onFail(message)
{
alert('Failed because: ' + message);
}
function movePic(file)
{
window.resolveLocalFileSystemURI(file, resolveOnSuccess, resOnError);
}
function resolveOnSuccess(entry)
{
var d = new Date();
var n = d.getTime();
var newFileName = n + ".jpg";
var myFolderApp = "MyAppFolder";
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys)
{
fileSys.root.getDirectory( myFolderApp,
{create:true, exclusive: false},
function(directory)
{
entry.moveTo(directory, newFileName, successMove, resOnError);
},
resOnError);
},
resOnError);
}
function successMove(entry)
{
alert(entry.fullPath);
sessionStorage.setItem('imagepath', entry.fullPath);
}
function resOnError(error)
{
alert(error.code);
}
function capturePhotoEdit()
{
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,
destinationType: destinationType.DATA_URL });
}
function getPhoto(source)
{
navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: source });
}
function onFail(message)
{
alert('Failed because: ' + message);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
alert(r.response);
}
function fail(error) {
alert("An error has occurred: Code = " = error.code);
}
04-14 19:33:46.010: E/FileTransfer(13550): java.io.FileNotFoundException: http:///jeeyoh/mobile/userService/funboard/upload
Thanks in Advance
Replace
options.fileKey="file";
To
options.fileKey="photoPath";

Categories