2013年7月9日 星期二

【Spring】Test in Spring MVC3

   1: package com.lywebii.goldprice;
   2:  
   3: import static org.junit.Assert.*;
   4:  
   5: import java.util.List;
   6:  
   7: import org.junit.After;
   8: import org.junit.Before;
   9: import org.junit.Test;
  10: import org.junit.runner.RunWith;
  11: import org.springframework.beans.factory.annotation.Autowired;
  12: import org.springframework.data.mongodb.core.MongoTemplate;
  13: import org.springframework.data.mongodb.core.geo.Box;
  14: import org.springframework.data.mongodb.core.geo.Point;
  15: import org.springframework.data.mongodb.core.index.GeospatialIndex;
  16: import org.springframework.data.mongodb.core.query.Criteria;
  17: import org.springframework.data.mongodb.core.query.Order;
  18: import org.springframework.data.mongodb.core.query.Query;
  19: import org.springframework.test.context.ContextConfiguration;
  20: import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  21:  
  22: import com.lywebii.goldprice.model.Floating;
  23:  
  24: @RunWith(SpringJUnit4ClassRunner.class)
  25: @ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/spring/root-context.xml"})
  26: public class TestFloatingController {
  27:     @Autowired
  28:     MongoTemplate mongoTemplate;
  29:     
  30:     @Before
  31:     public void setUp() throws Exception {
  32:         Floating floating = new Floating();
  33:         floating.setPosition(new double[]{25.0017035,121.5000121});//235台灣新北市中和區中和路37號
  34:         this.mongoTemplate.save(floating);
  35:         
  36:         floating = new Floating();
  37:         floating.setPosition(new double[]{25.0209304,121.4595818}); //220台灣新北市板橋區金華街90-140號
  38:         this.mongoTemplate.save(floating);
  39:         
  40:         floating = new Floating();
  41:         floating.setPosition(new double[]{25.0052171,121.4198273}); //238台灣新北市樹林區中正路214號
  42:         this.mongoTemplate.save(floating);
  43:         
  44:         floating = new Floating();
  45:         floating.setPosition(new double[]{22.6092776,120.316238}); //806台灣高雄市前鎮區南寧街
  46:         this.mongoTemplate.save(floating);
  47:     }
  48:  
  49:     @After
  50:     public void tearDown() throws Exception {
  51:         this.mongoTemplate.dropCollection(Floating.class);
  52:     }
  53:  
  54:     @Test
  55:     public void test() {
  56:         Query query = new Query();
  57:         query.sort().on("date", Order.DESCENDING);
  58:         
  59:  
  60:         this.mongoTemplate.indexOps(Floating.class).ensureIndex(new GeospatialIndex("position"));
  61:  
  62:  
  63:         List<Floating> list = this.mongoTemplate.find(new Query(Criteria.where("position").near(new Point(25.0052171,121.4198273)).maxDistance(5/111.12)),Floating.class);
  64:         System.out.println("Circle:"+list);
  65:  
  66:  
  67:         list = this.mongoTemplate.find(new Query(Criteria.where("position").within(new Box(new Point(0.2, 0.2), new Point(1, 1)))),Floating.class);
  68:         System.out.println("Box:"+list);
  69:  
  70:         
  71:     }
  72:  
  73: }

 


Above code was about usging monogdb template to save postion data and query near point that given.


IOC Configuration file using below code:



   1: @ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/spring/root-context.xml"})

2013年5月12日 星期日

【Parse.com】Why I like using Parse.com

When I wrote android app,I usually need to write server side code.(I used AppFog for the backend)In my experience,before start coding sever side,I should design Model(or said Er model),then I will create data object correspond with design model.And then I start coding the controller for business logic.(My sever side framework using Spring MVC3)If I need to check the data producing from client.I should add new controller and redirect to its match jsp page.

Now the cloud service Parse.com provide an easy way to above process.

Parse.com provide below function:

  1. Parse Data
  2. Parse Push
  3. Parse Social
  4. Parse Hosting
  5. Cloud Code

And she give us very lots of implementation:

  1. iOS/OSX
  2. Android
  3. JavaScript
  4. Window 8/WP8
  5. .NET
  6. REST API

Its free quota,I thought that it’s enought for small or tiny business requirement:

  1. Request: One million/month
  2. Pushes:  Alos one million/month
  3. Burst Limit 20/second(Ok,I don’t understand what’s that,if u can explain that for me,please tell me,thanks)

Although I did not try all functions,I will tell you that I have already try 2 of the functions in very short time,and that’s very short time I can complete the basis that I need.

First,if you wanna need to do tracing your user what thy do on your app,I thought that you need to get a model(or table) naming  “Floating”(my recently new function for my app,I created a Float Window in  my app,so my table name called “Floating”,and I let my user whether turn off or turn on this function,when then switch the fuction via the button,the app will send a log to the server),in this model I need to define a class,consist 5 columns,then like I said that  I implement a controller and creat a method in controller to make http post to let the app post those fields to the serer.At last I created antoher method to list the created data to a jsp page for showing the datas.After complete above,I turn to android to use HTTPClient to do the client request to send data to server.(HTTPClient code will make you generate about 15~25 lines of code),Now you just only need to do below code

   1: ParseObject floating = new ParseObject("Floating");
   2: floating.put("device_id", 12345678);
   3: floating.put("locale", "zh");
   4: floating.put("enabled", false);
   5:  
   6: floating.saveInBackground();

Then the data have sent to Parse.com server to store.Amazing?


Of course,we need other CRUD data controll,please refer this link to do that:https://parse.com/docs/android_guide#objects 


Remember?,in parse procedure,we did not do any server side code,right?


when you do save for your data,you can check on the dashboard as below(The picture was my another test,the test only contain one column in client,others was create by parse.com)


image


Very soon,right?


Another make me suprise thing is push service,in GCM(Google Cloud Message),I need to go to google console to register the service get appId and add at least 4~5 classe in android project,an……..d code lots controllers or classes in server side(3rd Party Server for controll reqister blah blan…) ,now using Parse.com,you just only do very bit time to do that.



  1. Setup push on android project(Add tag in  AndroidManifest.xml)
  2. Enable push in java code(or said in your activity)
  3. Send message on dashboard(need to send register id to Parse.com when completed above 2 steps)

Please refer this link:https://parse.com/tutorials/android-push-notifications


When you edit your message and click Send a push,your device received message immediately(If choose schedule send now,sure,you can book a spacify time to send that,but you need to upgrade to pro version)


Very soon,right?


Other functions,I did not try.But I thought Parse.com really eliminate lots of comprehensive complex job for us,go to sign up a new account and try it.


And when you go to facebook developer site,we can see facebook have already acquired Parse.com. Nice news.


image

2013年4月23日 星期二

【Android】Check or go to spacified app

   1: String appPackage = "jp.naver.line.android";
   2: Intent intent = getPackageManager().getLaunchIntentForPackage(appPackage);
   3: if(intent!=null){
   4:     startActivity(intent);
   5: }else{
   6:     intent = new Intent(Intent.ACTION_VIEW);
   7:     intent.setData(Uri.parse("market://details?id="+appPackage));
   8: }
   9: startActivity(intent);

2012年9月14日 星期五

【OAuth for plurk】Using plurk api(oauth)

Link below website to register an app

http://www.plurk.com/PlurkApp/http://www.plurk.com/PlurkApp/

image

image

(*Red block is required)

image

Then we can click the test tool(test console)

image

Next we should get Token Key first,click【Get Requet Token】directly.

The action will link to http://www.plurk.com/OAuth/request_token and using get method to get Token Key

and Token Secret

image

Next step we click the 【Optn Authorization URL】,the action will produce an link as below

 

http://www.plurk.com/OAuth/authorize?oauth_token=XX

and open another window to the link

The XX is above Token Key

i.e http://www.plurk.com/OAuth/authorize?oauth_token=Req1JK0ClV84

Below link will ask you login your plurk account,when you completed,you will get below page,ask your authorized.

image

When your confirm,you will get a pin as below.

image

Please remember the pin and back to 【test console】,click  【Get Access Token】

The action will popup an alert to ask you entering the pin

image

When you confirm,the app can do Api call via your account.We can check the app on your app list.

image

Sure,you can cancel the app’s authorization on above red block.

2012年8月14日 星期二

【Flex】Using resource bundles

We know in flex,we will define different property file in different locale folder,usually we can get string by key as below:

   1: hello=Hello



   2: you=You






   1: hello=你好



   2: you=你




In actionscript3 we will use resourceManager.getString('locale',’hello')  set to the value.



and in mxml we will use text="@Resource(key='hello', bundle='locale')" set to value



If we embed the assets in flash(fla),and wanna retrieive the asset by symbol,we will define our property as below:





   1: betarea=Embed(source="./assets/assets.swf", symbol="asset.MySymbol")






   1: betarea=Embed(source="./assets/assets.swf", symbol="asset.MySymbolTW")




In actionscript3 we will use resourceManager.getObject('locale',’betarea') set to the value



and in mxml we will use source="@Resource(key='betarea', bundle='locale')" set to the value



If we define a class by actionscript3 or mxml for customized component and customized skin,we will define our property as below:







   1: entertable=ClassReference("com.leon456.skin.EnterTableSkin")






   1: entertable=ClassReference("com.leon456.skin.EnterTableSkinTW")




In actionscript3 we will use resourceManager.getObject('locale',’betarea') set to the value



and in mxml we will use skinClass="@Resource(key='entertable', bundle='baccaratmoduleui')" set to the value

2012年6月4日 星期一

【BlazeDS】Message of customer adapter

1.Create an adapter class in java source code,in my example,we will pass xml format data to client,if the data from producer is valid,the xml data will send to consumer client correctly,otherwise nothing happened(Console still print print stack trace).

  1: package com.leon456.fake;
  2: 
  3: import java.io.IOException;
  4: import java.io.StringReader;
  5: 
  6: import javax.xml.parsers.DocumentBuilder;
  7: import javax.xml.parsers.DocumentBuilderFactory;
  8: import javax.xml.parsers.ParserConfigurationException;
  9: 
 10: import flex.messaging.messages.AsyncMessage;
 11: import flex.messaging.messages.Message;
 12: import flex.messaging.services.MessageService;
 13: import flex.messaging.services.messaging.adapters.MessagingAdapter;
 14: import org.w3c.dom.Document;
 15: import org.xml.sax.InputSource;
 16: import org.xml.sax.SAXException;
 17: 
 18: public class CommandAdapter extends MessagingAdapter {
 19: 
 20: 	@Override
 21: 	public Object invoke(Message arg0) {
 22: 		System.out.println(arg0.getBody());
 23: 		AsyncMessage newMessage = (AsyncMessage)arg0;
 24: 		DocumentBuilderFactory dbf =
 25:                 DocumentBuilderFactory.newInstance();
 26:                 DocumentBuilder db;
 27: 		try {
 28: 			db = dbf.newDocumentBuilder();
 29: 	                InputSource is = new InputSource();
 30: 	                is.setCharacterStream(new StringReader(arg0.getBody().toString()));
 31: 	                Document doc = db.parse(is);
 32: 	                newMessage.setBody(doc);
 33: 			MessageService msgService = (MessageService)getDestination().getService();
 34: 			msgService.pushMessageToClients(newMessage, true);
 35: 		} catch (ParserConfigurationException e) {
 36: 			e.printStackTrace();
 37: 		}catch (SAXException e) {
 38: 			e.printStackTrace();
 39: 		} catch (IOException e) {
 40: 			e.printStackTrace();
 41: 		}
 42: 		return null;
 43: 	}
 44: }
 45: 


2. In message-config.xml add adapter-definition and destination tag for our customer adapter



  1: <?xml version="1.0" encoding="UTF-8"?>
  2: <service id="message-service" 
  3:     class="flex.messaging.services.MessageService">
  4: 
  5:     <adapters>
  6:         <adapter-definition id="actionscript" class="flex.messaging.services.messaging.adapters.ActionScriptAdapter" default="true" />
  7:         <!-- <adapter-definition id="jms" class="flex.messaging.services.messaging.adapters.JMSAdapter"/> -->
  8:         <adapter-definition id="command" class="com.leon456.fake.CommandAdapter"></adapter-definition>
  9:     </adapters>
 10: 
 11:     <default-channels>
 12:         <channel ref="my-polling-amf"/>
 13:     </default-channels>
 14: 	
 15:     <destination id="fake-command">
 16:         <adapter ref="command"/>
 17:     </destination>
 18: </service>
 19: 


3.Final create a mxml cleint,and we put the producer and consumser together in this client



  1: <?xml version="1.0" encoding="utf-8"?>
  2: <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
  3: 			   xmlns:s="library://ns.adobe.com/flex/spark" 
  4: 			   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" creationComplete="application1_creationCompleteHandler(event)">
  5: 	<fx:Script>
  6: 		<![CDATA[
  7: 			import mx.events.FlexEvent;
  8: 			import mx.messaging.events.MessageEvent;
  9: 			import mx.messaging.events.MessageFaultEvent;
 10: 			import mx.messaging.messages.AsyncMessage;
 11: 			
 12: 			protected function application1_creationCompleteHandler(event:FlexEvent):void
 13: 			{
 14: 				consumer.subscribe();
 15: 			}
 16: 			
 17: 			protected function consumer_messageHandler(event:MessageEvent):void
 18: 			{
 19: 				var data:XML = event.message.body as XML;
 20: 				trace('consumer_messageHandler',typeof(event.message.body),data);
 21: 			}
 22: 			
 23: 			protected function consumer_faultHandler(event:MessageFaultEvent):void
 24: 			{
 25: 				trace('consumer_faultHandler');
 26: 				
 27: 			}
 28: 			
 29: 			protected function button1_clickHandler(event:MouseEvent):void
 30: 			{
 31: 				var message:AsyncMessage = new AsyncMessage();
 32: 				message.body = commandData.text;
 33: 				
 34: 				producer.send(message);
 35: 			}
 36: 		]]>
 37: 	</fx:Script>
 38: 	<fx:Declarations>
 39: 		<s:Consumer id="consumer"
 40: 					destination="fake-command"
 41: 					message="consumer_messageHandler(event)"
 42: 					fault="consumer_faultHandler(event)"/>
 43: 		<s:Producer id="producer"
 44: 				    destination="fake-command"/>
 45: 	</fx:Declarations> 
 46: 	<s:Button x="23" y="205" label="Button" click="button1_clickHandler(event)"/>
 47: 	<s:TextArea id="commandData" x="23" y="31"/>
 48: </s:Application>
 49: 


4.Now we can test it,put some xml string in the textarea,and send it.


image


5.We can see the message on the console window


 In server console


 


image



In flash console



image



 



Above source file,please link to this link to download source