<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>vaks.in&#039;s Blog</title>
	<atom:link href="http://v4ks1n.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://v4ks1n.wordpress.com</link>
	<description>a new Life, as the Oracle</description>
	<lastBuildDate>Sat, 12 Feb 2011 15:39:22 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='v4ks1n.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>vaks.in&#039;s Blog</title>
		<link>http://v4ks1n.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://v4ks1n.wordpress.com/osd.xml" title="vaks.in&#039;s Blog" />
	<atom:link rel='hub' href='http://v4ks1n.wordpress.com/?pushpress=hub'/>
		<item>
		<title>We Just MOVED!</title>
		<link>http://v4ks1n.wordpress.com/2011/02/12/we-just-moved/</link>
		<comments>http://v4ks1n.wordpress.com/2011/02/12/we-just-moved/#comments</comments>
		<pubDate>Sat, 12 Feb 2011 15:37:52 +0000</pubDate>
		<dc:creator>v4ks1n</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://v4ks1n.wordpress.com/?p=190</guid>
		<description><![CDATA[. Our New URL is http://vaks.in .<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=v4ks1n.wordpress.com&amp;blog=7180005&amp;post=190&amp;subd=v4ks1n&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>.</p>
<h1><strong>Our New URL is <a href="http://vaks.in">http://vaks.in</a></strong></h1>
<p>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/v4ks1n.wordpress.com/190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/v4ks1n.wordpress.com/190/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/v4ks1n.wordpress.com/190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/v4ks1n.wordpress.com/190/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/v4ks1n.wordpress.com/190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/v4ks1n.wordpress.com/190/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/v4ks1n.wordpress.com/190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/v4ks1n.wordpress.com/190/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/v4ks1n.wordpress.com/190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/v4ks1n.wordpress.com/190/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/v4ks1n.wordpress.com/190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/v4ks1n.wordpress.com/190/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/v4ks1n.wordpress.com/190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/v4ks1n.wordpress.com/190/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=v4ks1n.wordpress.com&amp;blog=7180005&amp;post=190&amp;subd=v4ks1n&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://v4ks1n.wordpress.com/2011/02/12/we-just-moved/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/276ef47c3a5018e58eb22d39eed513c9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">v4ks1n</media:title>
		</media:content>
	</item>
		<item>
		<title>Tooltips class for BlackBerry</title>
		<link>http://v4ks1n.wordpress.com/2011/01/28/tooltips-class-for-blackberry/</link>
		<comments>http://v4ks1n.wordpress.com/2011/01/28/tooltips-class-for-blackberry/#comments</comments>
		<pubDate>Fri, 28 Jan 2011 11:28:17 +0000</pubDate>
		<dc:creator>v4ks1n</dc:creator>
				<category><![CDATA[blackberry]]></category>
		<category><![CDATA[field]]></category>
		<category><![CDATA[icon]]></category>
		<category><![CDATA[popup]]></category>
		<category><![CDATA[tooltip]]></category>

		<guid isPermaLink="false">http://v4ks1n.wordpress.com/?p=188</guid>
		<description><![CDATA[here is the copy of tooltips class for BlackBerry, with 2 different approach. first: [1] Easy solution to create popup style tooltips on BlackBerry. Extend TooltipScreen instead of the usual MainScreen, usage: add(new ButtonField(&#8220;myButton&#8221;), &#8220;My Tooltip text&#8221;); and the source: import java.util.Timer; import java.util.TimerTask; import java.util.Vector; import net.rim.device.api.ui.Field; import net.rim.device.api.ui.Graphics; import net.rim.device.api.ui.XYRect; import net.rim.device.api.ui.container.MainScreen; public [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=v4ks1n.wordpress.com&amp;blog=7180005&amp;post=188&amp;subd=v4ks1n&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>here is the copy of tooltips class for BlackBerry,<br />
with 2 different approach.</p>
<p>first: [1]<br />
Easy solution to create popup style tooltips on BlackBerry.<br />
Extend TooltipScreen instead of the usual MainScreen, usage:</p>
<p>add(new ButtonField(&#8220;myButton&#8221;), &#8220;My Tooltip text&#8221;);<br />
and the source:</p>
<pre class="alt2" style="border:1px inset;overflow:auto;width:700px;height:450px;text-align:left;margin:0;padding:6px;">import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.XYRect;
import net.rim.device.api.ui.container.MainScreen;

public class TooltipScreen extends MainScreen {

    TooltipScreen screen = this;
    boolean doRedraw = false;//prevent infinte redrawing
    Vector tooltips = new Vector();//vector to hold tooltip strings
    private Timer tooltipTimer = new Timer();
    private TimerTask tooltipTask;
    boolean alive = false;//is the tooltip alive? used to pop it after our timeout
    int count = 0;//used to calculate time tooltip is displayed
    //tooltip popup colours:
    int backgroundColour = 0xeeeeee;
    int borderColour = 0xaaaaaa;
    int fontColour = 0x666666;
    //the tooltip:
    String tooltip;
    int tooltipWidth;
    int yCoord;
    int xCoord;
    //region parameters:
    XYRect contentArea;
    int contentBottom;
    int contentRight;

    public TooltipScreen() {
        super();

        //when timeout reaches 100ms*20 ie. 2seconds set alive to false and redraw screen:
        tooltipTask = new TimerTask() {

            public void run() {
                if (alive) {
                    count++;
                    if (count == 20) {
                        alive = false;
                        invalidate();
                    }
                }
            }
        };

        tooltipTimer.scheduleAtFixedRate(tooltipTask, 100, 100);

    }

    //override add method adds an empty string to tooltip vector:
    public void add(Field field) {
        tooltips.addElement("");
        super.add(field);
    }

    //custom add method for fields with tooltip: add(myField, "myTooltip");
    public void add(Field field, String tooltip) {
        super.add(field);
        tooltips.addElement(tooltip);
    }

    public void setColours(int backgroundColour, int borderColour, int fontColour) {
        this.backgroundColour = backgroundColour;
        this.borderColour = borderColour;
        this.fontColour = fontColour;
    }

    //reset everything when user changes focus,
    //possibly needs logic to check field has actually changed (for listfields, objectchoicefields etc etc)
    protected boolean navigationMovement(int dx, int dy, int status, int time) {
        count = 0;
        alive = true;
        doRedraw = true;
        return super.navigationMovement(dx, dy, status, time);
    }

    protected void paint(Graphics graphics) {
        super.paint(graphics);
        if (alive) {
            Field focusField = getFieldWithFocus();
            tooltip = (String) tooltips.elementAt(screen.getFieldWithFocusIndex());

            //don't do anything outside the norm unless this field has a tooltip:
            if (!tooltip.equals("")) {
                //get the field content region, this may fall inside the field actual region/coordinates:
                contentArea = focusField.getContentRect();
                contentBottom = contentArea.y + contentArea.height;
                contentRight = contentArea.x + contentArea.width;

                //+4 to accomodate 2 pixel padding on either side:
                tooltipWidth = graphics.getFont().getAdvance(tooltip) + 4;

                yCoord = contentBottom - focusField.getManager().getVerticalScroll();
                //check the tooltip is being drawn fully inside the screen height:
                if (yCoord &gt; (getHeight() - 30)) {
                    yCoord = getHeight() - 30;
                }

                //check the tooltip doesn't get drawn off the right side of the screen:
                if (contentRight + tooltipWidth &lt; getWidth()) {
                    xCoord = contentRight;
                } else {
                    xCoord = getWidth() - tooltipWidth;
                }

                //draw the tooltip
                graphics.setColor(backgroundColour);
                graphics.fillRect(xCoord, yCoord, tooltipWidth, 30);
                graphics.setColor(borderColour);
                graphics.drawRect(xCoord, yCoord, tooltipWidth, 30);
                graphics.setColor(fontColour);
                graphics.drawText(tooltip, xCoord + 2, yCoord);
            }
        }
        //doRedraw logic prevents infinite loop
        if (doRedraw) {
            //System.out.println("redrawing screen: " + System.currentTimeMillis());
            screen.invalidate();
            doRedraw = false;
        }
    }
}</pre>
<p>second: [2]</p>
<pre class="alt2" style="border:1px inset;overflow:auto;width:700px;height:450px;text-align:left;margin:0;padding:6px;">package ..;

/*

Display a 'Tooltip" (String) at a specified location for s specified time
This Tooltip can also be removed.
Note that in my testing, the display time is not consistent.

Following example shows it being added and removed using focus events.

ButtonField bf = new ButtonField("Test") {
    MyTooltip _tooltip;
    protected void onFocus(int direction) {
        if ( _tooltip != null ) {
            _tooltip.removeToolTip();
            _tooltip = null;
        }
        // Display tooltip at 50,50 for 5 seconds
        _tooltip = MyTooltip.addToolTip(UiApplication.getUiApplication(), "Press to test", 50, 50, 5);;
    }
    protected void onUnfocus() {
        if ( _tooltip != null ) {
            // We have displayed a Tooltip - remove it
            _tooltip.removeToolTip();
            _tooltip = null;
        }
    }
 };

*/

import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Screen;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.container.PopupScreen;

class MyTooltip extends PopupScreen{
    int _x;
    int _y;
    TooltipThread _tooltipThread;

    private MyTooltip(Manager manager) {
        super(manager);
     }
    public void sublayout(int width, int height)    {
        super.sublayout(width,height);
        setPosition(_x,_y);
        System.out.println("Tooltip x: " + Integer.toString(_x) + ", y: " + Integer.toString(_y));
    }
    protected void applyTheme() {
        // Overriden to suppress Border etc.
    }
    public void removeToolTip() {
        if ( _tooltipThread != null ) {
            _tooltipThread.dismiss();
        }
    }
    private void display(UiApplication uiApp, int x, int y, int displayTime) {
        _x = x;
        _y = y;
        _tooltipThread = new TooltipThread(uiApp, this, displayTime);
        _tooltipThread.start();
    }

    public static MyTooltip addToolTip(UiApplication uiApp, String toolTipString, int x, int y, int displayTime) {
        VerticalFieldManager manager = new VerticalFieldManager(Manager.FIELD_VCENTER|Manager.NON_FOCUSABLE) {
            protected void paint(Graphics graphics) {
                graphics.setColor(0x00FFFFFF); // White
                graphics.fillRect(0,0,getWidth(),getHeight());
                graphics.setColor(0x00000000); // Black
                graphics.drawRect(0,0,getWidth(),getHeight());
                super.paint(graphics);
            }
        };
        MyTooltip toolTip = new MyTooltip(manager);
        LabelField label = new LabelField(' ' + toolTipString + ' ', LabelField.NON_FOCUSABLE);
        label.setFont(Font.getDefault().derive(Font.PLAIN, 16));
        toolTip.add(label);
        toolTip.display(uiApp, x, y, displayTime);
        return toolTip;
    }

    class TooltipThread extends Thread {

        Object _notifyObject = new Object(); // Used to allow user to dismiss this Tooltip
        PopupScreen _tooltip; // Screen we are going to display
        UiApplication _ourApplication; // access to pushGlobalScreen and dismissStatus from our Application
        int _displayTime; // in seconds

        public TooltipThread(UiApplication ourApplication, PopupScreen tooltip, int displayTime) {
            _tooltip = tooltip;
            _ourApplication = ourApplication;
            _displayTime = displayTime;
        }

        public void run() {
            _ourApplication.pushGlobalScreen(_tooltip, 999, false);
            synchronized(_notifyObject) {
                try {
                    _notifyObject.wait(_displayTime * 1000);
                } catch (Exception e) {
                }
            };
            _ourApplication.dismissStatus(_tooltip);
        }

        public void dismiss() {
            // notify the waiting object to stop the Thread waiting
            synchronized(_notifyObject) {
                _notifyObject.notify();
            }
        }

    }

}</pre>
<p>[1] http://www.naviina.eu/wp/blackberry/390/<br />
[2] http://supportforums.blackberry.com/t5/Java-Development/Problem-with-Tooltip/td-p/102847</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/v4ks1n.wordpress.com/188/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/v4ks1n.wordpress.com/188/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/v4ks1n.wordpress.com/188/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/v4ks1n.wordpress.com/188/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/v4ks1n.wordpress.com/188/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/v4ks1n.wordpress.com/188/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/v4ks1n.wordpress.com/188/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/v4ks1n.wordpress.com/188/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/v4ks1n.wordpress.com/188/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/v4ks1n.wordpress.com/188/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/v4ks1n.wordpress.com/188/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/v4ks1n.wordpress.com/188/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/v4ks1n.wordpress.com/188/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/v4ks1n.wordpress.com/188/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=v4ks1n.wordpress.com&amp;blog=7180005&amp;post=188&amp;subd=v4ks1n&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://v4ks1n.wordpress.com/2011/01/28/tooltips-class-for-blackberry/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/276ef47c3a5018e58eb22d39eed513c9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">v4ks1n</media:title>
		</media:content>
	</item>
		<item>
		<title>Streaming Multimedia on BlackBerry</title>
		<link>http://v4ks1n.wordpress.com/2011/01/26/streaming-multimedia-on-blackberry/</link>
		<comments>http://v4ks1n.wordpress.com/2011/01/26/streaming-multimedia-on-blackberry/#comments</comments>
		<pubDate>Wed, 26 Jan 2011 04:58:55 +0000</pubDate>
		<dc:creator>v4ks1n</dc:creator>
				<category><![CDATA[blackberry]]></category>
		<category><![CDATA[audio]]></category>
		<category><![CDATA[connection]]></category>
		<category><![CDATA[multimedia]]></category>
		<category><![CDATA[streaming]]></category>
		<category><![CDATA[video]]></category>

		<guid isPermaLink="false">http://v4ks1n.wordpress.com/?p=185</guid>
		<description><![CDATA[Summary &#160; This article applies to the following: BlackBerry® Device Software 4.2.1 and later &#160; Details &#160; This article describes how to create a solid streaming media application and how to use the StreamingPlayer class, which is an open-source application programming interface (API) containing classes and methods that support streaming media. Basic Streaming Media There are [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=v4ks1n.wordpress.com&amp;blog=7180005&amp;post=185&amp;subd=v4ks1n&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h3>Summary</h3>
<p>&nbsp;</p>
<p>This article applies to the following:</p>
<blockquote>
<ul>
<li>BlackBerry® Device Software 4.2.1 and later</li>
</ul>
</blockquote>
<hr />
<p>&nbsp;</p>
<h3>Details</h3>
<p>&nbsp;</p>
<div>
<p>This article describes how to create a solid streaming media application and how to use the <code>StreamingPlayer</code> class, which is an open-source application programming interface (API) containing classes and methods that support streaming media.</p>
</div>
<div>
<h4>Basic Streaming Media</h4>
<p>There are two methods that can be used to stream media.</p>
<div>
<p>&nbsp;</p>
<h4>Streaming media over RTSP</h4>
<p>Real Time Streaming Protocol (RTSP) was first implemented in BlackBerry Device Software 4.3 for BlackBerry smartphones that operate on Code Division Multiple Access (CDMA) networks. RTSP is now supported by all BlackBerry smartphones running BlackBerry Device Software 4.5 and later. There are two ways to stream media content over RTSP.</p>
<p>&nbsp;</p>
<ul>
<div>
<li><strong>Using the browser (starts the Media application on the BlackBerry smartphone)</strong><code>String url = "rtsp://mystreamingserver.com/001.aac";Browser.getDefaultSession().displayPage(url);</code></li>
<li><strong>Using the Mobile Media API that is specified in JSR 135 (plays within an application)</strong><code>String url = "rtsp://mystreamingserver.com/001.aac";Player player = Manager.createPlayer(url);player.start();</code></li>
</div>
</ul>
</div>
<div>
<h4>Streaming media over HTTP</h4>
<p>Hypertext Transfer Protocol (HTTP) is a protocol that can stream media content and provide real-time playback. Like RTSP, there are two ways to stream media content over HTTP.</p>
<p>&nbsp;</p>
<ul>
<div>
<li><strong>Using the browser (starts the Media application on the BlackBerry smartphone)</strong>
<ul>
<li><code>String url = "http://mystreamingserver.com/001.mp3";</code></li>
<li><code>Browser.getDefaultSession().displayPage(url);</code></li>
</ul>
</li>
<li><strong>Using the Mobile Media API that is specified in JSR 135 (plays within an application)</strong>
<ul>
<li><code>String url = "http://mystreamingserver.com/001.mp3";</code></li>
<li><code>Player player = Manager.createPlayer(url);player.start();</code></li>
</ul>
</li>
</div>
</ul>
<h4>Advantages of streaming media over HTTP</h4>
<ul>
<div>
<li>API calls are simple to use.</li>
<li>This method hides many complex details.</li>
</div>
</ul>
<h4>Limitations of streaming media over HTTP</h4>
<ul>
<div>
<li>Raw data in the buffer cannot be accessed.</li>
<li>The data flow from the buffer to the media player cannot be controlled.</li>
<li>There is no <code>seek()</code> support prior to BlackBerry Device Software 5.0.</li>
<li>There is no access to the raw data stream.</li>
</div>
</ul>
</div>
</div>
<div>
<h4>Advanced streaming media</h4>
<p>The Mobile Media API (JSR 135) defines advanced APIs that you can use to control media streaming and allow flexibility in development. These APIs can be found in the<code> javax.microedition.media</code> package.</p>
<div>
<h4>Components of advanced streaming media</h4>
<p>The following diagram illustrates the different components and classes that are involved in streaming media and the data flow between a remote media source and the media player.</p>
<p>&nbsp;</p>
<table border="0" width="100%" align="center">
<tbody>
<tr>
<td><img title="1828i24A9F271819BF829" src="http://supportforums.blackberry.com/t5/image/serverpage/image-id/1828i24A9F271819BF829/image-size/original?v=mpbl-1&amp;px=-1" border="0" alt="1828i24A9F271819BF829" align="center" /></td>
</tr>
<tr>
<td></td>
</tr>
</tbody>
</table>
<div>
<h4>Source Media</h4>
<p>The media file that is located on a content server.</p>
<p>&nbsp;</p>
</div>
<div>
<h4>Download Thread</h4>
<p>A thread that connects to the source media and downloads the media file to the media buffer.</p>
</div>
<div>
<h4>Media Buffer</h4>
<p>A circular byte buffer for storing downloaded data until it is sent to media player for playback.</p>
</div>
<div>
<h4>SourceStream</h4>
<p>An instance of the <code>javax.microedition.media.protocol.SourceStream</code><code> class. The SourceStream</code> acts as an input stream for the media player by providing methods such as <code>read()</code> and <code>seek</code>().</p>
</div>
<div>
<h4>DataSource</h4>
<p>An instance of the <code>javax.microedition.media.protocol.DataSource</code>. DataSource class, and performs the following procedure:</p>
<ol>
<div>
<li>Open a connection to the remote source media.</li>
<li>Start the download thread.</li>
<li>Initialize and return <code>SourceStream</code> objects to play.</li>
<li>Close the connection.</li>
</div>
</ol>
</div>
<div>
<h4>Player</h4>
<p>An instance of <code>javax.microedition.media.Player</code>. The <code>Player</code> object plays media content as the content is downloaded. You can initialize a<code> Player</code>object by invoking</p>
<p><code>javax.microedition.media.Manager.createPlayer</code><code>(DataSource source)</code>.</p>
<p>&nbsp;</p>
</div>
</div>
<div>
<h4>Implementation</h4>
<p>The code sample that is included this article shows a complete implementation of all the components and classes that are mentioned. The code sample also includes a <code>StreamingPlayer</code> class and a <code>StreamingPlayerListener</code> interface that you can use as an API or extend to meet special use cases.</p>
</div>
<div>
<h4>Implementing the DataSource</h4>
<p><code>DataSource</code> is an abstract class and has six methods. Each of the following methods is invoked by the <code>Player</code> object:</p>
<p>&nbsp;</p>
<p><code>public void connect()</code></p>
<ul>
<div>
<li>Opens connections and input/output (I/O) streams</li>
</div>
</ul>
<p><code>public void disconnect()</code></p>
<ul>
<div>
<li>Closes connections, I/O streams, and so on</li>
</div>
</ul>
<p><code>public String getContentType()</code></p>
<ul>
<div>
<li>Returns the content type of the source media</li>
</div>
</ul>
<p><code>public SourceStream[] getStreams()</code></p>
<ul>
<div>
<li>Returns <code>SourceStream</code> objects</li>
</div>
</ul>
<p><code>public void start()</code></p>
<ul>
<div>
<li>Starts the download thread and begins downloading data</li>
</div>
</ul>
<p><code>public void stop()</code></p>
<ul>
<div>
<li>Stops downloading data</li>
</div>
</ul>
</div>
<div>
<h4>Implementing the SourceStream</h4>
<p><code>public ContentDescriptor getContentDescriptor()</code></p>
<ul>
<div>
<li>Returns a <code>ContentDescriptor</code> object based on the content type of the media</li>
</div>
</ul>
<p><code>public long getContentLength()</code></p>
<ul>
<div>
<li>Returns the content length.</li>
</div>
</ul>
<p><code>public int getSeekType()</code></p>
<ul>
<div>
<li>Returns <code>RANDOM_ACCESSIBLE</code>
<ul>
<div>
<li>Allows the <code>Player</code> to seek to nearby locations from the current position. <code>SourceStream RANDOM_ACCESSIBLE</code> must be set because video files can have audio and video at different offsets for each frame and the BlackBerry Device Software requires both for smooth playback. If -1 is returned by <code>getContentLength()</code>, the seek calls will only be to a previous position in the media file.</li>
</div>
</ul>
</li>
</div>
</ul>
<p><code>public int read(byte[] b, int off, int len)</code></p>
<ul>
<div>
<li>Sends data to the <code>Player</code>.</li>
<li>Blocks or resumes the feed,depending on the status of the buffer</li>
</div>
</ul>
<p><code>public long seek(long where)</code></p>
<ul>
<div>
<li>Called by the <code>Player</code> to seek to a point between 0 and the content length</li>
<li>Implementation varies based the following connection types:</li>
<li>HTTP streaming
<ul>
<div>
<li>Uses this method only if <code>seek() </code>is feasible.</li>
<li><code>seek()</code> point is within the buffered data. Otherwise, return the current position.</li>
</div>
</ul>
</li>
<li>FileConnection streaming
<ul>
<div>
<li>Uses this method with<code> mark()</code>, <code>reset()</code> and <code>skip()</code></li>
</div>
</ul>
</li>
</div>
</ul>
<p><code>public long tell()</code></p>
<ul>
<div>
<li>Returns the current position in the stream</li>
</div>
</ul>
<h4>How to handle user-initiated seek()</h4>
<p>There are two types of user-initiated seek calls. In both cases, <code>Player.setMediaTime(long microseconds)</code> must be invoked, which in turn invokes<code>SourceStream.seek(long position)</code>.</p>
<ul>
<div>
<li><strong>Seek calls within available data</strong>
<ul>
<div>
<li>Invoke <code>seek</code>() within the buffer using <code>mark()</code>, <code>reset()</code> or <code>skip()</code><br />
<table border="0" width="100%" align="center">
<tbody>
<tr>
<td><img title="1829iDBC451CCF5CA4D3D" src="http://supportforums.blackberry.com/t5/image/serverpage/image-id/1829iDBC451CCF5CA4D3D/image-size/original?v=mpbl-1&amp;px=-1" border="0" alt="1829iDBC451CCF5CA4D3D" align="center" /></td>
</tr>
<tr>
<td></td>
</tr>
</tbody>
</table>
</li>
</div>
</ul>
</li>
</div>
</ul>
<ul>
<div>
<li><strong>Seek calls beyond the data that is available</strong>
<ul>
<div>
<li>Block the feed to the <code>Player</code>.</li>
<li>Stop downloading data.</li>
<li>Close the HTTP connection.</li>
<li>Reopen the connection using the HTTP range header to get data from the seek position.</li>
<li>Start downloading using the new connection.</li>
<li>Resume the feed to the <code>Player</code> when buffer contains enough information.</li>
</div>
</ul>
<table border="0" width="100%" align="center">
<tbody>
<tr>
<td><img title="1830i3391D28D515A6667" src="http://supportforums.blackberry.com/t5/image/serverpage/image-id/1830i3391D28D515A6667/image-size/original?v=mpbl-1&amp;px=-1" border="0" alt="1830i3391D28D515A6667" align="center" /></td>
</tr>
<tr>
<td></td>
</tr>
</tbody>
</table>
</li>
</div>
</ul>
<h4>Stream control</h4>
<p>Because media is streaming over a wireless network, there must be a mechanism to stop data feed to the <code>Player</code> when the buffer runs out of space due to of network delay. There must also be a way to determine how much of the buffer should be filled before restarting or resuming playback. Downloaded data in the buffer must be held as long as possible to allow for backward seek calls made by the <code>Player</code>, but when buffer is full the data must be discarded to download more data. You can use the following variables to control the feed to the<code> Player</code>:</p>
<ol>
<div>
<li><code>initialBuffer</code>Determines how much data to buffer before playback starts for the first time. This variable can be determined dynamically by the following criteria:
<ul>
<div>
<li>Connection type</li>
<li>Bit rate</li>
<li>Bandwidth and latency</li>
</div>
</ul>
</li>
<li><code>restartThreshold</code>Determines when to resume the data feed to the <code>Player</code> based on the data that is available in the buffer. This variable can be determined dynamically by the following criteria:
<ul>
<div>
<li>Connection type</li>
<li>Bit rate</li>
<li>Bandwidth and latency</li>
</div>
</ul>
</li>
<li><code>bufferCapacity</code>Determines the size of the buffer where data is stored. This variable can be determined dynamically by the following criteria:
<ul>
<div>
<li>Connection type</li>
<li>Bit rate</li>
<li>Bandwidth and latency</li>
<li>If a buffer is too small, it can frequently run out of space.</li>
<li>If a buffer too big, it can waste system resources.</li>
</div>
</ul>
</li>
<li><code>bufferLeakSize</code>Video playback requires the <code>Player</code> to seek back from the current position because audio and video data for the same frame are at different offsets. To accommodate this situation, downloaded data is stored until the <code>Player </code>is at the end of the buffer and the buffer is full. This method requires that more data must be downloaded for the playback to continue. In this situation, the oldest data is discarded first to create space for downloading more data.<code>bufferLeakSize</code> determines how much data is discarded each time this occurs.</li>
</div>
</ol>
<h4>Creating a Player from a DataSource</h4>
<p>To create a <code>Player</code> from a <code>DataSource,</code> use the following code:</p>
<p><code>Player player = Manager.createPlayer(new MyDataSource());player.start();</code></p>
<p>&nbsp;</p>
</div>
</div>
<div>
<h4>Using the right transport method</h4>
<p>Wi-Fi® technology is the preferred transport because it is fast and free. If a Wi-Fi connection becomes available during a streaming session, it is recommended that the <code>Player</code> dynamically switch to the Wi-Fi connection after prompting the BlackBerry smartphone user to do so. If a Wi-Fi connection is not available, transport methods that are used by wireless service providers, such as Wireless Application Protocol (WAP/WAP2) or Transmission Control Protocol (TCP), are recommended. Using the BlackBerry® Mobile Data System (BlackBerry MDS) or the BlackBerry® Internet Service is not recommended because media streaming results in large data usage through these transport methods. Both the BlackBerry MDS and BlackBerry Internet Service also result in added latency because the data travels through the BlackBerry® Infrastructure.</p>
</div>
<div>
<h4>Downloads</h4>
<p>A complete implementation of a streaming media application is available to download. This example application uses the <code>StreamingPlayer</code> class and<code>StreamingPlayerListener</code> class as libraries, and can be used in your application to stream media over HTTP. This application will only play the media files that are supported by the target BlackBerry smartphone. Make sure that you type the web page and content type of your media file on the Options screen of the application before pressing play.</p>
<p>&nbsp;</p>
<p><strong>Note: </strong>The API needs an implementation of a thread safe Circular Byte Buffer. You can copy the implementation as CircularByteBuffer.java to rimx.media.streaming package and then complile the project. For an example, click <a href="http://ostermiller.org/utils/CircularByteBuffer.java.html">here</a>.</p>
<p>&nbsp;</p>
<table border="0" width="100%" align="center">
<tbody>
<tr>
<td><img title="1831i1650ADCE11412CDA" src="http://supportforums.blackberry.com/t5/image/serverpage/image-id/1831i1650ADCE11412CDA/image-size/original?v=mpbl-1&amp;px=-1" border="0" alt="1831i1650ADCE11412CDA" align="center" /></td>
</tr>
<tr>
<td>&nbsp;</p>
<p>Refer to attachment section below to download the example application, including the libraries.</td>
</tr>
</tbody>
</table>
<p>&nbsp;</p>
</div>
<p>&nbsp;</p>
<p>[1] http://supportforums.blackberry.com/t5/Java-Development/Streaming-media-Start-to-finish/ta-p/488255</p>
<p><a href="http://v4ks1n.files.wordpress.com/2011/01/streamingplayer-zip-rename.pdf">streamingplayersampleapp__download_pdf_renameto_zip</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/v4ks1n.wordpress.com/185/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/v4ks1n.wordpress.com/185/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/v4ks1n.wordpress.com/185/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/v4ks1n.wordpress.com/185/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/v4ks1n.wordpress.com/185/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/v4ks1n.wordpress.com/185/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/v4ks1n.wordpress.com/185/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/v4ks1n.wordpress.com/185/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/v4ks1n.wordpress.com/185/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/v4ks1n.wordpress.com/185/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/v4ks1n.wordpress.com/185/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/v4ks1n.wordpress.com/185/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/v4ks1n.wordpress.com/185/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/v4ks1n.wordpress.com/185/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=v4ks1n.wordpress.com&amp;blog=7180005&amp;post=185&amp;subd=v4ks1n&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://v4ks1n.wordpress.com/2011/01/26/streaming-multimedia-on-blackberry/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
<enclosure url="http://mystreamingserver.com/001.mp3" length="0" type="audio/mpeg" />
	
		<media:content url="http://0.gravatar.com/avatar/276ef47c3a5018e58eb22d39eed513c9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">v4ks1n</media:title>
		</media:content>

		<media:content url="http://supportforums.blackberry.com/t5/image/serverpage/image-id/1828i24A9F271819BF829/image-size/original?v=mpbl-1&#38;px=-1" medium="image">
			<media:title type="html">1828i24A9F271819BF829</media:title>
		</media:content>

		<media:content url="http://supportforums.blackberry.com/t5/image/serverpage/image-id/1829iDBC451CCF5CA4D3D/image-size/original?v=mpbl-1&#38;px=-1" medium="image">
			<media:title type="html">1829iDBC451CCF5CA4D3D</media:title>
		</media:content>

		<media:content url="http://supportforums.blackberry.com/t5/image/serverpage/image-id/1830i3391D28D515A6667/image-size/original?v=mpbl-1&#38;px=-1" medium="image">
			<media:title type="html">1830i3391D28D515A6667</media:title>
		</media:content>

		<media:content url="http://supportforums.blackberry.com/t5/image/serverpage/image-id/1831i1650ADCE11412CDA/image-size/original?v=mpbl-1&#38;px=-1" medium="image">
			<media:title type="html">1831i1650ADCE11412CDA</media:title>
		</media:content>
	</item>
		<item>
		<title>Implementing JSON in BlackBerry Application</title>
		<link>http://v4ks1n.wordpress.com/2011/01/25/implementing-json-in-blackberry-application/</link>
		<comments>http://v4ks1n.wordpress.com/2011/01/25/implementing-json-in-blackberry-application/#comments</comments>
		<pubDate>Tue, 25 Jan 2011 12:35:05 +0000</pubDate>
		<dc:creator>v4ks1n</dc:creator>
				<category><![CDATA[blackberry]]></category>
		<category><![CDATA[javame]]></category>
		<category><![CDATA[JSON]]></category>

		<guid isPermaLink="false">http://v4ks1n.wordpress.com/?p=180</guid>
		<description><![CDATA[JavaScript Object Notation (JSON) is a lightweight, low overhead, method of describing objects. This notation can be extremely useful when implemented as an alternative to web services though does typically require a bit more coding to handle how the custom data types are converted to and from JSON format. However, as this is controlled by [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=v4ks1n.wordpress.com&amp;blog=7180005&amp;post=180&amp;subd=v4ks1n&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>JavaScript Object Notation (JSON) is a lightweight, low overhead, method of describing objects. This notation can be extremely useful when implemented as an alternative to web services though does typically require a bit more coding to handle how the custom data types are converted to and from JSON format. However, as this is controlled by code and JSON handles most primitive data types that are common among programming languages, it can also be used as a communication medium between systems and applications built on different programming languages. Libraries for various languages have already been created and are ready to implement. For more information on these please refer to the JSON home page. This site also contains lots of background information about JSON and some source code.</p>
<p>The sample attached below shows a basic cake ordering system that helps construct a CakeObject that it then converted into a JSON String. This example will help familiarize you with the steps required to implement JSON in your own application as well as determine the benefit of its use and the way different data types are formatted once converted to JSON. It contains two projects, the application and the JSON ME library source code. These will need to be set up so that the application depends on the library in order to compile and test.</p>
<p>[1] http://supportforums.blackberry.com/t5/Java-Development/Sample-Code-Implementing-JSON-in-your-application/ta-p/539659<br />
[2] https://meapplicationdevelopers.dev.java.net/source/browse/meapplicationdevelopers/demobox/mobileajax/lib/json/src/org/json/me/</p>
<p><a href="http://v4ks1n.files.wordpress.com/2011/01/json_lib_javame-zip-rename.pdf">jsonlib_javame__download_pdf_and_renameto_zip</a><br />
<a href="http://v4ks1n.files.wordpress.com/2011/01/jsondemoapp-zip-rename.pdf">JSONDemoApp__download_pdf_renameto_zip</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/v4ks1n.wordpress.com/180/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/v4ks1n.wordpress.com/180/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/v4ks1n.wordpress.com/180/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/v4ks1n.wordpress.com/180/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/v4ks1n.wordpress.com/180/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/v4ks1n.wordpress.com/180/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/v4ks1n.wordpress.com/180/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/v4ks1n.wordpress.com/180/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/v4ks1n.wordpress.com/180/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/v4ks1n.wordpress.com/180/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/v4ks1n.wordpress.com/180/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/v4ks1n.wordpress.com/180/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/v4ks1n.wordpress.com/180/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/v4ks1n.wordpress.com/180/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=v4ks1n.wordpress.com&amp;blog=7180005&amp;post=180&amp;subd=v4ks1n&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://v4ks1n.wordpress.com/2011/01/25/implementing-json-in-blackberry-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/276ef47c3a5018e58eb22d39eed513c9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">v4ks1n</media:title>
		</media:content>
	</item>
		<item>
		<title>BlackBerry (JavaME) String Manipulation &#8211; split, replace, replaceAll</title>
		<link>http://v4ks1n.wordpress.com/2011/01/25/blackberry-javame-string-manipulation-split-replace-replaceall/</link>
		<comments>http://v4ks1n.wordpress.com/2011/01/25/blackberry-javame-string-manipulation-split-replace-replaceall/#comments</comments>
		<pubDate>Tue, 25 Jan 2011 02:10:52 +0000</pubDate>
		<dc:creator>v4ks1n</dc:creator>
				<category><![CDATA[blackberry]]></category>
		<category><![CDATA[javame]]></category>
		<category><![CDATA[replace]]></category>
		<category><![CDATA[replaceAll]]></category>
		<category><![CDATA[split]]></category>
		<category><![CDATA[String Manipulation]]></category>

		<guid isPermaLink="false">http://v4ks1n.wordpress.com/?p=177</guid>
		<description><![CDATA[The String class in the BlackBerry API set is defined on the J2ME® specification, which doesn&#8217;t include all methods available in J2SE. RIM has provided a StringUtilities class that contains some of the J2SE methods. This article provides some additional methods that aren&#8217;t included in the String and StringUtilities classes. public String[] split(String strString, String [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=v4ks1n.wordpress.com&amp;blog=7180005&amp;post=177&amp;subd=v4ks1n&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The String class in the BlackBerry API set is defined on the J2ME® specification, which doesn&#8217;t include all methods available in J2SE.  RIM has provided a StringUtilities class that contains some of the J2SE methods.  This article provides some additional methods that aren&#8217;t included in the String and StringUtilities classes.</p>
<pre class="alt2" style="border:1px inset;overflow:auto;width:700px;height:450px;text-align:left;margin:0;padding:6px;">
public String[] split(String strString, String strDelimiter)
	{
		int iOccurrences = 0;
		int iIndexOfInnerString = 0;
		int iIndexOfDelimiter = 0;
		int iCounter = 0;

		// Check for null input strings.
		if (strString == null)
		{
			throw new NullPointerException("Input string cannot be null.");
		}
		// Check for null or empty delimiter
		// strings.
		if (strDelimiter.length() &lt;= 0 || strDelimiter == null)
		{
			throw new NullPointerException(&quot;Delimeter cannot be null or empty.&quot;);
		}

		// If strString begins with delimiter
		// then remove it in
		// order
		// to comply with the desired format.

		if (strString.startsWith(strDelimiter))
		{
			strString = strString.substring(strDelimiter.length());
		}

		// If strString does not end with the
		// delimiter then add it
		// to the string in order to comply with
		// the desired format.
		if (!strString.endsWith(strDelimiter))
		{
			strString += strDelimiter;
		}

		// Count occurrences of the delimiter in
		// the string.
		// Occurrences should be the same amount
		// of inner strings.
		while((iIndexOfDelimiter= strString.indexOf(strDelimiter,iIndexOfInnerString))!=-1)
		{
			iOccurrences += 1;
			iIndexOfInnerString = iIndexOfDelimiter + strDelimiter.length();
		}

		// Declare the array with the correct
		// size.
		String[] strArray = new String[iOccurrences];

		// Reset the indices.
		iIndexOfInnerString = 0;
		iIndexOfDelimiter = 0;

		// Walk across the string again and this
		// time add the
		// strings to the array.
		while((iIndexOfDelimiter= strString.indexOf(strDelimiter,iIndexOfInnerString))!=-1)
		{

			// Add string to
			// array.
			strArray[iCounter] = strString.substring(iIndexOfInnerString, iIndexOfDelimiter);

			// Increment the
			// index to the next
			// character after
			// the next
			// delimiter.
			iIndexOfInnerString = iIndexOfDelimiter + strDelimiter.length();

			// Inc the counter.
			iCounter += 1;
		}
            return strArray;
	}
</pre>
<pre class="alt2" style="border:1px inset;overflow:auto;width:700px;height:450px;text-align:left;margin:0;padding:6px;">
public String replace(String source, String pattern, String replacement)
	{	

		//If source is null then Stop
		//and return empty String.
		if (source == null)
		{
			return "";
		}

		StringBuffer sb = new StringBuffer();
		//Intialize Index to -1
		//to check against it later
		int idx = -1;
		//Intialize pattern Index
		int patIdx = 0;
		//Search source from 0 to first occurrence of pattern
		//Set Idx equal to index at which pattern is found.
		idx = source.indexOf(pattern, patIdx);
		//If Pattern is found, idx will not be -1 anymore.
		if (idx != -1)
		{
			//append all the string in source till the pattern starts.
			sb.append(source.substring(patIdx, idx));
			//append replacement of the pattern.
			sb.append(replacement);
			//Increase the value of patIdx
			//till the end of the pattern
			patIdx = idx + pattern.length();
			//Append remaining string to the String Buffer.
			sb.append(source.substring(patIdx));
		}
		//Return StringBuffer as a String

                if ( sb.length() == 0)
                {
                    return source;
                }
                else
                {
                    return sb.toString();
                }
	}
</pre>
<pre class="alt2" style="border:1px inset;overflow:auto;width:700px;height:450px;text-align:left;margin:0;padding:6px;">
public String replaceAll(String source, String pattern, String replacement)
{    

    //If source is null then Stop
    //and retutn empty String.
    if (source == null)
    {
        return "";
    }

    StringBuffer sb = new StringBuffer();
    //Intialize Index to -1
    //to check agaist it later
    int idx = -1;
    //Search source from 0 to first occurrence of pattern
    //Set Idx equal to index at which pattern is found.

    String workingSource = source;

    //Iterate for the Pattern till idx is not be -1.
    while ((idx = workingSource.indexOf(pattern)) != -1)
    {
        //append all the string in source till the pattern starts.
        sb.append(workingSource.substring(0, idx));
        //append replacement of the pattern.
        sb.append(replacement);
        //Append remaining string to the String Buffer.
        sb.append(workingSource.substring(idx + pattern.length()));

        //Store the updated String and check again.
        workingSource = sb.toString();

        //Reset the StringBuffer.
        sb.delete(0, sb.length());
    }

    return workingSource;
}
</pre>
<p>[1] http://supportforums.blackberry.com/t5/Java-Development/String-Manipulation-split-replace-replaceAll/ta-p/620038</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/v4ks1n.wordpress.com/177/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/v4ks1n.wordpress.com/177/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/v4ks1n.wordpress.com/177/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/v4ks1n.wordpress.com/177/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/v4ks1n.wordpress.com/177/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/v4ks1n.wordpress.com/177/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/v4ks1n.wordpress.com/177/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/v4ks1n.wordpress.com/177/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/v4ks1n.wordpress.com/177/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/v4ks1n.wordpress.com/177/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/v4ks1n.wordpress.com/177/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/v4ks1n.wordpress.com/177/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/v4ks1n.wordpress.com/177/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/v4ks1n.wordpress.com/177/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=v4ks1n.wordpress.com&amp;blog=7180005&amp;post=177&amp;subd=v4ks1n&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://v4ks1n.wordpress.com/2011/01/25/blackberry-javame-string-manipulation-split-replace-replaceall/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/276ef47c3a5018e58eb22d39eed513c9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">v4ks1n</media:title>
		</media:content>
	</item>
		<item>
		<title>Invoke the browser with raw HTML</title>
		<link>http://v4ks1n.wordpress.com/2011/01/25/invoke-the-browser-with-raw-html/</link>
		<comments>http://v4ks1n.wordpress.com/2011/01/25/invoke-the-browser-with-raw-html/#comments</comments>
		<pubDate>Tue, 25 Jan 2011 01:57:54 +0000</pubDate>
		<dc:creator>v4ks1n</dc:creator>
				<category><![CDATA[blackberry]]></category>
		<category><![CDATA[base64]]></category>
		<category><![CDATA[browser]]></category>
		<category><![CDATA[invoke]]></category>
		<category><![CDATA[raw HTML]]></category>

		<guid isPermaLink="false">http://v4ks1n.wordpress.com/?p=173</guid>
		<description><![CDATA[On the BrowserField2 (BlackBerry OS 5 and OS 6) the BrowserField has method to load the content from the String HTML raw. this is the code for the previous version of BlackBerry OS, how to invoke the browser with the raw HTML. The mechanism for using the BlackBerry Browser to invoke the browser with raw [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=v4ks1n.wordpress.com&amp;blog=7180005&amp;post=173&amp;subd=v4ks1n&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>On the BrowserField2 (BlackBerry OS 5 and OS 6) the BrowserField has method to load the content from the String HTML raw.</p>
<p>this is the code for the previous version of BlackBerry OS, how to invoke the browser with the raw HTML.</p>
<p>The mechanism for using the BlackBerry Browser to invoke the browser with raw HTML content is shown in the sample code below. The key aspect of the code is the section where you pass in the following string to the browser at the start of the data sequence:</p>
<p><strong>data:text/html;base64,</strong></p>
<pre class="alt2" style="border:1px inset;overflow:auto;width:700px;height:450px;text-align:left;margin:0;padding:6px;">/*
* RawHTMLBrowserSample.java
*
* © Research In Motion Limited, 2007
* Confidential and proprietary.
*/

import java.io.*;
import javax.microedition.io.*;
import net.rim.blackberry.api.browser.*;
import net.rim.device.api.io.*;
import net.rim.device.api.system.*;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.util.*;

/**
* A simple example of how to invoke the BlackBerry Browser using
* raw HTML data.
*/
public class RawHTMLBrowserSample extends UiApplication
{
    public static void main( String[] args )
    {
        RawHTMLBrowserSample sample = new RawHTMLBrowserSample();
        sample.enterEventDispatcher();
    }

    /**
    * Create the splash screen and start off the networking
    * thread that will eventually invoke the browser.
    */
    public RawHTMLBrowserSample()
    {
        MainScreen splashScreen = new MainScreen();
        splashScreen.add( new RichTextField( "Please Wait..." ));
        pushScreen( splashScreen );
        MyThread thread = new MyThread();
        thread.start();
    }
    private static class MyThread extends Thread
    {
        public void run()
        {
            try {
            // Open the connection and the input stream. Select your own URL.
            HttpConnection connection = (HttpConnection)Connector.open( "http://www.blackberry.com:80" );
            InputStream input = connection.openInputStream();
            DataBuffer buffer = new DataBuffer();
            byte[] temp = new byte[ 1024 ];
            // Read in the web page to the DataBuffer.
            for( ;; ) {
                int bytesRead = input.read( temp );
                if( bytesRead == -1 ) {
                    break;
                }
                buffer.write( temp, 0, bytesRead );
            }
            input.close();
            connection.close();
            // Create an output stream that will be used by the Base64 code.
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            Base64OutputStream boutput = new Base64OutputStream( output );
            // Write out the special sequence which indicates to the browser
            // that it should treat this as HTML data in base64 format.
            output.write( "data:text/html;base64,".getBytes() );
            boutput.write( buffer.getArray() );
            boutput.flush();
            boutput.close();
            output.flush();
            output.close(); // Invoke the browser with the encoded HTML content.
            BrowserSession bSession = Browser.getDefaultSession();
            bSession.displayPage( output.toString() );
        } catch( IOException e ) {
            System.out.println( "IOException: " + e );
        }
    }
}
}</pre>
<p>The browser uses the sequence to base64 decode the string following the comma and displays it in the browser. When displaying the page, images and other items do not appear because the browser cannot fetch them.</p>
<p>This article applies to BlackBerry® Device Software 4.2 and later.</p>
<p>[1] http://www.blackberry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/796557/800332/800440/How_To_-_Invoke_the_browser_with_raw_HTML.html?nodeid=1313878&amp;vernum=0?CPID=EMC-DM2007M-37</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/v4ks1n.wordpress.com/173/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/v4ks1n.wordpress.com/173/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/v4ks1n.wordpress.com/173/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/v4ks1n.wordpress.com/173/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/v4ks1n.wordpress.com/173/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/v4ks1n.wordpress.com/173/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/v4ks1n.wordpress.com/173/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/v4ks1n.wordpress.com/173/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/v4ks1n.wordpress.com/173/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/v4ks1n.wordpress.com/173/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/v4ks1n.wordpress.com/173/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/v4ks1n.wordpress.com/173/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/v4ks1n.wordpress.com/173/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/v4ks1n.wordpress.com/173/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=v4ks1n.wordpress.com&amp;blog=7180005&amp;post=173&amp;subd=v4ks1n&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://v4ks1n.wordpress.com/2011/01/25/invoke-the-browser-with-raw-html/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/276ef47c3a5018e58eb22d39eed513c9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">v4ks1n</media:title>
		</media:content>
	</item>
		<item>
		<title>Check The Network Coverage on BlackBerry</title>
		<link>http://v4ks1n.wordpress.com/2011/01/25/check-the-network-coverage-on-blackberry/</link>
		<comments>http://v4ks1n.wordpress.com/2011/01/25/check-the-network-coverage-on-blackberry/#comments</comments>
		<pubDate>Tue, 25 Jan 2011 01:48:34 +0000</pubDate>
		<dc:creator>v4ks1n</dc:creator>
				<category><![CDATA[blackberry]]></category>
		<category><![CDATA[BIS_B]]></category>
		<category><![CDATA[connection]]></category>
		<category><![CDATA[coverage]]></category>

		<guid isPermaLink="false">http://v4ks1n.wordpress.com/?p=169</guid>
		<description><![CDATA[Here&#8217;s the code from the BlackBerry PUSH API about the how to check the Network Coverage on the BlackBerry: public static boolean hasCoverage() { boolean bisCoverage = CoverageInfo.isCoverageSufficient( CoverageInfo.COVERAGE_BIS_B ); boolean carrierCoverage = false; carrierCoverage = CoverageInfo.isCoverageSufficient( CoverageInfo.COVERAGE_DIRECT ); return bisCoverage &#124;&#124; carrierCoverage; } [1] http://us.blackberry.com/developers/platform/pushapi.jsp<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=v4ks1n.wordpress.com&amp;blog=7180005&amp;post=169&amp;subd=v4ks1n&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s the code from the BlackBerry PUSH API about the how to check the Network Coverage on the BlackBerry:</p>
<pre class="alt2" style="border:1px inset;overflow:auto;width:700px;height:150px;text-align:left;margin:0;padding:6px;">public static boolean hasCoverage() {
       boolean bisCoverage = CoverageInfo.isCoverageSufficient( CoverageInfo.COVERAGE_BIS_B );
       boolean carrierCoverage = false;
       carrierCoverage = CoverageInfo.isCoverageSufficient( CoverageInfo.COVERAGE_DIRECT );
       return bisCoverage || carrierCoverage;
}</pre>
<p>[1] http://us.blackberry.com/developers/platform/pushapi.jsp</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/v4ks1n.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/v4ks1n.wordpress.com/169/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/v4ks1n.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/v4ks1n.wordpress.com/169/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/v4ks1n.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/v4ks1n.wordpress.com/169/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/v4ks1n.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/v4ks1n.wordpress.com/169/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/v4ks1n.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/v4ks1n.wordpress.com/169/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/v4ks1n.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/v4ks1n.wordpress.com/169/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/v4ks1n.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/v4ks1n.wordpress.com/169/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=v4ks1n.wordpress.com&amp;blog=7180005&amp;post=169&amp;subd=v4ks1n&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://v4ks1n.wordpress.com/2011/01/25/check-the-network-coverage-on-blackberry/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/276ef47c3a5018e58eb22d39eed513c9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">v4ks1n</media:title>
		</media:content>
	</item>
		<item>
		<title>Download large files using the BlackBerry Mobile Data System</title>
		<link>http://v4ks1n.wordpress.com/2010/08/04/download-large-files-using-the-blackberry-mobile-data-system/</link>
		<comments>http://v4ks1n.wordpress.com/2010/08/04/download-large-files-using-the-blackberry-mobile-data-system/#comments</comments>
		<pubDate>Wed, 04 Aug 2010 18:43:40 +0000</pubDate>
		<dc:creator>v4ks1n</dc:creator>
				<category><![CDATA[blackberry]]></category>
		<category><![CDATA[blackberry mobile data system]]></category>
		<category><![CDATA[connection]]></category>
		<category><![CDATA[download]]></category>
		<category><![CDATA[file split]]></category>
		<category><![CDATA[http range request header]]></category>
		<category><![CDATA[large file]]></category>
		<category><![CDATA[partial]]></category>

		<guid isPermaLink="false">http://v4ks1n.wordpress.com/?p=165</guid>
		<description><![CDATA[Background The size of files that can be downloaded to the BlackBerry smartphone using the BlackBerry® Mobile Data System (BlackBerry MDS) is limited due to storage availability on the BlackBerry smartphone and the cost of transferring data wirelessly. The BlackBerry MDS uses the Multipurpose Internet Mail Extensions (MIME) type reported by the web server to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=v4ks1n.wordpress.com&amp;blog=7180005&amp;post=165&amp;subd=v4ks1n&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h2>Background</h2>
<p>The size of files that can be downloaded to the BlackBerry smartphone using the BlackBerry® Mobile Data System (BlackBerry MDS) is limited due to storage availability on the BlackBerry smartphone and the cost of transferring data wirelessly. The BlackBerry MDS uses the Multipurpose Internet Mail Extensions (MIME) type reported by the web server to determine which file limit should be applied. This file limit may also include any additional overhead from the web server, and will apply both before and after transcoding is done by the BlackBerry MDS. BlackBerry MDS provides a response code of <strong>413</strong> if the file size is too big. For standard Hypertext Transfer Protocol (HTTP) file downloading, as is done in the following example, there is no additional overhead or transcoding. For more information on BlackBerry MDS file settings and response code 413, see <a href="http://www.blackberry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/800451/800563/What_Is_-_HTTP_413_Request_Entity_Too_Large.html?nodeid=1372369&amp;vernum=0">DB-00623</a>.</p>
<p><strong>HTTP Range request header</strong></p>
<p>If it is supported by the server, the Range header can be used to make individual requests for parts of a file. By keeping these file range requests below the limit of an individual file, larger files can be downloaded in parts and recombined on the BlackBerry smartphone. The file does not have to be separated into chunks on the server using this approach. The following example uses the Range header to request a file in several parts.</p>
<p><strong>Note: </strong>The use of response code 206 for partial content and downloading the file correctly is based entirely on calculating the correct byte range to request. The same approach could be used to resume downloading interrupted transfers.</p>
<pre class="alt2" style="border:1px inset;overflow:auto;width:500px;height:450px;text-align:left;margin:0;padding:6px;">private class DownloadCombiner extends Thread {
    private String remoteName;
    private String localName;
    private int connection;
    private int chunksize;
    public DownloadCombiner(String remoteName,
        String localName, int connection, int chunksize) {
        this.remoteName = remoteName;
        this.localName = localName;
        this.connection = connection;
        this.chunksize = chunksize;
    }
    public void run() {
        try {
            int chunkIndex = 0;
            int totalSize = 0;

            /*
             * File connection
             */
            FileConnection file =(FileConnection)Connector.open(localName);
            if (!file.exists()) {
                file.create();
            file.setWritable(true);
            OutputStream out = file.openOutputStream();

            /*
             * HTTP Connections
             */
            String currentFile = remoteName + connectionType();
            log("Full URL: " + currentFile);
            HttpConnection conn;
            InputStream in;
            int rangeStart = 0;
            int rangeEnd = 0;
            while (true) {
                log("Opening Chunk: " + chunkIndex);
                conn = (HttpConnection) Connector.open(currentFile,
                        Connector.READ_WRITE, true);
                rangeStart = chunkIndex * chunksize;
                rangeEnd = rangeStart + chunksize - 1;
                log("Requesting Range: " + rangeStart +
                     "-" + rangeEnd);
                conn.setRequestProperty("Range", "bytes=" +
                     rangeStart + "-" + rangeEnd);
                int responseCode = conn.getResponseCode();
                if (responseCode != 200 &amp;&amp; responseCode != 206)
                {
                    log("Response Code = " + conn.getResponseCode());
                    break;
                }
                log("Retreived Range: " + conn.getHeaderField("Content-Range"));
                in = conn.openInputStream();
                int length = -1;
                byte[] readBlock = new byte[256];
                int fileSize = 0;
                while ((length = in.read(readBlock)) != -1) {
                    out.write(readBlock, 0, length);
                    fileSize += length;
                    Thread.yield(); // Try not to get cut off
                }
                totalSize += fileSize;
                log("Chunk Downloaded: " + fileSize + " Bytes");
                chunkIndex++; // index (range) increase
                in.close();
                conn.close();
                in = null;
                conn = null;
                /*
                 * Pause to allow connections to close and other Threads
                 * to run.
                 */
                 Thread.sleep(1000);
            }
            log("Full file downloaded: " + totalSize + " Bytes");
            out.close();
            file.close();
            log("Wrote file to local storage");
            } catch (Exception e) {
                 log(e.toString());
            }
        }
    private String connectionType() {
        switch (connection) {
            case 1:
                return ";deviceside=false";
            case 2:
                return ";deviceside=true;interface=wifi";
            default:
                return ";deviceside=true";
        }
    }
}</pre>
<h2>File splitting</h2>
<p>A large file can be downloaded to the BlackBerry smartphone by splitting the file into multiple parts and then downloading each part to the microSD card, where the parts can be recombined into the original file.</p>
<p>The following code segment describes a scheme for splitting a file into defined part sizes. The file parts are labeled with the original filename and a part ID.</p>
<pre class="alt2" style="border:1px inset;overflow:auto;width:500px;height:450px;text-align:left;margin:0;padding:6px;">
public void splitFile() throws Exception {
    BufferedInputStream input = new BufferedInputStream(new FileInputStream(_file));
    byte[] readBlock = new byte[_chunksize];
    int chunkFileId = 0;
    int length = -1;
    while ((length = input.read(readBlock)) != -1) {
        String chunkFileName = _file.getName() + "." + chunkFileId++;
        BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(chunkFileName));
        output.write(readBlock, 0, length);
        output.flush();
        output.close();
        System.out.println("Wrote Chunk file " + chunkFileName + " of " + length + " Bytes");
    }
    System.out.println("Completed Splitting " + _file.getName());
}</pre>
<h2>File downloading</h2>
<p>Once the file has been split into a series of parts, each part can be downloaded in order and written out to one file on the microSD card.</p>
<p><strong>Note: </strong>The response code is used to determine whether the part exists. If the part does not exist, the downloading process is completed.</p>
<pre class="alt2" style="border:1px inset;overflow:auto;width:500px;height:450px;text-align:left;margin:0;padding:6px;">
private class DownloadCombiner extends Thread {

    private String remoteName;
    private String localName;
    private int connection;

    public DownloadCombiner(String remoteName, String localName) {
        this.remoteName = remoteName;
        this.localName = localName;
    }

    public void run() {
        try {
            int chunkIndex = 0;
            int totalSize = 0;
            FileConnection file = (FileConnection) Connector.open(localName);
            if (!file.exists()) {
                 file.create();
            }
            file.setWritable(true);
            OutputStream out = file.openOutputStream();
            HttpConnection conn;
            InputStream in;
            while (true) {
                 System.out.println("Opening Chunk: " + chunkIndex);
                 String currentFile = remoteName + "." + chunkIndex++;
                 conn = (HttpConnection) Connector.open(currentFile);
                 if (conn.getResponseCode() != 200) {
                     System.out.println("Response Code = " +
                                         conn.getResponseCode());
                     break;
                 }
                 in = conn.openInputStream();
                 int length = -1;
                 byte[] readBlock = new byte[256];
                 int fileSize = 0;
                 while ((length = in.read(readBlock)) != -1) {
                     out.write(readBlock, 0, length);
                     fileSize += length;
                 }
                 totalSize += fileSize;
                 System.out.println("Chunk Downloaded: " + fileSize + " Bytes");
                 in.close();
                 conn.close();
                 in = null;
                 conn = null;
                 Thread.yield(); // allow other threads time
            }
            System.out.println("Full file downloaded: " + totalSize + " Bytes");
            out.close();
            file.close();
            System.out.println("Wrote file to local storage");
        } catch (Exception e) {
            System.err.println(e.toString());
          }
    }
}
</pre>
<p>[1] http://www.blackberry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/800332/800431/How_To_-_Download_large_files_using_the_BlackBerry_Mobile_Data_System.html?nodeid=1371855&amp;vernum=0</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/v4ks1n.wordpress.com/165/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/v4ks1n.wordpress.com/165/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/v4ks1n.wordpress.com/165/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/v4ks1n.wordpress.com/165/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/v4ks1n.wordpress.com/165/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/v4ks1n.wordpress.com/165/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/v4ks1n.wordpress.com/165/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/v4ks1n.wordpress.com/165/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/v4ks1n.wordpress.com/165/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/v4ks1n.wordpress.com/165/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/v4ks1n.wordpress.com/165/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/v4ks1n.wordpress.com/165/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/v4ks1n.wordpress.com/165/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/v4ks1n.wordpress.com/165/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=v4ks1n.wordpress.com&amp;blog=7180005&amp;post=165&amp;subd=v4ks1n&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://v4ks1n.wordpress.com/2010/08/04/download-large-files-using-the-blackberry-mobile-data-system/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/276ef47c3a5018e58eb22d39eed513c9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">v4ks1n</media:title>
		</media:content>
	</item>
		<item>
		<title>Obfuscate code in a BlackBerry application</title>
		<link>http://v4ks1n.wordpress.com/2010/02/03/obfuscate-code-in-a-blackberry-application/</link>
		<comments>http://v4ks1n.wordpress.com/2010/02/03/obfuscate-code-in-a-blackberry-application/#comments</comments>
		<pubDate>Wed, 03 Feb 2010 14:14:59 +0000</pubDate>
		<dc:creator>v4ks1n</dc:creator>
				<category><![CDATA[blackberry]]></category>
		<category><![CDATA[cod]]></category>
		<category><![CDATA[obfuscate]]></category>
		<category><![CDATA[preverify]]></category>
		<category><![CDATA[rapc]]></category>

		<guid isPermaLink="false">http://v4ks1n.wordpress.com/?p=162</guid>
		<description><![CDATA[How To &#8211; Obfuscate code in a BlackBerry application [1] Unlike traditional compilers, the compiler for the BlackBerry platform is highly optimized for a constrained mobile environment where the goal is to minimize the size of the application. The resulting COD file provides a significant amount of obfuscation-like services similar to other true obfuscation packages [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=v4ks1n.wordpress.com&amp;blog=7180005&amp;post=162&amp;subd=v4ks1n&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><span id="support"> </span></p>
<h2 class="pTitle">How To &#8211; Obfuscate code in a BlackBerry application [1]</h2>
<p><span id="support"></p>
<p class="pBody">Unlike traditional compilers, the compiler for the BlackBerry platform is highly optimized for a constrained mobile environment where the goal is to minimize the size of the application. The resulting COD file provides a significant amount of obfuscation-like services similar to other true obfuscation packages in an effort to reduce the size of the COD file. For example, the following information is removed from a COD file:</p>
<ul class="UnOrderedList">
<div class="UnOrderedList">
<li>All debug information</li>
<li>Local variable names</li>
<li>Source Line Numbers</li>
<li>Private Method and Members names</li>
</div>
</ul>
<p></span><span id="support"></p>
<p class="pBody">Support for obfuscation via third-party tools is not integrated into the JDE. As such, a command line procedure is required to obfuscate COD files for use on BlackBerry wireless devices. This article provides the steps and techniques required to obfuscate a COD file and have it execute properly on the BlackBerry device.</p>
<ol class="OrderedList">
<div class="OrderedList1">
<li>Create an application in the JDE. You should place the project file in a separate directory for ease of use during this process.</li>
<li>Create a temporary directory.</li>
<li>Copy the associated <strong class="bB">JAR</strong> file created by the BlackBerry JDE to the temporary directory.</li>
<li>Extract the contents of the JAR file into the temporary directory using the following command: <code class="cCode">jar xvf SampleApplication.jar</code></li>
<li>Delete the COD file (that was extracted as part of the JAR file) and the JAR file. You will replace these files in the following steps.</li>
<li>Obfuscate the class files that are contained in the temporary directory.</li>
<li>Run the <strong class="bB">pre-verify</strong> tool on the contents of the temporary directory using the following command: <code class="cCode">preverify.exe -verbose -d . -classpath..\lib\net_rim_api.jar;</code></li>
<li>Run <strong class="bB">rapc</strong> on the obfuscated (and pre-verified) class files to create a COD file. Use the following command:</li>
<p class="pCode">rapc.exe  -verbose import=..\lib\net_rim_api.jar codename=SampleApplication SampleApplication.rapc C:\yourTempDir\SampleApplication.class</p>
</div>
</ol>
<p class="pBody">This produces a COD file that will work on a device that has its contents obfuscated.</p>
<p class="pBody">
<p class="pBody">[1] http://www.blackberry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/800901/How_To_-_Obfuscate_code_for_a_BlackBerry_application.html?nodeid=1033550&amp;vernum=0</p>
<p></span></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/v4ks1n.wordpress.com/162/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/v4ks1n.wordpress.com/162/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/v4ks1n.wordpress.com/162/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/v4ks1n.wordpress.com/162/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/v4ks1n.wordpress.com/162/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/v4ks1n.wordpress.com/162/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/v4ks1n.wordpress.com/162/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/v4ks1n.wordpress.com/162/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/v4ks1n.wordpress.com/162/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/v4ks1n.wordpress.com/162/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/v4ks1n.wordpress.com/162/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/v4ks1n.wordpress.com/162/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/v4ks1n.wordpress.com/162/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/v4ks1n.wordpress.com/162/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=v4ks1n.wordpress.com&amp;blog=7180005&amp;post=162&amp;subd=v4ks1n&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://v4ks1n.wordpress.com/2010/02/03/obfuscate-code-in-a-blackberry-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/276ef47c3a5018e58eb22d39eed513c9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">v4ks1n</media:title>
		</media:content>
	</item>
		<item>
		<title>Crucial Concepts Behind Advanced Regular Expressions</title>
		<link>http://v4ks1n.wordpress.com/2010/01/31/crucial-concepts-behind-advanced-regular-expressions/</link>
		<comments>http://v4ks1n.wordpress.com/2010/01/31/crucial-concepts-behind-advanced-regular-expressions/#comments</comments>
		<pubDate>Sun, 31 Jan 2010 12:42:28 +0000</pubDate>
		<dc:creator>v4ks1n</dc:creator>
				<category><![CDATA[regex]]></category>
		<category><![CDATA[concepts]]></category>

		<guid isPermaLink="false">http://v4ks1n.wordpress.com/?p=159</guid>
		<description><![CDATA[1. Greediness/Laziness All regex repetition operators are greedy. They try to match as much as possible in a string. Unfortunately, this might not always be a desired effect. Thus, lazy operators are used to solve this problem. They only match the smallest possible pattern and are used by adding a ‘?’ after the respective greedy [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=v4ks1n.wordpress.com&amp;blog=7180005&amp;post=159&amp;subd=v4ks1n&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h3>1. Greediness/Laziness</h3>
<p><img src="http://media.smashingmagazine.com/cdn_smash/images/advanced-regular-expressions-php/greed.jpg" alt="Greed in Crucial Concepts Behind Advanced Regular Expressions" width="400" height="300" /></p>
<p>All regex repetition operators are <strong>greedy</strong>. They try to match as much as possible in a string. Unfortunately, this might not always be a desired effect. Thus, lazy operators are used to solve this problem. They only match the smallest possible pattern and are used by adding a ‘?’ after the respective greedy operator. Alternatively, the ‘U’ modifier may be used to make all repetiton operators lazy. Differentiating between greediness and laziness is key to fully understanding advanced regular expressions.</p>
<h4>Greedy Operators</h4>
<p>The * operator matches the previous expression 0 or more times. It is a greedy operator. Consider the following expression:</p>
<div id="highlighter_85931" class="syntaxhighlighter">
<div class="bar">
<div class="toolbar"><a class="item viewSource" style="width:16px;height:16px;" title="view source" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#viewSource">view source</a></p>
<div class="item copyToClipboard"></div>
<p><a class="item printSource" style="width:16px;height:16px;" title="print" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#printSource">print</a><a class="item about" style="width:16px;height:16px;" title="?" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#about">?</a></div>
</div>
<div class="lines">
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>1</code></td>
<td class="content"><code class="plain">preg_match( </code><code class="string">'/&lt;h1&gt;.*&lt;\/h1&gt;/'</code><code class="plain">, '&lt;h1&gt;This is a heading.&lt;/h1&gt;</code></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt2">
<table>
<tbody>
<tr>
<td class="number"><code>2</code></td>
<td class="content"><code class="plain">&lt;h1&gt;This is another one.&lt;/h1&gt;', </code><code class="variable">$matches</code> <code class="plain">);</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p>Recall that a . means any character except a new line. The above regular expression is looking for an h1 tag and all of its contents. It uses the . and * operators to constantly match anything inside the tag. This pattern will match:</p>
<div id="highlighter_223981" class="syntaxhighlighter">
<div class="bar">
<div class="toolbar"><a class="item viewSource" style="width:16px;height:16px;" title="view source" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#viewSource">view source</a></p>
<div class="item copyToClipboard"></div>
<p><a class="item printSource" style="width:16px;height:16px;" title="print" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#printSource">print</a><a class="item about" style="width:16px;height:16px;" title="?" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#about">?</a></div>
</div>
<div class="lines">
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>1</code></td>
<td class="content"><code class="plain">&lt;h1&gt;This is a heading.&lt;/h1&gt;&lt;h1&gt;This is another one.&lt;/h1&gt;</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p>It returns the whole string. The * operator will continuously match everything — even the middle closing h1 tag — because it is greedy. Matching the whole string is the best it can do.</p>
<h4>Lazy Operators</h4>
<p>Let’s change the above operator by adding a ‘?’ after it. This will make it lazy:</p>
<div id="highlighter_806885" class="syntaxhighlighter">
<div class="bar">
<div class="toolbar"><a class="item viewSource" style="width:16px;height:16px;" title="view source" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#viewSource">view source</a></p>
<div class="item copyToClipboard"></div>
<p><a class="item printSource" style="width:16px;height:16px;" title="print" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#printSource">print</a><a class="item about" style="width:16px;height:16px;" title="?" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#about">?</a></div>
</div>
<div class="lines">
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>1</code></td>
<td class="content"><code class="plain">/&lt;h1&gt;.*?&lt;\/h1&gt;/</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p>The regex now fulfills its duty and matches only the first h1 tag. Another greedy operator that uses this same property is {n,}. This matches the previous expression n or more times. If it is used without a question mark, it looks for the most repetitions possible. Otherwise, it starts from n repetitions:</p>
<div id="highlighter_654316" class="syntaxhighlighter">
<div class="bar">
<div class="toolbar"><a class="item viewSource" style="width:16px;height:16px;" title="view source" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#viewSource">view source</a></p>
<div class="item copyToClipboard"></div>
<p><a class="item printSource" style="width:16px;height:16px;" title="print" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#printSource">print</a><a class="item about" style="width:16px;height:16px;" title="?" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#about">?</a></div>
</div>
<div class="lines">
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>1</code></td>
<td class="content"><code class="plain"># Set up a String</code></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt2">
<table>
<tbody>
<tr>
<td class="number"><code>2</code></td>
<td class="content"><code class="variable">$str</code> <code class="plain">= </code><code class="string">'hihi'</code><code class="plain">;</code></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>3</code></td>
<td class="content"></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt2">
<table>
<tbody>
<tr>
<td class="number"><code>4</code></td>
<td class="content"><code class="plain"># Match it using the greedy {n,} operator</code></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>5</code></td>
<td class="content"><code class="plain">preg_match( </code><code class="string">'/(hi){1,}/'</code><code class="plain">, </code><code class="variable">$str</code><code class="plain">, </code><code class="variable">$matches</code> <code class="plain">); # matches[0] will be </code><code class="string">'hihi'</code></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt2">
<table>
<tbody>
<tr>
<td class="number"><code>6</code></td>
<td class="content"></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>7</code></td>
<td class="content"><code class="plain"># Match it with the lazy {n,}? operator</code></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt2">
<table>
<tbody>
<tr>
<td class="number"><code>8</code></td>
<td class="content"><code class="plain">preg_match( </code><code class="string">'/(hi){1,}?/'</code><code class="plain">, </code><code class="variable">$str</code><code class="plain">, </code><code class="variable">$matches</code> <code class="plain">); # matches[0] will be </code><code class="string">'hi'</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<h3>2. Back Referencing</h3>
<p><img src="http://media.smashingmagazine.com/cdn_smash/images/advanced-regular-expressions-php/back.jpg" alt="Back in Crucial Concepts Behind Advanced Regular Expressions" width="300" height="290" /></p>
<h4>What it does</h4>
<p><strong>Back referencing</strong> is a way to refer to previously matched patterns inside a regular expression. For example, take a look at this simple regex that matches an expression in quotes:</p>
<div id="highlighter_68374" class="syntaxhighlighter">
<div class="bar">
<div class="toolbar"><a class="item viewSource" style="width:16px;height:16px;" title="view source" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#viewSource">view source</a></p>
<div class="item copyToClipboard"></div>
<p><a class="item printSource" style="width:16px;height:16px;" title="print" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#printSource">print</a><a class="item about" style="width:16px;height:16px;" title="?" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#about">?</a></div>
</div>
<div class="lines">
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>01</code></td>
<td class="content"><code class="plain"># Set up an </code><code class="keyword">array</code> <code class="plain">of matches</code></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt2">
<table>
<tbody>
<tr>
<td class="number"><code>02</code></td>
<td class="content"><code class="variable">$matches</code> <code class="plain">= </code><code class="keyword">array</code><code class="plain">();</code></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>03</code></td>
<td class="content"></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt2">
<table>
<tbody>
<tr>
<td class="number"><code>04</code></td>
<td class="content"><code class="plain"># Create a String</code></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>05</code></td>
<td class="content"><code class="variable">$str</code> <code class="plain">= </code><code class="string">"\"This is a 'string'\""</code><code class="plain">;</code></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt2">
<table>
<tbody>
<tr>
<td class="number"><code>06</code></td>
<td class="content"></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>07</code></td>
<td class="content"><code class="plain"># Traverse it with regular expressions</code></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt2">
<table>
<tbody>
<tr>
<td class="number"><code>08</code></td>
<td class="content"><code class="plain">preg_match( </code><code class="string">"/(\"|').*?(\"|')/"</code><code class="plain">, </code><code class="variable">$str</code><code class="plain">, </code><code class="variable">$matches</code> <code class="plain">);</code></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>09</code></td>
<td class="content"></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt2">
<table>
<tbody>
<tr>
<td class="number"><code>10</code></td>
<td class="content"><code class="plain"># Print the whole match</code></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>11</code></td>
<td class="content"><code class="functions">echo</code> <code class="variable">$matches</code><code class="plain">[0];</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p>Unfortunately, this will not correctly match the string. Instead, it will print:</p>
<div id="highlighter_750828" class="syntaxhighlighter">
<div class="bar">
<div class="toolbar"><a class="item viewSource" style="width:16px;height:16px;" title="view source" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#viewSource">view source</a></p>
<div class="item copyToClipboard"></div>
<p><a class="item printSource" style="width:16px;height:16px;" title="print" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#printSource">print</a><a class="item about" style="width:16px;height:16px;" title="?" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#about">?</a></div>
</div>
<div class="lines">
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>1</code></td>
<td class="content"><code class="plain">"This is a '</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p>This regular expression matches the opening double quote but finds a different type of quote to close it. This is because it was given the option of picking a double or single quote at the end. In order to fix this, you can use back referencing. The <strong>expressions \1, \2, ….,  \9</strong> hold references to previously captured subpatterns. The first matched quote, in this case, will be held by the variable \1.</p>
<h4>How to Use It</h4>
<p>In order to apply this concept to the aforementioned example, use \1 in place of the last quote:</p>
<div id="highlighter_636665" class="syntaxhighlighter">
<div class="bar">
<div class="toolbar"><a class="item viewSource" style="width:16px;height:16px;" title="view source" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#viewSource">view source</a></p>
<div class="item copyToClipboard"></div>
<p><a class="item printSource" style="width:16px;height:16px;" title="print" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#printSource">print</a><a class="item about" style="width:16px;height:16px;" title="?" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#about">?</a></div>
</div>
<div class="lines">
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>1</code></td>
<td class="content"><code class="plain">preg_match( </code><code class="string">'/("|\').*?\1/'</code><code class="plain">, </code><code class="variable">$str</code><code class="plain">, </code><code class="variable">$matches</code> <code class="plain">);</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p>This will now correctly return:</p>
<div id="highlighter_247239" class="syntaxhighlighter">
<div class="bar">
<div class="toolbar"><a class="item viewSource" style="width:16px;height:16px;" title="view source" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#viewSource">view source</a></p>
<div class="item copyToClipboard"></div>
<p><a class="item printSource" style="width:16px;height:16px;" title="print" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#printSource">print</a><a class="item about" style="width:16px;height:16px;" title="?" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#about">?</a></div>
</div>
<div class="lines">
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>1</code></td>
<td class="content"><code class="string">"This is a 'string'"</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p>Remember that back referencing may also be used by <code>preg_replace</code>. Note that instead of \1 … \9, you should use $1 … $9 … $n (any number of these will work). For example, if you want to replace all paragraph tags with text that represents them, use:</p>
<div id="highlighter_675021" class="syntaxhighlighter">
<div class="bar">
<div class="toolbar"><a class="item viewSource" style="width:16px;height:16px;" title="view source" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#viewSource">view source</a></p>
<div class="item copyToClipboard"></div>
<p><a class="item printSource" style="width:16px;height:16px;" title="print" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#printSource">print</a><a class="item about" style="width:16px;height:16px;" title="?" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#about">?</a></div>
</div>
<div class="lines">
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>1</code></td>
<td class="content"><code class="variable">$text</code> <code class="plain">= preg_replace( </code><code class="string">'/&lt;p&gt;(.*?)&lt;\/p&gt;/'</code><code class="plain">,</code></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt2">
<table>
<tbody>
<tr>
<td class="number"><code>2</code></td>
<td class="content"><code class="string">"&amp;lt;p&amp;gt;$1&amp;lt;/p&amp;gt;"</code><code class="plain">, </code><code class="variable">$html</code> <code class="plain">);</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p>The $1 back reference holds the text inside the paragraph and is being used in the replace pattern itself. This completely valid expression shows an easy way to access matched patterns even while replacing.</p>
<h3>3. Named Groups</h3>
<p>When using multiple back references, a regular expression can quickly become confusing and hard to understand. An alternative way to back reference is by using <strong>named groups</strong>. A named group is specified by using <code>(?P&lt;name&gt;pattern)</code>, where name is the name of the group and pattern is the regular expression in the group itself. The group can then be referred to by (?P=name). For example, consider the following:</p>
<div id="highlighter_960348" class="syntaxhighlighter">
<div class="bar">
<div class="toolbar"><a class="item viewSource" style="width:16px;height:16px;" title="view source" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#viewSource">view source</a></p>
<div class="item copyToClipboard"></div>
<p><a class="item printSource" style="width:16px;height:16px;" title="print" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#printSource">print</a><a class="item about" style="width:16px;height:16px;" title="?" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#about">?</a></div>
</div>
<div class="lines">
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>1</code></td>
<td class="content"><code class="plain">/(?P&lt;quote&gt;"|').*?(?P=quote)/</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p>The above expression will create the same effect as the previous back reference example, but by instead using named groups. It is also significantly easier to read.</p>
<p>Named groups are also useful when sifting through the array of matches. The name given to a specific pattern is also the key of the corresponding matches array.</p>
<div id="highlighter_451888" class="syntaxhighlighter">
<div class="bar">
<div class="toolbar"><a class="item viewSource" style="width:16px;height:16px;" title="view source" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#viewSource">view source</a></p>
<div class="item copyToClipboard"></div>
<p><a class="item printSource" style="width:16px;height:16px;" title="print" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#printSource">print</a><a class="item about" style="width:16px;height:16px;" title="?" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#about">?</a></div>
</div>
<div class="lines">
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>1</code></td>
<td class="content"><code class="plain">preg_match( </code><code class="string">'/(?P&lt;quote&gt;"|\')/'</code><code class="plain">, "</code><code class="string">'String'</code><code class="plain">", </code><code class="variable">$matches</code> <code class="plain">);</code></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt2">
<table>
<tbody>
<tr>
<td class="number"><code>2</code></td>
<td class="content"></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>3</code></td>
<td class="content"><code class="plain"># This will print </code><code class="string">"'"</code></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt2">
<table>
<tbody>
<tr>
<td class="number"><code>4</code></td>
<td class="content"><code class="functions">echo</code> <code class="variable">$matches</code><code class="plain">[1];</code></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>5</code></td>
<td class="content"></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt2">
<table>
<tbody>
<tr>
<td class="number"><code>6</code></td>
<td class="content"><code class="plain"># This will also print </code><code class="string">"'"</code><code class="plain">, </code><code class="keyword">as</code> <code class="plain">it is a named group</code></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>7</code></td>
<td class="content"><code class="functions">echo</code> <code class="variable">$matches</code><code class="plain">[</code><code class="string">'quote'</code><code class="plain">];</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p>Thus, named groups not only make code easier to read but also organize it.</p>
<h3>4. Word Boundaries</h3>
<p><img src="http://media.smashingmagazine.com/cdn_smash/images/advanced-regular-expressions-php/boundary.jpg" alt="Boundary in Crucial Concepts Behind Advanced Regular Expressions" width="400" height="284" /></p>
<p><strong>Word boundaries</strong> are places in a string that come between a word character and a non-word character. The specialty of these boundaries is the fact that they don’t actually match a character. Their length is <em>zero</em>. The <code>\b</code> regular expression matches any word boundary.</p>
<p>Unfortunately, boundaries are so often skimmed over that many do not recognize their real significance. For example, let’s say you want to match the word “import”:</p>
<div id="highlighter_504634" class="syntaxhighlighter">
<div class="bar">
<div class="toolbar"><a class="item viewSource" style="width:16px;height:16px;" title="view source" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#viewSource">view source</a></p>
<div class="item copyToClipboard"></div>
<p><a class="item printSource" style="width:16px;height:16px;" title="print" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#printSource">print</a><a class="item about" style="width:16px;height:16px;" title="?" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#about">?</a></div>
</div>
<div class="lines">
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>1</code></td>
<td class="content"><code class="plain">/import/</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p>Watch out! Regular expressions can be tricky. The above expression will also match:</p>
<div id="highlighter_201247" class="syntaxhighlighter">
<div class="bar">
<div class="toolbar"><a class="item viewSource" style="width:16px;height:16px;" title="view source" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#viewSource">view source</a></p>
<div class="item copyToClipboard"></div>
<p><a class="item printSource" style="width:16px;height:16px;" title="print" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#printSource">print</a><a class="item about" style="width:16px;height:16px;" title="?" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#about">?</a></div>
</div>
<div class="lines">
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>1</code></td>
<td class="content"><code class="plain">important</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p>You may think it is as simple as adding a space before and after import to prevent these bogus matches:</p>
<div id="highlighter_509974" class="syntaxhighlighter">
<div class="bar">
<div class="toolbar"><a class="item viewSource" style="width:16px;height:16px;" title="view source" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#viewSource">view source</a></p>
<div class="item copyToClipboard"></div>
<p><a class="item printSource" style="width:16px;height:16px;" title="print" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#printSource">print</a><a class="item about" style="width:16px;height:16px;" title="?" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#about">?</a></div>
</div>
<div class="lines">
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>1</code></td>
<td class="content"><code class="plain">/ import /</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p>But what about this case?</p>
<div id="highlighter_508629" class="syntaxhighlighter">
<div class="bar">
<div class="toolbar"><a class="item viewSource" style="width:16px;height:16px;" title="view source" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#viewSource">view source</a></p>
<div class="item copyToClipboard"></div>
<p><a class="item printSource" style="width:16px;height:16px;" title="print" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#printSource">print</a><a class="item about" style="width:16px;height:16px;" title="?" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#about">?</a></div>
</div>
<div class="lines">
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>1</code></td>
<td class="content"><code class="plain">The trader voted </code><code class="keyword">for</code> <code class="plain">the import</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p>When import is at the beginning or the end of a string, the modified regex will fail. Thus, splitting this up into cases is required:</p>
<div id="highlighter_194849" class="syntaxhighlighter">
<div class="bar">
<div class="toolbar"><a class="item viewSource" style="width:16px;height:16px;" title="view source" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#viewSource">view source</a></p>
<div class="item copyToClipboard"></div>
<p><a class="item printSource" style="width:16px;height:16px;" title="print" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#printSource">print</a><a class="item about" style="width:16px;height:16px;" title="?" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#about">?</a></div>
</div>
<div class="lines">
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>1</code></td>
<td class="content"><code class="plain">/(^import | import | import$)/i</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p>Looking back at our regular expression, it does not take periods or other punctuation into account. Just to match this single word, a regular expressions may look like this:</p>
<div id="highlighter_300345" class="syntaxhighlighter">
<div class="bar">
<div class="toolbar"><a class="item viewSource" style="width:16px;height:16px;" title="view source" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#viewSource">view source</a></p>
<div class="item copyToClipboard"></div>
<p><a class="item printSource" style="width:16px;height:16px;" title="print" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#printSource">print</a><a class="item about" style="width:16px;height:16px;" title="?" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#about">?</a></div>
</div>
<div class="lines">
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>1</code></td>
<td class="content"><code class="plain">/(^import(:|;|,)? | import(:|;|,)? | import(\.|\?|!)?$)/i</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p>That’s a lot of code to match just a single word. This is why word boundaries are so significant. To accomplish the above statement and <strong>many other variations</strong> with word boundaries, all that is necessary is:</p>
<div id="highlighter_466257" class="syntaxhighlighter">
<div class="bar">
<div class="toolbar"><a class="item viewSource" style="width:16px;height:16px;" title="view source" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#viewSource">view source</a></p>
<div class="item copyToClipboard"></div>
<p><a class="item printSource" style="width:16px;height:16px;" title="print" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#printSource">print</a><a class="item about" style="width:16px;height:16px;" title="?" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#about">?</a></div>
</div>
<div class="lines">
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>1</code></td>
<td class="content"><code class="plain">/\bimport\b/</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p>This will match every case above and more. <code>\b</code>’s flexibility comes from the fact that it matches a zero-length string. All it matches is an imaginary space between two characters. It checks if one of the characters is a non-word character and the other is a word character. If so, it matches it. If the beginning or end of a string is encountered, <code>\b</code> treats it as a non-word character. Because the <code>i</code> in import is still considered a word character, it will match import.</p>
<p>Note that the opposite of \b is \B. This operator will match the space in-between two word or two non-word characters. Thus, if you would like to match ‘hi’ inside another word, you could use:</p>
<div id="highlighter_211975" class="syntaxhighlighter">
<div class="bar">
<div class="toolbar"><a class="item viewSource" style="width:16px;height:16px;" title="view source" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#viewSource">view source</a></p>
<div class="item copyToClipboard"></div>
<p><a class="item printSource" style="width:16px;height:16px;" title="print" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#printSource">print</a><a class="item about" style="width:16px;height:16px;" title="?" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#about">?</a></div>
</div>
<div class="lines">
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>1</code></td>
<td class="content"><code class="plain">\Bhi\B</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<h3>5. Atomic Groups</h3>
<p><img src="http://media.smashingmagazine.com/cdn_smash/images/advanced-regular-expressions-php/groups.jpg" alt="Groups in Crucial Concepts Behind Advanced Regular Expressions" width="400" height="266" /></p>
<p><strong>Atomic groups</strong> are special regex groups that are non-capturing. They are usually used to increase the efficiency of a regular expression, but may also be applied to eliminate certain matches. An atomic group is specified by using (?&gt;pattern):</p>
<div id="highlighter_234429" class="syntaxhighlighter">
<div class="bar">
<div class="toolbar"><a class="item viewSource" style="width:16px;height:16px;" title="view source" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#viewSource">view source</a></p>
<div class="item copyToClipboard"></div>
<p><a class="item printSource" style="width:16px;height:16px;" title="print" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#printSource">print</a><a class="item about" style="width:16px;height:16px;" title="?" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#about">?</a></div>
</div>
<div class="lines">
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>1</code></td>
<td class="content"><code class="plain">/(?&gt;his|this)/</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p>When the regex engine matches an atomic group, it will discard backtracting positions that came with all tokens inside it. Consider the word ’smashing’. Using the above regular expression, the regex engine will first try to match the pattern ‘his’ in ’smashing’. It will not find a match. At this point, the atomic group will kick in. The engine will discard all backtracking positions. This means that it will not search for ‘this’ inside ’smashing’. Why? If ‘his’ did not return a match, then obviously ‘this’ (which includes ‘his’) will not return positive either.</p>
<p>The above example did not have many practical uses. We might as well have used <code>/t?his?/</code> instead. Look at the following:</p>
<div id="highlighter_638147" class="syntaxhighlighter">
<div class="bar">
<div class="toolbar"><a class="item viewSource" style="width:16px;height:16px;" title="view source" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#viewSource">view source</a></p>
<div class="item copyToClipboard"></div>
<p><a class="item printSource" style="width:16px;height:16px;" title="print" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#printSource">print</a><a class="item about" style="width:16px;height:16px;" title="?" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#about">?</a></div>
</div>
<div class="lines">
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>1</code></td>
<td class="content"><code class="plain">/\b(engineer|engrave|</code><code class="functions">end</code><code class="plain">)\b/</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p>If the regex engine is given the word ‘engineering’, it will correctly match ‘engineer’. The next word boundary, \b, will not match. Thus, it will move on to the next match: engrave. It realizes that the ‘eng’ matches, but the rest do not. Finally, ‘end’ is attempted and also failed. If you look carefully, you will realize that once the engine matches ‘engineer’ and fails the last word boundary, it can not possibly match ‘engrave’ or ‘end’. These two matches are smaller words than ‘engineer’, and thus the regex engine should not continue with the other trials.</p>
<div id="highlighter_311234" class="syntaxhighlighter">
<div class="bar">
<div class="toolbar"><a class="item viewSource" style="width:16px;height:16px;" title="view source" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#viewSource">view source</a></p>
<div class="item copyToClipboard"></div>
<p><a class="item printSource" style="width:16px;height:16px;" title="print" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#printSource">print</a><a class="item about" style="width:16px;height:16px;" title="?" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#about">?</a></div>
</div>
<div class="lines">
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>1</code></td>
<td class="content"><code class="plain">/\b(?&gt;engineer|engrave|</code><code class="functions">end</code><code class="plain">)\b/</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p>The above is a much better alternative that will save the regex engine time and improve the code’s efficiency.</p>
<h3>6. Recursion</h3>
<p><img src="http://media.smashingmagazine.com/cdn_smash/images/advanced-regular-expressions-php/recursion.jpg" alt="Recursion in Crucial Concepts Behind Advanced Regular Expressions" width="400" height="300" /></p>
<p><strong>Recursion</strong> in regular expressions can be used to match nested constructs, such as parentheses, (this (that)), and HTML tags, <code>&lt;div&gt;&lt;/div&gt;</code>. They require the use of <code>(?R)</code>, an operator that matches recursive sub-patterns. Consider the regular expression that matches nested parentheses:</p>
<div id="highlighter_30151" class="syntaxhighlighter">
<div class="bar">
<div class="toolbar"><a class="item viewSource" style="width:16px;height:16px;" title="view source" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#viewSource">view source</a></p>
<div class="item copyToClipboard"></div>
<p><a class="item printSource" style="width:16px;height:16px;" title="print" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#printSource">print</a><a class="item about" style="width:16px;height:16px;" title="?" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#about">?</a></div>
</div>
<div class="lines">
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>1</code></td>
<td class="content"><code class="plain">/\(((?&gt;[^()]+)|(?R))*\)/</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p>The outermost parentheses in this regular expression match the beginning of the nested constructs. Then comes an optional operator, which can either match non-parenthetical characters (<code>?&gt;[^()]+</code>) or the whole expression again in a sub-pattern, (?R). Notice that this operator is repeated as many times as possible to match all nested parentheses.</p>
<p>Another example of recursion at work is the following:</p>
<div id="highlighter_274759" class="syntaxhighlighter">
<div class="bar">
<div class="toolbar"><a class="item viewSource" style="width:16px;height:16px;" title="view source" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#viewSource">view source</a></p>
<div class="item copyToClipboard"></div>
<p><a class="item printSource" style="width:16px;height:16px;" title="print" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#printSource">print</a><a class="item about" style="width:16px;height:16px;" title="?" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#about">?</a></div>
</div>
<div class="lines">
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>1</code></td>
<td class="content"><code class="plain">/&lt;([\w]+).*?&gt;((?&gt;[^&lt;&gt;]+)|((?R)))*&lt;\/\1&gt;/</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p>The above expression combines character groups, greedy operators, back-tracking, and atomic groups to match nested tags. The first parenthesized group ([\w]+) matches the tag name for use later in the regular expression. It then proceeds to match the rest of the tag. The next parenthesized sub-expression is very similar to the one above. It either matches non-tag (?&gt;[^&lt;&gt;]+) characters or recurses over another tag (?R). Finally, the last part of the expression matches the close tag.</p>
<h3>7. Callbacks</h3>
<p><img src="http://media.smashingmagazine.com/cdn_smash/images/advanced-regular-expressions-php/call.jpg" alt="Call in Crucial Concepts Behind Advanced Regular Expressions" width="400" height="290" /></p>
<p>Certain matches in a pattern may require special modifications. In order to apply multiple or complex changes, <strong>callbacks</strong> can be used. A callback is used for dynamic substitution Strings in the <code>preg_replace_callback</code> function. They take in a function as a parameter to use when a match is found. This function receives the match array as a parameter and returns a modified string that is used as a replacement.</p>
<p>As an example, consider a regular expression that changes all words to uppercase in a given string. Unfortunately, PHP does not have a regex operator that changes a character to a different case. To accomplish this task, a callback may be used. First, the expression must match all letters that need to be capitalized:</p>
<div id="highlighter_250348" class="syntaxhighlighter">
<div class="bar">
<div class="toolbar"><a class="item viewSource" style="width:16px;height:16px;" title="view source" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#viewSource">view source</a></p>
<div class="item copyToClipboard"></div>
<p><a class="item printSource" style="width:16px;height:16px;" title="print" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#printSource">print</a><a class="item about" style="width:16px;height:16px;" title="?" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#about">?</a></div>
</div>
<div class="lines">
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>1</code></td>
<td class="content"><code class="plain">/\b\w/</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p>The above uses both word boundaries and character classes to work. Now that we have this expression, we can write a callback function:</p>
<div id="highlighter_651018" class="syntaxhighlighter">
<div class="bar">
<div class="toolbar"><a class="item viewSource" style="width:16px;height:16px;" title="view source" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#viewSource">view source</a></p>
<div class="item copyToClipboard"></div>
<p><a class="item printSource" style="width:16px;height:16px;" title="print" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#printSource">print</a><a class="item about" style="width:16px;height:16px;" title="?" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#about">?</a></div>
</div>
<div class="lines">
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>1</code></td>
<td class="content"><code class="keyword">function</code> <code class="plain">upper_case( </code><code class="variable">$matches</code> <code class="plain">) {</code></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt2">
<table>
<tbody>
<tr>
<td class="number"><code>2</code></td>
<td class="content"><code class="spaces"> </code><code class="keyword">return</code> <code class="functions">strtoupper</code><code class="plain">( </code><code class="variable">$matches</code><code class="plain">[0] );</code></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>3</code></td>
<td class="content"><code class="plain">}</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p><code>upper_case</code> takes in an array of matches and returns the whole matched pattern in uppercase. <code>$matches[0]</code>, in this case, represents the letter that needs to be capitalized. All of this can now be put together using the <code>preg_replace_callback</code> function:</p>
<div id="highlighter_829935" class="syntaxhighlighter">
<div class="bar">
<div class="toolbar"><a class="item viewSource" style="width:16px;height:16px;" title="view source" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#viewSource">view source</a></p>
<div class="item copyToClipboard"></div>
<p><a class="item printSource" style="width:16px;height:16px;" title="print" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#printSource">print</a><a class="item about" style="width:16px;height:16px;" title="?" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#about">?</a></div>
</div>
<div class="lines">
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>1</code></td>
<td class="content"><code class="plain">preg_replace_callback( </code><code class="string">'/\b\w/'</code><code class="plain">, </code><code class="string">"upper_case"</code><code class="plain">, </code><code class="variable">$str</code> <code class="plain">);</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p>That is the power of a simple callback.</p>
<h3>8. Commenting</h3>
<p><img src="http://media.smashingmagazine.com/cdn_smash/images/advanced-regular-expressions-php/comment.jpg" alt="Comment in Crucial Concepts Behind Advanced Regular Expressions" width="400" height="300" /></p>
<p><strong>Commenting</strong> is not a way to actually match strings, but it is one of the most important parts of regular expressions. As you dive deep into larger, more complex expressions, it becomes hard to decipher what is actually being matched. Using comments in the middle of regular expressions is the perfect way to minimize such confusion.</p>
<p>To place a comment inside a regular expression, use the <code>(?#comment)</code> format. Replace “comment” with the word(s) of your choice:</p>
<div id="highlighter_12377" class="syntaxhighlighter">
<div class="bar">
<div class="toolbar"><a class="item viewSource" style="width:16px;height:16px;" title="view source" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#viewSource">view source</a></p>
<div class="item copyToClipboard"></div>
<p><a class="item printSource" style="width:16px;height:16px;" title="print" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#printSource">print</a><a class="item about" style="width:16px;height:16px;" title="?" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#about">?</a></div>
</div>
<div class="lines">
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>1</code></td>
<td class="content"><code class="plain">/(?#digit)\d/</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p>It is especially important to comment regular expressions that you release to the public. Users of your regex will be able to easily understand and modify the pattern to meet their needs. It can even go so far as to help you decode it when revisiting a program.</p>
<p>Consider using the “x” or (?x) modifier for free-spacing mode with comments. This causes a regular expression to ignore white space between tokens. All spaces can still be represented with <code>[ ]</code> or <code>\ </code> (a backslash and a space):</p>
<div id="highlighter_454985" class="syntaxhighlighter">
<div class="bar">
<div class="toolbar"><a class="item viewSource" style="width:16px;height:16px;" title="view source" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#viewSource">view source</a></p>
<div class="item copyToClipboard"></div>
<p><a class="item printSource" style="width:16px;height:16px;" title="print" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#printSource">print</a><a class="item about" style="width:16px;height:16px;" title="?" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#about">?</a></div>
</div>
<div class="lines">
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>1</code></td>
<td class="content"><code class="plain">/</code></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt2">
<table>
<tbody>
<tr>
<td class="number"><code>2</code></td>
<td class="content"><code class="plain">\d    #digit</code></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>3</code></td>
<td class="content"><code class="plain">[ ]   #space</code></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt2">
<table>
<tbody>
<tr>
<td class="number"><code>4</code></td>
<td class="content"><code class="plain">\w+   #word</code></td>
</tr>
</tbody>
</table>
</div>
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>5</code></td>
<td class="content"><code class="plain">/x</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p>The above is the same as:</p>
<div id="highlighter_399226" class="syntaxhighlighter">
<div class="bar">
<div class="toolbar"><a class="item viewSource" style="width:16px;height:16px;" title="view source" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#viewSource">view source</a></p>
<div class="item copyToClipboard"></div>
<p><a class="item printSource" style="width:16px;height:16px;" title="print" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#printSource">print</a><a class="item about" style="width:16px;height:16px;" title="?" href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/#about">?</a></div>
</div>
<div class="lines">
<div class="line alt1">
<table>
<tbody>
<tr>
<td class="number"><code>1</code></td>
<td class="content"><code class="plain">/\d(?#digit)[ ](?#space)\w+(?#word)/</code></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p>Always create well-documented code.</p>
<p>[1] http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/v4ks1n.wordpress.com/159/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/v4ks1n.wordpress.com/159/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/v4ks1n.wordpress.com/159/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/v4ks1n.wordpress.com/159/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/v4ks1n.wordpress.com/159/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/v4ks1n.wordpress.com/159/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/v4ks1n.wordpress.com/159/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/v4ks1n.wordpress.com/159/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/v4ks1n.wordpress.com/159/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/v4ks1n.wordpress.com/159/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/v4ks1n.wordpress.com/159/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/v4ks1n.wordpress.com/159/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/v4ks1n.wordpress.com/159/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/v4ks1n.wordpress.com/159/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=v4ks1n.wordpress.com&amp;blog=7180005&amp;post=159&amp;subd=v4ks1n&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://v4ks1n.wordpress.com/2010/01/31/crucial-concepts-behind-advanced-regular-expressions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/276ef47c3a5018e58eb22d39eed513c9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">v4ks1n</media:title>
		</media:content>

		<media:content url="http://media.smashingmagazine.com/cdn_smash/images/advanced-regular-expressions-php/greed.jpg" medium="image">
			<media:title type="html">Greed in Crucial Concepts Behind Advanced Regular Expressions</media:title>
		</media:content>

		<media:content url="http://media.smashingmagazine.com/cdn_smash/images/advanced-regular-expressions-php/back.jpg" medium="image">
			<media:title type="html">Back in Crucial Concepts Behind Advanced Regular Expressions</media:title>
		</media:content>

		<media:content url="http://media.smashingmagazine.com/cdn_smash/images/advanced-regular-expressions-php/boundary.jpg" medium="image">
			<media:title type="html">Boundary in Crucial Concepts Behind Advanced Regular Expressions</media:title>
		</media:content>

		<media:content url="http://media.smashingmagazine.com/cdn_smash/images/advanced-regular-expressions-php/groups.jpg" medium="image">
			<media:title type="html">Groups in Crucial Concepts Behind Advanced Regular Expressions</media:title>
		</media:content>

		<media:content url="http://media.smashingmagazine.com/cdn_smash/images/advanced-regular-expressions-php/recursion.jpg" medium="image">
			<media:title type="html">Recursion in Crucial Concepts Behind Advanced Regular Expressions</media:title>
		</media:content>

		<media:content url="http://media.smashingmagazine.com/cdn_smash/images/advanced-regular-expressions-php/call.jpg" medium="image">
			<media:title type="html">Call in Crucial Concepts Behind Advanced Regular Expressions</media:title>
		</media:content>

		<media:content url="http://media.smashingmagazine.com/cdn_smash/images/advanced-regular-expressions-php/comment.jpg" medium="image">
			<media:title type="html">Comment in Crucial Concepts Behind Advanced Regular Expressions</media:title>
		</media:content>
	</item>
	</channel>
</rss>
