001/* 002 * JGrapes Event Driven Framework 003 * Copyright (C) 2016-2018 Michael N. Lipp 004 * 005 * This program is free software; you can redistribute it and/or modify it 006 * under the terms of the GNU Affero General Public License as published by 007 * the Free Software Foundation; either version 3 of the License, or 008 * (at your option) any later version. 009 * 010 * This program is distributed in the hope that it will be useful, but 011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 013 * for more details. 014 * 015 * You should have received a copy of the GNU Affero General Public License along 016 * with this program; if not, see <http://www.gnu.org/licenses/>. 017 */ 018 019package org.jgrapes.http.events; 020 021import java.nio.charset.Charset; 022import java.util.Map.Entry; 023import java.util.Optional; 024import java.util.stream.Stream; 025import org.jdrupes.httpcodec.MessageHeader; 026import org.jdrupes.httpcodec.protocols.http.HttpField; 027import org.jdrupes.httpcodec.protocols.http.HttpResponse; 028import org.jdrupes.httpcodec.types.Converters; 029 030/** 031 * Represents the response (header). 032 */ 033public class Response extends MessageReceived<Void> { 034 035 @SuppressWarnings("PMD.AvoidFieldNameMatchingTypeName") 036 private final MessageHeader response; 037 038 /** 039 * Instantiates a new response. 040 * 041 * @param response the response 042 */ 043 public Response(MessageHeader response) { 044 this.response = response; 045 } 046 047 /** 048 * @return the response 049 */ 050 public MessageHeader response() { 051 return response; 052 } 053 054 /** 055 * Convenience method for retrieving the {@link Charset} 056 * from the response. 057 * 058 * @return the optional 059 */ 060 @SuppressWarnings("PMD.AvoidCatchingGenericException") 061 public Optional<Charset> charset() { 062 return ((HttpResponse) response()) 063 .findValue(HttpField.CONTENT_TYPE, Converters.MEDIA_TYPE) 064 .map(mt -> mt.parameters().entrySet().stream()) 065 .orElse(Stream.empty()) 066 .filter(e -> "charset".equalsIgnoreCase(e.getKey())) 067 .findFirst().map(Entry::getValue).map(csn -> { 068 try { 069 return Charset.forName(csn); 070 } catch (Exception e) { 071 return null; 072 } 073 }); 074 } 075 076}