Phonegap FileUpload Java Server - java

I am trying to upload an Image on Java Server.the File is trnsfering from android device but saving null on server .
Here is server code
public UploadMediaServerResponse uploadFileForFunBoard(#FormDataParam("photoPath") InputStream photoInputStream,
#FormDataParam("photoPath") FormDataContentDisposition photoFileDetail,
#FormDataParam("userId") int userId, #FormDataParam("mediaType") String mediaType,
#FormDataParam("title") String title,#FormDataParam("funBoardId") int funBoardId)
{
MediaContenModel mediaContenModel = new MediaContenModel();
mediaContenModel.setFunBoardId(funBoardId);
mediaContenModel.setMediaType(mediaType);
mediaContenModel.setUserId(userId);
UploadMediaServerResponse uploadMediaServerResponse = new UploadMediaServerResponse();
boolean isMediaProcessedAndUploaded = true;
String mediaProcessingError = "";
if (photoInputStream != null && photoFileDetail != null)
{
uploadMediaServerResponse = mediaService.uploadOnServer(photoInputStream,
photoFileDetail.getFileName(), userId+"");
if (uploadMediaServerResponse != null
&& !uploadMediaServerResponse.getMediaUrl().equalsIgnoreCase("ERROR"))
{
mediaContenModel.setImageUrl(uploadMediaServerResponse.getMediaUrl());
logger.debug("ContentService --> createStroyline --> fearture Image url ::"
+ uploadMediaServerResponse.getMediaUrl());
}
else
{
isMediaProcessedAndUploaded = false;
mediaProcessingError = uploadMediaServerResponse.getMediaUrl();
logger.debug("ContentService --> createStroyline --> mediaProcessingError ::"
+ mediaProcessingError);
}
}
if (isMediaProcessedAndUploaded)
{
UploadMediaServerResponse response = funBoardService.uploadMediaContent(mediaContenModel);
uploadMediaServerResponse.setMediaUrl(response.getMediaUrl());
}
else
{
uploadMediaServerResponse.setError("Task Failed");
uploadMediaServerResponse.setStatus(ServiceAPIStatus.FAILED.getStatus());
}
return uploadMediaServerResponse;
}
here is my phonegap code
var pictureSource;
var destinationType;
function onPhotoURISuccess(imageURI)
{
console.log(imageURI);
var largeImage = document.getElementById('largeImage');
largeImage.style.display = 'block';
largeImage.src = imageURI;
var options = new FileUploadOptions();
options.fileKey="photoPath";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
options.params = {
"userId": 1,
"funBoardId": 3,
"mediaType": 'image'
};
console.log(JSON.stringify(options));
var ft = new FileTransfer();
ft.upload(imageURI, _BaseURL+"mobile/userService/funboard/upload", win, fail, options);
}
function onPhotoDataSuccess(imageURI)
{
var imgProfile = document.getElementById('imgProfile');
imgProfile.src = imageURI;
if(sessionStorage.isprofileimage==1)
{
getLocation();
}
movePic(imageURI);
}
function onFail(message)
{
alert('Failed because: ' + message);
}
function movePic(file)
{
window.resolveLocalFileSystemURI(file, resolveOnSuccess, resOnError);
}
function resolveOnSuccess(entry)
{
var d = new Date();
var n = d.getTime();
var newFileName = n + ".jpg";
var myFolderApp = "MyAppFolder";
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys)
{
fileSys.root.getDirectory( myFolderApp,
{create:true, exclusive: false},
function(directory)
{
entry.moveTo(directory, newFileName, successMove, resOnError);
},
resOnError);
},
resOnError);
}
function successMove(entry)
{
alert(entry.fullPath);
sessionStorage.setItem('imagepath', entry.fullPath);
}
function resOnError(error)
{
alert(error.code);
}
function capturePhotoEdit()
{
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,
destinationType: destinationType.DATA_URL });
}
function getPhoto(source)
{
navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: source });
}
function onFail(message)
{
alert('Failed because: ' + message);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
alert(r.response);
}
function fail(error) {
alert("An error has occurred: Code = " = error.code);
}
04-14 19:33:46.010: E/FileTransfer(13550): java.io.FileNotFoundException: http:///jeeyoh/mobile/userService/funboard/upload
Thanks in Advance

Replace
options.fileKey="file";
To
options.fileKey="photoPath";

Related

Android yuv_420_888 mp4 1080p output is graysale on some devices like S21 and green bars on S22

I am trying to make an mp4 video recoding, its not working on all android devices and I am getting grayscale recordings on S21 Android OS 12, S22 Green bars
Not sure where I went wrong, Following is all the possible code that could impact
What I am expecting is that it should work on all devices producing colored 1080p mp4 video and no green bars
ImageAnalysis Initilization
val imageAnalysis = ImageAnalysis.Builder()
// enable the following line if RGBA output is needed.
// .setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_RGBA_8888)
.setOutputImageRotationEnabled(true)
//.setTargetAspectRatio(quality.getAspectRatio(quality))
.setTargetResolution(fhdResolution)
.setBackpressureStrategy(ImageAnalysis.STRATEGY_BLOCK_PRODUCER)
.build()
imageAnalysis.setAnalyzer(executorService, ImageAnalysis.Analyzer { imageProxy ->
// convert image to bytearray before closing
val bytearray = ImageUtil.imageToNv21ByteArray(imageProxy)
imageProxy.close()
frameMetadata?.let {
val metadata = it
bytearray?.let {
trySend(
FrameWrapper(
it,
imageProxy.imageInfo,
imageProxy.width,
imageProxy.height,
state,
metadata
)
)
}
}
})
imageToNv21ByteArray
fun imageToNv21ByteArray(image: ImageProxy): ByteArray? {
var data: ByteArray? = null
if (image.format == ImageFormat.YUV_420_888) {
data = yuv_420_888toNv21(image) // <=== this seems to be the best one
} else {
Timber.e("Unrecognized image format: %s", image.format)
}
return data
}
yuv_420_888toNv21
private fun yuv_420_888toNv21(image: ImageProxy): ByteArray? {
val yPlane = image.planes[0]
val uPlane = image.planes[1]
val vPlane = image.planes[2]
val yBuffer = yPlane.buffer
val uBuffer = uPlane.buffer
val vBuffer = vPlane.buffer
yBuffer.rewind()
uBuffer.rewind()
vBuffer.rewind()
val ySize = yBuffer.remaining()
var position = 0
// TODO(b/115743986): Pull these bytes from a pool instead of allocating for every image.
val nv21 = ByteArray(ySize + image.width * image.height / 2)
// Add the full y buffer to the array. If rowStride > 1, some padding may be skipped.
for (row in 0 until image.height) {
yBuffer[nv21, position, image.width]
position += image.width
yBuffer.position(
Math.min(ySize, yBuffer.position() - image.width + yPlane.rowStride)
)
}
val chromaHeight = image.height / 2
val chromaWidth = image.width / 2
val vRowStride = vPlane.rowStride
val uRowStride = uPlane.rowStride
val vPixelStride = vPlane.pixelStride
val uPixelStride = uPlane.pixelStride
// Interleave the u and v frames, filling up the rest of the buffer. Use two line buffers to
// perform faster bulk gets from the byte buffers.
val vLineBuffer = ByteArray(vRowStride)
val uLineBuffer = ByteArray(uRowStride)
for (row in 0 until chromaHeight) {
vBuffer[vLineBuffer, 0, Math.min(vRowStride, vBuffer.remaining())]
uBuffer[uLineBuffer, 0, Math.min(uRowStride, uBuffer.remaining())]
var vLineBufferPosition = 0
var uLineBufferPosition = 0
for (col in 0 until chromaWidth) {
nv21[position++] = vLineBuffer[vLineBufferPosition]
nv21[position++] = uLineBuffer[uLineBufferPosition]
vLineBufferPosition += vPixelStride
uLineBufferPosition += uPixelStride
}
}
return nv21
}
Mp4EncoderFrameFlowConsumer
class Mp4EncoderFrameFlowConsumer(var context: Context, callback: (videoStartTime: Long) -> Unit) : OpsisModule {
var recording = false
var pendingStart = false
var encoder: VideoEncoder? = null
var job: Job? = null
var videoStartTime: Long? = null
var callback:((videoStartTime: Long) -> Unit) = callback
override fun start() {
thread(start = true) {
val frameFlow: FrameFlow = FlowManager.getFlow(FlowManager.FlowType.frame) as FrameFlow
runBlocking {
job = CoroutineScope(Job()).launch {
frameFlow.frameFlow().collect {
if (pendingStart) {
val wrapper = it
pendingStart = false
encoder?.let {
it.startEncoding(wrapper.width, wrapper.height)
}
}
if (recording) {
if (videoStartTime == null) {
videoStartTime = it.frameMetadata.timestamp
callback(videoStartTime!!)
}
addFrame(it)
}
}
}
}
}
Timber.d("Done encoder consumer")
}
override fun startRecording() {
recording = true;
Timber.d("Start Recording")
encoder = VideoEncoder()
pendingStart = true
}
override fun stopRecording(startFrame:Long, dir:File, callback: (result: File) -> Unit) {
if (recording) {
recording = false
encoder?.let {
try {
it.stopEncoding() { file ->
// copy file to directory
val newfile = File(dir.absolutePath + "/breeze_video.mp4")
if (file.exists()) {
file.copyTo(newfile)
file.delete()
}
callback(newfile)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
override fun stop() {
Timber.d("STOPPING ENCODER CONSUMER")
job?.let {
it.cancel()
}
}
suspend fun addFrame(wrapper: FrameWrapper) {
// Timber.d("RECORD META ${wrapper.frameMetadata.timestamp} FRAME ${wrapper.info.timestamp}")
encoder?.let {
it.addFrame(wrapper.image)
}
}
}
VideoEncoder
class VideoEncoder() {
var mOutputFile: File? = null
private var mediaCodec: MediaCodec? = null
private var mediaMuxer: MediaMuxer? = null
private var mGenerateIndex = 0
private var mTrackIndex = 0
private var mNoMoreFrames = false
private var mAbort = false
private val _encodingFlow = MutableSharedFlow<ByteArray>(
extraBufferCapacity = 20,
onBufferOverflow = BufferOverflow.DROP_OLDEST
)
init {
mOutputFile = File(Util.getFilePath("opsis_video", ".mp4"))
thread(start = true) {
runBlocking {
CoroutineScope(Job()).launch {
_encodingFlow.collect {
mediaCodec?.let { codec ->
mediaMuxer?.let { muxer ->
try {
val TIMEOUT_USEC: Long = 500000
val inputBufIndex = codec.dequeueInputBuffer(TIMEOUT_USEC)
val ptsUsec =
computePresentationTime(mGenerateIndex.toLong(), FRAME_RATE)
if (inputBufIndex >= 0) {
val inputBuffer: ByteBuffer? =
codec.getInputBuffer(inputBufIndex)
inputBuffer?.let { buffer ->
buffer.clear()
buffer.put(it)
try {
codec.queueInputBuffer(inputBufIndex, 0, it.size, ptsUsec, 0)
} catch (e: Exception) {
e.printStackTrace()
}
mGenerateIndex++
}
}
val mBufferInfo = MediaCodec.BufferInfo()
val encoderStatus =
codec.dequeueOutputBuffer(mBufferInfo, TIMEOUT_USEC)
if (encoderStatus == MediaCodec.INFO_TRY_AGAIN_LATER) {
// no output available yet
Timber.e("No output from encoder available")
} else if (encoderStatus == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
// not expected for an encoder
val newFormat = codec.outputFormat
mTrackIndex = muxer.addTrack(newFormat)
muxer.start()
} else if (encoderStatus < 0) {
Timber.e("unexpected result from encoder.dequeueOutputBuffer: $encoderStatus")
} else if (mBufferInfo.size != 0) {
val encodedData: ByteBuffer? =
codec.getOutputBuffer(encoderStatus)
if (encodedData == null) {
Timber.e("encoderOutputBuffer $encoderStatus was null")
} else {
encodedData.position(mBufferInfo.offset)
encodedData.limit(mBufferInfo.offset + mBufferInfo.size)
muxer.writeSampleData(
mTrackIndex,
encodedData,
mBufferInfo
)
codec.releaseOutputBuffer(encoderStatus, false)
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
}
}
}
}
fun encodingFlow(): Flow<ByteArray> {
return _encodingFlow
}
val isEncodingStarted: Boolean
get() = mediaCodec != null && mediaMuxer != null && !mNoMoreFrames && !mAbort
fun startEncoding(width: Int, height: Int) {
mWidth = width
mHeight = height
val outputFile = mOutputFile!!
val outputFileString: String
outputFileString = try {
outputFile.getCanonicalPath()
} catch (e: IOException) {
Timber.e("Unable to get path for $outputFile")
return
}
val codecInfo = selectCodec(MIME_TYPE)
if (codecInfo == null) {
Timber.e("Unable to find an appropriate codec for " + MIME_TYPE)
return
}
Timber.d("found codec: " + codecInfo.name)
mediaCodec = try {
MediaCodec.createByCodecName(codecInfo.name)
} catch (e: IOException) {
Timber.e("Unable to create MediaCodec " + e.message)
return
}
val mediaFormat = MediaFormat.createVideoFormat(MIME_TYPE, mWidth, mHeight)
mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, BIT_RATE)
mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, FRAME_RATE)
mediaFormat.setInteger(
MediaFormat.KEY_COLOR_FORMAT,
CodecCapabilities.COLOR_FormatYUV420Flexible
)
mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, I_FRAME_INTERVAL)
mediaCodec?.let { codec ->
codec.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
codec.start()
mediaMuxer = try {
MediaMuxer(outputFileString, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4)
} catch (e: IOException) {
Timber.e("MediaMuxer creation failed. " + e.message)
return
}
Timber.d("Initialization complete. Starting encoder...")
}
}
suspend fun addFrame(frame: ByteArray) {
_encodingFlow.emit(frame)
}
fun stopEncoding(callback: (result: File) -> Unit) {
release()
callback(mOutputFile!!)
}
private fun release() {
mediaCodec?.let {
try {
it.stop()
it.release()
} catch (e: Exception) {
e.printStackTrace()
}
mediaCodec = null
}
mediaMuxer?.let {
try {
it.stop()
it.release()
} catch (e: Exception) {
e.printStackTrace()
}
mediaMuxer = null
}
}
// from google:
// https://android.googlesource.com/platform/cts/+/jb-mr2-release/tests/tests/media/src/android/media/cts/EncodeDecodeTest.java#1128
private fun computePresentationTime(frameIndex: Long, framerate: Int): Long {
return 132 + frameIndex * 1000000 / framerate
}
companion object {
private const val MIME_TYPE = "video/avc" // H.264 Advanced Video Coding
private var mWidth = 0
private var mHeight = 0
private const val BIT_RATE = 16000000
private const val FRAME_RATE = 30 // Frames per second
private const val I_FRAME_INTERVAL = 1
private fun selectCodec(mimeType: String): MediaCodecInfo? {
val numCodecs = MediaCodecList.getCodecCount()
for (i in 0 until numCodecs) {
val codecInfo = MediaCodecList.getCodecInfoAt(i)
if (!codecInfo.isEncoder) {
continue
}
val types = codecInfo.supportedTypes
for (j in types.indices) {
if (types[j].equals(mimeType, ignoreCase = true)) {
return codecInfo
}
}
}
return null
}
}
}

Uncaught SyntaxError: Unexpected end of JSON input at Function.parse [as parseJSON] (<anonymous>)

I've been getting this error. How can I fix it?
Error
Uncaught SyntaxError: Unexpected end of JSON input
at Function.parse [as parseJSON] ()
at Object. (:128:24)
at i (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at A (jquery.min.js:4)
at XMLHttpRequest. (jquery.min.js:4)
Screenshot of the error (transcribed here)
File asqBatch.jsp
When I click the button.
function genExcelRep() {
var param = "${urlExcelLink}?year=${batchData.year}&period=${batchData.period}&programId=${batchData.programId}&batchId=${batchData.batchId}";
repDialog = BootstrapDialog.show({
title: "Generating Report",
message: '<h1 style="text-align:center;vertical-align: middle;"><i class="fa fa-spinner fa-spin" style="font-size:40px;color:black"></i> 5%</h1>',
onshow: function(dialogRef) {
dialogRef.enableButtons(false);
dialogRef.setClosable(false);
$.ajax({
type: "POST",
url: param,
cache: false
})
.done(function(result) {
console.log(result);
var data = $.parseJSON(result);
alert(json.pid);
alert("done(function(result) 1");
dialogRef.setMessage(data.result);
alert("done(function(result) 2");
if(data.isSuccess) {
alert("if(data.isSuccess)");
if(data.result == "Session Timeout") {
alert("Session Timeout");
SessionTimeOutRedirect("${redirectLink}");
}
else {
alert("generateExcelReport jsp");
generateExcelReport(data);
}
}
else {
alert("else(data.isSuccess)");
dialogRef.enableButtons(true);
dialogRef.setClosable(true);
}
});
},
closable: false,
closeByBackdrop: false,
closeByKeyboard: false,
buttons: [{
label: 'Close',
action: function(dialogRef) {
dialogRef.close();
}
}]
});
}
Controller
model.addAttribute("urlExcelLink", "mainASQBatch/DownloadExcel.htm");
model.addAttribute("contGenExcelUrl", "mainASQBatch/contGenerateExcel.htm");
The #RequestMapping part
#RequestMapping(method = RequestMethod.POST, value="/DownloadExcel") //
public void DownloadExcel(#ModelAttribute("ResultASQDataVO") ResultASQBatchVO vo, ModelMap model, HttpServletRequest req, HttpSession session, HttpServletResponse res) {
logger.info("generateExcelReportPart1 year:" + vo.getYear() +
"," + vo.getPeriod() +
"," + vo.getProgramId() +
"," + vo.getBatchId());
ResultASQDataVO rec = new ResultASQDataVO(vo.getYear(),
vo.getPeriod(),
vo.getProgramId(),
vo.getBatchId());
if(CommonMethod.IsSessionTimeOut(session)) {
rec.setResult("Session Timeout");
rec.setSuccess(true);
}
else {
boolean isSuccess = false;
String result = "";
try {
logger.info("generateExcelReportPart1 1");
List<ResultASQDataVO> lstReport = resultASQDataSER.distinctWorkSheet(
new ResultASQDataVO(rec.getYear(),
rec.getPeriod(),
rec.getProgramId(),
rec.getBatchId()));
String arr = lstReport.toString();
rec.setListReports(String.join(";", arr));
logger.info("generateExcelReportPart1 2");
int cnt = lstReport.size() + 1;
String dirReports = ReportCommonMethod.getTempReportFolderWithTimeStamp(new File(context.getRealPath("/")));
rec.setDirPath(dirReports);
rec.setFiles("");
float noIncrement = 0f;
rec.setSuccess(isSuccess);
logger.info("generateExcelReportPart1 3");
if(CommonMethod.validate(rec.getListReports())) {
rec.setSuccess(true);
noIncrement = 100/(cnt);
logger.info("generateExcelReportPart1 4");
while(noIncrement*cnt>100) {
noIncrement -= 0.25;
}
isSuccess = true;
result = REPORT_GENERATE_RESULT.PROGRESS.getAlert(String.valueOf(Math.round(noIncrement)) + "%");
}
logger.info("generateExcelReportPart1 5");
rec.setCurrentProgress(noIncrement);
rec.setNoIncrement(noIncrement);
rec.setResult(result);
rec.setSuccess(isSuccess);
}
catch (SQLException e) {
logger.info("Localized Message: " + e.getLocalizedMessage());
logger.info("Exception Message: " + e.getMessage());
logger.info("Exception Cause: " + e.getCause());
e.printStackTrace();
e.printStackTrace();
}
}
}
The values in "rec.setResult(result)" should be shown in the module .jsp file.

Unable to upload a file through multipart form data from java as well as postman

I have been trying to upload a file from java as well as postman. But I am unable to upload. The server is giving back the response as 200 Ok. But, the file is not being uploaded.
API Details:
I have an API for uploading file as "FileExplorerController". This API has a method "upload()" to upload the files. Url to access this method is"/fileupload". The API is working fine if I upload a file through HTML UI.
But I am trying to upload using Java. I have tried using Postman as well.
I have passed the multipart form data in several ways. But unable to resolve the issue. The code is as follows.
API - Upload - Function
public Result upload() {
String fileName="";
String folderPath="";
String fileDescription="";
String userName = "";
StopWatch stopWatch = null;
List<FileUploadStatusVo> fileStatus = new ArrayList<>();
try {
stopWatch = LoggerUtil.startTime("FileExplorerController -->
upload() : File Upload");
StringBuilder exceptionBuilder = new StringBuilder();
Http.MultipartFormData body =
play.mvc.Controller.request().body().asMultipartFormData();
Http.Context ctx = Http.Context.current();
userName = ctx.session().get(SessionUtil.USER_NAME);
String password = "";
if(StringUtils.isBlank(userName)) {
Map<String, String[]> formValues = play.mvc.Controller.
request().body().asMultipartFormData().asFormUrlEncoded();
if(formValues != null) {
if(formValues.get("userName") != null &&
formValues.get("userName").length > 0) {
userName = formValues.get("userName")[0];
}
if(formValues.get("password") != null &&
formValues.get("password").length > 0) {
password = formValues.get("password")[0];
}
}
if(StringUtils.isBlank(userName) ||
StringUtils.isBlank(password)) {
return Envelope.ok();
}
UserVo userVo = userService.findUserByEmail(userName);
boolean success = BCrypt.checkpw(password, userVo.password);
if(!success) {
return badRequest("Password doesn't match for the given user
name: "+userName);
}
if(userVo == null) {
return Envelope.ok();
}
}
boolean override = false;
String fileTags="";
boolean isPublicView = false;
boolean isPublicDownload = false;
boolean isPublicDelete = false;
boolean isEmailNotification = false;
boolean isEmailWithS3Link = false;
List<String> viewerGroupNames = new ArrayList<>();
List<String> downloaderGroupNames = new ArrayList<>();
List<String> deleterGroupNames = new ArrayList<>();
List<String> viewerUserNames = new ArrayList<>();
List<String> downloaderUserNames = new ArrayList<>();
List<String> deleterUserNames = new ArrayList<>();
List<String> emailIds = new ArrayList<>();
Map<String, String[]> formValues =
play.mvc.Controller.request().body().
asMultipartFormData().asFormUrlEncoded();
JSONObject obj = new JSONObject(formValues.get("model")[0]);
Set<String> groupNames = new HashSet<>();
Set<String> userNames = new HashSet<>();
if(obj != null) {
if(obj.get("override") != null) {
override = Boolean.valueOf(obj.get("override").toString());
}
if(obj.get("description") != null) {
fileDescription = obj.get("description").toString();
}
if(obj.get("tags") != null) {
fileTags = obj.get("tags").toString();
}
if(obj.get("folderPath") != null){
folderPath = obj.get("folderPath").toString();
} else {
folderPath =
ctx.session().get(SessionUtil.LOCAL_STORAGE_PATH);
}
if(obj.get("isPublicView") != null) {
isPublicView =
Boolean.parseBoolean(obj.get("isPublicView").toString());
}
if(obj.get("isPublicDownload") != null) {
isPublicDownload =
Boolean.parseBoolean(obj.get("isPublicDownload").toString());
}
if(obj.get("isPublicDelete") != null) {
isPublicDelete = Boolean.parseBoolean(
obj.get("isPublicDelete").toString());
}
if(obj.get("emailNotification") != null) {
isEmailNotification =
Boolean.parseBoolean(obj.get("emailNotification").toString());
}
if(obj.get("emailWithFileAttachement") != null) {
isEmailWithS3Link =
Boolean.parseBoolean(obj.get(
"emailWithFileAttachement").toString());
}
if(obj.get("viewerGroupNames") != null) {
//TODO
if(!isPublicView) {
String[] namesArr =
(obj.get("viewerGroupNames").toString()).split(",");
for(String name:namesArr) {
if(StringUtils.isNotEmpty(name)) {
viewerGroupNames.add(name);
groupNames.add(name);
}
}
}
}
if(obj.get("downloaderGroupNames") != null) {
//TODO
if(!isPublicDownload) {
String[] namesArr =
(obj.get("downloaderGroupNames").toString().split(","));
for(String name:namesArr){
if(StringUtils.isNotEmpty(name)) {
downloaderGroupNames.add(name);
groupNames.add(name);
}
}
}
}
if(obj.get("deleteGroupNames") != null) {
//TODO
if(!isPublicDelete){
String[] namesArr =
(obj.get("deleteGroupNames").toString().split(","));
for(String name:namesArr){
if(StringUtils.isNotEmpty(name)) {
deleterGroupNames.add(name);
groupNames.add(name);
}
}
}
}
if(obj.get("viewerUserNames") != null) {
//TODO
if(!isPublicView) {
String[] namesArr =
(obj.get("viewerUserNames").toString()).split(",");
for(String name:namesArr) {
if(StringUtils.isNotEmpty(name)) {
viewerUserNames.add(name);
userNames.add(name);
}
}
}
}
if(obj.get("downloaderUserNames") != null) {
//TODO
if(!isPublicDownload) {
String[] namesArr =
(obj.get("downloaderUserNames").toString().split(","));
for(String name:namesArr){
if(StringUtils.isNotEmpty(name)) {
downloaderUserNames.add(name);
userNames.add(name);
}
}
}
}
if(obj.get("deleteUserNames") != null) {
//TODO
if(!isPublicDelete){
String[] namesArr =
(obj.get("deleteUserNames").toString().split(","));
for(String name:namesArr){
if(StringUtils.isNotEmpty(name)) {
deleterUserNames.add(name);
userNames.add(name);
}
}
}
}
if(obj.get("emailIds") != null) {
if(isEmailWithS3Link) {
String[] emailIdsArr =
(obj.get("emailIds").toString()).split(",");
for(String emailId:emailIdsArr){
if(StringUtils.isNotEmpty(emailId)){
emailIds.add(emailId);
}
}
}
}
}
if(groupNames.size() == 0 && userNames.size() == 0){
isEmailNotification = false;
}
List<Http.MultipartFormData.FilePart> files = body.getFiles();
boolean multiUpload = false;
if(files != null && files.size() > 1) {
multiUpload = true;
}
Logger.info("Total Number of files is to be uploaded:"+ files.size()
+" by user: " + userName);
int uploadCount = 0;
List<String> fileNames = new ArrayList<>();
List<String> fileMasters = new ArrayList<>();
FileMasterVo fileMasterVo = null;
UserVo userVo = userService.findUserByEmail(userName);
for(Http.MultipartFormData.FilePart uploadedFile: files) {
if (uploadedFile == null) {
return badRequest("File upload error for file " +
uploadedFile + " for file path: " + fileName);
}
uploadCount++;
String contentType = uploadedFile.getContentType();
String name = uploadedFile.getFile().getName();
Logger.info("Content Type: " + contentType);
Logger.info("File Name: " + fileName);
Logger.info("Name: " + name);
Logger.info("Files Processed : "+uploadCount+"/"+files.size()+"
for user: "+userName);
try {
String extension =
FileUtil.getExtension(uploadedFile.getFilename()).toLowerCase();
File renamedUploadFile =
FileUtil.moveTemporaryFile(System.getProperty("java.io.tmpdir"),
System.currentTimeMillis() + "_" +
uploadedFile.getFilename(), uploadedFile.getFile());
FileInputStream fis = new
FileInputStream(renamedUploadFile);
String errorMsg = "";
fileName = folderPath + uploadedFile.getFilename();
fileNames.add(uploadedFile.getFilename());
if(multiUpload) {
Logger.info("Attempting to upload file " + folderPath +
"/" + uploadedFile.getFilename());
fileMasterVo = fileService.upload(folderPath,fileName,
fileDescription, new Date(), fis, fis.available(),
extension, override,
fileTags, isPublicView, isPublicDownload,
isPublicDelete, viewerGroupNames, downloaderGroupNames,
deleterGroupNames, viewerUserNames,
downloaderUserNames,
deleterUserNames,userName,isEmailNotification);
} else if(fileName != null) {
Logger.info("Attempting to upload file " + fileName);
int index = fileName.lastIndexOf("/");
if (index > 1) {
fileMasterVo =
fileService.upload(folderPath,fileName, fileDescription,
new Date(), fis, fis.available(), extension, override,
fileTags, isPublicView, isPublicDownload,
isPublicDelete, viewerGroupNames, downloaderGroupNames,
deleterGroupNames, viewerUserNames,
downloaderUserNames,
deleterUserNames,userName,isEmailNotification);
} else {
errorMsg = "Root Folder MUST exist to upload any
file";
return badRequest(errorMsg);
}
} else {
errorMsg = "File Name is incorrect";
return badRequest(errorMsg);
}
createFileActivityLog(
fileMasterVo,userVo,ViewConstants.UPLOADED);
if (fileMasterVo != null && fileMasterVo.getId() != null) {
fileMasters.add(fileMasterVo.getId().toString());
}
} catch (Exception inEx) {
createErrorLog(userName,fileName,inEx);
exceptionBuilder.append("Exception occured in uploading
file: ");
exceptionBuilder.append(name);
exceptionBuilder.append(" are as follows ");
exceptionBuilder.append(ExceptionUtils.getStackTrace(inEx));
}
fileStatus.add(new
FileUploadStatusVo(uploadedFile.getFilename(),
fileMasterVo.getStatus()));
}
if(isEmailNotification){
fileService.sendNotificationForFile(folderPath,fileNames,
userName, groupNames,
userNames, ViewConstants.UPLOADED);
}
if (isEmailWithS3Link) {
//fileService.sendFileS3Link(folderPath, emailIds, fileMasters);
// Replacing sending S3 link with sending cdi specific link
fileService.sendFilesLink(emailIds, fileMasters);
}
String exceptions = exceptionBuilder.toString();
LoggerUtil.endTime(stopWatch);
if(!StringUtils.isBlank(exceptions)) {
Logger.error("Exception occured while uploading file: " +
fileName + " are as follows " + exceptions);
}
return Envelope.ok(fileStatus);
} catch (Exception inEx) {
createErrorLog(userName,fileName,inEx);
return badRequest("There is a system error please contact
support/administrator" );
} }
Client
**Client - Program**
multipart.addFormField("fileName",file.getAbsolutePath());
multipart.addFormField("folderPath","D/");
multipart.addFormField("fileDescription","Desc");
multipart.addFormField("userName","superadmin");
multipart.addFormField("password","admin");
multipart.addFormField("override","false");
multipart.addFormField("fileTags","tag");
multipart.addFormField("isPublicView","true");
multipart.addFormField("isPublicDownload","true");
multipart.addFormField("isPublicDelete","false");
multipart.addFormField("isEmailNotification","false");
multipart.addFormField("isEmailWithS3Link","true");*/
multipart.addFormField("file", input);
System.out.print("SERVER REPLIED: ");
for (String line : response)
{
System.out.print(line);
}
// synchronize(clientFolder, uploadFolder, true);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
I am able to upload using the following code snippet.
Here "model" is a json object which contain all parameters.
DefaultHttpClient client = new DefaultHttpClient();
HttpEntity entity = MultipartEntityBuilder
.create()
.addTextBody("userName", userName)
.addTextBody("password", passWord)
.addBinaryBody("upload_file", new File(sourceFolder + "/" + fileName), ContentType.create("application/octet-stream"), fileName)
.addTextBody("model", object.toString())
.build();
HttpPost post = new HttpPost(uploadURL);
post.setEntity(entity);
HttpResponse response = null;
try {
response = client.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
logger.info("File " + file.getName() + " Successfully Uploaded At: " + destination);
} else {
logger.info("File Upload Unsuccessful");
}
logger.info("Response from server:" + response.getStatusLine());
} catch (ClientProtocolException e) {
logger.error("Client Protocol Exception");
logger.error(e.getMessage());

Request body empty (?) after migrating to Endpoints Framework 2.0

I have a Java Google Endpoint as follows
#ApiMethod(
name="createShiftlist",
path="jeugdhuis/{websafeJeugdhuisKey}/shiftlists",
httpMethod="POST",
authenticators={FirebaseAuthenticator.class}
)
public void createShiftlist(User user, #Named("websafeJeugdhuisKey") String websafeJeugdhuisKey, ShiftlistForm shiftlistForm)
throws UnauthorizedException {
if (shiftlistForm.getStart() == null)
throw new IllegalArgumentException(shiftlistForm.getStart() + " " + shiftlistForm.getPartyName() + " " + shiftlistForm.getEnd());
if (user == null)
throw new UnauthorizedException("User is not logged in!");
if (!JukteUserAPI.isJeugdhuisAdmin(user, websafeJeugdhuisKey))
throw new UnauthorizedException("Logged in user is not an admin of the given Jeugdhuis.");
OfyService.ofy().save().entities(new Shiftlist[] {
new Shiftlist(
OfyService.factory().allocateId(Key.create(websafeJeugdhuisKey), Shiftlist.class).getId(),
websafeJeugdhuisKey, shiftlistForm.getPartyName(), shiftlistForm.getStart(), shiftlistForm.getEnd())
});
}
I use the following .js to call it.
var jukteapi = jukteapi || {};
var jukteKey = 'myKey';
function XHRBuilder(appId, apiName, version) {
this.root = "https://" + appId + ".appspot.com/_ah/api/" + apiName + "/" + version + "/";
this.params;
this.method;
this.endpoint;
this.authorizationToken;
this.onsucces;
this.get = function() {
this.method = 'GET';
return this;
};
this.post = function() {
this.method = 'POST';
return this;
};
this.delete = function() {
this.method = 'DELETE';
return this;
};
this.put = function() {
this.method = 'PUT';
return this;
}
this.path = function(endpointPath) {
this.endpoint = endpointPath;
return this;
};
this.authorizationToken = function(token) {
this.authorizationToken = token;
return this;
};
this.onsucces = function(func) {
this.onsucces = func;
return this;
};
this.addParam = function(paramName, paramValue) {
if (this.params === undefined)
this.params = new FormData();
this.params.append(paramName, paramValue);
return this;
};
this.send = function() {
var xhr = new XMLHttpRequest();
xhr.open(this.method, this.root + this.endpoint);
var self = this.onsucces;
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200)
self(JSON.parse(xhr.responseText));
else if (xhr.readyState == 4 && xhr.status == 204)
self();
else if (xhr.readyState == 4 && xhr.status == 400)
alert(JSON.parse(xhr.responseText).error.message);
};
xhr.setRequestHeader('Authorization', 'Bearer ' + this.authorizationToken);
if (typeof this.params !== "undefined")
for (var pair of this.params.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
xhr.send(this.params);
};
}
jukteapi.http = function() {
return new XHRBuilder('jhjukte','jukte','v1')
}
jukteapi.createShiftlist = function(onsucces, name, start, end) {
firebase.auth().currentUser.getIdToken().then(function(idToken) {
jukteapi.http().post()
.path('jeugdhuis/' + jukteKey + '/shiftlists')
.authorizationToken(idToken)
.addParam('partyName', name)
.addParam('start', start + ':00')
.addParam('end', end + ':00')
.onsucces(onsucces)
.send();
});
}
This is the ShiftlistForm class.
package jukte.form;
import java.util.Date;
public class ShiftlistForm {
private String partyName;
private Date start;
private Date end;
#SuppressWarnings("unused")
private ShiftlistForm() {}
public ShiftlistForm(String partyName, Date start, Date end){
this.partyName = partyName;
this.start = start;
this.end = end;
}
public String getPartyName() {
return partyName;
}
public Date getStart() {
return start;
}
public Date getEnd() {
return end;
}
public void setPartyName(String partyName) {
this.partyName = partyName;
}
public void setStart(Date start) {
this.start = start;
}
public void setEnd(Date end) {
this.end = end;
}
}
The endpoint is called, but the variables in ShiftlistForm (start, end, partyName) are null. It worked perfectly before I migrated to 2.0 from 1.0. What is going on?
I believe you may want to try setting your Content-Type header to application/json.

Primefaces wizard. How to return js function tab for onnext

I use Primefaces 3.5. And try to call js function in onnext handler of <p:wizard/>.
I want that onnext return on tab on specific tab after validation result ob current tab. My validation function
function validateManageOtherTournaments(wizard, validationTab, lang) {
var currentTabId = validationTab;
if (currentTabId != 'competitionId') {
return wizard.next();
}
var seasonVal = document.getElementById('manageTournament:name_season_input').value;
var dateFromVal = document.getElementById('manageTournament:dateFrom_input').value;
var dateToVal = document.getElementById('manageTournament:dateTo_input').value;
/*var compNameVal = document.getElementById('manageTournament:title_input').value;*/
var isValidName = validateFieldsInOtherTournament('manageTournament', ['title'], lang);
if (isValidName) {
if (validRuContentT) {
var filledBothDate = (dateFromVal != "" && dateToVal != "");
var isEmptySeason = ("" != String(seasonVal));
if ( filledBothDate || isEmptySeason) {
return wizard.next();
}
}
}
return "competitionId"; // currentTab
}
I use code js wizard. But it still doesn't work.(
//UPDATED
I try to do something like this
function validateManageOtherTournaments(wizard, validationTab, lang) {
/*var wizardElement = document.getElementById('wiz');*/
var currentTabId = validationTab;
if (currentTabId != 'competitionId') {
var currentStepIndex = wizard.getStepIndex(wizard.getState().currentStep),
stepIndexToGo = currentStepIndex + 1;
var stepIdToGo = wizard.cfg.steps[stepIndexToGo];
return wizard.loadStep(stepIdToGo, stepIndexToGo, false); // next
}
var seasonVal = document.getElementById('manageTournament:name_season_input').value;
var dateFromVal = document.getElementById('manageTournament:dateFrom_input').value;
var dateToVal = document.getElementById('manageTournament:dateTo_input').value;
/*var compNameVal = document.getElementById('manageTournament:title_input').value;*/
var isValidName = validateFieldsInOtherTournament('manageTournament', ['title'], lang);
if (isValidName) {
if (validRuContentT) {
var filledBothDate = (dateFromVal != "" && dateToVal != "");
var isEmptySeason = ("" != String(seasonVal));
if ( filledBothDate || isEmptySeason) {
var currentStepIndex = wizard.getStepIndex(wizard.getState().currentStep),
stepIndexToGo = currentStepIndex + 1;
var stepIdToGo = wizard.cfg.steps[stepIndexToGo];
return wizard.loadStep(stepIdToGo, stepIndexToGo, false); // next
}
}
}
var currentStepIndex = wizard.getStepIndex(this.getState().currentStep),
stepIndexToGo = currentStepIndex;
var stepIdToGo = wizard.cfg.steps[stepIndexToGo];
return wizard.loadStep(stepIdToGo, stepIndexToGo, false); //competitionId
}
How I can return in onnext function tab of wizard?
I did something like this:
public String onFlowProcess(FlowEvent event)
{
if (!event.getOldStep().equals("competitionId"))
{
return event.getNewStep();
}
if (validationPassed())
{
return event.getNewStep();
}
else
{
return event.getOldStep();
}
}
private boolean validationPassed()
{
// do your validation here.
// return true if validation passed
}
Then in my wizard: flowListener="#{myBean.onFlowProcess}"

Categories