Search in sources :

Example 1 with StreamConverter

use of jp.ossc.nimbus.util.converter.StreamConverter 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 2 with StreamConverter

use of jp.ossc.nimbus.util.converter.StreamConverter 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 3 with StreamConverter

use of jp.ossc.nimbus.util.converter.StreamConverter 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

StreamConverter (jp.ossc.nimbus.util.converter.StreamConverter)3 StreamStringConverter (jp.ossc.nimbus.util.converter.StreamStringConverter)3 BufferedReader (java.io.BufferedReader)2 File (java.io.File)2 InputStream (java.io.InputStream)2 BindingStreamConverter (jp.ossc.nimbus.util.converter.BindingStreamConverter)2 FormatConverter (jp.ossc.nimbus.util.converter.FormatConverter)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 FileInputStream (java.io.FileInputStream)1 FileOutputStream (java.io.FileOutputStream)1 InputStreamReader (java.io.InputStreamReader)1 OutputStreamWriter (java.io.OutputStreamWriter)1 PrintWriter (java.io.PrintWriter)1 StringWriter (java.io.StringWriter)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 GZIPInputStream (java.util.zip.GZIPInputStream)1 InflaterInputStream (java.util.zip.InflaterInputStream)1