달력

42024  이전 다음

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
출처 : http://struts.apache.org/2.0.12/docs/how-do-i-set-a-global-resource-bundle.html



In Struts 2, resource bundles can be associated with classes. The framework will automatically discover and load class-orientated resource bundles. You can also specify one or more global resource bundles, which would be available to all classes in the application, using either the standard properties file, or a custom listener.

Properties file

Global resource bundles can be specified in the struts.properties configuration file.

struts.properties
struts.custom.i18n.resources=global-messages
The framework searches the class heirarchy first, then, as a last resource, checks the global resources.

Multiple resource bundles can be specified by providing a comma-separated list.

struts.properties
struts.custom.i18n.resources=global-messages, image-messages

Listener

Aside from the properties file, a Listener could also be used to load global resource bundles.

ActionGlobalMessagesListener.java
public class ActionGlobalMessagesListener implements ServletContextListener {
private static Logger log = Logger.getLogger(ActionGlobalMessagesListener .class);
private static final String DEFAULT_RESOURCE = "global-messages";

/**
* Uses the LocalizedTextUtil to load messages from the global message bundle.
* @see
javax.servlet.ServletContextListener#contextInitialized(javax.servlet.Servle
tContextEvent)
*/
public void contextInitialized(ServletContextEvent arg0) {
log.info("Loading global messages from " + DEFAULT_RESOURCE);
LocalizedTextUtil.addDefaultResourceBundle(DEFAULT_RESOURCE);
log.info("Global messages loaded.");
}

/**
* @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
*/
public void contextDestroyed(ServletContextEvent arg0) {

// do nothing

}
}

web.xml:
(under listeners section)

web.xml
<listener>
<listener-class>mypackagename.ActionGlobalMessagesListener</listener-class>
</listener>

Posted by tornado
|
간단하게 되는군요

<page:applyDecorator name="theDecorator">
    <s:action name="footer" executeResult="true" />
</page:applyDecorator>
Posted by tornado
|

import java.io.*;
import java.security.*;
import sun.misc.*;

public class TestSHA{
 public static void main(String[] args) throws Exception {

  byte[] txtByte = "테스트테스트".getBytes();

  MessageDigest md = MessageDigest.getInstance("SHA-1");

  md.update(txtByte);

  byte[] digest = md.digest();

  BASE64Encoder encoder = new BASE64Encoder();

  String base64 = encoder.encode(digest);

        // should be 20 bytes, 160 bits long
        System.out.println( digest.length );

        // dump out the hash
        for ( byte b : digest )
        {
            System.out.print( Integer.toHexString( b & 0xff )  );
        }

  //String result = new String(digest.toCha);

  System.out.println("\r\n" + toString(digest, 0, digest.length));

  //System.out.println("hexaString : " + HexString.bufferToHex(md.digest()));

 }

 private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray();


 public static final String toString(byte[] ba, int offset, int length) {
      char[] buf = new char[length * 2];
      for (int i = 0, j = 0, k; i < length; ) {
         k = ba[offset + i++];
         buf[j++] = HEX_DIGITS[(k >>> 4) & 0x0F];
         buf[j++] = HEX_DIGITS[ k        & 0x0F];
      }
      return new String(buf);
  }

}
Posted by tornado
|
원문 : http://edocs.bea.com/wls/docs61/webServices/advanced.html


Invoking Web Services Without Using the WSDL File


This Appendix shows an example of a dynamic client application that does not use the WSDL file when it invokes a WebLogic Web Service. In particular, the example invokes a message-style Web service and sends data to WebLogic Server.

Dynamic client applications that do not use the WSDL of the Web service are dynamic in every way, because they can invoke a Web service without knowing either the interface of the Web service, or the JavaBean interface of return values and parameters, or even the number and signatures of the methods that make up the Web service.

The example uses the URL http://www.myHost.com:7001/msg/sendMsg to invoke the Web Service. Because the example shows a dynamic client application that does not use the WSDL of the Web service, the preceding URL is for the Web service itself, rather than the URL for the WSDL of the Web service.

The procedure after the example discusses relevant sections of the example as part of the basic steps you follow to create this client.

import java.util.Properties;
import java.net.URL;
import javax.naming.Context;
import javax.naming.InitialContext;
import weblogic.soap.WebServiceProxy;
import weblogic.soap.SoapMethod;
import weblogic.soap.SoapType;
import weblogic.soap.codec.CodecFactory;
import weblogic.soap.codec.SoapEncodingCodec;
import weblogic.soap.codec.LiteralCodec;
public class ProducerClient{
  public static void main( String[] arg ) throws Exception{
    CodecFactory factory = CodecFactory.newInstance();
    factory.register( new SoapEncodingCodec() );
    factory.register( new LiteralCodec() );
    WebServiceProxy proxy = WebServiceProxy.createService( 
       new URL( "http://www.myHost.com:7001/msg/sendMsg" ) );
    proxy.setCodecFactory( factory );
    proxy.setVerbose( true );
    SoapType param = new SoapType( "message", String.class );
    proxy.addMethod( "send", null, new SoapType[]{ param } ); 
    SoapMethod method = proxy.getMethod( "send" );
    String toSend = arg.length == 0 ? "No arg to send" : arg[0];
    Object result = method.invoke( new Object[]{ toSend } );
  } 
}

Follow these steps to create a dynamic Java client that does not use WSDL to invoke a message-style WebLogic Web Service that sends data to WebLogic Server:

  1. Get the Java client JAR file from the WebLogic Server hosting the WebLogic Web Service.

    For detailed information on this step, refer to Downloading the Java Client JAR File from the Web Services Home Page.

  2. Add the Java client JAR file to your CLASSPATH on your client computer.
  3. Create the client Java program. The following steps describe the Web services-specific Java code:

    1. In the main method of your client application, create a factory of encoding styles and register the two that are supported by WebLogic Server (the SOAP encoding style and Apache's Literal XML encoding style):
      CodecFactory factory = CodecFactory.newInstance();
      factory.register( new SoapEncodingCodec() );
      factory.register( new LiteralCodec() );
      
    2. Add the following Java code to create the connection to the Web service and set the encoding style factory:
      WebServiceProxy proxy = WebServiceProxy.createService( 
             new URL( "http://www.myHost.com:7001/msg/sendMsg" ) );
      proxy.setCodecFactory( factory );
      proxy.setVerbose( true );
      
    3. Add the following Java code to dynamically get the send method of the Web service:
       SoapType param = new SoapType( "message", String.class );
       proxy.addMethod( "send", null, new SoapType[]{ param } ); 
       SoapMethod method = proxy.getMethod( "send" );
      
    4. Invoke the send method and send data to the Web service. In the example, the client application simply takes its first argument and sends it as a String; if the user does not specify an argument specified, then the client application sends the string No arg to send:
      String toSend = arg.length == 0 ? "No arg to send" : arg[0];
      Object result = method.invoke( new Object[]{ toSend } );
      
  4. Compile and run the client Java program as usual.

The following more complex example shows how to use a send method that accepts a org.w3c.dom.Document, org.w3c.dom.DocumentFragment, or org.w3c.dom.Element data type as its parameter. The example shows how to set literal encoding on this flavor of the send method.

import java.util.Properties;
import java.net.URL;
import java.io.File;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import weblogic.apache.xml.serialize.OutputFormat;
import weblogic.apache.xml.serialize.XMLSerializer;
import weblogic.apache.xerces.dom.DocumentImpl;
import weblogic.soap.WebServiceProxy;
import weblogic.soap.SoapMethod;
import weblogic.soap.SoapType;
import weblogic.soap.codec.CodecFactory;
import weblogic.soap.codec.SoapEncodingCodec;
import weblogic.soap.codec.LiteralCodec;
public class ProducerClient{
  public static void main(String[] args) throws Exception{
    String url = "http://localhost:7001";
    // Parse the arguments list
    if (args.length != 2) {
      System.out.println("Usage: java examples.webservices.message.ProducerClient 
http://hostname:port \"message\"");
      return;
    } else if (args.length == 2) {
      url = args[0];
    }
    CodecFactory factory = CodecFactory.newInstance();
    factory.register(new SoapEncodingCodec());
    factory.register(new LiteralCodec());
    URL newURL = new URL(url + "/msg/sendMsg");
    WebServiceProxy proxy = WebServiceProxy.createService(newURL);
    proxy.setCodecFactory(factory);
    proxy.setVerbose(true);
    SoapType param = new SoapType( "message", Document.class );
    proxy.addMethod( "send", null, new SoapType[]{ param } );
    SoapMethod method = proxy.getMethod("send");
    // Print out proxy to make sure method signature looks good
    System.out.println("Proxy:"+proxy);
    DocumentBuilderFactory dbf =
                     DocumentBuilderFactory.newInstance();
    //Obtain an instance of a DocumentBuilder from the factory.
    DocumentBuilder db = dbf.newDocumentBuilder();
    //Parse the document.
    Document w3cDoc = db.parse(new File("/test/fdr_nodtd.xml"));
    //Class parserClass = Class.forName("org.jdom.adapters.XercesDOMAdapter");
    //DOMAdapter da = (DOMAdapter)parserClass.newInstance();
    //Document w3cDoc = da.getDocument(new File("/test/fdr_nodtd.xml"),false);
    // Print out XML just to make sure the document was read successfully
    OutputFormat of = new OutputFormat();
    of.setEncoding("UTF-8");
    of.setLineWidth(40);
    of.setIndent(4);
    XMLSerializer xs = new XMLSerializer(System.out,of);
    xs.serialize(w3cDoc);
    System.out.println("Before Invoke");
    Object result = method.invoke( new Object[]{w3cDoc} );
    System.out.println("Done");
  }
}
Posted by tornado
|

출처 : http://javaexchange.com/aboutRandomGUID.html

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


Random GUID generator in Java


Download RandomGUID. -- generates truly random GUIDs in the standard format.


RandomGUID.java


/* * RandomGUID * @version 1.2.1 11/05/02 * @author Marc A. Mnich * * From www.JavaExchange.com, Open Software licensing * * 11/05/02 -- Performance enhancement from Mike Dubman. * Moved InetAddr.getLocal to static block. Mike has measured * a 10 fold improvement in run time. * 01/29/02 -- Bug fix: Improper seeding of nonsecure Random object * caused duplicate GUIDs to be produced. Random object * is now only created once per JVM. * 01/19/02 -- Modified random seeding and added new constructor * to allow secure random feature. * 01/14/02 -- Added random function seeding with JVM run time * */ import java.net.*; import java.util.*; import java.security.*; /* * In the multitude of java GUID generators, I found none that * guaranteed randomness. GUIDs are guaranteed to be globally unique * by using ethernet MACs, IP addresses, time elements, and sequential * numbers. GUIDs are not expected to be random and most often are * easy/possible to guess given a sample from a given generator. * SQL Server, for example generates GUID that are unique but * sequencial within a given instance. * * GUIDs can be used as security devices to hide things such as * files within a filesystem where listings are unavailable (e.g. files * that are served up from a Web server with indexing turned off). * This may be desireable in cases where standard authentication is not * appropriate. In this scenario, the RandomGUIDs are used as directories. * Another example is the use of GUIDs for primary keys in a database * where you want to ensure that the keys are secret. Random GUIDs can * then be used in a URL to prevent hackers (or users) from accessing * records by guessing or simply by incrementing sequential numbers. * * There are many other possiblities of using GUIDs in the realm of * security and encryption where the element of randomness is important. * This class was written for these purposes but can also be used as a * general purpose GUID generator as well. * * RandomGUID generates truly random GUIDs by using the system's * IP address (name/IP), system time in milliseconds (as an integer), * and a very large random number joined together in a single String * that is passed through an MD5 hash. The IP address and system time * make the MD5 seed globally unique and the random number guarantees * that the generated GUIDs will have no discernable pattern and * cannot be guessed given any number of previously generated GUIDs. * It is generally not possible to access the seed information (IP, time, * random number) from the resulting GUIDs as the MD5 hash algorithm * provides one way encryption. * * ----> Security of RandomGUID: <----- * RandomGUID can be called one of two ways -- with the basic java Random * number generator or a cryptographically strong random generator * (SecureRandom). The choice is offered because the secure random * generator takes about 3.5 times longer to generate its random numbers * and this performance hit may not be worth the added security * especially considering the basic generator is seeded with a * cryptographically strong random seed. * * Seeding the basic generator in this way effectively decouples * the random numbers from the time component making it virtually impossible * to predict the random number component even if one had absolute knowledge * of the System time. Thanks to Ashutosh Narhari for the suggestion * of using the static method to prime the basic random generator. * * Using the secure random option, this class compies with the statistical * random number generator tests specified in FIPS 140-2, Security * Requirements for Cryptographic Modules, secition 4.9.1. * * I converted all the pieces of the seed to a String before handing * it over to the MD5 hash so that you could print it out to make * sure it contains the data you expect to see and to give a nice * warm fuzzy. If you need better performance, you may want to stick * to byte[] arrays. * * I believe that it is important that the algorithm for * generating random GUIDs be open for inspection and modification. * This class is free for all uses. * * * - Marc */ public class RandomGUID extends Object { public String valueBeforeMD5 = ""; public String valueAfterMD5 = ""; private static Random myRand; private static SecureRandom mySecureRand; private static String s_id; /* * Static block to take care of one time secureRandom seed. * It takes a few seconds to initialize SecureRandom. You might * want to consider removing this static block or replacing * it with a "time since first loaded" seed to reduce this time. * This block will run only once per JVM instance. */ static { mySecureRand = new SecureRandom(); long secureInitializer = mySecureRand.nextLong(); myRand = new Random(secureInitializer); try { s_id = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { e.printStackTrace(); } } /* * Default constructor. With no specification of security option, * this constructor defaults to lower security, high performance. */ public RandomGUID() { getRandomGUID(false); } /* * Constructor with security option. Setting secure true * enables each random number generated to be cryptographically * strong. Secure false defaults to the standard Random function seeded * with a single cryptographically strong random number. */ public RandomGUID(boolean secure) { getRandomGUID(secure); } /* * Method to generate the random GUID */ private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } // This StringBuffer can be a long as you need; the MD5 // hash will always return 128 bits. You can change // the seed to include anything you want here. // You could even stream a file through the MD5 making // the odds of guessing it at least as great as that // of guessing the contents of the file! sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } /* * Convert to the standard format for GUID * (Useful for SQL Server UniqueIdentifiers, etc.) * Example: C2FEEEAC-CFCD-11D1-8B05-00600806D9B6 */ public String toString() { String raw = valueAfterMD5.toUpperCase(); StringBuffer sb = new StringBuffer(); sb.append(raw.substring(0, 8)); sb.append("-"); sb.append(raw.substring(8, 12)); sb.append("-"); sb.append(raw.substring(12, 16)); sb.append("-"); sb.append(raw.substring(16, 20)); sb.append("-"); sb.append(raw.substring(20)); return sb.toString(); } /* * Demonstraton and self test of class */ public static void main(String args[]) { for (int i=0; i< 100; i++) { RandomGUID myGUID = new RandomGUID(); System.out.println("Seeding String=" + myGUID.valueBeforeMD5); System.out.println("rawGUID=" + myGUID.valueAfterMD5); System.out.println("RandomGUID=" + myGUID.toString()); } } }

Download RandomGUID. -- generates truly random GUIDs in the standard format.
Posted by tornado
|

Subversion 설치.

 

설치 파일 : CollabNetSubversion-server-1.5.0-23.win32.exe

 

 

설치시에 repository 부분 설정하는 곳이 있는데 윈도우 인스톨 된 드라이브 말고

 

d 드라이브나 데이터 저장되는 드라이브로 변경해 주세요.

 

 

1. ehr 소스가 저장될 프로젝트를 생성해 주세요.

 

커맨드 창에서 아래와 같이 해주시면 됩니다.

 

svnadmin create --fs-type fsfs c:\svn_repository\ehr_2008_07

 

 

2. 소스세이프에 생성된 프로젝트 에서 현재 프로젝트의 접근 설정을 해주세요.

 

c:\svn_repository\ehr_2008_07\conf 디렉토리에 보면

 

 

svnserve.conf 파일이 있습니다.

 

이곳에서 아래의 부분을 수정해 주세요.(# 표시를 지워주세요)

 

12번째 줄 : #anon-access = read --> anon-access = none

 

13번째 줄 : #auth-access = write

 

20번째 줄 : #password-db = passwd --> 앞에 # 표시 제거

 

32번째 줄 : # realm = My First Repository --> realm = ehr_2008_07

 

 

 

 

3. 사용자를 등록해야 합니다.

 

c:\svn_repository\ehr_2008_07\conf 디렉토리에 보면

 

passwd 라는 텍스트 파일이 존재합니다.

 

해당 파일을 아래와 같이 수정해 주세요.

 

### This file is an example password file for svnserve.

### Its format is similar to that of svnserve.conf. As shown in the

### example below it contains one section labelled [users].

### The name and password for each user follow, one account per line.

 

[users]

# harry = harryssecret

# sally = sallyssecret

 

jy = 1111

tornado = 1111

 

 

4. svn manager 설치해주세요.(재부팅 되도 svn 이 자동실행 됩니다)

 

SVNManager-1.1.1-Setup.msi  파일을 설치

 

설치 하신 후 아래의 순서로 셋팅해 주시면 됩니다.

 

시작 --> 모든 프로그램 --> Subversion --> SVNServe manager 를 실행

 

실행하면 작업 트레이에 아이콘 생성됨.

 

아이콘 더블클릭 하면 설정 화면 보여짐.

 

Subversion Repository 에서 경로를 d:\svn_repository 로 맞춤

 

Port --> 3690  으로 입력

 

Run Mode --> Normal 로 선택

 

Start 버튼 클릭

 

Hide 버튼 클릭

 

 

끝입니다

Posted by tornado
|

현재 프로젝트 weblogic 6.1 -.-;

웹서비스 작업해야 하는데, 6.1 에서는 Stateless Session Bean, Message Driven Bean 에만

웹서비스를 생성 할 수 있다.

ant task 중에서 wsgen 이라는게 있더군.

그래서 ant build 파일 만들어서 빌드 하고 ear 을 weblogic 에 심어줬다.

자바 클라이언트로는 dynamic, static 둘다 잘 됨.

그러나~~~~~

asp.net 2.0 에서 자바 웹서비스를 생성하지 못한다.

웹서비스 참조 걸었을 경우 map파일을 만들지 못함.

왜!!!!

웹로직에서 생성한 웹서비스의 wsdl.jsp 에 문제가 있다.

<definitions
targetNamespace="java:com.xxx"
xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/1999/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="java:com.xxx"
>

xmlns 가 1999 라서 문제가 생긴다.

문제를 빨랑 해결해야 해서...

ear 파일 까고, war 파일 까서...

아래와 같이 고쳤다.

<definitions
targetNamespace="java:com.xxx"
xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="java:com.xxx"
>

년도만 2001 로 고쳤더니 잘 됨.

버젼이 낮으니 이런 문제도 발생을 하는군요.

Posted by tornado
|

http://jcifs.samba.org/



http://jcifs.samba.org/src/docs/ntlmhttpauth.html



읽어보구 현재 프로젝트에 적용할 수 있을때 해야겠다.




Posted by tornado
|
Posted by tornado
|

resin.conf에 아래와 같이 추가해주던가....

    <system-property javax.xml.parsers.DocumentBuilderFactory="org.apache.xerces.jaxp.DocumentBuilderFactoryImpl" />
    <system-property javax.xml.parsers.SAXParserFactory="org.apache.xerces.jaxp.SAXParserFactoryImpl" />
    <system-property javax.xml.transform.TransformerFactory="org.apache.xalan.processor.TransformerFactoryImpl" />
    <system-property org.xml.sax.driver="org.apache.xerces.parsers.SAXParser" />


아니면 다음과 같이 리스너를 구현한다.

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class XmlTranslateListener implements ServletContextListener {

 public void contextInitialized(ServletContextEvent arg0) {
 
  System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
  System.setProperty("javax.xml.parsers.SAXParserFactory","org.apache.xerces.jaxp.SAXParserFactoryImpl");
  System.setProperty("javax.xml.transform.TransformerFactory","org.apache.xalan.processor.TransformerFactoryImpl");
  System.setProperty( "org.xml.sax.driver",  "org.apache.xerces.parsers.SAXParser" );
 }
   

 public void contextDestroyed(ServletContextEvent arg0) {
  // TODO Auto-generated method stub

 }

}

Posted by tornado
|


getSqlMapClientTemplate().execute(new SqlMapClientCallback() {
    public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException {
       executor.startBatch();
             
        while(....){
           // job....

        }

         return new Integer( executor.executeBatch()) ;    
    }
   });
Posted by tornado
|

OS 는 솔라리스이고, 메일서버는 sendmail
was 는 resin

메세지를 MimeMessage 로 선언하고 setContent 메서드를 이용해서

HTML 메세지를 넣었다.

허걱..

익셉션 발생...

왜 그러지?? 하고 쳐다보다가 문득 !! 예전에 웹 메일 만들던 생각이 남.

아~~ 맞다... 바디파트에 넣고 하면 되지~~

   Multipart multi = new MimeMultipart();    

   MimeBodyPart mbp = new MimeBodyPart();
  
   mbp.setContent("여기에 내용을 ~~~", "text/html; charset=KSC5601");
  
   multi.addBodyPart(mbp);
  
   msg.setContent(multi);

   Transport.send(msg);


해결...

메일링 보낼때 뭔가 찜찜해서 스레드로 백그라운드에서 메일 전송하게 함 ..

현재로서는 탄탄하게 잘 돌아감.

Posted by tornado
|
[펌] http://forum.java.sun.com/thread.jspa?threadID=247536&messageID=913161


i got the solution for the problem myself
if any one encounter same problem ,

Just change
session = javax.mail.Session.geDefaultInstance(props,auth);


to

session = javax.mail.Session.getInstance(props,auth);
while using in more than one smtps,user,passwords etc in same JRE
bye
Posted by tornado
|

JSP/Servlet 환경에서 다운로드를 사용할 경우는
아래와 같은 순서를 가진다.

1. HttpServletResponse 로 부터 OutStream 을 얻는다.
2. Header, ContentsType 등을 설정한다.
3. FileStream 을 통해 전송될 파일의 스트림을 얻는다.
4. Response 로 부터 얻은 outputStream 에 파일을 쏜다.
5. 열려진 모든 자원을 닫는다.


뭐 다른것들은 괜찮지만  2번 항목에서 환경에 따라 헤더 설정이 틀려진다.
단독 WAS 환경인지, WAS 앞에 Apache 나 IIS 가 있는지 등등..

웬만한 부분에서는 아래와 같은 Header 설정이면 충분하다.

res.setContentType("appliction/octet-stream");
res.setHeader("Accept-Ranges","bytes");
res.setHeader("Content-Transfer-Encoding", "binary;");
res.setHeader("Pragma", "no-cache;");
res.setHeader("Expires", "-1;");

res.setHeader("Content-Disposition", "attachment; filename=" + fileName + ";");



문제는 위 설정으로 zip 파일이나, 다른 파일들은 저장, 열기가 잘 되지만 유독 HWP 파일에서 문제가 생긴다.

다운로드 창까지는 잘 뜨는데, 열기 버튼을 누르면 파일을 찾을 수 없다고 나온다.

저장해서 보면 잘 보이지만 ㅎㅎ

여차저차 해서 헤더에 아래와 같이 추가해줬다.

res.setHeader("Cache-control","private");

잘 된다 ^^

캐시 컨트롤을 private 으로 하겠다는 의미는 전송되는 개체가 공유 캐시에 보관되지 않고 특정 클라이언트만을 대상으로 해야 한다는 말이다.

Posted by tornado
|
http://weblogs.java.net/blog/gmurray71/archive/2006/09/preventing_cros.html


Preventing Cross Site Scripting Attacks

Posted by gmurray71 on September 27, 2006 at 12:01 PM | Comments (9)

Preventing Cross Site Scripting Attacks

Cross site scripting (XSS) is basically using JavaScript to execute JavaScript from an unwanted domain in a page. Such scripts could expose any data in a page that is accessible by JavaScript including, cookies, form data, or content to a 3rd party. Here is how you can prevent your web pages from being exploited on both the client and the server. This is followed with tips on how to avoid vulnerable sites.

  • Escape parameters and User Input - The safest step you can take is to escape all parameters to a page where the parameters are displayed in the content.The same applies for any user input that may be displayed or re-displayed in a web page rendered by a server. The downside is that your users can not provide markup.
  • Remove eval(), javascript, and script from User Provided Markup - If you allow users to provide markup in any part of your application that is displayed in a page make sure to remove eval() and javascript: calls from element attributes including styles as they can be used to execute JavaScript. Also remove script blocks.
  • Filter User Input on the Server - You should always filter user input that is stored or processed on a server because URLs and GET/POST requests can be created manually.
  • Use Caution with Dynamic Script Injection - Be careful when dynamically injecting external scripts to retrieve JSON based data as you are potentially exposing everything accessible by JavaScript.
  • Avoid XSS Phishing Attacks - Be aware of sites that contain vulnerabilities and phishing style attacks containing external script references.

Escape Parameters and User Input

This is the classic XSS attack that can open your service or web application up to hackers. By design the site displays a user's id that is passed in as a URL parameter. The following script will take the id and display a welcome message.

<script type="text/javascript">
  var start = window.location.href.indexOf("id");
  var stop = window.location.href.length;
  var id = "guest";
  if (start < stop) {
    id = decodeURIComponent(window.location.href.substring(start,stop));
  }
  document.write("Hi " + id);
</script>

A request to the URL index.html?id=greg (assuming the page containing the script is index.html) will result in:

Hi greg

What would happen if instead of "greg" I used the following URL:

index.html?id=%3Cscript%20src=%22http://baddomain.com/badscript.js%22%3E%3C/script%3E

Notice the URL above contains a link to script http://baddomain.com/badscript.js which contains malicious code from a different domain. This script will be evaluated when the page is loaded putting the page and all the data in it at risk.

To prevent from these types of attacks your client code should always escape "<" and ">" parameters that are displayed or evaluated by JavaScript code.

You can do this with a simple line of code as can be seen in the next example.

<script type="text/javascript">
  var start = window.location.href.indexOf("id");
  var stop = window.location.href.length;
  var id = "guest";
  if (start < stop) {
    id = decodeURIComponent(window.location.href.substring(start,stop));
	
  }
  document.write("hi " + id);
</script>

Consider the following containing a form where a user enters a description that will be visible to other users.

<html>
<head>
<script type="text/javascript">
  function displayName() {
    var description = document.getElementById("description").value;
    var display = document.getElementById("display");
    display.innerHTML = description;
  }
</script>
</head>
<body>
<form onsubmit="displayName();return false;">
<textarea id="description" type="text" cols="55" rows="5"></textarea>
<input type="submit" value="Show Description">
</form>
<div id="display"></div>
</body>
</html>

Seems innocent enough right? Try including the following content in the text area.

<a onmouseover="eval('s=document.createElement(\'script\'); document.body.appendChild(s); s.src=\'badscript.js\'')">Mouse Over Me</a>

A mouseover of the link will cause a script in a badscript.js to be loaded. This script could also pass along cookies or any other information it wanted to as parameters of the "s.src" URL. Unlike the first example where the user would need to click on a bad link this type of attack requires a simple mouseover to load the badscript.js.

So the question now comes to mind: 'How do you protect your web page from being being exploited?'

Along with the parameters you should escape form input. If you plan to allow users to provide their own markup consider the next solution titled Remove eval(), javascript, and script from User Provided Markup.

The following code shows how to escape markup on the client.

<html>
<head>
<script type="text/javascript">
  function displayName() {
    var description = document.getElementById("description").value;
    var display = document.getElementById("display");
    description = description .replace(/</g, "&lt;").replace(/>/g, "&gt;");
    display.innerHTML = description;
  } 
</script>
</head>
<body>
<form onsubmit="displayName();return false;">
<textarea id="description" type="text" cols="55" rows="5"></textarea>
<input type="submit" value="Show Description">
</form>
<div id="display"></div>
</body>
</html>

The code description = description.replace(//g, ">"); filters the user input and prevents unwanted scripts from being executed.

Now that we have looked at how to prevent most attacks the next section focuses on cases where you want to allow users to provide markup that does not contain malicious code.

Remove eval(), javascript:, and script from User Provided Markup

There may be cases where you want to allow a user to add markup such as links or HTML content that is displayed for other users to see. Consider a blog that allows for HTML markup, user provided URLs, HTML comments, or any other markup. The solution would be to filter all markup before it is displayed in a page or before it is sent to a server or service. The following example shows how to allow for some HTML markup while preventing malicious code.

<html>
<head>
<script type="text/javascript">
  function displayName() {
    var description = document.getElementById("description").value;
    var display = document.getElementById("display");
    description.replace(/[\"\'][\s]*javascript:(.*)[\"\']/g, "\"\"");
    description = description.replace(/script(.*)/g, "");    
    description = description.replace(/eval\((.*)\)/g, "");
    display.innerHTML = description;
  } 
</script>
</head>
<body>
<form onsubmit="displayName();return false;">
<textarea id="description" type="text" cols="55" rows="5"></textarea>
<input type="submit" value="Show Description">
</form>
<div id="display"></div>
</body>
</html>

The example above removes all eval(), javascript and script references that may be entered in the description field. The replacement here is not a perfect as it may replace legitimate uses of the words javascript and script in the body of a document. You may consider refining the regular expressions to only look in tag attributes for example and to remove full scripts. There are other considerations you should keep in mind when filtering client code such as line breaks, charsets, case sensitivity which are commonly exploited in attacks. As some browsers will allow you to specify JavaScript calls from CSS styles you should also consider searching user provided CSS styles as well.

Filter User Input on the Server

Most of the problems related to cross site scripting are because of poorly designed clients. Servers can also unwillingly become participants in cross domain scripting attacks if they redisplay unfiltered user input. Consider the following example where a hacker manually makes a HTTP POST request to set the homepage URL with the following.

<a href="javascipt:eval('alert(\'bad\')');">Click Me</a>

The URL would end up being stored as is on the server as is and expose any user that clicks on the URL to the JavaScript. The example above seems innocent enough but consider what would happen if in place of an alert('bad') the "javascript" contained malicious code. To prevent such attacks you should filter user input on the server. The following Java example shows how to use regular expression replacement to filter user input.

String description = request.getParameter("description");
description = description.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
description = description.replaceAll("eval\\((.*)\\)", "");
description = description.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
description = description.replaceAll("script", "");

The code above removes eval() calls, javascript: calls, and script references the replacement here is not a perfect as it may replace legitimate uses of the words javascript and script in the body of a document. The code above may be applied using a servlet, servlet filter, or JSF component on all input parameters or on a per parameter basis depending on what how much markup you would like to allow users to provide. You may want refine the regular expressions that filter the content to handle more or consider a Java library built that specializes in removing malicious code.

Use Caution with Dynamic Script Injection

Dynamic script injection to retrieve JSON data (also known as JSONP) can be powerful and useful as it decouples your client from the server of origin. There is still a bit of debate over using JSONP as some consider it as a hack or security hole in JavaScript because when you dynamically include a reference to a 3rd party script you are giving that script full access to everything in your page. That script could go on to inject other scripts or do pretty much whatever it wanted.

If you choose to use JSONP make sure you trust the site for which you are interacting with. There is nothing stopping a JSONP provider from including unwanted script with JSONP data. One alternative would be to provide a proxy service which you can control the output, restrict access to, and can cache as needed.

Avoid XSS Phishing Attacks

This next recommendation focuses on protecting yourself as a user from a site that is vulnerable to cross site scripting attacks.

Phishing attacks, or attacks where what appears to be a valid URL links to a fraudulent web page who's purpose is to collect a users data, are nothing new to the web world. A related attack involves cross site scripting attacks where a URL to a legitimate site that has a cross site scripting vulnerability contains a script reference. Such a link may appear in an email message, blog posting/comment, or other user generated content that contains a URL. Clicking a link to a site containing a cross site scripting vulnerability would cause a 3rd party script to be included along with your request and could expose your password, user id, or any other data. Consider the following example:

<a href="http://foobar.com/index.html?id=%3Cscript%20src=%22http://baddomain.com/badscript.js%22%3E%3C/script%3E">See foobar</a>

A quick look at the URL shows it references the site http://foobar.com/index.html. An unsuspecting user may not see the script included as a parameter later in the URL.

It is also wise to always look at carefully at URLs and the URL parameters that are provided with them. URLs will always appear in the status bar of your browser as and you should always look for external script reference. Another solution would be to manually type in links into the URL bar of your browser if a link is suspect.

Be aware of sites known to have vulnerabilities and be very careful with any personal data you provide those sites.

While JavaScript based interfaces can be very flexible you need to be very careful with all user provided input whether it be as parameters or form data. Always make sure to escape or filter input on the both the client and server. As a user you should be cautious not to become a victim of a vulnerable site. It's better to be safe than in the news!

What other things do you do to prevent XSS attacks?

Posted by tornado
|

원문 : http://blog.naver.com/jkhljesus?Redirect=Log&logNo=70016617377



여기저기 자료를 참고하며 고생끝에 해결 했네요.. ㅋ

iBatis 의 SqlMaps 를 이용 시 IN 절을 동적으로 생성할 때 처리하는 방법

IN절 이외에도 Dynamic SQL 구문 작성 시 유용할 듯 합니다.


XXX.java
--------------------------------------------------------------------------

List list = new ArrayList();
list.add(id);
list.add(id);


Map map = new HashMap();
map.put("listId",list);

return (Map) sm.getItem("em.ss.board.getBoardDetail", map);

XXX.xml

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

 <!-- CLOB Data 조회를 위한 정의  -->
 <resultMap id="getClobBoardData" class="hmap">
         <result property="TITLE" column="TITLE"/>
        <result property="CONTENT" column="CONTENT" typeHandler="clobHanlder"/>
</resultMap>


<select id="getBoardDetail" parameterClass="map" resultMap="getClobBoardData">
   SELECT  TITLE
               , CONTENT
   FROM TEX_BULLETIN_H
   WHERE ID
     <iterate prepend="IN" property="listId" open="(" close=")" conjunction=",">
       #listId[]#
     </iterate>  
         
</select>


Posted by tornado
|
대충 에러메세지가 아래와 같다.

java.lang.NullPointerException
        at com.opensymphony.module.sitemesh.taglib.decorator.TitleTag.doEndTag(TitleTag.java:32)

나는 sitemesh 의 decorator.xml 설정에 <excludes> 를 사용한다.

이 태그에 포함되어진 페이지는 sitemesh 장식자에서 제외된다.

그런데.. 디자인 변경작업중에 잘라내기/붙여넣기 도중 사이트메시 장식자에서 제거된 페이지에

<title><decorator:title default=" 사이트 타이틀 " /></title>

이 부분이 포함이 되어 있었던 상황이다.

이 부분이 없으니 사이트메시 태그라이브러리의 getPage().getTitle() 에서

널포인터 익셉션을 출력한 것이였다.

copy & paste  작업중 맘이 급해 생긴 상황이다.
Posted by tornado
|

원 출처 : http://blog.naver.com/hifrand/150016344742 


Lambda Probe logoLambda Probe for Apache Tomcat



이미 아는분들이 있을지도 모르지만...

국내에 아직 소개가 않된것 같아 람바다 프로브를 소개한다.

항상 먼저 툴을 만져보고 소개한다는 것은 기분좋은 일이다...

 

톰캣의 기본모니터링 툴이 워낙 좋다보니 --;; 여타 마땅한 모니터링 툴이

없어 뒤지다가.... 드디어...

춤추는 프로브를 찾았다 ㅋㅋ 스타가 생각난다 후후


여하튼 내용은 GPL을 따르고... 5.*대 이상에서 돌아가고...

설치는  WAR파일로 원빵에 설치가 후와 <-- 가장 마음에 든다 ㅍㅍ


그리고 톰캣의 권한을 설정하면 된다.

화면 잘 돌아간다.....

다각도의 모니터링 화면의 구성과 ...

무지 쉽다는것이 장점이다.


상용툴과 비교해도 결코 뒤지지 않는 멋진놈이다.

오늘의 자바헌터는 성공적이다. ^^

모두 같이 톰캣을 람바다를 추시기를 ~~



Welcome to the home of Lambda Probe (formerly known as Tomcat Probe) - the ultimate tool for monitoring and management of Apache Tomcat instance in real time. Lambda Probe will help you to visualise real time information about Apache Tomcat instance via easy to use and friendly web interface. For more information please visit the overview section.


Looking for Tomcat Probe? Read on...

To cut the long story short Tomcat Probe has changed its name to Lambda Probe. This is only a name change, Lambda Probe is the same code, same GPL license and it is the same person developing it :). Frankly there were two reasons for changing the name: one is to stay well clear of possible trademark infringement claims and the second one is that I simply could not come up with more or less decent logo for the former name. Yes, I'm being honest here! discuss...


Latest release

UI improvements, bugxies, ability to view IP address of the session, ability to view servlets, filters, desployment descriptor and many more

LambdaProbe 1.7b, BINARIES please see the CHANGELOG
Released on 28 Nov 2006 Size ~7Mb

Featured screenshots

They say a picture worth a thouthand words... Well, here are some of the screenshots of what you get when you download the latest release of Lambda Probe. You can find a whole lot more pictures in the screenshot section of this site.

Cluster stats Tailing log file

Tomcat compatibility

Lambda Probe is designed for Apache Tomcat and only Apache Tomcat. It will not work with any other application server. Lambda Probe has been tested with Java 1.4 and Java 1.5 and I found it to be working perfectly on both. It is also compatible with Tomcat5 versions 5.0.x and 5.5.x. Unfortunately it is not compatible with older versions such as 4.1.x and 3.3 because of lack of EL support in JSP 1.2.

'JAVA > WAS' 카테고리의 다른 글

Tomcat Authentication and Authorization Sequences  (0) 2010.02.11
아파치 + 톰캣 연동후 8009 커넥터 조정  (0) 2007.02.22
PermGen Space  (0) 2007.02.13
아파치 튜닝 정리  (0) 2007.01.19
[펌]아파치 + 톰캣 연동  (0) 2006.09.25
Posted by tornado
|

오랜만에 자바 코딩해봤음 ^^

jxl 예제에 엑셀 파일 생성, 읽기 부분만 나와있고 기존 파일에 추가하는 방법이 안나와서,
API 를 보니


public static WritableWorkbook createWorkbook(java.io.File file,
                                              Workbook in)
                                       throws java.io.IOException
Creates a writable workbook with the given filename as a copy of the workbook passed in. Once created, the contents of the writable workbook may be modified
Parameters:
file - the output file for the copy
in - the workbook to copy
Returns:
a writable workbook
Throws:
java.io.IOException



요런 부분이 있음.

글치.. 왜 없었겠어~ 그래서 API 를 자세히 봐야지~

아래는 간단하게 테스트 해본 소스이다.

1번줄 부터 생성한 이유는 엑셀 파일 첫줄이 Select box 로 정렬 할 수 있게 해놨기 때문임.



----------------------------------------------------------------------------------
package com.javarush;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class JxlUtil {
 
 public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
 
 public File getExcelToOrder() throws Exception{
 
  File dir = new File("d:/springStudy/JxlTest/src/com/javarush/");
  File f = new File(dir, "excel_default.xls");
 
  if(!f.exists()){
   throw new Exception("file not found");
  }
 
  if(!f.canRead()){
   throw new Exception("can't read file");
  }

  Workbook workbook = Workbook.getWorkbook(f);
 
  if(workbook == null){
   throw new Exception("Workbook is null!!");
  }
 
  File newExcel = new File(dir, System.currentTimeMillis() + ".xls");
     
  WritableWorkbook writeBook = Workbook.createWorkbook(newExcel, workbook);

  WritableSheet writeSheet = writeBook.getSheet(0);
 
  // 1열의 0번행에 ^^ 를 출력
  Label a = new Label(0,1, "^^");
 
  // 1열의 1번행에 날짜 출력
  Label d = new Label(1, 1, sdf.format( Calendar.getInstance().getTime()));
   
  writeSheet.addCell(a);
  writeSheet.addCell(d);
 
  writeBook.write();
  writeBook.close();
 
  return newExcel;
 }
}

Posted by tornado
|
출처 : http://coffeenix.net/bbs/viewtopic.php?t=1186&view=previous



올리기올려짐: 2006.7.21 금, 4:11 pm    주제: Re: 아파치와 톰캣 연동을 햇는데요?? (톰캣 튜닝) 인용과 함께 답변

tomcat도 아파치 튜닝처럼 운영하면서 최적의 설정값을 찾아내야 합니다.
apache의 80포트로는 접속이 잘 안되는데, tomcat이 사용하는 8080 포트로는 해당 페이지가 잘 열리는지 살펴보세요.
아주 예전에 이런 경험이 있어 설정 변경을 했습니다.

다음은 TOMCAT 홈/conf/server.xml 의 일부 default 설정입니다.
(2004.중순 tomcat 5.0.x의 기준입니다. 오래됐네요. ^^)

코드:

    <Connector port="8080"
               maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
               enableLookups="false" redirectPort="8443" acceptCount="100"
               debug="0" connectionTimeout="20000"
               disableUploadTimeout="true" />

    <Connector port="8009"
               enableLookups="false" redirectPort="8443" debug="0"
               protocol="AJP/1.3" />


위에서 8080으로 쓰이는 connector의 thread 설정 튜닝과
8009포트를 사용하는 AJP connector의 KeepAlive on/off와 Min/Max process 개수 등의 설정이 필요합니다.
thread 설정을 약간 늘려보시구요, AJP connector의 maxKeepAliveRequests는 off로 하고 process개수를 변경해보세요.
80은 접속이 잘 안되고, 8080은 된다면 다음 설정이 효과가 있을겁니다. 설정값은 님이 직접 튜닝하시구요.

코드:

    <Connector port="8080"
               maxThreads="300" minSpareThreads="75" maxSpareThreads="150"
               enableLookups="false" redirectPort="8443" acceptCount="250"
               debug="0" connectionTimeout="20000"
               disableUploadTimeout="true" />

    <Connector port="8009"
               enableLookups="false" redirectPort="8443" debug="0"
               maxKeepAliveRequests="-1" minProcessors="150" maxProcessors="500"
               protocol="AJP/1.3" />

'JAVA > WAS' 카테고리의 다른 글

Tomcat Authentication and Authorization Sequences  (0) 2010.02.11
[펌] Lambda Probe 톰캣 모니터링툴 ^^ 멋진놈이다.  (2) 2007.04.06
PermGen Space  (0) 2007.02.13
아파치 튜닝 정리  (0) 2007.01.19
[펌]아파치 + 톰캣 연동  (0) 2006.09.25
Posted by tornado
|