org.apache.wicket.markup.html.form.upload.FileUpload Java Examples

The following examples show how to use org.apache.wicket.markup.html.form.upload.FileUpload. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LicenseErrorPage.java    From nextreports-server with Apache License 2.0 6 votes vote down vote up
@Override
      protected void onSubmit() {
          FileUpload upload = fileUploadField.getFileUpload();
          if (upload != null) {
              File licenseFile = new File(getUploadFolder(), "license.dat"/*upload.getClientFileName()*/);

              // check new file, delete if it allready existed
              checkFileExists(licenseFile);
              try {
                  // Save to new file
                  licenseFile.createNewFile();
                  upload.writeTo(licenseFile);

                  LicenseErrorPage.this.info("Uploaded file: " + upload.getClientFileName());
                  setResponsePage(getApplication().getHomePage());
              } catch (Exception e) {
                  throw new IllegalStateException("Unable to write file");
              }
          }
}
 
Example #2
Source File: UploadIFrame.java    From ontopia with Apache License 2.0 6 votes vote down vote up
@Override
public void onSubmit() {
  FileUpload upload = uploadField.getFileUpload();         
  if (upload != null) {
    try {
      Reader input = new InputStreamReader(new Base64InputStream(upload.getInputStream(), true), "utf-8");
      FieldInstance fieldInstance = fieldValueModel.getFieldInstanceModel().getFieldInstance();
      StringWriter swriter = new StringWriter();
      IOUtils.copy(input, swriter);
      String value = swriter.toString();
      fieldInstance.addValue(value, getLifeCycleListener());
      fieldValueModel.setExistingValue(value);
      uploaded = true;
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
 
Example #3
Source File: BinaryEditPanel.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
public BinaryEditPanel(String id, IModel<byte[]> model) {
	super(id, model);
	fileUploadField = new FileUploadField("data", Model.ofList(new ArrayList<FileUpload>()));
	add(fileUploadField);
	fileUploadField.setOutputMarkupId(true);

	clear = new AjaxCheckBox("clear", Model.of(Boolean.FALSE)) {
		@Override
		protected void onUpdate(AjaxRequestTarget target) {
			Boolean shouldClear = clear.getConvertedInput();
			if (shouldClear) {
				fileUploadField.clearInput();
			}

			fileUploadField.setEnabled(!shouldClear);
			target.add(fileUploadField);
		}
	};

	add(clear);
}
 
Example #4
Source File: UploadableImagePanel.java    From openmeetings with Apache License 2.0 6 votes vote down vote up
public void process(Optional<AjaxRequestTarget> target) {
	FileUpload fu = fileUploadField.getFileUpload();
	if (fu != null) {
		File temp = null;
		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);
}
 
Example #5
Source File: BinaryEditPanel.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
@Override
public void convertInput() {
	if (clear.getConvertedInput())
	{
		setConvertedInput(null);
		tempName = null;
		return;
	}

	FileUpload fileUpload = fileUploadField.getFileUpload();
	if(fileUpload!=null) {
		setConvertedInput(fileUpload.getBytes());
		tempName = fileUpload.getClientFileName();
	}
	else {
		setConvertedInput(getModelObject());
	}
}
 
Example #6
Source File: AbstractUploadFilePanel.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
public AbstractUploadFilePanel(String id, final ModalWindow modal,final AbstractModalWindowCommand<?> command) {
	super(id);
	modal.setMinimalHeight(300);
	modal.showUnloadConfirmation(false);
	Form<?> uploadForm = new Form<Object>("uploadForm");
	final FileUploadField inputFile = new FileUploadField("inputFile");
	uploadForm.add(inputFile);
	uploadForm.add(new AjaxButton("loadFile",getLoadButtonTitle(),uploadForm)
	{
		private static final long serialVersionUID = 1L;

		@Override
		protected void onSubmit(AjaxRequestTarget target) {
			FileUpload file = inputFile.getFileUpload();
			if (file!=null){
				onLoadFile(file);
				command.onAfterModalSubmit();
				modal.close(target);
			}
		}
		
	});
	add(uploadForm);		
}
 
Example #7
Source File: DatevImportPage.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
protected void importAccountList()
{
  checkAccess();
  final FileUpload fileUpload = form.fileUploadField.getFileUpload();
  if (fileUpload != null) {
    try {
      final InputStream is = fileUpload.getInputStream();
      actionLog.reset();
      final String clientFileName = fileUpload.getClientFileName();
      setStorage(datevImportDao.importKontenplan(is, clientFileName, actionLog));
    } catch (final Exception ex) {
      log.error(ex.getMessage(), ex);
      error("An error occurred (see log files for details): " + ex.getMessage());
      clear();
    }
  }
}
 
Example #8
Source File: DatevImportPage.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
protected void importAccountRecords()
{
  checkAccess();
  final FileUpload fileUpload = form.fileUploadField.getFileUpload();
  if (fileUpload != null) {
    try {
      final InputStream is = fileUpload.getInputStream();
      actionLog.reset();
      final String clientFileName = fileUpload.getClientFileName();
      setStorage(datevImportDao.importBuchungsdaten(is, clientFileName, actionLog));
    } catch (final Exception ex) {
      log.error(ex.getMessage(), ex);
      error("An error occurred (see log files for details): " + ex.getMessage());
      clear();
    }
  }
}
 
Example #9
Source File: ReportObjectivesPage.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
protected void importReportObjectivs()
{
  checkAccess();
  log.info("import report objectives.");
  final FileUpload fileUpload = form.fileUploadField.getFileUpload();
  if (fileUpload != null) {
    try {
      final String clientFileName = fileUpload.getClientFileName();
      final InputStream is = fileUpload.getInputStream();
      final Report report = reportDao.createReport(is);
      reportStorage = new ReportStorage(report);
      reportStorage.setFileName(clientFileName);
      putUserPrefEntry(KEY_REPORT_STORAGE, reportStorage, false);
    } catch (final Exception ex) {
      log.error(ex.getMessage(), ex);
      error("An error occurred (see log files for details): " + ex.getMessage());
    }
  }
}
 
Example #10
Source File: TeamCalImportPage.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
protected void importEvents()
{
  checkAccess();
  final FileUpload fileUpload = form.fileUploadField.getFileUpload();
  if (fileUpload != null) {
    try {
      final InputStream is = fileUpload.getInputStream();
      actionLog.reset();
      final String clientFilename = fileUpload.getClientFileName();
      final CalendarBuilder builder = new CalendarBuilder();
      final Calendar calendar = builder.build(is);
      final ImportStorage<TeamEventDO> storage = teamCalImportDao.importEvents(calendar, clientFilename, actionLog);
      setStorage(storage);
    } catch (final Exception ex) {
      log.error(ex.getMessage(), ex);
      error("An error occurred (see log files for details): " + ex.getMessage());
      clear();
    } finally {
      fileUpload.closeStreams();
    }
  }
}
 
Example #11
Source File: ScriptingPage.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
protected void upload()
{
  accessChecker.checkIsLoggedInUserMemberOfGroup(ProjectForgeGroup.FINANCE_GROUP, ProjectForgeGroup.CONTROLLING_GROUP);
  accessChecker.checkRestrictedOrDemoUser();
  log.info("upload");
  final FileUpload fileUpload = form.fileUploadField.getFileUpload();
  if (fileUpload != null) {
    final boolean delete = false;
    try {
      final InputStream is = fileUpload.getInputStream();
      final String clientFileName = fileUpload.getClientFileName();
      if (clientFileName.endsWith(".jrxml") == true) {
        log.error("Jasper reports not supported.");
        // delete = true;
        // final JasperReport report = JasperCompileManager.compileReport(is);
        // if (report != null) {
        // getReportScriptingStorage().setJasperReport(report, clientFileName);
        // }
      } else if (clientFileName.endsWith(".xls") == true) {
        final StringBuffer buf = new StringBuffer();
        buf.append("report_").append(FileHelper.createSafeFilename(PFUserContext.getUser().getUsername(), 20)).append(".xls");
        final File file = new File(ConfigXml.getInstance().getWorkingDirectory(), buf.toString());
        fileUpload.writeTo(file);
        getReportScriptingStorage().setFilename(clientFileName, file.getAbsolutePath());
      } else {
        log.error("File extension not supported: " + clientFileName);
      }
    } catch (final Exception ex) {
      log.error(ex.getMessage(), ex);
      error("An error occurred (see log files for details): " + ex.getMessage());
    } finally {
      if (delete == true) {
        fileUpload.delete();
      }
    }
  }
}
 
Example #12
Source File: UserOArtifactPanel.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private File getJarFile(FileUploadField fileUploadField) {
    FileUpload fileUpload = fileUploadField.getFileUpload();
    if (fileUpload == null) return null;
    String clientFileName = fileUpload.getClientFileName();
    if (!fileUpload.getClientFileName().endsWith(".jar")) return null;
    return OrienteerClassLoaderUtil.createJarTempFile(clientFileName, fileUpload);
}
 
Example #13
Source File: ImageEditPanel.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
public void validate() {
    super.validate();
    FileUpload fileUpload = fileUploadField.getFileUpload();
    if(fileUpload!=null) {
        byte[] bytes = fileUpload.getBytes();
        boolean isImage = new Tika().detect(bytes).startsWith("image/");
        if (!isImage) {
            error(getString("errors.wrong.image.uploaded"));
        }
    }
}
 
Example #14
Source File: AddressImportForm.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @see org.apache.wicket.Component#onInitialize()
 */
@Override
protected void onInitialize()
{
  super.onInitialize();
  gridBuilder.newSplitPanel(GridSize.COL50);
  final FieldsetPanel newFieldset = gridBuilder.newFieldset(getString("address.book.vCardImport.fileUploadPanel"));

  final FileUploadField uploadField = new FileUploadField(FileUploadPanel.WICKET_ID, new PropertyModel<List<FileUpload>>(this, "uploads"));
  newFieldset.add(new FileUploadPanel(newFieldset.newChildId(), uploadField));
}
 
Example #15
Source File: FileUploadPanel.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Called by validator.
 */
protected void upload(final FileUpload fileUpload)
{
  if (fileUpload != null) {
    final String clientFileName = FileHelper.createSafeFilename(fileUpload.getClientFileName(), 255);
    log.info("Upload file '" + clientFileName + "'.");
    final byte[] bytes = fileUpload.getBytes();
    filename.setObject(clientFileName);
    file.setObject(bytes);
  }
}
 
Example #16
Source File: OrienteerClassLoaderUtil.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
/**
 * Add artifact jar file to temp folder
 * @param artifactName artifact name
 * @param fileUpload {@link FileUpload} of artifact's jar
 * @return {@link File} of artifact's jar file or Optional.absent() if can't add artifact's jar file to folder
 * @throws IllegalArgumentException if artifactName is null or empty. Or when fileUpload is null.
 */
public static File createJarTempFile(String artifactName, FileUpload fileUpload) {
    Args.notEmpty(artifactName, "artifactName");
    Args.notNull(fileUpload, "fileUpload");
    String fileName = fileUpload.getClientFileName();
    try {
        File file = File.createTempFile(fileName.replaceAll("\\.jar", ""), ".jar");
        fileUpload.writeTo(file);
        return file;
    } catch (Exception e) {
        LOG.error("Cannot upload file: {}", fileName, e);
    }
    return null;
}
 
Example #17
Source File: CSVPullWizardBuilder.java    From syncope with Apache License 2.0 5 votes vote down vote up
public Details(final CSVPullSpec spec) {
    FileInputConfig csvFile = new FileInputConfig().
            showUpload(false).showRemove(false).showPreview(false).
            browseClass("btn btn-success").browseIcon("<i class=\"fas fa-folder-open\"></i> &nbsp;");
    String language = SyncopeConsoleSession.get().getLocale().getLanguage();
    if (!Locale.ENGLISH.getLanguage().equals(language)) {
        csvFile.withLocale(language);
    }
    BootstrapFileInputField csvUpload =
            new BootstrapFileInputField("csvUpload", new ListModel<>(new ArrayList<>()), csvFile);
    csvUpload.add(new AjaxFormSubmitBehavior(Constants.ON_CHANGE) {

        private static final long serialVersionUID = 5538299138211283825L;

        @Override
        protected void onSubmit(final AjaxRequestTarget target) {
            FileUpload uploadedFile = csvUpload.getFileUpload();
            if (uploadedFile != null) {
                if (maxUploadSize != null && uploadedFile.getSize() > maxUploadSize.bytes()) {
                    SyncopeConsoleSession.get().error(getString("tooLargeFile").
                            replace("${maxUploadSizeB}", String.valueOf(maxUploadSize.bytes())).
                            replace("${maxUploadSizeMB}", String.valueOf(maxUploadSize.bytes() / 1000000L)));
                    ((BasePage) getPageReference().getPage()).getNotificationPanel().refresh(target);
                } else {
                    csv.setObject(uploadedFile.getBytes());
                }
            }
        }
    });
    add(csvUpload.setRequired(true).setOutputMarkupId(true));

    add(new CSVConfPanel("csvconf", spec));
}
 
Example #18
Source File: AccessSpecificSettingsPanel.java    From inception with Apache License 2.0 5 votes vote down vote up
public void handleUploadedFiles()
{
    try {
        for (FileUpload fu : fileUpload.getFileUploads()) {
            File tmp = uploadFile(fu);
            kbModel.getObject().putFile(fu.getClientFileName(), tmp);
        }
    }
    catch (Exception e) {
        log.error("Error while uploading files", e);
        error("Could not upload files");
    }
}
 
Example #19
Source File: ImportGuidelinesPanel.java    From webanno with Apache License 2.0 5 votes vote down vote up
private void actionImport(AjaxRequestTarget aTarget, Form<Void> aForm)
{
    List<FileUpload> uploadedFiles = fileUpload.getFileUploads();
    Project project = projectModel.getObject();

    if (isNull(project.getId())) {
        aTarget.addChildren(getPage(), IFeedback.class);
        error("Project not yet created, please save project details!");
        return;
    }
    if (isEmpty(uploadedFiles)) {
        aTarget.addChildren(getPage(), IFeedback.class);
        error("No document is selected to upload, please select a document first");
        return;
    }

    for (FileUpload guidelineFile : uploadedFiles) {
        try {
            // Workaround for WICKET-6425
            File tempFile = File.createTempFile("webanno-guidelines", null);
            try (InputStream is = guidelineFile.getInputStream();
                    OutputStream os = new FileOutputStream(tempFile);) {
                IOUtils.copyLarge(is, os);

                String fileName = guidelineFile.getClientFileName();
                projectRepository.createGuideline(project, tempFile, fileName);
            }
            finally {
                tempFile.delete();
            }
        }
        catch (Exception e) {
            error("Unable to write guideline file " + ExceptionUtils.getRootCauseMessage(e));
        }
    }

    WicketUtil.refreshPage(aTarget, getPage());
}
 
Example #20
Source File: FileUploadDownloadHelper.java    From inception with Apache License 2.0 5 votes vote down vote up
/**
 * Writes the input stream to a temporary file. The file is deleted if the object behind marker
 * is garbage collected. The temporary file will keep its extension based on the specified file
 * name.
 *
 * @param fileUpload The file upload handle to write to the temporary file
 * @param marker The object to whose lifetime the temporary file is bound
 * @return A handle to the created temporary file
 */
public File writeFileUploadToTemporaryFile(FileUpload fileUpload, Object marker)
    throws IOException
{
    String fileName = fileUpload.getClientFileName();
    File tmpFile = File.createTempFile(INCEPTION_TMP_FILE_PREFIX, fileName);
    log.debug("Creating temporary file for [{}] in [{}]", fileName, tmpFile.getAbsolutePath());
    fileTracker.track(tmpFile, marker);
    try (InputStream is = fileUpload.getInputStream()) {
        FileUtils.copyInputStreamToFile(is, tmpFile);
    }
    return tmpFile;
}
 
Example #21
Source File: ProjectLayersPanel.java    From webanno with Apache License 2.0 5 votes vote down vote up
private void actionImport(AjaxRequestTarget aTarget, Form<String> aForm)
{
    List<FileUpload> uploadedFiles = fileUpload.getFileUploads();
    Project project = ProjectLayersPanel.this.getModelObject();

    if (isEmpty(uploadedFiles)) {
        error("Please choose file with layer details before uploading");
        return;
    }
    else if (isNull(project.getId())) {
        error("Project not yet created, please save project details!");
        return;
    }
    for (FileUpload uploadedFile : uploadedFiles) {
        try (BufferedInputStream bis = IOUtils.buffer(uploadedFile.getInputStream())) {
            byte[] buf = new byte[5];
            bis.mark(buf.length + 1);
            bis.read(buf, 0, buf.length);
            bis.reset();

            // If the file starts with an XML preamble, then we assume it is an UIMA
            // type system file.
            if (Arrays.equals(buf, new byte[] { '<', '?', 'x', 'm', 'l' })) {
                importUimaTypeSystemFile(bis);
            }
            else {
                importLayerFile(bis);
            }
        }
        catch (Exception e) {
            error("Error importing layers: " + ExceptionUtils.getRootCauseMessage(e));
            aTarget.addChildren(getPage(), IFeedback.class);
            LOG.error("Error importing layers", e);
        }
    }
    featureDetailForm.setVisible(false);
    aTarget.add(ProjectLayersPanel.this);
}
 
Example #22
Source File: AccessSpecificSettingsPanel.java    From inception with Apache License 2.0 5 votes vote down vote up
private File uploadFile(FileUpload fu) throws IOException
{
    String fileName = fu.getClientFileName();
    if (!uploadedFiles.containsKey(fileName)) {
        FileUploadDownloadHelper fileUploadDownloadHelper = new FileUploadDownloadHelper(
            getApplication());
        File tmpFile = fileUploadDownloadHelper.writeFileUploadToTemporaryFile(fu, kbModel);
        uploadedFiles.put(fileName, tmpFile);
    }
    else {
        log.debug("File [{}] already downloaded, skipping!", fileName);
    }
    return uploadedFiles.get(fileName);
}
 
Example #23
Source File: StringMatchingRecommenderTraitsEditor.java    From inception with Apache License 2.0 5 votes vote down vote up
private void actionUploadGazeteer(AjaxRequestTarget aTarget)
{
    aTarget.addChildren(getPage(), IFeedback.class);
    aTarget.add(gazeteers);
    
    for (FileUpload importedGazeteer : uploadField.getModelObject()) {
        Gazeteer gazeteer = new Gazeteer();
        gazeteer.setName(importedGazeteer.getClientFileName());
        gazeteer.setRecommender(getModelObject());
        
        // Make sure the gazetter name is unique
        int n = 2;
        while (gazeteerService.existsGazeteer(gazeteer.getRecommender(), gazeteer.getName())) {
            String baseName = FilenameUtils.getBaseName(importedGazeteer.getClientFileName());
            String extension = FilenameUtils.getExtension(importedGazeteer.getClientFileName());
            gazeteer.setName(baseName + ' ' + n + '.' + extension);
            n++;
        }
        
        try (InputStream is = importedGazeteer.getInputStream()) {
            gazeteerService.createOrUpdateGazeteer(gazeteer);
            gazeteerService.importGazeteerFile(gazeteer, is);
            success("Imported gazeteer: [" + gazeteer.getName() + "]");
        }
        catch (Exception e) {
            error("Error importing gazeteer: " + ExceptionUtils.getRootCauseMessage(e));
            LOG.error("Error importing gazeteer", e);
        }
    }
}
 
Example #24
Source File: DropzoneField.java    From onedev with MIT License 5 votes vote down vote up
@Override
public void convertInput() {
	if (fileItems.isEmpty()) {
		setConvertedInput(null);
	} else {
		Collection<FileUpload> uploads = new ArrayList<>();
		for (FileItem fileItem: fileItems) {
			uploads.add(new FileUpload(fileItem));
		}
		setConvertedInput(uploads);
	}
}
 
Example #25
Source File: BackupPanel.java    From openmeetings with Apache License 2.0 4 votes vote down vote up
@Override
public List<FileUpload> getObject() {
	return new ArrayList<>();
}
 
Example #26
Source File: ConsoleImportProjectPage.java    From artifact-listener with Apache License 2.0 4 votes vote down vote up
public ConsoleImportProjectPage(PageParameters parameters) {
	super(parameters);
	
	addHeadPageTitleKey("console.import.project");
	
	// File select form
	final FileUploadField fileSelect = new FileUploadField("fileSelectInput", this.fileUploadsModel);
	fileSelect.setLabel(new ResourceModel("console.import.project.file"));
	fileSelect.add(AttributeModifier.replace("accept", getAcceptAttribute()));
	
	Form<Void> form = new Form<Void>("fileSelectForm") {
		private static final long serialVersionUID = 1L;

		@Override
		protected void onSubmit() {
			File file = null;
			try {
				FileUpload fileUpload = fileSelect.getFileUpload();
				
				if (fileUpload == null) {
					getSession().error(getString("console.import.project.error.noFile"));
					return;
				}
				
				file = File.createTempFile("uploaded-", ".xls", configurer.getTmpDirectory());
				fileUpload.writeTo(file);
				
				projectImportDataService.importProjects(file);
				
				Session.get().success(getString("console.import.project.success"));
			} catch (Exception e) {
				LOGGER.error("Unable to parse " + fileSelect.getFileUpload().getClientFileName() + " file", e);
				
				Session.get().error(getString("console.import.project.error"));
			} finally {
				FileUtils.deleteQuietly(file);
			}
		}
	};
	form.add(fileSelect);
	
	// Example excel file download link
	form.add(new ResourceLink<Void>("downloadTemplate", ProjectImportModelResourceReference.get()));
	
	form.add(new SubmitLink("importButton"));
	
	add(form);
}
 
Example #27
Source File: UploadJasperReportPanel.java    From nextreports-server with Apache License 2.0 4 votes vote down vote up
private JasperContent getReportContent(FileUpload upload,
		Collection<FileUpload> subreportsFileUpload, FileUpload paramUpload,
		Collection<FileUpload> imgUpload) throws IOException, ReportEngineException {
    JasperContent reportContent = new JasperContent();
    reportContent.setName("content");
    reportContent.setPath(StorageUtil.createPath(report.getPath(), "content"));
    try {
        List<JcrFile> jasperFiles = new ArrayList<JcrFile>();
        JcrFile masterFile = new JcrFile();
        masterFile.setName(upload.getClientFileName());
        masterFile.setPath(StorageUtil.createPath(reportContent.getPath(), masterFile.getName()));
        masterFile.setMimeType("text/xml");
        masterFile.setLastModified(Calendar.getInstance());
        masterFile.setDataProvider(new JcrDataProviderImpl(upload.getBytes()));

        JasperReportSaxParser parser = new JasperReportSaxParser();
        parser.process(upload.getBytes());
        String language = parser.getLanguage();
        if ((language != null) && !"java".equals(language)) {
            throw new ReportEngineException("Report language is '" + language + "'. Only reports with 'java' may be added.");
        }

        jasperFiles.add(masterFile);
        for (FileUpload subUpload : subreportsFileUpload) {
            JcrFile subreportFile = new JcrFile();
            subreportFile.setName(subUpload.getClientFileName());
            subreportFile.setPath(StorageUtil.createPath(reportContent.getPath(), subreportFile.getName()));
            subreportFile.setMimeType("text/xml");
            subreportFile.setLastModified(Calendar.getInstance());
            subreportFile.setDataProvider(new JcrDataProviderImpl(subUpload.getBytes()));

            parser.process(subUpload.getBytes());
            language = parser.getLanguage();
            if ((language != null) && !"java".equals(language)) {
                throw new ReportEngineException("Report language is '" + language + "'. Only reports with 'java' may be added.");
            }

            jasperFiles.add(subreportFile);
        }
        reportContent.setJasperFiles(jasperFiles);

        if (paramUpload != null) {
            JcrFile parametersFile = new JcrFile();
            parametersFile.setName(paramUpload.getClientFileName());
            parametersFile.setPath(StorageUtil.createPath(reportContent.getPath(), parametersFile.getName()));
            parametersFile.setMimeType("text/xml");
            parametersFile.setLastModified(Calendar.getInstance());
            parametersFile.setDataProvider(new JcrDataProviderImpl(paramUpload.getBytes()));
            reportContent.setParametersFile(parametersFile);
        }

        List<JcrFile> imageFiles = new ArrayList<JcrFile>();
        for (FileUpload iu : imgUpload) {
            JcrFile imageFile = new JcrFile();
            imageFile.setName(iu.getClientFileName());
            imageFile.setPath(StorageUtil.createPath(reportContent.getPath(), imageFile.getName()));
            imageFile.setMimeType(iu.getContentType());
            imageFile.setLastModified(Calendar.getInstance());
            imageFile.setDataProvider(new JcrDataProviderImpl(iu.getBytes()));
            imageFiles.add(imageFile);
        }
        reportContent.setImageFiles(imageFiles);
    } catch (Exception e) {
        if (e instanceof ReportEngineException) {
            throw (ReportEngineException)e;
        }
        e.printStackTrace();
        LOG.error(e.getMessage(), e);
        error(e.getMessage());
    }

    return reportContent;
}
 
Example #28
Source File: FileUploadPanel.java    From projectforge-webapp with GNU General Public License v3.0 4 votes vote down vote up
public FileUpload getFileUpload()
{
  return fileUploadField.getFileUpload();
}
 
Example #29
Source File: ProjectsOverviewPage.java    From inception with Apache License 2.0 4 votes vote down vote up
private void actionImport(AjaxRequestTarget aTarget, Form<Void> aForm)
{
    aTarget.addChildren(getPage(), IFeedback.class);
    
    List<FileUpload> exportedProjects = fileUpload.getFileUploads();
    for (FileUpload exportedProject : exportedProjects) {
        try {
            // Workaround for WICKET-6425
            File tempFile = File.createTempFile("project-import", null);
            try (
                    InputStream is = new BufferedInputStream(exportedProject.getInputStream());
                    OutputStream os = new FileOutputStream(tempFile);
            ) {
                if (!ZipUtils.isZipStream(is)) {
                    throw new IOException("Invalid ZIP file");
                }
                IOUtils.copyLarge(is, os);
                
                if (!ImportUtil.isZipValidWebanno(tempFile)) {
                    throw new IOException("ZIP file is not a valid project archive");
                }
                
                ProjectImportRequest request = new ProjectImportRequest(false, false,
                        Optional.of(userRepository.getCurrentUser()));
                Project importedProject = exportService.importProject(request,
                        new ZipFile(tempFile));
                
                success("Imported project: " + importedProject.getName());
            }
            finally {
                tempFile.delete();
            }
        }
        catch (Exception e) {
            error("Error importing project: " + ExceptionUtils.getRootCauseMessage(e));
            LOG.error("Error importing project", e);
        }
    }
    
    // After importing new projects, they should be visible in the overview, but we do not
    // redirect to the imported project. Could do that... maybe could do that if only a single
    // project was imported. Could also highlight the freshly imported projects somehow.
    
    aTarget.add(projectListContainer);
}
 
Example #30
Source File: BackupPanel.java    From openmeetings with Apache License 2.0 4 votes vote down vote up
@Override
public void setObject(List<FileUpload> object) {
	//no-op
}