Skip to main content

Posts

Showing posts from 2012

Akka: Printing list of actors

To print the list of actors that are running in the actor system, you can add following scheduler that will print actor path every 10 seconds: import akka.actor.{Actor, ActorIdentity, ActorLogging, ActorRef, Cancellable, Props} class TestActor extends Actor with ActorLogging { private var scheduler: Cancellable = _ @scala.throws[Exception](classOf[Exception]) override def preStart(): Unit = { import scala.concurrent.duration._ scheduler = context.system.scheduler.schedule( initialDelay = 0 seconds, interval = 10 seconds, receiver = self, message = ActorIdentity("", Some(self)) ) } @scala.throws[IOException](classOf[IOException]) override def postStop() = { scheduler.cancel } override def receive = { case ActorIdentity(_, Some(ref)) => log.info(ref.path.toString) } }

Scala simple concepts

A simple iteration over Array in Scala can be done as: val xs:Array[String] = Array[String]("a", "b", "c", "d", "e") for((x,i) <- xs.iterator.zipWithIndex) println(i + "th element is " + x) for((x,i) <- xs.view.zipWithIndex) println(i + "th element is " + x) for (i <- xs.indices) println(i + "th element is " + xs(i)) for (i <- 0 until xs.length) println(i + "th element is " + xs(i)) for (i <- xs.length - 1 to 0 by -1) println(i + "th element is " + xs(i))

Terminating a run or test in Scala Build Tool (SBT)

When running a program or test in SBT, if you want to exit from it (and not from SBT) try adding following lines in your build.sbt file: fork := true To directly add forking in an SBT session, type set fork := true This will not detach and open a new consule from the original sbt console. But, users can kill this separately. The way to do this in Max OS or Windows is to search a Java process with command line having sbt-launch in Activity Monitor / Windows Task Manager, and end it. In Unix, try grepping a process with sbt-launch in a new terminal, and kill it. Command to do that is: kill -9 `ps -h | grep java | grep -v sbt-launch | grep -v grep | awk '{print $1}'` By default, the run or test tasks run in the JVM as sbt. Forking can be used to run these tasks in a child process. By default, a forked process uses the same Java and Scala versions being used for the build and the working directory and JVM options of the current process. SBT documentation page discusse

Eclipse crashing and not starting

Problem: After restarting Eclipse, it crashes immediately and asks me to check C:\Users\username\Adobe Flash Builder 4.6\.metadata\.log In log it shows following error: !ENTRY org.eclipse.osgi 4 0 2013-02-13 11:53:46.760 !MESSAGE Application error !STACK 1 org.eclipse.swt.SWTError: Cannot initialize Drop     at org.eclipse.swt.dnd.DND.error(DND.java:266)     at org.eclipse.swt.dnd.DND.error(DND.java:227)     at org.eclipse.swt.dnd.DropTarget. (DropTarget.java:142)     at org.eclipse.ui.internal.EditorSashContainer.addDropSupport(EditorSashContainer.java:542)     at org.eclipse.ui.internal.EditorSashContainer.createControl(EditorSashContainer.java:534)     at org.eclipse.ui.internal.EditorAreaHelper. (EditorAreaHelper.java:41)     at org.eclipse.ui.internal.WorkbenchPage.init(WorkbenchPage.java:2507)     at org.eclipse.ui.internal.WorkbenchPage. (WorkbenchPage.java:653)     at org.eclipse.ui.internal.tweaklets.Workbench3xImplementation.createWorkbenchPage(Workbench3xImple

Preserving open nodes in AdvancedDataGrid with HierarchicalCollectionView

My dataProvider is an ArrayCollection, which is populated using XML. var initXML:XML = <items>    <item id="News" label="News" value_1="unchecked" value_2="unchecked" value_3="checked"/>    <item id="BBC" label="The Web" value_1="unchecked" value_2="unchecked" value_3="checked">        <item id="BBC1" label="BBC Homepage" value_1="unchecked" value_2="unchecked" value_3="checked">       <item id="YouTube" label="YouTube" value_1="unchecked" value_2="unchecked" value_3="checked"/>       <item id="GoogleMaps" label="Google Maps" value_1="unchecked" value_2="unchecked" value_3="checked"/>       <item id="MSN" label="MSN" value_1="unchecked" value_2="unchecked" valu

Flash trace log file in Windows 7

In my recent project, I need to look at the Trace output from the Flex application outside Flash Builder. I have Windows 7 as my operating System. Following are the steps to setup trace log file: Download and install Flash player debug version. Check at www.flashplayerversion.com for the version details. Create a new file named mm.cfg in your home directory. To figure out home directory open a command wondow and type echo %HOMEDRIVE%     TraceOutputFileEnable=1     ErrorReportingEnable=1     MaxWarnings=500     TraceOutPutFileName=C:\Users\(username)\AppData\Roaming\Macromedia\Flash Player\Logs\flashlog.txt Last line is optional if you are fine with the output file location. Open web browser and your Flash application.4. Use a tool like baretail to check the log file.

Deploying swc library in repository and adding maven artifacts for that

We can either deploy the swc file on a web server or a local Maven repository. To deploy xyz.swc on a webserver, the command is (in the folder containing xyz.swc): mvn deploy:deploy-file -Dfile=xyz.swc -Durl=file:///path/to/repository -DgroupId=com.abc -DartifactId=xyz -Dversion=1.01 -Dpackaging=swc This deploys the xyz.swc file to /path/to/repository (using the groupId, artifactId, version). Users then can refer to this Web URL (by defining a repository in their Maven project) and use xyz as a dependency in their Maven projects. To deploy the swc in a local Maven repository, we can execute (in the folder containing xyz.swc): mvn install:install-file -Dfile=xyz.swc -DgroupId=com.abc -DartifactId=xyz -Dversion=1.01 -Dpackaging=swc -DgeneratePom=true -DcreateChecksum=true Users then can add the dependency in the pom.xml file under <project> tag as:     <dependencies>         <dependency>             <groupId>com.abc</groupId>             <artifactId

Spark TextInput for Currency values

In my project, I wanted to have an spark TextInput to show currency values. While formatting it should show unformatted number. The way I did it is by creating a new CurrencyTextInput class extending spark TextInput. Code for the component is (CurrencyTextInput.as): package com.abcd.component {     import flash.events.Event;     import flash.events.FocusEvent;     import spark.components.TextInput;     import spark.formatters.CurrencyFormatter;     public class CurrencyTextInput extends TextInput     {         public function CurrencyTextInput()         {             super();             formatter = new CurrencyFormatter();             formatter.currencySymbol = "£";             formatter.fractionalDigits = 2;             formatter.useGrouping = true;             formatter.useCurrencySymbol = true;             formatter.negativeCurrencyFormat = 1;             formatter.trailingZeros = true;         }         public var formatter:CurrencyFormatter = null;         publ

Check if a string converted to a number is actually a number in ActionScript (Flex) and setting scale of a number

An easy way to check if a String is actually a number of not is to actually convert the string to a Number and test if it's NaN. Flex API reference mentions that the top-level function Number(str) returns NaN if the string passed to the method cannot be converted to a Number. The problem with this approach is that if you take Number(null) or Number(undefined) or Number(""), all will return 0 and will evaluate to "is a number". The correct way to do this is shown in following code snippet. It also sets scale of the converted number to two decimal digits. public static function getNumberFromString(val:*, scale:uint = 2):* {     if ((val === null || StringUtil.trim(val) === "" || isNaN(val)) == false)         return setScale(Number(val)).toFixed(scale);     else         return ""; } public static function setScale(number:Number, scale:uint = 2):Number {      scale = Math.pow(10, scale);      return (Math.round(number * scale) / scale); }

Use 64 bit data model JVM on Sun X Solaris

Goal: Either to determine the bit width in a Java program or use a 64 bit data model JVM. OS: SunX Solaris 64 bit OS. First of all install 32 bit JDK/JRE (steps 1 and 2 are valid for JDK 1.6) Then add 64 bit packages over it. This will convert the JDK to work in both 32 bit and 64 bit modes (but 32 bit is still default). To test it for 32 bit, run $ java -version To test it for 64 bit, run $ java -d64 -version In ant binary file (in bin folder of apache-ant) add line ANT_OPTS="$ANT_OPTS -d64" If you do not want to change ant binary file, then you can set the environment variable every time you run the ant command. For e.g. setenv ANT_OPTS -d64 Next you add instructions in build.xml file used by ant. In Java/JUnit tags, add property clonevm="true" if you have fork="true" property. This will clone the same VM environment for all forked processes, as for ant process itself. clonevm will not have any effect if fork is false. Run you ant target. Follo

MojoExecutionException: TargetPlayer and playerglobal dependency version doesn't match

If you get this error while compiling Flex modules using Maven, then you just need to exclude playerGlobal dependancy: <dependency> <groupId>com.adobe.flex.framework</groupId> <artifactId>flex-framework</artifactId> <version>${flex.version}</version> <type>pom</type> <exclusions> <exclusion> <groupId>com.adobe.flex.framework</groupId> <artifactId>playerglobal</artifactId> </exclusion> </exclusions> </dependency>

TeamCity fails running FlashUnit tests with "socket write error"

Error log: Failed to execute goal org.sonatype.flexmojos:flexmojos-maven-plugin:3.9:test-run (default-test-run) on project Project1: Software caused connection abort: socket write errorC:\TeamCity\buildAgent\work\Project1\src\main\test\target\test-classes\TestRunner.swf This error is caused due to Flash Player's 9+ security configurations. Solution: The TeamCity agent should be installed as a domain user and not as SYSTEM user. Uninstall TeamCity agent and try reinstalling agent as domain user. If this does not work, then reinstall server also as domain user.

Enable “Open Command Window Here” context menu option in Windows 7

By default you need to SHIFT + right-click a folder, in order to access "Open command window here" context menu option. You can enable it permanently by following steps: Click Start, Run and type Regedit.exe Navigate to the following locations and delete "Extended" key with REG_SZ value: HKEY_CLASSES_ROOT\Directory\shell\cmd HKEY_CLASSES_ROOT\Directory\Background\shell\cmd HKEY_CLASSES_ROOT\Drive\shell\cmd Tip: You might want to take a backup of these keys, in case you want to revert to old setting.

Download a file using FileReference in Flex

Following function gives an example of how to doanload a file in Flex. "file" object passed to the function is a simple object having following structure: file.fileName = "Abc.png" file.fileType = "image/png" file.url = "/documents/Abc.png" A pattern match-replacement is used to determine file extension, in case fileName does not have it. public function downloadFile(file:Object):void { if (file != null) { var fileName:String = (file.fileName != null && file.fileName.length > 0) ? file.fileName : (new Date()).time.toString(); var fileExtension:String = file.fileExtension; if (fileName.indexOf(".") < 0) { if (fileExtension.lastIndexOf(".") >= 0) fileExtension = fileExtension.slice(fileExtension.lastIndexOf("."), fileExtension.length); else if (fileExtension.lastIndexOf("/") >= 0) fileExten

Flex ByteArray to Java ByteArray

While trying to import XLS files from Flex front-end, we needed to pass the file contents to Java middle tier, where Apache POI library was used to parse the contents. The Java method expects a Java ByteArray containing the file contents, but when we pass a Flex ByteArray to it, it throws error. To overcome this instead of passing Flex ByteArray, we should pass an Array of bytes, as depicted in following code snippet: public static function byteArrayToArrayOfBytes(ba:ByteArray):Array {     var arrayOfBytes:Array = [];     ba.position = 0;     while(ba.bytesAvailable > 0)         arrayOfBytes.push(ba.readByte());     ba.position = 0;     return arrayOfBytes; } public function onFileSelectionComplete(fileReference:FileReference) {     var payload:Object = new Object();     payload.byteArray = byteArrayToArrayOfBytes(fileReference.data);     ExternalInterface.call("parseXLS", payload); }