use of org.codelibs.curl.CurlResponse in project fess by codelibs.
the class AdminEsreqAction method upload.
@Execute
@Secured({ ROLE })
public ActionResponse upload(final UploadForm form) {
validate(form, messages -> {
}, () -> asListHtml(null));
verifyTokenKeep(() -> asListHtml(this::saveToken));
String header = null;
final StringBuilder buf = new StringBuilder(1000);
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(form.requestFile.getInputStream(), Constants.UTF_8))) {
header = ReaderUtil.readLine(reader);
if (header == null) {
throwValidationError(messages -> messages.addErrorsInvalidHeaderForRequestFile(GLOBAL, "no header"), () -> asListHtml(this::saveToken));
// no-op
return redirect(getClass());
}
String line;
while ((line = ReaderUtil.readLine(reader)) != null) {
buf.append(line);
}
} catch (final Exception e) {
throwValidationError(messages -> messages.addErrorsFailedToReadRequestFile(GLOBAL, e.getMessage()), () -> asListHtml(this::saveToken));
}
final CurlRequest curlRequest = getCurlRequest(header);
if (curlRequest == null) {
final String msg = header;
throwValidationError(messages -> messages.addErrorsInvalidHeaderForRequestFile(GLOBAL, msg), () -> asListHtml(this::saveToken));
} else {
try (final CurlResponse response = curlRequest.body(buf.toString()).execute()) {
final File tempFile = ComponentUtil.getSystemHelper().createTempFile("esreq_", ".json");
try (final InputStream in = response.getContentAsStream()) {
CopyUtil.copy(in, tempFile);
} catch (final Exception e1) {
if (tempFile != null && tempFile.exists() && !tempFile.delete()) {
logger.warn("Failed to delete {}", tempFile.getAbsolutePath());
}
throw e1;
}
return asStream("es_" + System.currentTimeMillis() + ".json").contentTypeOctetStream().stream(out -> {
try (final InputStream in = new FileInputStream(tempFile)) {
out.write(in);
} finally {
if (tempFile.exists() && !tempFile.delete()) {
logger.warn("Failed to delete {}", tempFile.getAbsolutePath());
}
}
});
} catch (final Exception e) {
logger.warn("Failed to process request file: {}", form.requestFile.getFileName(), e);
throwValidationError(messages -> messages.addErrorsInvalidHeaderForRequestFile(GLOBAL, e.getMessage()), () -> asListHtml(this::saveToken));
}
}
// no-op
return redirect(getClass());
}
Aggregations