List of usage examples for org.apache.wicket.markup.html.form.upload FileUpload writeToTempFile
public final File writeToTempFile() throws Exception
From source file:com.doculibre.constellio.wicket.panels.admin.thesaurus.AddEditThesaurusPanel.java
License:Open Source License
public AddEditThesaurusPanel(String id) { super(id, false); this.thesaurusModel = new EntityModel<Thesaurus>(new LoadableDetachableModel() { @Override/*from w w w. j a v a2s . c om*/ protected Object load() { AdminCollectionPanel collectionAdminPanel = (AdminCollectionPanel) findParent( AdminCollectionPanel.class); RecordCollection collection = collectionAdminPanel.getCollection(); Thesaurus thesaurus = collection.getThesaurus(); return thesaurus != null ? thesaurus : newThesaurus; } }); Form form = getForm(); form.setModel(new CompoundPropertyModel(thesaurusModel)); final List<String> errorMessages = new ArrayList<String>(); errorsModalWindow = new ModalWindow("errorsModal"); errorsModalWindow.setCssClassName(ModalWindow.CSS_CLASS_GRAY); skosFileField = new FileUploadField("skosFile"); uploadButton = new Button("uploadButton") { @Override public void onSubmit() { errorMessages.clear(); FileUpload upload = skosFileField.getFileUpload(); if (upload != null) { try { skosFile = upload.writeToTempFile(); } catch (IOException e) { throw new WicketRuntimeException(e); } } AddEditThesaurusPanel.this.add(new AbstractAjaxTimerBehavior(Duration.seconds(1)) { @Override protected void onTimer(AjaxRequestTarget target) { stop(); if (!importing && skosFile != null && skosFile.exists()) { importing = true; importCompleted = false; progressInfo = new ProgressInfo(); progressPanel.start(target); getForm().modelChanging(); new Thread() { @Override public void run() { try { SkosServices skosServices = ConstellioSpringUtils.getSkosServices(); FileInputStream is = new FileInputStream(skosFile); AdminCollectionPanel collectionAdminPanel = (AdminCollectionPanel) findParent( AdminCollectionPanel.class); RecordCollection collection = collectionAdminPanel.getCollection(); Thesaurus importedThesaurus = skosServices.importThesaurus(is, progressInfo, errorMessages); List<ImportThesaurusPlugin> importThesaurusPlugins = PluginFactory .getPlugins(ImportThesaurusPlugin.class); if (!importThesaurusPlugins.isEmpty()) { for (ImportThesaurusPlugin importThesaurusPlugin : importThesaurusPlugins) { is = new FileInputStream(skosFile); importThesaurusPlugin.afterUpload(is, importedThesaurus, collection); } } FileUtils.deleteQuietly(skosFile); thesaurusModel.setObject(importedThesaurus); importing = false; importCompleted = true; } catch (FileNotFoundException e) { throw new WicketRuntimeException(e); } } }.start(); } } }); } }; uploadButton.setDefaultFormProcessing(false); progressInfo = new ProgressInfo(); progressInfoModel = new LoadableDetachableModel() { @Override protected Object load() { return progressInfo; } }; progressPanel = new ProgressPanel("progressPanel", progressInfoModel) { @Override protected void onFinished(AjaxRequestTarget target) { // while (!importCompleted) { // // Wait for the import to be completed // try { // Thread.sleep(500); // } catch (InterruptedException e) { // throw new WicketRuntimeException(e); // } // } target.addComponent(rdfAbout); target.addComponent(dcTitle); target.addComponent(dcDescription); target.addComponent(dcDate); target.addComponent(dcCreator); if (!errorMessages.isEmpty()) { IModel errorMsgModel = new LoadableDetachableModel() { @Override protected Object load() { StringBuffer sb = new StringBuffer(); for (String errorMsg : errorMessages) { sb.append(errorMsg); sb.append("\n"); } return sb.toString(); } }; MultiLineLabel multiLineLabel = new MultiLineLabel(errorsModalWindow.getContentId(), errorMsgModel); multiLineLabel.add(new SimpleAttributeModifier("style", "text-align:left;")); errorsModalWindow.setContent(multiLineLabel); errorsModalWindow.show(target); } } }; progressPanel.setVisible(false); deleteButton = new Button("deleteButton") { @Override public void onSubmit() { Thesaurus thesaurus = thesaurusModel.getObject(); if (thesaurus.getId() != null) { SkosServices skosServices = ConstellioSpringUtils.getSkosServices(); EntityManager entityManager = ConstellioPersistenceContext.getCurrentEntityManager(); if (!entityManager.getTransaction().isActive()) { entityManager.getTransaction().begin(); } skosServices.makeTransient(thesaurus); entityManager.getTransaction().commit(); AdminCollectionPanel collectionAdminPanel = (AdminCollectionPanel) findParent( AdminCollectionPanel.class); RecordCollection collection = collectionAdminPanel.getCollection(); collection.setThesaurus(null); AddEditThesaurusPanel.this.replaceWith(newReturnComponent(AddEditThesaurusPanel.this.getId())); } } @Override public boolean isVisible() { return super.isVisible() && thesaurusModel.getObject().getId() != null; } @Override protected String getOnClickScript() { String confirmMsg = getLocalizer().getString("confirmDelete", AddEditThesaurusPanel.this) .replace("'", "\\'"); return "if (confirm('" + confirmMsg + "')) { return true;} else { return false; }"; } }; deleteButton.setDefaultFormProcessing(false); rdfAbout = new Label("rdfAbout"); rdfAbout.setOutputMarkupId(true); dcTitle = new Label("dcTitle"); dcTitle.setOutputMarkupId(true); dcDescription = new Label("dcDescription"); dcDescription.setOutputMarkupId(true); dcDate = new Label("dcDate"); dcDate.setOutputMarkupId(true); dcCreator = new Label("dcCreator"); dcCreator.setOutputMarkupId(true); form.add(skosFileField); form.add(uploadButton); form.add(progressPanel); form.add(errorsModalWindow); form.add(deleteButton); form.add(rdfAbout); form.add(dcTitle); form.add(dcDescription); form.add(dcDate); form.add(dcCreator); }
From source file:com.userweave.components.image.ImageListPanel.java
License:Open Source License
private List<UploadedImage> extractUploadedImagesFromZipFile(FileUpload fileUpload) { List<UploadedImage> uploadedImages = new ArrayList<UploadedImage>(); File tempFile = null;/*from w w w.ja va 2 s . c om*/ try { tempFile = fileUpload.writeToTempFile(); tempFile.deleteOnExit(); ZipFile zipFile = new ZipFile(tempFile); for (Enumeration<ZipEntry> e = getEntries(zipFile); e.hasMoreElements();) { ZipEntry zipEntry = e.nextElement(); if (isImage(zipEntry.getName())) { InputStream inputStream = zipFile.getInputStream(zipEntry); uploadedImages.add(new UploadedImage(null, readByteArray(inputStream), zipEntry.getName())); inputStream.close(); } else { warn(new StringResourceModel("notSupportedImageInZipFile", this, null, new Object[] { zipEntry.getName() }).getString()); } } return uploadedImages; } catch (IOException e) { error(new StringResourceModel("unexpectedErrorDuringExtractionOfZipFile", this, null).getString()); if (logger.isErrorEnabled()) { logger.error( new StringResourceModel("unexpectedErrorDuringExtractionOfZipFile", this, null).getString(), e); } return Collections.emptyList(); } finally { if (tempFile != null) { tempFile.delete(); } } }
From source file:com.userweave.module.methoden.iconunderstandability.page.conf.terms.ITMTermsUpload.java
License:Open Source License
private List<String> extractUploadedTermsFromTxtFile(FileUpload fileUpload) { List<String> uploadedTerms = new ArrayList<String>(); File tempFile = null;/*from w ww. j ava 2 s . co m*/ try { tempFile = fileUpload.writeToTempFile(); tempFile.deleteOnExit(); Scanner scanner = new Scanner(tempFile); try { //first use a Scanner to get each line while (scanner.hasNextLine()) { String curLine = scanner.nextLine(); if (!curLine.trim().equals("")) { uploadedTerms.add(curLine); //use a second Scanner to parse the content of each line // Scanner lineScanner = new Scanner(curLine); // while ( lineScanner.hasNext() ){ // String token = lineScanner.next(); // if (token != null) { // uploadedTerms.add(token); // // if (logger.isDebugEnabled()) { // logger.debug("token is : " + token.trim()); // } // } // } // // (no need for finally here, since String is source) // lineScanner.close(); } } } finally { //ensure the underlying stream is always closed scanner.close(); } return uploadedTerms; } catch (IOException e) { error(new StringResourceModel("unexpectedErrorDuringExtractionOfFile", this, null).getString()); if (logger.isErrorEnabled()) { logger.error( new StringResourceModel("unexpectedErrorDuringExtractionOfFile", this, null).getString(), e); } return Collections.emptyList(); } finally { if (tempFile != null) { tempFile.delete(); } } }
From source file:de.tudarmstadt.ukp.clarin.webanno.automation.project.ProjectTrainingDocumentsPanel.java
License:Apache License
@SuppressWarnings({ "unchecked", "rawtypes" })
public ProjectTrainingDocumentsPanel(String id, IModel<Project> aProjectModel,
final IModel<TabSepDocModel> aTabsDocModel, IModel<AnnotationFeature> afeatureModel) {
super(id);//from w ww .j a v a2 s . c om
this.selectedProjectModel = aProjectModel;
feature = afeatureModel.getObject();
try {
if (aTabsDocModel.getObject().isTabSep()) {
readableFormats = new ArrayList<String>(Arrays.asList(new String[] { WebAnnoConst.TAB_SEP }));
selectedFormat = WebAnnoConst.TAB_SEP;
} else {
readableFormats = new ArrayList<String>(repository.getReadableFormatLabels());
selectedFormat = readableFormats.get(0);
}
} catch (IOException e) {
error("Properties file not found or key not int the properties file " + ":"
+ ExceptionUtils.getRootCauseMessage(e));
} catch (ClassNotFoundException e) {
error("The Class name in the properties is not found " + ":" + ExceptionUtils.getRootCauseMessage(e));
}
add(fileUpload = new FileUploadField("content", new Model()));
add(readableFormatsChoice = new DropDownChoice<String>("readableFormats", new Model(selectedFormat),
readableFormats) {
private static final long serialVersionUID = 2476274669926250023L;
@Override
public boolean isEnabled() {
return !aTabsDocModel.getObject().isTabSep();
}
});
add(new Button("import", new ResourceModel("label")) {
private static final long serialVersionUID = 1L;
@Override
public void onSubmit() {
uploadedFiles = fileUpload.getFileUploads();
Project project = selectedProjectModel.getObject();
if (isEmpty(uploadedFiles)) {
error("No document is selected to upload, please select a document first");
return;
}
if (project.getId() == 0) {
error("Project not yet created, please save project Details!");
return;
}
for (FileUpload documentToUpload : uploadedFiles) {
String fileName = documentToUpload.getClientFileName();
if (repository.existsSourceDocument(project, fileName)) {
error("Document " + fileName + " already uploaded ! Delete "
+ "the document if you want to upload again");
continue;
}
try {
File uploadFile = documentToUpload.writeToTempFile();
String username = SecurityContextHolder.getContext().getAuthentication().getName();
User user = userRepository.get(username);
SourceDocument document = new SourceDocument();
document.setName(fileName);
document.setProject(project);
document.setTrainingDocument(true);
// Since new training document is added, all
// non-tarining document should be
// re-annotated
for (SourceDocument sd : repository.listSourceDocuments(project)) {
if (!sd.isTrainingDocument()) {
sd.setProcessed(false);
}
}
for (SourceDocument sd : automationService.listTabSepDocuments(project)) {
if (!sd.isTrainingDocument()) {
sd.setProcessed(false);
}
}
// If this document is tab-sep and used as a feature itself, no need to add
// a feature to the document
if (aTabsDocModel.getObject().isTraining() || !aTabsDocModel.getObject().isTabSep()) {
document.setFeature(feature);
}
if (aTabsDocModel.getObject().isTabSep()) {
document.setFormat(selectedFormat);
} else {
String reader = repository.getReadableFormatId(readableFormatsChoice.getModelObject());
document.setFormat(reader);
}
repository.createSourceDocument(document, user);
repository.uploadSourceDocument(uploadFile, document);
info("File [" + fileName + "] has been imported successfully!");
} catch (ClassNotFoundException e) {
error(e.getMessage());
} catch (IOException e) {
error("Error uploading document " + e.getMessage());
} catch (UIMAException e) {
error("Error uploading document " + ExceptionUtils.getRootCauseMessage(e));
}
}
}
});
add(new ListMultipleChoice<String>("documents", new Model(selectedDocuments), documents) {
private static final long serialVersionUID = 1L;
{
setChoices(new LoadableDetachableModel<List<String>>() {
private static final long serialVersionUID = 1L;
@Override
protected List<String> load() {
Project project = selectedProjectModel.getObject();
documents.clear();
if (project.getId() != 0) {
if (aTabsDocModel.getObject().isTabSep()) {
for (SourceDocument document : automationService.listTabSepDocuments(project)) {
// This is tab-sep training document to the target layer
if (aTabsDocModel.getObject().isTraining() && document.getFeature() != null) {
documents.add(document.getName());
}
// this is tab-sep training document used as a feature
else if (!aTabsDocModel.getObject().isTraining()
&& document.getFeature() == null) {
documents.add(document.getName());
}
}
} else {
for (SourceDocument document : repository.listSourceDocuments(project)) {
if (document.getFeature() != null && document.getFeature().equals(feature)) {
documents.add(document.getName());
}
}
}
}
return documents;
}
});
}
});
add(new Button("remove", new ResourceModel("label")) {
private static final long serialVersionUID = 1L;
@Override
public void onSubmit() {
Project project = selectedProjectModel.getObject();
boolean isTrain = false;
for (String document : selectedDocuments) {
try {
String username = SecurityContextHolder.getContext().getAuthentication().getName();
User user = userRepository.get(username);
SourceDocument srDoc = repository.getSourceDocument(project, document);
if (srDoc.isTrainingDocument()) {
isTrain = true;
}
repository.removeSourceDocument(srDoc);
} catch (IOException e) {
error("Error while removing a document document " + ExceptionUtils.getRootCauseMessage(e));
}
documents.remove(document);
}
// If the deleted document is training document, re-training an automation should be possible again
if (isTrain) {
List<SourceDocument> docs = repository.listSourceDocuments(project);
docs.addAll(automationService.listTabSepDocuments(project));
for (SourceDocument srDoc : docs) {
srDoc.setProcessed(false);
}
}
}
});
}
From source file:de.tudarmstadt.ukp.clarin.webanno.project.page.AnnotationGuideLinePanel.java
License:Apache License
@SuppressWarnings({ "unchecked", "rawtypes" })
public AnnotationGuideLinePanel(String id, IModel<Project> aProjectModel) {
super(id);/*w w w . j a v a 2s . c o m*/
this.selectedProjectModel = aProjectModel;
add(fileUpload = new FileUploadField("content", new Model()));
add(new Button("importGuideline", new ResourceModel("label")) {
private static final long serialVersionUID = 1L;
@Override
public void onSubmit() {
uploadedFiles = fileUpload.getFileUploads();
Project project = selectedProjectModel.getObject();
if (project.getId() == 0) {
error("Project not yet created, please save project Details!");
return;
}
if (isEmpty(uploadedFiles)) {
error("No document is selected to upload, please select a document first");
return;
}
for (FileUpload guidelineFile : uploadedFiles) {
try {
File tempFile = guidelineFile.writeToTempFile();
String fileName = guidelineFile.getClientFileName();
String username = SecurityContextHolder.getContext().getAuthentication().getName();
projectRepository.createGuideline(project, tempFile, fileName, username);
} catch (IOException e) {
error("Unable to write guideline file " + ExceptionUtils.getRootCauseMessage(e));
}
}
}
});
add(new ListMultipleChoice<String>("documents", new Model(selectedDocuments), documents) {
private static final long serialVersionUID = 1L;
{
setChoices(new LoadableDetachableModel<List<String>>() {
private static final long serialVersionUID = 1L;
@Override
protected List<String> load() {
Project project = selectedProjectModel.getObject();
documents.clear();
if (project.getId() != 0) {
documents.addAll(projectRepository.listGuidelines(project));
}
return documents;
}
});
}
});
Button removeGuidelineButton = new Button("remove", new ResourceModel("label")) {
private static final long serialVersionUID = -5021618538109114902L;
@Override
public void onSubmit() {
Project project = selectedProjectModel.getObject();
for (String document : selectedDocuments) {
try {
String username = SecurityContextHolder.getContext().getAuthentication().getName();
projectRepository.removeGuideline(project, document, username);
} catch (IOException e) {
error("Error while removing a document document " + ExceptionUtils.getRootCauseMessage(e));
}
documents.remove(document);
}
}
};
// Add check to prevent accidental delete operation
removeGuidelineButton.add(new AttributeModifier("onclick",
"if(!confirm('Do you really want to delete this Guideline document?')) return false;"));
add(removeGuidelineButton);
// add(new Button("remove", new ResourceModel("label"))
// {
// private static final long serialVersionUID = 1L;
//
// @Override
// public void onSubmit()
// {
// Project project = selectedProjectModel.getObject();
// for (String document : selectedDocuments) {
// try {
// String username = SecurityContextHolder.getContext().getAuthentication()
// .getName();
// projectRepository.removeGuideline(project, document, username);
// }
// catch (IOException e) {
// error("Error while removing a document document "
// + ExceptionUtils.getRootCauseMessage(e));
// }
// documents.remove(document);
// }
// }
// });
}
From source file:de.tudarmstadt.ukp.clarin.webanno.project.page.ProjectDocumentsPanel.java
License:Apache License
@SuppressWarnings({ "unchecked", "rawtypes" })
public ProjectDocumentsPanel(String id, IModel<Project> aProjectModel) {
super(id);/*from w w w .j a v a2s. c o m*/
this.selectedProjectModel = aProjectModel;
try {
readableFormats = new ArrayList<String>(repository.getReadableFormatLabels());
selectedFormat = readableFormats.get(0);
} catch (IOException e) {
error("Properties file not found or key not int the properties file " + ":"
+ ExceptionUtils.getRootCauseMessage(e));
} catch (ClassNotFoundException e) {
error("The Class name in the properties is not found " + ":" + ExceptionUtils.getRootCauseMessage(e));
}
add(fileUpload = new FileUploadField("content", new Model()));
add(readableFormatsChoice = new DropDownChoice<String>("readableFormats", new Model(selectedFormat),
readableFormats));
add(new Button("import", new ResourceModel("label")) {
private static final long serialVersionUID = 1L;
@Override
public void onSubmit() {
uploadedFiles = fileUpload.getFileUploads();
Project project = selectedProjectModel.getObject();
if (isEmpty(uploadedFiles)) {
error("No document is selected to upload, please select a document first");
return;
}
if (project.getId() == 0) {
error("Project not yet created, please save project Details!");
return;
}
for (FileUpload documentToUpload : uploadedFiles) {
String fileName = documentToUpload.getClientFileName();
if (repository.existsSourceDocument(project, fileName)) {
error("Document " + fileName + " already uploaded ! Delete "
+ "the document if you want to upload again");
continue;
}
try {
File uploadFile = documentToUpload.writeToTempFile();
String username = SecurityContextHolder.getContext().getAuthentication().getName();
User user = userRepository.get(username);
SourceDocument document = new SourceDocument();
document.setName(fileName);
document.setProject(project);
String reader = repository.getReadableFormatId(readableFormatsChoice.getModelObject());
document.setFormat(reader);
repository.createSourceDocument(document, user);
repository.uploadSourceDocument(uploadFile, document);
info("File [" + fileName + "] has been imported successfully!");
} catch (ClassNotFoundException e) {
error(e.getMessage());
LOG.error(e.getMessage(), e);
} catch (IOException e) {
error("Error uploading document " + e.getMessage());
LOG.error(e.getMessage(), e);
} catch (UIMAException e) {
error("Error uploading document " + ExceptionUtils.getRootCauseMessage(e));
LOG.error(e.getMessage(), e);
}
}
}
});
add(new ListMultipleChoice<String>("documents", new Model(selectedDocuments), documents) {
private static final long serialVersionUID = 1L;
{
setChoices(new LoadableDetachableModel<List<String>>() {
private static final long serialVersionUID = 1L;
@Override
protected List<String> load() {
Project project = selectedProjectModel.getObject();
documents.clear();
if (project.getId() != 0) {
for (SourceDocument document : repository.listSourceDocuments(project)) {
if (!document.isTrainingDocument()) {
documents.add(document.getName());
}
}
}
return documents;
}
});
}
});
Button removeDocumentButton = new Button("remove", new ResourceModel("label")) {
private static final long serialVersionUID = 4053376790104708784L;
@Override
public void onSubmit() {
Project project = selectedProjectModel.getObject();
for (String document : selectedDocuments) {
try {
String username = SecurityContextHolder.getContext().getAuthentication().getName();
User user = userRepository.get(username);
repository.removeSourceDocument(repository.getSourceDocument(project, document));
} catch (IOException e) {
error("Error while removing a document document " + ExceptionUtils.getRootCauseMessage(e));
}
documents.remove(document);
}
}
};
// Add check to prevent accidental delete operation
removeDocumentButton.add(new AttributeModifier("onclick",
"if(!confirm('Do you really want to delete this Document?')) return false;"));
add(removeDocumentButton);
// add(new Button("remove", new ResourceModel("label"))
// {
// private static final long serialVersionUID = 1L;
//
// @Override
// public void onSubmit()
// {
// Project project = selectedProjectModel.getObject();
// for (String document : selectedDocuments) {
// try {
// String username = SecurityContextHolder.getContext().getAuthentication()
// .getName();
// User user = userRepository.get(username);
// repository.removeSourceDocument(
// repository.getSourceDocument(project, document));
// }
// catch (IOException e) {
// error("Error while removing a document document "
// + ExceptionUtils.getRootCauseMessage(e));
// }
// documents.remove(document);
// }
// }
// });
}
From source file:de.tudarmstadt.ukp.clarin.webanno.project.page.ProjectPage.java
License:Apache License
private void actionImportProject(List<FileUpload> exportedProjects, boolean aGenerateUsers) { Project importedProject = new Project(); // import multiple projects! for (FileUpload exportedProject : exportedProjects) { InputStream tagInputStream; try {//from www . j a v a 2 s . c om tagInputStream = exportedProject.getInputStream(); if (!ZipUtils.isZipStream(tagInputStream)) { error("Invalid ZIP file"); return; } File zipFfile = exportedProject.writeToTempFile(); if (!ImportUtil.isZipValidWebanno(zipFfile)) { error("Incompatible to webanno ZIP file"); } ZipFile zip = new ZipFile(zipFfile); InputStream projectInputStream = null; for (Enumeration zipEnumerate = zip.entries(); zipEnumerate.hasMoreElements();) { ZipEntry entry = (ZipEntry) zipEnumerate.nextElement(); if (entry.toString().replace("/", "").startsWith(ImportUtil.EXPORTED_PROJECT) && entry.toString().replace("/", "").endsWith(".json")) { projectInputStream = zip.getInputStream(entry); break; } } // projectInputStream = // uploadedFile.getInputStream(); String text = IOUtils.toString(projectInputStream, "UTF-8"); de.tudarmstadt.ukp.clarin.webanno.model.export.Project importedProjectSetting = JSONUtil .getJsonConverter().getObjectMapper() .readValue(text, de.tudarmstadt.ukp.clarin.webanno.model.export.Project.class); importedProject = ImportUtil.createProject(importedProjectSetting, repository, userRepository); Map<de.tudarmstadt.ukp.clarin.webanno.model.export.AnnotationFeature, AnnotationFeature> featuresMap = ImportUtil .createLayer(importedProject, importedProjectSetting, userRepository, annotationService); ImportUtil.createSourceDocument(importedProjectSetting, importedProject, repository, userRepository, featuresMap); ImportUtil.createMiraTemplate(importedProjectSetting, automationService, featuresMap); ImportUtil.createCrowdJob(importedProjectSetting, repository, importedProject); ImportUtil.createAnnotationDocument(importedProjectSetting, importedProject, repository); ImportUtil.createProjectPermission(importedProjectSetting, importedProject, repository, aGenerateUsers, userRepository); /* * for (TagSet tagset : importedProjectSetting.getTagSets()) { * ImportUtil.createTagset(importedProject, tagset, projectRepository, * annotationService); } */ // add source document content ImportUtil.createSourceDocumentContent(zip, importedProject, repository); // add annotation document content ImportUtil.createAnnotationDocumentContent(zip, importedProject, repository); // create curation document content ImportUtil.createCurationDocumentContent(zip, importedProject, repository); // create project log ImportUtil.createProjectLog(zip, importedProject, repository); // create project guideline ImportUtil.createProjectGuideline(zip, importedProject, repository); // create project META-INF ImportUtil.createProjectMetaInf(zip, importedProject, repository); // create project constraint ImportUtil.createProjectConstraint(zip, importedProject, repository); } catch (IOException e) { error("Error Importing Project " + ExceptionUtils.getRootCauseMessage(e)); } } projectDetailForm.setModelObject(importedProject); SelectionModel selectedProjectModel = new SelectionModel(); selectedProjectModel.project = importedProject; projectSelectionForm.setModelObject(selectedProjectModel); projectDetailForm.setVisible(true); RequestCycle.get().setResponsePage(getPage()); }
From source file:org.apache.openmeetings.web.common.UploadableImagePanel.java
License:Apache License
public void process(Optional<AjaxRequestTarget> target) { FileUpload fu = fileUploadField.getFileUpload(); if (fu != null) { File temp = null;// w ww. j a va 2s .c om try { temp = fu.writeToTempFile(); StoredFile sf = new StoredFile(fu.getClientFileName(), temp); if (sf.isImage()) { processImage(sf, temp); } } catch (Exception e) { log.error("Error", e); } finally { if (temp != null && temp.exists()) { log.debug("Temp file was deleted ? {}", temp.delete()); } fu.closeStreams(); fu.delete(); } } update(target); }
From source file:org.apache.openmeetings.web.common.UploadableProfileImagePanel.java
License:Apache License
public UploadableProfileImagePanel(String id, final long userId) { super(id, userId); final Form<Void> form = new Form<Void>("form"); form.setMultiPart(true);//w w w . j ava 2 s .c o m form.setMaxSize(Bytes.bytes(getBean(ConfigurationDao.class).getMaxUploadSize())); // Model is necessary here to avoid writing image to the User object form.add(fileUploadField = new FileUploadField("image", new IModel<List<FileUpload>>() { private static final long serialVersionUID = 1L; //FIXME this need to be eliminated @Override public void detach() { } @Override public void setObject(List<FileUpload> object) { } @Override public List<FileUpload> getObject() { return null; } })); form.add(new UploadProgressBar("progress", form, fileUploadField)); fileUploadField.add(new AjaxFormSubmitBehavior(form, "change") { private static final long serialVersionUID = 1L; @Override protected void onSubmit(AjaxRequestTarget target) { FileUpload fu = fileUploadField.getFileUpload(); if (fu != null) { StoredFile sf = new StoredFile(fu.getClientFileName()); if (sf.isImage()) { boolean asIs = sf.isAsIs(); try { //FIXME need to work with InputStream !!! getBean(GenerateImage.class).convertImageUserProfile(fu.writeToTempFile(), userId, asIs); } catch (Exception e) { // TODO display error log.error("Error", e); } } else { //TODO display error } } update(); target.add(profile, form); } }); add(form.setOutputMarkupId(true)); add(BootstrapFileUploadBehavior.INSTANCE); }
From source file:org.devproof.portal.core.module.theme.panel.UploadThemePanel.java
License:Apache License
private Form<FileUpload> newUploadForm() { uploadForm = new Form<FileUpload>("uploadForm") { private static final long serialVersionUID = 1L; @Override/*from w w w . java2 s .c o m*/ protected void onSubmit() { FileUpload fileUpload = uploadField.getFileUpload(); try { File tmpFile = fileUpload.writeToTempFile(); ValidationKey key = themeService.validateTheme(tmpFile); if (key == ValidationKey.VALID) { themeService.install(tmpFile); info(getString("msg.installed")); } else { handleErrorMessage(key); } if (!tmpFile.delete()) { logger.error("Could not delete " + tmpFile); } } catch (IOException e) { throw new UnhandledException(e); } UploadThemePanel.this.onSubmit(); super.onSubmit(); } private void handleErrorMessage(ValidationKey key) { if (key == ValidationKey.INVALID_DESCRIPTOR_FILE) { error(getString("msg.invalid_descriptor_file")); } else if (key == ValidationKey.MISSING_DESCRIPTOR_FILE) { error(getString("msg.missing_descriptor_file")); } else if (key == ValidationKey.NOT_A_JARFILE) { error(getString("msg.not_a_jarfile")); } else if (key == ValidationKey.WRONG_VERSION) { error(getString("wrong_version")); } else { throw new IllegalArgumentException("Unknown ValidationKey: " + key); } } }; return uploadForm; }