Thing which seemed very Thingish inside you is quite different when it gets out into the open and has other people looking at it

Saturday, June 30, 2012

How Logging works with Log4j


In my last blog I explained the importance of logging in your enterprise application. In this post I am going to explain how we can used logging using Log4J logging framework.
 As always using a framework makes your life much easier and efficient. And main use of using a framework is it takes care of the underline platform. So when it comes to log4j which is an open source project created by Apache foundation and currently there are three logging frameworks
  1.  Log4j for java 
  2.   log4cxx for C++
  3.   log4net for the Microsoft .NET framework.

So lets look at how log4j works...

 Log4j takes care of logging using three main components.  1) Loggers, 2) Appenders, 3) Layouts
  In simple terms if you want to know what these three main components does is mainly logger logs to an appender in a particular layout (pattern/style). But lets look at these three components in details

Loggers 

If you look it in the simplest way Loggers are actually logical class of file names.  These names are known to  your java application. For example if you have a class call HelloWorld.
The  standard logger should be 

Logger logger = Logger.getLogger("HelloWorld.class");

Logger should be defined class level. So one of the main advantage of using a framework for logging is you can control what you log in a hierarchical manner. If you put system.printline instead of using a logging platform you cannot actually disable some printlines while others are enabled. So here  using a logger you can actually define your log lines in an hierarchical order.

Loggers have 5 different hierarchical categories. I’l list them down by their order
 



 
Fatal  -  “The FATAL level designates very severe error events that will presumably lead the application to abort.” Fatal is the highest log level used to indicate that application is in a severe stage and application will get terminated due to this condition.
                            log.fatal(“Program termination”);

Error – “The ERROR level designates error events that might still allow the application to continue running.” Errors are not soo serious as Fatal  and program can still run with this condition however, it implies that program is going through an unexpected behavior in the execution flow. For example when the application is suppose to read a file and if that file not found you can log the exception using log.error(e.getMessage) to tell the user that this file is not there in the system.

Warn – warnings are used to tell the user that there is a chance of having a harmful situation due to a certain condition.  “The WARN level designates potentially harmful situations.”

Info – “ The INFO level designates informational messages that highlight the progress of the application at coarse-grained level.” Info is the most commonly used logger method. It is used to highlight the process of the event flow in an application.

Debug -   “The DEBUG Level designates fine-grained informational events that are most useful to debug an application.” This is used for debugging purposes if you need to debug your application you can enable debug level logs and see the execution flow.

Trace – “The TRACE Level designates finer-grained informational events than the DEBUG”  Gives more detail information than debug level. The lowest logger level. This is enable mainly to see finer grained information regarding the application.

Appenders

Another important feature of a logging API is to send logs to different locations. Depending on the user requirements logs should be sent to the console, remote monitor, o file systems. This is achieved by the appenders. Appender is responsible for the log destination.  There are couple of pre-define appenders in log4j.



  1. ConsoleAppender - Sends log events to the System.out or System.err using a layout specified by the user. The default target is System.out
  2. FileAppender - Sends log events to a file. (DailyRollingFileAppender, RollingFileAppender)
  3. SoketAppender - Sends events to a remote log server, usually a SoketNode
  4. JMSAppender - Sends events to a JMS topic.
  5. NTEventLogAppender - Sends  events to the NT event log system.
  6. SyslogAppender - Sends events to a remote syslog daemon.

    And many more .. You can also define your own appender so that it will send log events to differant/multiple destnations. You can easily do it by extending AppenderSkeleton class. I will explain how that can be done in my next blogs.

    Layouts

    Layouts allow you to format your log messages before it is sent to the log destination. It actually stype your log message which can be very useful for filtering purposes and better monitoring approaches. By adding a pattern to your layout, you can exclude/include log event properties such as date time, log level, logger, message etc. You can also define your of layout by extending the log4j Layout class . Howeverm there are couple of predefine layouts in log4j such as PatternLayout, SimpleLayout, DateLayout, HTMLLayout, and XMLLayout.
    Defining the layout in log4j.
     
    log4j.appender.CARBON_LOGFILE.layout=org.wso2.carbon.utils.logging.TenantAwarePatternLayout
    log4j.appender.CARBON_LOGFILE.layout.ConversionPattern=TID: [%T] [%S] [%d] %P%5p {%c} - %x %m {%c}%n
    log4j.appender.CARBON_LOGFILE.layout.TenantPattern=%U%@%D [%T] [%S]

    Sample patternlayout using log4j

    TID: [-1234] [Application Server] [2012-06-30 20:26:17,156]  INFO {org.wso2.carbon.coordination.core.services.impl.ZKCoordinationService} -  Coordination service disabled. {org.wso2.carbon.coordination.core.services.impl.ZKCoordinationService}





    Tuesday, June 26, 2012

    Monitor your application with system logs !!!


    Tired of finding an issue with a current running application??? Your application started giving unexpected behavior and can’t figure out why? .. Cannot monitor your application properly? THEN LOGGING IS YOUR SOLUTION!!!!
     
    Why Logging ???

    Logging is a way of storing information about events happening during a program execution. Logging can be very useful when it comes to identify the event flow/ program execution or unexpected behavior of an execution such as errors/exceptions (error tracking) and it can be also useful when it comes to monitor performance.  Almost every developer use Logging!!! Even if they don’t use a special framework to do logging. For instance even if you are not using a particular logging frame work you most probably be using  system.printline in order to track  useful information and print them on the console so that you can monitor your application’s behavior and it’s current activities.

    Importance of using a Logging Framework ?

    However, using a logging frame work is a major plus point. Mostly because logs  are the very lifeline of your production application and it should not be taken lightly or as an afterthought. For example let’s say you don’t use logging at all and your application is out of development environment and your application is giving an unexpected behavior, it will be like finding a needle in a haystack to figure out what’s gone wrong in your application if you don’t use proper logging using a proper logging framework. 
      
    Of cause using a logging framework is a plus point when it comes to enterprise applications. Because by using a logging frame work you can easily define log levels and filter logs accordingly. Further, when it comes to distributed applications (such as web/remote application) logging is a very crucial task because system administrators always needs to keep eye of what happening and  always need to see the logs for a given period of time. So filtering logs and viewing logs is also very important. This is why Logging has become the most frequent implementation of the Monitoring attribute and also in most cases it is the only implementation of monitoring (Mainly because it is the most easiest thing in the world for a busy developer to just put lnfor.log() in the code. However, apart from the ease of use logging frameworks also allow you to send logs to many different parties such as file systems, consoles, and databases. Which makes it easy for a system admin to filter logs from timestamp, log levels, and log messages.

    Drawbacks of Logging

    Even though, logging is a very important thing when it comes to developing application there is such thing  as too much logging and it’s important to know how to log efficiently.  Before we look into that lets see the common draw backs of bad logging.
    Performance – There can be performance hit in your application if you don’t put the logs in the right way. One thing is if you have too many logs at unwanted places it can be a major performance hit and also it will reduce the speed of your application. And also pollute and increase the size of your code.

    Scalability issues – When you log unwanted information or not have proper log levels in your application you might end up having huge log files. And it will increase the size of your log files. And it can eat up your software and hard ware resources.

    Security – Logging can be security vulnerability because logs can carry security information such as passwords of user accounts and other sensitive information which may expose a system vulnerabilities.
    These are very important points because our ultimate goal is to have efficient application which can be monitored efficiently at all time.

     
    Best Practices of Logging
    Therefore I would like to list down some of the best practices when it comes for logging however, I would like to discuss them in details in my next blog post.


    1. Use an appropriate logging framework depending on your need - The proper selection of logging frame work will lead you to store and filter your information in an orderly fashion)
    2. Proper use of Log levels - There are different levels of log levels choosing the right level at the right time can increase the performance and the scalability of your application.
    3. Do Not Log unwanted information – Always make sure you know what you are logging and also make sure logging will not give side effects to your application. (Make sure you avoid null pointer exception while logging ;) ) And ALWAYS be concise and descriptive when you log 
    4.  Make sure you use your own pattern. Logging frameworks let you design your own pattern layout which helps you filter your logs in an efficient manner. Make sure you use features of logging frame work when its needed.








    Wednesday, June 13, 2012

    How to Upgrade WSO2 ESB?

    Following steps describes how to update(migrate) WSO2 products to newer versions

    Step 1 - Deploying existing artifacts

    Copy the deployed artifacts to WSO2 ESB old version to WSO2 ESB new version by copying wso2esb-4.0.0/repository/deployment/server folder to wso2esb-4.0.3/repository/deployment/server Also Copy all the content of repository/component/lib {wso2esb-4.0.0} to the new installation {wso2esb-4.0.3} (this will help you install the existing drivers and additional plug-ins used in your earlier installation)

    Step 2 - Apply Patches

    Most of the patches are applied when we release newer versions however, some patches can be not applied such as a custom patches or patches which were given after the release. Therefore you need to check the needed patches and apply them
    Step 3 - Allocate proper memory numbers (if applicable).
    If you have allocated memory numbers don't forget to allocate them to the new installation as well.

    Step 3 - Change the configuration files

    Apply the same changes you have done to configurations files inside OldVersion/repository/conf to NewVersion/repository/conf (if you have done any such to any configuration files)

    Note
    1. If you have done registry mounting make sure you apply to the new installation as done before by changing relevant configuration files such as carbon.xml,axis2.xml,user-mgt.xml,mgt-transports.xml
    2. If you have created external data sources (Carbon data sources) make sure you copy datasources.properties file from repository/conf to the newer version repository conf
    Step 4 - Apply security.

    Apply the security measures taken as before. such as Encrypting passwords {as done previously}, Changing key stores etc

    Friday, June 8, 2012

    How to configure proxy service for an exsisting web application Using WSO2 ESB


    norder to configure a proxy for an existing web application you need to set up binary relay, which allows users to send messages to differant parties at byte level while making decicions using transport headers. It further enables to passthrough SOAP messages without performing heavy XML parsing. Here are the steps to expose a webapplication through WSO2 ESB.

    1. Enable the message relay module.
    Go to ESB management console and go to Manage --> Modules --> List and click on engage icon associated with relay module to engage the module globally.

    2. Configure message formatters and message builders in axis2.xml
    Go to repository-->conf and edit the axis2 xml. Uncomment the nessary messageFormatters, messageBuilders as shown below.



    <messageFormatters>
     <!--JSON Message Formatters-->
      <messageFormatter contentType="application/json"
              class="org.apache.axis2.json.JSONMessageFormatter"/>
      <messageFormatter contentType="application/json/badgerfish"
    
              class="org.apache.axis2.json.JSONBadgerfishMessageFormatter"/>
    
       <messageFormatter contentType="text/javascript"
    
              class="org.apache.axis2.json.JSONMessageFormatter"/>
    
        <messageFormatter contentType="application/x-www-form-urlencoded"
    
               class="org.wso2.carbon.relay.ExpandingMessageFormatter"/>
    
         <messageFormatter contentType="multipart/form-data"
    
                class="org.wso2.carbon.relay.ExpandingMessageFormatter"/>
    
         <messageFormatter contentType="application/xml"
    
                 class="org.wso2.carbon.relay.ExpandingMessageFormatter"/>
    
         <messageFormatter contentType="text/html"
              class="org.wso2.carbon.relay.ExpandingMessageFormatter"/>
    
         <messageFormatter contentType="application/soap+xml"
    
               class="org.wso2.carbon.relay.ExpandingMessageFormatter"/>
    
         <messageFormatter contentType="text/xml"
    
                class="org.wso2.carbon.relay.ExpandingMessageFormatter"/>
    
          <messageFormatter contentType="x-application/hessian"
    
              class="org.apache.synapse.format.hessian.HessianMessageFormatter"/>
    
          <messageFormatter contentType=""
              class="org.apache.synapse.format.hessian.HessianMessageFormatter"/>
    
    </messageFormatters>




    <messageBuilders>
    
        <messageBuilder contentType="application/xml"
    
           class="org.apache.axis2.builder.ApplicationXMLBuilder"/>
    
        <messageBuilder contentType="application/x-www-form-urlencoded"
    
             class="org.apache.axis2.builder.XFormURLEncodedBuilder"/>
    
        <messageBuilder contentType="multipart/form-data"
    
              class="org.apache.axis2.builder.MultipartFormDataBuilder"/>
    
        <!--JSON Message Builders-->
    
         <messageBuilder contentType="application/json"
    
              class="org.apache.axis2.json.JSONOMBuilder"/>
    
         <messageBuilder contentType="application/json/badgerfish"
    
              class="org.apache.axis2.json.JSONBadgerfishOMBuilder"/>
    
         <messageBuilder contentType="text/javascript"
    
              class="org.apache.axis2.json.JSONOMBuilder"/>
    
    
         <messageBuilder contentType="application/xml"
    
              class="org.wso2.carbon.relay.BinaryRelayBuilder"/>
    
         <messageBuilder contentType="application/x-www-form-urlencoded"
    
               class="org.wso2.carbon.relay.BinaryRelayBuilder"/>
    
         <messageBuilder contentType="multipart/form-data"
    
               class="org.wso2.carbon.relay.BinaryRelayBuilder"/>
    
         <messageBuilder contentType="multipart/related"
    
               class="org.wso2.carbon.relay.BinaryRelayBuilder"/>
    
         <messageBuilder contentType="application/soap+xml"
    
               class="org.wso2.carbon.relay.BinaryRelayBuilder"/>
    
          <messageBuilder contentType="text/plain"
    
               class="org.wso2.carbon.relay.BinaryRelayBuilder"/>
    
          <messageBuilder contentType="text/xml"
    
                class="org.wso2.carbon.relay.BinaryRelayBuilder"/>
    
          <messageBuilder contentType="x-application/hessian"
    
                class="org.apache.synapse.format.hessian.HessianMessageBuilder"/>
    
          <messageBuilder contentType=""
    
                 class="org.apache.synapse.format.hessian.HessianMessageBuilder"/>
    
    </messageBuilders>





    Save axis2.xml and restart the server to affect the axis2.xml changes.


    3.Creating the proxy service.


    Go to ESB management console and  create a pass through proxy service by giving the target endpoint as your webapplication url.



    <proxy xmlns="http://ws.apache.org/ns/synapse" name="amt" 
    transports="http" statistics="disable" trace="enable" startOnLoad="true">
    
      <target>
    
         <outSequence>
    
            <send />
    
         </outSequence>
    
         <endpoint>
    
            <address uri="http://localhost/webapp/index.html" 
    format="get" />
    
         </endpoint>
    
      </target>
    
    </proxy> 



    You can now access your proxy service through esb port. ie http://localhost:8282/services/MyProxyService1 

    Monday, April 30, 2012

    Installing WSO2 Developer studio

    In this tutorial I am going to explain how to install WSO2 Development studio (earlier known as WSO2 Carbon Studio) in details.

    To give a brief overview of WSO2 development studio...



    Development studio is an eclipse plugin (a development tool) which provide an extensive tool kit to develop/deploy and test applications which can be deployed in WSO2 Carbon servers. It provides rich set of editors such as synapse editors to deploy proxy services and sequances, axis2 editors to create and deploy axis2 service, data services editor to create data services ect. To create carbon applications (also known as CAPPS), there is a new project type called carbon application project. This provide a packaging mechanism for carbon based deployment artifacts such as ESB proxy services, data services and many more.
    Dev studio has the capabilities to expose CApps to any type of carbon server as CAR files. Car is a deployment model for this capp which testing debuging, if you look at a car file each car file contains a name version and a role to make the car file unique and also to identify the type of the car file.

    With that small introduction, lets look how we can install development studio into your eclipse IDE.


    First you need to download WSO2 Developer Studio binary distribution.  Please note that if you download WSO2 Developer Studio With Dependencies version, you can go ahead with the Offline Installation.

    Start Eclipse and Go to Help -> Install New Software .



    Click on Add button to add and give an appropriate name and the location of your dev studio binary distribution. And click ok.



    If you want, you may uncheck/untick Contact all update sites during install to find required software to stop Eclipse from installing updates of existing eclispe features
     

    Note: Sometimes you may have to leave the check box ticked/checked in case the Eclipse distribution you are using is missing some of the WTP features required for the Developer Studio Features If you download WSO2 Developer Studio Without Dependencies version, you need to leave the checkbox ticked. If you download the WSO2 Developer Studio With Dependencies version, you can go ahead and un-tick "Contact all update sites during install to find required software" option. Select WSO2 Developer Studio Feature from the list or select all the features Then click on the button Next
    Then click on Next on the wizard page which allows you to review the the items to be installed.


    Click Next and then accept the license agreement and click Finish .



      Accept the security warning while installation.


    That is it ... Once you have installed the dev studio you need to restart the IDE to apply the changes. Then you will see an Overview of WSO2 Dev studio which has useful links and help pages. If you click on the dashboard you will get quick start links to samples and create new carbon applications.


    In my next blog post I will explain how to create a proxy service using WSO2 Development studio.

    Friday, March 16, 2012

    Validate Domain Ownership using StratosLive


    In order to prove that your company is the owner of the domain, you need to validate the ownership of your domain. In < a href="https://stratoslive.wso2.com/home/index.html">WSO2 StratosLive there are two ways to validate your domain.
    • Creating a text file in the domain web root
    • Setting up a CNAME entry in your DNS.
    From the above two methods creating a text file in the domain web root is the fastest way to validate your domain and you can do it within few seconds. If you proceed with the second option, it'll take up to 48 hours to reflect the added CNAME entry in your DNS. So in this knowledge-base, I'll explains how we can validate the domain ownership by adding a text file in the web root using WSO2 StratosLive.

    Domain validation in stratos is easy. First login to WSO2 StratosLive as tenant admin using your account and go to Configurations -> Account -> Domain validation.


    Under "Validate Domain Ownership", click on "Validate Now" and it will redirect to the domain validation page.
    Then  you will get two options to validate your domain. Use the first option. And create a text file in your domain root call wso2multitenancy.txt. And add the given text content inside that text file you just created.

    Click the "Validate" button, after you complete the above step. You will get a success message  for a successful validation. Click on continue to finish the validation process. After a sucessful validation, you will be redirected to Account management page with a message saying "Domain Validation Sucessful".

    Expose your entire database as data services in two steps !!!


    WSO2-Data Services Server provides the feature to expose your data as a service right away!!!. All you need to give is your database information and then generate data services to expose your database tables/schemas as per your need.

    if you are using wso2 products for the first time ...
    You need to download wso2 dataservices server.
    Start up the server -> go to DS_HOME/bin/wso2server.bat | wso2server.sh (DS_HOME is where your set up is located)
    Once the server is up and running open a web browser and navigate to https://localhost:9443/carbon.
    Login it the server using the default credentials (username=admin, password=admin).

    Also note that you need to provide the related jdbc driver for the database and put in repository/component/lib in order for this feature to work.

    Step 1 :- Create a data source

    In order to expose your database you need to create a data source using wso2 data services server.
    To create data source click on Configure -> datasources

    Click on add data source and give your data base information.


    Once you create your data source you can test your connection by giving a validation query (ie Select 1) to make sure your connection is successful.

    Step 2 Generating data services

    You can start by clicking on the generate link in the main menue. Once you click on generate you will be directed to a wizard which will ask for the datasource and the database name which will be needed to expose.

    Once you create you give your database name you will get the list of schemas/tables to select for your data service.

    Click on next to view the created data services


    Click on finish to view the deployed services.

    You can try your service by clicking on try this sample for database transactions :) You can also generate axis2 clients by clicking on the data service and going to the service dashboard.



    Once you create your data service there are features to enable security, throttling and caching by going to the service dashboard as shown below.
    Try your service - using the try it tool.

    Sunday, October 9, 2011

    Adding Chords to your melody using jMusic (Adding Accompaniments)


    In my last post I showed how we can easily create a song (twinkle twinkle little star), which is basically the tune of that song or in western music language we call it the melody, in this post I am going to talk about how we can accompany this melody by adding chords.
    Let’s see how we can accompany our melody ..

    This is in our today’s TODO list
    -          Adding Chords to our song
    -          Arranging the chords in choral fashion
    -          Adding  guitar chords (o any other instruments)

    Adding Chords to the song “Twinkle twinkle”


     
    Following diagram shows the chord arrangements for the song twinkle Twinkle however this is not static you can select appropriate chord of your choice depending on the mood and the sound you want. However let’s just use a very basic chord progression to our song.

    Since we already created our song in my last post I will use the same code to add chord progression.

    When we were creating the notes we needed a pitch array which is an integer array to store the notes(pitch classes), likewise we need Chord array to keep Chord structure.  

    A Chord represents 3  or 4 notes together playing at once.  So I am going to create array of three notes for each of our chord. 

    Here we need  3 Types of  Chords
    Chord Notes
    CMaj C E G
    FMaj F A C
    GMaj G B D

    Adding  Chords is bit complicated than just creating notes therefore, I will explain simple as possible. 

    Here we are going to have two parts. First one is our melody line(tune) which we created earlier. And the other part is the base part (the chords) to accompany our melody.

       Phrase phr = new Phrase("Twinkle twinkle", 0.0);
            Part treblePart = new Part("PIANO-Right", PIANO, 0);
            int[] pitchArray = {C4, C4, G4, G4, A4, A4, G4, F4, F4, E4, E4, D4, D4, C4, G4, G4, F4, F4, E4, E4, D4, G4, G4, F4, F4, E4, E4, D4};
            double[] rhythmArray = {C, C, C, C, C, C, M, C, C, C, C, C, C, M, C, C, C, C, C, C, M, C, C, C, C, C, C, M};
            phr.addNoteList(pitchArray, rhythmArray);
            treblePart.add(phr);

    And then we create the base part
    static Part bassPart = new Part("PIANO-Left", PIANO, 0);

    To create chords we need to define each type of chord we are using. First we’l creates our three types of chords.

            Note cMaj[] = {new Note(C3, M), new Note(E3, M), new Note(G3, M)};
            Note fMaj[] = {new Note(F3, M), new Note(A3, M), new Note(C3, M)};
            Note gMaj[] = {new Note(G3, M), new Note(B3, M), new Note(D3, M)};


    Earlier I created a Phrase  to store the pitch classes (notes) and their durations (time slots) here we need to create a  CPhrase chord = new CPhrase(); to store our chords. 
    And we add each chord to the basePart to complete the phase.

    So to make this code much efficient and elegant I am going to create a separate method which adds a given chord to our basePart.

    public static void addChordsPart(Note chrd[]) {
            CPhrase chord = new CPhrase();
            chord.addChord(chrd);
            bassPart.addCPhrase(chord);
        }

    Getting things all together
    1. Create two parts
    2. Add the melody to the first part by giving the pitch classes and durations
    3. Create the types of the chords
    4. Add each chord to the second part by giving the chord name and their duration per each chord
    5. Create the Score and add Part one and part two together
    6. Play/Save the midi

    package mymusicapp;
    
    import jm.JMC;
    import jm.music.data.CPhrase;
    import jm.music.data.Note;
    import jm.music.data.Part;
    import jm.music.data.Phrase;
    import jm.music.data.Score;
    import jm.util.Play;
    import jm.util.Write;
    
    
    public class Main implements JMC {
    
        static Part bassPart = new Part("PIANO-Left", PIANO, 0);
    
        public static void main(String[] args) {
            Phrase phr = new Phrase("Twinkle twinkle", 0.0);
            Part treblePart = new Part("PIANO-Right", PIANO, 0);
            int[] pitchArray = {C4, C4, G4, G4, A4, A4, G4, F4, F4, E4, E4, D4, D4, C4, G4, G4, F4, F4, E4, E4, D4, G4, G4, F4, F4, E4, E4, D4};
            double[] rhythmArray = {C, C, C, C, C, C, M, C, C, C, C, C, C, M, C, C, C, C, C, C, M, C, C, C, C, C, C, M};
            phr.addNoteList(pitchArray, rhythmArray);
            treblePart.add(phr);
    
            Note cMaj[] = {new Note(C3, M), new Note(E3, M), new Note(G3, M)};
            Note fMaj[] = {new Note(F3, M), new Note(A3, M), new Note(C3, M)};
            Note gMaj[] = {new Note(G3, M), new Note(B3, M), new Note(D3, M)};
    
            addChordsPart(cMaj);
            addChordsPart(cMaj);
            addChordsPart(fMaj);
            addChordsPart(cMaj);
            addChordsPart(fMaj);
            addChordsPart(cMaj);
            addChordsPart(gMaj);
            addChordsPart(cMaj);
            addChordsPart(cMaj);
            addChordsPart(fMaj);
            addChordsPart(cMaj);
            addChordsPart(gMaj);
            addChordsPart(cMaj);
            addChordsPart(fMaj);
            addChordsPart(cMaj);
            addChordsPart(gMaj);
    
            Score score = new Score("Twinkle-Twinkle");
            score.addPart(treblePart);
            score.addPart(bassPart);
    
            Play.midi(score);
            Write.midi(score);
    
        }
    
        public static void addChordsPart(Note chrd[]) {
            CPhrase chord = new CPhrase();
            chord.addChord(chrd);
            bassPart.addCPhrase(chord);
        }
    }


    Now we added chords to our songs. You can try out the songs by simply playing the song.

    Arranging  the chords.

    Just playing the chord progression for a song can be lil boarding. To make the song more interesting we can arrange the base chords into different variations. 

    Following diagram shows how we can arrange the chords using each note of the chord.

    So for that we need to change our method a little bit by giving the notes of each chord separately and  arranging them with proper durations.

     public static void addbaseNotesPart(Note chrd[]) {
            Phrase chord = new Phrase();
            int[] pitchArray = {chrd[0].getPitch(), chrd[2].getPitch(), chrd[1].getPitch(), chrd[2].getPitch()};
            double[] rhythmArray = {Q, Q, Q, Q};
            chord.addNoteList(pitchArray, rhythmArray);
            bassPart.addPhrase(chord);
        }

    We can use the same code, but instead of using addChordsPart, use addbaseNotesPart to get the styling of our chord progression.


    Adding  guitar chords (o any other instruments)

    This Chord Arrangements can be done using any instrument. All you need to do is change the  Part instrument to the instrument of your choice.
      static Part bassPart = new Part("PIANO-Left", GUITAR, 0);

    You can also experiment by changing the chords/durations and adding new parts. 







    Thursday, October 6, 2011

    Steve Jobs: tributes to the Apple co-founder and a very Inspirational man!!!

    "3 Apples changed the World. 1st one seduced Eve, 2nd fell on Newton and 3rd was offered to the World half bitten by Steve Jobs"


    Steve Jobs : You are a great inspiration to everyone ... your work is un-beleivable your creativity is endless and your imagination is real which makes our day today life much more exiting and easy... You sure change the world and touched many people's hearts. You are a true entrepreneur showed technology is something which should be easy and it sure need good taste!!!! You enjoy the process as much as the success!!!

    These are the two most favourite quotes which inspired my life ...

    “Your work is going to fill a large part of your life, and the only way to be truly satisfied is to do what you believe is great work. And the only way to do great work is to love what you do. If you haven’t found it yet, keep looking. Don’t settle. As with all matters of the heart, you’ll know when you find it. And, like any great relationship, it just gets better and better as the years roll on. So keep looking until you find it. Don’t settle.”-Steve Jobs

    "No one wants to die. Even people who want to go to heaven don't want to die to get there. And yet, death is the destination we all share. No one has ever escaped it, and that is how it should be, because death is very likely the single best invention of life. It's life's change agent. It clears out the old to make way for the new." - Steve Jobs '


    Steve Jobs : We are going to miss you alot and May you Attain Nibbana...


    Tuesday, September 27, 2011

    Kick Start on Music Programming – Create your first music program in java

    In this tutorial I am going to talk about basics of music programming and music technology. Music programming is an interesting but a very vast area of learning and applying however, jMusic project makes music programmer’s life much easier and makes music programming more effective. jMusic library is an API for Java music programming and provides tools to for music compositional and audio processing.

    Today I am going to talk about the fundamentals of music programming using jMusisc library and compose, and process and monitor simple music.

    Today's TODO list ...
    1. Create a Simple Song
    2. Add Instrumentals
    3. Save and notate
    Create Your First Song 

    Creating your first song is crucial :) If you know the music notation to a particular song you can create almost any song using this technique (make sure you select your favorite song for this task) . Since most people know twinkle twinkle little star and its quite catchy I am going to select that song.

    Before we start we need to make sure we have jMusic library, you need to download and import this library to your java class path.
    First look at the manuscript notation of our songs.

    For those who are not fluent with music notations and western music theory this is how it looks likes in abc format. (More like c,d,e,f,g format :) )


    Now let's create this song in java.
    package mymusicapp; 
    import jm.JMC; 
    import jm.music.data.Note;  
    import jm.music.data.Part; import jm.music.data.Phrase; import jm.music.data.Score; import jm.util.Play;
    import jm.util.Write;
    public class Main implements JMC {
    public static void main(String[] args) { 
    Phrase phr = new Phrase("Twinkle twinkle", 0.0); int[] pitchArray = {C4,C4,G4,G4,A4,A4,G4,F4,F4,E4,E4,D4,D4,C4,G4,G4,F4,F4,E4,E4,D4,G4,G4,F4,F4,E4,E4,D4};
    double[] rhythmArray = {C, C, C, C, C, C, M, C, C, C, C, C, C, M, C, C, C, C, C, C, M, C, C, C, C, C, C, M}; phr.addNoteList(pitchArray, rhythmArray);
    Play.midi(phr);}
    }
    }
    As you can see it is very easy to create music using jMusic library. All you need to do is add the notes and the pitch classes and put them together. If you look at it closely, Notes are given in “pitchArray” int array of pitch classes in C,D,E,F,G manner number 4 represents the fourth octave. And the duration of each pitch classes are given Crochet ( C ), Quaver (Q), Semi Quaver (SQ), Minim (M) ect.
    Following table list duration of each note.


    Musical Notation Name Duration jMusic Notation
    Semibreve

    Whole Note
    4 Crotchets
    4.0 SB
    Minim

    Half Note
    2 Crotchets
    2.0 M


    Crotchet

    Quarter Note
    1 Crotchets
    1.0 C
    Quaver

    Eight Note
    ½ a Crotchet
    0.5 Q
    Semi-Quaver

    16th note
    ¼ a Crotchet
    0.25 SQ


    Add Instrumentals

    Changing the instrument is easier than creating the song all you need to do is map your phrase to a part and play the part as shown below.

    phr = new Phrase("Twinkle twinkle", 0.0);
    Part p = new Part("FLUTE", FLUTE, 0);  
    phr.addNoteList(pitchArray, rhythmArray);
    p.add(phr);
    Play.midi(p);

    You can try and experiment with different musical instruments such as guitar violin ect. :)


    Save and notate

    You can save your creation as a midi file by simply adding the following code.
    Write.midi(phr,"twinkle.mid");


    Click here to listen to our creation

    To view the manuscript notation you can use View.notate method and you can view the manuscript notation of your music creation.

    View.notate(phr);