001/**
002 * Copyright 2015 Tampere University of Technology, Pori Department
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 */
016package core.tut.pori.http;
017
018import java.io.IOException;
019
020import javax.servlet.http.HttpServletResponse;
021
022import org.apache.commons.lang3.StringUtils;
023import org.apache.log4j.Logger;
024
025/**
026 * Prints data as raw strings format.
027 * 
028 */
029public class StringResponse extends Response {
030  private static final Logger LOGGER = Logger.getLogger(StringResponse.class);
031  private StringData _stringData = null;
032
033  /**
034   * for serialization
035   */
036  public StringResponse(){
037    // nothing needed
038  }
039  
040  /**
041   * 
042   * @param status
043   */
044  public StringResponse(Status status){
045    super(status);
046  }
047  
048  /**
049   * 
050   * @param data
051   */
052  public StringResponse(StringData data){
053    _stringData = data;
054  }
055  
056  /**
057   * @throws UnsupportedOperationException if data is not of type {@link core.tut.pori.http.StringResponse.StringData}
058   * @see #setStringData(StringData)
059   */
060  @Override
061  public void setResponseData(ResponseData data) throws UnsupportedOperationException {
062    if(data == null){
063      setStringData((StringData)null);
064    }else if(data instanceof StringData){
065      setStringData((StringData) data);
066    }else{
067      throw new UnsupportedOperationException("Using "+ResponseData.class.toString()+" with class "+StringResponse.class.toString()+" is not supported.");
068    }
069  }
070
071  @Override
072  public void writeTo(HttpServletResponse response) {
073    response.setCharacterEncoding((_stringData == null ? Definitions.ENCODING_UTF8 : _stringData.getEncoding()));
074    
075    Status status = getStatus();
076    if(status != Status.OK){
077      LOGGER.debug("Ignoring content because of error condition: "+status.name());
078      String message = getMessage();
079      if(!StringUtils.isBlank(message)){
080        response.setContentType(Definitions.CONTENT_TYPE_TEXT);
081        try {
082          response.getWriter().write(message);
083        } catch (IOException ex) {
084          LOGGER.error(ex, ex);
085          setStatus(Status.INTERNAL_SERVER_ERROR);
086        }
087      }
088    }else if(_stringData == null){
089      LOGGER.warn("No content given.");
090      setStatus(Status.NO_CONTENT);
091    }else{
092      response.setContentType(_stringData.getContentType());
093      try {
094        response.getWriter().write(_stringData.toResponseString());
095      } catch (IOException ex) {
096        LOGGER.error(ex, ex);
097        setStatus(Status.INTERNAL_SERVER_ERROR);
098      }
099    }
100    
101    status = getStatus();
102    if(status != Status.OK){  // don't change defaults if there is OK status
103      response.setStatus(status.toStatusCode());
104      if(status == Status.UNAUTHORIZED){
105        setDefaultAuthenticationHeader(response);
106      }
107    }
108  }
109
110  /**
111   * @return the stringData
112   */
113  public StringData getStringData() {
114    return _stringData;
115  }
116
117  /**
118   * @param stringData the stringData to set
119   */
120  public void setStringData(StringData stringData) {
121    _stringData = stringData;
122  }
123
124
125  /**
126   * Interface for classes, which should support conversion to string-based response data
127   * 
128   */
129  public interface StringData {
130    /**
131     * 
132     * @return the data as response
133     */
134    public String toResponseString();
135    
136    /**
137     * 
138     * @return the content type (<a href="http://www.w3.org/Protocols/rfc1341/4_Content-Type.html">The Content-Type Header Field</a>) for the response.
139     */
140    public String getContentType();
141    
142    /**
143     * 
144     * @return encoding for the response data, such as {@link core.tut.pori.http.Definitions#ENCODING_UTF8}}
145     * @see #toResponseString()
146     */
147    public String getEncoding();
148  } // interface SubtitleData
149}