Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Wednesday, March 13, 2013

comment_icon 2 File Download Script For JSP

In this Tutorial  i'm going to explain how you can serve files to your users using JSP. Since we are not serving a HTML page so first we need to tell the browser that what kind of data we are going to serve for that we set Response Headers
 response.setContentType("application/msword");
 response.addHeader( "Content-Disposition","attachment; filename=your file name" );
Here application/msword is the mime type you can search internet for diff. mime type required for  diff. extensions few commonly used are
  • image/jpeg
  • text/plain
  • application/pdf

link format for filedownload

<a href="download.jsp?filename=myresume.doc">Download my resume</a>

Download.jsp


<%@ page  import="java.io.FileInputStream" %>
<%@ page  import="java.io.BufferedInputStream"  %>
<%@ page  import="java.io.File"  %>
<%@ page import="java.io.IOException" %>


<%

   // you  can get your base and parent from the database
   String base="file";
   
   String filename=request.getParameter("filename");
// you can  write http://localhost
   String filepath="http://localhost:8080/filedownload/"+base+"/";

BufferedInputStream buf=null;
   ServletOutputStream myOut=null;

try{

myOut = response.getOutputStream( );
     File myfile = new File(filepath+filename);
     
     //set response headers
     response.setContentType("application/msword");
     
     response.addHeader(
        "Content-Disposition","attachment; filename="+filename );

     response.setContentLength( (int) myfile.length( ) );
     
     FileInputStream input = new FileInputStream(myfile);
     buf = new BufferedInputStream(input);
     int readBytes = 0;

     //read from the file; write to the ServletOutputStream
     while((readBytes = buf.read( )) != -1)
       myOut.write(readBytes);

} catch (IOException ioe){
     
        throw new ServletException(ioe.getMessage( ));
         
     } finally {
         
     //close the input/output streams
         if (myOut != null)
             myOut.close( );
          if (buf != null)
          buf.close( );
         
     }

   
   
%>

Project Structure


Download zip

Friday, August 17, 2012

comment_icon 1 Create Facebook Application with JSP

Today i was just seeing the  traffic sources of my blog and i found few search queries .which made me to write this post.
 make a facebook application with jsp 
 facebook canvas app jsp tutorial
For those who are looking for the same kind of tutorial there is a good news and a bad news for them.
Bad news is that Facebook  doesn't have any SDK for Java but good news is that Facebook have an SDK for JavaScript so if you are going to build the Facebook application in jsp you can try the JavaScript SDK

There is also an Api on Google Project , i haven't tried it but you can try that  http://code.google.com/p/javarunaround/
i hope you will find this api useful 

There are few more api available on the internet . don't forget to visit the link's given below you surely gonna find them useful.

facebook-api-and-facebook-connect-using-java

http://www.socialjava.com/

Friday, April 6, 2012

comment_icon 0 working with Java Beans

In this tutorial i am going to talk about the java beans.
i am going to cover the following  things


  1. what is  Java Bean ?
  2. how we use java beans in JSP
  3. scope of java Beans
what is  Java Bean ?
   If i say in general wordings java beans is the component that can be reused again and again .it just follow write once and use whenever required.

for more details and basics follow the link java Beans

how we use java beans in JSP

JSP provides a usebean tag for using beans in java

 Syntax :
   <jsp:useBean 
id="beanInstanceName" 
  scope="page|request|session|application"
 { class="package.class" | 
  type="package.class" | 
  class="package.class" type="package.class" |
  beanName="{ package.class | <%= expression %> }" type="package.class"  
 }
/>
Example:

Examples

<jsp:useBean id="db" scope="session" class="database.DataConnect" />
How it works (from  http://java.sun.com ) ? 
The <jsp:useBean> tag attempts to locates a Bean, or if the Bean does not exist, instantiates it from a class or serialized template. To locate or instantiate the Bean, <jsp:useBean> takes the following steps, in this order:
  1. Attempts to locate a Bean with the scope and name you specify.
  2. Defines an object reference variable with the name you specify.
  3. If it finds the Bean, stores a reference to it in the variable. If you specified type, gives the Bean that type.
  4. If it does not find the Bean, instantiates it from the class you specify, storing a reference to it in the new variable. If the class name represents a serialized template, the Bean is instantiated byjava.beans.Beans.instantiate.
  5. If it has instantiated (rather than located) the Bean, and if it has body tags (between <jsp:useBean> and </jsp:useBean>), executes the body tags.
Attributes and their Usage 
  • id="beanInstanceName"Names a variable that identifies the Bean in the scope you specify. You can use the variable name in expressions or scriptlets in the same JSP file. The name is case sensitive and must conform to the naming conventions of the page scripting language.
  • scope="page|request|session|application"Defines a scope in which the Bean exists and the variable named in id is available. The default value is page. latter we see explanation about other scopes
  • class="package.class"Instantiates a Bean from a class, using the new keyword and the class constructor. The class must not be abstract and must have a public, no-argument constructor. The package and class name are case sensitive.
  • class="package.class" type="package.class"Instantiates a Bean from a class, using the new keyword and the class constructor, and gives the Bean the type you specify in type. The class you specify in class must not be abstract and must have a public, no-argument constructor. The package and class names you use with both class and type are case sensitive. The value of type can be the same as class, a superclass of class, or an interface implemented by class.
  • type="package.class"If the Bean already exists in the specified scope, gives the Bean the type you specify. If you use type without class or beanName, no Bean is instantiated. The package and class name are case sensitive
 Bean Scopes page Scope:in this scope bean is available for that particular page, as soon as page finishes the the processing the bean will disappear. request scope :if a bean is set to request scope it will be available until that request get processed , if the request results in the page redirection the bean will be also available on the redirected page. session Scope: when a bean is requested as session scope the bean instance will be available for the whole session Application scope: here the bean will be available for the entire application it will exist until application is running on server

Working demo of java Bean : using Bean For db2 connectivity

Download files used in demo  Demo.zip





Sunday, February 26, 2012

comment_icon 5 Sending E-Mail via G-mail using Java


package mymail;



import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Mymail   {
 
 
 public Mymail(){
  super();
 }


/*REMOVE THIS TO TEST AS JAVA APPLICATION 

public static void main(String args[]) throws AddressException, MessagingException{
  Mymail m =new Mymail();
  m.GmailSend("coolasr@gmail.com", "hello", "hello");
 }*/


public boolean GmailSend  (String to,String subject,String messageText) throws AddressException, MessagingException{
  
String host="smtp.gmail.com", user="YOUE USERNAME", pass="YOUR PASSWORD";

      
String SSL_FACTORY ="javax.net.ssl.SSLSocketFactory";       
boolean sessionDebug = true;
Properties props = System.getProperties();
props.put("mail.host", host);
props.put("mail.transport.protocol.", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.fallback", "false");
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
Session mailSession = Session.getDefaultInstance(props,null);
mailSession.setDebug(sessionDebug);
Message msg =new MimeMessage(mailSession);
//msg.setFrom(new InternetAddress(from));
 try
  {
   InternetAddress[] address = {new InternetAddress(to)};
 msg.setRecipients(Message.RecipientType.TO, address);
 msg.setSubject(subject);
 msg.setContent(messageText,"text/plain"); // use setText if you want to send text
 Transport transport = mailSession.getTransport("smtp");
 transport.connect(host, user, pass);
 transport.sendMessage(msg, msg.getAllRecipients());//WasEmailSent = true; // assume it was sent
 return true; 
      
 }
 catch(Exception err) {
      
 //WasEmailSent = false; // assume it's a fail
 return false; 
 //System.out.println("Error"+err.getMessage());
 }
         //transport.close();

 }
}














Sunday, February 5, 2012

comment_icon 0 Uploading a File in JSP

This Tutorial tell that how to upload a File using JSP .
This tutorial is based on the tutorial i found on tutorialspoint .
I updated the code according to RAD so you can easily work on it .
few things to take care about it are
1. copy the class packages from src folder or you can find in links given bellow

Following example depends on FileUpload, so make sure you have the latest version of commons-fileupload.x.x.jar file in your classpath. You can download it from http://commons.apache.org/fileupload/.

FileUpload depends on Commons IO, so make sure you have the latest version of commons-io-x.x.jar file in your classpath. You can download it from http://commons.apache.org/io/.

2.Make sure you have created directories temp and upload in webcontet folder of your project in
advance.
3. change the filepath to to project workspace use \\ in place of \

4. Download Complete Source


INDEX.JSP

File Upload:

Select a file to upload:




UPLOAD.JSP

<%@ page import="java.io.*,java.util.*, javax.servlet.*" %>
<%@ page import="javax.servlet.http.*" %>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.disk.*" %>
<%@ page import="org.apache.commons.fileupload.servlet.*" %>
<%@ page import="org.apache.commons.io.output.*" %>


<%
   File file,file1 ;
   int maxFileSize = 5000 * 1024;
   int maxMemSize = 5000 * 1024;
   ServletContext context = pageContext.getServletContext();
  String dir = request.getServletPath();
    int slashIndex = dir.lastIndexOf('/');
    dir = slashIndex != -1 ? dir.substring(0, slashIndex+1) : "";
     String temppath=  application.getRealPath(dir + "\\temp\\"); //temp directory  crete two directory in web content folder
   dir = application.getRealPath(dir + "\\upload\\"); /* upload directoy if it is not saved then file will not get updated until you restart your RAD/eclipse
   */
   //dir=application.getContextPath();
   //String filePath = dir;
  /*original file path on system Dir path will store image till ur application is running on server */
   String filePath = "C:\\Documents and Settings\\Abhi\\IBM\\rationalsdp\\workspace\\uploadtest\\WebContent\\upload\\";
   // Verify the content type
   String contentType = request.getContentType();
   if ((contentType.indexOf("multipart/form-data") >= 0)) {

      DiskFileItemFactory factory = new DiskFileItemFactory();
      // maximum size that will be stored in memory
      factory.setSizeThreshold(maxMemSize);
      // Location to save data that is larger than maxMemSize.
      factory.setRepository(new File(temppath));

      // Create a new file upload handler
      ServletFileUpload upload = new ServletFileUpload(factory);
      // maximum file size to be uploaded.
      upload.setSizeMax( maxFileSize );
      try{ 
         // Parse the request to get file items.
         List fileItems = upload.parseRequest(request);

         // Process the uploaded file items
         Iterator i = fileItems.iterator();

         out.println("");
         out.println("");
         out.println("JSP File upload");  
         out.println("");
         out.println("");
         while ( i.hasNext () ) 
         { dir=dir+"\\";
         
            FileItem fi = (FileItem)i.next();
            if ( !fi.isFormField () ) 
            {
            // Get the uploaded file parameters
            String fieldName = fi.getFieldName();
            String fileName = fi.getName();
            boolean isInMemory = fi.isInMemory();
            long sizeInBytes = fi.getSize();
            // Write the file
            if( fileName.lastIndexOf("\\") >= 0 ){
            file = new File( filePath + 
            fileName.substring( fileName.lastIndexOf("\\"))) ;
           file1=new File( dir +
            fileName.substring( fileName.lastIndexOf("\\"))) ;
            }else{
            file = new File( filePath + 
            fileName.substring(fileName.lastIndexOf("\\")+1)) ;
            file1 = new File( dir + 
            fileName.substring(fileName.lastIndexOf("\\")+1)) ;
            }
            fi.write( file ) ;
            fi.write(file1);
            out.println("Uploaded Filename: " + dir + " "+
            fileName + "
");
            }
         }
         out.println("");
         out.println("");
      }catch(Exception ex) {
         System.out.println(ex);
      }
   }else{
      out.println("");
      out.println("");
      out.println("Servlet upload");  
      out.println("");
      out.println("");
      out.println("No file uploaded
"); out.println(""); out.println(""); } %>












Friday, December 9, 2011

comment_icon 2 Download RSA ( Rational Software Architect ) - A tool for software Modeling

Download via IBM site

Download Via Torrent

Torrent Includes :

Files:13
Size: 5.35 GB (5741557433 Bytes)

IBM® Rational® Software Architect is an integrated analysis, design, and development toolset that supports the comprehension, design, management, and evolution of enterprise solutions and services. It includes design, analysis, and development capabilities for software architects and model-driven developers creating service-oriented architecture (SOA), J2EE, and portal applications.

This product offering includes:
1)Quick Start CD
2)Rational Software Architect
3)Rational Agent Controller
4)WebSphere® Portal test environments
5)Rational ClearCase® LT
6)Crystal Reports Server

7)Activation Kit for Rational Software Architect
8)Rational License Server
9)IBM Installation Manager
10(IBM Packaging Utility
11)WebSphere Application Server for Developers
12)CICS® Transaction Gateway

For more info
http://www-1.ibm.com/support/docview.wss?uid=swg24013690

comment_icon 173 Sending sms via way2sms using Java


This Page has been no more upadted please visit thie link for updated information How to send sms in java : onl9class.com

API NOT WORKING ANYMORE - INDYAROCKS MESSAGE NOT GETTING DELIVERED

i have a paid API
If you are willing to pay small amount such as 50-100RS for 100-300sms
contact me at abhirathore2006@gmail.com

The sole purpose of the Api is to be used in development by students.so i am not releasing the actual sour

UPDATED CODE
This Tutorial showz that how you can use the http://www.indyarocks.com/ for sending message using your java application
Steps to Follow

  1. create a account on http://www.indyarocks.com/ 
  2. after getting indiarocks username and password use the code given below.
  3. modify the following details
    1. put your email id in Email string
    2. put your indiarocks username
    3. put your indiarocks password
    4. put number as the number on which you want to send sms
    5. put your messgae in messgae string , i limited the length to 110 char for stopping the misuse
  4. if you copy the code in your application's jsp page don't forget to import java.net.*,java.io.*,java.net.URLEncoder

Sunday, December 4, 2011

comment_icon 0 Ajax From Scratch - a WORKING demo for Jquery-Ajax in jsp

This tutorial covers a working example of ajax in jsp
note: example is just same as i used in my previous tutorial so to setup thing use that tutorial :creating-simple-db2-database-Application




Saturday, December 3, 2011

comment_icon 0 Learning Resources for DB2 pure XML with samples


XForms and DB2 pureXML
Handle pureXML data in Java applications with pureQuery



pureXML Samples

The pureXML feature enables well-formed XML documents to be stored in their hierarchical format within columns of a table. XML columns are defined with the new XML data type. Because the pureXML feature is fully integrated into the DB2 database system, the stored XML data can be accessed and managed by leveraging DB2 functionality. This functionality includes administration support, application development support and efficient search and retrieval of XML via support for XQuery, SQL or a combination of SQL/XML functions.
There are various samples provided to demonstrate the XML support; these are broadly categorized as:
Administration samples
These samples demonstrate the following features:
  • XML schema support : Schema registration and validation of XML documents
  • XML data indexing support : Indexes on different node types of XML value
  • Utility support for XML : Import , export, runstats, db2look, and db2batch support for the XML data type
Application Development samples
These samples demonstrate the following features:
  • XML insert, update, and delete : Inserting XML values in XML typed columns, updating and deleting existing values
  • XML parsing, validation, and serialization support : Implicit and explicit parsing of compatible data types, validating an XML document, serializing XML data
  • Hybrid use of SQL and XQuery : Using SQL/XML functions like XMLTABLE, XMLQUERY and the XMLEXISTS predicate
  • XML data type support in SQL and external procedures: Passing XML data to SQL and external procedures by including parameters of data type XML
  • Annotated XML schema decomposition support : Decomposing an XML document based on annotated XML schemas
  • XML publishing functions : Using functions to construct XML values
XQuery samples
These samples demonstrate the use of axes, FLWOR expressions, and queries written with XQuery and SQL/XML.
These samples can be found in the following location:
  • On Windows: %DB2PATH%\sqllib\samples\xml (where %DB2PATH% is a variable that determines where DB2® database server is installed)
  • On UNIX: $HOME/sqllib/samples/xml (where $HOME is the home directory of the instance owner)