Search in sources :

Example 1 with IFileItem

use of com.helger.web.fileupload.IFileItem in project phoss-smp by phax.

the class PageSecureServiceGroupImport method fillContent.

@Override
protected void fillContent(@Nonnull final WebPageExecutionContext aWPEC) {
    final HCNodeList aNodeList = aWPEC.getNodeList();
    final Locale aDisplayLocale = aWPEC.getDisplayLocale();
    final ISMPSettings aSettings = SMPMetaManager.getSettings();
    final ISMPServiceGroupManager aServiceGroupMgr = SMPMetaManager.getServiceGroupMgr();
    final ISMPBusinessCardManager aBusinessCardMgr = SMPMetaManager.getBusinessCardMgr();
    final IUserManager aUserMgr = PhotonSecurityManager.getUserMgr();
    final ICommonsSet<String> aAllServiceGroupIDs = aServiceGroupMgr.getAllSMPServiceGroupIDs();
    final ICommonsSet<String> aAllBusinessCardIDs = aBusinessCardMgr.getAllSMPBusinessCardIDs();
    final FormErrorList aFormErrors = new FormErrorList();
    final HCUL aImportResultUL = new HCUL();
    if (aWPEC.hasAction(CPageParam.ACTION_PERFORM)) {
        // Start import
        final IFileItem aImportFile = aWPEC.params().getAsFileItem(FIELD_IMPORT_FILE);
        final boolean bOverwriteExisting = aWPEC.params().isCheckBoxChecked(FIELD_OVERWRITE_EXISTING, DEFAULT_OVERWRITE_EXISTING);
        final String sDefaultOwnerID = aWPEC.params().getAsString(FIELD_DEFAULT_OWNER);
        final IUser aDefaultOwner = aUserMgr.getActiveUserOfID(sDefaultOwnerID);
        if (aImportFile == null || aImportFile.getSize() == 0)
            aFormErrors.addFieldError(FIELD_IMPORT_FILE, "A file to import must be selected!");
        if (StringHelper.hasNoText(sDefaultOwnerID))
            aFormErrors.addFieldError(FIELD_DEFAULT_OWNER, "A default owner must be selected!");
        else if (aDefaultOwner == null)
            aFormErrors.addFieldError(FIELD_DEFAULT_OWNER, "A valid default owner must be selected!");
        if (aFormErrors.isEmpty()) {
            final SAXReaderSettings aSRS = new SAXReaderSettings();
            final IMicroDocument aDoc = MicroReader.readMicroXML(aImportFile, aSRS);
            if (aDoc == null || aDoc.getDocumentElement() == null)
                aFormErrors.addFieldError(FIELD_IMPORT_FILE, "The provided file is not a valid XML file!");
            else {
                // Start interpreting
                final String sVersion = aDoc.getDocumentElement().getAttributeValue(CSMPExchange.ATTR_VERSION);
                if (CSMPExchange.VERSION_10.equals(sVersion)) {
                    // Version 1.0
                    final ICommonsList<ImportActionItem> aActionList = new CommonsArrayList<>();
                    final ImportSummary aImportSummary = new ImportSummary();
                    ServiceGroupImport.importXMLVer10(aDoc.getDocumentElement(), bOverwriteExisting, aDefaultOwner, aAllServiceGroupIDs, aAllBusinessCardIDs, aActionList, aImportSummary);
                    for (final ImportActionItem aAction : aActionList) {
                        final IErrorLevel aErrorLevel = aAction.getErrorLevel();
                        final EBootstrapBadgeType eBadgeType;
                        if (aErrorLevel.isGE(EErrorLevel.ERROR))
                            eBadgeType = EBootstrapBadgeType.DANGER;
                        else if (aErrorLevel.isGE(EErrorLevel.WARN))
                            eBadgeType = EBootstrapBadgeType.WARNING;
                        else if (aErrorLevel.isGE(EErrorLevel.INFO))
                            eBadgeType = EBootstrapBadgeType.INFO;
                        else
                            eBadgeType = EBootstrapBadgeType.SUCCESS;
                        // By default is is centered
                        aImportResultUL.addItem(new BootstrapBadge(eBadgeType).addChild((aAction.hasParticipantID() ? "[" + aAction.getParticipantID() + "] " : "") + aAction.getMessage()).addChild(SMPCommonUI.getTechnicalDetailsUI(aAction.getLinkedException())).addClass(CBootstrapCSS.TEXT_LEFT));
                    }
                } else {
                    // Unsupported or no version present
                    if (sVersion == null)
                        aFormErrors.addFieldError(FIELD_IMPORT_FILE, "The provided file cannot be imported because it has the wrong layout.");
                    else
                        aFormErrors.addFieldError(FIELD_IMPORT_FILE, "The provided file contains the unsupported version '" + sVersion + "'.");
                }
            }
        }
    }
    final boolean bHandleBusinessCards = aSettings.isDirectoryIntegrationEnabled();
    if (aImportResultUL.hasChildren()) {
        final BootstrapCard aPanel = new BootstrapCard();
        aPanel.createAndAddHeader().addChild("Import results");
        aPanel.createAndAddBody().addChild(aImportResultUL);
        aNodeList.addChild(aPanel);
    }
    aNodeList.addChild(info("Import service groups incl. all endpoints" + (bHandleBusinessCards ? " and business cards" : "") + " from a file."));
    final BootstrapForm aForm = aNodeList.addAndReturnChild(getUIHandler().createFormFileUploadSelf(aWPEC));
    aForm.addFormGroup(new BootstrapFormGroup().setLabelMandatory("File to import").setCtrl(new BootstrapFileUpload(FIELD_IMPORT_FILE, aDisplayLocale)).setErrorList(aFormErrors.getListOfField(FIELD_IMPORT_FILE)));
    aForm.addFormGroup(new BootstrapFormGroup().setLabel("Overwrite existing elements").setCtrl(new HCCheckBox(new RequestFieldBoolean(FIELD_OVERWRITE_EXISTING, DEFAULT_OVERWRITE_EXISTING))).setHelpText("If this box is checked, all existing endpoints etc. of a service group are deleted and new endpoints are created! If the " + SMPWebAppConfiguration.getDirectoryName() + " integration is enabled, existing business cards contained in the import are also overwritten!").setErrorList(aFormErrors.getListOfField(FIELD_OVERWRITE_EXISTING)));
    aForm.addFormGroup(new BootstrapFormGroup().setLabelMandatory("Owner of the new service groups").setCtrl(new HCUserSelect(new RequestField(FIELD_DEFAULT_OWNER), aDisplayLocale)).setHelpText("This owner is only selected, if the owner contained in the import file is unknown.").setErrorList(aFormErrors.getListOfField(FIELD_DEFAULT_OWNER)));
    final BootstrapButtonToolbar aToolbar = aForm.addAndReturnChild(getUIHandler().createToolbar(aWPEC));
    aToolbar.addHiddenField(CPageParam.PARAM_ACTION, CPageParam.ACTION_PERFORM);
    aToolbar.addChild(new BootstrapSubmitButton().addChild("Import Service Groups").setIcon(EDefaultIcon.ADD));
}
Also used : Locale(java.util.Locale) ISMPServiceGroupManager(com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroupManager) HCNodeList(com.helger.html.hc.impl.HCNodeList) IUserManager(com.helger.photon.security.user.IUserManager) ImportSummary(com.helger.phoss.smp.exchange.ImportSummary) RequestFieldBoolean(com.helger.photon.core.form.RequestFieldBoolean) FormErrorList(com.helger.photon.core.form.FormErrorList) ImportActionItem(com.helger.phoss.smp.exchange.ImportActionItem) SAXReaderSettings(com.helger.xml.serialize.read.SAXReaderSettings) BootstrapFileUpload(com.helger.photon.bootstrap4.uictrls.ext.BootstrapFileUpload) IFileItem(com.helger.web.fileupload.IFileItem) IUser(com.helger.photon.security.user.IUser) BootstrapButtonToolbar(com.helger.photon.bootstrap4.buttongroup.BootstrapButtonToolbar) RequestField(com.helger.photon.core.form.RequestField) BootstrapCard(com.helger.photon.bootstrap4.card.BootstrapCard) BootstrapBadge(com.helger.photon.bootstrap4.badge.BootstrapBadge) BootstrapForm(com.helger.photon.bootstrap4.form.BootstrapForm) HCUserSelect(com.helger.phoss.smp.ui.secure.hc.HCUserSelect) ISMPBusinessCardManager(com.helger.phoss.smp.domain.businesscard.ISMPBusinessCardManager) HCUL(com.helger.html.hc.html.grouping.HCUL) ISMPSettings(com.helger.phoss.smp.settings.ISMPSettings) EBootstrapBadgeType(com.helger.photon.bootstrap4.badge.EBootstrapBadgeType) IErrorLevel(com.helger.commons.error.level.IErrorLevel) IMicroDocument(com.helger.xml.microdom.IMicroDocument) HCCheckBox(com.helger.html.hc.html.forms.HCCheckBox) BootstrapSubmitButton(com.helger.photon.bootstrap4.button.BootstrapSubmitButton) BootstrapFormGroup(com.helger.photon.bootstrap4.form.BootstrapFormGroup) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList)

Example 2 with IFileItem

use of com.helger.web.fileupload.IFileItem in project ph-web by phax.

the class AbstractFileUploadTestCase method parseUpload.

protected final ICommonsList<IFileItem> parseUpload(final byte[] bytes, final String contentType) throws FileUploadException {
    final ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory(10240));
    final HttpServletRequest request = new MockHttpServletRequest().setContent(bytes).setContentType(contentType);
    final ICommonsList<IFileItem> fileItems = upload.parseRequest(request);
    return fileItems;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) MockHttpServletRequest(com.helger.servlet.mock.MockHttpServletRequest) ServletFileUpload(com.helger.web.fileupload.servlet.ServletFileUpload) MockHttpServletRequest(com.helger.servlet.mock.MockHttpServletRequest) IFileItem(com.helger.web.fileupload.IFileItem)

Example 3 with IFileItem

use of com.helger.web.fileupload.IFileItem in project ph-web by phax.

the class DiskFileItemTest method testAboveThreshold.

/**
 * Test creation of a field for which the amount of data falls above the
 * configured threshold.
 */
@Test
public void testAboveThreshold() {
    // Create the FileItem
    final byte[] testFieldValueBytes = _createContentBytes(THRESHOLD + 1);
    final IFileItem item = _createFileItem(testFieldValueBytes);
    // Check state is as expected
    assertFalse("Initial: in memory", item.isInMemory());
    assertEquals("Initial: size", item.getSize(), testFieldValueBytes.length);
    _compareBytes("Initial", item.directGet(), testFieldValueBytes);
    // Serialize & Deserialize
    if (false)
        try {
            final IFileItem newItem = (IFileItem) _serializeDeserialize(item);
            // Test deserialized content is as expected
            assertFalse("Check in memory", newItem.isInMemory());
            _compareBytes("Check", testFieldValueBytes, newItem.directGet());
            // Compare FileItem's (except byte[])
            _compareFileItems(item, newItem);
        } catch (final Exception e) {
            fail("Error Serializing/Deserializing: " + e);
        }
}
Also used : IFileItem(com.helger.web.fileupload.IFileItem) IOException(java.io.IOException) Test(org.junit.Test)

Example 4 with IFileItem

use of com.helger.web.fileupload.IFileItem in project ph-web by phax.

the class DiskFileItemTest method testThreshold.

/**
 * Test creation of a field for which the amount of data equals the configured
 * threshold.
 */
@Test
public void testThreshold() {
    // Create the FileItem
    final byte[] testFieldValueBytes = _createContentBytes(THRESHOLD);
    final IFileItem item = _createFileItem(testFieldValueBytes);
    // Check state is as expected
    assertTrue("Initial: in memory", item.isInMemory());
    assertEquals("Initial: size", item.getSize(), testFieldValueBytes.length);
    _compareBytes("Initial", item.directGet(), testFieldValueBytes);
    // Serialize & Deserialize
    if (false)
        try {
            final IFileItem newItem = (IFileItem) _serializeDeserialize(item);
            // Test deserialized content is as expected
            assertTrue("Check in memory", newItem.isInMemory());
            _compareBytes("Check", testFieldValueBytes, newItem.directGet());
            // Compare FileItem's (except byte[])
            _compareFileItems(item, newItem);
        } catch (final Exception e) {
            fail("Error Serializing/Deserializing: " + e);
        }
}
Also used : IFileItem(com.helger.web.fileupload.IFileItem) IOException(java.io.IOException) Test(org.junit.Test)

Example 5 with IFileItem

use of com.helger.web.fileupload.IFileItem in project ph-web by phax.

the class ServletFileUploadTest method testFilenameCaseSensitivity.

@Test
public void testFilenameCaseSensitivity() throws FileUploadException {
    final List<IFileItem> fileItems = parseUpload("-----1234\r\n" + "Content-Disposition: form-data; name=\"FiLe\"; filename=\"FOO.tab\"\r\n" + "Content-Type: text/whatever\r\n" + "\r\n" + "This is the content of the file\n" + "\r\n" + "-----1234--\r\n");
    assertEquals(1, fileItems.size());
    final IFileItem file = fileItems.get(0);
    assertEquals("FiLe", file.getFieldName());
    assertEquals("FOO.tab", file.getName());
}
Also used : IFileItem(com.helger.web.fileupload.IFileItem) Test(org.junit.Test)

Aggregations

IFileItem (com.helger.web.fileupload.IFileItem)17 Test (org.junit.Test)11 IOException (java.io.IOException)5 CommonsArrayList (com.helger.commons.collection.impl.CommonsArrayList)4 MockHttpServletRequest (com.helger.servlet.mock.MockHttpServletRequest)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 NonBlockingByteArrayOutputStream (com.helger.commons.io.stream.NonBlockingByteArrayOutputStream)2 HCUL (com.helger.html.hc.html.grouping.HCUL)2 HCNodeList (com.helger.html.hc.impl.HCNodeList)2 BootstrapButtonToolbar (com.helger.photon.bootstrap4.buttongroup.BootstrapButtonToolbar)2 BootstrapForm (com.helger.photon.bootstrap4.form.BootstrapForm)2 BootstrapFormGroup (com.helger.photon.bootstrap4.form.BootstrapFormGroup)2 BootstrapFileUpload (com.helger.photon.bootstrap4.uictrls.ext.BootstrapFileUpload)2 FormErrorList (com.helger.photon.core.form.FormErrorList)2 IFileItemFactory (com.helger.web.fileupload.IFileItemFactory)2 FileUploadException (com.helger.web.fileupload.exception.FileUploadException)2 OutputStream (java.io.OutputStream)2 Nonnull (javax.annotation.Nonnull)2 CGlobal (com.helger.commons.CGlobal)1 ReturnsMutableCopy (com.helger.commons.annotation.ReturnsMutableCopy)1