use of com.helger.web.scope.mgr.WebScoped 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.web.scope.mgr.WebScoped in project phase4 by phax.
the class MainPhase4CEFSenderToop method main.
public static void main(final String[] args) {
WebScopeManager.onGlobalBegin(MockServletContext.create());
// Dump (for debugging purpose only)
AS4DumpManager.setIncomingDumper(new AS4IncomingDumperFileBased());
AS4DumpManager.setOutgoingDumper(new AS4OutgoingDumperFileBased());
try (final WebScoped w = new WebScoped()) {
final byte[] aPayloadBytes = SimpleFileIO.getAllFileBytes(new File("src/test/resources/examples/base-example.xml"));
if (aPayloadBytes == null)
throw new IllegalStateException();
// Start configuring here
final IParticipantIdentifier aReceiverID = Phase4CEFSender.IF.createParticipantIdentifier("iso6523-actorid-upis", "9915:tooptest");
final IAS4ClientBuildMessageCallback aBuildMessageCallback = new IAS4ClientBuildMessageCallback() {
public void onAS4Message(final AbstractAS4Message<?> aMsg) {
final AS4UserMessage aUserMsg = (AS4UserMessage) aMsg;
LOGGER.info("Sending out AS4 message with message ID '" + aUserMsg.getEbms3UserMessage().getMessageInfo().getMessageId() + "'");
LOGGER.info("Sending out AS4 message with conversation ID '" + aUserMsg.getEbms3UserMessage().getCollaborationInfo().getConversationId() + "'");
}
};
if (Phase4CEFSender.builder().documentTypeID(Phase4CEFSender.IF.createDocumentTypeIdentifier("toop-doctypeid-qns", "urn:eu:toop:ns:dataexchange-1p40::Response##urn:eu.toop.response.registeredorganization::1.40")).processID(Phase4CEFSender.IF.createProcessIdentifier("toop-procid-agreement", "urn:eu.toop.process.datarequestresponse")).senderParticipantID(Phase4CEFSender.IF.createParticipantIdentifier("iso6523-actorid-upis", "9914:phase4-test-sender")).receiverParticipantID(aReceiverID).fromPartyID(new SimpleParticipantIdentifier("type", "POP000306")).fromRole("http://www.toop.eu/edelivery/gateway").toPartyID(new SimpleParticipantIdentifier("type", "POP000306")).toRole("http://www.toop.eu/edelivery/gateway").payload(Phase4OutgoingAttachment.builder().data(aPayloadBytes).mimeTypeXML()).smpClient(new BDXRClientReadOnly(Phase4CEFSender.URL_PROVIDER, aReceiverID, SML_TOOP)).rawResponseConsumer(new AS4RawResponseConsumerWriteToFile()).buildMessageCallback(aBuildMessageCallback).sendMessage().isSuccess()) {
LOGGER.info("Successfully sent CEF message via AS4");
} else {
LOGGER.error("Failed to send CEF message via AS4");
}
} catch (final Exception ex) {
LOGGER.error("Error sending CEF message via AS4", ex);
} finally {
WebScopeManager.onGlobalEnd();
}
}
use of com.helger.web.scope.mgr.WebScoped in project ph-web by phax.
the class XServletAsyncHandler method _handleAsync.
private void _handleAsync(@Nonnull final HttpServletRequest aHttpRequest, @Nonnull final HttpServletResponse aHttpResponse, @Nonnull final EHttpVersion eHttpVersion, @Nonnull final EHttpMethod eHttpMethod, @Nonnull final IRequestWebScope aRequestScope) {
final ExtAsyncContext aExtAsyncCtx = ExtAsyncContext.create(aHttpRequest, aHttpResponse, eHttpVersion, eHttpMethod, m_aAsyncSpec);
// Remember outside before it is too late :)
final IAttributeContainerAny<String> aAttrs = aRequestScope.attrs().getClone();
final IAttributeContainerAny<String> aParams = aRequestScope.params().getClone();
// Put into async processing queue
s_aAsyncServletRunner.runAsync(aHttpRequest, aHttpResponse, aExtAsyncCtx, () -> {
try (final WebScoped aWebScoped = new WebScoped(aHttpRequest, aHttpResponse)) {
// Restore all attributes (display locale etc.) that are missing
aWebScoped.getRequestScope().attrs().putAllIn(aAttrs);
aWebScoped.getRequestScope().params().putAllIn(aParams);
m_aNestedHandler.onRequest(aExtAsyncCtx.getRequest(), aExtAsyncCtx.getResponse(), aExtAsyncCtx.getHTTPVersion(), aExtAsyncCtx.getHTTPMethod(), aWebScoped.getRequestScope());
} catch (final Exception ex) {
if (LOGGER.isErrorEnabled())
LOGGER.error("Error processing async request " + aExtAsyncCtx.getRequest(), ex);
try {
final String sErrorMsg = "Internal error processing your request. Please try again later. Technical details: " + ex.getClass().getName() + ":" + ex.getMessage();
aExtAsyncCtx.getResponse().getWriter().write(sErrorMsg);
} catch (final Exception ex2) {
LOGGER.error("Error writing first exception to response", ex2);
}
} finally {
try {
aExtAsyncCtx.complete();
} catch (final Exception ex) {
LOGGER.error("Error completing async context", ex);
}
}
});
}
use of com.helger.web.scope.mgr.WebScoped in project phase4 by phax.
the class MainCEFeInvoicingConnectivityTest method main.
public static void main(final String[] args) {
WebScopeManager.onGlobalBegin(MockServletContext.create());
// Dump (for debugging purpose only)
AS4DumpManager.setIncomingDumper(new AS4IncomingDumperFileBased());
AS4DumpManager.setOutgoingDumper(new AS4OutgoingDumperFileBased());
try (final WebScoped w = new WebScoped()) {
// Read a UBL Invoice
final byte[] aPayloadBytes = SimpleFileIO.getAllFileBytes(new File("src/test/resources/examples/base-example.xml"));
if (aPayloadBytes == null)
throw new IllegalStateException();
final IAS4ClientBuildMessageCallback x1 = new IAS4ClientBuildMessageCallback() {
public void onAS4Message(final AbstractAS4Message<?> aMsg) {
final AS4UserMessage aUserMsg = (AS4UserMessage) aMsg;
LOGGER.info("Sending out AS4 message with message ID '" + aUserMsg.getEbms3UserMessage().getMessageInfo().getMessageId() + "'");
LOGGER.info("Sending out AS4 message with conversation ID '" + aUserMsg.getEbms3UserMessage().getCollaborationInfo().getConversationId() + "'");
}
public void onSoapDocument(@Nonnull final Document aDoc) {
if (false)
LOGGER.info("SOAP Document:\n" + XMLWriter.getNodeAsString(aDoc, new XMLWriterSettings().setIndent(EXMLSerializeIndent.INDENT_AND_ALIGN)));
}
};
// TODO The message ID to use in the UI
final String sAS4MessageID = "36999089-662a-441f-95fd-470bec2b538e-100@phase4";
final ESimpleUserMessageSendResult eRes = Phase4CEFSender.builder().cryptoFactory(CF).httpRetrySettings(new HttpRetrySettings().setMaxRetries(0)).action("TC1Leg1").service("tc1", "bdx:noprocess").senderParticipantID(new SimpleParticipantIdentifier("connectivity-partid-qns", YOUR_ID)).receiverParticipantID(new SimpleParticipantIdentifier("connectivity-partid-qns", "domibus-gitb")).fromPartyIDType("urn:oasis:names:tc:ebcore:partyid-type:unregistered").fromPartyID(YOUR_ID).fromRole(CAS4.DEFAULT_INITIATOR_URL).toPartyIDType("urn:oasis:names:tc:ebcore:partyid-type:unregistered").toPartyID("domibus-gitb").toRole(CAS4.DEFAULT_RESPONDER_URL).messageID(sAS4MessageID).payload(Phase4OutgoingAttachment.builder().data(aPayloadBytes).filename("businessContentPayload").compressionGZIP().mimeType(CMimeType.TEXT_XML).contentID("message").build()).buildMessageCallback(x1).endpointDetailProvider(new AS4EndpointDetailProviderConstant(CertificateHelper.convertStringToCertficateOrNull("-----BEGIN CERTIFICATE-----\r\n" + "MIIDOzCCAiOgAwIBAgIJAKbwaKpEwNTKMA0GCSqGSIb3DQEBCwUAMDQxDTALBgNV\r\n" + "BAoMBEdJVEIxDTALBgNVBAsMBEdJVEIxFDASBgNVBAMMC2dpdGItZW5naW5lMB4X\r\n" + "DTE0MTIyNDEzMjIzNFoXDTI0MTIyMTEzMjIzNFowNDENMAsGA1UECgwER0lUQjEN\r\n" + "MAsGA1UECwwER0lUQjEUMBIGA1UEAwwLZ2l0Yi1lbmdpbmUwggEiMA0GCSqGSIb3\r\n" + "DQEBAQUAA4IBDwAwggEKAoIBAQCpNuRRMhpd2SvNKsZe/WTxm4zuX2Zc5by3zGcm\r\n" + "uzwePdMCnCXk2FAUH67qS9r5VBa4USfiB7l1piyLrNwYWGRDo5OeWIz6Q821/1v7\r\n" + "UHq7FfB0LFPcJ+mOwrDqS+VL0MjcSW4pocJHrpFwObWHTY/R4WmW2xwGOKVh0OUL\r\n" + "UhqQsHDnDhCzFaEWhS8n1lUw3GRipwKLyYvXK8XgLceEmh+j0+cdmIj4a1L4oza/\r\n" + "UgBnCqSob+vowgClyZnGVihE9K8eLLwCSLlIiD+bXWf0VJPLXBNLdNIkRRC0QO0j\r\n" + "T9TuE5TF3SknkA5D0NFp023Alz7jieI0D6JE78QyNQN6y6QRAgMBAAGjUDBOMB0G\r\n" + "A1UdDgQWBBQpAkry20hAcvlw+4poxQC8TI+EgTAfBgNVHSMEGDAWgBQpAkry20hA\r\n" + "cvlw+4poxQC8TI+EgTAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQBS\r\n" + "dfmT3E9uvhiEgVefdwXkkxqlXLQQxfjaqVRVzPTHLqdVs/nBK+iQNhqg+6eLcaGQ\r\n" + "yyDy88vwQ85rqwOFbZd05esIFXYl0pgl1pVsb7HmMNmKT3UPay3HDlHX45ZoexDU\r\n" + "pza4OcrauEM8Yg/5i9dCIPC1GiHebJpYusMVfP78b+5DAyARrHtcb0EJ8rOLxHh6\r\n" + "K2S4EHI6sqQkGHEt1z4m66LyK+vnkLGaq3y6MWEufh78eICDyyVz0DhdIhr18ZHX\r\n" + "dpcsH2VOkE36KnWSo0spEXa6ZtP8MqQ60kJgBt4XcuArKfjIGC6vB6dE0NzXngBD\r\n" + "PHgMfmHJW018/6eN/f0q\r\n" + "-----END CERTIFICATE-----"), "https://www.itb.ec.europa.eu/cef/domibus/services/msh")).sendMessageAndCheckForReceipt();
LOGGER.info("Sending AS4 message to CEF with result " + eRes);
} finally {
WebScopeManager.onGlobalEnd();
}
}
use of com.helger.web.scope.mgr.WebScoped in project phase4 by phax.
the class AS4DumpReader method decryptAS4In.
/**
* Utility method to decrypt dumped .as4in message late.<br>
* Note: this method was mainly created for internal use and does not win the
* prize for the most sexy piece of software in the world ;-)
*
* @param aAS4InData
* The byte array with the dumped data.
* @param aCF
* The Crypto factory to be used. This crypto factory must use use the
* private key that can be used to decrypt this particular message. May
* not be <code>null</code>.
* @param aHttpHeaderConsumer
* An optional HTTP Header map consumer. May be <code>null</code>.
* @param aDecryptedConsumer
* The consumer for the decrypted payload - whatever that is :). May
* not be <code>null</code>.
* @throws WSSecurityException
* In case of error
* @throws Phase4Exception
* In case of error
* @throws IOException
* In case of error
* @throws MessagingException
* In case of error
*/
public static void decryptAS4In(@Nonnull final byte[] aAS4InData, final IAS4CryptoFactory aCF, @Nullable final Consumer<HttpHeaderMap> aHttpHeaderConsumer, @Nonnull final Consumer<byte[]> aDecryptedConsumer) throws WSSecurityException, Phase4Exception, IOException, MessagingException {
final HttpHeaderMap hm = new HttpHeaderMap();
int nHttpStart = 0;
int nHttpEnd = -1;
boolean bLastWasCR = false;
for (int i = 0; i < aAS4InData.length; ++i) {
final byte b = aAS4InData[i];
if (b == '\n') {
if (bLastWasCR) {
nHttpEnd = i;
break;
}
bLastWasCR = true;
final String sLine = new String(aAS4InData, nHttpStart, i - nHttpStart, StandardCharsets.ISO_8859_1);
final String[] aParts = StringHelper.getExplodedArray(':', sLine, 2);
hm.addHeader(aParts[0].trim(), aParts[1].trim());
nHttpStart = i + 1;
} else {
if (b != '\r')
bLastWasCR = false;
}
}
if (aHttpHeaderConsumer != null)
aHttpHeaderConsumer.accept(hm);
LOGGER.info("Now at byte " + nHttpEnd + " having " + hm.getCount() + " HTTP headers");
WebScopeManager.onGlobalBegin(MockServletContext.create());
try (final WebScoped w = new WebScoped();
final AS4RequestHandler rh = new AS4RequestHandler(aCF, DefaultPModeResolver.DEFAULT_PMODE_RESOLVER, IAS4IncomingAttachmentFactory.DEFAULT_INSTANCE, new AS4IncomingMessageMetadata(EAS4MessageMode.REQUEST))) {
final IAS4ServletMessageProcessorSPI aSPI = new IAS4ServletMessageProcessorSPI() {
public AS4MessageProcessorResult processAS4UserMessage(final IAS4IncomingMessageMetadata aMessageMetadata, final HttpHeaderMap aHttpHeaders, final Ebms3UserMessage aUserMessage, final IPMode aPMode, final Node aPayload, final ICommonsList<WSS4JAttachment> aIncomingAttachments, final IAS4MessageState aState, final ICommonsList<Ebms3Error> aProcessingErrorMessages) {
try {
final byte[] aDecryptedBytes = StreamHelper.getAllBytes(aIncomingAttachments.getFirst().getInputStreamProvider());
aDecryptedConsumer.accept(aDecryptedBytes);
LOGGER.info("Handled decrypted payload with " + aDecryptedBytes.length + " bytes");
return AS4MessageProcessorResult.createSuccess();
} catch (final Exception ex) {
throw new IllegalStateException(ex);
}
}
public AS4SignalMessageProcessorResult processAS4SignalMessage(final IAS4IncomingMessageMetadata aMessageMetadata, final HttpHeaderMap aHttpHeaders, final Ebms3SignalMessage aSignalMessage, final IPMode aPMode, final IAS4MessageState aState, final ICommonsList<Ebms3Error> aProcessingErrorMessages) {
LOGGER.error("Unexpected signal msg");
return AS4SignalMessageProcessorResult.createSuccess();
}
};
rh.setProcessorSupplier(() -> new CommonsArrayList<>(aSPI));
rh.handleRequest(new NonBlockingByteArrayInputStream(aAS4InData, nHttpEnd, aAS4InData.length - nHttpEnd), hm, new IAS4ResponseAbstraction() {
public void setStatus(final int nStatusCode) {
}
public void setMimeType(final IMimeType aMimeType) {
}
public void setContent(final HttpHeaderMap aHeaderMap, final IHasInputStream aHasIS) {
}
public void setContent(final byte[] aResultBytes, final Charset aCharset) {
}
});
} finally {
WebScopeManager.onGlobalEnd();
}
}
Aggregations