วันอังคารที่ 19 กรกฎาคม พ.ศ. 2554

การ submit เว็บผ่าน java class

1.File dataAction.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
String firstName = request.getParameter("fname");
String lastName = request.getParameter("lname");
String idCard = request.getParameter("idcard");
String date = request.getParameter("date");

System.out.println("firstName : " + firstName);
System.out.println("lastName : " + lastName);
System.out.println("idCard : " + idCard);
System.out.println("date : " + date);
System.out.println("############################################");
   %>

2.Class HtmlSubmitServlet.java 
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;

public class HtmlSubmitServlet {

                // the hard-coded URL to the Service I want to invoke (should be injected of
                // course)
                private static final String BASE_URL = "http://localhost:8080/TestWEB/dataAction.jsp";

                public static void main(String[] args) {
                                HtmlSubmitServlet h = new HtmlSubmitServlet();
                                String firstName = "Tester";
                                String lastName = "java";
                                String idCard = "123456678";
                                String date = "12/10/1985";
                                h.submitData(firstName, lastName, idCard, date);
                }

                public void submitData(String firstName, String lastName, String idCard, String date) {
                                try {
                                                URL url = new URL(BASE_URL);
                                                URLConnection con = url.openConnection();

                                                // inform the connection that we will send output and accept input
                                                con.setDoInput(true);
                                                con.setDoOutput(true);

                                                // Don't use a cached version of URL connection.
                                                con.setUseCaches(false);
                                                con.setDefaultUseCaches(false);
                                                con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                                                // define a new PrintWriter on the output stream
                                                PrintWriter outWriter = new PrintWriter(con.getOutputStream());

                                                // send data to the servlet
                                                outWriter.print("fname=" + firstName);
                                                outWriter.print("&lanme=" + lastName);
                                                outWriter.print("&idcard=" + idCard);
                                                outWriter.print("&date=" + date);
                                                outWriter.close();
                                                InputStream input = con.getInputStream();
                                                File outputFile = new File("z.txt");
                                                FileOutputStream out = new FileOutputStream(outputFile);

                                                boolean eof = false;
                                                // read all bytes from the input and write them to the output
                                                while (!eof) {
                                                                int byteValue = input.read(); // read the stream
                                                                out.write(byteValue);
                                                                if (byteValue == -1)
                                                                                eof = true;
                                                }
                                                out.close();
                                } catch (FileNotFoundException fnfe) {
                                                fnfe.printStackTrace();
                                } catch (IOException ioe) {
                                                ioe.printStackTrace();
                                }
                }
}

ขั้นตอนการทำงาน  ให้ทำการ run file jsp ทิ้งไว้ จากนั้นให้มารัน .java เราจะเห็น output ที่ console
   ผลลัพธ์ที่ได้ 
firstName : Tester
lastName : java
idCard : 123456678
date : 12/10/1985
############################################

วันเสาร์ที่ 9 กรกฎาคม พ.ศ. 2554

ตัวอย่างการเขียน java ลงไฟล์ .DOC

ตัวอย่างการเขียน java ลงไฟล์ .DOC


import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

public class WriteDocFile {
       public static void main(String args[]) throws IOException {
                File witches = new File("C:/Documents and Settings/All Users/Desktop/test.doc");
                PrintWriter out = new PrintWriter(witches);
                char[] array0 = { 'O', 'c', 'o', 'p', 's', 'O' }, array1 = { 's', 't',
                    'i', 'l', 'l', '0' }, array2 = { 'e', 's', 'c', 'a', 'p', 'e',
                    'd', '0' };
                String str0 = new String("chasing"), str1 = "Thieves";

                out.write(str1);
                out.print(" ");
                out.write(array2, 0, 7);

                out.println("");

                out.write(array0, 1, 4);
                out.print(" ");
                out.write(array1, 0, 5);
                out.print(" ");
                out.write(str0);

                out.flush();
              }
}

วันพฤหัสบดีที่ 7 กรกฎาคม พ.ศ. 2554

การส่ง E-Mail โดยใช้ smtp.gmail.com



ตัวอย่างการเขียน Class สำหรับการส่ง Email โดยใช้ บริการของ Gmail และมีการใช้ SSL ด้วย


/**
 * http://www.javaworkspace.com/javaMail.do เข้าไปดูตัวอย่างเพิ่มเติมได้ที่นี่นะครับ
 */
import java.security.Security;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SimpleGmailSSL {

      private static final String SMTP_HOST_NAME = "66.249.93.109";//"smtp.gmail.com";
      private static final String SMTP_PORT = "465";
      private static final String emailMsgTxt = "Test Message Contents";
      private static final String emailSubjectTxt = "A test from gmail";
      private static final String emailFromAddress = "test.01@gmail.com";
      private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
      private static final String[] sendTo = { "test.01@gmail.com", "test0.1@gmail.com" };

      public static void main(String args[]) throws Exception {

            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

            new SimpleGmailSSL().sendSSLMessage(sendTo, emailSubjectTxt, emailMsgTxt, emailFromAddress);
            System.out.println("Sucessfully Sent mail to All Users");
      }

      public void sendSSLMessage(String recipients[], String subject, String message, String from) throws MessagingException {
            try {
                  boolean debug = true;

                  Properties props = new Properties();
                  props.put("mail.smtp.host", SMTP_HOST_NAME);
                  props.put("mail.smtp.auth", "true");
                  props.put("mail.smtp.starttls.enable", "true");
                  props.put("mail.debug", "true");
                  props.put("mail.smtp.port", SMTP_PORT);
                  props.put("mail.smtp.socketFactory.port", SMTP_PORT);
                  props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
                  props.put("mail.smtp.socketFactory.fallback", "false");

                  Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
                        protected PasswordAuthentication getPasswordAuthentication() {
                              return new PasswordAuthentication("email.test@gmail.com", "password");
                        }
                  });

                  session.setDebug(debug);

                  Message msg = new MimeMessage(session);
                  InternetAddress addressFrom = new InternetAddress(from);
                  msg.setFrom(addressFrom);

                  InternetAddress[] addressTo = new InternetAddress[recipients.length];
                  for (int i = 0; i < recipients.length; i++) {
                        addressTo[i] = new InternetAddress(recipients[i]);
                  }
                  msg.setRecipients(Message.RecipientType.TO, addressTo);

                  // Setting the Subject and Content Type
                  msg.setSubject(subject);
                  msg.setContent(message, "text/plain");
                  Transport.send(msg);
            } catch (MessagingException e) {
                  throw new RuntimeException(e);
            }
           
      }
}




ขอให้สนุกกับการเขียนโปรแกรมนะครับ
่โดย : http://java-thai-talk.blogspot.com

วันพุธที่ 6 กรกฎาคม พ.ศ. 2554

Code วิธีการรัน คำสั่ง shell ด้วย java.


Code วิธีการรัน คำสั่ง shell ด้วย java.
============================================
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;

public class ExecuteSH {
      public static void main(String args[]) {

            String path = "./";
            String fileShell = "executeable.sh";
            String cmd ="sh "+path + fileShell;
            File inputFile = null;
            try {
                  inputFile = new File(path + fileShell);
                  if (!inputFile.exists()) {
                        throw new FileNotFoundException("input file not found: " + inputFile.getPath());
                  } else {
                        System.out.println("Input Path :: " + inputFile.getPath());
                        System.out.println("shell command :: " + cmd);
                        System.out.println(MNPExecuteSH.executeSH(cmd));
                  }

            } catch (FileNotFoundException fe) {
                  System.out.println("xx error 1:: >> ");
                  fe.printStackTrace();
            } catch (Exception e) {
                  System.out.println("xx error 2:: >> ");
                  e.printStackTrace();

            } finally {
                  System.out.println("Run Done...");
            }

      }

      public static String executeSH(String cmd) {
            System.out.println("Command=" + cmd);
            try {
                  Runtime run = Runtime.getRuntime();
                  Process pr = run.exec(cmd);
                  //System.out.println("Obj Process "+pr);
                  pr.waitFor();
                  //System.out.println("pr.getInputStream() "+pr.getInputStream());
                  BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
                  String line = "";
                  while ((line = buf.readLine()) != null) {
                        System.out.println(line);
                  }
                  //System.out.println("Test executeSH");
            } catch (Exception e) {
                  // return e.toString();
                  System.out.println(e.toString());
            }
            return "Success";
      }
}