Java Code
Capture Video from ip camera using JMF
Following is the java code – which gets video from D-Link DCS900 (ip-camera) & display in frame. This is pure java class. (NO JMF)
Please give ur DCS900’s ip-address on line no. 27/28
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 | import java.net.; import com.sun.image.codec.jpeg.; import java.io.; import java.awt.; import java.awt.event.; import java.awt.image.; import javax.swing.; import java.applet.; public class AxisCamera extends Applet implements Runnable { public boolean useMJPGStream = true; String appletToLoad; Thread appletThread; //URL for Axis 2420 //public String jpgURL="http://www.easemarry.com/axis-cgi/jpg/image.cgi?resolution=352x240"; //public String mjpgURL="http://www.easemarry.com/axis-cgi/mjpg/video.cgi?resolution=352x240"; //Following 3-lines added //URL for D-Link DCS-900 public String jpgURL = "http://www.easemarry.com/IMAGE.JPG"; public String mjpgURL = "http://www.easemarry.com/video.cgi"; DataInputStream dis; private Image image=null; public Dimension imageSize = null; public boolean connected = false; private boolean initCompleted = false; HttpURLConnection huc=null; Component parent; /* Creates a new instance of AxisCamera */ public AxisCamera (Component parent_) { parent = parent_; } public void connect() { try { URL u = new URL(useMJPGStream?mjpgURL:jpgURL); huc = (HttpURLConnection) u.openConnection(); //System.out.println(huc.getContentType()); InputStream is = huc.getInputStream(); connected = true; BufferedInputStream bis = new BufferedInputStream(is); dis= new DataInputStream(bis); if(!initCompleted) initDisplay(); } catch(IOException e) { //incase no connection exists wait and try again, instead of printing the error try { huc.disconnect(); Thread.sleep(60); } catch(InterruptedException ie) { huc.disconnect();connect(); } connect(); } catch(Exception e){;} } public void initDisplay() { //setup the display if (useMJPGStream) readMJPGStream(); else { readJPG(); disconnect(); } imageSize = new Dimension(image.getWidth(this), image.getHeight(this)); //setPreferredSize(imageSize); //parent.setSize(imageSize); //parent.validate(); initCompleted = true; } public void disconnect() { try { if(connected) { dis.close(); connected = false; } } catch(Exception e){;} } public void init() { System.out.println("Starting Applet"); appletToLoad = getParameter("appletToLoad"); setBackground(Color.white); } public void paint(Graphics g) { //used to set the image on the panel if (image != null) g.drawImage(image, 0, 0, this); } /public void run() { try { connect(); readStream(); Class appletClass = Class.forName(appletToLoad); Applet realApplet = (Applet)appletClass.newInstance(); //realApplet.setStub(this); setLayout( new GridLayout(1,0)); add(realApplet); realApplet.init(); realApplet.start(); } catch (Exception e) { System.out.println( e ); } validate(); } public void start() { appletThread = new Thread(this); appletThread.start(); } public void stop() { appletThread.stop(); appletThread = null; } public void readStream() { //the basic method to continuously read the stream try { if (useMJPGStream) { while(true) { readMJPGStream(); //parent.repaint(); } } else { while(true) { connect(); readJPG(); //parent.repaint(); disconnect(); } } } catch(Exception e){;} } public void readMJPGStream() { //preprocess the mjpg stream to remove the mjpg encapsulation //Following commented on 07/08/2006 //readLine(3,dis); //discard the first 3 lines //Following added on 07/08/2006 readLine(4, dis); //discard the first 4 lines for D-Link DCS-900 readJPG(); readLine(2,dis); //discard the last two lines } public void readJPG() { //read the embedded jpeg image try { JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(dis); image = decoder.decodeAsBufferedImage(); } catch(Exception e) { e.printStackTrace();disconnect(); } } public void readLine(int n, DataInputStream dis) { //used to strip out the header lines for (int i=0; i<n ;i++) { readLine(dis); } } public void readLine(DataInputStream dis) { try { boolean end = false; String lineEnd = "\n"; //assumes that the end of the line is marked with this byte[] lineEndBytes = lineEnd.getBytes(); System.out.println("lineEndBytes....."+lineEndBytes); byte[] byteBuf = new byte[lineEndBytes.length]; System.out.println("byteBuf......."+byteBuf); while(!end) { //dis.read(byteBuf,0,lineEndBytes.length); String t = ""; if(byteBuf != null) { dis.read(byteBuf,0,lineEndBytes.length); t = new String(byteBuf); } //System.out.print(t); //uncomment if you want to see what the lines actually look like if(t.equals(lineEnd)) end=true; } } catch(Exception e) { e.printStackTrace(); } } public void run() { connect(); readStream(); } /*public static void main(String[] args) { JFrame jframe = new JFrame(); jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); AxisCamera axPanel = new AxisCamera(); AxisCamera axPanel = new AxisCamera(jframe); new Thread(axPanel).start(); jframe.getContentPane().add(axPanel); jframe.pack(); jframe.show(); } */ } |
Send Email from your GMAIL account using java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | package com.util.mail; import java.security.Security; import java.util.Date; import java.util.Properties; import javax.mail.Authenticator; 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; import org.apache.log4j.Logger; public static final void sendMail(String to, String title, String content) { try { Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; Properties props = System.getProperties(); props.setProperty("mail.smtp.host", "smtp.gmail.com"); props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.port", "465"); props.setProperty("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.auth", "true"); final String username = "your@gmail.com"; final String password = "your password"; Session session = Session.getDefaultInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); // -- Create a new message -- Message msg = new MimeMessage(session); // -- Set the FROM and TO fields -- msg.setFrom(new InternetAddress(to)); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse( to, false)); msg.setSubject(title); msg.setText(content); msg.setSentDate(new Date()); Transport.send(msg); } catch (MessagingException e) { _log.error(e); } } } |
How to use Java to compile the NT service
1. NT services introduced
The so-called NT service, in fact is a kind of special application procedure so-called NT service, in fact is one may when the system initiation automatically adjoint system long time existence advancement which starts under certain status. Looks like FTP server, HTTP server, the off-line printing and so on to use the NT service the form to provide. This in fact similar Unix root daemon advancement. The NT service induces, NT service following several characteristics:
1st, may be self-starting, does not need to start alternately. This regarding the server is an important characteristic. Certainly, you may decide that serves whether self-starting, even may shield some service.
2nd, the NT service does not have the user interface, basically is similar a DOS procedure, because the NT service must the long time movement, therefore did not think that the ordinary win32 advancement has own contact surface equally. But the NT service may have the contact surface with the user to be interactive, this is a kind of special service advancement. May see the service advancement through the NT service supervisor
3rd, the NT service (Services Control Manager) the connection manages through SCM, the installment, the start, the stop, the removal and so on need the SCM interface function to carry on. Control panel’s service controller uses in SCM connection management system management system’s all services. In fact, but also has some may control the service the procedure or the order, has net.exe, the server supervisor and so on, SCM.exe and so on.
4th, these advancements by certain status movement, by facilitate carry on the server resources the deposit. In the ordinary circumstances uses in the territory the LocalSystem account number movement, this account number to this aircraft’s majority resources (, only if forbids to have the complete deposit jurisdiction specially), like this may guarantee the service routine “formidable”. But, also some services use the special account number movement, you may also establish a service specially the account number.
5th, by the system by the thread way movement, in the ordinary circumstances takes the system resources automatically, this has the difference with the ordinary advancement, if does not select the thread method, generally the advancement often consumes the entire CPU resources. Generally needs to exist at times, cannot the excessively many consumption resources duty service realize appropriately.
2. the Java compilation service’s preparation
1st, as localized realization, realizes NT the service Java procedure is certainly not 100% pure Java, depends on the standard class storehouse is only unable to realize our compilation NT service goal, (what therefore MS provided set of SDK for Java this article to use was Microsoft SDK for Java 4.0), mentioned how expansion class storehouse which and corresponding tool provided using MS, realized conforms to the procedure which the Windows platform needed. And included has realized the kind of storehouse API frame which as well as Java the NT service needed the translation class document assembles the standard the NT service routine tool. The SDK downloading way may search from www.microsoft.com/java/.
2nd, after installing SDK, may see in installs under the table of contents to have the jntsvc table of contents, this table of contents has contained the service.zip document, it in fact is a NT services kind of storehouse frame, sealed some NT service to realize the detail, caused us to be possible to defer to the detail which the frame realized us to care comfortably. Launches service.zip to develops machine’s system installation Service storehouse to Java expansion storehouse \ Winnt \ java \ TrustLib, if carries on the development under other operating system, according to the senate the system directorycarries on installs the document.
3rd, under this table of contents also some jntsvc.exe document, is also the Java NT Service meaning. The translation class document which after she may help you to realize will defer to SDK to provide the frame which realizes to assemble a standard NT service to be possible the execution document. JntSvc helped us already to translate in the good .class document foundation established all NT service routine to the characteristic, was the very important tool, how obtained the NT service to be decided by to use her effectively. For we can facilitate from any other table of contents control bench window transfer her, we the table of contents full path which is at JntSvc.exe joins the path environment variable. This may carry on the environment variable through the establishment system attribute high-quality attribute page in the middle of the hypothesis.
4th, defers to the request, we write each code, then the translation compiles the Java procedure, obtains the class document. We will certainly not start her in Vj Studio, because it did not have to be possible at present the execution document entrance, the system will be unable to start her. In order to obtain the NT service routine, we need to carry out an order in the class document in the table of contents control bench window: X:>jntsvc *.class /OUT: ECHOSvc.exe /SVCMAIN: EchoSvc “/SERVICENAME:ECHOSvc”. The concrete Jntsvc parameter we may look at jntsvc -? Obtains, here meaning is probably: Assembles NT current directory’s under all class document the service advancement exe document, document named EchoSvc.exe, the service start entrance in echosvc.class,in the registry the corresponding service name is EchoSvc which the /Servicename parameter assigns. If has many NT services to need to assemble in a Exe document, but may also after /Out parameter assigns each service demonstration name. the /SVCMAIN parameter assigns the service the entrance, which kind of example beginning the so-called entrance is refers to the service to start is starts from.”/SERVICENAME: “the parameter will assign this service to appear by any name. These parameters are the jntsvc.exe practical tool needs to assemble the service station to the information, will translate after these information the .class document obtains one according to the win32 form request to be possible the execution document. What needs to pay attention, this exe document’s movement must have the JVM existence, she in fact is through explained that .class realizes the service to provide. If needs other expansion package, may through assign a other expansion package of position in the /Classpath parameter. Therefore in installs on the NT service machine which the Java compilation obtains to have JVM. If has IE5.x that not to need to worry about this question, the IE core module had already included JVM; But if is the IE6 edition, then needs to arrive at MS in the website to download JVM. If you spoke SDK for Java to install on the server are more convenient.
5th, if does not have what mistake, you will obtain one to be possible execution document echosvc.exe. Looks like the majority services to be possible the execution document to be the same, it may install in the system: echosvc.exe – install, this process will increase some projects toward the system registry, specially about the service project, SCM might also list this to serve. We may use DOS under the control bench the NT service control to order Net start/stop to test serve whether to look like the ordinary service to be possible really to defer to the standard way equally to control, certainly will serve in the middle of the supervisor to open stops this service not to have the question.
3. when the Echo service’s type example the system writes down the service advancement, the entrance is in the EchoSvc structure function, we may see this structure function has with the general procedure entrance main() :
import com.ms.service.* ;
public class EchoSvc extends Service
{ static Thread mainSvc=null ;
public EchoSvc (String[] args)
{
CheckPoint(1000);
setRunning(ACCEPT_SHUTDOWN | ACCEPT_PAUSE_CONTINUE |ACCEPT_STOP);
mainSvc = new Thread((Runnable) new MainSvcThread());
mainSvc.start();
System.out.println( “The Echo Service Was Started Successfully!”);
}
}
CheckPoint is the Service synchronized method, the indicating system is changing the service the condition, needs to let the system wait 1 second. What here we start is a thread, in fact is equal to an advancement, she is serves the advancement the main thread. We respond the control which in this thread SCM serves regarding this. The approximate expression is:
public class MainSvcThread implements Runnable
{
public static boolean STOP = false;
public static boolean PAUSE = false;
public void run()
{
while (!STOP)
{
while (!PAUSE && !STOP)
{
…
}
try
{Thread.sleep(5000);}
catch (InterruptedException e)
{ }
}
try
{Thread.sleep(1000);}
catch (InterruptedException ie)
{}
}
}
}
Middle the service logical control, we will realize the Echo service specifically. Our Echo service monitors 2002 ports, receive client side any line of inputs, then adds on “Echo: ” latter returns. If the client side inputs a quit phrase that to serve thought that this is the customer closes this sleeve joint character the order, the automatic shut-off current sleeve joint character connection, will stop to the current connection service. Concrete realizes (the EchoThread.java code):
public void run(){
String line;
DataInputStream in;
PrintWriter out;
boolean exitflag=false;
try{
in=new DataInputStream(so.getInputStream()) ;
out=new PrintWriter(new DataOutputStream(so.getOutputStream())) ;
out.println(”You have connected to EchoSvc!”);
out.flush();
while((line=in.readLine())!=null)
{
line=line.trim();
if (line.equalsIgnoreCase(”quit”) )
{
out.println(”ECHO:” + line );
out.flush();
return;
}
else
{
out.println(”ECHO:” + line );
out.flush();
}
}
in.close();
out.close();
}
catch(IOException ioe)
{}
}
The Echo service is mainly returns the customer transmission character obviously gives the customer, and adds on Echo: The prefix, indicated that is content which returns from the server. If the customer input “quit” that expressed that this is requests the server to stop the service the performance. How to debug the NT service advancement project. If provides the client side directly this function call the ECHO sleeve joint character service, in logic does not have what mistake, but is unable to support many users also to visit. For can provide the multi-services, at the same time the permission are also many a user to connect this server (this kind of situation in many network services not to be possible few), we may this logic, in founds by MainSvcTread in the thread realizes, moreover may allow many users simultaneously to visit this service. The concrete expression realizes in the MainSvcTread run function:
while(ListenThreadCount
{
server=li.accept();
EchoThread p=new EchoThread(server,this);
Thread t=new Thread(g,(Runnable)p) ;
t.start();
ListenThreadCount++;
}
Above the reference mentioned tool Jntsvc.exe may help you to say translates the good .class document to assemble the exe document, moves this article and adds on – the install parameter to be possible to help you to speak a good service automatically to increase to the registry, might be similar to through the service supervisor or the suitable utility program other services carries on equally controls. The removal service uses – the uninstall parameter.
This routine uses the sleeve joint character, the multithreading to realize the technology to explain that realizes Java to compile the NT service, according to this in fact is similar such many network aspect the service to be possible to realize according to the standard, for example POP3 service, FTP service, even WWW service and so on. We also contact have looked like Java and so on Tomcat, Jrun often to use the NT service form using the server in the NT platform start, then you may also attempt through this example compiles own Java service application.
Finally, if needs to debug the NT service logic, may use the means which is accommodating. We increase a Main static state method in EchoSvc.java, then has a EchoSvc example, like this is the Exe document which standard VJ produces, we may remove the hideaway using the Vj debugging function the mistake. Once after the accent passes, our annotation falls the main static state method, after the translation, may obtain one to debug the good NT service.
4. why can use Java to compile the NT service
to compare VC and so on “original installation” the NT service development way saying that the Java development pattern may be quicker, because possesses the service frame through to expand the Services kind nearly to be possible to achieve, saves many complex detail processing. The Java language has provided the rich kind of storehouse, may for own use, be possible to raise the efficiency, moreover compiles the program structure clear understand easily, to facilitate the later maintenance.
Java provides the exception handling pattern, may let us write the structure to be good, safer code. Considers if compiles because the service advancement uses the VC compilation actually to forget to some memory release, then serves starts the latter period of time, because memory divulging causes the service performance to drop, even the system collapses; But Java language characteristic may cause us not to need the time to guard against the memory management, may even more pay attention to the service logic itself, is realizes is more effective.
Uses VC, if compilation multithreading service advancement, although may realize, but will be quite troublesome. But serves the advancement multithreading is each performance good service necessary characteristic nearly, the Java language itself may provide this aspect good support, simultaneously Java oneself to the network natural good support, makes each kind of network sleeve joint character programming to be easy.
Finally, if does not use other expansion storehouse, we realize very easily this service logic on other operating system. Compiles the good NT service routine, may, in removes a kind of quotation which expands after the Ms related localization realizes, facilitates transplants to platforms and so on other for example Linux, as far as possible to Java “a compilation, everywhere may move”ideal boundary stem for stem.
5, sound code
/* attaches ZIP document newspaper including demonstration’s complete project document, but also after having the translation NT service to be possible the execution document, you may test this to serve the exe document directly the installment, the service to open stop */
/*EchoSvc.java*/
import com.ms.service.* ;
public class EchoSvc extends Service
{
static Thread mainSvc=null ;
public EchoSvc (String[] args) {
CheckPoint(1000);
setRunning(ACCEPT_SHUTDOWN | ACCEPT_PAUSE_CONTINUE |ACCEPT_STOP);
mainSvc = new Thread((Runnable) new MainSvcThread());
mainSvc.start();
System.out.println( “The Echo Service Was Started Successfully!”);
}
}
/*————– EchoSvc.java——————-*/
/*MainSvcThread.java*/
import java.io.*;
import java.net.*;
public class MainSvcThread implements Runnable {
public static boolean STOP = false;
public static boolean PAUSE = false;
public int ListenThreadCount=0;
int maxSocket=10;
int SvcPort=2002;
public void run()
{
try
{
while (!STOP)
{
while (!PAUSE && !STOP)
{
{
Socket server;
ServerSocket li=new ServerSocket(SvcPort);
ThreadGroup g=new ThreadGroup(”EchoThreads”);
System.out.println(”Echo service starting…”);
while(ListenThreadCount
server=li.accept();
EchoThread p=new EchoThread(server,this);
Thread t=new Thread(g,(Runnable)p) ;
t.start();
ListenThreadCount++;
}
}
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{ }
}
try
{
Thread.sleep(1000);
}
catch (InterruptedException ie)
{ }
}
}
catch (IOException ioe)
{}
}
}
/*————– MainSvcThread.java——————-*/
/*EchoThread.java*/
import java.io.*;
import java.net.*;
public class EchoThread implements Runnable
{
Socket so=null;
MainSvcThread p;
public void run()
{
String line;
DataInputStream in;
PrintWriter out;
boolean exitflag=false;
try
{
in=new DataInputStream(so.getInputStream()) ;
out=new PrintWriter(new DataOutputStream(so.getOutputStream())) ;
out.println(”You have connected to EchoSvc!”);
out.flush();
while((line=in.readLine())!=null && ! exitflag)
{
line=line.trim();
if (line.equalsIgnoreCase(”quit”) )
{
in.close();
out.flush();
out.close();
p.ListenThreadCount –;
return;
}
else
{
out.println(”ECHO:” + line );
out.flush();
}
}
in.close();
out.close();
p.ListenThreadCount –;
}
catch(IOException ioe)
{}
}
EchoThread(Socket s,MainSvcThread parent)
{
so=s;
p= parent;
}

