Search in sources :

Example 11 with MockHttpServletRequest

use of com.helger.servlet.mock.MockHttpServletRequest in project phoss-smp by phax.

the class MainCreate1MillionEndpoints method main.

public static void main(final String[] args) throws Throwable {
    final SMPServerRESTTestRule aRule = new SMPServerRESTTestRule(ClassPathResource.getAsFile("test-smp-server-mongodb.properties").getAbsolutePath());
    aRule.before();
    try {
        // Set the special PhotonSecurityManager factory
        PhotonSecurityManager.setFactory(new PhotonSecurityManagerFactoryMongoDB());
        final ObjectFactory aObjFactory = new ObjectFactory();
        final PeppolDocumentTypeIdentifier aDT = EPredefinedDocumentTypeIdentifier.INVOICE_EN16931_PEPPOL_V30.getAsDocumentTypeIdentifier();
        final String sDT = aDT.getURIEncoded();
        final PeppolProcessIdentifier aProcID = EPredefinedProcessIdentifier.BIS3_BILLING.getAsProcessIdentifier();
        final StopWatch aSWOverall = StopWatch.createdStarted();
        for (int i = 639276; i < 1_000_000; ++i) {
            final StopWatch aSW = StopWatch.createdStarted();
            final PeppolParticipantIdentifier aPI = PeppolIdentifierFactory.INSTANCE.createParticipantIdentifierWithDefaultScheme("9999:test-philip-" + StringHelper.getLeadingZero(i, 7));
            final String sPI = aPI.getURIEncoded();
            final ServiceMetadataType aSM = new ServiceMetadataType();
            final ServiceInformationType aSI = new ServiceInformationType();
            aSI.setParticipantIdentifier(new SimpleParticipantIdentifier(aPI));
            aSI.setDocumentIdentifier(aDT);
            {
                final ProcessListType aPL = new ProcessListType();
                final ProcessType aProcess = new ProcessType();
                aProcess.setProcessIdentifier(aProcID);
                final ServiceEndpointList aSEL = new ServiceEndpointList();
                final EndpointType aEndpoint = new EndpointType();
                aEndpoint.setEndpointReference(W3CEndpointReferenceHelper.createEndpointReference("http://test.smpserver/as2"));
                aEndpoint.setRequireBusinessLevelSignature(false);
                aEndpoint.setCertificate("blacert");
                aEndpoint.setServiceDescription("Unit test service");
                aEndpoint.setTechnicalContactUrl("https://github.com/phax/phoss-smp");
                aEndpoint.setTransportProfile(ESMPTransportProfile.TRANSPORT_PROFILE_AS2.getID());
                aSEL.addEndpoint(aEndpoint);
                aProcess.setServiceEndpointList(aSEL);
                aPL.addProcess(aProcess);
                aSI.setProcessList(aPL);
            }
            aSM.setServiceInformation(aSI);
            try (final WebScoped aWS = new WebScoped(new MockHttpServletRequest())) {
                // Delete old - don't care about the result
                if (false)
                    ClientBuilder.newClient().target(aRule.getFullURL()).path(sPI).path("services").path(sDT).request().header(CHttpHeader.AUTHORIZATION, CREDENTIALS.getRequestValue()).delete();
                // Create a new
                final Response aResponseMsg = ClientBuilder.newClient().target(aRule.getFullURL()).path(sPI).path("services").path(sDT).request().header(CHttpHeader.AUTHORIZATION, CREDENTIALS.getRequestValue()).put(Entity.xml(aObjFactory.createServiceMetadata(aSM)));
                _testResponseJerseyClient(aResponseMsg, 200);
            }
            aSW.stop();
            LOGGER.info(sPI + " took " + aSW.getMillis() + " ms");
        }
        aSWOverall.stop();
        LOGGER.info("Overall process took " + aSWOverall.getMillis() + " ms or " + aSWOverall.getDuration());
    } finally {
        aRule.after();
    }
}
Also used : WebScoped(com.helger.web.scope.mgr.WebScoped) PhotonSecurityManagerFactoryMongoDB(com.helger.phoss.smp.backend.mongodb.PhotonSecurityManagerFactoryMongoDB) MockHttpServletRequest(com.helger.servlet.mock.MockHttpServletRequest) PeppolProcessIdentifier(com.helger.peppolid.peppol.process.PeppolProcessIdentifier) ServiceInformationType(com.helger.xsds.peppol.smp1.ServiceInformationType) SimpleParticipantIdentifier(com.helger.peppolid.simple.participant.SimpleParticipantIdentifier) SMPServerRESTTestRule(com.helger.phoss.smp.mock.SMPServerRESTTestRule) StopWatch(com.helger.commons.timing.StopWatch) PeppolParticipantIdentifier(com.helger.peppolid.peppol.participant.PeppolParticipantIdentifier) Response(javax.ws.rs.core.Response) ProcessType(com.helger.xsds.peppol.smp1.ProcessType) ObjectFactory(com.helger.xsds.peppol.smp1.ObjectFactory) PeppolDocumentTypeIdentifier(com.helger.peppolid.peppol.doctype.PeppolDocumentTypeIdentifier) EndpointType(com.helger.xsds.peppol.smp1.EndpointType) ProcessListType(com.helger.xsds.peppol.smp1.ProcessListType) ServiceMetadataType(com.helger.xsds.peppol.smp1.ServiceMetadataType) ServiceEndpointList(com.helger.xsds.peppol.smp1.ServiceEndpointList)

Example 12 with MockHttpServletRequest

use of com.helger.servlet.mock.MockHttpServletRequest in project ph-web by phax.

the class UnifiedResponseTest method testSetAllowMimeSniffing.

@Test
public void testSetAllowMimeSniffing() {
    final UnifiedResponse aResponse = UnifiedResponse.createSimple(new MockHttpServletRequest());
    assertTrue(aResponse.responseHeaderMap().containsHeaders(CHttpHeader.X_CONTENT_TYPE_OPTIONS));
    aResponse.setAllowMimeSniffing(true);
    assertFalse(aResponse.responseHeaderMap().containsHeaders(CHttpHeader.X_CONTENT_TYPE_OPTIONS));
    aResponse.setAllowMimeSniffing(false);
    assertTrue(aResponse.responseHeaderMap().containsHeaders(CHttpHeader.X_CONTENT_TYPE_OPTIONS));
    final ICommonsList<String> aValues = aResponse.responseHeaderMap().getAllHeaderValues(CHttpHeader.X_CONTENT_TYPE_OPTIONS);
    assertEquals(1, aValues.size());
    assertEquals(CHttpHeader.VALUE_NOSNIFF, aValues.get(0));
}
Also used : MockHttpServletRequest(com.helger.servlet.mock.MockHttpServletRequest) Test(org.junit.Test)

Example 13 with MockHttpServletRequest

use of com.helger.servlet.mock.MockHttpServletRequest 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 14 with MockHttpServletRequest

use of com.helger.servlet.mock.MockHttpServletRequest 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 15 with MockHttpServletRequest

use of com.helger.servlet.mock.MockHttpServletRequest in project ph-web by phax.

the class AbstractScopeAwareJob method beforeExecute.

@Override
@OverrideOnDemand
@OverridingMethodsMustInvokeSuper
protected void beforeExecute(@Nonnull final JobDataMap aJobDataMap, @Nonnull final IJobExecutionContext aContext) {
    // Scopes (ensure to create a new scope each time!)
    final MockHttpServletRequest aHttpRequest = createMockHttpServletRequest();
    final MockHttpServletResponse aHttpResponse = createMockHttpServletResponse();
    WebScopeManager.onRequestBegin(aHttpRequest, aHttpResponse);
    // Invoke callback
    beforeExecuteInScope(aJobDataMap, aContext);
}
Also used : MockHttpServletRequest(com.helger.servlet.mock.MockHttpServletRequest) MockHttpServletResponse(com.helger.servlet.mock.MockHttpServletResponse) OverridingMethodsMustInvokeSuper(javax.annotation.OverridingMethodsMustInvokeSuper) OverrideOnDemand(com.helger.commons.annotation.OverrideOnDemand)

Aggregations

MockHttpServletRequest (com.helger.servlet.mock.MockHttpServletRequest)20 Test (org.junit.Test)10 StopWatch (com.helger.commons.timing.StopWatch)6 WebScoped (com.helger.web.scope.mgr.WebScoped)6 PeppolParticipantIdentifier (com.helger.peppolid.peppol.participant.PeppolParticipantIdentifier)5 HttpServletRequest (javax.servlet.http.HttpServletRequest)5 Response (javax.ws.rs.core.Response)5 ServletFileUpload (com.helger.web.fileupload.servlet.ServletFileUpload)4 ObjectFactory (com.helger.xsds.peppol.smp1.ObjectFactory)4 PeppolDocumentTypeIdentifier (com.helger.peppolid.peppol.doctype.PeppolDocumentTypeIdentifier)3 PeppolProcessIdentifier (com.helger.peppolid.peppol.process.PeppolProcessIdentifier)3 SimpleParticipantIdentifier (com.helger.peppolid.simple.participant.SimpleParticipantIdentifier)3 IFileItem (com.helger.web.fileupload.IFileItem)3 DiskFileItemFactory (com.helger.web.fileupload.parse.DiskFileItemFactory)3 WebScopeTestRule (com.helger.web.scope.mock.WebScopeTestRule)3 ICommonsList (com.helger.commons.collection.impl.ICommonsList)2 PhotonSecurityManagerFactoryMongoDB (com.helger.phoss.smp.backend.mongodb.PhotonSecurityManagerFactoryMongoDB)2 SMPServerRESTTestRule (com.helger.phoss.smp.mock.SMPServerRESTTestRule)2 MockHttpServletResponse (com.helger.servlet.mock.MockHttpServletResponse)2 MockServletContext (com.helger.servlet.mock.MockServletContext)2