Search in sources :

Example 1 with HttpRequest

use of jp.ossc.nimbus.service.http.HttpRequest 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 HttpRequest

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

the class HttpResponseImplTest method testSetHttpMethod.

/**
 * HTTPメソッドを設定するテスト。
 * <p>
 * 条件:
 * <ul>
 * <li>定義ファイルをロードし、HttpClientFactoryServiceインスタンスを生成する</li>
 * <li>HttpRequestImpl#createRequest(論理アクション名)を実行し、HttpRequestを生成</li>
 * <li>生成したHttpRequestを指定して、HttpClientImpl#createHttpMethod()を実行</li>
 * <li>生成したMethodを指定して、HttpResponseImpl#setHttpMethod()を実行</li>
 * </ul>
 * 確認:
 * <ul>
 * <li>正常終了することを確認</li>
 * </ul>
 */
public void testSetHttpMethod() {
    try {
        if (!ServiceManagerFactory.loadManager("jp/ossc/nimbus/service/http/httpclient/service-clientTest.xml")) {
            System.exit(-1);
        }
        final HttpClientFactory factory = (HttpClientFactory) ServiceManagerFactory.getServiceObject("HttpClientFactory");
        HttpClientImpl client = (HttpClientImpl) factory.createHttpClient();
        HttpRequest request = factory.createRequest("login");
        HttpRequestImpl rec = (HttpRequestImpl) request;
        HttpMethodBase method = rec.createHttpMethod();
        client.client.executeMethod(method);
        HttpResponseImpl res = new HttpResponseImpl();
        res.setHttpMethod(method);
    } catch (Exception e) {
        e.printStackTrace();
        fail("例外発生");
    } finally {
        ServiceManagerFactory.unloadManager("jp/ossc/nimbus/service/http/httpclient/service-clientTest.xml");
    }
}
Also used : HttpRequest(jp.ossc.nimbus.service.http.HttpRequest) HttpMethodBase(org.apache.commons.httpclient.HttpMethodBase) HttpClientImpl(jp.ossc.nimbus.service.http.httpclient.HttpClientFactoryService.HttpClientImpl) HttpClientFactory(jp.ossc.nimbus.service.http.HttpClientFactory) ConvertException(jp.ossc.nimbus.util.converter.ConvertException) PropertySchemaDefineException(jp.ossc.nimbus.beans.dataset.PropertySchemaDefineException)

Example 3 with HttpRequest

use of jp.ossc.nimbus.service.http.HttpRequest 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 4 with HttpRequest

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

the class HttpResponseImplTest method testGetHeaderMapNull.

/**
 * ヘッダー情報を取得するテスト。
 * <p>
 * 条件:
 * <ul>
 * <li>定義ファイルをロードし、HttpClientFactoryServiceインスタンスを生成する</li>
 * <li>HttpRequestImpl#createRequest(論理アクション名)を実行し、HttpRequestを生成</li>
 * <li>HttpRequestImpl#executeRequest()を実行し、HttpResponseを生成</li>
 * <li>レスポンスのヘッダーにContent-Type=text/html;charset=Shift_JISが含まれている</li>
 * <li>HttpResponseImpl#getHeader(),getHeaders()を実行</li>
 * </ul>
 * 確認:
 * <ul>
 * <li>HttpResponseImpl#getHeader(),getHeaders()が正しい結果が返されることを確認</li>
 * </ul>
 */
public void testGetHeaderMapNull() {
    try {
        if (!ServiceManagerFactory.loadManager("jp/ossc/nimbus/service/http/httpclient/service-clientTest.xml")) {
            System.exit(-1);
        }
        final HttpClientFactory factory = (HttpClientFactory) ServiceManagerFactory.getServiceObject("HttpClientFactory");
        HttpClientImpl client = (HttpClientImpl) factory.createHttpClient();
        DataSet requestDs = new DataSet("Login");
        requestDs.setHeaderSchema("UserInfo", ":name,java.lang.String,,,\n" + ":age,int,,,");
        Header userInfo = requestDs.getHeader("UserInfo");
        userInfo.setProperty("name", "hoge");
        userInfo.setProperty("age", 25);
        HttpRequest request = factory.createRequest("login");
        request.setObject(requestDs);
        HttpResponseImpl res = (HttpResponseImpl) client.executeRequest(request);
        assertEquals("text/html;charset=Shift_JIS", res.getHeader("Content-Type"));
        assertEquals("text/html;charset=Shift_JIS", res.getHeaders("Content-Type")[0]);
    } catch (Exception e) {
        e.printStackTrace();
        fail("例外発生");
    } finally {
        ServiceManagerFactory.unloadManager("jp/ossc/nimbus/service/http/httpclient/service-clientTest.xml");
    }
}
Also used : HttpRequest(jp.ossc.nimbus.service.http.HttpRequest) Header(jp.ossc.nimbus.beans.dataset.Header) DataSet(jp.ossc.nimbus.beans.dataset.DataSet) HttpClientImpl(jp.ossc.nimbus.service.http.httpclient.HttpClientFactoryService.HttpClientImpl) HttpClientFactory(jp.ossc.nimbus.service.http.HttpClientFactory) ConvertException(jp.ossc.nimbus.util.converter.ConvertException) PropertySchemaDefineException(jp.ossc.nimbus.beans.dataset.PropertySchemaDefineException)

Example 5 with HttpRequest

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

the class HttpResponseImplTest method testGetHeaderMap.

/**
 * ヘッダー情報を取得するテスト。
 * <p>
 * 条件:
 * <ul>
 * <li>定義ファイルをロードし、HttpClientFactoryServiceインスタンスを生成する</li>
 * <li>HttpRequestImpl#createRequest(論理アクション名)を実行し、HttpRequestを生成</li>
 * <li>HttpRequestImpl#executeRequest()を実行し、HttpResponseを生成</li>
 * <li>レスポンスのヘッダーにContent-Type=text/html;charset=Shift_JISが含まれている</li>
 * <li>HttpResponseImpl#getHeadermap()を実行してmapを生成</li>
 * <li>HttpResponseImpl#getHeader(),getHeaders()を実行</li>
 * </ul>
 * 確認:
 * <ul>
 * <li>HttpResponseImpl#getHeader(),getHeaders()が正しい結果が返されることを確認</li>
 * </ul>
 */
public void testGetHeaderMap() {
    try {
        if (!ServiceManagerFactory.loadManager("jp/ossc/nimbus/service/http/httpclient/service-clientTest.xml")) {
            System.exit(-1);
        }
        final HttpClientFactory factory = (HttpClientFactory) ServiceManagerFactory.getServiceObject("HttpClientFactory");
        HttpClientImpl client = (HttpClientImpl) factory.createHttpClient();
        DataSet requestDs = new DataSet("Login");
        requestDs.setHeaderSchema("UserInfo", ":name,java.lang.String,,,\n" + ":age,int,,,");
        Header userInfo = requestDs.getHeader("UserInfo");
        userInfo.setProperty("name", "hoge");
        userInfo.setProperty("age", 25);
        HttpRequest request = factory.createRequest("login");
        request.setObject(requestDs);
        HttpResponseImpl res = (HttpResponseImpl) client.executeRequest(request);
        res.getHeaderMap();
        assertEquals("text/html;charset=Shift_JIS", res.getHeader("Content-Type"));
        assertEquals("text/html;charset=Shift_JIS", res.getHeaders("Content-Type")[0]);
    } catch (Exception e) {
        e.printStackTrace();
        fail("例外発生");
    } finally {
        ServiceManagerFactory.unloadManager("jp/ossc/nimbus/service/http/httpclient/service-clientTest.xml");
    }
}
Also used : HttpRequest(jp.ossc.nimbus.service.http.HttpRequest) Header(jp.ossc.nimbus.beans.dataset.Header) DataSet(jp.ossc.nimbus.beans.dataset.DataSet) HttpClientImpl(jp.ossc.nimbus.service.http.httpclient.HttpClientFactoryService.HttpClientImpl) HttpClientFactory(jp.ossc.nimbus.service.http.HttpClientFactory) ConvertException(jp.ossc.nimbus.util.converter.ConvertException) PropertySchemaDefineException(jp.ossc.nimbus.beans.dataset.PropertySchemaDefineException)

Aggregations

HttpRequest (jp.ossc.nimbus.service.http.HttpRequest)7 PropertySchemaDefineException (jp.ossc.nimbus.beans.dataset.PropertySchemaDefineException)3 HttpClient (jp.ossc.nimbus.service.http.HttpClient)3 HttpClientFactory (jp.ossc.nimbus.service.http.HttpClientFactory)3 HttpResponse (jp.ossc.nimbus.service.http.HttpResponse)3 HttpClientImpl (jp.ossc.nimbus.service.http.httpclient.HttpClientFactoryService.HttpClientImpl)3 ConvertException (jp.ossc.nimbus.util.converter.ConvertException)3 InputStream (java.io.InputStream)2 Iterator (java.util.Iterator)2 Map (java.util.Map)2 DataSet (jp.ossc.nimbus.beans.dataset.DataSet)2 Header (jp.ossc.nimbus.beans.dataset.Header)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