下面列出了怎么用org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody的API类实例代码及写法,或者点击链接到github查看源代码。
@RequestMapping(value = "/subscriptions/{subscription_id}/events", method = RequestMethod.GET)
public StreamingResponseBody streamEvents(
@PathVariable("subscription_id") final String subscriptionId,
@Nullable @RequestParam(value = "max_uncommitted_events", required = false) final Integer
maxUncommittedEvents,
@Nullable @RequestParam(value = "batch_limit", required = false) final Integer batchLimit,
@Nullable @RequestParam(value = "stream_limit", required = false) final Long streamLimit,
@Nullable @RequestParam(value = "batch_timespan", required = false) final Long batchTimespan,
@Nullable @RequestParam(value = "batch_flush_timeout", required = false) final Integer batchTimeout,
@Nullable @RequestParam(value = "stream_timeout", required = false) final Long streamTimeout,
@Nullable @RequestParam(value = "stream_keep_alive_limit", required = false) final Integer
streamKeepAliveLimit,
@Nullable @RequestParam(value = "commit_timeout", required = false) final Long commitTimeout,
final HttpServletRequest request, final HttpServletResponse response, final Client client) {
final UserStreamParameters userParameters = new UserStreamParameters(batchLimit, streamLimit, batchTimespan,
batchTimeout, streamTimeout, streamKeepAliveLimit, maxUncommittedEvents, ImmutableList.of(),
commitTimeout);
final StreamParameters streamParameters = StreamParameters.of(userParameters,
nakadiSettings.getMaxCommitTimeout(), client);
return stream(subscriptionId, request, response, client, streamParameters,
TracingService.extractSpan(request, "stream_events_request")
.setTag("subscription.id", subscriptionId));
}
@Test
public void whenNoCursorsThenLatestOffsetsAreUsed() throws IOException, InvalidCursorException {
when(eventTypeCache.getEventType(TEST_EVENT_TYPE_NAME)).thenReturn(EVENT_TYPE);
final List<PartitionStatistics> tps2 = ImmutableList.of(
new KafkaPartitionStatistics(timeline, 0, 0, 87),
new KafkaPartitionStatistics(timeline, 1, 0, 34));
when(timelineService.getActiveTimeline(any(EventType.class))).thenReturn(timeline);
when(topicRepositoryMock.loadTopicStatistics(eq(Collections.singletonList(timeline))))
.thenReturn(tps2);
final ArgumentCaptor<EventStreamConfig> configCaptor = ArgumentCaptor.forClass(EventStreamConfig.class);
final EventStream eventStreamMock = mock(EventStream.class);
when(eventStreamFactoryMock.createEventStream(any(), any(), configCaptor.capture(), any()))
.thenReturn(eventStreamMock);
final StreamingResponseBody responseBody = createStreamingResponseBody(1, 0, 1, 1, 0, null);
responseBody.writeTo(new ByteArrayOutputStream());
final EventStreamConfig streamConfig = configCaptor.getValue();
assertThat(
streamConfig.getCursors(),
equalTo(tps2.stream().map(PartitionStatistics::getLast).collect(Collectors.toList())));
}
public static StreamingResponseBody toStreaming(final HystrixCommand<InputStream> command) {
return outputStream -> {
final Observable<InputStream> stream = command.toObservable();
stream.toBlocking().subscribe(inputStream -> {
try {
IOUtils.copyLarge(inputStream, outputStream);
outputStream.flush();
} catch (IOException e) {
try {
inputStream.close();
} catch (IOException closingException) {
LOGGER.warn("could not close command result, a http connection may be leaked !",
closingException);
}
LOGGER.error("Unable to fully copy command result '{}'.", command.getClass(), e);
}
}, TDPException::rethrowOrWrap);
};
}
/**
* Get the suggested action dynamic params. Dynamic params depends on the context (dataset / preparation / actual
* transformations)
*/
@RequestMapping(value = "/api/transform/suggest/{action}/params", method = GET, produces = APPLICATION_JSON_VALUE)
@ApiOperation(value = "Get the transformation dynamic parameters", notes = "Returns the transformation parameters.")
@Timed
public ResponseEntity<StreamingResponseBody> suggestActionParams(
@ApiParam(value = "Transformation name.") @PathVariable("action") final String action, @ApiParam(
value = "Suggested dynamic transformation input (preparation id or dataset id") @Valid final DynamicParamsInput dynamicParamsInput) {
// get preparation/dataset content
HystrixCommand<InputStream> inputData;
final String preparationId = dynamicParamsInput.getPreparationId();
if (isNotBlank(preparationId)) {
inputData = new AsyncGet<>(
() -> getCommand(PreparationGetContent.class, preparationId, dynamicParamsInput.getStepId()),
commonAPI);
} else {
inputData = datasetClient.getDataSetGetCommand(dynamicParamsInput.getDatasetId(), false, false);
}
// get params, passing content in the body
final GenericCommand<InputStream> getActionDynamicParams =
getCommand(SuggestActionParams.class, inputData, action, dynamicParamsInput.getColumnId());
return CommandHelper.toStreaming(getActionDynamicParams);
}
@RequestMapping(value = "/apply", method = POST)
@ApiOperation(value = "Run the transformation given the provided export parameters",
notes = "This operation transforms the dataset or preparation using parameters in export parameters.")
@VolumeMetered
@AsyncOperation(conditionalClass = GetPrepContentAsyncCondition.class, //
resultUrlGenerator = PreparationGetContentUrlGenerator.class, //
executionIdGeneratorClass = ExportParametersExecutionIdGenerator.class //
)
public StreamingResponseBody
execute(@ApiParam(
value = "Preparation id to apply.") @RequestBody @Valid @AsyncParameter @AsyncExecutionId final ExportParameters parameters)
throws IOException {
// Async behavior
final ConditionalTest conditionalTest = applicationContext.getBean(GetPrepContentAsyncCondition.class);
if (conditionalTest.apply(parameters)) {
// write to cache
executeSampleExportStrategy(parameters).writeTo(new NullOutputStream());
return outputStream -> {
};
} else {
// sync behavior
return executeSampleExportStrategy(parameters);
}
}
/**
* Apply the preparation to the dataset out of the given IDs.
*
* @param preparationId the preparation id to apply on the dataset.
* @param datasetId the dataset id to transform.
* @param formatName The output {@link ExportFormat format}. This format also set the MIME response type.
* @param stepId the preparation step id to use (default is 'head').
* @param name the transformation name.
* @param exportParams additional (optional) export parameters.
*/
//@formatter:off
@RequestMapping(value = "/apply/preparation/{preparationId}/dataset/{datasetId}/{format}", method = GET)
@ApiOperation(value = "Transform the given preparation to the given format on the given dataset id", notes = "This operation transforms the dataset using preparation id in the provided format.")
@VolumeMetered
public StreamingResponseBody applyOnDataset(@ApiParam(value = "Preparation id to apply.") @PathVariable(value = "preparationId") final String preparationId,
@ApiParam(value = "DataSet id to transform.") @PathVariable(value = "datasetId") final String datasetId,
@ApiParam(value = "Output format") @PathVariable("format") final String formatName,
@ApiParam(value = "Step id", defaultValue = "head") @RequestParam(value = "stepId", required = false, defaultValue = "head") final String stepId,
@ApiParam(value = "Name of the transformation", defaultValue = "untitled") @RequestParam(value = "name", required = false, defaultValue = "untitled") final String name,
@RequestParam final Map<String, String> exportParams) {
//@formatter:on
final ExportParameters exportParameters = new ExportParameters();
exportParameters.setPreparationId(preparationId);
exportParameters.setDatasetId(datasetId);
exportParameters.setExportType(formatName);
exportParameters.setStepId(stepId);
exportParameters.setExportName(name);
exportParameters.getArguments().putAll(exportParams);
return executeSampleExportStrategy(exportParameters);
}
/**
* Add the following preparation in cache.
*
* @param preparation the preparation to cache.
* @param stepId the preparation step id.
*/
private void addPreparationInCache(PreparationDTO preparation, String stepId) {
final ExportParameters exportParameters = new ExportParameters();
exportParameters.setPreparationId(preparation.getId());
exportParameters.setExportType("JSON");
exportParameters.setStepId(stepId);
exportParameters.setDatasetId(preparation.getDataSetId());
final StreamingResponseBody streamingResponseBody = executeSampleExportStrategy(exportParameters);
try {
// the result is not important here as it will be cached !
streamingResponseBody.writeTo(new NullOutputStream());
} catch (IOException e) {
throw new TDPException(UNEXPECTED_EXCEPTION, e);
}
}
@Override
public StreamingResponseBody execute(ExportParameters parameters) {
final String formatName = parameters.getExportType();
final ExportFormat format = getFormat(formatName);
ExportUtils.setExportHeaders(parameters.getExportName(), //
parameters.getArguments().get(ExportFormat.PREFIX + CSVFormat.ParametersCSV.ENCODING), //
format);
return outputStream -> {
// get the dataset content (in an auto-closable block to make sure it is properly closed)
final String datasetId = parameters.getDatasetId();
try (DataSet dataSet = datasetClient.getDataSet(datasetId, false, true)) {
// get the actions to apply (no preparation ==> dataset export ==> no actions)
Configuration configuration = Configuration
.builder() //
.args(parameters.getArguments()) //
.outFilter(rm -> filterService.build(parameters.getFilter(), rm)) //
.format(format.getName()) //
.volume(Configuration.Volume.SMALL) //
.output(outputStream) //
.limit(limit) //
.build();
factory.get(configuration).buildExecutable(dataSet, configuration).execute();
}
};
}
@Test
void testDownload() {
String fileId = "MyFileId";
String contentType = "application/octet-stream";
String filename = "filename";
FileMeta fileMeta = mock(FileMeta.class);
when(fileMeta.getContentType()).thenReturn(contentType);
when(fileMeta.getFilename()).thenReturn(filename);
when(dataService.findOneById("sys_FileMeta", fileId, FileMeta.class)).thenReturn(fileMeta);
ResponseEntity<StreamingResponseBody> responseEntity = filesApiServiceImpl.download(fileId);
assertEquals(OK, responseEntity.getStatusCode());
assertEquals(valueOf(contentType), responseEntity.getHeaders().getContentType());
assertEquals(
parse("attachment; filename=\"filename\""),
responseEntity.getHeaders().getContentDisposition());
}
@Test
public void shouldUsedVersionedPreparation() throws IOException {
// Given
final ExportParameters parameters = new ExportParameters();
parameters.setExportType("JSON");
parameters.setPreparationId("prep-1234");
parameters.setStepId("step-1234");
final PreparationDTO preparation = new PreparationDTO();
preparation.setId("prep-1234");
preparation.setHeadId("step-1234");
configurePreparation(preparation, "prep-1234", "step-1234");
// When
final StreamingResponseBody body = strategy.execute(parameters);
body.writeTo(new NullOutputStream());
// Then
final ArgumentCaptor<Configuration> captor = ArgumentCaptor.forClass(Configuration.class);
verify(transformer).buildExecutable(any(), captor.capture());
assertEquals("prep-1234", captor.getValue().getPreparationId());
assertEquals("step-1234", captor.getValue().getPreparation().getHeadId());
}
@Test
public void shouldUsedHeadPreparation() throws IOException {
// Given
final ExportParameters parameters = new ExportParameters();
parameters.setExportType("JSON");
parameters.setPreparationId("prep-1234");
parameters.setStepId("head");
final PreparationDTO preparation = new PreparationDTO();
preparation.getSteps().add(Step.ROOT_STEP.id());
preparation.setId("prep-1234");
preparation.setHeadId("head");
configurePreparation(preparation, "prep-1234", "head");
// When
final StreamingResponseBody body = strategy.execute(parameters);
body.writeTo(new NullOutputStream());
// Then
final ArgumentCaptor<Configuration> captor = ArgumentCaptor.forClass(Configuration.class);
verify(transformer).buildExecutable(any(), captor.capture());
assertEquals("prep-1234", captor.getValue().getPreparationId());
assertEquals("head", captor.getValue().getPreparation().getHeadId());
}
@RequestMapping(value = "/api/preparations/preview/add", method = POST, consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
@ApiOperation(value = "Get a preview between the head step and a new appended transformation")
public StreamingResponseBody previewAdd(@RequestBody @Valid final PreviewAddParameters input) {
//@formatter:on
PreparationDTO preparation = null;
List<Action> actions = new ArrayList<>(0);
// get preparation details with dealing with preparations
if (StringUtils.isNotBlank(input.getPreparationId())) {
preparation = internalGetPreparation(input.getPreparationId());
actions = internalGetActions(preparation.getId());
}
final HystrixCommand<InputStream> transformation = getCommand(PreviewAdd.class, input, preparation, actions);
return executePreviewCommand(transformation);
}
@RequestMapping(value = "/api/datasets/preview/{id}", method = GET, produces = APPLICATION_JSON_VALUE)
@ApiOperation(value = "Get a data set by id.", produces = APPLICATION_JSON_VALUE,
notes = "Get a data set based on given id.")
@Timed
public ResponseEntity<StreamingResponseBody> preview(
@ApiParam(value = "Id of the data set to get") @PathVariable(value = "id") String id,
@RequestParam(defaultValue = "true") @ApiParam(name = "metadata",
value = "Include metadata information in the response") boolean metadata,
@RequestParam(defaultValue = "") @ApiParam(name = "sheetName",
value = "Sheet name to preview") String sheetName) {
if (LOG.isDebugEnabled()) {
LOG.debug("Requesting dataset #{} (pool: {})...", id, getConnectionStats());
}
try {
GenericCommand<InputStream> retrievalCommand = getCommand(DataSetPreview.class, id, metadata, sheetName);
return toStreaming(retrievalCommand);
} finally {
if (LOG.isDebugEnabled()) {
LOG.debug("Request dataset #{} (pool: {}) done.", id, getConnectionStats());
}
}
}
@GetMapping(path = "/sitemap.xml", produces = MediaType.APPLICATION_XML_VALUE)
public ResponseEntity<StreamingResponseBody> getSitemap() throws ParserConfigurationException {
var document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
document.setXmlStandalone(true);
var urlset = document.createElementNS(NAMESPACE_URI, "urlset");
document.appendChild(urlset);
var baseUrl = getBaseUrl();
var timestampFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
repositories.findAllExtensions().forEach(extension -> {
var entry = document.createElement("url");
var loc = document.createElement("loc");
loc.setTextContent(UrlUtil.createApiUrl(baseUrl, "extension", extension.getNamespace().getName(), extension.getName()));
entry.appendChild(loc);
var lastmod = document.createElement("lastmod");
lastmod.setTextContent(extension.getLatest().getTimestamp().format(timestampFormatter));
entry.appendChild(lastmod);
urlset.appendChild(entry);
});
StreamingResponseBody stream = out -> {
try {
var transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(new DOMSource(document), new StreamResult(out));
} catch (TransformerException exc) {
throw new RuntimeException(exc);
}
};
return new ResponseEntity<>(stream, HttpStatus.OK);
}
@GetMapping (value = "/download", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<StreamingResponseBody> download(final HttpServletResponse response) {
response.setContentType("application/zip");
response.setHeader(
"Content-Disposition",
"attachment;filename=sample.zip");
StreamingResponseBody stream = out -> {
final String home = System.getProperty("user.home");
final File directory = new File(home + File.separator + "Documents" + File.separator + "sample");
final ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());
if(directory.exists() && directory.isDirectory()) {
try {
for (final File file : directory.listFiles()) {
final InputStream inputStream=new FileInputStream(file);
final ZipEntry zipEntry=new ZipEntry(file.getName());
zipOut.putNextEntry(zipEntry);
byte[] bytes=new byte[1024];
int length;
while ((length=inputStream.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
inputStream.close();
}
zipOut.close();
} catch (final IOException e) {
logger.error("Exception while reading and streaming data {} ", e);
}
}
};
logger.info("steaming response {} ", stream);
return new ResponseEntity(stream, HttpStatus.OK);
}
@PostMapping(value = "/download.action")
public ResponseEntity<StreamingResponseBody> download(ComAdmin admin, UserActivityLogForm form) throws Exception {
DateTimeFormatter datePickerFormatter = admin.getDateFormatter();
LocalDate localDateFrom = form.getDateFrom().get(LocalDate.now(), datePickerFormatter);
LocalDate localDateTo = form.getDateTo().get(LocalDate.now(), datePickerFormatter);
ZoneId zoneId = AgnUtils.getZoneId(admin);
List<AdminEntry> admins = adminService.getAdminEntriesForUserActivityLog(admin);
String tempFileName = String.format("user-activity-log-%s.csv", UUID.randomUUID());
File mailingRecipientsExportTempDirectory = AgnUtils.createDirectory(AgnUtils.getTempDir() + File.separator + "UserActivityLogExport");
File exportTempFile = new File(mailingRecipientsExportTempDirectory, tempFileName);
UserActivityLogExportWorker exportWorker = exportWorkerFactory.getBuilderInstance()
.setFromDate(DateUtilities.toDate(localDateFrom, zoneId))
.setToDate(DateUtilities.toDate(localDateTo.plusDays(1), zoneId))
.setFilterDescription(form.getDescription())
.setFilterAction(form.getUserAction())
.setFilterAdminUserName(form.getUsername())
.setFilterAdmins(admins)
.setExportFile(exportTempFile.getAbsolutePath())
.setDateFormat(admin.getDateFormat())
.setDateTimeFormat(admin.getDateTimeFormatWithSeconds())
.setExportTimezone(TimeZone.getTimeZone(admin.getAdminTimezone()).toZoneId())
.build();
exportWorker.call();
String dateString = new SimpleDateFormat(DateUtilities.YYYY_MM_DD_HH_MM_SS_FORFILENAMES).format(new Date());
String fileName = String.format("user-activity-log-%s.csv", dateString);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment;filename=\"%s\"", fileName))
.contentLength(exportTempFile.length())
.contentType(MediaType.parseMediaType(HttpUtils.CONTENT_TYPE_CSV))
.body(new FileResponseBody(exportTempFile, true));
}
@RequestMapping(params = "streamingSlow")
public StreamingResponseBody getStreamingSlow() {
return os -> {
os.write("name=Joe".getBytes());
try {
Thread.sleep(200);
os.write("&someBoolean=true".getBytes(StandardCharsets.UTF_8));
}
catch (InterruptedException e) {
/* no-op */
}
};
}
@GetMapping(value = "/hello2")
public StreamingResponseBody hello2() throws InterruptedException {
Thread.sleep(500);
return (OutputStream outputStream) -> {
outputStream.write("HelloWorld".getBytes());
outputStream.flush();
outputStream.close();
};
}
@GetMapping(Constants.API_SRB)
public ResponseEntity<StreamingResponseBody> handleRbe() {
StreamingResponseBody stream = out -> {
String msg = Constants.API_SRB_MSG + " @ " + new Date();
out.write(msg.getBytes());
};
return new ResponseEntity(stream, HttpStatus.OK);
}
@Override
public ResponseEntity<StreamingResponseBody> readFile(String fileLocation, String imageDir, String id,
String fileName) {
StreamingResponseBody streamingResponseBody = new StreamingResponseBody() {
@Override
public void writeTo(OutputStream outputStream) {
try {
String fileStr = fileLocation + File.separator + imageDir + File.separator + id + File.separator
+ fileName;
RandomAccessFile file = new RandomAccessFile(fileStr, "r");
FileChannel inChannel = file.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (inChannel.read(buffer) > 0) {
buffer.flip();
for (int i = 0; i < buffer.limit(); i++) {
outputStream.write(buffer.get());
}
buffer.clear();
outputStream.flush();
}
inChannel.close();
file.close();
} catch (IOException e) {
logger.error("Image Not Found : error " + e.getMessage());
throw new ResourceNotFoundException("Image Not Found : " + id + "/" + fileName);
}
}
};
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_TYPE, "image/*");
return new ResponseEntity<StreamingResponseBody>(streamingResponseBody, headers, HttpStatus.OK);
}
@Override
public ResponseEntity<StreamingResponseBody> readFile(String fileLocation, String imageDir, String id,
String fileName) {
StreamingResponseBody streamingResponseBody = new StreamingResponseBody() {
@Override
public void writeTo(OutputStream outputStream) {
try {
String fileStr = SEPARATOR + imageDir + SEPARATOR + id + SEPARATOR + fileName;
DbxRequestConfig config = new DbxRequestConfig(APP_IDENTIFIER);
DbxClientV2 client = new DbxClientV2(config, ACCESS_TOKEN);
client.files().download(fileStr).download(outputStream);
} catch (Exception e) {
logger.error(e.getMessage());
throw new ResourceNotFoundException("Image Not Found : " + id + "/" + fileName);
}
}
};
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_TYPE, "image/*");
return new ResponseEntity<StreamingResponseBody>(streamingResponseBody, headers, HttpStatus.OK);
}
@GetMapping(value = "/export", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<StreamingResponseBody> backup(HttpServletRequest req, HttpServletResponse response) {
Profile authUser = utils.getAuthUser(req);
if (!utils.isAdmin(authUser)) {
return new ResponseEntity<StreamingResponseBody>(HttpStatus.UNAUTHORIZED);
}
String fileName = App.identifier(Config.getConfigParam("access_key", "scoold")) + "_" +
Utils.formatDate("YYYYMMdd_HHmmss", Locale.US);
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".zip");
return new ResponseEntity<StreamingResponseBody>(out -> {
ObjectWriter writer = ParaObjectUtils.getJsonWriterNoIdent().without(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {
long count = 0;
int partNum = 0;
// find all objects even if there are more than 10000 users in the system
Pager pager = new Pager(1, "_docid", false, Config.MAX_ITEMS_PER_PAGE);
List<ParaObject> objects;
do {
objects = pc.findQuery("", "*", pager);
ZipEntry zipEntry = new ZipEntry(fileName + "_part" + (++partNum) + ".json");
zipOut.putNextEntry(zipEntry);
writer.writeValue(zipOut, objects);
count += objects.size();
} while (!objects.isEmpty());
logger.info("Exported {} objects to {}. Downloaded by {} (pager.count={})", count, fileName + ".zip",
authUser.getCreatorid() + " " + authUser.getName(), pager.getCount());
} catch (final IOException e) {
logger.error("Failed to export data.", e);
}
}, HttpStatus.OK);
}
private StreamingResponseBody getStreamingResponse(DataSet data, boolean headers, boolean zipped) {
return new StreamingResponseBody() {
@Override
public void writeTo(OutputStream out) throws IOException {
OutputStreamWriter ow = zipped ? new OutputStreamWriter(new GZIPOutputStream(out, true)) : new OutputStreamWriter(out);
data.writeCsv(ow, new Locale(config.getFormatter().getLocale()), config.getFormatter().getSeparator(),
headers);
}
};
}
private StreamingResponseBody getErrorStreamingResponse(String message) {
return new StreamingResponseBody() {
@Override
public void writeTo(OutputStream out) throws IOException {
out.write(message != null ? message.getBytes() : "".getBytes());
}
};
}
public void getData() throws IOException {
WebRequestMock wr = new WebRequestMock();
wr.setAttribute("format", "csv", 0);
wr.setParameter("headers", (String[]) Collections.singletonList("true").toArray(new String[1]));
ResponseEntity <StreamingResponseBody> resp = resource.getData("iteslasim", "test", "2017", "data", wr);
assertEquals(200, resp.getStatusCodeValue());
}
public void getDataZip() throws IOException {
WebRequestMock wr = new WebRequestMock();
wr.setAttribute("format", "zip", 0);
wr.setParameter("headers", (String[]) Collections.singletonList("true").toArray(new String[1]));
ResponseEntity <StreamingResponseBody> resp = resource.getData("iteslasim", "test", "2017", "data", wr);
assertEquals(200, resp.getStatusCodeValue());
}
public void getFilteredData() throws IOException {
WebRequestMock wr = new WebRequestMock();
wr.setAttribute("format", "zip", 0);
wr.setParameter("headers", (String[]) Collections.singletonList("true").toArray(new String[1]));
wr.setParameter("forecast", (String[]) Collections.singletonList("0").toArray(new String[1]));
wr.setParameter("time", (String[]) Collections.singletonList("[2017-01-10T01:00:00Z,2017-01-10T12:00:00Z]").toArray(new String[1]));
wr.setParameter("daytime", (String[]) Collections.singletonList("[00:30:00,23:59:59]").toArray(new String[1]));
String[] countries = {"FR,BE"};
wr.setParameter("country", countries);
String[] equip = {"gen,loads,shunts,stations,2wt,3wt,lines,dangling"};
wr.setParameter("equip", equip);
wr.setParameter("colRange", (String[]) Collections.singletonList("2-5").toArray(new String[1]));
ResponseEntity <StreamingResponseBody> resp = resource.getData("iteslasim", "test", "2017", "data", wr);
assertEquals(200, resp.getStatusCodeValue());
}
public void getDataByIds() throws IOException {
WebRequestMock wr = new WebRequestMock();
wr.setAttribute("format", "csv", 0);
wr.setParameter("headers", (String[]) Collections.singletonList("true").toArray(new String[1]));
String[] ids = {"load1,load2,substation1,generator1,LINE1"};
wr.setParameter("ids", ids);
ResponseEntity <StreamingResponseBody> resp = resource.getData("iteslasim", "test", "2017", "data", wr);
assertEquals(200, resp.getStatusCodeValue());
}
public void getStats() throws IOException {
WebRequestMock wr = new WebRequestMock();
wr.setAttribute("format", "csv", 0);
wr.setParameter("headers", (String[]) Collections.singletonList("true").toArray(new String[1]));
ResponseEntity <StreamingResponseBody> resp = resource.getData("iteslasim", "test", "2017", "stats", wr);
assertEquals(200, resp.getStatusCodeValue());
}
@Test
void testDownloadFile() {
when(userPermissionEvaluator.hasPermission(new EntityTypeIdentity(FILE_META), READ_DATA))
.thenReturn(true);
String fileId = "MyId";
@SuppressWarnings("unchecked")
ResponseEntity<StreamingResponseBody> responseEntity = mock(ResponseEntity.class);
when(filesApiService.download(fileId)).thenReturn(responseEntity);
assertEquals(responseEntity, filesApiController.downloadFile(fileId));
}