TOMCAT - jmx 로 monitoring

Programming/Java 2017.12.07 23:46 Posted by 파란크리스마스

출처 : 아파치 톰캣(apache tomcat) 을 jmx 로 monitoring 하기

catalina-jmx-remote.jar 파일 Tomcat이 설치된 디렉토리의 lib디렉토리에 복사

https://archive.apache.org/dist/tomcat/tomcat-8/v8.5.23/bin/extras/

$ cd /usr/local/apache-tomcat-8.5.23/lib
$ wget https://archive.apache.org/dist/tomcat/tomcat-8/v8.5.23/bin/extras/catalina-jmx-remote.jar

IP 확인

$ ifconfig | grep "inet addr"
          inet addr:192.168.0.24  Bcast:192.168.0.255  Mask:255.255.255.0
          inet addr:127.0.0.1  Mask:255.0.0.0

setenv.sh 파일 생성

$ cd /usr/local/apache-tomcat-8.5.23/bin

setenv.sh 파일 내용

$ vi setenv.sh
  • -Dcom.sun.management.jmxremote.authenticate=false / 인증하지 않음
  • -Djava.rmi.server.hostname=192.168.0.24 / 톰캣이 구동되는 서버의 IP
  • -Dcom.sun.management.jmxremote.ssl=false / SSL 을 사용하지 않음
#!/bin/sh

JMX_OPTS=" -Dcom.sun.management.jmxremote \
                 -Dcom.sun.management.jmxremote.authenticate=false \
                 -Djava.rmi.server.hostname=192.168.0.24 \
                 -Dcom.sun.management.jmxremote.ssl=false "
CATALINA_OPTS=" ${JMX_OPTS} ${CATALINA_OPTS}"

conf/server.xml 수정 - Listener 추가

<Server port="8005" shutdown="SHUTDOWN">

<!-- 생략 --->

<Listener className="org.apache.catalina.mbeans.JmxRemoteLifecycleListener"
        rmiRegistryPortPlatform="9840" rmiServerPortPlatform="9841"/>

jdk의 jconsole.exe 실행

권한파일(jmxremote.access)과 로그인 암호파일(jmxremote.password) 생성

$ cd /usr/local/apache-tomcat-8.5.23/
$ echo -e "monitorRole readonly\ncontrolRole readwrite" > conf/jmxremote.access
$ cat conf/jmxremote.access
monitorRole readonly
controlRole readwrite
$ echo -e "monitorRole tomcat\ncontrolRole tomcat" > conf/jmxremote.password
$ cat conf/jmxremote.password
monitorRole tomcat
controlRole tomcat

setenv.sh 파일 수정

$ cd /usr/local/apache-tomcat-8.5.23/bin
$ vi setenv.sh

#!/bin/sh

JMX_OPTS=" -Dcom.sun.management.jmxremote \
           -Dcom.sun.management.jmxremote.authenticate=true \
           -Dcom.sun.management.jmxremote.password.file=$CATALINA_BASE/conf/jmxremote.password  \
           -Dcom.sun.management.jmxremote.access.file=$CATALINA_BASE/conf/jmxremote.access  \
           -Djava.rmi.server.hostname=192.168.0.24 \
           -Dcom.sun.management.jmxremote.ssl=false "
CATALINA_OPTS=" ${JMX_OPTS} ${CATALINA_OPTS}"

setenv.bat 파일 내용 - Windows 용

set JMX_OPTS=-Dcom.sun.management.jmxremote ^
-Dcom.sun.management.jmxremote.authenticate=true ^
-Dcom.sun.management.jmxremote.password.file=%CATALINA_HOME%/conf/jmxremote.password ^
-Dcom.sun.management.jmxremote.access.file=%CATALINA_HOME%/conf/jmxremote.access ^
-Djava.rmi.server.hostname=192.168.0.31 ^
-Dcom.sun.management.jmxremote.ssl=false

set CATALINA_OPTS=%JMX_OPTS% %CATALINA_OPTS%
저작자 표시
신고

Srping Security - 커스텀 UserDetailsService

Programming/Java 2017.11.22 13:26 Posted by 파란크리스마스

출처 : Spring Security part V : Security tags | DuyHai's Java Blog
Spring security authorize taglib with jstl variable if statement not working

UserDetails 구현

package com.iot.dao.domain;

import java.util.Collection;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

public class UserInfo implements UserDetails {

	// pk
	private String user_id;

	private String passwd;
	private int level;
	
	private Collection<? extends GrantedAuthority> authorities;

	public void setUser_id(String user_id) {
		this.user_id = user_id;
	}

	public String getUser_id() {
		return this.user_id;
	}

	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}

	public String getPasswd() {
		return this.passwd;
	}

	public int getLevel() {
		return level;
	}

	public void setLevel(int level) {
		this.level = level;
	}

	public void setAuthorities(Collection<? extends GrantedAuthority> authorities) {
		this.authorities = authorities;
	}

	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		return this.authorities;
	}

	@Override
	public String getPassword() {
		return this.passwd;
	}

	@Override
	public String getUsername() {
		return this.user_id;
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@Override
	public boolean isEnabled() {
		return true;
	}
}

UserDetailsService 구현

package com.iot.dao.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.iot.dao.domain.UserInfo;

@Service
public class AuthDetailsService implements UserDetailsService {

	@Autowired
	private UserInfoService userService;

	@Override
	public UserInfo loadUserByUsername(String user_id) throws UsernameNotFoundException {
		UserInfo userInfo = userService.selectUserInfo(user_id);

		//
		if (userInfo == null || userInfo.getDelete_yn().equals("Y")) {
			throw new UsernameNotFoundException("User details not found with this username: " + user_id);
		}

		String role = userInfo.getAuthority();

		List<GrantedAuthority> authList = getAuthorities(role);

		//
		userInfo.setAuthorities(authList);

		return userInfo;
	}

	private List<GrantedAuthority> getAuthorities(String role) {
		List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
		authList.add(new SimpleGrantedAuthority("ROLE_USER"));

		// 
		if (role != null && role.trim().length() > 0) {
			if (role.equals("A")) {
				authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
			} else if (role.equals("S")) {
				authList.add(new SimpleGrantedAuthority("ROLE_MBER_MANAGER"));
			}
		}

		return authList;
	}
}

***-security.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:security="http://www.springframework.org/schema/security"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
           http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security-3.2.xsd">

	<!-- 확장자를 이용해 패턴을 걸때는 /**/*.해당 확장자 로 할 것(Ant Pattern 규칙) -->
	<security:http pattern="/**/*.js" security="none" />
	<security:http pattern="/**/*.css" security="none" />
	<security:http pattern="/images/*" security="none" />
	<security:http pattern="/login.iot" security="none" />

	<bean id="userService" class="com.iot.dao.service.AuthDetailsService" />

	<security:http auto-config="true">
		<security:intercept-url pattern="/json.iot" access="ROLE_ANONYMOUS,ROLE_USER" />
		<security:intercept-url pattern="/**/*.iot" access="ROLE_USER" />
		<security:intercept-url pattern="/user_add_ajax.iot" access="ROLE_ANONYMOUS" />

		<security:intercept-url pattern="/loginfailed.iot" access="ROLE_ANONYMOUS" />
		<security:intercept-url pattern="/logout" access="ROLE_ANONYMOUS" />

		<security:form-login login-page="/login.iot" default-target-url="/iot/transinfo_list.iot" authentication-failure-url="/loginfailed.iot" />
		<security:logout logout-success-url="/login.iot" />
		<security:access-denied-handler error-page="/loginfailed.iot" />

		<security:logout logout-url="/logout" success-handler-ref="/login.iot" />
	</security:http>

	<security:authentication-manager>
		<security:authentication-provider user-service-ref="userService" />
		<security:authentication-provider>
			<security:jdbc-user-service
				data-source-ref="dataSource"
				users-by-username-query="select user_id username, passwd, 1 as enabled from user_info where user_id = ? and delete_yn = 'N'"
				authorities-by-username-query="select name username, 'ROLE_USER' authority from user_info where user_id = ? and delete_yn = 'N'" />
		</security:authentication-provider>
	</security:authentication-manager>

</beans>

JSP

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

<sec:authentication property="principal.level" var="user_level"/>
${user_level}

<li class="dropdown">
	<a href="javascript:;" class="dropdown-toggle">사용자관리 <b class="caret"></b></a>
	<ul class="dropdown-menu">
		<c:if test="${user_level == 1}">
			<li class=""><a href="<c:url value="/car/user_list.car"/>">사용자관리</a></li>
		</c:if>
		<li><a href="<c:url value="/car/user_info.car"/>">내 정보</a></li>
		<li><a href="<c:url value="/logout"/>">로그아웃</a></li>
	</ul>
</li>
저작자 표시
신고

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

Programming/Java 2017.07.22 18:38 Posted by 파란크리스마스

출처 : 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();
		}
	}
}
저작자 표시
신고

Spring MVC - ObjectMapper이용 Object to JSON 반환

Programming/Java 2017.07.16 17:13 Posted by 파란크리스마스

출처 : 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;
	}
}

실행

저작자 표시
신고

Spring MVC - Object to JSON 반환

Programming/Java 2017.07.15 20:12 Posted by 파란크리스마스

출처 : 스프링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;
	}
}

실행

저작자 표시
신고

Spring - 파일 업로드

Programming/Java 2017.06.18 10:39 Posted by 파란크리스마스

출처 : [Spring, Tomcat] Could not parse multipart servlet request Unable to process parts as no multi-part configuration has been provided 해결 [소림사의 홍반장!]
[Apache/Tomcat] Context.xml 수정을 통한 문제 해결 - Cache, CSRF(Upload) [PostIT]
[Spring] Multipart를 사용한 페이지에서 Filter 적용하기 : 네이버 블로그

pom.xml

		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.2</version>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.5</version>
		</dependency>

MultipartFilter 적용(web.xml)

	<!-- MultipartFilter 적용 -->
	<filter>
		<filter-name>MultipartFilter</filter-name>
		<filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>MultipartFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

MultipartResolver 등록 (spring bean 등록)

	<!--  이미지 드래그 앤 드롭 업로드 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- max upload size in bytes -->
		<property name="maxUploadSize" value="209715200" /> <!-- 20MB -->
		<!-- max size of file in memory (in bytes) -->
		<property name="maxInMemorySize" value="1048576" /> <!-- 1MB -->
	</bean>

allowCasualMultipartParsing 설정 (context.xml)

방법1 %TOMCAT%/conf/context.xml - Tomcat 전체 적용

<Context allowCasualMultipartParsing="true">

	<WatchedResource>WEB-INF/web.xml</WatchedResource>
	<WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

	<!-- Default set of monitored resources. If one of these changes, the -->
	<!-- web application will be reloaded. -->
	<WatchedResource>WEB-INF/web.xml</WatchedResource>
	<WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

	<!-- Uncomment this to disable session persistence across Tomcat restarts -->
	<!-- <Manager pathname="" /> -->

	<!-- 케시문제 해결 -->
	<Resources cachingAllowed="true" cacheMaxSize="100000"></Resources>

</Context>

방법2 WebContent\META-INF\context.xml - Eclipse 사용시 프로젝트에 적용

<?xml version="1.0" encoding="UTF-8"?>
<Context allowCasualMultipartParsing="true">
</Context>

form의 enctype

<form action="<c:url value="/insertCompleteForProblem.do"/>" method="post" enctype="multipart/form-data">
	    <tr>
	        <th scope="row">file</th>
	        <td><input type="file" size="20"  name="file1"></td>
	    </tr>

controller

	@RequestMapping(value = "/insertCompleteForProblem.do", method = RequestMethod.POST, headers = ("content-type=multipart/*"))
	public String joinComplete(
			@RequestParam("seq") int seq, 
			@RequestParam("quiz_name") String quiz_name, 
			@RequestParam("user_id") String user_id, 
			@RequestParam("price") String price,
			@RequestParam(value = "file1", required = false) MultipartFile mediaFile, 
			HttpServletRequest request, 
			ModelMap modelMap) throws Exception 
	{

		System.out.println("seq : " + seq);
		System.out.println("quiz_name : " + quiz_name);
		System.out.println("user_id : " + user_id);
		System.out.println("price : " + price);

		if (mediaFile.isEmpty() == false) {
			System.out.println("------------- file start -------------");
			System.out.println("name : " + mediaFile.getName());
			System.out.println("filename : " + mediaFile.getOriginalFilename());
			System.out.println("size : " + mediaFile.getSize());
			System.out.println("-------------- file end --------------\n");

			String originalFilename = mediaFile.getOriginalFilename(); // 파일명

			// 파일 확장자 추출
			String fileExt = FileUtils.getFileExt(originalFilename);

			UUID uuid = UUID.randomUUID();
			String targetFilename = uuid.toString() + "." + fileExt.toLowerCase();

			File file = new File(getDestinationLocation() + targetFilename);
			mediaFile.transferTo(file);
		}

		return "redirect:/main.do";
	}

	private String getDestinationLocation() {
		// return "/home/hosting_users/terecal/www/intel_images/";
		return "c:\\test\\";
	}


저작자 표시
신고

Spring 설정 pom.xml

Programming/Java 2017.06.05 19:50 Posted by 파란크리스마스

Spring 설정 pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>iotweb</groupId>
	<artifactId>iotweb</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<build>
		<!-- ROOT.war 가 생성된다. -->
		<finalName>ROOT</finalName>
		<sourceDirectory>src/java</sourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.5.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>3.0.0</version>
				<configuration>
					<archiveClasses>true</archiveClasses>
					<warSourceDirectory>WebContent</warSourceDirectory>
				</configuration>
			</plugin>
		</plugins>
		<resources>
			<resource>
				<directory>src/mybatis</directory>
			</resource>
		</resources>
	</build>

	<properties>
		<org.springframework-version>4.1.7.RELEASE</org.springframework-version>
		<org.springframework.security-version>3.2.10.RELEASE</org.springframework.security-version>
		<org.aspectj-version>1.8.1</org.aspectj-version>
		<org.slf4j-version>1.7.6</org.slf4j-version>
	</properties>
	<dependencies>
		<!--
		http://egloos.zum.com/laydios/v/2789441
		compile : 컴파일 할때 필요. 테스트 및 런타임에도 클래스 패스에 포함 된다. scorp 을 설정 하지 않는 경우 기본값이다.
		runtime : 런타임에 필요. JDBC 드라이버 등이 예가 된다. 컴파일 시에는 필요하지 않지만, 실행 시에 필요한 경우.
		provided : 컴파일 시에 필요하지만, 실제 런타임 때에는 컨테이너 같은 것에서 제공되는 모듈. servlet, jsp api 등이 이에 해당. 배포시 제외된다. 
		-->
		<!-- Web dependencies -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.0.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.2</version>
			<scope>provided</scope>
		</dependency>
		<!-- log4j -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.16</version>
			<scope>provided</scope>
		</dependency>
	
		<!-- Spring dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
	
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
	
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.2</version>
		</dependency>
	
		<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.5</version>
		</dependency>
	
		<!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>
	
		<!-- spring framework jdbc 설정 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<!-- mybatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.2.2</version>
		</dependency>
		<!-- mybatis spring -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.2.0</version>
		</dependency>
	
		<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	
		<dependency>
			<groupId>bluexmas.util</groupId>
			<artifactId>bluexams</artifactId>
			<version>1</version>
			<scope>system</scope>
			<systemPath>${basedir}/libs/bluexmas.jar</systemPath> <!-- must match file name -->
		</dependency>

		<dependency>
			<groupId>com.oracle</groupId>
 			<artifactId>ojdbc</artifactId>
			<version>16</version>
			<scope>system</scope>
			<systemPath>${basedir}/libs/ojdbc6.jar</systemPath>
		</dependency>
 
		<!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
		<!--
		<dependency>
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib</artifactId>
			<version>2.4</version>
			<classifier>jdk15</classifier>
		</dependency>
		-->
		<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
	
	
		<!-- https://mvnrepository.com/artifact/org.json/json -->
		<dependency>
			<groupId>org.json</groupId>
			<artifactId>json</artifactId>
			<version>20170516</version>
		</dependency>
	
		<!-- https://mvnrepository.com/artifact/javax.inject/javax.inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>
	
		<dependency>
			<groupId>org.apache.tiles</groupId>
			<artifactId>tiles-extras</artifactId>
			<version>3.0.7</version>
		</dependency>
	
		<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-core -->
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-core</artifactId>
			<version>${org.springframework.security-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
			<version>${org.springframework.security-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
			<version>${org.springframework.security-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-taglibs</artifactId>
			<version>${org.springframework.security-version}</version>
		</dependency>
	
	
		<!-- https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf-spring3 -->
		<dependency>
			<groupId>org.thymeleaf</groupId>
			<artifactId>thymeleaf-spring3</artifactId>
			<version>1.0.1</version>
		</dependency>
		
	</dependencies>
 
</project>
저작자 표시
신고

java - mysql jdbc 연결

Programming/Java 2017.05.08 11:00 Posted by 파란크리스마스

출처 : 초보개발자 이야기. :: JAVA : JDBC를 사용하여 MySQL 과 연동하기 ...

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

public class MySQLJDBCTest {
	
	public static void main(String [] args) throws Exception {
		
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		
		try {
			Class.forName("org.gjt.mm.mysql.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://bluexmas.tistory.com:3306/test_db", "test", "test");
			System.out.println("connection = " + conn);
			
			// 
			stmt = conn.prepareStatement("SHOW DATABASES");
			rs = stmt.executeQuery();
			
			//
			ResultSetMetaData rsmd = rs.getMetaData();
			int cols = rsmd.getColumnCount();
			System.out.printf("The query fetched %d columns\n",cols);
			System.out.println("These columns are: ");
			for (int i=1;i<=cols;i++) {
				String colName = rsmd.getColumnName(i);
				String colType = rsmd.getColumnTypeName(i);
				System.out.println(colName+" of type "+colType);
			}
			
			//
			while (rs.next()) {
				String str = rs.getNString(1);
				System.out.println(str);
			}
		} catch (SQLException sqex) {
			System.out.println("SQLException: " + sqex.getMessage());
			System.out.println("SQLState: " + sqex.getSQLState());
		} finally {
			if (rs != null) try { rs.close(); } catch (SQLException e) { }
			if (stmt != null) try { stmt.close(); } catch (SQLException e) { }
			if (conn != null) try { conn.close(); } catch (SQLException e) { }
		}
	}

}
저작자 표시
신고

Maven - Spring 설정

Programming/Java 2017.05.05 19:55 Posted by 파란크리스마스

Maven - Spring 설정

Properties 추가

[Properties]항목에서 [Create]버튼을 선택해서 아래와 같이 입력하고 [OK]버튼을 선택

Name : org.springframework-version
Value : 4.1.7.RELEASE

Dependencies 추가

groupId : org.springframework
artifactId : spring-context
version : ${org.springframework-version}

저작자 표시
신고

Maven 설치

Programming/Java 2017.05.05 18:15 Posted by 파란크리스마스

Maven 설치

출처 : MAVEN 설치 및 Eclipse 연동하기 - FREESTROKES' Develog - Tistory

Maven 다운로드

Maven 다운로드 사이트에서 최신 Maven 파일(apache-maven-3.5.0-bin.zip)을 다운받아 적당한 폴더에 압축을 푼다. 

환경설정

환경 변수 MAVEN_HOME 를 설정

Maven의 bin 폴더 Path에 추가

환경변수 path 항목에 구분자(;) 와 함께 추가 %MAVEN_HOME%\bin 추가

JDK 설치후 JAVA_HOME 설정

Maven 설치 확인

명령 프롬프트에서 mvn --version 실행

Eclipse Maven 설정

Maven 설정 변경 (옵션)

%MAVEN_HOME%\conf\settings.xml 파일을 C:\spring\maven 폴더에 복사

복사한 settings.xml 수정 - localRepository 주석을 제거하고 적당한 폴더 설정

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ${user.home}/.m2/repository
  -->
  <localRepository>C:/spring/maven/repository</localRepository>

eclipse - maven user settings

이클립스 프로젝트 Maven 연동

출처 : HunIT Blog :: Eclipse〃이클립스에 메이븐(Maven) 연동 및 환경설정


저작자 표시
신고

JsonConfig 사용

Programming/Java 2017.04.23 16:48 Posted by 파란크리스마스

JsonConfig 사용하기

출처 : 알팅스님의 개발 스토리 : Java Object(POJO) To JSON String

Mybatis XML

	<resultMap id="resultMapUserInfo" type="map">
		<result property="user_id" column="user_id" javaType="java.lang.String"/>
		<result property="email" column="email" javaType="java.lang.String"/>
		<result property="mobile" column="mobile" javaType="java.lang.String"/>
		<result property="name" column="name" javaType="java.lang.String"/>
		<result property="point" column="point" javaType="int"/>
		<result property="reg_date" column="reg_date" javaType="java.util.Date"/>
		<result property="service_start_date" column="service_start_date" javaType="java.util.Date"/>
		<result property="service_end_date" column="service_end_date" javaType="java.util.Date"/>
	</resultMap>

	<!-- listUser -->
	<select id="listUser" parameterType="map" resultMap="resultMapUserInfo">
		select a.*
		  FROM user_info a
		 WHERE a.delete_yn = 'N'
	</select>

Java

	JsonConfig jsonConfig = new JsonConfig();
	jsonConfig.registerJsonValueProcessor(java.util.Date.class, new JsonValueProcessor() {

		@Override
		public Object processArrayValue(Object value, JsonConfig jsonConfig) {
			
			java.util.Date[] dates = (java.util.Date[]) value;
			Long[] result = new Long[dates.length];
			for (int index = 0; index < dates.length; index++) {
				result[index] = dates[index].getTime();
			}
			return result;
		}

		@Override
		public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
			java.util.Date date = (java.util.Date) value;
			return date.getTime();
		}
	});
	
	List<Map<String, Object>> listUser = service.listUser(null);
	jsonObjet.put("listUser", JSONArray.fromObject(listUser, jsonConfig));
저작자 표시
신고

CKEditor 4.6

Programming/Java 2017.04.09 17:29 Posted by 파란크리스마스

CKEditor 4.6

출처 : CKEditor 4.6
CKEditor not working after opening jQuery UI Dialog - Stack Overflow

CKEditor - JQuery UI Dialog와 같이 사용하기

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="<c:url value="/resources/js/jquery-1.12.0.js"/>"></script>
<script type="text/javascript" src="<c:url value="/resources/js/jquery-ui.js"/>"></script>
<script type="text/javascript" src="<c:url value="/resources/ckeditor/ckeditor.js"/>"></script>
<link rel="stylesheet" href="<c:url value="/resources/css/jquery-ui.css"/>">
<title>JQuery Dialog</title>
<script type="text/javascript">
// CKEditor 기본 경로 설정 - config.js의 경로 설정
window.CKEDITOR_BASEPATH = '<c:url value="/resources/ckeditor"/>';
//window.parent.CKEDITOR.tools.callFunction('콜백의 식별 ID 값', '파일의 URL', '전송완료 메시지')

// CKEditor 제거 함수 - CKEditor 생성 되어 있는지 확인 후 제거
function DestryoCKEditorInstances(textarea_name) {
	if (CKEDITOR.instances[textarea_name])	{
		CKEDITOR.instances[textarea_name].destroy();
	}
}

function insertPopUpForSubject(){
	// 팝업 다이얼로그
	$("#tabb_subject_insert").dialog({
		position : {
			my : 'center center',
			at : 'center top'
		},
		width : 800,
		//height : 800,
		modal : true,
		open: function( event, ui ) {
			// 팝업창 열릴때 CKEditor 설정
			CKEDITOR.replace( 'example_subject_insert' , {
				extraPlugins: 'uploadimage,image2',
				uploadUrl: '<c:url value="/dragdrop/fileUpload/ckeditor2.do"/>',
				filebrowserImageUploadUrl: '<c:url value="/dragdrop/fileUpload/ckeditor.do"/>'
			});
		},
		close: function () {
			// 반듯이 팝업창 닫힐때 제거 되어함
			DestryoCKEditorInstances('example_subject_insert');
		}
	});
}
</script>
</head>
<body>

<button class="button button2" onclick="javascript:insertPopUpForSubject();">문제 입력1</button>

<div id="tabb_subject_insert"  title="문제 입력!"  style="display:none">
	<table align="center" width="90%" border="0" cellspacing="0" cellpadding="0">
	<tr>
		 <td>seq</td>
		 <td><input type="text" size="20" id="seq_subject_insert" ></td>
	</tr>
	<tr>
		 <td>보기</td>
		 <td>
			<textarea id="example_subject_insert" name="example_subject_insert" form="usrform">Enter text here...</textarea>
		 </td>
	</tr>
	</table>
	<center>
		<button class="button button5" onclick="javascript:insert_subject1_complete(1);">입력 완료(과목1)</button>
		<button class="button button5" onclick="javascript:cancle_insert();">취 소</button>
	</center>
</div>

</body>
</html>


저작자 표시
신고


 

티스토리 툴바