Tag Archives: Java

Getting the http Request Parameters in a Servlet

Introduction

The implicit HttpServlet interface comes with two methods which must be implemented.  These are doGet(HttpServletRequest req, HttpServletResponse res) and doPost(HttpServletRequest req, HttpServletResponse res). The example below shows how to get both.

// See also The HttpServlet

// This method is called by the servlet container to process a GET request.
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    doGetOrPost(req, resp);
}

// This method is called by the servlet container to process a POST request.
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    doGetOrPost(req, resp);
}

// This method handles both GET and POST requests.
private void doGetOrPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Get the value of a request parameter; the name is case-sensitive
    String name = "param";
    String value = req.getParameter(name);
    if (value == null) {
        // The request parameter 'param' was not present in the query string
        // e.g. http://hostname.com?a=b
    } else if ("".equals(value)) {
        // The request parameter 'param' was
       // present in the query string but has no
       // value
       // e.g. http://hostname.com?param=&a=b
    }

    // The following generates a page showing all
    // the request parameters
    PrintWriter out = resp.getWriter();
    resp.setContentType("text/plain");

    // Get the values of all request parameters
    Enumeration enum = req.getParameterNames();
    for (; enum.hasMoreElements(); ) {
        // Get the name of the request parameter
        name = (String)enum.nextElement();
        out.println(name);

        // Get the value of the request parameter
        value = req.getParameter(name);

        // If the request parameter can appear
        // more than once in the query string,
        // get all values
        String[] values =
        req.getParameterValues(name);

        for (int i=0; i<values.length; i++) {
            out.println("    "+values[i]);
        }
    }
    out.close();
}

 

Creating a Temp File

Introduction

Every Operating System has it’s own location for storing temporary files. In UNIX/Linux this is /tmp. In Windows it’s C:\temp.

The example below shows how it can be done in the (platform independent way with Java:

try {
    // Create temp file.
    File temp = File.createTempFile("pattern", ".suffix");

    // Delete temp file when program exits.
    temp.deleteOnExit();

    // Write to temp file
    BufferedWriter out = new BufferedWriter(new FileWriter(temp));
    out.write("aString");
    out.close();
} catch (IOException e) {
}

 

Getting the Manifest of a Jar file.

Introduction

JAR files support a wide range of functionality, including electronic signing, version control, package sealing, and others. What gives a JAR file this versatility? The answer is the JAR file’s manifest.

The manifest is a special file that can contain information about the files packaged in a JAR file. By tailoring this “meta” information that the manifest contains, you enable the JAR file to serve a variety of purposes.

This example  will explain the contents of the manifest file and show you how to work with it, with examples for the basic features.

For more information about the MANIFEST See https://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html

try {
    // Open the JAR file
    JarFile jarfile = new JarFile("filename.jar");

    // Get the manifest
    Manifest manifest = jarfile.getManifest();

    // Get the manifest entries
    Map map = manifest.getEntries();

    // Enumerate each entry
    for (Iterator it=map.keySet().iterator(); it.hasNext(); ) {
        // Get entry name
        String entryName = (String)it.next();

        // Get all attributes for the entry
        Attributes attrs = (Attributes)map.get(entryName);

        // Enumerate each attribute
        for (Iterator it2=attrs.keySet().iterator(); it2.hasNext(); ) {
            // Get attribute name
            Attributes.Name attrName = (Attributes.Name)it2.next();

            // Get attribute value
            String attrValue = attrs.getValue(attrName);
        }
    }
} catch (IOException e) {
}

 

Setting Cookies

Introduction

An HTTP cookie (also called web cookie, Internet cookie, browser cookie, or simply cookie) is a small piece of data sent from a website and stored on the user’s computer by the user’s web browser while the user is browsing. Cookies were designed to be a reliable mechanism for websites to remember stateful information (such as items added in the shopping cart in an online store) or to record the user’s browsing activity (including clicking particular buttons, logging in, or recording which pages were visited in the past). They can also be used to remember arbitrary pieces of information that the user previously entered into form fields such as names, addresses, passwords, and credit card numbers. To set a cookie in a JSP, the following code is used:

Set-Cookie: cookie-value; expires=date; path=path; domain=domain-name; secure

 

Creating Mandelbrot graphics



Introduction

You probably have seen Mandelbrot graphics. Mandelbrot graphics have taken a huge flight the last years. Especially in animated movies like the ones from pixar studio’s.

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.*;

// Instantiate this class and then use the draw()
// method to draw the generated on the graphics
// context.
public class  {
    // Holds the generated image
    Image image;

    // 16-color model; this method is defined in
    // Creating an Image from an Array of Color-
    // Indexed Pixel Values
    ColorModel colorModel = generateColorModel();
    public (int width, int height) {
        // Initialize with default location
     this(width, height, new
     Rectangle2D.Float(-2.0f, -1.2f, 3.2f,
     2.4f));
   }

    public (int width, int height,
    Rectangle2D.Float loc) {
     //Generate the pixel data; this method is
     //defined in
        // Creating an Image from an Array of
        // Color-Indexed Pixel Values
        byte[] pixels = generatePixels(width,
        height, loc);

        // Create a data buffer using the byte
        // buffer of pixel data.
        // The pixel data is not copied; the data
        // buffer uses the byte buffer array.
        // DataBuffer dbuf = new
        DataBufferByte(pixels, width*height, 0);

        // The number of banks should be 1
        int numBanks = dbuf.getNumBanks(); // 1

        // Prepare a sample model that specifies
        // a storage 4-bits of
        // pixel datavd in an 8-bit data element
        // int bitMasks[] = new int[]{(byte)0xf};
        SampleModel sampleModel = new
        SinglePixelPackedSampleModel(
        DataBuffer.TYPE_BYTE, width, height,
        bitMasks);

        // Create a raster using the sample model
        // and data buffer
        WritableRaster raster = 
        Raster.createWritableRaster(sampleModel,
        dbuf, null);

        // Combine the color model and raster
        // into a buffered image
        image = new BufferedImage(colorModel,
        raster, false, 
        null);//newjava.util.Hashtable());
    }

    public void draw(Graphics g, int x, int y) {
        g.drawImage(image, x, y, null);
    }
}

 

Exiting from your program

Introduction

If you need to exit from a running program, you can do it with the System.exit() command. The parameter of exit should qualify if the execution of the program went good or bad. It’s a sort of heredity from older programming languages where it’s useful to know if something went wrong and what went wrong.

// No errors
int errorCode = 0;

// An error occurred
errorCode = -1;

// Terminate
System.exit(errorCode);

 

Listing all Threads in an Application

Introduction

Java allows multi threading. A good technique to make Applications run faster and can handle more tasks at the same time. In some cases you want to keep track on the number of active threads. The example below shows how to get an overview of all active threads.

// Find the root thread group
ThreadGroup root = Thread.currentThread().getThreadGroup().getParent();
while (root.getParent() != null) {
    root = root.getParent();
}

// Visit each thread group
visit(root, 0);

// This method recursively visits all thread groups under `group'.
public static void visit(ThreadGroup group, int level) {
    // Get threads in `group'
    int numThreads = group.activeCount();
    Thread[] threads = new Thread[numThreads*2];
    numThreads = group.enumerate(threads, false);

    // Enumerate each thread in `group'
    for (int i=0; i<numThreads; i++) {
        // Get thread
        Thread thread = threads[i];
    }

    // Get thread subgroups of `group'
    int numGroups = group.activeGroupCount();
    ThreadGroup[] groups = new ThreadGroup[numGroups*2];
    numGroups = group.enumerate(groups, false);

    // Recursively visit each subgroup
    for (int i=0; i<numGroups; i++) {
        visit(groups[i], level+1);
    }
}

 

Reading from a file

Introduction

Similar to writing to files we can also read from a file. This is done as follows:

try {
    BufferedReader in = new BufferedReader(new FileReader("infilename"));
    String str;
    while ((str = in.readLine()) != null) {
        process(str);
    }
    in.close();
} catch (IOException e) {
}

Please note the similarities between writing. The only difference is that here the FileReader is used in stead of the FileWriter.

Formatting Dates and Times depending of the location

Introduction

We already saw the DateFormat. This example shows how to set the format depending on the location.

// Format
Locale locale = Locale.ITALIAN;
Date date = new Date();

String s = DateFormat.getTimeInstance(DateFormat.SHORT, locale).format(date);
// 22.33

s = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale).format(date);
// 22.33.03

s = DateFormat.getTimeInstance(DateFormat.LONG, locale).format(date);
// 22.33.03 PST

s = DateFormat.getTimeInstance(DateFormat.FULL, locale).format(date);
// 22.33.03 PST

s = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale).format(date);
// 22.33.03

// Parse
try {
    date = DateFormat.getTimeInstance(
        DateFormat.DEFAULT, locale).parse("22.33.03");
} catch (ParseException e) {
}