Playing with Play: Json POJO binding

13. Oktober 2011

0 Kommentare

Since I am used to the handy and easy way of binding HTTP requests parameters to POJOs in Spring I despredly searched for a possibilities to do that in play! It is possible by default for JPA like parameters like obj[1].key=value&obj[2].key=value, but not for json objects. Since Gson is very handy and powerful in parsing json to POJOs I decided to extend play by that functionality.

For this I needed to write a PlayPlugin, since play is treating HTTP parameters based on the naming convention key=value, where key matches the controller parameter name (which btw. is not accessible with Java Reflection, but with a own crafted Java.parameterNames(Method) byte code parser, which only works when play compiles and controls the classes), as a JPA Model object, which is then converted to an empty POJO by the JPAPlugin, and so returned to the Controller method. In order to prevent that I needed to sneak between the other data binding plugins in order to convert the params.

My work is based on this stackoverflow answer. First you place a play.plugins file in your application conf directory with a line like: 101:controllers.JsonDataBindingPlugin, where 101 is the plugin id which is pretty at the beginning of the data binding chain then you extend the PlayPlugin class like that:

package controllers;

import play.PlayPlugin;
...

public class JsonDataBindingPlugin extends PlayPlugin {

	private Gson gson;

	// 101:controllers.JsonDataBindingPlugin
	private Gson getGson() {
		if (gson == null) {
			gson = new Gson();
		}
		return gson;
	}

	@Override
	public Object bind(String name, Class clazz, Type type,
			Annotation[] annotations, Map<String, String[]> params) {

		if (params.containsKey(name)) {

			String[] strings = params.get(name);
			if (strings.length == 1) {
				String param = strings[0];
				if (param.startsWith("{")) {
					try {
						Object fromJson = getGson().fromJson(param, type);
						return fromJson;
					} catch (JsonSyntaxException e) {
						return null;
					}
				}
			}
		}
		return super.bind(name, clazz, type, annotations, params);
	}
}

¬ geschrieben von joecks in Tech, Uncategorized

Importing Cisco pcf settings to Mac OS 10.6 ’s Cisco IPSec Client

1. Dezember 2009

0 Kommentare

So far importing the pcf config file is not supported. But you just need to use the informations provided by the pcf file itself:
- group name
- group Secret
for that you need to decode the hash using this cisco vpnclient password decoder. Based on the cisco-decrypt.c code, which you might like to compile by your own.

Then you type in you password and username, and everything should work.

¬ geschrieben von joecks in Uncategorized, mac

View All Icons in android.R.drawable

23. Oktober 2009

0 Kommentare

Based on an IconViewer I found in the web I desigend this app to show all icons on android.R.drawable. If you need you might change the Class easily.

Icon Viewer App

Icon Viewer App

package de.dailab.iconviewer;

import java.lang.reflect.Field;

import android.app.*;
import android.content.*;
import android.graphics.*;
import android.os.*;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;

public class IconViewer extends Activity {

    
	private int[] IDS;
	
    private int[] getIDS(){
    //	android.R.drawable.ic_menu_zoom
    //	17301504
    //	17301655
    //	android.R.drawable.ic_menu_zoom
    	int[] ids = new int[800];
    	for (int i = 0; i < ids.length; i++) {
			ids[i]= 17301504+i;
		}
    	return ids;
    }

    /**
     * Determines the Name of a Resource,
     * by passing the R.xyz.class and
     * the resourceID of the class to it.
     * @param aClass : like R.drawable.class
     * @param resourceID : like R.drawable.icon
     * @throws IllegalArgumentException if field is not found.
     * @throws NullPointerException if aClass-Parameter is null.
     * <br><br>
     * <b>Example-Call:</b><br>
     * String resName = getResourceNameFromClassByID(R.drawable.class, R.drawable.icon);<br>
     * Then resName would be '<b>icon</b>'.*/
    public String getResourceNameFromClassByID(Class<?> aClass, int resourceID)
                             throws IllegalArgumentException{
         /* Get all Fields from the class passed. */
         Field[] drawableFields = aClass.getFields();
         
         /* Loop through all Fields. */
         for(Field f : drawableFields){
              try {
                   /* All fields within the subclasses of R
                    * are Integers, so we need no type-check here. */
                   
                   /* Compare to the resourceID we are searching. */
                   if (resourceID == f.getInt(null))
                        return f.getName(); // Return the name.
              } catch (Exception e) {
                   e.printStackTrace();
              }
         }
         /* Throw Exception if nothing was found*/
         throw new IllegalArgumentException();
    }
    
    
    private OnClickListener onClicker;
    
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        IDS = getIDS();
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        
        onClicker = new OnClickListener(){

			@Override
			public void onClick(View v) {
				myImageView mv = (myImageView) v;
				String resName = "noname";
				try {
					resName  = getResourceNameFromClassByID(android.R.drawable.class, mv.resId); 
				} catch (IllegalArgumentException e) {
					// TODO: handle exception
				}
				
				String str = "this image is: " + mv.getResId() + "\n And name: "+ resName;
				System.out.println(str);
				Toast.makeText(getBaseContext(), str, Toast.LENGTH_SHORT).show();
			}
        	
        };
        
        AbsoluteLayout layout=new AbsoluteLayout(this);
        layout.setBackgroundColor(Color.rgb(255,255,255));
        setContentView(layout); 

        GridView gridView=new GridView(this);
        setALParams(gridView,0,0);
        gridView.setNumColumns(4);
        gridView.setGravity(Gravity.CENTER);
        gridView.setAdapter(new ImageAdapter(this));
        layout.addView(gridView);
        
        
    }
    
    public class myImageView extends ImageView{

		private int resId;

		public int getResId() {
			return resId;
		}

		public myImageView(Context context) {
			super(context);
			// TODO Auto-generated constructor stub
		}
		
		@Override
		public void setImageResource(int res){
			super.setImageResource(res);
			resId = res;
		}
    	
    }
    
    public class ImageAdapter extends BaseAdapter {
        private Context context;//コンテキスト
		
		

        public ImageAdapter(Context c) {
            context=c;
        }

        public int getCount() {
            return IDS.length;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }
        
        

        public View getView(int position,View convertView,ViewGroup parent) {
            ImageView imageView;
            if (convertView==null) {
                imageView=new myImageView(context);
                imageView.setLayoutParams(new GridView.LayoutParams(45,45));
                imageView.setAdjustViewBounds(false);
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setPadding(8,8,8,8);
            } else {
                imageView=(ImageView)convertView;
            }
            imageView.setImageResource(IDS[position]);
            imageView.setOnClickListener(onClicker);
            return imageView;
        }
    }

    private static void setALParams(View view,int x,int y) {
        setALParams(view,x,y,
            AbsoluteLayout.LayoutParams.WRAP_CONTENT,
            AbsoluteLayout.LayoutParams.WRAP_CONTENT);
    }
    
    private static void setALParams(View view,int x,int y,int w,int h) {
        view.setLayoutParams(
            new AbsoluteLayout.LayoutParams(w,h,x,y));
    }
}

¬ geschrieben von joecks in android

iMob

21. Juni 2009

0 Kommentare

Beim Versuch den Tempelhof Flughafen zu besetzen am 20.6 fiel mir auf wie schlecht die Demonstranten im Gegensatz zu den Polizisten organisiert waren. Letzteren mussten jedoch eine viel größere Fläche schützen als sie eigentlich mit 1400 Polizisten bewerkstelligen konnten, gegen fast 5000 Demonstranten. Doch warum ist es den Besetzern trotzdem nicht gelungen?

Eine simple Antwort ist sicherlich, dass Sie nicht wussten wo wie viele Polizisten in welcher Anzahl standen und sich deswegen entgegen ihren eigentlichen Motivation, in die Kessel der Polizei treiben ließen. Doch es wäre eigentlich super einfach eine Applikation zu schreiben, die auf einem IPhone/Android liefe und über die aktuelle GPS Position solche Informationen sammelt und auswertet. Auch wenn die Idee einfach Klingt und sicherlich für viele Zwecke einsetzbar wäre (Katastrophensituationen, Konzerte, Umweltschäden ) muss man zunächst ein mathematisches Problem lösen: Wie kann man aus Schätzung verschiedener unabhängigen/ abhängigen Über eine bestimmte Position, einen realen (mit hoher Sicherheit) Wert für die gesamte Menge ermitteln. Wobei man das Problem beachten muss was sich aus der Überlagerung der Quellen ergibt und so eventuell zu Viele Teilnehmer geschätzt werden und man auch wie man eine spezielle Geographie in die Positionirung einflißen läßt. Auch sollten die Teilnehmer nicht von einander wissen welche Schätzung sie abgegeben haben, sodass falsche Einschätzungen vermieden werden können. Doch zuerst wird es wichtig herauszufinden, wie viele aktiv Teilnehmen es bedarf um ein relativ korrektes Ergebnis zu liefern?

Mathematische Lösung und eine genaue Skizze folgt.

¬ geschrieben von joecks in Science

Umlaute in Wordpress 2.7.1 mit Textile PlugIn

13. Mai 2009

0 Kommentare

Ich hatte einen Merkwürdigen Fehler bei der Standart Installation von Wordpress 2.7.1- de und en, der bei einem anderen enviroment nicht vorkam, dass die Umlaute nicht korrekt angezeigt wurden.

Ich dachte zunächst das Problem lag an einer fehlenden mysql SET NAME query Anweisung , die über die Variable define('DB_COLLATE','') auf utf8 gesetzt werden müsste.

Doch schlißlich war es das Textile 2 (Improved) Plugin für Wordpress, was die Codierung falsch gemacht hat. Die Werte für das eingehende und ausgehende Codec müssen einfach frei bleiben.

¬ geschrieben von joecks in wordpress

Theme von BenediktRB • Powered by Wordpress • Abonniere den RSS Feed