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.Collections;
024import java.util.List;
025
026import org.apache.http.client.methods.CloseableHttpResponse;
027import org.apache.http.client.methods.HttpPost;
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.CouchDbResult;
037import net.sf.jkniv.whinstone.couchdb.HttpBuilder;
038
039public class FullResponseFindCommand extends AbstractCommand implements CouchCommand
040{
041    private static final Logger LOG = LoggerFactory.getLogger(FullResponseFindCommand.class);
042    private static final Logger LOGSQL = net.sf.jkniv.whinstone.couchdb.LoggerFactory.getLogger();
043    private HttpBuilder httpBuilder;
044    private Queryable queryable;
045    
046    public FullResponseFindCommand(HttpBuilder httpBuilder, Queryable queryable)
047    {
048        super();
049        this.queryable = queryable;
050        this.httpBuilder = httpBuilder;
051    }
052    
053    @Override
054    public <T> T execute()
055    {
056        String json = null;
057        CloseableHttpResponse response = null;
058        CouchDbResult answer = null;
059        List list = Collections.emptyList();
060        try
061        {
062            CloseableHttpClient httpclient = HttpClients.createDefault();
063            HttpPost httpPost = httpBuilder.newFind(body);
064            if(LOGSQL.isInfoEnabled())
065                LOGSQL.info("\nHTTP POST [{}] \n {}", httpPost.getURI(), body);
066
067            response = httpclient.execute(httpPost);
068            json = EntityUtils.toString(response.getEntity());
069            printResponse(response, json);
070
071            int statusCode = response.getStatusLine().getStatusCode();
072            if (isOk(statusCode))
073            {
074                JsonMapper.setCurrentQuery(queryable);
075                answer = JsonMapper.MAPPER.readerFor(CouchDbResultImpl.class).readValue(json);
076                list = answer.getRows();
077                setBookmark(answer.getBookmark(), queryable);
078                queryable.setTotal(answer.getRows().size());
079            }
080            else if (isNotFound(statusCode))
081            {
082                queryable.setTotal(0);
083                // 204 No Content, 304 Not Modified, 205 Reset Content
084                LOGSQL.warn(errorFormat(httpPost, response.getStatusLine(), json));
085            }
086            else
087            {
088                LOG.error(errorFormat(httpPost, response.getStatusLine(), json));
089                throw new RepositoryException(response.getStatusLine().toString());
090            }
091            //commandHandler.postCommit();
092        }
093        catch (Exception e) // ClientProtocolException | JsonParseException | JsonMappingException | IOException
094        {
095            //queryable.setTotal(Statement.EXECUTE_FAILED);
096            //commandHandler.postException();
097            //if (currentRow != null)
098            //    LOG.error("Failure to parser the current row {}", currentRow, e);
099            handlerException.handle(e);
100        }
101        finally
102        {
103            if (response != null)
104            {
105                try
106                {
107                    response.close();
108                }
109                catch (IOException e)
110                {
111                    handlerException.handle(e);
112                }
113            }
114        }
115        return (T)list;
116    }
117
118    @Override
119    public String getBody()
120    {
121        return this.body;
122    }
123
124    @Override
125    public HttpMethod asGet()
126    {
127        this.method = HttpMethod.GET;
128        return this.method;
129    }
130
131    @Override
132    public HttpMethod asPost()
133    {
134        this.method = HttpMethod.POST;
135        return this.method;
136    }
137}