import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
public class MetadataStripper {
/**
* Strips metadata from response headers.
*
* @param responseHeaders A map of response headers.
* @param stripFlags A string containing flags to control stripping behavior.
* Valid flags: "user-agent", "content-length", "date", "server", "cache-control", "transfer-encoding", "content-type", "location", "etag", "last-modified"
* @return A map of stripped response headers. Returns an empty map if input is null.
*/
public static Map<String, String> stripMetadata(Map<String, String> responseHeaders, String stripFlags) {
if (responseHeaders == null) {
return new HashMap<>();
}
Map<String, String> strippedHeaders = new HashMap<>();
if (stripFlags == null || stripFlags.isEmpty()) {
return responseHeaders; // No flags, return original headers
}
String[] flags = stripFlags.split(",");
for (String flag : flags) {
String trimmedFlag = flag.trim(); // remove leading/trailing whitespace
if (trimmedFlag.equalsIgnoreCase("user-agent") || trimmedFlag.equalsIgnoreCase("content-length") || trimmedFlag.equalsIgnoreCase("date") || trimmedFlag.equalsIgnoreCase("server") || trimmedFlag.equalsIgnoreCase("cache-control") || trimmedFlag.equalsIgnoreCase("transfer-encoding") || trimmedFlag.equalsIgnoreCase("content-type") || trimmedFlag.equalsIgnoreCase("location") || trimmedFlag.equalsIgnoreCase("etag") || trimmedFlag.equalsIgnoreCase("last-modified")) {
strippedHeaders.put(trimmedFlag, null); // Set value to null to effectively remove the header
}
}
return strippedHeaders;
}
public static void main(String[] args) throws IOException {
// Example Usage
Map<String, String> headers = new HashMap<>();
headers.put("User-Agent", "MyUserAgent");
headers.put("Content-Length", "1234");
headers.put("Date", "Thu, 26 Oct 2023 10:00:00 GMT");
headers.put("Server", "Apache/2.4.41");
headers.put("Cache-Control", "no-cache");
headers.put("Content-Type", "text/html");
String stripFlags = "user-agent,content-length,date";
Map<String, String> stripped = stripMetadata(headers, stripFlags);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
for (Map.Entry<String, String> entry : stripped.entrySet()) {
pw.println(entry.getKey() + ": " + entry.getValue());
}
System.out.println(sw.toString());
}
}
Add your comment