adoroszlai commented on code in PR #9126:
URL: https://github.com/apache/ozone/pull/9126#discussion_r2445552247


##########
hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/conf/HddsConfServlet.java:
##########
@@ -69,74 +66,53 @@ public void doGet(HttpServletRequest request, 
HttpServletResponse response)
       return;
     }
 
-    String format = parseAcceptHeader(request);
-    if (FORMAT_XML.equals(format)) {
-      response.setContentType("text/xml; charset=utf-8");
-    } else if (FORMAT_JSON.equals(format)) {
-      response.setContentType("application/json; charset=utf-8");
+    HttpServletUtils.ResponseFormat format = 
HttpServletUtils.getResponseFormat(request);
+    if (format == HttpServletUtils.ResponseFormat.UNSPECIFIED) {
+      // use XML as default response format
+      format = HttpServletUtils.ResponseFormat.XML;
     }
 
+    response.setContentType(format.getContentType());
+
     String name = request.getParameter("name");
     Writer out = response.getWriter();
     String cmd = request.getParameter(COMMAND);
 
     processCommand(cmd, format, request, response, out, name);
-    out.close();
   }
 
-  private void processCommand(String cmd, String format,
-      HttpServletRequest request, HttpServletResponse response, Writer out,
-      String name)
+  private void processCommand(String cmd, HttpServletUtils.ResponseFormat 
format, HttpServletRequest request,
+                              HttpServletResponse response, Writer out, String 
name)
       throws IOException {
     try {
       if (cmd == null) {
         writeResponse(getConfFromContext(), out, format, name);
       } else {
         processConfigTagRequest(request, cmd, out);
       }
-    } catch (BadFormatException bfe) {
-      response.sendError(HttpServletResponse.SC_BAD_REQUEST, bfe.getMessage());
     } catch (IllegalArgumentException iae) {
-      response.sendError(HttpServletResponse.SC_NOT_FOUND, iae.getMessage());
+      HttpServletUtils.writeErrorResponse(HttpServletResponse.SC_NOT_FOUND, 
iae.getMessage(), format, response);
     }
   }
 
-  @VisibleForTesting
-  static String parseAcceptHeader(HttpServletRequest request) {
-    String format = request.getHeader(HttpHeaders.ACCEPT);
-    return format != null && format.contains(FORMAT_JSON) ?
-        FORMAT_JSON : FORMAT_XML;
-  }
-
   /**
    * Guts of the servlet - extracted for easy testing.
    */
-  static void writeResponse(OzoneConfiguration conf,
-      Writer out, String format, String propertyName)
-      throws IOException, IllegalArgumentException, BadFormatException {
-    if (FORMAT_JSON.equals(format)) {
+  static void writeResponse(OzoneConfiguration conf, Writer out, 
HttpServletUtils.ResponseFormat format,
+                            String propertyName)

Review Comment:
   ```suggestion
     static void writeResponse(OzoneConfiguration conf, Writer out, 
HttpServletUtils.ResponseFormat format,
         String propertyName)
   ```



##########
hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/conf/HddsConfServlet.java:
##########
@@ -69,74 +66,53 @@ public void doGet(HttpServletRequest request, 
HttpServletResponse response)
       return;
     }
 
-    String format = parseAcceptHeader(request);
-    if (FORMAT_XML.equals(format)) {
-      response.setContentType("text/xml; charset=utf-8");
-    } else if (FORMAT_JSON.equals(format)) {
-      response.setContentType("application/json; charset=utf-8");
+    HttpServletUtils.ResponseFormat format = 
HttpServletUtils.getResponseFormat(request);
+    if (format == HttpServletUtils.ResponseFormat.UNSPECIFIED) {
+      // use XML as default response format
+      format = HttpServletUtils.ResponseFormat.XML;
     }
 
+    response.setContentType(format.getContentType());
+
     String name = request.getParameter("name");
     Writer out = response.getWriter();
     String cmd = request.getParameter(COMMAND);
 
     processCommand(cmd, format, request, response, out, name);
-    out.close();
   }
 
-  private void processCommand(String cmd, String format,
-      HttpServletRequest request, HttpServletResponse response, Writer out,
-      String name)
+  private void processCommand(String cmd, HttpServletUtils.ResponseFormat 
format, HttpServletRequest request,
+                              HttpServletResponse response, Writer out, String 
name)

Review Comment:
   ```suggestion
     private void processCommand(String cmd, HttpServletUtils.ResponseFormat 
format, HttpServletRequest request,
         HttpServletResponse response, Writer out, String name)
   ```



##########
hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/utils/TestHttpServletUtils.java:
##########
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.hadoop.hdds.utils;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import jakarta.annotation.Nullable;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.stream.Stream;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.core.HttpHeaders;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+class TestHttpServletUtils {
+  public static Stream<Arguments> provideGetResponseFormatTestCases() {
+    return Stream.of(
+        Arguments.of("text/plain", HttpServletUtils.ResponseFormat.XML),
+        Arguments.of(null, HttpServletUtils.ResponseFormat.UNSPECIFIED),
+        Arguments.of("text/xml", HttpServletUtils.ResponseFormat.XML),
+        Arguments.of("application/xml", HttpServletUtils.ResponseFormat.XML),
+        Arguments.of("application/json", HttpServletUtils.ResponseFormat.JSON)
+    );
+  }
+
+  @ParameterizedTest
+  @MethodSource("provideGetResponseFormatTestCases")
+  public void testGetResponseFormat(@Nullable String contentType,
+                                    HttpServletUtils.ResponseFormat 
expectResponseFormat) {

Review Comment:
   ```suggestion
     public void testGetResponseFormat(@Nullable String contentType,
         HttpServletUtils.ResponseFormat expectResponseFormat) {
   ```



##########
hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/utils/HttpServletUtils.java:
##########
@@ -0,0 +1,170 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.hadoop.hdds.utils;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.Serializable;
+import java.io.Writer;
+import java.util.HashMap;
+import java.util.Map;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import org.apache.hadoop.hdds.server.JsonUtils;
+import org.apache.hadoop.util.XMLUtils;
+import org.apache.ratis.util.MemoizedCheckedSupplier;
+import org.apache.ratis.util.function.CheckedSupplier;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+/**
+ * Utility class for HTTP servlet operations.
+ * Provides methods for parsing request headers and writing responses.
+ */
+public final class HttpServletUtils implements Serializable {
+
+  private static final CheckedSupplier<DocumentBuilderFactory, 
ParserConfigurationException> DOCUMENT_BUILDER_FACTORY =
+      
MemoizedCheckedSupplier.valueOf(XMLUtils::newSecureDocumentBuilderFactory);
+
+  private HttpServletUtils() {
+    // Utility class, prevent instantiation
+  }
+
+  /**
+   * Get the response format from request header.
+   *
+   * @param request the HTTP servlet request
+   * @return {@link ResponseFormat#JSON} if Accept header contains 
"application/json",
+   * otherwise {@link ResponseFormat#XML} (default for backwards compatibility)
+   * @see HttpHeaders#ACCEPT
+   */
+  @VisibleForTesting
+  public static ResponseFormat getResponseFormat(HttpServletRequest request) 
throws IllegalArgumentException {
+    String format = request.getHeader(HttpHeaders.ACCEPT);
+    if (format == null) {
+      return ResponseFormat.UNSPECIFIED;
+    }
+    return format.contains(ResponseFormat.JSON.getValue()) ?
+        ResponseFormat.JSON : ResponseFormat.XML;
+  }
+
+  /**
+   * Write error response according to the specified format.
+   *
+   * @param errorMessage the error message
+   * @param format       the response format
+   * @param response     the response
+   */
+  public static void writeErrorResponse(int status, String errorMessage, 
ResponseFormat format,
+                                        HttpServletResponse response)

Review Comment:
   ```suggestion
     public static void writeErrorResponse(int status, String errorMessage, 
ResponseFormat format,
         HttpServletResponse response)
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to