2011年12月26日 星期一

Visual Studio Code Auto Format

Select the text, hold CTRL and hit K followed by F (CTRL+K-F)
or (Ctrl + E -D) to format the whole document

2011年12月13日 星期二

半形轉全形

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(new Program().ToWChar("abcd,.123"));
        }
        string ToWChar(string v)
        {
            Encoding big5 = Encoding.GetEncoding("big5");
            StringBuilder sb = new StringBuilder();
            int ascii = 0;
            foreach (char c in v.ToCharArray())
            {
                // Big5難字檢查
                string cInBig5 = big5.GetString(big5.GetBytes(new char[] { c }));
                ascii = Convert.ToInt32(c);
                if (ascii == 32 || (c != '?' && cInBig5 == "?")) // 難字亦使用全型空白取代 
                    sb.Append(Convert.ToChar(12288)); // 全型空白 
                else if (ascii < 65248) // 半形檢查 
                    sb.Append(Convert.ToChar(ascii + (ascii < 127 ? 65248 : 0))); // 半型轉全型 
                else
                    sb.Append(Convert.ToChar(ascii));
            }
            return sb.ToString();
        } 
    }
}

2011年8月30日 星期二

String, Stream互轉

  private static String streamToString(InputStream input) throws Exception {
    String output = "";
    while (input.available() > 0) {
      output += ((char) (input.read()));
    }
    return output;
  }
  private static OutputStream stringToStream(String charset) throws IOException {
    byte[] bytes = charset.getBytes();
    InputStream is = null;
    OutputStream os = null;
    is = new ByteArrayInputStream(charset.getBytes("UTF-8"));
    int numRead;
    while ((numRead = is.read(bytes)) >= 0) {
      os.write(bytes, 0, numRead);
    }
    return os;
  }

SQL*Loader基本用法

指令:
sqlldr username/password control=loader.ctl DIRECT=TRUE

loader.ctl:

load data
infile 'd:\work\mydata.csv'
append into table SPECIAL_PRODUCT
fields terminated by "," optionally enclosed by '"'         
( UUID, PROD_NO, PROD_NAME, PRICE )

mydata.csv:

"10013","Scott Tiger","1000",40
"10014","Frank Naude","500",20

參考:
http://www.orafaq.com/wiki/SQL*Loader_FAQ

EnterpriseDB對應的工具是EDB*Loader:
http://www.enterprisedb.com/docs/en/8.4/oracompat/Postgres_Plus_Advanced_Server_Oracle_Compatibility_Guide-191.htm

用jsch執行遠端ssh command的範例

jsch home: http://www.jcraft.com/jsch/

package test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class JschTest {
  /**
   * @param args
   */
  public static void main(String[] args) throws Exception {
    JSch jsch = new JSch();
    System.out.println("Getting session...");
    String host = "yourhost";
    String userName = "userName";
    String password = "password";
    String cmd = "ls";
    Session session = jsch.getSession(userName, host, 22);
    System.out.println("session " + session.getUserName() + "@" + session.getHost() + " established");
    session.setPassword(password);
    Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.connect(40000);
    Channel channel = session.openChannel("exec");
    ((ChannelExec) channel).setCommand(cmd);
    channel.connect();
    channel.run();
    // get I/O streams for remote scp
    OutputStream out = channel.getOutputStream();
    InputStream in = channel.getInputStream();
    String output = "";
    while (channel.isClosed() != true) {
      output += streamToString(in);
    }
    System.out.println("output:\n" + output);
    channel.disconnect();
    session.disconnect();
  }
  private static String streamToString(InputStream input) throws Exception {
    String output = "";
    while (input.available() > 0) {
      output += ((char) (input.read()));
    }
    return output;
  }
}

2011年7月12日 星期二

How a Java Application Can Discover its Process ID (PID)

On UNIX the subclass of Process has a private field with the PID that the default JVM security settings allow you to get via reflection:

  static int getPID(Process process) throws IllegalAccessException, IllegalArgumentException,
      NoSuchFieldException, SecurityException {
    Field field = process.getClass().getDeclaredField("pid");
    field.setAccessible(true);
    return field.getInt(process);
  }


source: http://blog.igorminar.com/2007/03/how-java-application-can-discover-its.html

2011年6月28日 星期二

Read file contents to string

 

package mytest;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
public class ReadFileToStringSample {
  public static void main(String[] args) {
    // In this example we use FileUtils class from Apache
    // Commons IO (commons.io) to read the content of a
    // file. FileUtils have two static methods called
    // readFileToString(File file) and readFileToString(
    // File file, String encoding) that we can user.
    // Here we create an instance of File to hold our
    // sample.txt file.
    File file = new File("sample.txt");
    try {
      // Read the entire contents of sample.txt
      String content = FileUtils.readFileToString(file);
      // For shake of this example we show the file content here.
      System.out.println("File content: " + content);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

2011年4月25日 星期一

讓不同版本的oracle jdbc driver並存於同一個JVM

package manager;

import java.sql.Connection;
import java.sql.DriverManager;
public class OracleDriverManager
{
  public Connection getConnection(String databaseURL, String userName, String password)
  {
    Connection ret = null;
    try {
      Class.forName("oracle.jdbc.driver.OracleDriver");
      ret = DriverManager.getConnection(databaseURL, userName, password);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    return ret;
  }
}

當程式需同時連接oracle 8i及oracle 11g而需不同的jdbc driver時,可另外用一個UrlClassLoader將舊的jdbc driver load進來,並將上面的class也load進與舊版jdbc driver同一個ClassLoader,再主程式用reflection的方式來使用OracleDriverManager去取得connection,如此才能讓DriverManager裡註冊的driver一致。

package tester;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import aic.Oracle8iManager;

public class Oracle8iTester {

    /**
     * @param args
     */
    public static void main(String[] args) {
        new Oracle8iTester().test();

    }

    private void test() {
        String driverClassName = "oracle.jdbc.driver.OracleDriver";
        String orclURL = "jdbc:oracle:thin:@localhost:1521:orcl";//11g
        String ora8iURL = "jdbc:oracle:thin:@ora8ihost:1521:ora8i";//8i
        String userName = "apps";
        String password = "apps";

        try {
            Connection ora8iConn = Oracle8iManager.getInstance().getConnection(ora8iURL, userName, password);
            println(ora8iConn);
            testConnection(ora8iConn);
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            Class.forName(driverClassName);
            Connection orclConn = DriverManager.getConnection(orclURL, userName, password);
            println(orclConn);
            testConnection(orclConn);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void testConnection(Connection conn) throws Exception {
        Statement statement = conn.createStatement();
        ResultSet resultSet = statement.executeQuery("SELECT 'success' FROM dual");

        String str = null;
        if (resultSet.next()) {
            str = resultSet.getString(1);
        }
        resultSet.close();
        statement.close();
        conn.close();

        println(str);
    }

    private void println(Object o) {
        System.out.println(o);
    }

}

限制某程序使用特定的CPU

image 

image

2011年4月20日 星期三

Oracle ERP R12 Demo環境 免費使用

Oracle ERP R12 體驗網址 : http://vis1200.solutionbeacon.net/OA_HTML/AppsLogin

登入資訊:
username=TK9420
密碼: 9420TK

2011年3月15日 星期二

強迫IE用IE7的相容性檢視模式

寫個class繼承javax.servlet.Filter,在doFilter裡撰寫以下程式:

public void doFilter(ServletRequest aRequest, ServletResponse aResponse, FilterChain aChain)
        throws IOException, ServletException {
    //強迫IE用IE7的相容性檢視模式
    ((HttpServletResponse) aResponse).setHeader("X-UA-Compatible", "IE=EmulateIE7");
    aChain.doFilter(aRequest, aResponse);
}