Search in sources :

Example 16 with IFileItem

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

the class ServletFileUploadTest method testEmptyFile.

/**
 * This is what the browser does if you submit the form without choosing a
 * file.
 *
 * @throws FileUploadException
 *         In case of error
 */
@Test
public void testEmptyFile() throws FileUploadException {
    final List<IFileItem> fileItems = parseUpload("-----1234\r\n" + "Content-Disposition: form-data; name=\"file\"; filename=\"\"\r\n" + "\r\n" + "\r\n" + "-----1234--\r\n");
    assertEquals(1, fileItems.size());
    final IFileItem file = fileItems.get(0);
    assertFalse(file.isFormField());
    assertEquals("", file.getString());
    assertEquals("", file.getName());
}
Also used : IFileItem(com.helger.web.fileupload.IFileItem) Test(org.junit.Test)

Example 17 with IFileItem

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

the class SizesFuncTest method testFileSizeLimit.

/**
 * Checks, whether limiting the file size works.
 *
 * @throws FileUploadException
 *         In case of error
 */
@Test
public void testFileSizeLimit() throws FileUploadException {
    final String request = "-----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";
    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory(10240));
    upload.setFileSizeMax(-1);
    HttpServletRequest req = new MockHttpServletRequest().setContent(request.getBytes(StandardCharsets.US_ASCII)).setContentType(CONTENT_TYPE);
    List<IFileItem> fileItems = upload.parseRequest(req);
    assertEquals(1, fileItems.size());
    IFileItem item = fileItems.get(0);
    assertEquals("This is the content of the file\n", new String(item.directGet(), StandardCharsets.US_ASCII));
    upload = new ServletFileUpload(new DiskFileItemFactory(10240));
    upload.setFileSizeMax(40);
    req = new MockHttpServletRequest().setContent(request.getBytes(StandardCharsets.US_ASCII)).setContentType(CONTENT_TYPE);
    fileItems = upload.parseRequest(req);
    assertEquals(1, fileItems.size());
    item = fileItems.get(0);
    assertEquals("This is the content of the file\n", new String(item.directGet(), StandardCharsets.US_ASCII));
    upload = new ServletFileUpload(new DiskFileItemFactory(10240));
    upload.setFileSizeMax(30);
    req = new MockHttpServletRequest().setContent(request.getBytes(StandardCharsets.US_ASCII)).setContentType(CONTENT_TYPE);
    try {
        upload.parseRequest(req);
        fail("Expected exception.");
    } catch (final FileSizeLimitExceededException e) {
        assertEquals(30, e.getPermittedSize());
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) MockHttpServletRequest(com.helger.servlet.mock.MockHttpServletRequest) MockHttpServletRequest(com.helger.servlet.mock.MockHttpServletRequest) FileSizeLimitExceededException(com.helger.web.fileupload.exception.FileSizeLimitExceededException) IFileItem(com.helger.web.fileupload.IFileItem) DiskFileItemFactory(com.helger.web.fileupload.parse.DiskFileItemFactory) Test(org.junit.Test)

Example 18 with IFileItem

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

the class SizesFuncTest method testFileUpload.

/**
 * Runs a test with varying file sizes.
 *
 * @throws IOException
 *         In case of error
 * @throws FileUploadException
 *         In case of error
 */
@Test
public void testFileUpload() throws IOException, FileUploadException {
    try (final NonBlockingByteArrayOutputStream baos = new NonBlockingByteArrayOutputStream()) {
        int add = 16;
        int num = 0;
        for (int i = 0; i < 16384; i += add) {
            if (++add == 32) {
                add = 16;
            }
            final String header = "-----1234\r\n" + "Content-Disposition: form-data; name=\"field" + (num++) + "\"\r\n" + "\r\n";
            baos.write(header.getBytes(StandardCharsets.US_ASCII));
            for (int j = 0; j < i; j++) {
                baos.write((byte) j);
            }
            baos.write("\r\n".getBytes(StandardCharsets.US_ASCII));
        }
        baos.write("-----1234--\r\n".getBytes(StandardCharsets.US_ASCII));
        final ICommonsList<IFileItem> fileItems = parseUpload(baos.toByteArray());
        final Iterator<IFileItem> fileIter = fileItems.iterator();
        add = 16;
        num = 0;
        for (int i = 0; i < 16384; i += add) {
            if (++add == 32) {
                add = 16;
            }
            final IFileItem item = fileIter.next();
            assertEquals("field" + (num++), item.getFieldName());
            final byte[] bytes = item.directGet();
            assertEquals(i, bytes.length);
            for (int j = 0; j < i; j++) {
                assertEquals((byte) j, bytes[j]);
            }
        }
        assertFalse(fileIter.hasNext());
    }
}
Also used : NonBlockingByteArrayOutputStream(com.helger.commons.io.stream.NonBlockingByteArrayOutputStream) IFileItem(com.helger.web.fileupload.IFileItem) Test(org.junit.Test)

Example 19 with IFileItem

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

the class RequestMultipartHelper method handleMultipartFormData.

/**
 * Parse the provided servlet request as multipart, if the Content-Type starts
 * with <code>multipart/form-data</code>.
 *
 * @param aHttpRequest
 *        Source HTTP request from which multipart/form-data (aka file
 *        uploads) should be extracted.
 * @param aConsumer
 *        A consumer that takes either {@link IFileItem} or
 *        {@link IFileItem}[] or {@link String} or {@link String}[].
 * @return {@link EChange#CHANGED} if something was added
 */
@Nonnull
public static EChange handleMultipartFormData(@Nonnull final HttpServletRequest aHttpRequest, @Nonnull final BiConsumer<String, Object> aConsumer) {
    if (aHttpRequest instanceof MockHttpServletRequest) {
        // UnsupportedOperationExceptions
        return EChange.UNCHANGED;
    }
    if (!RequestHelper.isMultipartFormDataContent(aHttpRequest)) {
        // It's not a multipart request
        return EChange.UNCHANGED;
    }
    // It is a multipart request!
    // Note: this handles only POST parameters!
    boolean bAddedFileUploadItems = false;
    try {
        // Setup the ServletFileUpload....
        final ServletFileUpload aUpload = new ServletFileUpload(PROVIDER.getFileItemFactory());
        aUpload.setSizeMax(MAX_REQUEST_SIZE);
        aUpload.setHeaderEncoding(CWeb.CHARSET_REQUEST_OBJ.name());
        final IProgressListener aProgressListener = ProgressListenerProvider.getProgressListener();
        if (aProgressListener != null)
            aUpload.setProgressListener(aProgressListener);
        ServletHelper.setRequestCharacterEncoding(aHttpRequest, CWeb.CHARSET_REQUEST_OBJ);
        // Group all items with the same name together
        final ICommonsMap<String, ICommonsList<String>> aFormFields = new CommonsHashMap<>();
        final ICommonsMap<String, ICommonsList<IFileItem>> aFormFiles = new CommonsHashMap<>();
        final ICommonsList<IFileItem> aFileItems = aUpload.parseRequest(aHttpRequest);
        for (final IFileItem aFileItem : aFileItems) {
            if (aFileItem.isFormField()) {
                // We need to explicitly use the charset, as by default only the
                // charset from the content type is used!
                aFormFields.computeIfAbsent(aFileItem.getFieldName(), k -> new CommonsArrayList<>()).add(aFileItem.getString(CWeb.CHARSET_REQUEST_OBJ));
            } else
                aFormFiles.computeIfAbsent(aFileItem.getFieldName(), k -> new CommonsArrayList<>()).add(aFileItem);
        }
        // set all form fields
        for (final Map.Entry<String, ICommonsList<String>> aEntry : aFormFields.entrySet()) {
            // Convert list of String to value (String or String[])
            final ICommonsList<String> aValues = aEntry.getValue();
            final Object aValue = aValues.size() == 1 ? aValues.getFirst() : ArrayHelper.newArray(aValues, String.class);
            aConsumer.accept(aEntry.getKey(), aValue);
        }
        // name)
        for (final Map.Entry<String, ICommonsList<IFileItem>> aEntry : aFormFiles.entrySet()) {
            // Convert list of String to value (IFileItem or IFileItem[])
            final ICommonsList<IFileItem> aValues = aEntry.getValue();
            final Object aValue = aValues.size() == 1 ? aValues.getFirst() : ArrayHelper.newArray(aValues, IFileItem.class);
            aConsumer.accept(aEntry.getKey(), aValue);
        }
        // Parsing complex file upload succeeded -> do not use standard scan for
        // parameters
        bAddedFileUploadItems = true;
    } catch (final FileUploadException ex) {
        if (!StreamHelper.isKnownEOFException(ex.getCause()))
            LOGGER.error("Error parsing multipart request content", ex);
    } catch (final RuntimeException ex) {
        LOGGER.error("Error parsing multipart request content", ex);
    }
    return EChange.valueOf(bAddedFileUploadItems);
}
Also used : StreamHelper(com.helger.commons.io.stream.StreamHelper) ServletHelper(com.helger.servlet.ServletHelper) IFileItemFactoryProviderSPI(com.helger.web.fileupload.IFileItemFactoryProviderSPI) LoggerFactory(org.slf4j.LoggerFactory) ProgressListenerProvider(com.helger.web.progress.ProgressListenerProvider) EChange(com.helger.commons.state.EChange) RequestHelper(com.helger.servlet.request.RequestHelper) HttpServletRequest(javax.servlet.http.HttpServletRequest) FileUploadException(com.helger.web.fileupload.exception.FileUploadException) CWeb(com.helger.web.CWeb) IProgressListener(com.helger.web.progress.IProgressListener) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) Nonnull(javax.annotation.Nonnull) ServletFileUpload(com.helger.web.fileupload.servlet.ServletFileUpload) ArrayHelper(com.helger.commons.collection.ArrayHelper) CGlobal(com.helger.commons.CGlobal) Logger(org.slf4j.Logger) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) IFileItem(com.helger.web.fileupload.IFileItem) CommonsHashMap(com.helger.commons.collection.impl.CommonsHashMap) ICommonsList(com.helger.commons.collection.impl.ICommonsList) ServiceLoaderHelper(com.helger.commons.lang.ServiceLoaderHelper) MockHttpServletRequest(com.helger.servlet.mock.MockHttpServletRequest) ICommonsMap(com.helger.commons.collection.impl.ICommonsMap) ICommonsList(com.helger.commons.collection.impl.ICommonsList) MockHttpServletRequest(com.helger.servlet.mock.MockHttpServletRequest) IProgressListener(com.helger.web.progress.IProgressListener) ServletFileUpload(com.helger.web.fileupload.servlet.ServletFileUpload) CommonsHashMap(com.helger.commons.collection.impl.CommonsHashMap) IFileItem(com.helger.web.fileupload.IFileItem) Map(java.util.Map) CommonsHashMap(com.helger.commons.collection.impl.CommonsHashMap) ICommonsMap(com.helger.commons.collection.impl.ICommonsMap) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) FileUploadException(com.helger.web.fileupload.exception.FileUploadException) Nonnull(javax.annotation.Nonnull)

Example 20 with IFileItem

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

the class PagePublicToolsSMPSML method _deleteSMPfromSML.

private void _deleteSMPfromSML(@Nonnull final WebPageExecutionContext aWPEC, @Nonnull final FormErrorList aFormErrors) {
    final HCNodeList aNodeList = aWPEC.getNodeList();
    final Locale aDisplayLocale = aWPEC.getDisplayLocale();
    final ISMLConfigurationManager aSMLConfigurationMgr = PPMetaManager.getSMLConfigurationMgr();
    final String sSMLID = aWPEC.params().getAsString(FIELD_SML_ID);
    final ISMLConfiguration aSMLInfo = aSMLConfigurationMgr.getSMLInfoOfID(sSMLID);
    final String sSMPID = aWPEC.params().getAsString(FIELD_SMP_ID);
    final IFileItem aKeyStoreFile = aWPEC.params().getAsFileItem(FIELD_KEYSTORE);
    final String sKeyStorePassword = aWPEC.params().getAsString(FIELD_KEYSTORE_PW);
    if (aSMLInfo == null)
        aFormErrors.addFieldError(FIELD_SML_ID, "A valid SML must be selected!");
    if (StringHelper.hasNoText(sSMPID))
        aFormErrors.addFieldError(FIELD_SMP_ID, "A non-empty SMP ID must be provided!");
    else if (!RegExHelper.stringMatchesPattern(CPPApp.PATTERN_SMP_ID, sSMPID))
        aFormErrors.addFieldError(FIELD_SMP_ID, "The provided SMP ID contains invalid characters. It must match the following regular expression: " + CPPApp.PATTERN_SMP_ID);
    final SSLSocketFactory aSocketFactory = _loadKeyStoreAndCreateSSLSocketFactory(EKeyStoreType.JKS, SECURITY_PROVIDER, aKeyStoreFile, sKeyStorePassword, aFormErrors, aDisplayLocale);
    if (aFormErrors.isEmpty()) {
        try {
            final ManageServiceMetadataServiceCaller aCaller = _create(aSMLInfo.getSMLInfo(), aSocketFactory);
            aCaller.delete(sSMPID);
            final String sMsg = "Successfully deleted SMP '" + sSMPID + "' from the SML '" + aSMLInfo.getManagementServiceURL() + "'.";
            LOGGER.info(sMsg);
            aNodeList.addChild(success(sMsg));
            AuditHelper.onAuditExecuteSuccess("smp-sml-delete", sSMPID, aSMLInfo.getManagementServiceURL());
        } catch (final Exception ex) {
            final String sMsg = "Error deleting SMP '" + sSMPID + "' from the SML '" + aSMLInfo.getManagementServiceURL() + "'.";
            aNodeList.addChild(error(sMsg).addChild(AppCommonUI.getTechnicalDetailsUI(ex, true)));
            AuditHelper.onAuditExecuteFailure("smp-sml-delete", sSMPID, aSMLInfo.getManagementServiceURL(), ex.getClass(), ex.getMessage());
        }
    } else
        aNodeList.addChild(BootstrapWebPageUIHandler.INSTANCE.createIncorrectInputBox(aWPEC));
}
Also used : Locale(java.util.Locale) ISMLConfigurationManager(com.helger.peppol.app.mgr.ISMLConfigurationManager) HCNodeList(com.helger.html.hc.impl.HCNodeList) ManageServiceMetadataServiceCaller(com.helger.peppol.smlclient.ManageServiceMetadataServiceCaller) ISMLConfiguration(com.helger.peppol.domain.ISMLConfiguration) IFileItem(com.helger.web.fileupload.IFileItem) PDTToString(com.helger.commons.datetime.PDTToString) PDTFromString(com.helger.commons.datetime.PDTFromString) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) CertificateExpiredException(java.security.cert.CertificateExpiredException) ClientTransportException(com.sun.xml.ws.client.ClientTransportException) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) UnknownHostException(java.net.UnknownHostException)

Aggregations

IFileItem (com.helger.web.fileupload.IFileItem)21 Test (org.junit.Test)11 HCNodeList (com.helger.html.hc.impl.HCNodeList)6 Locale (java.util.Locale)6 IOException (java.io.IOException)5 CommonsArrayList (com.helger.commons.collection.impl.CommonsArrayList)4 PDTFromString (com.helger.commons.datetime.PDTFromString)4 PDTToString (com.helger.commons.datetime.PDTToString)4 ISMLConfigurationManager (com.helger.peppol.app.mgr.ISMLConfigurationManager)4 ISMLConfiguration (com.helger.peppol.domain.ISMLConfiguration)4 ClientTransportException (com.sun.xml.ws.client.ClientTransportException)4 UnknownHostException (java.net.UnknownHostException)4 CertificateExpiredException (java.security.cert.CertificateExpiredException)4 CertificateNotYetValidException (java.security.cert.CertificateNotYetValidException)4 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)4 ManageServiceMetadataServiceCaller (com.helger.peppol.smlclient.ManageServiceMetadataServiceCaller)3 NonBlockingByteArrayOutputStream (com.helger.commons.io.stream.NonBlockingByteArrayOutputStream)2 SimpleURL (com.helger.commons.url.SimpleURL)2 HCUL (com.helger.html.hc.html.grouping.HCUL)2 MockHttpServletRequest (com.helger.servlet.mock.MockHttpServletRequest)2