All Downloads are FREE. Search and download functionalities are using the official Maven repository.

br.com.objectos.http.Response Maven / Gradle / Ivy

/*
 * 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.http;

import java.io.IOException;
import java.util.List;

import br.com.objectos.core.util.ImmutableList;

/**
 * @author [email protected] (Marcio Endo)
 */
public abstract class Response {

  private final StatusCode status;
  private final List
headerList; Response(StatusCode status, List
headerList) { this.status = status; this.headerList = headerList; } public static Builder ok() { return new Builder(StatusCode._200_OK); } public static Builder notFound() { return new Builder(StatusCode._404_NOT_FOUND); } 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); } } public static class Builder { private final StatusCode status; private final ImmutableList.Builder
headerList = ImmutableList.builder(); private String body; private Builder(StatusCode status) { this.status = status; } public Response build() { return body != null ? new TextResponse(status, headerList.build(), body) : new SimpleResponse(status, headerList.build()); } public Builder header(Header header) { headerList.add(header); return this; } public Builder body(String body) { this.body = body; return this; } } private static class SimpleResponse extends Response { public SimpleResponse(StatusCode status, List
headerList) { super(status, headerList); } } private static class TextResponse extends Response { private final String text; public TextResponse(StatusCode status, List
headerList, String text) { super(status, headerList); this.text = text; } @Override public void respond(SocketWriter writer) throws IOException { super.respond(writer); writer.newLine(); writer.newLine(); writer.writeString(text); } } }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy