Servlet is a Java-based technologies for creating programs such as bulletin boards. Just as the java.sql package is called JDBC, the javax.servlet and javax.servlet.http packages are called Servlet. Servlet is designed to be independent of the network protocol, but it is mostly used to create dynamic content in the HTTP protocol environment. JSPs can easily make the application element corresponding to the screen than Servlet. When you learn Servlet, it is a good start to first learn the basic structure of Servlet.
The basic structure of Servlet consists of:
As shown in the figure1 below, GenericServlet implements the javax.servlet.ServletConfig interface for programmers' convenience.
The javax.servlet.Servlet interface is the heart of the servlet architecture. All servlets must implement this Servlet interface. Servlet lifecycle methods are declared in the body of the servlet interface.
The servlet container calls the init() method once after the servlet object is created. The servlet can be serviced only when the init() method completes without errors. The request before the init() method completes is blocked. When the init() method is called, it receives the object of the ServletConfig interface type as argument, If you set the Servlet initialization parameters in web.xml, this ServletConfig will have the Servlet initialization parameters information set in web.xml. If there are the Servlet initialization parameters, then the init() method should have code to do the initialization of the servlet.
void init(ServletConfig config) throws ServletException;
Each time a client sends a request to a servlet, the servlet container calls the service() method of the servlet. The service() method reads the request information using an object of the ServletRequest type, which is the first argument, and responds to the client using an object of the ServletResponse type, which is the second argument. Note that the servlet container executes the service() method on the new thread whenever the client requests it. The service() method runs simultaneously on a separate thread, so it can respond to a large number of client requests without delay. However, critical section problems can arise with the resources that the servlet uses (eg, files, network connections, static variables, instance variables, etc.). Therefore, it is best not to create static or instance variables that can cause problems with your servlets. Synchronizing the resources used by the servlet is not good code in most cases.
void service(ServletRequest req, ServletResponse res) throws ServletException, IOException;
It is called by the servlet container when the servlet should no longer be serviced. This method is not what the programmer calls in code. To call destroy(), you must use the "Tomcat manager" to unload the application or shut down Tomcat. Tomcat manager is a web application that can be accessed at http://localhost:8080/manager. It is the web application that manages web applications. To view the Tomcat Manager screen, you must log in using the administrator and administrator password you set when installing Tomcat. If you do not remember your administrator and Administrator password, open CATALINA_HOME/conf/tomcat-users.xml and you'll see it.
void destroy();
Most servlets inherit the GenericServlet class. The GenericServlet class implements the ServletConfig interface. GenericServlet implements the Servlet interface incompletely. Because GenericServlet does not implement the service() method of the Servlet interface, GenericServlet's service() method is an abstract method, so GenericServlet is an abstract class. Subclasses that inherit GenericServlet must implement the service() method.
public abstract void service(ServletRequest req, ServletResponse res) throws ServletException, IOException;
The init(ServletConfig config) method is implemented in GenericServlet as follows:
public void init(ServletConfig config) throws ServletException { this.config = config; this.init(); }
The init(ServletConfig config) method calls the init() method with no parameters on the last line. The parameterless init() method was added to the GenericServlet for convenience, This method has nothing in the method body as shown below.
public void init() throws ServletException { }
It is convenient to override this method rather than overriding the init(ServletConfig config) method in the sub class. This is because you do not have to worry about storing the ServletConfig object. When overriding the init(ServletConfig config) method in a sub class, you need to add super(config); code on the first line. Without this code, the servlet will not store ServletConfig objects.
The init(ServletConfig config) method saves the ServletConfig object received as an argument in the instance variable config. The getServletConfig() method of GenericServlet returns this config.
public ServletConfig getServletConfig() { return config; }
The getServletContext() is method of ServletConfig interface. GenericServlet implements ServletConfig interface. The getServletContxt() method of GenericServlet returns an object of type ServletContext as shown below.
public ServletContext getServletContext() { return getServletConfig().getServletContext(); }
The getInitParameter() and getInitParameterNames() methods of the ServletConfig interface are implemented as follows in the GenericServlet.
public String getInitParameter(String name) { return getServletConfig().getInitParameter(name); }
public Enumeration getInitParameterNames() { return getServletConfig().getInitParameterNames(); }
It is for the convenience of the programmer that GenericServlet implements ServletConfig. Let's look at examples. It is convenient to use this.getServletContext(); rather than this.getServletConfig().GetServletContext(); to get a reference to a ServletContext object in a servlet. It is convenient to use String driver = this.getInitParameter("driver"); rather than String driver = this.getServletConfig().GetInitParameter("driver"); to get servlet initialization parameter information.
A servlet servicing an HTTP request must inherit HttpServlet. The HttpServlet class inherits the GenericServlet abstract class and is a servlet specific to the HTTP protocol. The HttpServlet class provides methods for handling HTTP requests. The client's request is passed to the servlet as the HttpServletRequest object type, and the servlet responds using the HttpServletResponse object type. The HttpServlet class implements the GenericServlet's service() abstract method by simply calling the protected void service (HttpServletRequest req, HttpServletResponse resp) method.
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { HttpServletRequest request; HttpServletResponse response; try { request = (HttpServletRequest) req; response = (HttpServletResponse) res; } catch (ClassCastException e) { throw new ServletException("non-HTTP request or response"); } service(request, response); }
Eventually, the following method handles the HTTP request.
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String method = req.getMethod(); if (method.equals(METHOD_GET)) { long lastModified = getLastModified(req); if (lastModified == -1) { // servlet doesn't support if-modified-since, no reason // to go through further expensive logic doGet(req, resp); } else { long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE); if (ifModifiedSince < (lastModified / 1000 * 1000)) { // If the servlet mod time is later, call doGet() // Round down to the nearest second for a proper compare // A ifModifiedSince of -1 will always be less maybeSetLastModified(resp, lastModified); doGet(req, resp); } else { resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } } } else if (method.equals(METHOD_HEAD)) { long lastModified = getLastModified(req); maybeSetLastModified(resp, lastModified); doHead(req, resp); } else if (method.equals(METHOD_POST)) { doPost(req, resp); } else if (method.equals(METHOD_PUT)) { doPut(req, resp); } else if (method.equals(METHOD_DELETE)) { doDelete(req, resp); } else if (method.equals(METHOD_OPTIONS)) { doOptions(req,resp); } else if (method.equals(METHOD_TRACE)) { doTrace(req,resp); } else { // // Note that this means NO servlet supports whatever // method was requested, anywhere on this server. // String errMsg = lStrings.getString("http.method_not_implemented"); Object[] errArgs = new Object[1]; errArgs[0] = method; errMsg = MessageFormat.format(errMsg, errArgs); resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg); } }
The only thing the HttpServlet's +service() method does is call the #service() method. (Where + denotes the public access modifier and # the protected access modifier) When the #service() method of the HttpServlet class is called, this method reads the HTTP METHOD (eg, POST, GET etc.) in the request object (an object of type HttpServletRequest) and calls the matching method according to this value. For example, if the HTTP method is "GET", it calls doGet() and if it is "POST" it calls the doPost() method. Methods like doGet() and doPost() are the methods we need to override. The HttpServletRequest interface inherits the ServletRequest interface. The HttpServletResponse interface inherits the ServletResponse interface. When a client's request comes in, the servlet container creates an object of type HttpServletRequest and an object of type HttpServletResponse and passes them as the argument values to the servlet's +service(ServletRequest req, ServletResponse res) method. Making classes that implement the HttpServletRequest and HttpServletResponse interfaces is the responsibility of the vendor making the servlet container.
Write all the examples below in the ROOT application. In the Creating a new web application, we changed the application with the document base C:/www/myapp to the ROOT application. Create JSPs in C:/www/myapp and java sources in C:/www/myapp/WEB-INF/src. Instead of using Eclipse, use a regular editor such as EditPlus.
package example; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class SimpleServlet extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req,resp); } @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html; charset=UTF-8"); PrintWriter out = resp.getWriter(); out.println(""); out.println(""); //Output the IP of client out.println("Your IP Address is " + req.getRemoteAddr() + ".\n"); out.println(""); out.close(); } }
SimpleServlet does not implement servlet lifecycle methods init() and destroy(). These methods are already implemented in the GenericServlet and are not visible in the above sources because there is no reason to override them. Open the /WEB-INF/web.xml file and add the servlet element to the sub element of the web-app element as shown below.
<servlet> <servlet-name>SimpleServlet</servlet-name> <servlet-class>example.SimpleServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>SimpleServlet</servlet-name> <url-pattern>/simple</url-pattern> </servlet-mapping>
At the command prompt, navigate to the folder where SimpleServlet.java is located and compile as shown below.
C:\ Command Promptjavac -d C:/www/myapp/WEB-INF/classes ^ -cp "C:/Program Files/Apache Software Foundation/Tomcat 8.0/lib/servlet-api.jar" ^ SimpleServlet.java
Restart Tomcat and visit http://localhost:8080/simple.
public class SimpleServlet extends HttpServlet
Servlets that inherit the HttpServlet class must be declared public.
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //.. omit .. }
The doGet() and doPost() methods are methods that override the doGet() and doPost() methods of HttpServlet. A servlet that receives a GET request overrides the doGet() method. It is a request of the GET method to request the resource of the web server by inputting the address in the web browser. In the above example, the doGet() method calls the doPost() method. Therefore, the same code is executed whether it is a GET or a POST request. The doGet() and doPost() methods have HttpServletRequest and HttpServletResponse as parameters.
resp.setContentType("text/html; charset=UTF-8"); PrintWriter out = resp.getWriter();
resp.setContentType("text/html; charset=UTF-8") sets the content type of the response (HttpServletResponse). That is, this code sets the MIME 2 type of the document to be output in response to the web browser. This code can be used only once in a servlet and must be executed before getting a PrintWriter object. Removing the ; charset=UTF-8 part breaks non-English characters. PrintWriter object can be obtained by calling getWriter() of the HttpServletResponse as follows:
PrintWriter out = resp.getWriter(); out.println(""); out.println(""); //Output the IP of client out.println("Your IP Address is " + req.getRemoteAddr() + ".\n");
PrintWriter's println() method prints the string passed as argument value to the client's web browser. As you can see, SimpleServlet uses PrintWriter's println() method to send HTML to the client. HttpServletRequest's getRemoteAddr() is a method that returns the IP address of the client. HttpServeltRequest object contains the information sent by the client and information about the client. Let's take a look at the process until the SimpleServlet servlet sends a response. The client uses the web browser to request the server's SimpleSerlvet. Tomcat calls the + service(ServletRequest req, ServletResponse res) method of SimpleServlet and passes the object (HttpSerlvetRequest interface implementation) encapsulating the client 's request and the response object (HttpSerlvetResponse interface implementation) as method arguments. The +service(ServletRequest req, ServletResponse res) method simply calls the #service(HttpServletRequest req, HttpServletResponse resp) method. The #service(HttpServletRequest req, HttpServletResponse resp) method invokes methods such as doGet() or doPost() depending on the HTTP method type (GET, POST, etc.). The above example is a GET request because you requested a servlet resource from the web browser address bar. So the doGet() method is called.
In the Web environment, dynamic elements are elements that respond differently depending on the string data sent by the client. Web programmers who need to create dynamic elements on the Web need to know how to let a client send string data to a server-side resource using a web browser, and how to obtain string data sent by a client on a server-side resource. All web programmers mainly use form and its sub-elements to allow clients to send string data to server-side resources.3 The data that the client sends is passed to the server-side resource specified by the form element's action attribute.
In the table below, the "HTML Form" item shows the HTML tag for receiving the value from the user, and the "Servlet" item shows how servlet to get the parameter values sent from the client.
| HTML Form | Servlet |
|---|---|
<input type="text" name="addr" /> |
req.getParameter("addr"); |
<input type="radio" name="os" value="Windows" /> <input type="radio" name="os" value="Linux" /> |
req.getParameter("os"); |
<input type="hidden" name="curPage" value="1" /> |
req.getParameter("curPage"); |
<input type="password" name="passwd" /> |
req.getParamter("passwd"); |
<textarea name="content" cols="60" rows="12">blah blah</textarea> |
req.getParamter("content"); |
<select name="grade"> <option value="A">A</option> <option value="B">B</option> <option value="C">C</option> <option value="D">D</option> <option value="F">F</option> </select> |
req.getParameter("grade"); |
<input type="checkbox" name="hw" value="Intel" /> <input type="checkbox" name="hw" value="AMD" /> |
req.getParameterValues("hw"); |
<select name="sports" multiple="multiple"> <option value="soccer">Soccer</option> <option value="baseball">Baseball</option> <option value="basketball">Basketball</option> </select> |
req.getParameterValues("sports"); |
The getParameter(String name) method of ServletRequest is the most common method used to get data sent by the user. The type of character data that the client sends to the server is a parameter name-value pair. Here, the name of the parameter is the value of the name attribute of the form's subelements (input, textarea, select, etc.), and value is the user input. In the server-side resource code, if the name of the parameter passed by the client is given as the argument of the getParameter(String name) method, this method returns the value that the user has entered or selected. An input element whose type attribute value is radio is called a radio button. Radio buttons with the same name attribute value can form a group and select only one item within a group.
When a client sends multiple values with one parameter, the getParamterValues(String name) method of the HttpServletRequest is needed to get these values from the server-side resource. This method returns an array of strings consisting of the values chosen by the user. If you want the client to send multiple values with one parameter, add the checkbox or select element whose multiple attribute value is "multiple" to your HTML. (the checkbox indicates that the value of the type attribute of the input element is "checkbox") If the value of the name attribute is the same, these checkboxes belongs to the same group. A checkbox differs from a radio button in that multiple checkboxes within a group can be selected. With the select element, the user can generally select only one item. However, if the select element's multiple attribute value is set to "multiple", the user can select multiple items using the Ctrl or Shift buttons.
To find out what parameter the user is sending, the server side code needs the getParamterNames() method of HttpServletRequest. The getParameterNames() method returns an Enumeration4 type object containing the parameter names.
Let's practice how to receive data from the user in the servlet through the below example. Create SignUp.html in the documentbase/example diretory.
<!DOCTYPE html>   <meta charset="UTF-8"> <title>Sign Up</title>
Sign Up
 <form id="joinForm" action="../RegisterServlet" method="post">
ID <input type="text" name="id" />

Nickname <input type="text" name="nickname" />

Password <input type="password" name="passwd" />

Name <input type="text" name="name" />

Gender Male <input type="radio" name="gender" value="M" /> Female <input type="radio" name="gender" value="F" />

Birthday <input type="text" name="birthday" />

Mobile <input type="text" name="mobile" />

Telephone <input type="text" name="tel" />

Address <input type="text" name="address" />

Email <input type="text" name="email" />

 Sports <input type="checkbox" name="sports" value="soccer" />soccer <input type="checkbox" name="sports" value="baseball" />baseball <input type="checkbox" name="sports" value="basketball" />Basketball <input type="checkbox" name="sports" value="tennis" />Tennis <input type="checkbox" name="sports" value="tabletennis" />Tabletennis

 Lectures <select name="main-menu" multiple="multiple"> <option value="">-- Multiple Select --</option> <option value="java">JAVA</option> <option value="jdbc">JDBC</option> <option value="jsp">JSP</option> <option value="css-layout">CSS Layout</option> <option value="jsp-prj">JSP Project</option> <option value="spring">Spring</option> <option value="javascript">JavaScript</option> </select>

 About Me <textarea name="aboutMe" cols="40" rows="7"></textarea>

<input type="submit" value="Submit" />
 </form>
Create RegisterServlet.java in /WEB-INF/src/example directory as shown below.
package example; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class RegisterServlet extends HttpServlet { @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException,ServletException { resp.setContentType("text/html; charset=UTF-8"); PrintWriter out = resp.getWriter(); req.setCharacterEncoding("UTF-8"); String id = req.getParameter("id"); out.println(""); out.println("id : " + id); String[] sports = req.getParameterValues("sports"); int len = sports.length; out.println("
"); for (int i = 0; i < len; i++) { out.println("
" + sports[i] + "
"); } out.println("
"); String path = req.getContextPath(); out.println("Join"); out.println(""); } }
Open a command prompt and go to /WEB-INF/src/example and compile as below.
C:\ Command Promptjavac -d C:/www/myapp/WEB-INF/classes ^ -cp "C:/Program Files/Apache Software Foundation/Tomcat 8.0/lib/servlet-api.jar" ^ RegisterServlet.java
Add the following to web.xml:
<servlet> <servlet-name>RegisterServlet</servlet-name> <servlet-class>example.RegisterServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>RegisterServlet</servlet-name> <url-pattern>/RegisterServlet</url-pattern> </servlet-mapping>
After restarting Tomcat, go to http://localhost:8080/example/SignUp.html. TODO: Add a code to the servlet to check for values other than ID and sports.
RequestDispathcer has two methods, include() and forward(). The include() method is used to pass control to another resource and to take control again when another resource is completed. It is used to add messages produced by other resources to the response. The forward() method passes control to another resource. As a result, the resource that receives the control responds to the client. Let's practice the forward() method example. Create the ControllerServlet.java file in the /WEB-INF/src/example directory as follows:
package example; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ControllerServlet extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); String uri = req.getRequestURI(); String contextPath = req.getContextPath(); String command = null; String view = null; boolean isRedirect = false; command = uri.substring(contextPath.length()); if (command.equals("/example/SignUp.action")) { view = "/example/SignUp.html"; } if (isRedirect == false) { ServletContext sc = this.getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(view); rd.forward(req, resp); } else { resp.sendRedirect(view); } } }
Open a command prompt and go to /WEB-INF/src/example and compile as follows:
C:\ Command Promptjavac -d C:/www/myapp/WEB-INF/classes ^ -cp "C:/Program Files/Apache Software Foundation/Tomcat 8.0/lib/servlet-api.jar" ^ ControllerServlet.java
Add the following to web.xml:
<servlet> <servlet-name>Controller</servlet-name> <servlet-class>example.ControllerServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Controller</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping>
After restarting Tomcat, go to http://localhost:8080/example/SignUp.action and verify that /example/SignUp.html responds. TODO: In ControllerServlet.java, change isRedirect to true and recompile and test.
We have added ControllerServlet servlet declarations and mappings in web.xml so that ControllerServlet would handle all requests ending in .action. When a request string which ends in .action comes, Tomcat interprets the mapping information in web.xml and invokes the +servlet(servletRequest req, ServletResponse resp) method of the ControllerServlet servlet. The +service(ServletRequest req, ServletResponse resp) method simply calls the #service(HttpServletRequest req, HttpServletResponse resp) method. The #service (HttpServletRequest req, HttpServletResponse resp) method checks the HTTP METHOD of the request and calls the appropriate method. This is the GET method because you requested http://localhost:8080/example/SignUp.action in the address bar of your web browser. So, doGet() method is called. The controllerServlet's doGet() method simply calls doPost(). The following table summarizes the HttpServletRequest methods used in the implementation of doPost().
| getRequestURI() |
|---|
| When requesting http://localhost:8080/example/SignUp.action in a web browser, it returns "/example/SignUp.action". |
| getContextPath() |
| Returns the value of the path property of the context file (this value is called ContextPath). As we work in the ROOT application, the value we can get through this method is "". |
| req.getRequestURI().substring(req.getContextPath().length()) |
| The above code returns "/example/SignUp.action". |
The user requesting /example/SignUp.action receives a response of /example/SignUp.html.
Let's convert the GetEmp.java file, which we practiced in the JDBC chapter, into a servlet. This is an example of turning a pure Java application into a servlet. Create the GetEmpServlet.java file in the /WEB-INF/src/example directory of the ROOT application.
package example; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class GetEmpServlet extends HttpServlet { private String DB_URL = "jdbc:oracle:thin:@<IP_ADDRESS>:1521:XE"; private String DB_USER = "scott"; private String DB_PASSWORD = "tiger"; /* * GenericServlet's init() method * init(ServletConfig config) invoke this method. * Therefore, you do not need to override the init(ServletConfig config) method. */ @Override public void init() throws ServletException { try { Class.forName( "oracle.jdbc.driver.OracleDriver" ); } catch (ClassNotFoundException e) { e.printStackTrace(); } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html; charset=UTF-8"); PrintWriter out = resp.getWriter(); Connection con = null; Statement stmt = null; ResultSet rs = null; String sql = "select * from emp"; try { con = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); stmt = con.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { String empno = rs.getString(1); String ename = rs.getString(2); String job = rs.getString(3); String mgr = rs.getString(4); String hiredate = rs.getString(5); String sal = rs.getString(6); String comm = rs.getString(7); String depno = rs.getString(8); out.println( empno + " : " + ename + " : " + job + " : " + mgr + " : " + hiredate + " : " + sal + " : " + comm+" : " + depno + "
" ); } } catch (SQLException e) { e.printStackTrace(out); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
Use the command prompt to navigate to the /WEB-INF/src/example directory of the ROOT application and compile it as follows:
C:\ Command Promptjavac -d C:/www/myapp/WEB-INF/classes ^ -cp "C:/Program Files/Apache Software Foundation/Tomcat 8.0/lib/servlet-api.jar" ^ GetEmpServlet.java
Add the following to web.xml:
<servlet> <servlet-name>GetEmpServlet</servlet-name> <servlet-class>example.GetEmpServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>GetEmpServlet</servlet-name> <url-pattern>/empList</url-pattern> </servlet-mapping>
Copy the JDBC driver file to CATALINA_HOME/lib.
Let's modify the GetEmpServlet example to use the ServletConfig initialization parameter. Create the following servlet in the /WEB-INF/src/example directory.
package example; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class InitParamServlet extends HttpServlet { private String url; private String user; private String passwd; private String driver; @Override public void init() throws ServletException { url = this.getInitParameter("url"); user = this.getInitParameter("user"); passwd = this.getInitParameter("passwd"); driver = this.getInitParameter("driver"); try { Class.forName(driver); } catch (ClassNotFoundException e) { e.printStackTrace(); } } @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { resp.setContentType("text/html; charset=UTF-8"); PrintWriter out = resp.getWriter(); Connection con = null; PreparedStatement stmt = null; ResultSet rs = null; String sql = "SELECT * FROM emp"; try { con = DriverManager.getConnection(url, user, passwd); stmt = con.prepareStatement(sql); rs = stmt.executeQuery(); while (rs.next()) { String empno = rs.getString(1); String ename = rs.getString(2); String job = rs.getString(3); String mgr = rs.getString(4); String hiredate = rs.getString(5); String sal = rs.getString(6); String comm = rs.getString(7); String depno = rs.getString(8); out.println(empno + " : " + ename + " : " + job + " : " + mgr + " : " + hiredate + " : " + sal + " : " + comm+" : " + depno + "
"); } } catch (SQLException e) { e.printStackTrace(out); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
Add the following to web.xml:
<servlet> <servlet-name>InitParamServlet</servlet-name> <servlet-class>example.InitParamServlet</servlet-class> <init-param> <param-name>driver</param-name> <param-value>oracle.jdbc.driver.OracleDriver</param-value> </init-param> <init-param> <param-name>url</param-name> <param-value>jdbc:oracle:thin:@<IP_ADDRESS>:1521:XE</param-value> </init-param> <init-param> <param-name>user</param-name> <param-value>scott</param-value> </init-param> <init-param> <param-name>passwd</param-name> <param-value>tiger</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>InitParamServlet</servlet-name> <url-pattern>/initParam</url-pattern> </servlet-mapping>
The value of the initialization parameter of ServletConfig set above is obtained by using getInitParameter(String name) method of ServletConfig. After restarting Tomcat, visit http://localhost:8080/initParam.
The ServletConfig initialization parameters can only be referenced in the corresponding servlet. The ServletContext initialization parameters can be referenced in any servlet and JSP in the web application. The ServletContext initialization parameter is set in web.xml using the context-param element. For the schema and dtd there is a specified order. The following excerpts from http://java.sun.com/dtd/web-app_2_3.dtd.
You can see that the context-param must be declared ahead of the servlet. Open web.xml and add the following:
<context-param> <param-name>url</param-name> <param-value>jdbc:oracle:thin:@<IP_ADDRESS>:1521:XE</param-value> </context-param>
A reference to a ServletContext object can be obtained using the servlet's getServletContext() method. The value of url, which is the ServletContext initialization parameter declared above, is obtained by using getInitParameter(String name) method of ServletContext. Add the following code to the existing SimpleSerlvet.java in the appropriate location and recompile.
ServletContext sc = getServletContext(); String url = sc.getInitParameter("url"); out.println(url);
After restarting Tomcat, visit http://localhost:8080/simple. TODO: Modify InitParamServlet.java so that the url is set with the ServletContext initialization parameter.
The listener runs on the web application event. Web application events have been added to the Servlet 2.3 specification. Web application events are divided into:
An application startup event occurs when a web application is first loaded and started by a servlet container, such as Tomcat. Application shutdown events occur when the web application is shut down. Session creation events occur when a new session is created. Session invalidation events occur each time a session is invalidated. To use events, you need to write a class called Listener. The Listener class is a pure Java class that implements the following interfaces:
If you want listeners for application startup or shutdown events, implement the ServletContextListener interface. If you want listeners for session creation and session invalidation events, implement the HttpSessionListener interface. The ServletContextListener interface consists of two methods:
The HttpSessionListener interface consists of two methods:
Write the following Listener class, which it, right after the web application startup, creates an OracleConnectionManager object and stores it in the ServletContext.
package net.java_school.listener; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import net.java_school.db.dbpool.OracleConnectionManager; public class MyServletContextListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { ServletContext sc = sce.getServletContext(); OracleConnectionManager dbmgr = new OracleConnectionManager(); sc.setAttribute("dbmgr", dbmgr); } @Override public void contextDestroyed(ServletContextEvent sce) { ServletContext sc = sce.getServletContext(); sc.removeAttribute("dbmgr"); } }
Add the following to web.xml, below the context-param, above the servlet declaration.
<listener> <listener-class>net.java_school.listener.MyServletContextListener</listener-class> </listener>
Add all the java source files from the lession entitled "ConnectionPool" in the JDBC chapter to the ROOT application's WEB-INF/src directory. Open Log.java and modify it as follows:
public String logFile = "C:/www/myapp/WEB-INF/myapp.log";
Copy the orcale.properties file in the "ConnectionPool" to the ROOT application's WEB-INF directory. Open ConnectionManager.java and modify it as follows:
configFile = "C:/www/myapp/WEB-INF/" + poolName + ".properties";
Now when the ROOT web application is started, an OracleConnectionManager object will be created and its reference will be stored in the ServletContext. To test it, modify the GetEmpServlet.java file as shown below.
package example; import java.sql.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import net.java_school.db.dbpool.*; public class GetEmpServlet extends HttpServlet { private OracleConnectionManager dbmgr; @Override public void init() throws ServletException { ServletContext sc = getServletContext(); dbmgr = (OracleConnectionManager) sc.getAttribute("dbmgr"); } @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { resp.setContentType("text/html; charset=UTF-8"); PrintWriter out = resp.getWriter(); Connection con = null; PreparedStatement stmt = null; ResultSet rs = null; String sql = "SELECT * FROM emp"; try { con = dbmgr.getConnection(); stmt = con.prepareStatement(sql); rs = stmt.executeQuery(); while (rs.next()) { String empno = rs.getString(1); String ename = rs.getString(2); String job = rs.getString(3); String mgr = rs.getString(4); String hiredate = rs.getString(5); String sal = rs.getString(6); String comm = rs.getString(7); String depno = rs.getString(8); out.println( empno + " : " + ename + " : " + job + " : " + mgr + " : " + hiredate + " : " + sal + " : " + comm+" : " + depno + "
" ); } } catch (SQLException e) { e.printStackTrace(out); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
Compile the custom connection pool source and GetEmpServlet.java. Restart Tomcat and visit http://localhost:8080/empList. (The declarations and mappings for the GetEmpServlet servlet have already been set up in previous exercises)
The HttpSessionListener interface consists of two methods. One for session creation events and the other for session invalidation events.
The following is an example of an HttpSessionListener.
package net.java_school.listener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class SessionCounterListener implements HttpSessionListener { public static int totalCount; @Override public void sessionCreated(HttpSessionEvent event) { totalCount++; System.out.println("Session Increase. Total Sessions:" + totalCount); } @Override public void sessionDestroyed(HttpSessionEvent event) { totalCount--;. System.out.println("Session Reduction. Total Sessions:" + totalCount); } }
Add the following to web.xml:
<listener> <listener-class>net.java_school.listener.SessionCounterListener</listener-class> </listener>
Restart Tomcat and visit http://localhost:8080/simple. Visit http://localhost:8080/simple with another web browser. Check the log messages in the Tomcat log file.
A filter is used when there is code that must be executed before a user's request is delivered to a server resource. For the filter to work, you need to add filter declarations and filter mappings to web.xml. If filter 1 followed by filter 2 in web.xml is mapped in order, then filter 1 - filter 2 - server resource - filter 2 - filter 1 - web browser will be executed in order. The filter class must implement the javax.servlet.Filter interface.
The following is a pure Java application created to understand the filter mechanism.
package net.java_school.filter; import java.util.ArrayList; import java.util.Iterator; public class ChainFilter { private ArrayList<Filter> filters; private Iterator<Filter> iterator; public void doFilter() { if (iterator.hasNext()) { iterator.next().doFilter(this); } else { System.out.println("Run Server resource"); } } public ArrayList<Filter> getFilters() { return filters; } public void setFilters(ArrayList<Filter> filters) { this.filters = filters; this.iterator = filters.iterator(); } }
package net.java_school.filter; public interface Filter { public void doFilter(ChainFilter chain); }
package net.java_school.filter; public class Filter1 implements Filter { @Override public void doFilter(ChainFilter chain) { System.out.println("Run Filter 1 before the server resource runs"); chain.doFilter(); System.out.println("Run Filter 1 after the server resource runs"); } }
package net.java_school.filter; public class Filter2 implements Filter { @Override public void doFilter(ChainFilter chain) { System.out.println("Run Filter 2 before the server resource runs"); chain.doFilter(); System.out.println("Run Filter 2 after the server resource runs"); } }
package net.java_school.filter; import java.util.ArrayList; public class Tomcat { public static void main(String[] args) { ChainFilter chain = new ChainFilter(); ArrayList<Filter> filters = new ArrayList<Filter>(); Filter f1 = new Filter1(); Filter f2 = new Filter2(); filters.add(f1); filters.add(f2); chain.setFilters(filters); chain.doFilter(); } }
Run Filter 1 before the server resource runs Run Filter 2 before the server resource runs Run Server resource. Run Filter 2 after the server resource runs Run Filter 1 after the server resource runs
The arguments of the doFilter() method show that the filter can access the ServletRequest, ServletResponse, and javax.servlet.FilterChain objects when it intercepts the request or response. The FilterChain object has a list of filters that should be called in order. In the doFilter() method of the filter class, the code before FilterChain's doFilter() method call is the filtering code that is executed before the request reaches the server resource and the code after FilterChain's doFilter() method call is the filtering code that is executed before the response.
The following is an example that runs req.setCharacterEncoding("UTF-8"); code before all server resources are executed. Create a CharsetFilter.java file as follows:
package net.java_school.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class CharsetFilter implements Filter { private String charset = null; @Override public void init(FilterConfig config) throws ServletException { this.charset = config.getInitParameter("charset"); } @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { if (req.getCharacterEncoding() == null) { req.setCharacterEncoding(charset); chain.doFilter(req,resp); } } @Override public void destroy() { //Implement it if you have resources to return. } }
At the command prompt, go to the /WEB-INF/src/net/java_school/filter/directory and compile as follows.
C:\ Command Promptjavac -d C:/www/myapp/WEB-INF/classes ^ -cp "C:/Program Files/Apache Software Foundation/Tomcat 8.0/lib/servlet-api.jar" ^ CharsetFilter.java
Open the following web.xml file and add the following: Note the order with existing elements. The following code should be placed between the context-param element and the listener element.
<filter> <filter-name>CharsetFilter</filter-name> <filter-class>net.java_school.filter.CharsetFilter</filter-class> <init-param> <param-name>charset</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharsetFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
Open the RegisterServlet.java source and comment out the req.setCharacterEncoding("UTF-8"); and recompile RegisterServlet.java. Go to http://localhost:8080/example/SignUp.html and input the non-English characters into the ID and click submit button. If req.setCharacterEncoding("UTF-8"); is executed, the ID will be output correctly.
The filter initialization parameters are set using the filters sub-element, init-param. The getInitParameter() and getInitParameters() methods of FilterConfig are used to read filter initialization parameters. The filter-mapping element in web.xml specifies the resource to be filtered. Filters are added to the FilterChain in the order in which they are listed in web.xml, but the filter mapped to the servlet name is added after the filter that matches the URL pattern. The doFilter() method of FilterChain calls the next filter of FilterChain.
Most programmers are using external libraries to upload files.
The MultipartRequest package is a package that is widely used for file upload. Download cos.26Dec2008.zip from the following address. http://www.servlets.com/cos/index.html After decompressing, copy the cos.jar file to the ROOT application's /WEB-INF/lib directory. There are eight constructors for the MultipartRequest class. For a more detailed explanation, please refer to the following address. http://www.servlets.com/cos/javadoc/com/oreilly/servlet/MultipartRequest.html The following constructor resolves the encoding problem for non-English characters and automatically rename the file name when the file name is duplicate.
public MultipartRequest( HttpServletRequest request, String saveDirectory, int maxPostSize, String encoding, FileRenamePolicy policy) throws IOException
If the MultipartRequest constructor was successfully executed, the upload was successful. The following table shows the member methods of MultipartRequest that are available after uploading files to the server's file system. Suppose you upload the logo.gif image file using the <input type="file" name="photo" />.
| getContentType("photo"); |
|---|
| Return the MIME type of the uploaded file. For example, if the extension of the file is gif, "image/gif" is returned. |
| getFile("photo"); |
| Return the File object of the file uploaded and stored in the server. |
| getFileNames(); |
| Return parameter names whose type attribute is "file" as Enumeration type. |
| getFilesystemName("photo"); |
| Returns the actual file name that is uploaded and exists in the server file system. |
| getOriginalFileName("photo"); |
| Return original file name |
| getParameter(String name); |
|---|
| Return value of parameter corresponding to name as String |
| getParameterNames(); |
| Return all parameter names as Enumeration type. |
| getParameterValues(String name); |
| Returns values of the parameter corresponding to name as String[]. |
Create the following HTML file in the example subdirectory of the ROOT application's top-level directory:
<!DOCTYPE html>   <title>MultipartRequest Servlet Example</title> <meta charset="UTF-8" />
File Upload Test with MultipartRequest
 <form action="../servlet/UploadTest" method="post" enctype="multipart/form-data">
Name: <input type="text" name="name" />

File 1: <input type="file" name="file1" />

File 2: <input type="file" name="file2" />

<input type="submit" value="Submit" />
 </form>
Create and compile the following servlet. When compiling, you need to tell the Java compiler the path to the cos.jar file.
package example; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.oreilly.servlet.MultipartRequest; import com.oreilly.servlet.multipart.DefaultFileRenamePolicy; public class UploadTest extends HttpServlet { @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { resp.setContentType("text/html; charset=UTF-8"); PrintWriter out = resp.getWriter(); ServletContext cxt = getServletContext(); String dir = cxt.getRealPath("/upload"); try { MultipartRequest multi = new MultipartRequest(req, dir, 5*1024*1024, "UTF-8", new DefaultFileRenamePolicy()); out.println(""); out.println(""); out.println("
Parameters passed by the user
"); out.println("
"); Enumeration<?> params = multi.getParameterNames(); while (params.hasMoreElements()) { String name = (String) params.nextElement(); String value = multi.getParameter(name); out.println("
" + name + "=" + value + "
"); } out.println("
"); out.println("
Uploaded files
"); Enumeration<?> files = multi.getFileNames(); while (files.hasMoreElements()) { out.println("
"); String name = (String) files.nextElement(); String filename = multi.getFilesystemName(name); String originalName =multi.getOriginalFileName(name); String type = multi.getContentType(name); File f = multi.getFile(name); out.println("
Parameter name: " + name + "
"); out.println("
File name: " + filename + "
"); out.println("
File original name: " + originalName + "
"); out.println("
File type: " + type + "
"); if (f != null) { out.println("
File size: " + f.length() + "
"); } out.println("
"); } } catch(Exception e) { out.println("
"); e.printStackTrace(out); out.println("
"); } out.println(""); } }
Add the following to web.xml:
<servlet> <servlet-name>UploadTest</servlet-name> <servlet-class>example.UploadTest</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadTest</servlet-name> <url-pattern>/servlet/UploadTest</url-pattern> </servlet-mapping>
Before running the example, create an upload subdirectory in the top-level directory of your ROOT web application. Restart Tomcat and visit http://localhost:8080/example/upload.html. After uploading duplicate files, check the file name in upload folder. If you upload a duplicate file, you can see that the file name except the extension is appended with a number at the end. If the test fails, check the list below.
Commons-fileupload is a file upload library provided by Apache, which is famous for its open source. Download the latest binary file from the following address. http://commons.apache.org/proper/commons-fileupload/download_fileupload.cgi http://commons.apache.org/proper/commons-io/download_io.cgi Uncompress and copy the commons-fileupload-x.x.jar and commons-io-x.x.jar files to the ROOT application's /WEB-INF/lib.
<!DOCTYPE html>   <meta charset="UTF-8"> <title>commons-fileupload Test</title>
Uploading files using commons-fileupload
 <form action="../CommonsUpload" method="post" enctype="multipart/form-data">
File : <input type="file" name="upload" />

<input type="submit" value="Submit" />
 </form>
package example; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.Iterator; import java.io.File; import java.util.List; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class CommonsUpload extends HttpServlet { @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { resp.setContentType("text/html; charset=UTF-8"); PrintWriter out = resp.getWriter(); //Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(req); //Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); //Configure a repository (to ensure a secure temp location is used) ServletContext servletContext = this.getServletConfig().getServletContext(); File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); factory.setRepository(repository); //Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); try { //Parse the request List<FileItem> items = upload.parseRequest(req); //Process a file upload Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); String fileName = null; if (!item.isFormField()) { String fieldName = item.getFieldName(); out.println(fieldName); fileName = item.getName(); out.println(fileName); String contentType = item.getContentType(); out.println(contentType); boolean isInMemory = item.isInMemory(); out.println(isInMemory); long sizeInBytes = item.getSize(); out.println(sizeInBytes); } // Process a file upload ServletContext cxt = getServletContext(); String dir = cxt.getRealPath("/upload"); File uploadedFile = new File(dir + "/" + fileName); item.write(uploadedFile); } } catch (Exception e) { out.println("
"); e.printStackTrace(out); out.println("
"); } out.println("commons-fileupload.html"); } }
Add the following to web.xml:
<servlet> <servlet-name>commonsUpload</servlet-name> <servlet-class>example.CommonsUpload</servlet-class> </servlet> <servlet-mapping> <servlet-name>commonsUpload</servlet-name> <url-pattern>/CommonsUpload</url-pattern> </servlet-mapping>
Restart Tomcat and visit http://localhost:8080/example/commons-fileupload.html. After uploading duplicate files, check the file name in upload folder. If you upload a duplicate file, you will notice that unlike cos.jar, it overwrites the existing file. An example of showing uploaded files is covered in the JSP chapter.
The HTTP protocol is a protocol that can not maintain state. A cookie is one of technologies for overcoming that a web browser cannot maintain a session in communication with a server due to the characteristics of the HTTP protocol. When the server sends a cookie, the web browser passes the cookie to the server for each request so that the user information can be maintained.
For the cookie to work, the server must make and send the cookie to a web browser. The cookie looks like as follows:
Set-Cookie : name = value ; expires = date ; path = path ; domain = domain ; secure
Cookies are stored in files managed by the web browser.
Once the cookie is set in the web browser, the web browser sends the cookie whenever it requests the server resource. The cookie looks like as follows:
Cookie ; name = value1 ; name2 = value2 ;
The cookie name and value can not contain characters such as [] () = "/? @ :;
Creates a cookie using the Cookie (String name, String value) constructor.
| setValue(String value) |
|---|
| It is used to reset the value of created cookie. |
| setDomain(String pattern) |
| By default, cookies are only returned to the server that sent them. To send a cookie to a server using the same domain, use the setDomain() method. Domains not related to the server can not be set with setDomain(). |
| setMaxAge(int expiry) |
| Set the validity period of the cookie in seconds. If you set a negative number, the cookie is deleted when you close the browser. |
| setPath(String uri) |
| Sets the path to which cookies will be applied. If the path is set, the web browser will send the cookie to the web server only if it visit the set path. |
| setSecure(boolean flag) |
| If flag is true, cookies are sent only for servers using secure channels. (https) |
If you create a cookie with the cookie constructor and call the cookie method to set the cookie appropriately, you must send the cookie to the web browser. The following is the code that sends the cookie to the web browser.
resp.addCookie(cookie);
Cookie[] cookie = req.getCookies();
Use the getCookies() method of HttpServletRequest to get the cookie array. (If there is no cookie, the getCookies() method returns null) You can get information about cookies by using the following method. Among them, getName() and getValue() are mainly used.
| getName() |
|---|
| Return cookie name |
| getValue() |
| Return cookie value |
| getDomain() |
| Return cookie domain |
| getMaxAge() |
| Return cookie expiration |
Here is a snippet of code that gets the cookie value from the server resource.
String id = null; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { String name = cookies[i].getName(); if (name.equals("id")) { id = cookies[i].getValue(); break; } } }
Below is an example of deleting cookies. It creates a cookie with the same name as the cookie you want to delete, calls setMaxAge(0), and sends the cookie to a web browser.
Cookie cookie = new Cookie("id",""); cookie.setMaxAge(0); resp.addCookie(cookie);
Cookie exercises are covered in JSP chapter.
A session is a cookie-based technology, which were made to overcome weaknesses in cookie security. Unlike cookies, the web browser stores only the session ID that the server has set as the cookie value. A session ID cookie stored in a web browser and a session object (HttpSession Type) mapped to a session ID cookie in the server cooperate to maintain the state of the user. The code for creating the session is as follows.
HttpSession session = req.getSession(true); //If there is no session, create it. HttpSession session = req.getSession(false); //If there is no session, it returns null.
Once the session object has been created, you can store the information in the session.
User user = new User("Alison", "11111111"); session.setAttribue("user", user);
Session exercises are covered in the JSP chapter.
Comments


Title goes here
<
>
all
Content goes here
Notes:
Currently, it's assumed fields marked Cash represent costs, so are plotted as negatives. This might not be the case. The legend needs fixing.
Current fake data is not ideal for testing.


new Helenus
Helenus, a NodeJS Cassandra Driver
- Source:
- helenus.js, line 12
Members
-
<static> Column
-
The Column
- Source:
- helenus.js, line 54
- See:
-
<static> ColumnFamily
-
The ColumnFamily
- Source:
- helenus.js, line 47
- See:
-
<static> Connection
-
The connection
- Source:
- helenus.js, line 33
- See:
-
<static> ConnectionPool
-
The connection pool
- Source:
- helenus.js, line 26
- See:
-
<static> Keyspace
-
The Keyspace
- Source:
- helenus.js, line 40
- See:
-
<static> Marshal
-
An object for de/serializing data for consumption by Cassandra
- Source:
- helenus.js, line 68
- See:
-
<static> Row
-
The Row
- Source:
- helenus.js, line 61
- See:
-
<static> TimeUUID
-
TimeUUID
- Source:
- helenus.js, line 80
- See:
-
<static> UUID
-
UUID
- Source:
- helenus.js, line 74
- See:
-
<static, constant> version
-
The current dirver version
- Source:
- helenus.js, line 19


Additional resources about issues: Index
Well-described, easy-to-apply patches are a pleasure for other developers to encounter and go a long way towards making the module or component more stable and powerful.
If you are not yet a member of an open source project on this site but you have mailing list access, you can post a message about your proposed patch to the project's developer mailing list. (Read more about subscribing to project mailing lists.) If you are a project member, first conduct a query of the project's issue database to determine whether this patch is associated with an already reported defect.
If your patch pertains to an existing issue, you should use the File Attach field in the issue edit screen to submit your patch and the Add Comment section to post an explanatory message. (Remember that changes to issues generate automatic email messages to the issue's owner and anyone on the cc list. All of those people will receive your message and a link to your patch.)
If an issue does not exist, submit your patch as a new issue, using the Patch link in the "Enter An Issue" section of the Project Issues page. Attach your patch file to the new issue. Here's how to do it:
cvs diff -c > mypatch
... to get a context-format patch for the sources. This gives you a patch file which includes information about the version you are patching, the filenames, and the contents of the change. This is the preferred way to keep track of patches and makes it easier for others to find and test your patch.
patch < issuepatch.diff
The developer responsible for the section of code affected should either apply the patch and mark the defect (if there is one registered) as fixed, or reply with an objection if it does not seem safe, does not appear to fix the problem, or there is not really a problem to begin with. Notifications of any changes to the issues database, as well as CVS check-ins, are automatically sent to the appropriate issue assignee/cc'd and CVS mailing lists, so you can monitor whether the patch has been applied. Be sure to subscribe to at least the CVS and issue mailing lists for the module you are working on.
If you do not know exactly how to fix a problem, but have an idea about what is causing it, you can post a message about this on the developer discussion list for other project members' suggestions or to find someone who knows how to fix it.


There is no registered stock for those products and attribute set values.
As your client does not allow negative stock, it is needed to automatically create a physical inventory for those products, in order to be able to void the receipt.


Simple Neural Network
Input matrix
Result matrix
Random matrix
Random matrix after learning
Result matrix after learning
Result matrix (rounded)
New situation
Result
Stats


ANALYZE THIS
Reviewed by Harvey Karten, Ph.D. Warner Bros./Village Roadshow Pictures Director: Harold Ramis Writer: Peter Tolan and Harold Ramis and Kenneth Lonergan Cast: Robert De Niro, Billy Crystal, Lisa Kudrow, Joe Viterelli, Chazz Palminteri
There may still be some people out there who think that you've got to be crazy to see a psychiatrist. Not so long ago a guy named Eagleburger was dropped from the vice presidential ticket because he had visited a shrink. But anyone with a semblance of education knows that we all have problems and that people who seek help are probably the most stable of us all. No wonder, then, that convicted killers talk out their feelings only on the day they are to be executed. You'd never expect a member of the Mob to go on the couch purely on his own volition, and since comedy is often dependent for laughs on unexpected occurrences that look silly (slipping on a banana peel, for example), a movie like "Analyze This" should have no problems getting laughs. When a nationally known gangster weepingly pours out his problems to a reluctant psychiatrist, the stage is set for chuckles.
"Analyze This" does get its share of chortles. With one of America's great comics, Billy Crystal, in the role of a frightened shrink who is forced to blend in with members of Organized Crime, how could it not? The trouble is that Robert De Niro, so suited for roles as sociopaths ("Taxi Driver," ""The Godfather Part II," "Mean Streets"), is about as convincing in the part of a vulnerable, whimpering mafioso as Kenneth Branagh was as a clone of Woody Allen in "Celebrity." Casting De Niro with a comic constitution makes as much sense as posting Billy Crystal as "Henry V."
The story takes off after Dr. Ben Sobel (Billy Crystal) accidentally rear-ends the car of a mafioso, Jelly (Joe Viterelli), exposing a man who is tied up in its trunk. He hands his business card to Jelly (Joe Viterelli) who, in turn, recommends that his boss, Paul Vitti (Robert De Niro), contact the psychiatrist about anxiety attacks he had experienced. Their sessions together take on comic import because the talking cure works only if the patient is educated, liberal, and open-minded--everything that Vitti is not. Alternately threatening his doctor and praising him ("You've got a gift...yes you do...YES YOU DO!"), Vitti is at first disappointed that his anxiety is not relieved in just ten minutes, but ultimately the doctor is able to use both his Freudian background and his ability to improvise to successfully turn the gangster's life around.
"Analyze This" is filled with standard psychiatrist jokes together with some insights into Freudian thinking that would sound tiresome to those who know, mind-boggling to those who do not. Take Ben Sobel's explanation of the Oedipal conflict to a baffled new patient.  Later he reports that he's afraid even to call his mom after what the doctor had told him.
The picture is anything but a rout, however, because the masterful Billy Crystal shows his mettle as a stand-up comic able to conform to romantic and other situations with his stock of surprises. He is at his best (as in "When Harry Met Sally") when reacting to the demands of those he is with. In the movie's choice scene, he is required to don a $1200 suit and blend in with a score of gangsters at a Mafia summit meeting. Watching his mentor Jelly, he proceeds to throw his arms around large and scary mobsters and kiss them on each cheek. In one such cuddle he mumbles "Easter Weekend" to a gangster--apropos of nothing. Crystal succeeds as well in holding on to his fiance Laura (Lisa Kudrow) even after Jelly has caused a disruption in their Miami marriage ceremony--while fending off threats by his patient's rival, Primo Sindone (Chazz Palminteri).
Director Harold Ramis has proved himself in working with comedy troupes that included Bill Murray, John Belushi and Gilda Radner. He is best known for directing lowbrow comedies with box office appeal, such as "Meatball," "Caddyshack," and "National Lampoon's Vacation." This time he has raised his sights a few notches, elevating his material with psychoanalytic terminology This is a dependable idea considering the top-notch comedian he is working with. A bad film featuring Crystal has not been made. See it to admire the talents of this master comedian and forget the many ways that crackerjack actor Robert De Niro is compelled to embarrass himself.
Rated R. Running Time: 100 minutes. (C) 1999 Harvey Karten
The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.
Please direct comments/criticisms of the review to relevant newsgroups.
Broken URLs inthe reviews are the responsibility of the author.
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
Related links: index of all rec.arts.movies.reviews reviews


About Me
With a background of over twenty years experience in building and maintaing ecommerce websites and applications for a wide range of companies in the United States.
I am front-end and server-side all-round kind of guy with strong technical and people skills in addition to user experience. Specialising in responsive builds using the latest techniques and technologies hand crafting beautiful web interfaces.
I enjoy learning, developing and pushing myself to embrace the latest ideas through a lot of industry reading and learning. For fun I love to ride my motorcycle and to get out of state fishing whenever i get the chance and I always enjoy a good cup of coffee, a good cold beer, and great pizza.


--- layout: page title: "Zach Liu's Blog about Programming" description: "" --- {% include JB/setup %} {% for post in site.posts %}
{{ post.date| date: "%b-%-d-%Y" }}


'Taxonomic' information from 'Wikipedia', 'Wikicommons',
'Wikispecies', and 'Wikidata'. Functions included for getting
taxonomic information from each of the sources just listed, as
well performing taxonomic search.
| Version: |
0.3.0 |
| Depends: |
R (≥ 3.2.1) |
| Imports: |
WikidataR, data.table, curl, crul (≥ 0.3.4), tibble, jsonlite, xml2 |
| Suggests: |
roxygen2 (≥ 6.1.0), testthat, knitr, rmarkdown, vcr |
| Published: |
2018-10-19 |
| Author: |
Scott Chamberlain [aut, cre],
Ethan Welty [aut] |
| Maintainer: |
Scott Chamberlain <myrmecocystus+r at gmail.com> |
| BugReports: |
https://github.com/ropensci/wikitaxa/issues |
| License: |
MIT + file LICENSE |
| URL: |
https://github.com/ropensci/wikitaxa |
| NeedsCompilation: |
no |
| Language: |
en-US |
| Materials: |
README NEWS |
| CRAN checks: |
wikitaxa results |


Solid Notifications Use Cases and Requirements
Editor’s Draft, 2022-01-20
- This version
- https://solid.github.io/notifications-panel/notifications-ucr
- Latest version
- https://solid.github.io/notifications-panel/notifications-ucr
- Created
- Published
- Modified
- Repository
- GitHub
- Language
- English
- License
- MIT License
- Document Status
- Editor’s Draft
- In Reply To
- Solid Origin
- Notifications Panel Charter
- Policy
-
- Rule
- Offer
- Unique Identifier
- https://solid.github.io/notifications-panel/notifications-ucr#document-policy-offer
- Target
- https://solid.github.io/notifications-panel/notifications-ucr
- Permission
-
- Assigner
- W3C Solid Community Group
- Action
Copyright © 2021 W3C Solid Community Group.
Abstract
Solid Notifications Use Cases and Requirements.
Issue: Update Notifications UCR
UCR needs a review/revision. Solution-centric references have no place in a UCR document. issues/76.
Status of This Document
This section describes the status of this document at the time of its publication.
This document was published by the Solid Community Group as an Editor’s Draft. The sections that have been incorporated have been reviewed following the Solid process. However, the information in this document is still subject to change. You are invited to contribute any feedback, comments, or questions you might have.
Publication as an Editor’s Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.
This document was produced by a group operating under the W3C Community Contributor License Agreement (CLA). A human-readable summary is available.
Introduction
This section is non-normative.
Motivation...
..
This document is for:
- Technical communicators that want to develop information and media concepts, standards, structures and software tool support.
Terminology
This section is non-normative.
This document defines the following terms. These terms are referenced throughout this document.
- Foo Bar Baz
- Foo Bar Baz...
Use Cases
This section is non-normative.
Immediate Notification of Data Changes
For many clients, it is important to know when a resource state changes. This includes collaborative editing apps, chat apps or any client that expects the underlying data to change frequently based on updates made by others.
Notification of Data Changes on Multiple Resources
Clients might want to know state changes of multiple resources at the same time. For example, an app may simultaneously receive notifications from a container, resource(s) within the container, and/or resource(s) linked to the container.
Amend List of Resources for Notification of Data Changes
Clients might want to amend the list of resources from which they receive notifications of data change. This allows the client to respond to modifications made to a container, such as a resource being created or removed from within it.
Frequency of Notifications
Sometimes a client doesn't need to be alerted for every change. If a client only needs infrequent updates (for example, every 5 minutes), it should be possible to avoid floods of data that might otherwise place a higher burden on the client application. Ideally, a client should be able to define what that aggregation window would be: for some clients, 10 seconds might be appropriate; for others, several minutes might be more appropriate.
Filtered Notifications
Certain categories of notifications may be more or less interesting to clients. For example, a client may not care about UPDATE operations or may only care about notifications for resources of certain types.
Time-bound Subscriptions
Occasionally, a client only needs a subscription to be in effect for a limited period of time. While a client may easily close a WebSocket itself, subscriptions for other, more asynchronous forms of notifications, such as LDN alerts or WebHook operations, may be more difficult to terminate.
Lost Update Notifications
For WebSockets and subscriptions that rely on an active, live connection to a notification server, the subscription channel needs to make sure that clients do not miss notifications in the event of a dropped connection.
- Requirements
- Create Events
- Update Events
- Delete Events
- Authorization
Capability Discovery
A given Solid Notification server may support certain technologies (e.g., WebSockets and LDN) but not others (e.g., EventSource and WebSub). Likewise, a client may not support the same set of technologies that are implemented by a server. As such, there needs to be a mechanism for clients and servers to agree on a mutually supported subscription type. In addition to simply determining the set of protocols that work for client and server, there may be particular features (e.g., notification aggregation, notification filtering) that are required by the client. This could be used to further filter the protocol selection.
- Requirements
- Capability Discovery
Requirements
This section is non-normative.
This section lists the functional and non-functional requirements arising from the use-cases catalogued in this document. Specific requirements that have been de-prioritized or rejected have been left in the document for completeness, but are shown as struck out.
The use cases and their requirements are tabulated below, followed by a definition of each requirement.
| Use Case | Functional Requirements | Non-Functional Requirements | |||||||
|---|---|---|---|---|---|---|---|---|---|
| F1 | F2 | F3 | F4 | F5 | F6 | F7 | F8 | NF1 | |
| Immediate Notification of Data Changes | ✔ | ✔ | ✔ | ⌙ | ✔ | ⌙ | ✔ | ⌙ | ⌙ |
| Notification of Data Changes on Multiple Resources | ✔ | ✔ | ✔ | ⌙ | ✔ | ⌙ | ✔ | ⌙ | ⌙ |
| Amend List of Resources for Notification of Data Changes | ✔ | ✔ | ✔ | ⌙ | ✔ | ⌙ | ⌙ | ✔ | ⌙ |
| Frequency of Notifications | ✔ | ✔ | ✔ | ✔ | ✔ | ⌙ | ✔ | ✔ | ⌙ |
| Filtered Notifications | ✔ | ✔ | ✔ | ✔ | ✔ | ⌙ | ✔ | ✔ | ⌙ |
| Time-Bound Subscriptions | ✔ | ✔ | ✔ | ⌙ | ✔ | ⌙ | ✔ | ✔ | ⌙ |
| Lost Update Notifications | ✔ | ✔ | ✔ | ⌙ | ✔ | ⌙ | ⌙ | ⌙ | ⌙ |
| Capability Discovery | ⌙ | ⌙ | ⌙ | ⌙ | ⌙ | ✔ | ⌙ | ⌙ | ⌙ |
|
Functional Requirements
This section is non-normative.
- F1. Create Events
- A subscribed entity is alerted when a new resource is created.
- F2. Update Events
- A subscribed entity is alerted when an existing resource is updated.
- F3. Delete Events
- A subscribed entity is alerted when an existing resource is deleted.
- F4. Event Filtering
- A subscribed entity can request a subset of all notifications.
- F5. Authorization
- Authorization is enforced on all subscriptions.
- F6. Capability Discovery
- A client is able to discover the notification capabilities of a Solid Storage.
- F7. Handling Subscription Requests
- >When a subscriber makes request for a new subscription, the Solid storage must be able to process the request including the parameters for subscription provided by the client.
- F8. Handling Subscription Modifications
- When a subscriber requests for parameters of a subscription to be modified, the Solid storage must be able to process the request.
Non-Functional Requirements
This section is non-normative.
- NF1. Baz
- Baz
Considerations
This section details privacy, accessibility and ethical considerations.
Privacy Considerations
This section is non-normative.
Accessibility Considerations
This section is non-normative.
Ethical Considerations
This section is non-normative.
References
Informative References
- [ETHICAL-WEB]
- W3C TAG Ethical Web Principles. Daniel Appelquist; Hadley Beeman. W3C. 27 October 2020. TAG Finding. URL: https://www.w3.org/2001/tag/doc/ethical-web-principles/
- [RFC3986]
- Uniform Resource Identifier (URI): Generic Syntax. T. Berners-Lee; R. Fielding; L. Masinter. IETF. January 2005. Internet Standard. URL: https://datatracker.ietf.org/doc/html/rfc3986
- [RFC6454]
- The Web Origin Concept. A. Barth. IETF. December 2011. Proposed Standard. URL: https://datatracker.ietf.org/doc/html/rfc6454
- [RFC7231]
- Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content. R. Fielding, Ed.; J. Reschke, Ed.. IETF. June 2014. Proposed Standard. URL: https://httpwg.org/specs/rfc7231.html
- [SOLID-PROTOCOL]
- Solid Protocol. Sarven Capadisli; Tim Berners-Lee; Ruben Verborgh; Kjetil Kjernsmo; Justin Bingham; Dmitri Zagidulin. W3C Solid Community Group. W3C Editor’s Draft. URL: https://solidproject.org/TR/protocol
- [WEBARCH]
- Architecture of the World Wide Web, Volume One. Ian Jacobs; Norman Walsh. W3C. 15 December 2004. W3C Recommendation. URL: https://www.w3.org/TR/webarch/


Description
1 RULES OF PROCEDURE
• This event is for a group of 3-4 people, and hence you are required to register as a
group. In case, you don’t have one already, we will make one for you don’t worry!
• This is a two-tier event wherein the first one is an elimination round which builds up
to the finale.
• The first round will consist of a situation which shall be read out to you by the
narrator, which shall end on an open but directive note.
• Students will have to suggest a solution (pathway) on how to move forward in that
situation and pen it down. Then all teams will read out their written responses, and
the judges will eliminate the at least
• The same process mentioned in point 4 will be reiterated thrice and a final of 6-7
teams move to the next and final round.
• This round will now consist of a monologue type narration by a speaker which may
either be cryptic or mysterious or something open-ended
• Now each team will be allowed to privately ask the narrator 3 questions which can
be very open-ended or irrelevant or just about anything related to the narration and
we promise you’ll get an interesting/creative answer from the narrator. Make note
that no clarification/repetition/explanation of any part of narration will be given
• Now, once the narrator has visited all the teams and all questions have been
answered. You will be given a 10 minute discussion time for mapping out and
discussing your plot with your teammates in which no writing will be allowed. Then
in the next 45 minutes you’re supposed to write down the piece in the most
interesting way you can and submit the paper.
2 JUDGING CRITERIA
• Creativity
• Vocabulary
• Content
• Deviation/Introduction of new elements (-ve)
• Grammatical errors (-ve)
• Problem Tackling skills
3 TERMS AND CONDITIONS
• Registration of the event should be for a group of 2-4
• In case, you cannot form one yourself, register individually, we’ll make one for you
• English shall be the official working language of the whole event.
• No use of electronic devices shall be permitted during the event
• Any judgement delivered shall be final and binding, this is not subject to debate
• Each team will be provided with sheets and pens
• Rounds: Elimination and Finals
• Strict silence is mandatory during any narration and any unruly behaviour regarding
this will result in disqualification of the team
• Obscene or discriminatory content is forbidden


Farm insurance allows you to take out a policy which could cover you farm, farm equipment, land, crop, farm structures and so forth. A ‘farm’ is typically that which has over 500 acres of land. You may want into inquire further with our agents to help you figure out if you qualify for a ‘farm’ policy or an ‘estate/hobby’ policy. You can read more about 'estate/hobby' qualifications below.
Estate/Hobby Farm insurance allows you to more specifically cover your assets that some homeowners insurance policies won’t cover. If you don’t farm, but you own a barn - this may be when you’d want to checkout an ‘estate/hobby’ policy. These typically are farms or land typically less than 500 acres. You may want into inquire further with our agents to help you figure out if you qualify for a ‘estate/hobby’ policy or an ‘farm’ policy. You can read more about ‘farm’ policies above.


|
ibisami
0.8
Public domain IBIS-AMI model creation infrastructure.
|
An example device specific Rx model implementation. More...
Public Member Functions | |
| MyRx () | |
| Constructor. More... | |
| ~MyRx () | |
| Destructor. More... | |
| void | init (double *impulse_matrix, const long number_of_rows, const long aggressors, const double sample_interval, const double bit_time, const std::string &AMI_parameters_in) override |
| Initializer. More... | |
| Public Member Functions inherited from AmiRx | |
| AmiRx () | |
| virtual | ~AmiRx () |
| void | init (double *impulse_matrix, const long number_of_rows, const long aggressors, const double sample_interval, const double bit_time, const std::string &AMI_parameters_in) override |
| Initializer. More... | |
| void | proc_imp () override |
| Override of AMIModel::proc_imp() specific to Rx models. More... | |
| bool | proc_sig (double *sig, long len, double *clock_times) override |
| Override of AMIModel::proc_sig() specific to Rx models. More... | |
| Public Member Functions inherited from AMIModel | |
| virtual | ~AMIModel () |
| std::string & | msg () |
| Retrieve the model message. More... | |
| std::string & | param_str () |
| Retrieve the model parameter string. More... | |
Additional Inherited Members | |
| Protected Member Functions inherited from AMIModel | |
| ParseRes | parse_params (const std::string &AMI_parameters_in) |
| Parse the incoming AMI parameter string. More... | |
| std::string | get_param (const std::vector< std::string > &node_names) const |
| Get the string value of a parameter. More... | |
| long | get_param_int (const std::vector< std::string > &node_names, long default_val) const |
| Get the value of an integer parameter. More... | |
| double | get_param_float (const std::vector< std::string > &node_names, double default_val) const |
| Get the value of a floating point parameter. More... | |
| bool | get_param_bool (const std::vector< std::string > &node_names, bool default_val) const |
| Get the value of a Boolean parameter. More... | |
| void | gen_data (double *res_vec) |
| Generate random binary oversampled data. More... | |
| void | log (std::string msg) |
| Protected Attributes inherited from AmiRx | |
| DigitalFilter * | ctle_ |
| DFE * | dfe_ |
| std::ofstream | dfe_dump_stream_ |
| std::ofstream | dfe_input_stream_ |
| bool | dump_dfe_adaptation_ |
| bool | dump_adaptation_input_ |
| std::string | dfe_dump_file_ |
| std::string | dfe_input_file_ |
| int | sig_tap_ |
| int | init_adapt_tap_ |
| Protected Attributes inherited from AMIModel | |
| std::string | msg_ |
| std::string | param_str_ |
| std::string | name_ |
| double | sample_interval_ |
| double | bit_time_ |
| double * | impulse_matrix_ |
| double | gen_data_last_ |
| long | number_of_rows_ |
| long | aggressors_ |
| long | samples_per_bit_ |
| unsigned long | gen_data_cnt_ |
| ibisami::ParamTree | param_tree_ |
| std::ofstream | clog_ |
| bool | log_ |
| int | shift_reg_ [PRBS_LEN] |
An example device specific Rx model implementation.
Definition at line 21 of file example_rx.cpp.
|
inline |
Constructor.
Definition at line 26 of file example_rx.cpp.
|
inline |
Destructor.
Definition at line 29 of file example_rx.cpp.
|
inlineoverridevirtual |