dnet-applications/apps/dnet-orgs-database-application/src/main/java/eu/dnetlib/organizations/controller/PublicApiController.java

70 lines
2.2 KiB
Java

package eu.dnetlib.organizations.controller;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import eu.dnetlib.organizations.utils.DatabaseUtils;
@RestController
@RequestMapping("/public-api")
public class PublicApiController {
@Autowired
private DatabaseUtils dbUtils;
@GetMapping("/logs")
public void findJournalById(@RequestParam final String id,
final HttpServletResponse res) throws IOException {
final String filename = String.format("%s.log", id.replaceAll(":", "_"));
res.setContentType(MediaType.TEXT_PLAIN.getType());
res.setHeader("Content-Disposition", "attachment; filename=" + filename);
try (final ServletOutputStream out = res.getOutputStream()) {
for (final String s : dbUtils.obtainLogEntries(id)) {
IOUtils.write(s, out, StandardCharsets.UTF_8);
}
}
}
@GetMapping("/logs/{year}/{month}/{country}")
public void findJournalByCountry(@PathVariable final int year,
@PathVariable final int month,
@PathVariable final String country,
final HttpServletResponse res) throws IOException {
if (month < 1 || month > 12) {
res.sendError(HttpStatus.BAD_REQUEST.value(), "Invalid month");
}
if (year < 2020 || year > 2100) {
res.sendError(HttpStatus.BAD_REQUEST.value(), "Invalid year");
}
final String filename = String.format("%04d_%02d_%s.log", year, month, country);
res.setContentType(MediaType.TEXT_PLAIN.getType());
res.setHeader("Content-Disposition", "attachment; filename=" + filename);
try (final ServletOutputStream out = res.getOutputStream()) {
for (final String s : dbUtils.obtainLogEntries(year, month, country)) {
IOUtils.write(s, out, StandardCharsets.UTF_8);
}
}
}
}