Search

'Programming/Java'에 해당되는 글 75건

  1. 2011.08.25 HTML + TagSoup + XPath
  2. 2010.12.06 Antlr - java.g
  3. 2010.11.17 Eclipse - JavaCC Plig-in 설치 (1)
  4. 2010.11.16 Eclipse svn plug-in 설치
  5. 2010.10.07 Quartz - JobStoreSupport
  6. 2010.09.17 Quartz Web Application (1)
  7. 2010.09.14 Spring Quartz Batch (2)
  8. 2010.09.09 Quartz - SimpleTrigger 사용하기
  9. 2010.09.03 Tomcat 7 - Spring MVC 설치
  10. 2010.09.02 Maven / Jetty 설치
  11. 2009.05.08 Lucene - indexer
  12. 2009.01.12 Tomcat 5.5 Connection Pool 설정

HTML + TagSoup + XPath

Programming/Java 2011.08.25 15:29 Posted by 파란크리스마스

출처 : http://www.supermind.org/blog/613/dom4j-xpath-tagsoup-namespaces-sweet
http://tomasblue.tistory.com/entry/Dom4j-XPath%EB%A5%BC-%EC%9D%B4%EC%9A%A9%ED%95%9C-%EC%BF%BC%EB%A6%AC-%EB%AC%B8%EC%A0%9C%EC%A0%90-%ED%95%B4%EA%B2%B0-Namespace%EA%B4%80%EB%A0%A8

//
XPath xpath = XPathFactory.newInstance().newXPath(); 

//
BufferedReader bis = new BufferedReader (new InputStreamReader ("index.html"), "UTF-8")); 

//
XMLReader tagsoup = new org.ccil.cowan.tagsoup.Parser(); 
SAXReader reader = new SAXReader(tagsoup);
Document doc = reader.read(bis); 
 
// 네임스페이스 제거 XPath를 이용하려면 네임스페이스를 제거해야 함
XMLUtils.fixNamespaces(doc);
//XMLUtils.generateXmlFile(doc, "index.xml");

//<li class="bar">하나
DefaultText han_mean_Node = (DefaultText)ajax_pron_dlNode.selectSingleNode("//li[@class='bar']/text()[1]");

//<span class="count"> 
//  <b>2</b>개
//</span>  
DefaultElement hanziCountNode = (DefaultElement)doc.selectSingleNode("//span[@class=\"count\"]/b");

//<div id="content"> 
//  <div id="detail">
//    <ul id="data1">1</ul>
//    <ul id="data2">2</ul>
List contentList = doc.selectNodes("//div[@id='content']/div[@id='detail']/node()");
XMLUtils.java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.dom4j.Node;
import org.dom4j.QName;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class XMLUtils {
	/**
	 * @param doc DOM4J XML Document
	 * Generate XML File
	 */
	public static void generateXmlFile(Document doc, String xmlfile) {
		XMLWriter writer = null;
		try {
			OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(new File(xmlfile)), "UTF-8");
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("UTF-8");
			writer = new XMLWriter(osw,format);
			
			writer.write(doc);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	
	} 
	
	/**
	 * @param doc DOM4J XML Document
	 * Generate XML File
	 */
	private static void generateXmlFile(Element doc, String xmlfile) {
		XMLWriter writer = null;
		try {
			OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(new File(xmlfile)), "UTF-8");
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("UTF-8");
			writer = new XMLWriter(osw,format);
			
			writer.write(doc);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}  			

	/**
	 * 네임스페이스 제거 XPath를 이용하려면 네임스페이스를 제거해야 함
	 */
	public static void fixNamespaces(Document doc) {
		Element root = doc.getRootElement();
		if (root.getNamespace() != Namespace.NO_NAMESPACE)
			removeNamespaces(root.content());
	}

	/**
	 * 네임스페이스 원복
	 */
	public static void unfixNamespaces(Document doc, Namespace original) {
		Element root = doc.getRootElement();
		if (original != null)
			setNamespaces(root.content(), original);
	}

	/**
	 * 목록내 모든 element의 네임스페이스 제거
	 */
	@SuppressWarnings("unchecked")
	private static void removeNamespaces(List l) {
		setNamespaces(l, Namespace.NO_NAMESPACE);
	}

	/**
	 * Element의 네임스페이스 설정(child포함)
	 */
	private static void setNamespaces(Element elem, Namespace ns) {
		setNamespace(elem, ns);
		setNamespaces(elem.content(), ns);
	}

	/**
	 * 목록내 node(child포함)의 네임스페이스 설정
	 */
	@SuppressWarnings("unchecked")
	private static void setNamespaces(List l, Namespace ns) {
		Node n = null;
		for (int i = 0; i < l.size(); i++) {
			n = (Node) l.get(i);
			if (n.getNodeType() == Node.ATTRIBUTE_NODE)
				((Attribute) n).setNamespace(ns);
			if (n.getNodeType() == Node.ELEMENT_NODE)
				setNamespaces((Element) n, ns);
		}
	}

	/**
	 * Elemnet의 네임스페이스 설정
	 */
	private static void setNamespace(Element elem, Namespace ns) {
		elem.setQName(QName.get(elem.getName(), ns, elem.getQualifiedName()));
	}
}

Antlr - java.g

Programming/Java 2010.12.06 13:41 Posted by 파란크리스마스

@header {
package xxx;
}

@members {
private AppBase appBase;

public void SetAppBase(AppBase appBase) {
  this.appBase = appBase;
}
}

@lexer::header {
package xxx;
}

packageDeclaration 
    :   'package' qualifiedName {
         System.out.println("--" + $qualifiedName.result.getLine() + "/" + $qualifiedName.result.getQualifiedName());
      }
        ';'
    ;

qualifiedName returns [AstQualifiedName result]
scope {
  AstQualifiedName current;
}
@init {
  $qualifiedName::current = new AstQualifiedName();
}

    :   IDENTIFIER {
          $qualifiedName::current.setLine($IDENTIFIER.getLine());
          $qualifiedName::current.addIdentifier($IDENTIFIER.getText());
      }
        ('.' IDENTIFIER {
          $qualifiedName::current.addIdentifier($IDENTIFIER.getText());
        }
        )* {
          $result = $qualifiedName::current;
        }
    ;

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

package xxx;

import xxx.AppBase;

import org.antlr.runtime.ANTLRFileStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.RuleReturnScope;
import org.antlr.runtime.Token;
import org.antlr.runtime.TokenStream;
import org.antlr.runtime.tree.CommonErrorNode;
import org.antlr.runtime.tree.CommonTreeAdaptor;
import org.antlr.runtime.tree.TreeAdaptor;

public class JavaTestMain {
 
 public static void main(String[] args) throws Exception {
  
  AppBase appBase = new AppBase();
  
  ANTLRFileStream fileStream = new ANTLRFileStream("ASTMain.java");
  JavaLexer lexer = new JavaLexer(fileStream);
  CommonTokenStream tokens = new CommonTokenStream(lexer);
  JavaParser parser = new JavaParser(tokens);
  parser.SetAppBase(appBase);
  parser.compilationUnit();
  }
}


Eclipse - JavaCC Plig-in 설치

Programming/Java 2010.11.17 10:45 Posted by 파란크리스마스
출처 : http://eclipse-javacc.sourceforge.net/

1. 메뉴 [Help] -> [Install New Software] 선택



2. [Install]창에서 [Add] 버튼 선택



3. 아래와 같이 입력하고 [OK] 버튼 선택

Name : JavaCC Plug-In
Location : http://eclipse-javacc.sourceforge.net/



4. JavaCC Eclipse Plug-in 선택하고  [Next] 버튼 선택



5. [Next] 버튼 선택



6. 라이센스 수용하고, [Finish] 버튼 선택



7. [OK] 버튼 선택



8. Plug-in 설치 완료 후, [Restar Now] 버튼을 선택하여 Eclipse을 다시 시작한다.



- jj 파일을 열어본 화면



- jj 파일에서 오른쪽 마우스를 선택하여 Compile 하기



- jj Compile 결과



- jj 파일 Compile 하여 생성된 java 파일들



Eclipse svn plug-in 설치

Programming/Java 2010.11.16 10:16 Posted by 파란크리스마스

출처 http://jungkun86.egloos.com/4139049
http://www.eclipse.org/subversive/downloads.php

1 Eclipse을 실행한다.

2 메뉴 [Help] > [Install New Software...]을 선택한다.



3. 버튼 [Add...] 선택하여 추가 하거나 이미 등록되어 있는 사이트의 경우 [Availbale Software Sites] 선택한다.

Location 주소 : http://download.eclipse.org/technology/subversive/0.7/update-site/



4. [Enable] 버튼을 선택한다. 



5. Work with : http://download.eclipse.org/technology/subversive/0.7/update-site/ 선택하고, [Next] 버튼 선택한다.



6. [Next] 버튼 선택한다.



7. 라이센트 동의하고, [Finish] 버튼 선택한다.



8. 플러그인이 설치가 완료 되면 Eclipse 제시작한다.

Quartz - JobStoreSupport

Programming/Java 2010.10.07 15:57 Posted by 파란크리스마스

package org.quartz.impl.jdbcjobstore;

public abstract class JobStoreSupport implements JobStore, Constants {

    class MisfireHandler extends Thread {
        public void run() {
            while (!shutdown) {

                RecoverMisfiredJobsResult recoverMisfiredJobsResult = manage();

                if (!shutdown) {
                    long timeToSleep = 50l;  // At least a short pause to help balance threads
                    if (!recoverMisfiredJobsResult.hasMoreMisfiredTriggers()) {
                        timeToSleep = getMisfireThreshold() - (System.currentTimeMillis() - sTime);
                        if(numFails > 0) {
                            timeToSleep = Math.max(getDbRetryInterval(), timeToSleep);
                        }
                    }
                    Thread.sleep(timeToSleep);
                }//while !shutdown
            }
        }

        private RecoverMisfiredJobsResult manage() {
            try {
                RecoverMisfiredJobsResult res = doRecoverMisfires();
            } catch (Exception e) {
            }
            return RecoverMisfiredJobsResult.NO_OP;
        }
    }

    protected RecoverMisfiredJobsResult doRecoverMisfires() throws JobPersistenceException {
        boolean transOwner = false;
        Connection conn = getNonManagedTXConnection();
        try {
            RecoverMisfiredJobsResult result = RecoverMisfiredJobsResult.NO_OP;
           
            // Before we make the potentially expensive call to acquire the
            // trigger lock, peek ahead to see if it is likely we would find
            // misfired triggers requiring recovery.
            int misfireCount = (getDoubleCheckLockMisfireHandler()) ?
                getDelegate().countMisfiredTriggersInStates(conn, STATE_MISFIRED, STATE_WAITING, getMisfireTime()) :
                Integer.MAX_VALUE;
           
            if (misfireCount == 0) {
                getLog().debug("Found 0 triggers that missed their scheduled fire-time.");
            } else {
                transOwner = getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS);
               
                result = recoverMisfiredJobs(conn, false);
            }
           
            commitConnection(conn);
            return result;
        } catch (JobPersistenceException e) {
        }
    }

    protected RecoverMisfiredJobsResult recoverMisfiredJobs(Connection conn, boolean recovering)
        throws JobPersistenceException, SQLException {

        // If recovering, we want to handle all of the misfired
        // triggers right away.
        int maxMisfiresToHandleAtATime =
            (recovering) ? -1 : getMaxMisfiresToHandleAtATime();
       
        List misfiredTriggers = new ArrayList();
        long earliestNewTime = Long.MAX_VALUE;
        // We must still look for the MISFIRED state in case triggers were left
        // in this state when upgrading to this version that does not support it.
        boolean hasMoreMisfiredTriggers =
            getDelegate().selectMisfiredTriggersInStates(
                conn, STATE_MISFIRED, STATE_WAITING, getMisfireTime(),
                maxMisfiresToHandleAtATime, misfiredTriggers);

        for (Iterator misfiredTriggerIter = misfiredTriggers.iterator(); misfiredTriggerIter.hasNext();) {
            Key triggerKey = (Key) misfiredTriggerIter.next();
           
            Trigger trig = retrieveTrigger(conn, triggerKey.getName(), triggerKey.getGroup());

            if (trig == null) {
                continue;
            }

            doUpdateOfMisfiredTrigger(conn, null, trig, false, STATE_WAITING, recovering);

            if(trig.getNextFireTime() != null && trig.getNextFireTime().getTime() < earliestNewTime)
             earliestNewTime = trig.getNextFireTime().getTime();
        }

        return new RecoverMisfiredJobsResult(
                hasMoreMisfiredTriggers, misfiredTriggers.size(), earliestNewTime);
    }

    protected Trigger retrieveTrigger(Connection conn, String triggerName, String groupName)
        throws JobPersistenceException {
        try {
            Trigger trigger = getDelegate().selectTrigger(conn, triggerName, groupName);
            if (trigger == null) {
                return null;
            }
           
            // In case Trigger was BLOB, clear out any listeners that might
            // have been serialized.
            trigger.clearAllTriggerListeners();
           
            String[] listeners = getDelegate().selectTriggerListeners(conn, triggerName, groupName);
            for (int i = 0; i < listeners.length; ++i) {
                trigger.addTriggerListener(listeners[i]);
            }

            return trigger;
        } catch (Exception e) {
            throw new JobPersistenceException("Couldn't retrieve trigger: " + e.getMessage(), e);
        }
    }
}

package org.quartz.impl.jdbcjobstore;

public class StdJDBCDelegate implements DriverDelegate, StdJDBCConstants {

    public boolean selectMisfiredTriggersInStates(Connection conn, String state1, String state2,

    String SELECT_MISFIRED_TRIGGERS_IN_STATES = "SELECT "
        + COL_TRIGGER_NAME + ", " + COL_TRIGGER_GROUP + " FROM "
        + TABLE_PREFIX_SUBST + TABLE_TRIGGERS + " WHERE "
        + COL_NEXT_FIRE_TIME + " < ? "
        + "AND ((" + COL_TRIGGER_STATE + " = ?) OR (" + COL_TRIGGER_STATE + " = ?)) "
        + "ORDER BY " + COL_NEXT_FIRE_TIME + " ASC";        

    }

    public Trigger selectTrigger(Connection conn, String triggerName,
            String groupName) throws SQLException, ClassNotFoundException,
            IOException {

    String SELECT_TRIGGER = "SELECT *" + " FROM "
            + TABLE_PREFIX_SUBST + TABLE_TRIGGERS + " WHERE "
            + COL_TRIGGER_NAME + " = ? AND " + COL_TRIGGER_GROUP + " = ?";

    String SELECT_CRON_TRIGGER = "SELECT *" + " FROM "
            + TABLE_PREFIX_SUBST + TABLE_CRON_TRIGGERS + " WHERE "
            + COL_TRIGGER_NAME + " = ? AND " + COL_TRIGGER_GROUP + " = ?";

    }
}

Quartz Web Application

Programming/Java 2010.09.17 10:18 Posted by 파란크리스마스

출처 : http://journae.springnote.com/pages/6100033



WEB-INF\web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app id="starter" version="2.4" ...>

 <context-param>
  <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
  <param-value>ApplicationResources</param-value>
 </context-param>

 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:applicationContext.xml</param-value>
 </context-param>

 <context-param>
  <param-name>webAppRootKey</param-name>
  <param-value>quartz.root</param-value>
 </context-param>

 <context-param>
  <param-name>log4jConfigLocation</param-name>
  <param-value>classpath:log4j.xml</param-value>
 </context-param>

 <filter>
  <filter-name>action2-cleanup</filter-name>
  <filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class>
 </filter>

 <filter>
  <filter-name>sitemesh</filter-name>
  <filter-class>com.opensymphony.module.sitemesh.filter.PageFilter</filter-class>
 </filter>

 <filter>
  <filter-name>sitemesh-freemarker</filter-name>
  <filter-class>org.apache.struts2.sitemesh.FreeMarkerPageFilter</filter-class>
 </filter>

 <filter>
  <filter-name>action2</filter-name>
  <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
 </filter>

 <filter-mapping>
  <filter-name>action2-cleanup</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
 <filter-mapping>
  <filter-name>sitemesh-freemarker</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
 <filter-mapping>
  <filter-name>action2</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

 <!-- Listeners -->
 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

 <listener>
  <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
 </listener>

 <servlet>
  <servlet-name>freemarker</servlet-name>
  <servlet-class>com.opensymphony.module.sitemesh.freemarker.FreemarkerDecoratorServlet</servlet-class>
 </servlet>

 <servlet>
  <servlet-name>DefinitionInitializer</servlet-name>
  <servlet-class>org.quartz.ui.web.init.DefinitionInitializer</servlet-class>
  <init-param>
   <param-name>definition-file</param-name>
   <param-value>(PATH_TO_DEFINITIONS_FILE)</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <!-- Servlets -->
 <servlet>
  <servlet-name>jspSupportServlet</servlet-name>
  <servlet-class>org.apache.struts2.views.JspSupportServlet</servlet-class>
  <load-on-startup>5</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>freemarker</servlet-name>
  <url-pattern>*.ftl</url-pattern>
 </servlet-mapping>

 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>

 </web-app>

WEB-INF\classes\applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans ...>

 <bean id="authenticator" class="org.quartz.ui.web.security.SimpleAuthenticator">
  <property name="username">
   <value>quartz</value>
  </property>
  <property name="password">
   <value>quartz</value>
  </property>
 </bean>

 <bean id="logonAction" class="org.quartz.ui.web.action.LogonAction" scope="prototype">
  <property name="authenticator" ref="authenticator" />
 </bean>

 <bean id="quartzUser" class="org.quartz.ui.web.security.User">
  <property name="username"><value>quartz</value></property>
  <property name="password"><value>quartz</value></property>
  <property name="roles">
  <map>
   <entry key="manager">
    <value>manager</value>
   </entry>
  </map>
  </property>
 </bean>

 <bean id="users" class="org.quartz.ui.web.security.Users">
  <property name="userMap">
  <map>
   <entry key="quartz">
    <ref bean="quartzUser"/>
   </entry>
  </map>
  </property>
 </bean>

</beans>

WEB-INF\classes\quartz.properties

#============================================================================
# Configure Main Scheduler Properties 
#============================================================================

 
org.quartz.scheduler.instanceName = TestScheduler
org.quartz.scheduler.instanceId = AUTO
 
#============================================================================
# Configure ThreadPool 
#============================================================================

 
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 5
org.quartz.threadPool.threadPriority = 4
 
#============================================================================
# Configure JobStore 
#============================================================================

 
org.quartz.jobStore.misfireThreshold = 60000
#org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
##org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.oracle.OracleDelegate
#org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.PostgreSQLDelegate

org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
org.quartz.jobStore.useProperties = true
org.quartz.jobStore.dataSource=myDS
org.quartz.jobStore.tablePrefix = QRTZ_

org.quartz.jobStore.isClustered= true
org.quartz.jobStore.clusterCheckinInterval= 20000
 
#============================================================================
# Configure Datasources 
#============================================================================


org.quartz.dataSource.myDS.driver=com.mysql.jdbc.Driver
org.quartz.dataSource.myDS.URL=jdbc:mysql://localhost:5141/batch
org.quartz.dataSource.myDS.user=root
org.quartz.dataSource.myDS.password=

#org.quartz.dataSource.myDS.driver = oracle.jdbc.driver.OracleDriver
#org.quartz.dataSource.myDS.URL = jdbc:oracle:thin:@polarbear:1521:dev
#org.quartz.dataSource.myDS.user = quartz
#org.quartz.dataSource.myDS.password = quartz
#org.quartz.dataSource.myDS.maxConnections = 5

 
#org.quartz.dataSource.myDS.driver = org.postgresql.Driver
#org.quartz.dataSource.myDS.URL = jdbc:postgresql:dev
#org.quartz.dataSource.myDS.user = jhouse
#org.quartz.dataSource.myDS.password =
#org.quartz.dataSource.myDS.maxConnections = 5

 
#============================================================================
# Configure Plugins
#============================================================================

 
#*  org.quartz.plugin.triggHistory.class = org.quartz.plugins.history.LoggingJobHistoryPlugin

#*  org.quartz.plugin.jobInitializer.class = org.quartz.plugins.xml.JobInitializationPlugin
#*  # init plugin will load jobs.xml as a classpath resource i.e. /jobs.xml if not found on file system
#*  org.quartz.plugin.jobInitializer.fileNames=jobs.xml
#*  org.quartz.plugin.jobInitializer.overWriteExistingJobs = false
#*  org.quartz.plugin.jobInitializer.failOnFileNotFound = false
#*  org.quartz.plugin.jobInitializer.scanInterval = 30
#*  # org.quartz.plugin.jobInitializer.wrapInUserTransaction = true

#*  org.quartz.plugin.jobInitializerMultiple.class = org.quartz.plugins.xml.JobInitializationPlugin
#*  # init plugin will load jobs.xml as a classpath resource i.e. /jobs.xml and jobs2.xml if not found on file system
#*  org.quartz.plugin.jobInitializerMultiple.fileNames=jobs2.xml,jobs3.xml
#*  org.quartz.plugin.jobInitializerMultiple.overWriteExistingJobs = false
#*  org.quartz.plugin.jobInitializerMultiple.failOnFileNotFound = false
#*  # org.quartz.plugin.jobInitializerMultiple.wrapInUserTransaction = true

quartz.properties 환경 파일 로딩 순서

org.quartz.ui.web.init.DefinitionInitializer.init
  |
  org.quartz.ee.servlet.QuartzInitializerServlet.init
    |
    org.quartz.impl.StdSchedulerFactory.getScheduler
      |
      org.quartz.impl.StdSchedulerFactory
        initialize() 메소드에서 quartz.properties 파일 로딩

DB의 설정된 Job을 조회 하여 등록하는 순서

org.quartz.simpl.SimpleThreadPool$WorkerThread.run
  |
  org.quartz.core.JobRunShell.run
    |
    org.quartz.jobs.FileScanJob.execute
      |
      org.quartz.impl.jdbcjobstore.JobStoreSupport.retrieveTrigger
        |
        org.quartz.impl.jdbcjobstore.StdJDBCDelegate.selectTrigger

StdJDBCDelegate의 selectTrigger 메소드

package org.quartz.impl.jdbcjobstore;

public class StdJDBCDelegate implements DriverDelegate, StdJDBCConstants {

    public Trigger selectTrigger(Connection conn, String triggerName,
            String groupName) throws SQLException, ClassNotFoundException,
            IOException {

        try {
            Trigger trigger = null;

            ps = conn.prepareStatement(rtp(SELECT_TRIGGER));
            rs = ps.executeQuery();

                if (triggerType.equals(TTYPE_SIMPLE)) {
                    ps = conn.prepareStatement(rtp(SELECT_SIMPLE_TRIGGER));

                    if (rs.next()) {
                        SimpleTrigger st = new SimpleTrigger(triggerName,
                                groupName, jobName, jobGroup, startTimeD,
                                endTimeD, repeatCount, repeatInterval);

                        if (null != map) {
                            st.setJobDataMap(new JobDataMap(map));
                        }
                        trigger = st;
                    }
                } else if (triggerType.equals(TTYPE_CRON)) {
                    ps = conn.prepareStatement(rtp(SELECT_CRON_TRIGGER));

                    CronTrigger ct = new CronTrigger(triggerName, groupName,
                                    jobName, jobGroup, startTimeD, endTimeD,
                                    cronExpr, timeZone);
                    if (null != map) {
                        ct.setJobDataMap(new JobDataMap(map));
                    }
                    trigger = ct;

                } else if (triggerType.equals(TTYPE_BLOB)) {
                    ....
                } else {
                    throw new ClassNotFoundException("class for trigger type '"
                            + triggerType + "' not found.");
                }
            }

            return trigger;
        } finally {
            closeResultSet(rs);
            closeStatement(ps);
        }
    }

Cluster 관련 내용

org.quartz.impl.jdbcjobstore.JobStoreSupport

public abstract class JobStoreSupport implements JobStore, Constants {

    protected boolean doCheckin() throws JobPersistenceException {
        failedRecords = clusterCheckIn(conn);
    }

    class ClusterManager extends Thread {
        private boolean manage() {
            res = doCheckin();
            return res;
        }

        public void run() {
            while (!shutdown) {

                if (!shutdown) {
                    long timeToSleep = getClusterCheckinInterval();
                    timeToSleep = Math.max(getDbRetryInterval(), timeToSleep);
                    Thread.sleep(timeToSleep);
                    this.manage()) {
                }

            }//while !shutdown
        }
    }
}

- end -

Spring Quartz Batch

Programming/Java 2010.09.14 16:31 Posted by 파란크리스마스

출처 : http://wiki.dev.daewoobrenic.co.kr/mediawiki/index.php/Spring_Quartz_Batch

WEB-INF\web.xml

 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>
   classpath:/job-bean.xml
  </param-value>
 </context-param>

 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

WEB-INF\classes\job-bean.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans ...>

 <import resource="classpath:simple-job-launcher-context.xml"/>
 <import resource="classpath:myHelloJob.xml"/>
 
 <bean id="helloJob" class="org.springframework.scheduling.quartz.JobDetailBean">
  <property name="jobClass" value="quartz.example.HelloJob" />
  <property name="jobDataAsMap">
   <map>
    <entry key="launcher" value-ref="jobLauncher"/>
    <entry key="job" value-ref="myHelloJob"/>
   </map>
  </property>
 </bean>

 <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
  <property name="jobDetail" ref="helloJob" />
  <property name="startDelay" value="10000" />
  <property name="repeatInterval" value="50000" />
 </bean>
 
 <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
  <property name="triggers">
   <list>
    <ref bean="simpleTrigger"/>
   </list>
  </property>
 </bean>
</beans>

WEB-INF\classes\simple-job-launcher-context.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans ...>

 <import resource="classpath:data-source-context.xml"/>

 <bean id="jobRepository" class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
  <property name="databaseType" value="MYSQL" />
  <property name="dataSource" ref="dataSource" />
  <property name="transactionManager" ref="transctionManager" />
 </bean>

 <bean id="jobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
  <property name="jobRepository" ref="jobRepository" />
 </bean>

 <bean id="simpleJob" class="org.springframework.batch.core.job.SimpleJob" abstract="true">
  <property name="jobRepository" ref="jobRepository" />
 </bean>

 <bean id="taskletStep" class="org.springframework.batch.core.step.tasklet.TaskletStep" abstract="true">
  <property name="jobRepository" ref="jobRepository" />
  <property name="transactionManager" ref="transctionManager" />
 </bean>

</beans>

WEB-INF\classes\data-source-context.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans ...>

 <import resource="classpath:data-source-context-init.xml"/>

 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="org.gjt.mm.mysql.Driver"></property>
  <property name="url" value="jdbc:mysql://127.0.0.1:5141/batch"></property>
  <property name="username" value="sa"></property>
  <property name="password" value="sqldba"></property>
 </bean>

 <bean id="transctionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
  lazy-init="true">
  <property name="dataSource" ref="dataSource"></property>
 </bean>

</beans>

WEB-INF\classes\data-source-context-init.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans ...>

 <bean id="initializingFactoryBean" class="quartz.example.InitializingDataSourceFactoryBean">
  <property name="dataSource" ref="dataSource"></property>
  <property name="initScript">
   <value>classpath:schema-mysql.sql</value>
  </property>
 </bean>
 
</beans>

WEB-INF\classes\myHelloJob.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans ...>

 <bean id="myHelloJob" parent="simpleJob">
  <property name="name" value="myHelloJob" />
  <property name="steps">
   <list>
    <bean id="firstHello" parent="taskletStep">
     <property name="tasklet">
      <bean class="quartz.example.MyHello">
       <property name="message" value="Hi~" />
      </bean>
     </property>
    </bean>
   </list>
  </property>
 </bean>
 
</beans>

package quartz.example;

public class InitializingDataSourceFactoryBean extends AbstractFactoryBean {

 private Resource initScript;
 private Resource destroyScript;
 DataSource dataSource;

 protected Object createInstance() throws Exception {
  
  Assert.notNull(dataSource);
  try {
   doExecuteScript(destroyScript);
  }
  catch (Exception e) {
   logger.debug("Could not execute destroy script [" + destroyScript + "]", e);
  }
  doExecuteScript(initScript);
  return dataSource;
 }

 private void doExecuteScript(final Resource scriptResource) {
  
  try {
  
   if (scriptResource == null || !scriptResource.exists())
    return;
   TransactionTemplate transactionTemplate = new TransactionTemplate(new DataSourceTransactionManager(dataSource));
   if (initScript != null) {
    transactionTemplate.execute(new TransactionCallback() {

     public Object doInTransaction(TransactionStatus status) {
      JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
      String[] scripts;
      try {
       scripts = StringUtils.delimitedListToStringArray(stripComments(IOUtils.readLines(scriptResource
         .getInputStream())), ";");
      }
      catch (IOException e) {
       throw new BeanInitializationException("Cannot load script from [" + initScript + "]", e);
      }
      for (int i = 0; i < scripts.length; i++) {
       String script = scripts[i].trim();
       if (StringUtils.hasText(script)) {
        jdbcTemplate.execute(scripts[i]);
       }
      }
      return null;
     }

    });

   }
  } catch (Exception e) {
   logger.debug("기존에 스키마가 생성된 경우 오류가 발생 할 수 있으며, 오류 발생시 무시", e);
  }
 }

 private String stripComments(List list) {
  StringBuffer buffer = new StringBuffer();
  for (Iterator iter = list.iterator(); iter.hasNext();) {
   String line = (String) iter.next();
   if (!line.startsWith("//") && !line.startsWith("--")) {
    buffer.append(line + "\n");
   }
  }
  return buffer.toString();
 }

package quartz.example;

import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.InitializingBean;

public class MyHello implements InitializingBean, Tasklet {
 
 private static Log _log = LogFactory.getLog(MyHello.class);
 
 private String message = "";
 
 public void setMessage(String message) {
  this.message = message;
 }

 @Override
 public void afterPropertiesSet() throws Exception {
  _log.info("========= " + this.getClass().getSimpleName() + "=============" + message);
 }

 @Override
 public RepeatStatus execute(StepContribution arg0, ChunkContext arg1) throws Exception {
  _log.info(">>>>>>>>>>> " + this.getClass().getSimpleName() + "=====" + message );
  
  return RepeatStatus.FINISHED;
 }

}

package quartz.example;

import java.util.Date;
import java.util.Iterator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.JobExecutionContext;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.scheduling.quartz.QuartzJobBean;

//public class HelloJob implements Job {
public class HelloJob extends QuartzJobBean {

  private static Log _log = LogFactory.getLog(HelloJob.class);
    
  private JobLauncher launcher;
  private Job job;
    
  private int count = 0;
    
  public void setLauncher(JobLauncher launcher) {
    this.launcher = launcher;
  }

  public void setJob(Job job) {
    this.job = job;
  }

  public HelloJob() {
  }
    
  protected void executeInternal(JobExecutionContext context) {
    _log.info("<<<<<<<< " +  " Hello World! - " + new Date() + " >>>>>>>>");
     
    System.out.println("aaaa");
     
    JobParametersBuilder jobParameterBulider = new JobParametersBuilder();
    jobParameterBulider.addDate("date", new Date());
     
    try {
      JobExecution jobExecution = launcher.run(job, jobParameterBulider.toJobParameters());
   
      for(Iterator<StepExecution> iterator = 
        jobExecution.getStepExecutions().iterator(); iterator.hasNext();) {
          StepExecution stepExecution = iterator.next();
        }
    } catch (JobExecutionAlreadyRunningException e) {
      e.printStackTrace();
    } catch (JobRestartException e) {
      e.printStackTrace();
    } catch (JobInstanceAlreadyCompleteException e) {
      e.printStackTrace();
    }
  }
}

Quartz - SimpleTrigger 사용하기

Programming/Java 2010.09.09 14:54 Posted by 파란크리스마스

출처
http://whiteship.tistory.com/1516
http://blog.naver.com/an5asis/60019595888

Job - 이 인터페이스를 상속 받아서 execute 메소드를 구현해야 됩니다. (실행 수행되는 내용)
JobDetail - 
Trigger - 작업을 언제 실행할 지 정의합니다.
  SimpleTrigger - start time, end time, interval time, repeat times 등을 설정할 수 있습니다.
  CronTrigger - Linux의 cron 하고 비슷하게, 특정 시간이 되면 발동하게 해줍니다.
 
SchedulerFactory
  StdSchedulerFactory - 클래스패스에 quartz.properties 파일을 먹고 삽니다. 
    Scheduler - 스케쥴 팩토리에서 얻어 옵니다. JobDetail과 Trigger를 가지고 스케쥴을 정할 수 있습니다.

package QuartzApp;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class HelloJob implements Job {

 @Override
 public void execute(JobExecutionContext arg0) throws JobExecutionException {
  System.out.println("HelloJob !!!");  
 }
}

package QuartzApp;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;

public class HelloJobTest1Main {

 public static void main(String[] args) {
   try {
     SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory();
     Scheduler sched = schedFact.getScheduler();
     sched.start();

     JobDetail jobDetail = new JobDetail("HelloJob", HelloJob.class);
     SimpleTrigger trigger = new SimpleTrigger("HelloJob");
     trigger.setRepeatInterval(1l);
     trigger.setRepeatCount(100);  // 100번 반복
     sched.scheduleJob(jobDetail, trigger);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
}

Tomcat 7 - Spring MVC 설치

Programming/Java 2010.09.03 17:08 Posted by 파란크리스마스

출처 : http://pelican7.egloos.com/2584679

Tomcat 7
Spring Framework 3.0.3.RELEASE
Eclipse 3.6

간단하게 브라우저에서 hello.htm을 호출하면 내부에서 hello.jsp를 호출하는 예제입니다.

1. Project 생성



2. jar 복사

경로 : SpringMVC\WebContent\WEB-INF\lib

commons-logging-1.1.1.jar
org.springframework.asm-3.0.4.RELEASE.jar
org.springframework.beans-3.0.4.RELEASE.jar
org.springframework.context-3.0.4.RELEASE.jar
org.springframework.core-3.0.4.RELEASE.jar
org.springframework.expression-3.0.4.RELEASE.jar
org.springframework.web-3.0.4.RELEASE.jar
org.springframework.web.servlet-3.0.4.RELEASE.jar

3. web.xml 파일 작성

경로 : SpringMVC\WebContent\WEB-INF

---------------------------------------
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0">

  <servlet>
    <servlet-name>springapp</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springapp</servlet-name>
    <url-pattern>*.htm</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>
      index.jsp
    </welcome-file>
  </welcome-file-list>

</web-app>
---------------------------------------

4. springapp-servlet.xml 파일 작성

경로 : SpringMVC\WebContent\WEB-INF

---------------------------------------
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       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-2.5.xsd">

  <!-- the application context definition for the springapp DispatcherServlet -->

  <bean name="/hello.htm" class="springapp.web.HelloController"/>

</beans>
---------------------------------------

5. HelloController.java 작성 / 컴파일

---------------------------------------
package springapp.web;

import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;

public class HelloController implements Controller {

    protected final Log logger = LogFactory.getLog(getClass());

    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        logger.info("Returning hello view");

        return new ModelAndView("hello.jsp");
    }
}
---------------------------------------

6. hello.jsp 파일 작성

경로 : SpringMVC\WebContent

---------------------------------------
 <html>
  <head><title>Hello :: Spring Application</title></head>
  <body>
    <h1>Hello - Spring Application</h1>
    <p>Greetings.</p>
  </body>
</html>
---------------------------------------

7. Test

http://localhost:8080/SpringMVC/hello.htm


Maven / Jetty 설치

Programming/Java 2010.09.02 14:48 Posted by 파란크리스마스

출처 : http://zzyzzy.textcube.com/14

Maven 설치

1. 다운로드

경로 : http://maven.apache.org/

apache-maven-2.2.1-bin.zip 파일 다운로드

2. OS 환경변수 추가

M2_HOME=C:\source.java\apache-maven-2.2.1
PATH에 추가  ;%M2_HOME%\bin

3. Maven 환경 파일 수정 (settings.xml)

경로 : C:\source.java\apache-maven-2.2.1\conf

- localRepository 내용추가

<localRepository>C:/source.java/apache-maven-2.2.1/repo</localRepository> 

4. 설치 확인

C:\Users\bluesanta>mvn -vsersion
Apache Maven 2.2.1 (r801777; 2009-08-07 04:16:01+0900)
Java version: 1.6.0_13
Java home: C:\source.java\jdk1.6.0_13\jre
Default locale: ko_KR, platform encoding: MS949
OS name: "windows vista" version: "6.1" arch: "x86" Family: "windows"
C:\Users\bluesanta> 

5. Maven 초기화

C:\Users\bluesanta>mvn install

Jetty 설치

1. 다운로드

경로 : http://dist.codehaus.org/jetty/

jetty-6.1.25.zip

2.  실행배치 파일 만들기 ( start.bat )

경로 : C:\source.java\jetty-6.1.25

start.bat 내용
----------------------------------
@echo off
%JAVA_HOME%\bin\java -jar start.jar etc/jetty.xml
----------------------------------

3. 설치 확인

브라우저에서 http://localhost:8080/ 주소 입력

m2eclipse 설치

1. 이클립스 실행 -> [Help] > [Install New Software...] -> [Add]

- ajdt 설치

http://download.eclipse.org/tools/ajdt/35/dev/update





- m2eclipse 설치




TAG maven

Lucene - indexer

Programming/Java 2009.05.08 01:00 Posted by 파란크리스마스
출처 : http://www.lucene.kr/26
http://freesearch.pe.kr/452

TAG lucene

Tomcat 5.5 Connection Pool 설정

Programming/Java 2009.01.12 01:37 Posted by 파란크리스마스

출처 : http://blog.bagesoft.com/725
http://fallacy.tistory.com/76
http://kwon37xi.egloos.com/2852803?89a004e0

1) C:\apache-tomcat-5.5.27\conf\server.xml 내용추가

   <Resource name="jdbc/myoracle" auth="Container"
              type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver"
              url="jdbc:oracle:thin:127.0.0.1:1521:orcl"
              username="scott" password="tiger" maxActive="20" maxIdle="10"
              maxWait="-1"/>   

2) C:\apache-tomcat-5.5.27\conf\context.xml 내용추가

  <ResourceLink global="jdbc/myoracle" name="jdbc/myoracle" type="javax.sql.DataSource"/> 

3) C:\oracle\product\10.2.0\db_1\jdbc\lib 폴더의 ojdbc14.jar 파일을 C:\apache-tomcat-5.5.27\common\lib 폴더에 복사

4) C:\apache-tomcat-5.5.27\webapps\ROOT\WEB-INF\web.xml 내용 추가

    <resource-ref>
      <description>Oracle Datasource example</description>
      <res-ref-name>jdbc/myoracle</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
    </resource-ref>

5) Tomcat 재실행

6) 테스트 JSP 파일 작성

<%@ page import="java.sql.*, javax.naming.*, javax.sql.*"%>
<%

Context initCtx = new InitialContext();

/*
  Context envContext  = (Context)initContext.lookup("java:/comp/env");
  DataSource ds = (DataSource)envContext.lookup("jdbc/myoracle");
*/

DataSource ds =  (DataSource)initCtx.lookup("java:comp/env/jdbc/myoracle");
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

try {
 conn = ds.getConnection();
 stmt = conn.createStatement();
  String query = "select to_char(sysdate,'yyyy/mm/dd hh24:mi:ss') from dual"; // 현재 시간을 구하는 query
  rs = stmt.executeQuery(query);

  if(rs.next()) {
    out.println("<br>" + rs.getString(1));
  }
} catch (Exception e) {
  out.println("<br>" + e.toString());
} finally {
  if (rs!=null) try { rs.close(); } catch (Exception e) { }
  if (stmt!=null) try { stmt.close(); } catch (Exception e) { }
  if (conn!=null) try { conn.close(); } catch (Exception e) { }
}

%>




 

티스토리 툴바