728x90

출처 : Apache POI - the Java API for Microsoft Documents
java - Get an image and its position from excel file using Apache POI

POI로 엑셀 파일 열기

import java.io.File;
import java.io.FileInputStream;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class TestPoiMain {
	
	public static void main(String[] args) throws Exception {
		// 
		String fileName = "test1.xlsx";
		//
		File xlsFile = new File(fileName);
		
		Workbook workbook = null;
		try {
			if (xlsFile.exists()) {
				FileInputStream inputStream = new FileInputStream(xlsFile);
				workbook = new XSSFWorkbook(inputStream);

				System.out.println(workbook);
			}
		} finally {
			if (workbook != null)
				workbook.close();
		}
	}
}

POI로 Excel 파일 내에 이미지 추출

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFPicture;
import org.apache.poi.xssf.usermodel.XSSFPictureData;
import org.apache.poi.xssf.usermodel.XSSFShape;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class TestPoiMain {
	
	public static void main(String[] args) throws Exception {
		// 
		String fileName = "test1.xlsx";
		String tarDir = "c:\\test";
		//
		File xlsFile = new File(fileName);
		
		Workbook workbook = null;
		try {
			if (xlsFile.exists()) {
				FileInputStream inputStream = new FileInputStream(xlsFile);
				workbook = new XSSFWorkbook(inputStream);
				
				XSSFSheet sheet = (XSSFSheet) workbook.getSheetAt(0);
				XSSFDrawing drawing = sheet.createDrawingPatriarch(); // I know it is ugly, actually you get the actual instance here
				for (XSSFShape shape : drawing.getShapes()) {
					if (shape instanceof XSSFPicture) {
						XSSFPicture picture = (XSSFPicture) shape;
						
						if (picture.getPictureData()==null) {
							System.out.println("사진 Path 사용");
							continue;
						}
						XSSFPictureData xssfPictureData = picture.getPictureData();
						ClientAnchor anchor = picture.getPreferredSize();
						int row1 = anchor.getRow1();
						int row2 = anchor.getRow2();
						int col1 = anchor.getCol1();
						int col2 = anchor.getCol2();
						System.out.println("Row1: " + row1 + " Row2: " + row2);
						System.out.println("Column1: " + col1 + " Column2: " + col2);
						// Saving the file
						String ext = xssfPictureData.suggestFileExtension();
						byte[] data = xssfPictureData.getData();
						
						FileOutputStream out = new FileOutputStream(String.format("%s\\%s_%d_%d.%s", tarDir, sheet.getSheetName(), row1, col1, ext));
						out.write(data);
						out.close();
					}
				}
			}
		} finally {
			if (workbook != null)
				workbook.close();
		}
	}
}
728x90
728x90

출처 : How to convert Java object to / from JSON (Jackson) - Mkyong
스프링3(Spring3) - @ResponseBody + jackson을 이용하여 심플하게 구현하기
Chapter16. 스프링 MVC로 REST API 사용하기 · Spring Study Group
Spring에서 JSON과 연동방법 - 와이케이의 마구잡이 - GitHub Pages
[ERROR:] cvc-complex-type.2.1: Element 'mvc ... - kkan's - Tistory

pom.xml 내용 추가

		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.9.13</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-core-asl</artifactId>
			<version>1.9.13</version>
		</dependency>

VO 객체

package com.myhome.dto;

import java.util.ArrayList;

public class JSONTest {
	
	private int id;
	private String txt;
	private ArrayList<String> list;
	private String[] arr;

	public String[] getArr() {
		return arr;
	}

	public void setArr(String[] arr) {
		this.arr = arr;
	}

	public ArrayList<String> getList() {
		return list;
	}

	public void setList(ArrayList<String> list) {
		this.list = list;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getTxt() {
		return txt;
	}

	public void setTxt(String txt) {
		this.txt = txt;
	}
}

Controller

package com.myhome.ui;

import java.io.IOException;
import java.util.ArrayList;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.myhome.dto.JSONTest;

@Controller
public class HelloController {

	@RequestMapping(value = "/jsonTest.do", method = RequestMethod.GET, produces = "application/json")
	public @ResponseBody String jsonTest() throws JsonGenerationException, JsonMappingException, IOException {
		
		// 가상의 배열및 리스트에 데이터 add
		ArrayList<String> arraylist = new ArrayList<String>();
		arraylist.add("a");
		arraylist.add("b");
		String[] array = { "a", "b", "c" };

		// VO객체에 SET한후 vo객체자체를 return
		JSONTest test = new JSONTest();
		test.setId(1);
		test.setTxt("textTxt");
		test.setList(arraylist);
		test.setArr(array);
		
		ObjectMapper mapper = new ObjectMapper();
		String jsonString = mapper.writeValueAsString(test);
		
		return jsonString;
	}
}

실행

728x90
728x90

출처 : 스프링3(Spring3) - @ResponseBody + jackson을 이용하여 심플하게 구현하기
Chapter16. 스프링 MVC로 REST API 사용하기 · Spring Study Group
Spring에서 JSON과 연동방법 - 와이케이의 마구잡이 - GitHub Pages
[ERROR:] cvc-complex-type.2.1: Element 'mvc ... - kkan's - Tistory

pom.xml 내용 추가

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.6.3</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.6.3</version>
		</dependency>

***-servlet.xml 내용 추가

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:security="http://www.springframework.org/schema/security"
       xsi:schemaLocation="http://www.springframework.org/schema/aop       http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
                           http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                           http://www.springframework.org/schema/context   http://www.springframework.org/schema/context/spring-context-2.5.xsd
                           http://www.springframework.org/schema/jee       http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
                           http://www.springframework.org/schema/mvc       http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
                           http://www.springframework.org/schema/tx        http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
                           http://www.springframework.org/schema/security  http://www.springframework.org/schema/security/spring-security-2.0.xsd">

	<mvc:annotation-driven>
		<mvc:message-converters>
			<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
				<property name="supportedMediaTypes">
					<list>
						<value>text/html;charset=UTF-8</value>
						<value>application/json;charset=UTF-8</value>
					</list>
				</property>
			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>

VO 객체

package com.myhome.dto;

import java.util.ArrayList;

public class JSONTest {
	
	private int id;
	private String txt;
	private ArrayList<String> list;
	private String[] arr;

	public String[] getArr() {
		return arr;
	}

	public void setArr(String[] arr) {
		this.arr = arr;
	}

	public ArrayList<String> getList() {
		return list;
	}

	public void setList(ArrayList<String> list) {
		this.list = list;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getTxt() {
		return txt;
	}

	public void setTxt(String txt) {
		this.txt = txt;
	}
}

Controller

package com.myhome.ui;

import java.util.ArrayList;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.myhome.dto.JSONTest;

@Controller
public class HelloController {

	@RequestMapping(value = "/jsonTest.do", method = RequestMethod.GET, produces = "application/json")
	public @ResponseBody JSONTest jsonTest() {
		
		// 가상의 배열및 리스트에 데이터 add
		ArrayList<String> arraylist = new ArrayList<String>();
		arraylist.add("a");
		arraylist.add("b");
		String[] array = { "a", "b", "c" };

		// VO객체에 SET한후 vo객체자체를 return
		JSONTest test = new JSONTest();
		test.setId(1);
		test.setTxt("textTxt");
		test.setList(arraylist);
		test.setArr(array);
		return test;
	}
}

실행

JavaScript : array to json string

JSON.stringify

function doSave() {
	
	var arr_select_class = [];
	
	var class_combo_list = $('.div_sel_class');
	
	$.each(class_combo_list, function(index, data) {
		var main_yn = $(data).find('#main_yn').attr('checked');
		var sel_class6 = $(data).find('#sel_class6').val();
		
		var data1 = {
			index : index,
			main_yn : main_yn,
			class_index : sel_class6
		};
		
		arr_select_class.push(data1);
	});
	
	var form1 = document.InsertForm2;
	form1.json_select_class.value = JSON.stringify(arr_select_class); 
	form1.submit();
}

Java : json string to json object

		JSONParser parser = new JSONParser();
		JSONObject json_select_class_obj = (JSONObject) parser.parse(json_select_class);
		
		logger.debug(json_select_class_obj.toString());
728x90
728x90

출처 : [nodejs] 윈도우에서 node.js 설치 및 실행하기 - 워크식스 블로그

PATH에 추가

C:\server\node-v6.11.2-win-x64

Hello world

C:\> node
>
(To exit, press ^C again or type .exit)
> console.log('hello world!')
hello world!
undefined

웹서비스

// 모듈을 추출합니다.
var http = require('http');

// 웹 서버를 만들고 실행합니다.
http.createServer(function (request, response) {
  response.writeHead(200, { 'Content-Type': 'text/html' });
  response.end('<h1>Hello World!</h1>');
}).listen(80, function () {
  console.log('Server running at http://127.0.0.1/');
});

실행

C:\> node http_test.js
728x90
728x90

Swift - 외부라이브러리 사용

출처 : DLRadioButton
Seorenn SIGSEGV: Swift 프로젝트에서 Objective-C 코드를 함께 사용하기

외부라이브러리 파일 추가

파일 추가 옵션 선택

브릿지 헤더 파일 생성

브릿지 헤더 파일 설정

자동으로 설정되지만 설정이 되지 않았을 경우 아래와 같이 설정 필요

Button Type 변경

Button Type 변경 전

Button Type 변경 후

Button 라디오버튼의 경우 그룹으로 묶기

Button 라디오버튼 하나의 이벤트 생성


Button 라디오버튼 이벤트 구현

    @IBAction func optionClicked(_ sender: DLRadioButton) {
        print(sender.currentTitle!)

        if (sender == radio1) { // (sender.currentTitle == "석굴암") {
            imageView.image = image1
        } else if (sender.currentTitle == "남대문") {
            imageView.image = image2
        } else if (sender.currentTitle == "독립기념관") {
            imageView.image = image3
        }
    }
728x90
728x90

출처 : IOS 오토레이아웃(AUTOLAYOUT) 사용패턴1 화면 가운데 버튼 배치하기

Top, Width, Height 설정

가운데 정렬


상대 좌표 배치

수평 상대 좌표 설정

수직 상대 좌표 배치

멀티터치 옵션 설정

728x90
728x90

출처 : Freehand drawing on iOS in Swift - Ilya Puchka


    override func touchesBegan(_ touches: Set<uitouch>, with event: UIEvent?) {
        if let touch = touches.first {
            messageLabel.text = "touchesBegan"
            tapCountLabel.text = String(touch.tapCount)
            touchCountLabel.text = String(touches.count)
            
            lastPoint = touch.location(in: drawImageView)
        }
    }
    
    override func touchesMoved(_ touches: Set<uitouch>, with event: UIEvent?) {
        if let touch = touches.first {
            messageLabel.text = "touchesMoved"
            tapCountLabel.text = String(touch.tapCount)
            touchCountLabel.text = String(touches.count)
            
            lineWidth = CGFloat(Int(textLineWidth.text!)!);
            
            UIGraphicsBeginImageContext(drawImageView.frame.size)
            if let context = UIGraphicsGetCurrentContext() {
                context.setLineWidth(lineWidth)
                context.setStrokeColor(lineColor)
                context.setLineCap(CGLineCap.round)
                
                drawImageView.image?.draw(in: CGRect(origin: CGPoint(x : 0, y : 0), size: drawImageView.frame.size))
                
                context.move(to: lastPoint)
                let currentPoint = touch.location(in: drawImageView)
                context.addLine(to : currentPoint)
                context.strokePath()
                
                drawImageView.image = UIGraphicsGetImageFromCurrentImageContext()
                
                lastPoint = currentPoint
            }
            UIGraphicsEndImageContext()
        }
    }

    override func touchesEnded(_ touches: Set<uitouch>, with event: UIEvent?) {
        if let touch = touches.first {
            messageLabel.text = "touchesEnded"
            tapCountLabel.text = String(touch.tapCount)
            touchCountLabel.text = String(touches.count)
        }
    }


728x90
728x90

출처 : Swift 에러 (Error) 처리, 예외 상황 다루기 (try, throws, defer 등) : 네이버 ...

    enum ParseError : Error {
        case OverSize
        case UnderSize
        case InvalidFormat(value : String)
        case InvalidData(value : String)
    }

예외발생

    func parseTime(timeString : NSString) throws -> Time {
        
        var retTime = Time(hour : 0, min : 0, sec : 0)
        
        guard timeString.length == 8 else {
            if timeString.length > 8 {
                throw ParseError.OverSize
            } else {
                throw ParseError.UnderSize
            }
        }
        
        if let hour = Int(timeString.substring(to: 2)) {
            print(hour)
            guard hour >= 0 && hour < 24 else {
                throw ParseError.InvalidFormat(value: "시간")
            }
            
            retTime.hour = hour
        } else {
            throw ParseError.InvalidFormat(value: "시간")
        }
        
        if let min = Int(timeString.substring(with : NSRange(location : 3, length : 2))) {
            print(min)
            guard min >= 0 && min < 60 else {
                throw ParseError.InvalidFormat(value: "분")
            }
            
            retTime.min = min
        } else {
            throw ParseError.InvalidFormat(value: "분")
        }
        
        if let sec = Int(timeString.substring(from : 6)) {
            print(sec)
            guard sec >= 0 && sec < 60 else {
                throw ParseError.InvalidFormat(value: "초")
            }
            
            retTime.sec = sec
        } else {
            throw ParseError.InvalidFormat(value: "초")
        }
        
        return retTime		
    }

예외처리

    func getPartTime(timeString : NSString, type : String) {
        do {
            let time = try parseTime(timeString : timeString)
            
            switch type {
            case "hour":
                print("\(time.hour)시")
            case "min":
                print("\(time.min)분")
            case "sec":
                print("\(time.sec)초")
            default:
                print("입력값 배당 시간 정보 없음")
            }
            
        }
        catch ParseError.OverSize {
            print("입력 문자열이 깁니다.")
        }
        catch ParseError.UnderSize {
            print("입력 문자열이 짧습니다.")
        }
        catch ParseError.InvalidData(let part) {
            print("입력값의 \(part)에 해당하는 형식 오류")
        }
        catch ParseError.InvalidFormat(let part) {
            print("입력값의 \(part)에 해당하는 값 오류")
        }
        catch {
            print("알 수 없는 오류")
        }
    }
728x90

+ Recent posts