Search in sources :

Example 1 with StreamStringConverter

use of jp.ossc.nimbus.util.converter.StreamStringConverter in project nimbus by nimbus-org.

the class BeanFlowRestServerService method processReadRequestBody.

protected boolean processReadRequestBody(RestRequest request, RestResponse response, List paths, ResourceMetaData resource) throws Exception {
    String contentType = request.request.getHeader(HTTP_HEADER_NAME_CONTENT_TYPE);
    BindingStreamConverter requestConverter = null;
    if (contentType == null) {
        if (requestConverterMapping != null) {
            requestConverter = (BindingStreamConverter) requestConverterMapping.values().iterator().next();
        }
    } else {
        final MediaType mediaType = new MediaType(contentType);
        if (requestConverterMapping != null) {
            requestConverter = (BindingStreamConverter) requestConverterMapping.get(mediaType.getMediaType());
        }
    }
    if (requestConverter == null) {
        return processReadParameter(request, response, paths, resource);
    } else if (request.getRequestObject() != null) {
        String encode = null;
        if (requestConverter instanceof StreamStringConverter) {
            if (request.getRequest().getCharacterEncoding() != null && !request.getRequest().getCharacterEncoding().equals(((StreamStringConverter) requestConverter).getCharacterEncodingToObject())) {
                requestConverter = (BindingStreamConverter) ((StreamStringConverter) requestConverter).cloneCharacterEncodingToObject(request.getRequest().getCharacterEncoding());
            }
            encode = ((StreamStringConverter) requestConverter).getCharacterEncodingToObject();
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ByteArrayInputStream bais = null;
        try {
            final ServletInputStream sis = request.getRequest().getInputStream();
            byte[] bytes = new byte[2048];
            try {
                int size = 0;
                while ((size = sis.read(bytes)) != -1) {
                    baos.write(bytes, 0, size);
                }
            } finally {
                if (sis != null) {
                    sis.close();
                }
                bytes = null;
            }
            decompress(request.getRequest(), baos);
            if (journal != null) {
                Object requestBody = null;
                if (encode == null) {
                    requestBody = baos.toByteArray();
                } else {
                    try {
                        requestBody = new String(baos.toByteArray(), encode);
                    } catch (UnsupportedEncodingException e) {
                        requestBody = baos.toByteArray();
                    }
                }
                journal.addInfo(JOURNAL_KEY_REQUEST_BODY, requestBody);
            }
            bais = new ByteArrayInputStream(baos.toByteArray());
            baos = null;
            request.setRequestObject(requestConverter.convertToObject(bais, request.getRequestObject()));
        } catch (ConvertException e) {
            getLogger().write("BFRS_00018", new Object[] { resource.resourcePath.path, request.getRequestObject().getClass().getName() }, e);
            if (journal != null) {
                journal.addInfo(JOURNAL_KEY_EXCEPTION, e);
            }
            response.setResult(HttpServletResponse.SC_BAD_REQUEST);
            return false;
        } finally {
            if (bais != null) {
                try {
                    bais.close();
                } catch (IOException e) {
                }
            }
        }
    }
    return true;
}
Also used : BindingStreamConverter(jp.ossc.nimbus.util.converter.BindingStreamConverter) ServletInputStream(javax.servlet.ServletInputStream) ConvertException(jp.ossc.nimbus.util.converter.ConvertException) ByteArrayInputStream(java.io.ByteArrayInputStream) StreamStringConverter(jp.ossc.nimbus.util.converter.StreamStringConverter) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException)

Example 2 with StreamStringConverter

use of jp.ossc.nimbus.util.converter.StreamStringConverter in project nimbus by nimbus-org.

the class BeanFlowRestServerService method processWriteResponseBody.

protected boolean processWriteResponseBody(RestRequest request, RestResponse response, List paths, ResourceMetaData resource) throws Exception {
    Object responseObject = response.getResponseObject();
    if (responseObject == null) {
        return true;
    }
    if (journal != null) {
        journal.addInfo(JOURNAL_KEY_RESPONSE_OBJECT, responseObject);
    }
    String acceptStr = request.request.getHeader(HTTP_HEADER_NAME_ACCEPT);
    StreamConverter responseConverter = null;
    String mediaType = null;
    if (acceptStr == null) {
        mediaType = (String) responseConverterMapping.keySet().iterator().next();
        responseConverter = (StreamConverter) responseConverterMapping.get(mediaType);
    } else {
        Accept accept = null;
        try {
            accept = new Accept(acceptStr);
        } catch (IllegalArgumentException e) {
        // 事前にチェックするため起こらないはず
        }
        for (int i = 0; i < accept.mediaRanges.size(); i++) {
            MediaRange mr = (MediaRange) accept.mediaRanges.get(i);
            responseConverter = (StreamConverter) responseConverterMapping.get(mr.getMediaType());
            if (responseConverter != null) {
                mediaType = mr.getMediaType();
                break;
            }
        }
    }
    String encode = null;
    if (responseConverter instanceof StreamStringConverter) {
        if (response.getResponse().getCharacterEncoding() != null && !response.getResponse().getCharacterEncoding().equals(((StreamStringConverter) responseConverter).getCharacterEncodingToStream())) {
            responseConverter = ((StreamStringConverter) responseConverter).cloneCharacterEncodingToStream(response.getResponse().getCharacterEncoding());
        }
        encode = ((StreamStringConverter) responseConverter).getCharacterEncodingToStream();
    }
    response.getResponse().setContentType(new ContentType(mediaType, response.getResponse().getCharacterEncoding()).toString());
    InputStream is = null;
    try {
        is = responseConverter.convertToStream(responseObject);
    } catch (ConvertException e) {
        getLogger().write("BFRS_00024", new Object[] { resource.resourcePath.path, responseObject.getClass().getName() }, e);
        if (journal != null) {
            journal.addInfo(JOURNAL_KEY_EXCEPTION, e);
        }
        response.setResult(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return false;
    }
    final ServletOutputStream sos = response.getResponse().getOutputStream();
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] bytes = new byte[2048];
    int readLen = 0;
    while ((readLen = is.read(bytes)) != -1) {
        baos.write(bytes, 0, readLen);
        sos.write(bytes, 0, readLen);
    }
    if (journal != null) {
        Object responseBody = null;
        if (encode == null) {
            responseBody = baos.toByteArray();
        } else {
            try {
                responseBody = new String(baos.toByteArray(), encode);
            } catch (UnsupportedEncodingException e) {
                responseBody = baos.toByteArray();
            }
        }
        journal.addInfo(JOURNAL_KEY_RESPONSE_BODY, responseBody);
    }
    return true;
}
Also used : ConvertException(jp.ossc.nimbus.util.converter.ConvertException) ServletOutputStream(javax.servlet.ServletOutputStream) GZIPInputStream(java.util.zip.GZIPInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InflaterInputStream(java.util.zip.InflaterInputStream) ServletInputStream(javax.servlet.ServletInputStream) InputStream(java.io.InputStream) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) StreamConverter(jp.ossc.nimbus.util.converter.StreamConverter) BindingStreamConverter(jp.ossc.nimbus.util.converter.BindingStreamConverter) StreamStringConverter(jp.ossc.nimbus.util.converter.StreamStringConverter)

Example 3 with StreamStringConverter

use of jp.ossc.nimbus.util.converter.StreamStringConverter in project nimbus by nimbus-org.

the class ObjectToFileConvertActionService method execute.

/**
 * リソースの内容を読み込んで、オブジェクトをファイルに変換する。<p>
 * リソースのフォーマットは、以下。<br>
 * <pre>
 * targetObjectId
 * outputFilePath
 * format
 * </pre>
 * targetObjectIdは、変換対象となるオブジェクトを指定するもので、同一テストケース中に、このTestActionより前に、変換対象となるオブジェクトを戻すテストアクションが存在する場合は、そのアクションIDを指定する。また、同一シナリオ中に、このTestActionより前に、変換対象となるオブジェクトを戻すテストアクションが存在する場合は、テストケースIDとアクションIDをカンマ区切りで指定する。preResultを使用する場合は、空行を指定する。<br>
 * outputFilePathは、ファイルのパスを指定する。パスは、絶対パスまたは、相対パスで指定する。空行を指定した場合は、アクションIDに拡張子".obj"を付与したファイル名となる。<br>
 * formatは、設定されている{@link FormatConverter}の{@link FormatConverter#setFormat(String) setFormat(format)}に渡すフォーマット文字列を指定する。指定しない場合は、フォーマットは設定しない。<br>
 *
 * @param context コンテキスト
 * @param actionId アクションID
 * @param preResult 変換対象となるオブジェクト
 * @param resource リソース
 * @return 変換後ファイル
 */
public Object execute(TestContext context, String actionId, Object preResult, Reader resource) throws Exception {
    BufferedReader br = new BufferedReader(resource);
    File outputFile = null;
    Object targetObject = preResult;
    String format = null;
    try {
        final String targetObjectId = br.readLine();
        if (targetObjectId != null && targetObjectId.length() != 0) {
            Object actionResult = null;
            if (targetObjectId.indexOf(",") == -1) {
                actionResult = context.getTestActionResult(targetObjectId);
            } else {
                String[] ids = targetObjectId.split(",");
                if (ids.length != 2) {
                    throw new Exception("Illegal targetObjectId format. id=" + targetObjectId);
                }
                actionResult = context.getTestActionResult(ids[0], ids[1]);
            }
            if (actionResult == null) {
                throw new Exception("TestActionResult not found. id=" + targetObjectId);
            }
            targetObject = actionResult;
        }
        final String outputFilePath = br.readLine();
        if (outputFilePath == null || outputFilePath.length() == 0) {
            outputFile = new File(context.getCurrentDirectory(), actionId + ".obj");
        } else {
            outputFile = new File(outputFilePath);
            if (!outputFile.isAbsolute()) {
                outputFile = new File(context.getCurrentDirectory(), outputFilePath);
            }
            if (outputFile.getParentFile() != null && !outputFile.getParentFile().exists()) {
                outputFile.getParentFile().mkdirs();
            }
        }
        format = br.readLine();
        if (format != null && format.length() == 0) {
            format = null;
        }
    } finally {
        br.close();
        br = null;
    }
    if (streamConverter != null) {
        FileOutputStream fos = new FileOutputStream(outputFile);
        InputStream is = null;
        try {
            StreamConverter sc = streamConverter;
            if (fileEncoding != null && sc instanceof StreamStringConverter && !fileEncoding.equals(((StreamStringConverter) sc).getCharacterEncodingToStream())) {
                sc = ((StreamStringConverter) sc).cloneCharacterEncodingToStream(fileEncoding);
            }
            is = sc.convertToStream(targetObject);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = is.read(buf, 0, buf.length)) > 0) {
                fos.write(buf, 0, len);
            }
        } catch (Exception e) {
            if (targetObject == null) {
                byte[] buf = "null".getBytes();
                fos.write(buf, 0, buf.length);
            } else {
                throw e;
            }
        } finally {
            if (is != null) {
                is.close();
            }
            fos.close();
        }
    } else if (formatConverter != null) {
        FormatConverter fc = formatConverter;
        if (formatConverterServiceName != null) {
            fc = (FormatConverter) ServiceManagerFactory.getServiceObject(formatConverterServiceName);
        }
        if (format != null) {
            fc.setFormat(format);
        }
        OutputStreamWriter osw = fileEncoding == null ? new OutputStreamWriter(new FileOutputStream(outputFile)) : new OutputStreamWriter(new FileOutputStream(outputFile), fileEncoding);
        try {
            Object ret = fc.convert(targetObject);
            char[] chars = ret == null ? "null".toCharArray() : ret.toString().toCharArray();
            osw.write(chars, 0, chars.length);
        } catch (Exception e) {
            if (targetObject == null) {
                char[] chars = "null".toCharArray();
                osw.write(chars, 0, chars.length);
            } else {
                throw e;
            }
        } finally {
            osw.close();
        }
    } else {
        OutputStreamWriter osw = fileEncoding == null ? new OutputStreamWriter(new FileOutputStream(outputFile)) : new OutputStreamWriter(new FileOutputStream(outputFile), fileEncoding);
        try {
            char[] chars = targetObject == null ? "null".toCharArray() : targetObject.toString().toCharArray();
            osw.write(chars, 0, chars.length);
        } catch (Exception e) {
            if (targetObject == null) {
                char[] chars = "null".toCharArray();
                osw.write(chars, 0, chars.length);
            } else {
                throw e;
            }
        } finally {
            osw.close();
        }
    }
    return outputFile;
}
Also used : InputStream(java.io.InputStream) FormatConverter(jp.ossc.nimbus.util.converter.FormatConverter) FileOutputStream(java.io.FileOutputStream) BufferedReader(java.io.BufferedReader) StreamConverter(jp.ossc.nimbus.util.converter.StreamConverter) StreamStringConverter(jp.ossc.nimbus.util.converter.StreamStringConverter) OutputStreamWriter(java.io.OutputStreamWriter) File(java.io.File)

Example 4 with StreamStringConverter

use of jp.ossc.nimbus.util.converter.StreamStringConverter in project nimbus by nimbus-org.

the class FileToObjectConvertActionService method execute.

/**
 * リソースの内容を読み込んで、ファイルをオブジェクトに変換する。<p>
 * リソースのフォーマットは、以下。<br>
 * <pre>
 * filePath
 * bindingObjectScript|format
 * </pre>
 * filePathは、ファイルのパスを指定する。パスは、絶対パスまたは、相対パスで指定する。<br>
 * bindingObjectScriptは、設定されている{@link StreamConverter}が、{@link BindingStreamConverter}の場合に、変換後オブジェクトとしてバインドするオブジェクトを生成するスクリプトを指定する。スクリプトは、{@link Interpreter#evaluate(String,Map)}で評価され、引数の変数マップには、"context"で{@link TestContext}、"preResult"で引数のpreResultが渡される。<br>
 * formatは、設定されている{@link FormatConverter}の{@link FormatConverter#setFormat(String) setFormat(format)}に渡すフォーマット文字列を指定する。指定しない場合は、フォーマットは設定しない。<br>
 *
 * @param context コンテキスト
 * @param actionId アクションID
 * @param preResult 変換後オブジェクトとしてバインドするオブジェクト
 * @param resource リソース
 * @return 変換後オブジェクト
 */
public Object execute(TestContext context, String actionId, Object preResult, Reader resource) throws Exception {
    BufferedReader br = new BufferedReader(resource);
    File file = null;
    String bindingObjectScript = null;
    String format = null;
    try {
        final String filePath = br.readLine();
        if (filePath == null) {
            throw new Exception("Unexpected EOF on filePath");
        }
        file = new File(filePath);
        if (!file.exists()) {
            file = new File(context.getCurrentDirectory(), filePath);
        }
        if (!file.exists()) {
            throw new Exception("File not found. filePath=" + filePath);
        }
        String line = null;
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        try {
            while ((line = br.readLine()) != null) {
                pw.println(line);
            }
            pw.flush();
            if (streamConverter != null) {
                bindingObjectScript = sw.toString();
                if (bindingObjectScript.length() == 0) {
                    bindingObjectScript = null;
                }
            } else {
                format = sw.toString();
                if (format.length() == 0) {
                    format = null;
                }
            }
        } finally {
            sw.close();
            pw.close();
        }
        if (bindingObjectScript != null) {
            if (streamConverter == null) {
                throw new UnsupportedOperationException("StreamConverter is null.");
            }
            if (interpreter == null) {
                throw new UnsupportedOperationException("Interpreter is null.");
            }
            if (!(streamConverter instanceof BindingStreamConverter)) {
                throw new Exception("StreamConverter is not BindingStreamConverter. streamConverter=" + streamConverter.getClass());
            }
        }
    } finally {
        br.close();
        br = null;
    }
    if (streamConverter != null) {
        Object bindingObject = null;
        if (bindingObjectScript != null) {
            final Map params = new HashMap();
            params.put("context", context);
            params.put("preResult", preResult);
            bindingObject = interpreter.evaluate(bindingObjectScript, params);
        } else {
            bindingObject = preResult;
        }
        FileInputStream fis = new FileInputStream(file);
        try {
            StreamConverter sc = streamConverter;
            if (fileEncoding != null && sc instanceof StreamStringConverter && !fileEncoding.equals(((StreamStringConverter) sc).getCharacterEncodingToObject())) {
                sc = ((StreamStringConverter) sc).cloneCharacterEncodingToObject(fileEncoding);
            }
            if (bindingObject != null && (sc instanceof BindingStreamConverter)) {
                return ((BindingStreamConverter) sc).convertToObject(fis, bindingObject);
            } else {
                return sc.convertToObject(fis);
            }
        } finally {
            fis.close();
        }
    } else {
        InputStreamReader isr = fileEncoding == null ? new InputStreamReader(new FileInputStream(file)) : new InputStreamReader(new FileInputStream(file), fileEncoding);
        StringWriter sw = new StringWriter();
        String str = null;
        try {
            int len = 0;
            char[] buf = new char[1024];
            while ((len = isr.read(buf, 0, buf.length)) > 0) {
                sw.write(buf, 0, len);
            }
            str = sw.toString();
        } finally {
            isr.close();
            sw.close();
        }
        FormatConverter fc = formatConverter;
        if (formatConverterServiceName != null) {
            fc = (FormatConverter) ServiceManagerFactory.getServiceObject(formatConverterServiceName);
        }
        if (format != null) {
            fc.setFormat(format);
        }
        return fc.convert(str);
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) HashMap(java.util.HashMap) FormatConverter(jp.ossc.nimbus.util.converter.FormatConverter) FileInputStream(java.io.FileInputStream) BindingStreamConverter(jp.ossc.nimbus.util.converter.BindingStreamConverter) StringWriter(java.io.StringWriter) BufferedReader(java.io.BufferedReader) BindingStreamConverter(jp.ossc.nimbus.util.converter.BindingStreamConverter) StreamConverter(jp.ossc.nimbus.util.converter.StreamConverter) StreamStringConverter(jp.ossc.nimbus.util.converter.StreamStringConverter) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map) PrintWriter(java.io.PrintWriter)

Aggregations

StreamStringConverter (jp.ossc.nimbus.util.converter.StreamStringConverter)4 BindingStreamConverter (jp.ossc.nimbus.util.converter.BindingStreamConverter)3 StreamConverter (jp.ossc.nimbus.util.converter.StreamConverter)3 BufferedReader (java.io.BufferedReader)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 File (java.io.File)2 InputStream (java.io.InputStream)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 ServletInputStream (javax.servlet.ServletInputStream)2 ConvertException (jp.ossc.nimbus.util.converter.ConvertException)2 FormatConverter (jp.ossc.nimbus.util.converter.FormatConverter)2 FileInputStream (java.io.FileInputStream)1 FileOutputStream (java.io.FileOutputStream)1 IOException (java.io.IOException)1 InputStreamReader (java.io.InputStreamReader)1 OutputStreamWriter (java.io.OutputStreamWriter)1 PrintWriter (java.io.PrintWriter)1 StringWriter (java.io.StringWriter)1 HashMap (java.util.HashMap)1