001/* 
002 * JKNIV, whinstone one contract to access your database.
003 * 
004 * Copyright (C) 2017, the original author or authors.
005 *
006 * This library is free software; you can redistribute it and/or
007 * modify it under the terms of the GNU Lesser General Public
008 * License as published by the Free Software Foundation; either
009 * version 2.1 of the License.
010 * 
011 * This library is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014 * Lesser General Public License for more details.
015 * 
016 * You should have received a copy of the GNU Lesser General Public
017 * License along with this library; if not, write to the Free Software Foundation, Inc., 
018 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
019 */
020package net.sf.jkniv.whinstone.couchdb.commands;
021
022import java.io.IOException;
023import java.util.ArrayList;
024import java.util.List;
025
026import org.apache.http.client.methods.CloseableHttpResponse;
027import org.apache.http.client.methods.HttpGet;
028import org.apache.http.impl.client.CloseableHttpClient;
029import org.apache.http.impl.client.HttpClients;
030import org.apache.http.util.EntityUtils;
031import org.slf4j.Logger;
032import org.slf4j.LoggerFactory;
033
034import net.sf.jkniv.sqlegance.RepositoryException;
035import net.sf.jkniv.whinstone.Queryable;
036import net.sf.jkniv.whinstone.couchdb.HttpBuilder;
037
038public class GetCommand extends AbstractCommand implements CouchCommand
039{
040    private static final Logger LOG = LoggerFactory.getLogger(GetCommand.class);
041    private static final Logger LOGSQL = net.sf.jkniv.whinstone.couchdb.LoggerFactory.getLogger();
042    private String              body;
043    private Queryable           queryable;
044    private HttpBuilder         httpBuilder;
045    
046    public GetCommand(HttpBuilder httpBuilder, Queryable queryable)
047    {
048        super();
049        this.httpBuilder = httpBuilder;
050        this.queryable = queryable;
051    }
052    
053    @Override
054    public <T> T execute()
055    {
056        String json = null;
057        CloseableHttpResponse response = null;
058        //Map<String, Object> answer = null;
059        List<T> list = new ArrayList<T>(1);
060        T answer = null;
061        try
062        {
063            CloseableHttpClient httpclient = HttpClients.createDefault();
064            String url = httpBuilder.getUrlForGet(queryable);
065            HttpGet http = null;
066            if (this.method == HttpMethod.GET)
067            {
068                http = new HttpGet(url);
069            }
070            else
071                throw new RepositoryException("Get Command just support GET HTTP method!");
072            
073            httpBuilder.setHeader(http);
074            printRequest(http);
075            response = httpclient.execute(http);
076            json = EntityUtils.toString(response.getEntity());
077            printResponse(response, json);
078            int statusCode = response.getStatusLine().getStatusCode();
079            if (statusCode == HTTP_OK)
080            {
081                answer =  (T) JsonMapper.mapper(json, queryable.getReturnType());
082                list.add(answer);
083            }
084            else if (isNotFound(statusCode))
085            {
086                // 204 No Content, 304 Not Modified, 205 Reset Content
087                LOGSQL.warn(errorFormat(http, response.getStatusLine(), json));
088            }
089            else
090            {
091                //LOG.error("Http Body\n{}", EntityUtils.toString(http.getEntity()));
092                LOG.error(errorFormat(http, response.getStatusLine(), json));
093                throw new RepositoryException(response.getStatusLine().toString());
094            }
095            //commandHandler.postCommit();
096        }
097        catch (Exception e) // ClientProtocolException | JsonParseException | JsonMappingException | IOException
098        {
099            //commandHandler.postException();
100            handlerException.handle(e);
101        }
102        finally
103        {
104            if (response != null)
105            {
106                try
107                {
108                    response.close();
109                }
110                catch (IOException e)
111                {
112                    handlerException.handle(e);
113                }
114            }
115        }
116        return (T)list;
117    }
118    
119    @Override
120    public String getBody()
121    {
122        return this.body;
123    }
124    
125    @Override
126    public HttpMethod asGet()
127    {
128        this.method = HttpMethod.GET;
129        return this.method;
130    }
131}