JNDI for Oracle JDBC Connection Pooling

How to Setup Global JNDI Mapping
for Oracle JDBC Connection Pooling
with Tomcat

by Gregg Lagnese, MicroDeveloper, Inc.
May 16, 2005 v1.3

Steps to Implement:

1) Modify the server.xml file 

In <CATALINA_HOME>/conf/server.xml between <GlobalNamingResources> and </GlobalNamingResources> add the following 

<Resource name="jdbc/<alias>"
   auth="Container"
   type="oracle.jdbc.pool.OracleDataSource"
   driverClassName="oracle.jdbc.driver.OracleDriver"
   factory="oracle.jdbc.pool.OracleDataSourceFactory"
   url="jdbc:oracle:thin:@<host>:<port>:<sid>"
   [user=<user>]
   [password=<password>]
   maxActive="20"
   maxIdle="10"
   maxWait="-1" />
    
Example

<!-- Global JNDI resources -->
 <GlobalNamingResources> <!-- Test entry for demonstration purposes -->
 <Environment name="simpleVal     ue" type="java.lang.Integer" value="30"/> <!-- Editable user database that can also be used by
   UserDatabaseRealm to authenticate users -->
 <Resource name="UserDatabase" auth="Container"
   type="org.apache.catalina.UserDatabase"
   description="User database that can be updated and saved"
   factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
   pathname="conf/tomcat-users.xml" />
  
 <!-- Every connection to 'db1' uses the same user -->
 <Resource name="jdbc/db1"
   auth="Container"
   type="oracle.jdbc.pool.OracleDataSource"
   driverClassName="oracle.jdbc.driver.OracleDriver"
   factory="oracle.jdbc.pool.OracleDataSourceFactory"
   url="jdbc:oracle:thin:@oracle.microdeveloper.com:1521:db1"
   user="scott"
   password="tiger"
   maxActive="20"
   maxIdle="10"
   maxWait="-1" />
  
 <!-- Every connection to 'db2' must provide a username and password -->
 <Resource name="jdbc/db2"
   auth="Container"
   type="oracle.jdbc.pool.OracleDataSource"
   driverClassName="oracle.jdbc.driver.OracleDriver"
   factory="oracle.jdbc.pool.OracleDataSourceFactory"
   url="jdbc:oracle:thin:@oracle.microdeveloper.com:1521:db2"
   maxActive="20"
   maxIdle="10"
   maxWait="-1" />
  
 </GlobalNamingResources>
 
2) Modify the context.xml file 

In <CATALINA_HOME>/conf/context.xml between <Context> and </Context> add the following for each entry in the JNDI resource list:
<ResourceLink global="jdbc/<alias>" name="jdbc/<alias>" type="oracle.jdbc.pool.OracleDataSource"/>
Example
<!-- The contents of this file will be loaded for each web application -->
 <Context> <!-- Default set of monitored resources -->
 <WatchedResource>WEB-INF/web.xml</WatchedResource>
 <WatchedResource>META-INF/context.xml</WatchedResource>
  
 <!-- Uncomment this to disable session persistence across Tomcat restarts -->
 <!--
 <Manager pathname="" />
   -->
 <ResourceLink global="jdbc/db1" name="jdbc/db1" type="oracle.jdbc.pool.OracleDataSource"/>
 <ResourceLink global="jdbc/db2" name="jdbc/db2" type="oracle.jdbc.pool.OracleDataSource"/>
 </Context>
 
3) Modify the context's web.xml file (5.0.x step only - not necessary for 5.5.x) 
In the <CONTEXT>/WEB-INF/web.xml between <web-app> and </web-app> add the following:
<resource-ref>
   <description><Your Description></description>
   <res-ref-name>jdbc/<alias></res-ref-name>
   <res-type>oracle.jdbc.pool.OracleDataSource</res-type>
   <res-auth>Container</res-auth>
</resource-ref>

Example

<resource-ref>
   <description>Oracle Development Datasource</description>
   <res-ref-name>jdbc/db1</res-ref-name>
   <res-type>oracle.jdbc.pool.OracleDataSource</res-type>
   <res-auth>Container</res-auth>
</resource-ref>

<resource-ref>
   <description>Oracle Development Datasource</description>
   <res-ref-name>jdbc/db2</res-ref-name>
   <res-type>oracle.jdbc.pool.OracleDataSource</res-type>
   <res-auth>Container</res-auth>
</resource-ref>
 
4) Restart Tomcat 
 
 
Testing the Changes 
 
5) Create a connection class (in the example it will be called ConnectionPool.java) 
 
package com.microdeveloper.db.jndi;import oracle.jdbc.pool.OracleDataSource;

import javax.naming.Context;
import javax.naming.InitialContext;
import java.io.Serializable;
import java.sql.Connection;import java.sql.SQLException;import java.sql.ResultSet;import java.sql.Statement;
import java.util.Properties;public class ConnectionPool implements Serializable {
   String message = "Not Connected";public void init() {
   Connection conn = null;
   ResultSet rst = null;
   Statement stmt = null;
   try {
      Context initContext = new InitialContext();
      Context envContext = (Context) initContext.lookup("java:/comp/env");
      OracleDataSource ds = (OracleDataSource) envContext.lookup("jdbc/db1");
            if (envContext == null) throw new Exception("Error: No Context");
     if (ds == null) throw new Exception("Error: No DataSource");
     if (ds != null) conn = ds.getConnection();     if (conn != null) {
        message = "Got Connection " + conn.toString() + ", ";
        stmt = conn.createStatement();
        rst = stmt.executeQuery("SELECT 'Success obtaining connection' FROM DUAL");
     }
     if (rst.next()) message = rst.getString(1);

   rst.close();
   rst = null;
   stmt.close();
   stmt = null;
   conn.close(); // Return to connection pool
   conn = null; // Make sure we don't close it twice } catch (Exception e) {
   e.printStackTrace();
 } finally {
   // Always make sure result sets and statements are closed,
   // and the connection is returned to the pool
   if (rst != null) {
      try {
         rst.close();
      } catch (SQLException e) {;}
      rst = null;
   }

   if (stmt != null) {
      try {
         stmt.close();
      } catch (SQLException e) {;}
      stmt = null;
   }

   if (conn != null) {
      try {
         conn.close();
      } catch (SQLException e) {;}
      conn = null;
   }
 }
}public String getMessage() {return message;}} 
 
6) Create a JSP page to test with: 
 
<%@page contentType="text/html"%>
 <%@page pageEncoding="UTF-8"%>
<html>
   <head><title>JSP Page</title></head>
<body>
<% com.microdeveloper.db.jndi.ConnectionPool ocp = new com.microdeveloper.db.jndi.ConnectionPool();
   ocp.init(); %><h2>Results</h2>
    Message: <%= ocp.getMessage() %>
</body>
</html>
 
7) Compile the class and deploy the context
Either manually or through your IDE, compile the class, then deploy the context to Tomcat. Now run the JSP page created in step 6. You should see the following:

Results

Message: Success obtaining connection


Troubleshooting
 
8) Check the database first

Verify database connectivity
a) TNSPing the database
b) Connect using the username and password in step 1
c) Verify the server, sid, and port
 
9) Error messages 

Driver errors usually look like (Cannot create JDBC driver of class '' for connect URL 'null'):

Place the ojdbc14.jar file in the <CATALINA_HOME>\common\lib directory
Do NOT place the JAR in your <CONTEXT>/WEB-INF/lib directory (this can cause problems)
If used with an IDE that auto-deploys, exclude the JAR from the deployment

Javax Driver errors looking like "java.sql.SQLException: No suitable driver"

Usually means the JNDI lookup could not use the default javax implementation or Oracle driver (or both). Most people will tell you to use this construct:

<Resource name="jdbc/<alias>"
          auth="Container"
          type="javax.sql.DataSource"
          driverClassName="oracle.jdbc.driver.OracleDriver"
          ...But I never found that to work reliably. This works every time (see step 1); note the inclusion of the factory:

<Resource name="jdbc/<alias>"
          auth="Container"
          type="oracle.jdbc.pool.OracleDataSource"
          driverClassName="oracle.jdbc.driver.OracleDriver"          factory="oracle.jdbc.pool.OracleDataSourceFactory"         
...

Ensure that the resource link (step 2) is in either:

the <CONTEXT>/META-INF/context.xml file (for context configurations)

- or -

the <CATALINA_HOME>/conf/context.xml (for global configurations)

Error messages that 'jdbc' is an unknown context:

Verify that step (3 for 5.0) is complete and accurate.
Verify that you have all the correct JARs in place. Specifically these:

naming-factory.jar
naming-factory-dbcp.jar
naming-resources.jar    

   IO Error Messages 'Io exception: The Network Adapter could not establish the connection'

This almost always means that the URL is improperly formed. For the Oracle thin driver it's jdbc:oracle:thin:@<host>:<port>:<sid>
Pay extra attention to the colon ':' after 'thin' and the '@' symbol. These tend to be left out often (for me anyway).
 

Making a User Dependent Connection

11) Add code to the class to set the username and password 

In the class, before the connection is formed, add a call to the datasource to set the username and password. This can be done in one of two ways as shown below:
 
try {   
  Context initContext = new InitialContext();   
  Context envContext = (Context) initContext.lookup("java:/comp/env");         
  OracleDataSource ds = (OracleDataSource) envContext.lookup("jdbc/db2");  
  if (envContext == null) throw new Exception("Error: No Context");
    if (ds == null) throw new Exception("Error: No DataSource");
    if (ds != null){
       ds.setUser("scott");
       ds.setPassword("tiger");
       conn = ds.getConnection();
    } catch (Exception e) {
   e.printStackTrace();
}
- or - 

try {   
   Context initContext = new InitialContext();   
   Context envContext = (Context) initContext.lookup("java:/comp/env");   
   OracleDataSource ds = (OracleDataSource) envContext.lookup("jdbc/db2");   
  
    if  (envContext == null) throw new Exception("Error: No Context");
    if (ds == null) throw new Exception("Error: No DataSource");
    if (ds != null){
       conn = ds.getConnection("scott","tiger");
    } catch (Exception e) {
   e.printStackTrace();


Making a User Dependent Connection
11) Add code to the class to set the username and password 
In the class, before the connection is formed, add a call to the datasource to set the username and password. This can be done in one of two ways as shown below:
 
try {   
  Context initContext = new InitialContext();   
  Context envContext = (Context) initContext.lookup("java:/comp/env");     
  OracleDataSource ds = (OracleDataSource) envContext.lookup("jdbc/db2");   

    if (envContext == null) throw new Exception("Error: No Context");
    if (ds == null) throw new Exception("Error: No DataSource");
    if (ds != null){
       ds.setUser("scott");
       ds.setPassword("tiger");
       conn = ds.getConnection();
    } catch (Exception e) {
   e.printStackTrace();
}
- or - 

try {   
   Context initContext = new InitialContext();   
   Context envContext = (Context) initContext.lookup("java:/comp/env");    
   OracleDataSource ds = (OracleDataSource) envContext.lookup("jdbc/db2");   
   
   if (envContext == null) throw new Exception("Error: No Context");
    if (ds == null) throw new Exception("Error: No DataSource");
    if (ds != null){
       conn = ds.getConnection("scott","tiger");
    } catch (Exception e) {
   e.printStackTrace();
}

by 슬럼퍼 | 2009/01/29 23:35 | 웹개발 | 트랙백 | 덧글(0)

Trac Installation Guide for 0.11

Trac Installation Guide for 0.11

NOTE: For installing previous Trac versions, please refer to 0.10/TracInstall.

WARNING: Trac is not currently compatible with Python 2.6 or 3.0.

Trac is written in the Python programming language and needs a database, SQLite, PostgreSQL, or MySQL. For HTML rendering, Trac uses the Genshi templating system.

What follows are generic instructions for installing and setting up Trac and its requirements. While you can find instructions for installing Trac on specific systems at TracInstallPlatforms on the main Trac site, please be sure to first read through these general instructions to get a good understanding of the tasks involved.

Short - Install a released version

For the quick install, make sure you have Python-2.5, easy_install and SQlite-3.3.4 installed (or above). (You also might want to install python-dev to build genshi)

sudo easy_install Trac

Requirements

The hardware requirements for running Trac obviously depend on the expected data volume (number of wiki pages, tickets, revisions) and traffic. Very small projects will run fine with a 500MHz processor and 128MB RAM using SQLite. In general, the more RAM, the better. A fast hard disk also helps.

To install Trac, the following software packages must be installed:

  • Python, version >= 2.3
    • if using mod_python together with xml-related things, use python-2.5. expat is namespaced there and does not cause apache to crash any more(see here for details).
    • For RPM-based systems you might also need the python-devel and python-xml packages.
    • See instructions in TracOnWindows/Python2.5
  • setuptools, version >= 0.6
  • Genshi, version >= 0.5 (was version >= 0.4.1 on previous 0.11 release candidates)
  • You also need a database system and the corresponding python drivers for it. The database can be either SQLite, PostgreSQL or MySQL (experimental).
  • Optional if some plugins require it: ClearSilver

For SQLite

  • SQLite, version 3.3.4 and above preferred (note: it is preinstalled in Python 2.5.2).
  • If not using Python-2.5: PySQLite, version 1.x (for SQLite 2.x) or version 2.x (for SQLite 3.x), version 2.3.2 preferred. For details see PySqlite

Note: It appears that PySQLite 2.x is required for Trac 0.9+/SQLite 3.x if you plan to use the 'trac-post-commit-hook.py' script available from the 'contrib' section of the source repository.

Note: Users of Mac OS X please take care; the Apple-supplied SQLite contains additional code to support file locking on network filesystems like AFP or SMB. This is not presently (3.3.6) in the mainline sources, so if you build your own SQLite from source it will not function correctly on such filesystems - typically it gives the error "database is locked". A patch is available for version 3.3.6, based on Apple's code, otherwise you're probably best off using the Apple supplied version (presently 3.1.3).

For PostgreSQL

Warning: PostgreSQL 8.3 uses a strict type checking mechanism. To use Trac with the 8.3 Version of PostgreSQL, you will need trac-0.11 or later.

For MySQL

Warning: MySQL support is currently still experimental. That means it works for some people, but several issues remain, in particular regarding the use of unicode and the key length in the repository cache. See MySqlDb for more detailed information.

  • MySQL, version 4.1 or later
  • MySQLdb, version 1.2.1 or later

Optional Requirements

Version Control System

Please note: if using Subversion, Trac must be installed on the same machine. Remote repositories are currently not supported.

  • Subversion, version >= 1.0. (versions recommended: 1.2.4, 1.3.2 or 1.4.2) and the corresponding Python bindings. For troubleshooting, check TracSubversion
    • Trac uses the SWIG bindings included in the Subversion distribution, not PySVN (which is sometimes confused with the standard SWIG bindings).
    • If Subversion was already installed without the SWIG bindings, on Unix you'll need to re-configure Subversion and make swig-py, make install-swig-py.
    • There are pre-compiled bindings available for win32.
  • Support for other version control systems is provided via third-parties. See PluginList and VersioningSystemBackend.

Web Server

For those stuck with Apache 1.3, it is also possible to get Trac working with mod_python 2.7 (see TracModPython2.7). This guide hasn't been updated since 0.84, so it may or may not work.

Other Python Utilities

Attention: The various available versions of these dependencies are not necessarily interchangable, so please pay attention to the version numbers above. If you are having trouble getting Trac to work please double-check all the dependencies before asking for help on the MailingList or IrcChannel.

Please refer to the documentation of these packages to find out how they are best installed. In addition, most of the platform-specific instructions also describe the installation of the dependencies. Keep in mind however that the information there probably concern older versions of Trac than the one you're installing (there are even some pages that are still talking about Trac 0.8!).

Installing Trac

One way to install Trac is using setuptools. With setuptools you can install Trac from the subversion repository; for example, to install release version 0.11 do:

easy_install http://svn.edgewall.org/repos/trac/tags/trac-0.11

But of course the python-typical setup at the top of the source directory also works:

$ python ./setup.py install

Note: you'll need root permissions or equivalent for this step.

This will byte-compile the python source code and install it as an .egg file or folder in the site-packages directory of your Python installation. The .egg will also contain all other resources needed by standard Trac, such as htdocs and templates.

The script will also install the trac-admin command-line tool, used to create and maintain project environments, as well as the tracd standalone server.

Advanced Options

To install Trac to a custom location, or find out about other advanced installation options, run:

easy_install --help

Also see Installing Python Modules for detailed information.

Specifically, you might be interested in:

easy_install --prefix=/path/to/installdir

or, if installing Trac to a Mac OS X system:

easy_install --prefix=/usr/local --install-dir=/Library/Python/2.5/site-packages

The above will place your tracd and trac-admin commands into /usr/local/bin and will install the Trac libraries and dependencies into /Library/Python/2.5/site-packages, which is Apple's preferred location for third-party Python application installations.

Creating a Project Environment

A Trac environment is the backend storage where Trac stores information like wiki pages, tickets, reports, settings, etc. An environment is basically a directory that contains a human-readable configuration file and various other files and directories.

A new environment is created using trac-admin:

$ trac-admin /path/to/myproject initenv

trac-admin will prompt you for the information it needs to create the environment,
such as the name of the project, the type and the path to an existing source code repository,
the database connection string, and so on. If you're not sure what to specify for one of these options,
just leave it blank to use the default value. The database connection string in particular will always work
as long as you have SQLite installed. Leaving the path to the source code repository empty will disable
any functionality related to version control, but you can always add that back when the basic system is running.

Also note that the values you specify here can be changed later by directly editing the TracIni configuration file.

Note: The user account under which the web server runs will require write permissions to the environment directory
and
all the files inside. On Linux, with the web server running as user apache and group apache, enter:

chown -R apache.apache /path/to/myproject

Warning: If the trac.cgi files are not installed where you expect, then the current documentation is insufficient; it might be necessary to use the 'deploy' command in trac-admin. See tickets http://trac.edgewall.org/ticket/7312 and possibly http://trac.edgewall.org/ticket/6827

Running the Standalone Server

After having created a Trac environment, you can easily try the web interface by running the standalone server tracd:

$ tracd --port 8000 /path/to/myproject

Then, fire up a browser and visit http://localhost:8000/. You should get a simple listing of all environments that tracd knows about. Follow the link to the environment you just created, and you should see Trac in action. If you only plan on managing a single project with trac you can have the standalone server skip the environment list by starting it like this:

$ tracd -s --port 8000 /path/to/myproject

Running Trac on a Web Server

Trac provides three options for connecting to a "real" web server: CGI, FastCGI and mod_python. For decent performance, it is recommended that you use either FastCGI or mod_python.

If you're not afraid of running newer code, you can also try running Trac on mod_wsgi. This should deliver even better performance than mod_python, but the module isn't as extensively tested as mod_python.

Trac also supports AJP which may be your choice if you want to connect to IIS.

Setting up the Plugin Cache

Some Python plugins need to be extracted to a cache directory. By default the cache resides in the home directory of the
current user. When running Trac on a Web Server as a dedicated user (which is highly recommended) who has no
home directory, this might prevent the plugins from starting. To override the cache location you can set the PYTHON_EGG_CACHE environment variable. Refer to your server documentation for detailed instructions.

Configuring Authentication

The process of adding, removing, and configuring user accounts for authentication depends on the specific way you run Trac. The basic procedure is described in the Adding Authentication section on the TracCgi page. To learn how to setup authentication for the frontend you're using, please refer to one of the following pages:

Platform-specifics installations

Using Trac

Once you have your Trac site up and running, you should be able to browse your subversion repository, create tickets,
view the timeline, etc.

Keep in mind that anonymous (not logged in) users can by default access most but not all of the features. You will need to configure authentication and grant additional permissions to authenticated users to see the full set of features.

Enjoy!

The Trac Team


See also: TracInstallPlatforms, TracGuide, TracCgi, TracFastCgi, TracModPython, TracModWSGI, TracUpgrade, TracPermissions

by 슬럼퍼 | 2009/01/14 11:25 | 협업 | 트랙백 | 덧글(0)

Eclipse + MyLyn + Trac

Mylyn

  1. 협업 tool

설치 방법

  1. eclipse menu Help->Software Updates->Find and Install.
  2. Search for new features to install -> Next.
  3. New Remote Site 선택.
  4. Name에 "Mylyn" 입력 , URL에 아래 버젼에 맞도록 입력
  5. Select OK.
  6. Mylyn box 선택 후 Finish.

Mylyn extra를 update 하지 않을 경우 trac 연결이 되지 않음

  1. eclipse menu Help->Software Updates->Find and Install.
  2. Search for new features to install -> Next.
  3. Mylyn Extra 선택 후 Finish

eclipse3.4 의 경우

  1. eclipse menu Help->Software Updates->Add Site
  2. http://download.eclipse.org/tools/mylyn/update/extras
    • 바로 보이지 않을 경우 Manage에서 search해서 체크해 줄것

trac 연결

  1. eclipse menu Window -> Show View -> Other
  2. Mylyn Task Repositories 선택
  3. Task Repositores -> 마우스 우측 버튼 선택 -> Add Task Repository
  4. Trac 선택 -> Next
  5. Server: http://isdev.nhncorp.com/isac (연결한 trac wiki 지정)
  6. Label : ISAC (본인이 원한는 이름으로 지정)
  7. Anonymous Access uncheck
  8. UserID : 발급된 id 입력
  9. Password : 발급된 passwd 입력
  10. Save Password check
  11. Additionla Settings 선택
  12. Access Type : XML-RPC Plugin 선택
  13. Validate Settings 선택 후 연결이 잘되는지 확인
  14. Finish
  15. Add new query popup 창에이 뜨면 Yes 선택
  16. Query Title : 쿼리의 이름 지정(구분하기 쉽도록 지정)
  17. Component, Version, Milestone, Satus, Resolution Type, Priority 중 자기가 검색하고 싶은 조건 선택
  • Owner에 자기 id 입력 Status에 new, reopened를 선택
  1. Finish

trac 사용법

  1. Mylyn Task List 선택
  2. 발급된 ticket 선택
  3. ticket 옆의 context 버튼 선택 ( 조그만한 동그라미)
  4. 티켓과 관련된 소스만 open 후 작업
  • 작업 중간 중간에 Description 수시 udpate
  • Ticket의 하단에 Planning 탭 선택 후 작업 기간 선택
  1. 작업 완료시 Resove as '문제가 고쳐짐' 상태를 선택하고 Attach Context 선택 후 Submit

by 슬럼퍼 | 2009/01/14 10:57 | Ruby | 트랙백 | 덧글(0)

콘솔프로그램을 윈도우즈 서비스에 등록하기

  playarrow.exe (64.0K), Down : 6, 2007-07-29 04:27:21
   instsrv.exe (31.5K), Down : 11, 2007-07-29 04:27:21
   srvany.exe (8.0K), Down : 3, 2007-07-29 04:27:21
   playarrow_src.zip (22.9K), Down : 1, 2008-01-20 02:48:39
 
 
윈도우즈에서 일반 콘솔프로그램 중에 서비스로 등록되면 좋을 것 같은 프로그램들이 있습니다.
서비스는 로그인이 되지 않더라도 부팅만 되면 실행되므로 이런 프로그램을 서비스로 등록할 수 있으면 많은 장점을 얻을 수 있을 것입니다. 
일반적으로 오픈소스는 리눅스나 유닉스를 대상으로 개발된 것들이 많아 일반 유닉스 deamon프로그램이 윈도우즈에 포팅되면 콘솔 프로그램이 되어 있는 경우가 많은데 이런 콘솔 프로그램을 윈도우즈의 서비스에 등록하는 방법에 대해서 알아보도록 하겠습니다.
 
MS사에서는 이러한 일들을 처리하기 위해 instsvr.exe과 srvany.exe라는 툴을 제공하고 잇습니다.
이 툴은 Windows설치시 같이 설치되지는 않고 Windows Resource Kit을 별도로 설치하여 구할 수 있습니다.
 
Windows 2003 Resource Kit을 받을 수 있는 곳은 다음과 같습니다.
 
여기서 이야기하는 툴만이 필요하다면 본 강좌에 첨부된 파일을 다운 받아 사용하셔도 됩니다.
 
이 툴이 돌아가 수 있는 요구 조건으로는 Windows XP Professional 또는 Windows Server 2003 family 라고 되어 있는데 아마 윈도우즈 서비스가 제공되는 모든 윈도우즈(NT계열만)에서 사용할 수 있을 거라 생각됩니다.
 
현재 사용자는 서비스를 다루어야 하기 때문에 Administrators 그룹의 멤버 권한을 갖은 계정에서만 정상적으로 돌아 갑니다.
 
instsvr의 사용방법은 다음과 같습니다.
 
1) 서비스 등록시
 
instsrv <ServiceName> <PathToExecuteable> [-a AccountName] [-p AccountPassword]
 
<ServiceName>은 서비스로 등록할 때 사용할 이름을 지정합니다.
<PathToExecuteable>은 서비스로 등록할 프로그램의 전체경로입니다.
[-a AccountName] 서비스가 동작할 때 사용할 계정을 지정할 수 있습니다. 지정하지 않으면 "로컬 시스템"이라는 가상으로 계정으로 등록됩니다.
[-p AccountPassword] -a에 의해 지정된 계정의 암호를 지정할 수 있습니다.
 
2) 서비스 등록 해제시 
 
instsrv <ServiceName> Remove
 
<ServiceName>은 서비스로 등록할 때 사용할 이름을 지정합니다.
 
서비스의 이름만 지정하면 되기 때문에 설치 후 삭제를 했는데도 서비스만 남아서 오류가 발생하는(잘못 등록되어 있는 서비스)를 제거하는 도구로도 사용할 수 있습니다.
 
서비스가 될 수 있는 프로그램은 서비스 관리자와의 통신과 제어 신호를 처리해야 하는 프로그램이여야 하는데 우리는 지금 일반 콘솔 프로그램을 등록하려고 하고 있으니 이런 일을 대신하는 프로그램이 있어야 합니다.
 
이러한 역할을 하는 툴이 바로 srvany.exe라는 툴입니다.
이툴은 또한 콘솔 프로그램을 백그라운드로 돌리는 역할을 수행할 수도 있습니다.
 
예를 들어서 설명하도록 하겠습니다.
 
우선 실행하면 5초에 한번씩 화살이 날아가는 소리를 내는 그런 콘솔 프로그램이 있다고 합시다.
playarrow.exe라는 파일을 첨부하였습니다. 뭐 하는 일이라고는 5초마다 쓩 소리를 내는 그런 프로그램입니다. 왜 이런 프로그램을 만들었냐구요? ㅋㅋ 아~무 이유없어.
 
아무튼 첨부되어 있는 palyarrow.exe와 instsvr.exe, srvany.exe파일을 다운받아서 한 디렉토리에 저장하세요. 저는 C:\testsvr 이라는 디렉토리로 하겠습니다.
 
그럼 명령프롬프트 창을 열어서 C:\testsvr 로 이동하세요.
그런 다음 다음과 같은 명령을 실행합니다.
 
 
C:\testsvr>instsrv PlayArrowSound "C:\testsvr\srvany.exe"The service was successfuly added!Make sure that you go into the Control Panel and usethe Services applet to change the Account Name andPassword that this newly installed service will usefor its Security Context.
 
위와 같이 서비스가 성공적으로 추가되었다고 나오네요. 
진짜로 추가 되었는지 확인하기 위해 서비스관리자를 열어서 한번 확인해 보세요.
 
 
보시는 것 처럼 PlayArrowSound라는 서비스가 추가되었네요.
하지만 아직 아무 것도 할 작업이 없으므로 시작을 시켜도 바로 중지됩니다.
 
그럼 이제 palyarrow.exe 를 등록해 보도록 하겠습니다.
등록작업은 직접 레지스트리의 값을 변경하여야 합니다.
 
시작 > 열기로 regedit 를 엽니다.
 
"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\PlayArrowSound"로 갑니다.
 
마우스 오른쪽 버튼을 클릭해서 "새로만들기" > "키"를 선택하신 다음에 이름을 "Parameters" 라고 줍니다.
 
이번에는 "Parameters"를 선택하고 "새로만들기" > "문자열 값"을 선택하신 다음 이름을 "Application" 라고 줍니다.
 
그리고 "Application"을 더블 클릭해서 나타나는 대화상자에 값으로 playarrow.exe 파일의 전체경로를 적어 주세요.
 
 
확인을 누른 다음 서비스 관리자에서 PlayArrowSound 서비스를 시작시켜 보십시오.
 
잘 동작하나요? 만약 안된다면 리부팅이 필요할 수도 있습니다.
 
어찌되었건 콘솔 프로그램을 서비스로 등록시켰네요.
 
이렇게 등록된 서비스를 삭제하시고 싶다면 다음과 같이 입력하여 삭제할 수 있습니다.
 
물론 서비스를 먼저 멈춰야 겠죠?
 
 
C:\testsvr>instsrv PlayArrowSound RemoveThe service was successfully deleted!
 
 
여기서 한가지만 더 알아보도록 하겠습니다.
 
레지스트리를 건드린 김에 하나만 더 건드리도록 하겠습니다.
서비스 관리자에 보면 "설명"이라는 칸이 있고 거기에 서비스가 뭐하는 서비스 인지가 적혀있는 것을 보셨을 겁니다. 이것을 추가해 보도록 하겠습니다.
 
regedit에서 다시 "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\PlayArrowSound" 에 갑니다.
 
그런 뒤 마우스 오른쪽 버튼 클릭 후 "새로만들기" > "문자열 값" 을 선택해서 "Descript-xion"이라는 이름을 추가하세요.
 
그리고 "Descript-xion"을 더블클릭해서 자유롭게 설명을 적으세요. 단, 1024문자까지만 가능합니다.
 
저는 "5초마다 화살이 나르는 소리를 들려주는 연습용 서비스입니다." 라고 적겠습니다.
 
다시 서비스 관리자를 띄우시고 보세요. 이미 띄워져 있다면 F5번을 누릅니다.
 
위에서 설정한 설명이 화면에 표시되나요?
 
 
 ^^;
레지스트리의 다른 부분도 서비스와 관련된 설정들을 조작할 수는 있지만 잘 모르시면 괜히 건드리지 마십시오. 레지스트리는 확실히 안다고 해도 안건드리는 것이 좋습니다.
 
여기까지 입니다.
 

by 슬럼퍼 | 2008/08/29 11:08 | 웹개발 | 트랙백 | 덧글(0)

RoR(ruby on rails) 설정


## Ruby on Rails 설치 ##


1. Ruby(186) 설치

   http://rubyforge.org/frs/?group_id=167
   ruby186-26 : http://rubyforge.org/frs/download.php/29263/ruby186-26.exe


2. Rails 설치
   gem install rails --include-dependencies
 
   (option) Rails 버전 별 설치
   gem install rails --include-dependencies -v 1.2.3

   (option)Rake 설치
   gem install rake --include-dependencies


3. Mongrel 서버 설치
   gem install mongrel --include-dependencies

4. Mysql 드라이버 설치
    gem install mysql
 
   - Mysql 설치
   - Mysql\bin\libmySQL.dll 을 Ruby\bin\ 에 복사

   > database.yml 설정
     development:
    adapter: mysql
    encoding: euckr
    database: mydb
    username: myidd
    password: mypw
    host: localhost

  
   (option) SQLite 설치
   gem install sqlite3-ruby


5. scaffolding 설치

 ruby script/plugin install scaffolding

6. will_paginate 설정

   > 설치
   ruby script/plugin install svn://errtheblog.com/svn/plugins/will_paginate 
  또는 ruby script/plugin install http://tools.assembla.com/svn/breakout/breakout/vendor/plugins/will_paginate/ 
  또는 gem install mislav-will_paginate -s http://gems.github.com

 
 a. environment.rb 설정
  Rails::Initializer.run do |config|
   ....
  end
  require 'will_paginate'
  
 b. pagination.css 복사
  $ruby_home\gems\1.8\gems\will_paginate-2.2.2\examples\pagination.css 를
  $project_home\public\stylesheets\ 에 복사
 
 c. pagination.css 설정
  $project_home\app\views\layouts\project.html.erb에 css 설정
  <%= stylesheet_link_tag 'scaffold', 'pagination' %>
 
 d. 해당 Controller 파일 수정
  def index
   #@peoples = People.find(:all) 에서
         @peoples = People.paginate :page => params[:page], :per_page => 5
  end
 
 e. 해당 html (페이징) 파일 수정
  <div class='flickr_pagination'>
      <%= will_paginate @peoples %>
  </div>


## 프로젝트 생성 ##


1. phonebook 프로젝트 생성 (mysql 사용)
 rails phonebook -d mysql


2. scaffold 사용
 ruby script/generate scaffold People name:string phone_number:string note:text


3. 테이블 스키마 생성(복수형) : peoples

by 슬럼퍼 | 2008/08/20 17:45 | Ruby | 트랙백 | 덧글(0)

◀ 이전 페이지          다음 페이지 ▶