How do I get the last date of a month?

You want to know what is the last date for a current month. The code below show you how to get it.

package org.kodejava.util;

import java.util.Calendar;

public class LastDateOfMonth {
    public static void main(String[] args) {
        // Get a calendar instance
        Calendar calendar = Calendar.getInstance();

        // Get the last date of the current month. To get the last date for 
        // a specific month you can set the calendar month using calendar 
        // object calendar.set(Calendar.MONTH, theMonth) method.
        int lastDate = calendar.getActualMaximum(Calendar.DATE);

        // Print the current date and the last date of the month
        System.out.println("Date     : " + calendar.getTime());
        System.out.println("Last Date: " + lastDate);
    }
}

Here is the result of the code snippet:

Date     : Fri Sep 24 06:42:18 CST 2021
Last Date: 30

How do I convert day-of-the-year to date?

In the following example we want to get the date of the specified day-of-the-year. We can define a calendar for a specific day of the year by setting the java.util.Calendar object DAY_OF_YEAR field using the set() method. The method take the field to be set and a value.

package org.kodejava.util;

import java.util.Calendar;

public class DayOfYearToDate {
    public static void main(String[] args) {
        // In the example we want to get the date value of the specified
        // day of the year. Using the calendar object we can define our
        // calendar for a specific day of the year.
        int dayOfYear = 112;
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, dayOfYear);
        System.out.println("Day " + dayOfYear + " of the current year = "
                + calendar.getTime());

        // If you want to get the date for a specific day of year and for
        // a specific year, you can also pass the year information to the
        // calendar object.
        int year = 2020;
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.DAY_OF_YEAR, dayOfYear);
        System.out.println("Day " + dayOfYear + " in year " + year
                + " = " + calendar.getTime());
    }
}

And here is an example result of the code above:

Day 112 of the current year = Thu Apr 22 06:34:14 CST 2021
Day 112 in year 2020 = Tue Apr 21 06:34:14 CST 2020

How do I use JNDI to get database connection or data source?

package org.kodejava.jndi;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.Servlet;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name = "JNDITestServlet", urlPatterns = "/jndi-datasource-test")
public class JNDITestServlet extends HttpServlet implements Servlet {

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

        // This implementation of doGet method show us an example to use
        // conn obtained in the getConnection() method.
        DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");

        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();

        try (Connection connection = getConnection()) {
            // A query to get current date time from Oracle database
            String sql = "select current_timestamp() as SYSDATE";
            PreparedStatement statement = connection.prepareStatement(sql);
            ResultSet rs = statement.executeQuery();
            while (rs.next()) {
                Date date = rs.getTimestamp("SYSDATE");
                writer.println("The current date is " + format.format(date));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * Get a database connection from the registered data source in the
     * servlet container. To registered the JNDI data source you should
     * refer to your servlet container documentation.
     *
     * @return a database connection
     */
    private Connection getConnection() {
        Connection connection = null;
        try {
            InitialContext initialContext = new InitialContext();
            Context context = (Context) initialContext.lookup("java:/comp/env");
            DataSource dataSource = (DataSource) context.lookup("jdbc/DataSource");
            connection = dataSource.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }
}

Configure the JNDI DataSource in Tomcat conf/context.xml configuration file. And don’t forget to copy the JDBC driver library to Tomcat’s lib directory.

<?xml version="1.0" encoding="UTF-8"?>
<Context>
    ...
    <Resource name="jdbc/DataSource" auth="Container" type="javax.sql.DataSource"
               maxTotal="100" maxIdle="30" maxWaitMillis="10000"
               username="root" password="" driverClassName="com.mysql.cj.jdbc.Driver"
               url="jdbc:mysql://localhost:3306/kodejava"/>
    ...
</Context>

Maven dependencies

<dependencies>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
    </dependency>
</dependencies>

Maven Central

How can I get current working directory?

A system properties named user.dir can be used if you want to find the current working directory of your Java program.

package org.kodejava.io;

public class CurrentDirectoryExample {
    public static void main(String[] args) {
        // System property key to get current working directory.
        String USER_DIR_KEY = "user.dir";
        String currentDir = System.getProperty(USER_DIR_KEY);

        System.out.println("Working Directory: " + currentDir);
    }
}

Result example:

Working Directory: F:\Wayan\Kodejava\kodejava-example

How do I check if parameter is exists in servlet request?

ServletRequest or HttpServletRequest object has a map object that maps parameter name and its value. By accessing this map we can check if a parameter was passed in servlet request. Let’s see the example below.

package org.kodejava.servlet;

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 java.io.IOException;

@WebServlet(name = "ParameterCheck", urlPatterns = "/parameter-check")
public class ParameterCheck extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {

        // Check if username parameter exists
        if (req.getParameterMap().containsKey("username")) {
            String username = req.getParameter("username");
            System.out.println("username = " + username);
        }

        // Check if password parameter exists
        if (req.getParameterMap().containsKey("password")) {
            String password = req.getParameter("password");
            System.out.println("password = " + password);
        }
    }
}

Maven dependencies

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

Maven Central