Java, Servlet, JSP에 대한 기본적인 사항을 정리한다.
// 한줄 짜리 주석
/* 여러줄 짜리 주석 */
try {
} catch(ex) {
} finally {
}
request.setCharacterEncoding("utf-8");
String name = request.getParameter("name");
URL
URL url = null;
HttpURLConnection conn = null;
//BufferedWriter out = null;
PrintWriter out = null;
BufferedReader inp = null;
String buf = null;
try {
url = new URL(requestURL);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
conn.setDoOutput(true);
conn.setDoInput(true);
//out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "8859_1"), true);
out.write("Post data");
out.flush();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inp = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
while ((buf = inp.readLine()) != null) {
System.out.println(buf);
}
} else {
System.out.println("Bad post ... : " + conn.getResponseCode() + " : " + conn.getResponseMessage());
}
inp.close();
out.close();
} catch (MalformedURLException e) {
System.out.println(e);
return false;
} catch (IOException e) {
System.out.println(e);
return false;
} finally {
if (inp != null) {
try { inp.close(); } catch (IOException e) { }
inp = null;
}
if (out != null) {
try { out.close(); } catch (Exception e) { }
out = null;
}
}
Cookie 조회
private String getCookie(HttpServletRequest req, String name)
{
String rtStr = null;
Cookie cookies[](.md) = null;
cookies = req.getCookies();
for (int idx = 0;idx < cookies.length;idx++) {
if (cookies[idx](idx.md).getName().equals(name)) {
rtStr = cookies[idx](idx.md).getValue();
break;
}
}
return rtStr;
}
Cookie 등록
Cookie cookie = new Cookie("username", name);
cookie.setMaxAge(30*60); //30분...
response.addCookie(cookie);
String inputLine = null;
File tmpFile = null;
BufferedReader inp = null;
tmpFile = new File("/docs/hello.html");
try {
inp = new BufferedReader(new FileReader(tmpFile));
while ((inputLine = inp.readLine()) != null) {
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inp != null) {
try {
inp.close();
} catch (IOException e) {
e.printStackTrace();
}
}
inp = null;
}
Library
UtilExcel.java with POI
package com.jopenbusiness.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
//--- HSSF : ~.xls, XSSF : ~.xlsx
public class UtilExcel {
public static XSSFWorkbook getWorkbook(String fileName) {
try {
return new XSSFWorkbook(new FileInputStream(new File (fileName)));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static XSSFSheet getSheet(String fileName, String sheetName) {
XSSFWorkbook excel = null;
excel = getWorkbook(fileName);
return (excel == null) ? null:excel.getSheet(sheetName);
}
public static XSSFCell getCell(XSSFSheet sheet, Integer idxRow, Integer idxCol) {
XSSFRow row = null;
row = sheet.getRow(idxRow);
return (row == null) ? null:row.getCell(idxCol);
}
public static String getCellType(XSSFCell cell) {
if (cell == null) {
return "String";
}
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC : return (DateUtil.isCellDateFormatted(cell)) ? "Date/" + cell.getCellType():"Numeric/" + cell.getCellType();
case Cell.CELL_TYPE_STRING : return "String/" + cell.getCellType();
case Cell.CELL_TYPE_FORMULA : return "Formula/" + cell.getCellType();
case Cell.CELL_TYPE_BOOLEAN : return "Boolean/" + cell.getCellType();
case Cell.CELL_TYPE_BLANK : return "Blank/" + cell.getCellType();
case Cell.CELL_TYPE_ERROR : return "Error/" + cell.getCellType();
default : return "Other/" + cell.getCellType();
}
}
public static String getCellType(XSSFSheet sheet, Integer idxRow, Integer idxCol) {
return getCellType(getCell(sheet, idxRow, idxCol));
}
public static String getCellString(XSSFCell cell, String defaultValue) {
String rtStr = null;
if (cell == null) {
return defaultValue;
}
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING :
rtStr = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_NUMERIC :
if (DateUtil.isCellDateFormatted(cell)) {
rtStr = UtilDate.getFormattedDate(cell.getDateCellValue(), UtilDate.SIMPLE_DATE_FORMAT);
} else {
rtStr = String.valueOf(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN :
rtStr = (cell.getBooleanCellValue()) ? "true":"false";
break;
case Cell.CELL_TYPE_FORMULA :
// rtStr = cell.getCellFormula();
rtStr = cell.getRawValue();
break;
case Cell.CELL_TYPE_BLANK :
rtStr = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_ERROR :
rtStr = cell.getErrorCellString();
break;
default :
rtStr = "/" + cell.getCellType() + "/" + cell.toString() + "/";
}
return rtStr;
}
public static String getCellString(XSSFCell cell) {
return getCellString(cell, "");
}
public static String getCellString(XSSFSheet sheet, Integer idxRow, Integer idxCol, String defaultValue) {
return getCellString(getCell(sheet, idxRow, idxCol), defaultValue);
}
public static String getCellString(XSSFSheet sheet, Integer idxRow, Integer idxCol) {
return getCellString(sheet, idxRow, idxCol, "");
}
public static List getRowStrings(XSSFSheet sheet, Integer idxRow, Integer idxColFr, Integer idxColTo) {
List rtList = null;
rtList = new ArrayList();
for (Integer idx = idxColFr;idx <= idxColTo;idx++) {
rtList.add(getCellString(sheet, idxRow, idx));
}
return rtList;
}
public static List> getTableStrings(XSSFSheet sheet, Integer idxColFr, Integer idxColTo) {
List> rtList = null;
List rowList = null;
Integer cntSkip = null;
Integer idxRow = null;
String tmpApply = null;
idxRow = 0;
cntSkip = 0;
rtList = new ArrayList>();
while (true) {
rowList = getRowStrings(sheet, idxRow, idxColFr, idxColTo);
if (sheet.getLastRowNum() < idxRow) {
break;
}
idxRow++;
tmpApply = rowList.get(0);
if ((tmpApply != null) && (tmpApply.equalsIgnoreCase("End Table"))) {
break;
}
if ((tmpApply == null) || (!tmpApply.equals("적용"))) {
cntSkip = cntSkip + 1;
if (100 < cntSkip) {
break;
}
continue;
}
cntSkip = 0;
rtList.add(rowList);
}
return rtList;
}
public static List findRowStrings(XSSFSheet sheet, Integer findIdx, String findStr, Integer idxColFr, Integer idxColTo) {
String tmpStr = null;
for (Integer idx = sheet.getFirstRowNum();idx <= sheet.getLastRowNum();idx++) {
tmpStr = getCellString(sheet, idx, findIdx);
if ((tmpStr != null) && (tmpStr.equals(findStr))) {
return getRowStrings(sheet, idx, idxColFr, idxColTo);
}
}
return null;
}
public static String toString(List dataStr) {
String rtStr = null;
for (String item : dataStr) {
rtStr = (rtStr == null) ? "":rtStr + ", ";
rtStr = rtStr + "[+ item + "](")";
}
return rtStr;
}
}
Java에서 제공하는 Java Reflection 기능을 사용하면 동적으로 Class, Method를 관리할 수 있다.
try {
Class c = Class.forName(args[0](0.md)); //--- c = String.class
Method m[](.md) = c.getDeclaredMethods();
//--- getDeclaredMethods()메소드 대신 getMethods()를 사용하게 되면, 상속된 메소드의 정보까지 얻을수있다.
for (int i = 0; i < m.length; i++)
System.out.println(m[i](i.md).toString());
}
catch (Throwable e) {
System.err.println(e);
}
HashMap map = new HashMap();
map.put("name", "value");
for (Map.Entry entry : processInfo.entrySet()) {
entry.getKey(), entry.getValue()
}
extractHtml.vbs (WScript 파일)
'===============================================================================
' 프로그램 명 : /extractHtml.vbs
' 프로그램 설명 : Java를 컴파일하고 실행하기 위한 스크립트
' 작성자 : 산사랑
' 작성일 : 2008.07.08 ~ 2008.07.08
'------ [관리](History) ---------------------------------------------------------
' 수정자 :
' 수정일 :
' 수정 내용 :
'------ [Copyright](Copyright.md) ------------------------------------------------------------
' Copyright (c) 1995-2008 pnuskgh, All rights reserved.
'===============================================================================
On Error Resume Next
'-------------------------------------------------------------------------------
' Main Routine
'-------------------------------------------------------------------------------
Dim objShell
Set objShell = CreateObject("WScript.Shell")
'objShell.Run "cmd /C ""javac extractHtml.java & java extractHtml & notepad extractHtml.out & pause"""
objShell.Run "cmd /C ""javac extractHtml.java & java extractHtml & notepad extractHtml.out"""
Set objShell = Nothing
'===============================================================================
' 프로그램 명 : /ant_run.vbs
'===============================================================================
DES 암호화, 복호화 모듈
public class UtilCrypto {
public static Key desKey = null;
public static Key getDesKey() {
if (desKey == null) {
desKey = makeDesKey();
}
return desKey;
}
public static void setDesKey(Key desKey) {
UtilCrypto.desKey = desKey;
}
public static Key makeDesKey() {
KeyGenerator generator = null;
try {
generator = KeyGenerator.getInstance("DES");
// generator = KeyGenerator.getInstance("TripleDES");
// generator = KeyGenerator.getInstance("AES");
generator.init(new SecureRandom());
return generator.generateKey();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
public static String crypt(String algorithm, Integer cryptMode, Key key, String inpStr) {
String rtStr = null;
Cipher cipher = null;
if ((inpStr == null) || (inpStr.length() == 0)) {
return "";
}
try {
if (algorithm.equals("DES")) {
cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
} else if (algorithm.equals("TripleDES")) {
cipher = Cipher.getInstance("TripleDES/ECB/PKCS5Padding");
} else if (algorithm.equals("RSA")) {
cipher = Cipher.getInstance("RSA");
} else {
cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
}
if (cryptMode == Cipher.ENCRYPT_MODE) {
cipher.init(Cipher.ENCRYPT_MODE, key);
rtStr = Base64Encoder.encode(cipher.doFinal(inpStr.getBytes("UTF-8")));
} else {
cipher.init(Cipher.DECRYPT_MODE, key);
rtStr = new String(cipher.doFinal(Base64Decoder.decodeToBytes(inpStr)), "UTF-8");
}
} 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();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return rtStr;
}
public static String encryptDes(String plain) {
return crypt("DES", Cipher.ENCRYPT_MODE, getDesKey(), plain);
}
public static String decryptDes(String security) {
return crypt("DES", Cipher.DECRYPT_MODE, getDesKey(), security);
}
}
public class UtilCrypto {
public static KeyPair rsaKey = null;
public static KeyPair getRsaKeyPair() {
if (rsaKey == null) {
rsaKey = makeRsaKeyPair();
}
return rsaKey;
}
public static Key getRsaPublicKey() {
if (rsaKey == null) {
getRsaKeyPair();
}
return rsaKey.getPublic();
}
public static Key getRsaPrivateKey() {
if (rsaKey == null) {
getRsaKeyPair();
}
return rsaKey.getPrivate();
}
public static void setRsaKeyPair(KeyPair rsaKey) {
UtilCrypto.rsaKey = rsaKey;
}
public static KeyPair makeRsaKeyPair() {
KeyPairGenerator generator = null;
try {
generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048); //--- keysize
return generator.genKeyPair();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
public static String encryptRsa(String plain) {
return crypt("RSA", Cipher.ENCRYPT_MODE, getRsaPublicKey(), plain);
}
public static String decryptRsa(String security) {
return crypt("RSA", Cipher.DECRYPT_MODE, getRsaPrivateKey(), security);
}
}
extractHtml.java : 여러 페이지로 작성된 HTML에서 원하는 문자열을 추출하는 프로그램, 필요시 수정하여 사용하세요.
//==============================================================================
// 프로그램 명 : extractHtml.java, Version 0.01
// 프로그램 설명 : HTML에서 원하는 문자열을 추출
// 작성자 : 산사랑
// 작성일 : 2008.07.08 ~ 2008.07.08
//----- [관리](History) ---------------------------------------------------------
// 수정자 :
// 수정일 :
// 수정 내용 :
//----- [Copyright](Copyright.md) ------------------------------------------------------------
// Copyright (c) 1995-2008 pnuskgh, All rights reserved.
//==============================================================================
import java.io.*;
import java.net.*;
class extractHtml
{
public static void main(String args[](.md))
{
int idx = 0, checkIdx = 0, cntRead = 0;
URL url = null;
String strUrl = "http://serverHost/main.php?catid=&skey=&page=";
String inputLine = null;
BufferedReader inp = null;
BufferedWriter out = null;
File outFile = null;
String fileNameOut = "extractHtml.out";
String delimiter = "|";
try {
outFile = new File(fileNameOut);
if (outFile.exists()) {
outFile.delete();
}
out = new BufferedWriter(new FileWriter(outFile));
for (idx = 1;idx <= 221;idx++) {
url = new URL(strUrl + idx);
inp = new BufferedReader(new InputStreamReader(url.openStream()));
while ((inputLine = inp.readLine()) != null) {
if (-1 < inputLine.indexOf("main.php?in=building_detail")) {
checkIdx = checkIdx + 1;
if (checkIdx == 1) {
out.write(idx + delimiter + ++cntRead + delimiter);
out.write(inputLine.substring(inputLine.lastIndexOf("'>") + 2, inputLine.indexOf("")) + delimiter);
}
if (checkIdx == 2) {
out.write(inputLine.substring(inputLine.lastIndexOf("'>") + 2, inputLine.indexOf("")) + delimiter);
}
}
if (-1 < inputLine.indexOf("/main.php?in=corp_detail&type=corp")) {
checkIdx = checkIdx + 1;
if (checkIdx == 5) {
out.write(inputLine.substring(inputLine.lastIndexOf("'>") + 2, inputLine.indexOf("")) + delimiter);
out.write("http://serverHost/main.php?id=" + inputLine.substring(inputLine.indexOf("id=") + 3, inputLine.indexOf("page=") - 1) + "\r\n");
checkIdx = 0;
} else {
out.write(inputLine.substring(inputLine.lastIndexOf("'>") + 2, inputLine.indexOf("")) + delimiter);
}
}
}
inp.close();
}
out.flush();
out.close();
} catch (Exception e) {
System.out.println(e);
} finally {
if (inp != null) {
try {
inp.close();
} catch (IOException e) {
e.printStackTrace();
}
}
inp = null;
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
out = null;
}
}
}
//==============================================================================
// 프로그램 명 : extractHtml.java
//==============================================================================
Universally Unique Identifier(또는 Globally Unique Identifier)의 종류
UUID의 구성
Sample
package kr.co.daou.common;
import java.util.Random;
import java.util.UUID;
import org.safehaus.uuid.UUIDGenerator;
public class GUID
{
private static Random rand = null;
public static void main(String args[](.md)) {
System.out.println("Unique ID Generation Test");
for (int cnt = 0;cnt < 100;cnt ++) {
System.out.println(getPrefixUUID("user"));
}
}
public static String getPrefixUUID(String prefix)
{
return prefix + "." + getUUID1();
}
public static String getUUID() {
return getUUID1();
}
//--- MAC address based, [uuid-3.2.jar (MIT License)](http://johannburkard.de/software/uuid/) 사용
public static String getUUID1() {
return (new com.eaio.uuid.UUID()).toString();
}
//--- Name based + MD5 hash, java.util.UUID 사용
public static String getUUID3() {
return getUUID3("Hello World!");
}
public static String getUUID3(String seed) {
seed = seed + Long.toString(rand.nextLong());
return UUID.nameUUIDFromBytes(seed.getBytes()).toString();
}
//--- Random, java.util.UUID 사용
public static String getUUID4() {
return UUID.randomUUID().toString();
}
//--- Random, [jug-lgpl-2.0.0.jar (GNU LGPL)](http://jug.safehaus.org/) 사용
public static String getUUID4_1() {
return UUIDGenerator.getInstance().generateRandomBasedUUID().toString();
}
//--- [jug-lgpl-2.0.0.jar (GNU LGPL)](http://jug.safehaus.org/) 사용
public static String getUUID_jug() {
return UUIDGenerator.getInstance().generateTimeBasedUUID().toString();
}
static {
rand = new Random(System.currentTimeMillis());
}
}
- 참고 문헌
- [Universally unique identifier](http://en.wikipedia.org/wiki/Universally_Unique_Identifier)
- [Java UUID Generators](http://ultteky.egloos.com/10506237)
- [uuidgen](http://www.famkruithof.net/uuid/uuidgen)
- [Java Uuid Generator (JUG)](http://jug.safehaus.org/)
## Java 8
- [Eclipse LUNA](http://www.eclipse.org/downloads/index-developer.php)에서 Java 8을 공식적으로 지원
- Jigsaw
- 참고 문헌
- *[Java 8 개선 사항 관련 글 모음, 2014.05](http://blog.fupfin.com/?p=27)
- *[http://blog.fupfin.com/?p=27 [http://www.techempower.com/blog/2013/03/26/everything-about-java-8/]](http://www.techempower.com/blog/2013/03/26/everything-about-java-8/)
- *[http://blog.fupfin.com/?p=27 [http://www.techempower.com/blog/2013/03/26/everything-about-java-8/ [http://www.oracle.com/kr/corporate/magazines/winter-tech2-1429486-ko.pdf]]](http://www.oracle.com/kr/corporate/magazines/winter-tech2-1429486-ko.pdf)
### 람다식 (Lambda Expression)
함수형 프로그램밍을 통해 멀티 코어 CPU 지원
람다식 형태
- (x, y) -> { x + y }
- (x, y) -> x + y
- x -> x + 5
//--- 함수형 인터페이스 : 추상 메서드가 한개인 인터페이스
@FunctionalInterface
public interface funcArg {
int methodOne(int a, int b);
}
funcArg aa = (a, b) -> { return a + b }
public void test(int one, int two, funcArg arg1) { arg1.methodOne(one, two); } test(1, 2, aa);
### Stream (Java Collection API)
- Collection을 Pipe 형식으로 처리하는 함수형 API 지원
- Collection (List, Map, Set)을 Stream으로 처리
- java.util.stream
List
numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
for (Integer number : numbers) { //--- 예전 방식 System.out.println(number); }
numbers.forEach(value -> System.out.println(value)); //--- 최신 방식 //--- numbers.forEach((Integer value) -> System.out.println(value)); //--- numbers.forEach(System.out::println);
strings = numbers.stream() .filter(v -> v > 4) .map(v -> new String("" + (v + 10))) .collect(Collectors.toList()); strings.forEach(System.out::println);
스트림의 종류
- Stream<T>
- IntStream, LongStream, DoubleStream
병렬 처리
- 순차 처리 스트림
- *numbers.stream()
- *numbers.parallelStream().sequential()
- 병렬 처리 스트림
- *numbers.parallelStream()
- *numbers.stream().parallel()
스트림용 함수
- ~.forEach(~) : 각각에 대해서 처리
- ~.anyMatch(~) : 조건을 만족할 때 True 반환
- ~.filter(~) : True에 해당하는 데이터 반환
- ~.sorted(~) : 정렬 조건에 따라 정렬
- ~.collect(Collectors.toList()) : List 반환
- ~.findFirst() : 첫번째 데이터 반환
- ~.orElseThrow(() -> new Exception(~)) : 데이터가 없으면 Exception 발생
### Nashorn
[[JavaScript|JavaScript]] 엔진으로 [ECMAScript](ECMAScript.md) 5.1 (ECMA-262) 준수
Java 7의 invokedynamic 활용, Java 객체 호출 가능
javax.script (JSR 223) API 지원
Nashorn (나즈혼) 실행
- jjs 명령어
- ScriptManager
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval("~");
## 문제 해결
- "java.lang.OutOfMemoryError: PermGen space" 오류가 발생할 경우 다음 옵션을 준다.
-Xms512m -Xmx1024m -XX:PermSize=64M //--- 해당 옵션 -XX:MaxPermSize=128M //--- 해당 옵션 -verbose:gc -verbose:class
```