public static Result upload() { try { Http.MultipartFormData body = request().body().asMultipartFormData(); Http.MultipartFormData.FilePart picture = body.getFile("picture"); if (picture != null) { String fileName = picture.getFilename(); logger.info("Uploading file name: {}", fileName); File pictureFile = picture.getFile(); pictureFile.getTotalSpace(); logger.info("Total space: {}", pictureFile); File folder = pictureFile.getParentFile(); File renamedFile = new File(folder, fileName); File result = ExifImageUtils.rotateFromOrientationData(pictureFile, renamedFile); // final String absolutePath = pictureFile.getAbsolutePath(); // final String escapedPath = UrlEscapers.urlPathSegmentEscaper().escape(absolutePath); // return ok(views.html.main.render(escapedPath)); return ok(views.html.main.render(result.getAbsolutePath())); } return ok("asdf"); } catch (Exception e) { logger.error("Error uploading", e); return internalServerError(e.getMessage()); } }
@Security.Authenticated(Secured.class) public static Result upload() { User user = getCurrentUser(); if (!user.isAdmin) return redirect(routes.Application.contacts()); Http.MultipartFormData body = request().body().asMultipartFormData(); Http.MultipartFormData.FilePart contactfile = body.getFile("contactfile"); if (contactfile != null) { String fileName = contactfile.getFilename(); File file = contactfile.getFile(); try { File f = new File("public/upload/" + fileName); if (f.isFile()) f.delete(); FileUtils.moveFile(file, new File("public/upload", fileName)); } catch (IOException ioe) { System.out.println("Problem operating on filesystem"); } PoiExcelFileReader.readFile(fileName); flash("success", "Datei: " + fileName + " hochgeladen und Kontakte importiert"); return redirect(routes.Application.contacts()); } else { flash("error", "Ein Fehler ist aufgetreten, bitte versuchen sie es erneut"); return redirect(routes.Application.contacts()); } }
public static String getContentType(String key) { Http.MultipartFormData multipartFormData = getContext().request().body().asMultipartFormData(); Http.MultipartFormData.FilePart filePart = multipartFormData.getFile(key); if (filePart != null) { String contentType = filePart.getContentType(); return contentType; } return null; }
public static String getFileName(String key) { Http.MultipartFormData multipartFormData = getContext().request().body().asMultipartFormData(); Http.MultipartFormData.FilePart filePart = multipartFormData.getFile(key); if (filePart != null) { String fileName = filePart.getFilename(); Logger.info("filename:" + fileName); return fileName; } return null; }
/** * Start the workflow run asynchronously. * * @param name The name of the workflow * @return json response containing id */ @Security.Authenticated(Secured.class) public Result runWorkflow(String name) { FormDefinition form = formDefinitionForWorkflow(name); // Process file upload first if present in form data Http.MultipartFormData body = request().body().asMultipartFormData(); for (Object obj : body.getFiles()) { Http.MultipartFormData.FilePart filePart = (Http.MultipartFormData.FilePart) obj; UserUpload userUpload = uploadFile(filePart); BasicField fileInputField = form.getField(filePart.getKey()); fileInputField.setValue(userUpload); } // Set the form definition field values from the request data Map<String, String[]> data = body.asFormUrlEncoded(); for (String key : data.keySet()) { BasicField field = form.getField(key); field.setValue(data.get(key)); } // Transfer form field data to workflow settings map Map<String, Object> settings = new HashMap<>(); for (BasicField field : form.fields) { settings.put(field.name, field.value()); } settings.putAll(settingsFromConfig(form)); // Update the workflow model object and persist to the db Workflow workflow = Workflow.find.where().eq("name", form.name).findUnique(); if (workflow == null) { workflow = new Workflow(); } workflow.name = form.name; workflow.title = form.title; workflow.yamlFile = form.yamlFile; workflow.save(); // Run the workflow ObjectNode response = runYamlWorkflow(form.yamlFile, workflow, settings); return redirect(routes.Application.index()); }
public static Result upload() { MultipartFormData body = request().body().asMultipartFormData(); FilePart input = body.getFile("inputFile"); if (input != null) { String fileName = input.getFilename(); String contentType = input.getContentType(); File file = input.getFile(); SeqFile seq = new SeqFile(file); return redirect(routes.Application.results(true)); } else { flash("error", "Missing file"); return redirect(routes.Application.results(false)); } }
/** * Updates currently selected restaurant. Checks if room with selected id exists, if it does, * collects data from the form and updates the room. * * @param restaurantId * @return */ @Security.Authenticated(Authenticators.SellerFilter.class) public Result updateRestaurant(Integer restaurantId) { // Creating restaurant with provided restaurantId Restaurant restaurant = Restaurant.findRestaurantById(restaurantId); // Checking if such restaurant exists // If it does, collects its data and updates the restaurant. if (restaurant != null) { Form<Restaurant> restaurantForm1 = restaurantForm.bindFromRequest(); String name = restaurantForm1.field("name").value(); String restaurantType = restaurantForm1.field("restauranType").value(); Integer capacity = Integer.parseInt(restaurantForm1.field("capacity").value()); String description = restaurantForm1.field("description").value(); String open = restaurantForm1.field("restOpen").value(); String close = restaurantForm1.field("restClose").value(); String workingHours = open + " - " + close; restaurant.name = name; restaurant.restauranType = restaurantType; restaurant.capacity = capacity; restaurant.workingHours = workingHours; restaurant.description = description; // Adding images for the restaurant. Http.MultipartFormData body1 = request().body().asMultipartFormData(); List<Http.MultipartFormData.FilePart> fileParts = body1.getFiles(); if (fileParts != null) { for (Http.MultipartFormData.FilePart filePart1 : fileParts) { File file = filePart1.getFile(); Image image = Image.create(file, null, null, null, null, restaurantId); restaurant.images.add(image); } } restaurant.update(); } if (session("userId") != null) { flash("edit", "The restaurant was updated!"); return redirect(routes.Hotels.showSellerHotels()); } else { return redirect(routes.Application.index()); } }
/** * Helper method creates a temp file from the multipart form data and persists the upload file * metadata to the database * * @param filePart data from the form submission * @return an instance of UploadFile that has been persisted to the db */ private static UserUpload uploadFile(Http.MultipartFormData.FilePart filePart) { File src = (File) filePart.getFile(); File file = null; try { file = File.createTempFile(filePart.getFilename() + "-", ".csv"); FileUtils.copyFile(src, file); } catch (IOException e) { throw new RuntimeException("Could not create temp file for upload", e); } UserUpload uploadFile = new UserUpload(); uploadFile.absolutePath = file.getAbsolutePath(); uploadFile.fileName = filePart.getFilename(); uploadFile.user = Application.getCurrentUser(); uploadFile.save(); return uploadFile; }
@Security.Authenticated(Secured.class) public Result deploy() { Http.MultipartFormData body = request().body().asMultipartFormData(); Http.MultipartFormData.FilePart filePart = body.getFile("filename"); if (filePart != null) { ConfigManager configManager = ConfigManager.getInstance(); try { configManager.unpack((File) filePart.getFile()); } catch (Exception e) { flash("error", "Could not verify package."); return redirect(routes.Workflows.uploadWorkflow()); } flash("message", "Packages zip file was successfully deployed"); return redirect(routes.Workflows.uploadWorkflow()); } else { flash("error", "Missing file"); return badRequest(); } }
public static Result index() { if (Utils.isPOST(request())) { form = Form.form(Credentials.class).bindFromRequest(); // Check errors if (form.hasErrors()) { return badRequest(views.html.sample44.render(false, null, null, form)); } // Save credentials to session Credentials credentials = form.get(); session().put("clientId", credentials.getClientId()); session().put("privateKey", credentials.getPrivateKey()); session().put("basePath", credentials.getBasePath()); credentials.normalizeBasePath("https://api.groupdocs.com/v2.0"); // Get request parameters Http.MultipartFormData body = request().body().asMultipartFormData(); String name = Utils.getFormValue(body, "firstName"); String lastName = Utils.getFormValue(body, "lastName"); String firstEmail = Utils.getFormValue(body, "firstEmail"); String secondEmail = Utils.getFormValue(body, "secondEmail"); String gender = Utils.getFormValue(body, "gender"); String basePath = credentials.getBasePath(); ApiInvoker.getInstance() .setRequestSigner(new GroupDocsRequestSigner(credentials.getPrivateKey())); try { // String guid = null; // Http.MultipartFormData.FilePart file = body.getFile("file"); StorageApi storageApi = new StorageApi(); // Initialize API with base path storageApi.setBasePath(credentials.getBasePath()); FileInputStream is = new FileInputStream(file.getFile()); UploadResponse uploadResponse = storageApi.Upload( credentials.getClientId(), file.getFilename(), "uploaded", "", 1, new FileStream(is)); // Check response status uploadResponse = Utils.assertResponse(uploadResponse); guid = uploadResponse.getResult().getGuid(); guid = Utils.assertNotNull(guid); // MergeApi mergeApi = new MergeApi(); // Initialize API with base path mergeApi.setBasePath(credentials.getBasePath()); Datasource datasource = new Datasource(); datasource.setFields(new ArrayList<DatasourceField>()); DatasourceField datasourceField = null; datasourceField = new DatasourceField(); datasourceField.setName("gender"); datasourceField.setType("text"); datasourceField.setValues(new ArrayList<String>()); datasourceField.getValues().add(gender); datasource.getFields().add(datasourceField); datasourceField = new DatasourceField(); datasourceField.setName("name"); datasourceField.setType("text"); datasourceField.setValues(new ArrayList<String>()); datasourceField.getValues().add(name); datasource.getFields().add(datasourceField); AddDatasourceResponse datasourceResponse = mergeApi.AddDataSource(credentials.getClientId(), datasource); // Check response status datasourceResponse = Utils.assertResponse(datasourceResponse); MergeTemplateResponse mergeTemplateResponse = mergeApi.MergeDatasource( credentials.getClientId(), guid, Double.toString(datasourceResponse.getResult().getDatasource_id()), "pdf", null); // Check response status mergeTemplateResponse = Utils.assertResponse(mergeTemplateResponse); Thread.sleep(8000); AsyncApi asyncApi = new AsyncApi(); // Initialize API with base path asyncApi.setBasePath(credentials.getBasePath()); GetJobDocumentsResponse jobDocumentsResponse = asyncApi.GetJobDocuments( credentials.getClientId(), Double.toString(mergeTemplateResponse.getResult().getJob_id()), null); // Check response status jobDocumentsResponse = Utils.assertResponse(jobDocumentsResponse); if ("Postponed".equalsIgnoreCase(jobDocumentsResponse.getResult().getJob_status())) { throw new Exception("Job is failed"); } if ("Pending".equalsIgnoreCase(jobDocumentsResponse.getResult().getJob_status())) { throw new Exception("Job is pending"); } String resultGuid = jobDocumentsResponse.getResult().getInputs().get(0).getOutputs().get(0).getGuid(); String resultName = jobDocumentsResponse.getResult().getInputs().get(0).getOutputs().get(0).getName(); // Create Signature api object SignatureApi signatureApi = new SignatureApi(); // Initialize API with base path signatureApi.setBasePath(basePath); // Make a requests to Signature Api to create an envelope SignatureEnvelopeSettingsInfo env = new SignatureEnvelopeSettingsInfo(); env.setEmailSubject("Sign this!"); SignatureEnvelopeResponse envelopeResponse = signatureApi.CreateSignatureEnvelope( credentials.getClientId(), resultName, null, null, resultGuid, true, env); envelopeResponse = Utils.assertResponse(envelopeResponse); // Get an ID of created envelope final String envelopeGuid = envelopeResponse.getResult().getEnvelope().getId(); // Make a request to Signature Api to get all available roles SignatureRolesResponse signatureRolesResponse = signatureApi.GetRolesList(credentials.getClientId(), null); // Check response status signatureRolesResponse = Utils.assertResponse(signatureRolesResponse); List<SignatureRoleInfo> roles = signatureRolesResponse.getResult().getRoles(); String roleGuid = null; for (SignatureRoleInfo role : roles) { // Get an ID of Signer role if ("Signer".equalsIgnoreCase(role.getName())) { roleGuid = role.getId(); break; } } // Check emptiness lastName string if (Strings.isNullOrEmpty(lastName)) { lastName = name; } // Make a request to Signature Api to add new first recipient to envelope SignatureEnvelopeRecipientResponse signatureEnvelopeRecipientResponse = signatureApi.AddSignatureEnvelopeRecipient( credentials.getClientId(), envelopeGuid, firstEmail, name, lastName, roleGuid, null); // Check response status signatureEnvelopeRecipientResponse = Utils.assertResponse(signatureEnvelopeRecipientResponse); String recipientGuid = signatureEnvelopeRecipientResponse.getResult().getRecipient().getId(); // Make a request to Signature Api to add new second recipient to envelope SignatureEnvelopeRecipientResponse signatureEnvelopeSecondRecipientResponse = signatureApi.AddSignatureEnvelopeRecipient( credentials.getClientId(), envelopeGuid, secondEmail, name + "2", lastName + "2", roleGuid, null); // Check response status signatureEnvelopeSecondRecipientResponse = Utils.assertResponse(signatureEnvelopeSecondRecipientResponse); String recipientSecondGuid = signatureEnvelopeSecondRecipientResponse.getResult().getRecipient().getId(); // Make a request to Signature Api to get all available fields SignatureEnvelopeDocumentsResponse getEnvelopDocument = signatureApi.GetSignatureEnvelopeDocuments(credentials.getClientId(), envelopeGuid); // Check response status getEnvelopDocument = Utils.assertResponse(getEnvelopDocument); // Create new first field called singlIndex1 SignatureEnvelopeFieldSettingsInfo envField1 = new SignatureEnvelopeFieldSettingsInfo(); envField1.setName("singlIndex1"); envField1.setLocationX(0.15); envField1.setLocationY(0.23); envField1.setLocationWidth(150.0); envField1.setLocationHeight(50.0); envField1.setForceNewField(true); envField1.setPage(1); // Make a request to Signature Api to add city field to envelope SignatureEnvelopeFieldsResponse signatureEnvelopeFieldsResponse = signatureApi.AddSignatureEnvelopeField( credentials.getClientId(), envelopeGuid, getEnvelopDocument.getResult().getDocuments().get(0).getDocumentId(), recipientGuid, "0545e589fb3e27c9bb7a1f59d0e3fcb9", envField1); // Create new second field called singlIndex2 SignatureEnvelopeFieldSettingsInfo envField2 = new SignatureEnvelopeFieldSettingsInfo(); envField2.setName("singlIndex2"); envField2.setLocationX(0.35); envField2.setLocationY(0.23); envField2.setLocationWidth(150.0); envField2.setLocationHeight(50.0); envField2.setForceNewField(true); envField2.setPage(1); // Make a request to Signature Api to add city field to envelope SignatureEnvelopeFieldsResponse signatureEnvelopeSecondFieldsResponse = signatureApi.AddSignatureEnvelopeField( credentials.getClientId(), envelopeGuid, getEnvelopDocument.getResult().getDocuments().get(0).getDocumentId(), recipientSecondGuid, "0545e589fb3e27c9bb7a1f59d0e3fcb9", envField2); // Check response status Utils.assertNotNull(signatureEnvelopeFieldsResponse); SignatureEnvelopeSendResponse signatureEnvelopeSendResponse = signatureApi.SignatureEnvelopeSend(credentials.getClientId(), envelopeGuid, null); Utils.assertResponse(signatureEnvelopeSendResponse); String server = credentials .getBasePath() .substring(0, credentials.getBasePath().indexOf(".com") + 4) .replace("api", "apps"); String embedUrl = server + "/signature2/signembed/" + envelopeGuid + "/" + recipientGuid; String embedUrl2 = server + "/signature2/signembed/" + envelopeGuid + "/" + recipientSecondGuid; // Render view return ok(views.html.sample44.render(true, embedUrl, embedUrl2, form)); } catch (Exception e) { return badRequest(views.html.sample44.render(false, null, null, form)); } } else if (Utils.isGET(request())) { form = form.bind(session()); } return ok(views.html.sample44.render(false, null, null, form)); }
public static Result index() { if (Utils.isPOST(request())) { form = Form.form(Credentials.class).bindFromRequest(); // Check errors if (form.hasErrors()) { return badRequest(views.html.sample18.render(false, null, form)); } // Save credentials to session Credentials credentials = form.get(); session().put("clientId", credentials.getClientId()); session().put("privateKey", credentials.getPrivateKey()); session().put("basePath", credentials.getBasePath()); credentials.normalizeBasePath("https://api.groupdocs.com/v2.0"); // Get request parameters Http.MultipartFormData body = request().body().asMultipartFormData(); String sourse = Utils.getFormValue(body, "sourse"); String convertType = Utils.getFormValue(body, "convertType"); String callbackUrl = Utils.getFormValue(body, "callbackUrl"); callbackUrl = (callbackUrl == null) ? "" : callbackUrl; // Initialize SDK with private key ApiInvoker.getInstance() .setRequestSigner(new GroupDocsRequestSigner(credentials.getPrivateKey())); try { // String guid = null; // if ("guid".equals(sourse)) { // File GUID guid = Utils.getFormValue(body, "fileId"); } else if ("url".equals(sourse)) { // Upload file fron URL String url = Utils.getFormValue(body, "url"); StorageApi storageApi = new StorageApi(); // Initialize API with base path storageApi.setBasePath(credentials.getBasePath()); UploadResponse uploadResponse = storageApi.UploadWeb(credentials.getClientId(), url); // Check response status uploadResponse = Utils.assertResponse(uploadResponse); guid = uploadResponse.getResult().getGuid(); } else if ("local".equals(sourse)) { // Upload local file Http.MultipartFormData.FilePart file = body.getFile("file"); StorageApi storageApi = new StorageApi(); // Initialize API with base path storageApi.setBasePath(credentials.getBasePath()); FileInputStream is = new FileInputStream(file.getFile()); UploadResponse uploadResponse = storageApi.Upload( credentials.getClientId(), file.getFilename(), "uploaded", "", 1, new FileStream(is)); // Check response status uploadResponse = Utils.assertResponse(uploadResponse); guid = uploadResponse.getResult().getGuid(); } guid = Utils.assertNotNull(guid); // Render view AsyncApi api = new AsyncApi(); // Initialize API with base path api.setBasePath(credentials.getBasePath()); ConvertResponse response = api.Convert( credentials.getClientId(), guid, "", "description", false, callbackUrl, convertType); // Check response status response = Utils.assertResponse(response); Double jobId = response.getResult().getJob_id(); Thread.sleep(5000); GetJobDocumentsResponse jobDocumentsResponse = api.GetJobDocuments(credentials.getClientId(), jobId.toString(), ""); jobDocumentsResponse = Utils.assertResponse(jobDocumentsResponse); String resultGuid = jobDocumentsResponse.getResult().getInputs().get(0).getOutputs().get(0).getGuid(); FileOutputStream fileOutputStream = new FileOutputStream(USER_INFO_FILE); DataOutputStream dataOutputStream = new DataOutputStream(fileOutputStream); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(credentials.getClientId()); stringBuilder.append("|"); stringBuilder.append(credentials.getPrivateKey()); stringBuilder.append("|"); stringBuilder.append(credentials.getBasePath()); dataOutputStream.writeUTF(stringBuilder.toString()); dataOutputStream.flush(); fileOutputStream.close(); return ok(views.html.sample18.render(true, resultGuid, form)); } catch (Exception e) { return badRequest(views.html.sample18.render(false, null, form)); } } else if (Utils.isGET(request())) { form = form.bind(session()); } return ok(views.html.sample18.render(false, null, form)); }
@Transactional(rollbackFor = Exception.class) public GeneralResponse doctorSendNormalChat( Doctor doctor, NormalChatMessage msg, Http.MultipartFormData body) throws Exception { User user = userRepo.findOne(msg.receiver.id); String chatFileStore = Play.application().path() + "/store/chats"; if (user != null) { try { ChatParticipantInfo sender = new ChatParticipantInfo(); sender.id = doctor.id; sender.role = 0; sender.name = doctor.name; sender.avatar = doctor.avatar; ChatParticipantInfo receiver = new ChatParticipantInfo(); receiver.id = user.id; receiver.role = 1; receiver.name = user.name; String fileDirPath = ""; String id = MD5Generator.getMd5Value( UUIDGenerator.getUUID() + "doctor" + doctor.id + "user" + user.id); fileDirPath = chatFileStore + "/" + id; File filesDir = null; switch (msg.subCategory) { case 1: if (msg.content == null || msg.content.isEmpty()) { return new GeneralResponse(53, "Can't send empty content"); } else { NormalChatMessageResponse response = new NormalChatMessageResponse(); response.category = 1; response.sender = sender; response.receiver = receiver; response.subCategory = msg.subCategory; response.content = msg.content; response.inquiryID = msg.inquiryID; IMScheduler.defaultSender.tell( new IMSenderMessage(user.jid, 1, user.clientID, user.deviceType, response), null); ChatRecord record = new ChatRecord(); record.category = msg.category; record.content = msg.content; record.subCategory = msg.subCategory; record.senderID = doctor.id; record.receiverID = user.id; record.inquiryID = msg.inquiryID; record.createTime = System.currentTimeMillis(); chatRepo.save(record); } break; case 2: filesDir = new File(fileDirPath); if (!filesDir.exists()) { filesDir.mkdirs(); } Http.MultipartFormData.FilePart imgFlPart = body.getFile("file"); if (imgFlPart != null) { NormalChatMessageResponse response = new NormalChatMessageResponse(); response.sender = sender; response.receiver = receiver; response.category = 1; response.subCategory = msg.subCategory; response.inquiryID = msg.inquiryID; String fileName = imgFlPart.getFilename(); String newFlName; if (!fileName.contains(".")) { newFlName = MD5Generator.getMd5Value(fileName + System.currentTimeMillis()); } else { newFlName = MD5Generator.getMd5Value( fileName.substring(0, fileName.lastIndexOf(".")) + System.currentTimeMillis()) + fileName.substring(fileName.lastIndexOf(".")); } FileUtils.moveFile(imgFlPart.getFile(), new File(filesDir, newFlName)); response.content = "/chat/" + id + "/image/" + newFlName; IMScheduler.defaultSender.tell( new IMSenderMessage(user.jid, 1, user.clientID, user.deviceType, response), null); ChatRecord record = new ChatRecord(); record.category = msg.category; record.content = response.content; record.subCategory = msg.subCategory; record.senderID = doctor.id; record.receiverID = user.id; record.inquiryID = msg.inquiryID; record.createTime = System.currentTimeMillis(); chatRepo.save(record); } else { return new GeneralResponse(56, "Not has file"); } break; case 3: filesDir = new File(fileDirPath); if (!filesDir.exists()) { filesDir.mkdirs(); } Http.MultipartFormData.FilePart sndFlPart = body.getFile("file"); if (sndFlPart != null) { NormalChatMessageResponse response = new NormalChatMessageResponse(); response.category = 1; response.sender = sender; response.receiver = receiver; response.subCategory = msg.subCategory; response.inquiryID = msg.inquiryID; String fileName = sndFlPart.getFilename(); String newFlName; if (!fileName.contains(".")) { newFlName = MD5Generator.getMd5Value(fileName + System.currentTimeMillis()); } else { newFlName = MD5Generator.getMd5Value( fileName.substring(0, fileName.lastIndexOf(".")) + System.currentTimeMillis()) + fileName.substring(fileName.lastIndexOf(".")); } FileUtils.moveFile(sndFlPart.getFile(), new File(filesDir, newFlName)); response.content = "/chat/" + id + "/audio/" + newFlName; IMScheduler.defaultSender.tell( new IMSenderMessage(user.jid, 1, user.clientID, user.deviceType, response), null); ChatRecord record = new ChatRecord(); record.category = msg.category; record.content = response.content; record.subCategory = msg.subCategory; record.senderID = doctor.id; record.receiverID = user.id; record.inquiryID = msg.inquiryID; record.createTime = System.currentTimeMillis(); chatRepo.save(record); } else { return new GeneralResponse(56, "Not has file"); } break; default: return new GeneralResponse(54, "Not indicate subcategory"); } return new GeneralResponse(); } catch (Exception e) { Logger.error("Send message failed", e); throw new IMServerException(e.getMessage()); } } else { return new GeneralResponse(11, "Please push necessary data"); } }
public static Result index() { if (Utils.isPOST(request())) { form = Form.form(Credentials.class).bindFromRequest(); // Check errors if (form.hasErrors()) { return badRequest(views.html.sample19.render(false, null, null, null, form)); } // Save credentials to session Credentials credentials = form.get(); session().put("clientId", credentials.getClientId()); session().put("privateKey", credentials.getPrivateKey()); session().put("basePath", credentials.getBasePath()); credentials.normalizeBasePath("https://api.groupdocs.com/v2.0"); // Get request parameters Http.MultipartFormData body = request().body().asMultipartFormData(); String sourse = Utils.getFormValue(body, "sourse"); String callbackUrl = Utils.getFormValue(body, "callbackUrl"); // Initialize SDK with private key ApiInvoker.getInstance() .setRequestSigner(new GroupDocsRequestSigner(credentials.getPrivateKey())); try { // String sourseGuid = null; // if ("guid".equals(sourse)) { // File GUID sourseGuid = Utils.getFormValue(body, "sourceFileId"); } else if ("url".equals(sourse)) { // Upload file fron URL String url = Utils.getFormValue(body, "url"); StorageApi storageApi = new StorageApi(); // Initialize API with base path storageApi.setBasePath(credentials.getBasePath()); UploadResponse uploadResponse = storageApi.UploadWeb(credentials.getClientId(), url); // Check response status uploadResponse = Utils.assertResponse(uploadResponse); sourseGuid = uploadResponse.getResult().getGuid(); } else if ("local".equals(sourse)) { // Upload local file Http.MultipartFormData.FilePart file = body.getFile("local"); StorageApi storageApi = new StorageApi(); // Initialize API with base path storageApi.setBasePath(credentials.getBasePath()); FileInputStream is = new FileInputStream(file.getFile()); UploadResponse uploadResponse = storageApi.Upload( credentials.getClientId(), file.getFilename(), "uploaded", "", 1, new FileStream(is)); // Check response status uploadResponse = Utils.assertResponse(uploadResponse); sourseGuid = uploadResponse.getResult().getGuid(); } // Target String targetGuid = null; // if ("guid".equals(sourse)) { // File GUID targetGuid = Utils.getFormValue(body, "targetFileId"); } else if ("url".equals(sourse)) { // Upload file fron URL String url = Utils.getFormValue(body, "targetUrl"); StorageApi storageApi = new StorageApi(); // Initialize API with base path storageApi.setBasePath(credentials.getBasePath()); UploadResponse uploadResponse = storageApi.UploadWeb(credentials.getClientId(), url); // Check response status uploadResponse = Utils.assertResponse(uploadResponse); targetGuid = uploadResponse.getResult().getGuid(); } else if ("local".equals(sourse)) { // Upload local file Http.MultipartFormData.FilePart file = body.getFile("target_local"); StorageApi storageApi = new StorageApi(); // Initialize API with base path storageApi.setBasePath(credentials.getBasePath()); FileInputStream is = new FileInputStream(file.getFile()); UploadResponse uploadResponse = storageApi.Upload( credentials.getClientId(), file.getFilename(), "uploaded", "", 1, new FileStream(is)); // Check response status uploadResponse = Utils.assertResponse(uploadResponse); targetGuid = uploadResponse.getResult().getGuid(); } sourseGuid = Utils.assertNotNull(sourseGuid); targetGuid = Utils.assertNotNull(targetGuid); ComparisonApi api = new ComparisonApi(); // Initialize API with base path api.setBasePath(credentials.getBasePath()); callbackUrl = callbackUrl == null ? "" : callbackUrl; CompareResponse compareResponse = api.Compare(credentials.getClientId(), sourseGuid, targetGuid, callbackUrl); compareResponse = Utils.assertResponse(compareResponse); AsyncApi asyncApi = new AsyncApi(); // Initialize API with base path asyncApi.setBasePath(credentials.getBasePath()); // GetJobDocumentsResponse jobDocumentsResponse = null; do { Thread.sleep(5000); jobDocumentsResponse = asyncApi.GetJobDocuments( credentials.getClientId(), compareResponse.getResult().getJob_id().toString(), ""); jobDocumentsResponse = Utils.assertResponse(jobDocumentsResponse); } while ("Inprogress".equalsIgnoreCase(jobDocumentsResponse.getResult().getJob_status())); String resultGuid = jobDocumentsResponse.getResult().getOutputs().get(0).getGuid(); Utils.assertNotNull(resultGuid); MgmtApi mgmtApi = new MgmtApi(); // Initialize API with base path mgmtApi.setBasePath(credentials.getBasePath()); GetUserEmbedKeyResponse userEmbedKeyResponse = mgmtApi.GetUserEmbedKey(credentials.getClientId(), "comparison"); Utils.assertResponse(userEmbedKeyResponse); String compareKey = userEmbedKeyResponse.getResult().getKey().getGuid(); FileOutputStream fileOutputStream = new FileOutputStream(USER_INFO_FILE); DataOutputStream dataOutputStream = new DataOutputStream(fileOutputStream); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(credentials.getClientId()); stringBuilder.append("|"); stringBuilder.append(credentials.getPrivateKey()); stringBuilder.append("|"); stringBuilder.append(credentials.getBasePath()); dataOutputStream.writeUTF(stringBuilder.toString()); dataOutputStream.flush(); fileOutputStream.close(); String server = credentials .getBasePath() .substring(0, credentials.getBasePath().indexOf(".com") + 4) .replace("api", "apps"); // Render view return ok(views.html.sample19.render(true, resultGuid, compareKey, server, form)); } catch (Exception e) { return badRequest(views.html.sample19.render(false, null, null, null, form)); } } else if (Utils.isGET(request())) { form = form.bind(session()); } return ok(views.html.sample19.render(false, null, null, null, form)); }