001/* 002 * The contents of this file are subject to the terms of the Common Development and 003 * Distribution License (the License). You may not use this file except in compliance with the 004 * License. 005 * 006 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the 007 * specific language governing permission and limitations under the License. 008 * 009 * When distributing Covered Software, include this CDDL Header Notice in each file and include 010 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL 011 * Header, with the fields enclosed by brackets [] replaced by your own identifying 012 * information: "Portions Copyright [year] [name of copyright owner]". 013 * 014 * Copyright 2009 Sun Microsystems Inc. 015 * Portions Copyright 2010–2011 ApexIdentity Inc. 016 * Portions Copyright 2011-2016 ForgeRock AS. 017 */ 018 019package org.forgerock.http.protocol; 020 021import java.io.IOException; 022 023import org.forgerock.http.io.BranchingInputStream; 024 025/** 026 * Abstract message base class. 027 * 028 * @param <T> 029 * The sub-type of this message. 030 */ 031public abstract class MessageImpl<T extends MessageImpl<T>> implements Message { 032 033 /** Message entity body. */ 034 private final Entity entity; 035 036 /** Message header fields. */ 037 private final Headers headers; 038 039 /** Protocol version. Default: {@code HTTP/1.1}. */ 040 private String version = "HTTP/1.1"; 041 042 MessageImpl() { 043 // Hidden constructor. 044 entity = new Entity(this); 045 headers = new Headers(); 046 } 047 048 /** 049 * Defensive copy constructor. 050 */ 051 MessageImpl(MessageImpl<T> message) throws IOException { 052 headers = new Headers(message.headers); 053 entity = new Entity(this, message.entity); 054 setVersion0(message.version); 055 } 056 057 @Override 058 public void close() { 059 entity.close(); 060 } 061 062 @Override 063 public final Entity getEntity() { 064 return entity; 065 } 066 067 @Override 068 public final Headers getHeaders() { 069 return headers; 070 } 071 072 @Override 073 public final String getVersion() { 074 return version; 075 } 076 077 final void setEntity0(final Object o) { 078 if (o instanceof BranchingInputStream) { 079 entity.setRawContentInputStream((BranchingInputStream) o); 080 } else if (o instanceof byte[]) { 081 entity.setBytes((byte[]) o); 082 } else if (o instanceof String) { 083 entity.setString((String) o); 084 } else { 085 entity.setJson(o); 086 } 087 } 088 089 final void setVersion0(final String version) { 090 this.version = version; 091 } 092}