廣告

顯示具有 java 標籤的文章。 顯示所有文章
顯示具有 java 標籤的文章。 顯示所有文章

2017年4月21日 星期五

[java] Deep clone

使用原因

  Map a = new HashMap();
  Map b = new HashMap();

  a.put("1","a");
  a.put("2", "b");

  b.remove("1");
//此時 a的"1"也會被rm掉



usage:
Map> tempMap = DeepClone.deepClone(conditionMap);


package com.ws.util;

import java.lang.reflect.Array;
import java.util.*;

/**
* Created by 1409035 lewisli on 2016/11/30.
*/
public final class DeepClone {

  private DeepClone(){}

  @SuppressWarnings("unchecked")
  public static  X deepClone(final X input) {
  if (input == null) {
  return input;
  } else if (input instanceof Map) {
  return (X) deepCloneMap((Map) input);
  } else if (input instanceof Collection) {
  return (X) deepCloneCollection((Collection) input);
  } else if (input instanceof Object[]) {
  return (X) deepCloneObjectArray((Object[]) input);
  } else if (input.getClass().isArray()) {
  return (X) clonePrimitiveArray((Object) input);
  }

  return input;
  }

  @SuppressWarnings("unchecked")
  private static Object clonePrimitiveArray(final Object input) {
  final int length = Array.getLength(input);
  final Object copy = Array.newInstance(input.getClass().getComponentType(), length);
  // deep clone not necessary, primitives are immutable
  System.arraycopy(input, 0, copy, 0, length);
  return copy;
  }

  @SuppressWarnings("unchecked")
  private static  E[] deepCloneObjectArray(final E[] input) {
  final E[] clone = (E[]) Array.newInstance(input.getClass().getComponentType(), input.length);
  for (int i = 0; i < input.length; i++) {
  clone[i] = deepClone(input[i]);
  }

  return clone;
  }

  @SuppressWarnings("unchecked")
  private static  Collection deepCloneCollection(final Collection input) {
  Collection clone;
  // this is of course far from comprehensive. extend this as needed
  if (input instanceof LinkedList) {
  clone = new LinkedList();
  } else if (input instanceof SortedSet) {
  clone = new TreeSet();
  } else if (input instanceof Set) {
  clone = new HashSet();
  } else {
  clone = new ArrayList();
  }

  for (E item : input) {
  clone.add(deepClone(item));
  }

  return clone;
  }

  @SuppressWarnings("unchecked")
  private static  Map deepCloneMap(final Map map) {
  Map clone;
  // this is of course far from comprehensive. extend this as needed
  if (map instanceof LinkedHashMap) {
  clone = new LinkedHashMap();
  } else if (map instanceof TreeMap) {
  clone = new TreeMap();
  } else {
  clone = new HashMap();
  }

  for (Map.Entry entry : map.entrySet()) {
  clone.put(deepClone(entry.getKey()), deepClone(entry.getValue()));
  }

  return clone;
  }
}


ref: http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value

2016年9月22日 星期四

[java] dynamic key-value set from config.properties


config.properties
terminalID =abStoreA1: 11199942, abStoreWeekend: 11199943, abStoreEP: 11199944


LoadPropertyUtil.java
public class LoadPropertyUtil {

    private static Map mapTerminalID = new HashMap();

    public final static String merchantID = PropertyLoader.getInstance().getValue(Constants.MERCHANT_ID_KEY);

    public final static String authMessageType = PropertyLoader.getInstance().getValue(Constants.AUTH_MESSAGE_TYPE_KEY);
    public final static String authProcessingCode = PropertyLoader.getInstance().getValue(Constants.AUTH_PROCESSING_CODE_KEY);
    public final static String authPosEntryMode = PropertyLoader.getInstance().getValue(Constants.AUTH_POSENTRYMODE_KEY);

    public final static String inquireAuthMessageType = PropertyLoader.getInstance().getValue(Constants.INQUIRE_AUTH_MESSAGE_TYPE_KEY);
    public final static String inquireAuthProcessingCode = PropertyLoader.getInstance().getValue(Constants.INQUIRE_AUTH_PROCESSING_CODE_KEY);
    public final static String inquireAuthPosEntryMode = PropertyLoader.getInstance().getValue(Constants.INQUIRE_AUTH_POSENTRYMODE_KEY);

    static {
      /**
        * split the tid property "srcProject1:TID1,srcProject2:TID2,srcProject3:TID3"
        */
      String[] tIDs = PropertyLoader.getInstance().getValue(Constants.TERMINAlID_KEY).split(",");
      for (String string : tIDs) {
        String[] pair = string.split(":");
        if(pair.length == 2)
            mapTerminalID.put(pair[0].trim(), pair[1].trim());
      }
    }

    public static String getTerminalID(String srcProject) {
      return mapTerminalID.get(srcProject);
    }

    public static boolean containsSrcProjectName(String srcProject) {
      if (srcProject!=null && srcProject.length()>0) {
        return mapTerminalID.containsKey(srcProject);
      }
      return false;
    }
}



PropertyLoader.java
public class PropertyLoader {
  private static PropertyLoader instance = null;
  private Properties props = null;

  /* Singleton Design Pattern */
  private PropertyLoader() {
      try {
        props = new Properties();
        props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(Constants.PROPS_FILE_NAME));
      } catch (IOException e) {
        e.printStackTrace();
      }
  }

  public static synchronized PropertyLoader getInstance() {
      if (instance == null)
        instance = new PropertyLoader();
      return instance;
  }

  public String getValue(String propKey) {
      return this.props.getProperty(propKey);
  }
}



using example
LoadPropertyUtil.getTerminalID("abStoreA1")

[java] Extract digits from a string in Java


A:
str.replaceAll("[^0-9]", "")

B:
str.replaceAll("\\D+","")

C:
public static String stripNonDigits(
  final CharSequence input /* inspired by seh's comment */){
  final StringBuilder sb = new StringBuilder(
  input.length() /* also inspired by seh's comment */);
  for(int i = 0; i < input.length(); i++){
  final char c = input.charAt(i);
  if(c > 47 && c < 58){
  sb.append(c);
  }
  }
  return sb.toString();}


http://stackoverflow.com/questions/4030928/extract-digits-from-a-string-in-java

[java] ftp upload fail (enterLocalPassiveMode)


ftpClient .connect (Constants . FTP_URL) ;
ftpClient .login (Constants . FTP_ID, Constants . FTP_PWD) ;
ftpClient .enterLocalPassiveMode ();

[java] multipart/form-data POST request using Java  | mailgun with attachment


        CredentialsProvider credsProvider = new BasicCredentialsProvider();

        credsProvider.setCredentials(

                new AuthScope(HOST_NAME, PORT),

                new UsernamePasswordCredentials(USER_NAME, TOKEN));

        CloseableHttpClient httpclient = HttpClients.custom()

                .setDefaultCredentialsProvider(credsProvider)

                .build();

        try {

            HttpPost httpPost = new HttpPost(BASE_URL + EMAIL_API_NAME);


            MultipartEntityBuilder builder = MultipartEntityBuilder.create();


            builder.addBinaryBody("attachment", new File("D:/opt/test.pdf"), ContentType.APPLICATION_OCTET_STREAM, "file.ext");

            builder.addTextBody("from", FROM_ADDRESS, ContentType.APPLICATION_JSON);

            builder.addTextBody("to", toEmail, ContentType.APPLICATION_JSON);

            builder.addTextBody("bcc", bcc, ContentType.APPLICATION_JSON);

            builder.addTextBody("subject", subject, ContentType.APPLICATION_JSON);

            builder.addTextBody("html", this.loadTemplate(template, values), ContentType.APPLICATION_JSON);

            HttpEntity multipart = builder.build();

            httpPost.setEntity(multipart);

            CloseableHttpResponse response2 = httpclient.execute(httpPost);

            log.info(response2.toString());


            try {

                System.out.println(response2.getStatusLine());

                HttpEntity entity2 = response2.getEntity();

                // do something useful with the response body

                // and ensure it is fully consumed

                EntityUtils.consume(entity2);

            } finally {

                response2.close();

            }

        } finally {

            httpclient.close();

        }


ref:http://stackoverflow.com/questions/1378920/how-can-i-make-a-multipart-form-data-post-request-using-java

[java] isKeysExistInMap (keys ,map )



package test;

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

public class testMapContainMultiKey {

       public static void main( String[] args ) {
             // TODO Auto-generated method stub

             ArrayList< String> keys = new ArrayList< String> ();
            keys .add ("a" );
            keys .add ("b" );

             HashMap< String, String > map = new HashMap<> ();
            map .put ("a" , "a" );
            map .put ("c" , "b" );

             System. out .println ( isKeysExistInMap (keys ,map ) );


       }

       public static boolean  isKeysExistInMap( ArrayList< String> keys , HashMap  map ) {
             boolean result = true;
             for (String key : keys) {
                 result = map. containsKey (key );
                 if (result == false ) {
                     return result;
                 }
             }
             return result;
       }

}


2016年6月8日 星期三

Hibernate paging get error result if row have same value


Query queryHot = session.createQuery(
   "from HotPost ORDER BY popularity DESC");

queryHot.setFirstResult((page - 1) * pageSize);
queryHot.setMaxResults(pageSize);

solve:
Query queryHot = session.createQuery(
   "from HotPost ORDER BY popularity DESC,id");
==================================
Before:
id   popularity 
1     9   |
2     8   |  page 1
3     8   |

5     8   |
6     7   |  page 2
7     5   |

AFTER:
id   popularity 
1     9  |
2     8  |  page 1
3     8  |

4     8  |
5     7  |  page 2
6     5  |


2016年5月19日 星期四

Hibernate  one-to-one mapping cautions


正確用法
@OneToOne(mappedBy = "post")
@JsonView(View.Detail.class)
private HotPost hotPost;

一開始犯傻
@OneToOne(mappedBy = "post")
@JsonView(View.Detail.class)
Set hotpost = new HashSet<>(0);
CautionsCautionsCautions
log只會說:Unknown mappedBy in: com.ws.pojo.Post.hotPost, referenced property unknown: java.util.Set.post


but @OneToMany
remember to use Set


ref:




Hibernate batch process


 //in pojo (java bean)
      @BatchSize(size=5)
------------------------------------------------
      public void insertOldPost2HotPost() throws Exception{
       
       Session session = sessionFactory.getCurrentSession();

        @SuppressWarnings("unchecked")
        List posts = session.createQuery("from Post ").list();
        int itCount=0;
        for(Iterator it = posts.iterator(); it.hasNext(); ) {

            itCount++;

            Post post = (Post) it.next();

            HotPost hotPost = new HotPost(post);
            session.saveOrUpdate(hotPost);

            if (itCount % 5 == 0) {
            
                session.flush();
                session.clear();
            }
        }
    }


ref:


2016年5月10日 星期二

Spring MVC @JsonView使用详解


     public class View {
      interface Summary {}
      interface SummaryWithDetail extends Summary{}
    }
    -----------------------------------
    public class User {
      @JsonView(View.Summary.class)
      private Long id;
      @JsonView(View.SummaryWithDetail.class)
      private String firstname;
    }
    -----------------------------------
    @RequestMapping("/user")[
    @JsonView(View.Summary.class)
    //or @JsonView(View.SummaryWithDetail.class)
    public List getUsers(){
     return userService.listUsers();
    }
    -----------------------------------
    result of @JsonView(View.Summary.class)
    [
     {
        "id": 70,
     }
    ]

    result of @JsonView(View.SummaryWithDetail.class)
    [
     {
        "id": 70,
        "firstname": 222
     }
    ]


2016年3月28日 星期一

Hibernate openSession() vs getCurrentSession()


      SessionFactory.openSession():
      always opens a new session that you have to
      close once you are done with the operations.
     
      SessionFactory.getCurrentSession():
      returns a session bound to a context - you don't need to close this. 
     
      should always use "one session per request" or "one session per transaction"
      In one application, if the DAO layer, using Spring hibernate,
      control the life cycle via Spring session to ,

      First choice  getCurrentSession ().

2016年3月17日 星期四

Usage of @JsonView (annotation of spring)


    public class View {
      interface Summary {}
      interface SummaryWithDetail extends Summary{}
    }
    -----------------------------------
    public class User { 
      @JsonView(View.Summary.class) 
      private Long id; 
      @JsonView(View.SummaryWithDetail.class) 
      private String firstname; 
    }
    -----------------------------------
    @RequestMapping("/user")
    @JsonView(View.Summary.class) 
    //or @JsonView(View.SummaryWithDetail.class) 
    public List getUsers(){
     return userService.listUsers();
    }
    -----------------------------------
    result of @JsonView(View.Summary.class)
    [
     {
        "id": 70,
     }
    ]
    
    result of @JsonView(View.SummaryWithDetail.class)
    [
     {
        "id": 70,
        "firstname": 222
     }
    ]

ref:
http://www.jianshu.com/p/633d83dd303b#

2015年6月15日 星期一

XMLHttpRequest cannot load URL 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

ws為spring+restful
前端為html+ajax

新增下列程式
package com.cihm.controller;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

@Component
public class SimpleCORSFilter implements Filter {

 public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
  HttpServletResponse response = (HttpServletResponse) res;
  response.setHeader("Access-Control-Allow-Origin", "*");
  response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
  response.setHeader("Access-Control-Max-Age", "3600");
  response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
  chain.doFilter(req, res);
 }

 public void init(FilterConfig filterConfig) {}

 public void destroy() {}

}


web.xml添加
 
       SimpleCORSFilter
       
        com.cihm.controller.SimpleCORSFilter
       
     
     
    
    SimpleCORSFilter
    /*
    


參考https://spring.io/guides/gs/rest-service-cors/

2015年6月7日 星期日

[java][hibernate] HQL not work because i add constructor with parameter


今天遇到一個問題,就是我的HQL一直不work,

後來看了我與資料庫對應的物件,

在看了這篇http://stackoverflow.com/questions/4488716/java-default-constructor

因為HQL(hibernate query language) need default constructor or non-parameter constructor,

而我那個物件少了non-parameter constructor,因為我有一個constructor是帶有變數的,

根據定義,只要有定義constructor的話,default的就不會產生,所以我需要再新增一個

行為跟default一模一樣的constructor,也就是non-parameter constructor.

2015年5月28日 星期四

[java] html parser use jsoup lib

complete project https://github.com/cihm/JavaHtmlParser
package com.test.parser;

import java.net.URL;
import java.util.Iterator;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class testJsoup {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
        //online parser 
  //http://try.jsoup.org/~LGB7rk_atM2roavV0d-czMt3J_g
  try{
   
   Document doc = Jsoup.connect("http://en.wikipedia.org/").get();
   Elements newsHeadlines = doc.select("#mp-itn b a");
   // Get first table

   Element table = doc.select("table").first();
   // Get td Iterator
   Iterator <Element> ite = table.select("td").iterator();
   // Print content
   int cnt = 0;
   while (ite.hasNext()) {
    cnt++;
    System.out.println("Value " + cnt + ": " + ite.next().text());
   }
  }catch(Exception e){
   e.printStackTrace();
  }
  
         
 }

}


2015年5月21日 星期四

[gson] read / write large file use gson stream

in order to handle with read/write "big" file,
so use gson stream



read
    File jsonInputFile = new File(path);
		FileInputStream fisInput;
		JsonReader reader;
		try {
			fisInput = new FileInputStream(jsonInputFile);
			reader = new JsonReader(new InputStreamReader(fisInput, "UTF-8"));

			ArrayList<Map> categoryALHM = gson.fromJson(reader,
					ArrayList.class);
			
			if(null == categoryALHM || categoryALHM.size() == 0){
				log.info(path+":is null or empty");
				return false;
			}
			reader.close();
			fisInput.close();

		} catch (Exception e) {
			log.info(e.getMessage().toString());
			return false;
		}

write
	 File jsonFile = new File(originalDatpath);
		FileOutputStream fos;
		JsonWriter writer;
		try {
			fos = new FileOutputStream(jsonFile);
			writer = new JsonWriter(new OutputStreamWriter(fos, "UTF-8"));
			writer.setIndent(" ");

			Map getCategoryMap = JsonTool.Json2Map(IbobarDataUtil
					.viewCategory());
			ArrayList<HashMap<String, Object>> getCategoryMapList = (ArrayList) getCategoryMap
					.get("list");

			log.info("original category:" + getCategoryMapList);
			
			gson.toJson(getCategoryMapList, ArrayList.class, writer);
			
			writer.close();
			fos.flush();
			fos.close();

		} catch (Exception e) {
			log.info(e.getMessage().toString());
		}

read and write
	File jsonInputFile = new File(organizeDataPath);
		File jsonOutputFile = new File(usingDatPath);

		FileOutputStream fosOutput;
		FileInputStream fisInput;

		JsonWriter writer;
		JsonReader reader;

		try {
			fosOutput = new FileOutputStream(jsonOutputFile);
			writer = new JsonWriter(new OutputStreamWriter(fosOutput, "UTF-8"));
			writer.setIndent(" ");

			fisInput = new FileInputStream(jsonInputFile);
			reader = new JsonReader(new InputStreamReader(fisInput, "UTF-8"));

			writer.beginObject();
			reader.beginObject();

			while (reader.hasNext()) {
				String key = reader.nextName();

				List<Map> bookOranizeList = gson.fromJson(reader,
						ArrayList.class);
				
				writer.name(key);
				gson.toJson(bookOranizeList, ArrayList.class, writer);
			}

			writer.endObject();
			writer.close();
			fosOutput.flush();
			fosOutput.close();

			reader.endObject();
			reader.close();
			fisInput.close();

		} catch (Exception e) {
			log.info(e.getMessage().toString());
		}

2015年5月10日 星期日

[searchEngine] [java] Build solr index & search it

this complete project can download from my github
https://github.com/cihm/GradleAndSolr





SolrSearch.java
package com.job;

import java.net.MalformedURLException;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;

import com.vo.SolrArgVo;

public class SolrSearch {

	public static Logger log = Logger.getLogger(SolrSearch.class.getName());

	public boolean solrSearch(SolrArgVo solrArgVo) throws MalformedURLException, SolrServerException{

		//HttpSolrServer solr = new HttpSolrServer("http://10.24.100.237:8080/solr/collection1");
		HttpSolrServer solr = new HttpSolrServer("http://192.168.22.148:8080/solr/collection1");
		SolrQuery query = new SolrQuery();
		
		//英文是精確比對,中文是模糊比對
		//查詢條件
	
		
		query.setQuery( "*:*" );
		//query.setFilterQueries("name:" + "登基", "description:" + "登基", "channel:" + "ylib");
		String keyword = solrArgVo.getKetWord();
		String channel = solrArgVo.getChanneCode();
		query.addFilterQuery("channel:" + channel);
		query.setQuery("name:"+keyword+" OR description:"+keyword); 
		//query.setQuery("name:"+"王道  AND currency:"+"NTD");
		
		
		
		
		//can use to be get book by cat 
		query.setRows(100); //get row of query result//default is 10
		//query.setQuery("title:國王");
		//query.setQuery("title: art");
	    
	    QueryResponse response = solr.query(query);
	    SolrDocumentList results = response.getResults();
	    System.out.println("NumFound="+results.getNumFound());
	    System.out.println("SIZE="+results.size());
	    //System.out.println(results);
	    //System.out.println(results.get(0).get("title"));
	      for (int i = 0; i < results.size(); ++i) {
	          System.out.println("result "+i+"= "+results.get(i).get("id"));
	    	  System.out.println("result "+i+"="+ results.get(i));
	      }
		
		
		
		return true;
	}
	
}


SolrBuildIndex.java
package com.job;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.BinaryRequestWriter;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.common.SolrInputDocument;
import com.util.DataUtil;
import com.util.SolrConstants;

public class SolrBuildIndex {

	public static Logger log = Logger.getLogger(SolrBuildIndex.class.getName());

	public boolean solrBuildIndex() throws MalformedURLException, SolrServerException,IOException{

		
		 HttpSolrServer server = new HttpSolrServer("http://192.168.22.148:8080/solr/collection1");
		 // 清空之前建立的索引數據 // delete all doc
	     server.deleteByQuery( "*:*" );
		
		 //提升性能
		 server.setRequestWriter(new BinaryRequestWriter());
		 
		 String datFilePath =  "C:/Users/1409035/Desktop/FTP_server_backup/candelete/";
		 //String datFilePath = PropertyLoader.getInstance().getValue(DAT_FILE_PATH_KEY);
		 Map zinioMap= (HashMap) DataUtil.DeSerialization(datFilePath + "Zinio" + "-" + "getItemListByCategoryCode" + "-using" + ".dat");
		 Map ylibMap =(HashMap) DataUtil.DeSerialization(datFilePath + "Ylib" + "-" + "getItemListByCategoryCode" + "-using" + ".dat");
		 Map ibobarMap =(HashMap) DataUtil.DeSerialization(datFilePath + "Ibobar" + "-" + "getItemListByCategoryCode" + "-using" + ".dat");
		 Map linkingMap =(HashMap) DataUtil.DeSerialization(datFilePath + "Linking" + "-" + "getItemListByCategoryCode" + "-using" + ".dat");
		 
	     Collection docs2 = new ArrayList();
	     
	     int k=0;
	     Iterator linkingIter = linkingMap.entrySet().iterator();
		 while (linkingIter.hasNext()) {
			Map.Entry entry = (Map.Entry) linkingIter.next();
			ArrayList> bookAL = (ArrayList>) entry
					.getValue();
			for (HashMap hm : bookAL) {
				k++;

				SolrInputDocument doc = new SolrInputDocument();
				doc.addField("id", k);
				doc.addField("channel", "Linking");
				doc.addField("name", hm.get("name"));
				doc.addField("description", hm.get("description"));

				docs2.add(doc);
			}

		 }

		Iterator ylibIter = ylibMap.entrySet().iterator();
		while (ylibIter.hasNext()) {
			Map.Entry entry = (Map.Entry) ylibIter.next();
			ArrayList> bookAL = (ArrayList>) entry
					.getValue();

			for (HashMap hm : bookAL) {
				k++;

				SolrInputDocument doc = new SolrInputDocument();
				doc.addField("id", k);
				doc.addField("channel", "Ylib");
				doc.addField("name", hm.get("name"));
				doc.addField("description", hm.get("description"));
				System.out.println(doc.toString());
				docs2.add(doc);
			}
		}
		     
	     Iterator zinioIter = zinioMap.entrySet().iterator();
	     
	     
	     while(zinioIter.hasNext()) { 
	    	 Map.Entry entry = (Map.Entry) zinioIter.next(); 
	    	 //下述不能用ALHM 去接,否則會拋出ArrayList can't be cast to ALHM的錯誤
	    	 ArrayList> bookAL=(ArrayList>)entry.getValue();
	    	 for(HashMap hm:bookAL){
	    		 k++;
	    		 System.out.println(entry.getKey()+" "+hm.get("Title"));
	    		 
	    		 SolrInputDocument doc = new SolrInputDocument();
				 doc.addField("id", k);
				 doc.addField("channel", "Zinio");
				 doc.addField("name", hm.get("name"));
				 doc.addField("description", hm.get("description"));
				 
				 
				 docs2.add(doc);
	    	 }
	     }
	     
	     
	     Iterator ibobarIter = ibobarMap.entrySet().iterator(); 
	     while(ibobarIter.hasNext()) { 
	    	 Map.Entry entry = (Map.Entry) ibobarIter.next(); 
	    	 ArrayList> bookAL=(ArrayList>)entry.getValue();
	    	 
	    	 for(HashMap hm:bookAL){
	    		 k++;
	    		 
	    		 SolrInputDocument doc = new SolrInputDocument();
				 doc.addField("id", k);
				 doc.addField("channel", "Ibobar");
				 doc.addField("name", hm.get("name"));
				 doc.addField("description", hm.get("description"));
				 
				 docs2.add(doc);
	    	 }
	     }
		 
		 //將ArrayList轉為XML格式
		 //String resultList=GeneralXmlPullParser.reverse(contentAL);
	     System.out.println("=======");
	     //System.out.println(docs2.toString());
	     server.add(docs2);
		
		 server.commit();
		 server.optimize(true, true);
		 
		 System.out.println("finish");
		
		
		
		return true;
	}

}


2015年4月30日 星期四

[linux] [java] download jdk1.7 64bit on linux and add to environment path



download jdk1.7 64bit for linux 

這樣是不行的
wget http://download.oracle.com/otn-pub/java/jdk/7u55-b13/jdk-7u55-linux-x64.tar.gz" \
-O jdk-7-linux-x64.tar.gz


要加header
wget --no-cookies \
--no-check-certificate \
--header "Cookie: oraclelicense=accept-securebackup-cookie" \
"http://download.oracle.com/otn-pub/java/jdk/7u55-b13/jdk-7u55-linux-x64.tar.gz" \
-O jdk-7-linux-x64.tar.gz


因為下載頁面有一個需要點選接受的按鈕.


解壓縮:
tar -xzf jdk-7-linux-x64.tar.gz -C /opt/

新增環境變數
export PATH=$PATH:/opt/jdk1.7.0_55/bin

export JAVA_HOME=/opt/jdk1.7.0_55/

2015年4月27日 星期一

[design pattern] [java] Decorator pattern

這種模式讓你不用修改現有的interface,
並且對其新添加功能,

重點在於Employee.java的第七行,
除了複寫walk的method,還添加了
run的method在裡面.




Human.java
package com.test.decoratorpattern;

public interface Human {

 void walk(String msg);
}




Man.java
package com.test.decoratorpattern;

public class Man implements Human{

 @Override
 public void walk(String msg) {
  System.out.println("class is Man , "+msg);
 }

}




ManDecorator.java
package com.test.decoratorpattern;

public class ManDecorator implements Human {

 protected Human decoratedHuman;

 public ManDecorator(Human decoratedHuman) {
  this.decoratedHuman = decoratedHuman;
 }

 public void walk(String msg) {
  decoratedHuman.walk("class is ManDecorator:"+msg);
 }

}




Employee.java
package com.test.decoratorpattern;

public class Employee extends ManDecorator {

 public Employee(Human decoratedHuman) {
  super(decoratedHuman);
  // TODO Auto-generated constructor stub
 }

 @Override
 public void walk(String msg) {
  decoratedHuman.walk(msg);
  run(decoratedHuman);
 }

 private void run(Human decoratedHuman) {
  System.out.println("class is Employee: Run");
 }

}




testDecorator.java
package com.test.decoratorpattern;

public class testDecorator {

 public static void main(String[] args) {
  // TODO Auto-generated method stub

  Human man = new Man();
  man.walk(" man ");
  
  Human employee = new Employee(new Man());
  employee.walk(" employee ");

        
 }

}




Console
class is Man ,  man 
class is Man ,  employee 
class is Employee: Run

2015年4月20日 星期一

[linux] Run jar on linux with command line


here is java test code
package testJava;

public class testLinuxArg {

 public static void main(String[] args) {

  System.out.println("args lenght:" + args.length);

  for (int i = 0; i < args.length; i++) {
   System.out.println("args:" + i + " is : " + args[i] + " type   is "
     + args[i].getClass() + "  length is " + args[i].length());
  }
 }
}

export as jar,
put it to your linux

run jar on linux
 java -cp "the lib you need" fileName
 ex: java -cp "./*:./lib/*" testJava.testLinuxArg "1" "" "3" $(pwd)