패키지 컴파일러

 | JAVA
2012. 5. 15. 18:37
  • 패키지 컴파일 방법
  1.  cmd> java -classpath classes;. com.example.model.BeerExpert

    - -classpath classes;. --> 뒤에 나올 클래스의 위치

    - com.example.model 은 classpath을 루트로 했을때 순서대로 있어야할 디렉토리(패키지는 디렉토리임)

 

Collection Class Sorting

  1. public class Pnode {
        private int start;
        private int end;
        private int max_vd_idx;
        private double max_vd_value;

        static public class PnodeComparator implements Comparator<Pnode>{

            public int compare(Pnode o1, Pnode o2) {
                return o1.start - o2.start;
            }

        }

    static void Main(String args[]){

  2. /* split_queue : list of pnodes */

  3. Collections.sort(split_queue, new Pnode.PnodeComparator());

  4. }

    }

이 글은 스프링노트에서 작성되었습니다.

Posted by 사라링

자바로 컴퓨터 종료

 | JAVA
2012. 5. 15. 18:36

 

import java.io.IOException;
import java.io.OutputStream;

public class Deepak {
 
 public static void main(String[] args) throws InterruptedException {
  Runtime runtime = Runtime.getRuntime();
  try {
   Process process = runtime.exec("C:\\WINDOWS\\system32\\cmd.exe");
   OutputStream os = process.getOutputStream();
   os.write("shutdown -s -f -t 90 \n\r".getBytes());
   os.close();
   process.waitFor();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

 

 

이 글은 스프링노트에서 작성되었습니다.

'JAVA' 카테고리의 다른 글

Swing - windowBuilder 설치 하기.  (0) 2012.06.13
패키지 컴파일러  (0) 2012.05.15
자바( 스크립트 사용 하여 리턴값 받기)  (0) 2012.05.15
어트리뷰트(애플릿)  (0) 2012.05.15
실시간 파일 변경 알림  (0) 2012.05.15
Posted by 사라링

 import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
 
public class RunJavaScript {
  public static void main(String args[]) {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("javascript");
    try {
      Double hour = (Doubleengine.eval("var date = new Date();" "date.getHours();");
      String msg;
      if (hour < 10) {
        msg = "Good morning";
      else if (hour < 16) {
        msg = "Good afternoon";
      else if (hour < 20) {
        msg = "Good evening";
      else {
        msg = "Good night";
      }
      System.out.println(hour);
      System.out.println(msg);
    catch (ScriptException e) {
      System.err.println(e);
    }
  }
}

이 글은 스프링노트에서 작성되었습니다.

'JAVA' 카테고리의 다른 글

패키지 컴파일러  (0) 2012.05.15
자바로 컴퓨터 종료  (0) 2012.05.15
어트리뷰트(애플릿)  (0) 2012.05.15
실시간 파일 변경 알림  (0) 2012.05.15
간단 수식계산기  (0) 2012.05.15
Posted by 사라링

어트리뷰트(애플릿)

 | JAVA
2012. 5. 15. 18:36

 

// AttribStringDemo.java

import java.applet.Applet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import java.awt.font.TextAttribute;

import java.text.AttributedString;

public class AttribStringDemo extends Applet
{
   AttributedString as;

   public void init()
   {
      as = new AttributedString("An AttributedString holds text and related "+
                                "attribute information.");
      as.addAttribute(TextAttribute.FONT,
                      new Font("Courier New"Font.BOLD, 12), 319);
      as.addAttribute(TextAttribute.FOREGROUND, Color.BLUE, 319);
   }

   public void paint(Graphics g)
   {
      if (as != null)
      {
         ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                           RenderingHints.VALUE_ANTIALIAS_ON);
         g.drawString(as.getIterator(), 3030);
      }
   }
}




이 글은 스프링노트에서 작성되었습니다.

'JAVA' 카테고리의 다른 글

자바로 컴퓨터 종료  (0) 2012.05.15
자바( 스크립트 사용 하여 리턴값 받기)  (0) 2012.05.15
실시간 파일 변경 알림  (0) 2012.05.15
간단 수식계산기  (0) 2012.05.15
String(문자열)내의 한글 확인  (0) 2012.05.15
Posted by 사라링

실시간 파일 변경 알림

 | JAVA
2012. 5. 15. 18:36

 테스트 파일 변경 소스 .

How to write Java code to listen runtime changes in text file

 
I had a requirement to write a java code to listen continues changing text file.i have used following code to do that.

public void listenServer() throws IOException {
Reader fileReader = new FileReader("/home/chamara/server.log");
BufferedReader input = new BufferedReader(fileReader);
String line = null;
while (true) {
if ((line = input.readLine()) != null) {
System.out.println(line);
continue;
}
try {
Thread.sleep(1000L);
} catch (InterruptedException x) {
Thread.currentThread().interrupt();
break;
}
}
input.close();
return isException;
}

이 글은 스프링노트에서 작성되었습니다.

'JAVA' 카테고리의 다른 글

자바( 스크립트 사용 하여 리턴값 받기)  (0) 2012.05.15
어트리뷰트(애플릿)  (0) 2012.05.15
간단 수식계산기  (0) 2012.05.15
String(문자열)내의 한글 확인  (0) 2012.05.15
Socket Simple 채팅 프로그램  (0) 2012.05.15
Posted by 사라링

간단 수식계산기

 | JAVA
2012. 5. 15. 18:35
Parse postfix arithmetic expressions
 
Parse
 
import java.io.IOException;
 
public class ParsePost {
  private Stack theStack;
 
  private String input;
 
  public ParsePost(String s) {
    input = s;
  }
 
  public int doParse() {
    theStack = new Stack(20);
    char ch;
    int j;
    int num1, num2, interAns;
 
    for (j = 0; j < input.length(); j++) {
      ch = input.charAt(j)
      theStack.displayStack("" + ch + " ");
      if (ch >= '0' && ch <= '9'// if a number push it
        theStack.push((int) (ch - '0'));   
      else // it's an operator
      {
        num2 = theStack.pop();
        num1 = theStack.pop();
        switch (ch) {
        case '+':
          interAns = num1 + num2;
          break;
        case '-':
          interAns = num1 - num2;
          break;
        case '*':
          interAns = num1 * num2;
          break;
        case '/':
          interAns = num1 / num2;
          break;
        default:
          interAns = 0;
        }
        theStack.push(interAns);
      }
    }
    interAns = theStack.pop();
    return interAns;
  }
 
  public static void main(String[] argsthrows IOException {
    String input = "1-2+3*4+5/6-7+8*9";
    int output;
    ParsePost aParser = new ParsePost(input);
    output = aParser.doParse();
    System.out.println("Evaluates to " + output);
  }
  class Stack {
    private int maxSize;
  
    private int[] stackArray;
  
    private int top;
  
    public Stack(int size) {
      maxSize = size;
      stackArray = new int[maxSize];
      top = -1;
    }
  
    public void push(int j) {
      stackArray[++top= j;
    }
  
    public int pop() {
      return stackArray[top--];
    }
  
    public int peek() {
      return stackArray[top];
    }
  
    public boolean isEmpty() {
      return (top == -1);
    }
  
    public boolean isFull() {
      return (top == maxSize - 1);
    }
  
    public int size() {
      return top + 1;
    }
  
    public int peekN(int n) {
      return stackArray[n];
    }
  
    public void displayStack(String s) {
      System.out.print(s);
      System.out.print("Stack (bottom>top): ");
      for (int j = 0; j < size(); j++) {
        System.out.print(peekN(j));
        System.out.print(' ');
      }
      System.out.println("");
    }
  }
}
 

 출처: http://www.java2s.com/Code/Java/Collections-Data-Structure/Parsepostfixarithmeticexpressions.htm

Parse postfix arithmetic expressions
 
Parse
 
import java.io.IOException;
 
public class ParsePost {
  private Stack theStack;
 
  private String input;
 
  public ParsePost(String s) {
    input = s;
  }
 
  public int doParse() {
    theStack = new Stack(20);
    char ch;
    int j;
    int num1, num2, interAns;
 
    for (j = 0; j < input.length(); j++) {
      ch = input.charAt(j)
      theStack.displayStack("" + ch + " ");
      if (ch >= '0' && ch <= '9'// if a number push it
        theStack.push((int) (ch - '0'));   
      else // it's an operator
      {
        num2 = theStack.pop();
        num1 = theStack.pop();
        switch (ch) {
        case '+':
          interAns = num1 + num2;
          break;
        case '-':
          interAns = num1 - num2;
          break;
        case '*':
          interAns = num1 * num2;
          break;
        case '/':
          interAns = num1 / num2;
          break;
        default:
          interAns = 0;
        }
        theStack.push(interAns);
      }
    }
    interAns = theStack.pop();
    return interAns;
  }
 
  public static void main(String[] argsthrows IOException {
    String input = "1-2+3*4+5/6-7+8*9";
    int output;
    ParsePost aParser = new ParsePost(input);
    output = aParser.doParse();
    System.out.println("Evaluates to " + output);
  }
  class Stack {
    private int maxSize;
  
    private int[] stackArray;
  
    private int top;
  
    public Stack(int size) {
      maxSize = size;
      stackArray = new int[maxSize];
      top = -1;
    }
  
    public void push(int j) {
      stackArray[++top= j;
    }
  
    public int pop() {
      return stackArray[top--];
    }
  
    public int peek() {
      return stackArray[top];
    }
  
    public boolean isEmpty() {
      return (top == -1);
    }
  
    public boolean isFull() {
      return (top == maxSize - 1);
    }
  
    public int size() {
      return top + 1;
    }
  
    public int peekN(int n) {
      return stackArray[n];
    }
  
    public void displayStack(String s) {
      System.out.print(s);
      System.out.print("Stack (bottom>top): ");
      for (int j = 0; j < size(); j++) {
        System.out.print(peekN(j));
        System.out.print(' ');
      }
      System.out.println("");
    }
  }
}
 
 

 

 

import java.io.IOException;
 
public class ParsePost {
  private Stack theStack;
 
  private String input;
 
  public ParsePost(String s) {
    input = s;
  }
 
  public int doParse() {
    theStack = new Stack(20);
    char ch;
    int j;
    int num1, num2, interAns;
 
    for (j = 0; j < input.length(); j++) {
      ch = input.charAt(j)
      theStack.displayStack("" + ch + " ");
      if (ch >= '0' && ch <= '9'// if a number push it
        theStack.push((int) (ch - '0'));   
      else // it's an operator
      {
        num2 = theStack.pop();
        num1 = theStack.pop();
        switch (ch) {
        case '+':
          interAns = num1 + num2;
          break;
        case '-':
          interAns = num1 - num2;
          break;
        case '*':
          interAns = num1 * num2;
          break;
        case '/':
          interAns = num1 / num2;
          break;
        default:
          interAns = 0;
        }
        theStack.push(interAns);
      }
    }
    interAns = theStack.pop();
    return interAns;
  }
 
  public static void main(String[] argsthrows IOException {
    String input = "1-2+3*4+5/6-7+8*9";
    int output;
    ParsePost aParser = new ParsePost(input);
    output = aParser.doParse();
    System.out.println("Evaluates to " + output);
  }
  class Stack {
    private int maxSize;
  
    private int[] stackArray;
  
    private int top;
  
    public Stack(int size) {
      maxSize = size;
      stackArray = new int[maxSize];
      top = -1;
    }
  
    public void push(int j) {
      stackArray[++top= j;
    }
  
    public int pop() {
      return stackArray[top--];
    }
  
    public int peek() {
      return stackArray[top];
    }
  
    public boolean isEmpty() {
      return (top == -1);
    }
  
    public boolean isFull() {
      return (top == maxSize - 1);
    }
  
    public int size() {
      return top + 1;
    }
  
    public int peekN(int n) {
      return stackArray[n];
    }
  
    public void displayStack(String s) {
      System.out.print(s);
      System.out.print("Stack (bottom>top): ");
      for (int j = 0; j < size(); j++) {
        System.out.print(peekN(j));
        System.out.print(' ');
      }
      System.out.println("");
    }
  }
}
 

 

이 글은 스프링노트에서 작성되었습니다.

'JAVA' 카테고리의 다른 글

어트리뷰트(애플릿)  (0) 2012.05.15
실시간 파일 변경 알림  (0) 2012.05.15
String(문자열)내의 한글 확인  (0) 2012.05.15
Socket Simple 채팅 프로그램  (0) 2012.05.15
SMS 보내기  (0) 2012.05.15
Posted by 사라링

 

public boolean containsHangul(String str)
{
    for(int i = 0 ; i < str.length() ; i++)
    {
        char ch = str.charAt(i);
        Character.UnicodeBlock unicodeBlock = Character.UnicodeBlock.of(ch);
        if(UnicodeBlock.HANGUL_SYLLABLES.equals(unicodeBlock) ||
                UnicodeBlock.HANGUL_COMPATIBILITY_JAMO.equals(unicodeBlock) ||
                UnicodeBlock.HANGUL_JAMO.equals(unicodeBlock))
            return true;
    }
    return false;
}

이 글은 스프링노트에서 작성되었습니다.

'JAVA' 카테고리의 다른 글

실시간 파일 변경 알림  (0) 2012.05.15
간단 수식계산기  (0) 2012.05.15
Socket Simple 채팅 프로그램  (0) 2012.05.15
SMS 보내기  (0) 2012.05.15
Printf 수식 모음  (0) 2012.05.15
Posted by 사라링

Socket Simple 채팅 프로그램

 | JAVA
2012. 5. 15. 18:35

서버

 

package kr.hun.mesange;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class ServerMessinger {
    ArrayList<EachThread> clients=new ArrayList<EachThread>();

    public static void main(String[] args) {
        new ServerMessinger();
    }
    public ServerMessinger(){
        try {
           
            ServerSocket serverSocket= new ServerSocket(7777);
            System.out.println("nomally Server Turn ON");
           
           
            while (true) {
               
                Socket socket = serverSocket.accept();
                EachThread buff=new EachThread(socket);
                clients.add(buff);
                buff.start();
                System.out.println("client"+socket);
                   
            }
           
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
   
    class EachThread extends Thread{
        Socket socket=null;
    public     DataInputStream dis = null;
    public     DataOutputStream dos = null;
       
       
        public EachThread(Socket socket){
            this.socket=socket;
        }
       
        public void run(){
           
           
            try {
                dis=new DataInputStream(socket.getInputStream());
                dos=new DataOutputStream(socket.getOutputStream());
               
                while (true) {
                    String msg=dis.readUTF();
                   
                    for(int i =0;i<clients.size();i++){
                        clients.get(i).dos.writeUTF(msg);
                    }
                   
                    if(msg.equals("exit")){
                        break;
                    }
                }
                clients.remove(this);
                System.out.println("exit by user's request ");
               
            } catch (Exception e) {
                // TODO Auto-generated catch block
                clients.remove(this);
                System.out.println("exit by system's error");
            }
       
       
        }
    }
   
}

클라이언트

package kr.hun.mesange;

import java.awt.EventQueue;

public class MessangerTest extends JFrame {
    public DataInputStream dis=null;
    public DataOutputStream dos=null;;
    private JPanel contentPane;
    private JTextField tfIP;
    private JScrollPane scrollPane;
    private JTextField tfword;
    private JTextField tfPORT;
   
    boolean connect =false;
    private JTextArea taResult;
   
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MessangerTest frame = new MessangerTest();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public MessangerTest() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 384, 547);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
       
        JButton btnSocket = new JButton("\uC811\uC18D");
        btnSocket.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                btnSocketGo();
            }
        });
        btnSocket.setBounds(261, 15, 73, 44);
        contentPane.add(btnSocket);
       
        tfIP = new JTextField();
        tfIP.setText("127.0.0.1");
        tfIP.setBounds(90, 15, 159, 22);
        contentPane.add(tfIP);
        tfIP.setColumns(10);
       
        scrollPane = new JScrollPane();
        scrollPane.setViewportBorder(null);
        scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scrollPane.setBounds(12, 85, 340, 354);
        contentPane.add(scrollPane);
       
        taResult = new JTextArea();
        taResult.setEnabled(false);
        scrollPane.add(taResult);
        scrollPane.setViewportView(taResult);
       
       
       
        tfword = new JTextField();
        tfword.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
            if(e.getKeyCode()==10){
                btnWordSend();
            }
            }
        });
       
        tfword.setFont(new Font("굴림", Font.PLAIN, 15));
        tfword.setBounds(12, 449, 340, 30);
        contentPane.add(tfword);
        tfword.setColumns(10);
       
        tfPORT = new JTextField();
        tfPORT.setText("7777");
        tfPORT.setColumns(10);
        tfPORT.setBounds(90, 47, 159, 22);
        contentPane.add(tfPORT);
       
        JLabel lblIP = new JLabel("I P       :");
        lblIP.setBounds(12, 20, 57, 15);
        contentPane.add(lblIP);
       
        JLabel lblPort = new JLabel("PORT   :");
        lblPort.setBounds(12, 50, 57, 15);
        contentPane.add(lblPort);
       
       
       
    }
    public void btnWordSend(){
        if(connect==true){
       
            String msg=tfword.getText();
            tfword.setText("");
            try {
                dos.writeUTF("ID:sararing :: "+msg);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if(msg.equals("exit"))System.exit(0);
        }else {
            tfword.setText("");
            taResult.append("서버에 접속 해야만 채팅이 가능 합니다. \n");
        }
       
    }
    public void btnSocketGo(){
        String str=tfIP.getText();

        int port = Integer.parseInt(tfPORT.getText());
       
        try {
           
            Socket socket = new Socket(str,port);
            taResult.append("서버에 성공적으로 접속되었습니다...\n");
           
            connect=true;
            dis=new DataInputStream(socket.getInputStream());
            dos=new DataOutputStream(socket.getOutputStream());
            new EachThread().start();


        } catch (Exception e) {
            taResult.append("서버가 작동 하지 않거나.\n IP,PORT 를 확인해주세요.\n ");
        }
    }

    class EachThread extends Thread{
        public void run(){
            while(true){
            try {
                String msg=    dis.readUTF();
                taResult.append(msg+"\n");
                taResult.setSelectionStart(taResult.getText().length());  // 스크롤펜이 내려 가면서 최신화 시켜서 밑에 줄에 위치 할수 있도록 한다.
               
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            }
        }
    }
}

이 글은 스프링노트에서 작성되었습니다.

'JAVA' 카테고리의 다른 글

간단 수식계산기  (0) 2012.05.15
String(문자열)내의 한글 확인  (0) 2012.05.15
SMS 보내기  (0) 2012.05.15
Printf 수식 모음  (0) 2012.05.15
passwd 암호화  (0) 2012.05.15
Posted by 사라링

SMS 보내기

 | JAVA
2012. 5. 15. 18:35

HTTP POST 프로토콜로 모 휴대폰 문자 서비스 웹사이트로 자동접속 하여 휴대폰으로 문자 메시지를 보내 주는 소스 입니다.

고가의 SMS 단문메시지 전송 솔루션이 있지만 간단하게 웹사이트 장애나, 모니터링 용도로 자신의 시스템에 SMS 기능을 간단히 접목 시킬수 있습니다.

 

 

 

 

/**
 * @(#) SMS.java
 * Copyright 1999-2003 by  Java Service Network Community, KOREA.
 * All rights reserved.  http://www.javaservice.net
 *
 * NOTICE !      You can copy or redistribute this code freely,
 * but you should not remove the information about the copyright notice
 * and the author.
 *
 * @author  WonYoung Lee, javaservice@hanmail.net
 */
import java.net.*;
import java.io.*;
import java.util.StringTokenizer;
public class SMS {
    public final static String SERVER =  "www.smsphone.co.kr";
    public final static int PORT =  80;
    public static boolean TRACE = false;

    public static void main(String[] args) throws Exception
    {
        if ( args.length < 5 ) {
            System.out.println("Copyright 1999-2003 by  Java Service Network Community, KOREA.");
            System.out.println("All rights reserved. http://www.javaservice.net, javaservice@hanmail.net");
            System.out.println("Note: you shoud have id/passwd on http://www.smsphone.co.kr");
            System.out.println("      But, I hove no relationship with the SMSPHONE.co.kr web site.");
            System.out.println();
            System.out.println("Usage: java SMS <id> <passwd> <sender> <tolist> \"<message>\"");
            System.out.println("Ex: java SMS 0118987904 MyPasswd 0118987904 0118987904 재밌지?");
            System.out.println("Ex: java SMS 0118987904 MyPasswd 0118987904 0118987904;0118986266 \"햐~ 신기하지?\"");
            System.out.println("Ex: java -Dsms.trace=true SMS 0118987904 MyPasswd 0118987904 0118987904 \"trace할려구?\"");
            System.out.println("Ex: java -DproxySet=true -DproxyHost=proxy.our.com -DproxyPort=80 SMS \\");
            System.out.println("       0118987904 MyPasswd 0118987904 0118987904 \"프락시서버가 있다구?\"");
            System.out.println();
            System.exit(1);
        }
        if( "true".equals(System.getProperty("sms.trace"))) TRACE = true;
        sendsms(args[0], args[1], args[2], args[3],args[4]);
        System.out.println("Message sent to " + args[3] + " successfully.\n");
        System.out.println("Copyright 1999-2003 by  Java Service Network Community, KOREA.");
        System.out.println("All rights reserved. http://www.javaservice.net, javaservice@hanmail.net");
        System.out.println("Note: I hove no relationship with the SMSPHONE.co.kr web site.");
    }

    public static void sendsms(String id, String pwd, String returnphone, String tolist, String msg) throws Exception
    {
        if(TRACE) System.out.print("> login to http://" + SERVER + "/login_ok.asp");
        Socket socket =  new Socket(SERVER,PORT);
        if(TRACE) System.out.println("connected");
        InputStream in = null;
        OutputStream out = null;
        try{
            in = socket.getInputStream();
            out = socket.getOutputStream();
            //==========================================================
            // 1. login to www.smsphone.co.kr
            String sessionid = null;
            try{
                java.util.Hashtable data = new java.util.Hashtable();
                data.put("id", id); 
                data.put("pwd", pwd);
                //sessionid = http_post_send(in,out,"/login_ok.asp","",url_encoding(data),"parent.location.href='index.asp'");
            }
            catch(Exception e){
                throw new Exception( "login failed: " + e.toString());
            }

            //==========================================================
            // 2. SMS send to www.smsphone.co.kr
            try{
                java.util.Hashtable data = new java.util.Hashtable();
                data.put("mode", "1"); 
                data.put("ResGubn", "0");
    tolist = tolist.endsWith(";") ? tolist : tolist + ";"; // bug(?) patch ....
                data.put("SendList", tolist);
                data.put("SendLenCount", ""+(new StringTokenizer(tolist,";")).countTokens());
                data.put("returnNumber", returnphone);
                data.put("Message", msg);
                data.put("msgLen", ""+msg.getBytes().length );
                //http_post_send(in,out,"/send_msg.asp", sessionid, url_encoding(data),":"+id);
    System.out.println(data.toString());
            }
            catch(Exception e){
                throw new Exception( "login success but message send failed: " + e.toString());
            }
            //==========================================================
        }
        finally {
            if ( in != null ) try{in.close();}catch(Exception e){}
            if ( out != null ) try{out.close();}catch(Exception e){}
            if ( socket != null ) try{socket.close();}catch(Exception e){}
        }
    }

    private static String url_encoding(java.util.Hashtable hash){
        if ( hash == null ) throw new IllegalArgumentException("argument is null");
        java.util.Enumeration enum = hash.keys();
        StringBuffer buf = new StringBuffer();
        boolean isFirst = true;
        while(enum.hasMoreElements()){
          if (isFirst) isFirst = false;
          else buf.append('&');
          String key = (String)enum.nextElement();
          String value = (String)hash.get(key);
          buf.append(java.net.URLEncoder.encode(key));
          buf.append('=');
          buf.append(java.net.URLEncoder.encode(value));
        }
        return buf.toString();
    }
  

    public void setProxy(String host, String port, String id, String password) {
        // java -DproxySet=true -DproxyHost=proxy.our.com -DproxyPort=80 SMS \
        // Ex:       0118987904 MyPasswd 0118987904 0118987904 "프락시서버가 있다구?"
        java.util.Properties props = System.getProperties();
        props.put( "proxySet", "true" );
        props.put( "proxyHost", host );
        props.put( "proxyPort", port );
        System.setProperties(props);
        /*
        if ( id != null ) {
            String pw = id + ":" + password;
            String encodedPassword = com.sun.mail.imap.protocol.BASE64MailboxEncoder.encode( pw );
            httpURLConn.setRequestProperty( "Proxy-Authorization", encodedPassword );
        }
        */
    }

    private static String http_post_send(InputStream in, OutputStream out, String url, String sessionid, String body, String return_ok_str ) throws Exception
    {
        PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out)));
        String header =
            "POST " + url + " HTTP/1.0\n" +
            //"Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*\n" +
            "Accept-Language: ko\n" +
            "Content-Type: application/x-www-form-urlencoded\n" +
            "Accept-Encoding: gzip, deflate\n" +
            "User-Agent: SMS_API(http://www.javaservice.net)\n" +
            "Host: " + SERVER + "\n" +
            "Content-Length: " + body.getBytes().length + "\n" +
            "Cookie: " + sessionid + "\n" +
            "Connection: Keep-Alive\n" +
            "Cache-Control: no-cache\n";
        if(TRACE){
          System.out.println("> -----------------------------------------------------------------------------");
          System.out.print(header);
          System.out.println(); // dummy line
        }
        pw.print(header);
        pw.println(); // dummy line
        pw.flush();

        if(TRACE) System.out.println(body);
        pw.print(body);
        pw.flush();
        if(TRACE){
          System.out.println("> -----------------------------------------------------------------------------");
          System.out.println("> header & data flushed");
          System.out.println("> now, wait response .....");
          System.out.println("> -----------------------------------------------------------------------------");
        }

        StringBuffer buf = new StringBuffer();
        int length = -1;
        String line = null;
        while( ( line = read_line(in)) != null ) {
            if(TRACE) System.out.println(line);
            if ( line.length() == 0 ) break;
            int x = line.indexOf("Content-Length:");
            if ( x > -1 ) {
                length = Integer.valueOf(line.substring(x+16)).intValue();
                if(TRACE) System.out.println("LENGTH:" + length);
            }
            int y = line.indexOf("Set-Cookie:");
            if ( y > -1 ) {
                sessionid = line.substring(y+12);
                int z = sessionid.indexOf("path");
                if ( z > -1 ) sessionid = sessionid.substring(0, z);
                if(TRACE) System.out.println("COOKIE:" + sessionid);
            }
        }
        if ( line == null ) throw new Exception("unexcepted header data format");

        if ( length != -1 ) {
            // (mayby) HTTP 1.1 "Content-Length" field exist in the header.
            byte[] d = read_data(in,length);
            buf.append(new String(d));
            if(TRACE) System.out.println(new String(d));
        }
        else {
            // NO "Content-Length" field exist in the header
            String length_hex = read_line(in);
            if ( length_hex == null ) throw new Exception("there is no HTTP body data");
            try{
                length = Integer.valueOf(length_hex.trim(),16).intValue();
            }
            catch(Exception e){
                //This means, the following data is just normal BODY data.
                //And length is still -1.
            }
            if ( length != -1 ) {
                // Yap. WebSphere 3.0.x, 3.5.x
                read_line(in); // dummy line
                byte[] d = read_data(in,length);
                buf.append(new String(d));
                if(TRACE) System.out.println(new String(d));
            }
            else {
                byte[] d = read_data(in);
                buf.append(new String(d));
                if(TRACE) System.out.println(new String(d));
            }
        }
        if( buf.toString().indexOf(return_ok_str) == -1) throw new Exception("No Excepted Result.\n"+ buf.toString());
        return sessionid;
    }
   
    public static final int INTPUTSTREAM_READ_RETRY_COUNT = 10;

    /**
     * The <code>read_data</code> method of <code>SocketUtil</code> reads the
     * specified length of bytes from the given input stream.
     *
     * @param      in   an inputstream
     * @param      len  the number of bytes read.
     * @return     The specified number of bytes read until the end of
     *             the stream is reached.
     * @exception  Exception  if an I/O error or unexpected EOF occurs
     */
    private static byte[] read_data(InputStream in, int len) throws Exception {
        java.io.ByteArrayOutputStream bout = new java.io.ByteArrayOutputStream();
        int bcount = 0;
        byte[] buf = new byte[2048];
        int read_retry_count = 0;
        while( bcount < len ) {
            int n = in.read(buf,0, len-bcount < 2048 ? len-bcount : 2048 );
            // What would like to do if you've got an unexpected EOF before
            // reading all data ?
            //if (n == -1) break;
            if ( n == -1 ) throw
                 new java.io.IOException("inputstream has returned an unexpected EOF");

            if ( n == 0 && (++read_retry_count == INTPUTSTREAM_READ_RETRY_COUNT) )
                throw new java.io.IOException("inputstream-read-retry-count( " +
                    INTPUTSTREAM_READ_RETRY_COUNT + ") exceed !");
            if ( n != 0 ) {
                bcount += n;
                bout.write(buf,0,n);
            }
        }
        bout.flush();
        return bout.toByteArray();
    }

    /**
     * The <code>read_data</code> method of <code>SocketUtil</code> reads all
     * the bytes from the given inputstream until the given input stream
     * has not returned an EOF(end-of-stream) indicator.
     *
     * @param      in   an inputstream
     * @return     all bytes read if the end of the stream is reached.
     * @exception  Exception  if an I/O error occurs
     */
    private static byte[] read_data(InputStream in) throws Exception {
        java.io.ByteArrayOutputStream bout = new java.io.ByteArrayOutputStream();
        int bcount = 0;
        byte[] buf = new byte[2048];
        int read_retry_count = 0;
        while( true ) {
            int n = in.read(buf);
            if (n == -1) break;
            if ( n == 0 && (++read_retry_count == INTPUTSTREAM_READ_RETRY_COUNT) )
                throw new java.io.IOException("inputstream-read-retry-count( " +
                    INTPUTSTREAM_READ_RETRY_COUNT + ") exceed !");
            if ( n != 0 ) {
                bcount += n;
                bout.write(buf,0,n);
            }
        }
        bout.flush();
        return bout.toByteArray();
    }
 
    /**
     * Read a line of text.  A line is considered to be terminated by a line
     * feed ('\n') or a carriage return followed immediately by a linefeed.
     *
     * @return     A String containing the contents of the line, not including
     *             any line-termination characters, or null if the end of the
     *             stream has been reached
     *
     * @exception  IOException  If an I/O error occurs
     */
    private static String read_line(InputStream in) throws Exception {
        java.io.ByteArrayOutputStream bout = new java.io.ByteArrayOutputStream();
        boolean eof = false;
        while( true ) {
            int b = in.read();
            if (b == -1) { eof = true; break;}
            if ( b != '\r' && b != '\n' ) bout.write((byte)b);
            if (b == '\n') break;
        }
        bout.flush();
        if ( eof && bout.size() == 0 ) return null;
        //Or return ""; ? what's fit for you?
        return bout.toString();
    }
}

이 글은 스프링노트에서 작성되었습니다.

'JAVA' 카테고리의 다른 글

String(문자열)내의 한글 확인  (0) 2012.05.15
Socket Simple 채팅 프로그램  (0) 2012.05.15
Printf 수식 모음  (0) 2012.05.15
passwd 암호화  (0) 2012.05.15
OS CPU MEMORY 값 보여주기  (0) 2012.05.15
Posted by 사라링

Printf 수식 모음

 | JAVA
2012. 5. 15. 18:33

java_printf.jpg 

Printf 와 SimpleFormatDate

http://blog.naver.com/burberry5/90132916326

달력

http://blog.naver.com/burberry5/90132916893

 

public class PrintEx {
 public static void main(String[] args) {
 char ch = '가';
 int i = 77;
 float f= 3.33f;
 String str="가나다";
 System.out.printf("문자 ch=%c입니다\n",ch);
 System.out.printf("문자열 str=%s입니다\n",str);
 System.out.printf("실수 f=%f, %e입니다\n",f,f);
 System.out.printf("문자 ch=%c입니다\n문자열 str=%s입니다\n 실수 f=%f, %e입니다\n",ch,str,f,f);
//"10진수 100은 8진수로 xx이고, 16진수는 xx입니다.)  
 System.out.printf("10진수 %d은 8진수로 %o이고, 16진수로 %x \n",i,i,i);
 
 }
}

 

 

 

 

 

 

 

 

이 글은 스프링노트에서 작성되었습니다.

'JAVA' 카테고리의 다른 글

Socket Simple 채팅 프로그램  (0) 2012.05.15
SMS 보내기  (0) 2012.05.15
passwd 암호화  (0) 2012.05.15
OS CPU MEMORY 값 보여주기  (0) 2012.05.15
유니코드 표  (0) 2012.05.08
Posted by 사라링

passwd 암호화

 | JAVA
2012. 5. 15. 18:33

 

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 *
 *
 * @author
 */
public class strEnDeConvert {

    private  byte[] hexaMap = {0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68};

    protected  byte[] getHexaEncodingBytes(byte[] src)
 {
        byte[] buffer=new byte[src.length*2];
        int index=0;

  System.out.println("src.length="+ src.length);  

        for (int i=0; i < src.length; i++)
  {   buffer[index++] = hexaMap[ ( (src[i]&0xf0) >> 4 ) ];
            buffer[index++] = hexaMap[ ( src[i]&0x0f ) ];
        }
  return buffer;
    }

    protected  String getHexaEncoding(byte[] src,String charSet) throws UnsupportedEncodingException
 {
        byte[] strBytes=getHexaEncodingBytes(src);
        return new String(strBytes,charSet);
    }

    protected  String getHexaEncoding(byte[] src)
 {
        byte[] strBytes=getHexaEncodingBytes(src);
        return new String(strBytes);
    }

    /**
     * Digest 알고리즘을 수행한다.
     */
    public String getDigest(String str, String digest, String charset) {
        try
  {   MessageDigest md = MessageDigest.getInstance(digest);
            try
   {   byte[]      raw = str.getBytes(charset);
                byte[] digested = md.digest(raw);
                System.out.println("digested.length="+ digested.length); 
    System.out.println("str.length="+ str.length());

    return getHexaEncoding(digested, charset);
            } catch (UnsupportedEncodingException e) {
            } 
  } catch (NoSuchAlgorithmException e) {
        }       
        return str;
    }
 
 // Test
 public static void main(String[] args) throws Exception
 {
  strEnDeConvert ec = new strEnDeConvert();
  Defines        df = new Defines();
  System.out.println(ec.getDigest("1111122222333334445",df.PASSWORD_DIGEST, df.PASSWORD_CHARSET));
 }

}

 

이 글은 스프링노트에서 작성되었습니다.

'JAVA' 카테고리의 다른 글

SMS 보내기  (0) 2012.05.15
Printf 수식 모음  (0) 2012.05.15
OS CPU MEMORY 값 보여주기  (0) 2012.05.15
유니코드 표  (0) 2012.05.08
SqlExploler(eclipse)  (0) 2012.05.08
Posted by 사라링

OS CPU MEMORY 값 보여주기

 | JAVA
2012. 5. 15. 18:33

 

[소스]

import java.io.File;
import java.lang.management.ClassLoadingMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.lang.management.RuntimeMXBean;
import java.lang.management.ThreadMXBean;

import com.sun.management.OperatingSystemMXBean;

/**
 * @co.kr.codein
 * @author yonghoon
 * 
 */

public class UseMxBean
{

  
/**
 * @param args
 */

  public static void main(String[] args) {
    // TODO Auto-generated method stub
    new UseMxBean();
  }

  
/*
 * 디스크용량
 */

  private void showDisk() {
    File root = null;

    try {
      root = new File("/");

      System.out.println("Total Space: " + toMB(root.getTotalSpace()));
      System.out.println("Usable Space: " + toMB(root.getUsableSpace()));
      
      /* added by cafe mocha */
      System.exit(0);

    } catch (Exception e) {
      e.printStackTrace();
    }

  }

  
/*
 * cpu 사용량
 */

  private void showCPU() {
    OperatingSystemMXBean osbean = (OperatingSystemMXBean) ManagementFactory
      .getOperatingSystemMXBean();
    RuntimeMXBean runbean = (RuntimeMXBean) ManagementFactory
      .getRuntimeMXBean();

    long bfprocesstime = osbean.getProcessCpuTime();
    long bfuptime = runbean.getUptime();
    long ncpus = osbean.getAvailableProcessors();

    for (int i = 0; i < 1000000; ++i) {
      ncpus = osbean.getAvailableProcessors();
    }

    long afprocesstime = osbean.getProcessCpuTime();
    long afuptime = runbean.getUptime();

    float cal = (afprocesstime - bfprocesstime)
      / ((afuptime - bfuptime) * 10000f);

    float usage = Math.min(99f, cal);

    System.out.println("Calculation: " + cal);
    System.out.println("CPU Usage: " + usage);

  }

  private void showRuntime() {
    RuntimeMXBean runbean = (RuntimeMXBean) ManagementFactory
      .getRuntimeMXBean();

  }

  
/*
 * 메모리 사용량
 */

  private void showMemory() {
    MemoryMXBean membean = (MemoryMXBean) ManagementFactory
      .getMemoryMXBean();

    MemoryUsage heap = membean.getHeapMemoryUsage();
    System.out.println("Heap Memory: " + heap.toString());

    MemoryUsage nonheap = membean.getNonHeapMemoryUsage();
    System.out.println("NonHeap Memory: " + nonheap.toString());

  }

  private void showClassLoading() {
    ClassLoadingMXBean classbean = (ClassLoadingMXBean) ManagementFactory
      .getClassLoadingMXBean();

    System.out.println("TotalLoadedClassCount: "
        + classbean.getTotalLoadedClassCount());
    System.out.println("LoadedClassCount: "
        + classbean.getLoadedClassCount());
    System.out.println("UnloadedClassCount: "
        + classbean.getUnloadedClassCount());

  }

  private void showThreadBean() {
    ThreadMXBean tbean = (ThreadMXBean) ManagementFactory.getThreadMXBean();

    long[] ids = tbean.getAllThreadIds();

    System.out.println("Thread Count: " + tbean.getThreadCount());

    for (long id : ids) {
      System.out.println("Thread CPU Time(" + id + ")"
          + tbean.getThreadCpuTime(id));
      System.out.println("Thread User Time(" + id + ")"
          + tbean.getThreadCpuTime(id));
    }

  }

  
/**
 * OS 정보
 */

  private void showOSBean() {

    OperatingSystemMXBean osbean = (OperatingSystemMXBean) ManagementFactory
      .getOperatingSystemMXBean();

    System.out.println("OS Name: " + osbean.getName());
    System.out.println("OS Arch: " + osbean.getArch());
    System.out.println("Available Processors: "
        + osbean.getAvailableProcessors());
    System.out.println("TotalPhysicalMemorySize: "
        + toMB(osbean.getTotalPhysicalMemorySize()));
    System.out.println("FreePhysicalMemorySize: "
        + toMB(osbean.getFreePhysicalMemorySize()));
    System.out.println("TotalSwapSpaceSize: "
        + toMB(osbean.getTotalSwapSpaceSize()));
    System.out.println("FreeSwapSpaceSize: "
        + toMB(osbean.getFreeSwapSpaceSize()));
    System.out.println("CommittedVirtualMemorySize: "
        + toMB(osbean.getCommittedVirtualMemorySize()));
    System.out.println("SystemLoadAverage: "
        + osbean.getSystemLoadAverage());

  }

  public UseMxBean() {
    seperator(); showOSBean();
    seperator(); showThreadBean();
    seperator(); showClassLoading();
    seperator(); showMemory();
    seperator(); showDisk();
    seperator(); showCPU();
    seperator();
  }
  
  /* added cafe mocha 2009-06 */
  private void seperator() {
    System.out.println("-----------------------------------------------");
  }
  /* added cafe mocha 2009-06 */
  private String toMB(long size)
  {
    return (int)(size/(1024*1024))+"(MB)";
  }


 

이 글은 스프링노트에서 작성되었습니다.

'JAVA' 카테고리의 다른 글

Printf 수식 모음  (0) 2012.05.15
passwd 암호화  (0) 2012.05.15
유니코드 표  (0) 2012.05.08
SqlExploler(eclipse)  (0) 2012.05.08
자바 EXE 만들기.  (0) 2012.05.08
Posted by 사라링

Progressbar

2012. 5. 15. 09:46
Progress Dialog 생성하기


프로그레스 다이얼로그 ( Progress Dialog ) 는 AlertDialog 클래스를 상속받은 클래스 입니다. 이것은 끝나는 시점이 명확하지 않은 상태의 태스크에 대한 진행상황을 '진행바퀴' 로 보여줍니다.

끝나는 시점이 정해진 태스크라면 좀 더 명확하게 '진행바' 로 보여주는것도 좋겠네요

이 다이얼로그는 버튼을 제공할 수도 있습니다. ProgressDialog 의 구현은 ProgressDialog.show() 메소드를 호출하는 것만으로 처리할 수 있습니다.


show() 메소드는 모두 static 메소드라는 점에 주의하시면 되겠습니다.


    ProgressDialog dialog = ProgressDialog.show(AndroidTest.this, "",
    "로딩 중입니다. 잠시 기다려주세요", true);





show() 메소드의 첫번째 인자는 어플리케이션의 컨텍스트, 두번재는 다이얼로그 타이틀, 세번째는 텍스트 내용, 네번째는 '진행바'에서 사용되는 루프 진행 여부를 나타냅니다.

프로그레스 다이얼로그의 디폴트 스타일은 '진행바퀴' 입니다.


진행바 표시하기



명확한 진행율을 보여주는 진행바를 만들기 위해선 아래와 같은 방법을 일반적으로 사용합니다.
1. 생성자인 ProgressDialog(Context context) 로 초기화 합니다.
2. 진행 스타일을 setProgressStyle() 메소드에 "STYLE_xxx" 로 지정하고 그외 속성들을 지정합니다
3. 다이얼로그 표시를 위해 show() 메소드를 호출 하거나, onCreateDialog() 에서 ProgressDialog 객체를 리턴해도 됩니다.
4. 전체 값을 setProgress() 로 지정하거나 incrementProgressBy(int) 메소드로 현재 진행양에 증가분 값을 더할 수 있습니다.


ProgressDialog progressDialog;
progressDialog = new ProgressDialog(AndroidTest.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("로딩중입니다...");
progressDialog.setCancelable(false);
progressDialog.show();


 


직접 소스코드를 테스트 해보시는 분들도 계시겠지만, 직접 테스트해보면 다이얼로그가 시작되면 그 다이얼로그가 끝나서 종료되어 끝나기 전에는 해당 액티비티에서 "BACK" 버튼을 눌러도 반응을 하지 않습니다.

진행상태라는것의 특성상 어떤 진행 상태는 오래걸릴수도 있고 다른 기타 이유들 때문에 별도의 스레드에서 처리하고 , 메인 스레드는 계속 사용자에게 즉각 반응을 해야되는데요, 이 작업을 위해선 스레드를 새로 생성 후 핸들러를 이용하여 메인스레드에게 결과를 알려주는 방식을 써야 합니다.


별도의 스레드에서 ProgressBar 구현

진행상태 표시와 처리를 위하여 , 별도의 스레드를 만들고 그 스레드는 진행이 이루어질 때 마다 핸들러를 통해 메인 스레드로 알려주면 됩니다. 그러면 메인 액티비티에서 Progress 다이얼로그를 업데이트하게 하면 되겠지요.


package exam.androidtest;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class NotificationTest extends Activity {
static final int PROGRESS_DIALOG = 0;
Button button;
ProgressThread progressThread;
ProgressDialog progressDialog;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

button = (Button) findViewById(R.id.btn);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(PROGRESS_DIALOG);
}
});
}

protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS_DIALOG:
progressDialog = new ProgressDialog(NotificationTest.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Loading...");
progressThread = new ProgressThread(handler);
progressThread.start();
return progressDialog;
default:
return null;
}
}

// 핸들러는 정의하여 스레드가 메시지를 보내면 프로그레스를 업데이트 합니다.
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
int total = msg.getData().getInt("total");

progressDialog.setProgress(total);
if (total >= 100) {
dismissDialog(PROGRESS_DIALOG);
progressThread.setState(ProgressThread.STATE_DONE);
}
}
};

/** 프로그레스를 처리하는 클래스를 내부 클래스로 정의. */
private class ProgressThread extends Thread {
Handler mHandler;
final static int STATE_DONE = 0;
final static int STATE_RUNNING = 1;
int mState;
int total;

ProgressThread(Handler h) {
mHandler = h;
}

public void run() {
mState = STATE_RUNNING;
total = 0;
while (mState == STATE_RUNNING) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// 에러처리
}
Message msg = mHandler.obtainMessage();
Bundle b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
total++;
}
}

// 현재의 상태를 설정하는 메소드
public void setState(int state) {
mState = state;
}
}
}





AsyncTask 를 이용한 프로그레스바 추가.java


package kr.or.ddit;

import java.security.PublicKey;
import java.util.ArrayList;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class AsyncTaskProgressbarActivity extends Activity {

    ProgressBar bar;
    TextView textView;
    Handler handler;
    AsyncTaskProgress task;
    int cnt=0;
    float fileSize = 1024;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ArrayList<String> list = new ArrayList<String>();
       
        bar = (ProgressBar) findViewById(R.id.progressbar);
        bar.setMax(100);
        textView= (TextView) findViewById(R.id.textView);
     
        Button startBtn = (Button) findViewById(R.id.startBtn);
        startBtn.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View arg0) {
            task = new AsyncTaskProgress();
            task.execute(fileSize);
            }
        });
        Button cancelBtn = (Button) findViewById(R.id.cancelBtn);
        cancelBtn.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                task.cancel(true);
            }
        });
    }
    class AsyncTaskProgress extends AsyncTask<Float, Integer, Integer>{

        @Override
        protected void onPreExecute() {
            cnt=0;
            bar.setProgress(0);
            textView.setText("push ple download");
        }
        @Override
        protected Integer doInBackground(Float... value) {
            while (!isCancelled()) {
                if(cnt>value[0]){
                    break;
                }else {
                    publishProgress(cnt);
                }
               
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                cnt++;
            }
            return cnt;
       
        }
        @Override
        protected void onProgressUpdate(Integer... integers) {
            //bar.incrementProgressBy(integers[0].intValue());
            bar.setProgress((int) (integers[0].floatValue()/fileSize*100));
            textView.setText((int)(integers[0].floatValue()/fileSize*100)+"% down loading.. ");
        }
        @Override
        protected void onPostExecute(Integer result) {
            bar.setProgress(0);
            textView.setText("down loading compleate!");
           
        }
       
        @Override
        protected void onCancelled() {
            bar.setProgress(0);
            textView.setText("down load cancel");
        }
    }
   

}

'안드로이드' 카테고리의 다른 글

소켓 통신 구현  (0) 2012.05.15
You must supply a layout_width attribute  (0) 2012.05.15
안드로이드 색상표  (0) 2012.05.11
안드로이드 강좌 모음 pdf&동영상 강좌.  (0) 2012.05.11
화면회전  (0) 2012.05.08
Posted by 사라링

html5 살펴보기

<!DOCTYPE html> 

DTD 선언이 간략해 졋다. 기존 DTD에 비해서,

실용성을 강조하므로, 필요없는것들을 다 제외햇다.


<html lang="ko">
<head> 요소. 열림태그와 닫힘태그로 구성,속성. 
<meta charset="utf-8" />

 

html4까지는 charset이 없다.

간략화 할수 있다. 인코딩 관련 meta태그가 간략화 되었다

 

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

ie에서만 해석

ie는 버전별로 렌더링 모드가 따로 있다.

그래서 IE=edge 로 하면 최신버전으로 렌더링해달라는 의미,

IE=7 이렇게 쓸수도 있다.

 

chrome=1 크롬프레임사용하겠다는 뜻

크롬프레임 : ActiveX이고, activeX는 ie에서민 작동한다.

크롬프레임은 activeX를 이용해서, 모양은 ie인데 그 안의 내부적으로는 크롬이 동작하는것.

그러면 ie6에서도 html5를 사용할수 있게 한다는 뜻

이것은 activeX를 사용하는 것이므로 좋은 방법은 아니다.

설치가 되어있어야만 한다. 그래서 코드를 띄우고 해야함.

chrome=1 을 기재안하면 ie6이 실행, 기재하면 activeX를 설치하는 화면을 띄워서 구동하는 원리임.

 

<title>1_html5템플릿</title>


<meta name="description" content="" />

<meta name="author" content="timo0003" />

설명과 저자.. 정도.

 

<meta name="viewport" content="width=device-width; initial-scale=1.0" />

viewport 모바일에 최적화된 page라는 뜻

모바일 기기에서 읽어서 원활하게 page를 보여준다는 의미

처음에 들어갓을때의 스케일을 1로 지정한다는것.

이 부분에 대한 내용은 3일차에서 다시 설명하도록 하겠습니다.


<!-- Replace favicon.ico & apple-touch-icon.png in the root of your domain and delete these references -->
<link rel="shortcut icon" href="/favicon.ico" />

일단 데스크탑에서 favico설정하는것.

 

<link rel="apple-touch-icon" href="/apple-touch-icon.png" />

모바일에서 바탕화면에 나타나는 아이콘 지정.

 

현재 웹 표준에서 쓰고 있는 id들을 분석을 해서, 요소로 만들어버린것.

전부  div로 선언하던것들이 요소로 추가가 많이 되었다.

 

 

 

실습, 2단 레이어 만들어보기

자동완성기능도 사용해보자.

자동완성 기능중에 요소가 어디어디에서 되는지 확장해서 보기. window - preference에 가서

Aptana studio - Content Assist 에 가서 web으로 프로젝트 바꾸고 브라우저를 체크해준다.

 

 

Aptana studio 단축키 잠깐 설명!

* 자동완성기능 활성화 : Ctrl + spaceBar

* 실행 : Ctrl + F11 아이콘을 클릭, 오른쪽 마우스 Run as 로 해도 된다. 실행되는 기본 브라우저는 FireFox

 

자동 포멧팅 : Ctrl + Shift + F

 

<div id="wrap">
 
 <div id="header"></div>
 <div id="sidebar"></div>
 <div id="content"></div>
 <div id="footer"></div>
 
</div>

 

이렇게 구조를 만들고 스타일을 입혀보자 참고 : clearboth.org

 

 

html5로 바꿔보자.

 

 

  <div id="wrap">
   <header id="header"></header>
   <aside id="sidebar"></aside>
   <section id="content"></section>
   <footer id="footer"></footer>
  </div>

 

 

 

 

html5 하위호환성 고려

현재 html5에로 마크업 하기 위해서는 데스크탑 기준으로 봣을때, 모바일은 다 되니까.

하위호환성을 고려해야 하는데,

그렇게 하려면 2가지 개념이 필요하다.

 

1.

ie6,7,8 에서는 새로운 요소들을 아예 인식하지 못한다.

한마디로  DOM트리에 생성이 안됩니다.

 

해결1 : FM적인 해결책은 자바스크립트에서 createElement()로 요소를 직접 생성... 하지만 귀찮앙

해결2 : ie9.js를 사용합니다. (구글에 가서. ie9.js 를 검색한다)

첫번째 나오는 검색 클릭. 해서 붙여넣기.

  <!--[if lt IE 9]>
  <script src="http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE9.js"></script>
  <![endif]-->

 

  

 

2.

이젠이런일이 거의 없지만 표준브라우저도 예전 버전들은 FireFox 3.6같은 경우.

새로운 요소들을 인라인 요소로 인식합니다.

인라인들은 높이값이 없다.

 

 

<link rel="stylesheet" href="css/reset.css" /> 이렇게 해서 예전버전들도 블록레벨로 인정하게끔 해준다.

 

이렇게까지만 해도, html5로 마크업 할 수가 있다.

 

 

 <!DOCTYPE  html>
<html lang="ko">
 <head>
  <meta charset="utf-8"/>
  <title>2_2단레이아웃</title>
  <!--[if lt IE 9]>
  <script src="http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE9.js"></script>
  <![endif]-->
  <link rel="stylesheet" href="css/reset.css" />
  <style>
   body {
    margin: 0px;
    padding: 0px;
   }
   #wrap {
    width: 900px;
    margin: auto;
    border: 1px solid red;
   }
   #header {
    width: 900px;
    height: 100px;
    background: pink;
   }
   #sidebar {
    float: left;
    width: 300px;
    height: 300px;
    background: lightgreen;
   }
   #content {
    float: right;
    width: 600px;
    min-height: 300px;
    background: skyblue;
   }
   #footer {
    clear: both;
    display: block;
    content: '';
    width: 900px;
    height: 100px;
    background: yellow;
   }
  </style>
 </head>
 <body>
  <div id="wrap">
   <header id="header"></header>
   <aside id="sidebar"></aside>
   <section id="content"></section>
   <footer id="footer"></footer>
  </div>
 </body>
</html>

 

 

 



'HTML5.0' 카테고리의 다른 글

캔버스 이미지 뛰우기 .  (0) 2012.06.04
canvas 사이트 모음 .  (0) 2012.05.24
Canvas  (0) 2012.05.22
Aptana 설치  (0) 2012.05.14
HTML 이란.  (0) 2012.05.14
Posted by 사라링

Aptana 설치

2012. 5. 14. 20:19

===========================================================================================================================

Aptana설치하기 http://aptana.org/

===========================================================================================================================

 

 

일단 aptana사이트에 접속! http://aptana.org/

 

 

 

 

 

 

 

이렇게 보이는 화면에서 하단에 보시면 아이콘 있습니다.

클릭해서 다운로드하시고

ok ok ok 등등 하시면 기본설치됩니다.

 

 

 

 

 

 

 

 

 

 

계속 ok ok 해서 설치하면 됨

 

 

 

 

설치가 끝나고, 압타나를 실행시키면 첫화면에 작업할 워크스페이스 지정하는 화면이 나옴..

 

 

 

 

 

 

 

1. htnml5템플릿 만들어 보기

프로젝트 오른쪽 마우스 - new From Templete - html - html5 Templete  를 선택해서

파일명  1_html5템플릿.html 로 만들어 보기

 

'HTML5.0' 카테고리의 다른 글

캔버스 이미지 뛰우기 .  (0) 2012.06.04
canvas 사이트 모음 .  (0) 2012.05.24
Canvas  (0) 2012.05.22
html4.0 을 html 5.0 으로 변환  (0) 2012.05.14
HTML 이란.  (0) 2012.05.14
Posted by 사라링

유용한 이클립스 단축키 사용을 통해 빠르고 편한 코딩을 해보자.



위와 같이 코딩을 하고 있었다.

그 와중에 fin 이라는 BufferedInputStream 변수를 전역으로 빼야 하는 상황이 나올 경우가 심심치 않게 이때에 보통은

드레그 한후에 맨 위로 올라 가서 복사 붙여넣기를 해야 한다 . 우리는 문화 인이니 단축키를 사용해 보자.


fin 에 커서를 놓은후 ctrl +1 을 눌러 보자 그러면 가운데에 convert local variable to filed  가 보일것이다. 눌러 보자. 

이렇게 봐뀌면서 위로 가 보면 

이렇게 자동으로 선언 되어 있음을 알수 있다. 

초기 값을 주지는 못하는것 같다.. 하는 방법 아시는분은 댓글 부탁 . ;;



Posted by 사라링

2005-03-06.hwp


2005-05-29.hwp


2005-09-04.hwp


2006-03-05.pdf


2006-05-14.pdf


2006-09-10.hwp


2007-03-04.hwp


2007-05-13.hwp


200709.hwp


gisa-08-1.hwp


gisa-08-2.hwp


gisa-08-4.hwp


gisa-09-1.hwp


gisa-09-2.hwp


gisa-09-4.hwp


gisa-10-4.hwp


gisa-11-1.hwp


gisa_20100307.hwp


gisa_20100509.hwp


gisa_20100905.hwp



Posted by 사라링

Spring3.0 Tiles

2012. 5. 14. 19:15

기본 세팅 Tiles 프로젝트 파일


==============================


=================================이론=====================================

컨트롤러생성

template 메뉴에 링크등록

바디생성

dispatcher-servlet.xml 등록

tilesdef.xml 등록 - 타일스 설정


===============================프로젝트===================================
=================================코드=====================================
titlesDemo
src
    kr.spring.tiles.controller
           IndexController
package kr.spring.tiles.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class IndexController {
    @RequestMapping("/index.do")
    public String process() {
            return "index";
        }
}

           Menu1Controller
package kr.spring.tiles.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class Menu1Controller {
    @RequestMapping("/menu1.do")
    public String process() {
            return "menu1";
        }
}

           Menu2Controller
package kr.spring.tiles.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class Menu2Controller {
    @RequestMapping("/menu2.do")
    public String process() {
            return "menu2";
        }
}

           Menu3Controller
package kr.spring.tiles.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class Menu3Controller {
    @RequestMapping("/menu3.do")
    public String process() {
            return "menu3";
        }
}

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

<!DOCTYPE tiles-definitions PUBLIC
       "-//Apache Software Foundation//DTD Tiles Configuration 2.1//EN"
       "http://tiles.apache.org/dtds/tiles-config_2_1.dtd">

<tiles-definitions>
    <definition name="index" template="/WEB-INF/viewtiles2/template/layout.jsp">
        <put-attribute name="title"  value="Spring Tiles Example"/>
        <put-attribute name="menu"   value="/WEB-INF/viewtiles2/template/menu.jsp"/>
        <put-attribute name="header" value="/WEB-INF/viewtiles2/template/header.jsp"/>
        <put-attribute name="body"   value="/WEB-INF/viewtiles2/body.jsp"/>
        <put-attribute name="footer" value="/WEB-INF/viewtiles2/template/footer.jsp"/>
    </definition>
   
    <definition name="menu1" extends="index">
        <put-attribute name="body"   value="/WEB-INF/viewtiles2/body-menu1.jsp"/>
    </definition>
   
    <definition name="menu2" extends="index">
        <put-attribute name="body"   value="/WEB-INF/viewtiles2/body-menu2.jsp"/>
    </definition>
   
    <definition name="menu3" extends="index">
        <put-attribute name="body"   value="/WEB-INF/viewtiles2/body-menu3.jsp"/>
    </definition>
</tiles-definitions>

      viewtiles2
           template
                footer.jsp
<%@page contentType="text/html; charset=euc-kr"%>
<div align="center" style="background:yellow;">
    company information
</div>

                header.jsp
<%@page contentType="text/html; charset=euc-kr"%>
<h2 align="center">Spring Tiles Examples!!!</h2>

                layout.jsp
<%@ page contentType="text/html; charset=euc-kr"%>
<%@ taglib prefix="tiles"  uri="http://tiles.apache.org/tags-tiles"%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title><tiles:getAsString name="title" /></title>
    </head>
    <body>

    <table border=0 cellpadding=0 cellspacing=1 bgcolor="#a0a0a0" width="100%">
        <tr height=100 valign="middle" bgcolor="#ffffff">
            <td colspan=2><tiles:insertAttribute name="header"/></td>
        </tr>
        <tr height="670" bgcolor="#ffffff">
            <td width="15%" valign="top"><tiles:insertAttribute name="menu"/></td>
            <td width="85%" align="center"><tiles:insertAttribute name="body"/></td>
        </tr>
        <tr bgcolor="#ffffff">
            <td colspan=2><tiles:insertAttribute name="footer"/></td>
        </tr>
    </table>
    </body>
</html>

                menu.jsp
<%@page contentType="text/html; charset=euc-kr"%>
<ul>
   
    <li><a href="index.do">main</a></li>
    <li><a href="menu1.do">menu1</a></li>
    <li><a href="menu2.do">menu2</a></li>
    <li><a href="menu3.do">menu3</a></li>
</ul>

      body.jsp
<%@page contentType="text/html; charset=euc-kr"%>
<b>main page body !!!</b>

      body-menu1.jsp
<%@page contentType="text/html; charset=euc-kr"%>
<br />
<br />
menu 1 body location

      body-menu2.jsp
<%@page contentType="text/html; charset=euc-kr"%>
<br />
<br />
menu 2 body location

      body-menu3.jsp
<%@page contentType="text/html; charset=euc-kr"%>
<br />
<br />
menu 3 body location

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

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean class="kr.spring.tiles.controller.IndexController"/>
    <bean class="kr.spring.tiles.controller.Menu1Controller"/>
    <bean class="kr.spring.tiles.controller.Menu2Controller"/>   
    <bean class="kr.spring.tiles.controller.Menu3Controller"/>

    <bean id="tilesConfigurer"
        class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
        <property name="definitions">
            <list>
                <value>/WEB-INF/tiles2def/tilesdef.xml</value>
            </list>
        </property>
        <property name="preparerFactoryClass"
            value="org.springframework.web.servlet.view.tiles2.SpringBeanPreparerFactory" />
    </bean>

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.tiles2.TilesView" />
    </bean>

</beans>

      web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>EUC-KR</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

index.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
   response.sendRedirect(request.getContextPath()+"/index.do");
%>

================================결과값====================================


'스프링3.0' 카테고리의 다른 글

Missing artifact ojdbc:ojdbc:jar:14:compile  (0) 2012.05.18
스프링 3.0 AOP 에러. 문제 해결  (1) 2012.05.15
Spring3.0 DB  (0) 2012.05.14
Spring3.0 View error filedown  (0) 2012.05.14
Spring3.0 MVC 웹요청 처리  (0) 2012.05.14
Posted by 사라링

Spring3.0 DB

2012. 5. 14. 19:14

기본프로젝트
=================
완료프로젝트


=================================이론=====================================
p394

p412

p416

    //@Valid @InitBinder 와 연동해서 검증을 해줌
    @RequestMapping(value="/update.do", method=RequestMethod.POST)
    public String submit(@Valid MemberCommand memberCommand, BindingResult result){

        if(result.hasErrors()){
            return formViewName;
        }
        memberDao.updateMember(memberCommand);
        return "redirect:/list.do";
    }
    @InitBinder //initBinder 검증 등록
    protected void initBinder(WebDataBinder binder){
        binder.setValidator(new MemberValidator());
    }




===============================프로젝트===================================



=================================코드=====================================



===============================출력결과===================================


DB MEMBER1 테이블


멤버등록



리스트뿌리기

상세보기

수정하기

삭제하기






'스프링3.0' 카테고리의 다른 글

스프링 3.0 AOP 에러. 문제 해결  (1) 2012.05.15
Spring3.0 Tiles  (1) 2012.05.14
Spring3.0 View error filedown  (0) 2012.05.14
Spring3.0 MVC 웹요청 처리  (0) 2012.05.14
Spring 3.0 AOP  (0) 2012.05.14
Posted by 사라링

기본 세팅 프로젝트 파일


=================================이론=====================================
P309
뷰 영역 구현
P260
에러코드의 출력

P361
파일다운로드처리

p373~378
국제화처리

p362~367
엑셀,pdf 파일다운로드



===============================프로젝트===================================
chap07
src
    madvirus.spring.chap07.controller
           AuthenticationException *1 - 로그인 테스트 뷰영역 구현 에러코드출력
           Authenticator *1
           DownloadController *2 - 파일다운로드
           LocaleChangeController *3 - p376 Locale resolver
           LoginCommandValidator *1
           LoginCommnad *1
           LoginController *1
           MockAuthenticator *1
           PageRank *4 - 엑셀파일
           PageRanksController *4 - 엑셀파일 다운로드
           PageReportController *4 - pdf파일
    madvirus.spring.chap07.view
           DownloadView *2
           PageRanksView *4 - 엑셀파일
           PageReportView *4 - pdf파일

     messages
           label_en.properties *1
           label.properties *1
           validation_en.properties *1
           validation.properties *1

WebContent
      viewjsp
           loginForm.jsp *1
           loginSuccess.jsp *1

      dispatcherInternal-servlet.xml *1
      dispatcherNonHtml-servlet.xml *2
      web.xml

index.jsp
=================================코드=====================================
chap07
src
    madvirus.spring.chap07.controller
           AuthenticationException *1 - 로그인 테스트 뷰영역 구현 에러코드출력
package madvirus.spring.chap07.controller;

public class AuthenticationException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    public AuthenticationException(String message) {
        super(message);
    }
}

           Authenticator *1
package madvirus.spring.chap07.controller;

public interface Authenticator {
    void authenticate(String id,String password);
}

           DownloadController *2 - 파일다운로드
package madvirus.spring.chap07.controller;

import java.io.File;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.ModelAndView;
    
@Controller
public class DownloadController implements ApplicationContextAware {

    private WebApplicationContext context = null;
   
    @RequestMapping("/file")
    public ModelAndView download() throws Exception {
        File downloadFile = getFile();
        return new ModelAndView("download","downloadFile",downloadFile);
    }
   
    private File getFile(){
        String path = context.getServletContext().getRealPath("/WEB-INF/설명.txt");
        return new File(path);
    }
   
    public void setApplicationContext(ApplicationContext applicationContext)throws BeansException {
        this.context = (WebApplicationContext)applicationContext;
    }
}

           LocaleChangeController *3 - p376 Locale resolver
package madvirus.spring.chap07.controller;

import java.util.Locale;

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

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.LocaleResolver;

@Controller
public class LocaleChangeController {

    private LocaleResolver localeResolver;

    @RequestMapping("/changLanguage")
    public String change(@RequestParam("lang")String language,HttpServletRequest request, HttpServletResponse response){
        Locale locale = new Locale(language);
        localeResolver.setLocale(request, response, locale);
        return "redirect:/index.jsp";
    }           
    public void setLocaleResolver(LocaleResolver localeResolver){
        this.localeResolver = localeResolver;
    }
}

           LoginCommandValidator *1
package madvirus.spring.chap07.controller;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

public class LoginCommandValidator implements Validator {

    public void validate(Object target, Errors errors) {
        //비어있거나 공백이있으면 돌려보냄
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "id", "required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "loginType", "required");
    }

    public boolean supports(Class<?> clazz) {
        return LoginCommnad.class.isAssignableFrom(clazz);
    }   
}

           LoginCommnad *1
package madvirus.spring.chap07.controller;

public class LoginCommnad {
   
    private String id;
    private String password;
    private String loginType;
   
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getLoginType() {
        return loginType;
    }
    public void setLoginType(String loginType) {
        this.loginType = loginType;
    }
}

           LoginController *1
package madvirus.spring.chap07.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

   /*//web.xml 에서 
  <servlet-mapping>
    <servlet-name>dispatcherInternal</servlet-name>
    <url-pattern>/jsp/*</url-pattern>
  </servlet-mapping>  => /jsp/login/login.do */
@Controller  
@RequestMapping("/login/login.do")
public class LoginController {

    private Authenticator authenticator;

    @ModelAttribute("login")
    public LoginCommnad formBacking(){
        return new LoginCommnad();
    }

    @RequestMapping(method = RequestMethod.GET)
    public String form(){
        return "loginForm";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String submit(@ModelAttribute("login") LoginCommnad loginCommand,BindingResult result){
        new LoginCommandValidator().validate(loginCommand, result);

        if(result.hasErrors()){
            return "loginForm";
        }
        try{
            authenticator.authenticate(loginCommand.getId(), loginCommand.getPassword());

            return "loginSuccess";
        }catch (AuthenticationException ex){                    //null : loginCommand.getId() 가 null이면 default 값
            result.reject("invalidIdOrPassword", new Object[] {loginCommand.getId()},null);
            return "loginForm";
        }
    }

    @ModelAttribute("loginTypes")
    protected List<String> referenceData() throws Exception {
        List<String> loginTypes = new ArrayList<String>();
        loginTypes.add("일반회원");
        loginTypes.add("기업회원");
        loginTypes.add("헤드헌터회원");
        return loginTypes;
    }
   
    public void setAuthenticator(Authenticator authenticator){
        this.authenticator = authenticator;
    }
}

           MockAuthenticator *1
package madvirus.spring.chap07.controller;

public class MockAuthenticator implements Authenticator{

    public void authenticate(String id, String password) {
        if(!id.equals("madvirus")){
            throw new AuthenticationException("invalid id"+ id);
        }       
    }
}

           PageRank *4 - 엑셀파일
package madvirus.spring.chap07.controller;

public class PageRank {
 
    private int rank;
    private String page;
   
    public PageRank() {
    }
   
    public PageRank(int rank, String page) {
        super();
        this.rank = rank;
        this.page = page;
    }
   
    public int getRank() {
        return rank;
    }
    public String getPage() {
        return page;
    }   
}

           PageRanksController *4 - 엑셀파일 다운로드
package madvirus.spring.chap07.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class PageRanksController {

    @RequestMapping("/pageRanks")
    public ModelAndView handleRequestInternal(){
       
        List<PageRank> pageRanks = new ArrayList<PageRank>();
       
        pageRanks.add(new PageRank(1, "/bbs/mir2/list"));
        pageRanks.add(new PageRank(2, "/bbs/mir3/list"));
        pageRanks.add(new PageRank(3, "/bbs/changchun2/list"));
       
        return new ModelAndView("pageRanks","pageRanks",pageRanks);
    }
}

           PageReportController *4 - pdf파일
package madvirus.spring.chap07.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class PageReportController {

    @RequestMapping("/pageReport")
    public ModelAndView pdfReport(){
        List<PageRank> pageRanks = new ArrayList<PageRank>();
        pageRanks.add(new PageRank(1, "/bbs/mir2/list"));
        pageRanks.add(new PageRank(2, "/bbs/mir3/list"));
        pageRanks.add(new PageRank(3, "/bbs/changchun2/list"));
        return new ModelAndView("pageReport","pageRanks",pageRanks);
    }
}

    madvirus.spring.chap07.view
           DownloadView *2
package madvirus.spring.chap07.view;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;

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

import org.springframework.util.FileCopyUtils;
import org.springframework.web.servlet.view.AbstractView;

public class DownloadView extends AbstractView {

    public DownloadView() {
        setContentType("application/download; charset=utf-8");
    }
       
    @Override
    protected void renderMergedOutputModel(Map<String, Object> model,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        File file = (File) model.get("downloadFile");

        response.setContentType(getContentType());
        response.setContentLength((int) file.length());

        String userAgent = request.getHeader("User-Agent");
        boolean ie = userAgent.indexOf("MSIE") > -1;
        String fileName = null;
        if (ie) {
            fileName = URLEncoder.encode(file.getName(), "utf-8");
        } else {
            fileName = new String(file.getName().getBytes("utf-8"),
                    "iso-8859-1");
        }
        response.setHeader("Content-Disposition", "attachment; filename=\""
                + fileName + "\";");
        response.setHeader("Content-Transfer-Encoding", "binary");
        OutputStream out = response.getOutputStream();
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            FileCopyUtils.copy(fis, out);
        } finally {
            if (fis != null)
                try {
                    fis.close();
                } catch (IOException ex) {
                }
        }
        out.flush();
    }
}

           PageRanksView *4 - 엑셀파일
package madvirus.spring.chap07.view;

import java.util.List;
import java.util.Map;

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

import madvirus.spring.chap07.controller.PageRank;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.view.document.AbstractExcelView;

public class PageRanksView extends AbstractExcelView {

    //@SuppressWarnings("unchecked") : 문법에 문제가없는데 나오는 노란줄 경고 안나오게함
    @SuppressWarnings("unchecked")
    @Override
    protected void buildExcelDocument(Map<String, Object> model,
            HSSFWorkbook workbook, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        HSSFSheet sheet = createFirstSheet(workbook);
        createColumnLabel(sheet);

        List<PageRank> pageRanks = (List<PageRank>) model.get("pageRanks");
        int rowNum = 1;
        for (PageRank rank : pageRanks) {
            createPageRankRow(sheet, rank, rowNum++);
        }
    }

    private HSSFSheet createFirstSheet(HSSFWorkbook workbook) {
        HSSFSheet sheet = workbook.createSheet();
        workbook.setSheetName(0, "페이지 순위");
        sheet.setColumnWidth(1, 256 * 20);
        return sheet;
    }

    private void createColumnLabel(HSSFSheet sheet) {
        HSSFRow firstRow = sheet.createRow(0);
        HSSFCell cell = firstRow.createCell(0);
        cell.setCellValue("순위");

        cell = firstRow.createCell(1);
        cell.setCellValue("페이지");
    }

    private void createPageRankRow(HSSFSheet sheet, PageRank rank, int rowNum) {
        HSSFRow row = sheet.createRow(rowNum);
        HSSFCell cell = row.createCell(0);
        cell.setCellValue(rank.getRank());

        cell = row.createCell(1);
        cell.setCellValue(rank.getPage());

    }
}

           PageReportView *4 - pdf파일
package madvirus.spring.chap07.view;

import java.util.List;
import java.util.Map;

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

import madvirus.spring.chap07.controller.PageRank;

import org.springframework.web.servlet.view.document.AbstractPdfView;

import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;

public class PageReportView extends AbstractPdfView {

    @SuppressWarnings("unchecked")
    @Override
    protected void buildPdfDocument(Map<String, Object> model,
            Document document, PdfWriter writer, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        List<PageRank> pageRanks = (List<PageRank>) model.get("pageRanks");
        Table table = new Table(2, pageRanks.size() + 1);
        table.setPadding(5);

        BaseFont bfKorean = BaseFont.createFont(
                "c:\\windows\\fonts\\batang.ttc,0", BaseFont.IDENTITY_H,
                BaseFont.EMBEDDED);

        Font font = new Font(bfKorean);
        Cell cell = new Cell(new Paragraph("순위", font));
        cell.setHeader(true);
        table.addCell(cell);
        cell = new Cell(new Paragraph("페이지", font));
        table.addCell(cell);
        table.endHeaders();

        for (PageRank rank : pageRanks) {
            table.addCell(Integer.toString(rank.getRank()));
            table.addCell(rank.getPage());
        }
        document.add(table);
    }
}

     messages
           label_en.properties *1
login.form.title=Login Form
login.form.type=Login Type
login.form.id=ID
login.form.password=Password
login.form.submit=Login

           label.properties *1
login.form.title=로그인
login.form.type=로그인 타입
login.form.id=회원Id
login.form.password=비밀번호
login.form.submit=전송

           validation_en.properties *1
required=required
required.login.id=login id is required
required.login.password=login password is requreid
required.login.loginType=You have to select login type
invalidIdOrPassword.login=Login id and password do not match. (You provided {0})

           validation.properties *1
required=필수입니다.
required.login.id=ID는 필수입니다.
required.login.password=비밀번호는 필수입니다.
required.login.loginType=로그인 타입을 선택하세요.
invalidIdOrPassword.login=당신이 입력한 id {0}. 로그인 아이디와 비밀번호가 일치하지 않습니다.

WebContent
      viewjsp
           loginForm.jsp *1
<%@ page contentType="text/html; charset=EUC-KR" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title><spring:message code="login.form.title"/></title>
</head>
<body>
<form:form commandName="login">
<form:errors />
<p>                       
    <label for="loginType"><spring:message code="login.form.type" /></label>
    <form:select path="loginType" items="${loginTypes}" />
</p>
<p>
    <label for="id"><spring:message code="login.form.id" /></label>
    <form:input id="id" path="id"/>
    <form:errors path="id" />
</p>
<p>
    <label for="password"><spring:message code="login.form.password" /></label>
    <form:password id="password" path="password"/>
    <form:errors path="password" />
</p>
<p>
    <input type="submit" value="<spring:message code="login.form.submit" />">
</p>
</form:form>
</body>
</html>

           loginSuccess.jsp *1
<%@ page language="java" contentType="text/html; charset=EUC-KR" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>로그인 성공</title>
</head>
<body>
로그인에 성공했습니다.
</body>
</html>

      dispatcherInternal-servlet.xml *1
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- 커스텀태그이용 -->
    <bean class="madvirus.spring.chap07.controller.LoginController">
        <property name="authenticator">
            <bean class="madvirus.spring.chap07.controller.MockAuthenticator"/>
        </property>
    </bean>   
   
    <!-- 국제화 -->
    <bean class="madvirus.spring.chap07.controller.LocaleChangeController">
        <property name="localeResolver" ref="localeResolver"/>
    </bean>
    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"/>
   
    <!-- 국제화2 -->
    <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" p:paramName="language"/>
    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
        <property name="interceptors">
            <list>
                <ref bean="localeChangeInterceptor"/>
            </list>
        </property>
    </bean>
   
    <!-- View 글로벌 설정 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/viewjsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
   
    <!-- 리소스 번들 지정 -->
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basenames">
            <list>
                <value>messages.validation</value>
                <value>messages.label</value>
            </list>
        </property>   
    </bean>
</beans>

      dispatcherNonHtml-servlet.xml *2
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <!-- 파일 다운로드 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
    <bean id="downloadController" class="madvirus.spring.chap07.controller.DownloadController"/>
    <bean id="download" class="madvirus.spring.chap07.view.DownloadView"></bean>
   
   
    <!-- 엑셀 다운로드 -->
    <bean id="pageRanksController" class="madvirus.spring.chap07.controller.PageRanksController" />
    <bean id="pageRanks" class="madvirus.spring.chap07.view.PageRanksView" />

    <!-- PDF 다운로드 -->
    <bean id="pageReportController" class="madvirus.spring.chap07.controller.PageReportController" />
    <bean id="pageReport" class="madvirus.spring.chap07.view.PageReportView"/>
   
    </beans>      

      web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <context-param>
    <param-name>defaultHtmlEscape</param-name>
    <param-value>false</param-value>
  </context-param>
  <servlet>
    <servlet-name>dispatcherInternal</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherInternal</servlet-name>
    <url-pattern>/jsp/*</url-pattern>
  </servlet-mapping>
   <servlet>
    <servlet-name>dispatcherNonHtml</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherNonHtml</servlet-name>
    <url-pattern>/download/*</url-pattern>
  </servlet-mapping>
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

설명.txt
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>View 연습</title>
</head>
<body>
<a href="http://localhost:8080/chap07/jsp/login/login.do">LoginController </a><br>
<a href="http://localhost:8080/chap07/download/file">DownloadController - 파일 다운로드</a><br>
<a href="http://localhost:8080/chap07/jsp/changLanguage?lang=ko">LocaleChangeController -1 한글</a><br>
<a href="http://localhost:8080/chap07/jsp/changLanguage?lang=en">LocaleChangeController -2 영어</a><br>
<a href="http://localhost:8080/chap07/jsp/login/login.do?language=ko">LocaleChangeInterceptor -1 한글</a><br>
<a href="http://localhost:8080/chap07/jsp/login/login.do?language=en">LocaleChangeInterceptor -2 영어</a><br>
<a href="http://localhost:8080/chap07/download/pageRanks">PageRanksController - 엑셀파일  다운로드</a><br>
<a href="http://localhost:8080/chap07/download/pageReport">PageReportController - PDF파일  다운로드</a><br>
</body> 
</html>

===============================결과값====================================

1.로그인 테스트


en_US


ko_KR


2.다운로드


3. 국제화 LocaleReslover를 이용한 Locale 변경


국제화 LocaleChangeInterceptor


4.엑셀파일 다운로드 , PDF 다운로드





'스프링3.0' 카테고리의 다른 글

Spring3.0 Tiles  (1) 2012.05.14
Spring3.0 DB  (0) 2012.05.14
Spring3.0 MVC 웹요청 처리  (0) 2012.05.14
Spring 3.0 AOP  (0) 2012.05.14
Spring3.0 DI 3  (0) 2012.05.14
Posted by 사라링

BLOG main image
.. by 사라링

카테고리

사라링님의 노트 (301)
JSP (31)
J-Query (41)
JAVA (24)
디자인패턴 (1)
스트러츠 (3)
안드로이드 (11)
오라클 (45)
우분투-오라클 (1)
이클립스메뉴얼 (6)
스프링3.0 (23)
자바스크립트 (10)
HTML5.0 (17)
정보처리기사 (1)
기타(컴퓨터 관련) (1)
문제점 해결 (3)
프로젝트 (2)
AJAX (4)
하이버네이트 (3)
트러스트폼 (11)
Jeus (2)
재무관리(회계) (5)
정규식 (5)
아이바티스 (8)
취미 (2)
소프트웨어 보안 관련모음 (0)
정보보안기사 (6)
C언어 베이직 및 프로그램 (3)
보안 관련 용어 정리 (2)
넥사크로 (6)
웹스퀘어_ (0)
Total :
Today : Yesterday :