廣告

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;
       }

}