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();
}
}
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));
}
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());
}
}
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);
}
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);
}
Aggregations