tag:blogger.com,1999:blog-3292552327718551432024-03-13T14:40:45.513-05:00Travis DazellI wanted a place to create random jabberings about software topics I'm working on. You'll find posts about software architecture, Java, web development, DSL development, language implementation, etc.travisdazellhttp://www.blogger.com/profile/18318464927126013291noreply@blogger.comBlogger53125tag:blogger.com,1999:blog-329255232771855143.post-41433351300835282702015-06-30T00:23:00.001-05:002015-06-30T00:34:58.087-05:00Android ListView ExampleHere's a very simple example to get you started with an Android ListView. This example just displays a hard-coded list of colors in a ListView control. The key components are the ArrayAdapter and the additional layout file.<br />
<br />
ListViews work via an adapter pattern. So, we have to create an adapter that lists the items that we're going to display in the ListView. We also have to create a layout with the type of entity that we're displaying for each item in the ListView. In this example, each item in the ListView will be a simple TextView. However, it could be something more involved (like an image).<br />
<br />
<br />
<b>res/layout/activity_main.xml :</b><br />
<br />
<pre class="prettyprint"><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<ListView
android:id="@+id/list_of_colors"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="20sp" />
</RelativeLayout>
</pre>
<br />
<br />
<b>res/layout/listview_item.xml :
</b><br />
<br />
<pre class="prettyprint"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView android:id="@+id/color_item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp" />
</LinearLayout>
</pre>
<br />
<b>src/{package-name}/MainActivity.java :</b><br />
<br />
<pre class="prettyprint">public class MainActivity extends Activity {
private final String[] COLORS = new String[] { "Red", "Orange",
"Yellow", "Green", "Blue", "Indigo", "Violet" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter<string> adapter = new ArrayAdapter<string>(this, R.layout.listview_item,
R.id.color_item, COLORS);
ListView lv = (ListView) findViewById(R.id.list_of_colors);
lv.setAdapter(adapter);
}
}
</string></string></pre>
<br />
I put this code on GitHub for you to reference: <a href="https://github.com/travisdazell/android-listview-example">https://github.com/travisdazell/android-listview-example</a>travisdazellhttp://www.blogger.com/profile/18318464927126013291noreply@blogger.com0tag:blogger.com,1999:blog-329255232771855143.post-66368881646787559322015-06-28T22:58:00.002-05:002015-06-30T00:24:02.412-05:00Android ExamplesHere is a list of Android examples that I've put together. I will continue adding to it over time.<br />
<br />
<ul>
<li>Android Basics</li>
</ul>
<ul><ul>
<li><a href="http://travisdazell.blogspot.com/2015/01/android-development-hello-world.html">Android Hello World Example</a></li>
</ul>
</ul>
<ul><ul>
<li><a href="http://travisdazell.blogspot.com/2015/06/android-listview-example.html">Android ListView Example</a></li>
</ul>
</ul>
<ul>
<ul>
<li><a href="http://travisdazell.blogspot.com/2015/06/android-starting-new-activity-explicit.html">Explicit Intent Example (to start a new activity</a>)</li>
</ul>
</ul>
<ul><ul>
<li><a href="http://travisdazell.blogspot.com/2015/01/android-implicit-intents.html">Implicit Intent Example</a></li>
</ul>
</ul>
<ul>
<li>Android Concurrency</li>
</ul>
<ul><ul>
<li><a href="http://travisdazell.blogspot.com/2015/06/android-asynctask-example.html">AsyncTask Example</a></li>
</ul>
</ul>
travisdazellhttp://www.blogger.com/profile/18318464927126013291noreply@blogger.com0tag:blogger.com,1999:blog-329255232771855143.post-43077436009048024442015-06-28T22:53:00.000-05:002015-06-28T22:54:08.938-05:00Android - Starting a New Activity - Explicit IntentIn Android, each screen or presentation is done via its own activity. So, we will have a main activity that runs when the application is first started. Launching a new activity is simple, using an explicit intent.<br />
<br />
Let's say that we have a button that launches a new activity when it's clicked. Here's the code for doing this, using an explicit intent.<br />
<br />
<pre class="prettyprint">
public void openOtherActivityClick(View view) {
// create an explicit intent and specify
// the exact class name of the activity that we want
Intent otherActivityIntent = new Intent(this, OtherActivity.class);
// start the other activity
startActivity(otherActivityIntent);
}
</pre>
<br />
With an explicit intent, we specify the exact class name of the activity that we want to start. Another way to start an activity, is with an implicit intent. Here's an example of how to use an implicit intent: <a href="http://travisdazell.blogspot.com/2015/01/android-implicit-intents.html">http://travisdazell.blogspot.com/2015/01/android-implicit-intents.html</a><br />
<br />travisdazellhttp://www.blogger.com/profile/18318464927126013291noreply@blogger.com1tag:blogger.com,1999:blog-329255232771855143.post-90992026072137400492015-06-24T22:44:00.002-05:002015-06-24T22:44:50.227-05:00Android AsyncTask ExampleOften times, you will need to run an operation in the background of your Android app, so that you're not blocking the UI thread. For short running operations, AsyncTask is the perfect tool for the job. The best part is that it's very easy to use.<br />
<br />
Let's consider an app that takes an image and adjusts the contrast of the image to make it brighter. By clicking a button in the app, a predefined image is made brighter and then displayed on the screen. To implement the image contrast functionality, let's pretend that we've already written a Java class called <b>ImageUtils</b> that contains a method called <b>setContrast</b><i>. </i>The signature for this method looks like this:<br />
<br />
<pre class="prettyprint">public Bitmap setContrast(Bitmap image, double contrastValue);
</pre>
<br />
Naively, we could call this method within our button's <b>onClickListener</b>. However, if we do that, then while the image is being manipulated, we will block the UI thread and cause the application to "freeze". So, we can use AsyncTask to perform this image manipulation in the background!<br />
<br />
Here's a naive approach to processing the image, within the button's <b>onClickListener</b>:
<br />
<br />
<pre class="prettyprint">public void onClickListener(View target) {
// get the Android icon bitmap that's included in this project
Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
ImageUtils imageConverter = new ImageUtils();
Bitmap result = imageConverter.setContrast(originalBitmap, CONTRAST_VALUE);
ivAndroidIcon.setImageBitmap(result);
}
</pre>
<br />
Thankfully, to use AsyncTask, all that's needed is for us to create a new Java class that extends AsyncTask. Within this class, we'll call our setContrast method. In a sense, we're simply wrapping our current image logic with a class that extends AsyncTask. Pretty simple indeed! Here's how this new class looks:<br />
<br />
<pre class="prettyprint">class BrightenImageTask extends AsyncTask<Bitmap, Void, Bitmap> {
@Override
protected Bitmap doInBackground(Bitmap... params) {
// create a new image that's much brighter than the original image
ImageUtils imageConverter = new ImageUtils();
return imageConverter.setContrast(params[0], CONTRAST_VALUE);
}
@Override
protected void onPostExecute(Bitmap result) {
// display the updated image
ivAndroidIcon.setImageBitmap(result);
}
}
</pre>
<br />
Now that we have our image processing logic inside an AsyncTask, we can modify our button's onClickListener to call our AsyncTask:<br />
<br />
<pre class="prettyprint">public void onClickListener(View target) {
// get the Android icon bitmap that's included in this project
Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
new BrightenImageTask().execute(originalBitmap);
}
</pre>
<br />
There are a couple things to note about AsyncTask:
<br />
<ol>
<li>The generic types that are defined on our AsyncTask class are specifying that a Bitmap is passed into the doInBackground method and a Bitmap is returned by our onPostExecute method.</li>
<li>The VOID type specifies the type that's used to as the unit of progress for the background operation. I didn't use a "progress indicator" in this example, but this is where you would do this type of indication. You could specify this as an Integer and then override the method onProgressUpdate(Integer... progress) to set a progress indicator.</li>
</ol>
If you really want to get an appreciation for AsyncTask, you can add a <b>Thread.sleep(5000)</b> inside your <b>doInBackground </b>method. You'll notice that you can still click around on the screen while the operation is happening in the background. If instead, you put the image processing logic directly inside the button's onClickListener, you will find that the screen becomes non-responsive while the image is being processed (namely that the button remains depressed and it's obvious that the UI is blocked).<br />
<br />
So, next time you need to quickly make an operation run in the background, consider using AsyncTask. Note that this works great for operations that only take a few seconds to complete. However, if you have long running operations, you should consider using an Android service. This is because AsyncTask processes are still connected to the activity stack that executed the AsyncTask. As all of us Android developers know, the Android OS could decide to kill your activity at any time, if the OS needs to recover system resources. This could leave your background task in an unknown state. If you have a long running process, you'll want to use a service that continues to run, just in case your activity is shut down for some unplanned reason.<br />
<br />
For reference, I've placed all of the source code for this application on GitHub: <a href="https://github.com/travisdazell/asynctask-example">https://github.com/travisdazell/asynctask-example</a>travisdazellhttp://www.blogger.com/profile/18318464927126013291noreply@blogger.com0tag:blogger.com,1999:blog-329255232771855143.post-39972471413180175642015-01-24T21:06:00.002-06:002015-06-28T22:41:22.932-05:00Android Implicit IntentsThere are times that you want to utilize another application on the Android device for some action in your application. For example, let's say you have an application that opens a browser and navigate to a web site. You wouldn't want to build your own browser (most likely anyway), so you'd just let the Android device choose an application to use for navigating to the web site. When you do this, you're using an implicit intent. Here's how you do it.<br />
<br />
<pre class="prettyprint">private void navigateToWebSite() {
// Create an intent for viewing a specific web site
Uri google = Uri.parse("http://developer.android.com");
Intent intent = new Intent(Intent.ACTION_VIEW, google);
// Create a chooser intent
Intent chooserIntent = Intent.createChooser(intent, "Browse with...");
// Start the chooser activity
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(chooserIntent);
}
}
</pre>
<br />
The chooserIntent is optional. I'm using it to add a custom title to the chooser dialog. You can simply create the intent and call "startActivity(intent)" and let Android display the standard chooser dialog.<br />
<br />
In this example, we just told Android to include any application that can handle the ACTION_VIEW intent. What if you have written your own application that you want to include as an option for handling this type of intent? In your application's AndroidManifest.xml file, you simply add an intent-filter within the definition of the activity.<br />
<br />
For example, here I've added a second intent-filter to handle any applications that initiates an intent on the Intent.ACTION_VIEW with "http" requests, just like in the example above.<br />
<br />
<pre class="prettyprint"><activity android:label="@string/app_name" android:name=".MyOtherActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER">
</intent-filter>
<span style="font-family: Verdana,sans-serif;"><span style="font-size: small;"> <intent-filter>
<action android:name="android.intent.action.VIEW">
<category android:name="android.intent.category.DEFAULT">
<data android:scheme="http">
</intent-filter></span></span>
</activity>
</pre>
<br />
<br />travisdazellhttp://www.blogger.com/profile/18318464927126013291noreply@blogger.com0tag:blogger.com,1999:blog-329255232771855143.post-25945791774432167692015-01-19T20:25:00.001-06:002015-01-19T20:26:50.259-06:00Android - Handling Configuration Changes YourselfThere are many things that can happen outside of your Android application. One of the most common occurrences is a change in the device settings. For example, the user might leave your app running, while they go into the display settings and change the font size.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-Pa2RrIiXFfM/VL21HoadTAI/AAAAAAAAC2k/e6iPe8ufqGY/s1600/change-font-size.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Android Font Size Setting" border="0" src="http://1.bp.blogspot.com/-Pa2RrIiXFfM/VL21HoadTAI/AAAAAAAAC2k/e6iPe8ufqGY/s1600/change-font-size.png" height="320" title="" width="188" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
When the user goes back to your application, the activity in your application is recreated, which means onCreate() is called all over again. Most times, this is o.k. In fact, for the most part, you want to trust Android to handle these global settings and manage the effects of those changes to the lifecycle of your application's activities. However, there are times when you may want to manually handle these configuration changes. One obvious advantage to manually handling the config changes, is that you can avoid the activity being killed and recreated. Note that onStart(), onResume(), and onRestart() will still be called.<br />
<br />
To manually handle config changes, simply add the "android:configChanges" attribute to the activity in your Manifest file. For example:<br />
<br />
<activity<br />
<b>android:configChanges="fontScale"</b><br />
android:name="net.company.app.MainActivity"<br />
android:label="@string/app_name" ><br />
<br />
There's a listing of the configChanges defined here: <a href="http://developer.android.com/guide/topics/manifest/activity-element.html">http://developer.android.com/guide/topics/manifest/activity-element.html</a>.<br />
<br />
The next step, is to override the onConfigurationChanged() method in the activity, like this:<br />
<br />
<pre class="prettyprint lang-dart"> @Override
public void onConfigurationChanged(Configuration newConfig) {
Log.i(TAG, "newConfig.fontScale = " + newConfig.fontScale);
super.onConfigurationChanged(newConfig);
}
</pre>
<br />
<br />
When the font size changes in the device settings, your onConfigurationChanged() method is called and an object containing the new device configuration is passed to the method, for you to handle as you please.travisdazellhttp://www.blogger.com/profile/18318464927126013291noreply@blogger.com0tag:blogger.com,1999:blog-329255232771855143.post-48589454769790042542015-01-17T17:23:00.003-06:002015-01-17T17:24:18.139-06:00Android Development - Hello World ApplicationIf you know Java, you can learn Android development. In this blog post, we'll create a very simple Android application in Android Studio and run it with an Android emulator.
To get started, download the Android Studio installer here: <a href="http://developer.android.com/sdk/index.html">http://developer.android.com/sdk/index.html</a>.<br />
<br />
Take note of the system requirements, most importantly being the Java Development Kit (JDK).<br />
<br />
Now that you've installed Android Studio, let's create a simple application for Android. Start up Android Studio and click the option for "Start a new Android Studio project".<br />
<br />
<a href="http://2.bp.blogspot.com/-RNS_tbfmEgA/VLrjk8qSdTI/AAAAAAAAC0I/IDLGAamExOY/s1600/android-studio.png" imageanchor="1"><img alt="Welcome to Android Studio Dialog" border="0" src="http://2.bp.blogspot.com/-RNS_tbfmEgA/VLrjk8qSdTI/AAAAAAAAC0I/IDLGAamExOY/s320/android-studio.png" title="" /></a>
<br />
<br />
The next dialog prompts you to name your application and provide the Company Domain. For all intents and purposes, this is simply the package name for your Java classes. Choose a name for your application and package directory and click the "Next" button.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-IwawZeRhruU/VLrkcMbyM8I/AAAAAAAAC0Q/QxWq6U9yWOk/s1600/android-studio-2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Android Studio New Project Dialog" border="0" src="http://4.bp.blogspot.com/-IwawZeRhruU/VLrkcMbyM8I/AAAAAAAAC0Q/QxWq6U9yWOk/s1600/android-studio-2.png" height="192" title="" width="320" /></a></div>
<br />
The next dialog prompts you for the platform where you want to develop and deploy your application. Android is a very cool platform, in that you can develop apps for TV and wearables (e.g. watches), but for this example, I'm going to select "Phone and Tablet" and choose "API 8: Android 2.2 (Froyo)" for my minimum SDK version. When you develop applications for Android, you specify the minimum and maximum SDK version. For this application, API 8 Froyo will be the minimum SDK version needed to run the application. After you select the platform, click "Next".<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-u7640_4SWmc/VLrliE_yObI/AAAAAAAAC0Y/aKBOaaVocos/s1600/android-studio-3.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Android Studio Select API Version Dialog" border="0" src="http://1.bp.blogspot.com/-u7640_4SWmc/VLrliE_yObI/AAAAAAAAC0Y/aKBOaaVocos/s1600/android-studio-3.png" height="192" title="" width="320" /></a></div>
<br />
Next, you select an activity for you application and click "Next". I'm going to choose a Blank Activity. As you get more experienced with Android development, you'll become familiar with activities and the Activity class. For now, you can think of an activity as a screen or view in your application. By choosing Blank Activity, the application will have a blank screen to start building an application.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-WYiC5Y9BbJU/VLrl6oceCBI/AAAAAAAAC0g/7u6biEuW3Cg/s1600/android-studio-4.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Android Studio Activity Dialog" border="0" src="http://2.bp.blogspot.com/-WYiC5Y9BbJU/VLrl6oceCBI/AAAAAAAAC0g/7u6biEuW3Cg/s1600/android-studio-4.png" height="192" title="" width="320" /></a></div>
<br />
The next dialog prompts you for a name for the activity. I'm going to leave it as MainActivity and click "Finish".<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-9cjvx86RcQs/VLrmuSpMTxI/AAAAAAAAC0s/mubueLGS8lg/s1600/android-studio-5.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Android Studio - Name Activity Dialog" border="0" src="http://1.bp.blogspot.com/-9cjvx86RcQs/VLrmuSpMTxI/AAAAAAAAC0s/mubueLGS8lg/s1600/android-studio-5.png" height="192" title="" width="320" /></a></div>
<br />
<br />
<br />
After clicking the "Finish" button, you'll see a progress dialog, as your application is being created. <br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-bZT9lbHBkZI/VLrnAFxd8cI/AAAAAAAAC00/z6ljWr_W3VI/s1600/android-studio-6.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Android Studio - Create Project Progress Dialog" border="0" src="http://1.bp.blogspot.com/-bZT9lbHBkZI/VLrnAFxd8cI/AAAAAAAAC00/z6ljWr_W3VI/s1600/android-studio-6.png" height="55" title="" width="320" /></a></div>
<br />
When Android Studio is finished building your project, you'll see your new Android application open in the IDE.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-ck1UBdX6qps/VLrnh_6YwBI/AAAAAAAAC08/3lrhr85TZ_w/s1600/android-studio-7.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Android Studio - IDE Screenshot" border="0" src="http://1.bp.blogspot.com/-ck1UBdX6qps/VLrnh_6YwBI/AAAAAAAAC08/3lrhr85TZ_w/s1600/android-studio-7.png" height="213" title="" width="320" /></a></div>
<br />
<br />
<br />
Next, let's run the application in an Android emulator. You can start up an emulator from the menu option under Tools-> Android -> AVD Manager. Note that AVD Manager is short for Android Virtual Device Manager.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-fg6kC5Q0dUI/VLrn7GlnuVI/AAAAAAAAC1E/oP51OJ552Yo/s1600/android-studio-8.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Android Studio - AVD Manager Menu Option" border="0" src="http://1.bp.blogspot.com/-fg6kC5Q0dUI/VLrn7GlnuVI/AAAAAAAAC1E/oP51OJ552Yo/s1600/android-studio-8.png" height="271" title="" width="320" /></a></div>
<br />
The AVD Manager dialog prompts you to start a virtual device / emulator. If you don't have a virtual device created, you need to click the button for "Create Virtual Device...". This will allow you to device configuration and Android API version that you want to emulate. For this example, I'm going to use the virtual device that emulates a Nexus 5 using API 21. Because I already have it created, I'll click the green start button on the right side of the device listing, to start the device emulator.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-a5nWdtEKtPw/VLroYP1JvpI/AAAAAAAAC1M/k7qr4Rn7L3Q/s1600/android-studio-9.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Android Studio - Choose Virtual Device" border="0" src="http://3.bp.blogspot.com/-a5nWdtEKtPw/VLroYP1JvpI/AAAAAAAAC1M/k7qr4Rn7L3Q/s1600/android-studio-9.png" height="192" title="" width="320" /></a></div>
<br />
Next, you'll see a progress dialog, as your device emulator is starting.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-AayRNnBWVjc/VLrqyeJXIjI/AAAAAAAAC1Y/VA3lAw74zQo/s1600/android-studio-10.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Android Studio - Starting Android Virtual Device Progress Dialog" border="0" src="http://3.bp.blogspot.com/-AayRNnBWVjc/VLrqyeJXIjI/AAAAAAAAC1Y/VA3lAw74zQo/s1600/android-studio-10.png" height="42" title="" width="320" /></a></div>
<br />
Note that it can take a few minutes to start the emulator, so be patient. After your emulator has started, you'll see the Android welcome screen (just as you'd see if you were powering on an actual Android device). After powering on, you'll see the Android home screen.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-uXZrD99HF98/VLrrR8YH_9I/AAAAAAAAC1g/olOBDNBfEFE/s1600/android-studio-11.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Android Studio - Galaxy Nexus Startup Screen" border="0" src="http://1.bp.blogspot.com/-uXZrD99HF98/VLrrR8YH_9I/AAAAAAAAC1g/olOBDNBfEFE/s1600/android-studio-11.png" height="320" title="" width="182" /></a></div>
<br />
To unlock the welcome screen, just click on the unlock icon and swipe upwards, as you would on an actual Nexus device.<br />
<br />
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-sjJrwBsvSmE/VLrrsUodGAI/AAAAAAAAC1o/AwVJd43R0iM/s1600/android-studio-12.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Android Studio - Galaxy Nexus Home Screen" border="0" src="http://1.bp.blogspot.com/-sjJrwBsvSmE/VLrrsUodGAI/AAAAAAAAC1o/AwVJd43R0iM/s1600/android-studio-12.png" height="320" title="" width="185" /></a></div>
<br />
Now that the emulator is running, go back to your Android Studio IDE to run your application on the emulator. From the Android Studio menu, select Run -> Run...<br />
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-3n4gwe0JuFY/VLrsTfW6iZI/AAAAAAAAC1w/s7s6oj9VDMo/s1600/android-studio-13.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Android Studio - Run Application Menu" border="0" src="http://3.bp.blogspot.com/-3n4gwe0JuFY/VLrsTfW6iZI/AAAAAAAAC1w/s7s6oj9VDMo/s1600/android-studio-13.png" height="133" title="" width="320" /></a></div>
<br />
You'll be prompted for the device where you want to run the application. Choose the emulator that's already running and click "OK".<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-jGIPjnv8eMo/VLrszVj9nKI/AAAAAAAAC14/BKP1LFKkaSA/s1600/android-studio-14.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Android Studio - Choose Running Device Dialog" border="0" src="http://3.bp.blogspot.com/-jGIPjnv8eMo/VLrszVj9nKI/AAAAAAAAC14/BKP1LFKkaSA/s1600/android-studio-14.png" height="293" title="" width="320" /></a></div>
<br />
After a few seconds, you'll see the application running on the device emulator.<br />
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-hZJt13hUceM/VLrtbBaTc0I/AAAAAAAAC2A/SlbUkszMxto/s1600/android-studio-15.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Android Studio - Hello World Application" border="0" src="http://2.bp.blogspot.com/-hZJt13hUceM/VLrtbBaTc0I/AAAAAAAAC2A/SlbUkszMxto/s1600/android-studio-15.png" height="320" title="" width="188" /></a></div>
<br />
Congratulations, you've just created your first Android application! In the next Android blog post, I'll talk about the project structure and the files in the project, as well as provide a more involved application example.<br />
<br />travisdazellhttp://www.blogger.com/profile/18318464927126013291noreply@blogger.com0tag:blogger.com,1999:blog-329255232771855143.post-44728785120103794192014-02-13T22:32:00.000-06:002014-02-13T22:33:31.551-06:00Scala Traits Tutorial - Part 2 (Objects with Traits)In my <a href="http://travisdazell.blogspot.com/2014/02/scala-traits-part-1.html">previous tutorial on Scala traits</a>, I talked about the motivation behind traits and how they can be used to solve problems that crop-up in other languages, due to the lack of traits. It's obvious, from my previous tutorial, that traits can be used in the same way that interfaces are used in Java. But, traits can also contain default/concrete implementations, which gives us added benefit. In this tutorial, I'm going to give some examples of how you can instantiate classes and mix-in traits at the time the object is defined.<br />
<br />
Using the same example as the first tutorial, let's assume we have a trait for a WorkVehicle, as follows.<br />
<br />
<pre class="prettyprint lang-dart">trait WorkVehicle {
def towWeight: Integer = {
return 2500
}
}
</pre>
<br />
This trait has a default/concrete implementation for the <i>towWeight</i> method. Next, let's consider a class for a PersonalVehicle that extends a base abstract class called Vehicle. Note that the class itself does not mix-in the WorkVehicle trait.<br />
<br />
<pre class="prettyprint lang-dart">abstract class Vehicle
class PersonalVehicle extends Vehicle
</pre>
<br />
Rather than creating a new class that mixes-in the WorkVehicle trait, we can do this at the time the class is created, like such.<br />
<br />
<pre class="prettyprint lang-dart">val myWorkVehicle = new PersonalVehicle with WorkVehicle
</pre>
<br />
This is a powerful feature. It allows us to mix-in traits for individual objects, only when needed, rather than doing it at the time that the class is designed. Very cool!travisdazellhttp://www.blogger.com/profile/18318464927126013291noreply@blogger.com1tag:blogger.com,1999:blog-329255232771855143.post-81515156353330059522014-02-11T23:27:00.002-06:002014-02-12T22:09:09.530-06:00Scala Traits Tutorial - Part 1One thing I hear from people new to Scala is confusion around traits. How are they different than an abstract class, what are some real-world use cases for traits, and how do you know when to use a trait versus an abstract class, etc. These are all questions that come up quite a bit with new Scala developers. So, I thought it would be a good idea to write a series of articles around traits.<br />
<br />
In this first article on traits, I'm going to discuss two topics regarding traits:<br />
<br />
<ul>
<li>What is the motivation behind traits and why do we need them?</li>
<li>How can we use traits to accomplish what C++ gives us with multiple inheritance?</li>
</ul>
<br />
Let's start by talking about why traits are needed. Most of us Java programmers spent some time writing OOP code in C++. In C++, we had multiple inheritance. As powerful as it seems, multiple inheritance can lead to a ton of problems in the world of OOP. For example, what if we are designing an inventory system for an automotive dealership that specializes in selling both personal vehicles and work vehicles. We decide to create a class called "WorkVehicle" and "PersonalVehicle". Both classes inherit from a base class called "Vehicle". But along comes a new vehicle to the market that is both a personal vehicle and a work vehicle. So, we create a new class called "HybridVehicle" that extends both WorkVehicle and PersonalVehicle. The end-result is a messy class diagram that illustrates the dreaded diamond inheritance relationship. We now have to code around the merging of common fields.<br />
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-IB908A_2j3I/Uvr_QiBa_aI/AAAAAAAACj0/QyUdX7bDc80/s1600/diagram.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-IB908A_2j3I/Uvr_QiBa_aI/AAAAAAAACj0/QyUdX7bDc80/s1600/diagram.png" height="245" width="400" /></a></div>
<br />
<br />
<br />
Java decided that this is enough of a problem, that it's excluded from the language altogether. You're just now allowed to extend multiple classes. However, this scenario crops-up fairly often in software development, where we need to model entities that share characteristics with other entities in the system, but a parent-child relationship isn't the appropriate fit. Scala's answer to this problem is <i>traits. </i>A Scala trait can have a combination of abstract methods and methods with default implementation. <br />
<br />
Let's look at a simple example of how the vehicle problem might be solved using a trait. In the code example below, we have an abstract class named Vehicle. We've extended Vehicle to create a PersonalVehicle class. We've realized that the thing that makes a WorkVehicle a "vehicle capable of doing work" is that it has a weight that it can safely tow/haul, so we've created a trait called WorkVehicle. This trait has a method with a default implementation, which can be overridden if you need. Notice the use of the <b>with</b> keyword when we mix-in a trait.<br />
<br />
<br />
<pre class="prettyprint lang-dart">abstract class Vehicle
class PersonalVehicle extends Vehicle
trait WorkVehicle {
def towWeight: Integer = {
return 2500
}
}
class HybridVehicle extends PersonalVehicle with WorkVehicle
</pre>
<br />
<br />
This should illustrate how easy it is in Scala, to model various
characteristics of objects using traits and mix-in these traits where we
need. The result is a clean relationship that you don't get with
multiple inheritance in C++, yet we still have the same power that we
like out of multiple inheritance, which Java doesn't provide.travisdazellhttp://www.blogger.com/profile/18318464927126013291noreply@blogger.com0tag:blogger.com,1999:blog-329255232771855143.post-66931981440790778502013-09-27T22:16:00.003-05:002014-02-12T22:10:52.325-06:00Scala Parser Combinators - JavaOne 2013 BOFIn this post, I wanted to share my working example that I demonstrated in my JavaOne 2013 BOF session on "Building Small Languages with Scala Parser Combinators". In the interest of a simple demo, I kept the language features to a minimum. For example, the language types are only integer values. In other words, there are no floating point values, booleans, strings, or chars. Also, the language is interpreted, which means that I'm not generating byte codes.<br />
<br />
These simplifications aside, there are some cool things that I present in this demonstration, all of which form a good foundation for you to use as a starting point for your own language. For example, there are complex expressions, supporting multiplication, division, addition, subtraction, and modulo. There are also several things you'd expect in a small language, such as if-else statements, loops, variable references, and functions.<br />
<br />
Here's an example script that the language can process:<br />
<br />
<pre class="prettyprint lang-dart">// an example of a function that returns a value
func subtractNumbers( x, y, z )
return x - y - z
endfunc
// an example of a function that doesn't return anything
func doSomething()
println 100
endfunc
// main program routine
main:
var a = 10
var b = 20
if (a > b) then
loop 3 times
var d = subtractNumbers( x = 10, y = 5, z = 3 )
println d
endloop
else
if (b > 0) then
loop 2 times
println b
endloop
endif
endif
println 4
doSomething()
println 1
println 2
</pre>
<br />
<br />
The architecture consists of the following components:<br />
<br />
<ul>
<li>A parser written with the Scala parsing library</li>
<ul>
<li>The output of the parser is an AST which describes the structure of the input script </li>
</ul>
<li>An interpreter that walks the resulting AST and processes the nodes accordingly</li>
</ul>
Here's the source code for the parser:<br />
<br />
<pre class="prettyprint lang-dart">package net.travisdazell.parsers
import scala.util.parsing.combinator.syntactical.StandardTokenParsers
import net.travisdazell.parsers.model._
// small interpreted language with the following features:
// - variable definitions and references
// - if-else statements
// - loops
// - error handling
// - scoping
// - functions with named arguments
class SmallLanguageParser extends StandardTokenParsers {
lexical.reserved += ("var", "println", "loop", "times", "endloop", "if",
"then", "else", "endif", "func", "return", "endfunc", "main")
lexical.delimiters += ("*", "/", "%", "+", "-", "(", ")", "=",
"<", ">", "==", "!=", "<=", ">=", ",", ":")
def program: Parser[Program] = (rep(function) <~ ("main" ~ ":")) ~ codeblock ^^ {
case f ~ c => new Program(f, c)
}
def function: Parser[Function] = ("func" ~> ident) ~ ("(" ~> arguments) ~
(")" ~> codeblock) ~ opt(returnStatement) <~ "endfunc" ^^ {
case a ~ b ~ c ~ None => new Function(a, b, c, Number(0))
case a ~ b ~ c ~ d => new Function(a, b, c, d.get)
}
def returnStatement: Parser[Expr] = "return" ~> expr ^^ {
e => e
}
def arguments: Parser[Map[String, Int]] = repsep(ident, ",") ^^ {
argumentList =>
{
(for (a <- argumentList) yield (a -> 0)) toMap
}
}
def codeblock: Parser[List[Statement]] = rep(statement) ^^ { a => a }
def statement: Parser[Statement] = positioned(variableAssignment | outStatement |
loopStatement | ifStatement | functionCall | outStatement) ^^ { a => a }
def variableAssignment: Parser[VariableDefinition] = "var" ~> ident ~ "=" ~
positioned(functionCall | expr) ^^ { case a ~ "=" ~ b => { new VariableDefinition(a, b) } }
def outStatement: Parser[PrintStatement] = "println" ~> positioned(expr) ^^ {
case a => new PrintStatement(a)
}
def loopStatement: Parser[LoopStatement] = ("loop" ~> iterations <~ "times") ~
codeblock <~ "endloop" ^^ {
case i ~ s => {
new LoopStatement(i, s)
}
}
def ifStatement: Parser[IfStatement] = conditional ~ codeblock ~
opt("else" ~> codeblock) <~ "endif" ^^ {
case a ~ b ~ c => {
c match {
case None => new IfStatement(a, b, List())
case _ => new IfStatement(a, b, c.get)
}
}
}
def conditional: Parser[Condition] = "if" ~ "(" ~> condition <~ ")" ~ "then"
def condition: Parser[Condition] = positioned(expr) ~
("<" | ">" | "==" | "!=" | "<=" | ">=") ~ positioned(expr) ^^ {
case a ~ b ~ c => {
new Condition(b, a, c)
}
}
def iterations: Parser[Int] = numericLit ^^ { _ toInt }
def functionCall: Parser[FunctionCall] = ((ident) <~ "(") ~
functionCallArguments <~ ")" ^^ {
case a ~ l => new FunctionCall(a, l)
}
def functionCallArguments: Parser[Map[String, Expr]] =
repsep(functionArgument, ",") ^^ {
_ toMap
}
def functionArgument: Parser[(String, Expr)] = (ident <~ "=") ~ expr ^^ {
case a ~ b => (a, b)
}
def expr: Parser[Expr] = term ~ rep(("+" | "-") ~ term) ^^ {
case a ~ List() => a
case a ~ b => {
def appendExpression(c: Operator, p: Operator): Operator = {
p.left = c
p
}
var root: Operator = new Operator(b.head._1, a, b.head._2)
for (f <- b.tail) {
var parent =
f._1 match {
case "+" => new Operator("+", null, f._2)
case "-" => Operator("-", null, f._2)
}
root = appendExpression(root, parent)
}
root
}
}
def term: Parser[Expr] = multiplydividemodulo ^^ { l => l } | factor ^^ {
a => a
}
// note that "rep" returns a List
def multiplydividemodulo: Parser[Expr] = factor ~ rep(("*" | "/" | "%") ~ factor) ^^ {
case a ~ List() => a
case a ~ b => {
def appendExpression(e: Operator, t: Operator): Operator = {
t.left = e.right
e.right = t
t
}
var root: Operator = new Operator(b.head._1, a, b.head._2)
var current = root
// for each of these, i'm just building up the parse tree
for (f <- b.tail) {
var rightOperator =
f._1 match {
case "*" => Operator("*", null, f._2)
case "/" => Operator("/", null, f._2)
case "%" => Operator("%", null, f._2)
}
current = appendExpression(current, rightOperator)
}
root
}
}
def factor: Parser[Expr] = numericLit ^^ { a => Number(a.toInt) } |
"(" ~> expr <~ ")" ^^ { e => e } |
ident ^^ { new Identifier(_) }
def parseAll[T](p: Parser[T], in: String): ParseResult[T] = {
phrase(p)(new lexical.Scanner(in))
}
}
</pre>
<br />
Next, let's take a look at the interpreter:
<br />
<br />
<pre class="prettyprint lang-dart">package net.travisdazell.parsers.runtime
import net.travisdazell.parsers.model._
class Interpreter(program: Program) {
var currentScope = new Scope("global", null)
def run() {
walk(program.statements)
}
private def getVariable(ident: Identifier): Expr = {
var s: Scope = currentScope
while ((!s.name.equals("global")) && !s.variables.contains(ident.name)) {
s = s.parentScope
}
if (s.variables.contains(ident.name)) s.variables(ident.name)
else {
sys.error("Error: Undefined variable " + ident.name +
" at position [" +
ident.pos.column + "] on line: " +
ident.pos.line)
}
}
private def calculateExpr(e: Expr): Int = {
e match {
case Number(value) => value
case Identifier(name) => {
calculateExpr(getVariable(e.asInstanceOf[Identifier]))
}
case Operator(op, left, right) => {
op match {
case "*" => calculateExpr(left) * calculateExpr(right)
case "/" => calculateExpr(left) / calculateExpr(right)
case "%" => calculateExpr(left) % calculateExpr(right)
case "+" => calculateExpr(left) + calculateExpr(right)
case "-" => calculateExpr(left) - calculateExpr(right)
}
}
}
}
private def isConditionTrue(condition: Condition): Boolean = {
val a = calculateExpr(condition.left)
val b = calculateExpr(condition.right)
condition.op match {
case "==" => (a == b)
case "!=" => (a != b)
case "<=" => (a <= b)
case "<" => (a < b)
case ">=" => (a >= b)
case ">" => (a > b)
}
}
private def executeFunction(f: Function, arguments: Map[String, Expr]) {
currentScope = new Scope(f.name, currentScope)
for (v <- arguments) currentScope.variables(v._1) = v._2
walk(f.statements)
currentScope = currentScope.parentScope
}
private def walk(tree: List[Statement]) {
if (!tree.isEmpty) {
tree.head match {
case FunctionCall(name, values) => {
val f = program.functions.filter(x => x.name == name)
if (f.size < 1) sys.error("Error: Undefined function '" +
name + "' being called at position [" +
tree.head.pos.column + "] on line: " +
tree.head.pos.line)
else {
executeFunction(f(0), values)
walk(tree.tail)
}
}
case VariableDefinition(name, value) => {
// push this variable into scope
if (value.isInstanceOf[FunctionCall]) {
val functionCall = value.asInstanceOf[FunctionCall]
val function = program.functions.filter(x => x.name == functionCall.name)
// check if proc is defined and if not throw an error
if (function.size < 1) sys.error("Error: Undefined function '" +
functionCall.name + "' being called at position [" +
tree.head.pos.column + "] on line: " +
tree.head.pos.line)
else {
executeFunction(function(0), functionCall.values)
currentScope = currentScope.parentScope
// assign the return value of the function to the variable
currentScope.variables(name) = function(0).returnValue
}
} else {
currentScope.variables(name) = value
}
walk(tree.tail)
}
case PrintStatement(value) => {
println(calculateExpr(value))
walk(tree.tail)
}
case LoopStatement(iterations, statements) => {
currentScope = new Scope("", currentScope)
for (i <- 0 until iterations) walk(statements)
currentScope = currentScope.parentScope
walk(tree.tail)
}
case IfStatement(condition, trueBranch, falseBranch) => {
currentScope = new Scope("", currentScope)
if (isConditionTrue(condition)) walk(trueBranch) else walk(falseBranch)
currentScope = currentScope.parentScope
walk(tree.tail)
}
case _ => ()
}
}
}
}
</pre>
<br />
<br />
The last thing we need is a main routine that will read our input script and execute our parser:<br />
<br />
<pre class="prettyprint lang-dart">package net.travisdazell.parsers.runtime
import scala.io.Source
import net.travisdazell.parsers.SmallLanguageParser
object SmallLanguage {
def main(args: Array[String]) {
val inputFile = Source.fromFile("scripts/program.small")
val inputSource = inputFile.mkString
val parser = new SmallLanguageParser
parser.parseAll(parser.program, inputSource) match {
case parser.Success(r, n) => {
val interpreter = new Interpreter(r)
try {
interpreter.run
} catch {
case e: RuntimeException => println(e.getMessage)
}
}
case parser.Error(msg, n) => println("Error: " + msg)
case parser.Failure(msg, n) => println("Error: " + msg)
case _ =>
}
}
}
</pre>
<br />
<br />
The one thing I haven't included is the model classes that represent the AST nodes. However, as always, I've provided the full source code on GitHub: <a href="https://github.com/travisdazell/javaone-2013-BOF-small-language">https://github.com/travisdazell/javaone-2013-BOF-small-language</a>travisdazellhttp://www.blogger.com/profile/18318464927126013291noreply@blogger.com0tag:blogger.com,1999:blog-329255232771855143.post-8580462896981909642013-07-29T23:03:00.000-05:002013-09-27T22:04:25.551-05:00JavaOne 2013For those of you following my blog, you've probably noticed I haven't been actively posting tutorials as usual. I apologize for my slow posts lately. I'll be back to posting helpful tutorials soon. In the meantime, I'm glad to announce that I'll be at JavaOne this year. I'm speaking on the following topics:<br />
<ul>
<li>Building Small Languages with Scala Parser Combinators</li>
<li>Developing Domain-Specific Languages for the JVM</li>
</ul>
I hope to see you at JavaOne this fall!travisdazellhttp://www.blogger.com/profile/18318464927126013291noreply@blogger.com0tag:blogger.com,1999:blog-329255232771855143.post-73302991059503484512013-05-10T21:15:00.002-05:002014-02-12T22:12:20.251-06:00Scala Lists FlattenThe <i>flatten </i>method on Scala lists is used to remove one level of nested structure. For example, if we have a list that contains two lists, we can flatten that structure and result in a single one-dimensional list. Here's an example.<br />
<br />
<pre class='prettyprint lang-dart'>
val listOfLists = List(List(1, 3, 5), List(2, 4, 6))
listOfLists flatten // List(1, 3, 5, 2, 4, 6)
</pre>
<br />
<br />travisdazellhttp://www.blogger.com/profile/18318464927126013291noreply@blogger.com0tag:blogger.com,1999:blog-329255232771855143.post-1578790046827633862013-05-10T21:11:00.002-05:002014-02-12T22:12:40.403-06:00Scala Lists Zip and UnzipZipping is the process of taking two lists and merge them into a single list of tuples, where the first item in each list comprises the first tuple, the second item in each list comprises the second tuple, etc. It's best to think of this operation like a zipper on a jacket where the first teeth on each side of the zipper become merged, the second teeth on each side of the zipper become merged, etc.<br />
<br />
Here's an example of two lists that are zipped.<br />
<br />
<pre class="prettyprint lang-dart">val digits = List(1, 2, 3)
val chars = List("a", "b", "c")
val result = digits zip chars // result : List((1,"a"), (2,"b"), (3,"c"))
</pre>
<br />
<br />
The opposite of the zip method is <i>unzip</i>. Here's the result of unzipping the result from above.<br />
<br />
<pre class="prettyprint lang-dart">result unzip // (List(1, 2, 3),List("a", "b", "c"))
</pre>
<br />
<br />travisdazellhttp://www.blogger.com/profile/18318464927126013291noreply@blogger.com0tag:blogger.com,1999:blog-329255232771855143.post-4090699200578970502013-05-09T21:16:00.000-05:002014-02-12T22:12:55.984-06:00Scala - Transform All Elements in a Scala CollectionOften times, you need to transform all of the elements in a Scala collection. This is where the <i>map </i>method comes in handy. With the <i>map </i>method, you can apply a function to all of the elements in a collection and obtain a new collection with the results. Here's an example that uses the <i>map </i>method to create a new list where all of the elements in the list are converted to uppercase.<br />
<br />
<pre class="prettyprint lang-dart">val places = List("Atlanta", "Chicago", "Dallas", "New York City")
val uppercasePlaces = places.map(_.toUpperCase)
</pre>
<br />
This has the same effect as iterating over all of the elements and calling <i>toUpperCase</i> on each element individually.<br />
<br />
Sometimes you'll have a collection of various types. For example, your collection might contain Int and String values and you want to convert all of the String values to uppercase and still keep the Int values in the resulting list. For this, we have the <i>collect </i>method, along with case classes. Here's an example.<br />
<br />
<pre class="prettyprint lang-dart">val numbersAndStrings = List(1, "Atlanta", 10, "Boston", "Dallas")
val numbersAndUppercaseStrings = numbersAndStrings.collect {
case s: String => s.toUpperCase; case i: Int => i
}
</pre>
<br />
<br />travisdazellhttp://www.blogger.com/profile/18318464927126013291noreply@blogger.com0tag:blogger.com,1999:blog-329255232771855143.post-10588436398999536162013-05-01T18:15:00.002-05:002014-02-12T22:13:06.925-06:00Throttling Service Requests Using CamelThis tutorial shows how to use Camel to throttle the sending of messages to a service. This is necessary when you don't want to overload the service. For example, the service might have a published service level agreement (SLA) requiring you to only send a certain number of requests per second or minute. If you're not familiar with Camel, read my blog post on <a href="http://travisdazell.blogspot.com/2013/03/implementing-pipes-and-filters-using.html">Implementing Pipes and Filters Using Camel</a>.<br />
<br />
The source code for this example is available on GitHub: <a href="https://github.com/travisdazell/camel-throttler">https://github.com/travisdazell/camel-throttler</a><br />
<br />
Let's consider an integration scenario where we receive orders via an incoming file drop. We then pick up the file, process it with some custom Java code, and then place a message on a JMS queue. Here's the Camel route, with a throttler that only allows one message to be sent to the JMS queue every five seconds.<br />
<br />
<pre class="prettyprint lang-dart"><camelcontext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="file://incoming" />
<to uri="bean:orderProcessor?method=processIncomingOrder" />
<throttle timePeriodMillis="5000">
<constant>1</constant>
<to uri="activemq:queue:ORDERS.INCOMING" />
</throttle>
</route>
</camelcontext>
</pre>
<br />
<br />travisdazellhttp://www.blogger.com/profile/18318464927126013291noreply@blogger.com0tag:blogger.com,1999:blog-329255232771855143.post-58231001831537980432013-04-29T17:27:00.004-05:002014-02-12T22:13:34.491-06:00Scala Lists - PartitionTwo very common list functions are <i>filter </i>and <i>filterNot</i>, where the former function returns a new list where all of the elements in the list hold true for a specified predicate and the latter function returns a new list where all of the elements in the list do not hold true for a specified predicate. For example, we can use these two functions to traverse a list of integers and generate a list of all positive integers, as well as a list of all negative integers.
<br />
<br />
<pre class="prettyprint lang-dart"> val l: List[Int] = List(-12, 2, -2, -3, 4, 5, 6)
val positiveList = l.filter(x => x > 0)
val negativeList = l.filterNot(x => x > 0)
</pre>
<br />
<br />
The list function <i>partition</i> combines both of these operations into a single traversal of the original list and returns two lists, one list of values where the predicate holds true and another list of values where the predicate does not hold true.<br />
<br />
<pre class="prettyprint lang-dart">val l: List[Int] = List(-12, 2, -2, -3, 4, 5, 6)
val positiveAndNegativeLists = l.partition(x => x > 0)
</pre>
<br />
<br />
We can then access each list using positiveAndNegativeLists._1 and positiveAndNegativeLists._2, where the former is the list of all elements where the predicate is true and the latter contains all elements where the predicate is false.
<br />
<br />
<pre class="prettyprint lang-dart"> for (y <- positiveAndNegativeLists._1) println(y)
for (y <- positiveAndNegativeLists._2) println(y)
</pre>
travisdazellhttp://www.blogger.com/profile/18318464927126013291noreply@blogger.com0tag:blogger.com,1999:blog-329255232771855143.post-12514455204957032752013-04-29T17:14:00.001-05:002014-02-12T22:13:56.061-06:00Scala Lists - Map and FilterTwo very common List operations in Scala are <i>map </i>and <i>filter</i>. Let's start by looking at <i>map. </i>This function is used when you need to map all of the elements in the list to some over value. For example, if we have a list of integer values and we need to produce a new list where each value in the original list is multiplied by 3, we can write the following <i>map</i> implementation in Scala.<br />
<br />
<pre class="prettyprint lang-dart"> val l: List[Int] = List(1, 2, 2, 3, 4, 5, 6)
val newList = l.map(x => x * 3)
</pre>
<br />
<br />
Another useful function is <i>filter</i>. Filter is like map, in that it traverses every element in the list. However, <i>filter </i>will return a new list where all of the elements in the original list hold true for a particular predicate/test. For example, if we wanted to filter out all odd integer values in a list, we can write the following in Scala.<br />
<br />
<pre class="prettyprint lang-dart"> val l: List[Int] = List(1, 2, 2, 3, 4, 5, 6)
val newList = l.filter(x => (x %2 == 0))
</pre>
<br />
<br />
Of course, we can combine both <i>map </i>and <i>filter</i>. Here's an example.<br />
<br />
<pre class="prettyprint lang-dart"> val l: List[Int] = List(1, 2, 2, 3, 4, 5, 6)
val newList = l.map(x => x * 3).filter(x => (x % 2) == 0)
</pre>
<br />
<br />travisdazellhttp://www.blogger.com/profile/18318464927126013291noreply@blogger.com0tag:blogger.com,1999:blog-329255232771855143.post-72317836957657186692013-04-29T06:25:00.005-05:002014-02-12T22:14:39.246-06:00Scala Parser Combinators - Part 3In a <a href="http://travisdazell.blogspot.com/2013/03/scala-parser-combinators-part-2.html">previous post on Scala parser combinators</a>, I demonstrated how to use Scala's parser library to write a simple arithmetic parser. This example resulted in a parser that parsed an arithmetic expression and returned the results of the operation. In this tutorial, I'm going to expand on this parser by generating a parse tree, instead of simply evaluating the expression. For the expression "2 * 8 + 6", the parser will output the following parse tree. <br />
<br />
<pre class="prettyprint lang-dart"><span style="font-size: large;"> *
/ \
2 +
/ \
8 6</span>
</pre>
<br />
<br />
Notice that every node in our tree is either an expression consisting of an operator and a left and right side, or a single digit. For example, "8+6" is the addition operator (+) with a left side of 8 and a right side of 6. 8 and 6 are the other type of tree node (i.e. number). We'll start by defining these two types of nodes in our parse tree with a case class.<br />
<br />
<pre class="prettyprint lang-dart">class Expr
case class Number(value: Int) extends Expr
case class Operator(symbol: String, left: Expr, right: Expr) extends Expr
</pre>
<br />
<br />
Next, we'll define the rules of our parser. Note that if you read my <a href="http://travisdazell.blogspot.com/2013/03/scala-parser-combinators-part-2.html">previous posts on Scala parser combinators</a>, I've simply added the "term" and "factor" class members.<br />
<br />
<pre class="prettyprint lang-dart">class ExprParser extends RegexParsers {
val number = "[1-9][0-9]*".r
def expr: Parser[Int] = (number ^^ { _.toInt }) ~ opt(operator ~ expr) ^^ {
case a ~ None => a
case a ~ Some("*" ~ b) => a * b
case a ~ Some("/" ~ b) => a / b
case a ~ Some("+" ~ b) => a + b
case a ~ Some("-" ~ b) => a - b
}
def operator: Parser[String] = "+" | "-" | "*" | "/"
def term: Parser[Expr] = (factor ~ opt(operator ~ term)) ^^ {
case a ~ None => a
case a ~ Some(b ~ c) => Operator(b, a, c)
}
def factor: Parser[Expr] = number ^^ (n => Number(n.toInt))
}
</pre>
<br />
Let's test the parser and evaluate the results.<br />
<br />
<pre class="prettyprint lang-dart"> def main(args: Array[String]) {
val parser = new ExprParser
val result = parser.parseAll(parser.term, "9*8+2")
println(result.get)
}
</pre>
<br />
The output from this test is the following parse tree.<br />
<br />
<pre class="prettyprint lang-dart">Operator(*,Number(2),Operator(+,Number(8),Number(6)))
</pre>
<br />
<br />
In order to look at this response and recognize a parse tree, notice that a tree of the form "8+6" is printed as "Operator(+, Number(8), Number(6))". This is because the "+" is the root of the node, so it's listed first. Thus, we have a subtree that looks like this.
<br />
<br />
<pre class="prettyprint lang-dart"><span style="font-size: large;">
+
/ \
8 6
</span>
</pre>
<br />
<br />
After applying this to the rest of our parse tree response of "Operator(*, Number(2), ...)", our resulting parse tree looks like this.
<br />
<br />
<pre class="prettyprint lang-dart"><span style="font-size: large;"> *
/ \
2 +
/ \
8 6</span>
</pre>
<br />
<br />travisdazellhttp://www.blogger.com/profile/18318464927126013291noreply@blogger.com0tag:blogger.com,1999:blog-329255232771855143.post-1678820691442680822013-04-28T19:05:00.000-05:002014-02-12T22:14:54.291-06:00Scala Nested FunctionsIn Scala, we have the ability to define a function within another function. Here's an example of a function named "appliesToMoreThanHalf" that determines whether a certain predicate holds true for more than half of the values in a list. The function contains a nested function named "iter" that processes the list.<br />
<br />
<pre class="prettyprint lang-dart"> def appliesToMoreThanHalf(s: List[Int], p: Int => Boolean): Boolean = {
var count = 0
def iter(startingIndex: Int): Boolean = {
if (startingIndex < s.length) {
if (p(s(startingIndex))) {
count += 1
}
iter(startingIndex + 1)
}
count >= (s.length / 2 + 1)
}
iter(0)
}
</pre>
<br />
Here's an example of this function being called to determine if more than half of the elements in a list are even (i.e. evenly divisible by 2).
<br />
<br />
<pre class="prettyprint lang-dart"> def main(args: Array[String]) {
val l: List[Int] = List(1, 2, 2, 3, 4, 5, 6)
if (appliesToMoreThanHalf(l, p => (p % 2 == 0))) {
println("the function applies to more than half of the elements")
} else {
println("the function does not apply to more than half of the elements")
}
}
</pre>
<br />
<br />
Granted, there is a much simpler way to determine if more than half of the elements hold true for a particular predicate, but this serves as a demonstration of nested functions.travisdazellhttp://www.blogger.com/profile/18318464927126013291noreply@blogger.com0tag:blogger.com,1999:blog-329255232771855143.post-47332943567443192952013-04-28T11:16:00.001-05:002014-02-12T22:15:27.445-06:00Scala Tail RecursionWhen you write a recursive function, every call to the recursive function results in another method call being placed on to the call stack. If the stack grows too much, you'll get a stack overflow error. For example, look at the following Scala code that uses recursion to calculate the sum of all integers in a list.<br />
<br />
<pre class="prettyprint lang-dart">
def sum(s: Seq[Int]): BigInt = {
if (s.isEmpty) 0 else s.head + sum(s.tail)
}
</pre>
<br />
<br />
When we execute this method for very large lists, we get a stack overflow error.<br />
<br />
<pre class="prettyprint lang-dart">Exception in thread "main" java.lang.StackOverflowError
at scala.collection.AbstractTraversable.<init>(Traversable.scala:105)
at scala.collection.AbstractIterable.<init>(Iterable.scala:54)
at scala.collection.AbstractSeq.<init>(Seq.scala:40)
at scala.collection.immutable.Range.<init>(Range.scala:44)
at scala.collection.immutable.Range$Inclusive.<init>(Range.scala:330)
at scala.collection.immutable.Range$Inclusive.copy(Range.scala:333)
at scala.collection.immutable.Range.drop(Range.scala:170)
at scala.collection.immutable.Range.tail(Range.scala:196)
at scala.collection.immutable.Range.tail(Range.scala:44)
...
</init></init></init></init></init></pre>
<br />
<br />
In Scala, we can use tail recursion to tell the compiler to turn our recursive call into a loop to avoid a stack overflow error. To do this, simply add a "tailrec" annotation to the method call.
<br />
<br />
@tailrec def sum(s: Seq[Int]): BigInt = {
if (s.isEmpty) 0 else s.head + sum(s.tail)
}
<br />
<br />
However, if we add the annotation and re-run our example, we get the following compiler error.
<br />
<br />
<pre class="prettyprint lang-dart">could not optimize @tailrec annotated method sum: it contains a recursive call not in tail position
</pre>
<br />
<br />
This error is the result of the Scala compiler not being able to utilize tail recursion due to the structure of our code. Why is that? Well, if we take the "else" path in our sum method, the first step is the recursive call to "sum", passing in the tail of the list. The result of the recursive call is added to the head of the list, making the addition operation the last step in the computation. In order to utilize tail recursion, we need to refactor our code to make the recursive call the last step of the computation. Here's the same algorithm, after refactoring to make the recursive call to "sum" be the last step in the computation.
<br />
<br />
<pre class='prettyprint lang-dart'>
@tailrec def sum(s: Seq[Int], p: BigInt): BigInt = {
if (s.isEmpty) p else sum(s.tail, s.head + p)
}
def main(args: Array[String]) {
val result = sum(1 to 1000000, 0)
println(result)
}
</pre>
<br />
<br />
Now, after running the example, we get a successful result.
<br />
<br />
<pre class='prettyprint lang-dart'>
500000500000
</pre>
<br />
<br />
Note that the Scala compiler will try to use tail recursion when it can; however, it's a good practice to annotate any methods where you expect this optimization to be done (i.e. the last step in your recursive algorithm is the call to the recursive function). That way, you'll be warned at compile-time that there was an issue applying the optimization, preventing surprises at run-time.travisdazellhttp://www.blogger.com/profile/18318464927126013291noreply@blogger.com0tag:blogger.com,1999:blog-329255232771855143.post-50454026629099782902013-04-05T22:07:00.004-05:002014-02-12T22:16:01.731-06:00Higher-Order Functions in ScalaThe functions that most of us are familiar with take some type(s) as parameters and return some type as a result. These are called first order functions. Higher-order functions, however, are functions that take other functions as parameters and/or return a function as a result. In other words, higher-order functions act on other functions.<br />
<br />
To demonstrate with a simple example, let's look at how we might define a first order function that takes two integer values and returns the sum of both values squared.<br />
<br />
<br />
<pre class="prettyprint lang-dart">def sumOfSquares(a: Int, b: Int): Int = {
a * a + b * b
}
</pre>
<br />
<br />
Next, let's look at how we could refactor this to use a higher-order function. Here is a function that takes 3 parameters:<br />
<ul>
<li>a function that takes an Int and returns an Int</li>
<li>an Int named a</li>
<li>an Int named b</li>
</ul>
<br />
<pre class="prettyprint lang-dart">def sumOfTwoOperations(f: Int => Int, a: Int, b: Int): Int = {
f(a) + f(b)
}
</pre>
<br />
<br />
Next, let's call the sumOfTwoOperations function, passing a "squared" function as the first parameter.<br />
<br />
<br />
<pre class="prettyprint lang-dart">def squared(x: Int): Int = x * x
val result = sumOfTwoOperations(squared, 2, 5) // result = 29
</pre>
<br />
<br />
The beauty of higher-order functions is that now we can define another operation, such as "cubed", and pass that to the sumOfTwoOperations.
<br />
<br />
<pre class="prettyprint lang-dart">def cubed(x: Int): Int = x * x * x
val result = sumOfTwoOperations(cubed, 2, 5) // result = 133
</pre>
<br />
<br />travisdazellhttp://www.blogger.com/profile/18318464927126013291noreply@blogger.com0tag:blogger.com,1999:blog-329255232771855143.post-80349645112784779212013-03-29T21:44:00.002-05:002014-02-12T22:16:27.589-06:00Scala Call-By-Value Versus Call-By-NameThis tutorial demonstrates the difference between call-by-value and call-by-name method parameters. By default, method arguments are passed call-by-value. This is the evaluation that you're probably already familiar with from Java. With call-by-value, the arguments that are passed to the method are evaluated as an expression before the control flow is passed to the method. Here are two methods with the exact same code in the method body. They simply execute a loop for five iterations, referencing the parameter "x" within each iteration. The only difference is that the first method takes a call-by-value parameter (notice the => syntax), while the second method takes a call-by-name parameter.<br />
<br />
<pre class="prettyprint lang-dart"> def callByValue(x : Unit) = {
for (i <- 0 until 5) {
print(x)
}
}
def callByName(x : => Unit) = {
for (i <- 0 until 5) {
print(x)
}
}
</pre>
<br />
<br />
Now, let's see what happens to the value of the parameter when we call these two methods with an expression that increments the function value by one (i = i + 1). When we call the callByValue method, the result of the value after the function call is simply i = i + 1.<br />
<br />
<br />
<pre class="prettyprint lang-dart"> def main(args: Array[String]) {
var i = 0
callByValue(i = i + 1)
print(i) // "1"
}
</pre>
<br />
<br />
What's happening here is that the expression i = i + 1 is being evaluated one time, before the control flow is passed to the callByValue method. However, after calling the callByName method instead of callByValue, the result of the variable "i" is 5.<br />
<br />
<br />
<pre class="prettyprint lang-dart"> def main(args: Array[String]) {
var i = 0
callByName(i = i + 1)
print(i) // "5"
}
</pre>
<br />
<br />
The reason this is happening is because when a parameter is call-by-name, the value of the parameter is evaluated every time it's referenced in the method. It's being referenced 5 times, so the expression i = i + 1 is being executed 5 times.travisdazellhttp://www.blogger.com/profile/18318464927126013291noreply@blogger.com1tag:blogger.com,1999:blog-329255232771855143.post-65979279263889568142013-03-26T18:37:00.002-05:002014-02-12T22:17:00.760-06:00JVM Code Generation with JasminWhen you write your own programming language, you're tasked with writing a lexer and parser. But, once that's complete, you still have to execute the code somehow. If you're looking to target the JVM as a runtime, you need to compile your source code down to JVM bytecode, which can seem like a daunting task. However, Jasmin, which has been around for many years, is a very useful framework that makes this much easier. This tutorial takes you through the steps of creating a simple Hello World program with Jasmin. The result is a HelloWorld.class file that you can run at the command-prompt with Java. In future tutorials, I'll go through more complex examples, but you have to start somewhere. I put the full code on GitHub: <a href="https://github.com/travisdazell/Jasmin-HelloWorld">https://github.com/travisdazell/Jasmin-HelloWorld</a><br />
<br />
<br />
<b>Step 1: Download Jasmin</b><br />
<br />
You can download Jasmin here: <a href="http://jasmin.sourceforge.net/">http://jasmin.sourceforge.net.</a><br />
<br />
Download and extract the ZIP file to your PC. I have it installed on my root, so the result is a C:\jasmin-2.4\ directory on my PC.<br />
<br />
<br />
<b>Step 2: Write the Jasmin code for the HelloWorld class.</b><br />
<br />
Let's create a simple Hello World program and then discuss the code in more detail. Here's the complete example:<br />
<br />
<pre class="prettyprint lang-dart">; class definition
.class public HelloWorld
; extends java.lang.Object
.super java/lang/Object
; default constructor -- public HelloWorld() { super(); }
.method public <init>()V
aload_0
invokenonvirtual java/lang/Object/<init>()V
return
.end method
; main method -- public static void main(String args[]) { ... }
.method public static main([Ljava/lang/String;)V
.limit stack 2 ; we're allocating 2 items we plan to put on the stack
; push System.out onto the stack
getstatic java/lang/System/out Ljava/io/PrintStream;
; push the constant "Hello World" string onto the stack
ldc "Hello World"
; print the result that's on the top of the stack
invokevirtual java/io/PrintStream/println(Ljava/lang/String;)V
return
.end method
</pre>
<br />
<br />
Let's review the Jasmin code so that you get an understanding of what's involved. The first two lines are fairly self-explanatory. We're just defining the name of the Java class and its superclass. In this example, the superclass is just java.lang.Object.<br />
<br />
<br />
<pre class="prettyprint lang-dart">; class definition
.class public HelloWorld
; extends java.lang.Object
.super java/lang/Object
</pre>
<br />
<br />
Note the use of the slash (/) in the package structure. That's one of the differences between actual Java code and Jasmin. The next step is to define the default constructor.<br />
<br />
<br />
<pre class="prettyprint lang-dart">; default constructor -- public HelloWorld() { super(); }
.method public()V
aload_0
invokenonvirtual java/lang/Object/()V
return
.end method
</pre>
<br />
The last section of code is our main method. Within this method, the first thing we do is specify the size of the stack for the method. In our case, we only need a stack size of 2, because we're only going to be putting System.out and the constant "Hello World" string on the stack. The last step is to print the result that's on top of the stack and return.<br />
<br />
<br />
<pre class="prettyprint lang-dart">; main method -- public static void main(String args[]) { ... }
.method public static main([Ljava/lang/String;)V
.limit stack 2 ; we're allocating 2 items we plan to put on the stack
; push System.out onto the stack
getstatic java/lang/System/out Ljava/io/PrintStream;
; push the constant "Hello World" string onto the stack
ldc "Hello World"
; print the result that's on the top of the stack
invokevirtual java/io/PrintStream/println(Ljava/lang/String;)V
return
.end method
</pre>
<br />
<br />
<b>Step 3: Save the file and compile it to bytecode</b><br />
<br />
Save the file as HelloWorld.j and then run the following command from the command-prompt:<br />
<br />
<br />
<pre class="prettyprint lang-dart">C:\> java -jar "C:\jasmin-2.4\jasmin.jar" HelloWorld.j
</pre>
<br />
The output will be a HelloWorld.class file that you can run using Java!<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-PjeevW0h8WM/UVIxHuLaAqI/AAAAAAAAB8Y/cpCcKc0jASk/s1600/jasmin-1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="140" src="http://2.bp.blogspot.com/-PjeevW0h8WM/UVIxHuLaAqI/AAAAAAAAB8Y/cpCcKc0jASk/s400/jasmin-1.png" width="400" /></a></div>
<br />travisdazellhttp://www.blogger.com/profile/18318464927126013291noreply@blogger.com0tag:blogger.com,1999:blog-329255232771855143.post-55140635727294548632013-03-20T21:04:00.001-05:002014-02-12T22:17:11.693-06:00Implementing a Content-Based Router Using Camel<code><span style="font-size: small;"><span style="font-family: inherit;"><span style="font-size: small;"><span style="font-size: small;"><span style="font-size: small;">Often times</span></span></span></span></span></code>, we're faced with the problem of routing a message at run-time based on the content of the message. Consider the following example. Let's say we receive all incoming orders in a single queue. However, we have two order processing services. The first service processes our normal customer orders, but we have a separate service that processes orders placed internally by employees. How do we solve this problem? A content-based router pattern solves this problem of determining where to route a message at run-time. Here's an example of a Content-Based Router implementing the example I described (the image is credited to <a href="http://www.enterpriseintegrationpatterns.com/ContentBasedRouter.html">http://www.enterpriseintegrationpatterns.com/ContentBasedRouter.html</a>).<br />
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-om71NArQe18/UUpeLFap0PI/AAAAAAAAB8I/doO5bDrlAoY/s1600/cbr.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="96" src="http://1.bp.blogspot.com/-om71NArQe18/UUpeLFap0PI/AAAAAAAAB8I/doO5bDrlAoY/s400/cbr.png" width="400" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />
<br />
Thankfully, it's extremely easy to implement a content-based router pattern in Camel. If you're not familiar with using Camel, refer to my tutorial on <a href="http://travisdazell.blogspot.com/2013/03/implementing-pipes-and-filters-using.html">Implementing Pipes and Filters Using Camel</a>. It's a different integration pattern, but it walks through the basics of using Camel.<br />
<br />
Now that you're familiar with Camel, let's look at how you would define a content-based router in your Camel route.<br />
<br />
<br />
<pre class="prettyprint lang-dart"> <!-- content based router -->
<route>
<!-- get message from JMS ORDERS.INCOMING queue -->
<from uri="activemq:queue:ORDERS.INCOMING">
<!-- route the order to the correct queue -->
<choice>
<when>
<simple>${header.type} == 'customer'</simple>
<to uri="activemq:queue:ORDERS.CUSTOMER"></to>
</when>
<when>
<simple>${header.type} == 'employee'</simple>
<to uri="activemq:queue:ORDERS.EMPLOYEE"></to>
</when>
</choice>
</from>
</route>
</pre>
travisdazellhttp://www.blogger.com/profile/18318464927126013291noreply@blogger.com0tag:blogger.com,1999:blog-329255232771855143.post-73375171416020766412013-03-19T01:51:00.002-05:002013-03-19T02:05:58.290-05:00Web Service Client in Java Using JAX-WSThis tutorial describes how to consume a SOAP web service in Java using JAX-WS. For this tutorial, we'll create a client application that makes a call to a SOAP service hosted on wsf.cdyne.com.<br />
<br />
<ul>
</ul>
<ol>
<li>The first step is to import the WSDL of the web service to create the client proxy code. From the command prompt, navigate to the directory where you want to generate the client code and type: "wsimport -s . http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL". After running this command, you'll find a \com\cdyne\ws\weatherws directory has been created with a number of .java and .class files.</li>
<br />
<div class="separator" style="clear: both;">
<a href="http://3.bp.blogspot.com/-TxyUpZBU28Q/UUgGPv5_3VI/AAAAAAAAB7o/HqSii8nmQ-k/s1600/wsimport.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em; padding-left: -15px;"><img border="0" height="248" src="http://3.bp.blogspot.com/-TxyUpZBU28Q/UUgGPv5_3VI/AAAAAAAAB7o/HqSii8nmQ-k/s640/wsimport.png" width="570" /></a></div>
<br />
<br />
<li> Next, we'll write a simple Java class and main method to invoke the web service.</li>
public class WeatherTest {<br />
<br />
public static void main(String args[]) {<br />
Weather weather = new Weather();<br />
<br />
WeatherSoap weatherSoap = weather.getWeatherSoap();<br />
<br />
ForecastReturn forecastReturn = weatherSoap.getCityForecastByZIP("56701");<br />
<br />
ArrayOfForecast arrayOfForecast = forecastReturn.getForecastResult();<br />
List<Forecast> forecasts = arrayOfForecast.getForecast();<br />
<br />
for (Forecast forecast : forecasts) {<br />
System.out.println(forecast.getDate().toString() + " " + forecast.getDesciption());<br />
}<br />
}<br />
<br />
}<br />
<br />
<br />
<li>The output from this program is:</li>
</ol>
<div style="text-align: left;">
2013-03-14T00:00:00 Mostly Cloudy<br />
2013-03-15T00:00:00 Snow<br />
2013-03-16T00:00:00 Partly Cloudy<br />
2013-03-17T00:00:00 Partly Cloudy<br />
2013-03-18T00:00:00 Snow<br />
2013-03-19T00:00:00 Partly Cloudy<br />
2013-03-20T00:00:00 Partly Cloudy<br />
<br /></div>
travisdazellhttp://www.blogger.com/profile/18318464927126013291noreply@blogger.com0