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;
}
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;
}
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;
}
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);
}
}
Aggregations