2014年11月12日 星期三
QuartzSchedulerListener
<listener>
<listener-class>
com.quart.QuartzSchedulerListener
</listener-class>
</listener>
2014年11月11日 星期二
HibernateUtil
http://www.mediatek.com.tw/?a=url&k=86218eff&u=aHR0cDovL3NlZ21lbnRmYXVsdC5jb20vYmxvZy93YW5nZGFpLzExOTAwMDAwMDA2NzM1MzI=&t=SGliZXJuYXRlLWNvcmUgNC4zLjYgRmluYWwg6YWN572u5Lit5Ye6546w55qE5LiA5Lqb5bCP6Zeu6aKYIC0gU2VnbWVudC4uLg==&s=aGliZXJuYXRlNC4zLjbphY3nva4=
package com;
import javax.persistence.EntityManagerFactory;
import org.apache.struts2.ServletActionContext;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateUtil {
private org.hibernate.Transaction tx;
private Session session;
private static Boolean isAvaliable = true;
private static final SessionFactory sessionFactory = buildSessionFactory();
public HibernateUtil(){
this.session = sessionFactory.openSession();
}
private static SessionFactory buildSessionFactory() {
try {
Configuration config = new Configuration();
String sessionFactoryPath = (String) ServletActionContext.getServletContext().getInitParameter("SessionFactoryPath");
config.configure(sessionFactoryPath);
return config.buildSessionFactory(new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build());
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public String[] getColumnNames(Class<?> calsss) {
ClassMetadata hibernateMetadata = sessionFactory.getClassMetadata(calsss);
String[] columnNames = hibernateMetadata.getPropertyNames();
return columnNames;
}
public org.hibernate.type.Type[] getColumnTypes(Class<?> calsss) {
ClassMetadata hibernateMetadata = sessionFactory.getClassMetadata(calsss);
org.hibernate.type.Type[] columnTypes = hibernateMetadata.getPropertyTypes();
return columnTypes;
}
public Boolean getIsAvaliable() {
return isAvaliable;
}
public Session getSession() {
return this.session;
}
public int sessionBeginTransaction() {
try {
tx = session.beginTransaction();
} catch (HibernateException e) {
e.printStackTrace();
return 0;
}
return 1;
}
public int commitTransactionAndClose() {
try {
this.tx.commit();
System.err.println("commitTransactionAndClose() sus");
return 1;
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
return 0;
} finally {
session.close();
}
}
public Transaction getTransaction() {
return this.tx;
}
public void close() {
try {
if (tx != null) {
if (tx.isActive()) {
tx.rollback();
}
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (session != null) {
if (session.isOpen()) {
session.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
20150214
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
new Configuration().configure().buildSessionFactory(
new StandardServiceRegistryBuilder().build() );
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
return null;
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
package com;
import javax.persistence.EntityManagerFactory;
import org.apache.struts2.ServletActionContext;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateUtil {
private org.hibernate.Transaction tx;
private Session session;
private static Boolean isAvaliable = true;
private static final SessionFactory sessionFactory = buildSessionFactory();
public HibernateUtil(){
this.session = sessionFactory.openSession();
}
private static SessionFactory buildSessionFactory() {
try {
Configuration config = new Configuration();
String sessionFactoryPath = (String) ServletActionContext.getServletContext().getInitParameter("SessionFactoryPath");
config.configure(sessionFactoryPath);
return config.buildSessionFactory(new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build());
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public String[] getColumnNames(Class<?> calsss) {
ClassMetadata hibernateMetadata = sessionFactory.getClassMetadata(calsss);
String[] columnNames = hibernateMetadata.getPropertyNames();
return columnNames;
}
public org.hibernate.type.Type[] getColumnTypes(Class<?> calsss) {
ClassMetadata hibernateMetadata = sessionFactory.getClassMetadata(calsss);
org.hibernate.type.Type[] columnTypes = hibernateMetadata.getPropertyTypes();
return columnTypes;
}
public Boolean getIsAvaliable() {
return isAvaliable;
}
public Session getSession() {
return this.session;
}
public int sessionBeginTransaction() {
try {
tx = session.beginTransaction();
} catch (HibernateException e) {
e.printStackTrace();
return 0;
}
return 1;
}
public int commitTransactionAndClose() {
try {
this.tx.commit();
System.err.println("commitTransactionAndClose() sus");
return 1;
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
return 0;
} finally {
session.close();
}
}
public Transaction getTransaction() {
return this.tx;
}
public void close() {
try {
if (tx != null) {
if (tx.isActive()) {
tx.rollback();
}
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (session != null) {
if (session.isOpen()) {
session.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
20150214
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
new Configuration().configure().buildSessionFactory(
new StandardServiceRegistryBuilder().build() );
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
return null;
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
gson TableExclusionStrategy
http://hashtagfail.com/post/44606137082/mobile-services-android-serialization-gson
http://stackoverflow.com/questions/4802887/gson-how-to-exclude-specific-fields-from-serialization-without-annotations
public class TableExclusionStrategy implements ExclusionStrategy{
@Override
public boolean shouldSkipField(FieldAttributes f) {
if(f.getName().equals("transactions")){
return true;
}
if(f.getName().equals("memberowners")){
return true;
}
return false;
}
@Override
public boolean shouldSkipClass(Class<?> f) {
return false;
}
}
2014年11月10日 星期一
ATTRIBUTE NAME: " + field.getName()
http://stackoverflow.com/questions/1038308/how-to-get-the-list-of-all-attributes-of-a-java-object-using-beanutils-introspec
java得到類別名稱
String name = "godleon";
Class stringClass = name.getClass();
System.out.println("類別名稱:" + stringClass.getName());
System.out.println("getSimpleName:" + stringClass.getSimpleName());
System.out.println("是否為介面:" + stringClass.isInterface());
System.out.println("是否為基本型態:" + stringClass.isPrimitive());
System.out.println("是否為陣列物件:" + stringClass.isArray());
System.out.println("父類別名稱:" + stringClass.getSuperclass().getName());
Class stringClass = name.getClass();
System.out.println("類別名稱:" + stringClass.getName());
System.out.println("getSimpleName:" + stringClass.getSimpleName());
System.out.println("是否為介面:" + stringClass.isInterface());
System.out.println("是否為基本型態:" + stringClass.isPrimitive());
System.out.println("是否為陣列物件:" + stringClass.isArray());
System.out.println("父類別名稱:" + stringClass.getSuperclass().getName());
2014年11月7日 星期五
BufferedReader example ->texttoInsertSql
texttoInsertSql:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package acerrcode;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author linkulife
*/
public class AcerRcode {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
File file = null;
file = new File("D:\\keith\\linkulife\\AcerRcode.txt");
readfileByLine(file);
}
public static void readfileByLine(File file) {
ArrayList<String[]> list = new ArrayList<String[]>();
InputStreamReader isr = null;
try {
try {
isr = new InputStreamReader(new FileInputStream(file), "UTF-8");
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(AcerRcode.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(AcerRcode.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedReader br = new BufferedReader(isr);
String str = null;
try {
while((str = br.readLine())!=null){
list.add(parseTosql(str));
}
} catch (IOException ex) {
Logger.getLogger(AcerRcode.class.getName()).log(Level.SEVERE, null, ex);
}
//System.out.println(Arrays.toString(list));
}
public static String[] parseTosql(String line) {
String[] linearray = line.split("\\s+");
//System.out.println(Arrays.toString(linearray));
String sql=setToSql(linearray[0],linearray[1],linearray[2],linearray[3]);
System.out.println(sql);
return linearray;
}
public static String setToSql(String acerCode, String acerResponse, String ewalletCode, String appShowMsg) {
String temp = "INSERT INTO `ewalletValue`.`acerResponse` (`acerResponseId`, `acerCode`, `acerResponse`, `ewalletCode`, `appShowMsg`) VALUES (NULL"
+ ", '" + acerCode + "', '" + acerResponse + "', '" + ewalletCode + "', '" + appShowMsg + "');";
return temp;
}
}
input:
00 授權成功 A00 交易成功
01 請查詢發卡銀行 A01 交易失敗(A01):請洽原發卡行
02 請查詢發卡銀行 A02 交易失敗(A02):請洽原發卡行
03 未核准之特約店 A03 交易失敗(A03):請洽客服
04 非正常卡 A04 交易失敗(A04):卡片異常,請洽原發卡行
05 拒絕交易 A05 交易失敗(A05):拒絕交易,請洽客服
12 本交易不接受 A12 交易失敗(A12):拒絕交易,請洽客服
13 金額不符 A13 交易失敗(A13):請洽客服
14 帳號不符 A14 交易失敗(A14):請洽客服
15 原發卡行不符 A15 交易失敗(A15):請洽客服
19 請重試交易 A19 交易失敗(A19):請洽原發卡行確認交易結果
25 請查詢銀行 A25 交易失敗(A25):請洽原發卡行
30 請查詢銀行 A30 交易失敗(A30):請洽原發卡行
31 本交易不接受 A31 交易失敗(A31):拒絕交易,請洽客服
41 非正常卡 A41 交易失敗(A41):卡片異常,請洽原發卡行
43 非正常卡 A43 交易失敗(A43):卡片異常,請洽原發卡行
51 餘額不足 A51 交易失敗(A51):額度不足,請洽原發卡行
54 卡片過期 A54 交易失敗(A54):卡片過期,請洽原發卡行
55 密碼錯誤 A55 交易失敗(A55):請洽客服
57 本交易不接受 A57 交易失敗(A57):拒絕交易,請洽客服
58 本交易不接受 A58 交易失敗(A58):拒絕交易,請洽客服
59 無此帳號 A59 交易失敗(A59):請洽客服
61 提款超過限額 A61 交易失敗(A61):請洽原發卡行
62 非正常卡 A62 交易失敗(A62):卡片異常,請洽原發卡行
63 主機安全碼有誤 A63 交易失敗(A63):請洽客服
75 密碼超過次數 A75 交易失敗(A75):請洽客服
77 總額不符 A77 交易失敗(A77):請洽客服
79 批號已開啟 A79 交易失敗(A79):請洽客服
80 批號錯誤 A80 交易失敗(A80):請洽客服
85 無此批號 A85 交易失敗(A85):請洽客服
88 特約店帳號不符 A88 交易失敗(A88):請洽客服
89 終端機號錯誤 A89 交易失敗(A89):請洽客服
91 請查詢發卡銀行 A91 交易失敗(A91):請洽原發卡行
94 傳輸重覆 A94 交易失敗(A94):請洽客服
95 檔案傳輸中 A95 交易失敗(A95):請洽客服
96 主機系統故障 A96 交易失敗(A96):請洽客服
outpunt
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package acerrcode;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author linkulife
*/
public class AcerRcode {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
File file = null;
file = new File("D:\\keith\\linkulife\\AcerRcode.txt");
readfileByLine(file);
}
public static void readfileByLine(File file) {
ArrayList<String[]> list = new ArrayList<String[]>();
InputStreamReader isr = null;
try {
try {
isr = new InputStreamReader(new FileInputStream(file), "UTF-8");
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(AcerRcode.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(AcerRcode.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedReader br = new BufferedReader(isr);
String str = null;
try {
while((str = br.readLine())!=null){
list.add(parseTosql(str));
}
} catch (IOException ex) {
Logger.getLogger(AcerRcode.class.getName()).log(Level.SEVERE, null, ex);
}
//System.out.println(Arrays.toString(list));
}
public static String[] parseTosql(String line) {
String[] linearray = line.split("\\s+");
//System.out.println(Arrays.toString(linearray));
String sql=setToSql(linearray[0],linearray[1],linearray[2],linearray[3]);
System.out.println(sql);
return linearray;
}
public static String setToSql(String acerCode, String acerResponse, String ewalletCode, String appShowMsg) {
String temp = "INSERT INTO `ewalletValue`.`acerResponse` (`acerResponseId`, `acerCode`, `acerResponse`, `ewalletCode`, `appShowMsg`) VALUES (NULL"
+ ", '" + acerCode + "', '" + acerResponse + "', '" + ewalletCode + "', '" + appShowMsg + "');";
return temp;
}
}
input:
00 授權成功 A00 交易成功
01 請查詢發卡銀行 A01 交易失敗(A01):請洽原發卡行
02 請查詢發卡銀行 A02 交易失敗(A02):請洽原發卡行
03 未核准之特約店 A03 交易失敗(A03):請洽客服
04 非正常卡 A04 交易失敗(A04):卡片異常,請洽原發卡行
05 拒絕交易 A05 交易失敗(A05):拒絕交易,請洽客服
12 本交易不接受 A12 交易失敗(A12):拒絕交易,請洽客服
13 金額不符 A13 交易失敗(A13):請洽客服
14 帳號不符 A14 交易失敗(A14):請洽客服
15 原發卡行不符 A15 交易失敗(A15):請洽客服
19 請重試交易 A19 交易失敗(A19):請洽原發卡行確認交易結果
25 請查詢銀行 A25 交易失敗(A25):請洽原發卡行
30 請查詢銀行 A30 交易失敗(A30):請洽原發卡行
31 本交易不接受 A31 交易失敗(A31):拒絕交易,請洽客服
41 非正常卡 A41 交易失敗(A41):卡片異常,請洽原發卡行
43 非正常卡 A43 交易失敗(A43):卡片異常,請洽原發卡行
51 餘額不足 A51 交易失敗(A51):額度不足,請洽原發卡行
54 卡片過期 A54 交易失敗(A54):卡片過期,請洽原發卡行
55 密碼錯誤 A55 交易失敗(A55):請洽客服
57 本交易不接受 A57 交易失敗(A57):拒絕交易,請洽客服
58 本交易不接受 A58 交易失敗(A58):拒絕交易,請洽客服
59 無此帳號 A59 交易失敗(A59):請洽客服
61 提款超過限額 A61 交易失敗(A61):請洽原發卡行
62 非正常卡 A62 交易失敗(A62):卡片異常,請洽原發卡行
63 主機安全碼有誤 A63 交易失敗(A63):請洽客服
75 密碼超過次數 A75 交易失敗(A75):請洽客服
77 總額不符 A77 交易失敗(A77):請洽客服
79 批號已開啟 A79 交易失敗(A79):請洽客服
80 批號錯誤 A80 交易失敗(A80):請洽客服
85 無此批號 A85 交易失敗(A85):請洽客服
88 特約店帳號不符 A88 交易失敗(A88):請洽客服
89 終端機號錯誤 A89 交易失敗(A89):請洽客服
91 請查詢發卡銀行 A91 交易失敗(A91):請洽原發卡行
94 傳輸重覆 A94 交易失敗(A94):請洽客服
95 檔案傳輸中 A95 交易失敗(A95):請洽客服
96 主機系統故障 A96 交易失敗(A96):請洽客服
outpunt
2014年11月6日 星期四
log4j to separate log files
http://stackoverflow.com/questions/9652032/how-can-i-create-2-separate-log-files-with-one-log4j-config-file
# Define the root logger with appender file A1
log4j.rootLogger = INFO,stdout,detail
#log4j.category.* private static Logger log = Logger.getLogger("struts2");
log4j.category.struts2 = WARN,struts2
#private static Logger log = Logger.getLogger("error");
log4j.category.error = ERROR,error
log4j.category.org.hibernate = INFO,hibernatelog
# Direct log messages to a log file
log4j.appender.error=org.apache.log4j.DailyRollingFileAppender
log4j.appender.error.File=/opt/apache-tomcat-7.0.54/webapps/mwallet/error.log
log4j.appender.error.DatePattern='.'yyyy-MM-dd
log4j.appender.error.MaxFileSize=10MB
log4j.appender.error.MaxBackupIndex=100
log4j.appender.error.Append=true
log4j.appender.error.encoding=UTF-8
log4j.appender.error.layout=org.apache.log4j.PatternLayout
log4j.appender.error.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p](%F:%L) - %m%n
# Direct log messages to a log file
log4j.appender.struts2=org.apache.log4j.DailyRollingFileAppender
log4j.appender.struts2.File=/opt/apache-tomcat-7.0.54/webapps/mwallet/struts2ex.log
log4j.appender.struts2.DatePattern='.'yyyy-MM-dd
log4j.appender.struts2.MaxFileSize=10MB
log4j.appender.struts2.MaxBackupIndex=100
log4j.appender.struts2.Append=true
log4j.appender.struts2.encoding=UTF-8
log4j.appender.struts2.layout=org.apache.log4j.PatternLayout
log4j.appender.struts2.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p](%F:%L) - %m%n
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p](%F:%L) - %m%n
# Direct log messages to a hibernatelog file
log4j.appender.hibernatelog=org.apache.log4j.DailyRollingFileAppender
log4j.appender.hibernatelog.File=/opt/apache-tomcat-7.0.54/webapps/mwallet/hibernatelog.log
log4j.appender.hibernatelog.DatePattern='.'yyyy-MM-dd
log4j.appender.hibernatelog.MaxFileSize=10MB
log4j.appender.hibernatelog.MaxBackupIndex=100
log4j.appender.hibernatelog.Append=true
log4j.appender.hibernatelog.layout=org.apache.log4j.PatternLayout
log4j.appender.hibernatelog.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p](%F:%L) - %m%n
# Direct log messages to a detail file
log4j.appender.detail=org.apache.log4j.DailyRollingFileAppender
log4j.appender.detail.File=/opt/apache-tomcat-7.0.54/webapps/mwallet/detail.log
log4j.appender.detail.DatePattern='.'yyyy-MM-dd
log4j.appender.detail.MaxFileSize=10MB
log4j.appender.detail.MaxBackupIndex=100
log4j.appender.detail.Append=true
log4j.appender.detail.layout=org.apache.log4j.PatternLayout
log4j.appender.detail.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p](%F:%L) - %m%n
# hibernate
org.hibernate.tool.hbm2ddl=hibernatelog
# Define the root logger with appender file A1
log4j.rootLogger = INFO,stdout,detail
#log4j.category.* private static Logger log = Logger.getLogger("struts2");
log4j.category.struts2 = WARN,struts2
#private static Logger log = Logger.getLogger("error");
log4j.category.error = ERROR,error
log4j.category.org.hibernate = INFO,hibernatelog
# Direct log messages to a log file
log4j.appender.error=org.apache.log4j.DailyRollingFileAppender
log4j.appender.error.File=/opt/apache-tomcat-7.0.54/webapps/mwallet/error.log
log4j.appender.error.DatePattern='.'yyyy-MM-dd
log4j.appender.error.MaxFileSize=10MB
log4j.appender.error.MaxBackupIndex=100
log4j.appender.error.Append=true
log4j.appender.error.encoding=UTF-8
log4j.appender.error.layout=org.apache.log4j.PatternLayout
log4j.appender.error.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p](%F:%L) - %m%n
# Direct log messages to a log file
log4j.appender.struts2=org.apache.log4j.DailyRollingFileAppender
log4j.appender.struts2.File=/opt/apache-tomcat-7.0.54/webapps/mwallet/struts2ex.log
log4j.appender.struts2.DatePattern='.'yyyy-MM-dd
log4j.appender.struts2.MaxFileSize=10MB
log4j.appender.struts2.MaxBackupIndex=100
log4j.appender.struts2.Append=true
log4j.appender.struts2.encoding=UTF-8
log4j.appender.struts2.layout=org.apache.log4j.PatternLayout
log4j.appender.struts2.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p](%F:%L) - %m%n
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p](%F:%L) - %m%n
# Direct log messages to a hibernatelog file
log4j.appender.hibernatelog=org.apache.log4j.DailyRollingFileAppender
log4j.appender.hibernatelog.File=/opt/apache-tomcat-7.0.54/webapps/mwallet/hibernatelog.log
log4j.appender.hibernatelog.DatePattern='.'yyyy-MM-dd
log4j.appender.hibernatelog.MaxFileSize=10MB
log4j.appender.hibernatelog.MaxBackupIndex=100
log4j.appender.hibernatelog.Append=true
log4j.appender.hibernatelog.layout=org.apache.log4j.PatternLayout
log4j.appender.hibernatelog.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p](%F:%L) - %m%n
# Direct log messages to a detail file
log4j.appender.detail=org.apache.log4j.DailyRollingFileAppender
log4j.appender.detail.File=/opt/apache-tomcat-7.0.54/webapps/mwallet/detail.log
log4j.appender.detail.DatePattern='.'yyyy-MM-dd
log4j.appender.detail.MaxFileSize=10MB
log4j.appender.detail.MaxBackupIndex=100
log4j.appender.detail.Append=true
log4j.appender.detail.layout=org.apache.log4j.PatternLayout
log4j.appender.detail.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p](%F:%L) - %m%n
# hibernate
org.hibernate.tool.hbm2ddl=hibernatelog
DaoFactory greendao
http://android.hew.io/octa-george/android-greendao-sample
1.https://github.com/SureCase/GreenDaoForAndroidStudio
android {
package citygo.ewallet.com.facebookexample;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import dao.BoxDao;
import dao.DaoMaster;
import dao.DaoSession;
import de.greenrobot.dao.AbstractDao;
/**
* Created by linkulife on 2014/11/5.
*/
public class DaoFactory {
private DaoSession daoSession;
private static DaoFactory daoFactory;
public static DaoFactory getInstance(){
if(daoFactory==null){
daoFactory = new DaoFactory();
}
return daoFactory;
}
public void init(Context context){
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, "example-db", null);
SQLiteDatabase db = helper.getWritableDatabase();
DaoMaster daoMaster = new DaoMaster(db);
daoSession = daoMaster.newSession();
}
public DaoSession getDaoSession() {
return daoSession;
}
public void beginTransaction(AbstractDao dao){
dao.getDatabase().beginTransaction();
}
public void rollback(AbstractDao dao){
dao.getDatabase().endTransaction();
}
public void commit(AbstractDao dao){
dao.getDatabase().setTransactionSuccessful();
dao.getDatabase().endTransaction();
}
public void setDaoSession(DaoSession daoSession) {
this.daoSession = daoSession;
}
public BoxDao getBoxDao(){
return daoSession.getBoxDao();
}
}
public class DaoExampleApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
DaoFactory.getInstance().init(this);
}
}
使用:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
QueryBuilder.LOG_SQL = true;
QueryBuilder.LOG_VALUES = true;
BoxDao b = DaoFactory.getInstance().getBoxDao();
b.deleteAll();
Box box= new Box();
box.setDescription("de");
box.setName("name");
b.insertOrReplace(box);
DaoFactory.getInstance().beginTransaction(b);
Box box1= new Box();
box1.setName("name2");
b.insert(box1);
DaoFactory.getInstance().rollback(b);
List<Box> all = b.loadAll();
for(Box bb:all){
Log.d("",""+bb.getName());
}
}
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme"
android:name=".DaoExampleApplication"
>

package ex.lfo.com.myapplicationex;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import de.greenrobot.dao.query.QueryBuilder;
import greendao.BoxDao;
import greendao.DaoMaster;
import greendao.DaoSession;
/**
* Created by Administrator on 2015/2/14.
*/
public class Orm {
private static Orm instance=null;
private SQLiteOpenHelper helper;
private SQLiteDatabase db;
private DaoMaster daoMaster;
private Orm(Context context){
QueryBuilder.LOG_SQL = true;
QueryBuilder.LOG_VALUES = true;
initDb(context);
}
private void initDb(Context context) {
helper = new DaoMaster.DevOpenHelper(context, "box", null);
db = helper.getWritableDatabase();
daoMaster = new DaoMaster(db);
}
public DaoSession getDaoSession(){
DaoSession daoSession = daoMaster.newSession();
// BoxDao boxDao= daoSession.getBoxDao();
return daoSession;
}
public static Orm getInstance(Context context ){
if(instance==null){
instance=new Orm(context);
}
return instance;
}
}
1.https://github.com/SureCase/GreenDaoForAndroidStudio
Download module
2.Add module to project
3.
Connect generator with project
4.
Run module
5.
Make project aware of GreenDao files
6.- Project is still not aware of new Java files because it isn't located in
../<PROJECT NAME>/src/main/javadirectory. To fix this we must specify projects source sets. It is important to point two java file sources:/src/main/javaand/src/main/java-gen. You can do it by placingsourceSetssection intoandroidsection ingradle.buildfile:
android {
sourceSets {main {manifest.srcFile 'src/main/AndroidManifest.xml'java.srcDirs = ['src/main/java', 'src/main/java-gen']res.srcDirs = ['src/main/res']}}}
package citygo.ewallet.com.facebookexample;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import dao.BoxDao;
import dao.DaoMaster;
import dao.DaoSession;
import de.greenrobot.dao.AbstractDao;
/**
* Created by linkulife on 2014/11/5.
*/
public class DaoFactory {
private DaoSession daoSession;
private static DaoFactory daoFactory;
public static DaoFactory getInstance(){
if(daoFactory==null){
daoFactory = new DaoFactory();
}
return daoFactory;
}
public void init(Context context){
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, "example-db", null);
SQLiteDatabase db = helper.getWritableDatabase();
DaoMaster daoMaster = new DaoMaster(db);
daoSession = daoMaster.newSession();
}
public DaoSession getDaoSession() {
return daoSession;
}
public void beginTransaction(AbstractDao dao){
dao.getDatabase().beginTransaction();
}
public void rollback(AbstractDao dao){
dao.getDatabase().endTransaction();
}
public void commit(AbstractDao dao){
dao.getDatabase().setTransactionSuccessful();
dao.getDatabase().endTransaction();
}
public void setDaoSession(DaoSession daoSession) {
this.daoSession = daoSession;
}
public BoxDao getBoxDao(){
return daoSession.getBoxDao();
}
}
public class DaoExampleApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
DaoFactory.getInstance().init(this);
}
}
使用:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
QueryBuilder.LOG_SQL = true;
QueryBuilder.LOG_VALUES = true;
BoxDao b = DaoFactory.getInstance().getBoxDao();
b.deleteAll();
Box box= new Box();
box.setDescription("de");
box.setName("name");
b.insertOrReplace(box);
DaoFactory.getInstance().beginTransaction(b);
Box box1= new Box();
box1.setName("name2");
b.insert(box1);
DaoFactory.getInstance().rollback(b);
List<Box> all = b.loadAll();
for(Box bb:all){
Log.d("",""+bb.getName());
}
}
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme"
android:name=".DaoExampleApplication"
>

package ex.lfo.com.myapplicationex;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import de.greenrobot.dao.query.QueryBuilder;
import greendao.BoxDao;
import greendao.DaoMaster;
import greendao.DaoSession;
/**
* Created by Administrator on 2015/2/14.
*/
public class Orm {
private static Orm instance=null;
private SQLiteOpenHelper helper;
private SQLiteDatabase db;
private DaoMaster daoMaster;
private Orm(Context context){
QueryBuilder.LOG_SQL = true;
QueryBuilder.LOG_VALUES = true;
initDb(context);
}
private void initDb(Context context) {
helper = new DaoMaster.DevOpenHelper(context, "box", null);
db = helper.getWritableDatabase();
daoMaster = new DaoMaster(db);
}
public DaoSession getDaoSession(){
DaoSession daoSession = daoMaster.newSession();
// BoxDao boxDao= daoSession.getBoxDao();
return daoSession;
}
public static Orm getInstance(Context context ){
if(instance==null){
instance=new Orm(context);
}
return instance;
}
}
2014年11月5日 星期三
Android Icons
http://www.creativefreedom.co.uk/icon-designers-blog/android-4-1-icon-size-guide-made-simple/
2014年11月1日 星期六
MYSQL找出兩個月前
SELECT * FROM `servicecard` where `update_date` > (DATE_SUB(CURDATE(), INTERVAL 2 MONTH))
兩個月前
http://stackoverflow.com/questions/2793619/mysql-query-working-with-interval-and-curdate
2014年10月31日 星期五
Collections SORT 自小而大
自小而大
List<ServiceCategoryVo> list = serviceCategoryResponseVo.getServiceCategory();
Collections.sort(list, new Comparator<ServiceCategoryVo>() {
@Override
public int compare(ServiceCategoryVo a, ServiceCategoryVo b) {
if(a.getNo()>b.getNo()){
return 1;
}else{
return 0;
}
}
});
for(ServiceCategoryVo s:list){
Log.d("TAG","NO:"+s.getNo()+"getServiceName:"+s.getServiceName());
}
List<ServiceCategoryVo> list = serviceCategoryResponseVo.getServiceCategory();
Collections.sort(list, new Comparator<ServiceCategoryVo>() {
@Override
public int compare(ServiceCategoryVo a, ServiceCategoryVo b) {
if(a.getNo()>b.getNo()){
return 1;
}else{
return 0;
}
}
});
for(ServiceCategoryVo s:list){
Log.d("TAG","NO:"+s.getNo()+"getServiceName:"+s.getServiceName());
}
MonkeyTest
Please help to test MonkeyTest by following command:
adb shell monkey -p com.ewallet.citygo.dev -v 1500
http://android-test-tw.blogspot.tw/2012/10/android-monkey-automation-test.html
http://www.slideshare.net/ContusQA/monkey-talk-automation
adb shell monkey -p com.ewallet.citygo.dev -v 1500
http://android-test-tw.blogspot.tw/2012/10/android-monkey-automation-test.html
http://www.slideshare.net/ContusQA/monkey-talk-automation
2014年10月29日 星期三
facebook sdk
copy -patse fbExampleMyApplication.zip下載
http://1drv.ms/1LpzJjB
0.build.gradle
compile 'com.android.support:appcompat-v7:19.1.+'
compile 'com.facebook.android:facebook-android-sdk:3.23.0'
1.AndroidManifest.xml
uses-permission and com.facebook.LoginActivity and meta-data
2.strings.xml app_id
3.mainfragment.xml com.facebook.widget.LoginButton
4.MainFragment LoginButton
5.dashboard
use pkname and activityname to get app_id and
Single Sign On
https://developers.facebook.com/apps/935943056446383/settings/basic/
reading
https://developers.facebook.com/docs/android/login-with-facebook/v2.2?locale=zh_TW
printKeyHash method provide hashkey you need
ps
1."C:\Program Files\Java\jdk1.7.0_67\bin\keytool.exe" -exportcert -alias androiddebugkey -keystore C:\Users\linkulife\.android\debug.keystore | C:\openssl\bin\openssl.exe sha1 -binary | C:\openssl\bin\openssl.exe base64
2.http://javatechig.com/android/how-to-get-key-hashes-for-android-facebook-app
如果要取得個人資訊請看
https://developers.facebook.com/docs/android/graph/?locale=zh_TW
https://developers.facebook.com/docs/graph-api/using-graph-api/v2.2?locale=zh_TW#fieldexpansion
2014年10月27日 星期一
androidannotation 獲得view的方法
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.visacard, container, false);
return null;
}
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.visacard, container, false);
return null;
}
VolleyErrorController
package com.ewallet.citygo.controller;
import android.content.Context;
import com.android.volley.*;
import com.android.volley.VolleyError;
import com.ewallet.citygo.utils.Utils;
public class VolleyErrorController {
VolleyError volleyError;
Context context;
public VolleyErrorController(Context context,VolleyError volleyError) {
this.volleyError = volleyError;
this.context=context;
}
TimeoutError timeoutError = new TimeoutError();
//AuthFailureError:如果在做一个HTTP的身份验证,可能会发生这个错误。
//NetworkError:Socket关闭,服务器宕机,DNS错误都会产生这个错误。
//NoConnectionError:和NetworkError类似,这个是客户端没有网络连接。
//ParseError:在使用JsonObjectRequest或JsonArrayRequest时,如果接收到的JSON是畸形,会产生异常。
//SERVERERROR:服务器的响应的一个错误,最有可能的4xx或5xx HTTP状态代码。
//TimeoutError:Socket超时,服务器太忙或网络延迟会产生这个异常。默认情况下,Volley的超时时间为2.5秒。如果得到这个错误可以使用RetryPolicy。
public void showMsg() {
if (volleyError instanceof NoConnectionError) {
Utils.alertWithOneButton(context, "連不上伺服器,請開啟網路");
} else if (volleyError instanceof TimeoutError) {
Utils.alertWithOneButton(context, "網路逾時請洽客服");
} else if (volleyError instanceof AuthFailureError) {
Utils.alertWithOneButton(context, "伺服器認證失敗請洽客服");
} else if (volleyError instanceof ServerError) {
Utils.alertWithOneButton(context, "伺服器連線失敗請洽客服");
} else if (volleyError instanceof NetworkError) {
Utils.alertWithOneButton(context, "伺服器網域找不到 請稍後在試");
} else if (volleyError instanceof ParseError) {
Utils.alertWithOneButton(context, "收到不預期的結果請更新版本");
}
}
}
import android.content.Context;
import com.android.volley.*;
import com.android.volley.VolleyError;
import com.ewallet.citygo.utils.Utils;
public class VolleyErrorController {
VolleyError volleyError;
Context context;
public VolleyErrorController(Context context,VolleyError volleyError) {
this.volleyError = volleyError;
this.context=context;
}
TimeoutError timeoutError = new TimeoutError();
//AuthFailureError:如果在做一个HTTP的身份验证,可能会发生这个错误。
//NetworkError:Socket关闭,服务器宕机,DNS错误都会产生这个错误。
//NoConnectionError:和NetworkError类似,这个是客户端没有网络连接。
//ParseError:在使用JsonObjectRequest或JsonArrayRequest时,如果接收到的JSON是畸形,会产生异常。
//SERVERERROR:服务器的响应的一个错误,最有可能的4xx或5xx HTTP状态代码。
//TimeoutError:Socket超时,服务器太忙或网络延迟会产生这个异常。默认情况下,Volley的超时时间为2.5秒。如果得到这个错误可以使用RetryPolicy。
public void showMsg() {
if (volleyError instanceof NoConnectionError) {
Utils.alertWithOneButton(context, "連不上伺服器,請開啟網路");
} else if (volleyError instanceof TimeoutError) {
Utils.alertWithOneButton(context, "網路逾時請洽客服");
} else if (volleyError instanceof AuthFailureError) {
Utils.alertWithOneButton(context, "伺服器認證失敗請洽客服");
} else if (volleyError instanceof ServerError) {
Utils.alertWithOneButton(context, "伺服器連線失敗請洽客服");
} else if (volleyError instanceof NetworkError) {
Utils.alertWithOneButton(context, "伺服器網域找不到 請稍後在試");
} else if (volleyError instanceof ParseError) {
Utils.alertWithOneButton(context, "收到不預期的結果請更新版本");
}
}
}
2014年10月26日 星期日
關閉小鍵盤
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mainView.getWindowToken(), 0);
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mainView.getWindowToken(), 0);
2014年10月24日 星期五
INTENT中傳遞物件/fragment傳遞物件
傳送的LoginFragment
Bundle bundle = new Bundle();
bundle.putSerializable(BundleIndex.LoginFragment.toString(), user);
MoveStockFragment moveStockFragment = new MoveStockFragment();
TransactionHandler.getInstance().transition(getActivity(), bundle, this, moveStockFragment, R.id.mainFrameLayout);
收到的 MoveStockFragment中
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.movestockfragment, container, false);
Bundle bundle = getArguments();
if(bundle==null){
Utils.instance.log("MoveStockFragment:bundle==null");
}
user = (User) bundle.getSerializable(BundleIndex.LoginFragment.toString());
bundle.remove(BundleIndex.LoginFragment.toString());//要記得刪掉避免再次取得
ButterKnife.inject(this, v);
return v;
}
---------------------------------------------------------
送的ACTIVITY
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putSerializable("FavoriteStoreWrapper", favoriteStoreAryList.get(position));
intent.putExtras(bundle);
intent.setClass(getActivity(), NearByDetailActivity.class);
startActivity(intent);
收的ACTIVITY
Bundle bundle = this.getIntent().getExtras();
favoriteStoreWrapper =
(FavoriteStoreWrapper) getIntent().getSerializableExtra("FavoriteStoreWrapper");
Bundle bundle = new Bundle();
bundle.putSerializable(BundleIndex.LoginFragment.toString(), user);
MoveStockFragment moveStockFragment = new MoveStockFragment();
TransactionHandler.getInstance().transition(getActivity(), bundle, this, moveStockFragment, R.id.mainFrameLayout);
收到的 MoveStockFragment中
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.movestockfragment, container, false);
Bundle bundle = getArguments();
if(bundle==null){
Utils.instance.log("MoveStockFragment:bundle==null");
}
user = (User) bundle.getSerializable(BundleIndex.LoginFragment.toString());
bundle.remove(BundleIndex.LoginFragment.toString());//要記得刪掉避免再次取得
ButterKnife.inject(this, v);
return v;
}
---------------------------------------------------------
送的ACTIVITY
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putSerializable("FavoriteStoreWrapper", favoriteStoreAryList.get(position));
intent.putExtras(bundle);
intent.setClass(getActivity(), NearByDetailActivity.class);
startActivity(intent);
收的ACTIVITY
Bundle bundle = this.getIntent().getExtras();
favoriteStoreWrapper =
(FavoriteStoreWrapper) getIntent().getSerializableExtra("FavoriteStoreWrapper");
Genymotion 如何安裝 Google Play 商店?
http://portable.easylife.tw/3966
http://wiki.rootzwiki.com/Google_Apps#Universal_Packages_2
http://wiki.rootzwiki.com/Google_Apps#Universal_Packages_2
2014年10月23日 星期四
獲得螢幕的寬高.
/**
* 獲得螢幕的寬高.
*
* @return the sreen width height
*/
public void getSreenWidthHeight() {
/*
DisplayMetrics dm = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
m_density = dm.density;
mWidth = dm.widthPixels;
mHeight = dm.heightPixels;
m_dpi = dm.densityDpi;
*/
}
* 獲得螢幕的寬高.
*
* @return the sreen width height
*/
public void getSreenWidthHeight() {
/*
DisplayMetrics dm = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
m_density = dm.density;
mWidth = dm.widthPixels;
mHeight = dm.heightPixels;
m_dpi = dm.densityDpi;
*/
}
日期格式轉換
public static String strtimestampToStr(String strtimestamp){
Timestamp stamp = new Timestamp(Long.parseLong(strtimestamp));
Date date = new Date(stamp.getTime());
return Utils.dateToStr(date);
}
public static String dateToStr(Date date) {
//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date1 = sdf.format(date);
return date1;
// 把日期字串轉為想要的格式
}
把原本是字串的轉乘字串
DateFormat formatter = new SimpleDateFormat("yyyy-MM-DD");
Date mydate = null;
try {
mydate = formatter.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
info2.m_strDate = Utils.dateToStr(mydate);
Timestamp stamp = new Timestamp(Long.parseLong(strtimestamp));
Date date = new Date(stamp.getTime());
return Utils.dateToStr(date);
}
public static String dateToStr(Date date) {
//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date1 = sdf.format(date);
return date1;
// 把日期字串轉為想要的格式
}
把原本是字串的轉乘字串
DateFormat formatter = new SimpleDateFormat("yyyy-MM-DD");
Date mydate = null;
try {
mydate = formatter.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
info2.m_strDate = Utils.dateToStr(mydate);
2014年10月22日 星期三
JsonUtils
/*
*
*/
package com.ewallet.citygo.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;
import com.ewallet.citygo.config.AppConfig;
// TODO: Auto-generated Javadoc
/**
* The Class JsonUtils.
*/
public class JsonUtils {
/**
* The Constant URL.
*/
public static final String URL = AppConfig.PHOTOSERVERIP;
public static final String RETRIEVE_MESSAGE_DETAIL = JsonUtils.URL + "SmartCatchCityGoWsWeb/ws/message/RETRIEVE_MESSAGE_DETAIL";
//public static final String URL = "http://125.227.157.216:9168/";//JsonUtils周邊商家圖庫 2014/08/20 廢棄
public static final String QUERY_NEARBY_BRANCH_BY_CONDITION = "SmartCatchCityGoWsWeb/ws/user/QUERY_NEARBY_BRANCHS_BY_CONDITIONS_AND_PAGING";
// public static final String QUERY_DISTRICT_BRANCHES = "user/QUERY_DISTRICT_BRANCHES_BY_CONDITIONS_AUTO_SORT_AND_PAGING";
public static final String QUERY_MESSAGES_BY_TYPE_PAGING = "SmartCatchCityGoWsWeb/ws/message/QUERY_MESSAGES_BY_TYPE_PAGING";
// public static final String QUERY_SERVICE_NAME_BY_CATEGORY = "SmartCatchCityGoWsWeb/ws/service_category/get_category";
public static final String QUERY_SERVICE_NAME_BY_CATEGORY = "SmartCatchCityGoWsWeb/ws/category/get_category";
public static final String SUCCESS_MESSAGE = "SUCCESS";
public static final String NOT_FOUND = "NOT_FOUND";
/**
* The Constant QUERY_NEARBY_BRANCH.
*/
public static final String QUERY_NEARBY_BRANCH = "user/QUERY_NEARBY_BRANCHS_BY_CONDITIONS_AND_PAGING";
// public static final String QUERY_DISTRICT_BRANCHES = "user/QUERY_DISTRICT_BRANCHES_BY_CONDITIONS_AUTO_SORT_AND_PAGING";
/** The Constant QUERY_MESSAGES_BY_TYPE_PAGING. */
/**
* String convert to json object.
*
* @param value the value
* @return the JSON object
*/
public static JSONObject stringConvertToJsonObject(String value) {
JSONObject object = null;
try {
object = new JSONObject(value);
} catch (Exception e) {
// TODO: handle exception
}
return object;
}
/**
* Post.
*
* @param url the url
* @param json the json
* @return the string
*/
public static String POST(String url, String json) {
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
//Log.d("JsonUtils POST json.toString()", json.toString());
// ** Alternative way to convert Person object to JSON string usin
// Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json.toString(), HTTP.UTF_8);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the
// content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// httpPost.setHeader("user-agent", "Java/1.7.0_17");
// httpPost.setHeader("connection", "keep-alive");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
e.printStackTrace();
}
// 11. return result
Utils.myLog(result);
return result;
}
/**
* Convert input stream to string.
*
* @param inputStream the input stream
* @return the string
* @throws IOException Signals that an I/O exception has occurred.
*/
private static String convertInputStreamToString(InputStream inputStream)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
*
*/
package com.ewallet.citygo.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;
import com.ewallet.citygo.config.AppConfig;
// TODO: Auto-generated Javadoc
/**
* The Class JsonUtils.
*/
public class JsonUtils {
/**
* The Constant URL.
*/
public static final String URL = AppConfig.PHOTOSERVERIP;
public static final String RETRIEVE_MESSAGE_DETAIL = JsonUtils.URL + "SmartCatchCityGoWsWeb/ws/message/RETRIEVE_MESSAGE_DETAIL";
//public static final String URL = "http://125.227.157.216:9168/";//JsonUtils周邊商家圖庫 2014/08/20 廢棄
public static final String QUERY_NEARBY_BRANCH_BY_CONDITION = "SmartCatchCityGoWsWeb/ws/user/QUERY_NEARBY_BRANCHS_BY_CONDITIONS_AND_PAGING";
// public static final String QUERY_DISTRICT_BRANCHES = "user/QUERY_DISTRICT_BRANCHES_BY_CONDITIONS_AUTO_SORT_AND_PAGING";
public static final String QUERY_MESSAGES_BY_TYPE_PAGING = "SmartCatchCityGoWsWeb/ws/message/QUERY_MESSAGES_BY_TYPE_PAGING";
// public static final String QUERY_SERVICE_NAME_BY_CATEGORY = "SmartCatchCityGoWsWeb/ws/service_category/get_category";
public static final String QUERY_SERVICE_NAME_BY_CATEGORY = "SmartCatchCityGoWsWeb/ws/category/get_category";
public static final String SUCCESS_MESSAGE = "SUCCESS";
public static final String NOT_FOUND = "NOT_FOUND";
/**
* The Constant QUERY_NEARBY_BRANCH.
*/
public static final String QUERY_NEARBY_BRANCH = "user/QUERY_NEARBY_BRANCHS_BY_CONDITIONS_AND_PAGING";
// public static final String QUERY_DISTRICT_BRANCHES = "user/QUERY_DISTRICT_BRANCHES_BY_CONDITIONS_AUTO_SORT_AND_PAGING";
/** The Constant QUERY_MESSAGES_BY_TYPE_PAGING. */
/**
* String convert to json object.
*
* @param value the value
* @return the JSON object
*/
public static JSONObject stringConvertToJsonObject(String value) {
JSONObject object = null;
try {
object = new JSONObject(value);
} catch (Exception e) {
// TODO: handle exception
}
return object;
}
/**
* Post.
*
* @param url the url
* @param json the json
* @return the string
*/
public static String POST(String url, String json) {
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
//Log.d("JsonUtils POST json.toString()", json.toString());
// ** Alternative way to convert Person object to JSON string usin
// Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json.toString(), HTTP.UTF_8);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the
// content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// httpPost.setHeader("user-agent", "Java/1.7.0_17");
// httpPost.setHeader("connection", "keep-alive");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
e.printStackTrace();
}
// 11. return result
Utils.myLog(result);
return result;
}
/**
* Convert input stream to string.
*
* @param inputStream the input stream
* @return the string
* @throws IOException Signals that an I/O exception has occurred.
*/
private static String convertInputStreamToString(InputStream inputStream)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
2014年10月21日 星期二
PopupMenu
PopupMenu popup = new PopupMenu(getActivity(), radioMember);
popup.getMenuInflater().inflate(R.menu.onmemberclick, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.EditProfile: {
EditProfile editProfile = new EditProfile_();
editProfile.setMemberFragmentChildFragmentManager(getChildFragmentManager());
FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.replace(R.id.memberFramelayout, editProfile, "editProfile").addToBackStack(null);
ft.commit();
}
case R.id.ChangePw: {
ChangePw changePw = new ChangePw_();
changePw.setMemberFragmentChildFragmentManager(getChildFragmentManager());
FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.replace(R.id.memberFramelayout, changePw, "changePw").addToBackStack(null);
ft.commit();
}
case R.id.ChangeTransactionPw: {
ChangeTransactionPw changeTransactionPw = new ChangeTransactionPw_();
changeTransactionPw.setMemberFragmentChildFragmentManager(getChildFragmentManager());
FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.replace(R.id.memberFramelayout, changeTransactionPw, "changeTransactionPw").addToBackStack(null);
ft.commit();
}
}
return true;
}
});
popup.show();
popup.getMenuInflater().inflate(R.menu.onmemberclick, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.EditProfile: {
EditProfile editProfile = new EditProfile_();
editProfile.setMemberFragmentChildFragmentManager(getChildFragmentManager());
FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.replace(R.id.memberFramelayout, editProfile, "editProfile").addToBackStack(null);
ft.commit();
}
case R.id.ChangePw: {
ChangePw changePw = new ChangePw_();
changePw.setMemberFragmentChildFragmentManager(getChildFragmentManager());
FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.replace(R.id.memberFramelayout, changePw, "changePw").addToBackStack(null);
ft.commit();
}
case R.id.ChangeTransactionPw: {
ChangeTransactionPw changeTransactionPw = new ChangeTransactionPw_();
changeTransactionPw.setMemberFragmentChildFragmentManager(getChildFragmentManager());
FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.replace(R.id.memberFramelayout, changeTransactionPw, "changeTransactionPw").addToBackStack(null);
ft.commit();
}
}
return true;
}
});
popup.show();
2014年10月20日 星期一
2014年10月17日 星期五
ksop2
/*
*
*/
package com.ewallet.citygo.utils;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.util.Log;
import com.ewallet.citygo.bean.TransactionCreateBean;
import com.ewallet.citygo.bean.TransactionStatusBean;
import com.ewallet.citygo.config.AppConfig;
import com.ewallet.citygo.manager.AccountManager;
// TODO: Auto-generated Javadoc
/**
* The Class Transaction.
*/
public class Transaction {
/**
* Creates the.
*
* @param bean the bean
* @param source_id the source_id
* @param source_count the source_count
* @param tpaytype the tpaytype
* @param price the price
* @return true, if successful
*/
public boolean create(TransactionCreateBean bean, int source_id, int source_count, String tpaytype, int price) {
boolean result = false;
SoapObject request = new SoapObject(AppConfig.NAMESPACE, "create");
request.addProperty("source_id", source_id);
request.addProperty("source_count", source_count);
request.addProperty("tpaytype", tpaytype);
request.addProperty("price", price);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(AppConfig.SERVER_SITE + AppConfig.JAVA_TRANSACTION_SITE);
try {
androidHttpTransport.call(AppConfig.SERVER_SITE + AppConfig.JAVA_TRANSACTION_ACTION, envelope);
SoapObject response = (SoapObject) envelope.getResponse();
bean.status = getInt(response, "status");
bean.message = getString(response, "message");
bean.txId = getInt(response, "txId");
AccountManager.getAccountManager().myAccount.setTransactionId(String.valueOf(bean.txId));
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* Listen status.
*
* @param bean the bean
* @param tx_id the tx_id
* @return true, if successful
*/
public boolean listenStatus(TransactionStatusBean bean, int tx_id) {
boolean result = false;
SoapObject request = new SoapObject(AppConfig.NAMESPACE, "listenStatus");
request.addProperty("tx_id", tx_id);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(AppConfig.SERVER_SITE + AppConfig.JAVA_TRANSACTION_SITE);
try {
androidHttpTransport.call(AppConfig.SERVER_SITE + AppConfig.JAVA_TRANSACTION_ACTION, envelope);
SoapObject response = (SoapObject) envelope.getResponse();
bean.status = getInt(response, "tstatus");
Log.v("ListenStatus", String.valueOf(bean.status));
if (bean.status == 1)
result = true;
} catch (Exception e) {
}
return result;
}
/**
* Scan update info.
*
* @param source_id the source_id
* @param source_count the source_count
* @param price the price
* @param dest_id the dest_id
* @param dest_count the dest_count
* @param tx_id the tx_id
* @param issuer the issuer
* @param serial_no the serial_no
* @param card_id the card_id
* @param card_no the card_no
* @return true, if successful
*/
public boolean scanUpdateInfo(int source_id, int source_count, int price,
int dest_id, int dest_count, int tx_id,
String issuer, String serial_no, int card_id, String card_no) {
TransactionStatusBean bean = new TransactionStatusBean();
boolean result = false;
SoapObject request = new SoapObject(AppConfig.NAMESPACE, "scanUpdateInfo");
request.addProperty("source_id", source_id);
request.addProperty("source_count", source_count);
request.addProperty("tpaytype", "1");
request.addProperty("price", price);
request.addProperty("dest_id", dest_id);
request.addProperty("dest_count", dest_count);
request.addProperty("tx_id", tx_id);
request.addProperty("issuer", issuer);
request.addProperty("serial_no", serial_no);
request.addProperty("card_id", card_id);
request.addProperty("card_no", card_no);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(AppConfig.SERVER_SITE + AppConfig.JAVA_TRANSACTION_SITE);
try {
androidHttpTransport.call(AppConfig.SERVER_SITE + AppConfig.JAVA_TRANSACTION_ACTION, envelope);
SoapObject response = (SoapObject) envelope.getResponse();
bean.status = getInt(response, "status");
bean.message = getString(response, "message");
if (getInt(response, "tstatus") == 1)
result = true;
} catch (Exception e) {
}
return result;
}
/**
* Gets the int.
*
* @param response the response
* @param name the name
* @return the int
*/
private int getInt(SoapObject response, String name) {
return Integer.parseInt(response.getProperty(name).toString());
}
/**
* Gets the string.
*
* @param response the response
* @param name the name
* @return the string
*/
private String getString(SoapObject response, String name) {
return response.getProperty(name).toString();
}
}
*
*/
package com.ewallet.citygo.utils;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.util.Log;
import com.ewallet.citygo.bean.TransactionCreateBean;
import com.ewallet.citygo.bean.TransactionStatusBean;
import com.ewallet.citygo.config.AppConfig;
import com.ewallet.citygo.manager.AccountManager;
// TODO: Auto-generated Javadoc
/**
* The Class Transaction.
*/
public class Transaction {
/**
* Creates the.
*
* @param bean the bean
* @param source_id the source_id
* @param source_count the source_count
* @param tpaytype the tpaytype
* @param price the price
* @return true, if successful
*/
public boolean create(TransactionCreateBean bean, int source_id, int source_count, String tpaytype, int price) {
boolean result = false;
SoapObject request = new SoapObject(AppConfig.NAMESPACE, "create");
request.addProperty("source_id", source_id);
request.addProperty("source_count", source_count);
request.addProperty("tpaytype", tpaytype);
request.addProperty("price", price);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(AppConfig.SERVER_SITE + AppConfig.JAVA_TRANSACTION_SITE);
try {
androidHttpTransport.call(AppConfig.SERVER_SITE + AppConfig.JAVA_TRANSACTION_ACTION, envelope);
SoapObject response = (SoapObject) envelope.getResponse();
bean.status = getInt(response, "status");
bean.message = getString(response, "message");
bean.txId = getInt(response, "txId");
AccountManager.getAccountManager().myAccount.setTransactionId(String.valueOf(bean.txId));
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* Listen status.
*
* @param bean the bean
* @param tx_id the tx_id
* @return true, if successful
*/
public boolean listenStatus(TransactionStatusBean bean, int tx_id) {
boolean result = false;
SoapObject request = new SoapObject(AppConfig.NAMESPACE, "listenStatus");
request.addProperty("tx_id", tx_id);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(AppConfig.SERVER_SITE + AppConfig.JAVA_TRANSACTION_SITE);
try {
androidHttpTransport.call(AppConfig.SERVER_SITE + AppConfig.JAVA_TRANSACTION_ACTION, envelope);
SoapObject response = (SoapObject) envelope.getResponse();
bean.status = getInt(response, "tstatus");
Log.v("ListenStatus", String.valueOf(bean.status));
if (bean.status == 1)
result = true;
} catch (Exception e) {
}
return result;
}
/**
* Scan update info.
*
* @param source_id the source_id
* @param source_count the source_count
* @param price the price
* @param dest_id the dest_id
* @param dest_count the dest_count
* @param tx_id the tx_id
* @param issuer the issuer
* @param serial_no the serial_no
* @param card_id the card_id
* @param card_no the card_no
* @return true, if successful
*/
public boolean scanUpdateInfo(int source_id, int source_count, int price,
int dest_id, int dest_count, int tx_id,
String issuer, String serial_no, int card_id, String card_no) {
TransactionStatusBean bean = new TransactionStatusBean();
boolean result = false;
SoapObject request = new SoapObject(AppConfig.NAMESPACE, "scanUpdateInfo");
request.addProperty("source_id", source_id);
request.addProperty("source_count", source_count);
request.addProperty("tpaytype", "1");
request.addProperty("price", price);
request.addProperty("dest_id", dest_id);
request.addProperty("dest_count", dest_count);
request.addProperty("tx_id", tx_id);
request.addProperty("issuer", issuer);
request.addProperty("serial_no", serial_no);
request.addProperty("card_id", card_id);
request.addProperty("card_no", card_no);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(AppConfig.SERVER_SITE + AppConfig.JAVA_TRANSACTION_SITE);
try {
androidHttpTransport.call(AppConfig.SERVER_SITE + AppConfig.JAVA_TRANSACTION_ACTION, envelope);
SoapObject response = (SoapObject) envelope.getResponse();
bean.status = getInt(response, "status");
bean.message = getString(response, "message");
if (getInt(response, "tstatus") == 1)
result = true;
} catch (Exception e) {
}
return result;
}
/**
* Gets the int.
*
* @param response the response
* @param name the name
* @return the int
*/
private int getInt(SoapObject response, String name) {
return Integer.parseInt(response.getProperty(name).toString());
}
/**
* Gets the string.
*
* @param response the response
* @param name the name
* @return the string
*/
private String getString(SoapObject response, String name) {
return response.getProperty(name).toString();
}
}
2014年10月16日 星期四
gson
public static String toJson(Object obj) {
ObjectMapper om = new ObjectMapper();
om.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.FALSE);
// 忽略新增未知 回傳參數
om.setSerializationInclusion(Inclusion.NON_NULL);
try {
return om.writeValueAsString(obj);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
return null;
}
public static <T> T fromJson(String src, Class<T> t) {
ObjectMapper om = new ObjectMapper();
om.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.FALSE);
// 忽略新增未知 回傳參數
try {
return ((T) om.readValue(src, t));
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
return null;
}
ObjectMapper om = new ObjectMapper();
om.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.FALSE);
// 忽略新增未知 回傳參數
om.setSerializationInclusion(Inclusion.NON_NULL);
try {
return om.writeValueAsString(obj);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
return null;
}
public static <T> T fromJson(String src, Class<T> t) {
ObjectMapper om = new ObjectMapper();
om.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.FALSE);
// 忽略新增未知 回傳參數
try {
return ((T) om.readValue(src, t));
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
return null;
}
2014年10月12日 星期日
struts2 ServletConfig
http://www.codejava.net/frameworks/struts/reading-parameters-from-webxml-in-struts2-action-class
<context-param>
<param-name>host</param-name>
<param-value>192.168.123.233</param-value>
</context-param>
String conf = ServletActionContext.getServletContext().getInitParameter("host");
System.out.println("Login,conf: "+conf);
<context-param>
<param-name>host</param-name>
<param-value>192.168.123.233</param-value>
</context-param>
String conf = ServletActionContext.getServletContext().getInitParameter("host");
System.out.println("Login,conf: "+conf);
2014年10月9日 星期四
Android. Layout background stretches
如果用 ScrollView在最外層 會導致背景拉長 解決辦法
http://stackoverflow.com/questions/11448416/android-layout-background-stretches
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/m_bg"
android:gravity="center" />
//don't use this if you want scrollView`
// getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
se
http://stackoverflow.com/questions/11448416/android-layout-background-stretches
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/m_bg"
android:gravity="center" />
//don't use this if you want scrollView`
// getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
se
2014年10月6日 星期一
join
select transaction.* ,member.*, memberowner.* ,store.* from transaction
right join member on transaction.`memberId`=member.`memberId`
right join memberowner on transaction.`mo_sn` =memberowner.`mo_sn`
right join store on transaction.`storeId`=store.storeId
right join member on transaction.`memberId`=member.`memberId`
right join memberowner on transaction.`mo_sn` =memberowner.`mo_sn`
right join store on transaction.`storeId`=store.storeId
2014年10月5日 星期日
小鍵盤往上頂
小鍵盤往上頂
1.activity設定
<activity
android:name=".MainActivity"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateUnspecified|adjustResize">
2.layout上ScrollView作為根 並且設定粗體
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="@+id/butto_register"
android:windowSoftInputMode="adjustPan">
//don't use this if you want scrollView`
// getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
install git on server
https://www.digitalocean.com/community/tutorials/how-to-install-git-on-a-centos-6-4-vps
http://git-scm.com/book/en/Getting-Started-First-Time-Git-Setup
http://git-scm.com/book/en/Getting-Started-First-Time-Git-Setup
git bash
git bash指令
切換資料夾
cd "D:/keith/android/JrSysDev"
git init
git remote add sci_ewallet https://adsl99801@bitbucket.org/sciewallet/sci-ewallet.git
如果不能push 要先
http://git-scm.com/book/zh-tw/Git-%E5%9F%BA%E7%A4%8E-%E6%AA%A2%E8%A6%96%E6%8F%90%E4%BA%A4%E7%9A%84%E6%AD%B7%E5%8F%B2%E8%A8%98%E9%8C%84
如果要用local的蓋過遠端的
git push --force ori
查詢歷史某個字串
切換資料夾
cd "D:/keith/android/JrSysDev"
git init
git remote add sci_ewallet https://adsl99801@bitbucket.org/sciewallet/sci-ewallet.git
如果不能push 要先
fetch 再merge 再pull 就可以push了
aAav1432.cc18tv.com/http://git-scm.com/book/zh-tw/Git-%E5%9F%BA%E7%A4%8E-%E6%AA%A2%E8%A6%96%E6%8F%90%E4%BA%A4%E7%9A%84%E6%AD%B7%E5%8F%B2%E8%A8%98%E9%8C%84
如果要用local的蓋過遠端的
git push --force ori
查詢歷史某個字串
git rev-list --all | xargs git grep expression
2014年9月27日 星期六
hibernate GETconstraintName/自動產生class
http://docs.jboss.org/tools/OLD/2.0.0.GA/hibernatetools/en/html_single/index.html
http://hibernate.org/tools/
http://tools.jboss.org/features/hibernate.html
e.getErrorCode() :1452
e.getConstraintName() :null
e.getMessage() :could not execute statement
e.getCause().getMessage(() :Cannot add or update a child row: a foreign key constraint fails (`ewallet`.`transaction`, CONSTRAINT `transaction_ibfk_2` FOREIGN KEY (`storeId`) REFERENCES `store` (`storeId`) ON DELETE CASCADE ON UPDATE CASCADE)
package com.transaction;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.hibernate.exception.ConstraintViolationException;
import com.HibernateUtil;
import com.Jdbcmysql;
import com.QueryTool;
import com.Tool;
import com.WebConfig;
import com.google.gson.Gson;
import com.hibernatebean.Store;
import com.hibernatebean.Transaction;
import com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException;
import com.object.ForgotPwObject;
import com.object.RegisterTransactionObject;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class RegisterTransaction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = -3094866975438328785L;
private HashMap<String, Object> registerTransactionReturnMes;
public HashMap<String, Object> getRegisterTransactionReturnMes() {
return registerTransactionReturnMes;
}
public void setRegisterTransactionReturnMes(HashMap<String, Object> registerTransactionReturnMes) {
this.registerTransactionReturnMes = registerTransactionReturnMes;
}
int effectLines = 0;
Jdbcmysql jdbcmysql;
String preparedStatementSql;
private HibernateUtil hibernateUtil;
public String execute() {
registerTransactionReturnMes = new HashMap<String, Object>();
// test();
ActionContext context = ActionContext.getContext();
HttpServletRequest request = (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST);
/*
* String encodeData = request.getParameter("encodeData"); Tool tool =
* new Tool(); Gson gson = new Gson(); RegisterTransactionObject
* registerTransactionObject = new RegisterTransactionObject();
* registerTransactionObject =
* gson.fromJson(tool.decryptionToString(encodeData),
* RegisterTransactionObject.class);
*/
String storeId = request.getParameter("storeId");
String price = request.getParameter("price");
// jdbcmysql = new Jdbcmysql("ewallet", WebConfig.DatabaseIp);
try {
hibernateUtil = new HibernateUtil();
Transaction transaction = new Transaction();
Store store = new Store();
store.setStoreId(Integer.parseInt(storeId));
transaction.setStore(store);
transaction.setPrice(Integer.parseInt(price));
hibernateUtil.sessionBeginTransaction();
int transactionId = (Integer) hibernateUtil.getSession().save(transaction);
hibernateUtil.commitTransactionAndClose();
registerTransactionReturnMes.put("issus", "1");
registerTransactionReturnMes.put("msg", "註冊交易成功");
registerTransactionReturnMes.put("transactionId", transactionId);
} catch (ConstraintViolationException e) {
System.out.println("e.getErrorCode() :" + e.getErrorCode());
System.out.println("e.getConstraintName() :" + e.getConstraintName());
System.out.println("e.getMessage() :" + e.getMessage());
System.out.println("e.getCause().getMessage(() :" + e.getCause().getMessage());
} catch (Exception e) {
e.printStackTrace();
hibernateUtil.close();
return SUCCESS;
}
hibernateUtil.close();
return SUCCESS;
}
}
2014年9月24日 星期三
service mysqld restart 查看被占用的port
http://stackoverflow.com/questions/5310945/deployment-errorstarting-of-tomcat-failed-the-server-port-8080-is-already-in-u
查看被占用的port
netstat -tulpn | grep 'your_port_number'
kill -9 248
service mysqld restart
[mysql安裝位置]
/var/lib/mysql
SHOW PROCESSLIST
2014年9月23日 星期二
zbar in android studio
https://github.com/dm77/ZBarScanner/tree/master/ZBarScannerLibrary
https://github.com/ZBar/ZBar/tree/master/android
https://groups.google.com/forum/#!msg/adt-dev/nQobKd2Gl_8/ctDp9viWaxoJ
http://stackoverflow.com/questions/17340240/jni-folder-in-android-studio/22488155#22488155
http://stackoverflow.com/questions/16952388/android-studio-zbar
Did anyone of you noticed that this process include the .so files twice into the final apk? I recently switched to Android Studio and started using Gradle to build my Android project and I've got a weird behavior. Basically, I have a lib in app/src/main/jniLibs, divided in two folders: armeabi and armeabi-7va. The problem is that since I use Gradle, the APK file is twice more heavier. The reason is that Gradle copy the *.so files twice in the APK at two different locations: - lib/ - main/jniLibs/ When I used to build using Eclipse, everything was fine, *.so files were copied only one time. Does anyone know if there is a way to avoid this behavior? Is this a bug in Gradle or am I doing something wrong?
2014年9月22日 星期一
otto+androidannotations
package com.ewallet.citygo.fragment.home;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import com.ewallet.citygo.R;
import com.ewallet.citygo.otto.OttoBus;
import com.ewallet.citygo.otto.UpdateTitleEvent;
import com.ewallet.citygo.utils.Utils;
import com.squareup.otto.Subscribe;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
@EFragment(R.layout.forgotpw)
public class ForgotPw extends Fragment {
@ViewById
EditText etCode;
@ViewById
EditText etpw1;
@ViewById
EditText etpw2;
@ViewById
Button butCancle;
@ViewById
Button butSure;
@Bean
OttoBus bus;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//v = inflater.inflate(R.layout.forgotpw, container, false);
bus.post(new UpdateTitleEvent("Clicks"));
// Utils.alert(getActivity(), "post");
return null;
}
@Click // When R.id.butSure button is clicked
void butSure() {
try{
if(etpw1.getText().length()>1){
}
//Utils.alert(getActivity(), "按了按鈕");
// etpw1.setText("ffe");
}catch (Exception e){
e.printStackTrace();
Utils.alert(getActivity(), "請不要留空!");
}
}
@Click
void butCancle() {
onUpdateTitle(new UpdateTitleEvent("title"));
}
@Subscribe
public void onUpdateTitle(UpdateTitleEvent event) {
etCode.setText(event.title);
Utils.alert(getActivity(), "Subscribe!"+event.title);
}
}
</pre>
2014年9月18日 星期四
2014年9月16日 星期二
Google Analytics_TrackedFragment
https://developers.google.com/analytics/devguides/collection/android/v4/events
把要用的extends TrackedFragment
package com.ewallet.sdk;
使用方法:trackedFragmentSetupEvent(v,"button5");
把要用的extends TrackedFragment
package com.ewallet.sdk;
使用方法:trackedFragmentSetupEvent(v,"button5");
要顯示的 code
import com.ewallet.citygo.CGApplication;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.Fields;
import com.google.analytics.tracking.android.MapBuilder;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.HitBuilders.EventBuilder;
import com.google.android.gms.analytics.Tracker;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.Button;
public class TrackedFragment extends Fragment {
private Tracker tracker;
private String activityId;
private String fragmentId;
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.tracker = CGApplication.getInstance().getTracker(CGApplication.TrackerName.APP_TRACKER);
this.fragmentId = getClass().getSimpleName();
this.activityId = getActivity().getClass().getSimpleName();
}
@Override
public void onResume() {
super.onResume();
//this.tracker.set(Fields.SCREEN_NAME, getClass().getSimpleName());
this.tracker.send( MapBuilder.createAppView().set("page:", activityId+":"+fragmentId).build() );
}
public void trackedFragmentSetupEvent(View v, String labelId) {
EventBuilder h=new HitBuilders.EventBuilder();
h.setCategory(activityId);
h.setAction(fragmentId);
h.setLabel(labelId);
this.tracker.send(h.build());
}
}
訂閱:
意見 (Atom)

