Search in sources :

Example 26 with File

use of org.apache.wicket.util.file.File in project midpoint by Evolveum.

the class ImportReportPopupPanel method importConfirmPerformed.

private void importConfirmPerformed(AjaxRequestTarget target, Model<String> nameModel, Model<String> fileStringImport) {
    String dataName;
    if (nameModel == null || StringUtils.isEmpty(nameModel.getObject())) {
        dataName = getModelObject().getName().getOrig() + "-IMPORT " + getDataTime();
    } else {
        dataName = nameModel.getObject();
    }
    // Create new file
    MidPointApplication application = getPageBase().getMidpointApplication();
    WebApplicationConfiguration config = application.getWebApplicationConfiguration();
    String midpointHome = System.getProperty(MidpointConfiguration.MIDPOINT_HOME_PROPERTY);
    File importDir = new File(midpointHome, "import");
    if (!importDir.exists() || !importDir.isDirectory()) {
        if (!importDir.mkdir()) {
            LOGGER.error("Couldn't create import dir {}", importDir);
            FeedbackAlerts feedback = getFeedbackPanel();
            feedback.error(getPageBase().createStringResource("ImportReportPopupPanel.message.error.createImportDir", importDir).getString());
            target.add(feedback);
            return;
        }
    }
    FileUpload uploadedFile = getUploadedFile();
    if (uploadedFile == null && StringUtils.isEmpty(fileStringImport.getObject())) {
        LOGGER.error("Please upload file for import");
        FeedbackAlerts feedback = getFeedbackPanel();
        feedback.error(getPageBase().createStringResource("ImportReportPopupPanel.message.error.uploadFile", importDir).getString());
        target.add(feedback);
        return;
    }
    String newFilePath;
    if (uploadedFile != null) {
        String fileName = FilenameUtils.removeExtension(uploadedFile.getClientFileName()) + " " + getDataTime() + "." + FilenameUtils.getExtension(uploadedFile.getClientFileName());
        File newFile = new File(importDir, fileName);
        // Check new file, delete if it already exists
        if (newFile.exists()) {
            newFile.delete();
        }
        try {
            newFile.createNewFile();
            FileUtils.copyInputStreamToFile(uploadedFile.getInputStream(), newFile);
            newFilePath = newFile.getAbsolutePath();
        } catch (IOException e) {
            LOGGER.error("Couldn't create new file " + newFile.getAbsolutePath(), e);
            FeedbackAlerts feedback = getFeedbackPanel();
            feedback.error(getPageBase().createStringResource("ImportReportPopupPanel.message.error.createImportFile", newFile.getAbsolutePath()).getString());
            target.add(feedback);
            return;
        }
    } else {
        newFilePath = new File(importDir, dataName).getAbsolutePath();
        try {
            Files.write(Paths.get(newFilePath), fileStringImport.getObject().getBytes());
        } catch (IOException e) {
            LOGGER.error("Couldn't create new file " + newFilePath, e);
            FeedbackAlerts feedback = getFeedbackPanel();
            feedback.error(getPageBase().createStringResource("ImportReportPopupPanel.message.error.createImportFile", newFilePath).getString());
            target.add(feedback);
            return;
        }
    }
    ReportDataType reportImportData = null;
    try {
        @NotNull PrismObject<ReportDataType> prismObject = getPrismContext().getSchemaRegistry().findObjectDefinitionByCompileTimeClass(ReportDataType.class).instantiate();
        reportImportData = prismObject.asObjectable();
    } catch (SchemaException e) {
        LOGGER.error("Couldn't instantiate new Report Data from definition", e);
        FeedbackAlerts feedback = getFeedbackPanel();
        feedback.error(getPageBase().createStringResource("ImportReportPopupPanel.message.error.createInstantiateReportData").getString());
        target.add(feedback);
        return;
    }
    reportImportData.setName(new PolyStringType(dataName));
    reportImportData.setFilePath(newFilePath);
    ObjectReferenceType reportRef = new ObjectReferenceType();
    reportRef.setType(ReportType.COMPLEX_TYPE);
    reportRef.setOid(getModelObject().getOid());
    reportImportData.setReportRef(reportRef);
    Collection<ObjectDelta<? extends ObjectType>> deltas = Collections.singleton(reportImportData.asPrismObject().createAddDelta());
    Task task = getPageBase().createSimpleTask(OPERATION_CREATE_REPORT_DATA);
    try {
        Collection<ObjectDeltaOperation<? extends ObjectType>> retDeltas = getPageBase().getModelService().executeChanges(deltas, null, task, task.getResult());
        reportImportData = (ReportDataType) retDeltas.iterator().next().getObjectDelta().getObjectToAdd().asObjectable();
    } catch (ObjectAlreadyExistsException e) {
        LOGGER.error("Report Data with name " + dataName + " already exists", e);
        FeedbackAlerts feedback = getFeedbackPanel();
        feedback.error(getPageBase().createStringResource("ImportReportPopupPanel.message.error.importReportDataAlreadyExists", dataName).getString());
        target.add(feedback);
        return;
    } catch (Exception e) {
        LOGGER.error("Couldn't create new Report Data with name " + dataName, e);
        FeedbackAlerts feedback = getFeedbackPanel();
        feedback.error(getPageBase().createStringResource("ImportReportPopupPanel.message.error.createImportReportData", dataName).getString());
        target.add(feedback);
        return;
    }
    importConfirmPerformed(target, reportImportData);
}
Also used : PolyStringType(com.evolveum.prism.xml.ns._public.types_3.PolyStringType) Task(com.evolveum.midpoint.task.api.Task) IOException(java.io.IOException) NotNull(org.jetbrains.annotations.NotNull) IOException(java.io.IOException) MidPointApplication(com.evolveum.midpoint.web.security.MidPointApplication) ObjectDeltaOperation(com.evolveum.midpoint.schema.ObjectDeltaOperation) FeedbackAlerts(com.evolveum.midpoint.web.component.message.FeedbackAlerts) WebApplicationConfiguration(com.evolveum.midpoint.web.security.WebApplicationConfiguration) ObjectDelta(com.evolveum.midpoint.prism.delta.ObjectDelta) File(org.apache.wicket.util.file.File) FileUpload(org.apache.wicket.markup.html.form.upload.FileUpload)

Example 27 with File

use of org.apache.wicket.util.file.File in project midpoint by Evolveum.

the class PageDebugDownloadBehaviour method initFile.

@Override
protected File initFile() {
    PageBase page = getPage();
    OperationResult result = new OperationResult(OPERATION_CREATE_DOWNLOAD_FILE);
    MidPointApplication application = page.getMidpointApplication();
    WebApplicationConfiguration config = application.getWebApplicationConfiguration();
    File folder = new File(config.getExportFolder());
    if (!folder.exists() || !folder.isDirectory()) {
        folder.mkdir();
    }
    String suffix = isUseZip() ? "zip" : "xml";
    String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_m_s"));
    String fileName = "ExportedData_" + getType().getSimpleName() + "_" + currentTime + "." + suffix;
    File file = new File(folder, fileName);
    LOGGER.debug("Creating file '{}'.", file.getAbsolutePath());
    try (Writer writer = createWriter(file)) {
        LOGGER.debug("Exporting objects.");
        dumpHeader(writer);
        dumpObjectsToStream(writer, result);
        dumpFooter(writer);
        LOGGER.debug("Export finished.");
        result.recomputeStatus();
    } catch (Exception ex) {
        LoggingUtils.logUnexpectedException(LOGGER, "Couldn't init download link", ex);
        result.recordFatalError(getPage().createStringResource("PageDebugDownloadBehaviour.message.initFile.fatalError").getString(), ex);
    }
    if (!WebComponentUtil.isSuccessOrHandledError(result)) {
        page.showResult(result);
        page.getSession().error(page.getString("pageDebugList.message.createFileException"));
        LOGGER.debug("Removing file '{}'.", file.getAbsolutePath());
        Files.remove(file);
        throw new RestartResponseException(PageDebugList.class);
    }
    return file;
}
Also used : MidPointApplication(com.evolveum.midpoint.web.security.MidPointApplication) RestartResponseException(org.apache.wicket.RestartResponseException) WebApplicationConfiguration(com.evolveum.midpoint.web.security.WebApplicationConfiguration) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) PageBase(com.evolveum.midpoint.gui.api.page.PageBase) File(org.apache.wicket.util.file.File) AjaxDownloadBehaviorFromFile(com.evolveum.midpoint.web.component.AjaxDownloadBehaviorFromFile) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) RestartResponseException(org.apache.wicket.RestartResponseException) SystemException(com.evolveum.midpoint.util.exception.SystemException)

Example 28 with File

use of org.apache.wicket.util.file.File in project midpoint by Evolveum.

the class AjaxDownloadBehaviorFromFile method onRequest.

public void onRequest() {
    final File file = initFile();
    IResourceStream resourceStream = new FileResourceStream(new File(file));
    getComponent().getRequestCycle().scheduleRequestHandlerAfterCurrent(new ResourceStreamRequestHandler(resourceStream) {

        @Override
        public void respond(IRequestCycle requestCycle) {
            try {
                super.respond(requestCycle);
            } finally {
                if (removeFile) {
                    LOGGER.debug("Removing file '{}'.", file.getAbsolutePath());
                    Files.remove(file);
                }
            }
        }
    }.setFileName(file.getName()).setContentDisposition(ContentDisposition.ATTACHMENT).setCacheDuration(Duration.ofSeconds(1)));
}
Also used : FileResourceStream(org.apache.wicket.util.resource.FileResourceStream) IResourceStream(org.apache.wicket.util.resource.IResourceStream) File(org.apache.wicket.util.file.File) ResourceStreamRequestHandler(org.apache.wicket.request.handler.resource.ResourceStreamRequestHandler) IRequestCycle(org.apache.wicket.request.IRequestCycle)

Aggregations

File (org.apache.wicket.util.file.File)28 Test (org.junit.Test)12 IOException (java.io.IOException)7 FileUpload (org.apache.wicket.markup.html.form.upload.FileUpload)6 AjaxDownloadBehaviorFromFile (com.evolveum.midpoint.web.component.AjaxDownloadBehaviorFromFile)5 MidPointApplication (com.evolveum.midpoint.web.security.MidPointApplication)5 WebApplicationConfiguration (com.evolveum.midpoint.web.security.WebApplicationConfiguration)5 FileInputStream (java.io.FileInputStream)5 MidpointConfiguration (com.evolveum.midpoint.common.configuration.api.MidpointConfiguration)4 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)4 RestartResponseException (org.apache.wicket.RestartResponseException)4 FormTester (org.apache.wicket.util.tester.FormTester)4 CommonException (com.evolveum.midpoint.util.exception.CommonException)3 ObjectNotFoundException (com.evolveum.midpoint.util.exception.ObjectNotFoundException)3 IManageablePage (org.apache.wicket.page.IManageablePage)3 ISerializer (org.apache.wicket.serialize.ISerializer)3 DeflatedJavaSerializer (org.apache.wicket.serialize.java.DeflatedJavaSerializer)3 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)2 FileOutputStream (java.io.FileOutputStream)2 InputStream (java.io.InputStream)2