date관련 작업을 할때 유틸 처럼 사용할 클래스를 만들면서 기본 java api이외에 사용할 패키지를 검색 하다

joda-time을 발견하고 오래전 부터 많은 사람들이 사용하던 패키지 라는걸 알고는 관련 함수를 해당 패키지를

이용해서 작업해 보았다

import java.util.Date;



import org.joda.time.DateTime;

import org.joda.time.Days;

import org.joda.time.format.DateTimeFormat;

import org.joda.time.format.DateTimeFormatter;



public class DateUtil {

 private DateTime dateTime;





 public DateUtil(){}



 public DateUtil(Date date){

 dateTime = new DateTime(date);

 }



 public void defaultDateSetting(Date date){

 dateTime = new DateTime(date);

 }



 public int getYear(){

 return dateTime.getYear();

 }



 public int getMonth(){

 return dateTime.getMonthOfYear();

 }



 public int getDay(){

 return dateTime.getDayOfMonth();

 }



 public int getHour(){

 return dateTime.getHourOfDay();

 }



 public int getMinute(){

 return dateTime.getMinuteOfHour();

 }



 public String getYearToString(){

 int curYear = dateTime.getYear();

 return String.valueOf(curYear);

 }



 /**

  * 10이하의 값은 앞에 0을 붙이게 됩니다.

  * */

 public String getMonthToString(){

 int curMonth = dateTime.getMonthOfYear();

 if(curMonth<10){

 return "0"+curMonth;

 }else{

 return String.valueOf(curMonth);

 }

 }



 public String getMonthToStringDefault(){

 int curMonth = dateTime.getMonthOfYear();

 return String.valueOf(curMonth);

 }

 /**

  * 10이하의 값은 앞에 0을 붙이게 됩니다.

  * */

 public String getDayToString(){

 int curDay = dateTime.getDayOfMonth();

 if(curDay<10){

 return "0"+curDay;

 }else{

 return String.valueOf(curDay);

 }

 }



 public String getDayToStringDefault(){

 int curDay = dateTime.getDayOfMonth();

 return String.valueOf(curDay);

 }



 public String getSimpleDateFormat(String dateFormat){

 DateTimeFormatter dateTimeFormat = DateTimeFormat.forPattern(dateFormat);

 return dateTime.toString(dateTimeFormat);

 }



 public String getSimpleDateFormat(Date date, String dateFormat){

 DateTimeFormatter dateTimeFormat = DateTimeFormat.forPattern(dateFormat);

 return new DateTime(date).toString(dateTimeFormat);

 }

 /**

  * 전달 받은 Date의 year,month,day에 해당하는 margin만큰 지난 날짜를 반환하는 

  * 메소드

  * */

 public Date dayCalForStr(Date date, int margin, String mode){

 DateTime calDateTime = new DateTime(date);

 if(mode.endsWith("year")){

 calDateTime.plusYears(margin);

 }else if(mode.endsWith("month")){

 calDateTime.plusMonths(margin);

 }else{

 calDateTime.plusDays(margin);

 }

 return calDateTime.toDate();

 }



 /**

  * 생성시 설정된 date의 year,month,day에 해당하는 margin만큰 지난 날짜를 반환하는 

  * 메소드

  * */

 public Date dayCalForStr(int margin, String mode){

 if(mode.endsWith("year")){

 dateTime.plusYears(margin);

 }else if(mode.endsWith("month")){

 dateTime.plusMonths(margin);

 }else{

 dateTime.plusDays(margin);

 }

 return dateTime.toDate();

 }



 /**

  * 전달 받은 날짜(targetDate-yyyy-mm-dd)가 현재 날짜 기준으로 checkNum(날짜) 기준안의 글인지 체크 하는 메소드

  * checkNum 날짜 보다 더 전의 글은 false 안의 글이면 true

  * */

 public boolean marginCheck(String dateStr, int checkNum){

 DateTime checkDateTime  = new DateTime(dateStr);

 Days checkDays  = Days.daysBetween(dateTime, checkDateTime);

 int checkCnt  = checkDays.getDays();

 if(checkCnt>checkNum){

 return false;

 }else{

 return true;

 }

 }



 /**

  * 전달 받은 날짜(targetDate-yyyy-mm-dd)가 (checkDate-yyyy-mm-dd)기준으로 checkNum(날짜) 기준안의 날짜인지 체크 하는 메소드

  * checkNum 날짜 보다 더 전의 날짜는 true 안의 날짜면 false

  * */

 public boolean marginCheck(String checkDate, String targetDate, int checkNum){

 DateTime checkDateTime  = new DateTime(checkDate);

 DateTime targetDateTime  = new DateTime(targetDate);

 Days checkDays  = Days.daysBetween(targetDateTime, checkDateTime);

 int checkCnt  = checkDays.getDays();

 if(checkCnt>checkNum){

 return false;

 }else{

 return true;

 }

 }



 /**

  * 전달 받은 날짜(targetDate yyyy-mm-dd, hour, minute)가 현재 날짜 기준으로 이전인지 이후 인지 체크하는 메소드

  * 현재 날짜 보다 이전일 경우 false 이후 이면 true

  * */

 public boolean atferDateCheck(String targetDate, String hour, String minute){

 String[] tDate = targetDate.split("-");

 if("".equals(hour)){hour = "0";}

 if("".equals(minute)){minute = "0";}



 DateTime targetDateTime = new DateTime(Integer.parseInt(tDate[0]), Integer.parseInt(tDate[1]), Integer.parseInt(tDate[2]), Integer.parseInt(hour), Integer.parseInt(minute));

 if(dateTime.isAfter(targetDateTime)){

 return true;

 }else{

 return false;

 }

 }

 /**

  * 시작 날짜(startDate yyyy-mm-dd, hour, minute)와

  * 종료 날짜(endDate yyyy-mm-dd, hour, minute) 기준으로 

  * 오늘 날짜가 속해 있을경우 true 

  * 오늘 날짜가 속해 있지 않을 경우 false

  * */

 public boolean innerDateCheck(String startDate, String startHour, String startMinute, String endDate, String endHour, String endMinute){

 String[] sDate = startDate.split("-");

 String[] eDate = endDate.split("-");

 if("".equals(startHour)){startHour = "00";}

 if("".equals(startMinute)){startMinute = "00";}

 if("".equals(endHour)){endHour = "00";}

 if("".equals(endMinute)){endMinute = "00";}



 DateTime startDateTime  = new DateTime(Integer.parseInt(sDate[0]), Integer.parseInt(sDate[1]), Integer.parseInt(sDate[2]), Integer.parseInt(startHour), Integer.parseInt(startMinute));

 DateTime endDateTime  = new DateTime(Integer.parseInt(eDate[0]), Integer.parseInt(eDate[1]), Integer.parseInt(eDate[2]), Integer.parseInt(endHour), Integer.parseInt(endMinute));



 if(dateTime.isAfter(startDateTime) && dateTime.isBefore(endDateTime)){

 return true;

 }else{

 return false;

 }

 }





 /**

  * 넘겨준 year,month,day,time,minute값으로 디비에 저장할 Date함수를 넘겨주는 메소드

  * @param int year 년도

  * @param int month 월

  * @param int day 일

  * @param int time 시간

  * @param int minute 분

  * @return Date

  * */

 public Date dateInString(int year, int month, int day, int time, int minute){

 DateTime createDateTime = new DateTime(year, month, day, time, minute);

 return createDateTime.toDate();

 }



 /**

  * dateStr 을 format형식으로 받아서 Date로 반환하는 메소드 

  * DateTimeFormatter 에 맞는 포멧을 넘겨 주면 자동 변환

  * */

 public Date dateInSimpleDateFormat(String dateStr, String format){

 DateTime createDateTime = new DateTime(dateStr);

 return createDateTime.toDate();

 }

}
반응형

'JAVA' 카테고리의 다른 글

POI/jfreeChart 이용한 엑셀파일 만들기  (0) 2015.08.26
common-io 를 사용한 파일관련 class  (0) 2015.08.04
class 컴파일 버전 확인  (0) 2015.07.30
cookie관련 기본 자바 소스  (0) 2015.07.24
excel파일 생성하는 메소드  (0) 2015.07.24
Posted by 질주하는구
,

class 컴파일 버전 확인

JAVA 2015. 7. 30. 15:28

class파일의 자바 컴파일 버전 정보를 확인 하기 위한 방법

-유닉스/리눅스

javap -verbose {클래스파일명} | grep version

=> javap -verbose TestClass.class | grep version

-윈도우

javap -verbose {클래스파일명(.class 제외)} | find /N "version"

=>javap -verbose TestClass | find /N "version"


-major버전과 monor 버전에 따른 자바 플랫폼 버전

major  minor    Java platform version 

   45       3           1.0 

   45       3           1.1 

   46       0           1.2 

   47       0           1.3 

   48       0           1.4 

   49       0           1.5 

   50       0           1.6 


   

반응형

'JAVA' 카테고리의 다른 글

common-io 를 사용한 파일관련 class  (0) 2015.08.04
joda-time을 이용한 date함수  (0) 2015.08.04
cookie관련 기본 자바 소스  (0) 2015.07.24
excel파일 생성하는 메소드  (0) 2015.07.24
CaseInsensitiveMap (common-collections.jar)  (0) 2015.07.15
Posted by 질주하는구
,

java소스에서 쿠키를 저장 및 가지고 오는 기본 소스 입니다.


Noname3.java


반응형

'JAVA' 카테고리의 다른 글

joda-time을 이용한 date함수  (0) 2015.08.04
class 컴파일 버전 확인  (0) 2015.07.30
excel파일 생성하는 메소드  (0) 2015.07.24
CaseInsensitiveMap (common-collections.jar)  (0) 2015.07.15
java동작 환경 메모리 상태  (0) 2015.07.03
Posted by 질주하는구
,

list 정보를 받아서 엑셀파일을 생성하는 메소드 입니다.

데이터를 공통으로 받아서 처리 할 수 있게 정보 배열을 따로 받게 되어 있습니다.

완성전에 로직을 만들기 위해서 Map계열을 사용하는데 완성하게 되면 Bean을 받아서 처리 하는 방식으로

변경 할 예정 입니다.



createExcel.java


반응형
Posted by 질주하는구
,

apache에서 제공하는 패키지중 common-collections의 경우 java collections을 변형해서 사용 할 수 있게

해주는 패키지 입니다.


HashMap등의 경우 대소문자 구분을 해서 key를 사용해야 하지만 CaseInsensitiveMap의 경우에는 

그럴 필요가 없다거나 FastHashMap의 경우에는 map에 배열을 지정해서 지정된 배열 이외의 데이터는

받지 않는등의 변형된 collection을 사용 할 수 있습니다.


CaseInsensitiveMap의 경우 ibatis에서 HashMap으로 받던 부분을 대체하기 좋은 클래스 입니다.

반응형
Posted by 질주하는구
,

Runtime runtime = Runtime.getRuntime();
DecimalFormat format = new DecimalFormat("###,###,###.##");
long max = runtime.maxMemory();
long total = runtime.totalMemory();
long free = runtime.freeMemory();
System.out.println("=============================================");
System.out.println("=============================================");
System.out.println("Max : " + format.format(max));
System.out.println("Total : " + format.format(total));
System.out.println("Free : " + format.format(free));


java동작 환경의 메모리 사용량을 확인 할 수 있는 소스 입니다.

반응형
Posted by 질주하는구
,

해당 프로그램의 경우 url에 해당하는 정보를 가지고 와서 해당 정보를 pdf혹은 이미지로 저장하는 프로그램 샘플 입니다.

이미지 및 pdf모두 object/javascript로 생성된 객체에는 접근을 하지 못하기 때문에 그 부분의 경우 정상적인

생성이 되지 않을수 있습니다. 또한 pdf생성의 경우 itext모듈에서 img 및 css의 경로를 http 로 시작하는 전체 경로를

입력 하지 않은 경우 정상적으로 인식 하지 못하는 문제가 있습니다.


요청사항 처리를 위해서 간략하게 샘플만을 만든 소스이기 때문에 다른 인터넷의 소스보다 허접한 상태 입니다.

작업이 완료 되면 수정할 예정 입니다.


pdf_java.zip


반응형
Posted by 질주하는구
,

int/double/String 형태의 데이터를 받아서 해당 데이터의 숫자형태를 000,000,000 식으로 변경하는

소스 입니다.


double num = 29600000;

DecimalFormat df = new DecimalFormat("#,##0.00");

System.out.println(df.format(num));


"#,##0.00" 경우 소숫점 2자리 까지 출력 되게 됩니다.


DecimalFormat df = new DecimalFormat("#,###");

System.out.println(df.format(num));

이렇게 하는 경우에는 소숫점 숫자를 반올림 하게 됩니다.


int i = 1000000;

String str = String.format("%,d", i);


float f = 234000.987654;

String str = String.format("%,.3", f);


이렇게 처리 하는 방법도 있습니다.


String 형태의 경우 replaceAll을 이용해서 

String str = "2231342112134.6";

str = str.replaceAll("(?<=[0-9])(?=([0-9][0-9][0-9])+(?![0-9]))", ",");

System.out.println(str);

수정 하는 방법도 있습니다.

반응형
Posted by 질주하는구
,

XML파일로 환결 설정 혹은 참고 설정을 작업 하는 경우 해당 파일을 읽어 오기 위해서 

직접 프로그램을 작성 하지 않고 아파치 프로젝트의 

http://commons.apache.org/proper/commons-configuration/download_configuration.cgi

jar파일을 이용해서 작업을 진행 할 수 있습니다.


<!--?xml version="1.0" encoding="UTF-8" ?--> 
<modules> 
 <exporter-config> 
 <version>2.0</version> 
 <charset>utf-8</charset> 
 <logging prefix="expt-">/home/exporter/log</logging> 
 <work>/home/exporter/work</work> 
 <cache-file>/home/exporter/cache</cache-file> 
 </exporter-config> 
</modules>


xml 파일을 java파일에서 가지고 오는 경우 아래의 소스과 같이 실행 할 수 있습니다.

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;

public class ConfigTest {

	public static void main(String[] args) {
		XMLConfiguration config;
		try {
			config = new XMLConfiguration("/src/homepage/WEB-INF/config/configuration.xml");
			config.setDelimiterParsingDisabled(false);
			config.load();
			
			String basePath = config.getBasePath();
			debug("Base Path", basePath);
			
			String version = config.getString("exporter-config.version");
			debug("Version", version);
			
			String charset = config.getString("exporter-config.charset");
			debug("CharacterSet", charset);
			
			String logging = config.getString("exporter-config.logging");
			debug("Logging", logging);
			
			String work = config.getString("exporter-config.work");
			debug("Work", work);
			
			String cacheFile = config.getString("exporter-config.cache-file");
			debug("Cache File", cacheFile);
		} catch(ConfigurationException e) {
			e.printStackTrace();
		}
	}
	
	public static void debug(String prefix, String value) {
		System.out.println("- " + prefix + " : " + value);
	}
}
반응형
Posted by 질주하는구
,

동작중인 url의 내용을 가지고 오는 소스는 아래와 같다

URL url 							= null;
URLConnection connection 			= null;
InputStream is 						= null;
InputStreamReader isr 				= null;
BufferedReader br 					= null;
FileOutputStream fo 				= null;
Writer out 							= null;
try{
	url 			= new URL(miniListUrlpath);
	connection 		= url.openConnection();
	connection.setConnectTimeout(1000);
	connection.setReadTimeout(1000);
	
	is 					= connection.getInputStream();
	isr 				= new InputStreamReader(is,"UTF-8");
	br 					= new BufferedReader(isr);
	
	String buf 		= null;
	String readStr = "";
	
	while(true){
		buf 	= br.readLine();
		if(buf == null) break;
		readStr += buf+"\n";
	}
	
	File compilefile 	= new File(targetFilePath+"/"+targetFileName);
	File compileDir		= new File(targetFilePath);
	if(!compileDir.exists()){
		compileDir.mkdirs();
	}
	if(!compilefile.exists()){
		compilefile.createNewFile();
	}
	fo = new FileOutputStream(compilefile);
	out = new OutputStreamWriter(fo,"UTF-8");
	out.write(readStr);
	out.flush();
}catch(IOException e){
	e.printStackTrace();
	isSuccess = false;
	System.out.println("IOException");
}finally{
	if(out != null){try{out.close();}catch(IOException e){}}
	if(fo != null){try{fo.close();}catch(IOException e){}}
	if(br != null){try{br.close();}catch(IOException e){}}
	if(isr != null){try{isr.close();}catch(IOException e){}}
	if(is != null){try{is.close();}catch(IOException e){}}
}


해당 소스를 이용해서 작업을 하는 경우 반드시 setConnectTimeout/setReadTimeout 이용해서 데이터를 가지고 오지 못하는 경우를 데비 해야 한다... 이것을 설정 하지 않는 경우 데이터를 받아 오지 못하는 상황 발생시 서버에 부하를 줄수 있다는걸 명심 해야 한다.


반응형
Posted by 질주하는구
,