Untitled
File Method Jsonunknown
plain_text
8 months ago
1.9 kB
5
Indexable
Never
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import java.io.*; import java.nio.file.Files; import java.util.Map; @RestController public class JsonController { // Your existing code for AWS credentials and S3 bucket/object keys goes here @GetMapping("/json") @ResponseBody public Map<String, Object> getJsonFromS3() { AmazonS3 s3Client = AmazonS3ClientBuilder.standard() .withRegion("your-region") .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(AWS_ACCESS_KEY, AWS_SECRET_KEY))) .build(); S3Object s3Object = s3Client.getObject(BUCKET_NAME, OBJECT_KEY); File tempFile = null; try { tempFile = File.createTempFile("temp", ".json"); try (InputStream inputStream = s3Object.getObjectContent(); OutputStream outputStream = new FileOutputStream(tempFile)) { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } } ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.readValue(tempFile, new TypeReference<Map<String, Object>>() {}); } catch (IOException e) { e.printStackTrace(); } finally { if (tempFile != null) { try { Files.delete(tempFile.toPath()); } catch (IOException e) { e.printStackTrace(); } } } return null; } }
Leave a Comment