Programming

Android: ItemClickListner with CheckBox or RadioButton.

Android: ItemClickListner with CheckBox or RadioButton.

Lets take a scenario to understand the need of a listview which will have checkbox embedded in it.

Consider the flipkart mobile app, in that we want to compare 2 or more products, in order to do that I will go on selecting the items which I want to compare and then click on the compare button.

 

So we have multiple items in that and hence we cant use the android built in types for creating the list view. Hence we need to follow the below mentioned approach.

 

  1. Create an activity, which contains 2 listviews, one listview for displaying all available mobiles and another listview for displaying selected mobiles.
  2. Create an adapter for filling the mobile list for the above mentioned listviews.
  3. The layout which will be used for creating row which will make ItemClickListner work is as follows,

 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:descendantFocusability="blocksDescendants"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:clickable="false">

    <CheckBox
        android:id="@+id/selectMob"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:clickable="false"
        />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="2"
        android:layout_toRightOf="@id/selectMob"
        android:layout_alignTop="@id/selectMob">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Nokia"
        android:id="@+id/make"
        android:layout_gravity="center_horizontal"
        android:layout_weight="1"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Lumia"
            android:id="@+id/model"
            android:layout_weight="1"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="3"
        android:layout_below="@id/selectMob">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Android"
            android:id="@+id/os"
            android:layout_gravity="center_horizontal"
            android:layout_weight="2"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="20000"
            android:id="@+id/price"
            android:layout_weight="1"/>
        </LinearLayout>

</RelativeLayout>

Observe the following attributes for Checkbox,

        android:focusable="false"
        android:focusableInTouchMode="false"
        android:clickable="false"

These make the checkbox non clickable and eventually the event will be transferred to its parent i.e the row and hence the ItemClickListner will be invoked.

You can download the files here

Circle drawing and filling arc in android

Circle drawing and filling arc in android

It is always a fun to play with mathematics, everything in this world is happening because mathematics. Mathematics is everywhere, every moment. Computers, physics, chemistry, biology every area is just standing upon Math.

Being an enthusiastic developer I always love to play with mathematics, so here is an example which draws a circle and a filling arc within the circle. Definitely you will get a the code in many web sites if you just google. But i would like to explain the math that plays an important role to achieve this.

The result should look as follow.

CircleFillingAndroid

CircleFillingAndroid

Let me divide the code in three sections.

Section 1 : Drawing a circle

How to draw a circle in android using Canvas and Paint ?

Code :

   

        int screenWidth = 420;  //Give your device screen width here 
        int horizontalCentreX = screenWidth/2;
        int circleCentrex = horizontalCentreX;
        int circleCentreY = 150;
        int radius = 130;
        int arcStartingAngle = 270;
        int minutes = 15;
        int seconds = 60;
        int minsToSecondsConverionFactor= minutes * seconds; //just to fill the circle for 15 mins
        int arcRectStartingX = circleCentrex - radius;
        int arcRectStartingY = 20;
        int arcRectEndingX = circleCentrex + radius;
        int arcRectEndingY = 280;

       //Just create a bit map of size (width = screen width, height = depends on how big circle you want
         Bitmap b = Bitmap.createBitmap(screenWidth, 300, Bitmap.Config.ARGB_8888);

        Paint paint = new Paint();
        Canvas canvas = new Canvas(b);
        paint.setColor(Color.rgb(62, 176, 220));
        paint.setStrokeWidth(10);
        paint.setStyle(Paint.Style.FILL);
        paint.setAntiAlias(true);
  
        canvas.drawCircle(circleCentrex, circleCentreY, radius, paint);

Section 2 : Drawing an Arc

So How to draw a filling arc in android using Canvas and Paint ?

Code :

   paint.setColor(Color.rgb(250, 64, 129));
        paint.setStrokeWidth(10);
        paint.setStyle(Paint.Style.FILL);
        final RectF oval = new RectF();
        paint.setStyle(Paint.Style.STROKE);
        oval.set(arcRectStartingX, arcRectStartingY, arcRectEndingX, arcRectEndingY);
        canvas.drawArc(oval, arcStartingAngle, ((i * 360) / minsToSecondsConverionFactor), false, paint);

Section 3 : Drawing a Point at the end of the filling arc

Here is the trick, to calculate the end point in the filling arc, we need to apply Trigonometry. Let me explain this in steps.

Observe the figure given below,

circle

circle

The figure shows Circle drawn at the centre point(CenterX,CenterY) . We have have an arc which will be continuously drawn and the arc fills the circle in the direction as shown in the figure. So our job is to find out the point(x,y) and the end of the arc.

If you observe a triangle drawn with Centre of the circle and point over the arc, it will be a right angled triangle.

So by applying trigonometry

  cos(θ) = adjacent / hypotenuse
         = adjacent / radius ( because radius == hypotenuse)
         
  adjacent = cos(θ) * radius
       x   = cos(θ) * radius ( this is because point (x,y) is nothing but point is X distance (along X-Axis) aways from Centre and Y distance away (along Y-Axis).

 sin(θ) = opposite / hypotenuse
        = opposite / radius
      y = sin(θ) * radius ( this is because point (x,y) is nothing but point is X distance (along X-Axis) aways from Centre and Y distance away (along Y-Axis).

But the values we got x and y are from the centre but the centre is centreX distance aways from the left side of the screen and centreY distance away from the top side of the screen.

Hence point x on the arc must be = centreX + x distance aways from Left side of the screen
                                 = centreX + cos(θ) * radius

Hence point y on the arc must be = centreY + y distance aways from Left side of the screen
                                 = centreY + sin(θ) * radius


If you debug and observe the y value we get will increase initially and start decreasing, this depends upon the angle, angle less than or equal to 90deg will be give +ve value for cos(θ) and angle greater than 90deg will give -ve value.

Hence the above calculation always gives you end point of the filling arc along the circumference of the circle.

 

 

Arduino Android Interfacing – Example Code and Troubleshooting

Arduino Android Interfacing – Example Code and Troubleshooting

 

Mobile phones playing key role in our day to day life, when Google presented Android to the world and aimed to make every phones smart the mobile industry started growing and today even a low end mobile is a smart phone. In this smartphones era hardware interfacing and automation using smart phones is emerging.

The future is in Artificial intelligence, your smart phones are really becoming smart day by day. In this article we will see how to interface Arduino with Android Smart phone. We will divide this article into three sections

Arduino circuit diagram, Arduino code and Android code. 

How Arduino-Android interfacing using HC 05  Works ?

   After doing proper connections and both Android and HC 05 bluetooth module are paired. The android code will infinitely keep listening to incoming data from HC05 bluetooth module. When a button is pressed in which is connected to Arduino a data will be sent from HC05 to android. android code will read the incoming data.

Devices and Softwares needed :

  • HC – 05 Bluetooth module 
  • Arduino Uno R3
  • Breadboard and Jumper wires
  • Arduino IDE

Block diagram for Arduino-Android interfacing

block diagram Arduino-Android

block diagram Arduino-Android

Arduino Circuit Diagram –

Connection details : 

HC – 05 GND          ————>  Arduino GND Pin

HC – 05 VCC (5V)   ————> Arduino 5V

HC – 05 TX               ————>  Arduino Pin 10 ( soft RX )

HC – 05 RX               ————>  Arduino Pin 11 ( soft TX )

HC – 05 Key (Pin 34 ) ————>  Arduino Pin 9

Arduino Circuit diagram

Arduino Circuit diagram

Arduino-Android-Interfacing

Arduino-Android-Interfacing

 

Arduino Code :

#include 
SoftwareSerial mySerial(10,11); 
int button=9; 
int buttonState=0; 

void setup() {
    mySerial.begin(38400);  
    pinMode(button,INPUT_PULLUP); 
} 

void loop() {    
  buttonState=digitalRead(button); //Reads data when button is pressed      

 if(mySerial.available()) 
    Serial.write(mySerial.read());      
 if (buttonState==LOW) {          
     mySerial.write("1"); //Send data 1 to Android.          
     delay(500);
  } 
}

Android Code :

Declare necessary variables
/*Adapter helps to get a handler for device object which can be used to communicate with Bluetooth module*/
private BluetoothAdapter btAdapter = null;
/* Socket is used to connect and to get output/input streams to write/Read data To/From Bluetooth module */
 private BluetoothSocket btSocket = null;

/* Output stream used to send data to Bluetooth module
 private OutputStream outStream = null;

/* input stream used to read data from Bluetooth module */
 private InputStream inStream;

// UUID is used as a key to connect to the device
 private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

// Insert your server's MAC address
 private static String address = "00:00:00:00:00:00";
protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
      btAdapter = BluetoothAdapter.getDefaultAdapter();
      checkBTState();
       runnable = new Runnable() {
          @Override
           public void run() { 
             //Create a thread which infinitely listen to the incoming data
               listen();
            }
        };
       thread = new Thread(runnable);
  }
@Override
 public void onResume() {
   super.onResume();
  // Set up a pointer to the remote node using it's address.
   BluetoothDevice device = btAdapter.getRemoteDevice(address);
 // Two things are needed to make a connection:
 //   A MAC address, which we got above.
 //   A Service ID or UUID.  In this case we are using the
 //     UUID for SPP.
   try {
      btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
    } catch (IOException e) {
        errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
    }
  // Discovery is resource intensive.  Make sure it isn't going on
  // when you attempt to connect and pass your message.
   btAdapter.cancelDiscovery();
  // Establish the connection.  This will block until it connects.
  try {
       btSocket.connect();
    } catch (IOException e) {
   try {
        btSocket.close();
     } catch (IOException e2) {
      
    }
 }
// Create a data stream so we can talk to server.
 try {
     outStream = btSocket.getOutputStream();
     inStream = btSocket.getInputStream();
      thread.start();
 } catch (IOException e) {
 }
}
//Run listen in different thread
 public void listen() {
    // Keep listening to the InputStream until an exception occurs
    while (true) {
        try {
           // Read from the InputStream
           byte buffer[];
           buffer = new byte[1024];
           //Read is synchronous call which keeps on waiting until data is available
           int bytes = inStream.read(buffer); 
            if(bytes &gt; 0){
              /*If data is non zero which means a data has been sent from Arduino to
               Android */
             //Do your stuff here
           }
     } catch (IOException e) {
        break;
    }
  }
 }
private void checkBTState() {
    // Check for Bluetooth support and then check to make sure it is turned on
    // Emulator doesn't support Bluetooth and will return null
    if (btAdapter == null) {
    } else {
  }
 }
 }
private void sendData(String message) {
    byte[] msgBuffer = message.getBytes();
    try {
      outStream.write(msgBuffer);
     } catch (IOException e) {
        String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
     if (address.equals("00:00:00:00:00:00"))
             msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 37 in the java code";
        msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
         errorExit("Fatal Error", msg);
    }
 }

<span style="color: #ff0000;">App Manifest file :</span>
<span style="color: #000000;">Download Manifest file here :</span> <span style="text-decoration: underline;"><span style="color: #0000ff;"><a style="color: #0000ff; text-decoration: underline;" href="https://drive.google.com/file/d/0BxDQP8DqOYBceDQ0SEw2Q2liek0/view?usp=sharing">Link

</a></span></span>

Troubleshooting Arduino HC 05:

There are many issues you might face and the troubleshooting techniques are as follows. 1. Some times Android and HC 05 will not connect ( android btSocket.connect();) might fail In this case unpair your HC 05 from android mobile and restart your Arduino(power off and power on). Pair again with android. If this doesn’t work then restart your mobile phone. 2. Some times android reads junk data even though data is not sent from HC 05. In this case also do the same stuff as described in above point. You can find many examples in – http://www.instructables.com

Project done by :

1. Vidya

2. Savitri

3. Shabnam

4. Niharika

Basaveshwar Engineering College – Bagalkot

Integrating Facebook In iOS Applications

Integrating Facebook In iOS Applications

Environment Setup :

Step1: Login into your Facebook developer account 

https://developers.facebook.com

Download Facebook iOS sdk – https://developers.facebook.com/resources/facebook-ios-sdk-current.pkg

Step 2: Go to My Apps and select your application ( If App is not created then do create new app)

iOSFacebookIntegration-MyApps

iOSFacebookIntegration-MyApps

Step 3: Go to facebook app settings page 

iOSFacebookIntegration - Settings page

iOSFacebookIntegration – Settings page

Step 4: Add new platform for iOS in settings page and fill the details

iOSFacebookIntegration - Platform

iOSFacebookIntegration – Platform

 

Step 5: Now copy the App ID generated and Display name

iSOFacebookIntegration

iSOFacebookIntegration

 

Step 6 : In your iOS project file set Facebook App ID and URL types as shown below. 

Inside iOS project set FacebookAppID and FacebookDisplayName 

Facebook Integration in iOS shows Blank Screen after login :

Setting FacebookAppId and FacebookDisplayName in iOS project plist file

This is most common problem many people face when Facebook is integrated in iOS application.

This is because the Facebook App id has not been set in plist file.

URL types and URL Schemes should be added

iOSFacebookIntegration - plist

iOSFacebookIntegration – plist

 

Facebook integration using Javascript library

If you are using javascript and web view then the screen black out issue can be fixed by specifying redirect URL as given below

This should work:

function loginUser()
{
 FB.login(function(response) { },
 {scope:'email', redirect_uri:'http://your-redirect-url'}); 
}

Amazon AWS EC2 Security Group and S3 Bucket Configuration

Amazon AWS EC2  Security Group and S3 Bucket configuration

Read our previous post : How to Create And Configure Amazon EC2 Free tier account

Amazon AWS is an awesome cloud service, It is worth writing a post on AWS service and its usage.

It is very easy to create an AWS account and use it, but most people will struck when its matter of security. Amazon setup is little bit complicated for security configuration. Please follow the steps given below to enable security group in your amazon cloud service.

Steps For Amazon EC2 Security Group:

Step 1: Go to your EC2 Service as shown in the image below

EC2

EC2

Step 2: Go to the section Security Group

Amazon Security Group

Amazon Security Group

 

Step 3: Enter Group Details 

Amazon Security group details

Amazon Security group details

 

Step 4: Add following rules 

Inbound

  • Rule 1

 Type : HTTP

 Protocol : TCP

 Port Range : 80

 Source : 0.0.0.0/0

  • Rule 2

 Type : All traffic

 Protocol : All traffic

 Port Range : All traffic

 Source : Your Ip Address ( search in google What Is My IP, copy paste the same IP here )

  • Rule 3

 Type : SSH

 Protocol : TCP

 Port Range : 22

 Source : Your Security Group Id

  • Rule 4

 Type : MYSQL

 Protocol : TCP

 Port Range : Mysql port ( 3306 )

 Source : Your Security Group Id

Outbound

  • Rule 1

 Type : HTTP

 Protocol : TCP

 Port Range : 80

 Source : 0.0.0.0/0

  • Rule 2

 Type : All traffic

 Protocol : All traffic

 Port Range : All traffic

 Source : Your Ip Address ( search in google What Is My IP, copy paste the same IP here )

  • Rule 3

 Type : MYSQL

 Protocol : TCP

 Port Range : Mysql port ( 3306 )

 Source : Your Security Group Id

Amazon S3 Bucket configuration

Step 1 : Go to Administration and Security from Amazon Services

Amazon S3 : IAM

Amazon S3 : IAM

 

Step 2 : Select Group from the IAM page

Step 3: Create new group, Give any name for the group

Step 4: The most important step is to set Policy type for the S3 bucket.

For file upload/download, Select AmazonEC2FullAccess

If this is done then your Amazon S3 is ready for use.

Step 5: Go to S3 service from the main menu

There create new bucket. Set permissions to your bucket as per your need.

File Upload to Amazon S3 bucket in Java 

Code Sample :

private static String bucketName = “”; //Give your YourS3Bucket name
private static String keyName = “”; // Give SomeKey

public final static String FOLDER_PATH = “TestFolder”;

public final static String rootServerURL = “”; //Your S3 Bucket Path =&gt; Your Amazon Instance / BucketName

BasicAWSCredentials awsCreds = new BasicAWSCredentials(“AccessKey”, “SecretKey”);

AmazonS3 s3client = new AmazonS3Client(awsCreds);

PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, keyName, fileObject);
putObjectRequest.withCannedAcl(CannedAccessControlList.PublicRead); // Read Permission for all
s3client.putObject(putObjectRequest);

Lambda Expressions in java – A Java 8 feature

What are Lambda Expression – Java 8 new feature?

Lambda expressions refers to what we had anonymous classes in the older versions of java.

So the very next straight forward thing comes to our mind, if already java is having anonymous classes why a replacement for the same is needed?

Why are Lambda Expressions needed, even if anonymous classes already exist?

The answer goes very simple, Lambda expressions when used makes our code more lighter as compared to when we use anonymous classes.

For Example:

Consider there is a class called Person
To sort the Person class by name if we use anonymous class we have to use the following code

Collections.sort(list, new Comparator() {
  @Override
  public int compare(Person p1, Person p2) {
       return p1.getName().compareTo(p2.getName());
  }
 });

But if we use Lambda expressions it will reduce to just 1 line, as show below,

Collections.sort(list, (Person p1, Person p2) -&gt; p1.getName().compareTo(p2.getName()));

reduces lot of bulky codes.

Lets Discuss one example in detail:

We all are aware of Service Oriented Architecture if not please go through the tutorial 

Calling services will always be time consuming (in general all network calls are considered slow), so we handle those requests asynchronously. If the call is asynchronous then in order to get the response from the service we expect a call back to be called which will return us the result.

The following example demonstrates rather tries to simulate such a scenario,
Consider the following class “ThreadCallableClass” which will make the call to service,

//CallBack.java
package com.dhi.callback;

@FunctionalInterface
public interface CallBack {
	void operationCompelte(String args);
}


//ThreadCallableClass.java

package com.dhi.thread;

import java.util.concurrent.Callable;

import com.dhi.callback.CallBack;

public class ThreadCallableClass implements Callable<String>{
	
	public ThreadCallableClass(CallBack callBack) {
		this.callBack = callBack;
	}

	CallBack callBack;

	String str;
	
	public String getStr() {
		return str;
	}

	public void setStr(String str) {
		this.str = str;
	}
	
	@Override
	public String call() throws Exception {
		System.out.println("service is getting called with the value: " + str);
		//code to call the service to fetch some details
		callBack.operationCompelte(str);
		return "return " + str;
	}

}

//MAIN.JAVA

package com.dhi.main;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.dhi.thread.ThreadCallableClass;

public class MainClass {

	public static void main(String[] args) {
		List<String> list = new ArrayList<>();
		for (int i = 0; i < 10; i++) {
			list.add("dhi" + i);
		}

		ArrayBlockingQueue<Runnable> arrayBlockingQueue = new ArrayBlockingQueue<Runnable>(
				1000);
		ExecutorService executorService = new ThreadPoolExecutor(10, 100, 20,
				TimeUnit.SECONDS, arrayBlockingQueue);
		for (String eachStr : list) {
			ThreadCallableClass callable = new ThreadCallableClass((String test1) -> {System.out.println(" call back getting called for the service for "+ test1);});
			callable.setStr(eachStr);
			executorService.submit(callable);
		}
		System.out.println("after thread pool");
		executorService.shutdown();
	}

}

//Person.java
package com.dhi.main;

import java.io.Serializable;

public class Person implements Serializable{
	
	String name;
	String mob;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getMob() {
		return mob;
	}
	public void setMob(String mob) {
		this.mob = mob;
	}

}


Download Code
DhiJava8LambdaFeature

Spring3 Issue with java8

Spring3 Issue with java8

Most common problem every one face during upgrading java to java8

Problem: All is well in your java spring3 web application, suddenly you start getting,







java.lang.IllegalArgumentException
at org.springframework.asm.ClassReader.(Unknown Source)
at org.springframework.asm.ClassReader.(Unknown Source)
at org.springframework.asm.ClassReader.(Unknown Source)
at org.springframework.core.type.classreading.SimpleMetadataReader.(SimpleMetadataReader.java:52)
at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:80)
at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:101)
at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:76)
at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:298)
at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:300)
at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:300)
at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:230)
at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:153)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:130)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:285)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:223)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:630)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:461)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:383)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4961)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5455)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)


			




Solution:

This issue is due to update of java to java 8, Following are the solutions for the same,

  1. You still intend to use java8 then spring must be upgraded to 4 or
  2. Change back the version of java to java7.

Steps to change in eclipse,

  1. Right click on the project and goto properties.
  2. Select “Java Build Path”.
  3. Goto “Libraries” tab.
  4. Select JRE System Lib (sometimes the name will mislead, it will be showing java7 but internally it will be pointing to java8).
  5. Click on “Edit” button present on the right side.
  6. Select “Alternate JRE” and click on “Installed JRE”.
  7. Click on “Add” è “Standard VM”.
  8. Click on “Directory” and select the JRE7 home.
  9. An entry for jre7 will be present, check the check box present against jre7.
  10. Click “Ok”
  11. Click on “Finish”.
  12. Click “Ok” again.
  13. Click on “Project” menu and then “Clean”
  14. Wait till the build completes.

You are good with all now again.

Mathematics to solve real-world problem

Analysing problem of global warming using Mathematics

we studied mathematics in high-school, degree college but never tried to apply the concepts in real-world. I was just thinking what example I shall take and how to write a program for the same. I got to know an interesting problem, only the problem is interesting but in real the problem is really worrying.

Problem – WRITING SOME WHAT DIFFERENT PROGRAM, SIMPLE BUT DIFFERENT

in Arctic the ice surface reflects 90% of the radiation but the water surface reflects only 10% of the radiation. Considering the fact in last two decades the Arctic like places showing effect of climate change. The water surface absorbs 90% of the radiation and hence leads to chain reaction. Assuming for every 1000 gray radiation, 0.65 sqft/hr water formation from ice surface, to predict how much ice surface might vanish and what could be the impact on global warming in next two decades?

To solve this problem one must apply integration which we study in Mathematics calculus, the same problem in other way to find out the rate of change of water surface can be evaluated using differential calculus.

Let me try out this problem with a C program, definitely I still didn’t find the integration or differential calculus equation to solve, but let me prepare set of simulated data with certain assumptions.

C Program

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/*
    Ice surface - reflects 90% of the sun light
    Water surface - reflects 10% of the sub light
    100 ice surface             - 10% absorbs
    100 water surface           - 90%
    Radiation = 100 gray
    100 * 90 = 9000 gray
    100 * 10 = 1000 gray
    assume that as temperature decreases ice surface increases, at the rate say 0.6 sqft per 1000 gray
*/
struct ICE_RADIATION_INFO{
    float iceSurfaceArea;
    float waterSurfaceArea;
    float radiationQuantity;
    
    float iceSurfaceAbsorption;
    float waterSurfaceAbsorption;
    
    float waterFormationPerHour;
};
typedef struct ICE_RADIATION_INFO ICE_RADIATION_INFO;
int main(int argc, const char * argv[])
{
    ICE_RADIATION_INFO iceRadiationSamples[100];
    short int index;
    
// Just to initialise the set of data for analysis - 
    for (index = 0; index < 100; ++index) {
        ICE_RADIATION_INFO  *iceRadiationSample = &iceRadiationSamples[index];
        // 1.5 is constant taken to generate area in floating point number
        iceRadiationSample->iceSurfaceArea = (rand() % 100) * 1.5;
        iceRadiationSample->waterSurfaceArea = iceRadiationSample->iceSurfaceArea;
     
        iceRadiationSample->radiationQuantity = (rand() % 1000) * 1.5;
        
      // absorption is as per discussion 90% from water surface and 10% from ice surface
        iceRadiationSample->iceSurfaceAbsorption = iceRadiationSample->radiationQuantity * 0.1;
        iceRadiationSample->waterSurfaceAbsorption = iceRadiationSample->radiationQuantity * 0.9;
    // with an assumption for every 1000 gray radiation, 0.65 sqft water forms
        iceRadiationSample->waterFormationPerHour = ( 0.65 * iceRadiationSample->radiationQuantity) / 1000; // 0.65 sqft/hr for 1000 gray
        /*
            Every hour 0.65 sqft water occumulation , this intern absorbs 90% of radiation , here have to apply integration
            dx/dt = 0.65
         */
    }
    
    printf("Surface Area \t Radiation \t\t Ice Absorption \t Water absorption\n");
    
    for (index = 0; index < 50; ++index) {
        ICE_RADIATION_INFO iceRadiationSample = iceRadiationSamples[index];
        printf("%f\t\t %f \t\t %f \t\t %f\n",iceRadiationSample.iceSurfaceArea,iceRadiationSample.radiationQuantity,iceRadiationSample.iceSurfaceAbsorption,iceRadiationSample.waterSurfaceAbsorption);
    }
    return 0;
}

OUTPUT –

Surface Area              Radiation                    Ice Absorption                  Water absorption

10.500000                   373.500000                  37.349998                           336.149994

109.500000                 987.000000                  98.699997                            888.299988

45.000000                   408.000000                   40.799999                           367.200012

66.000000                   1317.000000                 131.699997                         1185.300049

34.500000                   1063.500000                 106.349998                         957.150024

Jersey ClientHandlerException : A message body writer for Java type, class org.json.JSONObject, and MIME media type,

lientHandlerException: com.sun.jersey.api.client.ClientHandlerException: A message body writer for Java type, class org.json.JSONObject, and MIME media type, application/json,

com.sun.jersey.api.client.ClientHandlerException: com.sun.jersey.api.client.ClientHandlerException: A message body writer for Java type, class org.json.JSONObject, and MIME media type, application/json, was not found
    at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:149)
    at com.sun.jersey.api.client.Client.handle(Client.java:648)
    at com.sun.jersey.api.client.WebResource.handle(WebResource.java:670)
    at com.sun.jersey.api.client.WebResource.access$200(WebResource.java:74)
    at com.sun.jersey.api.client.WebResource$Builder.post(WebResource.java:563)
    at com.knowledgecess.test.service.impl.TestServiceImpl.getQuestions(TestServiceImpl.java:48)
    at com.knowledgecess.test.action.TestAction.demotest(TestAction.java:70)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:453)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:292)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:255)
    at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265)
    at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:236)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:236)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:190)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:90)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:243)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:176)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:192)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
    at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:511)
    at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:432)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1653)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)
Caused by: com.sun.jersey.api.client.ClientHandlerException: A message body writer for Java type, class org.json.JSONObject, and MIME media type, application/json, was not found
    at com.sun.jersey.api.client.RequestWriter.writeRequestEntity(RequestWriter.java:288)
    at com.sun.jersey.client.urlconnection.URLConnectionClientHandler._invoke(URLConnectionClientHandler.java:204)
    at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:147)
    ... 74 more
knowledgecess







Solution :
Just find jsonInput, second parameter for post() in the below code add toString to jsoninput data

ClientResponse clientResponse = webResource
                .accept(MediaType.APPLICATION_JSON)
                .type(MediaType.APPLICATION_JSON)
                .post(ClientResponse.class, jsonInput);

FIX –

ClientResponse clientResponse = webResource
.accept(MediaType.APPLICATION_JSON)
.type(MediaType.APPLICATION_JSON)
.post(ClientResponse.class, jsonInput.toString());

HTML Style , CSS properties Browser compatibility

CSS Proprties and Browser compatibility

CSS Properties :

1) content

  Never use content to set background image for div, instead use background-image :
Example 

			



 
.divItem{
    position: absolute;
    top: 12px;
    right: 11px;
    width: 40px;
    height: 40px;
    content: url(../../images/elective.png)
}
 
The above properties works fine in Chrome, but in firefox the image doesn't appear.
.divItem{
    position: absolute;
    top: 12px;
    right: 11px;
    width: 40px;
    height: 40px;
    content: url(../../images/elective.png)
}

2) background-size

.divItem{
    position: absolute;
    top: 12px;
    right: 11px;
    width: 40px;
    height: 40px;
    background-image: url(../../images/elective.png);
    -webkit-background-size: 100%;
    background-size: 100%
}

-webkit-background-size: is specifically for those browsers which support web kit layout rendering engine.
Note : http://en.wikipedia.org/wiki/WebKit






Opera supports 
-o-background-size:
But in latest opera versions, webkit itself is sufficient

3) box-shadow

.divItem{
   border: 1px solid #08c;
   box-shadow: 0 1px 0 rgba(255, 255, 255, 0.25), inset 0 3px 6px rgba(0, 0, 0, 0.25)
 }

This doesn't works in Firefox,

.divItem
{
   border: 1px solid #08c;
  -moz-box-shadow: 0 1px 0 rgba(255, 255, 255, 0.25), inset 0 3px 6px rgba(0, 0, 0, 0.25);
  -webkit-box-shadow: 0 1px 0 rgba(255, 255, 255, 0.25), inset 0 3px 6px rgba(0, 0, 0, 0.25);
  box-shadow: 0 1px 0 rgba(255, 255, 255, 0.25), inset 0 3px 6px rgba(0, 0, 0, 0.25)
 }


4) border-radius:

.divItem{
    border-radius: 100px;
}

For Firefox and other browsers
.divItem{
    -moz-border-radius: 100px;
    -webkit-border-radius: 100px;
    border-radius: 100px;
}


5) innerText :
innerText is old style of using in older version of internet explorer.
Instead of using innerText , use textContent or innerHTML, this works fine in all browsers.

User innerHTML Or contentText