Tag Archives: Java

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) {
}

 

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) {
}

 

HiLighting words in a JTextPane

Introduction

This example shows how text can be HiLighted in the text of a JTextPane.

JTextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();

// Makes text red
Style style = textPane.addStyle("Red", null);
StyleConstants.setForeground(style, Color.red);

// Inherits from "Red"; makes text red and underlined
style = textPane.addStyle("Red Underline", style);
StyleConstants.setUnderline(style, true);

// Makes text 24pts
style = textPane.addStyle("24pts", null);
StyleConstants.setFontSize(style, 24);

// Makes text 12pts
style = textPane.addStyle("12pts", null);
StyleConstants.setFontSize(style, 12);

// Makes text italicized
style = textPane.addStyle("Italic", null);
StyleConstants.setItalic(style, true);

// A style can have multiple attributes; this one makes text bold and italic
style = textPane.addStyle("Bold Italic", null);
StyleConstants.setBold(style, true);
StyleConstants.setItalic(style, true);

// Set text in the range [5, 7) red
doc.setCharacterAttributes(5, 2, textPane.getStyle("Red"), true);

// Italicize the entire paragraph containing the position 12
doc.setParagraphAttributes(12, 1, textPane.getStyle("Italic"), true);

 

Creating a password field in Java



Introduction

JPasswordField is the Swing Password in Java. Just like the other javax.swing Components it’s a JavaBean. Here’s how to implement it:

JPasswordField textfield = new JPasswordField("Initial Text");
textfield.setEchoChar('#');
textfield.addActionListener(actionListener);

 

Centering the Screen

Introduction

This example shows how a Swing Window Object  can be centered on the screen. Note that the Window Object doesn’t have a CENTER method of its own so you need to implement the logic yourself.

// Get the size of the screen
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

// Determine the new location of the window
int w = window.getSize().width;
int h = window.getSize().height;
int x = (dim.width-w)/2;
int y = (dim.height-h)/2;

// Move the window
window.setLocation(x, y);

 

HTTP Post from a socket



Introduction

Earlier on we already saw how to read from a Socket. This example shows how to do a HTTP POST. The HTTP post can take more data. Such as binary data.

This example can therefore be useful to post multiple documents to another program such as Apache Solr. Note that you also can do this with the UNIX / Linux cURL command

try {
    // Construct data
    String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
    data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");

    // Create a socket to the host
    String hostname = "hostname.com";
    int port = 80;
    InetAddress addr = InetAddress.getByName(hostname);
    Socket socket = new Socket(addr, port);

    // Send header
    String path = "/servlet/SomeServlet";
    BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));
    wr.write("POST "+path+" HTTP/1.0rn");
    wr.write("Content-Length: "+data.length()+"rn");
    wr.write("Content-Type: application/x-www-form-urlencodedrn");
    wr.write("rn");

    // Send data
    wr.write(data);
    wr.flush();

    // Get response
    BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
        // Process line...
    }
    wr.close();
    rd.close();
} catch (Exception e) {
}

 

Determining the selected file in the JFileChooser

Introduction

The JFileChooser is a Swing component to choose files from the FileSystem. After you chose a file (or Directory you need to get the selected file back in your code. This example shows how it’s done.

JFileChooser
JFileChooser
JFileChooser chooser = new JFileChooser();

// Set the current directory to the 
// application's current directory
try {
    // Create a File object containing the
    // canonical path of the
    // desired file
    File f = new File(new File("filename.txt").getCanonicalPath());

    // Set the selected file
    chooser.setSelectedFile(f);
} catch (IOException e) {
}

// Show the dialog; wait until dialog is closed
chooser.showOpenDialog(frame);

// Get the currently selected file
File curFile = chooser.getSelectedFile();