public Result submit() { User user = User.findByEmail(session().get("email")); Form<UserProfile> filledForm = profileForm.bindFromRequest(); if (filledForm.hasErrors()) { return badRequest(createprofile.render(filledForm)); } else { MultipartFormData body = request().body().asMultipartFormData(); FilePart picture = body.getFile("image"); UserProfile newProfile = filledForm.get(); newProfile.image = picture.getFile(); String filePath = "public/user_pictures/"+ user.email + ".png"; newProfile.saveImage(picture.getFile(), filePath); newProfile.userId = user.id; newProfile.save(); return ok(viewprofile.render(user, newProfile)); } }
/** * Save the specified file as an attachment. * * @param fieldName * the field name * @param objectClass * the object class * @param objectId * the object id * @param attachmentPlugin * the service which is managing attachments */ public static Long saveAsAttachement(String fieldName, Class<?> objectClass, Long objectId, IAttachmentManagerPlugin attachmentPlugin) throws IOException { FileInputStream fIn = null; try { FileType fileType = getFileType(fieldName); switch (fileType) { case UPLOAD: FilePart filePart = getFilePart(fieldName); fIn = new FileInputStream(filePart.getFile()); return attachmentPlugin.addFileAttachment(fIn, filePart.getContentType(), getFileName(fieldName), objectClass, objectId); case URL: return attachmentPlugin.addUrlAttachment(getUrl(fieldName), getFileName(fieldName), objectClass, objectId); default: return null; } } catch (Exception e) { String message = String.format("Failure while creating the attachments for : %s [class %s]", objectId, objectClass); throw new IOException(message, e); } finally { IOUtils.closeQuietly(fIn); } }
public static Result guardarArchivo() { MultipartFormData body = request().body().asMultipartFormData(); FilePart fichero = body.getFile("archivo"); String nombreFichero = fichero.getFilename(); int indice = nombreFichero.lastIndexOf("."); String type = nombreFichero.substring(indice + 1, nombreFichero.length()); if(indice != -1) nombreFichero = nombreFichero.substring(0,indice); String tipo = fichero.getContentType(); File file = fichero.getFile(); File newFile = new File("public/data/" + nombreFichero + "."+ type); try { Files.copy(file, newFile); } catch (IOException e) { e.printStackTrace(); } return index(); }
public static Result uploadExcel() { try { MultipartFormData body = request().body().asMultipartFormData(); FilePart excel = body.getFile("excel"); if (excel != null) { File file = excel.getFile(); ExcelReader reader = new ExcelReader(); List<Observation> obsList = reader.read(new FileInputStream(file)); for (Observation obs: obsList) { obs.save(); } Logger.info("Excel file uploaded with " + obsList.size() + " observations"); return redirect(routes.Application.index()); } else { Logger.error("Missing file to upload "); return redirect(routes.Application.index()); } } catch (IOException e) { return(badRequest(Messages.get("read.excel.error") + "." + e.getLocalizedMessage())); } }
@Security.Authenticated(SecuredController.class) public static Result uploadExcel() { MultipartFormData body = request().body().asMultipartFormData(); FilePart picture = body.getFile("excelFile"); if(picture != null) { String fileName = picture.getFilename(); String contentType = picture.getContentType(); File file = picture.getFile(); Logger.info("Uploaded " + fileName); try { excelParser(file); flash("success", "File " + fileName + " uploaded"); } catch(Throwable e) { flash("error", "File " + fileName + " parse errors:"); flash("error_log", e.getMessage()); e.printStackTrace(); } return redirect(routes.TargetController.upload()); } else { Logger.info("Upload failed "); flash("error", "Missing file"); return redirect(routes.TargetController.upload()); } }
private static Attachment createNew(FilePart file, String path) { Attachment attachment = new Attachment(); attachment.setFileName(file.getFilename()); attachment.setFilePath(path); attachment.setMimeType(file.getContentType()); attachment.save(); return attachment; }
@Restrict({@Group("TEACHER"), @Group("ADMIN")}) public Result addAttachmentToQuestion() { MultipartFormData<File> body = request().body().asMultipartFormData(); FilePart<File> filePart = body.getFile("file"); if (filePart == null) { return notFound(); } File file = filePart.getFile(); if (file.length() > AppUtil.getMaxFileSize()) { return forbidden("sitnet_file_too_large"); } Map<String, String[]> m = body.asFormUrlEncoded(); Long qid = Long.parseLong(m.get("questionId")[0]); Question question = Ebean.find(Question.class) .fetch("examSectionQuestions.examSection.exam.parent") .where() .idEq(qid) .findUnique(); if (question == null) { return notFound(); } String newFilePath; try { newFilePath = copyFile(file, "question", qid.toString()); } catch (IOException e) { return internalServerError("sitnet_error_creating_attachment"); } // Remove existing one if found removePrevious(question); Attachment attachment = createNew(filePart, newFilePath); question.setAttachment(attachment); question.save(); return ok(attachment); }
@Restrict({@Group("TEACHER"), @Group("ADMIN")}) public Result addAttachmentToExam() { MultipartFormData<File> body = request().body().asMultipartFormData(); FilePart<File> filePart = body.getFile("file"); if (filePart == null) { return notFound(); } File file = filePart.getFile(); if (file.length() > AppUtil.getMaxFileSize()) { return forbidden("sitnet_file_too_large"); } Map<String, String[]> m = body.asFormUrlEncoded(); Long eid = Long.parseLong(m.get("examId")[0]); Exam exam = Ebean.find(Exam.class, eid); if (exam == null) { return notFound(); } User user = getLoggedUser(); if (!user.hasRole(Role.Name.ADMIN.toString(), getSession()) && !exam.isOwnedOrCreatedBy(user)) { return forbidden("sitnet_error_access_forbidden"); } String newFilePath; try { newFilePath = copyFile(file, "exam", eid.toString()); } catch (IOException e) { return internalServerError("sitnet_error_creating_attachment"); } // Delete existing if exists removePrevious(exam); Attachment attachment = createNew(filePart, newFilePath); exam.setAttachment(attachment); exam.save(); return ok(attachment); }
public Result submit() { User user = User.findByEmail(session().get("email")); Form<UserProfile> filledForm = profileForm.bindFromRequest(); if (filledForm.hasErrors()) { return badRequest(editprofile.render(user, profileForm)); } else { MultipartFormData body = request().body().asMultipartFormData(); FilePart picture = null; if (body != null && body.getFile("image") != null) { picture = body.getFile("image"); } UserProfile profile = null; if (user != null) { profile = UserProfile.findByUserId(user.id); } else { profile = UserProfile.findByUserId(filledForm.get().userId); } profile.set(filledForm.get()); if (picture != null && picture.getFile() != null) { profile.image = picture.getFile(); String filePath = "public/user_pictures/" + user.email + ".png"; profile.saveImage(picture.getFile(), filePath); } profile.save(); return GO_VIEW; } }
/** * Get the file part of the attachment for UPLOAD type. * * @param fieldName * the field name */ public static FilePart getFilePart(String fieldName) { FileType fileType = getFileType(fieldName); if (fileType.equals(FileType.UPLOAD)) { MultipartFormData body = Controller.request().body().asMultipartFormData(); FilePart filePart = body.getFile(getFileInputName(fieldName, fileType)); return filePart; } return null; }
/** * Handles the file upload. * @throws OWLOntologyCreationException * @throws InterruptedException */ public static Result uploadFile() throws OWLOntologyCreationException, InterruptedException { Form<Ontology> ontologyForm = form(Ontology.class); MultipartFormData body = request().body().asMultipartFormData(); FilePart ontologyFile = body.getFile("ontology"); if (ontologyFile != null) { String fileName = ontologyFile.getFilename(); String contentType = ontologyFile.getContentType(); // ontology.get File file = ontologyFile.getFile(); try{ loadOntology(file.getPath()); } catch(UnparsableOntologyException ex){ return ok(index.render("Not a valid Ontology File")); } //Initiate the reasoner to classify ontology if (BeeOntologyfile.exists()) { reasoner.precomputeInferences(InferenceType.CLASS_HIERARCHY); //System.out.println("suppp"); loadBeeCharacteristics(); } Ontology ontology = new Ontology(KeyDescriptionArraylist, null, null); return ok(view.render(ontology.features)); } else { flash("error", "Missing file"); return ok(index.render("File Not Found")); } }
public static Result importFeatures(String name){ DynamicForm form = form().bindFromRequest(); Logger.info("PARAMETERS : " + form.data().toString()); String table1Name = form.get("table1_name"); String table2Name = form.get("table2_name"); MultipartFormData body = request().body().asMultipartFormData(); FilePart fp = body.getFile("csv_file_path"); if (fp != null) { String fileName = fp.getFilename(); String contentType = fp.getContentType(); Logger.info("fileName: " + fileName + ", contentType: " + contentType); File file = fp.getFile(); Project project = ProjectDao.open(name); try{ Table table1 = TableDao.open(name, table1Name); Table table2 = TableDao.open(name, table2Name); List<Feature> features = RuleDao.importFeaturesFromCSVWithHeader(project, table1, table2, file.getAbsolutePath()); // save the features - this automatically updates and saves the project System.out.println(features); System.out.println(name); RuleDao.save(name, features); ProjectController.statusMessage = "Successfully imported " + features.size() + " features."; } catch(IOException ioe){ flash("error", ioe.getMessage()); ProjectController.statusMessage = "Error: " + ioe.getMessage(); } } else { flash("error", "Missing file"); ProjectController.statusMessage = "Error: Missing file"; } return redirect(controllers.project.routes.ProjectController.showProject(name)); }
public static Result importRules(String name){ DynamicForm form = form().bindFromRequest(); Logger.info("PARAMETERS : " + form.data().toString()); String table1Name = form.get("table1_name"); String table2Name = form.get("table2_name"); MultipartFormData body = request().body().asMultipartFormData(); FilePart fp = body.getFile("csv_file_path"); if (fp != null) { String fileName = fp.getFilename(); String contentType = fp.getContentType(); Logger.info("fileName: " + fileName + ", contentType: " + contentType); File file = fp.getFile(); Project project = ProjectDao.open(name); try{ List<Rule> rules = RuleDao.importRulesFromCSVWithHeader(project, table1Name, table2Name, file.getAbsolutePath()); // save the features - this automatically updates and saves the project RuleDao.saveRules(name, rules); ProjectController.statusMessage = "Successfully imported " + rules.size() + " rules."; } catch(IOException ioe){ flash("error", ioe.getMessage()); ProjectController.statusMessage = "Error: " + ioe.getMessage(); } } else { flash("error", "Missing file"); ProjectController.statusMessage = "Error: Missing file"; } return redirect(controllers.project.routes.ProjectController.showProject(name)); }
public static Result importMatchers(String name){ DynamicForm form = form().bindFromRequest(); Logger.info("PARAMETERS : " + form.data().toString()); String table1Name = form.get("table1_name"); String table2Name = form.get("table2_name"); MultipartFormData body = request().body().asMultipartFormData(); FilePart fp = body.getFile("csv_file_path"); if (fp != null) { String fileName = fp.getFilename(); String contentType = fp.getContentType(); Logger.info("fileName: " + fileName + ", contentType: " + contentType); File file = fp.getFile(); Project project = ProjectDao.open(name); try{ List<Matcher> matchers = RuleDao.importMatchersFromCSVWithHeader(project, table1Name, table2Name, file.getAbsolutePath()); // save the features - this automatically updates and saves the project RuleDao.saveMatchers(name, matchers); ProjectController.statusMessage = "Successfully imported " + matchers.size() + " matchers."; } catch(IOException ioe){ flash("error", ioe.getMessage()); ProjectController.statusMessage = "Error: " + ioe.getMessage(); } } else { flash("error", "Missing file"); ProjectController.statusMessage = "Error: Missing file"; } return redirect(controllers.project.routes.ProjectController.showProject(name)); }
@BodyParser.Of (value = BodyParser.MultipartFormData.class, maxLength = 2 * 1024 * 1024) public static Result handleFileUploadForm () { final MultipartFormData body = request ().body ().asMultipartFormData (); final FilePart uploadFile = body.getFile ("file"); if (uploadFile == null) { return ok (uploadFileForm.render (null)); } final String content = handleFileUpload (uploadFile.getFile ()); return ok (uploadFileForm.render (content)); }
public static Result uploadFile() { MultipartFormData part = request().body().asMultipartFormData(); FilePart file = part.getFile("file"); String filename = file.getFilename(); String[] parts = filename.split("."); String name = parts[0]; String ext; try { ext = parts[1]; } catch (ArrayIndexOutOfBoundsException iobe) { ext = "-"; } User user = User.findByUsername(session().get("login")); Document doc = new Document(file.getFile(), ext, user, name); user.documentos.add(doc); doc.save(); user.save(); return ok(profile.render(user)); }
public static Result upload() { MultipartFormData body = request().body().asMultipartFormData(); FilePart picture = body.getFile("picture"); String extensaoPadraoDeImagens = Play.application().configuration().getString("extensaoPadraoDeImagens"); if (picture != null) { String filmeId = form().bindFromRequest().get("filmeId"); String imagem = filmeId + extensaoPadraoDeImagens; String contentType = picture.getContentType(); File file = picture.getFile(); String diretorioDeImagens = Play.application().configuration().getString("diretorioDeImagens"); String contentTypePadraoDeImagens = Play.application().configuration().getString("contentTypePadraoDeImagens"); if (contentType.equals(contentTypePadraoDeImagens)) { file.renameTo(new File(diretorioDeImagens,imagem)); return ok(views.html.upload.render("Arquivo \"" + imagem + "\" do tipo [" + contentType + "] foi carregado com sucesso !")); } else { return ok(views.html.upload.render("Imagens apenas no formato \"" + contentTypePadraoDeImagens + "\" serão aceitas!")); } } else { flash("error","Erro ao fazer upload"); return redirect(routes.Application.index()); } }
/** * Upload the specified image and return the link to it * * @return the image link in the system */ private static String uploadImage() { String imageLocation = Play.application().configuration().getString("workshop.images.url") + File.separator; String defaultImage = imageLocation + "default.png"; MultipartFormData body = request().body().asMultipartFormData(); FilePart picture = body != null ? body.getFile("image") : null; if (picture != null) { String fileName = picture.getFilename(); File file = picture.getFile(); // We save the file String myUploadPath = Play.application().path() + File.separator + Play.application().configuration().getString("workshop.images.directory"); // We check if the dest file exists File dest = new File(myUploadPath, fileName); if ( dest.exists() ) { dest.delete(); } // If the file copy encounter an exception, we use the default picture if ( FilesUtils.fastCopyFileCore( file, dest ) ) { return imageLocation + fileName; } } return defaultImage; }
/** * Upload the specified File and return the link to it * * @return the File link in the system */ private static String uploadRessources( Workshop workshop ) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("[yyyy-MM]"); String destFolderName = simpleDateFormat.format( workshop.workshopSession.get(0).nextPlay ) + " - " + workshop.subject; String ressourceLocation = Play.application().configuration().getString("workshop.ressources.url") + File.separator + destFolderName + File.separator; MultipartFormData body = request().body().asMultipartFormData(); FilePart ressource = body != null ? body.getFile("workshopSupportFile") : null; if (ressource != null && !StringUtils.EMPTY.equals( ressource.getFilename()) ) { String fileName = ressource.getFilename(); File file = ressource.getFile(); // We save the file String myUploadPath = Play.application().path() + File.separator + Play.application().configuration().getString("workshop.ressources.directory") + File.separator + destFolderName; File destFolder = new File(myUploadPath); destFolder.mkdirs(); // We check if the dest file exists File dest = new File(myUploadPath, fileName); if ( dest.exists() ) { dest.delete(); } // If the file copy encounter an exception, we use the default picture if ( FilesUtils.fastCopyFileCore( file, dest ) ) { return ressourceLocation + fileName; } } return null; }
/** * Upload a new file into the shared storage. * * @param isInput * if true the field name containing the file uploaded is * IFrameworkConstants.INPUT_FOLDER_NAME * (IFrameworkConstants.OUTPUT_FOLDER_NAME otherwise) * @return */ @BodyParser.Of(value = BodyParser.MultipartFormData.class, maxLength = MAX_FILE_SIZE) public Promise<Result> upload(final boolean isInput) { final String folderName = isInput ? IFrameworkConstants.INPUT_FOLDER_NAME : IFrameworkConstants.OUTPUT_FOLDER_NAME; final // Test if the max number of files is not exceeded String[] files; try { files = getSharedStorageService().getFileList("/" + folderName); } catch (IOException e1) { return redirectToIndexAsPromiseWithErrorMessage(null); } int numberOfFiles = files != null ? files.length : 0; if (numberOfFiles >= getConfiguration().getInt("maf.sftp.store.maxfilenumber")) { return redirectToIndexAsPromiseWithErrorMessage(Msg.get("admin.shared_storage.upload.error.max_number")); } // Perform the upload return Promise.promise(new Function0<Result>() { @Override public Result apply() throws Throwable { try { MultipartFormData body = request().body().asMultipartFormData(); FilePart filePart = body.getFile(folderName); if (filePart != null) { IOUtils.copy(new FileInputStream(filePart.getFile()), getSharedStorageService().writeFile("/" + folderName + "/" + filePart.getFilename(), true)); Utilities.sendSuccessFlashMessage(Msg.get("form.input.file_field.success")); } else { Utilities.sendErrorFlashMessage(Msg.get("form.input.file_field.no_file")); } } catch (Exception e) { Utilities .sendErrorFlashMessage(Msg.get("admin.shared_storage.upload.file.size.invalid", FileUtils.byteCountToDisplaySize(MAX_FILE_SIZE))); String message = String.format("Failure while uploading a new file in %s", folderName); log.error(message); throw new IOException(message, e); } return redirect(routes.SharedStorageManagerController.index()); } }); }
@Override public boolean parseFile(ICustomAttributeManagerService customAttributeManagerService) { String fieldName = customAttributeManagerService.getFieldNameFromDefinitionUuid(getDefinition().uuid); if (FileAttachmentHelper.hasFileField(fieldName)) { FilePart filePart = FileAttachmentHelper.getFilePart(fieldName); if (authorizedContentType.contains(filePart.getContentType())) { if (customAttributeDefinition.maxWidth() != null || customAttributeDefinition.maxHeight() != null) { int imageWidth = 0; int imageHeight = 0; BufferedImage bimg; try { bimg = ImageIO.read(filePart.getFile()); imageWidth = bimg.getWidth(); imageHeight = bimg.getHeight(); } catch (IOException e) { } Logger.debug("imageWidth: " + imageWidth); Logger.debug("imageHeight: " + imageHeight); if (customAttributeDefinition.maxWidth() != null && customAttributeDefinition.maxWidth().intValue() < imageWidth) { this.hasError = true; this.errorMessage = Msg.get(customAttributeDefinition.getMaxWidthMessage(), customAttributeDefinition.maxWidth()); return false; } if (customAttributeDefinition.maxHeight() != null && customAttributeDefinition.maxHeight().intValue() < imageHeight) { this.hasError = true; this.errorMessage = Msg.get(customAttributeDefinition.getMaxHeightMessage(), customAttributeDefinition.maxHeight()); return false; } } this.value = "#attachment"; } else { this.hasError = true; this.errorMessage = Msg.get(Msg.get("form.input.image.required")); return false; } } return true; }
public static Result importTableFromCSV(String projectName) { DynamicForm form = form().bindFromRequest(); Logger.info("PARAMETERS : " + form.data().toString()); String tableName = form.get("table_name"); MultipartFormData body = request().body().asMultipartFormData(); FilePart fp = body.getFile("csv_file_path"); if (fp != null) { String fileName = fp.getFilename(); String contentType = fp.getContentType(); Logger.info("fileName: " + fileName + ", contentType: " + contentType); File file = fp.getFile(); Set<DefaultType> defaultTypes = new HashSet<DefaultType>(); boolean saveToDisk = false; if(null != form.get("table1_default")){ defaultTypes.add(DefaultType.TABLE1); } if(null != form.get("table2_default")){ defaultTypes.add(DefaultType.TABLE2); } if(null != form.get("candset_default")){ defaultTypes.add(DefaultType.CAND_SET); } if(null != form.get("matches_default")){ defaultTypes.add(DefaultType.MATCHES); } if(null != form.get("gold_default")){ defaultTypes.add(DefaultType.GOLD); } if(null != form.get("save_to_disk")){ saveToDisk = true; } try{ Table table = TableDao.importFromCSVWithHeader(projectName, tableName, file.getAbsolutePath()); // save the table - this automatically updates the project but does not save it TableDao.save(table, defaultTypes, saveToDisk); statusMessage = "Successfully imported Table " + tableName + " with " + table.getSize() + " tuples."; } catch(IOException ioe){ flash("error", ioe.getMessage()); statusMessage = "Error: " + ioe.getMessage(); } } else { flash("error", "Missing file"); statusMessage = "Error: Missing file"; } return redirect(controllers.project.routes.ProjectController.showProject(projectName)); }
public static Result importTable(String projectName) { DynamicForm form = form().bindFromRequest(); Logger.info("PARAMETERS : " + form.data().toString()); String tableName = form.get("table_name"); MultipartFormData body = request().body().asMultipartFormData(); FilePart fp = body.getFile("table_file_path"); if (fp != null) { String fileName = fp.getFilename(); String contentType = fp.getContentType(); Logger.info("fileName: " + fileName + ", contentType: " + contentType); File file = fp.getFile(); Set<DefaultType> defaultTypes = new HashSet<DefaultType>(); boolean saveToDisk = false; if(null != form.get("table1_default")){ defaultTypes.add(DefaultType.TABLE1); } if(null != form.get("table2_default")){ defaultTypes.add(DefaultType.TABLE2); } if(null != form.get("candset_default")){ defaultTypes.add(DefaultType.CAND_SET); } if(null != form.get("matches_default")){ defaultTypes.add(DefaultType.MATCHES); } if(null != form.get("gold_default")){ defaultTypes.add(DefaultType.GOLD); } if(null != form.get("save_to_disk")){ saveToDisk = true; } try{ Table table = TableDao.importTable(projectName, tableName, file.getAbsolutePath()); // save the table - this automatically updates the project but does not save it TableDao.save(table, defaultTypes, saveToDisk); statusMessage = "Successfully imported Table " + tableName + " with " + table.getSize() + " tuples."; } catch(IOException ioe){ flash("error", ioe.getMessage()); statusMessage = "Error: " + ioe.getMessage(); } } else { flash("error", "Missing file"); statusMessage = "Error: Missing file"; } return redirect(controllers.project.routes.ProjectController.showProject(projectName)); }