You are on page 1of 114

JAVA Tip

abstract class Calculate { public abstract int triple(int a); } class AbstractTest extends Calculate { public int triple(int a) { return a*3; } public static void main(String[] args) { AbstractTest abstractTest = new AbstractTest(); abstractTest.triple(10); } }

interface Calculate1 { public int add(int a, int b); } interface Calculate2 { public int multiple(int a, int b); } class InterfaceTest implements Calculate1, Calculate2 { public int add(int a, int b) { return a+b; } public int multiple(int a, int b) { return a*b; } public static void main(String[] args) { InterfaceTest interfaceTest = new InterfaceTest(); System.out.println(interfaceTest.add(10,10)); System.out.println(interfaceTest.multiple(10,10)); } }

class ArrayCopy { public static void main(String[] args) { int [] src = new int[10]; int [] dest = new int[10]; src[3] = 10; src[9] = 5; System.arraycopy(src, 0, dest, 0, 10); System.out.println("src[3]= " + src[3] + ", src[9] = " + src[9]); System.out.println("dest[3]= " + dest[3] + ", dest[9] = " + dest[9]); } }

import java.util.Properties; class ReadSystemPath { public static void main(String[] args) { Properties prop = System.getProperties(); System.out.println("java.library.path : " + prop.get("java.library.path")); } }

class GarbageCollector { public static void main(String[] args) { byte[] test = new byte[1024]; Runtime runtime = Runtime.getRuntime(); System.out.println(" : " + (runtime.totalMemory() runtime.freeMemory())/1024 + "k"); // test = null; System.gc(); runtime = Runtime.getRuntime(); System.out.println(" : " + (runtime.totalMemory() runtime.freeMemory())/1024 + "k"); } }

Super, this
class A { public A() { System.out.println("Class A Constructor invoked"); } public static int unumber =200; } class B extends A { public B() { super(); System.out.println("Class B Constructor invoked"); System.out.println("this.unumber + " + this.unumber); System.out.println("super.unumber : " + super.unumber); } public static int unumber =100; } class SuperAndThis { SuperAndThis() { B b = new B(); } public static void main(String[] args) { SuperAndThis test = new SuperAndThis(); } }

import java.io.*; class ErrorFile { public int triple(String a) { return Integer.parseInt(a)*3; } public static void main(String[] args) { File file = new File("error.log"); FileOutputStream fos = null; try { fos = new FileOutputStream(file); PrintStream ps = new PrintStream(fos, true); System.setErr(ps);//error.log } catch (Exception e) { e.printStackTrace(); } ErrorFile errorFile = new ErrorFile(); errorFile.triple("100a"); } }

class Destructor { protected void finalize() { System.out.println("Object removed"); } public static void main(String[] args) { Destructor d = new Destructor(); d = null; System.gc(); } }

import java.io.BufferedReader; import java.io.InputStreamReader; class InputChar { public static void main(String[] args) { String input = null; String result = null; BufferedReader br = null; // =>InputStreamReader=>BufferedReader //System.in : InputStream br = new BufferedReader(new InputStreamReader(System.in)); System.out.print(" : "); try { input = br.readLine(); } catch (Exception e) { System.out.println(" "); } result = String.valueOf(Integer.parseInt(input)*2); System.out.println(" : " + result); } }

class Concat { public static void main(String[] args) { String s1 = "Hell"; String s2 = "o W"; String s3 = "orld"; String result; result = s1 + s2 + s3; System.out.println(result); } }

Random Num
//java.lang.math.Random Seed import java.util.Random; class RandomNumber { public static void main(String[] args) { Random random = new Random(System.currentTimeMillis()); while(true) { try { Thread.currentThread().sleep(500); } catch (InterruptedException e) { } System.out.println(Math.abs(random.nextInt())); } } }

import java.util.Date; import java.util.Calendar; class GetTime { public static void main(String[] args) { Date date = new Date(); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); System.out.println(" MilliSecond Time : " + date.getTime()); System.out.println(" Representation of Date: " + date.toString()); System.out.println(" My Represenation \t : " + calendar.get(Calendar.YEAR) + " Year " + calendar.get(Calendar.MONTH) + " Month " + calendar.get(Calendar.DAY_OF_MONTH) + " Day "); } }

import java.util.Date; import java.util.Calendar; class GetRunTime { public void waitASecond() { try { Thread.currentThread().sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) { GetRunTime object = new GetRunTime(); long checkPoint1 = System.currentTimeMillis(); object.waitASecond(); long checkPoint2 = System.currentTimeMillis(); long howLong = checkPoint2 - checkPoint1; System.out.println("waitASecond() :"+ ((double)howLong/(double)1000) + " "); } }

import java.util.StringTokenizer; class Tokenize { public static void main(String[] args) { String path = new String("c:\\Program Files\\Internet Explorer\\IExplore.exe"); StringTokenizer tokenizer = new StringTokenizer(path,"\\"); System.out.println("Token Count : " + tokenizer.countTokens()); while(tokenizer.hasMoreTokens()) { System.out.println("Tokenized String : " + tokenizer.nextToken()); } } }

Property
} } import java.util.Properties; import java.io.FileOutputStream; import java.io.FileInputStream; class GetProperty { public static void main(String[] args) { Properties proper = System.getProperties(); System.out.println("path.separator = " + proper.getProperty("path.separator")); proper.list(System.out);//System Property try { FileOutputStream fileOut = new FileOutputStream("MySystem.Properties", true); proper.store(fileOut, "My System Properties"); FileInputStream fileIn = new FileInputStream("MySystem.Properties"); proper.load(fileIn); proper.list(System.out); } catch (Exception e) { e.printStackTrace(); }

,
import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.io.FileInputStream; import java.io.ObjectInputStream; class ObjectFile { public static void main(String[] args) { try { String writeString = new String("This is Serialized Object"); // FileOutputStream fout = new FileOutputStream("string.obj"); ObjectOutputStream oout = new ObjectOutputStream(fout); oout.writeObject(writeString); oout.close(); // FileInputStream fin = new FileInputStream("string.obj"); ObjectInputStream oin = new ObjectInputStream(fin); Object o = oin.readObject(); String readString = (String) o; oin.close(); System.out.println(readString); } catch (Exception e){ e.printStackTrace(); } } }

1
import import import import import import java.util.StringTokenizer; java.io.FileOutputStream; java.io.ObjectOutputStream; java.io.FileInputStream; java.io.ObjectInputStream; java.io.Serializable; class Serialize { public static void main(String[] args) { try { MyString writeString = new MyString("This is Serialized Object"); // FileOutputStream fout = new FileOutputStream("string.obj"); ObjectOutputStream oout = new ObjectOutputStream(fout); oout.writeObject(writeString); oout.close(); // FileInputStream fin = new FileInputStream("string.obj"); ObjectInputStream oin = new ObjectInputStream(fin); Object o = oin.readObject(); MyString readString = (MyString) o; oin.close(); System.out.println(readString); } catch (Exception e){ e.printStackTrace(); } } }

1
class MyString implements Serializable { //String class private String prefix = new String("["); private String surfix = new String("]"); private String content; public MyString(String myString){ setString(myString); } public void setString(String myString) { content = myString; } public String toString() { return "[MyString]" + prefix + content + surfix; } }

2
import java.util.StringTokenizer; import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.io.FileInputStream; import java.io.ObjectInputStream; import java.io.Serializable; import java.io.IOException; class Serialize2 { public static void main(String[] args) { try { MyString writeString = new MyString("This is Serialized Object"); // FileOutputStream fout = new FileOutputStream("string.obj"); ObjectOutputStream oout = new ObjectOutputStream(fout); oout.writeObject(writeString); oout.close(); // FileInputStream fin = new FileInputStream("string.obj"); ObjectInputStream oin = new ObjectInputStream(fin); Object o = oin.readObject(); MyString readString = (MyString) o; oin.close(); System.out.println(readString); } catch (Exception e){ e.printStackTrace(); } } }

2
class MyString implements Serializable { //String class private String prefix = new String("["); private String surfix = new String("]"); private String content; //StringTokenizer private String delimiter = new String(" "); private StringTokenizer st; public MyString(String myString){ setString(myString); } public void setString(String myString) { content = myString; st = new StringTokenizer(toString(), delimiter); } public String toString() { return "[MyString]" + prefix + content + surfix; } private void writeObject(java.io.ObjectOutputStream out) throws IOException { // out.writeObject(prefix); out.writeObject(content); out.writeObject(surfix); out.writeObject(delimiter); } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { // prefix = (String)in.readObject(); content = (String)in.readObject(); surfix = (String)in.readObject(); delimiter = (String)in.readObject(); //StringTokenizer , st = new StringTokenizer(toString(), delimiter); } }

Logging
import java.io.IOException; import java.util.logging.Logger; import java.util.logging.FileHandler; import java.util.logging.SimpleFormatter; class Logging { public static void main(String[] args) { Logger logger = Logger.getLogger("Logging.Test.log"); logger.setUseParentHandlers(false); //Parent Logger Handler FileHandler fileHandler = null; SimpleFormatter simpleFormatter = new SimpleFormatter(); try { fileHandler = new FileHandler("test.log"); } catch (IOException e){ e.printStackTrace(); } fileHandler.setFormatter(simpleFormatter); logger.addHandler(fileHandler); testLogging(logger); } public static void testLogging(Logger logger) { logger.config("built-in logging test"); logger.fine("built-in logging test"); logger.finer("built-in logging test"); logger.finest("built-in logging test"); logger.info("built-in logging test"); logger.warning("built-in logging test"); logger.severe("built-in logging test"); } }

ConsolHandler

Logger

Handler

Formatter

Logging
OFF SEV ERE WAR NIN G INF O CON FIG

2
FINE FINE R ALL/ FINE ST

Logging
import java.io.IOException; import java.util.logging.Logger; import java.util.logging.ConsoleHandler; import java.util.logging.FileHandler; import java.util.logging.SimpleFormatter; import java.util.logging.FileHandler; import java.util.logging.Level; class Logging1 { public static void main(String[] args) { Logger logger = Logger.getLogger("Logging1.Test.log"); logger.setUseParentHandlers(false); //Parent Logger Handler FileHandler fileHandler = null; ConsoleHandler consoleHandler = null; SimpleFormatter simpleFormatter = new SimpleFormatter(); try { fileHandler = new FileHandler("test.log"); consoleHandler = new ConsoleHandler(); } catch (IOException e){ e.printStackTrace(); } logger.setLevel(Level.ALL); //logger Level fileHandler.setLevel(Level.INFO); //INFO, WARNING,SEVERE consoleHandler.setLevel(Level.ALL);// fileHandler.setFormatter(simpleFormatter); consoleHandler.setFormatter(simpleFormatter); logger.addHandler(fileHandler); logger.addHandler(consoleHandler); testLogging(logger); }

ConsolHandler

Logging

public static void testLogging(Logger logger) { logger.config("built-in logging test"); logger.fine("built-in logging test"); logger.finer("built-in logging test"); logger.finest("built-in logging test"); logger.info("built-in logging test"); logger.warning("built-in logging test"); logger.severe("built-in logging test"); } }

XML
import java.io.IOException; import java.util.logging.Logger; import java.util.logging.FileHandler; import java.util.logging.XMLFormatter; import java.util.logging.Level;

Log

class XMLLog { public static void main(String[] args) { Logger logger = Logger.getLogger("Logging1.Test.log"); logger.setUseParentHandlers(false); //Parent Logger Handler FileHandler fileHandler = null; XMLFormatter xmlFormatter = new XMLFormatter(); try { fileHandler = new FileHandler("test.log"); } catch (IOException e){ e.printStackTrace(); } fileHandler.setFormatter(xmlFormatter); logger.addHandler(fileHandler); testLogging(logger); } public static void testLogging(Logger logger) { logger.config("built-in logging test"); logger.fine("built-in logging test"); logger.finer("built-in logging test"); logger.finest("built-in logging test"); logger.info("built-in logging test"); logger.warning("built-in logging test"); logger.severe("built-in logging test"); } }

ConsolHandler

Hash
import java.util.LinkedHashMap; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.HashSet; class Hash { static String[] country = {"Korea", "China", "japan"}; static String[] capital = {" "," "," "}; public void testMap() { LinkedHashMap ordered = new LinkedHashMap(); HashMap unordered = new HashMap(); for(int i=0;i<country.length;i++) { ordered.put(country[i],capital[i]); // unordered.put(country[i],capital[i]); } System.out.println("Ordered : " + ordered); System.out.println("Unordered : " + unordered); } public void testSet() { LinkedHashSet ordered = new LinkedHashSet(); HashSet unordered = new HashSet(); for(int i=0;i<country.length;i++) { ordered.add(country[i]);// unordered.add(country[i]); } System.out.println("Ordered : " + ordered); System.out.println("Unordered : " + unordered); } public static void main(String[] args) { Hash hash = new Hash(); hash.testMap(); hash.testSet(); } }

Channel :

File Lock
import java.io.RandomAccessFile; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; class Lock { public static void main(String[] args) { try { RandomAccessFile raf = new RandomAccessFile("Lock.java","rw"); FileChannel fc = raf.getChannel(); FileLock f1 = fc.lock(); if(f1 != null) { System.out.println("try Lock successful"); Thread.sleep(10000); f1.release(); System.out.println("Lock Release OK"); } else System.out.println("try Lock fail"); } catch (Exception e) { e.printStackTrace(); } } }

FileChannel
import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.channels.FileChannel; class FChannel { public static void main(String[] args) { long size = 0; try { FileInputStream fis = new FileInputStream("JAVA Tip.pptx");//source FileOutputStream fos = new FileOutputStream("test.pptx");//dest FileChannel fcin = fis.getChannel(); FileChannel fcout = fos.getChannel(); size = fcin.size(); System.out.println("File Size : " + size); fcin.transferTo(0, size, fcout); fcout.close(); fcin.close(); fos.close(); fis.close(); System.out.println("File Copy OK"); } catch (Exception e) { e.printStackTrace(); } } }

Little Endian, Big Endian


import java.io.FileInputStream; import java.nio.channels.FileChannel; import java.nio.MappedByteBuffer; import java.nio.ByteOrder; import java.nio.ShortBuffer; class LittleEndian { public static void main(String[] args) { // byte ordering : Big Endian //test : V4xV (0x56 0x34 0x78 0x56) try { FileInputStream fis = new FileInputStream("test"); FileChannel fc = fis.getChannel(); MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); mbb.order(ByteOrder.LITTLE_ENDIAN); //13398 22136 //mbb.order(ByteOrder.BIG_ENDIAN); //22068 30806 , JAVA BIGENDIAN ShortBuffer sb = mbb.asShortBuffer(); System.out.println("Read Short : " + sb.get() + " " + sb.get()); fc.close(); fis.close(); } catch (Exception e) { e.printStackTrace(); } } }

BigInteger
import java.math.BigInteger; class BigNumber { public static void main(String[] args) { BigInteger bi1 = new BigInteger("123456789012345678901234567890"); BigInteger bi2 = new BigInteger("2"); int i2 = 2; System.out.println(bi1 + " * " + bi2 + " = " + bi1.multiply(bi2)); System.out.println(bi1 + " / " + bi2 + " = " + bi1.divide(bi2)); } }

List, Map, Set, Collection

Collection Framework
import java.util.Vector; import java.util.Collections; class CollectionTest { public static void main(String[] args) { Vector vector1 = new Vector(); vector1.add("a"); vector1.add("b"); vector1.add("c"); vector1.add("d"); vector1.add("e"); System.out.println(vector1); Collections.rotate(vector1, 3);//3 System.out.println(vector1); Collections.swap(vector1, 1, 3); //1 3 System.out.println(vector1); Collections.shuffle(vector1);// System.out.println(vector1); Collections.sort(vector1);//sort System.out.println(vector1); } }

class PriorityThread1 extends Thread { private ThreadPriority main = null; public void run() { try { for(int i=0;i<10;i++) { System.out.println("PriorityThread1"); Thread.yield(); } } catch (Exception e) { e.printStackTrace(); } } public void set(ThreadPriority m) { main = m; } }

class PriorityThread2 extends Thread { private ThreadPriority main = null; public void run() { try { for(int i=0;i<10;i++) { System.out.println("PriorityThread2"); Thread.yield(); } } catch (Exception e) { e.printStackTrace(); } } public void set(ThreadPriority m) { main = m; } } class ThreadPriority { public int value = 0; public static void main(String[] args) { ThreadPriority o = new ThreadPriority(); o.run(); } public void run() { try { PriorityThread1 thread1 = new PriorityThread1(); PriorityThread2 thread2 = new PriorityThread2(); thread1.set(this); thread2.set(this); thread1.setPriority(10);//1~10 thread1.start(); thread2.start(); thread1.join(); thread2.join(); } catch (Exception e) { e.printStackTrace(); } } }

IP
import java.net.InetAddress; class GetInetAddress { public static void main(String[] args) { String server_name = "www.naver.com"; try { System.out.println(server_name + "'s IP Address "); InetAddress ia[] = InetAddress.getAllByName(server_name); for(int i=0;i<ia.length;i++) { System.out.println("IP["+i+"]:"+ia[i].getHostAddress()); } } catch (Exception ex){ System.out.println("Error : " + ex.toString()); } } }

import java.util.Enumeration; import java.net.NetworkInterface; import java.net.InetAddress; class GetNetDeviceInfo { public static void main(String[] args) { try { Enumeration e1 = NetworkInterface.getNetworkInterfaces(); Enumeration e2 = null; NetworkInterface ni = null; InetAddress ia = null; while(e1.hasMoreElements()) { ni = (NetworkInterface) e1.nextElement(); System.out.println(ni.getName() + ": "); e2 = ni.getInetAddresses(); while(e2.hasMoreElements()) { ia = (InetAddress)e2.nextElement(); System.out.println(ia.getHostAddress() + " "); } System.out.println(""); } } catch (Exception ex){ System.out.println("Error : " + ex.toString()); } } }

/
import java.net.ServerSocket; import java.net.Socket; import java.io.BufferedReader; import java.io.InputStreamReader; class SimpleServer { public static void main(String[] args) { int port = 7979; ServerSocket ss = null; Socket client_socket = null; BufferedReader br = null; String line = null; System.out.println("Echo Server Start"); try { ss = new ServerSocket(port); ss.setReuseAddress(true); client_socket = ss.accept(); br = new BufferedReader(new InputStreamReader(client_socket.getInputStream()));

while(true) { line = br.readLine(); if(line != null) System.out.println("READ : " + line); else break; } } catch (Exception ex){ System.out.println("Error : " + ex.toString()); } finally { try { client_socket.close(); } catch (Exception e) { } try { ss.close(); } catch (Exception e) { } } System.out.println("Echo Server End"); } }

import java.net.Socket; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; class SimpleClient { public static void main(String[] args) { int port = 7979; Socket socket = null; String hostname = "localhost"; BufferedReader br = null; String line = null; OutputStream os = null; System.out.println("Echo Client Start"); try { br = new BufferedReader(new InputStreamReader(System.in)); socket = new Socket(hostname, port); os = socket.getOutputStream(); while(true) { line = br.readLine(); os.write(line.getBytes()); os.write('\n'); } }

catch (Exception ex){ System.out.println("Error : " + ex.toString()); } finally { try { socket.close(); } catch (Exception e) { } } System.out.println("Echo Client End"); } }

ICMP

RAW Socket

Ping
Ping
Runtime Ping exec C , JNI ping

Thread
import java.lang.Thread; import java.net.ServerSocket; import java.net.Socket; import java.io.BufferedReader; import java.io.InputStreamReader;

Server

class ThreadServer extends Thread { Socket client_socket = null; public ThreadServer(Socket s) { client_socket = s; } public void run() { BufferedReader br = null; String line = null; try { br = new BufferedReader(new InputStreamReader(client_socket.getInputStream())); while(true) { line = br.readLine(); if(line != null) System.out.println("READ(" + Thread.currentThread().toString() + "): " + line); else break; } } catch (Exception ex){ System.out.println("Error : " + ex.toString()); }

finally { try { client_socket.close(); {

} catch (Exception e) }

} } public static void main(String[] args) { int port = 7979; ServerSocket ss = null; Socket client_socket = null; BufferedReader br = null; String line = null; System.out.println("Echo Server Start"); try { ss = new ServerSocket(port); ss.setReuseAddress(true); while(true) { ThreadServer te = new ThreadServer(ss.accept()); System.out.println("New Client Accepted!"); te.start(); } } catch (Exception ex){ System.out.println("Error : " + ex.toString()); } finally { try { ss.close(); } catch (Exception e) { } } System.out.println("Echo Server End"); } }

HttpUrlConnection
import java.net.URL; import java.net.HttpURLConnection;

Object Moved

class HttpUrlConnection { public void connect(URL url) { HttpURLConnection conn = null; int response_code = 0; try { conn = (HttpURLConnection)url.openConnection(); conn.setInstanceFollowRedirects(false); //302 redrects response_code = conn.getResponseCode(); switch(response_code) { case 200 : System.out.println("Connect OK : " + conn.getURL().toString()); break; case 302 : System.out.println("Object Moved : " + conn.getURL().toString()); connect(new URL(url, conn.getHeaderField("Location")));// url break; } } catch (Exception e) { } } public static void main(String[] args) { try { HttpUrlConnection httpUrlConnection = new HttpUrlConnection(); httpUrlConnection.connect(new URL("http://www.yahoo.co.kr")); } catch (Exception e) { e.printStackTrace(); } } }

JavaMail
Javamail
http://java.sun.com/products/javamail

JAF(JAVABeans Activation Framework)


http://java.sun.com/products/javabeans/glasgow/jaf.html

Mail.jar, activation.jar classpath

Header, content Message = header+content Bodypart = header+content Multipart=bodypart+bodypart+.

Transport class SMTP , Authenticator , mail.smtp.auth property true setting session

import javax.mail.Transport; class Mail { String to = "minpo@ysu.ac.kr"; String from = "minpo@ysu.ac.kr"; String subject = "Java Mail Code"; String content = "Java Mail Code Test"; public void sendMail() { Properties prop = System.getProperties(); prop.put("sm.ysu.ac.kr", "sm.ysu.ac.kr"); Session session = Session.getDefaultInstance(prop); MimeMessage mm = new MimeMessage(session); try { mm.setHeader("From", from); mm.setHeader("To", to); mm.setSubject(subject, "euc-kr"); mm.setText(content, "euc-kr"); Transport.send(mm); } catch (Exception e){ System.out.println("Message Sending Error"); e.printStackTrace(); } } public static void main(String[] args) { Mail mail = new Mail(); mail.sendMail(); } }

import java.io.*; import java.util.*; import javax.mail.*; import javax.mail.internet.*; class MailReceive { public static void main(String[] args) throws Exception { if(args.length !=3) { System.out.println("java MailReceive popserver user pass"); return; } String popServer = args[0]; String userId = args[1]; String password = args[2]; Session session = Session.getDefaultInstance(System.getProperties(), null); Store store = session.getStore("pop3"); store.connect(popServer, userId, password); Folder defaultFolder = store.getDefaultFolder(); if(defaultFolder == null) throw new Exception ("No default folder"); Folder inbox = defaultFolder.getFolder("INBOX"); inbox.open(Folder.READ_ONLY); Message[] messages = inbox.getMessages(); for(int i=0;i<messages.length;i++) { Message message = messages[i]; printMessage(message); } inbox.close(false); store.close(); }

Session :

, Store :

, Folder :

, Message :

public static void printMessage(Message message) { try { String from=((InternetAddress)message.getFrom()[0]).getPersonal(); if(from==null) from=((InternetAddress)message.getFrom()[0]).getAddress(); System.out.println("From : " + from); String subject = message.getSubject(); System.out.println("Subject: " + subject); Part messagePart = message; Object content = messagePart.getContent(); if(content instanceof Multipart) { messagePart = ((Multipart)content).getBodyPart(0); System.out.println("[Multipart Message]"); } String contentType = messagePart.getContentType(); System.out.println("CONTENT:"+contentType); if(contentType.startsWith("text/plain")) { InputStream is = messagePart.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String thisLine = reader.readLine(); while(thisLine != null) { System.out.println(thisLine); thisLine = reader.readLine(); } } System.out.println("======================================================="); } catch (Exception ex){ ex.printStackTrace(); } } }

FTP
import java.net.URL; import java.io.BufferedReader; import java.net.URLConnection; import java.io.InputStreamReader; class FTPTest { public static void main(String[] args) { try { URL url = new URL("ftp://linux.sarang.net/mirror/README.tree"); URLConnection conn = url.openConnection(); conn.connect(); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while((line = br.readLine()) != null) { System.out.println(line); } } catch (Exception e){ e.printStackTrace(); } } }

JDBC
JAVA Application

JDBC API
DB ODBC . JDBC .

JDBC Driver Manager/DataSource Object

JDBC-ODBC Bridge

Pure Java JDBC Driver

Pure Java JDBC Driver

Pure Java JDBC Driver

ODBC ODBC Client Lib ODBC Client Lib


.

DB Middleware

Database Server

Type1

Type2

Type3

Type4

JDBC-ODBC
import import import import java.sql.PreparedStatement; java.sql.DriverManager; java.sql.Connection; java.sql.ResultSet;

MS-Access

class ConnectAccess { public void connect() { Connection conn=null; PreparedStatement ps=null; ResultSet rs=null; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); conn = DriverManager.getConnection("jdbc:odbc:test"); String sql = "select * from minpo"; ps = conn.prepareStatement(sql); ps.execute(); rs = ps.getResultSet(); while(rs.next()) { System.out.println("Name : " + rs.getString(1) + ", Phone : " + rs.getString(2) + ", Age : " + rs.getInt(3)); } } catch (Exception e) { e.printStackTrace(); } finally { try { if(rs != null) rs.close(); if(ps != null) ps.close(); if(conn != null) conn.close(); } catch (Exception e) { e.printStackTrace(); } } } public static void main(String[] args) { ConnectAccess connectAccess1 = new ConnectAccess(); connectAccess1.connect(); } }

import java.security.Security; import java.security.Provider; import java.util.Iterator; import java.util.Set; class ListAlgorithm { public static void main(String[] args) { Provider[] providers = Security.getProviders(); Provider curr = null; Set keys = null; Iterator iterator = null; String value = null; String alias = "Alg.Alias."; String service = null; for(int i=0;i<providers.length;i++) { curr = providers[i]; System.out.println("Provider : " + curr.getName()); keys = curr.keySet(); iterator = keys.iterator(); while(iterator.hasNext()) { value = (String)iterator.next(); if(value.startsWith(alias)) { service = value.substring(alias.length()); } else service = value; System.out.println("\t" + service); } } } }

import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.crypto.SecretKey; import javax.crypto.spec.PBEParameterSpec; import javax.crypto.Cipher; class SecretKeyTest { public static void main(String[] args) { byte[] salt = { (byte)0x24, (byte)0x85, (byte)0x62,(byte)0x79, (byte)0xfe, (byte)0x10, (byte)0xa6, (byte)0xb2 }; int iteration = 9; String password = "minpo"; String plaintext = " "; byte[] encryptedtext = null; byte[] decryptedtext = null; try { System.out.println(" : " + plaintext); //base64 encoding System.out.println("B64PlainText : " + new sun.misc.BASE64Encoder().encode(plaintext.getBytes("euc-kr"))); //PBEWithMD5AndDES KeyFactory SecretKeyFactory skf = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); // password password based encryption PBEKeySpec pks = new PBEKeySpec(password.toCharArray()); SecretKey sk = skf.generateSecret(pks); //PBE

PBEParameterSpec pps = new PBEParameterSpec(salt, iteration); //PBEWithMD5AndDES Cipher Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES"); // cipher.init(Cipher.ENCRYPT_MODE, sk, pps); // byte[] encryptedtext = cipher.doFinal(plaintext.getBytes("euc-kr")); // byte[] base64 encoding System.out.println("B64EncryptedText : " + new sun.misc.BASE64Encoder().encode(encryptedtext)); // cipher.init(Cipher.DECRYPT_MODE, sk, pps); // bytep[ decryptedtext = cipher.doFinal(encryptedtext); // byte[] base64 encoding System.out.println("B64DecryptedText : " + new sun.misc.BASE64Encoder().encode(decryptedtext)); System.out.println(" : " + new String(decryptedtext,"euc-kr")); } catch (Exception e) { e.printStackTrace(); } } }

JRE_HOME/lib/security/java.policy
C:\Program Files\Java\jre1.6.0\lib\security
grant { permission java.io.FilePermission "c:\\*", "read"; };

,
Java Djava.security.manager PermissionTest

// Standard extensions get all permissions by default grant codeBase "file:${{java.ext.dirs}}/*" { permission java.security.AllPermission; }; // default permissions granted to all domains grant { // Allows any thread to stop itself using the java.lang.Thread.stop() // method that takes no argument. // Note that this permission is granted by default only to remain // backwards compatible. // It is strongly recommended that you either remove this permission // from this policy file or further restrict it to code sources // that you specify, because Thread.stop() is potentially unsafe. // See "http://java.sun.com/notes" for more information. permission java.lang.RuntimePermission "stopThread"; // allows anyone to listen on un-privileged ports permission java.net.SocketPermission "localhost:1024-", "listen"; // "standard" properies that can be read by anyone permission permission permission permission permission permission permission permission permission permission java.util.PropertyPermission java.util.PropertyPermission java.util.PropertyPermission java.util.PropertyPermission java.util.PropertyPermission java.util.PropertyPermission java.util.PropertyPermission java.util.PropertyPermission java.util.PropertyPermission java.util.PropertyPermission "java.version", "read"; "java.vendor", "read"; "java.vendor.url", "read"; "java.class.version", "read"; "os.name", "read"; "os.version", "read"; "os.arch", "read"; "file.separator", "read"; "path.separator", "read"; "line.separator", "read";

permission java.util.PropertyPermission "java.specification.version", "read"; permission java.util.PropertyPermission "java.specification.vendor", "read"; permission java.util.PropertyPermission "java.specification.name", "read"; permission permission permission permission permission permission }; java.util.PropertyPermission java.util.PropertyPermission java.util.PropertyPermission java.util.PropertyPermission java.util.PropertyPermission java.util.PropertyPermission "java.vm.specification.version", "read"; "java.vm.specification.vendor", "read"; "java.vm.specification.name", "read"; "java.vm.version", "read"; "java.vm.vendor", "read"; "java.vm.name", "read";

import java.io.FileOutputStream; import java.security.AccessControlException; import java.io.FilePermission; import java.security.AccessController; class PermissionTest { public static void main(String[] args) { try { try { FileOutputStream fos = new FileOutputStream("c:\\test.txt"); System.out.println("Permission granted"); } catch (AccessControlException ace) { ace.printStackTrace(); } } catch (Exception e){ e.printStackTrace(); } try { FilePermission fp = new FilePermission("c:\\test.txt", "read,write"); AccessController.checkPermission(fp); System.out.println("Permission granted"); } catch (AccessControlException ace){ System.out.println("Permission denied"); } } }

-Djava.security.manager option

import java.lang.Character; class StringInHangul { public static void main(String[] args) { String string = "My Name is "; char[] chars = string.toCharArray(); System.out.println("Original String : " + string + " Size: " + string.length()); for(int i=0;i<chars.length;i++) { System.out.println(chars[i] + ":" + Character.UnicodeBlock.of(chars[i])); } } }

,
import java.text.Collator; import java.util.Locale; import java.text.BreakIterator; class Boundary { static final String string1 = "determining Boundarys In unicode\nGood Lock!"; static final String string2 = "determining Boundarys In Unicode_Good Lock!";

public static void main(String[] args) { BreakIterator iterator = null; char[] breaks = null; System.out.println("Character Boundary"); iterator = BreakIterator.getCharacterInstance(Locale.US); iterator.setText(string1); breaks = findBoundary(iterator); System.out.println(string2); printBoundary(breaks); System.out.println("Word Boundary"); iterator = BreakIterator.getWordInstance(Locale.US); iterator.setText(string1); breaks = findBoundary(iterator); System.out.println(string2); printBoundary(breaks);

System.out.println("Line Boundary"); iterator = BreakIterator.getLineInstance(Locale.US); iterator.setText(string2); breaks = findBoundary(iterator); System.out.println(string2); printBoundary(breaks); System.out.println("Sentence Boundary"); iterator = BreakIterator.getSentenceInstance(Locale.US); iterator.setText(string1); breaks = findBoundary(iterator); System.out.println(string2); printBoundary(breaks); } public static char[] findBoundary(BreakIterator iterator) { char[] breaks = new char[50]; int idx=0; int i=0; for(i=iterator.first();i != BreakIterator.DONE ;i = iterator.next()){ breaks[i] = '^'; } return breaks; } public static void printBoundary(char[] charArray) { for(int i=0;i<charArray.length;i++) System.out.print(charArray[i]); System.out.println(" "); } }

TimeZone GMT(0 ) GMT 9

(GMT : 0 ,

. :9

GMT
import java.util.Date; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.TimeZone; class ChangeTimeOnTimeZone { public static void main(String[] args) { Calendar local = new GregorianCalendar(); System.out.println("[Local Time] " + local.get(Calendar.DAY_OF_MONTH) + " " + local.get(Calendar.HOUR_OF_DAY) + " " + local.get(Calendar.MINUTE) + " " + local.get(Calendar.SECOND)); Calendar gmt = new GregorianCalendar(TimeZone.getTimeZone("GMT")); gmt.setTimeInMillis(local.getTimeInMillis()); System.out.println("[GMT Time] " + gmt.get(Calendar.DAY_OF_MONTH) + " " + gmt.get(Calendar.HOUR_OF_DAY) + " " + gmt.get(Calendar.MINUTE) + " " + gmt.get(Calendar.SECOND)); } }

Timezone
import java.util.Date; import java.util.TimeZone; class ChangeDefaultTimeZone { public static void main(String[] args) { Date date = new Date(); System.out.println(date); TimeZone.setDefault(TimeZone.getTimeZone("French")); System.out.println(date); } }

I/O
US-ASCII
7 ASCII

Character set

ISO-8859-1
ISO Latin Alphabet No. 1

UTF-8
8 UTF(UCS Transforamtion Foramt) 16 16 16 UTF UTF UTF

UTF-16BE
Big Endian

UTF-16LE
Little Endian

UTF-16

import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.FileInputStream; import java.io.OutputStreamWriter; class FileEncoding { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader( new InputStreamReader ( new FileInputStream("FileEncoding.txt"), "UTF-16")); StringBuffer buffer = new StringBuffer(); String str = null; while((str = in.readLine()) != null) buffer.append(str); str = buffer.toString(); OutputStreamWriter out = new OutputStreamWriter(System.out); System.out.println("System.out : " + out.getEncoding()); out.write(str, 0, str.length()); out.flush(); out = new OutputStreamWriter(System.out,"UTF-16"); System.out.println("\n\n\nlocaled out : " + out.getEncoding()); out.write(str, 0, str.length()); out.flush(); } }

Javac , Javac encoding euc-kr javasourcefile

Ctrl+c
class ShutdownHook implements Runnable { public void run() { System.out.println("I'm a shutdown hook"); } public static void main(String[] args) { Runtime rt = Runtime.getRuntime(); rt.addShutdownHook(new Thread(new ShutdownHook())); for(int i=0;i<10;i++) { try { System.out.println("Press ctrl-c to exit program"); Thread.sleep(1000); } catch (InterruptedException e) { } } } }

import java.text.DecimalFormat; class MemoryStatus { public static void main(String[] args) { printMemStatus(); } static DecimalFormat df = new DecimalFormat("###,###,###,###,###"); static Runtime rt = Runtime.getRuntime(); public static String format(long val) { return df.format(val); } public static void printMemStatus() { long max = rt.maxMemory(); long total = rt.totalMemory(); long free = rt.freeMemory(); System.out.println("Max : " + format(max) + " ; Total : " + format(total) + " ; Free : " + format(free)); } }

import java.io.IOException; class Notepad { public static void main(String[] args) throws Exception { runNotepad(); } static Runtime rt = Runtime.getRuntime(); public static void runNotepad() throws IOException { Process notepad = rt.exec("notepad.exe"); } }

import java.io.IOException; class NotepadWait { public static void main(String[] args) throws Exception { runNotepad(); } static Runtime rt = Runtime.getRuntime(); public static void runNotepad() throws Exception { Process notepad = rt.exec("notepad.exe"); notepad.waitFor(); } }

import java.io.*; class RunJavaOutput { public static void main(String[] args) throws Exception { runJava(); } static Runtime rt = Runtime.getRuntime(); public static void runJava() throws IOException { Process dir = rt.exec("java.exe"); BufferedReader reader = new BufferedReader( new InputStreamReader(dir.getInputStream())); String line = null; while((line = reader.readLine()) != null) { System.out.println(line); } } }

Serial
http://java.sun.com/products/javacomm Class path comm.jar copy comm.jar \jdk1.3\jre\lib\ext copy win32com.dll \jdk1.3\bin copy javax.comm.properties \jdk1.3\jre\lib comm_api_win-jjheyday.zip ( )

import javax.comm.*; import java.util.Enumeration; class ListPorts { public static void main(String[] args) { Enumeration ports = CommPortIdentifier.getPortIdentifiers(); while(ports.hasMoreElements()) { CommPortIdentifier port = (CommPortIdentifier)ports.nextElement(); String type; switch(port.getPortType()) { case CommPortIdentifier.PORT_PARALLEL : type = "Parallel"; break; case CommPortIdentifier.PORT_SERIAL : type = "Serial"; break; default : type = "Unknown"; break; } System.out.println(port.getName() + ": " + type); } } }

Serial
import javax.comm.*; import java.io.*; import java.util.*; class SerialEcho implements Runnable, SerialPortEventListener { static CommPortIdentifier portId; static Enumeration portList; SerialPort serialPort; BufferedReader br; BufferedWriter bw; String echoMsg; Thread readThread; public static void main(String[] args) { portList = CommPortIdentifier.getPortIdentifiers(); while(portList.hasMoreElements()) { portId = (CommPortIdentifier)portList.nextElement(); if(portId.getPortType() == CommPortIdentifier.PORT_SERIAL) { //if(portId.getName().equals("/dev/term/a")) { //solaris if(portId.getName().equals("COM1")) { SerialEcho reader = new SerialEcho(); } } } }

public SerialEcho() { try { serialPort = (SerialPort)portId.open("SerialEcho", 2000); } catch (PortInUseException e){ } try { br = new BufferedReader(new InputStreamReader(serialPort.getInputStream())); bw = new BufferedWriter(new OutputStreamWriter(serialPort.getOutputStream())); } catch (IOException e){ } try { serialPort.addEventListener(this); } catch (TooManyListenersException e) { } serialPort.notifyOnDataAvailable(true);//input data try { serialPort.setSerialPortParams(19200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); } catch (UnsupportedCommOperationException e) { } readThread = new Thread(this); readThread.start(); }

public void run() { try

{ Thread.sleep(200); {

} catch (InterruptedException e) }

} public void serialEvent(SerialPortEvent event) { switch(event.getEventType()) { case SerialPortEvent.BI: //Break Interrupt case SerialPortEvent.OE: //Overrun error case SerialPortEvent.FE: //Framing error case SerialPortEvent.PE: //Parity error case SerialPortEvent.CD: //Carrier detect case SerialPortEvent.CTS: //Clear to send case SerialPortEvent.DSR: //Data set ready case SerialPortEvent.RI: //Ring Indicator case SerialPortEvent.OUTPUT_BUFFER_EMPTY: // break; case SerialPortEvent.DATA_AVAILABLE: byte[] readBuffer = new byte[20]; try { while(true) { echoMsg = br.readLine(); System.out.println("Echo: " + echoMsg); bw.write(echoMsg,0,echoMsg.length()); bw.newLine(); bw.flush(); } } catch (IOException e) { } break; } } }

EXE
java SoundPlayer 1-welcome.wav import java.io.File; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; class SoundPlayer { public static void main(String[] args) { int buffsize = 20480; int readbyte = 0; byte[] buff = new byte[buffsize]; if(args.length < 1) { System.out.println("Input mp3 filename"); return; } try { AudioInputStream ais = AudioSystem.getAudioInputStream(new File(args[0])); AudioFormat af = ais.getFormat(); SourceDataLine line = null; DataLine.Info info = new DataLine.Info(SourceDataLine.class, af); line = (SourceDataLine) AudioSystem.getLine(info); line.open(af); line.start(); while(readbyte >=0) { readbyte = ais.read(buff,0,buffsize); line.write(buff,0,readbyte); } line.drain(); line.close(); } catch (Exception e) { e.printStackTrace(); } } }

Image
import javax.imageio.ImageIO; class ListImageFormat { public static void main(String[] args) { try { String[] names = ImageIO.getReaderFormatNames(); System.out.println(" "); for(int i=0;i<names.length;i++) { System.out.println("\t"+names[i]); } System.out.println(" "); names = ImageIO.getWriterFormatNames(); for(int i=0;i<names.length;i++) { System.out.println("\t"+names[i]); } } catch (Exception e) { e.printStackTrace(); } } }

Png
import java.awt.image.BufferedImage; import java.awt.Graphics2D; import java.awt.Color; import java.io.File; import javax.imageio.ImageIO; class SaveImage { public static void main(String[] args) { BufferedImage image = new BufferedImage(200,200,BufferedImage.TYPE_INT_RGB); Graphics2D graphics = image.createGraphics(); graphics.setColor(Color.YELLOW); graphics.fillRect(0,0,200,200); try { File file = new File("test.png"); ImageIO.write(image,"png",file); } catch (Exception e) { e.printStackTrace(); } } }


For String charAt() String a = A quick bronze; For(int i=0;i<a.length;i++)

System.out.println(char + I + is + a.charAt(i));

StringBuffer reverse() . String sh = FCG; System.out.println(new StringBuffer(sh).reverse());

Cosine
Java.lang.Math Math.cos(1.1418)

e java.lang.Math log()

Double log_e = Math.log(someValue);

Math.log(value)/Math.log(base)


Java.util.Properties import java.util.*; class PropsCompanies { public static void main(String[] args) throws java.io.IOException { Properties props = new Properties(); props.setProperty("Adobe", "Moutain View, CA"); props.setProperty("IBM", "White Plains, NY"); props.load(System.in); // load props.list(System.out); } }

PropsDemo.dat
minpo=Professor young=student Sony=Japan Ericsson=Sweden

java PropsCompanies < PropsDemo.dat

import java.io.*; class CatStdin { public static void main(String[] args) { try { BufferedReader is = new BufferedReader(new InputStreamReader(System.in)); String inputLine; while((inputLine = is.readLine()) != null) { System.out.println(inputLine); } is.close(); } catch (IOException e) { System.out.println("IOException : " + e); } } }

int
import java.io.*; class ReadStdinInt { public static void main(String[] args) { String line = null; int val = 0; try { BufferedReader is = new BufferedReader(new InputStreamReader(System.in)); line = is.readLine(); val = Integer.parseInt(line); } catch (NumberFormatException ex) { System.out.println("Not a valid number : " + line); } catch (IOException e) { System.err.println("Unexpected IO Error : " + e); } System.out.println("I read this number: " + val); } }


Java ParallelPrint javacook.ps

CommPortOpen.java PortChooser.java

PortOwner.java

CommPortDial.java CommPortModem.java

SerialReadByEvents.java SerialLogger.java

Thread
CommPortThreaded.java

client(TCP/IP)
import java.net.*; public class Connect { public static void main(String[] argv) { String server_name = "localhost"; try { Socket sock = new Socket(server_name, 80); /* Finally, we can read and write on the socket. */ System.out.println(" *** Connected to " + server_name + " ***"); /* ... */ sock.close(); } catch (java.io.IOException e) { System.err.println("error connecting to " + server_name + ": " + e); return; } } }

import java.io.*; import java.net.*; public class InetAddrDemo { public static void main(String[] args) throws UnknownHostException, IOException { String ipNumber = "220.119.249.154"; String hostName = "minpo.pr.ysu.ac.kr"; // Look up a host by name System.out.println(hostName + "'s address is " + InetAddress.getByName(hostName).getHostAddress()); // Look up a host by address System.out.println(ipNumber + "'s name is " + InetAddress.getByName(ipNumber).getHostName()); Socket theSocket = new Socket("localhost", 80); int myPortNumber = 12345; // Connect to different portnum on same host as an open Socket InetAddress remote = theSocket.getInetAddress(); Socket anotherSocket = new Socket(remote, myPortNumber); } }

import java.io.*; import java.net.*; public class DaytimeText { public static final short TIME_PORT = 13; public static void main(String[] argv) { String hostName; if (argv.length == 0) hostName = "minpo.pr.ysu.ac.kr"; else hostName = argv[0]; try { Socket sock = new Socket(hostName, TIME_PORT); BufferedReader is = new BufferedReader(new InputStreamReader(sock.getInputStream())); String remoteTime = is.readLine(); System.out.println("Time on " + hostName + " is " + remoteTime); } catch (IOException e) { System.err.println(e); } } }

import java.io.*; import java.net.*; public class EchoClientOneLine { /** What we send across the net */ String mesg = "Hello across the net"; public static void main(String[] argv) { if (argv.length == 0) new EchoClientOneLine().converse("minpo.pr.ysu.ac.kr"); else new EchoClientOneLine().converse(argv[0]); } /** Hold one conversation across the net */ protected void converse(String hostName) { try { Socket sock = new Socket(hostName, 7); // echo server. BufferedReader is = new BufferedReader(new InputStreamReader(sock.getInputStream())); PrintWriter os = new PrintWriter(sock.getOutputStream(), true); // Do the CRLF ourself since println appends only a \r on // platforms where that is the native line ending. os.print(mesg + "\r\n"); os.flush(); String reply = is.readLine(); System.out.println("Sent \"" + mesg + "\""); System.out.println("Got \"" + reply + "\""); } catch (IOException e) { System.err.println(e); } } }

import java.io.*; import java.net.*; import java.util.*; /**DaytimeBinary - connect to the Daytime (ascii) service.*/ public class DaytimeBinary { /** The TCP port for the binary time service. */ public static final short TIME_PORT = 37; /** Seconds between 1970, the time base for Date(long) and Time. * Factors in leap years (up to 2100), hours, minutes, and seconds. * Subtract 1 day for 1900, add in 1/2 day for 1969/1970. */ protected static final long BASE_DAYS = (long)(((1970 - 1900) * 365.25) - 1 + .5); /* Seconds since 1970 */ public static final long BASE_DIFF = (BASE_DAYS * 24 * 60 * 60); /** Convert from seconds to milliseconds */ public static final int MSEC = 1000; public static void main(String[] argv) { String hostName; if (argv.length == 0) hostName = "minpo.pr.ysu.ac.kr"; else hostName = argv[0]; try { Socket sock = new Socket(hostName, TIME_PORT); DataInputStream is = new DataInputStream(new BufferedInputStream(sock.getInputStream())); // Need to read 4 bytes from the network, unsigned. // Do it yourself; there is no readUnsignedInt(). // Long is 8 bytes on Java, but we are using the // existing daytime protocol, which uses 4-byte ints. long remoteTime = ( ((long)(is.readUnsignedByte() & 0xff) << 24) | ((long)(is.readUnsignedByte() & 0xff) << 16) | ((long)(is.readUnsignedByte() & 0xff) << 8) | ((long)(is.readUnsignedByte() & 0xff) << 0)); System.out.println("Remote time is " + remoteTime); System.out.println("BASE_DIFF is " + BASE_DIFF); System.out.println("Time diff == " + (remoteTime - BASE_DIFF)); Date d = new Date((remoteTime - BASE_DIFF) * MSEC); System.out.println("Time on " + hostName + " is " + d.toString()); } catch (IOException e) { System.err.println(e); } } }

Tftp
import java.io.*; import java.net.*; /** * RemCat - remotely cat (DOS type) a file, using the TFTP protocol. * Inspired by the "rcat" exercise in Learning Tree Course 363, * Note that the TFTP server is NOT "internationalized"; the name and * mode in the protocol are defined in terms of ASCII, not UniCode. */ public class RemCat { /** The UDP port number */ public final static int TFTP_PORT = 69; /** The mode we will use - octet for everything. */ protected final String MODE = "octet"; /** The offset for the code/response as a byte */ protected final int OFFSET_REQUEST = 1; /** The offset for the packet number as a byte */ protected final int OFFSET_PACKETNUM = 3; /** Debugging flag */ protected static boolean debug = false;

/** TFTP op-code for a read request */ public final int OP_RRQ = 1, /** TFTP op-code for a read request */ OP_WRQ = 2, /** TFTP op-code for a read request */ OP_DATA = 3, /** TFTP op-code for a read request */ OP_ACK = 4, /** TFTP op-code for a read request */ OP_ERROR = 5; protected final static int PACKET_SIZE = 516; protected String host; protected InetAddress servAddr; protected DatagramSocket sock; protected byte buffer[]; protected DatagramPacket inp, outp;

// == 2 + 2 + 512

/** The main program that drives this network client. * @param argv[0] hostname, running TFTP server * @param argv[1..n] filename(s), must be at least one */ public static void main(String[] argv) throws IOException { if (argv.length < 2) { System.err.println("usage: rcat host filename[...]"); System.exit(1); } if (debug) System.err.println("Java RemCat starting"); RemCat rc = new RemCat(argv[0]); for (int i = 1; i<argv.length; i++) { if (debug) System.err.println("-- Starting file " + argv[0] + ":" + argv[i] + "---"); rc.readFile(argv[i]); } }

RemCat(String host) throws IOException { super(); this.host = host; servAddr = InetAddress.getByName(host); sock = new DatagramSocket(); buffer = new byte[PACKET_SIZE]; outp = new DatagramPacket(buffer, PACKET_SIZE, servAddr, TFTP_PORT); inp = new DatagramPacket(buffer, PACKET_SIZE); } /* Build a TFTP Read Request packet. This is messy because the * fields have variable length. Numbers must be in * network order, too; fortunately Java just seems * naturally smart enough :-) to use network byte order. */ void readFile(String path) throws IOException { byte[] bTemp; buffer[0] = 0; buffer[OFFSET_REQUEST] = OP_RRQ; // read request int p = 2; // number of chars into buffer // Convert filename String to bytes in buffer , using "p" as an // offset indicator to get all the bits of this request // in exactly the right spot. bTemp = path.getBytes("ISO8859_1"); // i.e., ASCII System.arraycopy(bTemp, 0, buffer, p, path.length()); p += path.length(); buffer[p++] = 0; // null byte terminates string // Similarly, convert MODE ("octet") to bytes in buffer bTemp = MODE.getBytes("ISO8859_1"); // i.e., ASCII System.arraycopy(bTemp, 0, buffer, p, MODE.length()); p += MODE.length(); buffer[p++] = 0; // null terminate /* Send Read Request to tftp server */ outp.setLength(p); sock.send(outp);

/* Loop reading data packets from the server until a short * packet arrives; this indicates the end of the file. */ int len = 0; do { sock.receive(inp); if (debug) System.err.println( "Packet # " + Byte.toString(buffer[OFFSET_PACKETNUM])+ "RESPONSE CODE " + Byte.toString(buffer[OFFSET_REQUEST])); if (buffer[OFFSET_REQUEST] == OP_ERROR) { System.err.println("rcat ERROR: " + new String(buffer, 4, inp.getLength()-4)); return; } if (debug) System.err.println("Got packet of size " + inp.getLength()); /* Print the data from the packet */ System.out.write(buffer, 4, inp.getLength()-4); /* Ack the packet. The block number we * want to ack is already in buffer so * we just change the opcode. The ACK is * sent to the port number which the server * just sent the data from, NOT to port * TFTP_PORT. */ buffer[OFFSET_REQUEST] = OP_ACK; outp.setLength(4); outp.setPort(inp.getPort()); sock.send(outp); } while (inp.getLength() == PACKET_SIZE); if (debug) System.err.println("** ALL DONE** Leaving loop, last size " + inp.getLength()); } }

server PC

tftp

java RemCat 220.119.249.139 a A

import java.net.*; import java.io.*; /** * Telnet - connect to a given host and service * This does not hold a candle to a real Telnet client, but * shows some ideas on how to implement such a thing. * @version $Id: Telnet.java,v 1.8 2001/04/28 23:36:03 ian Exp $ */ public class Telnet { String host; int portNum; public static void main(String[] argv) { new Telnet().talkTo(argv); } private void talkTo(String av[]) { if (av.length >= 1) host = av[0]; else host = "220.119.249.139"; if (av.length >= 2) portNum = Integer.parseInt(av[1]); else portNum = 23; System.out.println("Host " + host + "; port " + portNum);

try { Socket s = new Socket(host, portNum); // Connect the remote to our stdout new Pipe(s.getInputStream(), System.out).start(); // Connect our stdin to the remote new Pipe(System.in, s.getOutputStream()).start(); } catch(IOException e) { System.out.println(e); return; } System.out.println("Connected OK"); } } /** This class handles one side of the connection. */ /* This class handles one half of a full-duplex connection. * Line-at-a-time mode. Streams, not writers, are used. */ class Pipe extends Thread { DataInputStream is; PrintStream os; // Constructor Pipe(InputStream is, OutputStream os) { this.is = new DataInputStream(is); this.os = new PrintStream(os); } // Do something method public void run() { String line; try { while ((line = is.readLine()) != null) { os.print(line); os.print("\r\n"); os.flush(); } } catch(IOException e) { throw new RuntimeException(e.getMessage()); } } }

DayTime Server
import java.io.*; import java.net.*; /** * DaytimeServer - send the binary time.*/ public class DaytimeServer { /** Our server-side rendezvous socket */ ServerSocket sock; /** The port number to use by default */ public final static int PORT = 37; /** main: construct and run */ public static void main(String[] argv) { new DaytimeServer(PORT).runService(); } /** Construct an EchoServer on the given port number */ public DaytimeServer(int port) { try { sock = new ServerSocket(port); } catch (IOException e) { System.err.println("I/O error in setup\n" + e); System.exit(1); } }

/** This handles the connections */ protected void runService() { Socket ios = null; DataOutputStream os = null; while (true) { try { System.out.println("Waiting for connection on port " + PORT); ios = sock.accept(); System.err.println("Accepted from " + ios.getInetAddress().getHostName()); os = new DataOutputStream(ios.getOutputStream()); long time = System.currentTimeMillis(); time /= DaytimeBinary.MSEC; // Convert to Java time base. time += DaytimeBinary.BASE_DIFF; // Write it, truncating cast to int since it is using // the Internet Daytime protocol which uses 4 bytes. // This will fail in the year 2038, along with all // 32-bit timekeeping systems based from 1970. // Remember, you read about the Y2038 crisis here first! os.writeInt((int)time); os.close(); } catch (IOException e) { System.err.println(e); } } } } // Daytime Protocol is in seconds

import java.net.*; import java.io.*; /** * Threaded Echo Server, sequential allocation scheme.*/ public class EchoServerThreaded { public static final int ECHOPORT = 7; public static void main(String[] av) { new EchoServerThreaded().runServer(); } public void runServer() { ServerSocket sock; Socket clientSocket; try { sock = new ServerSocket(ECHOPORT); System.out.println("EchoServerThreaded ready for connections."); /* Wait for a connection */ while(true){ clientSocket = sock.accept(); /* Create a thread to do the communication, and start it */ new Handler(clientSocket).start(); } } catch(IOException e) { /* Crash the server if IO fails. Something bad has happened */ System.err.println("Could not accept " + e); System.exit(1); } }

/** A Thread subclass to handle one client conversation. */ class Handler extends Thread { Socket sock; Handler(Socket s) { sock = s; } public void run() { System.out.println("Socket starting: " + sock); try { DataInputStream is = new DataInputStream( sock.getInputStream()); PrintStream os = new PrintStream( sock.getOutputStream(), true); String line; while ((line = is.readLine()) != null) { os.print(line + "\r\n"); os.flush(); } sock.close(); } catch (IOException e) { System.out.println("IO Error on socket " + e); return; } System.out.println("Socket ENDED: " + sock); } } }

Thread Class
Static method
Static int activeCount();

Static Thread currentThread();


Thread Thread myself = Thread.currentThread();

Static void sleep(long millis)


CPU For(int i=0;i<1000;++i) {
// Thread.yield();

interrupt()

InterruptedException CPU yield()

Static void yield();


CPU

Java Native Interface(1)


Step 1
Write the java code, making methods implemented in native code with the native keyword

JNIMathClient.java
class JNIMathClient { public native int addTwoNumbers(int one, int two); public native int multiplyTwoNumbers(int one, int two); static { System.loadLibrary("JNIMathClient"); } public static void main(String[] args) { JNIMathClient client = new JNIMathClient(); int num1, num2; num1 = 5; num2 = 100; System.out.println(num1 + " + " + num2 + " = " + client.addTwoNumbers(num1, num2)); System.out.println(num1 + " * " + num2 + " = " + client.multiplyTwoNumbers(num1, num2)); } }

Java Native Interface(2)


Step 2
Javac JNIMathClient.java Generate a C++ header file using jaah

javac JNIMathClient.java

javah JNIMathClient

Javah

JNIMathClient.h

/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class JNIMathClient */ #ifndef _Included_JNIMathClient #define _Included_JNIMathClient #ifdef __cplusplus extern "C" { #endif /* * Class: JNIMathClient * Method: addTwoNumbers * Signature: (II)I */ JNIEXPORT jint JNICALL Java_JNIMathClient_addTwoNumbers (JNIEnv *, jobject, jint, jint); /* * Class: JNIMathClient * Method: multiplyTwoNumbers * Signature: (II)I */ JNIEXPORT jint JNICALL Java_JNIMathClient_multiplyTwoNumbers (JNIEnv *, jobject, jint, jint); #ifdef __cplusplus } #endif #endif

Java Native Interface(3)


Step 3
Write the native code in C++ based on the generated header file

Java Native Interface(3)

Java Native Interface(3)


DLL code

Java Native Interface(4)


Step 4
Place the name of the library in a call to System.load or System.loadLibrary in the Java source
#include "stdafx.h" #include "..\JNIMathClient.h" JNIEXPORT jint JNICALL Java_JNIMathClient_addTwoNumbers(JNIEnv *, jobject, jint one, jint two) { return(one + two); } JNIEXPORT jint JNICALL Java_JNIMathClient_multiplyTwoNumbers(JNIEnv *, jobject, jint one, jint two) { return(one * two); } BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { return TRUE; }

Java Native Interface(5)


, jni.h, jni_md.h error Visual c++ option include path
C:\jdk\include C:\jdk\include\win32

Java Native Interface(6)

Minpo.DLL

class

C:\javaproject\jni\MinpoDll\Debug>copy MinpoDll.dll c:\javaproject\jni 1 file(s) copied.

Java Native Interface(7)


C:\javaproject\jni>java JNIMathClient Exception in thread "main" java.lang.UnsatisfiedLinkError: no Minpo.Dll in java. library.path at java.lang.ClassLoader.loadLibrary(Unknown Source) at java.lang.Runtime.loadLibrary0(Unknown Source) at java.lang.System.loadLibrary(Unknown Source) at JNIMathClient.<clinit>(JNIMathClient.java:7) C:\javaproject\jni>java Djava.library.path=c:\javaproject\jni JNIMathClient

public class EnvironmentInfo { public static void main(String[] args) { System.getProperties().list(System.out); } } class EnvironmentInfo2 { public static void main(String[] args) { System.out.println ( "file.separator : " + System.getProperty("file.separator") ); System.out.println ( "java.specification.version : " + System.getProperty("java.specification.version") ); System.out.println ( "java.vm.version : " + System.getProperty("java.vm.version") ); System.out.println ( "java.class.path : " + System.getProperty("java.class.path") ); System.out.println ( "java.vendor : " + System.getProperty("java.vendor") ); System.out.println ( "line.separator : " + System.getProperty("line.separator") ); System.out.println ( "java.class.version : " + System.getProperty("java.class.version") ); System.out.println ( "java.vendor.url : " + System.getProperty("java.vendor.url") ); System.out.println ( "os.arch : " + System.getProperty("os.arch") ); System.out.println ( "java.compiler : " + System.getProperty("java.compiler") ); System.out.println ( "java.version : " + System.getProperty("java.version") ); System.out.println ( "os.name : " + System.getProperty("os.name") ); System.out.println ( "java.ext.dirs : " + System.getProperty("java.ext.dirs") ); System.out.println ( "java.vm.name : " + System.getProperty("java.vm.name") ); System.out.println ( "os.version : " + System.getProperty("os.version") ); System.out.println ( "java.home : " + System.getProperty("java.home") ); System.out.println ( "java.vm.specification.name : " + System.getProperty("java.vm.specification.name") ); System.out.println ( "path.separator : " + System.getProperty("path.separator") ); System.out.println ( "java.io.tmpdir : " + System.getProperty("java.io.tmpdir") ); System.out.println ( "java.vm.specification.vendor : " + System.getProperty("java.vm.specification.vendor") ); System.out.println ( "user.dir : " + System.getProperty("user.dir") ); System.out.println ( "java.library.path : " + System.getProperty("java.library.path") ); System.out.println ( "java.vm.specification.version : " + System.getProperty("java.vm.specification.version") ); System.out.println ( "user.home : " + System.getProperty("user.home") ); System.out.println ( "java.specification.name : " + System.getProperty("java.specification.name") ); System.out.println ( "java.vm.vendor : " + System.getProperty("java.vm.vendor") ); System.out.println ( "user.name : " + System.getProperty("user.name") ); System.out.println ( "java.specification.vendor : " + System.getProperty("java.specification.vendor") ); } }

You might also like