출처

위 기사는 Object serialization 를 사용하여 object를 로컬에 파일로 저장하거나 socket으로 전송하는 단순한 example 을 보여주고 있다. java.io.Serializable 객체를 implement 한 클래스를 소켓으로 어떻게 송/수신 한는지 보여주는 샘플을 간단히 정리해 보았다.

Server
ObjectInputStream   : readObject() 메소드를 사용하여 input stream 객체를 reading 한다.
ObjectOutputStream : writeObject() 메소드를 사용하여 output stream 객체를 writing 한다.

ObjectServer.java
- 무조건 요청을 받아주는 무식한 서버.
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ObjectServer extends Thread {

    private ServerSocket serverSocket;
   
    public ObjectServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
        this.start();
    }
   
    public void run() {
        while(true) {           
            Socket client;
            try {
                System.out.println("Waiting for connections.");
                client = serverSocket.accept();
                System.out.println("Accepted a connection from: "+client.getInetAddress());
                WorkerThread c = new WorkerThread(client);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
           
        }

    }
}

WorkerThread.java
- 요청을 처리하고 응답값을 보내는 worker thread.
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import study.socket.serializing.ResponseVo;
import study.socket.serializing.RequestVo;

public class WorkerThread extends Thread {
    private Socket client = null;
    // read stream
    private ObjectInputStream ois = null;
    // write stream
    private ObjectOutputStream oos = null;
       
    public WorkerThread() {}

    public WorkerThread(Socket clientSocket) {
        client = clientSocket;
       
        try {
            ois = new ObjectInputStream(client.getInputStream());
            oos = new ObjectOutputStream(client.getOutputStream());
        } catch(Exception e1) {
            try {
                client.close();
            }catch(Exception e) {
                System.out.println(e.getMessage());
            }
            return;
        }
        this.start();
    }
   
    public void readObject() throws IOException, ClassNotFoundException {
        RequestVo requestVo = (RequestVo) ois.readObject();
       
        System.out.println("id:"+requestVo.getId());
        System.out.println("msg:"+requestVo.getMsg());
    }
   
    public void wirteObject() throws IOException {
        ResponseVo responseVo = new ResponseVo();
        responseVo.setId("response id");
        responseVo.setMsg("응답값 전송했음.. 알아서 처리하삼.");
       
        oos.writeObject(responseVo);
    }
   
    public void run() {
       
        try {
            readObject();
            wirteObject();

            oos.flush();
            // close streams and connections
            ois.close();
            oos.close();
            client.close();
        } catch(Exception e) {}              
            try {
                ois.close();
                oos.close();
                client.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
           }
    }

Serializing Custom Classes
Serializable interface 를 implements 한 custom class 를 작성한다.

RequestVo.java
- 요청 객체
import java.io.Serializable;

public class RequestVo implements Serializable {

    private String id;
    private String msg;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }  
}

ResponseVo.java
- 응답 객체
import java.io.Serializable;

public class ResponseVo implements Serializable {

    private String id;
    private String msg;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
}

Client

ObjectClient.java
import java.io.*;
import java.net.*;
import java.util.*;

import study.socket.serializing.ResponseVo;
import study.socket.serializing.RequestVo;

public class ObjectClient {

    public static void main(String argv[]) {
          ObjectOutputStream oos = null;
          ObjectInputStream ois = null;
          Socket socket = null;

          try {
            // open a socket connection
            socket = new Socket("127.0.0.1", 20001);
            // open I/O streams for objects
            oos = new ObjectOutputStream(socket.getOutputStream());
            ois = new ObjectInputStream(socket.getInputStream());
           
            // send an object to the server
            RequestVo requestVo = new RequestVo();
            requestVo.setId("request id");
            requestVo.setMsg("요청했다.. 빨리 보내라 오바.");           
            oos.writeObject(requestVo);
           
            // read an object from the server
            ResponseVo rcvVo = (ResponseVo) ois.readObject();
            System.out.println("id:" + rcvVo.getId());
            System.out.println("msg:" + rcvVo.getMsg());
            oos.close();
            ois.close();
          } catch(Exception e) {
            System.out.println(e.getMessage());
          }
       }
}


'java > socket' 카테고리의 다른 글

DataInputStream 에서 전체 byte[] 읽기  (0) 2012.06.29
Posted by 짱가쟁이
2010. 6. 30. 09:33
출처

int to String
String str = Integer.toString(i);
String str = "" + i;


String to int
int i = Integer.parseInt(str);

int i = Integer.valueOf(str).intValue();


double to String
String str = Double.toString(d);


long to String
String str = Long.toString(l);


float to String
String str = Float.toString(f);


String to double
double d = Double.valueOf(str).doubleValue();


String to long
long l = Long.valueOf(str).longValue();

long l = Long.parseLong(str);


String to float
float f = Float.valueOf(str).floatValue();


decimal to binary
String binstr = Integer.toBinaryString(i);


decimal to hexadecimal
String hexstr = Integer.toString(i, 16);

String hexstr = Integer.toHexString(i);

Integer.toHexString( 0x10000 | i).substring(1).toUpperCase());


hexadecimal(String) to int
int i = Integer.valueOf("B8DA3", 16).intValue();

int i = Integer.parseInt("B8DA3", 16);


ASCII Code to String
String char = new Character((char)i).toString();


Integer to ASCII Code
int i = (int) c;


Integer to boolean
boolean b = (i != 0);


boolean to Integer
int i = (b)? 1 : 0;


'java > util' 카테고리의 다른 글

[java] - 소수점 자르기 (duble type)  (0) 2010.06.30
[java] - base54 String decode  (0) 2010.06.30
[java] - 외부 프로그램 실행하기..  (0) 2010.06.29
[java] - byte array to int  (0) 2010.06.29
[java] - int to byte array  (0) 2010.06.29
Posted by 짱가쟁이

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

<beans default-autowire="no" default-lazy-init="false"
 default-dependency-check="none"
 xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:jee="http://www.springframework.org/schema/jee"
 xsi:schemaLocation="
 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
 http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">

 <!-- DB 설정파일 위치 지정 -->
 <bean id="dbConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="location"><value>WEB-INF/config/db.properties</value></property>
 </bean>

    <!-- dataSource 정의 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName"><value>${jdbc.driverClassName}</value></property>
        <property name="url"><value>${jdbc.url}</value></property>
        <property name="username"><value>${jdbc.username}</value></property>
        <property name="password"><value>${jdbc.password}</value></property>
        <property name="maxActive"><value>${jdbc.maxActive}</value></property>
        <property name="maxIdle"><value>${jdbc.maxIdle}</value></property>
        <property name="maxWait"><value>${jdbc.maxWait}</value></property>
    </bean>
 
    <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
     <property name="dataSource" ref="dataSource" />
     <property name="configLocation" value="WEB-INF/config/sqlMapConfig.xml" />
    </bean>    
   
    <bean id="transactionManager"
  class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="dataSource"/>
 </bean>
 
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
     <tx:attributes>
      <tx:method name="execute*" read-only="false" rollback-for="BizException" propagation="REQUIRED"/>
     </tx:attributes>
    </tx:advice>
   
    <aop:config>
     <aop:pointcut id="testServiceProcOperation" expression="execution(* test.logic.proc.*Proc.*(..))" />
     <aop:advisor advice-ref="txAdvice" pointcut-ref="testServiceProcOperation"/>
    </aop:config>
</beans>

Posted by 짱가쟁이

Anroid 를 시작하면서 가장 당황한 부분이.. System.out.print() 로 로그를 볼 수 없다는 것이다.


대신 유용한 넘으로 Log가 있다.


Log.v() 를 이용하여 로그를 작성하면 console 창에 나올거 같지만.. 쩌ㅃ~ LogCat 창이 따로 존재한다.


Window-Show View-Android-LogCat 선택

 

Example
Log.v("bbaeggar", "grid position : " + gridView.getSelectedItemPosition() );


'android' 카테고리의 다른 글

[android] - XML 가지고 놀기  (0) 2010.06.29
[android] - AlertDialog 사용하기  (0) 2010.06.29
[android] - Intent  (0) 2010.06.29
Posted by 짱가쟁이
2010. 6. 30. 09:25
출처

SOAP (Simple Object Access Protocol)

 

소프트웨어간에 메시지(오브젝트)를 교환하는 형태의 프로토콜이다. 이는 확장가능한 분산 프로토콜로 HTTP나 SMTP 등의 다양한 통신 프로토콜을 사용하여 전달할 수 있으며, XML-RPC를 확장 계승한 형태이다.

SOAP 는 XML을 근간으로 헤더(header)와 바디(body)를 조합하는 디자인 패턴으로 설계되어
있다. 헤더(header)는 선택사항으로 반복이나 보안 및 트랜잭션(transaction)을 정보로 하는 메타정보를 갖고 있으며, 바디(body) 부분은 핵심 정보로 이루어져 있다.

 

XML-RPC (eXtensible Markeup Language - Remote Procedure Call)

 

HTTP를 통해 XML 기반의 메시지를 교환하는 프로토콜이다.
XML에 데이터 타입을 담을 수 있는 간단한 방법을 제공하여 원격지에 있는 함수(method)를 호출할 수 있도록 구성되어 있다.

* SOAP은 그 자체가 하나의 독립적인 HTTP 메시지를 구성했지만, XML-RPC는 HTTP의 POST 요청의 내용을 단순히 XML로 구성한 것에서 차이가 있다.
공통점은 인터넷 표준인 HTTP 프로토콜을 이용하고 플랫폼으로부터 독립적인 XML을 이용한다는 것.

 

 


XML-RPC

SOAP

CORBA

 

개발편의

개발이 용이.

쉬운 구조.

XML-RPC

보다 복잡함.

개발이 어려움.

매우 복잡함.

 

통합

운영체제 및 언어

독립적.

스텁코드가 필요 없음.

운영체제 및 언어에

독립적.

스텁 코드가 불필요.

제품간에 호환성에

다소 문제가 있음.

클라이언트 스텁

필요함.

 

서비스

형태

간단한 웹 서비스.

복잡한 웹 서비스.

응용프로그램

및 전사적 시스템.

 

확장

간단한 구조.

XML 스키마 기반에 확장성이 뛰어남.

확장성이 뛰어남.

 

보안

HTTPS.

HTTPS

XML 서명(진행 중)

XML 암호화(진행 중)

XML ACL(진행 중)

Object Security

Service.

ORB기반

보안 메커니즘.

 

서비스

제공서비스가 없음.

UDDI, 보안.

Name Service. Event Service, Transaction Service, Object Security Service 등 다수.

 

 


Posted by 짱가쟁이
swing tutorial 의 예제를 보면 알아서 테이블 헤더의 값이 중앙에 배치되는데.. 요넘.. NetBeans 를 사용해서 생성한 테이블은 기본이 왼쪽 정렬이 된다. 이것저것 뒤져봐도 마땅한 방법이 생각이 안나.. 그냥 코드로 추가했다.

이렇게 무식한 방법말고, 좋은 방법이 있을 법도 한데.. 더이상 찾기가 귀찮다. 쩌ㅃ~

밑의 소스코드를 보면 현재 테이블의 Header CellRenderer 를 가져와서 랜더의 수평 정렬을 center 로 설정했다.

Code
DefaultTableCellRenderer renderer =  

                         (DefaultTableCellRenderer)table.getTableHeader().getDefaultRenderer();
renderer.setHorizontalAlignment(SwingConstants.CENTER);
table.getTableHeader().setDefaultRenderer(renderer);


Posted by 짱가쟁이

<실행화면>



Cell Editor 를 콤보박스로 변경하는 단순한 형태의 코드.

changeCellEditor(table, table.getColumnModel().getColumn(3));

void changeCellEditor(JTable table, TableColumn column) {

        JComboBox comboBox = new JComboBox();
        comboBox.addItem("사람");
        comboBox.addItem("요크");
        comboBox.addItem("마르티스");
        comboBox.addItem("MIX");
        column.setCellEditor(new DefaultCellEditor(comboBox));

        DefaultTableCellRenderer renderer =
                new DefaultTableCellRenderer();
        renderer.setToolTipText("클릭하면 콤보박스로 변경됩니다.");
        column.setCellRenderer(renderer);
}


위 코드 샘플의 bold line 이 cell editor 를 변경하는 부분이다.

출처

Posted by 짱가쟁이

쉽게 번 돈은 쉽게 날려버린다고.. 이거 어딘가에서 쉽게 찾아 사용하던 코드라 그런지.. 또 사용할려고 하니.. 도통 기억이 안남..

보통 테이블에서 셀을 수정하다가(셀이 editing 상태임) 버튼을 눌러서 수정된 값을 저장할려고 시도하는 경우가 있다. 그런데 JTable 이라는 넘은 셀이 수정중이면 엔터를 치거나, 아니면 포커스를 변경해줘야지 값이 변경된다. 물론 사용자한테 책임을 떠 넘기고 '니들이 사용할 때 잘 사용해라' 라고 할 수 있겠지만, 보통은 이런식으로 작업을 하는 사람이 없을 듯 싶다.

위 문제를 해결하는 방법을 또 찾기 싫어서 여기에 올림 .. 쩌ㅃ~

1. editCellAt() 를 이용해서 현재 수정중인 값을 가져온다.

2. setValueAt() 넘을 사용해서 가져온 값으로 변경하면 땡.


editCellAt()   : 현재 수정중인 셀의 값을 가져오는 넘.

setValueAt() : 특정 셀에 값을 삽입한다.

editingStopped()  : 처음에 이넘을 사용하면 될듯 싶었지만. 저넘은 단순히 에디팅이 끝났다고 알려주기만 하는듯 싶다. 뭐.. 엄밀히 말해서 셀의 에디팅 상태를 종료하는 넘으로 해석하면 될듯.

 

table.setValueAt(table.editCellAt(table.getSelectedRow(), table.getSelectedColumn()), table.getSelectedRow(), table.getSelectedColumn());

table.editingStopped(null);

Posted by 짱가쟁이

하나만 만들어 놓고 언제나 사용할 수 있는 Table Model 을 만들자는 취지로 시작했지만.. Table 의 요구사항 변경에 따라 수정 할 수 밖에 없다. 좀 아쉬운 감이 있지만 모든걸 다 적용시키기는 힘들다는 결론에 다다르고 단순히 범용적으로 사용할 수 있는 넘 하나만 만들었다.

TableModel 은 column name 과 data 두개의 부분으로 나눠지는데.. 이 두개만 생성해 model에 등록하면 알아서 동작하는 넘으로 작성되었다. Reflection 기능을 이용하니 손쉽게 작성된듯...


MyTableModel.java

AbstractTableModel 클래스를 상속받아 구현된 단순한 넘. 기본 골격은 (http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#validtext) 참조했으며 신규 추가된 부분이 data 와 header 부분을 Value Object로 변경한 부분이다. 물론 변경된 사항에 따라서 column name 과 data get, set 부분이 수정되었다.

import javax.swing.table.AbstractTableModel;

 /**
 *
 * @author Administrator
 */
public class MyTableModel extends AbstractTableModel {

    private AbstractTableVo[] data;
    private CustomTableColumnName[] columnNames;

    public Object[] longValues;

    public Object[] getLongValues() {
        return longValues;
    }

    public void setLongValues(Object[] longValues) {
        this.longValues = longValues;
    }

    public CustomTableColumnName[] getColumnNames() {
        return columnNames;
    }

    public void setColumnNames(CustomTableColumnName[] columnNames) {
        this.columnNames = columnNames;
    }

   
    public AbstractTableVo[] getData() {
        return data;
    }

    public void setData(AbstractTableVo[] data) {
        this.data = data;
    }

    public String getColumnName(int col) {
        return columnNames[col].getName();
    }


    public int getRowCount() {
        return data.length;
    }

    public int getColumnCount() {
        return columnNames.length;
    }

    public Object getValueAt(int rowIndex, int columnIndex) {
        return data[rowIndex].getValueAt(columnNames[columnIndex].getId());
    }
   
    /*
     * Don't need to implement this method unless your table's
     * editable.
     */
    public boolean isCellEditable(int row, int col) {
        return true;
    }

    /*
     * Don't need to implement this method unless your table's
     * data can change.
     */
    public void setValueAt(Object value, int row, int col) {

        data[row].setValueAt(value, columnNames[col].getId());

    }

    /*
     * JTable uses this method to determine the default renderer/
     * editor for each cell.  If we didn't implement this method,
     * then the last column would contain text ("true"/"false"),
     * rather than a check box.
     */
    public Class getColumnClass(int c) {
        return getValueAt(0, c).getClass();
    }

}


SampleVo.java
- 샘플로 작성된 Table Data Value 객체. AbstractTableVo 클래스를 상속받아야 하는 rule 만 지켜주면 만사형통임.

/**
 *
 * @author Administrator
 */
public class SampleVo extends AbstractTableVo {

    private String firstName;
    private String lastName;
    private String sport;
    private Integer ofYears;
    private Boolean vegetarian;
       
    public Boolean getVegetarian() {
        return vegetarian;
    }

    public void setVegetarian(Boolean vegetarian) {
        this.vegetarian = vegetarian;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Integer getOfYears() {
        return ofYears;
    }

    public void setOfYears(Integer ofYears) {
        this.ofYears = ofYears;
    }

    public String getSport() {
        return sport;
    }

    public void setSport(String sport) {
        this.sport = sport;
    }  
}


AbstractTableVo.java
- CustomTableColumnName, SampleVo 클래스 들이 규칙에 따라 작성되면 TableModel 과 연결되어 알아서 작동한다.

import java.lang.reflect.Method;

/**
 *
 * @author Administrator
 */
public abstract class AbstractTableVo {

    public void setValueAt(Object value, String id) {
         try {

            String methodName = "set" + id.substring(0, 1).toUpperCase() + id.substring(1, id.length());

            Method method = this.getClass().getMethod(methodName , new Class[]{value.getClass()});

            method.invoke(this, value);
        } catch(Exception e) {

        }
    }
  
    public Object getValueAt(String id) {

        try {

            String methodName = "get" + id.substring(0, 1).toUpperCase() + id.substring(1, id.length());

            System.out.println("Method Name : " + methodName);

            Method method = this.getClass().getMethod(methodName ,null);

            return method.invoke(this, null);
        } catch(Exception e) {

        }
        return null;
    }
}


CustomTableColumnName.java
- table의 header 명을 가지는 클래스로 name 필드는 컬럼명을 의미하며, id 는 컴럼명을 의미하는 키로 SampleVo 의 필드명과 일치해야 한다.    

/**
 *
 * @author Administrator
 */
public class CustomTableColumnName {

    private String id;
    private String name;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}


사용법
Model 을 만드는 부분이 화면에 보여질 데이터를 작성하는 것이기 때문에 어쩔 수 없이 무식하고 지져분해질 수 밖에 없는듯하다. 좀더 좋은 방법이 있겠지만, 귀찮니즘 때문인지 단순히 데이터를 무식하게 쌓기만 했다. 사용은 각자가 알아서 하면 될듯하다.

SampleVo 를 토대로 작성했기 때문에 다른 Data Value Object 작성 시 아래 코드는 참조용으로만 사용해야 할듯.

private MyTableModel myTableModel = new MyTableModel();

// Table Model 초기화

private void initTable() {       

        SampleVo[] tableDataValues;
        CustomTableColumnName[] tableColumnNames;

        // table data 초기화

        tableDataValues = new SampleVo[5];
        setData(tableDataValues, 0, "Mary", "Campione", "Snowboarding", new Integer(5), new Boolean(false));
        setData(tableDataValues, 1, "Mary", "Campione", "Snowboarding", new Integer(5), new Boolean(true));
        setData(tableDataValues, 2, "Mary", "Campione", "Snowboarding", new Integer(5), new Boolean(false));
        setData(tableDataValues, 3, "Mary", "Campione", "Snowboarding", new Integer(5), new Boolean(true));
        setData(tableDataValues, 4, "Mary", "Campione", "Snowboarding", new Integer(5), new Boolean(true));
        myTableModel.setData(tableDataValues);

        // column name 초기화
        tableColumnNames = new CustomTableColumnName[5];
        setColumnName(tableColumnNames,0, "firstName", "First Name");
        setColumnName(tableColumnNames,1, "lastName", "Last Name");
        setColumnName(tableColumnNames,2, "sport", "Sport");
        setColumnName(tableColumnNames,3, "ofYears", "# of Years");
        setColumnName(tableColumnNames,4, "vegetarian", "Vegetarian");
        myTableModel.setColumnNames(tableColumnNames);

       // column 최대 사이즈를 구하기 위해서..
       Object[] longValues = {"Sharon", "Campione", "None of the above", new Integer(20), Boolean.TRUE};
       myTableModel.setLongValues(longValues);
    }

     public void setColumnName(CustomTableColumnName[] tableColumnNames, int offset, String id, String name) {
        tableColumnNames[offset] = new CustomTableColumnName();
        tableColumnNames[offset].setId(id);
        tableColumnNames[offset].setName(name);
    }
   
    public void setData(SampleVo[] tableDataValues, int offset, String firstName, String lastName, String sport, Integer integer, Boolean boo) {
        tableDataValues[offset] = new SampleVo();
        tableDataValues[offset].setFirstName(firstName);
        tableDataValues[offset].setLastName(lastName);
        tableDataValues[offset].setSport(sport);
        tableDataValues[offset].setOfYears(integer);
        tableDataValues[offset].setVegetarian(boo);
    }



Posted by 짱가쟁이
2010. 6. 30. 00:36

// Emits an audio beep

Toolkit.getDefaultToolkit().beep();

Posted by 짱가쟁이
이전버튼 1 2 3 4 5 6 7 ··· 11 이전버튼