Skip to content

Commit

Permalink
Add convenience method.
Browse files Browse the repository at this point in the history
  • Loading branch information
mnlipp committed May 2, 2024
1 parent dc4c714 commit cb8c255
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions org.jgrapes.http/src/org/jgrapes/http/events/Response.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,13 @@

package org.jgrapes.http.events;

import java.nio.charset.Charset;
import java.util.Optional;
import java.util.stream.Stream;
import org.jdrupes.httpcodec.MessageHeader;
import org.jdrupes.httpcodec.protocols.http.HttpField;
import org.jdrupes.httpcodec.protocols.http.HttpResponse;
import org.jdrupes.httpcodec.types.Converters;

/**
* Represents the response (header).
Expand All @@ -44,4 +50,25 @@ public MessageHeader response() {
return response;
}

/**
* Convenience method for retrieving the {@link Charset}
* from the response.
*
* @return the optional
*/
public Optional<Charset> charset() {
return ((HttpResponse) response())
.findValue(HttpField.CONTENT_TYPE, Converters.MEDIA_TYPE)
.map(mt -> mt.parameters().entrySet().stream())
.orElse(Stream.empty())
.filter(e -> "charset".equalsIgnoreCase(e.getKey()))
.findFirst().map(e -> e.getValue()).map(csn -> {
try {
return Charset.forName(csn);
} catch (Exception e) {
return null;
}
});
}

}

0 comments on commit cb8c255

Please sign in to comment.