Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to search / find files in a directory using DirectoryStream in Java 7.?

Given directory "D:\books\java" having 5 pdf files as shown below :




Program to demonstrate how to search / find files in a directory using DirectoryStream in Java 7.

package com.hubberspot.java7;

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class SearchFilesInDirectory {

 public static void main(String[] args) {

  // 1. Create a path to the directory
  // where search for the files is to be done.
  Path dirPath = Paths.get("D:\\books\\java");

  DirectoryStream < Path > dirStream = null;

  try {
   // 2. Create a DirectoryStream instance using 
   // Files.newDirectoryStream(). The instance
   // is created by passing the Path of the directory
   // to be searched and the type of files as a filter
   // here we are using filter to search all pdf files
   // in the directory
   dirStream = Files.newDirectoryStream(dirPath, "*.pdf");

   // 3. Looping each file and printing the name
   // on the console
   for (Path entry : dirStream) {

    System.out.println(entry.getFileName());

   }
  } catch (IOException e) {

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

  } finally {
   // 4. Closing the DirectoryStream
   try {

    dirStream.close();

   } catch (IOException e) {

    e.printStackTrace();
   }  
  }  
 }
}




Output of the program :



How to use param implicit object in a JSP page ?.

A simple web application demonstrating how to use param implicit object in a jsp.

1. Create a simple jsp page as "param.jsp".

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <form method="post" action="display.jsp">
            <tr>
                <td>Enter Your Name:</td>
                <td><input name="username" type="text"></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="Submit"></td>
            </tr>
        </form>
    </body>
</html>




2. Create a simple jsp page by name "display.jsp"

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        
        <h2>Name entered: ${param.username}</h2>
        
    </body>
</html>



display.jsp page use implicit object called as param to retrieve the form values coming as a post request.

Run param.jsp and enter username and click submit:



On clicking submit the form values passed as username to display.jsp which uses param implicit object to retrieve the value of username as shown below in the fig.



"Online Tweeter Enterprise Application" : Building and Running the Enterprise Application - Part 10

All the source code developed in previous posts is now ready to deploy and run on the Glassfish server.
Lets build the Online Tweeter Enterprise Application, to do so, right-click the Tweeter project and select the option Clean and Build as shown in diagram below:





The clean and build process is shown in the output window of the NetBeans IDE as shown below:













As soon as compilation and build process is done, just right-click tweets.jsp and run the file as shown in fig below:





                         

After running the jsp file, a browser window gets open and tweets.jsp page is displayed on the browser window as shown in the fig below:


                                                                     


Enter the username and tweet you want to publish and click Tweet button. After hitting Tweet button open a different browser window and open the same link and enter different username and tweet as shown below:




The DisplayTweet page gets open showing the two tweets by different users on both the browsers. This time it shows 2 current followers on the same page, that is two different users viewers viewing the page in two different browsers as shown below:





Just click on the link provided in the top right as "Add new tweets" as shown in fig below.




Enter the latest tweet and click Tweet button, the DisplayTweet window gets open showing the lastest tweet as shown below:










That ends our series of developing "Online Tweeter Enterprise Application", will be back with some new and powerful projects soon. Thanks and keep reading the blog.

"Online Tweeter Enterprise Application" : Creating a Servlet named DisplayTweets in NetBeans Web module - Part 9

Lets continue building "Online Tweeter Enterprise Application" in NetBeans. In this section of tutorial, you will create a Servlets in Web module by name "DisplayTweets.java". A Servlet is a server side program which executes at the server producing dynamic content for the web applications.

Step 1: Open "Tweeter-war" project and right click Source Packages and then select New and than Other as shown in fig below:




Step 2: On clicking Other a dialog box appears by name New File. In the Categories: list select Web and in the File Types: select Servlet as shown in fig below.




Step 3: Click

.
New Servlet
dialog box gets open. It prompts us to enter Class Name: , Project: , Location: , Package: and Created File: etc. Enter the values as shown in the fig below.





Step 4: Click

.
yet another New Servlet dialog box gets open. It prompts us to enter values related to Servlet deployment. Do not check "Add information to deployment descriptor (web.xml)". Just enter values as shown in figure below.








and than just click



A new servlet gets created in the source packages by name DisplayTweets.java. It has code which is generated by NetBeans. Just add or remove code given below.




package com.hubberspot.servlets;

import com.hubberspot.ejb.ActiveFollowersOnline;
import com.hubberspot.ejb.Tweet;
import com.hubberspot.ejb.TweetsFinder;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet(name = "DisplayTweets", urlPatterns = {"/DisplayTweets"})
public class DisplayTweets extends HttpServlet {

    @EJB
    private TweetsFinder tweetsFinder;
    
    @EJB
    private ActiveFollowersOnline activeFollowersOnline;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");

        request.getSession(true);

        PrintWriter out = response.getWriter();

        try {
            out.println("");
            out.println("");
            out.println("");
            out.println("Latest Tweets");
            out.println("");
            out.println("");
            out.println("");
            out.println("
");
            out.println("");
            out.println("");
            out.println("
");
            out.println("
"); out.println("Latest Tweets"); out.println(""); out.println("Add new tweets"); out.println(" | "); out.println(activeFollowersOnline.getFollowersOnline() + " follower(s) reading tweets."); out.println("
"); out.println("
"); List tweets = tweetsFinder.findAllTweets(); for (Iterator it = tweets.iterator(); it.hasNext();) { Tweet tweet = (Tweet) it.next(); out.println(""); out.println(" "); out.println(""); out.println(" "); out.println(" "); out.println(""); out.println(" "); out.println("
"); out.println("User: " + tweet.getUsername() + ""); out.println("
"); out.println("Tweeted: " + tweet.getTweet() + ""); out.println("
"); out.println("
"); } out.println(""); out.println(""); } finally { out.close(); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override public String getServletInfo() { return "Short description"; } }

In the next section of this blog (part 10) you will learn how to build and run the application in NetBeans.


How to use Arithmetic Operations in Expression Language ( el ) in a simple jsp page ?.

A simple jsp to demonstrate how to use Arithmetic Operations in Expression Language ( el ).

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body style="background-color: lightblue">
        <h2>Arithmetic Operations with EL !</h2>
        
        <table border="2">
            <thead>
                <tr>
                    <th>Operation</th>
                    <th>EL Expression</th>
                    <th>Result</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Digit</td>
                    <td>\${8}</td>
                    <td>${8}</td>
                </tr>
                <tr>
                    <td>Addition</td>
                    <td>\${4+4}</td>
                    <td>${4+4}</td>
                </tr>
                <tr>
                    <td>Addition</td>
                    <td>\${5.5+4.5}</td>
                    <td>${5.5+4.5}</td>
                </tr>
                <tr>
                    <td>Subtraction</td>
                    <td>\${15-5}</td>
                    <td>${15-5}</td>
                </tr>
                <tr>
                    <td>Division</td>
                    <td>\${20/4}</td>
                    <td>${20/4}</td>
                </tr>
                <tr>
                    <td>Multiplication</td>
                    <td>\${2*4}</td>
                    <td>${2*4}</td>
                </tr>
                <tr>
                    <td>Modulus</td>
                    <td>\${21%4}</td>
                    <td>${21%4}</td>
                </tr>
            </tbody>
        </table>        
    </body>
</html>



Output of the Jsp Page :



"Online Tweeter Enterprise Application" : Creating a Servlet named TweetsSubmit in NetBeans Web module - Part 8

Lets continue building "Online Tweeter Enterprise Application" in NetBeans. In this section of tutorial, you will create a Servlets in Web module by name "TweetsSubmit.java". A Servlet is a server side program which executes at the server producing dynamic content for the web applications.

Step 1: Open "Tweeter-war" project and right click Source Packages and then select New and than Other as shown in fig below:




Step 2: On clicking Other a dialog box appears by name New File. In the Categories: list select Web and in the File Types: select Servlet as shown in fig below.




Step 3: Click

.
New Servlet dialog box gets open. It prompts us to enter Class Name: , Project: , Location: , Package: and Created File: etc. Enter the values as shown in the fig below.





Step 4: Click

.
yet New Servlet dialog box gets open. It prompts us to enter values related to Servlet deployment. Do not check "Add information to deployment descriptor (web.xml)". Just enter values as shown in figure below.





and than just click



A new servlet gets created in the source packages by name TweetsSubmit.java. It has code which is generated by NetBeans. Just add or remove code given below.




package com.hubberspot.servlets;

import com.hubberspot.ejb.Tweet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.jms.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "TweetsSubmit", urlPatterns = {"/TweetsSubmit"})
public class TweetsSubmit extends HttpServlet {

    @Resource(mappedName = "jms/tweetsFactory")
    private ConnectionFactory connectionFactory;
    @Resource(mappedName = "jms/tweets")
    private Queue queue;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        response.setContentType("text/html;charset=UTF-8");
        
        PrintWriter out = response.getWriter();
        
        String username = request.getParameter("txtUsername");
        String tweet = request.getParameter("txtTweet");

        if (username != null && tweet != null) {
            try {

                Connection connection = connectionFactory.createConnection();
                Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                MessageProducer messageProducer = session.createProducer(queue);

                ObjectMessage objectMessage = session.createObjectMessage();
                
                Tweet newTweet = new Tweet();
                newTweet.setUsername(username);
                newTweet.setTweet(tweet);
                
                objectMessage.setObject(newTweet);
                
                messageProducer.send(objectMessage);
             
                connection.close();
                
                response.sendRedirect("DisplayTweets");

            } catch (JMSException ex) {
                Logger.getLogger(TweetsSubmit.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }
}



In the next section of this blog (part 9) you will learn how to create a yet another Servlet in NetBeans by name DisplayTweets, for this application in the Web module.


 
© 2021 Learn Java by Examples Template by Hubberspot