2 * jSite2 - FcpMessage.java -
3 * Copyright © 2008 David Roden
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 package net.pterodactylus.util.fcp;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.OutputStream;
25 import java.util.Collections;
26 import java.util.HashMap;
27 import java.util.Iterator;
29 import java.util.Map.Entry;
31 import net.pterodactylus.util.io.StreamCopier;
36 * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
39 public class FcpMessage implements Iterable<String> {
41 private static final String LINEFEED = "\r\n";
43 private final String name;
44 private final Map<String, String> fields = new HashMap<String, String>();
45 private InputStream dataInputStream;
47 public FcpMessage(String name) {
51 public FcpMessage(String name, InputStream dataInputStream) {
53 this.dataInputStream = dataInputStream;
56 public String getName() {
60 public void setField(String field, String value) {
61 if ((field == null) || (value == null)) {
62 throw new NullPointerException(((field == null) ? "field " : "value ") + "must not be null");
64 fields.put(field, value);
67 public String getField(String field) {
68 return fields.get(field);
71 public Map<String, String> getFields() {
72 return Collections.unmodifiableMap(fields);
78 public Iterator<String> iterator() {
79 return fields.keySet().iterator();
82 public void setDataInputStream(InputStream dataInputStream) {
83 this.dataInputStream = dataInputStream;
86 public void write(OutputStream outputStream) throws IOException {
87 writeLine(outputStream, name);
88 for (Entry<String, String> fieldEntry: fields.entrySet()) {
89 writeLine(outputStream, fieldEntry.getKey() + "=" + fieldEntry.getValue());
91 writeLine(outputStream, "EndMessage");
93 if (dataInputStream != null) {
94 StreamCopier.copy(dataInputStream, outputStream);
99 private void writeLine(OutputStream outputStream, String line) throws IOException {
100 outputStream.write((line + LINEFEED).getBytes("UTF-8"));