반응형

Key Code Reference Table

키코드값이 필요 해서 찾던 중에 찾았다.. ㅎㅎ 정리해 놓으면 유용할듯 하다.

매번 찾기는 귀찮으니 잘 포스팅 해놓자 ㅋㅋ

Key Pressed

Javascript Key Code

backspace

8

tab

9

enter

13

shift

16

ctrl

17

alt

18

pause/break

19

caps lock

20

escape

27

page up

33

page down

34

end

35

home

36

left arrow

37

up arrow

38

right arrow

39

down arrow

40

insert

45

delete

46

0

48

1

49

2

50

3

51

4

52

5

53

6

54

7

55

8

56

9

57

a

65

b

66

c

67

d

68

e

69

f

70

g

71

h

72

i

73

j

74

k

75

l

76

m

77

n

78

o

79

p

80

q

81

r

82

s

83

t

84

u

85

v

86

w

87

x

88

y

89

z

90

left window key

91

right window key

92

select key

93

numpad 0

96

numpad 1

97

numpad 2

98

numpad 3

99

numpad 4

100

numpad 5

101

numpad 6

102

numpad 7

103

numpad 8

104

numpad 9

105

multiply

106

add

107

subtract

109

decimal point

110

divide

111

f1

112

f2

113

f3

114

f4

115

f5

116

f6

117

f7

118

f8

119

f9

120

f10

121

f11

122

f12

123

num lock

144

scroll lock

145

semi-colon

186

equal sign

187

comma

188

dash

189

period

190

forward slash

191

grave accent

192

open bracket

219

back slash

220

close braket

221

single quote

222




<출처: http://protocolsofmatrix.blogspot.com/2007/09/javascript-keycode-reference-table-for.html >
반응형
Jar 파일에 리소스를 포함하여 배포하였을 경우 그 리소스에 접근하는 방법입니다.

예제코드:
package com.pmguda.resjar;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.sound.sampled.*;
import java.net.*;

public class JarResourceLoading extends JFrame
    implements ActionListener {

    JButton button;
    ImageIcon buttonIcon;
    Clip buhClip;

    public final static String SOUND_PATH = "res/gudaMid.wav";
    public final static String IMAGE_PATH = "res/gudaImage.jpg";

    public JarResourceLoading () {
        super ("Resources from .jar");
        // get image and make button
        URL imageURL = getClass().getClassLoader().getResource (IMAGE_PATH);
        System.out.println ("found image at " + imageURL);
        buttonIcon = new ImageIcon (imageURL);
        button = new JButton ("Click to Buh!", buttonIcon);
        button.setHorizontalTextPosition (SwingConstants.CENTER);
        button.setVerticalTextPosition (SwingConstants.BOTTOM);
        button.addActionListener (this);
        getContentPane().add (button);
        // load sound into Clip
        try {
            URL soundURL = getClass().getClassLoader().getResource (SOUND_PATH);
            System.out.println ("found sound at " + soundURL);
            Line.Info linfo = new Line.Info (Clip.class);
            Line line = AudioSystem.getLine (linfo);
            buhClip = (Clip) line;
            AudioInputStream ais = AudioSystem.getAudioInputStream(soundURL);
            buhClip.open(ais);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void actionPerformed (ActionEvent e) {
        System.out.println ("click!");
        if (buhClip != null) {
            buhClip.setFramePosition (0);
            buhClip.start();
        }
        else
            JOptionPane.showMessageDialog (this,
                                           "Couldn't load sound",
                                           "Error",
                                           JOptionPane.ERROR_MESSAGE);
    }

    public static final void main (String[] args) {
        JFrame frame = new JarResourceLoading();
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}
그림 1.


이클립스에서 jar 파일로 자동 배포 하였습니다. Jar 파일의 내부 구조도 이와 비슷하다.(압축을 풀어보면 알게된다.)

jar 파일안에 있는 이미지의 URL 은  Jar:file:/D:/resource.jar!/res/gudaImage.jpg

위의 코드에 대해 자세히 알아보고자 다른 자료를 찾아보았다.
다른 자료를 조금 인용하기 위해 긁어왔다.. 영문이다. ㅡㅡ;
해석해보면 그리 어렵지 않다. 위의 코드와 조금 다른 부분이 있을것이다. 잘 생각해 보자.


If you want to access a resource (configuration files, images, etc.) then you can certainly put it in a jar file, provided that jar file is in your classpath.

Then to access the resource, you can get a URL to it like this:
            URL url = this.getClass().getResource("/hello.jpg");
or you can get an InputStream to read it like this:
            InputStream is = this.getClass().getResourceAsStream("/app.properties");
Note that these methods will search for the resource in the directory tree relative to the package that "this" is in, so you will generally need the leading "/" to avoid that. But as for executable files in a jar file, forget it, there's no way to execute them from there. You can copy them out to a file and execute them from there, but that's the best you can do.


여기서 짚고 넘어가야 할 것은
패키지: com.pmguda.resjar
클래스: com.pmguda.resjar.JarResourceLoading
1.   getClass().getResource("gudaImage.jpg");
      현재 클래스의 위치에서 리소스를 찾는다
     클래스와 리소스의 위치가 같은 곳에 존재해야 한다.

2.   getClass().getResource("/res/gudaImage.jpg");
     패키지와 동일 루트에서 검색
3.   getClass().getClassLoader.getResource("res/gudaImage.jpg"); 
      패키지와 동일 루트에서의 상대 위치를 나타낸다.

java.lang.Class.getResource(String name)



번역이 완전하지가 않아 이해하기 어려울듯 하다.

java.lang.Class.getResource(String name)에서
name 가 "/gudaImage.jpg" 일 경우 절대 경로명(/gudaImage.jpg)으로 사용되고
"gudaImage.jpg" 일 경우 현 클래스의 위치에서 시작하는 상대경로가 되겠지요 이를
절대경로로
나타내면 (/com/pmguda/resjar/gudaImage.jpg)

java.lang.ClassLoader.getResource(String name)



1. getClass().getResource("/res/gudaImage.jpg"); 
2. getClass().getClassLoader.getResource("res/gudaImage.jpg"); 
동일한 URL을 리턴한다. 2번예시에서 앞에 "/" 을 넣어 시작하지 말도록 하자.
2번은 항상 상대경로만 인식하여 사용된다고 명심하시길..
ex)getClass().getClassLoader.getResource("/res/gudaImage.jpg");  

조금더 알아보고자 한다면 ClassLoader 에 대해 알아보는 것도 좋을듯 하다.
http://www.ibm.com/developerworks/kr/series/j-dclp.html?ca=dnn-krt-20071226

반응형

Java 6 update10 에서 윈도우 Frame 투명화가 가능해졌네요.

이리저리 찾아보고 있었는데 자료를 찾았습니다. ㅎㅎ

원래 투명하게 보이는걸 좋아해서.. 내가 만든 플램도 넣고 싶었는데..

Java 라서 안되는구나.. 했는데 드디어 지원한다니 ㅋㅋ

영문 자료입니다.. 즐프 하시길..^^

How to Create Translucent and Shaped Windows

http://java.sun.com/developer/technicalArticles/GUI/translucent_shaped_windows/

The article describes a feature that allows creating applications with translucent and shaped windows.

Contents
 
Introduction
Feature Overview
 
Translucent Windows
Shaped Windows
API Overview
Using the Feature
 
Determining the Support for a Desired Effect
Making a Window Translucent
 
Setting the Opacity Level of a Window
Enabling Per-Pixel Translucency
Setting the Opacity Level of a Window
Translucent and Shaped Windows Demo
Summary
 

JavaFX Script is a capable new language that offers a set of APIs for creating RIAs. It also provides you with access to the rich features of the the standard Java language. One of the major features introduced in the Java SE 6u10 release is the ability to create translucent and shaped windows. This includes:

  • making application windows translucent (tuning the general opacity of the window and using a per-pixel translucency effect)
  • setting shapes on application windows

This feature is available for objects of the java.awt.Window class and its descendants, for example javax.swing.JFrame, javax.swing.JFDialog, java.awt.Frame.

Translucent Windows
The translucent windows capability tunes the appearance of application windows using two different effects - simple translucency and per-pixel translucency. First, we will give an overview of the simple translucency effect. The simple translucency effect is used to make a window evenly translucent. When simple translucency is applied to a window, all the pixels of the window are assigned an alpha value which determines the level of opacity from the available range. The smaller the value, the more transparent the given window becomes. The minimum opacity level provides a completely transparent window, while the maximum opacity level represents a completely non-transparent (i.e. opaque) window. The following images demonstrate the use of the effect in four cases:

Dialog window without the effect applied Evenly translucent dialog window with opacity level 85%
Figure 1. Dialog window without the effect applied
Figure 2. Evenly translucent dialog window with opacity level 85%
Evenly translucent dialog window with opacity level 45% Evenly translucent dialog window with opacity level 25%
Figure 3. Evenly translucent dialog window with opacity level 45%
Figure 4. Evenly translucent dialog window with opacity level 25%
 

The screenshots are taken from the Translucent and Shaped Windows Demo. For details, see the Demo section. For more information about the effect and its use, see Setting the Opacity Level of a Window.

Another feature new to this release is the per-pixel translucency effect. Like simple translucency, per-pixel translucency can be used to make a window evenly translucent, though it is not recommended for performance reasons. However, it also enables you to control the opacity level of each individual pixel independently in order to make the window non-uniformly translucent or transparent. A good example of the use of the per-pixel effect is a gradient effect when the opacity "strength" of the window background increases from its top to the bottom. The following images show the per-pixel translucency effect in action for two cases:

The dialog window is evenly translucent using per-pixel alpha with 50% level
A gradient effect from fully translucent (upper left corner) to fully opaque
Figure 5. The dialog window is evenly translucent using per-pixel alpha with 50% level (note that the button remains opaque)
Figure 6. A gradient effect from fully translucent (upper left corner) to fully opaque (lower right corner) has been applied to the dialog window (note that the button remains opaque)
 

Note that when the per-pixel translucency effect is applied to make a window area transparent, the area may or may not remain clickable - this is a platform dependent behavior. For more information about the effect and its use, see Enabling Per-Pixel Translucency.

To sum up, the simple translucency effect is used to make a window evenly translucent or transparent, and the per-pixel translucency effect enables you to make a window evenly or non-uniformly translucent or transparent. Both the simple translucency and the per-pixel translucency can be used to make a window evenly translucent or transparent. However, when applied, the simple translucency effect consumes fewer system resources.

Shaped Windows
The other feature introduced in release 6u10 is the window shaping effect. Using shaping you can set any shape to an undecorated window. When the effect is applied, the desired area of a window becomes transparent. Thus, the combination of transparent and non-transparent pixels form the shape of a given window. The next images demonstrate window shaping in two cases:

Oval dialog window
Rounded rectangle dialog window
Figure 7. Oval dialog window
Figure 8. Rounded rectangle dialog window
 

Note that transparent areas of the window become unclickable. For more information about the effect and its use, see Setting the Shape of a Window.

These effects can be applied in combination. For example, you can create an oval shaped translucent window or a rounded rectangle window with the gradient effect applied:

Oval evenly translucent dialog window
Rounded rectangle dialog window with the gradient effect applied
Figure 9. Oval evenly translucent dialog window
Figure 10. Rounded rectangle dialog window with the gradient effect applied
 

Note that the effects may not be supported by the underlying platform (either because of hardware or software limitations or both). Therefore, before applying the effect, make sure that the platform supports it. For more details on system support, see Determining the Support for a Desired Effect.

The translucent and shaped windows feature is available through the new com.sun.awt.AWTUtilities class.

Note: the com.sun.awt.AWTUtilities class is not part of an officially supported API and appears as an implementation detail. The API is only meant for limited use outside of the core platform. It may change drastically between update releases, and it may even be removed or be moved in some other packages or classes. The class should be used via Java Reflection. Supported and public API will appear in the next major JDK release.

Method (* all the methods in the table are public and static)
Purpose
enum Translucency
Represents the kinds of translucency supported by the underlying system
boolean isTranslucencySupported(Translucency translucencyKind)
Returns if the given level of translucency is supported by the underlying system
void setWindowOpacity(Window window, float opacity)
Sets the opacity of a window
float getWindowOpacity(Window window)
Returns the opacity of a window
Shape getWindowShape(Window window)
Returns the shape of a window
void setWindowShape(Window window, Shape shape)
Sets the shape of a window
void setWindowOpaque(Window window, boolean isOpaque)
Enables the per-pixel translucency for a window
boolean isWindowOpaque(Window window)
Returns whether the window is opaque or translucent
boolean isTranslucencyCapable(GraphicsConfiguration gc)
Verifies whether a given graphics configuration supports the per-pixel translucency
 

Determining the Support for a Desired Effect
As already mentioned, the underlying system may not support the desired effect. That is why it is necessary to perform system support validation. The simple translucency and shaping effects require only general validation which indicates whether the system supports the effect in general.

To determine whether your system supports the effect, use the AWTUtilities.isTranslucencySupported() method passing a corresponding constant value as an argument. The constants PERPIXEL_TRANSPARENT, TRANSLUCENT, PERPIXEL_TRANSLUCENT represent shaping, simple translucency, and per-pixel translucency respectively. The next example shows how to determine whether your system supports simple translucency:

if (AWTUtilities.isTranslucencySupported(AWTUtilities.Translucency.TRANSLUCENT) {
      //perform translucency operations here
}
 

The per-pixel translucency also requires a window be created using a compatible graphics configuration. To check whether the given graphics configuration supports the per-pixel translucency effect use the isTranslucencyCapable() method. The following example shows how to determine whether the default graphics configuration supports per-pixel translucency:

if ((AWTUtilities.isTranslucencySupported(AWTUtilities.Translucency.PERPIXEL_TRANSLUCENT)) &&
      (AWTUtilities.isTranslucencyCapable(defaultTranslucencyCapableGC))) {
      //perform translucency operations here
}
 

In case the default graphics configuration is not per-pixel translucency capable, you can go through all available graphics configurations and find one capable of translucency. Use the following code snippet:

GraphicsEnvironment env =
           GraphicsEnvironment.getLocalGraphicsEnvironment();
       GraphicsDevice[] devices = env.getScreenDevices();

     for (int i = 0; i < devices.length && translucencyCapableGC == null; i++) {          GraphicsConfiguration[] configs = devices[i].getConfigurations();          for (int j = 0; j < configs.length && translucencyCapableGC == null; j++) {              if (AWTUtilities.isTranslucencyCapable(configs[j])) {                  translucencyCapableGC = configs[j];              }          }      }

 

Once it has been determined that the system supports the desired effect, you can proceed to apply it to your top-level windows.

Making a Window Translucent
Setting the Opacity Level of a Window
The general opacity level of the application window is controlled by the the setWindowOpacity method. This method takes window and opacity variables as arguments. The window argument defines the window to apply the effect to. This argument must be an instance of the java.awt.Window class or its descendant, such as javax.swing.JFrame. The opacity argument is responsible for the level of opacity of the window. The lower its value, the more transparent the window becomes. The range of allowed values is [0f ; 1f]. If you set the value to 0f, the window becomes completely transparent (i.e. invisible). If the value is set to 1f, then the window becomes completely opaque (which is equal to a case when the effect is not applied at all). If the opacity level value is out of the range, it throws an IllegalArgumentException. Note that the effect can not be applied to full-screen windows. If you are in full screen windows mode and the opacity value is lower than 1f, you will get an IllegalArgumentException.

The following code snippet shows how to set the opacity level for your window. To make the window translucent, the example uses the setWindowOpacity method via Java Reflection, passing window and 0.75f as arguments. Window is an instance of the JFrame class, 0.75f is the value of the translucency.

Note that all the examples from this article that use the AWTUtilities class should be implemented via Java Reflection API.

try {
   Class<?> awtUtilitiesClass = Class.forName("com.sun.awt.AWTUtilities");
   Method mSetWindowOpacity = awtUtilitiesClass.getMethod("setWindowOpacity", Window.class, float.class);
   mSetWindowOpacity.invoke(null, window, Float.valueOf(0.75f));
} catch (NoSuchMethodException ex) {
   ex.printStackTrace();
} catch (SecurityException ex) {
   ex.printStackTrace();
} catch (ClassNotFoundException ex) {
   ex.printStackTrace();
} catch (IllegalAccessException ex) {
   ex.printStackTrace();
} catch (IllegalArgumentException ex) {
   ex.printStackTrace();
} catch (InvocationTargetException ex) {
   ex.printStackTrace();
}
 

When applied, the method makes the frame translucent with a 75% level of opacity.

To get the current opacity of a window, use the getWindowOpacity method passing a window object as its argument. If the opacity level has not yet been set, this method returns 1.0f. In case the method returns 0f, the window is completely transparent. The next code snippet shows how to get the current level of opacity of a window:

float opacity = AWTUtilities.getWindowOpacity(frame);
 

Enabling Per-Pixel Translucency
The setWindowOpaque method is used to enable per-pixel alpha support for the given window. The method takes the window and isOpaque variables as arguments. The window argument defines the window you apply the effect to. Note that the argument must represent a window created using an effect compatible graphics configuration. For more information on graphics configurations, see Determining the Support for a Desired Effect. Also note that the window must not be in full-screen mode when making it non-opaque, or an IllegalArgumentException is thrown.

The isOpaque parameter defines whether the window must be opaque (true), or translucent (false). Once the window becomes non-opaque (the isOpaque is set to false), the drawing sub-system starts to respect the alpha value of each individual pixel. If a pixel gets painted with an alpha color component equal to zero, it becomes visually transparent; if the alpha of the pixel is equal to 255, the pixel is fully opaque. Interim values of the alpha color component make the pixel semi-transparent (i.e. translucent). The following code snippet shows how to enable the per-pixel alpha support for your window.

AWTUtilities.setWindowOpaque(frame, false);
 

If invoking the getWarningString on the window object returns a non-null String, this method will not affect the opacity of the window.

The following code snippet shows how to achieve the gradient effect. It is done by defining the parameters of the JPanel component using the GradientPaint method:

jPanel1 = new javax.swing.JPanel() {
      protected void paintComponent(Graphics g) {
          if (g instanceof Graphics2D) {
              final int R = 240;
              final int G = 240;
              final int B = 240; 

            Paint p =             new GradientPaint(0.0f, 0.0f, new Color(R, G, B, 0),                 getWidth(), getHeight(), new Color(R, G, B, 255), true);             Graphics2D g2d = (Graphics2D)g;             g2d.setPaint(p);             g2d.fillRect(0, 0, getWidth(), getHeight());      } else {     super.paintComponent(g);      }    }  }

 

Then the component should be placed on the frame:

frame.add(jPanel1);
 

Setting the Shape of a Window
To apply a shape to a window use the setWindowShape method. The method uses the window argument to define the window you want to set the shape to. Additionally, it uses the shape argument to define the desired shape. The shape can be any instance of the java.awt.Shape interface, for example, Ellipse2D.Float or RoundRectangle2D.Float. The next code snippet shows how to set an oval shape on your window. In the example, the fd argument represents the JFrame window, Ellipse2D.Float creates a new instance of an Ellipse2D object that defines the shape of the window:

fd.addComponentListener(new ComponentAdapter() {
     @Override
     public void componentResized(ComponentEvent evt) {
       Shape shape = null;
       shape = new Ellipse2D.Float(0, 0, fd.getWidth(), fd.getHeight());
       AWTUtilities.setWindowShape(fd, shape);
     }
});
 

It is recommended to set the shape using the componentResized() method as this enables precise control of the shape according to the current size of the window.

When setting the shape on your window, note that the effect supports only undecorated windows. If your window is decorated and you apply the effect, you will get the original shape of the window without the effect applied to it. If the window has been created by untrusted code (i.e. the window has a non-null warning string returned by getWarningString()), the method returns without affecting the shape of the window. Also note that the window must not be in the full-screen mode when setting a non-null shape. Otherwise, an IllegalArgumentException is thrown.

To get the current value of the shape of a window, use the getWindowShape method passing a window as an argument. The getWindowShape method returns an object that implements the shape interface and represents the shape previously set . If no shape has been set yet, or the shape has been reset to null, this method returns null. In other words, the default rectangular shape is displayed when the null argument is passed. The following code demonstrates how to get the current shape of the window:

Shape currentShape = AWTUtilities.getWindowShape(frame);
 

You can see the translucency and shape features in action by running the "TranslucencyShapeDemo" example. Click the Launch button to run Demo using Java Web Start. Note that in order to start the demo you must have JDK 6u10 or later installed and properly configured on your machine. You can download release 6u10 at the java.sun.com download page.

The application enables you to choose a desired effect or a combination of effects and apply it to an undecorated dialog window. The application interface contains the following elements: a slidebar to set the level of constant alpha for the simple translucency effect from the range [0% ; 100%], three radio buttons to set the shape of a window - rectangular, with rounded corners, or oval, a check box to enable or disable the per-pixel gradient effect, Paint Gradient check box to switch the per-pixel gradient effect on and off, Display/Hide the frame and Close the Application buttons. Once the settings are defined, click the Display the frame button to display the dialog window with the desired effect applied. Note that you can also change the effect spontaneously. To do so, choose an effect type when the window is displayed, the window will automatically switch its view. The dialog window itself contains the Reshape Me button. When clicked, the window randomly changes its size and location on the desktop. To hide the dialog window, click Hide the frame, to close the application, click Close the Application button.

Launches the TranslucentShapes application

You can find the entire code for this program in ControlFrame.java, FancyFrame.java, Main.java, and AWTUtilitiesWrapper.java, all of which are packed in the TranslucentShapes NetBeans project. Note that the application uses the Java Reflection API. The Reflection mechanism is implemented through the AWTUtilitiesWrapper class. You can download the TransclucentShapes NetBeans project as a zip file.

This article provides a description of the translucent and shaped windows feature. It includes an overview, discusses the feature API, and offers practical examples. The demo attached to the article shows the use of each featured effect individually as well as the use of the effects in combination.

반응형

http://www.sdnkorea.com/

썬 테크 블로거를 신청하였습니다.

자주 방문하는 사이트기도 하고 자바관련 자료도 블로그에 주를 이루고 있기 때문에 신청했습니다.

썬 메일링도 자주 블로그에 포스팅 하고 있구요.. 나름 썬매냐 기 때문에 ㅎㅎ

갠적으로 http://blog.sdnkorea.com/blog/  여기에 들어가서 JavaSE에 들어가서

재밌어 보이는 기술자료 있으면 적용해 보는 편입니다.

흥미유발 자료가 많은것 같아서.. 저한테는 말이죠.. ㅎㅎ

므튼 썬 테크 블로거로 화이팅!

반응형
FTP? 자바?

FTP는 요즘 같은 인터넷 세상에서 빠지지 않는 프로토콜이다. FTP가 무엇인지 잘 모른다면 다음을 참고하자.
FTP (File Transfer Protocol) ; 파일 전송 프로토콜

FTP[에프 티 피]는 인터넷상의 컴퓨터들간에 파일을 교환하기 위한 표준 프로토콜로서 가장 간단한 방법이기도 하다. 화면에 표시할 수 있는 웹 페이지와 관련 파일들을 전송하는 HTTP (Hypertext Transfer Protocol), 전자우편을 전송하는 SMTP (Simple Mail Transfer Protocol)등과 같이, FTP도 역시 인터넷의 TCP/IP 응용 프로토콜 중의 하나이다. FTP는 웹 페이지 파일들을 인터넷상에서 모든 사람이 볼 수 있도록 하기 위해 저작자의 컴퓨터로부터 서버로 옮기는 과정에서 사용된다. 또한, 다른 서버들로부터 자신의 컴퓨터로 프로그램이나 파일들을 다운로드 하는 데에도 많이 사용된다.

사용자 입장에서는 간단한 명령어를 통하여 FTP를 쓰거나, 또는 그래픽 사용자 인터페이스를 제공하는 상용 프로그램을 쓸 수도 있다. 보통은 웹 브라우저도 웹 페이지로부터 선택한 프로그램을 다운로드 하는데 FTP를 사용한다. FTP를 사용하여 서버에 있는 파일을 지우거나 이름을 바꾸거나 옮기거나 복사하는 등 갱신작업을 할 수도 있다. FTP 서버에는 로그온을 해야 하지만, 익명의 FTP를 사용하여 모든 사람들에게 공개된 파일들을 쉽게 접근할 수 있도록 하고 있다.

FTP는 보통 TCP/IP에 함께 딸려오는 일련의 프로그램 속에 포함되어 있다.
간단히 말해서 FTP는 파일 전송 프로토콜이다. 우리는 FTP라는 프로토콜을 알게 모르게 많이 사용하고 있다. 회사 동료들 사이에 문서를 주고 받거나, 친구들과 음악 파일, 동영상 등을 주고 받는데 항상 사용하고 있는 것이다. 일반 컴퓨터 사용자들은 프로토콜이니 그런 것에는 관심 없을 것이다. 내가 원하는 파일을 주고 받기만 하면 될 뿐이니까… 그래도 FTP를 사용하기 위해서는 기본 명령을 알아야 한다. 하지만 이런 기본 명령 조차도 귀찮을 다름이다.

FTP 클라이언트 프로그램을 사용하면 FTP 명령을 알지 못하는 사람들도 GUI 환경에서 쉽게 FTP 서버에 접속해서 원하는 파일들을 주고 받을 수 있다. 일반적으로 많이 사용되는 FTP 클라이언트 프로그램으로는 WS_FTP, CuteFTP, 알FTP 등이 있다. 그렇다면 과연 누가 이런 FTP 클라이언트 프로그램을 만드는가? 당연히 개발자의 몫이다. 그럼 또한 자바로는 가능한가. 당연히 자바로도 가능하다. 원래 자바라는 언어 자체가 네트워크 분야에서 강력한 힘을 발휘한다고 하지 않는가? 이제부터 우리는 자바로 FTP 클라이언트 프로그램을 개발해 볼 것이다. 물론 다른 상용 프로그램처럼 훌륭한 GUI를 지원하는 프로그램은 아니다. 콘솔에서 작동하는 “Hello FTP”를 개발할 것이다. “에이, GUI가 없다면 썰렁할텐데…” 물론 이렇게 생각하는 분들도 있을 것이다. 하지만 모든 프로그램은 항상 “Hello”로부터 시작되므로 무시해서는 안될 것이다. 화려한 GUI 개발은 여러분들이 직접 해보시길 바란다. 아마 쉽지 않은 작업이 분명할 듯…

무엇이 필요한가?

당연히 자바로 개발하기 위해서는 JDK가 있어야 한다. JDK를 구하고 설치하는 것은 다른 자바 기초 서적을 참고하기 바란다.

자바만으로도 FTP 관련 프로그램을 만들 수 는 있다. sun.net.ftp 패키지에 보면 FTP 클라이언트 구현을 위한 클래스들이 있다. 하지만 필자가 프로젝트를 하면서 이 패키지를 사용해 보았는데, 몇몇 기능이 원하는 기능을 지원하지 않는 것을 알게 되었다. 그리고 썬사의 문서를 참고하면 sun으로 시작되는 패키지는 사용하지 말라고 권하고 있다.

아… 그렇다면 어찌해야 한단 말인가?
FTP 프로토콜을 지원하는 모든 기능을 다 구현해야 한다는 말인가? 충분한 시간과 실력이 된다면 그것도 좋은 방법이다. 일단 실력은 둘째 치고라도 우리에게는 충분한 시간이 없다. 이럴 때 도움을 받을 수 있는 수 많은 오픈 소스들과 공짜 패키지 들이 있지 않은가? 비겁하고 치사하다고 생각할 필요는 없다고 생각하자. 어차피 우리는 생활에 필요한 대부분의 것을 남이 만든 것을 사다 쓰고 있는 현실이니…

http://www.savarese.org/java/index.html에 가면 NetComponents에 대한 설명이 있다. 자세한 것은 읽어보면 알겠지만 소스 코드까지 무료로 사용할 수 있다. 우리는 이것을 사용할 것이다. http://www.savarese.org/downloads/NetComponents/에서 다운로드 받으면 된다. 필자는 NetComponents-1.3.8-bin.zip 파일을 다운로드 받아서 압축을 풀었다. 여러 폴더와 파일들이 있다. 필자는 윈도우를 사용하고 있다. 혹시 다른 운영체제를 사용한다면 문서들을 살펴보길 바란다.

NetComponents.jar 파일을 클래스패스에 추가하자. 클래스패스에 추가하는 방법을 모르는 분들은 다른 자바 기초 서적을 참고하시길… Doc 폴더에는 API 도움말이 있고 examples 폴더에는 여러 예제가 있다. 눈치 빠른 개발자들이라면 예제 파일을 본 후에 NetComponents가 아주 많은 프로토콜을 지원한다는 것을 쉽게 예상 할 수 있을 것이다. 공짜로 사용하는 것 치고는 아주 많은 기능을 제공한다. 여유가 되는 분들은 다른 기능도 사용해보고 이에 대한 기사 올려준다면 다른 개발자들에게 큰 힘이 될 것이 분명하다. 물론 예제에는 FTP도 포함되어 있으며(ftp.java) 본 기사에서도 이 예제를 참고할 것이다.

어떤 기능을 개발할 것인가?

프로그램을 개발하기 위해서는 어떤 것을 개발할 것인지, 어떤 기능을 수행해야 하는지를 명확히 알아야 한다. 이런 것들을 소프트웨어 공학에서는 “요구 사항” 이라고 한다. 요구 사항이 명확히 정의 되지 않으면 개발 도중에 많은 실수를 반복하고 기간이 늘어나기 쉽상이지만 우리가 개발할 프로그램의 요구 사항은 아래와 같이 간단하다.
  • FTP 서버에 접속한다.
  • 정해진 디렉토리로 이동한다.
  • 디렉토리 내의 사이즈가 0보다 큰 모든 로그 파일들을 가져온다.
혹시 다른 기능이 더 필요하다면 API 도움말을 참고하면 된다. 적절한 클래스와 메소드들을 사용해서 상용 FTP 클라이언트 프로그램들이 제공하는 기능은 대부부분 구현이 가능하다.

소스코드

코드 자체는 그리 어려운 부분이 없으므로 따로 설명이 필요할 것이 없다. 기능 자체가 워낙 간단해서인가? 여러분들은 그저 중간에 간단히 적힌 주석 부분만 참고하면 될 것이다. 컴파일을 하고 실행을 하면 화면에서는 나타나는 것이 없지만 실제로 파일이 전송된다. 여러분도 적절히 수정을 하여 원하는 파일들을 서버로부터 전송 받을 수 있을 것이다.
import java.io.*;

import com.oroinc.net.ftp.*;
import com.oroinc.net.*;

public class MyFtpClient {
    static String server = "xxxxx";
    static int port = 21;
    static String id = "xxxxx";
    static String password = "xxxxx";
    FTPClient ftpClient;

    public MyFtpClient(String server, int port, String id, String password) {
        this.server = server;
        this.port = port;
        ftpClient = new FTPClient();
    }

    public static void main(String args[]) {
        MyFtpClient ftp = new MyFtpClient(server, port, id, password);
        ftp.connect();
        ftp.login(ftp.id, ftp.password);
        // 로그파일이 있는 디렉토리로 이동한다
        ftp.cd("/home/ems/emsprj/project/wos/WosLog/log");
        FTPFile[] files = ftp.list();
        for (int i = 0; i < files.length ; i++) {
            String fileName = files[i].getName();
            // 파일 이름에서 확장자만 추출
            String extension = fileName.substring(fileName.lastIndexOf(".") + 1);
            long size = files[i].getSize();
            // 파일 사이즈가 0보다 크고 로그 파일만 가져온다
            if ( (size > 0) && (extension.equalsIgnoreCase("log")) ) {
                File file = ftp.get(fileName, fileName);
            }
        }
        ftp.logout();
        ftp.disconnect();
        System.exit(1);
    }

    // 계정과 패스워드로 로그인
    public boolean login(String user, String password) {
        try {
            this.connect();
            return ftpClient.login(user, password);
        }
        catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return false;
    }

    // 서버로부터 로그아웃
    private boolean logout() {
        try {
            return ftpClient.logout();
        }
        catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return false;
    }

    // 서버로 연결
    public void connect() {
        try {
            ftpClient.connect(server, port);
            int reply;
            // 연결 시도후, 성공했는지 응답 코드 확인
            reply = ftpClient.getReplyCode();
            if(!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                System.err.println("서버로부터 연결을 거부당했습니다");
                System.exit(1);
            }
        }
        catch (IOException ioe) {
            if(ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch(IOException f) {
                    //
                }
            }
            System.err.println("서버에 연결할 수 없습니다");
            System.exit(1);
        }
    }

    // FTP의 ls 명령, 모든 파일 리스트를 가져온다
    public FTPFile[] list() {
        FTPFile[] files = null;
        try {
            files = this.ftpClient.listFiles();
            return files;
        }
        catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return null;
    }

    // 파일을 전송 받는다
    public File get(String source, String target) {
        OutputStream output = null;
        try {
            File local = new File(source);
            output = new FileOutputStream(local);
        }
        catch (FileNotFoundException fnfe) {
            fnfe.printStackTrace();
        }
        File file = new File(source);
        try {
            if (ftpClient.retrieveFile(source, output)) {
                return file;
            }
        }
        catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return null;
    }

    // 서버 디렉토리 이동
    public void cd(String path) {
        try {
            ftpClient.changeWorkingDirectory(path);
        }
        catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    // 서버로부터 연결을 닫는다
    private void disconnect() {
        try {
            ftpClient.disconnect();
        }
        catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

}
참고문헌


반응형
basicplayer 를 사용하려고 테스트하던 중에 다음과 같은 에러가 났다.

java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory

commons-logging.jar 라이브러리를 추가해주면 된다.

http://commons.apache.org/downloads/download_logging.cgi

다운받아서 추가해주자..
반응형
1. 첫번째 방법


2. 두번째 방법
반응형
반응형
달송
http://blog.naver.com/drub5?Redirect=Log&logNo=130033212540
알송을 Java로 만든거라고 합니다.


자테온
http://blog.kfmes.com/category/JaTeOn
네이트온을 Java로 만든것입니다.


다들 개발자분들이 자작하신 프로그램입니다.
반응형
자바웹스타트 응용 시스템을 만들다 보면 때로는 클레스와 함께 jar 화일에 묶여있는 이미지 화일이나 프로퍼티 화일, 자료 화일 등이 필요할 경우가 있다.  이러한 경우에는 java.lang.ClassLoader로 부터 해당 자원을 얻을 수 있다. 

다음은 jar화일에 묶여있는 이미지 화일로부터 Icon 객체를 생성해내는 예제이다.

ClassLoader loader = this.getClass().getClassLoader();
Icon myIcon = new ImageIcon(loader.getResource("imgs/myImg.gif"));

이 밖에도 java.lang.ClassLoader의 getResourceAsStream(String name) 메소드를 이용하면 다양한 자원을 InputStream을 통하여 얻을 수 있다.

  
  자바웹스타트 환경에서는 Java 2 SE API에서 제공하지 않는 추가적인 기능을 하는 API를 제공한다. 이것은 JNLP API라고 한다. JNLP API를 이용하여 개발할 경우는 jnlp.jar가 필요한데 이러한 파일은 JNLP Developer's Pack에 포함 되어 있다. 다음은 Developer's Pack을 다운로드 할 수 있는 URL이다.

http://java.sun.com/products/javawebstart/download-jnlp.html

  JNLP API가 추가적으로 제공하는 클레스는 javax.jnlp package로 묶여 있으며 BasicService, ClipboardService, DownloadService, FileOpenService, FileSaveService,  PrintService, PersistenceService 등이 있는데 이들은 ServiceManager 클레스를 통하여 사용할 수 있다. 각각의 기능은 다음과 같다.



- javax.jnlp.BasicService
BasicService는 웹스타트의 환경적인 면이나 브라우져를 통제하기 위한 API를 제공하는데 자바 애플릿의 경우 AppletContext와 비슷한 역할을 한다. 다음 예제는 웹스타트 환경에서 웹브라우져로하여금 특정 URL로 가도록 하는 것이다.

import javax.jnlp.*;
.....

BasicService bs = (BasicService)ServiceManager.lookup("javax.jnlp.BasicService");
bs.showDocument(new URL("http://www.javanuri.com"));

- javax.jnlp.ClipboardService
ClipboardService는 시스템에서 사용하는 클립보드에서 복사 객체를 가져오거나 클립보드로 복사하는 서비스를 제공한다. 자바웹스타트는 이 기능을 사용할 때 보안을 위하여 경고창을 보여준다. 다음은 간단한 스트링을 클립보드에 복사하는 예제이다.

import javax.jnlp.*;
.............

ClipboardService cs = (ClipboardService)ServiceManager.lookup("javax.jnlp.ClipboardService");
StringSelection ss = new StringSelection("Hello Web Start");
cs.setContents(ss);

- javax.jnlp.DownloadService
DownloadService는 자신의 자원을 Cache에 저장, 삭제등 Cache를 통제할 수 있는 서비스 API를 제공하는 클레스이다. 다음은 myapp.jar를 Cache에서 확인하고 있으면 삭제한후 다시 Cache에 저장하는 예제이다.

import javax.jnlp.*;
...........

DownloadServicd ds = (DownloadService)ServiceManager.lookup("javax.jnlp.DownloadService");
URL url = new URL("http://www.javanuri.com/jws/myapp.jar");
boolean isCached = ds.isResourceCached(url, "1.0");
if(isCached) {
ds.removeResource(url, "1.0");
}

DownloadServiceListener dsl = ds.getDefaultProgressWindow();
ds.loadResource(url, "1.0", dsl);

- javax.jnlp.FileOpenService
FileOpenService는 권한이 제약된 환경에서도 이를 사용자에게 알리고 화일을 열 수 있는 다이얼로그 윈도우를 열어주는 서비스이다.  다음 예제는 FileOpenService를 이용하여 화일을 여는 예제이다.

import javax.jnlp.*;
..............

FileOpenService fo = (FileOpenService)ServiceManager.lookup("javax.jnlp.FileOpenService");
FileContents fc = fo.openFileDialog(null, null);

- javax.jnlp.FileSaveService
FileSaveService는 권한이 제약된 환경에서도 local disk에 화일을 저장할 수 있는 기능을 제공하는 서비스 클레스이다. 이는 FileOpenService의 경우와 반대인 기능을 제공하는 클레스이다.  다음은 FileOpenService를 이용하여 화일을 연 후에 FileSaveService를 이용하여 화일을 저장하는 예제이다.

import javax.jnlp.*;
...................
..

FileOpenService fo = (FileOpenService)ServiceManager.lookup("javax.jnlp.FileOpenService");
FileContents fc = fo.openFileDialog(null, null);
FileContents newfc =
fss.saveFileDialog(null, null, fc.getInputStream(), "newfile.txt");

- javax.jnlp.PrintService

PrintService는 권한이 제약된 웹스타트 환경에서도 프린트를 가능하게 해주는 API 를 갖고 있는 서비스 클레스이다.  이 API를 이용하여 프린트를 요청하면 사용자에게 허가할 것인가를 묻는 다이얼로그가 나타난다. 다음은 PrintService를 이용한 프린트 요청 예제이다.

import javax.jnlp.*;
.....................

PrintService ps = (PrintService)ServiceManager.lookup("javax.jnlp.PrintService");

// default page format
PageFormat pf = ps.getDefaultPage();

// customizing page format
PageFormat npf = ps.showPageFormatDialog(pf);

// print
ps.print(new Doc());


// printable class
class Doc implements Printable {
....
public int print(Graphics g, PageFormat fm, int idx) {
....
}
}
}

- javax.jnlp.PersistenceService

PersistenceService는 브라우져의 쿠키와 마찬가지고 사용자의 클라이언트에 간단한 자료를 저장할 때 사용된다. 저장되는 형태는 url형태로 자장된다.
다음은 간단한 url을 저장하고 내용을 읽어들이는 예제이다.

import javax.jnlp.*;
.....................

PersistenceService ps = (PersistenceService)ServiceManager.lookup("javax.jnlp.PersistenceService");

String addr = "www.javanuri.com/some.txt";
java.net.URL = new URL(addr);

// create
ps.create(url, 1024);
FileContents fc = ps.get(url);
OutputStream os = fc.getOutputStream(false);
os.write(...);

// read
fc = ps.get(url);
InputStream in = fc.getInputStream();

in.read(...);

.......

- javax.jnlp.FileContents

FileContents 는 FileOpenService, FileSaveService, PersistenceService와 같은 서비스에서  input과 output을 처리할 수 있도록 만들어진 클레스이다. 일반적인 File 클레스와 비슷하게 생각하면 된다.  보안과 자료 저장 형태 등이 일반 File 클레스와는 다르다.

+ Recent posts