package de.fesere.hypermedia.cj.model;

import de.fesere.hypermedia.cj.exceptions.ElementNotFoundException;
import de.fesere.hypermedia.cj.http.HTTPClient;
import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;
import java.net.URI;

public class CjClient {

    private Collection collection;
    private final HTTPClient httpClient;


    public CjClient(HTTPClient httpClient) {
        this.httpClient = httpClient;
    }

    public CjClient use(Collection collection) {
        this.collection = collection;
        return this;
    }

    public Collection follow(Query query) {

        try {

            URI queryURI = query.buildURI();
            String json = httpClient.getLink(queryURI);

            ObjectMapper mapper = new ObjectMapper();

            return mapper.readValue(json, Collection.class);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
    public Query selectQuery(String search) {
        for(Query query : collection.getQueries()) {
            if(query.getRel().equals(search)) {
                return query;
            }
        }

        throw new ElementNotFoundException("Query '"+search+"' not found" );
    }

    public Collection read(URI uri) {
        String collectionJson = httpClient.getLink(uri);

        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(collectionJson, Collection.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

@@ -603,27 +603,8 @@
  %7B%0A%0A
-        try %7B%0A%0A    
     
@@ -636,28 +636,24 @@
 buildURI();%0A
-    
         Stri
@@ -705,211 +705,59 @@
     
-    ObjectMapper mapper = new ObjectMapper();%0A%0A            return mapper.readValue(json, Collection.class);%0A%0A        %7D catch (IOException e) %7B%0A            throw new RuntimeException(e);%0A        %7D%0A
+return deserialize(json, Collection.class);
 %0A    %7D%0A
+%0A
     
@@ -809,16 +809,17 @@
      for
+ 
 (Query q
@@ -866,16 +866,17 @@
       if
+ 
 (query.g
@@ -1012,16 +1012,20 @@
 y '%22
-+
+ + 
 search
-+
+ + 
 %22' n
@@ -1033,17 +1033,16 @@
 t found%22
- 
 );%0A    %7D
@@ -1135,24 +1135,164 @@
 Link(uri);%0A%0A
+        return deserialize(collectionJson, Collection.class);%0A    %7D%0A%0A    private %3CT%3E T deserialize(String input, Class%3CT%3E responseClass) %7B%0A%0A
         Obje
@@ -1325,24 +1325,25 @@
 ctMapper();%0A
+%0A
         try 
@@ -1384,36 +1384,24 @@
 lue(
-collectionJson, Collection.c
+input, responseC
 lass
@@ -1476,16 +1476,76 @@
 ception(
+%22Could not deseriliaze inout to %22 + responseClass.getName(),
 e);%0A    

Extract deserialization into a separate method