Sunday, February 8, 2015

What is Semaphore with example ?

What is Semaphore?

Semaphore is used to control access to common resource for completing multiple resources. It guards a critical section against entry by more than N threads at a time. The java.util.concurrent.Semaphore  class was first introduced by Java in V 1.5.

It has two main methods():
·         acquire()
·         release()

Semaphore is initialized with a given number of "permits” i.e. counter which keeps track of the number of resources available. When a request comes to resources, Semaphore checks the counter and if it is less than total count then it grant access to resources and subsequently reduces the counter. Similarly while releasing a resources, it increments the count.

Thus, at most N threads can access the acquire method without any release() calls where N is number of permits the semaphore was initialized with.

If the permits is in ON|OFF mode i.e. just one count then it is called binary semaphore.

Example:

Suppose there are 5 threads who wants to access particular resources which is guard by Semaphore having permits is 2, i.e. three threads has to wait for a semaphore to be released.

package in.waheed.semaphore.example;
import java.util.concurrent.Semaphore;

/**          
 * @author abdul waheed
 *
 */
public class SemaphoreExample {

            /**
             *
             * @param args
             */
            public static void main(String args[]) {

                        // Semaphore having counter as 2
                        Semaphore semaphore = new Semaphore(2);

                        // Creating 5 threads
                        SemaphoreTest test1 = new SemaphoreTest(semaphore);
                        SemaphoreTest test2 = new SemaphoreTest(semaphore);
                        SemaphoreTest test3 = new SemaphoreTest(semaphore);
                        SemaphoreTest test4 = new SemaphoreTest(semaphore);
                        SemaphoreTest test5 = new SemaphoreTest(semaphore);

                        // Starting all the threds
                        test1.start();
                        test2.start();
                        test3.start();
                        test4.start();
                        test5.start();
            }
}

class SemaphoreTest extends Thread {
            Semaphore semaphore;
            SemaphoreTest(Semaphore semaphore) {
                        this.semaphore = semaphore;
            }

            public void run() {
                        try {
                                    semaphore.acquire();
                                    System.out.println("Acquired : " + this.getName());
                        /*         System.out.println("Available permits : "
                                                            + semaphore.availablePermits());*/
                                    try {
                                                sleep(5000);
                                    } catch (Exception e) {
                                    }
                        } catch (InterruptedException ie) {
                        } finally {
                                    semaphore.release();
                                    System.out.println("Released : " + this.getName());
                        }
            }
}

Output:

Acquired: Thread-1
Acquired: Thread-0
Released: Thread-1
Acquired: Thread-4
Acquired: Thread-2
Released: Thread-0
Acquired: Thread-3
Released: Thread-4
Released: Thread-2
Released: Thread-3

Tuesday, December 9, 2014

How to extract a JSON value from a BASH script



Requirement : I was working on shell script where I need to get Id value from JSON and I tried so many thing but unable to get it without using any other tools. So, After trying so many failure attempt, I end up with this site (A big thanks to you) which resolved my issue.


Here is how I fetched value from JSON,


JSON = <YOUR_JSON>
PROPERTY_TO_FETCH="<VALUE>" (In my case, it was "id")

ID = `echo $JSON| sed 's/\\\\\//\//g' | sed 's/[{}]//g' | awk -v k="text" '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]}' | sed 's/\"\:\"/\|/g' | sed 's/[\,]/ /g' | sed 's/\"//g' | grep -w $PROPERTY_TO_FETCH`

echo ${ID ##*|}


Which will print the value of 'id' from JSON.

Tuesday, November 11, 2014

How to execute maven goal on parent module but not on childer

I am working on multi module maven project and If I define any plugin in the parent pom.xml file, It get executed for all the child build as well.

In simple language, I wanted to use one plugin in parent pom.xml file which read properties file from the base directory but whenever I executes it, all the sub pom.xml tries to read the properties file from their base directory and its ends up in maven failed.

To resolve the above issue, We just need to add "inherit' attributes in the plugin.

Example :

<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0-alpha-2</version>
<inherited>false</inherited>
<executions>
<execution>
<phase>initialize</phase>
<goals>
<goal>read-project-properties</goal>
</goals>
<configuration>
<files>
<file>${basedir}/rpm.properties</file>
</files>
</configuration>
</execution>
</executions>
</plugin>

Now the plugin will get executed from the parent pom.xml file.

Thank you :)

Thursday, October 30, 2014

How to Map a list of strings with JPA/Hibernate annotations ?

Yesterday while working on my project, I got one requirement where I need to store list of Array into the database, I checked on Google, went through various site but didn't get much information. Everyone talks about creating new entity and do onetomany relationship BUT I wanted to create a collection of basic types.

Finally I come across @ElementCollection annotation provided by JPA 2.0 which resolves my problem.

Problem :
Input JSON which we need to store in DB:

{
"schemas": ["urn:scim:schemas:core:1.0", "urn:scim:schemas:extension:enterprise:1.0"]
}
           Where schemas is Array of String.
Solution :


Just add following annotation in your POJO i,e
@ElementCollection
@CollectionTable(name = "SCIM_SCHEMAS", joinColumns = @JoinColumn(name = "SCHEMA_ID"))
@Column(name = "SCIM_SCHEMA")
private List<String> schemas;

It will create the table named "SCIM_SCHEMAS" having columns 'SCHEMA_ID' and 'SCIM_SCHEMA'


For details check section 2.2.5.3.3. Collection of basic types or embeddable objects or feel free to comment :)



Thursday, October 16, 2014

How to create Java Classes using xjc from XML file

This tutorial will demonstrate how can you generate Java Objects from XML documents using xjc tool. The tool “xjc” is used to generate the annotated Java classes from the XSD schema

Suppose I am using below XML file to generate Java Objects i,e
<?xml version="1.0" encoding="UTF-8"?>
<adaptorapp id="application">
<instance id="instance1">
<connectiondetails>
<accesskey>abcde</accesskey>
<secretkey>fghij</secretkey>
</connectiondetails>
</instance>
<instance id="instance2">
<connectiondetails>
<accesskey>klmnop</accesskey>
<secretkey>qrstuvwxyz</secretkey>
</connectiondetails>
</instance>
</adaptorapp>
Now  to generate Java Objects we need to create one xsd file(say "connection.xsd") :
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="adaptorapp" type="AdaptopApp" />
<xs:complexType name="AdaptopApp">
<xs:sequence>
<xs:element name="instance" type="Instance" maxOccurs="unbounded" />
</xs:sequence>
<xs:attribute name="id" type="xs:string" use="required" />
</xs:complexType>
<xs:complexType name="Instance">
<xs:sequence>
<xs:element name="connectiondetail" type="ConnectionDetail" />
</xs:sequence>
<xs:attribute name="id" type="xs:string" use="required" />
</xs:complexType>
<xs:complexType name="ConnectionDetail">
<xs:sequence>
<xs:element name="accesskey" type="xs:string" />
<xs:element name="secretkey" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:schema>
I have written XSD Schema based on my XML file, You can write something similar according to your requirement.

Lets use the 'xjc" tool to generate corresponding Java classes
                xjc.exe connection.xsd
By default, It will generates the Java classes in a directory named "generated".


Please let me know your feedback/queries as comments.

Thursday, October 9, 2014

Hibernate Error - Caused by: org.hibernate.DuplicateMappingException: duplicate import:

In hibernate, You cannot have two classes with the same name in the same or different packages else you will get an error at runtime like


"Caused by: org.hibernate.DuplicateMappingException: duplicate import: ....(try using auto-import="false")"


I have resolved this issue by adding property name on the Entity annotation.
Let us suppose I have Meta class in two different packages "com.database.user" and "com.database.group', you can resolve it as :
package com.database.user
@Entity(name= "com.database.user")
@Table(name="USER_META")
public class Meta

package com.database.group
@Entity(name= "com.database.group")
@Table(name="GROUP_META")
public class Meta

There must be some other ways too to resolve this issue, So please feel free to share it :)





Wednesday, August 13, 2014

How to upgrade ANT in Eclipse ?

To upgrade the ANT into the Eclipse, First you need to download the latest version of ANT anywhere on you machine.
Once you are done with the download then go to
EclipseWindowsPreferencesAntRuntimeAnt Home and Select the downloaded folder.

Now your Eclipse will use the latest version of ANT :)

How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...