RabbitMQ : Ubuntu에 설치

Programming/Java 2021. 4. 18. 21:54 Posted by 파란크리스마스

출처

저장소 추가

bluesanta@bluesanta-desktop:~$ sudo apt list --installed rabbitmq-server
나열 중... 완료

RabbitMQ 설치

bluesanta@bluesanta-desktop:~$ sudo apt install rabbitmq-server
패키지 목록을 읽는 중입니다... 완료
의존성 트리를 만드는 중입니다       
상태 정보를 읽는 중입니다... 완료
다음의 추가 패키지가 설치될 것입니다 :
  erlang-asn1 erlang-base erlang-crypto erlang-eldap erlang-ftp erlang-inets erlang-mnesia erlang-os-mon erlang-parsetools
  erlang-public-key erlang-runtime-tools erlang-snmp erlang-ssl erlang-syntax-tools erlang-tftp erlang-tools erlang-xmerl libsctp1
  locales-all
제안하는 패키지:
  erlang erlang-manpages erlang-doc lksctp-tools
다음 새 패키지를 설치할 것입니다:
  erlang-asn1 erlang-base erlang-crypto erlang-eldap erlang-ftp erlang-inets erlang-mnesia erlang-os-mon erlang-parsetools
  erlang-public-key erlang-runtime-tools erlang-snmp erlang-ssl erlang-syntax-tools erlang-tftp erlang-tools erlang-xmerl libsctp1
  locales-all rabbitmq-server
0개 업그레이드, 20개 새로 설치, 0개 제거 및 0개 업그레이드 안 함.
38.1 M바이트 아카이브를 받아야 합니다.
이 작업 후 276 M바이트의 디스크 공간을 더 사용하게 됩니다.

RabbitMQ 실행 상태 확인

bluesanta@bluesanta-desktop:~$ systemctl status rabbitmq-server
● rabbitmq-server.service - RabbitMQ Messaging Server
     Loaded: loaded (/lib/systemd/system/rabbitmq-server.service; enabled; vendor preset: enabled)
     Active: active (running) since Mon 2021-04-18 14:23:53 KST; 4min 59s ago
   Main PID: 2625 (beam.smp)
     Status: "Initialized"
      Tasks: 163 (limit: 18897)
     Memory: 85.5M
     CGroup: /system.slice/rabbitmq-server.service
             ├─2608 /bin/sh /usr/sbin/rabbitmq-server
             ├─2625 /usr/lib/erlang/erts-10.6.4/bin/beam.smp -W w -A 128 -MBas ageffcbf -MHas ageffcbf -MBlmbcs 512 -MHlmbcs 512 -MMmcs 30 -P 1048576 -t 5000000 -stbt db -zdbbl 128000 -K true -- -root /usr/lib/erlang -progname erl -- -home /var/lib/rabbit>
             ├─2970 erl_child_setup 65536
             ├─3007 inet_gethost 4
             └─3008 inet_gethost 4
 
 4월 18 14:23:50 bluesanta-desktop systemd[1]: Starting RabbitMQ Messaging Server...
 4월 18 14:23:53 bluesanta-desktop systemd[1]: rabbitmq-server.service: Supervising process 2625 which is not our child. We'll most likely not notice when it exits.
 4월 18 14:23:53 bluesanta-desktop systemd[1]: Started RabbitMQ Messaging Server.
 4월 18 14:23:53 bluesanta-desktop systemd[1]: rabbitmq-server.service: Supervising process 2625 which is not our child. We'll most likely not notice when it exits.

Management UI 플러그인 활성화

bluesanta@bluesanta-desktop:~$ sudo rabbitmq-plugins enable rabbitmq_management
Enabling plugins on node rabbit@bluesanta-desktop:
rabbitmq_management
The following plugins have been configured:
  rabbitmq_management
  rabbitmq_management_agent
  rabbitmq_web_dispatch
Applying plugin configuration to rabbit@bluesanta-desktop...
The following plugins have been enabled:
  rabbitmq_management
  rabbitmq_management_agent
  rabbitmq_web_dispatch
 
started 3 plugins.

사용자 추가

사용자 목록 조회

bluesanta@bluesanta-desktop:~$ sudo rabbitmqctl list_users
Listing users ...
user    tags
guest   [administrator]

사용자 추가

bluesanta@bluesanta-desktop:~$ sudo rabbitmqctl add_user admin 'passwd'
Adding user "admin" ...

사용자 권한 부여

bluesanta@bluesanta-desktop:~$ sudo rabbitmqctl set_user_tags admin administrator
Setting tags for user "admin" to [administrator] ...

암호 변경

bluesanta@bluesanta-desktop:~$ sudo rabbitmqctl change_password admin 'passwd'
Changing password for user "admin" ...

RabbitMQ 포트

  • 4369 : epmd, 여러 rabbitmq 서버끼리 서로를 찾을 수 있는 네임 서버 역할을 하는 데몬에서 사용
  • 5672, 5671 : AMQP 를 사용한 메시지 전달
  • 25672 : inter-node 와 CLI Tool 연결
  • 15672 : HTTP API, Management UI

RabbitMQ 관리페이지

웹브라우저로 http://serverip:15672/에 접속

MQTT 플러그인 활성화

bluesanta@bluesanta-desktop:~$ sudo rabbitmq-plugins enable rabbitmq_mqtt
Enabling plugins on node rabbit@bluesanta-desktop:
rabbitmq_mqtt
The following plugins have been configured:
  rabbitmq_management
  rabbitmq_management_agent
  rabbitmq_mqtt
  rabbitmq_web_dispatch
Applying plugin configuration to rabbit@bluesanta-desktop...
The following plugins have been enabled:
  rabbitmq_mqtt
 
started 1 plugins.
bluesanta@bluesanta-desktop:~$ netstat -nao | grep 1883
tcp6       0      0 :::1883                 :::*                    LISTEN      off (0.00/0/0)

댓글을 달아 주세요

Ubuntu 20.04 : Tomcat 서비스 등록

Programming/Java 2020. 11. 14. 13:25 Posted by 파란크리스마스

출처

tomcat 설치

pi@Kubuntu:~$ cd /bluesanta/apps
pi@Kubuntu:/bluesanta/apps$ wget https://downloads.apache.org/tomcat/tomcat-8/v8.5.59/bin/apache-tomcat-8.5.59.tar.gz
pi@Kubuntu:/bluesanta/apps$ tar xvfz apache-tomcat-8.5.59.tar.gz

tomcat /opt 디렉토리에 소프트 링크 걸기

pi@Kubuntu:/bluesanta/apps$ sudo ln -s /bluesanta/apps/apache-tomcat-8.5.59 /opt/apache-tomcat-8.5.59

서비스 등록 파일 tomcat.service 생성

pi@Kubuntu:/bluesanta/apps$ cd /etc/systemd/system
pi@Kubuntu:/etc/systemd/system$ sudo vi /etc/systemd/system/tomcat.service

tomcat.service 내용

[Unit]
Description=tomcat 8
After=network.target syslog.target

[Service]
Type=forking
Environment="JAVA_HOME=/opt/jdk1.8.0_271"
User=root
Group=root
ExecStart=/opt/apache-tomcat-8.5.59/bin/startup.sh
ExecStop=/opt/apache-tomcat-8.5.59/bin/shutdown.sh

[Install]
WantedBy=multi-user.target

tomcat 서비스 등록

pi@Kubuntu:/etc/systemd/system$ sudo systemctl enable tomcat.service
Created symlink /etc/systemd/system/multi-user.target.wants/tomcat.service → /etc/systemd/system/tomcat.service.

tomcat 서비스 실행

pi@Kubuntu:/etc/systemd/system$ sudo systemctl start tomcat.service

tomcat 서비스 상태 확인

pi@Kubuntu:/etc/systemd/system$ sudo systemctl status tomcat.service
● tomcat.service - tomcat 8
     Loaded: loaded (/etc/systemd/system/tomcat.service; enabled; vendor preset: enabled)
     Active: active (running) since Sat 2020-11-14 14:27:13 KST; 39s ago
    Process: 103228 ExecStart=/opt/apache-tomcat-8.5.59/bin/startup.sh (code=exited, status=0/SUCCESS)
   Main PID: 103256 (java)
      Tasks: 33 (limit: 18694)
     Memory: 119.5M
     CGroup: /system.slice/tomcat.service
             └─103256 /usr/bin/java -Djava.util.logging.config.file=/opt/apache-tomcat-8.5.59/conf/logging.properties -Djava.util.logging.manager=org.ap>

11월 14 14:27:13 Kubuntu systemd[1]: Starting tomcat 8...
11월 14 14:27:13 Kubuntu startup.sh[103228]: Tomcat started.
11월 14 14:27:13 Kubuntu systemd[1]: Started tomcat 8.

댓글을 달아 주세요

Jenkins - Svn, Ant, Tomcat 원격 배포

Programming/Java 2020. 10. 29. 01:50 Posted by 파란크리스마스

출처

Subversion 플로그인 설치

Deploy to container 플로그인 설치

프로젝트 생성

[새로운 Item] 메뉴 선택

item name(프로젝트 이름) 설정, Freestyle project, [OK] 버튼 선택

Subversion 선택, URL 주소 설정, Svn 접속 계정 추가 

Svn 계정 설정, [Add] 버튼 선택

추가 Svn 주소가 있는 경우, [Add module] 버튼 선택

Subversion 선택, URL 주소 설정

Build에서 [Invoke Ant] 설정

Ant - Target과 빌드 파일 설정

빌드 후 조치(배포), [Deploy war/ear to a container] 선택

베포 웹서버 설정 

댓글을 달아 주세요

Tomcat 관리자 페이지 설정

Programming/Java 2020. 10. 29. 00:08 Posted by 파란크리스마스

출처

%TOMCAT_HOME%/conf/tomcat-users.xml

관리자 페이지는 manager-gui 권한의 활성화와 계정 정보가 설정되어야 사용이 가능하므로 %TOMCAT_HOME%/conf/tomcat-users.xml 파일을 열어서 아래와 같이 manager-gui 권한을 추가합니다.

<!--
  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <user username="tomcat" password="<must-be-changed>" roles="tomcat"/>
  <user username="both" password="<must-be-changed>" roles="tomcat,role1"/>
  <user username="role1" password="<must-be-changed>" roles="role1"/>
-->
	
	<!-- manager-gui 권한 추가 -->
	<role rolename="manager-gui"/>
	<role rolename="manager-script"/>
	<role rolename="manager-status"/>
	<user username="admin" password="admin" roles="manager-gui,manager-script,manager-status"/>
</tomcat-users>

관리자 페이지 접속

관리자 암호를 설정하고 [로그인] 버튼 선택

관리자 페이지

댓글을 달아 주세요

Jenkins 설치

Programming/Java 2020. 10. 13. 01:11 Posted by 파란크리스마스

출처

Jenkins war 다운로드

Jenkins 사이트의 war 파일 다운로드

Jenkins war 복사

%TOMCAT_HOME%/warapps 폴더에 jenkins.war 파일 복사

Jenkins 접속

웹브라우져에서 https://localhost:8080/jenkins 접속

Unlock Jenkins

아래 경로에 비밀번호가 적힌 파일(initialAdminPassword)에 적힌 비밀번호를 확인 후 비밀번호를 입력하고, [Continue] 버튼 선택

플로그인 설치

[Install suggested plugins] 선택하고 설치 - 나중에 플러그인을 추가, 삭제 가능

플러그인 설치 과정

사용자 추가

Jenkins URL 정의

Jenkins 실행

Jenkins 설치 관료후 메인 화면

댓글을 달아 주세요

iReport

Programming/Java 2019. 6. 1. 20:32 Posted by 파란크리스마스

출처

가상 레코드 생성 예제

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();
	}

}

댓글을 달아 주세요

jni

Programming/Java 2018. 8. 25. 23:07 Posted by 파란크리스마스

출처

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

댓글을 달아 주세요

Linux에 Maven 설치하기

Programming/Java 2018. 7. 21. 22:06 Posted by 파란크리스마스

출처

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"

댓글을 달아 주세요

  1. 비밀글 2019.01.01 18:02  댓글주소  수정/삭제  댓글쓰기

    maven 설치경로가 navercorp면 사내경로 아닌가요...??

Tomcat SSL 설정 - https 서비스

Programming/Java 2018. 6. 21. 00:42 Posted by 파란크리스마스

출처

키생성 (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>

댓글을 달아 주세요

TOMCAT - jmx 로 monitoring

Programming/Java 2017. 12. 7. 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. 7. 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();
		}
	}
}

댓글을 달아 주세요

  1. 미말이 2019.06.21 14:28  댓글주소  수정/삭제  댓글쓰기

    혹시 HSSF 사용해서는 이미지 저장이 어려울까요?