Wednesday, 28 September 2016

Shut down all PCs(Windows 7) in LAN using Java from Linux

Shop on Amazon                                                                 Google Apps for Work


I have made a web application that shutdown all PCs in LAN in one click. I am working in a computer lab and shutting down all PCs daily is very irritating for me. So, I decided to develop an application that search all PCs, which are turned on and shut them all.

My environment is:- (prerequisite)
  1. I use Ubuntu 14.04 LTS on my PCs.
  2. All LAN PCs are using windows 7 Operating System.
  3. Java should be installed on server.
Since this application is client-server based, so some setting and software will be required on both side.

1. On client side:-

To shut down PC from remote location you require some registry edit in Windows 7 system.
Open command prompt as administrator and run following command:-

reg add HKLM\SOFTWARE\MICROSOFT\WINDOWS\CURRENTVERSION\POLICIES\SYSTEM /V LocalAccountTokenFilterPolicy /t REG_DWORD /d 1

OR

Open the registry editor by going to Start and typing in regedit. Now navigate to the following key:
HKEY_LOCAL_MACHINE – SOFTWARE – Microsoft – Windows – CurrentVersion – Policies – System
Right-click on System on the left hand side and choose New – DWORD (32-bit) Value.


Now your client machine is ready to shut down remotely.

2. On server side:-

In my case, I am running Ubuntu 14.04 and I have installed Java version “1.8.0_74” of Oracle.

To shut down windows PC from Linux machine, we required to install a package samba-common. We can install this by typing on terminal

sudo apt-get install samba-common

After installing this package run following command to check that everything is working:-

net rpc shutdown -I ipaddress -U username%password

note:- If server is windows machine, you can find the windows command to shutdown a remote PC.

3. A Java program

If remote shutdown is successful after above set up, we require a Java program to make it automatic.

To shut down a single machine, Java code is given below:-

import java.io.*;

String com="net rpc shutdown -I";
String ip="192.168.25.52";
String cred="-U admin%logitech";
String command=com+" " +ip+" "+cred;
try {
Process process = Runtime.getRuntime().exec(command);
System.out.println("the output stream is "+process.getOutputStream());
BufferedReader reader=new BufferedReader( new InputStreamReader(process.getInputStream()));
String s;
while ((s = reader.readLine()) != null){
System.out.println("The inout stream is " + s);
}
} catch (IOException e) {
e.printStackTrace();
}


If you want to shutdown all LAN PCs, code can be:-

try{
String com="net rpc shutdown -I";
String cred="-U admin%logitech";

byte[] ip = {(byte)192, (byte)168, 25, 1}; // for 192.168.0.x addresses and starting ip address
for (int i = 1; i <=5; i++) //this will shut 1 to 5 pcs in ip range, you can limit the loop as many pcs you want to shut
{

ip[3] = (byte)i;
InetAddress address = InetAddress.getByAddress(ip);
String ipad=address.toString().substring(1);
String command=com+" " +ipad+" "+cred;
System.out.println(command);
Process process = Runtime.getRuntime().exec(command);
System.out.println("the output stream is "+process.getOutputStream());
BufferedReader reader=new BufferedReader( new InputStreamReader(process.getInputStream()));
String s;
while ((s = reader.readLine()) != null){
System.out.println("The inout stream is " + s);
}
}

}
catch(Exception e)
{
}


Either you can implement this code on a java program or in JSP/Servlet to shut LAN PCs.

Monday, 19 September 2016

Getting started with Groovy in NetBeans 8.0.1


To start with Groovy in Netbeans IDE, download Netbeans from here . You should check that you have downloaded Netbeans bundle with groovy.

Then you should first check that everything is working in Netbeans by executing a Java program.

Open Netbeans, Click on File  ---
                                                     |
                                                     New File


after clicking new file, it will open a window, the select Groovy from category section and groovy script from File Type and click Next


After clicking next again it will open a new window, put the desired file name and click Finish.
 It will create a new file in you currently open project (in main project)



Now write the desired groovy code on this file and run file by right clicking on this file

def name='arvind'

println "Hello $name!"


See the result in output screen.


 About groovy:-
Apache Groovy is a powerfuloptionally typed and dynamic language, with static-typing and static compilation capabilities, for the Java platform aimed at improving developer productivity thanks to a concise, familiar and easy to learn syntax. It integrates smoothly with any Java program, and immediately delivers to your application powerful features, including scripting capabilities, Domain-Specific Language authoring, runtime and compile-time meta-programming and functional programming. (from Groovy website)
Read more about Groovy here.

Wednesday, 14 September 2016

Play audio/video on web page in HTML5

HTML5 has come with great support of playing audio or video file in web page. Before HTML5, you require any plug-in support to play any audio or video.

Now such kind of plug-in are obsolete in new version browsers and it was the part of old browser.

In HTML5 you just have to embed <audio> or <video> element on you webpage to play audio or video file on webpage. This <audio> or <video> element is fully supported by any modern browser.

It is simple to embed in you HTML code.

Browser support for these elements are given below. This table shows the minimum number of version of browser from where these element are supported- means browser version if equals or higher than specified- it will support  <audio> or <video> elements.

For video:-

 For audio:-

Now how we use this element in HTML5 code:-

We just have to put this element at required location in our code.

<video width="320" height="240" controls>
  <source src="location of file/file.mp4" type="video/mp4">
  <source src="location of file/file.ogg" type="video/ogg">

Your browser does not support the video tag.
</video>


<audio controls>
  <source src="location of file/file.ogg" type="audio/ogg">
  <source src="location of file/file.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>


If you want play video or audio automatically on startup, put the controls autoplay in tag e.g.

<audio controls autoplay>

<video width="320" height="240" controls autoplay>

It looks on page like:-

Monday, 12 September 2016

Ajax search from MYSQL database example in JSP

Ajax is used to get data dynamically by just pressing key. This example is the demonstration of getting data from database by just typing characters in textfield. In ajax you don't need to press submit button to get data. I assume that you have made MySQL database.

Now create a form that contains textfield.

search.html

To type something to be searched

<form name="vinform"  method="get" >
<input type="search" name="t1" size="80" placeholder="Type to search" onKeyUp="sendInfo()" class="textfieldsearch" style="height:35px;" autofocus>
</form>

To show data on this page add

<span id="arvind"> </span>

Include javascript code given bellow to this file

<script>
var request;
function sendInfo()
{
               var v=document.vinform.t1.value;
               var url="search.jsp?val="+v;

              if(window.XMLHttpRequest){
             request=new XMLHttpRequest();
             }
             else if(window.ActiveXObject){
             request=new ActiveXObject("Microsoft.XMLHTTP");
             }
             try
            {
              request.onreadystatechange=getInfo;
              request.open("GET",url,true);
              request.send();
             }
             catch(e)
            {
               alert("Unable to connect to server");
           }
}

function getInfo(){
          if(request.readyState==4){
          var val=request.responseText;
           document.getElementById('arvind').innerHTML=val;
           }
}
</script>


Now on search.jsp page write

search.jsp

<%@ page import="java.sql.*"%>

<%
String s=request.getParameter("val");
if(s==null || s.trim().equals("")){
out.print("Please Type anything to search");

}else{
out.println("<img src='ajax-loader.gif' alt='Searching'></img>");

String search=s;


try{

Statement stmt=null;
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/itcentre","root","aarvindd");

stmt = con.createStatement();
String sql="select * from table where cl_name like '%"+search+"%' " ;
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
out.println(rs.getString(1));
       out.println(rs.getString(2));

       }
rs.close();
stmt.close();
con.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}


%>

Earn by referring Google App Referring program

Google has announced a referral program for it's Google Apps for work in selected country. You can join this referral program and earn some money from Google.

Steps are:-\

Become a member

  • Just provide your name and email address
  • You’ll receive your unique referral link in your inbox                
  • A bank account is required to receive direct deposits
  • The programme is available in selected countries

Start referring today

  • Share the unique referral link that you’ll receive in your welcome email
  • Use the email and website templates that we’ll provide
  • Offer exclusive discounts to your referrals
  • Get exclusive tips and programme updates

Earn your rewards

  • After your referral subscribes to Google Apps, receive £10 for each user (up to £1,000 per domain)
  • Earn additional coupon codes as you continue to refer

The small print

  • You can sign up an unlimited number of referrals.
  • You’re rewarded for each referral’s first 100 users. A user is an individual account belonging to the referral’s domain.
  • Your referral reward will be based on the number of users who have paid for at least 120 days.
What you have to do, just join this program by entering you name and email address and you will get welcome email from Google.
You can get the Google App for Work from link below

                                            https://goo.gl/J9u6IS

You can also get 20% off using promotion code given below
                             
                                          E9DQF6CXHR47FW6

                                           X4HP4R4JG93HVUJ

Sunday, 11 September 2016

MySQL database connectivity in JSP/Servlet

Database connectivity with Java require some steps to be followed. If you have not done database connectivity in Java previously then it will be difficult to connect to database only using coding.

To do database connectivity in Java with MySQL, we require connector- more specific JDBC driver.

You can download it from here. It a jar file name some like mysql-connector-java-5.1.39.jar.

To install/load this file for use refer to this documentation, or follow instruction given below.

To load this driver, you have to put it at proper location. If you are working on project, you should put it into lib directory of your project (If you are using any IDE like Netbeans or Eclipse, you can find lib directory in your project).

But if you are not working on any project or IDE. Then this file (mysql-connector-java-5.1.39.jar) should be pasted in folder your java location\Java\jdk1.8.0_77\jre\lib\ext directly.

Now we are ready to use MySQL database.

1. Now in JSP/Servlet program we have to import java.sql.* package to use database interfaces to connect with database.

We can import this in JSP using

                             <%@ page import="java.sql.*"%>

and in Servlet
                                   import java.sql.*;

2. Now we require to register the JDBC driver using code
       Class.forName("com.mysql.jdbc.Driver");

3. Open a connection using

Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/database","user","password");

4. Now we ready to execute query

stmt = con.createStatement();
String sql="select username, password, type from users where username='"+username+"' and password='"+password+"'";// where tname like '"+search+"'";
ResultSet rs = stmt.executeQuery(sql);

5. Extract data from result set

while(rs.next()){
                out.println(rs.getString(table column index or name)); //if data is string
                out.println(rs.getInt(table column index or name)); //if data is Integer
}

6. After-all close all connections

                        rs.close();
                        stmt.close();
                        con.close();

Complete servlet Example

// login servlet
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Login extends HttpServlet {
  
  public void doPost(HttpServletRequest req, HttpServletResponse res)
                               throws ServletException, IOException {
    res.setContentType("text/plain");
    PrintWriter out = res.getWriter();
Connection conn = null;
Statement stmt=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database","user","password");
//db.dbConnect();
stmt = conn.createStatement();
String sql="select * from table_name";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next())
{
out.println(rs.getString(1));
        out.println(rs.getString(2));
}
rs.close();
stmt.close();
conn.close();
}
catch(Exception e)
{
out.println(e);
}
     }
}

 If you know JSP you can use same code in JSPs accordingly and vice-versa.

Thursday, 8 September 2016

Session management using user authentication in JSP/Servlet

AMAZON TV & APPLIANCES SALE
Session management is a very crucial technique to check whether authenticated user is using the service or not. Only login process is not enough to manage the authentication. System must be maintained to check every request from the authenticated user. It should be maintained till the user logout.

It means, system should maintain session on every page requested by user. We can see the very strict user authentication in bank websites.

In general, session management should check

  1. Whether user has pressed back button after logout and he/she can view the pages before logout, even he/she has logged out or not?
  2. Whether user can view pages by directly typing the URL in browser's address bar after loged out or not?
  3. Whether user can view pages from browser history or not?
  4. Whether user has pressed browser back button and not pressed back button provided by application, even he/she is logged in (Often in banking applications).

These are some aspects of session management, when we develop any application. This list may be increased.

Now look here, how we manage session using JSP/Servlet.
Create login page.

Login.jsp

<form id="form1" method="post" action="loginvalidate.jsp">
 <table width="835" height="217" border="1" align="center" bordercolor="" bgcolor="#C0EFDE">
        <tr>
          <td width="116" height="40">&nbsp;</td>
          <td colspan="2"><div align="center">
            <h4>Login</h4>
          </div></td>
          <td width="219">&nbsp;</td>
        </tr>
        <tr height="10">
          <td height="56">&nbsp;</td>
          <td width="200"><label>
            <div align="center">Username</div>
          </label></td>
          <td width="272"><label>
            <input name="username" type="text" size="35" style="height:30px;" placeholder="Enter Your Username" required />
          </label></td>
          <td>&nbsp;</td>
        </tr>
<tr height="10">
          <td height="61">&nbsp;</td>
          <td><label>
            <div align="center">Password</div>
          </label></td>
          <td><label>
            <input name="password" type="password" size="35" style="height:30px;" placeholder="Enter Your Password" required />
          </label></td>
          <td>&nbsp;</td>
</tr>
        
        <tr height="10">
          <td height="10">&nbsp;</td>
          <td><label>
            <div align="center">
              <label>              </label>
            </div>
          </label></td>
          <td><label>
            <input type="reset" name="Reset" value="Reset" />
            <input type="submit" name="Submit2" value="Submit" />
          </label></td>
          <td>&nbsp;</td>
        </tr>
        <tr height="10">
          <td height="10">&nbsp;</td>
          <td>&nbsp;</td>
          <td>&nbsp;</td>
          <td>&nbsp;</td>
        </tr>
  </table>
</form>

loginvalidate page check user from database and redirect to proper location.

loginvalidate.jsp

<%
       String username=req.getParameter("username");
String password=req.getParameter("password");
       Connection conn = null;
Statement stmt=null;
String user="";
String pass="";
String type="";
try
  {
Class.forName("com.mysql.jdbc.Driver");
conn =       DriverManager.getConnection("jdbc:mysql://localhost:3306/database","username","password");
//db.dbConnect();
stmt = conn.createStatement();
String sql="select username, password, type from users where username='"+username+"' and password='"+password+"'";
ResultSet rs = stmt.executeQuery(sql);
if(rs.next())
{
user=rs.getString(1);
pass=rs.getString(2);
type=rs.getString(3);
}
if(username.equals(user) && pass.equals(password) )
{
                         HttpSession session = req.getSession(true); 
                         session.setAttribute("user", username); 
                 session.setAttribute("type",type);
                if(type.equals("admin"))
                res.sendRedirect("../IT_JSF/admin/adminpanel.jsp");
                if(type.equals("normal"))
                res.sendRedirect("../IT_JSF/standerd/officehome.jsp");
}
else
{
                res.sendRedirect("../IT_JSF/login-failed.jsp");

}
rs.close();
stmt.close();
conn.close();
}
catch(Exception e)
{
                out.println(e);
}
%>


Now after successful logged in by user, check on every page that use is logged in or not by using code

if(session.getAttribute("user")!=null)
{
       //allow to view the page
       //your full page code
}
else
{
     //redirect to login page
}

Done !!!

Monday, 5 September 2016

Automatic startup of Apache Tomcat server in ubuntu on system startup

Apache tomcat server is used to run JSP/Servlet applications. When we install tomcat in Ubuntu/Linux it does not start automatically on system startup. We have to start it manually after system startup. In windows machine it is very simple to start Tomcat on system startup. We can just configure the tomcat service to automatic and it starts on system startup, But when we use tomcat in Ubuntu/Linux, it becomes sometime complex to start tomcat in system startup.

Some people suggest write to shell script to start tomcat, writing shell script is again complex. I have applied many methods to start tomcat in Ubuntu automatically, but I found this method is very simple to start Tomcat in Ubuntu.

Go to rc.local file in etc in root folder and open it with root privileges. Write the startup.sh path in this file and save.

sleep 10
/home/arvind/apache-tomcat-8.0.32/bin/startup.sh


Sunday, 4 September 2016

Send data with hyperlink via URL in JSP/JAVA

We all know that we send data to another page using form or using session variables. But, some time we have to send data to another page using hyperlink. Suppose, we have fetched data from database and made id as hyperlink and clicking on it we do some operation like edit, delete or some thing else.

Let's see how we can do it in simple JSP page.



Here you can see update and delete is associated with each record in the form of hyperlink.

Code is-

<td><a href='updaterecord.jsp?srno=<%=rs.getInt(1)%>' target='blank'>Update</td>
<td><a href='deleterecord.jsp?srno=<%=rs.getInt(1)%>' target='blank'>Delete</td>

Using hyperlink we send the srno(primary key- fetched by rs.getInt(1)) of corresponding record to updaterecord.jsp and deleterecord.jsp pages with the help of srno variable.

When we click on update and delete hyperlink the rs.getInt(1) data sent to another page using srno variable via URL. See the URL after clicking on link


 Now on updaterecord.jsp page we can receive srno variable  value using

                  int search=Integer.parseInt(request.getParameter("srno"));

After getting srno of that particular record, we can do anything related to this record.

Change image source dynamically on hyperlink

 Changing image source dynamically using JQuery. Here in this example I have created there hyperlink and stored all images in the same folde...