컴퓨터활용/프로프레임

프로프레임 소스 문자열 변환 프로그램

멜번초이 2008. 6. 18. 13:43
반응형

단어 변환 프로그램입니다.

긴 함수를 짧은 함수로 변환하는 프로그램입니다. 어젯밤에 만들었죠.. (버그 있을 수 있음 )
프로프레임의 모든 소스는 xml 형태로  DB에 저장됩니다. 프로그램 내의 특정 문자열을 다른 것으로 바꾸기 위해서는 프로프레임 스튜디오에서 하나씩 열어서 전체바꾸기 를 일일이 수작업으로 해 줘야 합니다.
본 프로그램은 DB 에 직접 접속하여 XML 속에 있는 특정 문자열을 변경한 후 다시 UPDATE 시켜 주는 프로그램입니다.  본 프로그램은 티맥스소프트의 오은경 전임이 만든 프로그램을 약간 변형(개작) 한 것임을 밝혀 둡니다.

1. 설치

적당한 곳에 첨부의 2개 파일을 갖다 놓으세요. 자바가 실행될 수 있는 환경이 이미 되어 있어야 합니다.
돌릴려면 ojdbc14.jar 와 ConvWord.class 가 필요합니다.

2. 사용법

사용법은 convword 라고 치면 간단한 사용법 안내가 나옵니다.

예를 들어 C:\ConvWord 에 파일 2개를 갖다 놓았다고 한다면    

C:\ConvWord>convword
This programe will replace word in source!
you need additional action for source generation in proframe studio.
Usage : ConvWord [-s|-r] physical_name [data_file]
        -s : show the list
        -r : replace the word

example :  ConvWord sfee2929a -r C:/hanabank_dev/ProFrame/convlist.dat
           data_file must have separate word with space between old and new.


간단한 사용설명이 나오게 되죠.

C:\ConvWord>convword -r sirt5000a
sirt5000a : 금리목록관리메인 PGM
sirt5000a.c [272] pfmStringIsNull -> pfmStrIsNull
정상적으로 완료되었습니다.

여기서 파일명과 해당 라인수 이전 단어와 변경단어를 보여 줍니다. 변환단어 데이타 파일은  아래와 같이 스페이스로 분리해서 텍스트 파일을 만들어 주심 됩니다.  그러나 아래 로직을 보시면 알겠지만 간단한 프로그램이라 단순 변환시켜 버리기 때문에 다음과 같이 파일을 만드시면 예기치 않은 결과를 얻게 됩니다.

get      gt
getName  gtNm

이런 경우 먼저 get을 get 을 gt 로 먼저 바뀌게 되므로 정작 getName 을 바꿀 순서가 되었을 때는  getName 은 이미 gtName 으로 바뀌어져 있는 상태라 변환이 안 됩니다. 결국 getName 을 gtNm 으로 바꾸고자 하는 당초 의도대로 바뀌지 않고 gtName 으로 어중간 하게 바뀐 채로 남게 됩니다.

이것을 해결 방법은 프로그램을 고쳐서 데이타의 소팅 기능을 넣거나 아니면 데이타파일을 만들 때 아예 소팅을 역순으로 해 놓으면 됩니다.  이렇게요..

getName  gtNm
get      gt



3. 주의사항

a. 사용시 데이타파일을 특별히 지정하지 않는다면 디폴트 금지함수 리스트파일이 적용됩니다.
    파일이 바꿀 단어를 더 추가하고자한다면 직접 수정하시고 convword 실행할 때 직접 파일을 지정해야 합니다.
b. convword  프로그램은 DB 상의 소스 변경이기 때문에 스튜디오에서 소스생성 버튼을 눌러줘야
    실제 개발서버 디렉토리에도 소스가 생성된다는 점을 유념하세요.
c. 그리고  검증되지 않은 프로그램이니 부작용에 대하여 책임 지지 않습니다.


ConvWord.java

import java.sql.*;
import java.io.*;
import java.util.*;

import oracle.jdbc.*;
import oracle.sql.*;

public class ConvWord
{

  static int arrSize=10000;
  static private String datafile;
  static private String physicalName;
  static private String option;
  static String[]  sr = new String[arrSize];
  static String[]  tr = new String[arrSize];
  static int ix=0;

  public static void main (String args [])  throws Exception
  {
    if (args.length < 2) {
      showUsage();
      return;
    } else if (args.length == 2) {
      datafile = "convlist.dat";
    } else {
      datafile = args[2];
    }

    option  = args[0];
    physicalName = args[1];

    if ( !"-s".equals(option) && !"-r".equals(option) ) {
      showUsage();
      return;
    }

    FileReader fr = null;
    BufferedReader br = null;
    try {
      fr = new FileReader(datafile);
      br = new BufferedReader(fr);
    } catch (Exception e) {
      System.out.println("file read error. check the file "+datafile);
      return;
    }

    String txt;

    while((txt = br.readLine()) != null)
    {

      StringTokenizer token = new StringTokenizer(txt," ");
      sr[ix] = token.nextToken().trim();
      tr[ix] = token.nextToken().trim();
      ix++;
      if ( ix >= arrSize) {
        System.out.println("maximum word count cannot be over "+arrSize+". ");
        br.close();
        return;
      }
    }
    br.close();


    Connection conn = null;
    DriverManager.registerDriver( new oracle.jdbc.driver.OracleDriver() );

    try
    {

      conn = DriverManager.getConnection( "jdbc:oracle:thin:@xx.xx.xx.xx:port:SID", "id","passwd" );
      conn.setAutoCommit (false);
      Statement stmt_name = conn.createStatement();
      Statement stmt_meta = conn.createStatement();

      BLOB blob = null;
      String logicalName = null;
      String resourceId = null;
      String new_meta = null;

      ResultSet rs = stmt_name.executeQuery(" SELECT logical_name, resource_id "+
                                            " FROM dev_resource WHERE physical_name = '"+physicalName+"'");
      if (rs.next()) {
        logicalName = rs.getString("logical_name");
        resourceId  = rs.getString("resource_id");

        System.out.println( physicalName +" : " + logicalName);

      }else {
        System.out.println("등록된 프로그램이 없습니다. 프로그램명이 ["+physicalName+ "]이 맞는지 확인하세요");
        return;
      }

      ResultSet rset = stmt_meta.executeQuery ("SELECT meta FROM dev_resource_contents WHERE resource_id = " +
                                               "(SELECT resource_id FROM dev_resource " +
                                               " WHERE physical_name = '"+physicalName+"')" );
      if (rset.next()) {

         blob = ((OracleResultSet)rset).getBLOB("meta");
         new_meta = replaceWord(blob );
      } else {
         System.out.println("검색된 메타 결과가 없습니다.");
      }

      if ("-r".equals(option)) {
        if ( updateMetaData(conn, stmt_meta, new_meta, resourceId)) {
          System.out.println("정상적으로 완료되었습니다.");
        } else {
          System.out.println("작업을 실패하였습니다.");
        }
      }

      rs.close();
      rset.close();

      stmt_name.close();
      stmt_meta.close();
      conn.commit();
      conn.close();
    } catch (SQLException e) {
      System.out.println("다음과 같은 문제가 발생하였습니다.\n");
      System.out.println(e.getMessage());
      e.printStackTrace();
      conn.close();
    } catch(Exception ex){
      System.out.println("다음과 같은 문제가 발생하였습니다.\n");
      System.out.println(ex.getMessage());
      ex.printStackTrace();
      conn.close();
    }
  }


  static String replaceWord (BLOB blob  ) throws Exception
  {
    InputStream input = blob.getBinaryStream();
    BufferedReader reader = new BufferedReader( new InputStreamReader( input, "UTF8" ));
   
    String line;
    String new_meta = "";
    String newLine = "";
    int lineno=1;
    while ( (line = reader.readLine()) != null )
    {
      lineno++;
      if (line == null){
        break;
      }
       // loop needed
      for ( int i=0; i<ix; i++) {
        newLine = "";
        int idx = line.indexOf(sr[i]);
        int idx2 = idx + sr[i].length();
        if (idx != -1) {
          System.out.println(physicalName+".c ["+lineno+"] "+sr[i]+" -> "+tr[i]);
          newLine = newLine + line.substring(0, idx) + tr[i] + line.substring(idx2);
        } else {
          newLine = line;
        }
          line = newLine;
      }
   
      new_meta = new_meta + newLine + "\n";
    }
    return new_meta;
  }


  static boolean updateMetaData (Connection conn, Statement stmt_meta, String new_meta, String resource_id) throws Exception
  {
    boolean insertOK = true;
    BLOB blob = null;
 
    try { // empty 시킴
      stmt_meta.executeUpdate("UPDATE dev_resource_contents " +
                              "SET meta=empty_blob() " +
                              "WHERE resource_id ='" + resource_id +"'");
    } catch(SQLException e) {
      System.err.println("<debug>BbsInput.modifyData1 : " + e.getMessage());
      insertOK = false;
    }
 
    if (insertOK)
    {
      try
      { // 변경된 내용을 셋팅
         ResultSet rset = stmt_meta.executeQuery("SELECT meta FROM dev_resource_contents " +
                                                 "WHERE resource_id ='" + resource_id +"' FOR UPDATE");
         while(rset.next())
         {
           blob =((OracleResultSet)rset).getBLOB("meta");
           Writer out = new OutputStreamWriter(blob.getBinaryOutputStream(), "UTF8");
           out.write(new_meta);
           out.close();
         }
      }
      catch(Exception e) {
        System.out.println("업데이트를 실패하였습니다.");
        System.out.println(e.getMessage());
        e.printStackTrace();
        return false;
      }
    }
    return true;
  }
 
  static void showUsage() {
    System.out.println("This programe will replace word in source!");
    System.out.println("you need additional action for source generation in proframe studio.");
    System.out.println("Usage : ConvWord [-s|-r] physical_name [data_file] ");
    System.out.println("        -s : show the list");
    System.out.println("        -r : replace the word");
    System.out.println("");
    System.out.println("example :  ConvWord sfee2929a -r C:/hanabank_dev/ProFrame/convlist.dat ");
    System.out.println("           data_file must have separate word with space between old and new.");
  }

}

convword.bat

@echo off
java -cp ojdbc14.jar;ConvWord.class ConvWord  %1 %2 %3


 

반응형