wikipedia

Support Wikipedia

Thursday, August 9, 2012

Overriding Ivy dependency

IvyDE (the eclipse plugin for Ivy) manages dependencies by automatically downloading them from the repository. It also attaches the sources(if they are available in the repository) to binaries under the hood without any custom settings. Helps to debug the source for any dependency.

That's great but what if you are working on multiple projects at the same time and want to test/debug the new code that you are writing in a dependency module.

One way to do that is to comment out the dependency(let's call it project X) entry in ivy.xml for X and then include the source for X by adding project X to the buildpath of the main project(let's call it project A).

Now if the dependency is used in multiple  projects(say B and C) and B and C are dependencies of project A,  then you have much more work to do.
Like
  • Comment out entries for projects B and C in project A's ivy.xml and then add project B and C to project A's build path.
  •  Comment out entries for X in project's B and C's ivy.xml
  • Add project X to the build path for projects B and C.

A quicker and much more cleaner alternative is to add the dependency (project X) to the main project's (A) buildpath and move the order of  X to the top of the classpath. In Eclipse IDE, this is available under "Order and Export" tab of "Java Build Path" menu under project properties. As shown in the picture below.


 You are done. Set a breakpoint within project X and see how it goes!


Thursday, May 31, 2012

Debugging dependency source with IvyDE

IvyDE an Eclipse plug-in for Ivy makes it a lot easier to work with Ivy. Some of the notable things that IvyDE does are automatic resolving of dependencies when ivy.xml is modified or the first time a project is loaded, ability to clear caches by providing a sub menu, Error checking/validation of ivy configurations and so on.
 Once you install IvyDE and enable a project to use IvyDE for managing dependencies, you lose the ability to attach a source to any of the jars in the classpath. That makes it difficult to debug the source for any dependency. The crude way I was doing it was to comment out the said dependency in ivy.xml. Saving the file should trigger a resolve on the project. That should remove the dependency from the build path. Then add the desired project to the classpath.

I found out later that it doesn't have to be that way though. IvyDE provides a neat way out. Even though there are no examples of how exactly to setup configure. After numerous trials and errors I got it working. Hope somebody else who is trying to Debug source with Ivy finds this post useful enough.

I created a tutorial at the following location. Utility is the project which publishes a binary Utility.jar and Utility-source.zip artifacts. TRY-IVY-DEBUG is the project which uses Utility.jar and has a simple class Test.java that can be used to debug into the source.
 
 <configurations>
      <conf name="default" description="binary" />
      <conf name="sources" description="source codes" />
     </configurations>
     <publications defaultconf="default">
      <artifact name="Utility" type="jar" conf="default" ext="jar" />
      <artifact name="Utility-sources" type="source" conf="sources" ext="zip" />
     </publications>
     <dependencies/>
There are two configurations defined, default and source. The description attribute is self explanatory. The artifacts are Utility.jar and Utility-sources. The key here is type=”source”. That's one of the two things IvyDE is looking for when trying to bind the sources to the jars. The other requirement is that the source artifact name suffix needs to match the ones in default IvyDE configuration as shown below.
If you load the two projects mentioned above in eclipse. Build the Utility project using the included build.xml and perform a resolve on the TRY-IVY-DEBUG project. That should make eclipse download and attach the Utility-sources.zip to the Utility.jar artifact.You should now be able to debug Test.java class and step into the attached source.

Sunday, March 18, 2012

Publishing to a branch using Ivy

Ivy off the shelf works fine if you are not dealing with branches. The examples in the samples that can be downloaded don't have much for using branches. That's because branches are optional for Ivy. All it cares about is the module name and revision number for getting the last build number or publishing an artifact to the repository.

If you can live without branches then things are fine with Ivy as a dependency manager. But life is not that simple! Once I started using branches everything went haywire. Because I had not made the configuration changes in all the right places. Having figured it out the hard way, would like to share the list of fixes.
The things to do when configuring ivy for branches are
  •  Include branch attribute in artifact and ivy pattern. Like shown below here
   ivy.artifact.pattern=[organisation]/[module]/[branch]/[revision]/[artifact].[ext]
   ivy.pattern=[organisation]/[module]/[branch]/[revision]/ivy.xml
  • Set default branch attribute in ivysettings file as shown below.
<ivysettings>
  <properties file="ivysettings.properties"/>
  <settings defaultCacheDir="${ivy.settings.dir}/ivy-cache" defaultBranch="trunk" defaultResolver="chain" latest="latest-compatible"/>  
   <resolvers>
      <chain name="chain">
          <url name="projects">
              <artifact pattern="http://buildserver/${repository.dir}/${ivy.artifact.pattern}" />
            <ivy pattern="http://buildserver/${repository.dir}/${ivy.pattern}" />
        </url>
        <ibiblio name="libraries" m2compatible="true" usepoms="false" /> 
        <ibiblio name="java-net-maven2" root="http://download.java.net/maven/2/" m2compatible="true" />
      </chain>
  </resolvers>
  
</ivysettings> 

  • Specify branch attribute in ivy.xml under the info section.
<ivy-module version="1.0">
    <info 
        organisation="org.coastal"
        module="mymodule"
        branch="RB-1.0.0"
        status="integration"
        revision="1.0"/>

    <publications/>
    <dependencies/>    
</ivy-module> 

  • Make sure the buildnumber ivy target has branch parameter too. Like shown below.
<target name="ivy-new-version" depends="" unless="ivy.new.revision">
 <!-- default module version prefix value -->
 <property name="module.version.prefix" value="${ivy.revision}." />
 
 <!-- gets next version number from ivy repository -->
 <ivy:info file="${ivy.file}" />

 <ivy:buildnumber 
  organisation="${ivy.organisation}" module="${ivy.module}" 
  branch="${ivy.branch}"
  revision="${module.version.prefix}" defaultBuildNumber="1" revSep=""/>
</target>

  • The publish ivy target has branch attribute as well.
<target name="publish-remote" depends="build" description="--> publish this project to ivy repository">
    <ivy:publish artifactspattern="${dist.dir}/[artifact].[ext]" 
           resolver="projects"
           pubrevision="${version}" 
           pubbranch="${ivy.branch}"
           update="true"
           status="${ivy.status}"
    />
<echo message="project ${ant.project.name} released with version ${version}" />
</target> 

Wednesday, December 21, 2011

Java 7 monitoring files/folders

Java 7 has this new watchservice which is a welcome development and you can read about it in many blogs as well as the oracle site. I tried playing with it using the code sample from some of the blogs. But unfortunately it seemed to work only the very first time and not after that.
Here is the code

public FileWatcher(String directoryPath) throws IOException {
        this.directoryPath  = directoryPath;
        FileSystem fileSystem = FileSystems.getDefault();
        watcher = fileSystem.newWatchService();
        
        Path myDir = fileSystem.getPath(this.directoryPath);
        myDir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, 
                  StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
        monitorFolder();
} 
 
private void monitorFolder() {
  executor = Executors.newSingleThreadScheduledExecutor();
  executor.submit(this);
} 
 
public void run() {
  WatchKey watckKey = null;
  try {
   while(!shutdown ) {
    watckKey = watcher.take();
    events = watckKey.pollEvents();
    listener.processEvent(events);       
   }
  } catch (InterruptedException e) {
   logger.error("Error monitoring directory", e);
  }
} 

Some more beating around the bush and googling I discovered that the WatchKey needs to be reset for subsequent events to flow through to the listener.
Wonder why this strange behaviour. Anyhow here is the fix and after that everything was fine and dandy!

public void run() {
  WatchKey watchKey = null;
  try {
   while(!shutdown ) {
    watchKey = watcher.take();
    events = watchKey.pollEvents();
    listener.processEvent(events);
          
    watchKey.reset();   }
  } catch (InterruptedException e) {
   logger.error("Error monitoring directory", e);
  }
} 
 

Found out later by paying more attention(!!) to the article on the oracle site that resetting the watchkey is key
to getting future events.

Friday, September 23, 2011

Interleaving audio files to different channels

Audio files have inherent characteristics like number of channels, sample size, frame size, sample rate, file type, number of samples, etc. to quote a few.


Here is a nice description of  samples and channels from the java sound faq.

Each second of sound has so many (on a CD, 44,100) digital samples of sound pressure per second. The number of samples per second is called sample rate or sample frequency. In PCM (pulse code modulation) coding, each sample is usually a linear representation of amplitude as a signed integer (sometimes unsigned for 8 bit).  
There is one such sample for each channel, one channel for mono, two channels for stereo, four channels for quad, more for surround sound. One sample frame consists of one sample for each of the channels in turn, by convention running from left to right.
Each sample can be one byte (8 bits), two bytes (16 bits), three bytes (24 bits), or maybe even 20 bits or a floating-point number. Sometimes, for more than 16 bits per sample, the sample is padded to 32 bits (4 bytes) The order of the bytes in a sample is different on different platforms. In a Windows WAV soundfile, the less significant bytes come first from left to right ("little endian" byte order). In an AIFF soundfile, it is the other way round, as is standard in Java ("big endian" byte order).

Some more audio file fundamentals from the javadocs...

frameSize is the number of bytes in each frame of a sound that has this format.

sampleRate is the number of samples played or recorded per second, for sounds that have this format.

More definitions can be found here.
Audio files are made up of samples and samples are made up of bytes.
Audio files come in two types, mono and stereo. Mono files have only one channel (perhaps was recorded with one receiver). Stereo audio files can have from two to as many channels.

Mono audio files when played, samples from the single channel are automatically duplicated and sent to all the channels. For example if speakers are attached to a computer, that would be two channels.In the case of a stereo audio file, it is pre-recorded for multiple channels.

Now what if you want to interleave two different audio files into one audio file such a way that each audio file is played on separate channels. There are many possible use cases for doing that. One could be to get the remix effect. For example you can take a song and mix it with some background music or add some percussion effect. Of course there are many sophisticated audio software out there which can do this and much more. But the goal here is to demonstrate a simple java program to achieve interleaving of audio files.

Here I am going to take two mono audio files of the same format (wave file), encoding (PCM) and sample rate. Interleave them to produce another wave file with different audio playing on each channel.

I am using Java Sound API for this exercise. Java supports only AU, AIFF and WAV formats. Extensions/plug-ins for MP3 and other audio formats are available through 3rd party vendors.
The audio files used in this example are leftChannelAudio.wav and rightChannelAudio.wav

The format details for the audio files are

rightChannelAudio.wav

nbChannel = 1
frameRate = 44100.0
frameSize = 2
sampleSize(bits)= 16
nbSamples = 1105408
encoding = PCM_SIGNED
sample rate = 44100.0

leftChannelAudio.wav

nbChannel = 1
frameRate = 44100.0
frameSize = 2
sampleSize(bits) = 16
nbSamples = 1069056
encoding = PCM_SIGNED
sample rate = 44100.0

Here is the main method of the class.
public static void main(String[] args) {
        try {
            String soundFileLeft = "leftChannelAudio.wav";
            File fileLeft = new File(soundFileLeft);   // This is the file we'll be playing on the left channel.
            String soundFileRight = "rightChannelAudio.wav";
            File fileRight = new File(soundFileRight);
            
            float sampleRate = 44100.0f;
            int sampleSizeInBits = 16;
            int channels = 2;
            boolean signed = true;
            boolean bigEndian = false;
            AudioFormat targetFormat = new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian);
            AudioMixer mixAudio = new AudioMixer(fileLeft, fileRight, targetFormat);
            
            File outFile = new File("outSingleSingleMixer.wav");
            mixAudio.mixnWrite(AudioFileFormat.Type.WAVE, outFile);
        } catch(Exception e) {
            e.printStackTrace();
        }
    } 





The interleaving of audio bytes is done in mixIntoStereoAudio method as shown below.
 private AudioInputStream mixIntoStereoAudio(AudioInputStream leftAudioInputStream,
                                                AudioInputStream rightAudioInputStream) throws IOException{
        ArrayList byteArrays = new ArrayList();
        int nbChannels = 1;
        byte[] compiledStream = null;
        int leftAudioBytes = -1;
        int rightAudioBytes = -1;
        
        byteArrays.add(convertStream(leftAudioInputStream));
        byteArrays.add(convertStream(rightAudioInputStream));
        
        long maxSamples;
        if (leftAudioInputStream.getFrameLength() > rightAudioInputStream.getFrameLength()) {
            maxSamples = leftAudioInputStream.getFrameLength();
            nbChannels = leftAudioInputStream.getFormat().getChannels();
        } else {
            maxSamples = rightAudioInputStream.getFrameLength();
            nbChannels = rightAudioInputStream.getFormat().getChannels();
        }
        long maxOutputSizeinBytes = maxSamples * sampleSizeinBytes;
        if (nbChannels == 1)
            maxOutputSizeinBytes = maxOutputSizeinBytes * 2;
        
        compiledStream = new byte[(int) maxOutputSizeinBytes]; //max size of number of bytes
            
        log.info("Output bytes size: " + compiledStream.length);
        for(int i = 0; i < compiledStream.length; i += sampleSizeinBytes){
            leftAudioBytes = writeSamplestoChannel(byteArrays, 0,
                    sampleSizeinBytes, compiledStream, leftAudioBytes, i);
            
            i += sampleSizeinBytes;
            
            rightAudioBytes = writeSamplestoChannel(byteArrays, 1, 
                    sampleSizeinBytes, compiledStream, rightAudioBytes, i);
        }

        AudioInputStream newaudioStream = generateNewAudioStream(compiledStream);
        return newaudioStream;
    }



In this case the sample has two bytes.  In a stereo audio file samples are written out in the following fashion. First sample for left channel and second for right and so on.
This example uses a simple technique of filling a sample from each audio file for each channel respectively.Filling in silence value whenever we run out of samples from an audio file. This is because the two audio files being interleaved might not have the same number of samples.

This technique can be extended easily to handle stereo audio files or list of audio files for each channel.
Go ahead and run this program with the sample audio files provided or you can just listen to how the interleaved output file plays out.

The complete program and sample audio files are available here.

Some good resources on using Java Sound API are listed below.

http://www.jsresources.org/faq_audio.html
http://www.builogic.com/java/javasound-read-write.html

Friday, July 8, 2011

Routing Serial data to a socket

You don't need  a hardware device (like Lantronix adapter) to route data from a Serial port to a socket. Thanks to socat, you can relay data from a serial port to another or serial port to a socket or socket to socket and plenty more such combos, all in one line! socat is exhaustive in what it can take as arguments. Check it out.

Here is an example of making available data from serial port /dev/ttyS0 on a linux environment (usually this is COM1 on windows boxes) through a socket (port = 8023).

socat TCP-LISTEN:8023,fork /dev/ttyS0,raw,b9600,echo=0

The baud rate specified here is 9600. fork option lets you make multiple connections to the source of data, which in this case is the serial port.

You can verify the data  from the socket by using a telnet or similar application.


telnet localhost 8023


Thursday, June 2, 2011

Monitoring data from a Serial port

Serialports have gone out of vogue! You no longer get serial ports on a computer except on Desktop PCs, unless you custom order it. Notebooks/Laptops, no such luck. But there there are many people and companies which deal with serial ports on a daily basis.

In the windows world we had the good old Hyperterminal program which was shipped with all windows distributions until recently.  Now Hyperterminal is a payware utility and can be purchased separately. No free utility available out there for windows!  But then in the linux world, things are friendlier. There is minicomm and many more free utilities that come with the operating system.

Well the point of this blog post is not to berate windows or anything. Just wanted to share a way you could look at the data coming in from a serial port without downloading/purchasing any  software. This is very handy for troubleshooting, say if you are looking for any control characters or any noise in the serial line, etc.All this while an app is running using the serialport. This can be done outside the app space to monitor activity on a serial port.
To see the data from a serial port on command line as well as save it to a file here is what you can do.

The script command writes data from a terminal to the specified output file.

script -af serialOut.txt

hexdump reads from a serial port and prints out the bytes in hex and ASCII

hexdump -vC /dev/ttyS0

Here is what the whole thing looks like after executing the commands above...

The top window shows the output from the terminal and the bottom one shows the contents of the output file in real time.

You can do this and much more on a windows platform too! By installing cygwin and running linux commands within the cygwin environment.