Monday, 29 September 2014

HashMap – Single Key and Multiple Values Example

HashMap can be used to store key-value pairs.
But sometimes you may want to store multiple values for the same key.
For example:
For Key A, you want to store - Apple, Aeroplane
For Key B, you want to store - Bat, Banana
For Key C, you want to store – Cat, Car
The following code snippets will show you at least 3 different ways of storing key-value pairs with a distinction of Single Key and Multiple Values

HashMap – Single Key and Multiple Values using List

package com.skilledmonster.examples.util.map;
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
/**
 * HashMap - Single Key and Multiple Values using List
 *
 * @author Jagadeesh Motamarri
 * @version 1.0
 */
public class SingleKeyMultipleValueUsingList {
 
    public static void main(String[] args) {
 
        // create map to store
        Map<String, List<String>> map = new HashMap<String, List<String>>();
 
        // create list one and store values
        List<String> valSetOne = new ArrayList<String>();
        valSetOne.add("Apple");
        valSetOne.add("Aeroplane");
 
        // create list two and store values
        List<String> valSetTwo = new ArrayList<String>();
        valSetTwo.add("Bat");
        valSetTwo.add("Banana");
 
        // create list three and store values
        List<String> valSetThree = new ArrayList<String>();
        valSetThree.add("Cat");
        valSetThree.add("Car");
 
        // put values into map
        map.put("A", valSetOne);
        map.put("B", valSetTwo);
        map.put("C", valSetThree);
 
        // iterate and display values
        System.out.println("Fetching Keys and corresponding [Multiple] Values n");
        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
            String key = entry.getKey();
            List<String> values = entry.getValue();
            System.out.println("Key = " + key);
            System.out.println("Values = " + values + "n");
        }
    }
}

HashMap – Single Key and Multiple Values using Google Guava Collections

package com.skilledmonster.examples.util.map;
 
import java.util.Set;
 
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
 
/**
 * HashMap - Single Key and Multiple Values using Google Guava Collections
 *
 * @author Jagadeesh Motamarri
 * @version 1.0
 */
public class SingleKeyMultipleValueUsingGuava {
 
    public static void main(String[] args) {
 
        // create multimap to store key and values
        Multimap<String, String> multiMap = ArrayListMultimap.create();
 
        // put values into map for A
        multiMap.put("A", "Apple");
        multiMap.put("A", "Aeroplane");
 
        // put values into map for B
        multiMap.put("B", "Bat");
        multiMap.put("B", "Banana");
 
        // put values into map for C
        multiMap.put("C", "Cat");
        multiMap.put("C", "Car");
 
        // retrieve and display values
        System.out.println("Fetching Keys and corresponding [Multiple] Values n");
 
        // get all the set of keys
        Set<String> keys = multiMap.keySet();
 
        // iterate through the key set and display key and values
        for (String key : keys) {
            System.out.println("Key = " + key);
            System.out.println("Values = " + multiMap.get(key) + "n");
        }
 
    }
}

 HashMap – Single Key and Multiple Values using Apache Commons Collection

package com.skilledmonster.examples.util.map;
 
import java.util.Set;
 
import org.apache.commons.collections.MultiMap;
import org.apache.commons.collections.map.MultiValueMap;
 
/**
 * HashMap - Single Key and Multiple Values using Apache Commons Collections
 *
 * @author Jagadeesh Motamarri
 * @version 1.0
 */
public class SingleKeyMultipleValueUsingApacheCollections {
 
    public static void main(String[] args) {
 
        // create multimap to store key and values
        MultiMap multiMap = new MultiValueMap();
 
        // put values into map for A
        multiMap.put("A", "Apple");
        multiMap.put("A", "Aeroplane");
 
        // put values into map for B
        multiMap.put("B", "Bat");
        multiMap.put("B", "Banana");
 
        // put values into map for C
        multiMap.put("C", "Cat");
        multiMap.put("C", "Car");
 
        // retrieve and display values
        System.out.println("Fetching Keys and corresponding [Multiple] Values n");
 
        // get all the set of keys
        Set<String> keys = multiMap.keySet();
 
        // iterate through the key set and display key and values
        for (String key : keys) {
            System.out.println("Key = " + key);
            System.out.println("Values = " + multiMap.get(key) + "n");
        }
 
    }
}

Output

The output for all the above 3 scenarios will be same as the one below
hashmap - single_key_multiple_values

Tuesday, 16 September 2014

Android add or include xml Layout

 
 way-1
 
LinearLayout myLayout = (LinearLayout)findViewById(R.id.linearLayout1);
        View itemInfo1 = getLayoutInflater().inflate(R.layout.item, myLayout, true);
        View itemInfo2 = getLayoutInflater().inflate(R.layout.item, myLayout, true);
        View itemInfo3 = getLayoutInflater().inflate(R.layout.item, myLayout, true);
 
 
 way-2
 
       LayoutInflater inflater = (LayoutInflater)      this.getSystemService(LAYOUT_INFLATER_SERVICE);
 View childLayout = inflater.inflate(R.layout.***************,
 (ViewGroup) findViewById(R.layout.***************));
 layout_daily_diary_content.addView(childLayout);*/
 
 way-3

    LinearLayout linearLayout = (LinearLayout) View.inflate(this,
   R.***********, null);
   layout_content.addView(linearLayout);

Wednesday, 10 September 2014

Gert Lombard's blog

Configure Google Nexus 7 to work with Android SDK Tools / ADB.exe

I wanted to deploy my first “hello world” Android application from Eclipse on Windows 8 to my Google Nexus 7 tablet. I plugged the Nexus 7 into my development PC using the USB cable and then I used adb.exe to list the devices, but no devices were found.
The summary of steps I took to get the device to show with ADB:
  1. Enabled the USB debugging setting on the tablet
  2. Changed the USB connection mode to Camera (PTP)
  3. Updated the Google USB Driver in Windows
Initially Adb.exe shows no devices:
01-adb-shows-no-devices
If the Android emulator is running, it shows as the only device:
02-adb-shows-only-emulator
The first step is to enable the Developer options the Nexus 7. Go to Settings –> About tablet. Then tap the “Build number” 7 times!
02-tap-build-number-7-times
Now you will see the “Developer options” setting. Go into Developer options and enable the “USB debugging” setting:
02-enable-usb-debugging
When you get the “USB debugging connected” notification, tap the “Connected as a media device” option.
02-usb-connected
The default USB mode is “Media device (MTP)”, change this to “Camera (PTP)”:
02-select-camera-ptp-mode
Install the Google USB Driver using Eclipse / ADT: Window –> Android SDK Manager. In the Android SDK Manager, select Extras –> Google USB Driver. This installs the driver to your android SDK folder under sdk\extras\google\usb_driver.
Now update the device driver using Device Manager in Windows 8:
03-open-device-manager-win8
Find the “Nexus 7” device in the Device Manager under “Other devices”, then right click and select “Update Driver Software…”:
04-device-manager
Provide the path to the Google USB Driver:
05-select-driver
Select “Always trust software from Google Inc” and install the driver:
06-install-driver
Now the “Android Composite ADB Interface” will show in the Device Manager:
07-android-device-in-device-manager
Run ADB.exe again and confirm the new device is available. It may show as offline:
08-adb-shows-new-device
If the device shows as “offline”, then make sure to confirm on the tablet that you allow USB debugging:
08-allow-usb-debugging
Now the device is online:
09-nexus-online

REST in Spring 3: RestTemplate

In an earlier post, I blogged about the REST capabilities we added to Spring @MVC version 3.0. Later, Alef wrote about using the introduced functionality to add an Atom view to the Pet Clinic application. In this post, I would like to introduce the client-side capabilities we added in Milestone 2.

RestTemplate

The RestTemplate is the central Spring class for client-side HTTP access. Conceptually, it is very similar to the JdbcTemplate, JmsTemplate, and the various other templates found in the Spring Framework and other portfolio projects. This means, for instance, that the RestTemplate is thread-safe once constructed, and that you can use callbacks to customize its operations.

RestTemplate Methods

The main entry points of the template are named after the six main HTTP methods:
HTTPRESTTEMPLATE
DELETEdelete(String, String...)
GETgetForObject(String, Class, String...)
HEADheadForHeaders(String, String...)
OPTIONSoptionsForAllow(String, String...)
POSTpostForLocation(String, Object, String...)
PUTput(String, Object, String...)
The names of these methods clearly indicate which HTTP method they invoke, while the second part of the name indicates what is returned. For instance, getForObject() will perform a GET, convert the HTTP response into an object type of your choice, and returns that object.postForLocation will do a POST, converting the given object into a HTTP request, and returns the response HTTP Location header where the newly created object can be found. As you can see, these methods try to enforce REST best practices.

URI Templates

Each of these methods takes a URI as first argument. That URI can be a URI template, and variables can be used to expand the template to a normal URI. The template variables can be passed in two forms: as a String variable arguments array, or as a Map. The string varargs variant expands the given template variables in order, so that
String result = restTemplate.getForObject("http://example.com/hotels/{hotel}/bookings/{booking}", String.class, "42", "21");
will perform a GET on http://example.com/hotels/42/bookings/21. The map variant expands the template based on variable name, and is therefore more useful when using many variables, or when a single variable is used multiple times. For example:
Map<String, String> vars = new HashMap<String, String>();
vars.put("hotel", "42");
vars.put("booking", "21");
String result = restTemplate.getForObject("http://example.com/hotels/{hotel}/bookings/{booking}", String.class, vars);
will also perform a GET on http://example.com/hotels/42/rooms/42.

HttpMessageConverters

Objects passed to and returned from the methods getForObject(), postForLocation(), andput() and are converted to HTTP requests and from HTTP responses byHttpMessageConverters. Converters for the main mime types and Java types are registered by default, but you can also write your own converter and plug it in the RestTemplate. In the example below, I will show you how that's done.

Using the RestTemplate to retrieve photos from Flickr

Rather than going through the various methods of the RestTemplate, I will show you how to use it for retrieving pictures from Flickr, Yahoo!s online photo-sharing application. This sample application searches Flickr for photos that match a given search term. It then shows these pictures using a simple Swing UI. To run the application yourself, you will need to create a Flickr account and apply for an API key.

Searching for photos

Flickr exposes various APIs to manipulate its vast library of photos. The flickr.photos.searchmethod allows you to search for photos, by issuing a GET request onhttp://www.flickr.com/services/rest?method=flickr.photos.search&api+key=xxx&tags=penguins, where you enter your API key and the thing to search for (penguins in this case). As a result, you get back a XML document, describing the photos that conform to your query. Something like:
<photos page="2" pages="89" perpage="10" total="881">
    <photo id="2636" owner="47058503995@N01" 
        secret="a123456" server="2" title="test_04"
        ispublic="1" isfriend="0" isfamily="0" />
    <photo id="2635" owner="47058503995@N01"
        secret="b123456" server="2" title="test_03"
        ispublic="0" isfriend="1" isfamily="1" />
    <photo id="2633" owner="47058503995@N01"
        secret="c123456" server="2" title="test_01"
        ispublic="1" isfriend="0" isfamily="0" />
    <photo id="2610" owner="12037949754@N01"
        secret="d123456" server="2" title="00_tall"
        ispublic="1" isfriend="0" isfamily="0" />
</photos>
Using the RestTemplate, retrieving such a document is quite trivial:
final String photoSearchUrl =
   "http://www.flickr.com/services/rest?method=flickr.photos.search&api+key={api-key}&tags={tag}&per_page=10";
Source photos = restTemplate.getForObject(photoSearchUrl, Source.class, apiKey, searchTerm);
where apiKey and searchTerm are two Strings given on the command line. This method uses the SourceHttpMessageConverter to convert the HTTP XML response into ajavax.xml.transform.Source (Note that the SourceHttpMessageConverter was introduced shortly after we released Spring 3.0 M2, so you will have to get a recent snapshot (or the upcoming M3) to use it. The sample project available below is set up to retrieve these via Maven).

Retrieving the photos

Next, we're going to use an XPath expression to retrieve all the photo elements of the document. For this, we are going to use the XPathTemplate from Spring Web Services. We are going to execute the //photo expressions, returning all photo elements occurring anywhere in the document. The NodeMapper is a callback interface, whose mapNode() method will be invoked for each photo element in the document. In this case, we are retrieving the server, id, and secret attributes of this element, and use those to fill up a Map. Finally, we use the RestTemplate again, to retrieve the photo as a java.awt.image.BufferedImage. Thus when the XPath evaluation is done, the resulting imageList will contain an image for each photo in the XML document.
List<BufferedImage> imageList = xpathTemplate.evaluate("//photo", photos, new NodeMapper() {
    public Object mapNode(Node node, int i) throws DOMException {
        Element photo = (Element) node;

        Map<String, String> variables = new HashMap<String, String>(3);
        variables.put("server", photo.getAttribute("server"));
        variables.put("id", photo.getAttribute("id"));
        variables.put("secret", photo.getAttribute("secret"));

        String photoUrl = "http://static.flickr.com/{server}/{id}_{secret}_m.jpg";
        return restTemplate.getForObject(photoUrl, BufferedImage.class, variables);
    }
});
For instance, given the XML document given above, the imageList will contain 4 images. The URL for the first image retrieved will be http://static.flickr.com/2/2636_ a123456_m.jpg, the second is http://static.flickr.com/2/2635_ b123456_m.jpg, etc.

Converting the images

There is one more thing that needs to be done in order for the code to work: we will need to write a HttpMessageConverter that is able to read from the HTTP response, and create aBufferedImagefrom that. Doing so with the Java Image I/O API is fairly simple, we just need to implement the read() method defined in the HttpMessageConverter interface. Overall, our simple converter looks like this:
public class BufferedImageHttpMessageConverter implements HttpMessageConverter<BufferedImage> {

    public List<MediaType> getSupportedMediaTypes() {
        return Collections.singletonList(new MediaType("image", "jpeg"));
    }

    public boolean supports(Class<? extends BufferedImage> clazz) {
        return BufferedImage.class.equals(clazz);
    }

    public BufferedImage read(Class<BufferedImage> clazz, HttpInputMessage inputMessage) throws IOException {
        return ImageIO.read(inputMessage.getBody());
    }

    public void write(BufferedImage image, HttpOutputMessage message) throws IOException {
        throw new UnsupportedOperationException("Not implemented");
    }

}
Note that we didn't implement write() because we are not uploading images, just downloading them. Now we just have to plug this converter into the RestTemplate. We do that in the Spring application context:
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="flickrClient" class="com.springsource.samples.resttemplate.FlickrClient">
        <constructor-arg ref="restTemplate"/>
        <constructor-arg ref="xpathTemplate"/>
    </bean>

    <bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"/>
                <bean class="com.springsource.samples.resttemplate.BufferedImageHttpMessageConverter"/>
            </list>
        </property>
    </bean>

    <bean id="xpathTemplate" class="org.springframework.xml.xpath.Jaxp13XPathTemplate"/>

</beans>

Showing the photos

The final stage is to show the photos in a simple GUI. For this, we use Swing:
JFrame frame = new JFrame(searchTerm + " photos");
frame.setLayout(new GridLayout(2, imageList.size() / 2));
for (BufferedImage image : imageList) {
    frame.add(new JLabel(new ImageIcon(image)));
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
which gives us the following:
Penguins
Overall, I hope this post showed you how simple it can be to use the RestTemplate to interact with HTTP servers. In just under 30 lines of Java code, we created a GUI that shows pictures of everybody's favorite bird: the penguin! Check out the RestTemplate and let us know what you think!

Downloads

A Maven project containing the code above can be downloaded here. Note that the project is based on a nightly snapshot build of Spring. The upcoming Milestone 3 of Spring will contain the necessary classes as well.