video streaming is very slow in java spring MVC - java

#RequestMapping(value = "/video/{clientID}/{fileName}", method = RequestMethod.GET)
public ResponseEntity<StreamingResponseBody> getClientVideo(#PathVariable(value = "clientID") Integer clientID, #PathVariable(value = "fileName") final String fileName) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
String absolutePath = new File(".").getAbsolutePath();
File file = new File(Paths.get(absolutePath).getParent() + "/" + clientID);
if (null != file) {
FilenameFilter beginswithm = new FilenameFilter() {
public boolean accept(File directory, String filename) {
return filename.contains("ClientVideo_"+fileName);
}
};
File[] files = file.listFiles(beginswithm);
if (null != files && files.length > 0) {
Resource resource = null;
for (final File f : files) {
headers.set("Content-Disposition", "inline; filename=" + f.getName());
StreamingResponseBody responseBody = new StreamingResponseBody() {
#Override
public void writeTo(OutputStream out) throws IOException {
out.write(Files.readAllBytes(f.toPath()));
out.flush();
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
return ResponseEntity.ok().headers(headers).contentType(MediaType.APPLICATION_OCTET_STREAM).body(responseBody); //(responseBody, headers, HttpStatus.OK);
}
}
}
RecruiterResponseBean resBean = new RecruiterResponseBean();
resBean.setStatusMessage("Video is not present : " + Constants.FAILED);
resBean.setStatusCode(Constants.FAILED_CODE);
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
video streaming is working but it is very slow. how to increase the efficiency?
There is no problem with internet it is 10mbps. i am using tomcat 7 and Spring MVC[4.2.4]. should I change the tomcat capacity or how it can be solve? i am not getting in google.

Related

How to return a view after download a file

My English Hope you can understand me.
Hello guys, im developing a web program using Apache Velocity, but i meet a problem, i cannot return view after output a file by OutPutStream, following is my code:
#Get("test")
public String getPdfInfoByTestId(Invocation invocation, #Param("testIds") String testIds) throws Exception {
HttpServletResponse response = invocation.getResponse();
if (testIds.length() == 0) {
invocation.addModel("status", PdfStatusEnum.NOT_FOUND.getType());
return "admin_pdf_info";
}
String[] idArray = testIds.split(",");
List<Long> idList = string2LongList(testIds);
List<ContestOneTest> contestOneTestList = contestOneTestService.getByIdList(idList);
if (contestOneTestList.size() == 0) {
invocation.addModel("status", PdfStatusEnum.NOT_FOUND.getType());
//response.sendRedirect("index");
return "admin_pdf_info";
}
List<PdfInfo> pdfInfos = new ArrayList<>(contestOneTestList.size() + 1);
//填充表格需要的数据
for (ContestOneTest contestOneTest : contestOneTestList) {
PdfInfo pdfInfo = new PdfInfo();
CtsTestUser ctsTestUser = ctsTestUserService.getUserById(contestOneTest.getActorId());
pdfInfo.setActorName(ctsTestUser.getName());
pdfInfo.setTestId(contestOneTest.getId());
pdfInfo.setPaperName(contestOneTest.getPaperName());
pdfInfo.setPaperId(contestOneTest.getPaperId());
if (contestOneTest.getStatus() == OneTestStatusEnum.FINISHED.getValue() && StringUtils.isNotBlank(contestOneTest.getPdfUrl())) {
pdfInfo.setGenStatus("已处理");
pdfInfo.setRank("无需排队");
pdfInfo.setPdfUrl(contestOneTest.getPdfUrl());
} else {
pdfInfo.setGenStatus("未处理");
Long rank = JedisAdapter.zRank(RedisKeyUtil.getNewContestPdfGenQueue(),
contestOneTest.getId() + "");
pdfInfo.setRank(String.valueOf(rank));
pdfInfo.setPdfUrl("暂无");
}
}
XSSFWorkbook workbook;
String fileName = new StringBuilder().append(contestOneTestList.size())
.append("位考试的PDF生成进度").toString();
try {
//生成表格并作为下载文件输出
workbook = ExcelUtils.buildWorkbook(pdfInfos);
invocation.addModel("status", PdfStatusEnum.HAS_GENERATED);
invocation.addModel("resultCount", contestOneTestList.size());
response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
response.setHeader("Content-Type",
"application/vnd.ms-excel");
OutputStream out = response.getOutputStream();
workbook.write(out);
} catch (Exception e) {
e.printStackTrace();
invocation.addModel("status", PdfStatusEnum.ExcelGenFailed.getType());
}
return "admin_pdf_info";
}
Is there any way to solve my problem?
Very grateful for all answers or suggesstions!

Why the String inside Controller not printing anything?

I am trying to send Image and Id using retrofit for that i am sending Multipart file and String.
This is my Upload Method on Android side ->
private void UploadFiles() {
File uploadFile = fileArrayList.get(0);
if (uploadFile != null) {
Log.d(TAG, "UploadFiles: File Name is -> " + uploadFile.getName());
// Parsing any Media type file
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), uploadFile);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part cropImage = MultipartBody.Part.createFormData("cropImage", uploadFile.getName(), requestFile);
RequestBody cropId = RequestBody.create(MediaType.parse("multipart/form-data"), uploadFile.getParentFile().getName());
Api.uploadCropImage(cropImage,cropId, new Callback<BasicResponse>() {
#Override
public void onResponse(Call<BasicResponse> call, Response<BasicResponse> response) {
if (response.body() != null) {
Log.d(TAG, "onResponse: Success" + response.body().getResponse());
}
else{
Log.d(TAG, "onResponse: null Response");
}
}
#Override
public void onFailure(Call<BasicResponse> call, Throwable t) {
Log.d(TAG, "onResponse: Failure");
}
});
}
}
My Upload CropImage Method ->
public static void uploadCropImage(MultipartBody.Part multipartBody,RequestBody cropId,
Callback<BasicResponse> callback) {
UploadCropImageApi uploadCropImageApi = retrofit.create(UploadCropImageApi.class);
Call<BasicResponse> call = uploadCropImageApi.uploadCropImage(multipartBody,cropId);
call.enqueue(callback);
}
My Interface ->
public interface UploadCropImageApi {
#Multipart
#POST(UPLOAD_FILE_TO_AWS_URL)
Call<BasicResponse> uploadCropImage(#Part MultipartBody.Part cropImage, #Part("cropId") RequestBody cropId);
}
This is my Spring Controller, What's wrong with it? It's not printing cropId.
#RequestMapping(value = "/UploadCropImage", method = RequestMethod.POST, consumes = {"multipart/form-data"})
#ResponseBody
public String UploadImage(#RequestBody MultipartFile cropImage,#RequestBody String cropId ,HttpServletRequest request) {
System.out.println("String is -> " + cropId);
return null;
}
You cannot use two #RequestBody as it can bind to a single object only (the body can be consumed only once)
You need to use #RequestParam String cropId instead of RequestBody.
See here for clarification
UPDATE :Here is your controller method look like
#RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public #ResponseBody ResponseEntity<GenericResponseVO<? extends IServiceVO>> uploadFileHandler(#RequestParam("name") String name, #RequestParam("file") MultipartFile file,HttpServletRequest request, HttpServletResponse response) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
// Creating the directory to store file
String rootPath = System.getProperty("catalina.home");
File dir = new File(rootPath + File.separator + "tmpFiles");
if (!dir.exists())
dir.mkdirs();
// Create the file on server
File serverFile = new File(dir.getAbsolutePath() + File.separator + name);
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
System.out.println("Server File Location=" + serverFile.getAbsolutePath());
return null;
} catch (Exception e) {
return null;
}
}
}

why java streaming video is not playing in crome browser but is playing in firefox

#RequestMapping(value = "/video/{clientID}/{fileName}", method = RequestMethod.GET)
public ResponseEntity<StreamingResponseBody> getClientVideo(#PathVariable(value = "clientID") Integer clientID, #PathVariable(value = "fileName") final String fileName) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
String absolutePath = new File(".").getAbsolutePath();
File file = new File(Paths.get(absolutePath).getParent() + "/" + clientID);
if (null != file) {
FilenameFilter beginswithm = new FilenameFilter() {
public boolean accept(File directory, String filename) {
return filename.contains("ClientVideo_"+fileName);
}
};
File[] files = file.listFiles(beginswithm);
if (null != files && files.length > 0) {
Resource resource = null;
for (final File f : files) {
headers.set("Content-Disposition", "inline; filename=" + f.getName());
StreamingResponseBody responseBody = new StreamingResponseBody() {
#Override
public void writeTo(OutputStream out) throws IOException {
out.write(Files.readAllBytes(f.toPath()));
out.flush();
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
return ResponseEntity.ok().headers(headers).contentType(MediaType.APPLICATION_OCTET_STREAM).body(responseBody); //(responseBody, headers, HttpStatus.OK);
}
}
}
RecruiterResponseBean resBean = new RecruiterResponseBean();
resBean.setStatusMessage("Video is not present : " + Constants.FAILED);
resBean.setStatusCode(Constants.FAILED_CODE);
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
I am using Spring MVC, I tried many methods but all are downloading the video. Above code is streaming the video, the problem is: in firefox it is streaming but in crome it is downloading. I want to play streaming video in crome also like below ex.
[Ex streaming video: http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4]
Do I need to add more Headers? [if so, which headers need to add?]
Or Did i miss anything?

Unit testing an endpoint with #RequestBody

So I am getting a 400 for my HTTP response code when it should be 200. I am passing in a byte[] object to the endpoint but it doesn't seem to be adding the content-type correctly? Any suggestions?
#RequestMapping(value = "/test", method = RequestMethod.POST, consumes = "application/octet-stream")
public ResponseEntity<String> receiveCompressedBinary(#RequestHeader String site, #RequestHeader String customer,
#RequestHeader String table, #RequestBody byte[] binary, #RequestHeader String loadStatus) {
if(binary.length < maxFileSize) {
return new ResponseEntity<String>(HttpStatus.OK);
}
else{
return new ResponseEntity<String>(HttpStatus.PAYLOAD_TOO_LARGE);
}
}
My test:
#Test
public void testUploadCompressedBinaryInitialRunning() throws Exception{
File file = new File("src/test/resources/testFile.txt");
String site = "site";
String customer = "customer";
String table = "table";
String loadStatus = "INITIALRUNNING";
this.mockMvc.perform(post("/test").header("site",site).param("customer",customer).
param("table", table).content(compress(file)).param("loadStatus",loadStatus)
.with(user("user"))).andExpect(status().isOk());
this.mockMvc.perform(post("/uploadCompressedBinary")).andDo(print()).andExpect(status().isOk());
}
Compress method:
public static byte[] compress(File file) throws IOException {
if (file.length() == 0) {
return null;
}
FileInputStream fileInputStream = null;
byte[] fileInBytes = new byte[(int)file.length()];
try {
//convert file into array of bytes
fileInputStream = new FileInputStream(file);
fileInputStream.read(fileInBytes);
fileInputStream.close();
} catch (IOException e) {
System.out.println("Exception whilst compressing the file: " + e.getMessage());
}
ByteArrayOutputStream obj = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(obj);
gzip.write(fileInBytes);
gzip.close();
return obj.toByteArray();
}
UPDATE: Got past it, rather than .param, I should be using .header
It does not look like you are setting the content type when you are posting.
Try
this.mockMvc.perform(post("/test").header("site",site).param("customer",customer).
param("table", table).content(compress(file)).contentType("application/octet-stream").param("loadStatus",loadStatus)
.with(user("user"))).andExpect(status().isOk());

Upload document on google drive in a folder

I want to upload my document on google drive but in a folder. can you please suggest how i insert this into the folder. I have uploaded but this is not in folder. Code is -
#RequestMapping(value = "/uploadDDFile", method = RequestMethod.POST)
public ModelAndView uploadDDFile(#RequestParam(value = "ddid", required = true) Integer ddid,
#RequestParam(value = "catageryId", required = true) Integer catageryId,
#RequestParam(value = "document", required = true) GMultipartFile document[], HttpServletRequest request) {
System.out.println("-------------------------");
String name = "";
DdeDriveDocuments ddeDriveDocuments = new DdeDriveDocuments();
if (ServletFileUpload.isMultipartContent(request) && document != null) {
for (GMultipartFile gdocument : document) {
try {
boolean user = true;
List<DdeDriveDocuments> dds = ddeDriveDocumentsService.fatchData(ddid, catageryId);
for (DdeDriveDocuments file : dds) {
System.out.println(file.getDocument_name());
if (file.getDocument_name().equals(gdocument.getOriginalFilename())) {
user = false;
}
}
if (user == true) {
Client client = sessionService.getClient();
System.out.println(gdocument.getOriginalFilename());
ddeDriveDocuments
.setDocument_name((gdocument.getName() != null ? gdocument.getOriginalFilename() : ""));
ddeDriveDocuments.setDocument_uploadby(client.getEmail());
ddeDriveDocuments.setDocument_created(new Date());
ddeDriveDocuments.setCatagery_id(catageryId);
ddeDriveDocuments.setDd_id(ddid);
ddeDriveDocuments.setDd_uuid(GeneralUtil.getUUID());
ddeDriveDocuments.setClientID(client.getClientID());
Lawyer googleAuthToken = lawyerService
.getAuthorisedUserToken(Configurator.getInstance().getDriveAccountEmail());
if (googleAuthToken != null) {
// upload file in drive
if (ServletFileUpload.isMultipartContent(request) && document != null) {
// It's value either we need to get from form.
String description = "Testing";
File file = DriveService.uploadDocumentToDrive(googleAuthToken, gdocument,
ddeDriveDocuments.getDocument_name(), description);
File thumFile = DriveService.getFileById(googleAuthToken, file.getId());
System.out.println("thumFile ====" + thumFile);
System.out.println("thab url" + thumFile.getIconLink());
if (file != null) {
ddeDriveDocuments.setDocument_drive_id(file.getId());
ddeDriveDocuments.setImageurl(thumFile.getIconLink());
ddeDriveDocuments = ddeDriveDocumentsService.create(ddeDriveDocuments);
}
}
} else {
System.out.println("Autorised token not available for configured drive account.");
}
} else {
System.out.println("wroung Input");
System.out.println("wroung Input");
name = name.concat(gdocument.getOriginalFilename() + " , ");
System.out.println("This is ::::::::::::: " + name);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
if(name !=""){
sessionService.setUnupload_files_name(name);
}
return new ModelAndView("redirect:/al/client/ddeclientportal/" + ddid + "/" + catageryId);
}
public static File uploadDocumentToDrive(Lawyer googleAuthToken,
GMultipartFile file, String fileName, String description) {
File driveFile = null;
try {
InputStream fileStream = file.getInputStream();
String mimeType = DocumentListEntry.MediaType.fromFileName(
file.getOriginalFilename()).getMimeType();
GoogleCredential googleCrednetial = getGoogleCredential(googleAuthToken);
Drive drive = buildService(googleCrednetial);
String file_name = fileName.contains(FilenameUtils.getExtension(file.getOriginalFilename())) ? fileName : fileName + "." + FilenameUtils.getExtension(file.getOriginalFilename());
File body1 = new File();
body1.setTitle("cloudbox");
body1.setMimeType("application/vnd.google-apps.folder");
driveFile = drive.files().insert(body1).execute();
File body = new File();
body.setTitle(file_name);
body.setDescription(description);
body.setMimeType(mimeType);
driveFile = drive.files()
.insert(body, new InputStreamContent(mimeType, fileStream))
.execute();
} catch (Exception e) {
e.printStackTrace();
}
return driveFile;
}
Please help i want insert my document in folder.
By Using
File body1 = new File();
body1.setTitle("cloudbox");
body1.setMimeType("application/vnd.google-apps.folder");
driveFile = drive.files().insert(body1).execute();
File body = new File();
body.setTitle(file_name);
body.setDescription(description);
body.setMimeType(mimeType);
body.setParents(Arrays.asList(new ParentReference().setId(driveFile.getId())));
driveFile = drive.files()
.insert(body, new InputStreamContent(mimeType, fileStream))
.execute();
Now can you please suggest how i can generate subfoler.

Categories