<?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/"
	>

<channel>
	<title>coder . cl &#187; java</title>
	<atom:link href="http://coder.cl/category/programming/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://coder.cl</link>
	<description>web developer &#38; system programmer</description>
	<lastBuildDate>Tue, 15 May 2012 10:46:18 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>my software design principles</title>
		<link>http://coder.cl/2012/05/my-software-design-principles/</link>
		<comments>http://coder.cl/2012/05/my-software-design-principles/#comments</comments>
		<pubDate>Sat, 05 May 2012 12:35:17 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=2448</guid>
		<description><![CDATA[Most modern applications are providing APIs. That allows you to integrate those applications providing APIs with third party applications and create a real cloud computing environment. From an architectural perspective, we should have at least to have in mind the architectural pattern to be used, design patterns to be implemented, the protocol to use and [...]]]></description>
			<content:encoded><![CDATA[<p>Most modern applications are providing APIs. That allows you to integrate those applications providing APIs with third party applications and create a real <i>cloud</i> computing environment. From an architectural perspective, we should have at least to have in mind the architectural pattern to be used, design patterns to be implemented, the protocol to use and the data format to expose the API. The architectural pattern should be simple, the design pattern efficient, the protocol lightweight and the data format flexible for your requirements. With a good API design, it should be stable enough to support changes along the time dynamically.</p>
<p><span id="more-2448"></span></p>
<p>The architectural pattern should be simple. Most people is thinking on the MVC architectural pattern as the most proper architectural for any application. But really the MVC pattern was designed with very old basis and mostly with the idea of generalizing the user interface of desktop applications. Currently, Web Applications are build on top of many technologies, not RDBMS engines only, so you should start using the proper architectural pattern, where technology diversity should follow the maximum cohesion principle, rather than coupling application components.</p>
<p>We have as key principle of design <i>&laquo;minimum coupling, maximum cohesion&raquo;</i>, but I would like to add <i>&laquo;proper generalization&raquo;</i>. So, finally we should have <i>&laquo;minimum coupling, maximum cohesion &amp; proper generalization&raquo;</i> as design basis. If we observe, generalizations are older than software, we can stage that the term comes from Maths, where a generalization is a concept that can be applied to multiple problems and solve them using that concept. Cohesion is the principle of independent components that can work together, and coupling is a design which cannot separate its components. One of the best and classical examples of maximum cohesion on its design is Unix, where there are many small tools that can work together without coupling its functionalities.</p>
<p>A good generalization comes with from a good model, and any good generalization usually is able to solve multiple problems at once. Object Oriented programming provides a rich interface for abstractions, where the generalization is one of the most powerful ones, but in words of real generalization, I can proudly say that Monads are one of the best abstractions and mostly generalization that I ever seen.</p>
<ul>
<li>Haskell Programmer: Hey Java programmer, you know how just about everything is represented by a class?</li>
<li>Java Programmer: Yea&#8230;</li>
<li>HP: Even stuff no business being a class</li>
<li>JP: Well, it is our fundamental abstraction for anything larger than a function. It may be clumsy, but it can be used to implement any other design pattern we need.</li>
<li>HP: Well Monads serve the same role for us.</li>
<li>JP: Nulls?</li>
<li>HP: Maybe Monad</li>
<li>JP: I/O?</li>
<li>HP: IO Monad</li>
<li>JP: Exceptions and error handling?</li>
<li>HP: We have several ways, but mostly Maybe Monad</li>
<li>JP: List comprehension?</li>
<li>HP: Again, Monads</li>
<li>JP: Mutable data structures?</li>
<li>HP: That would be the State Monad<sub><a href="#note_2">[2]</a></sub></li>
</ul>
<p>With the proper generalization you can make your design to be consistent, robust and reliable. But you must leave the generalization concept just as <i>hierarchy</i> problem. It should be stated globally as <i>computational</i> problem rather than design problem only. A generalization as computation can be applied to multiple problems, where applying computational generalizations we can find mapping functions that can be globally used. This can be reached combining the IPO model and Object Oriented models properly, working together.</p>
<p>Software design is not easy. An UML class model is not enough, where it can only display <i>structures</i>, probably with a sequence models and communication models you can reach a good IPO design, but not without the proper knowledge about the implementation. So, any <i>analyst</i> who does not <a href='http://programming-motherfucker.com/' title='Programming, Motherfucker!, Do you speak it?'>knows how to program</a>, is just wasting your <a href='http://www.lnds.net/blog/2012/04/programa-ctm.html' title='¡Programa CTM!'>money and time</a>, with the obvious further reimplementation and redesign of the software product.</p>
<p>And you should start adding the proper generalizations as computations to your design, working together with your hierarchical generalizations, so they can bring you the proper quality along the time.</p>
<p style="font-size:10pt;"><a name="note_2">[2]</a> This is an excerpt from a discussion on a programming forum.</p>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2012. |
<a href="http://coder.cl/2012/05/my-software-design-principles/">Permalink</a> |
<a href="http://coder.cl/2012/05/my-software-design-principles/#comments">No comment</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2012/05/my-software-design-principles/&title=my software design principles">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2012/05/my-software-design-principles/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>what is thread-safe?</title>
		<link>http://coder.cl/2011/11/what-is-thread-safe/</link>
		<comments>http://coder.cl/2011/11/what-is-thread-safe/#comments</comments>
		<pubDate>Sat, 26 Nov 2011 20:51:11 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[c]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=2044</guid>
		<description><![CDATA[What is thread-safe?. Thread-safe implies that for a given resource it will not be used at the same time by two or more threads or processes. By resource, we must understand a memory block or similar kind of resources. If you create a list that is shared between threads to store data, you will need [...]]]></description>
			<content:encoded><![CDATA[<p>What is thread-safe?. Thread-safe implies that for a given resource it will not be used at the same time by two or more threads or processes. By resource, we must understand a memory block or similar kind of resources. If you create a list that is shared between threads to store data, you will need a way to write that list &mdash; appending nodes or removing nodes &mdash; without writing it simultaneously. This implies the usage of thread-safety techniques that will bring you sequential access to the list allowing sequential writes, instead concurrent writes that will probably crash your application.</p>
<p><span id="more-2044"></span></p>
<p>There are various kinds of techniques that can be used to create thread-safe algorithms and data structures. The are two main classes called <i>blocking algorithms</i> and <i>non-blocking algorithms</i>. On a blocking algorithm, locks are used to encapsulate fragments of code where you must not do concurrent writes to avoid racing conditions, where that fragment is called <i>critical section</i>. On non-blocking algorithms, you do not use locks, instead you use atomic operations to switch between the used resources, for example using a technique called <i>compare and swap</i> or <i>CAS</i>.</p>
<p>A racing condition, is an event that occurs when two or more threads are accessing the same resource at the same time, leading to data corruption or system faults. The most classic lock techniques in Java and C, are the <tt>synchronized</tt> keyword on Java and <tt>pthread_mutex_lock()</tt> call in C. On Java we protect our critical section using <tt>synchronized</tt> as follows.</p>
<pre class="brush: java;">
class SingletonSampleImpl extends Object {  

    private static Object singletonMutex = new Object();
    private static SingletonSampleImpl instance = null;  

    public static SingletonSampleImpl getInstance() {
        synchronized (singletonMutex) {
            /* when we instantiate the singleton
               we have a critical section to protect
               from racing conditions */
            if (instance == null) {
                instance = new SingletonSampleImpl();
            }
        }
        return instance;
    }
}
</pre>
<p>The <tt>singletonMutex</tt> object acts as <i>mutex</i>, where a mutex &mdash; term that comes from <i>mutual exclusion</i> &mdash; has a flag that indicates to the other threads if it is blocked or not to jump into the critical section and execute the code. So, a mutex or semaphore is a mere <i>flag</i> that indicates to the program if the resource is busy or not. Using locks or blocking-algorithms is expensive on most systems, depending on how are they used. For example is very expensive to use a blocking algorithm to protect a socket, where it must <i>wait</i> its chance to be written by other threads, with inherent network time wait.</p>
<p>On the non-blocking side, we have three types of algorithms: <i>wait-free</i>, <i>lock-free</i> and <i>obstruction-free</i>. Where wait free is the strongest technique, but the hardest to handle, because once you implement it you have an algorithm that do not <i>waits</i> for writing or reading. Lock-free usually uses CAS, so it using a compare and swap operation to ensure that the critical section is protected, without locking. Obstruction-free uses locking, but a different one called live-locking.</p>
<p>The atomic operations used on the non-blocking techniques usually are operating on a very low level of the processor, because they must executed without the interference of any other threads. For example to work with atomic operations using the GCC compiler we have some <a href='http://gcc.gnu.org/onlinedocs/gcc-4.3.2/gcc/Atomic-Builtins.html' title='Built-in functions for atomic memory access'>special extensions to work with them</a>.</p>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2011. |
<a href="http://coder.cl/2011/11/what-is-thread-safe/">Permalink</a> |
<a href="http://coder.cl/2011/11/what-is-thread-safe/#comments">No comment</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2011/11/what-is-thread-safe/&title=what is thread-safe?">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2011/11/what-is-thread-safe/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>evolutionary unit tests</title>
		<link>http://coder.cl/2011/07/evolutionary-unit-tests/</link>
		<comments>http://coder.cl/2011/07/evolutionary-unit-tests/#comments</comments>
		<pubDate>Fri, 08 Jul 2011 15:45:37 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=1653</guid>
		<description><![CDATA[Evolutionary development depends on continuous iterations with the customer, being a final customer or not, like an intern QA engineer. If you create unit tests in your evolutionary development process, you can also work with evolutionary unit tests. An evolutionary unit test can be used on code hardening tasks, because you must make your test [...]]]></description>
			<content:encoded><![CDATA[<p>Evolutionary development depends on continuous iterations with the customer, being a final customer or not, like an intern QA engineer. If you create unit tests in your evolutionary development process, you can also work with evolutionary unit tests. An evolutionary unit test can be used on code hardening tasks, because you must make your test fail using unexpected environment behaviour, for example passing <tt>null</tt> references to your unit tests, avoiding the well known <a href='http://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare' title='Null References: The Billion Dollar Mistake'><i>&ldquo;Null References: The Billion Dollar Mistake&rdquo;</i></a>, once the code is refactored to support <tt>null</tt> references.</p>
<p><span id="more-1653"></span></p>
<p>You can start checking the <a href='http://cwe.mitre.org/top25/?2011' title='2011 CWE/SANS Top 25 Most Dangerous Software Errors'><i>&ldquo;2011 CWE/SANS Top 25 Most Dangerous Software Errors&rdquo;</i></a> using your unit tests. Regarding the best programming practices, and even using style checkers and static analysis tools, you will be generating better code. So, the cycle is simple while you are testing your application:</p>
<ol>
<li>Create a Test Case.</li>
<li>Check that the Test Case runs correctly.</li>
<li>Choose a well known error, for example <i>null references</i>.</li>
<li>Change the Test Case and add the wrong input to your code.</li>
<li>Refactor the application hardening its input.</li>
<li>Check that the Test Case runs correctly with wrong input.</li>
<li>Document your progress with source code comments or annotations.</li>
<li>Choose another error and make the Test Case fail again.</li>
</ol>
<div class="figure">
<a href='http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2011/07/test-cycle.jpg' title='Code Hardening Testing Cycle' target='_blank'><img src='http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2011/07/test-cycle.jpg' border='0' alt='Code Hardening Testing Cycle' /></a></p>
<div>Code Hardening Testing Cycle</div>
</div>
<p>There is also some interesting papers and documents with some techniques that you can integrate in your development process, so you can create more stable code, mostly applied to Object-Oriented software and strongly-typed languages, which are talking about using manually created evolutionary tests to using genetic programming for those tasks. I hope that we can see the results of that research using genetic programming to automate the test handling process. The advantage of strongly-typed languages is the fact that most of them require to be statically-typed, which means that your code must follow well implemented type declarations and variable declaration using the proper types. So, the type system on those languages can be used to ensure that implementations are correctly done.</p>
<blockquote><p>
Initially, the test cluster for the given class under test is defined using static analysis. The concerned classes are then instrumented; thereby, the test goals &mdash; in our case all branches of the methods of the class under test &mdash; are collected. We follow the goal oriented approach and carry out a search for a test program for each individual test goal.
</p></blockquote>
<p>Static analysis again plays an interesting role on this approach, where is easier to handle static analysis on strongly-typed languages, rather than using static analysis on dynamically-typed languages.</p>
<blockquote><p>
When comparing evolutionary-based approaches over random testing [21] several prominent advantages arise, which include: less need for human analysis, as the evolutionary algorithm pre-analyses the software in accordance to the fitness function; the ability to automatically test combinations of suspicious parameters; and the possibility of finding combinations of inputs that lead to a more severe fault behaviour. Drawbacks include the difficulty of detecting solitary errors (&ldquo;needles in a haystack&rdquo;) with greater efficiency than random testing, and the impossibility of guaranteeing code coverage in black-box testing.
</p></blockquote>
<p>But if we have a lack of that kind of tools in our environment, so we must do that kind of analysis manually, and manually make our test to be tested against suspicious environment conditions, so we can use manual evolutionary unit testing. I hope that you will enjoy hardening your code ;)</p>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2011. |
<a href="http://coder.cl/2011/07/evolutionary-unit-tests/">Permalink</a> |
<a href="http://coder.cl/2011/07/evolutionary-unit-tests/#comments">No comment</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2011/07/evolutionary-unit-tests/&title=evolutionary unit tests">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2011/07/evolutionary-unit-tests/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>considerations in code review</title>
		<link>http://coder.cl/2011/07/considerations-in-code-review/</link>
		<comments>http://coder.cl/2011/07/considerations-in-code-review/#comments</comments>
		<pubDate>Thu, 07 Jul 2011 00:04:37 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=1644</guid>
		<description><![CDATA[Once we have created code, we can evaluate how it was done. We can use various tools to check our creation among other activities. To do standard checks, we can use style checkers, static checkers, unit testing suites and the most important one, the human code review. We can use Python as example language, or [...]]]></description>
			<content:encoded><![CDATA[<p>Once we have created code, we can evaluate how it was done. We can use various tools to check our creation among other activities. To do standard checks, we can use style checkers, static checkers, unit testing suites and the most important one, the human code review.</p>
<p><span id="more-1644"></span></p>
<p>We can use Python as example language, or even Java. To check the Python style, we can use the <a href='http://pypi.python.org/pypi/pep8/0.6.1' title='PEP8 Style Checker'>pep8</a> style checker, which is based on the <a href='http://www.python.org/dev/peps/pep-0008/' title='PEP8, Python Style Guide'>PEP8 Python Style Guide</a>. To make lightweight Python correctness checks, we can use <a href='http://pypi.python.org/pypi/pylint/0.23.0' title='PyLint Static Checker'>PyLint</a> and <a href='http://pypi.python.org/pypi/pyflakes/0.4.0' title='PyFlakes Static Checker'>PyFlakes</a>, which are <i>static checkers</i>. To build unit test suites, we can use <a href='http://pypi.python.org/pypi/PyUnit/1.4.1'>PyUnit</a>. All those tools will help us in our coding tasks, so we can create a better and clean code. Very close to the required standards cited by the PEP8 and The Zen of Python. I have modified a script that runs all those checkers in one command to be integrated under Emacs, and you can download it <a href='http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2011/07/pycheckers.py_.gz' title='pycheckers.py script'>here</a>. To integrate that script on your Emacs editor, you can use the following settings:</p>
<pre class="brush: lisp;">
(defun my-python-mode-hook ()
  (setq py-indent-offset 4
        py-smart-indentation nil
        py-continuation-offset 4
        indent-tabs-mode nil
        py-pychecker-command "pycheckers.py"
        py-pychecker-command-args (quote ("")))
  (setq interpreter-mode-alist(cons '("python" . python-mode)
                                    interpreter-mode-alist))
  (eldoc-mode 1)
  (define-key py-mode-map "C-cC-w" (lambda ()
     (interactive)
     (command-execute 'py-pychecker-run)))
  (message ">>> done my-python-mode-hook..."))

(add-hook 'python-mode-hook 'my-python-mode-hook)
</pre>
<p>On the Java side, we have CheckStyle as style checker. As static checker, we have PMD and FindBugs. To build unit testing suites, we can use the well known JUnit. All of those tools can be integrated in your favourite Java IDE, like Eclipse or NetBeans, since you can integrate them on those IDEs using plug-ins. Java is quite different from Python, because it has several coding styles, among a wide variety of FOSS projects and company standards, so you need to choose between those styles.</p>
<p>Among other tasks, the code review matters. Static analysis tools and style checkers are not enough to ensure that your code is clean. You can use code hardening techniques to make safer code. But that requires that you must stay a little bit paranoid with your code, checking every execution path on it. There are some good books on code hardening techniques like <i>&ldquo;GNU/Linux Application Programming&rdquo;</i>, which explains some techniques and <i>&ldquo;Secure Coding Principles &amp; Practice&rdquo;</i>.</p>
<p>You can integrate those techniques in your evolutionary testing process. Debugging tests is not a ridiculous task, I think that it is a good approach to make better code, assuming that you will modify the program variables enough to make your unit tests fail, and then refactor the code, repair possible failure and fix a harder execution path. But those activities requires the proper time assignment, so your project manager must include enough time to test and prove that your code will work well, even if the environment fails.</p>
<p>I hope that you will enjoy changing your mind about thinking that the code that just works is fine, switching a little and make sure that your code will work <i>always</i>.</p>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2011. |
<a href="http://coder.cl/2011/07/considerations-in-code-review/">Permalink</a> |
<a href="http://coder.cl/2011/07/considerations-in-code-review/#comments">No comment</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2011/07/considerations-in-code-review/&title=considerations in code review">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2011/07/considerations-in-code-review/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>singleton are not dangerous</title>
		<link>http://coder.cl/2011/06/singleton-are-not-dangerous/</link>
		<comments>http://coder.cl/2011/06/singleton-are-not-dangerous/#comments</comments>
		<pubDate>Thu, 30 Jun 2011 16:39:34 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=1631</guid>
		<description><![CDATA[Yes, singleton patterns are not dangerous. That pattern is dangerous only for those developers that cannot handle concurrent programming or parallel programming, where you need to manage resources with concurrent access, even if they are read or write. There are some myths related to the singleton pattern, but they are just created by that kind [...]]]></description>
			<content:encoded><![CDATA[<p>Yes, singleton patterns are not dangerous. That pattern is dangerous only for those developers that cannot handle concurrent programming or parallel programming, where you need to manage resources with concurrent access, even if they are read or write. There are some myths related to the singleton pattern, but they are just created by that kind of developers. If you don&#8217;t know about concurrent programming techniques, is obvious that your application is at risk if your are using singletons with the wrong implementation. Also it depends on how large is your application, how do you apply governance over you application design and which platform is using.</p>
<p><span id="more-1631"></span></p>
<p>Certainly an application that uses a worker model, using threads, probably requires concurrent programming techniques to use the singleton pattern. That kind of applications, for example those implemented under JavaEE containers, like IBM WebSphere and Oracle WebLogic, require a good governance over the code and a good knowledge on how will be used a singleton implementation. In other environments, where static objects are not shared on the stack, you don&#8217;t need to care about singleton implementations, like PHP environments, where only one thread or process is reaching the singleton object, it just requires to be instanced once, and do not requires mutexes.</p>
<p>If you are good enough, you can use the singleton pattern on worker enabled environments. The well known <tt>getInstance</tt> method, should be implemented as follows in Java under JavaEE environments:</p>
<pre class="brush: java;">
class SingletonSampleImpl extends Object {

    private static Object singletonMutex = new Object();
    private static SingletonSampleImpl instance = null;

    public static SingletonSampleImpl getInstance() {
        synchronized (singletonMutex) {
            if (instance == null) {
                instance = new SingletonSampleImpl();
            }
        }
        return instance;
    }
}
</pre>
<p>In other environments like PHP, you do not need to care about creating a mutex that protects the singleton instance to be overwritten or allocated twice, you just need to care about an object instance that is not accessed twice by various threads concurrently.</p>
<pre class="brush: php;">
class SingletonSample {

    private static $instance = null;

    public static function getInstance() {
        if ($instance == null) {
            $instance = SingletonSample();
        }
        return $instance;
    }
}
</pre>
<p>Also you must be very careful, and never externalise the control of mutexes to external routines. A mutex must be controlled locally. The reason is simple, you just need to avoid a deadlock by double locking the mutex. If you externalise the control of a mutex, you are in risk of reaching a situation like the following problem, where the second lock will wait for the first one, creating a deadlock and killing the thread.</p>
<pre class="brush: java;">
synchronized (singletonMutex) {
    synchronized (singletonMutex) {
        instance = new SingletonSampleImpl();
    }
}
</pre>
<p>This is just the situation that you can reach by externalising the control of a mutex, not the algorithm itself that you will implement, but the risk that you run by allowing mutexes to be locked outside of the controlling class. This is a similar situation that generates a race condition when you are programming singletons in worker environments without using the proper mutex. The wrong implementation of a singleton that is under the risk of a race condition is on the following example, where the algorithm just checks for a null value, and do not uses a lock for the concurrent threads that can instantiate the <tt>instance</tt> object.</p>
<pre class="brush: java;">
class SingletonSampleImpl extends Object {

    private static Object singletonMutex = new Object();
    private static SingletonSampleImpl instance = null;

    public static SingletonSampleImpl getInstance() {
        if (instance == null) {
            instance = new SingletonSampleImpl();
        }
        return instance;
    }
}
</pre>
<p>So, using singletons is not dangerous. Just requires to have developers with the proper knowledge.</p>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2011. |
<a href="http://coder.cl/2011/06/singleton-are-not-dangerous/">Permalink</a> |
<a href="http://coder.cl/2011/06/singleton-are-not-dangerous/#comments">One comment</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2011/06/singleton-are-not-dangerous/&title=singleton are not dangerous">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2011/06/singleton-are-not-dangerous/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>code hardening techniques</title>
		<link>http://coder.cl/2011/02/code-hardening-techniques/</link>
		<comments>http://coder.cl/2011/02/code-hardening-techniques/#comments</comments>
		<pubDate>Wed, 23 Feb 2011 13:40:33 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=1348</guid>
		<description><![CDATA[Do you know something about Test Driven Development?, It is OK, you can reach optimal development performance using TDD, and similar methodologies. You will find yourself developing applications very quickly, but &#8220;how hard is your code?&#8221;. You can reach very high quality code only using your debugger, making tests is just not enough. Using some [...]]]></description>
			<content:encoded><![CDATA[<p>Do you know something about Test Driven Development?, It is OK, you can reach optimal development performance using TDD, and similar methodologies. You will find yourself developing applications very quickly, but <i>&ldquo;how hard is your code?&rdquo;</i>. You can reach very high quality code only using your debugger, making tests is just not enough. Using some debugging techniques, you can find not evident bugs, and you will probably find succesfuly some bugs that can cause your application to core dump &mdash; core dump is one of the ugliest forms of application failures, I prefer to think that each application failures is not another thing than a core dump.</p>
<p><span id="more-1348"></span></p>
<p>You can use unit tests and TDD, and double check that your algorithms are working. Also you can check your code using some <i>static checker</i>. Both will help to find you a little bit optimal code. This will allow you create more stable and reliable code, but not enough to be hard. When you code an aplication, you must think that the application and your code is merged within an environment, and it has dependencies. So, you need enough time to double check your code using tests and also, you need to double check your code using static checkers when they are available for your language. All is about input and output&#8230;</p>
<p>Your code has an input, from a service, from the user using a browser, from some data retrieval cron task, whatever, your application is subject of <i>input errors</i>. The typicall error is to reach <i>null references</i>, where your application tries to use an unallocated address space, using a reference to an object or anything related to it. The main technique against null reference, is to check the reference before you begin using it. Just to show some examples I will use Java code, I can use C++ or C code, but I prefer to use Java codes in this post:</p>
<pre class="brush: java;">
  /***
   * Returns a list of File objects that match the given stream
   * name on the given directory.
   *
   * @param strm    Stream name.
   * @param bdir    Directory to List.
   * @return      An array of found File objects.
   */
  public static File[] getFileNamesForStream(String strm, String bdir) {
    ArrayList&lt;File&gt; res = new ArrayList&lt;File&gt;();
    if (strm == null || bdir == null) {
      return new File[0];
    }
    if (strm.trim().length() == 0 || bdir.trim().length() == 0) {
      return new File[0];
    }
    File fdir = new File(bdir);
    File[] rawdir = fdir.listFiles();
    if (rawdir == null || rawdir.length == 0) {
      return new File[0];
    }
    for (int i = 0; i &lt; rawdir.length; i++) {
      String name = rawdir[i].getName();
      if (name.indexOf(strm) >= 0) {
        res.add(new File(bdir + File.separator + name));
      }
    }
    Collections.sort(res, new FileDateComparator());
    return (File[]) res.toArray(new File[0]);
  }
</pre>
<p>The code above does various checks. Ther first one is to check the <tt>strm</tt> and the <tt>bdir</tt> parameters to be <tt>null</tt>. If those parameters are null, the method returns an empty array &mdash; instead of returning a new null reference increasing the error probability &mdash; so the user do not process any file from the returned array, the returned object can be used <i>transparently</i>. Then checks for string emptyness, we cannot use empty file names, because the operating system do not allows empty file names, and again we are using a zero filled array as return object. Then we list files on the input directory <tt>bdir</tt>, and we check if there is any available file on the directory, if the directory is empty, we return a zero filled array, but <i>never returns a null reference</i>. The method is <i>hardened</i> against input and output. The example above is easy to handle, but <i>&ldquo;what happens to service enabled methods?&rdquo;</i>.</p>
<pre class="brush: java;">
  /**
   * Initial method to handle playlist items on server startup.
   *
   * @param server      The server where to put the streams.
   */
  private void refreshPlayList(IServer server) {
    try {
      if (server == null) {
        return;
      }
      if (minutesToShift &lt; 0 &amp;&amp; ownServer != null) {
        synchronized (schedulerMutex) {
          minutesToShift = Long.valueOf(ownServer.
              getProperties().
              getPropertyStr("MinutesToShift", "41")).
            longValue();
        }
      }
      IVHost vhost = VHostSingleton.getInstance(server.
                         getProperties().
                         getPropertyStr("PublishToVHost", VHost.VHOST_DEFAULT));
      if (vhost == null) {
        return;
      }
      IApplication app = vhost.getApplication(server.
                         getProperties().
                         getPropertyStr("PublishToApplication", "live"));
      if (app == null) {
        return;
      }
      streamsToAdd = WowzaTools.getStreams(server.
                         getProperties().
                         getPropertyStr("StreamsToAdd", "_default_"));
      for (int si = 0; si &lt; streamsToAdd.length; si++) {
        String streamName = streamsToAdd[si] + STREAM_SUFFIX;
        Stream stream = getStream(vhost, app, streamName);
        if (stream == null) {
          continue;
        }
        streamMap.put(streamName, stream);
        app.getAppInstance("_definst_").
          getProperties().
          setProperty(streamName, stream);
        setupStream(stream);
        IStreamActionNotify actionNotify = new
          StreamListener(app.getAppInstance("_definst_"));
        stream.addListener(actionNotify);
      }
      ScheduledItem sched = new ScheduledItem(
        new Date(System.currentTimeMillis() + 30000)
      );
      sched.start();
    } catch (Exception ex) {
      log.error(ex.getMessage());
      log.error(ex);
    }
  }
</pre>
<p>The method above is <tt>void</tt>, it do not have a return value. The first check is over the <tt>server</tt> argument, if it is a <i>null reference</i>, we exit from the method. Then checks for the <tt>minutesToShift</tt> and the <tt>ownServer</tt> static members, and uses a mutex to write on one of them, doing a synchronous write and doing it once. Then we check for the <tt>vhost</tt> and <tt>app</tt> variable to be null references, we exit from the method if any of them are null references. Those checks are made <i>before</i> using those variables. Depending on how do you handle that kind of errors, you should use an exception instead of a plain return, but it depends on how do you need to handle the error. Then, another check is done on the cycle, we check if the obtained stream is a null reference, if it is a null reference, we continue processing the loop, instead of using that null reference. On this method we depend on third party methods that can return null reference, so we <i>must</i> check for them, instead of being sure of their availability. If you are a good observer, you will notice that the method <tt>getPropertyStr()</tt> has a default return value when the parameter is not found, but <i>&ldquo;what happens with those methods without a default return value?&rdquo;</i>.</p>
<pre class="brush: java;">

  public ActionForward execute(ActionMapping mapping,
                               ActionForm form,
                               HttpServletRequest request,
                               HttpServletResponse response)
         throws IOException, ServletException {
    String target = "success";
    String request_arg = request.getParameter("request_arg") == null ?
                         "0" :
                         request.getParameter("request_arg");
    if (form != null) {
      NameForm nameForm = (NameForm)form;
      String name = nameForm.getName() == null ?
                    "" :
                    nameForm.getName();
    }
    if (name == null) {
      target = "failure";
    } else {
      request.setAttribute("name", name);
    }
    request.setAttribute("request_arg",
                         Integer.valueOf(request_arg));
    request.setAttribute("target", target);
    return (mapping.findForward(target));
  }
</pre>
<p>Above we have a typicall struts ActionForward method. It handles a request argument with a default value, using the ternary operator to do that. Checks for the possible null reference that can provide the <tt>request_arg</tt> parameter. The same applies to the form attribute <i>name</i> returned by the <tt>getName</tt> method. Using default values, can help you a lot. Null references are like a ninja waiting patiently to dismember you when are not expecting him. Again we have a method that is <i>a little bit hardened</i>. The same we can apply to our unit tests, we can ensure that they will not fail, for example if we have the following test:</p>
<pre class="brush: java;">
  /**
   * Test Video Info Handling.
   */
  public void testVideoInfo1() {
    System.out.println("testVideoInfo1() Entering ->");
    String streamNames1 = "CHANNEL_TV";
    String directoryName1 = "/home/dmw/tm";
    VideoInfo[] streamsToAdd1 = WowzaTools.getInfoList(streamNames1, directoryName1);
    for (int i = 0; i &lt; streamsToAdd1.length; i++) {
      VideoInfo current = streamsToAdd1[i];
      String msg = "Name: " + current.getVideo().getName()
        + "; Date: " + current.getTime()
        + "; Duration: " + WowzaTools.secondsToMinutes(current.getDuration());
      System.out.println(msg);
    }
    System.out.println("testVideoInfo1() Exiting &gt;-");
  }
</pre>
<p>On this method we are testing the <tt>getInfoList()</tt> method. Since it is a testing class, it is easy enough to change the arguments passed to the <tt>getInfoList()</tt> method. We can pass null references, incorrect arguments and anything we think that can generate an error. We must not <i>trust</i> in the user input. Is easy to change some lines to <i>streamNames1 = null;</i>, <i>streamNames1 = &#8220;xxx&#8221;;</i>, <i>directoryName1 = null;</i>, <i>directoryName1 = &#8220;/dev/null&#8221;;</i>, or whatever can help you to detect possible failures in your code. You will be hardening your code if you can handle more errors which the typicall user can generate. Also, you must request enough time to your project manager to complete code hardening tasks and debugging sessions, which are slow, since you need to trace the code various times. Is not enough to write unit tests, you need to run your tests and debug them, and change every dependent value to ensure that your code is free of flaws. I do not know if project managers are considering code hardening or testing time, usually I just see enough time only to <i>develop</i> software, not to ensure that it will not fail. If you do not have enough time to do those tasks, because your project manager is not measuring that time as part of the development process, your project manager sucks&#8230;</p>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2011. |
<a href="http://coder.cl/2011/02/code-hardening-techniques/">Permalink</a> |
<a href="http://coder.cl/2011/02/code-hardening-techniques/#comments">No comment</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2011/02/code-hardening-techniques/&title=code hardening techniques">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2011/02/code-hardening-techniques/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>wowza synchronization and required mutexes</title>
		<link>http://coder.cl/2011/01/wowza-synchronization-and-required-mutexes/</link>
		<comments>http://coder.cl/2011/01/wowza-synchronization-and-required-mutexes/#comments</comments>
		<pubDate>Tue, 11 Jan 2011 14:45:09 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=1208</guid>
		<description><![CDATA[As we have seen Wowza Media Server supports custom extensions through its Java API. One big deal with the Wowza Media Server, while I was creating the time shifted streaming extension, was the server thread synchronization. Not a big deal from the point of view regarding the client side stream, but the monitoring thread for [...]]]></description>
			<content:encoded><![CDATA[<p>As we have seen Wowza Media Server supports custom extensions through its Java API. One big deal with the Wowza Media Server, while I was creating the time shifted streaming extension, was the server thread synchronization. Not a big deal from the point of view regarding the client side stream, but the monitoring thread for each recorder and playlist was a problem to synchronize. Most problems were related to interface implementations.</p>
<p><span id="more-1208"></span></p>
<p><br/></p>
<h3>list implementation</h3>
<p>As we have seen, the playlist container uses a <i>List</i> implementation to store <i>PlaylistItem</i> objects. The problem with that implementation is that you can&#8217;t execute the <tt>clear()</tt> method properly, because it maintains the list size. So, each time that I was adding items to the playlist, and every time that a reschedule was required I was using the <tt>addToPlaylist()</tt> method before the <tt>clear()</tt> call, expecting the list to be emptied and resized to zero. That was not true. The trick was just to create a new playlist on each reschedule event.</p>
<pre class="brush: java;">
Playlist playlist = new Playlist(stream.getName());
playlistMap.put(stream.getName(), playlist);
long offset = WowzaTools.getTimeShiftOffset(videoList, minutesToShift);
synchronized (streamMutex) {
    for (int pi = 0; pi &lt; videoList.length; pi++) {
        VideoInfo cs = videoList[pi];
        if (pi == 0) {
            stream.addToPlaylist(stream.getPlaylist().size() + 1,
                                 cs.getVideo().getName(),
                                 (int) offset, cs.getDuration());
        } else {
            stream.addToPlaylist(stream.getPlaylist().size() + 1,
                                 cs.getVideo().getName(),
                                 0, cs.getDuration());
        }
    }
}
playlist.open(stream);
</pre>
<p><br/></p>
<h3>required mutexes</h3>
<p>When the stream recording cuts the stream recording twice &mdash; caused by network problems &mdash; the <tt>onPlaylistItemStop()</tt> is triggered twice too. This can cause a race condition, and causing the server to stop some stream transmissions, and even can cause the lost of the stream recording. Events are not triggered sequentially, and they seems to be using some asynchronous kind of execution mechanism. So, the playlist rescheduling mechanism has to deal with that condition. To solve that issue, I&#8217;ve created two mutexes. One mutex for the event scheduler and other mutex for the stream treating mechanism. That is ensuring &mdash; in some manner &mdash; that event handlers are executed sequentially.</p>
<pre class="brush: java;">
synchronized (schedulerMutex) {
    if (item.getIndex() == (stream.getPlaylist().size() - 1)) {
        synchronized (streamMutex) {
            setupStream(stream);
        }
    }
}
</pre>
<p>The previous algorithm ensures scheduler events are triggered sequentially and even stream treating methods are treating the streams blocking them on each event. Why I don&#8217;t used the stream itself as mutex, is because the stream can be blocked by other threads, and probably it can cause a deadlock, so I don&#8217;t have blocked server side objects. Probably, instead of using a <i>synchronized</i> mutex on Java for certain cases is less elegant than using <i>rwlocks</i> in POSIX threads, but the Java API do not offers <i>rwlocks</i>, and you can deal only with <i>synchronized</i> mutexes. I&#8217;ve missed rwlocks in this project.</p>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2011. |
<a href="http://coder.cl/2011/01/wowza-synchronization-and-required-mutexes/">Permalink</a> |
<a href="http://coder.cl/2011/01/wowza-synchronization-and-required-mutexes/#comments">No comment</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2011/01/wowza-synchronization-and-required-mutexes/&title=wowza synchronization and required mutexes">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2011/01/wowza-synchronization-and-required-mutexes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>wowza stream recorders</title>
		<link>http://coder.cl/2011/01/wowza-stream-recorders/</link>
		<comments>http://coder.cl/2011/01/wowza-stream-recorders/#comments</comments>
		<pubDate>Thu, 06 Jan 2011 16:35:58 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=1196</guid>
		<description><![CDATA[Wowza Media Server supports a wide variety of applications thanks to its extensible API. The media server API is exposed as a set of Java classes and interfaces to be implemented, so you can handle server side, application side and stream side events, metadata and media control routines. I&#8217;ve implemented a stream recorder because the [...]]]></description>
			<content:encoded><![CDATA[<p>Wowza Media Server supports a wide variety of applications thanks to its extensible API. The media server API is exposed as a set of Java classes and interfaces to be implemented, so you can handle server side, application side and stream side events, metadata and media control routines. I&#8217;ve implemented a stream recorder because the <tt>live-record</tt> stream type records all streams on the configured application and also it do not have any configuration directive to control the recorded stream.</p>
<p><span id="more-1196"></span></p>
<p>One of my current projects is to implement a time shifted stream scheduler for the Wowza Media Server. The difference between the original stream and the time shifted stream is large enough to flood the hard drive with recorded data if you leave configured the <tt>live-record</tt> stream type. Then I&#8217;ve coded a custom stream recorder. The API is very nice to do such task. I&#8217;ve created an <i>application side</i> module to record streams under certain conditions.</p>
<pre class="brush: xml;">
&lt;Property&gt;
        &lt;Name&gt;MediaFormat&lt;/Name&gt;
        &lt;Value&gt;1&lt;/Value&gt;
&lt;/Property&gt;
&lt;Property&gt;
        &lt;Name&gt;Append&lt;/Name&gt;
        &lt;Value&gt;false&lt;/Value&gt;
&lt;/Property&gt;
&lt;Property&gt;
        &lt;Name&gt;VersionFile&lt;/Name&gt;
        &lt;Value&gt;true&lt;/Value&gt;
&lt;/Property&gt;
&lt;Property&gt;
        &lt;Name&gt;StartOnKeyFrame&lt;/Name&gt;
        &lt;Value&gt;true&lt;/Value&gt;
&lt;/Property&gt;
&lt;Property&gt;
        &lt;Name&gt;RecordData&lt;/Name&gt;
        &lt;Value&gt;true&lt;/Value&gt;
&lt;/Property&gt;
&lt;Property&gt;
        &lt;Name&gt;RecordStreams&lt;/Name&gt;
        &lt;Value&gt;TV_STRM_CH_8,TV_STRM_CH_5,TV_STRM_CH_2&lt;/Value&gt;
&lt;/Property&gt;
</pre>
<p>The <i>MediaFormat</i> property allows you to record flv media when it&#8217;s set to 1 and mp4 media files when it&#8217;s set to 2. Otherwise, it records flv media files by default. If the <i>Append</i> property is set to true it must be used with <i>VersionFile</i>, <i>StartOnKeyFrame</i> and <i>RecordData</i> enabled. The <i>Append</i> property allows you to create one unique recorded media files for each stream. If you set <i>Append</i> to false, the module creates recorded media files with a timestamp suffix with the format <tt>yyyyMMddHHmm</tt>. And since the time shift module requires stream metadata information, I&#8217;m using Append as false and setting the full stream information with the other metadata information properties enabled too.</p>
<p>The <i>RecordStreams</i> property allows you to record only those configured streams, instead of recording all streams &mdash; by using the <tt>live-record</tt> stream type &mdash; and allowing you configure which information will be distributed along the media files.</p>
<p>The main trick to record streams is to use not early events. First I&#8217;ve tried using <tt>onAppStart()</tt> event method and then <tt>onStreamCreate()</tt> event method, but they didn&#8217;t work. Now I&#8217;m using the <i>IMediaStreamActionNotify2</i> interface with the proper events to handle the stream creation and the stream metadata, such as stream name, stream media type and related stuff. Probably the disadvantage of using custom media recorders is the fact that the API only provides <i>LiveStreamRecorderMP4</i> and <i>LiveStreamRecorderFLV</i> recording classes and if you want an open media format, such as OGG enabled streams, this will not work.</p>
<p>The stream recorder module uses the <i>ModuleBase</i> abstract class, the time shifter publisher implements the <i>IServerNotify</i> interface. You have a wide variety of classes and interfaces that can be used on different tasks, including some weird such as LDAP enabled authentication mechanisms. You just need to think and to architect your server extension a little.</p>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2011. |
<a href="http://coder.cl/2011/01/wowza-stream-recorders/">Permalink</a> |
<a href="http://coder.cl/2011/01/wowza-stream-recorders/#comments">No comment</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2011/01/wowza-stream-recorders/&title=wowza stream recorders">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2011/01/wowza-stream-recorders/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>more on wowza media server</title>
		<link>http://coder.cl/2010/12/more-on-wowza-media-server/</link>
		<comments>http://coder.cl/2010/12/more-on-wowza-media-server/#comments</comments>
		<pubDate>Thu, 30 Dec 2010 12:39:33 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=1158</guid>
		<description><![CDATA[As we have seen, the Wowza Media Server is an extensible Streaming Server that can allow you to create time shifted streams or scheduled streams. If you are using the live-record stream type or the LiveStreamRecord module, you can create a good time shifting module to schedule streams along a given set of streams. The [...]]]></description>
			<content:encoded><![CDATA[<p>As we have seen, the Wowza Media Server is an extensible Streaming Server that can allow you to create time shifted streams or scheduled streams. If you are using the <tt>live-record</tt> stream type or the <tt>LiveStreamRecord</tt> module, you can create a good time shifting module to schedule streams along a given set of streams. The problem is that the playlist must be dynamic, so I&#8217;ve solved that issue rescheduling the playlist.</p>
<p><span id="more-1158"></span></p>
<p></p>
<h3>non cycled media files</h3>
<p>If you have non-cycled media files you can&#8217;t the timestamp on files to cycle them. You need create a dynamic playlist, reading the media file metadata each time that the playlist finishes to transmit its contents. Fortunately, the Wowza Media Server API provides an event handling method called <tt>onPlaylistItemStop</tt> on the <tt>IStreamActionNotify</tt> interface. To reconstruct the playlist on that method, you just need to call a playlist refreshing method.</p>
<pre class="brush: java;">
try {
    log.error("---&gt; Scheduled: onPlaylistItemStop() -> Enter");
    if (item.getIndex() == (stream.getPlaylist().size() - 1)) {
        stream.getPlaylist().clear();
        setupStream(stream, pl);
    }
    log.error("---&gt; Scheduled: onPlaylistItemStop() -> Exit");
} catch (Exception ex) {
    log.error(ex.getMessage());
}
</pre>
<p>Once we clear the playlist, we call the <tt>setupStream</tt> method &mdash; which must be implemented by you &mdash; and it will reconstruct the playlist.</p>
<p>The arguments that I bring to the application through the <i>WowzaScheduler</i> module &mdash; which is a private development, so I can&#8217;t release the module, and even the code &mdash; are as follows:</p>
<pre class="brush: xml;">
&lt;Property&gt;
        &lt;Name&gt;StreamsToAdd&lt;/Name&gt;
        &lt;Value&gt;CH2_TV,CH3_TV,CH4_TV&lt;/Value&gt;&lt;!-- dmw: stream names to add --&gt;
&lt;/Property&gt;
&lt;Property&gt;
        &lt;Name&gt;MinutesToShift&lt;/Name&gt;
        &lt;Value&gt;30&lt;/Value&gt;&lt;!-- dmw: 30 minutes --&gt;
&lt;/Property&gt;
</pre>
<p>This will allow you to add only the streams CH2_TV, CH3_TV and CH4_TV, with a timeshift of 30 minutes.</p>
<p></p>
<h3>major problems found</h3>
<p>Major problems found while I was developing the extension are a little bit hard to handle. The main one is the fact that the API do not provides publicly any class or method that allows you to read metadata information about the media files. We used some external tools to handle that issue.</p>
<p>Another problem is that <tt>Stream.getPlaylist</tt> method provides an instance to the playlist in the form of a standard <tt>List&lt;PlaylistItem&gt;</tt>. So, we have some problems with that, since we don&#8217;t have any media type related methods and the <tt>PlaylistItem</tt> interface do not provides media file metadata information methods too. We are using a kind of catalog to handle media processing tasks. Probably we need to create a <i>daemon</i> to handle media processing, something done in a low level language, like <strong>C</strong>, and third party FOSS libraries.</p>
<p>You can find problematic some issues related to the streams storing on the media server. For example if the server is very <i>busy</i>, and you do a server restart or server stop, and the operating system requires to kill the process instead of doing a normal shutdown, some media files will be truncated, and certain data blocks for those media files will not be flushed to the hard drive, with the risk of lost recording seconds.</p>
<p>For now, the stream scheduler and stream time shifter is working fine. It passed many tests, but still we are testing the module. I hope that we will finish this project very well, as it is working now&#8230;</p>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2010. |
<a href="http://coder.cl/2010/12/more-on-wowza-media-server/">Permalink</a> |
<a href="http://coder.cl/2010/12/more-on-wowza-media-server/#comments">No comment</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2010/12/more-on-wowza-media-server/&title=more on wowza media server">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2010/12/more-on-wowza-media-server/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>wowza media server scheduler</title>
		<link>http://coder.cl/2010/12/wowza-media-server-scheduler/</link>
		<comments>http://coder.cl/2010/12/wowza-media-server-scheduler/#comments</comments>
		<pubDate>Fri, 24 Dec 2010 15:00:36 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=1139</guid>
		<description><![CDATA[Wowza Media Server is a Tomcat server adapted to serve audio and video streams using the RTMP protocol. One great advantage of this Media Server is the fact that you can extend it using Java modules. The API is a little bit hard to understand, but very flexible. One of my recent projects was to [...]]]></description>
			<content:encoded><![CDATA[<p>Wowza Media Server is a Tomcat server adapted to serve audio and video streams using the RTMP protocol. One great advantage of this Media Server is the fact that you can extend it using Java modules. The API is a little bit hard to understand, but very flexible. One of my recent projects was to create a Dynamic Scheduler Module for the Wowza Media Server.</p>
<p><span id="more-1139"></span></p>
<p></p>
<h3>cycled media files</h3>
<p>Media Files stored on the hard drive, were encoded using the MP4 codec. Those files were cycling in ranges of 10 to 20 files and updated dynamically, like rotation logs, but with video file names being reused along the Media Server play list. In other cases, the Media Server play list is very dynamic, and the list of media files changes during the playback recording. I&#8217;ve created a very simple algorithm which lists the files and sorts them. The plug-in must handle that list of files on the cycle and realign the file order to use the last modified file according to the given time of minutes.</p>
<pre class="brush: java;">
/***
 * Returns a list of File objects that match the given stream
 * name on the given directory.
 *
 * @param strm      Stream name.
 * @param bdir      Directory to List.
 * @return          An array of found File objects.
 */
public static File[] getFileNamesForStream(String strm, String bdir) {
    ArrayList&lt;File&gt; res = new ArrayList&lt;File&gt;();
    if (strm == null || bdir == null) {
        return new File[0];
    }
    if (strm.trim().length() == 0 || bdir.trim().length() == 0) {
        return new File[0];
    }
    File fdir = new File(bdir);
    if (fdir == null) {
        return new File[0];
    }
    File[] rawdir = fdir.listFiles();
    if (rawdir == null || rawdir.length == 0) {
        return new File[0];
    }
    for (int i = 0; i &lt; rawdir.length; i++) {
        String name = rawdir[i].getName();
        if (name.indexOf(strm) >= 0) {
            res.add(new File(bdir + File.separator + name));
        }
    }
    Collections.sort(res, new FileDateComparator());
    return (File[]) res.toArray(new File[0]);
}
</pre>
<p>Getting the file list sorted is quite easy. And reorder the the files according to the cycle and the given timestamp is very easy too.</p>
<pre class="brush: java;">
/**
 * Returns the cycled list of File object to be scheduled on the
 * Wowza Server.
 *
 * @param strm          input stream File name pattern.
 * @param bdir          input base directory.
 * @param mins          minutes elapsed.
 * @return              a list of files to cycle in the Wowza Server.
 */
public static File[] getCycledFileList(String strm, String bdir, long mins) {
    if (mins &lt;= 0) {
        return new File[0];
    }
    File[] lst1 = WowzaTools.getFileNamesForStream(strm, bdir);
    ArrayList&lt;File&gt; lst2 = new ArrayList&lt;File&gt;();
    ArrayList&lt;File&gt; lst3 = new ArrayList&lt;File&gt;();
    ArrayList&lt;File&gt; retLst = new ArrayList&lt;File&gt;();
    for (int i = 0; i &lt; lst1.length; i++) {
        if (WowzaTools.getMatchElapsedTime(lst1[i], mins)) {
            lst2.add(lst1[i]);
        } else {
            lst3.add(lst1[i]);
        }
    }
    for (int i = 0; i &lt; lst2.size(); i++) {
        retLst.add((File)lst2.get(i));
    }
    for (int i = 0; i &lt; lst3.size(); i++) {
        retLst.add((File)lst3.get(i));
    }
    return (File[]) retLst.toArray(new File[0]);
}
</pre>
<p>Probably the trick is in the timestamp comparing routine:</p>
<pre class="brush: java;">
/***
 * Looks if the file is immediate before the given range
 * of minutes.
 *
 * @param inf       input file.
 * @param mins      minutes.
 * @return          true if the file matches.
 */
public static boolean getMatchElapsedTime(File inf, long mins) {
    long ct = System.currentTimeMillis();
    long ct_d = ct - (mins * 60000);
    long modtm = inf.lastModified();
    return (modtm &gt;= ct_d);
}
</pre>
<p></p>
<h3>the matching timestamp</h3>
<p>The Wowza Media Server recordings are stored sequentially on the <i>&lt;StorageDir/&gt;</i> directory. Since the recordings are dynamically generated, and opening each stream to get his time is a little bit hard to the Media Server, I&#8217;ve used the <i>File</i> modification time to get information about the time sequence of each file. Once the files are sorted, timestamps looks as follows:</p>
<pre class="brush: java;">
if (filesToAdd.length > 1) {
    File prev = filesToAdd[(filesToAdd.length - 1)];
    for (int pi = 0; pi &lt; filesToAdd.length; pi++) {
        File cs = filesToAdd[pi];
        int secs = (int)((prev.lastModified() - cs.lastModified()) / 1000);
        secs = secs &gt; 0 ? secs : secs * -1;
        if (pi == 0) {
            playlist.addItem(cs.getName(), ft, secs);
        } else {
            playlist.addItem(cs.getName(), 0, secs);
        }
        prev = cs;
    }
}
</pre>
<p>The algorithm looks very simple. But the <tt>ft</tt> is the key argument for first list item: <img src='http://s.wordpress.com/latex.php?latex=%28%28c%20-%20s%29%20-%20%28c%20-%20m%29%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='((c - s) - (c - m))' title='((c - s) - (c - m))' class='latex' />. Where <img src='http://s.wordpress.com/latex.php?latex=c&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='c' title='c' class='latex' /> is the current time, <img src='http://s.wordpress.com/latex.php?latex=m&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='m' title='m' class='latex' /> is the modification time and <img src='http://s.wordpress.com/latex.php?latex=c&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='c' title='c' class='latex' /> is the time shifting argument. So, the difference is used to calculate the first file on the playlist time shifting to use the proper offset in seconds. The solution is simple, and can be used in other tasks on the Wowza Media Server. I think that you can avoid many complex tasks using the modification time on media files.</p>
<p>Now I&#8217;m thinking on the creation of commercial extensions for the Wowza Media Server ;)</p>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2010. |
<a href="http://coder.cl/2010/12/wowza-media-server-scheduler/">Permalink</a> |
<a href="http://coder.cl/2010/12/wowza-media-server-scheduler/#comments">No comment</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2010/12/wowza-media-server-scheduler/&title=wowza media server scheduler">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2010/12/wowza-media-server-scheduler/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
<!-- This Quick Cache file was built for ( 2e96b290f6c5ccd2bc6830557c0aba6e coder.cl/category/programming/java/feed/ ) in 0.57877 seconds, on May 15th, 2012 at 11:03 am UTC. -->
<!-- This Quick Cache file will automatically expire ( and be re-built automatically ) on May 22nd, 2012 at 11:03 am UTC -->
<!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<!-- Quick Cache Is Fully Functional :-) ... A Quick Cache file was just served for ( 2e96b290f6c5ccd2bc6830557c0aba6e coder.cl/category/programming/java/feed/ ) in 0.00055 seconds, on May 18th, 2012 at 12:07 pm UTC. -->
