import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
/**
*    일반문자열 유틸.
*
* @author someone
* @version 1.0.0
*/
public class JsonUtil {
    /**
     * 로그 출력.
     */
    @SuppressWarnings("unused")
    private static Logger logger = Logger.getLogger(JsonUtil.class);
    /**
     * Map을 jsonString으로 변환한다.
     *
     * @param map Map<String, Object>.
     * @return String.
     */
    @SuppressWarnings("unchecked")
    public static JSONObject getJsonStringFromMap( Map<String, Object> map ) {
        JSONObject json = new JSONObject();
        for( Map.Entry<String, Object> entry : map.entrySet() ) {
            String key = entry.getKey();
            Object value = entry.getValue();
            json.put(key, value);
        }
        
        return json;
    }
    
    /**
     * List<Map>을 json으로 변환한다.
     *
     * @param list List<Map<String, Object>>.
     * @return JSONArray.
     */
    @SuppressWarnings("unchecked")
    public static JSONArray getJsonArrayFromList( List<Map<String, Object>> list ) {
        JSONArray jsonArray = new JSONArray();
        for( Map<String, Object> map : list ) {
            jsonArray.add( getJsonStringFromMap( map ) );
        }
        
        return jsonArray;
    }
    
    /**
     * List<Map>을 jsonString으로 변환한다.
     *
     * @param list List<Map<String, Object>>.
     * @return String.
     */
    @SuppressWarnings("unchecked")
    public static String getJsonStringFromList( List<Map<String, Object>> list ) {
        JSONArray jsonArray = new JSONArray();
        for( Map<String, Object> map : list ) {
            jsonArray.add( getJsonStringFromMap( map ) );
        }
        
        return jsonArray.toJSONString();
    }
    /**
     * JsonObject를 Map<String, String>으로 변환한다.
     *
     * @param jsonObj JSONObject.
     * @return String.
     */
    @SuppressWarnings("unchecked")
    public static Map<String, Object> getMapFromJsonObject( JSONObject jsonObj ) {
        Map<String, Object> map = null;
        
        try {
            
            map = new ObjectMapper().readValue(jsonObj.toJSONString(), Map.class) ;
            
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }
    /**
     * JsonArray를 List<Map<String, String>>으로 변환한다.
     *
     * @param jsonArray JSONArray.
     * @return List<Map<String, Object>>.
     */
    public static List<Map<String, Object>> getListMapFromJsonArray( JSONArray jsonArray ) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        
        if( jsonArray != null )
        {
            int jsonSize = jsonArray.size();
            for( int i = 0; i < jsonSize; i++ )
            {
                Map<String, Object> map = JsonUtil.getMapFromJsonObject( ( JSONObject ) jsonArray.get(i) );
                list.add( map );
            }
        }
        
        return list;
    }


'프로그래밍 > JAVA' 카테고리의 다른 글

java 컬렉션 종류  (0) 2019.03.07
RSA암호화 key생성 암호화 복호화  (0) 2019.03.07
RSA암호화 sample  (0) 2019.03.07
날짜관련 util  (0) 2019.03.07
FCM push 보내기  (0) 2019.03.07
ArrayList
    배열기반, 데이터의 추가와 삭제에 불리, 순차적인 추가삭제는 제일 빠름.
    임의의 요소에 대한 접근성이 뛰어남. (데이터가 순차적일 경우)

LinkedList
    연결기반, 데이터의 추가와 삭제에 유리, 임의의 요소에 대한 접근성이 좋지 않다. 
    (접근시간이 오래 걸림)

HashMap 
    배열과 연결이 결합된 형태, 추가, 삭제, 검색, 접근성이 모두 뛰어남. 
    검색에는 최고의 성능을 보인다.

TreeMap
    연결기반, 정렬가 검색(특히 범위검색)에 적합, 검색성능은 HashMap보다 떨어짐.

Stack
    Vector를 상속받아 구현

Queue
    LinkedList가 Queue인터페이스를 구현

Properties
    Hashtable을 상속받아 구현

HashSet
    HashMap을 이용해서 구현

TreeSet
    TreeMap을 이용해서 구현

LinkedHashMap

LinkedHashSet 

    HashMap과 HashSet을 저장순서유지기능을 추가하였음. 


'프로그래밍 > JAVA' 카테고리의 다른 글

json을 map으로, map을 json으로 변환하는 예제들  (0) 2019.03.07
RSA암호화 key생성 암호화 복호화  (0) 2019.03.07
RSA암호화 sample  (0) 2019.03.07
날짜관련 util  (0) 2019.03.07
FCM push 보내기  (0) 2019.03.07
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

public class MoonRsaFullSample {

    private static String publicKey = "";
    private static String privateKey = "";

    public static void main(String[] args) throws Exception {

        createRsaGenKey(); // key 생성

        String encStr = "가나다라마ABCDefghi되는거냐";

        System.out.println(encStr);

        String decStr = rsaEnc(encStr);
        System.out.println(decStr);

        String finalEncStr = rsaDec(decStr);
        System.out.println(finalEncStr);

    }

    /**
     * "smart" 를 이용해 random 값을 추출하여 2048bit에 해당하는 키 생성
     * @throws Exception
     */
    private static void createRsaGenKey() throws Exception{

        String pubkey = "smart";

        SecureRandom random = new SecureRandom(pubkey.getBytes());
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA","SunJSSE"); // OK
        generator.initialize(2048, random); // 여기에서는 2048 bit 키를 생성하였음

        KeyPair pair = generator.generateKeyPair();
        Key pubKey = pair.getPublic(); // Kb(pub) 공개키
        Key privKey = pair.getPrivate();// Kb(pri) 개인키

        System.out.println("pubKeyHex:\n" + byteArrayToHex(pubKey.getEncoded())+"\n");
        System.out.println("privKeyHex:\n" + byteArrayToHex(privKey.getEncoded())+"\n");

        publicKey = byteArrayToHex(pubKey.getEncoded());
        privateKey = byteArrayToHex(privKey.getEncoded());

    }

    /**
     * 암호화
     * @param encStr
     * @return byteArrayToHex(cipherText)
     * @throws Exception
     */
    private static String rsaEnc(String encStr) throws Exception{

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING", "SunJCE"); // 알고리즘 명 / Cipher 알고리즘 mode / padding

        X509EncodedKeySpec ukeySpec = new X509EncodedKeySpec(hexToByteArray(publicKey));

        KeyFactory ukeyFactory = KeyFactory.getInstance("RSA");

        PublicKey publickey = null;

        try {
            // PublicKey에 공용키 값 설정
            publickey = ukeyFactory.generatePublic(ukeySpec);

        } catch (Exception e) {
            e.printStackTrace();
        }

        byte[] input = encStr.getBytes();
        cipher.init(Cipher.ENCRYPT_MODE, publickey);

        byte[] cipherText = cipher.doFinal(input);

        return byteArrayToHex(cipherText);

    }

    /**
     * 복호화
     * @param byteArrayToHex(cipherText) ==> decStr
     * @return
     * @throws Exception
     */
    private static String rsaDec(String decStr) throws Exception{

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING", "SunJCE");

        PKCS8EncodedKeySpec rkeySpec = new PKCS8EncodedKeySpec(hexToByteArray(privateKey));
        KeyFactory rkeyFactory = KeyFactory.getInstance("RSA");

        PrivateKey privateKey = null;

        try {
            privateKey = rkeyFactory.generatePrivate(rkeySpec);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 복호
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] plainText = cipher.doFinal(hexToByteArray(decStr));

        String returnStr = new String(plainText);

        return returnStr;
    }



    // hex string to byte[]
    public static byte[] hexToByteArray(String hex) {
        if (hex == null || hex.length() == 0) {
            return null;
        }
        byte[] ba = new byte[hex.length() / 2];
        for (int i = 0; i < ba.length; i++) {
            ba[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
        }
        return ba;
    }

    // byte[] to hex sting
    public static String byteArrayToHex(byte[] ba) {
        if (ba == null || ba.length == 0) {
            return null;
        }
        StringBuffer sb = new StringBuffer(ba.length * 2);
        String hexNumber;
        for (int x = 0; x < ba.length; x++) {
            hexNumber = "0" + Integer.toHexString(0xff & ba[x]);

            sb.append(hexNumber.substring(hexNumber.length() - 2));
        }
        return sb.toString();
    }


'프로그래밍 > JAVA' 카테고리의 다른 글

json을 map으로, map을 json으로 변환하는 예제들  (0) 2019.03.07
java 컬렉션 종류  (0) 2019.03.07
RSA암호화 sample  (0) 2019.03.07
날짜관련 util  (0) 2019.03.07
FCM push 보내기  (0) 2019.03.07
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import org.apache.commons.codec.binary.Base64;

public class MoonRSAManagerExample {

    public static void main(String[] args) {

        System.out.println("Server Start-----------------------------------");
        // 서버측 키 파일 생성 하기
        PublicKey publicKey1 = null;
        PrivateKey privateKey1 = null;

        SecureRandom secureRandom = new SecureRandom();

        KeyPairGenerator keyPairGenerator;

        try {

            keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(512, secureRandom);

            KeyPair keyPair = keyPairGenerator.genKeyPair();
            publicKey1 = keyPair.getPublic();
            privateKey1 = keyPair.getPrivate();

            KeyFactory keyFactory1 = KeyFactory.getInstance("RSA");

            RSAPublicKeySpec rsaPublicKeySpec = keyFactory1.getKeySpec(publicKey1, RSAPublicKeySpec.class);
            RSAPrivateKeySpec rsaPrivateKeySpec = keyFactory1.getKeySpec(privateKey1, RSAPrivateKeySpec.class);

            System.out.println("Public  key modulus : "+ rsaPublicKeySpec.getModulus());
            System.out.println("Public  key exponent: "+ rsaPublicKeySpec.getPublicExponent());
            System.out.println("Private key modulus : "+ rsaPrivateKeySpec.getModulus());
            System.out.println("Private key exponent: "+ rsaPrivateKeySpec.getPrivateExponent());

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }

        byte[] bPublicKey1 = publicKey1.getEncoded();
        String sPublicKey1 = Base64.encodeBase64String(bPublicKey1);

        byte[] bPrivateKey1 = privateKey1.getEncoded();
        String sPrivateKey1 = Base64.encodeBase64String(bPrivateKey1);

        try {

            BufferedWriter bw1 = new BufferedWriter(new FileWriter("PublicKey.txt"));
            bw1.write(sPublicKey1);
            bw1.newLine();
            bw1.close();

            BufferedWriter bw2 = new BufferedWriter(new FileWriter("PrivateKey.txt"));
            bw2.write(sPrivateKey1);
            bw2.newLine();
            bw2.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

        // 클라이언트측 키 파일 로딩
        System.out.println("Client Start-----------------------------------");
        String sPublicKey2 = null;
        String sPrivateKey2 = null;

        BufferedReader brPublicKey = null;
        BufferedReader brPrivateKey = null;
        try {
            brPublicKey = new BufferedReader(new FileReader("PublicKey.txt"));
            sPublicKey2 = brPublicKey.readLine(); // First Line Read
            brPrivateKey = new BufferedReader(new FileReader("PrivateKey.txt"));
            sPrivateKey2 = brPrivateKey.readLine(); // First Line Read
            System.out.println("Pubilc Key & Private Key Read");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (brPublicKey != null)
                    brPublicKey.close();
                if (brPrivateKey != null)
                    brPrivateKey.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        byte[] bPublicKey2 = Base64.decodeBase64(sPublicKey2.getBytes());
        PublicKey publicKey2 = null;

        byte[] bPrivateKey2 = Base64.decodeBase64(sPrivateKey2.getBytes());
        PrivateKey privateKey2 = null;

        try {
            KeyFactory keyFactory2 = KeyFactory.getInstance("RSA");

            X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(bPublicKey2);
            publicKey2 = keyFactory2.generatePublic(publicKeySpec);

            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(bPrivateKey2);
            privateKey2 = keyFactory2.generatePrivate(privateKeySpec);

        } catch (Exception e) {
            e.printStackTrace();
        }

        String sPlain1 = "Welcome to RSA";
        String sPlain2 = null;

        try {
            Cipher cipher = Cipher.getInstance("RSA");

            // 공개키 이용 암호화
            cipher.init(Cipher.ENCRYPT_MODE, publicKey2);
            byte[] bCipher1 = cipher.doFinal(sPlain1.getBytes());
            String sCipherBase64 = Base64.encodeBase64String(bCipher1);

            // 개인키 이용 복호화
            byte[] bCipher2 = Base64.decodeBase64(sCipherBase64.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, privateKey2);
            byte[] bPlain2 = cipher.doFinal(bCipher2);
            sPlain2 = new String(bPlain2);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }

        System.out.println("sPlain1 : " + sPlain1); // 평문(원본)
        System.out.println("sPlain2 : " + sPlain2); // 평문(암호화후 복호화된 평문)
    }


'프로그래밍 > JAVA' 카테고리의 다른 글

java 컬렉션 종류  (0) 2019.03.07
RSA암호화 key생성 암호화 복호화  (0) 2019.03.07
날짜관련 util  (0) 2019.03.07
FCM push 보내기  (0) 2019.03.07
Map을 VO로 변환  (0) 2019.03.07
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class MoonDateUtil {
    /**
     * //이번달 가져오기  ( 2011/10)
     * @return
     */
    public static String getNowMonthStr(){

        String thisMonth = new SimpleDateFormat("yyyy/MM" , Locale.getDefault()).format(Calendar.getInstance().getTime());

        return thisMonth;
    }

    /**
     * 이번년도 가져오기
     * @return
     */
    public static String getNowYearStr(){

        String thisYear = new SimpleDateFormat("yyyy" , Locale.getDefault()).format(Calendar.getInstance().getTime());

        return thisYear;
    }

    /**
     * 이번달 가져오기
     * @return
     */
    public static String getOnlyNowMonthStr(){

        String thisMonth = new SimpleDateFormat("MM" , Locale.getDefault()).format(Calendar.getInstance().getTime());

        return thisMonth;
    }
    /**
     * 오늘날짜 가져오기(2011.10.24)
     * @return
     */
    public static String getTodayDateStr(){
        return new SimpleDateFormat("yyyy/MM/dd" , Locale.getDefault()).format(Calendar.getInstance().getTime());
    }

    /**
     * String을 Date로 변환 yyyy/MM/dd 문자열
     *
     * @author 김준석
     * @return
     */
    public static Date getDate(String stringDate) throws Exception
    {
        return MoonDateUtil.getDate(stringDate, "yyyy/MM/dd");
    }

    /**
     * String을 Date로 변환 yyyy/MM/dd hh:mm 문자열로 반환
     *
     * @author ywkim
     * @return
     */
    public static Date getDateTime(String stringDate) throws Exception
    {
        Date aa = MoonDateUtil.getDate(stringDate, "yyyy/MM/dd hh:mm:ss");
        return aa;
    }

    /**
     * String을 Date로 변환
     * @param stringDate : 문자열
     * @param formatStr : 문자열의 날짜포멧
     * @author 김준석
     * @return
     */
    public static Date getDate(String stringDate, String formatStr) throws Exception
    {
        java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(formatStr);
        return format.parse(stringDate);
    }

    /**
     * 다음달로 조정한 Date를 리턴
     * ex. DateUtility.getAdjustedMonth(1) => 다음 달
     * @param adjustMonth : 조정월
     * @author 김준석
     * @return Date
     */
    public static Date getAdjustedMonth(int adjustMonth)
    {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, adjustMonth);

        return calendar.getTime();
    }

    /**
     * 년도를 조정한 Date를 리턴
     * ex. DateUtility.getAdjustedMonth(1) => 다음 달
     * @param adjustMonth : 조정월
     * @author 김준석
     * @return Date
     */
    public static Date getAdjustedYear(int adjustYear)
    {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.YEAR, adjustYear);

        return calendar.getTime();
    }

    /**
     * 일자를 조정한 Date를 리턴
     * ex. DateUtility.getAdjustedDate(1) => 다음 날
     * @param adjustDate : 조정 일자
     * @author 김준석
     * @return
     */
    public static Date getAdjustedDate(int adjustDate)
    {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, adjustDate);

        return calendar.getTime();
    }

    /**
     * 일자를 조정한 Date를 리턴(시분까지 입력)
     * ex. DateUtility.getAdjustedDate(1) => 다음 날
     * @param adjustDate : 조정 일자
     * @param hour : 지정 시
     * @param minute : 지정 분
     * @author 김준석
     * @return
     */
    public static Date getAdjustedDateHourMin(int adjustDate, int hour, int minute)
    {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, adjustDate);
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minute);

        return calendar.getTime();
    }

    /**
     * 일자를 조정한 Date를 리턴(문자열yyyy-MM-dd)
     * ex. DateUtility.getAdjustedDate(1) => 다음 날
     * @param adjustDate : 조정 일자
     * @author 김준석
     * @return
     */
    public static String getAdjustedDateStr(int adjustDate)
    {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, adjustDate);

        return new SimpleDateFormat("yyyy/MM/dd" , Locale.getDefault()).format(calendar.getTime());
    }

    /**
     * 해당월의 마지막 날
     * ex. DateUtility.getAdjustedDate(1) => 다음 날
     * @param adjustDate : 조정 일자
     * @author 김준석
     * @return
     */
    public static String getLastDayOfMonthStr(Date date)
    {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        String lastDateStr = calendar.getMaximum(Calendar.DAY_OF_MONTH)+"";
        if(lastDateStr.length() == 1) lastDateStr = "0" + lastDateStr;
        return lastDateStr;
    }

    /**
     * 해당월의 마지막 날
     * ex. DateUtility.getAdjustedDate(1) => 다음 날
     * @param adjustDate : 조정 일자
     * @author 김준석
     * @return
     */
    public static int getLastDayOfMonth(Date date)
    {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.getMaximum(Calendar.DAY_OF_MONTH);
    }

    /**
     * 해당월의 주의 개수
     * ex. DateUtility.getWeekCountOfMonth(date)
     * @author 김준석
     * @return
     */
    public static int getWeekCountOfMonth(Date date)
    {
        Calendar calendar = Calendar.getInstance();
        date.setDate(MoonDateUtil.getLastDayOfMonth(date));
        calendar.setTime(date);
        return calendar.get(Calendar.WEEK_OF_MONTH);
    }

    /**
     * 해당월의 주의 개수
     * ex. DateUtility.getWeekCountOfMonth("2016-05-07") => 5
     * @param adjustDate : 조정 일자
     * @author 김준석
     * @return
     */
    public static int getWeekCountOfMonthStr(String stringDate) throws Exception
    {
        Date date = MoonDateUtil.getDate(stringDate);

        return MoonDateUtil.getWeekCountOfMonth(date);
    }

    public static Date getDatetoString(String stringDate){

        Date rDate = null;

        try {
            SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy/MM/dd");
            rDate = format.parse(stringDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return rDate;
    }
    /**
     * DATE를 FORMAT 스트링으로 변환
     * @param date : 날짜
     * @param formatStr : 문자열의 날짜포멧
     * @author 김준석
     * @return
     */
    public static String getDateStringByFormmat(Date date , String formatStr) throws Exception
    {
        java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(formatStr);
        return format.format(date);
    }

    /**
     * 두 Date간의 날짜차이 구하기
     * @param startDate : 작은날짜
     * @param endDate : 큰날짜
     * @author 김준석
     * @return int(날짜차이)
     */
    public static int getDiffDayCountTwoDate(Date startDate , Date endDate) throws Exception
    {
        Calendar startCal = Calendar.getInstance();
        Calendar endCal   = Calendar.getInstance();

        startCal.setTime(startDate);
        endCal.setTime(endDate);

        long diffMillis = endCal.getTimeInMillis() - startCal.getTimeInMillis();

        int diffDayCount = (int)(diffMillis/(24*60*60*1000));

        return diffDayCount;
    }

    /**
     * 일자를 Date로 조정후 FORMAT 스트링으로 변환 리턴
     * ex. DateUtility.getAdjustedDateToString(new Date(),"yyyy/MM/dd",1) => 다음 날
     * @param date : 조정 시점 일자
     * @param formatStr : 리턴 스트링 포멧
     * @param adjustDate : 조정 일자
     * @author 이인희
     * @return
     */
    public static String getAdjustedDateToString(Date date, String formatStr, int adjustDate)
    {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime (date);
        calendar.add(Calendar.DATE, adjustDate);
        Date newDate = calendar.getTime();

        java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(formatStr);
        return format.format(newDate);
    }


'프로그래밍 > JAVA' 카테고리의 다른 글

RSA암호화 key생성 암호화 복호화  (0) 2019.03.07
RSA암호화 sample  (0) 2019.03.07
FCM push 보내기  (0) 2019.03.07
Map을 VO로 변환  (0) 2019.03.07
VO를 Map으로 변환  (0) 2019.03.07
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONObject;

public class MoonFcmTestSmartData {

    // FCM에서 가입 후 받는 키값
    public final static String AUTH_KEY_FCM = "AAAAfyq7cAo:APA91bHbB5R15a8uYPvn5DHUzXHwowDsI8m4LoZMilX8MsC78ZXZk8YF5P4sR7NDloj3W9NR4Zky_OWoySounMmXjXuiH70oJ-nIipS3w6xoww8mzQjyOM0nOJPa8sNZu9ZiDexD4th_";
    
    public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";

    public static void main(String[] args) throws Exception{

        //String token = tokenList.get(count).getDEVICE_ID();

        String _title = "앱 알림";
        String _body = "푸쉬메시지가 도착했습니다.";
        String _actionType = "new";
        String _code = "test";
        //String _token = "/topics/ALL"; // 전체
        
// 모바일기기에서 얻음
        String _token = "dl60nc4Zy8s:APA91bEAgHQWgwdDKCyuw6YWNyIsbsWGVdV_x2qYevkLHJz6eTM4OaTjgtlu7O8B4MlXR23__i74_tWwzoRmpm96KOWOmJBVEEcmrF8vg3TnqGTnV67lzN-gmXWQsOD5tZ0gQcy7dwUp"; // 개인

        final String apiKey = AUTH_KEY_FCM;
        URL url = new URL("https://fcm.googleapis.com/fcm/send");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", "key=" + apiKey);

        conn.setDoOutput(true);


        // 이렇게 보내면 주제를 ALL로 지정해놓은 모든 사람들한테 알림을 날려준다.
        String input = "{\"notification\" : {\"title\" : \"여기다 제목 넣기 \", \"body\" : \"여기다 내용 넣기\"}, \"to\":\"/topics/ALL\"}";

        // 이걸로 보내면 특정 토큰을 가지고있는 어플에만 알림을 날려준다  위에 둘중에 한개 골라서 날려주자
        //String input = "{\"notification\" : {\"title\" : \" 여기다 제목넣기 \", \"body\" : \"여기다 내용 넣기\"}, \"to\":\" 여기가 받을 사람 토큰  \"}";

        JSONObject json = new JSONObject();
        JSONObject notification = new JSONObject();
        JSONObject data = new JSONObject();

        notification.put("title", _title);
        notification.put("body", _body);

        data.put("actionType", _actionType);
        data.put("storeCode", _code);

        json.put("notification", notification);
        json.put("to", _token);
        json.put("data", data);

        String sendMsg = json.toString();

        OutputStream os = conn.getOutputStream();

        // 서버에서 날려서 한글 깨지는 사람은 아래처럼  UTF-8로 인코딩해서 날려주자
        //os.write(input.getBytes("UTF-8"));
        os.write(sendMsg.getBytes("UTF-8"));
        os.flush();
        os.close();

        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + input);
        System.out.println("Post parameters2 : " + sendMsg);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        // print result
        System.out.println(response.toString());
    }


'프로그래밍 > JAVA' 카테고리의 다른 글

RSA암호화 sample  (0) 2019.03.07
날짜관련 util  (0) 2019.03.07
Map을 VO로 변환  (0) 2019.03.07
VO를 Map으로 변환  (0) 2019.03.07
jsonString to Array 처리  (0) 2019.03.07

+ Recent posts