Search in sources :

Example 1 with HttpResponse

use of jp.ossc.nimbus.service.http.HttpResponse in project nimbus by nimbus-org.

the class HttpTestControllerClientService method request.

private Object request(String action, Map params) throws HttpException, Exception {
    HttpClient client = httpClientFactory.createHttpClient();
    HttpRequest request = httpClientFactory.createRequest(templateAction);
    String accept = request.getHeader("Accept");
    if (accept == null) {
        request.setHeader("Accept", "application/octet-stream");
    }
    String url = request.getURL();
    request.setURL(url + (url.endsWith("/") ? "" : "/") + action);
    if (params != null) {
        Iterator entries = params.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry entry = (Map.Entry) entries.next();
            Object value = entry.getValue();
            if (value != null && value.getClass().isArray()) {
                String[] values = (String[]) value;
                for (int i = 0; i < values.length; i++) {
                    values[i] = URLEncoder.encode(values[i], urlEncodeCharacterEncoding);
                }
                request.setParameters((String) entry.getKey(), values);
            } else {
                request.setParameter((String) entry.getKey(), URLEncoder.encode((String) entry.getValue(), urlEncodeCharacterEncoding));
            }
        }
    }
    HttpResponse response = client.executeRequest(request);
    if (response.getStatusCode() != 200) {
        throw new HttpException("Illegal http status : " + response.getStatusCode());
    }
    String contentLengthStr = response.getHeader("Content-Length");
    int contentLength = 0;
    if (contentLengthStr != null) {
        contentLength = Integer.parseInt(contentLengthStr);
    }
    if (contentLength == 0) {
        return null;
    } else {
        String contentTypeStr = response.getHeader("Content-Type");
        if (contentTypeStr == null) {
            throw new HttpException("Content-Type is null.");
        }
        final MediaType mediaType = new MediaType(contentTypeStr);
        InputStream is = response.getInputStream();
        if ("application/octet-stream".equals(mediaType.getMediaType())) {
            ObjectInputStream ois = new ObjectInputStream(is);
            Object responseObj = ois.readObject();
            if (responseObj instanceof Exception) {
                throw (Exception) responseObj;
            } else {
                return responseObj;
            }
        } else if ("application/zip".equals(mediaType.getMediaType())) {
            return new Object[] { mediaType.getParameter("name"), is };
        } else {
            throw new HttpException("Unsupported Content-Type : " + mediaType.getMediaType());
        }
    }
}
Also used : HttpRequest(jp.ossc.nimbus.service.http.HttpRequest) ZipInputStream(java.util.zip.ZipInputStream) ObjectInputStream(java.io.ObjectInputStream) InputStream(java.io.InputStream) HttpResponse(jp.ossc.nimbus.service.http.HttpResponse) HttpException(jp.ossc.nimbus.service.http.HttpException) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException) ZipEntry(java.util.zip.ZipEntry) HttpClient(jp.ossc.nimbus.service.http.HttpClient) Iterator(java.util.Iterator) HttpException(jp.ossc.nimbus.service.http.HttpException) HashMap(java.util.HashMap) Map(java.util.Map) ObjectInputStream(java.io.ObjectInputStream)

Example 2 with HttpResponse

use of jp.ossc.nimbus.service.http.HttpResponse in project nimbus by nimbus-org.

the class HttpRequestActionService method execute.

/**
 * HTTPリクエストを送信して、HTTPレスポンスをファイルに出力する。<p>
 *
 * @param context コンテキスト
 * @param actionId アクションID
 * @param preResult 1つ前のアクションの戻り値
 * @param resource リソース
 * @return JMXでMBeanを呼び出した戻り値
 * @return Map。キー"client"で、HttpClientオブジェクト。キー"response"で、HttpResponse。
 */
public Object execute(TestContext context, String actionId, Object preResult, Reader resource) throws Exception {
    BufferedReader br = new BufferedReader(resource);
    Map result = new LinkedHashMap();
    try {
        final String clientId = br.readLine();
        if (clientId == null) {
            throw new Exception("Unexpected EOF on clientId");
        }
        HttpClient client = null;
        if (clientId.length() == 0) {
            if (preResult != null && (preResult instanceof Map)) {
                client = (HttpClient) ((Map) preResult).get("client");
            } else {
                client = httpClientFactory.createHttpClient();
            }
        } else {
            Object actionResult = null;
            if (clientId.indexOf(",") == -1) {
                actionResult = context.getTestActionResult(clientId);
            } else {
                String[] ids = clientId.split(",");
                if (ids.length != 2) {
                    throw new Exception("Illegal clientId format. id=" + clientId);
                }
                actionResult = context.getTestActionResult(ids[0], ids[1]);
            }
            if (actionResult == null) {
                throw new Exception("TestActionResult not found. id=" + clientId);
            }
            if (actionResult == null || !(actionResult instanceof Map)) {
                throw new Exception("TestActionResult is not Map. result=" + actionResult);
            }
            client = (HttpClient) ((Map) actionResult).get("client");
        }
        result.put("client", client);
        final String actionName = br.readLine();
        if (actionName == null) {
            throw new Exception("Unexpected EOF on actionName");
        }
        HttpRequest request = httpClientFactory.createRequest(actionName);
        String line = null;
        Map replaceMap = null;
        while ((line = br.readLine()) != null && line.length() != 0) {
            int index = line.lastIndexOf("->");
            if (index == -1) {
                break;
            }
            if (replaceMap == null) {
                replaceMap = new LinkedHashMap();
            }
            String replaceValueId = line.substring(0, index);
            Object replaceValue = null;
            if (replaceValueId != null && replaceValueId.length() != 0) {
                if (replaceValueId.indexOf(",") == -1) {
                    replaceValue = context.getTestActionResult(replaceValueId);
                } else {
                    String[] ids = replaceValueId.split(",");
                    if (ids.length != 2) {
                        throw new Exception("Illegal replaceValueId format. id=" + replaceValueId);
                    }
                    replaceValue = context.getTestActionResult(ids[0], ids[1]);
                }
            }
            replaceMap.put(line.substring(index + 2), replaceValue == null ? "" : replaceValue.toString());
        }
        if (line != null && line.length() == 0) {
            line = br.readLine();
        }
        String bodyType = null;
        do {
            int index = line.indexOf(":");
            if (index == -1) {
                bodyType = line;
                break;
            }
            request.setHeader(line.substring(0, index), replace(line.substring(index + 1), replaceMap));
        } while ((line = br.readLine()) != null && line.length() != 0);
        if (line != null && bodyType == null) {
            bodyType = br.readLine();
        }
        if (bodyType != null) {
            if ("parameter".equals(bodyType)) {
                while ((line = br.readLine()) != null && line.length() != 0) {
                    int index = line.indexOf("=");
                    if (index == -1) {
                        throw new Exception("Illegal parameter format. parameter=" + line);
                    }
                    request.setParameter(line.substring(0, index), replace(line.substring(index + 1), replaceMap));
                }
            } else if ("text".equals(bodyType)) {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                String text = null;
                try {
                    while ((line = br.readLine()) != null) {
                        pw.println(line);
                    }
                    pw.flush();
                    text = sw.toString();
                } finally {
                    sw.close();
                    pw.close();
                }
                if (request.getCharacterEncoding() != null) {
                    request.getOutputStream().write(replace(text, replaceMap).getBytes(request.getCharacterEncoding()));
                } else {
                    text = replace(text, replaceMap);
                    request.getOutputStream().write(request.getCharacterEncoding() == null ? text.getBytes() : text.getBytes(request.getCharacterEncoding()));
                }
            } else if ("binary".equals(bodyType)) {
                String filePath = br.readLine();
                if (filePath == null) {
                    throw new Exception("Unexpected EOF on body");
                }
                File binaryFile = new File(filePath);
                if (!binaryFile.exists()) {
                    binaryFile = new File(context.getCurrentDirectory(), filePath);
                }
                if (!binaryFile.exists()) {
                    throw new Exception("File of body not found: " + filePath);
                }
                final FileInputStream fis = new FileInputStream(binaryFile);
                try {
                    byte[] bytes = new byte[1024];
                    int len = 0;
                    while ((len = fis.read(bytes)) > 0) {
                        request.getOutputStream().write(bytes, 0, len);
                    }
                } finally {
                    fis.close();
                }
            } else if ("object".equals(bodyType)) {
                if (interpreter == null) {
                    throw new UnsupportedOperationException("Interpreter is null.");
                }
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                String script = null;
                try {
                    while ((line = br.readLine()) != null) {
                        pw.println(line);
                    }
                    pw.flush();
                    script = sw.toString();
                } finally {
                    sw.close();
                    pw.close();
                }
                script = replace(script, replaceMap);
                Object requestObject = interpreter.evaluate(script);
                request.setObject(requestObject);
            } else if ("multipart".equals(bodyType)) {
                while ((line = br.readLine()) != null && line.length() != 0) {
                    int index = line.indexOf("=");
                    if (index == -1) {
                        throw new Exception("Illegal parameter format. parameter=" + line);
                    }
                    if (line.startsWith("file:")) {
                        String paramName = line.substring(5, index);
                        final String[] params = CSVReader.toArray(line.substring(index + 1), ',', '\\', '"', "", null, true, false, true, false);
                        String filePath = params[0];
                        String fileName = (params.length > 1 && params[1].length() != 0) ? params[1] : null;
                        String contentType = (params.length > 2 && params[2].length() != 0) ? params[2] : null;
                        File file = new File(filePath);
                        if (!file.exists()) {
                            file = new File(context.getCurrentDirectory(), filePath);
                        }
                        request.setFileParameter(paramName, file, fileName, contentType);
                    } else {
                        request.setParameter(line.substring(0, index), replace(line.substring(index + 1), replaceMap));
                    }
                }
            } else {
                throw new Exception("Unknown bodyType : " + bodyType);
            }
        }
        HttpResponse response = client.executeRequest(request);
        result.put("response", response);
        final File responseHeaderFile = new File(context.getCurrentDirectory(), actionId + ".h.rsp");
        PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(responseHeaderFile))));
        try {
            pw.println(response.getStatusCode());
            pw.println(response.getStatusMessage());
            final Iterator headerNames = response.getHeaderNameSet().iterator();
            while (headerNames.hasNext()) {
                final String headerName = (String) headerNames.next();
                final String[] values = response.getHeaders(headerName);
                pw.print(headerName);
                pw.print(": ");
                for (int i = 0, imax = values.length; i < imax; i++) {
                    pw.print(values[i]);
                    if (i == imax - 1) {
                        pw.println();
                    } else {
                        pw.print("; ");
                    }
                }
            }
            pw.flush();
        } finally {
            pw.close();
            pw = null;
        }
        final File responseBodyFile = new File(context.getCurrentDirectory(), actionId + ".b.rsp");
        final InputStream is = response.getInputStream();
        FileOutputStream fos = new FileOutputStream(responseBodyFile);
        try {
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = is.read(bytes)) > 0) {
                fos.write(bytes, 0, len);
            }
        } finally {
            fos.close();
            fos = null;
        }
    } finally {
        br.close();
    }
    return result;
}
Also used : HttpRequest(jp.ossc.nimbus.service.http.HttpRequest) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) HttpResponse(jp.ossc.nimbus.service.http.HttpResponse) FileInputStream(java.io.FileInputStream) LinkedHashMap(java.util.LinkedHashMap) BufferedWriter(java.io.BufferedWriter) StringWriter(java.io.StringWriter) HttpClient(jp.ossc.nimbus.service.http.HttpClient) FileOutputStream(java.io.FileOutputStream) BufferedReader(java.io.BufferedReader) Iterator(java.util.Iterator) OutputStreamWriter(java.io.OutputStreamWriter) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) File(java.io.File) PrintWriter(java.io.PrintWriter)

Example 3 with HttpResponse

use of jp.ossc.nimbus.service.http.HttpResponse in project nimbus by nimbus-org.

the class HttpKeepAliveCheckerService method checkAlive.

public boolean checkAlive() throws Exception {
    HttpClient client = httpClientFactory.createHttpClient();
    HttpRequest request = httpClientFactory.createRequest(checkTargetRequestName);
    try {
        HttpResponse response = client.executeRequest(request);
        if (response.getStatusCode() == 200) {
            if (assertString != null) {
                String responseBody = (String) response.getObject();
                if (assertString.equals(responseBody)) {
                    return true;
                }
            } else {
                return true;
            }
        }
    } catch (HttpClientConnectTimeoutException e) {
    } catch (HttpClientSocketTimeoutException e) {
    }
    return false;
}
Also used : HttpRequest(jp.ossc.nimbus.service.http.HttpRequest) HttpClient(jp.ossc.nimbus.service.http.HttpClient) HttpClientConnectTimeoutException(jp.ossc.nimbus.service.http.httpclient.HttpClientConnectTimeoutException) HttpResponse(jp.ossc.nimbus.service.http.HttpResponse) HttpClientSocketTimeoutException(jp.ossc.nimbus.service.http.httpclient.HttpClientSocketTimeoutException)

Aggregations

HttpClient (jp.ossc.nimbus.service.http.HttpClient)3 HttpRequest (jp.ossc.nimbus.service.http.HttpRequest)3 HttpResponse (jp.ossc.nimbus.service.http.HttpResponse)3 InputStream (java.io.InputStream)2 Iterator (java.util.Iterator)2 Map (java.util.Map)2 BufferedReader (java.io.BufferedReader)1 BufferedWriter (java.io.BufferedWriter)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 FileOutputStream (java.io.FileOutputStream)1 ObjectInputStream (java.io.ObjectInputStream)1 OutputStreamWriter (java.io.OutputStreamWriter)1 PrintWriter (java.io.PrintWriter)1 StringWriter (java.io.StringWriter)1 UndeclaredThrowableException (java.lang.reflect.UndeclaredThrowableException)1 HashMap (java.util.HashMap)1 LinkedHashMap (java.util.LinkedHashMap)1 ZipEntry (java.util.zip.ZipEntry)1 ZipInputStream (java.util.zip.ZipInputStream)1