001/*
002 *  Copyright 2010 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016
017package org.ametys.site;
018
019import java.io.IOException;
020
021import org.apache.cocoon.ProcessingException;
022import org.apache.cocoon.environment.ObjectModelHelper;
023import org.apache.cocoon.environment.Request;
024import org.apache.cocoon.reading.ServiceableReader;
025import org.apache.http.HttpEntity;
026import org.apache.http.HttpResponse;
027import org.apache.http.impl.client.CloseableHttpClient;
028import org.apache.http.util.EntityUtils;
029import org.xml.sax.SAXException;
030
031/**
032 * Writes the CMS data direct to the client.
033 */
034public class CMSResponseReader extends ServiceableReader
035{
036    @Override
037    public void generate() throws IOException, SAXException, ProcessingException
038    {
039        Request request = ObjectModelHelper.getRequest(objectModel);
040        
041        HttpResponse cmsResponse = (HttpResponse) request.getAttribute("cms-response");
042        HttpEntity entity = cmsResponse.getEntity();
043        entity.writeTo(out);
044        
045        EntityUtils.consume(entity);
046        
047        out.flush();
048    }
049    
050    @Override
051    public String getMimeType()
052    {
053        Request request = ObjectModelHelper.getRequest(objectModel);
054        
055        HttpResponse cmsResponse = (HttpResponse) request.getAttribute("cms-response");
056        HttpEntity entity = cmsResponse.getEntity();
057        return entity.getContentType() != null ? entity.getContentType().getValue() : null;
058    }
059    
060    @Override
061    public void recycle()
062    {
063        Request request = ObjectModelHelper.getRequest(objectModel);
064        
065        try (CloseableHttpClient httpClient = (CloseableHttpClient) request.getAttribute("http-client"))
066        {
067            httpClient.close();
068        }
069        catch (IOException e) 
070        {
071            // Nothing
072        }
073        
074        super.recycle();
075    }
076}