الفريق العربي للبرمجةأرشيف المنتديات · 2000 – 2023
نسخة أرشيفية للقراءة فقط — التسجيل والمشاركة مغلقان، والمحتوى محفوظ كما كان.

استعمال Beans في صفحة JSP

مغلق
بدأه رامي العيساوي في 28 فبراير 2003 · 36 رد · 2,967 مشاهدة · في JavaSE
مشاركة: واتساب X فيسبوك تيليجرام
#1 صاحب الموضوع

ليكم الوضع باختصار:يوجد صفحة JSP تشغل طريقة من كلاس اسمه RamyBean مهمتها فتح منفذ تسلسي و لكنني فشلت مع العلم انها نجحت ولكن في

كتابة ملف او تشغيل ملف عن طريق Runtime ولكن عند فتح المنفذ يظهر لي الخطا التالي:

Error: 500

Location: /rjsp/oport.jsp

Internal Servlet Error:



javax.servlet.ServletException

	at 



org.apache.jasper.runtime.PageContextImpl.handlePageException(Page



ContextImpl.java:460)

	at oport_1._jspService(oport_1.java:90)

	at 



org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:119



)

	at 



javax.servlet.http.HttpServlet.service(HttpServlet.java)

	at 



org.apache.tomcat.facade.ServletHandler.doService(ServletHandler.j



ava:574)

	at org.apache.tomcat.core.Handler.invoke(Handler.java:322)

	at 



org.apache.tomcat.core.Handler.service(Handler.java:235)

	at 



org.apache.tomcat.facade.ServletHandler.service(ServletHandler.jav



a:485)

	at 



org.apache.tomcat.core.ContextManager.internalService(ContextManag



er.java:917)

	at 



org.apache.tomcat.core.ContextManager.service(ContextManager.java:



833)

	at 



org.apache.tomcat.modules.server.Http10Interceptor.processConnecti



on(Http10Interceptor.java:176)

	at 



org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.j



ava:494)

	at 



org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(Thre



adPool.java:516)

	at java.lang.Thread.run(Thread.java:484)

Root cause:

java.lang.NullPointerException

	at RamyBean.open(RamyBean.java:15)

	at oport_1._jspService(oport_1.java:80)

	at 



org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:119



)

	at 



javax.servlet.http.HttpServlet.service(HttpServlet.java)

	at 



org.apache.tomcat.facade.ServletHandler.doService(ServletHandler.j



ava:574)

	at org.apache.tomcat.core.Handler.invoke(Handler.java:322)

	at 



org.apache.tomcat.core.Handler.service(Handler.java:235)

	at 



org.apache.tomcat.facade.ServletHandler.service(ServletHandler.jav



a:485)

	at 



org.apache.tomcat.core.ContextManager.internalService(ContextManag



er.java:917)

	at 



org.apache.tomcat.core.ContextManager.service(ContextManager.java:



833)

	at 



org.apache.tomcat.modules.server.Http10Interceptor.processConnecti



on(Http10Interceptor.java:176)

	at 



org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.j



ava:494)

	at 



org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(Thre



adPool.java:516)

	at java.lang.Thread.run(Thread.java:484)

ملف JSP هو كالتالي:

<head>

<title>Open Port</title>

</head>



<body>

<jsp:useBean id="ramy" class="RamyBean" />

<%

ramy.open();

%>

Status:<%=ramy.pass %>

</body>



</html>

ملف RamyBean هو كالتالي:

import javax.comm.*;

import java.io.*;

import javax.swing.*;

public class RamyBean

{

     String pass;

    static CommPortIdentifier portId;

    static SerialPort serialPort;

    static OutputStream outputStream;

    static InputStream inputStream;

     public void open()

    {

        try 



{portId=CommPortIdentifier.getPortIdentifier("COM2");}catch 



(NoSuchPortException np){pass="Error:"+np;}

  try {

  



serialPort=(SerialPort)portId.open("RamyAlisawi",2000);

  }catch (PortInUseException 



pin){pass="Error:"+pin;}

  



try{outputStream=serialPort.getOutputStream();inputStream=serialPo



rt.getInputStream();}catch (IOException e){pass="Error:"+e;}	

	}

    

}

و الآن ارجو منكم اخواني مساعدتي فانا تعلمت اللغة و نزلت Tomcat بس مشان افتح المنفذ و اتحكم بدارة و السبب هو ان الجافا ابليت لم تنجح في ذلك فقلت لنفسي ان JSP اكيد بتسطيع بسبب تعاملها السهل مع المخدم....مع جزيل الشكر مقدما

Theory is when you know something, but it doesn't work. Practice is when something works, but you don't know why. Programmers combine theory and practice: Nothing works and they don't know why

#2

..

تم تعديل هذه المشاركة بواسطة رامي العيساوي في 3 مايو 2005 في 18:18

Theory is when you know something, but it doesn't work. Practice is when something works, but you don't know why. Programmers combine theory and practice: Nothing works and they don't know why

#3

I'm reading the files now, if I find anything useful I'll soon send to you.(clock)

#4

can you please tell me where can I find the package javax.comm

cause I'm just sick and tired from serfing a thousand site to get it

you can just send the class you are using by mail

anloar@maktoob.com

#5

هذا هو العنوان :

http://java.sun.com/products/javacomm/

و لكن ارجوك ان تساعدني يا اخي علاء الدين

Theory is when you know something, but it doesn't work. Practice is when something works, but you don't know why. Programmers combine theory and practice: Nothing works and they don't know why

#6

My brother I had the following error message

500 Internal Server Error

java.lang.NoClassDefFoundError: javax/comm/PortInUseException

at java.lang.Class.forName0(Native Method)

at java.lang.Class.forName(Class.java:195)

at com.evermind.server.http.HttpApplication.vu(JAX)

at com.evermind.server.http.eg.tk(JAX)

at com.evermind.server.http.eg.sm(JAX)

at com.evermind.server.http.JSPPage.sm(JAX)

at com.evermind.server.http.HttpApplication.v4(JAX)

at com.evermind.server.http.HttpApplication.w5(JAX)

at com.evermind.server.http.JSPServlet.service(JAX)

at com.evermind.server.http.d1.si(JAX)

at com.evermind.server.http.d1.forward(JAX)

at com.evermind.server.http.ed.sp(JAX)

at com.evermind.server.http.ed.so(JAX)

at com.evermind.util.f.run(JAX)

I think it is some linking problem I wish I can find something usefull

I'll keep treing.

#7

java.lang.NoClassDefFoundError: javax/comm/PortInUseException

اظن ان هذا الخطا اما انه لم يجد كلاس المسؤول عن Exception

او ان المنفذ مستخدم او انت واصل عليه شي و الويندوز متحكم فيه و فاتحه قبلك لذا جرب غيره COM2 مثلا

مشكور كثير على مساعدتك لي

Theory is when you know something, but it doesn't work. Practice is when something works, but you don't know why. Programmers combine theory and practice: Nothing works and they don't know why

#8

السلام عليكم

اولا : سوي كلاس متخصص في التعامل مع الكوم بورت ومن ثم سرفلت تتعامل مع الكلاس وهذا مثال سويته قديما حيث يتم التعامل مع كاميرا عن طريق كوم بورت ولكن السرفلت لابد تكون في نفس الكمبوتر (اقرا عن Java Security)

:

import java.util.Enumeration;

import java.util.Vector;

import java.util.TooManyListenersException;

import javax.comm.*;

import java.io.OutputStream;

import java.io.InputStream;

import java.io.IOException;

import java.io.BufferedReader;

import java.io.InputStreamReader;



/**

 * Class to read and write to the Osprey webcamera

 *

 *@author Mohammed Bawazeer

 *@version 1.0

 *@see javax.comm.SerialPort

 *@see javax.comm.SerialPortEventListener

 *@see java.lang.Thread

 */

public class SerialPortWriter implements Runnable, SerialPortEventListener {



  private SerialPort serialPort;

  private OutputStream os;

  private InputStream is;



  /**

   * Run it from the command line

   * takes the name of the comm port as 

   * its first and only argument

   */

  public static void main(String args[])

  {

    /* check for errors */

    if (args.length != 1) {

      System.out.println("Usage: java SerialPortWriter <port_id>");

      System.exit(-1);

    }



    SerialPortWriter writer = null;



    /* init the writer */

    try {

      writer = new SerialPortWriter(args[0]);

    } catch (Exception e) {

      e.printStackTrace();

      System.exit(-1);

    }

    

    /* get input from the command line */

    BufferedReader in = null;

    try {

      in = new BufferedReader(

                         new InputStreamReader(System.in));

    } catch (Exception e) {

      e.printStackTrace();

      System.exit(-1);

    }



    /* run until the user enters a -1 */

    while (true)  {

      System.out.print("Enter next value to write (-1 to exit): ");

      int value = -1;

      /* read the integer from the command line */

      try {

        value = Integer.parseInt(in.readLine());

      } catch (NumberFormatException nfe) {

         System.out.println("nNumbers Only please.");

         continue;

      } catch (IOException iox) {

         iox.printStackTrace();

         continue;

      }



      /* exit on -1 */

      if (value == -1)

      {

        System.out.println("Exiting now.");

        System.exit(0);

      }

      /* 255 is equal to 0xFF hex */

      else if (value > 255)

      {

        System.out.println("Numbers between 00 and FF (Decimal 0 - 255) please.");

        continue;

      }



      /* okay, everything is fine, write the value */

      try {

        writer.write(value);

      } catch (Exception e) {

         System.out.println("Error: " + e.getMessage());

      }

    }

  }



  /**

   * Only constructor.

   *

   *@param port The name of the serial port to be used prints an

   *       error message if it can't find your port.

   *

   */

  public SerialPortWriter (String port)

     throws IOException, UnsupportedCommOperationException,

            PortInUseException, TooManyListenersException

  {



    CommPortIdentifier portId = null;

    Enumeration portList = CommPortIdentifier.getPortIdentifiers();

    boolean found = false;



    /* iterate through system ports, and find the right one */

    while (portList.hasMoreElements())

    {



      portId = (CommPortIdentifier)portList.nextElement();

    

      // uncomment for debugging

      // System.out.println(portId.getName());



      if (portId.getName().equalsIgnoreCase(port)) { 

        this.serialPort = (SerialPort) portId.open("CameraControl", 2000);

        found = true;

      }



    }



    /* throw an exception if we don't find it */

    if (!found)

      throw new IOException("Comm Port " + port + " not found on server.");



    initStreams();





    Thread readThread = new Thread(this);

    readThread.setDaemon(true);

    readThread.start();

  }



  /**

   * method to initialize the input and output streams to and

   * from the camera.  Databits is set to 8, speed to 9600, no parity

   * and stop bits set to 1.

   */

  public void initStreams() 

     throws IOException, UnsupportedCommOperationException, 

            TooManyListenersException

  {

    os = serialPort.getOutputStream();

    is = serialPort.getInputStream();



    this.serialPort.addEventListener(this);

    this.serialPort.notifyOnDataAvailable(true);



    serialPort.setSerialPortParams(

       9600,

       SerialPort.DATABITS_8,

       SerialPort.STOPBITS_1,

       SerialPort.PARITY_NONE);

  }



  /**

   * write a set of bytes to the camera

   *@param bytes the byte buffer to be sent

   */

  public void write(byte[] bytes)

      throws IOException

  {

     os.write(bytes);

  }



  /**

   * write a raw string to the camera.

   *@param string The string to be written

   */

  public void write(String string)

      throws IOException

  {

    os.write(string.getBytes());

  }



  /**

   * Write and integer to the camera

   *@param integer The int to be written

   */

  public void write(int integer)

      throws IOException

  {

    os.write(integer);

  }



  /**

   * Implement the run method

   */

  public void run()  {



    while (true)  {

        try {

            Thread.sleep(20000);

        } catch (InterruptedException e) {}

    }

  }



  /** 

   * Handle data when it becomes available

   *@param event The fired SerialPortEvent

   */

  public void serialEvent(SerialPortEvent event) {  



    switch(event.getEventType())  {

      case SerialPortEvent.BI:

      case SerialPortEvent.OE:

      case SerialPortEvent.FE:

      case SerialPortEvent.PE:

      case SerialPortEvent.CD:

      case SerialPortEvent.CTS:

      case SerialPortEvent.DSR:

      case SerialPortEvent.RI:

      case SerialPortEvent.OUTPUT_BUFFER_EMPTY:

        break;

      case SerialPortEvent.DATA_AVAILABLE:

        byte[] readBuffer = new byte[20];

        int numBytes = 0;

        try {

          while(is.available() > 0) {

            numBytes = is.read(readBuffer);

          }

          if (numBytes > 0)

            printToStdOut(readBuffer);

        } catch (IOException iox) {}

        break;

    }



  }



  /**

   * Print the read buffer to std out

   *@param buffer The byte buffer read from the port

   */

  public synchronized void printToStdOut(byte[] buffer)

  {

    System.out.print("nInput Buffer Contents:");

    for (int i = 0; i < buffer.length; i++)

      System.out.print(" " + (int)buffer);



    System.out.println();

  }

  

}

اخيك محمد

#9

مشكور جدا جدا جدا

انا كنت انتظر هكذا مساعدة من احد اخواني الاعزاء.

و انا ما عندي مشكلة في ان اتكون السيرفلت في جهاز المخدم لاني انا اريد ذلك و عامل جهازي هو المخدم.

ولكن ممكن تعطيني السيرفلت اذا امكن و سوف اكون مشكور جدا لك و ساكون باستعداد اول واحد لاقدم اي مساعدة تريدها او تطلبها.

و عندي سؤال ليش ما بصير عن طريق صفحة JSP ليش سيرفلت هل هذا ضروري انا كما رايت حاولت في صفحة JSP و ماشي الحال خايف لا تنجح في سيرفلت ايضا

و شكرا لك مرة اخرى على الاستاجابة

Theory is when you know something, but it doesn't work. Practice is when something works, but you don't know why. Programmers combine theory and practice: Nothing works and they don't know why

#10

اخي العزيز

لم اصبر لغد حتى اجرب الطريقة التي اخبرتني بها و سهرت لحد الآن مع انه لدي دوام باكر و للاسف لم احصل على نتيجة جيدة مثلما توقعت شوف الذي جرى معي و حسب طريقتك بان انشئ كلاس فيه طريقة لفتح المنفذ و من ثم استدعيها من سيرفلت .

ملف الكلاس المسؤول عن فتح المنفذ:

import javax.comm.*;

import java.io.*;

import javax.swing.*;

public class RamyBean  

{

  static   String pass;

    static CommPortIdentifier portId;

   static  SerialPort serialPort;

   static  OutputStream outputStream;

   static  InputStream inputStream;

     static public void open()

    {

        try {portId=CommPortIdentifier.getPortIdentifier("COM2");}catch (NoSuchPortException np){pass="Error:"+np;}

  try {

  serialPort=(SerialPort)portId.open("RamyAlisawi",2000);

  }catch (PortInUseException pin){pass="Error:"+pin;}

  try{outputStream=serialPort.getOutputStream();inputStream=serialPort.getInputStream();}catch (IOException e){pass="Error:"+e;}	

	pass="Yes Yes";

	} 

   

}

ملف السيرفلت الذي سوف يستدعى الطريقة:

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;



public class Ramyservlet extends HttpServlet {



    public void doGet(HttpServletRequest request, HttpServletResponse response)

    throws IOException, ServletException

    {

        PrintWriter out = response.getWriter();

        RamyBean.open();

    out.println(RamyBean.pass);

        

    }

}

الخطا الذي يظهر عند التشغيل:

Internal Servlet Error:



java.lang.NullPointerException

	at RamyBean.open(RamyBean.java:15)

	at Ramyservlet.doGet(Ramyservlet.java:13)

	at javax.servlet.http.HttpServlet.service(HttpServlet.java)

	at javax.servlet.http.HttpServlet.service(HttpServlet.java)

	at org.apache.tomcat.facade.ServletHandler.doService(ServletHandler.java:574)

	at org.apache.tomcat.core.Handler.invoke(Handler.java:322)

	at org.apache.tomcat.core.Handler.service(Handler.java:235)

	at org.apache.tomcat.facade.ServletHandler.service(ServletHandler.java:485)

	at org.apache.tomcat.core.ContextManager.internalService(ContextManager.java:917)

	at org.apache.tomcat.core.ContextManager.service(ContextManager.java:833)

	at org.apache.tomcat.modules.server.Http10Interceptor.processConnection(Http10Interceptor.java:176)

	at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:494)

	at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:516)

	at java.lang.Thread.run(Thread.java:484)

ارجو منك مساعدتي فانا اعمل بجهد و تعب و تعبت و تضايقت لعدم نجاح الطريقة معي و انت املي الوحيد.

Theory is when you know something, but it doesn't work. Practice is when something works, but you don't know why. Programmers combine theory and practice: Nothing works and they don't know why

#11

السلام عليكم java man

حابدا معاك من البدايه لكي تكون المساعده مفيده

اولا ما هو هدفك من البرنامج؟, هل تريد ان ترسل اشاره الي COM2 فقط؟

في العاده تكون هناك لوحه الكترونيه مثل MODEM او اي شي. ما هي اللوحه في COM2 ?

اما بالنسبه للكلاس ايش رائك تشيك هذا الكود اولا ومن ثم نبني عليه:

import javax.comm.*;

import java.util.*;

import java.io.*;





//import javax.swing.*;



public class RamyBean  

{

    private static String pass;

    private static CommPortIdentifier portId;

    private static SerialPort serialPort;

    private static OutputStream outputStream;

    private static InputStream inputStream;

    private static String port = "COM2";

    

    public static void main (String[] args){

     

      CommPortIdentifier portId = null;

      

      Enumeration portList = CommPortIdentifier.getPortIdentifiers();

           /* iterate through system ports, and find the right one */

      while (portList.hasMoreElements())

       {

      portId = (CommPortIdentifier)portList.nextElement();

             System.out.println(portId.getName());

             if (portId.getName().equalsIgnoreCase(port)) { 

  System.out.println( " my port is found " +port);

       }

      else{

  System.out.println( " my port " + port + " is not found ");

       }

              //before you open check if it does exist

       //this.serialPort = (SerialPort) portId.open("RamyAlisawi", 2000);

       }

     }
#12

السلام عليكم

الوقت تاخر علي وإن شاء الله بكره نكمل.

سلام

#13

نعم انا معك و مشكور كثيرا كثيرا

لحد لاىن لا يوجد مشاكل و كل شي عادي

نكمل بكرة بس لا تنساني ارجوك

البرنامج بختصار:

مخدم في البيت او المعمل وهو لك اي تستطيع التصرف به تتصل فيه من الخارج فتدخل الى موقع وفي الموقع تظهر لك لوحة تحكم تفتح المنفذ مع دارة تتحكم بالاضواء و الابواب ومن لوحة التحكم تختار ما تريد.

كل شي زبط و جاهز ماعدا الصفحة التي سوف تفتح المنفذ استطيع عمل ذلك على تطبيق و افتح المنفذ به و لكن اريدها في موقع في صفحة

شكرا لك لمساعدتي و اهتمامك بي

Theory is when you know something, but it doesn't work. Practice is when something works, but you don't know why. Programmers combine theory and practice: Nothing works and they don't know why

#14
Alsalam alakum,





   I am sorry, I have to write in English because I am at work and I don't have any Arabic Keys at my workstation. 



   OK, The class written above SerialWriter.java is made to write different paramaters, so if you want to write int, byte array, or string you can. Why don't you use it and fix it to your needs  !!! 

   If I were you I would create the following:



   - You need a server which resides on the machine at home or office.

      ( this server listens for requests and execute the Comm Class)

      and returns follow up data.



   - You need a servlet that resides on the same machine. Accepts requests from the JSP or Applet from the web and route the request to the server and the server does its work. 



   - Need a JSP or an applet that resides on a webserver on the same machine. With an interface and sends signals to the servlet telling it what to do. 



   To start doing this, start with the class above and start sending and receiving signals manually by hand using the main method of the class. if you determine that your class is executing commands then start with the server and then with the interface( jsp, applet). 



    Remember that JSP and Applets can not access system resources because of Java Security which prohbits that. 



    NOTE: Any JSP page becomes a servlet eventually with some differences and TOMCAT will convert your JSP page into a servlet and compile the code. 



   FI Aman Illah

,

#15

نعم اخي ولكن انا عملت التال و اخبرني ماهو الخطا:

-مخدم Tomcat يستقبل طلبات المستخدمين من الخارج.

- يظهر لهم موقع صفحة JSP او سيرفلت او ابليت تتولى فتح المنفذ .

- يوجد اوامر اخرى للدارة مثل الاضوية الخ...

اليست هذه لطريقة التي يجب ان اتبعها اذا كانت صحيحة

فان المشكلة الوحيدة هي فتح المنفذ انا عملت جافا ابليت و لكنني لا اعرف كيف اخبرها ان تفتح المنفذ و ترسل الاشارات الى المخدم التى محملة عليه و ليس على جهاز المستخدم.

وشكرا لك مرة ثانية

Theory is when you know something, but it doesn't work. Practice is when something works, but you don't know why. Programmers combine theory and practice: Nothing works and they don't know why

#16
Alsalam alakum,

     

   The best way to handle this is break your work into 3 parts to get rid of any security and connection issues. also it will be easy to program.



    1- Create and applet, webpage that is only the interface and has all the control interfaces. control applet or webpage will send a Form to a servlet on the machine that has the hardware. 

  

    2- create a servlet that will accept a form from the applet or page and process the paramaters to be sent to a program that will do the work.



    3- Create a program (server, deamon) that will run in the background and receives inputs via TCP and a port number from the servelt. This program will use the comm port class above that will write to the com port. This program will return the status to the servlet and the servlet will send info to the applet to display success or failure. 



   Now, if you do this, you will eliminate and problems with security and make your work broken into small pieces. 



   .



   You can email me at bawazeem@yahoo.com

   I have a drawing for you that I will send. 



  fi aman illah
#17

السلام عليكم

اخي العزيز java man

هذا كل الكود الي تحتاجه ويلزم عليك ان تغيره حسب حاجتك

قعدت فتره طويله لكتابه هذا الكود والسبب اني معجب باصرارك .

كنت اود ان نبرمج هذا الكود مع بعض حسب حاجتك ونوع اللوحه التي في الكمبيوتر تبعك.

1- سويت Applet ترسل اشارات الي سرفلت ومن ثم السرفلت ترسل اشاره الى مخدم والمخدم ياخذ كل التعليمات ويخزنها ومن ثم يسوي شغله.

2- المخدم يتعامل مع thread لانه لا بد نحسب حساب ان ال Applet في الويب وممكن ارسال اشارات كثيره.

-------------------------------------------------------------------------------

APPLET:

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

import java.io.*;

import java.net.*;

import java.lang.*;

import java.util.*;

import java.text.*;





public class ControlApplet extends Applet implements Runnable{

  boolean isStandalone = false;

  Thread timer;



  public static Label time = new Label();

  public static int rc = 0;



  Panel titlePanel = new Panel();

  Panel panel1 = new Panel();

  Panel upPanel = new Panel();

  Panel downPanel = new Panel();

  Panel centerPanel = new Panel();

  Panel timePanel = new Panel();



  Label title = new Label();



  Button left;

  Button right;

  Button up;

  Button down;

  Button stop;

  Button leftup;

  Button rightup;

  Button downleft;

  Button downright;



  //Get a parameter value

  public String getParameter(String key, String def) {

    return isStandalone ? System.getProperty(key, def) :

      (getParameter(key) != null ? getParameter(key) : def);

  }



  //Initialize the applet

  public void init() {



    DirectionListener direction = new DirectionListener();

    this.setSize(new Dimension(400,300));

    // layout of the applet

    this.setLayout( new BorderLayout());



    Label timeremaining = new Label();

    

    stop = new Button();

    left = new Button();

    right = new Button();

    up = new Button();

    down = new Button();

    leftup = new Button();

    rightup = new Button();

    downleft = new Button();

    downright = new Button();



    title.setForeground(Color.white);

    title.setText("Control Applet from the Web");

    Font f = new Font( "Serif", Font.BOLD, 16 );

    title.setFont(f);



    // left direction button

    left.setName("left");

    left.setLabel("   L    ");

    left.setBackground(Color.blue);

    left.setForeground(Color.white);

    left.setBounds(100, 150, 20, 15);



    // right direction button

    right.setName("right");

    right.setLabel("    R    ");

    right.setBackground(Color.blue);

    right.setForeground(Color.white);

    right.setBounds(300, 150, 20, 15);



    // up direction button

    up.setName("up");

    up.setLabel("   U    ");

    up.setBackground(Color.blue);

    up.setForeground(Color.white);

    up.setBounds(200, 100, 20, 15);



    // down direction button

    down.setName("down");

    down.setLabel("   D    ");

    down.setBackground(Color.blue);

    down.setForeground(Color.white);

    down.setBounds(200, 200, 20, 15);



    // stop direction button

    stop.setName("stop");

    stop.setLabel("   S    ");

    stop.setBackground(Color.red);

    stop.setForeground(Color.white);

    stop.setBounds(200, 150, 20, 15);



    leftup.setName("leftup");

    leftup.setLabel("  LU   ");

    leftup.setBackground(Color.blue );

    leftup.setForeground(Color.white);

    leftup.setBounds(200, 150, 20, 15);

    

    rightup.setName("rightup");

    rightup.setLabel("  RU   ");

    rightup.setBackground(Color.blue );

    rightup.setForeground(Color.white);

    rightup.setBounds(200, 150, 20, 15);



    downleft.setName("downleft");

    downleft.setLabel("  LD   ");

    downleft.setBackground(Color.blue );

    downleft.setForeground(Color.white);

    downleft.setBounds(200, 150, 20, 15);



    downright.setName("downright");

    downright.setLabel("  RD   ");

    downright.setBackground(Color.blue );

    downright.setForeground(Color.white);

    downright.setBounds(200, 150, 20, 15);



    time.setName("time");

    time.setForeground(Color.white);

    time.setFont(f);

    time.setText("0.0 seconds      ");

    

    timeremaining.setForeground(Color.white);

    timeremaining.setName("timeremaining");

    timeremaining.setText("time remaining");

    timeremaining.setFont(f);



// set the color of the panels

  panel1.setBackground(Color.darkGray);

  title.setBackground(Color.darkGray);

  upPanel.setBackground(Color.gray);

  downPanel.setBackground(Color.gray);

  centerPanel.setBackground(Color.gray);

  timePanel.setBackground(Color.darkGray);

    

// set the layout of each panel

  panel1.setLayout( new GridLayout(5,1));

  titlePanel.setLayout( new FlowLayout(10) );

  upPanel.setLayout( new FlowLayout(20, 50, 30));

  centerPanel.setLayout( new FlowLayout(20, 50, 30));

  downPanel.setLayout( new FlowLayout(20, 50, 30));

  timePanel.setLayout( new FlowLayout(FlowLayout.CENTER, FlowLayout.LEFT, FlowLayout.RIGHT));



// add component to each panel      

  titlePanel.add( title );

  upPanel.add( leftup );

  upPanel.add( up );

  upPanel.add( rightup );

  centerPanel.add(left);

  centerPanel.add(stop);

  centerPanel.add(right);

  downPanel.add(downleft);

  downPanel.add(down);

  downPanel.add(downright);



  timePanel.add(timeremaining);

  timePanel.add(time);



// add all panels to main panel

  panel1.add( titlePanel );    

  panel1.add( upPanel );    

  panel1.add( centerPanel );    

  panel1.add( downPanel );    

  panel1.add( timePanel );    





    add(panel1, BorderLayout.CENTER);



    // adding listeners for the buttons



    left.addActionListener( direction );

    right.addActionListener( direction );

    up.addActionListener( direction );

    down.addActionListener( direction );

    stop.addActionListener( direction );

    leftup.addActionListener( direction );

    rightup.addActionListener( direction );

    downright.addActionListener( direction );

    downleft.addActionListener( direction );



    Thread thread = new Thread(this);

    thread.start();

  }





  //Get Applet information

  public String getAppletInfo() {

    return "Control Applet from the Web";

  }



  //Get parameter info

  public String[][] getParameterInfo() {

    return null;

  }



     class DirectionListener implements ActionListener

     {

          /** Respond to the action events

            * @param e The applet event

            */

     

        public void actionPerformed( ActionEvent e )

        {



           if (RemoteControl.rc > 0)

             return;



           Object source = e.getSource();

            if ( source == up )

            {

              RemoteControl.rc = getObjReceived( "top"); 

            }

            else if ( source == down )

            {

              RemoteControl.rc = getObjReceived( "bottom"); 

            }

            else if ( source == left )

            {

              RemoteControl.rc = getObjReceived( "left"); 

            }

            else if ( source == right )

            {

              RemoteControl.rc = getObjReceived( "right"); 

            }

            else if ( source == stop )

            {

              RemoteControl.rc = getObjReceived( "home"); 

            }

            else if ( source == leftup )

            {

              RemoteControl.rc = getObjReceived( "leftup"); 

            }

            else if ( source == rightup )

            {

              RemoteControl.rc = getObjReceived( "rightup"); 

            }

            else if ( source == downleft )

            {

              RemoteControl.rc = getObjReceived( "downleft"); 

            }

            else if ( source == downright )

            {

              RemoteControl.rc = getObjReceived( "downright"); 

            }



            RemoteControl.rc += 15;

            

         }

         private int getObjReceived(String direction) 

         {



               URL url = null;

               URLConnection con = null;

               BufferedReader in = null;

               int response = -1; // -1 is error

              

               try 

               {



                 url = new URL(getCodeBase(), 

                  "ControlServlet?direction=" + direction);

                 con = url.openConnection();

                 in = new BufferedReader(

                                      new InputStreamReader(con.getInputStream())); 

                 response = Integer.parseInt(in.readLine()); 

                 in.close();

               }

               catch (Exception e) 

               {

                   System.out.println( " Error :" +e.getMessage() );

               }



               return response;

                           

          }



      }

       // end of action events class.



        // making this applet as a runnable thread.



         public void run()

           {

             while (true)  {

               if (rc == -1)  {

                 time.setText("Processing Error.");

                 rc = 0;

               }

               else if (rc == 0)  {

                 time.setText(rc + " seconds " );

                 try {

                   Thread.sleep(100);

                 } catch (InterruptedException ie) {}  

               }

               else {

                 while ( rc > 0 )

                 {

                   try {

                     Thread.sleep(1000);

                   } catch (InterruptedException ie) {}

                   time.setText( rc+ " seconds " );

                   rc--;

                 }

               }

             }

           

           }



// end of the program

              

}
#18

SERVLET

import java.util.Properties;

import java.util.Vector;

import java.util.StringTokenizer;

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

import java.io.PrintWriter;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.net.*;





public class ControlServlet extends HttpServlet   {







  /** propeties reader file, this file has what each command means

  *   from a hardware standpoint. See what you need to operate your

  *    Hardware and put it in a property file

  */

  Properties properties;



  static final String hardwareProp = "hardware.properties";



  

  public void init() throws ServletException  {



    properties = new Properties();

    try {

      properties.load(new FileInputStream(hardwareProp));

    } catch (Exception e) {

       System.out.println(e.getMessage());

       throw new ServletException(e.getMessage());

    }



  }



  public void reReadProperties()

    throws FileNotFoundException, IOException

  {

    properties.load(new FileInputStream(hardwareProp));

  }



  /**

   * Allow requests to come from either POST or GET methods.

   * This method processes the parameters and sends the appropriate

   * commands to the SerialPort

   */

  public void doGet(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException

  {

    PrintWriter out = response.getWriter();

    response.setContentType("text/plain");



     String temp = request.getParameter("reinit");

    if (temp != null)  {

      try {

        reReadProperties();

      } catch (Exception e) {

     }//catch

    }//if



       Socket hardConn = null;

       OutputStream send = null;

       InputStream receive = null;

       byte[] seconds = new byte[20];



       try {

         // chose a port to communicate with server

           hardConn = new Socket("localhost", 42000);

            send = hardConn.getOutputStream();

            receive = hardConn.getInputStream();

        } catch (UnknownHostException e) {

            out.println(-1);

            return;

        } catch (IOException e) {

            out.println(-1);

            return;

        }//catch

         // Now parse the argument coming from the applet

       temp = request.getParameter("direction");



         if (temp != null)  {

             int counter = 0;	

       String hardwareCommand = properties.getProperty(temp).trim();

      StringTokenizer st = new StringTokenizer(hardwareCommand, ":");

      byte[] buffer = new byte[st.countTokens()];

      while (st.hasMoreTokens())  

  buffer[counter++] = (byte)(Integer.parseInt(st.nextToken()));



             try {

               send.write(buffer);

               int reply = receive.read();

               out.println(reply);

             } catch (Exception e ) { out.println(-1); } 

                  



         }//if



       send.close();

       hardConn.close();

  }



}
#19

SERVER

import java.net.ServerSocket;

import java.net.Socket;

import java.io.InputStream;

import java.io.OutputStream;

import java.io.FileInputStream;

import java.util.Properties;

import java.util.Vector;



public class ControlServer  {



  private String propFile;

  private Properties properties;

  private ServerSocket server;

  private Thread thread;

  private ThreadManager manager;

  



  private ControlServer() {}



  public ControlServer(String propFile) 

    throws Exception  {



    this( propFile, 42000 );



  }



  public ControlServer(String propFile, int port) throws Exception {

    properties = new Properties();

    properties.load(new FileInputStream(propFile));

    server = new ServerSocket(port);

    manager = new ThreadManager(properties.getProperty("COMMPORT"));

    thread = new Thread(manager);

    thread.setDaemon(true);

    thread.start();

  }





  public int getPort()  {

    return server.getLocalPort();

  }



  /**

   * Wait for socket connections and

   * dispatch commands to the thread.

   */

  public void listen()  {



    Socket socket = null;

    byte[] buffer = new byte[20];

    InputStream is = null;

    OutputStream os = null;



    /* listen forever */

    while (true)  {

      

      try  {

        // instead of writing to console you can write 

        // these outputs to a log file to know what was

        // written

        System.out.println("Waiting for socket connection . . .");

        // block until there is a connection

        socket = server.accept();

        System.out.println("Connection received, processing . . .");



        // get streams for I/O

        is = socket.getInputStream();

        os = socket.getOutputStream();



        int bytes = is.read(buffer);



        System.out.println("Buffer contents: ");

        for (int i = 0; i < bytes; i++)  {

          System.out.print(" " + Byte.toString(buffer));

        }

        System.out.println();

        try  {

  /* add the command to be processed by

  * the thread manager

  * what this means is that you can send

  * as many commands as you want becasue it is web

  * and many people might send many commands at once and

  * the server will process the commands

  */

          int seconds = manager.addCommand(buffer);

          os.write(seconds);

        } catch (FullQueueException fqe)  {

          os.write(-1);

          fqe.printStackTrace();

        } 



      } catch (Exception e)  {

        e.printStackTrace();

      } // end try



    } // end while



  } // end listen



  /**

   * Okay, you can run it from the command line.

   * But at leas enter the name of the properties file

   * and optionally the port number (default is 42000)

   */

  public static void main(String[] args)  {



    ControlServer controlServer = null;



    /* must enter at least prop file on command line */

    if (args.length < 1)  {

      System.out.println("Usage: java ControlServer properties_file_name [port]");

      System.exit(0);

    }

    /* only the properties file was entered */

    if (args.length == 1)  {

      

      try  {

        controlServer = new ControlServer(args[0]);

        controlServer.listen();

      } catch (Exception e)  {

         e.printStackTrace();

      }



    }

    /* both prop file and port entered */

    else  {

      try {

        controlServer = new ControlServer(args[0],

                                        Integer.parseInt(args[1]));

        controlServer.listen();

      } catch (Exception e)  {

         e.printStackTrace();

      }

    }

  }



      public class ThreadManager implements Runnable

       {

           /**

           * A list of the commands to be executed.

            */

           protected Vector commands;

           /**

           * Object to write data to the serial port

            */

           protected SerialPortWriter writer;

           /** 

           * count is a reference to the number of

           * seconds we have left until the next command

           * Its an object so we can lock on it instead

           * of this whole thing.

            */

           protected Integer count;



         public ThreadManager(String commport)

           throws Exception

          {

              commands = new Vector();

              count = new Integer(0);

              writer = new SerialPortWriter(commport);

          }



          public synchronized int addCommand(byte[] buffer) 

          throws FullQueueException 

          {

             if (commands.size() >= 10)

               throw new FullQueueException("Too many commands");

               commands.addElement(buffer);

               int reply = 0;

               synchronized (count)  {

               reply = ((commands.size() - 1) + count.intValue());

            }



           return reply; 



          }



           /**

           * This object's run method just executes the next

           * command or sleeps if there are no commands.

           */

          public void run()  {

            while (true)  

     {

                /* if there's a command */

               if (commands.size() > 0) 

        {

                   /* reset count */

     synchronized (count)  {

            count = new Integer(10);

                   }



                   /* first send the buffer */

                   try  {

                       writer.write(getNextCommand());

                    } 

     catch (Exception e) {

                        e.printStackTrace();

                       /* reset count so the next command can just go */

                       synchronized (count) {

                       count = new Integer(0);

                     }

                   } // catch



                     /*

                     * then wait for a while keeping track

       * of the seconds so we can be very accurate

       */

       while (count.intValue() > 0)  {

 	 try {

            Thread.sleep(1000);

                          synchronized (count) {

                          count = new Integer(count.intValue() - 1);

                          }

                        } 

          catch (InterruptedException ie) {}

                      }

                  /* try to garbage collect */

                  System.runFinalization();

                } // end if



              /* otherwise, just sleep for a while */

              else  {

                 try {

                   Thread.sleep(1000);

                 } 

   catch (InterruptedException ie) {}

               } //end else

      

           } // end while

        } //end run



         /**

         * Get the next byte array from the command

  */

         public synchronized byte[] getNextCommand()

         {

            byte[] buffer = (byte[])commands.elementAt(commands.size()-1);

            commands.remove(commands.size()-1);

            return buffer;

         }



        

       }



         /**

         * I think you can guess what this is

         */

         class FullQueueException extends Exception

         {

           public FullQueueException(String message) {

             super( message );

           }



         }

      

}
#20

الكزود هذا يتعامل مع الكود الذي في SerialWriter في الصفحه الاولي.

السرفلت والمخدم لابد ان يكونو في نفس المكينه والا security exception حيملي عليك الصفحه.

اول ما تسوي هو انك تكتب ملف فيه احتاياجات البورت والاشارات التي حترسلها واذا قريت الكود حتعرف ما تحتاجه.

حمل المخدم وسويله كومبايل وشغله وضع السرفلت في Tomcat

ومن ثم حمل البلت في صفحه ويب وابدا بسم الله.

الابلت مسويه عن طريق يسار يمين شمال و جنوب وتقدر تغيرها حسب الحاجه.

اتمني ان اكون عملت ما يساعدك ولا تنساني من صالح دعاك!!!!

اخيك محمد

#22

شكرا كثير لك اخي انا لا اعرف كيف اشكرك و انا كنت مسافر الخمسة الايام الماضية و رشاهدت ردك و لكنني لم استطع الاجابة حتى عدت من السفر سوف اجربها اليوم و انا الحقيقة عاجز عن الشكر لك.....

Theory is when you know something, but it doesn't work. Practice is when something works, but you don't know why. Programmers combine theory and practice: Nothing works and they don't know why

#23

اخي ترجمت كل الملفات و لكن يظهر لي الخطا التالي

ان RemoteControl غير موجود وانا بحثت و ما عرفت ماهو RemoteControl

و و فق الله خطاك

Theory is when you know something, but it doesn't work. Practice is when something works, but you don't know why. Programmers combine theory and practice: Nothing works and they don't know why

#24

و اذا تجاوزت عمل الابليت و بقصد التجربة و شغلت السيرفلت مباشرة يحدث الخطا التالي:

Internal Servlet Error:



javax.servlet.ServletException: hardware.properties (The system cannot find the file specified)

	at ControlServlet.init(ControlServlet.java:34)

	at javax.servlet.GenericServlet.init(GenericServlet.java)

	at org.apache.tomcat.facade.ServletHandler.doInit(ServletHandler.java:447)

	at org.apache.tomcat.facade.ServletHandler.init(ServletHandler.java:263)

	at org.apache.tomcat.facade.ServletHandler.service(ServletHandler.java:472)

	at org.apache.tomcat.core.ContextManager.internalService(ContextManager.java:917)

	at org.apache.tomcat.core.ContextManager.service(ContextManager.java:833)

	at org.apache.tomcat.modules.server.Http10Interceptor.processConnection(Http10Interceptor.java:176)

	at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:494)

	at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:516)

	at java.lang.Thread.run(Thread.java:484)

و اين يجب ان يكون هذا الملف و هل هذا يعني ان انشئه بنفسي

آسف ان اثقلت عليك و لكن اقترب موعد المعرض و سمع عنه كثير من الناس و من الصعب علي ان اذهب و اقول لهم انه لا يعمل و لم انجح في تنفيذ ما قلته سابقا و انت الامل الوحيد الذي ارسله لي الله ليرشدني و يساعدني

Theory is when you know something, but it doesn't work. Practice is when something works, but you don't know why. Programmers combine theory and practice: Nothing works and they don't know why

#25
Alsalam alakum,



  you can change all Remote control to ControlApplet or create an Object of ControlApplet and call it RemoteControl.





Because I don't know the commands of your hardware the best way to know that is to put the hardware commands in a file. 



So you have two options:

1- code your commands in the servlet and server and remove the property file.

2- use the property file and this is how you can



the property file takes a name and value pair in one line like:

example:

name of command =  value of command(depends on hardware)

north  = 23 33 44 54 55



In the servlet look at this:



         // Now parse the argument coming from the applet

       temp = request.getParameter("direction");



Now that came from the applet as a direction HTML form

direction=up

now you check in the proprty file to see what does up transelate to a hardware command using the following:



         if (temp != null)  {

             int counter = 0;	

       String hardwareCommand = properties.getProperty(temp).trim();



So, the temp String came represent the string coming from the applet and hardwareCommand represent its match in the proprty file.



Now you have the command and you can sent it to the ControlServer and the hardware will be operated.



---------------------

The ControlServer also has one which has what comport you will use.

The reason I did that is becasue I did not know what comport or what hardware you are using so you can change that if you wish.

هذا الموضوع مغلق.

مواضيع مشابهة