廣告

2015年2月4日 星期三

[SQL] install mysql on ubuntu and start it. | create, insert , delete , update ,

sudo apt-get install mysql-server-5.5
/etc/mysql$ vim my.cnf
如果需要讓MySQL從遠端連進來的話,把 bind_address 這個參數從 127.0.0.1 改成主機的實體 IP 位址。
$ sudo service mysql start
sudo /etc/init.d/mysql start

進入mysql
 mysql -u root -p

change the password of root to "lewis"
GRANT ALL PRIVILEGES ON *.* TO root@localhost IDENTIFIED BY "lewis";

create database testdb;

create accoount: "lewis" , password:"lewis"
GRANT ALL PRIVILEGES ON testdb.* TO lewis@localhost IDENTIFIED BY "lewis" with grant option;

查看該使用者有無權限:
SHOW GRANTS FOR lewis@localhost;

use testdb;
create table testtable 
( id int not null auto_increment primary key, 
name char(35) not null, school char(35) not null, 
age int(11) not null);

發現用aqua一值連不到我vm的sql,最後發現是 權限問題,真是....
 sudo chmod -R 755 /var/lib/mysql/
這樣就可以了.



show出目前有的database
 SHOW DATABASES;

使用哪個db
  use testdb;

show出這個db裡面有哪些table
   show tables;

show出這個table裡面的內容 (select)
 select * from testtable;

新增一筆資料到table
 insert into testtable (name,school,age) values('jim','acer','35');

insert into testtable (name,school) values('jim','acer');


更新一筆資料到 table
 update testtable set age = '30' where name = 'leo'; 


刪除資料
 delete from testtable where age > '1111';

刪除table中所有資料
 truncate from testtable ;


名詞解釋:
索引:

primary key:一個表格只能有一個。
在一個表格中,設定為主索引鍵的欄位值不可以重複,且不可以儲存「NULL」值。
適合使用在類似編碼、代號或身份證字號這類欄位。

unique index(不可重複索引):表格中,設定為唯一索引的欄位值不可以重複,但是可以儲存「NULL」值。這種索引適合用在類似員工資料表格中儲存電子郵件帳號的欄位,因為員工不一定有電子郵件帳號,所以允許儲存「NULL」值,每一個員工的電子郵件帳號都不可以重複。

non-unique index:只是用來增加查詢與維護資料效率的索引。設定為非唯一索引的欄位值可以重複,也可以儲存「NULL」值。


ref:
http://www.codedata.com.tw/database/mysql-tutorial-getting-started
http://www.1keydata.com/sql/alter-table-drop-constraint.html

續:lampp 

ref:http://www.rackspace.com/knowledge_center/article/installing-mysql-server-on-ubuntu
補充: 這種安裝法會在/etc/init.d, 會註冊到service.
開機順序在etc/rc, s=start,k = stop,
mount point 要先起來,如果有其他要用到.
系統有需要的都要close/open.

2015年2月3日 星期二

[java] image base64 encode and decode

package image.process;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class imageCode64 {

 
 
 
    /**
     * Decode string to image
     * @param imageString The string to decode
     * @return decoded image
     */
    public static BufferedImage decodeToImage(String imageString) {

        BufferedImage image = null;
        byte[] imageByte;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            imageByte = decoder.decodeBuffer(imageString);
            ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
            image = ImageIO.read(bis);
            bis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return image;
    }

    /**
     * Encode image to string
     * @param image The image to encode
     * @param type jpeg, bmp, ...
     * @return encoded string
     */
    public static String encodeToString(BufferedImage image, String type) {
        String imageString = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        try {
            ImageIO.write(image, type, bos);
            byte[] imageBytes = bos.toByteArray();

            BASE64Encoder encoder = new BASE64Encoder();
            imageString = encoder.encode(imageBytes);

            
            
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageString;
    }

 
}

[ubuntu] 備份檔案,並傳送到其他主機. | tar, scp , tar

目的:
將測試機的A檔案傳到正式機的A檔案.

 1.備份測試機and正式機的A檔案.(tar) $ tar zcv -f FileName.tar.gz DirName

 2.將測試機的A檔案傳到正式機的A檔案 (scp) $ scp Run.sh    
    acer@xxx.xxx.xxx.xxx:~/opt/cronjobs/eInvoice/

 3.在正式區解開此A檔案(tar) $ tar zxv -f FileName.tar.gz
    || $ tar zxv -f FileName.tar.gz -C your path -z  .
 
    透過 gzip進行壓縮/解壓縮,檔名為 *.tar.gz -c .
    -c : 建立打包檔案
    -x :解打包或解壓縮  .
    -v : 在壓縮/解壓縮的過程中,將正在處理的檔名顯示出來 -f filename:
    -f 後面要立刻接要被處理的檔名 -p(小寫) :
    保留備份資料的原本權限與屬性,常用於備份(-c)重要的設定檔 -P(大寫) :
    保留絕對路徑,亦即允許備份資料中含有根目錄存在之意;
    (不建議大寫P) 因為在 tar 所記錄的檔名就是解壓縮後的實際檔名。
   如果拿掉了根目錄, 假設你將備份資料在/tmp 解開,那麼解壓縮的
   檔名就會變成/tmp/etc/xxx,如果沒有拿掉根目錄, 解壓縮後的檔名就
   會是絕對路徑, 亦即解壓縮後的資料一定會被放置到 /etc/xxx 去,
   如此一來, 你的原本的 /etc/ 底下的資料, 就會被備份資料所
   覆蓋 PS: rm -rf /root/etc /tmp/etc 務必要確認一下後面接的檔名. 如果
   我們要刪除的是 /root/etc 與 /tmp/etc, 可不要將 /etc/ 刪除掉了

[java][webService] struts2 action

網頁端程式上使用action:
  action="../payment/Pay.auth.do
  (..為出去2層的意思)

struts.xml的設定:
 
  
   /payment/result.jsp
   /epay/migs/auth.jsp
  
 


 解釋:
      第一個{1} = Pay 所以:
      class="com.acer.epay.action.PayAction"
      第一個{2} = auth 所以:
      method = auth() //會去呼叫class裡面的auth().
   
      兩個result可以把他們想成case switch.
      根據auth()回傳去執行哪個 xxx.jsp.

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)); // 副檔名
  
 }

}