앱)AWS SES Email Util java spring 예제 샘플

Posted by HULIA(휴리아)
2018. 6. 27. 14:59 백엔드개발/자바스프링
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-ses</artifactId>
<version>1.11.0</version>
</dependency>



@Service
public class AWSEmail{
    @Value("${ses.accessKey}")
    private String accessKey;
   
    @Value("${ses.secretKey}")
    private String secretKey;

    @Value("${ses.region}")
    private String region;

    public String sendMail(String fromEmail, List<String> toAddress, String subject, String emailBody) throws AmazonClientException, Exception {
           String resultMsg = "";
           SendEmailRequest request = new SendEmailRequest().withSource(fromEmail);
         
          Destination dest = new Destination().withToAddress(toAddress);
          request.setDestination(dest);

          Content subjContent = new Content().withData(subject);
          Message msg = new Message().withSubject(subjContent);

         //Include a body in HTML formats.
          Content htmlContent = new Content().withData(emailBody);
          Body body = new Body.withHtml(htmlContent);
          msg.setBody(body);

          request.setMessage(msg);

          //Set AWS access credentials
          String tmpAccessKey = "";
          String tmpSecretKey ="";
          
          if("Local".equals(System.getProperty("server.type"))){
              tmpAccessKey = accessKey;
              tmpSecretKey = secretKey;

                           } else {
                              try{
                                  tmpAccessKey = AESCipherUtil.decrypt(accessKey);
                                  tmpSecretKey = AESCipherUtil.decrypt(secretKey);
                              }catch(Exception e){
                                sysout("Credential decryption failed !");
                              }
                           }

                   AWSCredentilas credentilas = new BasicAWSCredentials(tmpAcessKey, tmpSecretKey);
                   AmazonSimpleEmailServiceClient client = null;
   
                  if("Local".equals(System.getProperty("server.type"))){
                      ClientConfiguration clientCfg = new ClientConfiguration();
                       clientCfg.setProtocol(Protocol.HTTP);
                      clientCfg.setProxyHost("XXX.XXX.XXX.XXX");
               clientCfg.setProxyPort(8080);
                     client = new AmazonSimpleEmailServiceClient(credentials, clientCfg);
             } else{
                    client = new AmazonSimpleEmailServiceClient(credentials);
              }


               Region regionCode = null;

               switch(region){
                         case "EU_WEST_1":
                                 regionCode = Region.getRegion(Region.EU_WEST_1);
                                 break;
                         case "AP_NORTHEAST_1":
                             regionCode = Region.getRegion(Region.AP_NORTHEAST_1);
                             break;

               }

                client.setRegion(regionCode);

                  //Call Amazon SES to send the message
                  SendEmailResult rs = client.sendEmail(request);
                   resultMsg = rs.toString();

                   return resultMsg;
    }
}

앱)jstl list search result table sample 예제

Posted by HULIA(휴리아)
2018. 6. 12. 15:49 백엔드개발/자바스프링
<table class="table_tp1">
            <caption class="hide-caption">list</caption>
            <colgroup>
                     <col width="15%">
                     <col width="15%">
                     <col width="15%">
                     <col width="*">
           </colgroup>
           <thead>
                   <tr>
                          <th scope="col"><span>AAAA</span></th>
                          <th scope="col"><span>AAAA</span></th>
                          <th scope="col"><span>AAAA</span></th>
                          <th scope="col"><span>AAAA</span></th>
                 </tr>
             </thead>
             <tbody>
                   <c:choose>
                        <c:when test="${null != list && !empty list}">
                                 <c:forEach var="list" items="${list}" varStatus="lineIndex">
                       <tr<c:if test="${lineIndex.count % 2 == 0}">class="line_c"</c:if>>
                              <td class="al_c2">${list.kkk}</td>
                                <td class="al_c"><a href="#" onclick="detail('${list.kkk}')">kkkk</a></td>
                                 <td class="al_c">${list.kkk}</td>
                                 <td class="al_c">${list.kkk}</td>
                       </tr>
                                 </c:forEach>
                        </c:when>
                        <c:otherwise>
                              <tr>
                                     <td colspan="4" class="al_c2">No results were found for your search.</td>
                              </tr>
                         </c:otherwise>
                   </c:choose>
            </tbody>
        </table>                       

앱)jstl sample 예제

Posted by HULIA(휴리아)
2018. 6. 12. 15:31 백엔드개발/자바스프링
===URL관련
location.href="<c:url value='/xxx/aaaa.do' />";
url : "<c:url value='/xxx/aaaa.do' />",
<span><a href="<c:url value='/aaaa/ggg.do' />" targe='_blank'>dkfkdkj</a>
document.searchForm.action ="<c:url value='/xxx/aaaa.do' />"

<c:url value="/ttet/tete.do">
   <c:param name="keyword" value="${searchTerm}" />
   <c:param name="keyword2" value="${searchTerm2}" />
</c:url>

===조건문관련
<c:if test="${null != xxxx && !empty xxxx}">
       <c:forEach var="xxxx" items="${xxxx}">
            ${xxxx.kkkk}
       </c:forEach>
</c:if>
<option value="kkk" <c:if test="${type} eq 'kkkok'}">selected</c:if>>History</option>


===조건문관련2
<c:choose>
    <c:when test="${null != pppp && !empty pppp}">
     </c:when>
     <c:when test="${null != pppp && !empty pppp}">
     </c:when>
     <c:when test="${null != pppp && !empty pppp}">
     </c:when>
     <c:otherwise>
     </c:otherwise>
</c:choose>

===반복문
<c:forEach var="xxxx" items="${xxxx}" varStatus="lineIndex">
     <!--반복할 내용 -->
</c:forEach>

lineIndex.current:현재 순환중인 아이템을 가져옵니다
lineIndex.index:현재 순환중인 아이템의 인덱스(0베이스)를 가져옵니다
lineIndex.count:현재 순환중인 아이템의 인덱스(1베이스)를 가져옵니다
lineIndex.first:현재 순환중인 아이템이 첫번째 아이템인지 여부를 확인합니다(booelan)
lineIndex.last:현재 순환중인 아이템이 마지막 아이템인지 여부를 확인합니다(boolean)
lineIndex.begin:forEach에서 지정할 수 있는 begin값을 가져옵니다
lineIndex.end:forEach에서 지정할 수 있는 end값을 가져옵니다
lineIndex.step:forEach에서 지정할 수 있는 step값을 가져옵니다

===세팅관련
<c:set var="sum" value="0" /><!-- sum변수에 0을 세팅 -->
<c:set var="sum" value="${sum+statisticsList.totalCount}" /><!--sum에 totalCount값을 더한후 sum변수에 세팅 -->


===출력관련
<c:out value="${now}" />
<c:out value="${fn:replace(list.userID, '||', '-')}" />


===문자열관련
<c:if test="${fn:contains(name, "searchString")}">
<c:if test="${fn:endWith(filename, ".txt")}">
<c:if test="${fn:indexOf(name, "-")}">
<c:if test="${fn:length(name)}">
<c:if test="${fn:startWith(filename, ".txt")}">
<c:if test="${fn:subString(filename, 6, 0)}">
<c:if test="${fn:subStringAfter(filename, "-")}">
<c:if test="${fn:subStringBefore(filename, "-")}">


===import관련
<c:import url="ftp://ftp.example.com/pacakge/index.html" />

<c:import url="/tkkdj/ted.do">
   <c:param name="keyword" value="${searchTerm}" />
</c:import>


===리다이렉트
<c:redirect>
URL이 변경되면서 페이지 이동

앱)java spring framework excel export jstl

Posted by HULIA(휴리아)
2018. 6. 11. 18:15 백엔드개발/자바스프링




<a href="#" class="com_s_excel" onclick="exportExcel();"><span>Export to Excel</span></a>

function exportExcel(){
        $("searchForm").attr("action","<c:url value='/exportExcel.do' />").submit();
}

@RequestMapping(value="/exportExcel", method= RequestMethod.POST)
public ModelAndView exportExcel(HttpServletRequest request, HttpServletResponse response, @ModelAttribute SearchVo searchVo){
        ModelAndView view = new ModelAndView();
        
         view.addObject("contents", ServiceObj.getExportExcel(searchVo);
          view.setViewName("/exportExcel");

        return view;
}




====exportExcel.jsp
<%@ page language="java" contentType="application/vnd.ms-excel; charset=utf-8" pageEncoding="utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%
       response.setHeader("Content-Type", "application/vnd.ms-xls");
       response.setHeader("Content-Disposition", "inline; filename=ExportList.xls");
%>

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
         <head>
                  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                    <style>td { mso-number-format:\@; } </style>
          </head>
<body>
         <table style="text-align:center; font-weight:normal; background:#fafafa; color:#333; font-size:12px; border:1px solid #CCC;">
           <caption class="hide-caption">List</caption>
           <thead>
                  <tr style="border:1px solid #CCC; color:#555">
                          <th scope="col"><span class="sort" id="id">ID</span></th>
                           <th scope="col"><span class="sort" id="id">ID</span></th>
                    </tr>
              </thead>
              <tbody>
                      <c:choose>
                               <c:when test="${null != contents && !empty contents}">
                      <c:forEach var="contents" items="${contents}" varStatus="lineIndex">
                           <tr style="padding:8px; line-height:16px; border:1px solid #CCC; color:#555; font-size:12px; vertical-align:middle; word-break:break-all;">
                              <td class="al_c">${contents.code}</td>
<td class="al_c">${contents.name}</td>
<td class="al_c">${contents.desc}</td>
<td class="al_c">${contents.code1}</td>
<td class="al_c">${contents.code2}</td>
<td class="al_c">${contents.code2}</td>
                                  <tr>
                               </c:forEach>
                           </c:when>
                       <c:otherwise>
                       </c:otherwise>
                     </c:choose>
                   </tbody>
                 </table>
            </body>
         </html>

앱)jsp jstl jquery basic structure sample 기본 템플릿

Posted by HULIA(휴리아)
2018. 6. 11. 18:00 백엔드개발/자바스프링
<%@ language="java" page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="string" uri="http://jakarta.apache.org/taglibs/string-1.1" %>

<%@ page import="java.util.Locale" %>
<%@ page import="javax.servlet.jsp.jstl.core.Config" %>

<script>

$(function(){
         $(document).ready(function(){
         
         });

});


function XXX(){
}

</script>

앱)java springframework select box jstl form sample 예제

Posted by HULIA(휴리아)
2018. 6. 11. 11:19 백엔드개발/자바스프링
<form name="searchForm" id="searchForm" method="post">

<select name="statusCode" id="statusCode" style="width:208px;" class="select">
         <option value="">ALL</option>
         <option value="R">R</option>
         <option value="R">R</option>
         <option value="R">R</option>
         <option value="R">R</option>
</select>


<select name="status" id="status">
              <option value="">ALL</option>
              <c:if test="${null != stsCdList && !empty stsCdList}">
                     <c:forEach var="stsCdList" items="${stsCdList}">
                           <option value="${stsCdList.code}">${stsCdList.codeName}</option>
                     </c:forEach>
              </c:if>
</select>



<select id="useType" name="useType" style="width:200px;">
      <c:if test="${null != useTpCdList && !empty useTpCdList}">
             <c:forEach var="useTpCdList" items="${useTpCdList}">
                     <c:if test="${useTpCdList.code != 'M' && useTpCdList.code != 'P'}">
                             <option value="${useTpCdList.code}">${useTpCdList.codeName}</option>
                      </c:if>
             </c:forEach>
</select>

<select class="select" name="historySelect" id="historySelect" onchange="showView()" style="width:150px;height:23px;">
           <option value="kkkk" <c:if test="${historyType eq 'kkkk'}">selected</c:if>>History</option>
           <option value="pppp" <c:if test="${historyType eq 'pppp'}">selected</c:if>>History</option>
</select>


</form>


function showView(){
      var selectVal = $('#historySelect').val();
      if(selectVal == "kkkk") {
                $.ajax({
                         url : "<c:url value='/showView.do' />",
                         type: 'post',
                         beforSend : function(xhr) {
                        xhr.setRequestHeader("AJAX","true");
                        },
                        data : {
                             key : "${}",
                             key2 : "D"
                        },
                        contentType : "application/x-www-form-urlencoded; charset=UTF-8",
                        success : function(data) {
                           $('#dkfkjf').val();
                           $('#dfkjfk').html(data);
                          },
                         error : function(xhr, status, err){
                  if(xhr.status==403) {
                            location.href="<c:url value='/login/intro.do' />";
                         }
                   }

             });
      }
}

@RequestMapping(value = "/showView", method = {RequestMethod.POST})
public ModelAndView showView(HttpServletRequest request, HttpServletResponse response){
           ModelAndView view = new ModelAndView();

           int pageNo = ParamUtil.param(request,"pageNo",null) == null? 1: Integer.parseInt(ParamUtil.param(request,"pageNo", null));

view.addObject("key", keyObject);
view.setViewName("kkkk/kkkk");

return view;

}

앱)logback 한줄 로그 나오게 하는 방법

Posted by HULIA(휴리아)
2018. 6. 8. 13:19 백엔드개발/자바스프링
  LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
      JoranConfigurator jc = new JoranConfigurator();
       jc.setContext(context);
  context.reset ();//우리가 설정한 logback 설정만 적용된다
      
          jc.doConfigure(new ClassPathResource("logback"+System.getProperty("server.type")+".xml").getInputStream());

앱)AWS S3 Util java spring 예제 샘플

Posted by HULIA(휴리아)
2018. 6. 8. 11:19 백엔드개발/자바스프링
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>1.11.0</version>
</dependency>


@Configuration
public class AWSS3Util{

        @Value("${s3.accessKey}")
        private String accessKey;
   
        @Value("${s3.secretKey}")
        private String secretKey;

        @Value("${s3.region}")
        private String region;


        @Bean
         public AmazonS3 amazonS3Client(){
                String tmpAccessKey = "";
                String tmpSecretKey="";

                 if("Local".equals(System.getProperty("server.type"))){
                       tmpAccessKey = accessKey;
                       tmpSecretKey = secretKey;
                 }else{
                      tmpAccessKey = AESCipherUtil.decrypt(accessKey);
                     tmpSecretKey = AESCipherUtil.decrypt(secretKey);
                  }
         
                  AWSCredentials credentials = new BasicAWSCredentials(tmpAccessKey, tmpSecretKey);

                AmazonS3 s3Client = null;
 
                if("Local".equals(System.getProperty("server.type"))){
                     ClientConfiguration clientCfg = new ClientConfiguration();
                     clientCfg.setProtocol(Protocol.HTTP);
                      clientCfg.setProxyHost("");
                     clientCfg.setProxyPort();
                     s3Client = new AmazonS3Client(credentials, clientCfg);

                 }else{
                        s3Client = new AmazonS3Client(credentials);
                  }

                  Region regionCode = null;
      
                  switch (region) {
                        case="EU_WEST_1":
                                   regionCode = Region.getRegion(Regions.EU_WEST_1);
                                   break;
                       case="AP_NORTHEAST_1":
                         regionCode = Region.getRegion(Regions.AP_NORTHEST_1);
                        break;
                  }

                  s3Client.setRegion(regionCode);

               return s3Client;

       }

}

앱)자바 batch pid 파일 만들기

Posted by HULIA(휴리아)
2018. 4. 27. 14:34 백엔드개발/자바스프링
==main==
//pid file creation
String pidDir = System.getProperty("pid.dir", jobmgrHome+System.getProperty("file.separator")+"pid")

try{
     PidUtil pidUtil = new PidUtil(pidDir, "jobmanager.pid");
if(pidUtil.existPidFile()){
     LoggerUtil.error(logger, "already running...");
     String pid = pidUtil.readPidFile();
     LoggerUtil.error(logger,"pid: "+pid);
     System.exit(0);
}

String pid = pidUtil.createPidFile();

LoggerUtil.info(logger, "PID file created. <pid : "+pid + ">");
}catch(IOException ie){
    ie.printStackTrace();
}

}




==PidUtil==
public class PidUtil{
       private String pidDir;
       private String pidFileName;

       pulbic PidUtil(String pidDirectory, String pidFileName) {
     makeDir(pidDirectory);
     this.pidFileName = pidFileName;
     pidDir = new File(pidDirectory).getPath();
}
  

    public File getPidFile(){
           return new File(pidDir + System.getProperty("file.separator")+pidFileName);
    }

    public String getPID() throws IOException{
    String str = ManagementFactory.getRuntimeMXBean().getName();
    return str.split("@")[0];
}

public String createPidFile() throws IOException{
      String pid = null;
      pid = getPID();

      //파일 생성
      writePID(getPidFile(), pid);
      return pid;
}

public void deletePID(){
      delete(getPidFile());
}

public String readPidFile() throws IOException{
         return readFile(getPidFile());
}

public boolean existPidFile() throws IOException{
        boolean isRet = false;
//pid파일 존재하는지 체크한다.
//파일 존재할 경우 pid 정보를 읽는다
//pid가 -1인 경우 실패한 경우이므로 pid파일이 존재하지 않는다는 결과를 반환한다
//pid가 -1가 아닌 경우 windows 2000이면 tilst로 해당 pid를 체크하고 windows 2000이상이면 tasklist로 체크한다
      if(getPidFile().exist()){
          String pid = readFile(getPidFile());
         if( !pid.equals("-1")){
               String winOsName = System.getProperty("os.name");
              boolean isWindow = winOsName.startWith("Windows");
              if( isWindow) {//windows
                  if(winOsName.indexOf("2000") > -1) {
      if(hasProcess(pid, "tlist")){
              isRet = true;
       }
}else{
       if(hasProcess(pid, "tasklist")){
               isRet = false;
       }
}

              }else{//linux & unix
                 if(hasProcess(pid, "ps -p "+ pid)){
       isRet = true;
}
             }
         }
      }
      return isRet;
}

private boolean hasProcess(String pid, String checkCMD) throws IOException{
       boolean isRet = false;
       Process p_start = Runtime.getRuntime().exec(checkCMD);
       BufferedReader stdout = new BufferedReader (new InputStreamReader(p_start.getInputStream()));
        String output;
        while((output=stdout.readLine())!=null){
         if(output.indexOf(pid) > -1 && (output.startsWith("java") || output.indexOf("java") > -1)){
               isRet = true;
               break;
           }
}
p_start.destory();
return isRet;
}

private void writePID(File file, String pid) throws IOException{
     FileWriter fw = null;
     try{
           fw=new FileWriter(file);
           fw.write(pid);
           fw.close();
       }catch (IOException ioe){
            throw ioe;
       }finally{
            if(fw != null){
                 fw.close();
            }
       }
}

public synchronized void makeDir(String path){
        File dir = new File(path);
        if( !dir.exists()){
                dir.mkdirs();
        }
}

public String readFile(File file) throws IOException{
        FileReader fileReader = null;
        String s = null;
        try{
            fileReader = new FileReader(file);
            s = readReader(fileReader);
        } finally{
             if( fileReader != null){
                   fileReader.close();                
             }
        }
         return s;
}

public void delete(File file){
         if(file != null){
                 if(file.exists()){
                      file.delete();
                 }
         }
}


public String readReader(Reader input) throws IOException{
 try{
     StringBuffer buf = new StringBuffer();
     BufferedReader in = new BufferedReader(input);
     int ch;
     while((ch=in.read())!= -1){
             buf.append((char)ch);
     }
     return buf.toString();
}finally{
      input.close();
}

}
}


===우분투 스크립트(메인 스크립트)
#!/bin/bash

NAME="batch"
DEFAULT = "opt/~/env.sh"
DESC="~~~~Batch Application Serve for $NAME"

#check privilegs
if [ ' id -u' -ne 0 ]; then
     echo "You need root privileges to run this script"
     exit 1
fi

# Make sure wildfly is started with system locale
if [ -r  /etc/default/locale ]; then
           . /etc/default/locale
           export LANG
fi

# Overwrite settings from default file
if [ -f "$DEFAULT" ]; then
              . "$DEFAULT:
fi

# Setup the JVM
if [ -z "$JAVA" ]; then
          if [ -n "$JAVA_HOME" ]; then
                  JAVA="$JAVA_HOME/bin/java"
          else
                   JAVA="java"
          fi
fi


# Check if wildfly is installed
if [ ! -f "$JOBMGR_HOME/JobMnager.jar" ]; then
           log_failure_msg "$NAME is not installed in \"$JOBMGR_HOME\""
            exit 1
fi

if [ -z "$JOBMGR_USER" ]; then
            JOBMGR_USER=root
fi

# Check wilfly user
id $JOBMGR_USER > /dev/null 2>&1
if [ $? -ne 0 -o -z "$JOBMGR_USER" ]; then
            log_failure_msg "User \"$JOBMGR_USER\" does not exist..."
            exit 1
fi

# Check owner of JOBMGR_HOME
if [ ! $(stat -L -c "%U" "$JOBMGR_HOME") = $JOBMGR_USER ]; then
         log_failure_msg "The user \"$JOBMGR_USER\" is not owner of \"$JOBMGR_HOME\""
         exit 1
fi


# The amount of time to wait for startup
if [ -z "$STARTUP_WAIT" ]; then
          STARTUP_WAIT=120
fi


# The amount of time to wait for shutdown
if [ -z "$SHUTDOWN_WAIT" ]; then
            SHUTDOWN_WAIT=120
fi


# Location to keep the console log
if [ -z "JOBMGR_CONSOLE_LOG" ]; then                      JOBMGR_CONSOLE_LOG="$JOBMGR_HOME/logs/console.log"
fi

export JOBMGR_CONSOLE_LOG

touch $JOBMGR_CONSOLE_LOG
chown $JOBMGR_USER $JOBMGR_CONSOLE_LOG

# Location to set the pid file
JOBMGR_PIDFILE="$JOBMGR_HOME/pid/jobmanager.pid"
export JOBMGR_PIDFILE

# Helper functions to check status of Jboss services
check_status() {
         echo "pidofproc -p \"$JOBMGR_PIDFILE\" \"$JAVA\" >/dev/null 2>&1"
         pidofproc -p "$JOBMGR_PIDFILE" "$JAVA" >/dev/null 2>&1
}


case "$1" in
  start)
       log_daemon_msg "Starting $DESC"
       check_status
       status_start=$?
       if [ $status_start -eq 3 ]; then
              cat /dev/null > "$JOBMGR_CONSOLE_LOG"
              source $DEFAULT; java $JOBMGR_OPTS $JAVA_OPTS -jar JobManager.jar > ${JOBMGR_CONSOLE_LOG} 2>&1 &"

               count=0
               launched=0
               until [ $count -gt $STARTUP_WAIT ]
                do
                           if check_status; then
                                     launched=1
                                     break
                           fi
                           sleep 1
                            count=$((count + 1));
                  done
                 
                   if [ $launched -eq 1 ]; then
                              chown $JOBMGR_USER $(dirname "$JOBMGR_PIDFILE") || true
                   fi
                  
                   if check_status; then
                               log_end_msg 0
                   else
                               log_end_msg 1
                    fi

                    if [ $launched -eq 0 ]; then
                                log_warning_msg "$DESC hasn't started within the timeout allowed"
                                log_warning_msg "please review file \"$JOBMGR_CONSOLE_LOG\" to see the status of the service"
                     fi
       elif [ $status_start -eq 1 ]; then
                log_failure_msg "$DESC is not running but the pid file exists"
                exit 1
       elif [ $status_start -eq 0 ]; then
                log_success_msg "$DESC (already running)"
        fi   
      
     ;;



  stop)
        check_status
        status_stop=$?
        if [ $status_stop -eq 0 ]; then
                  read kpid < "$JOBMGR_PIDFILE"
                  log_daemon_msg "Stopping $DESC"
                   if check_status; then
                               kill $kpid
                   fi

                    rm "$JOBMGR_PIDFILE"
                   
                     log_end_msg 0
          elif [ $status_stop -eq 1 ]; then
                    log_action_msg "$DESC is not running but the pid file exists, cleaning up"
                    rm -f $JOBMGR_PIDFILE
           elif [ $status_stop -eq 3 ]; then
                     log_action_msg "$DESC is not running"
           fi
      ;;

  restart)
         check_status
         status_restart=$?
         if [ $status_restart -eq 0 ]; then
                       $0 stop
         fi
         $0 start

         ;;

  status)
          check_status
          status=$?
          if [ $status -eq 0 ]; then
                 read pid < $JOBMGR_PIDFILE
                 log_action_msg "$DESC is running with pid $pid"
                 exit 0
           elif [ $status -eq 1 ]; then
                 log_action_msg "$DESC is not running and the pid file exists"
                 exit 1
            elif [ $status -eq 3 ]; then
                 log_action_msg "$DESC is not running"
                 exit 3
            else
                  log_action_msg "Unable to determine $NAME status"
                 exit 4
            fi

  ;;

  *)
   log_action_msg "Usage: $0 {start|stop|restart|status}"
   exit 2
   ;;

esac

exit 0


===우분투 스크립트(env 스크립트)
env.sh파일임

#!/bin/bash


export SERVER_HOME="/opt"
export SERVER_NAME="Batch"
export JOBMGR_HOME="${SERVER_HOME}/${SERVER_NAME}"
export SERVER_TYPE="Dev"


LIB_DIR=${JOBMGR_HOME}/lib

export JAVA_HOME=/opt/java
export CLASSPATH=.:/opt/java/jre/lib:$LIB_DIR

export PATH=$JAVA_HOME/bin:$PATH

if [ "x$JOBMGR_OPTS" ="x" ]; then
     JOBMGR_OPTS="-Djobmanager"
     JOBMGR_OPTS="$JOBMGR_OPTS -Djobmgr.home=${JOBMGR_HOME}"
JOBMGR_OPTS="$JOBMGR_OPTS -Dserver.type=${SERVER_TYPE}"
JOBMGR_OPTS="$JOBMGR_OPTS -Djobmgr.resourcepath=file:${JOBMGR_HOME}/conf/"
fi

if [ "x$JAVA_OPTS" = "x" ]; then
        JAVA_OPTS="-server"
        JAVA_OPTS="$JAVA_OPTS -noverify"
         JAVA_OPTS="$JAVA_OPTS -Xms512m"
         JAVA_OPTS="$JAVA_OPTS -Xmx5124m"
         JAVA_OPTS="$JAVA_OPTS -XX:NewRatio=7" #전체 메모리의 3/4를 old generation 영역으로 지정
         JAVA_OPTS="$JAVA_OPTS -XX:PermSize=64m"
         JAVA_OPTS="$JAVA_OPTS -XX:MaxPermSize=128m"
         JAVA_OPTS="$JAVA_OPTS -XX:+UseParNewGC"  #Young Generation 영역에서 parrel로 GC를 수행하도록 한다
         JAVA_OPTS="$JAVA_OPTS -XX:+UseConcMarkSweepGC"  #CMS Controller 활성화
         JAVA_OPTS="$JAVA_OPTS -XX:+CMSParallelRemarkEnabled"  #Remark 단계를 Parallel로 동작하도록 지정
         JAVA_OPTS="$JAVA_OPTS -XX:CMSFullGCsBeforeCompaction=0" # Concurrent Full GC는 항상 Compaction을 수반하도록 한다
         JAVA_OPTS="$JAVA_OPTS -XX:+ExplicitGCInvokesConcurrent"  #system.gc() 하더라도 CMS GC를 실행하도록 한다
         JAVA_OPTS="$JAVA_OPTS -verbose:gc"
         JAVA_OPTS="$JAVA_OPTS -Xloggc:$JOBMGR_HOME/gclog/gc_'date "+%Y%m%d%H"'.log"
         JAVA_OPTS="$JAVA_OPTS -XX:+PrintGCDetails"  # GC에 대한 상세출력
         JAVA_OPTS="$JAVA_OPTS -XX:+PrintGCDateStamps"  # 시스템 날짜 기록
         JAVA_OPTS="$JAVA_OPTS -XX:+PrintHeapAtGC"
         JAVA_OPTS="$JAVA_OPTS -XX:+HeapDumpOnOutOfMemoryError"
         JAVA_OPTS="$JAVA_OPTS -XX:HeapDumpPath=$JOBMGR_HOME/gclog/java_pid.hprof"
         JAVA_OPTS="$JAVA_OPTS -Djava.security.egd=file:/dev/./urandom"
         JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote"
         JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote.port=8286"
         JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote.ssl=false"
         JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote.authenticate=false"
         JAVA_OPTS="$JAVA_OPTS -Djava.net.preferIPv4Stack=true"
         JAVA_OPTS="$JAVA_OPTS -Dsun.lang.ClassLoader.allowArraySyntax=true"
         JAVA_OPTS="$JAVA_OPTS -Dsun.net.inetaddr.ttl=10"
         JAVA_OPTS="$JAVA_OPTS -Dsun.net.inetaddr.negative.ttl.10"
fi


export JAVA_OPTS JOBMGR_OPTS

앱)jar 파일 실행하는 법 정리

Posted by HULIA(휴리아)
2018. 4. 13. 10:16 백엔드개발/자바스프링
기본 실행방법
java -jar jar파일이름.jar

옵션 넣어서 실행방법
java -Dserver.type=Local -jar jar파일이름.jar

참고로 -jar 옵션보다 -D가 뒤에 있다면 jar파일 실행할때 옵션값을 못 가지고 가게됨