001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.util;
019
020import static org.junit.Assert.assertEquals;
021
022import java.io.BufferedReader;
023import java.io.IOException;
024import java.io.InputStreamReader;
025import java.net.HttpURLConnection;
026import java.net.URL;
027import org.apache.hadoop.hbase.LocalHBaseCluster;
028
029public class TestServerHttpUtils {
030  private static final String PLAIN_TEXT_UTF8 = "text/plain;charset=utf-8";
031
032  private TestServerHttpUtils() {
033  }
034
035  public static String getMasterInfoServerHostAndPort(LocalHBaseCluster cluster) {
036    return "http://localhost:" + cluster.getActiveMaster().getInfoServer().getPort();
037  }
038
039  public static String getPageContent(URL url, String mimeType) throws IOException {
040    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
041    conn.connect();
042
043    assertEquals(200, conn.getResponseCode());
044    assertEquals(mimeType, conn.getContentType());
045
046    return TestServerHttpUtils.getResponseBody(conn);
047  }
048
049  public static String getMasterPageContent(LocalHBaseCluster cluster) throws IOException {
050    URL debugDumpUrl = new URL(getMasterInfoServerHostAndPort(cluster) + "/dump");
051    return getPageContent(debugDumpUrl, PLAIN_TEXT_UTF8);
052  }
053
054  public static String getRegionServerPageContent(String hostName, int port) throws IOException {
055    URL debugDumpUrl = new URL("http://" + hostName + ":" + port + "/dump");
056    return getPageContent(debugDumpUrl, PLAIN_TEXT_UTF8);
057  }
058
059  private static String getResponseBody(HttpURLConnection conn) throws IOException {
060    StringBuilder sb = new StringBuilder();
061    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
062    String output;
063    while ((output = br.readLine()) != null) {
064      sb.append(output);
065    }
066    return sb.toString();
067  }
068}