참고사이트
https://www.baeldung.com/java-web-start
https://github.com/eugenp/tutorials/tree/master/jws
https://docs.oracle.com/javase/7/docs/technotes/guides/javaws/developersguide/development.html#security
* 이클립스에서 dynamic web app 프로젝트 생성
* Hello 클래스 구현
--------------------------------------------------------------------------------
package com.example;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Hello {
public static void main(String[] args) throws Exception {
JFrame f = new JFrame("main");
f.setSize(200, 100);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Hello, world!");
f.add(label);
f.setVisible(true);
//FilePermission p = new FilePermission("<>", "execute");
Runtime.getRuntime().exec("cmd /c start excel.exe");
}
}
--------------------------------------------------------------------------------
* Configure > Add maven nature
* pom.xml
--------------------------------------------------------------------------------
'>http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0webappwebapp0.0.1-SNAPSHOTwarsrcmaven-compiler-plugin3.7.01.81.8maven-war-plugin3.0.0WebContentorg.apache.maven.pluginsmaven-jar-plugincompilejar
com.example.Hello
${project.basedir}/WebContent
--------------------------------------------------------------------------------
* servlet 관련 jar 파일 복사
아래 URL에서 jardiff.jar, jnlp-servlet.jar 파일을 받아 WEB-INF/lib에 복사
https://github.com/eugenp/tutorials/tree/master/jws/java-core-samples-lib
* WEB-INF/web.xml 편집
--------------------------------------------------------------------------------
Java Web StartJNLP Example for Java Web Start ArticleJnlpDownloadServletjnlp.sample.servlet.JnlpDownloadServletJnlpDownloadServlet*.jarJnlpDownloadServlet*.jnlpindex.html
--------------------------------------------------------------------------------
* WebContent 디렉토리에 index.html 파일생성
--------------------------------------------------------------------------------
Launch
--------------------------------------------------------------------------------
* WebContent 디렉토리에 hello.jnlp 파일생성
--------------------------------------------------------------------------------
HelloExample
--------------------------------------------------------------------------------
* jar 파일생성: 프로젝트 우클릭 > Run As > Maven Install
* jar 파일 sign
cmd > cd [webapp-dir]
# keytool -genkey -keystore myKeystore -alias myself
# keytool -selfcert -alias myself -keystore myKeystore
# keytool -list -keystore myKeystore
# jarsigner -keystore myKeystore webapp-0.0.1-SNAPSHOT.jar myself
* 톰켓에 Dynamic web app 프로젝트를 추가하고 시작
* http://localhost:8080/webapp/ 접속 & Launch 버튼클릭
hello.jnlp 다운로드
hello.jnpl 파일열기
public static void main(String[] args) throws Exception{ String packageName = "a.b.c.d"; List<?> list = getClasses(packageName); System.out.println(list); }
/** * Scans all classes accessible from the context class loader which belong to the given package and subpackages. * * @param packageName The base package * @return The classes * @throws ClassNotFoundException * @throws IOException */ public static List<?> getClasses(String packageName) throws ClassNotFoundException, IOException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); assert classLoader != null; String path = packageName.replace('.', '/'); Enumeration<URL> resources = classLoader.getResources(path); List<File> dirs = new ArrayList<File>(); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); dirs.add(new File(resource.getFile())); } ArrayList<Class<?>> classes = new ArrayList<Class<?>>(); for (File directory : dirs) { classes.addAll(findClasses(directory, packageName)); } return classes; }
/** * Recursive method used to find all classes in a given directory and subdirs. * * @param directory The base directory * @param packageName The package name for classes found inside the base directory * @return The classes * @throws ClassNotFoundException */ private static List<Class<?>> findClasses(File directory, String packageName) throws ClassNotFoundException { List<Class<?>> classes = new ArrayList<Class<?>>(); if (!directory.exists()) { return classes; } File[] files = directory.listFiles(); for (File file : files) { if (file.isDirectory()) { assert !file.getName().contains("."); classes.addAll(findClasses(file, packageName + "." + file.getName())); } else if (file.getName().endsWith(".class")) { classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6))); } } return classes; }
JAX-WS
JAX-RS
SAAJ
Web Services Metadata for the Java Platform
first, last
가장 널리 사용되고 있는 추세
(AXIS2에서 CXF로 넘어오는 경우가 많음)
AXIS2 보다 사용하기 편리
웹서비스 관련 표준들을 준수
(WSDL 2.0은 아직 지원하지 않음)
최소한의 오버해드로 웹서비스 관련 프레임웍 중 성능이 가장 뛰어남(?)
Spring framework 적용가능
전자정부 표준 프레임워크에서 사용
Jersey
JAX-RS
?
Spring-WS
JAX-RS
first
JAX-WS 표준을 완벽히 지원하지 않음
JAX-WS 같은 Spring annotation 지원
개발자가 작성해야할 코드가 가장 작음
RESTEasy
JAX-RS
JAXB
?
JBoss 프로젝트
Rich set of providers for: XML, JSON, YAML, Fastinfoset, Multipart, XOP, Atom, etc.
JAXB marshalling into XML, JSON, Jackson, Fastinfoset, and Atom
as well as wrappers for maps, arrays, lists, and sets of JAXB Objects.
Gzip content-encoding 지원
Restlet
JAX-RS
?
경량 REST 프레임워크
Xstream, Jackson을 이용한 XML, JSON marshalling, unmarshalling 지원
FreeMarker, Velocity 통합가능
대용량 멀티파트 데이터 처리를 위해 Apache FileUpload와 통합가능
public class UserInfoDAOImpl extends BaseDAO implements UserInfoDAO{
@Override
public int insertJob(UserVo userVo) throws OSPException {
int returnVal = -1;
returnVal = (Integer) getSqlSession().insert("com.test.dao.UserInfoDAO.insertUser", userVo);
Runtime runtime = Runtime.getRuntime();
BufferedReader reader = null;
List<CpuInfoVo> prevInfoList = new ArrayList<CpuInfoVo>();
List<CpuInfoVo> diffInfoList = new ArrayList<CpuInfoVo>();
try {
Process process = runtime.exec(command);
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
String[] columns = null;
long total = 0;
long idle = 0;
int x = 0;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String ymd = sdf.format(Calendar.getInstance().getTime().getTime());
StringBuilder message = new StringBuilder();
message.append(ymd);
int total = 0;
for ( int i = 0 ; i < cpuRates.length ; i++ ) {
message.append(" ").append(cpuRates[i]);
total += Integer.parseInt(cpuRates[i]);
}
int cpuRate = total / cpuRates.length;
message.append(" (avg)").append(cpuRate);
System.out.println(message);
}
다운로드
http://logging.apache.org/log4j/1.2/download.html
설정
log4j는 log4j.properties 파일로 설정
src 디렉토리 아래에 log4j.properties 파일을 생성
(파일 저장시 이클립스가 log4j.properties 파일을 WEB-INF/classes로 알아서 복사함)
log4j.properties 파일을 아래와 같이 편집
# Print only messages of level ERROR or above in the package noModule.
log4j.logger.noModule=WARN
# Pattern to output the caller's file name and line number.
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %5p (%c:%L) - %m%n
APPLICATION LOG CONFIGURATION 이후의 내용을 수정
log4j.logger 이후에 설정할 패키지명 역순으로 적고 로그레벨과 appender 이름을 입력
위의 경우 com.test.Tester 클래스는 INFO level로 com.test 이하에 속한 패키지의 클래스들은 DEBUG 레벨로 로그가 기록
** 참고: 로그레벨
1. DEBUG (the least serious)
2. INFO
3. WARN
4. ERROR
5. FATAL (the most serious)
JAVA 클래스에서 사용예
--------------------------------------------------------------------------------
public class Tester {
private Logger logger = Logger.getLogger(Tester.class);
...
public void logIt() {
logger.info("im info log");
logger.debug("im debug log");
}
...
}
--------------------------------------------------------------------------------
아래를 클릭해서 jar 파일을 다운로드 한다.
http://files.zentus.com/sqlitejdbc/sqlitejdbc-v056.jar
JAVA 클래스패스에 다운로드 jar 파일을 추가한다.
이클립스 환경이라면 Build Path에 추가하던지 Dynamic Web Project라면 WEB-INF/lib에 파일을 복사
테스트 클래스를 만들고 아래 코드를 추가한 다음 실행!
이클립스 환경이라면 F11 누르고 Java Application 실행
*참고 http://www.zentus.com/sqlitejdbc/usage.html
import java.sql.*;
public class Test {
public static void main(String[] args) throws Exception {
Class.forName("org.sqlite.JDBC");
Connection conn =
DriverManager.getConnection("jdbc:sqlite:test.db");
Statement stat = conn.createStatement();
stat.executeUpdate("drop table if exists people;");
stat.executeUpdate("create table people (name, occupation);");
PreparedStatement prep = conn.prepareStatement(
"insert into people values (?, ?);");
/* MySQL Connector/J from MySql (www.mysql.com)*/ url = "jdbc:mysql://host/database"; driver = "com.mysql.jdbc.Driver";
/*JSQLConnect from JDBC Drivers from Microsoft MSSQL 2000*/ url = "jdbc:microsoft:sqlserver://host:port"; driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
/*DB2 Universal JDBC Driver from IBM jdbc classes: db2java.zip */ url = "jdbc:db2:host"; driver = "COM.ibm.db2.jdbc.app.DB2Driver";
/*DB2 Universal JDBC Driver from IBM type4 jdbc classes: db2jcc.jar*/ driver = "com.ibm.db2.jcc.DB2Driver" url = "jdbc:db2://{host}:50000/{database name}"
/*DB2 Universal JDBC Driver from IBM jdbc classes: db2java.zip */ url = "jdbc:db2://{host}:{port}/{database name}"; driver = "COM.ibm.db2.jdbc.net.DB2Driver";
/** * Zip 파일 생성 * @param os * @param filenameList * @param contentList * @return * @throws Exception */ public static ZipOutputStream makeZip(OutputStream os, List<String> filenameList, List<String> contentList) throws Exception {
ZipOutputStream jos = new ZipOutputStream(os); long now = System.currentTimeMillis(); for (int i = 0; i < filenameList.size(); i++) { String filename = filenameList.get(i); String content = contentList.get(i);
ZipEntry zipAdd = new ZipEntry(filename); zipAdd.setTime(now); jos.putNextEntry(zipAdd); byte[] b = content.getBytes("UTF-8"); jos.write(b, 0, b.length); } jos.close();
/* MySQL Connector/J from MySql (www.mysql.com)*/ url = "jdbc:mysql://host/database"; driver = "com.mysql.jdbc.Driver";
/*JSQLConnect from JDBC Drivers from Microsoft MSSQL 2000*/ url = "jdbc:microsoft:sqlserver://host:port"; driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
/*DB2 Universal JDBC Driver from IBM jdbc classes: db2java.zip */ url = "jdbc:db2:host"; driver = "COM.ibm.db2.jdbc.app.DB2Driver";
/*DB2 Universal JDBC Driver from IBM type4 jdbc classes: db2jcc.jar*/ driver = "com.ibm.db2.jcc.DB2Driver" url = "jdbc:db2://{host}:50000/{database name}"
/*DB2 Universal JDBC Driver from IBM jdbc classes: db2java.zip */ url = "jdbc:db2://{host}:{port}/{database name}"; driver = "COM.ibm.db2.jdbc.net.DB2Driver";