Unable to write to disk using GridFSFile in springboot 2.0.2 - spring

Trying to use code in:
http://javasampleapproach.com/spring-framework/spring-data/springdata-mongodb-gridfstemplate-save-retrieve-delete-binary-files-image-text-files
with springboot 1.5.13.
In this code to retrieve an image use GridFSDBFile like this:
GridFSDBFile imageFile = gridOperations.findOne(new Query(Criteria.where("_id").is(imageFileId)));
and later to save in filesystem use this:
imageFile.writeTo
Baeldung has the same code:
http://www.baeldung.com/spring-data-mongodb-gridfs
I have my project in springboot 2.0.2 and this line:
GridFSDBFile imageFile = gridOperations.findOne(new Query(Criteria.where("_id").is(imageFileId)));
throws an error:
Type mismatch: cannot convert from GridFSFile to GridFSDBFile
so, once I have changed to:
GridFSFile imageFile = gridOperations.findOne(new Query(Criteria.where("_id").is(imageFileId)));
no errors, but now I have not available the method:
writeTo
to write to disk.
UPDATE 1:
imageFileId = "5b0bff8b7cc45b32f43b47f4";
GridFSFile imageFile = gridOperations.findOne(new Query(Criteria.where("_id").is(imageFileId)));
try {
File file = new File("c:/JSA/retrieve/" + imageFile.getFilename());
FileOutputStream streamToDownloadTo = new FileOutputStream(file);
//This line doesn't works
gridFSBucket.downloadToStream(imageFile.getId(), streamToDownloadTo);
streamToDownloadTo.close();
} catch (IOException e) {
// handle exception
System.out.println("error: " + e.getMessage());
} catch (Exception e1) {
System.out.println("error1: " + e1.getMessage());
}
UPDATE 2:
try {
File file = new File("c:/JSA/retrieve/" + imageFile.getFilename());
FileOutputStream streamToDownloadTo = new FileOutputStream(file);
System.out.println("imageFile.getId(): " + imageFile.getId());
System.out.println("streamToDownloadTo: " + streamToDownloadTo.toString());
gridFSBucket.downloadToStream(imageFile.getId(), streamToDownloadTo);
streamToDownloadTo.close();
} catch (IOException e) {
// handle exception
System.out.println("error: " + e.getMessage());
} catch (Exception e1) {
System.out.println("error1: " + e1.getMessage());
}
Console
imageFile.getId(): BsonObjectId{value=5b0bff8b7cc45b32f43b47f4}
streamToDownloadTo: java.io.FileOutputStream#3b20c8e2
This line thrown an exception:
gridFSBucket.downloadToStream(imageFile.getId(), streamToDownloadTo);
and return null
Solved
Inject:
#Autowired
MongoGridFsTemplate mongoGridFsTemplate;
GridFSBucket gridFSBucket = GridFSBuckets.create(mongoGridFsTemplate.mongoDbFactory().getDb());
imageFileId = "5b0bff8b7cc45b32f43b47f4";
GridFSFile imageFile = gridOperations.findOne(new Query(Criteria.where("_id").is(new ObjectId(imageFileId))));
try {
File file = new File("c:/JSA/retrieve/" + imageFile.getFilename());
FileOutputStream streamToDownloadTo = new FileOutputStream(file);
gridFSBucket.downloadToStream(imageFile.getId(), streamToDownloadTo);
streamToDownloadTo.close();
} catch (IOException e) {
// handle exception
System.out.println("error: " + e.getMessage());
} catch (Exception e1) {
e1.printStackTrace();
}

Related

Downloading data from URL using Jsoup

I am tring to get .csv file from a url, when i loop through the links using the "a" tag, the href that i want doesn't exist. how can i get it's href.
` String URL = internalConstant.getMlcuURL();
String ffiListFile = null;
logger.info("Page URl: " + URL);
Document doc;
try {
doc = Jsoup.connect(URL).get();
Elements links = doc.select("a[href]");
for (Element link : links) {
logger.info("Elements aaaa"+ link);
String absHref = link.attr("abs:href");
if (absHref.endsWith(".csv")) {
logger.info(absHref);
ffiListFile = absHref;
break;
}
}
if (ffiListFile.isEmpty()) {
logger.error("file not found");
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "MLCU File not found in website");
}
this.fileDownloadFFIListService.downloadExcelFile(ffiListFile);
} catch (IOException e) {
e.printStackTrace();
logger.error("download error " + e.getMessage());
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Failed to download file");
`

File upload in Spring

I am trying to upload an audio file using the following code on server.Right now, it works perfectly well for image files but not for audios.I think MultipartFile should work with audio files as well.Can any one tell me what is wrong here?
I am getting "The server refused this request because the request entity is in a format not supported by the requested resource for the requested method." error.
Does MultipartFile not work with audio files?If no what is an alternative?
#Transactional
public BaseVO uploadImage(MultipartFile file, long userId){
Map<String, Object> alertParams = new HashMap<String, Object>();
try{
if (!file.isEmpty()) {
Image profileImage = imageRepository.findByUserId(userId);
if(profileImage == null){
profileImage = new Image();
profileImage.setUserId(userId);
}
File dir = null;
String realPath;
if(liveBuild == "true"){
realPath = liveImageUploadRepository;
dir = new File(realPath);
}else{
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
realPath = request.getSession().getServletContext().getRealPath("/") + devImageUploadRepository;
dir = new File(realPath);
}
if (!dir.exists()) {
dir.mkdirs();
}
String finalFileStorePath = realPath + "/" + userId + ".jpg";
File path = new File(finalFileStorePath);
file.transferTo(path);
profileImage.setImagePath(realPath);
//profileImage.setImageName(userId + ".jpg");
profileImage.setImageName(userId+"");
profileImage.setImageType(".jpg");
imageRepository.save(profileImage);
alertParams.put("id", profileImage.getId());
} else {
return new BaseVO(alertParams, Constants.STATUS_OK, Constants.STATUS_OK_MSG);
}
}catch(HibernateException e){
return new BaseVO(alertParams, Constants.STATUS_ERROR, Constants.STATUS_ERROR_MSG + " " + e.getMessage());
} catch (IllegalStateException e) {
e.printStackTrace();
return new BaseVO(alertParams, Constants.STATUS_ERROR, Constants.STATUS_ERROR_MSG);
} catch (IOException e) {
e.printStackTrace();
return new BaseVO(alertParams, Constants.STATUS_ERROR, Constants.STATUS_ERROR_MSG);
}
return new BaseVO(alertParams, Constants.STATUS_OK, Constants.STATUS_OK_MSG);
}

Hadoop compression

I was trying to compress a file using the following code. The compression works fine when the size of the file is small(say 1 GB). But when the size of the file is around 5GB the program does not fail rather it keeps on running for 2 days with out any result.
Based on the info message I get it seems like cluster issue although I am not sure enough.
Following is the code the error I am getting:
Error
Code I am using
public void compressData(final String inputFilePath,final String outputPath) throws DataFabricAppendException {
CompressionOutputStream compressionOutputStream = null;
FSDataOutputStream fsDataOutputStream = null;
FSDataInputStream fsDataInputStream = null;
CompressionCodec compressionCodec = null;
CompressionCodecFactory compressionCodecFactory = null;
try {
compressionCodecFactory = new CompressionCodecFactory(conf);
final Path compressionFilePath = new Path(outputPath);
fsDataOutputStream = fs.create(compressionFilePath);
compressionCodec = compressionCodecFactory
.getCodecByClassName(BZip2Codec.class.getName());
compressionOutputStream = compressionCodec
.createOutputStream(fsDataOutputStream);
fsDataInputStream = new FSDataInputStream(fs.open(new Path(
inputFilePath)));
IOUtils.copyBytes(fsDataInputStream, compressionOutputStream, conf,
false);
compressionOutputStream.finish();
} catch (IOException ex) {
throw new DataFabricAppendException(
"Error while compressing non-partitioned file : "
+ inputFilePath, ex);
} catch (Exception ex) {
throw new DataFabricAppendException(
"Error while compressing non-partitioned file : "
+ inputFilePath, ex);
} finally {
try {
if (compressionOutputStream != null) {
compressionOutputStream.close();
}
if (fsDataInputStream != null) {
fsDataInputStream.close();
}
if (fsDataOutputStream != null) {
fsDataOutputStream.close();
}
} catch (IOException e1) {
LOG.warn("Could not close necessary objects");
}
}
}

Open a .Bat Using Java Apllication

I'm trying to Open the CMD Using java + Applying code to it to open an .jar so the applications output is shown in the .bat file.
can someone tell me how to do it?
This is the code it got,it does run excecute the file but the CMD doesnt show.
btnTest.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String Bat = "C:"+File.separatorChar+"Users"+File.separatorChar+"Gebruiker"+File.separatorChar+"AppData"+File.separatorChar+"Local"+File.separatorChar+"Temp"+File.separatorChar+"hexT"+File.separatorChar+"run.bat";
Runtime rt = Runtime.getRuntime();
try {
rt.exec(Bat);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Edited: This works for me:
String Bat = "C:\\app.bat"; //Try to use \\ as path seperator
try {
Runtime.getRuntime().exec("cmd /c start " + Bat);
} catch (IOException e) {
e.printStackTrace();
}
Define this :
FileWriter writer;
then in your try/catch do the following :
try {
writer = new FileWriter("test.txt");
Process child = rt.exec(Bat);
InputStream input = child.getInputStream();
BufferedInputStream buffer = new BufferedInputStream(input);
BufferedReader commandResult = new BufferedReader(new InputStreamReader(buffer));
String line = "";
try {
while ((line = commandResult.readLine()) != null) {
writer.write(line + "\n");
}
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This will read the output as a buffer line by line and write it into a text file

Set Field Text, Java

I have two classes. MetaDataExtractor(GUI) and MetaData.
MetaData has the method which extracts the metadata from an image. MetaDataExtractor is designed to display the data in a JTextPane. (Please excuse the class names. I know it's a little confusing. I'm fairly new to Java).
MetaDataExtractor:
LongitudeField.setText("" + MetaDataTags.getLongitude());
MetaData:
public String getLongitude() {
try {
Metadata metadata = ImageMetadataReader.readMetadata(jpegFile);
if (metadata.containsDirectory(GpsDirectory.class)) {
GpsDirectory gpsDir = (GpsDirectory) metadata.getDirectory(GpsDirectory.class);
GpsDescriptor gpsDesc = new GpsDescriptor(gpsDir);
String Longitude = "" + gpsDesc.getGpsLongitudeDescription();
}
} catch (ImageProcessingException ex) {
Logger.getLogger(MetaData.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error 1");
} catch (IOException ex) {
Logger.getLogger(MetaData.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error 2");
}
return longitude;
}
If I set the longitude to be displayed in the JTextPane, it returns "null". If however, I set it to print out on the command line, it prints the longitude fine?
Please excuse me if its a simple solution. I'm still getting to grips with Java.
Java is case sensitive and declare firstly your variable outside of try & catch statement.
Use a IDE like Eclipse to reduce syntax errors like these.
so you should have :
public String getLongitude() {
String longitudeDesc ="";
try {
Metadata metadata = ImageMetadataReader.readMetadata(jpegFile);
if (metadata.containsDirectory(GpsDirectory.class)) {
GpsDirectory gpsDir = (GpsDirectory) metadata.getDirectory(GpsDirectory.class);
GpsDescriptor gpsDesc = new GpsDescriptor(gpsDir);
longitudeDesc = "" + gpsDesc.getGpsLongitudeDescription();
}
} catch (ImageProcessingException ex) {
Logger.getLogger(MetaData.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error 1");
} catch (IOException ex) {
Logger.getLogger(MetaData.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error 2");
}
return longitudeDesc ;
}

Resources