Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Mike Wilson www.whisperingwind.co.uk

« Newer Snippets
Older Snippets »
Showing 1-10 of 17 total  RSS 

'ant' build file for HelloWorldServlet and JettyLauncher

A pretty straightforward 'ant' build file. You will need to edit the jetty.home property to indicate where you installed Jetty.

<?xml version="1.0" encoding="UTF-8"?>
<project basedir="." default="compile" name="hello-servlet">
  <property name="build.dir"	location="classes" />
  <property name="src.dir"	location="src/main/java" />
  <property name="jetty.home"	location="/home/mrw/projects/jetty-6.1.3" />
  <property name="jetty.lib"	location="${jetty.home}/lib" />

  <path id="jetty.lib.path">
    <pathelement path="${jetty.lib}/jetty-6.1.3.jar" />
    <pathelement path="${jetty.lib}/jetty-util-6.1.3.jar" />
    <pathelement path="${jetty.lib}/servlet-api-2.5-6.1.3.jar" />
  </path>

  <target name="compile" description="Compile the project">
    <mkdir dir="${build.dir}" />
    <javac debug="true" destdir="${build.dir}" srcdir="${src.dir}"
	classpathref="jetty.lib.path">
      <compilerarg value="-Xlint:unchecked" />
      <compilerarg value="-Xlint:deprecation" />
    </javac>
  </target>

  <target name="all"  depends="clean,compile"
      description="Recompile from scratch"/>

  <target name="server" depends="compile" description="Launch the server">
    <java classname="com.babblemind.JettyLauncher" fork="true"
	classpathref="jetty.lib.path">
      <classpath>
	<pathelement path="${build.dir}" />
      </classpath>
    </java>
  </target>

  <target name="clean" description="Delete all files created by compile">
    <delete dir="${build.dir}" />
    <delete dir="docs/api" />
  </target>
</project>

Minimal Java servlet

There is nothing particularly original here -- there are variations of this all over the place. This works nicely with my JettyLauncher class (see my other posts on DZone Snippets).


package com.babblemind;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class HelloWorldServlet extends HttpServlet{
    protected void doGet(HttpServletRequest httpServletRequest,
	HttpServletResponse httpServletResponse)
	    throws ServletException, IOException {

        httpServletResponse.setContentType("text/plain");
        PrintWriter out = httpServletResponse.getWriter();
        out.println("Hello World!");
        out.close();
    }
}

Minimal Jetty http server with Java servlet

This will start a Jetty http server with a single Java servlet at the root. See http://www.mortbay.org/ for Jetty downloads. This needs HelloWorldServlet from one of my other posts. Make life easier by downloading my ant build.xml as well.


package com.babblemind;

import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.ServletHolder;

public class JettyLauncher {
    public static void main(String[] args) throws Exception {
	Server server = new Server(8080);    
	Context root = new Context(server, "/", Context.SESSIONS);
	root.addServlet(new ServletHolder(new HelloWorldServlet()), "/*");
	server.start();
    }
}

php image from database using PEAR::DB

This fetches an image from a MySQL database (I know, a database may not be the best place to keep images). The image is sent to the web client as an image/jpeg.

<?php
require_once 'DB.php';

define('DB_SERVER', 'localhost');
define('DB_USER', 'php');
define('DB_PASS', '');
define('DB_DATABASE', 'images');
define('DSN', 'mysql://'.DB_USER.':'.DB_PASS.'@'.DB_SERVER.'/'.DB_DATABASE);

global $db;
$db = DB::connect(DSN);

if (PEAR::isError($db)) {
    die($db->getMessage());
}

if (isset($_GET['id'])) {
  header('Content-Type: image/jpeg');
  $id = $_GET['id'];
  $sql = "select image_data from images where id = ?";
  $result =& $db->query($sql, $id);

  if (PEAR::isError($result)) {
    die($result->getMessage());
  } else {
    if ($result->fetchInto($row)) {
      echo $row[0];
    }
  }

} else {
  echo file_get_contents('broken.png');
}
?>

Very simple php file upload

I think this is the minimum necessary to upload a file in php. First, the form, index.php:

<form enctype="multipart/form-data" action="upload.php" method="POST">
    <input type="hidden" name="MAX_FILE_SIZE" value="512000" />
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form>


Next, the php to accept the file, upload.php

<?php

$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo "<p>";

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
  echo "File is valid, and was successfully uploaded.\n";
} else {
   echo "Upload failed";
}

echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";

?> 

Add a jar file to Java load path at run time

Sometimes it is necessary to amend the class load path at run time. For example, dynamically adding jar files containing user-configurable JDBC data sources. The way this is done is truly monstrous -- the URL Path format was only revealed when a colleague looked into the Java library sources.

import java.net.URL;
import java.io.IOException;
import java.net.URLClassLoader;
import java.net.MalformedURLException;

public class JarFileLoader extends URLClassLoader
{
    public JarFileLoader (URL[] urls)
    {
        super (urls);
    }

    public void addFile (String path) throws MalformedURLException
    {
        String urlPath = "jar:file://" + path + "!/";
        addURL (new URL (urlPath));
    }

    public static void main (String args [])
    {
        try
        {
            System.out.println ("First attempt...");
            Class.forName ("org.gjt.mm.mysql.Driver");
        }
        catch (Exception ex)
        {
            System.out.println ("Failed.");
        }

        try
        {
            URL urls [] = {};

            JarFileLoader cl = new JarFileLoader (urls);
            cl.addFile ("/opt/mysql-connector-java-5.0.4/mysql-connector-java-5.0.4-bin.jar");
            System.out.println ("Second attempt...");
            cl.loadClass ("org.gjt.mm.mysql.Driver");
            System.out.println ("Success!");
        }
        catch (Exception ex)
        {
            System.out.println ("Failed.");
            ex.printStackTrace ();
        }
    }
}

Simple Ruby ActiveRecord example

Using Ruby ActiveRecord with an in-memory SQLite database. A nice simple example of this wonderful library.

require 'active_record'

ActiveRecord::Base.logger = Logger.new(STDERR)
ActiveRecord::Base.colorize_logging = false

ActiveRecord::Base.establish_connection(
    :adapter => "sqlite3",
    :dbfile  => ":memory:"
)

ActiveRecord::Schema.define do
    create_table :albums do |table|
        table.column :title, :string
        table.column :performer, :string
    end

    create_table :tracks do |table|
        table.column :album_id, :integer
        table.column :track_number, :integer
        table.column :title, :string
    end
end

class Album < ActiveRecord::Base
    has_many :tracks
end

class Track < ActiveRecord::Base
    belongs_to :album
end

album = Album.create(:title => 'Black and Blue',
    :performer => 'The Rolling Stones')
album.tracks.create(:track_number => 1, :title => 'Hot Stuff')
album.tracks.create(:track_number => 2, :title => 'Hand Of Fate')
album.tracks.create(:track_number => 3, :title => 'Cherry Oh Baby ')
album.tracks.create(:track_number => 4, :title => 'Memory Motel ')
album.tracks.create(:track_number => 5, :title => 'Hey Negrita')
album.tracks.create(:track_number => 6, :title => 'Fool To Cry')
album.tracks.create(:track_number => 7, :title => 'Crazy Mama')
album.tracks.create(:track_number => 8,
    :title => 'Melody (Inspiration By Billy Preston)')

album = Album.create(:title => 'Sticky Fingers',
    :performer => 'The Rolling Stones')
album.tracks.create(:track_number => 1, :title => 'Brown Sugar')
album.tracks.create(:track_number => 2, :title => 'Sway')
album.tracks.create(:track_number => 3, :title => 'Wild Horses')
album.tracks.create(:track_number => 4,
    :title => 'Can\'t You Hear Me Knocking')
album.tracks.create(:track_number => 5, :title => 'You Gotta Move')
album.tracks.create(:track_number => 6, :title => 'Bitch')
album.tracks.create(:track_number => 7, :title => 'I Got The Blues')
album.tracks.create(:track_number => 8, :title => 'Sister Morphine')
album.tracks.create(:track_number => 9, :title => 'Dead Flowers')
album.tracks.create(:track_number => 10, :title => 'Moonlight Mile')

puts Album.find(1).tracks.length
puts Album.find(2).tracks.length

puts Album.find_by_title('Sticky Fingers').title
puts Track.find_by_title('Fool To Cry').album_id

Very simple script using Dojo widget and I/O

Dojo is a Java Script toolkit. This is a minimal HTML page which uses a widget and talks to the server. This is based on the Dojo tutorial at JotSpot.

<html>
<head>
  <title>Dojo: Hello World!</title>

  <script type="text/javascript" src="/js/dojo/dojo.js"></script>

  <script type="text/javascript">
    dojo.require("dojo.event.*");
    dojo.require("dojo.widget.*");
    dojo.require("dojo.widget.Button");

    function helloPressed()
    {
        dojo.io.bind({
                       url: '/cgi-bin/HelloWorldResponsePOST.rb',
                       handler: helloCallback,
                       formNode: dojo.byId('myForm')
                    });
    }

    function init()
    {
      var helloButton = dojo.widget.byId('helloButton');
      dojo.event.connect(helloButton, 'onClick', 'helloPressed')
    }

    function errorCallback(type, error)
    {
        alert(error)
    }

    function helloCallback(type, data, evt)
    {
      if (type == 'error')
        alert('Error when retrieving data from the server!');
      else
        alert(data);
    }

    dojo.addOnLoad(init);
  </script>
</head>

<body>
  <button dojoType="Button" widgetId="helloButton">Hello World!</button>
  <br>

  <form id="myForm" method="POST">
    Please enter your name: <input type="text" name="name">
  </form>

</body>
</html>

Very basic lighttpd configuration

The configuration of lighttpd is vast and complex. Here is a close to minimal configuration which allows for Perl and Ruby CGI.

server.document-root = "/opt/lighttpd/htdocs"

server.port = 3000

mimetype.assign = (
  ".html" => "text/html",
  ".txt" => "text/plain",
  ".jpg" => "image/jpeg",
  ".png" => "image/png"
)

static-file.exclude-extensions = ( ".rb", ".pl", ".fcgi", ".php", ".rb", "~", ".inc" )
index-file.names = ( "index.html" )
server.modules += ( "mod_cgi" )

cgi.assign = (  ".rb" => "/opt/ruby/bin/ruby",
                ".pl" => "/usr/bin/perl")

Very basic Ruby XML parse

Tiny code fragment which loads configuration options from an XML file.

require "rexml/document"

doc = REXML::Document.new File.new("dbiconfig.xml")
configuration = doc.elements["configuration"]
database = configuration.elements["database"]
url = database.elements["url"].attributes["value"]
puts url
« Newer Snippets
Older Snippets »
Showing 1-10 of 17 total  RSS