About Me

My photo
India
Hey there, lovely people! I'm Hemant Menaria, and I'm passionate about programming. Having completed my MCA in 2011, I've delved into the world of coding with fervor. I believe in sharing knowledge, making complex concepts easy to grasp for everyone. JAVA, PHP, and ANDROID hold a special place in my heart, and I spend most of my time immersed in them. Currently, I'm deeply engaged in API/Webservice frameworks and crafting Hybrid mobile applications to enhance flexibility in the digital realm. If you ever find yourself stuck with a programming challenge, feel free to reach out to me at +91-8955499900 or drop me a line at hemantmenaria008@gmail.com. I'm always eager to help fellow enthusiasts navigate the intricacies of coding!

Tuesday, July 22, 2014

Disable right click option on web page

<script type="text/javascript">

//functions starts for the disable selection

function disableSelection(target){
if (typeof target.onselectstart!="undefined") //IE route
    target.onselectstart=function(){return false}
else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
    target.style.MozUserSelect="none"
else //All other route (ie: Opera)
    target.onmousedown=function(){return false}
target.style.cursor = "default"
}

disableSelection(document.body);
</script>

<script type="text/javascript">
function md(e)
{
 try { if (event.button==2||event.button==3) return false; } 
  catch (e) { if (e.which == 3) return false; }
}
document.oncontextmenu = function() { return false; }
document.ondragstart   = function() { return false; }
document.onmousedown   = md;

//functions ends for the disable selection
</script>

Monday, May 12, 2014

File upload in java web through ajax Asynchronous



File upload process involves data to be sent from client side to server, in html terms this means submitting form to server side method that gets the file from request object and saves it to the server. Most of the time, it is desirable to implement file upload in ajax way without refreshing the whole page while updating the user on the progress.
It is a known fact that, it is not possible to do AJAX file uploads to server using $.ajax or XMLHttpRequest since jquery or javascript does not support file uploads for security reasons. We are now left out with two options/workarounds, to use flash or to use hidden iframe. Flash depends on a plugin to be installed on the user's browser which some people ans companies don't allow. So, out of the two options, the best option is to go for hidden iframe solution. This blog post contains an excellent article on how to do this with plain javascript.

To make the job more easier, let us use this jQuery plugin called jQuery.AjaxFileUpload.js which exactly implements the hidden iframe technique behind the scenes along with progress update and cancelling options. The logic is simple, instead of submitting the form to the server which would cause a postback, we submit the contents of the form to an iframe that is created dynamically and let the iframe communicate with the server, once the upload is complete - iframe sends the response back to the form. Steve explains this technique here in a very neat manner, so I don't want to repeat this here again.
To handle file upload in the server side, let us use Apache Commons File Upload library that makes the job very simple and easy.
1. Download all the required scripts and libraries,

2. Create a dynamic web project in Eclipse. Add the jar files to WEB-INF/lib directory and script files to WebContent folder.

2. Create a jsp file in WebContent and copy paste the below code,

01<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
02    pageEncoding="ISO-8859-1"%>
03http://www.w3.org/TR/html4/loose.dtd
">
04<html>
05<head>
06<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
07<title>Asynchronous file Upload in Java Web Application</title>
08<script src="jquery-1.8.2.js"></script>
09<script src="jquery.ajaxfileupload.js"></script>
10<script language="Javascript">
11$(document).ready(function(){
12  $('input[type="file"]').ajaxfileupload({
13       'action': 'UploadFile',           
14   'onComplete': function(response) {        
15         $('#upload').hide();
16         alert("File SAVED!!");
17       },
18       'onStart': function() {
19         $('#upload').show();
20       }
21  });
22});
23</script>
24</head>
25<body>
26<form>
27<div>                                
28 <input type="file" name="datafile" />  
29 
30 <div id="upload" style="display:none;">Uploading..</div>
31</div>
32</form>
33</body>
34</html>

Note that I have referenced jquery files in the head section of the html. The execution of script is very simple, whenever a file is selected using the file browse input, the script gets fired and submits the selected file to the servlet called 'UploadFile'. The action parameter takes the servlet url which handles the file upload logic in the server side. The onStart and onComplete methods are fired while the file starts to upload and after successful completion of file upload. I have used these methods to show file upload progress to the user.

3. Now let us use Apache Commons Fileupload library to handle file upload in the server side. Create a servlet and place the below code in it.

01import java.io.IOException;
02import javax.servlet.ServletException;
03import javax.servlet.annotation.WebServlet;
04import javax.servlet.http.HttpServlet;
05import javax.servlet.http.HttpServletRequest;
06import javax.servlet.http.HttpServletResponse;
07 
08import java.io.File;
09import java.util.Iterator;
10import java.util.List;
11 
12import org.apache.commons.fileupload.FileItem;
13import org.apache.commons.fileupload.FileItemFactory;
14import org.apache.commons.fileupload.FileUploadException;
15import org.apache.commons.fileupload.disk.DiskFileItemFactory;
16import org.apache.commons.fileupload.servlet.ServletFileUpload;
17/**
18 * Servlet implementation class UploadFile
19 */
20@WebServlet("/UploadFile")
21public class UploadFile extends HttpServlet {
22 private static final long serialVersionUID = 1L;
23 
24    /**
25     * Default constructor.
26     */
27    public UploadFile() {
28        // TODO Auto-generated constructor stub
29    }
30 
31 /**
32  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
33  */
34 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
35  // TODO Auto-generated method stub
36 }
37 
38 /**
39  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
40  */
41 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
42    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
43     
44         if (isMultipart) {
45          // Create a factory for disk-based file items
46          FileItemFactory factory = new DiskFileItemFactory();
47 
48          // Create a new file upload handler
49          ServletFileUpload upload = new ServletFileUpload(factory);
50   
51             try {
52              // Parse the request
53     List /* FileItem */ items = upload.parseRequest(request);
54     Iterator iterator = items.iterator();
55                 while (iterator.hasNext()) {
56                     FileItem item = (FileItem) iterator.next();
57                     if (!item.isFormField()) {
58                         String fileName = item.getName(); 
59                         String root = getServletContext().getRealPath("/");
60                         File path = new File(root + "/uploads");
61                         if (!path.exists()) {
62        boolean status = path.mkdirs();
63                         }
64   
65                         File uploadedFile = new File(path + "/" + fileName);
66                         System.out.println(uploadedFile.getAbsolutePath());
67                         item.write(uploadedFile);
68                     }
69                 }
70             } catch (FileUploadException e) {
71                 e.printStackTrace();
72             } catch (Exception e) {
73                 e.printStackTrace();
74             }
75         }
76 }
77 
78}
4. Now the last step is to map the servlet to the action url we have used in index.jsp file as shown below,
01<web-app>
02  <display-name>AjaxFileUpload</display-name>
03  <servlet>
04  <servlet-name>UploadFile</servlet-name>
05  <servlet-class>com.programmingfree.fileupload</servlet-class>
06 </servlet>
07 <servlet-mapping>
08  <servlet-name>UploadFile</servlet-name>
09  <url-pattern>/UploadFile</url-pattern>
10 </servlet-mapping>
11</web-app>

That is all! Now run the application in Tomcat server and upload a file to see how it gets uploaded without refreshing the whole page.



Once the file is uploaded,

Tuesday, January 7, 2014

Connect two computer Using cross cable



1: Make sure both computers are turned off.
2: Plug each end of the crossover cable into a network port on the back of each computer.
3: Turn both computers on (it does not matter which one you turn on first).
4: Sign-in to Windows on both computers, as you normally do.
5: Wait until both computers have fully loaded Windows and all startup programs (your mouse pointer will be the normal arrow shape and the programs that load in the system tray (usually located at the bottom right side of the screen, to the left of the time-clock) will all be there when the system is ready to use for configuration).
6. Select one of the computers to complete the rest of the process.
 7. Open The Network and Sharing Centre. Click "Start," then "Control Panel," then "Network and Internet." Lastly, click "Network and Sharing Centre." 
8. Double click the "Unidentified Network" icon.
If you have more than one network, this icon will be identified as "multiple networks."
9. In Network, click the information bar. Next, click on "Turn on network discovery and file sharing." If you are prompted for a password or confirmation, type it in or provide confirmation.

 Note: Both PC Should be on the same network. (or you can set ip address manually like: 1st PC- 10.68.2.20, 2nd PC- 10.68.2.21. with same Subnet 255.255.255.0

More Watch this Video:


Download a file in jsp


<%@ page import="java.util.*,java.io.*"%>

<%
   
    File f = new File ("filePahtNeedToDownload"); //read  file name.
    /* set  content type ( word,excel,pdf,txt..etc) here we try for a pdf file */
    response.setContentType ("application/pdf");
    //setting  header and the Name by which user will save the file.
    response.setHeader ("Content-Disposition", "attachment; filename=\"DownloadfileName.pdf\"");
   
    //retrive file name
    String name = f.getName().substring(f.getName().lastIndexOf("/") + 1,f.getName().length());
   
   
        InputStream in = new FileInputStream(f);
        ServletOutputStream outs = response.getOutputStream();
       
       
        int bit = 256;
        int i = 0;
        try {
            while ((bit) >= 0) {
                bit = in.read();
                outs.write(bit);
            }
       
        } catch (IOException ioe) {
            ioe.printStackTrace(System.out);
        }
        outs.flush();
        outs.close();
        in.close();   
%>

Remove Shortcut Virus from Pen drive or Memory Card


Open command prompt and type this command.
Note: here "g:" is drive on which you want to perform operation, so at the place of "g" write your drive label.

attrib -h -r -s /s /d g:\*.*

Friday, July 19, 2013

Eclipse “Failed to load JNI shared library”

Problem: When I try opening Eclipse, a pop-up dialog states:
Failed to load the JNI shared library "C:/JDK/bin/client/jvm.dll"`.
Following this, Eclipse force closes.

Solution:

Working pairings of OS, JDK and Eclipse:


  • 32-bit OS - 32-bit JDK - 32-bit Eclipse (32-bit only)
  • 64-bit OS - 32-bit JDK - 32-bit Eclipse
  • 64-bit OS - 64-bit JDK - 64bit Eclipse (64-bit only)

I had several JDKs and JREs installed.
Each of them had their own entry in the PATH variable, all was working more or less.
Judging from the PATH variables, some installations were completely useless, since they were never used. Of course, the "inactive" Javas could be referenced manually from within Eclipse if I needed, but I never did that, so I really did not need them. (At least I thought so at that time...)
I cleaned up the mess, deinstalled all current Java's, installed only JDK + JRE 1.7 64-bit.
One of the Eclipse 'installations' failed afterwards with the Failed to Load the JNI shared Library and a given path relative to the fresh installed JDK where it thought the jvm.dll to be.
The failing Eclipse was the only one of all my IDEs that was still a 32-bit version on my otherwise all-64-bit setup.
Adding VM arguments, like so often mentioned, in the eclipse.ini was no use in my case (because I had only the wrong JDK/JRE to relate to.)
I was also unable to find out how to check if this Eclipse was a 32-bit or 64-bit version (I could not look it up in the Task Manager, since this Eclipse 'installation' would not start up. And since it had been a while since I had set it up, I could not remember its version either.)
In case you use a newer JDK and a older JRE you might be in for trouble, too, but then it is more likely a java.lang.UnsupportedClassVersionError appears, IIRC.

 

 

Wednesday, April 10, 2013


// How to send an email by Java application using Gmail/ Yahoo/ Hotmail


import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


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

            try{
                String host = "smtp.gmail.com";
                String from = "from@gmail.com";
                String pass = " njkgyddddshqd ";  //if you are getting any error related to authentication use application specific password here.
                Properties props = System.getProperties();
                props.put("mail.smtp.starttls.enable", "true"); // added this line
                props.put("mail.smtp.host", host);
                props.put("mail.smtp.user", from);
                props.put("mail.smtp.password", pass);
                props.put("mail.smtp.port", "587");
                props.put("mail.smtp.auth", true);

                String[] to = {"to@gmail.com"}; // added this line

                Session session = Session.getDefaultInstance(props, null);
                MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(from));

                InternetAddress[] toAddress = new InternetAddress[to.length];

                // To get the array of addresses
                for( int i=0; i < to.length; i++ ) { // changed from a while loop
                    toAddress[i] = new InternetAddress(to[i]);
                }
                System.out.println(Message.RecipientType.TO);

                for( int i=0; i < toAddress.length; i++) { // changed from a while loop
                    message.addRecipient(Message.RecipientType.TO, toAddress[i]);
                }
                message.setSubject("sending in a group");
                message.setText("Welcome to JavaMail");
                Transport transport = session.getTransport("smtp");
                transport.connect(host, from, pass);
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();
            }catch (MessagingException mex) {
                mex.printStackTrace();
            }
}
}


/*********************************************/

if you are getting any type of error then read below carefully


My client isn't accepting my username and password

We suggest making some adjustments in your mail client's settings so you aren't always prompted to enter your username and password. Please check the following settings in your mail client:
  • Make sure that you've entered your full email address (e.g. username@gmail.com)
  • Re-enter your password to ensure that it's correct. Keep in mind that passwords are case-sensitive.
  • Make sure your mail client isn't set to check for new mail too often. If your mail client checks for new messages more than once every 10 minutes, your client might repeatedly request your username and password.
Now, please follow the steps below to resolve the problem:
  1. Open your web browser and sign in to Gmail at http://mail.google.com/mail. If you see a word verification request, type the letters in the distorted picture and finish signing in.
  2. Close your browser and try accessing your messages in your email client again.
  3. If you're still having problems, visit http://www.google.com/accounts/DisplayUnlockCaptcha and sign in with your Gmail username and password. If necessary, enter the letters in the distorted picture.
  4. Click Continue.
  5. Restart your mail client and try accessing messages in your email client again.  
Note: use that application specific password at the place of original password of sender password.

read more on : http://support.google.com/mail/answer/14257