728x90

출처

가상 레코드 생성 예제

public class DemoReport {
	
	public static void main(String[] args) throws Exception {
		JasperReport jasperReport = JasperCompileManager.compileReport("src/ireport/report1.jrxml");
		
		// creating the data source
		JRDataSource dataSource = new JREmptyDataSource(1000); // 가상의 1000개의 레코드 생성
		
		JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, dataSource);
		
		// view report to UI
		jasperReport.setWhenNoDataType(WhenNoDataTypeEnum.ALL_SECTIONS_NO_DETAIL);
		JasperViewer.viewReport(jasperPrint, false);
	}
}

PDF 출력 예제

public class DemoReport2 {

	public static void main(String[] args) throws Exception {
		String outfilename = "src/ireport/report1.pdf";
		JasperReport jasperReport = JasperCompileManager.compileReport("src/ireport/report1.jrxml");

		// compile report hm.put(“REPORT_TITLE”,”This is the title of the report”)
		HashMap<String, Object> hm = new HashMap<String, Object>();
		hm.put("id", "121");

		List list = new ArrayList();
		list.add("test data");
		JRBeanCollectionDataSource jrbcds = new JRBeanCollectionDataSource(list, false);

		// 리포트 목록
		// List<JasperPrint> japerPrintList = new ArrayList<JasperPrint>();

		JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, hm, jrbcds);

		// PDF 출력
		JRExporter ex = new JRPdfExporter();
		ex.setParameter(JRPdfExporterParameter.IS_COMPRESSED, true);
		ex.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, outfilename);
		// ex.setParameter(JRExporterParameter.JASPER_PRINT_LIST, japerPrintList);
		ex.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
		ex.exportReport();
	}
}

JRDataSource 확장

필드 추가

필드 이름 변경

필드 객체를 선택해서 Detail 밴드에 드래그해 놓기

필드 배치

최종 결과물

커스텀 JRDataSource

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

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRField;

public class SampleDS implements JRDataSource {

	String[] fields;
	String[][] data;

	private Map<String, Integer> fieldIndex = new HashMap<String, Integer>();
	
	public SampleDS(String[] fields, String[][] data) {
		this.fields = fields;
		this.data = data;

		for (int i = 0; i < fields.length; i++)
			fieldIndex.put(fields[i], i);
	}

	int pos = -1;

	@Override
	public boolean next() throws JRException {
		for (;;) {
			pos++;
			if (pos >= data.length)
				return false;

			return true;
		}
	}

	@Override
	public Object getFieldValue(JRField jrField) throws JRException {
		Integer index = fieldIndex.get(jrField.getName());
		return data[pos][index];
	}
	
	public static JRDataSource getDataSource() {
		String[] fields = { "a", "b", "c", "d", "e" }; 
		String[][] data = {
				{ "a1", "b1", "c1", "d1", "e1" },
				{ "a2", "b2", "c2", "d2", "e2" },
				{ "a3", "b3", "c3", "d3", "e3" }
		};
		
		return new SampleDS(fields, data);
	}

}

예제소스

public class DemoReport3 {
	
	public static void main(String[] args) throws Exception {
		String outfilename = "src/ireport/report2.pdf";
		JasperReport jasperReport = JasperCompileManager.compileReport("src/ireport/report2.jrxml");
		
		// 커스텀 JRDataSource 생성
		JRDataSource dataSource = SampleDS.getDataSource();
		
		//
		JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, dataSource);

		// PDF 출력
		JRExporter ex =new JRPdfExporter();
		ex.setParameter(JRPdfExporterParameter.IS_COMPRESSED, true);
		ex.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, outfilename);
		//ex.setParameter(JRExporterParameter.JASPER_PRINT_LIST, japerPrintList);
		ex.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
		ex.exportReport();
	}

}

실행

동적으로 이미지 출력

디자인

Image Expression

$P{image_home}+"/"+$F{image1}

ImageBean 소스

public class ImageBean {
	
	private String image1;
	
	private String image2;

	public ImageBean(String image1, String image2) {
		super();
		this.image1 = image1;
		this.image2 = image2;
	}

	public String getImage1() {
		return image1;
	}

	public void setImage1(String image1) {
		this.image1 = image1;
	}

	public String getImage2() {
		return image2;
	}

	public void setImage2(String image2) {
		this.image2 = image2;
	}

}

이미지 출력 예제 소스

public class DemoReport4 {
	
	public static void main(String[] args) throws Exception {
		String outfilename = "src/ireport/report3.pdf";
		JasperReport jasperReport = JasperCompileManager.compileReport("src/ireport/report3.jrxml");
		
		// compile report hm.put(“REPORT_TITLE”,”This is the title of the report”)
		HashMap<String, Object> hm = new HashMap<String, Object>();
		hm.put("image_home", "C:\\Users\\bluesanta\\Pictures");
		
		//
		List list = new ArrayList();
		list.add(new ImageBean("73196c49-adeb-4ebd-9bde-069791498a28.jpg", "70947765.jpg"));
		JRBeanCollectionDataSource jrbcds = new JRBeanCollectionDataSource(list, false);
		
		// 리포트 목록
		// List<JasperPrint> japerPrintList = new ArrayList<JasperPrint>();

		JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, hm, jrbcds);

		// PDF 출력
		JRExporter ex = new JRPdfExporter();
		ex.setParameter(JRPdfExporterParameter.IS_COMPRESSED, true);
		ex.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, outfilename);
		// ex.setParameter(JRExporterParameter.JASPER_PRINT_LIST, japerPrintList);
		ex.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
		ex.exportReport();
	}

}
728x90
728x90

출처

py_pwm.h

typedef struct
{
    //PyObject_HEAD
    unsigned int gpio;
    float freq;
    float dutycycle;
} PWMObject;

int PWM_init(PWMObject *self, int channel, float frequency);
void PWM_start(PWMObject *self, float dutycycle);
int PWM_ChangeDutyCycle(PWMObject *self, float dutycycle);

PWMObject.java

package com.pi4j.wiringpi;

public class PWMObject {

	public int gpio;
	public float freq;
	public float dutycycle;

	public PWMObject() {

	}

	public int getGpio() {
		return gpio;
	}

	public void setGpio(int gpio) {
		this.gpio = gpio;
	}

	public float getFreq() {
		return freq;
	}

	public void setFreq(float freq) {
		this.freq = freq;
	}

	public float getDutycycle() {
		return dutycycle;
	}

	public void setDutycycle(float dutycycle) {
		this.dutycycle = dutycycle;
	}

}

com_pi4j_wiringpi_ASUSGpio.h

#include <jni.h>
/* Header for class com_pi4j_wiringpi_ASUSGpio */

#ifndef _Included_com_pi4j_wiringpi_ASUSGpio
#define _Included_com_pi4j_wiringpi_ASUSGpio
#ifdef __cplusplus
extern "C" {
#endif

#undef com_pi4j_wiringpi_ASUSGpio_ASUS
#define com_pi4j_wiringpi_ASUSGpio_ASUS 13L
#undef com_pi4j_wiringpi_ASUSGpio_OUTPUT
#define com_pi4j_wiringpi_ASUSGpio_OUTPUT 1L

JNIEXPORT jint JNICALL Java_com_pi4j_wiringpi_ASUSGpio_pySetmode
  (JNIEnv *, jclass, jint);

JNIEXPORT jint JNICALL Java_com_pi4j_wiringpi_ASUSGpio_pySetupChannel
  (JNIEnv *, jclass, jint, jint);

JNIEXPORT jobject JNICALL Java_com_pi4j_wiringpi_ASUSGpio_pwmInit
  (JNIEnv *, jclass, jint, jfloat);

JNIEXPORT void JNICALL Java_com_pi4j_wiringpi_ASUSGpio_pwmStart
  (JNIEnv *, jclass, jobject, jfloat);

JNIEXPORT jint JNICALL Java_com_pi4j_wiringpi_ASUSGpio_pwmChangeDutyCycle
  (JNIEnv *, jclass, jobject, jfloat);

#ifdef __cplusplus
}
#endif
#endif

com_pi4j_wiringpi_ASUSGpio.c

#include <stdio.h>
#include <jni.h>
#include <wiringPi.h>
#include <RKIO.h>
#include <wiringTB.h>
#include <constants.h>
#include <common.h>
#include <c_gpio.h>
#include <py_gpio.h>
#include <py_pwm.h>
#include "com_pi4j_wiringpi_ASUSGpio.h"

void setPwmObject(JNIEnv *env, jclass targetClass, jobject newObject, PWMObject pwm) {
	
	jfieldID fid;
	
	// JniObject 객체의 intField 필드값 설정
	fid = (*env)->GetFieldID(env, targetClass, "gpio", "I");
	(*env)->SetIntField(env, newObject, fid, pwm.gpio);
	
	// JniObject 객체의 intField 필드값 설정
	fid = (*env)->GetFieldID(env, targetClass, "freq", "F");
	(*env)->SetFloatField(env, newObject, fid, pwm.freq);
	
	// JniObject 객체의 intField 필드값 설정
	fid = (*env)->GetFieldID(env, targetClass, "dutycycle", "F");
	(*env)->SetFloatField(env, newObject, fid, pwm.dutycycle);
}

void getPwmObject(JNIEnv *env, jclass targetClass, jobject newObject, PWMObject *pwm) {
	
	jfieldID fid;
	
	// JniObject 객체의 intField 필드값 설정
	fid = (*env)->GetFieldID(env, targetClass, "gpio", "I");
	pwm->gpio = (*env)->GetIntField(env, newObject, fid);
	
	// JniObject 객체의 intField 필드값 설정
	fid = (*env)->GetFieldID(env, targetClass, "freq", "F");
	pwm->freq = (*env)->GetFloatField(env, newObject, fid);
	
	// JniObject 객체의 intField 필드값 설정
	fid = (*env)->GetFieldID(env, targetClass, "dutycycle", "F");
	pwm->dutycycle = (*env)->GetFloatField(env, newObject, fid);
}

JNIEXPORT jint JNICALL Java_com_pi4j_wiringpi_ASUSGpio_pySetmode
(JNIEnv *env, jclass obj, jint new_mode)
{
	return py_setmode(new_mode);
}

JNIEXPORT jint JNICALL Java_com_pi4j_wiringpi_ASUSGpio_pySetupChannel
(JNIEnv *env, jclass obj, jint channel, jint direction)
{
	return py_setup_channel(channel, direction);
}

JNIEXPORT jobject JNICALL Java_com_pi4j_wiringpi_ASUSGpio_pwmInit
(JNIEnv *env, jclass obj, jint channel, jfloat frequency)
{
	//pwm = GPIO.PWM(myservo,50) # 50hz yani 20mslik periyod
	PWMObject pwm;
	PWM_init(&pwm, channel, frequency);
	//printf("pwm.gpio = %d\n", pwm.gpio);
	
	//
	jclass targetClass = (*env)->FindClass(env, "com/pi4j/wiringpi/PWMObject");
	
	// 생성자 찾기
	jmethodID mid = (*env)->GetMethodID(env, targetClass, "<init>", "()V");

	// 객체 생성(객체 레퍼런스 반환)
	jobject newObject = (*env)->NewObject(env, targetClass, mid, "()V");
	
	setPwmObject(env, targetClass, newObject, pwm);
	
	return newObject;
}

JNIEXPORT void JNICALL Java_com_pi4j_wiringpi_ASUSGpio_pwmStart
(JNIEnv *env, jclass obj, jobject thiz, jfloat dutycycle)
{
	PWMObject pwm;
	
	//
	jclass targetClass = (*env)->FindClass(env, "com/pi4j/wiringpi/PWMObject");
	getPwmObject(env, targetClass, thiz, &pwm);
	
	PWM_start(&pwm, dutycycle);
	setPwmObject(env, targetClass, thiz, pwm);
}

JNIEXPORT jint JNICALL Java_com_pi4j_wiringpi_ASUSGpio_pwmChangeDutyCycle
(JNIEnv *env, jclass obj, jobject thiz, jfloat dutycycle)
{
	PWMObject pwm;
	
	//
	jclass targetClass = (*env)->FindClass(env, "com/pi4j/wiringpi/PWMObject");
	getPwmObject(env, targetClass, thiz, &pwm);
	
	int result = PWM_ChangeDutyCycle(&pwm, dutycycle);
	setPwmObject(env, targetClass, thiz, pwm);
	
	return result;
}

ASUSGpio.java

package com.pi4j.wiringpi;

import com.pi4j.util.NativeLibraryLoader;

public class ASUSGpio {

  // private constructor
  private ASUSGpio()  {
    // forbid object construction
  }

  public static final int ASUS = 13;

  public static final int OUTPUT = 1;

  static {
    // Load the platform library
    NativeLibraryLoader.load("libpi4j.so");
  }

  public static native int pySetmode(int new_mode);

  public static native int pySetupChannel(int channel, int direction);

  public static native PWMObject pwmInit(int channel, float frequency);

  public static native void pwmStart(PWMObject self, float dutycycle);

  public static native int pwmChangeDutyCycle(PWMObject self, float dutycycle);
}

빌드

$ export SimulatedPlatform="TinkerBoard GPIO Provider"
$ mvn clean install

-----------------

hml-equation-parser 패키지를 설치

$ sudo apt-get install pandoc
$ sudo pip3 install typing
$ sudo pip3 install hml_equation_parser

jpserve 패키지를 설치

$ sudo pip install jpserve

jython 설치

$ java -jar jython-installer-2.7.0.jar
728x90
728x90

출처

Maven 다운로드

$ wget http://mirror.navercorp.com/apache/maven/maven-3/3.5.4/binaries/apache-maven-3.5.4-bin.tar.gz

Maven 압축 해제

$ tar xvf apache-maven-3.5.4-bin.tar.gz

Maven /opt 디렉토리 밑으로 이동

$ sudo mv apache-maven-3.5.4 /opt

Maven /opt/maven 링크 설정

$ sudo ln -s /opt/apache-maven-3.5.4 /opt/maven

Maven 환경설정

$ echo "export M2_HOME=/opt/maven" | sudo tee -a /etc/profile
$ source /etc/profile
$ echo "export PATH=$PATH:$M2_HOME/bin" | sudo tee -a /etc/profile
$ source /etc/profile

Maven 설치확인

$ mvn -version
Apache Maven 3.5.4 (1edded0938998edf8bf061f1ceb3cfdeccf443fe; 2018-06-18T02:33:14+08:00)
Maven home: /opt/maven
Java version: 1.8.0_171, vendor: Oracle Corporation, runtime: /usr/lib/jvm/java-8-openjdk-armhf/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "3.4.39-bpi-m2p-kernel", arch: "arm", family: "unix"
728x90
728x90

출처

키생성 (bluexmas.jks 파일 생성)

C:\Users\bluesanta>"%JAVA_HOME%\bin\keytool" -genkey -keysize 2048 -keyalg RSA -keystore bluexmas.jks -dname "CN=me.co.kr, OU=team, O=company, L=seoul, ST=seoul, C=kr" -validity 3650
키 저장소 비밀번호 입력:
새 비밀번호 다시 입력:
<mykey>에 대한 키 비밀번호를 입력하십시오.
        (키 저장소 비밀번호와 동일한 경우 Enter 키를 누름):
새 비밀번호 다시 입력:

Warning:
JKS 키 저장소는 고유 형식을 사용합니다. "keytool -importkeystore -srckeystore bluexmas.jks -destkeystore bluexmas.jks -deststoretype pkcs12"를 사용하는 산업 표준 형식인 PKCS12로 이전하는 것이 좋습니다.

키파일 적용 (conf/server.xml)

    <Connector 
    	port="8443" 
	protocol="HTTP/1.1" SSLEnabled="true"
	maxThreads="150" scheme="https" secure="true" clientAuth="false"
	keystoreFile="conf/bluexmas.jks" keystorePass="bluexmas"
	sslEnabledProtocols="TLSv1.1,TLSv1.2"
	ciphers="TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
		TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,
		TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA256,
		TLS_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA256,
		TLS_RSA_WITH_AES_256_CBC_SHA" />

리다이렉트 시키기 (WEB-INF/web.xml 내용추가)

	<security-constraint>   
		<web-resource-collection>      
			<web-resource-name>Secured</web-resource-name>      
			<url-pattern>/*</url-pattern>   
		</web-resource-collection>   
		<user-data-constraint>      
			<transport-guarantee>CONFIDENTIAL</transport-guarantee>   
		</user-data-constraint>
	</security-constraint>
728x90
728x90

출처 : 아파치 톰캣(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%
728x90
728x90

출처 : 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>
728x90
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

+ Recent posts