* 이미지 파일 DB에 넣는 과정입니다.

https://minaminaworld.tistory.com/212

 

[java]PostgreSQL DB (데이터베이스)에 file(이미지) 넣기

# Java와 PostgreSQL을 통한 파일을 집어 넣기 전 준비 사항 1. postgreSQL JDBC Jar 추가하기 (https://jdbc.postgresql.org/download.html) PostgreSQL JDBC Download Download About Binary JAR file downloads..

minaminaworld.tistory.com


1. 테이블 구조


2. DB에서 데이터 읽어오는 부분과 이미지 정보 DTO 구성

* DB 에서 이미지 정보 읽어 오기

public void readImg() {
        String sql = "SELECT file_id, filename, filesize, file, inst_dt from public.img_test";
        Connection connection = null;
        PreparedStatement pstmt = null;

        try {
            connection = DriverManager.getConnection(connurl, user, password);
            pstmt = connection.prepareStatement(sql);
            ResultSet resultSet = pstmt.executeQuery();

            ImgDto imgDto = new ImgDto();
            while (resultSet.next()) {
                imgDto.setFileId(resultSet.getInt("file_id"));
                imgDto.setFilename(resultSet.getString("filename"));
                imgDto.setFilesize(resultSet.getLong("filesize"));
                imgDto.setFile(resultSet.getBytes("file"));
                imgDto.setInsDt(resultSet.getTimestamp("inst_dt").toLocalDateTime());
            }
            System.out.println("imgDto.toString() = " + imgDto.toString());
            // 이미지 정보를 파일로 저장하는 함수 호출
            saveImg(imgDto);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

* DB에서 가져온 데이터 DTO로 변환

import java.time.LocalDateTime;

public class ImgDto {
    private int fileId;
    private String filename;
    private Long filesize;
    private byte[] file;
    private LocalDateTime insDt;

    public ImgDto() {
    }

    public int getFileId() {
        return fileId;
    }

    public void setFileId(int fileId) {
        this.fileId = fileId;
    }

    public String getFilename() {
        return filename;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }

    public Long getFilesize() {
        return filesize;
    }

    public void setFilesize(Long filesize) {
        this.filesize = filesize;
    }

    public byte[] getFile() {
        return file;
    }

    public void setFile(byte[] file) {
        this.file = file;
    }

    public LocalDateTime getInsDt() {
        return insDt;
    }

    public void setInsDt(LocalDateTime insDt) {
        this.insDt = insDt;
    }

    @Override
    public String toString() {
        return "ImgDto{" +
                "fileId=" + fileId +
                ", filename='" + filename + '\'' +
                ", filesize=" + filesize +
                ", insDt=" + insDt +
                '}';
    }
}

3. Img 파일로 저장

private void saveImg(ImgDto imgDto) {
		// 저장할 위치 
        String strPath = "D:/testFolder/aaa";
        Path path1 = Paths.get(strPath + "/" + imgDto.getFilename());
        try {
            Files.write(path1, imgDto.getFile());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

4. 결과화면

 * Console 로그

 * 저장된 파일 


더보기
public void readImg() {
    String sql = "SELECT file_id, filename, filesize, file, inst_dt from public.img_test";
    Connection connection = null;
    PreparedStatement pstmt = null;

    try {
        connection = DriverManager.getConnection(connurl, user, password);
        pstmt = connection.prepareStatement(sql);
        ResultSet resultSet = pstmt.executeQuery();

        ImgDto imgDto = new ImgDto();
        while (resultSet.next()) {
            imgDto.setFileId(resultSet.getInt("file_id"));
            imgDto.setFilename(resultSet.getString("filename"));
            imgDto.setFilesize(resultSet.getLong("filesize"));
            imgDto.setFile(resultSet.getBytes("file"));
            imgDto.setInsDt(resultSet.getTimestamp("inst_dt").toLocalDateTime());
        }
        System.out.println("imgDto.toString() = " + imgDto.toString());
        saveImg(imgDto);
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            pstmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

private void saveImg(ImgDto imgDto) {
    String strPath = "D:/testFolder/aaa";
    Path path1 = Paths.get(strPath + "/" + imgDto.getFilename());
    try {
        Files.write(path1, imgDto.getFile());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
블로그 이미지

미나미나미

,

# Java와 PostgreSQL을 통한 파일을 집어 넣기 전 준비 사항

1. postgreSQL JDBC Jar 추가하기 (https://jdbc.postgresql.org/download.html)

 

2. 데이터베이스에 기록하기

public class GeomTest {

    private String connurl = "jdbc:postgresql://localhost:5432/postgres";
    private String user = "postgres";
    private String password = "postgres";

    public void insert() {
        String sql = "INSERT INTO " +
                "public.geom_test (_gid, geom_4326, geom_3857, geom_5186, ins_dt, mod_dt) " +
                "VALUES(" +
                " ?, " +
                " st_transform(ST_SetSRID(ST_MakePoint(?, ?), ?), 3857)," +
                " st_transform(ST_SetSRID(ST_MakePoint(?, ?), ?), 4326)," +
                " st_transform(ST_SetSRID(ST_MakePoint(?, ?), ?), 5186)," +
                " ?, ?)" +
                ";";
        Connection connection = null;
        PreparedStatement pstmt = null;

        // 경복궁 지점, 4326 좌표
        double x = 126.97727;
        double y = 37.578472;

        try {
            connection = DriverManager.getConnection(connurl, user, password);
            pstmt = connection.prepareStatement(sql);

            pstmt.setLong(1, 2); // _gid
            // 4326 좌표를 3857로 변환
            // st_transform(ST_SetSRID(ST_MakePoint(?, ?), ?), 3857)
            pstmt.setDouble(2, x);
            pstmt.setDouble(3, y);
            pstmt.setInt(4, 4326); // 원본 좌표

            // 4326 좌표를 4326로 변환
            // st_transform(ST_SetSRID(ST_MakePoint(?, ?), ?), 4326)
            pstmt.setDouble(5, x);
            pstmt.setDouble(6, y);
            pstmt.setInt(7, 4326); // 원본 좌표

            // 4326 좌표를 5186로 변환
            // st_transform(ST_SetSRID(ST_MakePoint(?, ?), ?), 5186)
            pstmt.setDouble(8, x);
            pstmt.setDouble(9, y);
            pstmt.setInt(10, 4326); // 원본 좌표

            pstmt.setTimestamp(11, Timestamp.valueOf(LocalDateTime.now()));
            pstmt.setTimestamp(12, Timestamp.valueOf(LocalDateTime.now()));

            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}​

3. 결화화면


 

블로그 이미지

미나미나미

,

# Java와 PostgreSQL을 통한 파일을 집어 넣기 전 준비 사항

 

1. postgreSQL JDBC Jar 추가하기 (https://jdbc.postgresql.org/download.html)

 

PostgreSQL JDBC Download

Download About Binary JAR file downloads of the JDBC driver are available here and the current version with Maven Repository. Because Java is platform neutral, it is a simple process of just downloading the appropriate JAR file and dropping it into your cl

jdbc.postgresql.org

2. PostgreSQL 테이블 생성

-- Drop table

-- DROP TABLE public.img_test;

CREATE TABLE public.img_test (
	file_id int4 NOT NULL DEFAULT nextval('newtable_1_file_id_seq'::regclass),
	filename varchar NULL,
	filesize int8 NULL,
	file bytea NULL,
	inst_dt timestamp(0) NULL
);


# DB에 이미지 넣는 부분 소스 코드

 public void insertImg() {
        File file = new File("../TestFileDir/잔망루피 4월 달력_새싹.jpg");
        FileInputStream fis = null;

        String name = file.getName();
        System.out.println("name = " + name);

        String sql = "INSERT INTO public.img_test (filename, filesize, file, inst_dt) VALUES(?, ?, ?, ?);";
        Connection connection = null;
        PreparedStatement pstmt = null;

        try {
            fis = new FileInputStream(file); 

            connection = DriverManager.getConnection(connurl, user, password);
            pstmt = connection.prepareStatement(sql);

            pstmt.setString(1, file.getName());
            pstmt.setLong(2, file.length());
            pstmt.setBinaryStream(3, fis);
            pstmt.setTimestamp(4, Timestamp.valueOf(LocalDateTime.now()));

            pstmt.executeUpdate();
        } catch (SQLException | FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

 

# 결과 화면


# 전체소스코드

더보기
package com.example.Img;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.file.Files;
import java.sql.*;
import java.time.LocalDateTime;

public class DatabaseSaveImg {

    private String connurl = "jdbc:postgresql://localhost:5432/DB명";
    private String user = "postgres";
    private String password = "postgres";

    public void connTest() {
        try {
            Class.forName("org.postgresql.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        try (Connection connection = DriverManager.getConnection(connurl, user, password);) {
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT VERSION() AS version");

            while (rs.next()) {
                String version = rs.getString("version");

                System.out.println(version);
            }
            rs.close();
            stmt.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void insertImg() {
        File file = new File("D:/SOURCE_CODE/2022/study/Database/insertImg/TestFileDir/잔망루피 4월 달력_새싹.jpg");
        FileInputStream fis = null;

        String name = file.getName();
        System.out.println("name = " + name);

        String sql = "INSERT INTO public.img_test (filename, filesize, file, inst_dt) VALUES(?, ?, ?, ?);";
        Connection connection = null;
        PreparedStatement pstmt = null;

        try {
            fis = new FileInputStream(file);

            connection = DriverManager.getConnection(connurl, user, password);
            pstmt = connection.prepareStatement(sql);

            pstmt.setString(1, file.getName());
            pstmt.setLong(2, file.length());
            pstmt.setBinaryStream(3, fis);
            pstmt.setTimestamp(4, Timestamp.valueOf(LocalDateTime.now()));

            pstmt.executeUpdate();
        } catch (SQLException | FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

 

블로그 이미지

미나미나미

,

jar_files (1).zip
1.61MB

# Java 좌표를 통한 주소 구하기(Open API Geocoder API 사용하기)

 

공간정보 오픈플랫폼 오픈API

Geocoder API 2.0 레퍼런스 Geocoder API 2.0 레퍼런스입니다. API 버전 : Geocoder API 2.0 레퍼런스 Geocoder API 1.0 레퍼런스 소개 좌표를 주소로 변환하는 서비스를 제공합니다. 요청URL을 전송하면 지오코딩 서�

www.vworld.kr


1. Open API를 사용하기 위해서 KEY 값을 발급 받아야합니다.

 



3. JAVA 소스 

3-1.  main.java 

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Main
 */
public class Main {
	public static void main(String[] args) {
		JsonReader jsonReader = new JsonReader();
		// api 키값
		String key = "";
		// 경도
		String latitude = "37.57595319615567";
		// 위도
		String longitude = "126.97684687319756";
		// api 테스트
		// # 파라미터 종류 확인 : http://www.vworld.kr/dev/v4dv_geocoderguide2_s002.do
		String reverseGeocodeURL = "http://api.vworld.kr/req/address?"
				+ "service=address&request=getAddress&version=2.0&crs=epsg:4326&point="
				+  longitude + "," +  latitude
				+ "&format=json"
				+ "&type=both&zipcode=true"
				+ "&simple=false&"
				+ "key="+key;
		String getJson = jsonReader.callURL(reverseGeocodeURL);
		System.out.println("getJson => " + getJson);
		Map<String, Object> map = jsonReader.string2Map(getJson);
		System.out.println("json => " + map.toString());

		// 지도 결과 확인하기
		ArrayList reverseGeocodeResultArr = (ArrayList) ((HashMap<String, Object>) map.get("response")).get("result");

		String parcel_address = "";
		String road_address = "";

		for (int counter = 0; counter < reverseGeocodeResultArr.size(); counter++) {
			HashMap<String, Object> tmp = (HashMap<String, Object>) reverseGeocodeResultArr.get(counter);
			String level0 = (String) ((HashMap<String, Object>) tmp.get("structure")).get("level0");
			String level1 = (String) ((HashMap<String, Object>) tmp.get("structure")).get("level1");
			String level2 = (String) ((HashMap<String, Object>) tmp.get("structure")).get("level2");
			if (tmp.get("type").equals("parcel")) {
				parcel_address = (String) tmp.get("text");
				parcel_address = parcel_address.replace(level0, "").replace(level1, "").replace(level2, "").trim();
			} else {
				road_address = "도로 주소:" + (String) tmp.get("text");
				road_address = road_address.replace(level0, "").replace(level1, "").replace(level2, "").trim();
			}
		}

		System.out.println("parcel_address = > " + parcel_address);
		System.out.println("road_address = > " + road_address);
	}
}

3-2.  JsonReader.java

 - Jackson lib을 사용해서 String 값을 Map을 변경해서 사용합니다.

 - 첨부 파일에서 jar를 파일 다운 받아주세요.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;

import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonReader {
    public String callURL(String myURL) {

        System.out.println("Requeted URL:" + myURL);
        StringBuilder sb = new StringBuilder();
        URLConnection urlConn = null;
        InputStreamReader in = null;

        //error : Caused by: javax.net.ssl.SSLPeerUnverifiedException: Hostname not verified:
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                //특정 hostname만 승인을 해주는 형태             
                    return true;
            }
        };
        
        //
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

        try {
            URL url = new URL(myURL);
            urlConn = url.openConnection();
            if (urlConn != null)
                urlConn.setReadTimeout(60 * 1000);
            if (urlConn != null && urlConn.getInputStream() != null) {
                in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());
                //charset 문자 집합의 인코딩을 사용해 urlConn.getInputStream을 문자스트림으로 변환 객체를 생성.
                BufferedReader bufferedReader = new BufferedReader(in);
                //주어진 문자 입력 스트림 inputStream에 대해 기본 크기의 버퍼를 갖는 객체를 생성.
                if (bufferedReader != null) {
                    int cp;
                    while ((cp = bufferedReader.read()) != -1) {
                        sb.append((char) cp);
                    }
                    bufferedReader.close();
                }
            }
            in.close();
        } catch (Exception e) {
            throw new RuntimeException("Exception URL:"+ myURL, e);
        }
        System.out.println(sb.toString());
        return sb.toString();
    }
    
    public Map<String , Object> string2Map(String json){
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> map = null;

        try {
            map = mapper.readValue(json, Map.class);
            System.out.println(map);

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

        return map;
    }
    
}

4 결과화면

   - 테스트 위치

  - REST API  테스트 결과 

- JAVA 테스트 결과 

블로그 이미지

미나미나미

,

[JAVA] String []를 ArrayList변환

 

import java.util.ArrayList;
import java.util.Arrays;

public class StringArrToList {
    public static void main(String[] args) {
        String[] words = new String[] { "asd", "qqq", "aaa", "poi" };

        ArrayList<String> wordList = new ArrayList(Arrays.asList(words));

        for (String s : wordList) {
            System.out.println(s);
        }
    }
}

블로그 이미지

미나미나미

,

[JAVA] ArrayList를 String[] 변환 여러가지 방법

 

import java.util.ArrayList;

public class ListToStringArr {
    public static void main(String[] args) {
        ArrayList<String> testList = new ArrayList<String>();
        testList.add("철수");
        testList.add("영미");
        testList.add("김천");

        testList.forEach(
            x -> System.out.println( "testList => " + x)
        );

        // String[] 배열로 복사
        // testList.toArray 자체가 object[] 반환. 
        // 결론적으로 배열은 목록의 데이터로 채워지고 반환됨
        // new String[testList.size()] 보다 new String[0]로 사용하는 것이 더 좋다고 함.
        String[] strArr1 =  testList.toArray(new String[testList.size()]);
        String[] strArr2 =  testList.toArray(new String[0]);

        // JAVA 8 Stream을 사용한 방식
        String[] strArr3 = testList.stream().toArray(String[]::new);

        for(String s : strArr1){
            System.out.println("strArr1 => " + s);

        }

        for(String s : strArr2){
            System.out.println("strArr2 => " + s);
        }

		// JAVA 8 Stream을 사용한 결과 확인
        for(String s : strArr3){
            System.out.println("strArr3 => " + s);
        }
    }
}

 

# 결과화면

 

 

블로그 이미지

미나미나미

,

- 빌더패턴(Builder Pattern)

(# github 예제 소스 : https://github.com/HelloPlutoKid/JAVADesignPattern/tree/master/2.Builder)

 

정의 : 복합 객체의 생성 과정과 표현 방법을 분리하여 동일한 생성 절차에서 서로 다른 표현 결과를 만들 수 있게 하는 패턴

(#위키 백과 : https://ko.wikipedia.org/wiki/%EB%B9%8C%EB%8D%94_%ED%8C%A8%ED%84%B4  

 

빌더 패턴을 사용하면, 생성자를 통한 변수 초기화를 빌더 패턴을 대신함으로써 여러 생성자를 생성할 필요가 없고, 생성자의 순서에 맞게 변수 내용을 작성할 필요성이 없습니다. 또한, 변수의 내용을 보다 직관적으로 초기화가 가능합니다.


빌더 패턴을 통한 음식을 만들어 보겠습니다.

 

Food와 FoodBuilder의 관계

     Food을 생성을 FoodBuider를 통해서 Food 객체 생성과 변수 초기화를 진행합니다.       

 

클래스 구조


1. Food.java

package food;

/**
 *  국수 음식 
 */
public class Food {
    private String source;
    private String meat;
    private String noodle;

    public Food(String source, String meat, String noodle){
        this.source = source;
        this.meat = meat;
        this.noodle = noodle;
    }

    /**
     * @param meat the meat to set
     */
    public void setMeat(String meat) {
        this.meat = meat;
    }

    /**
     * @param noodle the noodle to set
     */
    public void setNoodle(String noodle) {
        this.noodle = noodle;
    }

    /**
     * @param source the source to set
     */
    public void setSource(String source) {
        this.source = source;
    }

    /**
     * @return the meat
     */
    public String getMeat() {
        return meat;
    }
    
    /**
     * @return the noodle
     */
    public String getNoodle() {
        return noodle;
    }

    /**
     * @return the source
     */
    public String getSource() {
        return source;
    }

    @Override
    public String toString() {
        return "source = >" + source + "," + "noodle = >" + noodle + "," + "meat = >" + meat;
    }
    
}

2. FoodBuilder.java

package food;

public class FoodBuilder {
    private Food food;

    public FoodBuilder(){
        food = new Food("","","");
    }

    public FoodBuilder start(){
        return this;
    }
    public FoodBuilder setSource(String source){
        this.food.setSource(source);
        return this;
    }

    public FoodBuilder setMeat(String meat){
        this.food.setMeat(meat);
        return this;
    }

    public FoodBuilder setNoodle(String noodle){
        this.food.setNoodle(noodle);
        return this;
    }

    public Food build(){
        return this.food;
    }
}

 

 

 


3. Main.java

import food.Food;
import food.FoodBuilder;

/**
 * Main
 */
public class Main {

    public static void main(String[] args) {
    	// 모든 변수를 초기화 하는 경우 
        Food food1 = new FoodBuilder()
        		.start()
        		.setSource("라면스프")
        		.setNoodle("라면사리")
        		.setMeat("소고기")
        		.build();
        
        // meat를 제외한 변수를 초기화 하는 경우 
        Food food2 = new FoodBuilder()
        		.start()
        		.setSource("쌀스프")
        		.setNoodle("국수")
        		.build();

        System.out.println(food1.toString());
        System.out.println(food2.toString());

    }
}

4. 결과화면

 

블로그 이미지

미나미나미

,

[Java] Super()의 이해

[java] 2019. 12. 23. 14:48

[Java] Super()의 이해

- Super() 부모의 요소를 접근 하기 위해서 사용. 

  - 클래스 생성자 , public 변수,  public 함수의 접근이 가능함.


 

- ParentClass를 생성 후, ChildClass의 상속하는 구조.


1. Parent와 Child 클래스

ParentClass 클래스

package parent;

public class ParentClass {
	// private 요소 
	private String mother;
	private String father;
	// public 요소
	public String car = "BMW";
	
	// 빈 생성자 
	public ParentClass() {
		this.mother = "ParentMother";
		this.father = "ParentFather";
	}
	
	public ParentClass(String mother , String father) {
		this.mother = mother;
		this.father = father;
	}
	
	public String toString() {
		return "Parent = > " + this.father + " / " + "Parent = > " + this.mother; 
	}
	
	public String getFather() {
		return father;
	}
	
	public String getMother() {
		return mother;
	}
}

 

 

 

ChildClass 클래스

package child;

import parent.ParentClass;

public class ChildClass extends ParentClass {

	private String daughter;
	private String son;
	
	// 자식의 요소에만 값 할당, 부모의 요소는 접근하지 않음.
	public ChildClass(String daughter, String son) {
		this.daughter = daughter;
		this.son = son;
	}

	// 자식 요소와 부모 요소에 접근. 
	public ChildClass() {
		// 부모의 생성자를 호출하여 사용.
		super("ChildDaughter", "ChildSon");
		// 부모의 public 변수에 접근하여 값 변경
		super.car = "K7";
		
		// 자식의 요소의 값 할당 
		this.daughter = "not";
		this.son = "not";
	}

	public String toString() {
		return "Child = > " + super.getFather() + "/" + "Child = > " + super.getMother() + "/" + "Child = > "
				+ this.daughter + "/" + "Child = > " + this.son + "/" + "car = > " + super.car;
	}
}

2. Main Class

import child.ChildClass;

public class Main {

	public static void main(String[] args) {
		
		System.out.println("부모 Class 그대로 사용");
		ChildClass child1 = new ChildClass("Main1" , "Main2");
		System.out.println(child1.toString());
		
		System.out.println("부모 Class 초기화(Super()) 사용");
		ChildClass child2 = new ChildClass();
		System.out.println(child2.toString());		
	}

}

3. 결과화면

 

블로그 이미지

미나미나미

,