廣告

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月25日 星期日

上線前須做的事

公司內部某單位不知道 何謂 "測試環境是啥"
特地說明==


以軟工上線流程來說會有三個階段

1. [測試環境]的上線及測試
    .此階段的所有資料都是假的.  
    .其目的在於資料欄位的正確性

2. 測試[正式環境]
    .此階段的所有資料都是真的.
    .此階段目的在於測試各家廠商
     的正式環境是否正常運行.因為我們在#1不會知道他們的正式
     環境是否正常
    .若此步驟的環節有錯,我們就不能進入第三步驟.  

3. [正式環境]上線
    .本系統與各家廠商的系統正式環境
     都正常運行才會到這步驟
   
所以如果我們直接就從#1進入#3是無法確定
我們自己的系統與各家廠商的系統的正式環境是正常的,
此時勢必會造成更多問題需要處理(因為已經有外部的使用者在使用)

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年8月10日 星期三

a bug in Chrome's live-edit CSS/JS. Notice how the number changes on each request.

Error msg:
Error shows “Failed to get text for stylesheet (#): No style sheet with given id found”

Ans:

closed all the files in the 'source' tab.


2016年8月7日 星期日

[git]Untrack files from git

This will tell git you want to start ignoring the changes to the file
git update-index --assume-unchanged path/to/file

When you want to start keeping track again
git update-index --no-assume-unchanged path/to/file

usage occasion : put some file in remote once and not track it anymore

                 ex:local config

2016年7月13日 星期三

2016年6月23日 星期四

Hibernate Eager vs Lazy Fetch Type


  @OneToOne(fetch=FetchType.EAGER) //LAZY
  @JoinColumn(name="user_profile_id")
  private Profile getUserProfile()
  {
   return userProfile;
  }

 FetchType.LAZY = Doesn’t load the relationships 
 unless explicitly “asked for” via getter
 FetchType.EAGER = Loads ALL relationships

ref:
https://m.oschina.net/blog/327056
https://howtoprogramwithjava.com/hibernate-eager-vs-lazy-fetch-type/

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#

2016年3月10日 星期四

Apache_httpd_to_Tomcat-Mod_Proxy_Setup.txt | 轉址


sudo vi /opt/lampp/etc/httpd.conf

Make sure the following are uncommented:
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so

Add these:
ProxyPass         /eInvoiceLocate http://localhost:8080/eInvoiceLocate
ProxyPassReverse  /eInvoiceLocate http://localhost:8080/eInvoiceLocate

Reload Apache conf
# cd /opt/lampp/bin
# sudo ./apachectl -k graceful


2016年2月25日 星期四

apache xmlhttprequest cannot load origin is not allowed by access-control-allow-origin |ajax 跨網頁存取圖片遇到cors

修改這個檔:
/opt/lampp/etc/httpd.conf

在 <Directory "/opt/lampp/htdocs"> 區段加入:
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "x-requested-with"
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"

重起
sudo /opt/lampp/bin/apachectl -k graceful

關於cors

Android Receive SMS Tutorial | android 取得sms內容


testReadSms.java
public class testReadSms extends BodyFragment{

    private SmsBroadcastReceiver receiver = new SmsBroadcastReceiver(new SmsBroadcastReceiver.UpdateSmsEvent() {
        @Override
        public void updateSms(String sms) {
            newMsg.setText(sms);
        }
    });

    private ArrayList smsMessagesList = new ArrayList();
    private ListView smsListView;
    private ArrayAdapter arrayAdapter;
    private TextView newMsg;

    @Override
    public void onStart() {
        super.onStart();

        //regist sms receiver
        Log. e("registerReceiver", "registerReceiver");
        receiver.registerSmsReceiver(activity);
    }

    @Override
    protected View fragmentLayout(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.test_body_sms, container, false);
    }

    @Override
    protected void setupComponents(View fragmentView) {
        newMsg = (TextView) fragmentView.findViewById(R.id. new_msg);
        smsListView = (ListView) fragmentView.findViewById(R.id. SMSList);
        arrayAdapter = new ArrayAdapter( activity, android.R.layout.simple_list_item_1 , smsMessagesList);
        smsListView.setAdapter(arrayAdapter);
        smsListView.setOnItemClickListener( this);

        refreshSmsInbox();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //activity.unregisterReceiver(receiver);
    }

    public void refreshSmsInbox() {
        ContentResolver contentResolver = activity.getContentResolver();
        Cursor smsInboxCursor = contentResolver.query(Uri.parse("content://sms/inbox"), null, null , null, null);
        int indexBody = smsInboxCursor.getColumnIndex( "body");
        int indexAddress = smsInboxCursor.getColumnIndex( "address");
        if (indexBody < 0 || !smsInboxCursor.moveToFirst()) return;
        arrayAdapter.clear();
        do {
            String str = "SMS From: " + smsInboxCursor.getString(indexAddress) +
                    "\n" + smsInboxCursor.getString(indexBody) + "\n";
            arrayAdapter.add(str);
        } while (smsInboxCursor.moveToNext());
    }

    public void updateList(final String smsMessage) {
        arrayAdapter.insert(smsMessage, 0);
        arrayAdapter.notifyDataSetChanged();
    }

    public void updateNewMsg(final String msg) {
        newMsg.setText(msg);
    }

}


SmsBroadcastReceiver.java
public class SmsBroadcastReceiver extends BroadcastReceiver {

    public static final String SMS_BUNDLE = "pdus";
    public Activity activity;
    public UpdateSmsEvent updateSmsEvent;


    public interface UpdateSmsEvent{
        void updateSms(String sms);
    }

    public SmsBroadcastReceiver(UpdateSmsEvent inte){
        updateSmsEvent = inte;
    }


    public void onReceive(Context context, Intent intent) {
        Bundle intentExtras = intent.getExtras();
        if (intentExtras != null) {
            Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
            String smsMessageStr = "";
            String smsMessageBody= "";
            for (int i = 0; i < sms. length; ++i) {
                SmsMessage smsMessage = SmsMessage. createFromPdu((byte[]) sms[i]);

                String smsBody = smsMessage.getMessageBody().toString();
                String address = smsMessage.getOriginatingAddress();

                //smsMessage.getTimestampMillis() is current time
                smsMessageStr += "SMS From: " + address + "\n" ;
                smsMessageStr += smsBody + "\n" ;
                smsMessageBody = smsMessage.getMessageBody().toString();
            }
            Toast.makeText (context, smsMessageBody, Toast.LENGTH_SHORT).show();
            smsMessageBody = smsMessageBody.replaceAll("\\D+","" );
            //this will update the UI with message
            updateSmsEvent.updateSms(smsMessageBody);
            activity.unregisterReceiver(this);
        }
    }

    public void registerSmsReceiver(Activity activity){
        this.activity = activity;
        IntentFilter filter = new IntentFilter();
        filter.setPriority(999 );
        filter.addAction("android.provider.Telephony.SMS_RECEIVED");
        activity.registerReceiver(this, filter);
    }
}



main ref:

ref: