Source code snippets (examples)

This is a list of Alvin Alexander's source code snippets (simple source code examples).

Source code for a Java SwingWorker with ProgressBar example (SwingWorker background thread)

Here's the source code for a Java SwingWorker with ProgressBar example from Sun:

/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Random;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;
public class ProgressBarDemo extends JPanel implements ActionListener,
    PropertyChangeListener {

  private JProgressBar progressBar;
  private JButton startButton;
  private JTextArea taskOutput;
  private Task task;

  class Task extends SwingWorker<Void, Void> {
    /*
     * Main task. Executed in background thread.
     */
    @Override
    public Void doInBackground() {
      Random random = new Random();
      int progress = 0;
      // Initialize progress property.
      setProgress(0);
      while (progress < 100) {
        // Sleep for up to one second.
        try {
          Thread.sleep(random.nextInt(1000));
        } catch (InterruptedException ignore) {
        }
        // Make random progress.
        progress += random.nextInt(10);
        setProgress(Math.min(progress, 100));
      }
      return null;
    }

    /*
     * Executed in event dispatching thread
     */
    @Override
    public void done() {
      Toolkit.getDefaultToolkit().beep();
      startButton.setEnabled(true);
      setCursor(null); // turn off the wait cursor
      taskOutput.append("Done!\n");
    }
  }

  public ProgressBarDemo() {
    super(new BorderLayout());

    // Create the demo's UI.
    startButton = new JButton("Start");
    startButton.setActionCommand("start");
    startButton.addActionListener(this);

    progressBar = new JProgressBar(0, 100);
    progressBar.setValue(0);
    progressBar.setStringPainted(true);

    taskOutput = new JTextArea(5, 20);
    taskOutput.setMargin(new Insets(5, 5, 5, 5));
    taskOutput.setEditable(false);

    JPanel panel = new JPanel();
    panel.add(startButton);
    panel.add(progressBar);

    add(panel, BorderLayout.PAGE_START);
    add(new JScrollPane(taskOutput), BorderLayout.CENTER);
    setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

  }

  /**
   * Invoked when the user presses the start button.
   */
  public void actionPerformed(ActionEvent evt) {
    startButton.setEnabled(false);
    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    // Instances of javax.swing.SwingWorker are not reusuable, so
    // we create new instances as needed.
    task = new Task();
    task.addPropertyChangeListener(this);
    task.execute();
  }

  /**
   * Invoked when task's progress property changes.
   */
  public void propertyChange(PropertyChangeEvent evt) {
    if ("progress" == evt.getPropertyName()) {
      int progress = (Integer) evt.getNewValue();
      progressBar.setValue(progress);
      taskOutput.append(String.format("Completed %d%% of task.\n", task
          .getProgress()));
    }
  }

  /**
   * Create the GUI and show it. As with all GUI code, this must run on the
   * event-dispatching thread.
   */
  private static void createAndShowGUI() {
    // Create and set up the window.
    JFrame frame = new JFrame("ProgressBarDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Create and set up the content pane.
    JComponent newContentPane = new ProgressBarDemo();
    newContentPane.setOpaque(true); // content panes must be opaque
    frame.setContentPane(newContentPane);

    // Display the window.
    frame.pack();
    frame.setVisible(true);
  }

  public static void main(String[] args) {
    // Schedule a job for the event-dispatching thread:
    // creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI();
      }
    });
  }
}

Scala, Scalatra, Gson, and JSON - Convert a JSON String to a Scala object with Gson

While working on a Scalatra web service recently, I decided to use JSON pass my data into a REST POST method, and within that POST method I decided to turn the JSON String back into an object using the Google Gson library. This was a little tricky, and kept throwing an exception until I realized that the Scalatra params.get method was returning a Scala Some reference instead of the plain String I was expecting.

Given that little bit of background, here's how I used the Gson library in my Scala/Scalatra project to convert a JSON String to a Scala object:

  /**
   * Use this Scala case class to give Gson a class/object to convert the JSON back into.
   */
  case class Dude(firstName: String, lastName: String, age: Int)

  /**
   * String looks like this:
   * 
   * {"firstName":"Leonard","lastName":"Nimoy","age":81}
   * 
   */
  post("/posttest") {
    val jsonString = params.get("JSON")
    try {
        println("CONVERTING JSON BACK TO OBJECT")
        val gson = new Gson
        // jsonString is actually a Some, need to use get() here
        val dude = gson.fromJson(jsonString.get, classOf[Dude])
        println("FNAME: " + dude.firstName)
        println("LNAME: " + dude.lastName)
    } catch {
        case e: Exception => e.printStackTrace
        case _ => println
    }
  }

Deserialize a JSON array using Gson, Scala, Scalatra, and a Scala case class

Here's an example of how I deserialize an array of objects encoded in JSON, in this case using Scalatra and Scala:

import scala.collection.JavaConversions._

/**
 * This method expects to receive Array[StickyNote].
 */
post("/saveStickyNote") {
  val json = params.get("STICKY_NOTE")
  val gson = new Gson
  try {

    // (1) convert the json string to an array of StickyNote
    val jsonString = json.get

    // (2) jsonString is actually a Some, need to use get() here (should also test for None)
    val stickyNotes = gson.fromJson(jsonString, classOf[Array[StickyNote]])

    // (3) do whatever you want with your object array
    for (stickyNote <- stickyNotes) {
      println("CONTENT: " + stickyNotes.content)
    }

  } catch {
    case e: Exception => e.printStackTrace
    case _ => println
  }
}

To get this to work, I've defined a StickyNote case class here on the server side, and Gson does a great job of converting properly formatted JSON into an array of StickyNote objects.

If you were using Gson with Java to deserialize a JSON array, your code would look very similar. The major change would be that your Java code in the gson.fromJson line would look something like this:

val stickyNotes = gson.fromJson(jsonString, StickyNote[].class)

I'm not sure what the exact syntax should be there, but I think that's right, or hopefully close enough to get you started if you're using Java.

A curl script to perform a POST to an HTTP web service using JSON data

You can use the following curl script to POST JSON data to a web service:

curl \
  --header "Content-type: application/json" \
  --request POST \
  --data '{"symbol":"GOOG","price":"600.00"}' \
  http://localhost:8080/stocks/saveJsonStock

If you're familiar with the curl command, and JSON web services, this should make sense.

Here are links to other curl shell scripts I've written:

For more information, see the (very long) curl man page.

A Sencha Touch 2 native dialog example

Source code for a Sencha Touch 2 native dialog:

Ext.device.Notification.show({
    title: 'One Button',
    message: 'This is a simple notification with one button.'
});

This example comes from this URL.

This is like an Ext.Msg dialog, but native instead. See http://docs.sencha.com/touch/2.2.1/#!/api/Ext.Msg for more information.

A Sencha Touch 2 List view with static data

Here's an example of a Sencha Touch 2 List view that's populated with static data:

Ext.create('Ext.List', {
    store: {
        fields: ['name'],
        data: [
            {name: 'Notes'},
            {name: 'To-Do List'},
            {name: 'Contacts'},
        ]
    },

    itemTpl: '{name}'
});

Something like this could be used for a list of data items, or menu items.

This example comes from this link.

Sencha Touch 2 example Store with static data

Here's a related example that shows how to populate a Sencha Touch 2 Store with static data:

Ext.create('Ext.data.Store', {
    model: 'User',
    data: [
        { firstName: 'Ed',    lastName: 'Spencer' },
        { firstName: 'Tommy', lastName: 'Maintz' },
        { firstName: 'Aaron', lastName: 'Conran' },
        { firstName: 'Jamie', lastName: 'Avins' }
    ]
});

It comes from this URL.

A Sencha Touch 2 Carousel example

Here's a quick Sencha Touch 2 Carousel example:

Ext.create('Ext.Carousel', {
    fullscreen: true,

    defaults: {
        styleHtmlContent: true
    },

    items: [
        {
            html : 'Item 1',
            style: 'background-color: #5E99CC'
        },
        {
            html : 'Item 2',
            style: 'background-color: #759E60'
        },
        {
            html : 'Item 3'
        }
    ]
});

It comes from this URL.

How to get a Drupal 7 custom form to work with Mollom

I just got a custom form in Drupal 7 to work with Mollom, and I wanted to share my source code here. I added the following code to the main module file (zenf.module) of my Drupal module:

function zenf_mollom_form_list() {
  $forms['organization_add'] = array(
    'title' => 'Form to add a new organization',
  );
  return $forms;
}

function zenf_mollom_form_info() {
  $form_info = array(
    'mode' => MOLLOM_MODE_CAPTCHA,
  );
  return $form_info;
}

This code adds the possibility of having a Mollom CAPTCHA form element on my custom form. I say "possibility" because after adding this code, you then need to configure Mollom as usual, in this case to protect my "Add a new organization" form. In Drupal 7, you configure a new form at the "/admin/config/content/mollom" URI of your website.

Drupal custom form Mollom CAPTCHA code

At this point, I just got this to work, so my code is very simple and basic. I may add more to it than this, but as shown, this code successfully adds a Mollom CAPTCHA widget to the form with the form_id "organization_add" in a custom Drupal module I've named "zenf".

As I understand it, as shown in the URL I've linked to, this is the correct way to integrate a custom Drupal form with Mollom, in this case always using the Mollom CAPTCHA approach. At least in my case, it doesn't make sense to use textual analysis, so I'm always invoking CAPTCHA.

You can see this form in action by clicking the "Add" button on the Zen Foundation Organization's List page.

A Scala 'send email' class (uses the JavaMail API)

Scala doesn't have any special email handling facilities, so I just use my normal Java approach to send mail.

Here's the source code for my Scala 'send email' class. It's basically just a port of my previous Java 'send email' class, and requires the Java Mail API and Activation Framework jar files:

import javax.mail._
import javax.mail.internet._
import java.util.Date
import java.util.Properties
import scala.collection.JavaConversions._

class MailAgent(to: String,
                cc: String,
                bcc: String,
                from: String,
                subject: String,
                content: String,
                smtpHost: String)
{
  var message: Message = null

  message = createMessage
  message.setFrom(new InternetAddress(from))
  setToCcBccRecipients

  message.setSentDate(new Date())
  message.setSubject(subject)
  message.setText(content)

  // throws MessagingException
  def sendMessage {
    Transport.send(message)
  }

  def createMessage: Message = {
    val properties = new Properties()
    properties.put("mail.smtp.host", smtpHost)
    val session = Session.getDefaultInstance(properties, null)
    return new MimeMessage(session)
  }

  // throws AddressException, MessagingException
  def setToCcBccRecipients {
    setMessageRecipients(to, Message.RecipientType.TO)
    if (cc != null) {
      setMessageRecipients(cc, Message.RecipientType.CC)
    }
    if (bcc != null) {
      setMessageRecipients(bcc, Message.RecipientType.BCC)
    }
  }

  // throws AddressException, MessagingException
  def setMessageRecipients(recipient: String, recipientType: Message.RecipientType) {
    // had to do the asInstanceOf[...] call here to make scala happy
    val addressArray = buildInternetAddressArray(recipient).asInstanceOf[Array[Address]]
    if ((addressArray != null) && (addressArray.length > 0))
    {
      message.setRecipients(recipientType, addressArray)
    }
  }

  // throws AddressException
  def buildInternetAddressArray(address: String): Array[InternetAddress] = {
    // could test for a null or blank String but I'm letting parse just throw an exception
    return InternetAddress.parse(address)
  }

}

I'll add an example that shows how to use this Scala email class at some point in the future, but I hope that's pretty obvious.

How to create and use multi-dimensional arrays (2D, 3D, etc.) in Scala

Here's a quick look at how to create a multi-dimensional array in Scala, in this case a 2D array (matrix), and then access the array elements. As you can see, these commands were issued using the Scala REPL, and I've added a few comments to them:

// create a 2D array
scala> val matrix = Array.ofDim[Int](2,2)
matrix: Array[Array[Int]] = Array(Array(0, 0), Array(0, 0))

// populate the array elements
scala> matrix(0)(0) = 0

scala> matrix(0)(1) = 1

scala> matrix(1)(0) = 2

scala> matrix(1)(1) = 3

// access a couple of array elements
scala> matrix(0)(1)
res4: Int = 1

scala> matrix(1)(0)
res5: Int = 2

If you ever need to create a multidimensional array in Scala, I hope this example is helpful.