廣告

2015年2月2日 星期一

[java] soap client sample code






package soapClient;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.soap.*;
//http://stackoverflow.com/questions/15948927/working-soap-client-example
//http://harryjoy.com/2011/10/20/soap-client-in-java/
//http://cafeconleche.org/books/xmljava/chapters/ch03s05.html
//maven http://www.logicsector.com/java/how-to-create-a-wsdl-first-soap-client-in-java-with-cxf-and-maven/
public class SOAPClientSAAJ {

 
 //  http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx?wsdl
  
    public static void main(String args[]) throws Exception {
        // Create SOAP Connection
        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection soapConnection = soapConnectionFactory.createConnection();
        
        // Send SOAP Message to SOAP Server
        String url = "http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx";
        SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);

        // print SOAP Response
        System.out.println("Response SOAP Message:");
        
        //save response string
        File file = new File("soapClient.txt");
        FileOutputStream fop = new FileOutputStream(file);
        if (!file.exists()) {
   file.createNewFile();
  }
        
        soapResponse.writeTo(fop);
        soapResponse.writeTo(System.out);
        soapConnection.close();
    }

    private static SOAPMessage createSOAPRequest() throws Exception {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();

        String serverURI = "http://ws.cdyne.com/";

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration("example", serverURI);

        /*example
        Constructed SOAP Request Message:
        
            
            
                
                    mutantninja@gmail.com
                    123
                
            
        
         */

        // SOAP Body
        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyElem = soapBody.addChildElement("VerifyEmail", "example");
        SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("email", "example");
        soapBodyElem1.addTextNode("mutantninja@gmail.com");
        SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("LicenseKey", "example");
        soapBodyElem2.addTextNode("123");

        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", serverURI  + "VerifyEmail");

        soapMessage.saveChanges();

        /* Print the request message */
        System.out.println("Request SOAP Message:");
        soapMessage.writeTo(System.out);
        System.out.println("getXmlFromSOAPMessage============");
        //get request string
        System.out.println(getXmlFromSOAPMessage(soapMessage));

        return soapMessage;
    }
    
    static String getXmlFromSOAPMessage(SOAPMessage msg) throws SOAPException, IOException {
        ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
        msg.writeTo(byteArrayOS);
        return new String(byteArrayOS.toByteArray());
    }
}


















ref:http://w3school.com.cn/soap/soap_header.asp

[java][webservice] structs2 x eclipse x window8

前言1:java , tomcat設定 可以參考.前面幾篇
前言2:struts2 架構


Struts 2 Architecture


Struts2 的 Action 能夠相容 POJO
講白話一點就是什麼都不用繼承的 class 就能當 Action 用.
POJO類別簡單來說,就是單純的
Java類別,不帶有其他框架 API 呼叫,開發者可以以簡單不複雜的方式(不必實
作一些繁複的介面或繼承)來開發商業邏輯,減少與其他元件的耦合性.
action:Each URL is mapped to a specific action.

專案結構:





2. create dynamic web project






















3. put structs2 lib to your web-inf\lib














4. create model =>HelloWorldAction.java  
Struts 2 framework will create an object of HelloWorldAction.java,
and call execute method.

package com.tutorialspoint.struts2;

public class HelloWorldAction{
   private String name;
   private String age;

 public String getAge() {
  return age;
 }

 public void setAge(String age) {
  this.age = age;
 }

 public String execute() throws Exception {
  System.out.println(name+age);
  return "success2";
 }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }
}


5. create view    under webContent=>HelloWorld.jsp
<s:property value="name"/> 會呼叫 HelloWorldAction.java的getname()

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>Hello World
</head>
<body>
   Hello World,<s:property value="name">
   

   age ,<s:property value="age">
</body>
</html>

6.create main page   under webContent => index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
   
<html>
<head>
Hello World
</head>
<body>
   

Hello World From Struts2

Hello World From Struts2 Extend

Hello World From Struts2 Map

</body> </html>

action = hello . mapping to HelloWorldAction class , use struts.xml to setting





7.create struts.xml under src/


   
     
      
            /HelloWorld.jsp
      
      
       
            /HelloWorld.jsp
            /AccessDenied.jsp
         
        
            /HelloWorldMap.jsp
            /AccessDenied.jsp
         
      
   
   









The only requirement for actions in Struts2 is that there must be one no-argument method that returns either a String or Result object and must be a POJO. If the no-argument method is not specified, the default behavior is to use the execute() method.



8.create web.xml  under webContent/web-inf

   
   Struts 2
   
      index.jsp
   
   
      struts2
      
         org.apache.struts2.dispatcher.FilterDispatcher
      
   

   
      struts2
      /*
 
 
   





9.enable detail log (先跳過)





10. [test] run your project 












11. struts.properties file (if need, this will have default)

### When set to true, Struts will act much more friendly for developers
struts.devMode = true

### Enables reloading of internationalization files
struts.i18n.reload = true

### Enables reloading of XML configuration files
struts.configuration.xml.reload = true

### Sets the port that the server is run on
struts.url.http.port = 8080

      create under web-inf/classes




Create Multiple Actions


_1.  create HelloWorldActionExtendActionSupport.java

package com.tutorialspoint.struts2;

import com.opensymphony.xwork2.ActionSupport;

public class HelloWorldActionExtendActionSupport extends ActionSupport{
   private String name;

   public String execute() throws Exception {
      if ("SECRET".equals(name))
      {
         return SUCCESS;
      }else{
         return ERROR;  
      }
   }
   
   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }
}


_2.  add content to struts.xml



   
     
      
            /HelloWorld.jsp
      
      
       
            /HelloWorld.jsp
            /AccessDenied.jsp
         
        
            /HelloWorldMap.jsp
            /AccessDenied.jsp
         
      
   
   













ValueStack/OGNL Example


The Object-Graph Navigation Language (OGNL) is a powerful expression language that is used to reference and manipulate data on the ValueStack. OGNL also helps in data transfer and type conversion.


=1.  create HelloWorldActionExtendActionMap.java

package com.tutorialspoint.struts2;

import java.util.*; 

import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class HelloWorldActionMap extends ActionSupport{
   private String name;

   public String execute() throws Exception {
      ValueStack stack = ActionContext.getContext().getValueStack();
      Map context = new HashMap();

      context.put("key1", this.name); 
      context.put("key2", this.name);
      stack.push(context);

      System.out.println("Size of the valueStack: " + stack.size());
      return "success";
   }  

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }
}

=2. add content to struts.xml(同上)
=3. add HolloWorldMap.jsp

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
Hello World
</head>
<body>
   Entered value : <s:property value="name">

   Value of key 1 : <s:property value="key1">

   Value of key 2 : <s:property value="key2"> 


</body>
</html>








2015年2月1日 星期日

[java] split string by dot | 用 dot 來切割字串

package test_fb_api;

import java.util.Arrays;

public class testStringSplite {

 public static void main(String[] args) {

  String locat = "http://ibobar-content.oss-cn-hangzhou.aliyuncs.com/book1669/hj1669_ipad.png";
  String[] temp = locat.split("/");
  String downloadPath = "ibobar" + "/" + "getBookList"
    + "/" + temp[temp.length - 2] + ".jpg";
  
  System.out.println("method 1:");
  String ss = temp[temp.length - 1];
  String[] temp2 = ss.split("\\.");
  System.out.println("副檔名 = "+temp2[temp2.length - 1]);
  //System.out.println(Arrays.toString(temp2));
  System.out.println("===============================");
  
  System.out.println("method 2:");
  int startIndex = ss.lastIndexOf(46) + 1;
  int endIndex = ss.length();
  System.out.println("副檔名 = " + ss.substring(startIndex, endIndex)); // 副檔名
  
 }

}


2015年1月31日 星期六

[python] use python-weather-api sample | 如何使用 python-weather-api

API網址python-weather-api
=========================================


wget https://launchpad.net/python-weather-api/trunk/0.3.8/+download/pywapi-0.3.8.tar.gz
tar -zxvf pywapi-0.3.8.tar.gz
cd pywapi-0.3.8/
python setup.py build
python setup.py install
cd .. 


cdoe
import  pywapi
import string
# coding=UTF-8

locate = 'taiwan taipei'

locatMap = pywapi.get_location_ids(locate)

print locatMap.keys()
keylist = []
for key in locatMap.keys():
 keylist.append(key)

usekey =  keylist[0].decode('utf-8')

print "search result: "+ usekey+"\n"

weather_com_result = pywapi.get_weather_from_weather_com(usekey)

yahoo_result = pywapi.get_weather_from_yahoo(usekey)

print "Weather.com says: It is " + string.lower(weather_com_result['current_conditions']['text']) + " and " + weather_com_result['current_conditions']['temperature'] + "C now in "+locate + ".\n"

print "Yahoo says: It is " + string.lower(yahoo_result['condition']['text']) + " and " + yahoo_result['condition']['temp'] + locate+".\n"



[python] BMI sample code

use BMI as sample.
this example will use:
math , class, flow control. def function, import src,




bmi.py
import bmiMethod


#read data from file
file = open('people.txt','r')
print 'the content is ',file.name

people = {}

for line in file.readlines():
   print 'read line:',line
   #rstrip = remove '\n'
   part = line.rstrip().split(' ')
   people[part[1]] = part

for key in people.keys():
        peolist = people.get(key)
        name    = peolist[1]
        height  = int(peolist[2])
        weight  = int(peolist[3])
        bmi = bmiMethod.getBmi(height,weight)
        print name,"'s bmi is ",bmi
        peolist.append(repr(bmi))
        people[key] = peolist
        print 'you are',bmiMethod.getRange(bmi)

f = open('people2.txt','w')
for key in people.keys():
 listp = people.get(key)
 str1 = ' '.join(listp)
 f.write(str1+"\n")

f.close()


bmiMethod.py

from __future__ import division

def getBmi(height , weight):
  print 'height = ',height, " weight = " ,weight
  hei2 = float(height/100)*float(height/100)
  bmi =float (weight/hei2)
  print 'bmi = ',bmi
  return bmi

def getRange(bmi):
  if bmi >= 24:
        return 'fat'
  elif bmi < 24 and bmi >= 19:
        return 'normal'
  else :
        return 'thin'


console
the content is  people.txt
read line: 1 lewis 183 70

read line: 2 leo 175 80

read line: 3 jim 170 60

read line: 4 7 170 80

read line: 5 fai 180 70

height =  183  weight =  70
bmi =  20.902385858
lewis 's bmi is  20.902385858
you are normal
height =  180  weight =  70
bmi =  21.6049382716
fai 's bmi is  21.6049382716
you are normal
height =  170  weight =  60
bmi =  20.7612456747
jim 's bmi is  20.7612456747
you are normal
height =  170  weight =  80
bmi =  27.6816608997
7 's bmi is  27.6816608997
you are fat
height =  175  weight =  80
bmi =  26.1224489796
leo 's bmi is  26.1224489796
you are fat
done


people.txt
1 lewis 183 70
2 leo 175 80
3 jim 170 60
4 7 170 80
5 fai 180 70



people2.txt
1 lewis 183 70 20.902385858042937
5 fai 180 70 21.604938271604937
3 jim 170 60 20.761245674740486
4 7 170 80 27.68166089965398
2 leo 175 80 26.122448979591837

2015年1月29日 星期四

[java] delete non-empty folder / (subfolders). | 刪除整個文件(包含裡面的文件)

以下提供兩種刪整個非空資料夾的方法,
但實際翻了一下
FileUtils.deleteDirectory(File folder);
的source code 後發現兩種是一樣的=.=...

另外:
FileUtils.waitFor(file, 5);
是個好用的東西,他實際上就是在時間內
一直呼叫file.exist(),並且程式會停在這邊,
直到時間到.
這樣就不用自己寫監控檔案下載完了沒XD

package test_fb_api;
import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

//http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#deleteDirectory%28java.io.File%29

public class testDeleteNonEmptyFolder {

 public static int tag = 0;

 public static void main(String[] args) {

  String path = "F:/opt_test/";
  String path2 = "F:/opt_test2/";

  File file = new File(path);

  System.out.println(FileUtils.waitFor(file, 5));

  System.out.println("deleteMethodB:");
  System.out.println("exists before delete : " + file.exists());
  deleteMethodB(file);
  System.out.println("exists after  delete : " + file.exists());

  System.out.println("===========================");
  System.out.println("deleteMethodA:");
  File file2 = new File(path2);
  // set tag = 0 , because "deleteMethodA" is recursive.
  // so you don't know where go false, or is still folder
  tag = 0;
  System.out.println("exists before delete : " + file2.exists());
  deleteMethodA(file2);
  if (tag == 0) {
   System.out.println("deleteMethodA: delete success");
  } else {
   System.out.println("deleteMethodA: have subFolder: " + tag);
  }
  System.out.println("exists after  delete : " + file2.exists());
 }

 public static void deleteMethodB(File folder) {
  try {
   FileUtils.deleteDirectory(folder);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   System.out.println(e.getMessage());
  }
 }

 public static void deleteMethodA(File folder) {
  // check if folder file is a real folder
  if (folder.isDirectory()) {
   File[] list = folder.listFiles();
   if (list != null) {
    for (int i = 0; i < list.length; i++) {
     File tmpF = list[i];
     if (tmpF.isDirectory()) {
      deleteMethodA(tmpF);
     }
     if (!tmpF.delete()) {
      tag++;
     }
    }
   }
   if (!folder.delete()) {
    System.out.println("can't delete folder : " + folder);
   }
  }
 }

}



2015年1月27日 星期二

[java] better way to remove object in arraylist, 從arraylist 拿掉不需要的

如果想在一個迴圈裡面拿掉不須要的item,有兩個可以呼叫,
1.remove(int index)
2.remove(object o)


package test_fb_api;

import java.util.ArrayList;
import java.util.HashMap;



public class testArrayListRemove {

	public static void main(String[] args) {
		
		ArrayList bookShelfData_ReName = new ArrayList();
		bookShelfData_ReName.add("1");
		bookShelfData_ReName.add("2");
		bookShelfData_ReName.add("3");
		bookShelfData_ReName.add("5");
		bookShelfData_ReName.add("2");
		
		System.out.println("remove(int index)");
		for(int i = 0 ; i< bookShelfData_ReName.size() ; i++)
		{	
			System.out.println("===============");
			System.out.println("before:"+bookShelfData_ReName);
			if(bookShelfData_ReName.get(i).equals("2"))
			{
				bookShelfData_ReName.remove(i);
			}
			System.out.println("after:"+bookShelfData_ReName);
			
		}
		System.out.println("****************************");
		
		ArrayList bookShelfData_ReName2 = new ArrayList();
		bookShelfData_ReName2.add("1");
		bookShelfData_ReName2.add("2");
		bookShelfData_ReName2.add("3");
		bookShelfData_ReName2.add("5");
		bookShelfData_ReName2.add("2");
		
		System.out.println("remove(object)");
		System.out.println("===============");
		ArrayList forRemove = new ArrayList();
		for(int i = 0 ; i< bookShelfData_ReName.size() ; i++)
		{	
			if(bookShelfData_ReName.get(i).equals("2"))
			{
				forRemove.add(bookShelfData_ReName.get(i));
			}
			
		}
		for(int i = 0 ; i< forRemove.size() ; i++)
		{
			bookShelfData_ReName.remove(forRemove.get(i));
		}
		System.out.println("after:"+bookShelfData_ReName);
		
		//still O(n)
	}

}



結果: