
br.com.objectos.rio.http.Response Maven / Gradle / Ivy
The newest version!
/*
* Copyright 2016 Objectos, Fábrica de Software LTDA.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package br.com.objectos.rio.http;
import java.io.IOException;
import java.util.List;
import br.com.objectos.core.util.ImmutableList;
import br.com.objectos.io.ByteSource;
/**
* @author [email protected] (Marcio Endo)
*/
public class Response {
private final StatusCode status;
private final List headerList;
private final MessageBody body;
public Response(StatusCode status, List headerList, MessageBody body) {
this.status = status;
this.headerList = headerList;
this.body = body;
}
public static ResponseBuilder builder() {
return new Builder();
}
public void respond(Socket socket) throws IOException {
SocketWriter writer = socket.openWriter();
respond(writer);
writer.flush();
}
void respond(SocketWriter writer) throws IOException {
writer.writeString("HTTP/1.1");
writer.writeString(" ");
status.writeTo(writer);
for (Header header : headerList) {
writer.newLine();
header.writeTo(writer);
}
body.writeTo(writer);
}
private static class Builder
implements
ResponseBuilder,
ResponseBuilder.ResponseBuilderHeaders,
ResponseBuilder.ResponseBuilderMessageBody {
private StatusCode status;
private final ImmutableList.Builder headerList = ImmutableList.builder();
private MessageBody body = MessageBody.empty();
private Builder() {
}
@Override
public Response build() {
return new Response(status, headerList.build(), body);
}
@Override
public ResponseBuilderHeaders contentLength(long size) {
headerList.add(Header.contentLength(size));
return this;
}
@Override
public ResponseBuilderHeaders contentType(ContentType contentType) {
headerList.add(Header.contentType(contentType));
return this;
}
@Override
public ResponseBuilderMessageBody messageBody(ByteSource source) {
body = MessageBody.ofByteSource(source);
return this;
}
@Override
public ResponseBuilderMessageBody messageBody(String text) {
body = MessageBody.ofString(text);
return this;
}
@Override
public ResponseBuilderHeaders sayError() {
status = StatusCode._500_INTERNAL_SERVER_ERROR;
return this;
}
@Override
public ResponseBuilderHeaders sayNotFound() {
status = StatusCode._404_NOT_FOUND;
return this;
}
@Override
public ResponseBuilderHeaders sayOk() {
status = StatusCode._200_OK;
return this;
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy