JAVA Console Token 구현

Programming/JAVA,JSP 2013. 8. 7. 13:37 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
public class Test
{
	public static void main(String[] args)
	{
		String text = "AAA BBB CCC DDD EEE FFF";
		int count = 0;

		for (int i = 0; i < text.length(); i++)
		{
			if (text.charAt(i) == ' ')
			{
				count++;
			} else
			{
			}
		}
		String[] textResult = new String[count + 1];

		int i, j, k;
		for (i = 0; i < text.length(); i++)
		{
			if (text.charAt(i) == ' ')
			{
				textResult[0] = text.substring(0, i);
				break;
			}
		}
		System.out.print(textResult[0]);
		int lastValue =	0;
		for (k = 1; i < text.length(); k++)
		{
			i = i + 1;
			j = i;
			for (; i < text.length(); i++)
			{
				if (text.charAt(i) == ' ')
				{
					System.out.print("\n");
					textResult[k] = text.substring(j, i);
					lastValue = i;
					break;
				}
			}
		}
		textResult[k-1] = text.substring(lastValue+1 , text.length() );		
		for( String s : textResult )
		{
			System.out.println(s);
		}
	}
}
시스템 라이브러리를 활용
public class Test
{
	public static void main(String[] args)
	{
		String text = "AAA BBB CCC DDD EEE FFF";
		
		StringTokenizer st = new StringTokenizer(text, " ");
		
		while(st.hasMoreTokens() )
		{
			System.out.println(st.nextToken());
		}
	}
}
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
package com.tansanc.tistory;

class Store
{
	private T[] data = (T[]) new Object[0];

	void add(T o)
	{
		if (data.length == 0)
		{
			data = (T[]) new Object[1];
			data[0] = o;
		} else
		{
			T[] temp = data;
			data = (T[]) new Object[data.length + 1];
			for (int i = 0; i < temp.length; i++)
			{
				data[i] = temp[i];
			}
			data[temp.length] = o;
		}
	}

	T get(int i)
	{
		return data[i];
	}
}

public class Test
{
	public static void main(String[] args)
	{
		Store s = new Store();
		s.add(3);
		s.add(4);
		System.out.println((Integer) s.get(0) + (Integer) s.get(1));
	}
}

'Programming > JAVA,JSP' 카테고리의 다른 글

JAVA 타자연습 프로그램  (0) 2013.08.13
JAVA Console Token 구현  (0) 2013.08.07
JAVA DRAG 가능한 Component 만들기  (0) 2013.08.03
JAVA Swing 두개의 판넬을 겹치기  (0) 2013.08.03
JAVA JNI  (0) 2013.05.01
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

 

class DraggableComponent extends JComponent

{

 

    /** If sets <b>TRUE</b> this component is draggable */

    private boolean draggable = true;

    /**

     * 2D Point representing the coordinate where mouse is, relative parent

     * container

     */

    protected Point anchorPoint;

    /** Default mouse cursor for dragging action */

    protected Cursor draggingCursor = Cursor

           .getPredefinedCursor(Cursor.HAND_CURSOR);

    /**

     * If sets <b>TRUE</b> when dragging component, it will be painted over each

     * other (z-Buffer change)

     */

    protected boolean overbearing = false;

 

    public DraggableComponent()

    {

        addDragListeners();

        setOpaque(true);

        setBackground(new Color(240, 240, 240));

    }

 

    /**

     * Add Mouse Motion Listener with drag function

     */

    private void addDragListeners()

    {

        /**

         * This handle is a reference to THIS because in next Mouse Adapter

         * "this" is not allowed

         */

        final DraggableComponent handle = this;

        addMouseMotionListener(new MouseAdapter()

        {

 

           @Override

           public void mouseMoved(MouseEvent e)

           {

               anchorPoint = e.getPoint();

           setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

           }

 

           @Override

           public void mouseDragged(MouseEvent e)

           {

               int anchorX = anchorPoint.x;

               int anchorY = anchorPoint.y;

 

               Point parentOnScreen = getParent().getLocationOnScreen();

               Point mouseOnScreen = e.getLocationOnScreen();

               Point position = new Point(mouseOnScreen.x - parentOnScreen.x

                       - anchorX, mouseOnScreen.y - parentOnScreen.y - anchorY);

               setLocation(position);

 

               // Change Z-Buffer if it is "overbearing"

               if (overbearing)

               {

                   getParent().setComponentZOrder(handle, 0);

                   repaint();

               }

           }

        });

    }

 

    @Override

    protected void paintComponent(Graphics g)

    {

        super.paintComponent(g);

        if (isOpaque())

        {

           g.setColor(getBackground());

           g.fillRect(0, 0, getWidth(), getHeight());

        }

    }

 

    private void removeDragListeners()

    {

        for (MouseMotionListener listener : this.getMouseMotionListeners())

        {

           removeMouseMotionListener(listener);

        }

        setCursor(Cursor.getDefaultCursor());

    }

}


http://www.codeproject.com/Articles/116088/Draggable-Components-in-Java-Swing

'Programming > JAVA,JSP' 카테고리의 다른 글

JAVA Console Token 구현  (0) 2013.08.07
JAVA 제네릭을 사용한 Store Class  (0) 2013.08.07
JAVA Swing 두개의 판넬을 겹치기  (0) 2013.08.03
JAVA JNI  (0) 2013.05.01
Eclipse Tips  (0) 2013.04.30
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
import java.awt.*;
import javax.swing.*;

class BgPanel extends JPanel {
    Image bg = new ImageIcon("water.jpg").getImage();
    @Override
    public void paintComponent(Graphics g) {
        g.drawImage(bg, 0, 0, getWidth(), getHeight(), this);
    }
}

class LoginPanel extends JPanel {
    LoginPanel() {
        setOpaque(false);
        setLayout(new FlowLayout());
        add(new JLabel("username: ")); add(new JTextField(10));
        add(new JLabel("password: ")); add(new JPasswordField(10));
    }
}

public class FrameTestBase extends JFrame {
    public static void main(String args[]) {
        JPanel bgPanel = new BgPanel();
        bgPanel.setLayout(new BorderLayout());
        bgPanel.add(new LoginPanel(), BorderLayout.CENTER);

        FrameTestBase t = new FrameTestBase();
        t.setContentPane(bgPanel);
        t.setDefaultCloseOperation(EXIT_ON_CLOSE);
        t.setSize(250, 100);
        t.setVisible(true);
    }
}



http://stackoverflow.com/questions/7092067/adding-a-background-image-to-a-panel-containing-other-components



'Programming > JAVA,JSP' 카테고리의 다른 글

JAVA 제네릭을 사용한 Store Class  (0) 2013.08.07
JAVA DRAG 가능한 Component 만들기  (0) 2013.08.03
JAVA JNI  (0) 2013.05.01
Eclipse Tips  (0) 2013.04.30
JAVA MYSQL ANDROID REST 활용  (0) 2013.04.28

JAVA JNI

Programming/JAVA,JSP 2013. 5. 1. 12:00 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.


1. 일단 자바 소스를 만듭니다.

2. 그리고 컴파일합니다.[ javac HelloWorld.java ]

3. C에서 사용하기 위한 헤더 파일을 얻습니다. [ javah -jni HelloWorld ]

4. 헤더 파일을 기준으로 C코드를 작성합니다.

5. C 파일을 컴파일 합니다.

   cl -I"C:\Program Files\Java\jdk1.6.0\include" -I"C:\Program Files\Java\jdk1.6.0\include\win32" -MD -LD HelloWorld.c

   (따옴표는 'Program Files' 사이의 공백을 포함한 한 문자열임을 나타내기 위해서 집어넣은 것입니다.)

6. 자바 프로그램을 실행합니다. [ java HelloWorld ]


참고 : http://blog.naver.com/PostView.nhn?blogId=777lover&logNo=10138852420

'Programming > JAVA,JSP' 카테고리의 다른 글

JAVA DRAG 가능한 Component 만들기  (0) 2013.08.03
JAVA Swing 두개의 판넬을 겹치기  (0) 2013.08.03
Eclipse Tips  (0) 2013.04.30
JAVA MYSQL ANDROID REST 활용  (0) 2013.04.28
JAVA MYSQL 활용 4 Android App  (0) 2013.04.28

Eclipse Tips

Programming/JAVA,JSP 2013. 4. 30. 02:50 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

Eclipse 팁 #1 (코드 Style 설정)

 

팀 프로젝트를 진행할때 개발자별로 Coding Style이 달라서 고생하는 경우가 많습니다. 
이를 위해 Eclipse는 코드 형식화를 지원하는데요,

아래와 같이 코딩 규칙을 위해바는 코드가 있다고 가정합시다.

 

해당 코드 위에서 [ Ctrl+Shift+F ] 키만 누르면 아래와 같이 코드가 이쁘게 정리됩니다.

 

이는 Eclipse에서 설정된 Code Formatter의 설정에 따른 것입니다. 
프로젝트에서 개발된 모든 코드에 같은 코딩 규칙을 적용하고 싶다면.. 
결정된 Coding Convention에 따라 Code Formatter의 설정을 바꾼 다음, 
그것을 XML 파일로 Export하고, 개발자에게 Import 시켜 적용하도록 하면 된답니다. 

아래 그림은 Windows - Preferences 에서 "Java - Code Style - Code Formatter"를 
선택했을 때 나오는 그림입니다. 
Eclipse 3.0은 기본적으로 2가지 코드 형식을 기본적으로 내장하고 있습니다.

 

Java Conventions를 선택하고, Show.. 버튼을 누르면 해당 설정을 커스터마이징 할 수 있습니다. 
탭 사이즈와 괄호의 위치 등 모든 것을 변경할 수 있습니다. 

Eclipse 팁 #2 (Import문 정리)

 

개발할 때 어떤 기능을 구현하기 위해 특정 라이브러리를 import 시켜놓고, 
그 기능이 필요없어져서 삭제한 다음에도 import문은 그대로 두는 경우가 많습니다. 

그때 Eclipse가 제공하는 Organize import 기능은 아주 유용한데요.. 
아래와 같이 사용되지 않는 라이브러리를 import한 경우 Eclipse는 앞에 전구를 키고 표시해줍니다. 
이때 [ Ctrl+Shift+O ] 버튼을 누르면 사용하지 않는 모든 import 문이 정리됩니다. 아래와 같이 깨끗하게 말이죠.

 

또 한가지 유용한 기능은 같은 패키지 내에서 여러 개의 클래스를 import할 경우입니다. 
예를 들어 한 패키지 내에서 4개 이상의 클래스를 import 한다면, 
그것을 *로 합쳐서 표시하도록 하고 싶을 때가 있습니다. 
그럴 때는 window - preference 로 가서 java - code style - organize import에서 
Number of imports needs for .*의 수를 4로 해놓으면, 
같은 패키지에서 4개이상의 클래스가 임포트되면 *로 합쳐서 표시해줍니다. 
(Apply 버튼 바로 위에 그 항목이 있습니다.)

 

Eclipse 팁 #3 (영역별 주석처리)

 

여러 줄에 걸쳐 있는 코드를 주석 처리하고 싶은데, 
주석 처리하고자 하는 영역 내에 /* */가 있을 경우 참 곤란하시죠? 

일일이 // 를 앞에 붙이려니 얼마나 손가락이 빠른지를 테스트하는거 같구.. ^^* 
그럴 때 주석처리할 영역을 선택 한 다음 [ Ctrl+/ ] 를 눌러보세요. 
아래와 같이 자동으로 해당 영역을 주석으로 만들어줍니다. 
주석을 해제하고 싶다면 다시 한번 더 [ Ctrl+/ ]를 눌러주면 됩니다.

 

Eclipse 팁 #4 (에디터칸이동)

 

실제 프로젝트를 작업하다 보면 한번에 열어놓은 파일이 30개가 넘는 것은 기본이죠? 
그때 해당 파일들 사이를 열려진 윈도우를 [ Alt+Tab ] 을 이용해서

이동하는 것 같은 기능이 있다면 편할겁니다. 
그러한 단축키가 [ Ctrl+F6 ] 입니다. 
그 키를 누르면 화면 중앙에 아래와 같은 에디터 이동 화면이 뜹니다

 

바로 이전으로 이동할 때는 [ Ctrl+F6 ]이 편하지만, 
여러 개 중 하나를 이동할 때는 [ Ctrl+F6 ]을 누른 후,

[Ctrl+화살표] 를 이용해서 원하는 에디터로 이동하는 것이 편합니다. 

Eclipse 팁 #6 (줄번호 표시 및 줄 이동하기)

 

Eclipse의 기본 설정에 라인 번호는 표시되지 않도록 되어 있습니다. 
디버깅할 때 특정 라인에 에러가 있음을 확인했는데, 일일이 줄을 세어가면서 이동할 수도 없구.. 
그때 해당 라인으로 이동하기 위한 단축키가 [ Ctrl+L ] 입니다. 
윈도우와 같이 Ctrl+G 로 단축키를 변경해서 쓰시는 것도 좋을 듯 합니다. 

아예 줄번호가 항상 표시되도록 하고 싶다면 window - preference 에서, 
Java - Editor로 이동한 다음 "Show line numbers"를 체크해두시면 됩니다. 

Eclipse 팁 #7 (변경사항 추적하기)

 

변경 사항을 추적하고자 하는 파일을 PackageExplorer에서 선택 후, 
오른쪽 버튼을 눌러 컨텍스트 메뉴에서 [ compare with Local History ] 선택합니다.

 

시간대 별로 이전의 작업 결과를 보실 수 있습니다. 
만일 이전의 코드로 되돌아가고 싶다면, 같은 방법으로 파일의 컨텍스트 메뉴에서 
[ Replace with ] 를 선택하고, [ Local History ]에서 변경하면 됩니다.

 

Eclipse 팁 #8 (Javadoc 문서생성 )

 

JavaDoc 형태의 주석으로 소스코드 문서화가 된 상태라고 가정하겠습니다. 
Project 메뉴의 [ Generate Javadoc... ] 기능을 실행하면 
간편한 마법사의 지원을 통해 Javadoc 문서를 생성할 수 있습니다. 

일반적으로 프로젝트 루트 밑에 doc 이란 폴더 안에 JavaDoc으로 생성된 API 문서를 포함합니다.

 

생성될 API 문서에 포함시킬 정보를 선택하는 것이 마법사의 다음 단계입니다. 
Finish 버튼을 누르면 Package Explorer에 아래와 같이 API 문서가 생성된 것을 확인할 수 있습니다. 

Eclipse 팁 #9 (전체프로젝트 ZIP 백업)

 

전체 프로젝트를 백업하기 위해 압축을 해야 할때 유용한 기능입니다. 
File 메뉴의 Export 기능을 실행하면 아래와 같은 윈도우가 뜹니다.

 

선택요소 중에서 ZIP 파일을 선택합니다. 
다음 화면은 백업할 요소들을 선택하는 것입니다. 
일반적으로 자동 생성되는 JavaDoc 문서나 Classes 파일들은 백업하지 않습니다. 
적당한 백업 파일 이름과 위치를 결정하고 Finish 버튼을 누르면 백업이 완료됩니다.

 

이클립스에서 유용한 단축키

 

Ctrl + e : 한줄지움
Ctrl + w : 메뉴보여줌
Ctrl + space : 클래스등 코드 도움
Ctrl + / : 한줄 주석 반대는 Ctrl + \
Ctrl + , : 찾기나, TASK항목 이동

Ctrl + . : 이동

Ctrl + F6 : Editor 선택

Ctrl + F7 : View 선택

Ctrl + F8 : Perspectieve 선택

Ctrl + F11 : 디버깅

Ctrl + 1 : QuickFix 실행

 

Ctrl + Shift + b : 브레이크 포인트

Ctrl + Shift + e : 현재 캐럿에서 끝까지 삭제

Ctrl + Shift + f : 코드 포맷팅

Ctrl + Shift + m : 자동 임포트
Ctrl + Shift + o : 임포트 자동 정리

Ctrl + Shift + space : 입력 파라미터 정보 보여줌


출처 : http://blog.naver.com/simz/



'Programming > JAVA,JSP' 카테고리의 다른 글

JAVA Swing 두개의 판넬을 겹치기  (0) 2013.08.03
JAVA JNI  (0) 2013.05.01
JAVA MYSQL ANDROID REST 활용  (0) 2013.04.28
JAVA MYSQL 활용 4 Android App  (0) 2013.04.28
JAVA MYSQL 활용 3  (0) 2013.04.28

JAVA MYSQL ANDROID REST 활용

Programming/JAVA,JSP 2013. 4. 28. 17:15 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
REST 사용방법 http://192.168.0.3:8182/books http://192.168.0.3:8182/books/where/OReilly http://192.168.0.3:8182/books/ insert/"제목"/"저자"/"가격' REST 서버
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.restlet.Application;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.Restlet;
import org.restlet.Server;
import org.restlet.data.MediaType;
import org.restlet.data.Protocol;
import org.restlet.routing.Router;

public class test extends Application {
	public static Connection makeConnection() {
		String url = "jdbc:mysql://localhost:3307/book_db";
		String id = "root";
		String password = "green";
		Connection con = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			System.out.println("드라이버 적재 성공");
			con = DriverManager.getConnection(url, id, password);
			System.out.println("데이터베이스 연결 성공");
		} catch (ClassNotFoundException e) {
			System.out.println("드라이버를 찾을 수 없습니다.");
		} catch (SQLException e) {
			System.out.println("연결에 실패하였습니다.");
		}
		return con;
	}

	public static Statement stmt;

	public static void main(String[] args) throws Exception {
		Connection con = makeConnection();
		stmt = con.createStatement();
		Server server = new Server(Protocol.HTTP, 8182);
		server.setNext(new test());
		server.start();
	}

	public static String selectBooks(Statement stmt) throws SQLException {
		ResultSet rs = stmt.executeQuery("SELECT * FROM books");
		String result = "";
		while (rs.next()) {
			int id = rs.getInt("book_id");
			String title = rs.getString("title");
			String publisher = rs.getString("publisher");
			String year = rs.getString("year");
			if (title != null) {
				result += id + " " + title + " " + publisher + " " + year
						+ "\n";
			}
		}
		return result;
	}

	public static String selectBooks(Statement stmt, String name)
			throws SQLException {
		ResultSet rs = stmt
				.executeQuery("SELECT * FROM books WHERE publisher = '" + name
						+ "'");
		String result = "";
		while (rs.next()) {
			int id = rs.getInt("book_id");
			String title = rs.getString("title");
			String publisher = rs.getString("publisher");
			String year = rs.getString("year");
			if (title != null) {
				result += id + " " + title + " " + publisher + " " + year
						+ "\n";
			}
		}
		return result;
	}

	@Override
	public Restlet createInboundRoot() {
		Router router = new Router();
		router.attach("http://localhost:8182/books", restlet1);
		router.attach("http://localhost:8182/books/where/{name}", restlet2);
		router.attach(
				"http://localhost:8182/books/insert/{title}/{publisher}/{year}/{price}",
				restlet3);
		router.attach("http://localhost:8182/datas/{year}/{month}/{day}",
				restlet4);
		router.attach("http://192.168.0.3:8182/books", restlet1);
		router.attach("http://192.168.0.3:8182/books/where/{name}", restlet2);
		router.attach(
				"http://192.168.0.3:8182/books/insert/{title}/{publisher}/{year}/{price}",
				restlet3);
		router.attach("http://192.168.0.3:8182/datas/{year}/{month}/{day}",
				restlet4);
		// (title, publisher, year, price)
		return router;
	}

	public Restlet restlet4 = new Restlet(getContext()) {
		@Override
		public void handle(Request request, Response response) {
			// Print the user name of the requested orders
			String year = (String) request.getAttributes().get("year");
			String month = (String) request.getAttributes().get("month");
			String day = (String) request.getAttributes().get("day");

			String message = "";
			try {
				message += selectDatas(stmt, year, month, day);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			response.setEntity(message, MediaType.TEXT_PLAIN);
		}
	};

	public static String selectDatas(Statement stmt, String year, String month,
			String day) throws SQLException {
		ResultSet rs = stmt.executeQuery("SELECT * FROM datas WHERE year = "
				+ year + " && month =" + month + "&& day=" + day + ";");
		String result = "";
		while (rs.next()) {
			int id = rs.getInt("data_id");
			String contents = rs.getString("contents");
			if (contents != null) {
				result += id + " " + year + " " + month + " " + day + " "
						+ contents + "\n";
			}
		}
		return result;
	}

	public Restlet restlet3 = new Restlet(getContext()) {
		@Override
		public void handle(Request request, Response response) {
			// Print the user name of the requested orders
			String title = (String) request.getAttributes().get("title");
			String publisher = (String) request.getAttributes()
					.get("publisher");
			String year = (String) request.getAttributes().get("year");
			String price = (String) request.getAttributes().get("price");
			try {
				insertBooks(stmt, title, publisher, year, price);
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			String message = "";
			try {
				message += selectBooks(stmt);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			response.setEntity(message, MediaType.TEXT_PLAIN);
		}

		private void insertBooks(Statement stmt, String title,
				String publisher, String year, String price)
				throws SQLException {
			// TODO Auto-generated method stub
			// INSERT INTO books (title, publisher, year, price)
			// VALUES('Operating System Concepts', 'Wiley', '2003', 30700);
			stmt.execute("INSERT INTO books (title, publisher, year, price)"
					+ "VALUES('" + title + "','" + publisher + "','" + year
					+ "'," + price + ");");
		}
	};

	public Restlet restlet2 = new Restlet(getContext()) {
		@Override
		public void handle(Request request, Response response) {
			// Print the user name of the requested orders
			String name = (String) request.getAttributes().get("name");
			String message = "";
			try {
				message += selectBooks(stmt, name);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			response.setEntity(message, MediaType.TEXT_PLAIN);
		}
	};
	public Restlet restlet1 = new Restlet() {
		public void handle(Request request, Response response) {
			String message = "";
			try {
				message += selectBooks(stmt);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			response.setEntity(message, MediaType.TEXT_PLAIN);
		}
	};
}

'Programming > JAVA,JSP' 카테고리의 다른 글

JAVA JNI  (0) 2013.05.01
Eclipse Tips  (0) 2013.04.30
JAVA MYSQL 활용 4 Android App  (0) 2013.04.28
JAVA MYSQL 활용 3  (0) 2013.04.28
MYSQL REST 실습 코드 2  (0) 2013.04.28

JAVA MYSQL 활용 4 Android App

Programming/JAVA,JSP 2013. 4. 28. 15:16 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {
	TextView result;

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

	public void mOnClick(View v) {
		Log.d("mOnClick", "mOnClick s1");
		String html;
		downloadThread dt = new downloadThread("http://192.168.0.3:8182/books");
		result = (TextView) findViewById(R.id.text);
		dt.start();
	}

	class downloadThread extends Thread {

		public String addr;

		public downloadThread(String addr) {
			this.addr = addr;
		}

		public void run() {

			StringBuilder html = new StringBuilder();
			try {
				URL url = new URL(addr);
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				if (conn != null) {
					conn.setConnectTimeout(10000);
					conn.setUseCaches(false);
					if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
						BufferedReader br = new BufferedReader(
								new InputStreamReader(conn.getInputStream()));
						while (true) {
							String line = br.readLine();
							if (line == null)
								break;
							html.append(line + '\n');
						}
						br.close();
					}
					conn.disconnect();
				}
			} catch (Exception ex) {
			}
			Message msg = new Message();
			msg.obj = html.toString();
			mHandler.sendMessage(msg);
		};
	};

	Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			result.setText((String) msg.obj);
		};
	};
}

'Programming > JAVA,JSP' 카테고리의 다른 글

Eclipse Tips  (0) 2013.04.30
JAVA MYSQL ANDROID REST 활용  (0) 2013.04.28
JAVA MYSQL 활용 3  (0) 2013.04.28
MYSQL REST 실습 코드 2  (0) 2013.04.28
MYSQL & REST 실습 코드  (0) 2013.04.28

JAVA MYSQL 활용 3

Programming/JAVA,JSP 2013. 4. 28. 14:20 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.restlet.Application;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.Restlet;
import org.restlet.Server;
import org.restlet.data.MediaType;
import org.restlet.data.Protocol;
import org.restlet.routing.Router;

public class test extends Application{
	public static Connection makeConnection() {
		String url = "jdbc:mysql://localhost/book_db";
		String id = "root";
		String password = "green";
		Connection con = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			System.out.println("드라이버 적재 성공");
			con = DriverManager.getConnection(url, id, password);
			System.out.println("데이터베이스 연결 성공");
		} catch (ClassNotFoundException e) {
			System.out.println("드라이버를 찾을 수 없습니다.");
		} catch (SQLException e) {
			System.out.println("연결에 실패하였습니다.");
		}
		return con;
	}
	public static Statement stmt;
	public static void main(String[] args) throws Exception {
		Connection con = makeConnection();
		stmt = con.createStatement();
		Server server = new Server(Protocol.HTTP, 8182);
		server.setNext(new test());
		server.start();
	}
	public static String selectBooks(Statement stmt) throws SQLException {
		ResultSet rs = stmt.executeQuery("SELECT * FROM books");
		String result = "";
		while (rs.next()) {
			int id = rs.getInt("book_id");
			String title = rs.getString("title");
			String publisher = rs.getString("publisher");
			String year = rs.getString("year");
			if( title != null)
			{
				result += id + " " + title +" " + publisher +" " + year + "\n";
			}
		}
		return result;
	}
	public static String selectBooks(Statement stmt, String name) throws SQLException {
		ResultSet rs = stmt.executeQuery("SELECT * FROM books WHERE publisher = '" + name + "'");
		String result = "";
		while (rs.next()) {
			int id = rs.getInt("book_id");
			String title = rs.getString("title");
			String publisher = rs.getString("publisher");
			String year = rs.getString("year");
			if( title != null)
			{
				result += id + " " + title +" " + publisher +" " + year + "\n";
			}
		}
		return result;
	}
	@Override
	public Restlet createInboundRoot() {
		Router router = new Router();
		router.attach("http://localhost:8182/books", restlet1);
		router.attach("http://localhost:8182/books/where/{name}", restlet2);
		router.attach("http://localhost:8182/books/insert/{title}/{publisher}/{year}/{price}", restlet3);
		//(title, publisher, year, price)
		return router;
	}

	public Restlet restlet3 = new Restlet(getContext()) {
		@Override
		public void handle(Request request, Response response) {
			// Print the user name of the requested orders
			String title = (String)request.getAttributes().get("title");
			String publisher = (String)request.getAttributes().get("publisher");
			String year = (String)request.getAttributes().get("year");
			String price = (String)request.getAttributes().get("price");
			try {
				insertBooks(stmt,title,publisher,year,price);
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			String message = "";
			try {
				message += selectBooks(stmt);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			response.setEntity(message, MediaType.TEXT_PLAIN);
		}

		private void insertBooks(Statement stmt, String title,
				String publisher, String year, String price) throws SQLException {
			// TODO Auto-generated method stub
			//INSERT INTO books (title, publisher, year, price)
			//VALUES('Operating System Concepts', 'Wiley', '2003', 30700);
			stmt.execute("INSERT INTO books (title, publisher, year, price)"
					+"VALUES('"+title+"','"+publisher+"','"+year+"',"+price+");");
		}
	};

	public Restlet restlet2 = new Restlet(getContext()) {
		@Override
		public void handle(Request request, Response response) {
			// Print the user name of the requested orders
			String name = (String)request.getAttributes().get("name");
			String message = "";
			try {
				message += selectBooks(stmt, name);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			response.setEntity(message, MediaType.TEXT_PLAIN);
		}
	};
	public Restlet restlet1 = new Restlet() {
		public void handle(Request request, Response response) {
			String message = "";
			try {
				message += selectBooks(stmt);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			response.setEntity(message, MediaType.TEXT_PLAIN);
		}
	};
}

'Programming > JAVA,JSP' 카테고리의 다른 글

JAVA MYSQL ANDROID REST 활용  (0) 2013.04.28
JAVA MYSQL 활용 4 Android App  (0) 2013.04.28
MYSQL REST 실습 코드 2  (0) 2013.04.28
MYSQL & REST 실습 코드  (0) 2013.04.28
JAVA MYSQL 활용 1  (0) 2013.04.27

MYSQL REST 실습 코드 2

Programming/JAVA,JSP 2013. 4. 28. 13:34 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.restlet.Application;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.Restlet;
import org.restlet.Server;
import org.restlet.data.MediaType;
import org.restlet.data.Protocol;
import org.restlet.routing.Router;

public class test extends Application{
	public static Connection makeConnection() {
		String url = "jdbc:mysql://localhost/book_db";
		String id = "root";
		String password = "green";
		Connection con = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			System.out.println("드라이버 적재 성공");
			con = DriverManager.getConnection(url, id, password);
			System.out.println("데이터베이스 연결 성공");
		} catch (ClassNotFoundException e) {
			System.out.println("드라이버를 찾을 수 없습니다.");
		} catch (SQLException e) {
			System.out.println("연결에 실패하였습니다.");
		}
		return con;
	}
	public static Statement stmt;
	public static void main(String[] args) throws Exception {
		Connection con = makeConnection();
		stmt = con.createStatement();
		Server server = new Server(Protocol.HTTP, 8182);
		server.setNext(new test());
		server.start();
	}
	public static String selectBooks(Statement stmt) throws SQLException {
		ResultSet rs = stmt.executeQuery("SELECT * FROM books");
		String result = "";
		while (rs.next()) {
			int id = rs.getInt("book_id");
			String title = rs.getString("title");
			if( title != null)
			{
				result += id + " " + title + "\n";
			}
		}
		return result;
	}
	public static String selectBooks(Statement stmt, String name) throws SQLException {
		ResultSet rs = stmt.executeQuery("SELECT * FROM books WHERE publisher = '" + name + "'");
		String result = "";
		while (rs.next()) {
			int id = rs.getInt("book_id");
			String title = rs.getString("title");
			if( title != null)
			{
				result += id + " " + title + "\n";
			}
		}
		return result;
	}
	@Override
	public Restlet createInboundRoot() {
		Router router = new Router();
		router.attach("http://localhost:8182/books", restlet1);
		router.attach("http://localhost:8182/books/where/{name}", restlet2);

		return router;
	}

	public Restlet restlet2 = new Restlet(getContext()) {
		@Override
		public void handle(Request request, Response response) {
			// Print the user name of the requested orders
			String name = (String)request.getAttributes().get("name");
			String message = "";
			try {
				message += selectBooks(stmt, name);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			response.setEntity(message, MediaType.TEXT_PLAIN);
		}
	};
	public Restlet restlet1 = new Restlet() {
		public void handle(Request request, Response response) {
			String message = "";
			try {
				message += selectBooks(stmt);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			response.setEntity(message, MediaType.TEXT_PLAIN);
		}
	};
}

'Programming > JAVA,JSP' 카테고리의 다른 글

JAVA MYSQL 활용 4 Android App  (0) 2013.04.28
JAVA MYSQL 활용 3  (0) 2013.04.28
MYSQL & REST 실습 코드  (0) 2013.04.28
JAVA MYSQL 활용 1  (0) 2013.04.27
JAVA MYSQL Test  (0) 2013.04.27