use of com.helger.httpclient.response.ResponseHandlerByteArray in project phoss-smp by phax.
the class APIExecutorQueryGetBusinessCard method invokeAPI.
public void invokeAPI(@Nonnull final IAPIDescriptor aAPIDescriptor, @Nonnull @Nonempty final String sPath, @Nonnull final Map<String, String> aPathVariables, @Nonnull final IRequestWebScopeWithoutResponse aRequestScope, @Nonnull final UnifiedResponse aUnifiedResponse) throws Exception {
final String sPathServiceGroupID = aPathVariables.get(SMPRestFilter.PARAM_SERVICE_GROUP_ID);
final ISMPServerAPIDataProvider aDataProvider = new SMPRestDataProvider(aRequestScope, sPathServiceGroupID);
// Is the remote query API disabled?
if (SMPServerConfiguration.isRestRemoteQueryAPIDisabled()) {
throw new SMPPreconditionFailedException("The remote query API is disabled. getRemoteBusinessCard will not be executed", aDataProvider.getCurrentURI());
}
final IIdentifierFactory aIF = SMPMetaManager.getIdentifierFactory();
final ESMPAPIType eAPIType = SMPServerConfiguration.getRESTType().getAPIType();
final IParticipantIdentifier aParticipantID = aIF.parseParticipantIdentifier(sPathServiceGroupID);
if (aParticipantID == null) {
throw SMPBadRequestException.failedToParseSG(sPathServiceGroupID, aDataProvider.getCurrentURI());
}
final SMPQueryParams aQueryParams = SMPQueryParams.create(eAPIType, aParticipantID);
final ZonedDateTime aQueryDT = PDTFactory.getCurrentZonedDateTimeUTC();
final StopWatch aSW = StopWatch.createdStarted();
final String sLogPrefix = "[QueryAPI] ";
LOGGER.info(sLogPrefix + "BusinessCard of '" + aParticipantID.getURIEncoded() + "' is queried using SMP API '" + eAPIType + "' from '" + aQueryParams.getSMPHostURI() + "'");
IJsonObject aJson = null;
final String sBCURL = aQueryParams.getSMPHostURI().toString() + "/businesscard/" + aParticipantID.getURIEncoded();
LOGGER.info(sLogPrefix + "Querying BC from '" + sBCURL + "'");
byte[] aData;
try (HttpClientManager aHttpClientMgr = new HttpClientManager()) {
final HttpGet aGet = new HttpGet(sBCURL);
aData = aHttpClientMgr.execute(aGet, new ResponseHandlerByteArray());
} catch (final Exception ex) {
aData = null;
}
if (aData == null)
LOGGER.warn(sLogPrefix + "No Business Card is available for that participant.");
else {
final PDBusinessCard aBC = PDBusinessCardHelper.parseBusinessCard(aData, (Charset) null);
if (aBC == null) {
LOGGER.error(sLogPrefix + "Failed to parse BC:\n" + new String(aData, StandardCharsets.UTF_8));
} else {
// Business Card found
aJson = aBC.getAsJson();
}
}
aSW.stop();
if (aJson == null) {
LOGGER.error(sLogPrefix + "Failed to perform the BusinessCard SMP lookup");
aUnifiedResponse.setStatus(CHttp.HTTP_NOT_FOUND);
} else {
LOGGER.info(sLogPrefix + "Succesfully finished BusinessCard lookup lookup after " + aSW.getMillis() + " milliseconds");
aJson.add("queryDateTime", DateTimeFormatter.ISO_ZONED_DATE_TIME.format(aQueryDT));
aJson.add("queryDurationMillis", aSW.getMillis());
final String sRet = new JsonWriter(JsonWriterSettings.DEFAULT_SETTINGS_FORMATTED).writeAsString(aJson);
aUnifiedResponse.setContentAndCharset(sRet, StandardCharsets.UTF_8).setMimeType(CMimeType.APPLICATION_JSON).enableCaching(1 * CGlobal.SECONDS_PER_HOUR);
}
}
use of com.helger.httpclient.response.ResponseHandlerByteArray in project phoss-smp by phax.
the class APIExecutorQueryGetDocTypes method invokeAPI.
public void invokeAPI(@Nonnull final IAPIDescriptor aAPIDescriptor, @Nonnull @Nonempty final String sPath, @Nonnull final Map<String, String> aPathVariables, @Nonnull final IRequestWebScopeWithoutResponse aRequestScope, @Nonnull final UnifiedResponse aUnifiedResponse) throws Exception {
final String sPathServiceGroupID = aPathVariables.get(SMPRestFilter.PARAM_SERVICE_GROUP_ID);
final ISMPServerAPIDataProvider aDataProvider = new SMPRestDataProvider(aRequestScope, sPathServiceGroupID);
// Is the remote query API disabled?
if (SMPServerConfiguration.isRestRemoteQueryAPIDisabled()) {
throw new SMPPreconditionFailedException("The remote query API is disabled. getRemoteDocTypes will not be executed", aDataProvider.getCurrentURI());
}
final IIdentifierFactory aIF = SMPMetaManager.getIdentifierFactory();
final ESMPAPIType eAPIType = SMPServerConfiguration.getRESTType().getAPIType();
final IParticipantIdentifier aParticipantID = aIF.parseParticipantIdentifier(sPathServiceGroupID);
if (aParticipantID == null) {
throw SMPBadRequestException.failedToParseSG(sPathServiceGroupID, aDataProvider.getCurrentURI());
}
final SMPQueryParams aQueryParams = SMPQueryParams.create(eAPIType, aParticipantID);
final boolean bQueryBusinessCard = aRequestScope.params().getAsBoolean("businessCard", false);
final boolean bXMLSchemaValidation = aRequestScope.params().getAsBoolean("xmlSchemaValidation", true);
final ZonedDateTime aQueryDT = PDTFactory.getCurrentZonedDateTimeUTC();
final StopWatch aSW = StopWatch.createdStarted();
final String sLogPrefix = "[QueryAPI] ";
LOGGER.info(sLogPrefix + "Document types of '" + aParticipantID.getURIEncoded() + "' are queried using SMP API '" + eAPIType + "' from '" + aQueryParams.getSMPHostURI() + "'; XSD validation=" + bXMLSchemaValidation);
ICommonsSortedMap<String, String> aSGHrefs = null;
switch(eAPIType) {
case PEPPOL:
{
final SMPClientReadOnly aSMPClient = new SMPClientReadOnly(aQueryParams.getSMPHostURI());
aSMPClient.setXMLSchemaValidation(bXMLSchemaValidation);
// Get all HRefs and sort them by decoded URL
final com.helger.xsds.peppol.smp1.ServiceGroupType aSG = aSMPClient.getServiceGroupOrNull(aParticipantID);
// Map from cleaned URL to original URL
if (aSG != null && aSG.getServiceMetadataReferenceCollection() != null) {
aSGHrefs = new CommonsTreeMap<>();
for (final com.helger.xsds.peppol.smp1.ServiceMetadataReferenceType aSMR : aSG.getServiceMetadataReferenceCollection().getServiceMetadataReference()) {
// Decoded href is important for unification
final String sHref = CIdentifier.createPercentDecoded(aSMR.getHref());
if (aSGHrefs.put(sHref, aSMR.getHref()) != null)
LOGGER.warn(sLogPrefix + "The ServiceGroup list contains the duplicate URL '" + sHref + "'");
}
}
break;
}
case OASIS_BDXR_V1:
{
aSGHrefs = new CommonsTreeMap<>();
final BDXRClientReadOnly aBDXR1Client = new BDXRClientReadOnly(aQueryParams.getSMPHostURI());
aBDXR1Client.setXMLSchemaValidation(bXMLSchemaValidation);
// Get all HRefs and sort them by decoded URL
final com.helger.xsds.bdxr.smp1.ServiceGroupType aSG = aBDXR1Client.getServiceGroupOrNull(aParticipantID);
// Map from cleaned URL to original URL
if (aSG != null && aSG.getServiceMetadataReferenceCollection() != null) {
aSGHrefs = new CommonsTreeMap<>();
for (final com.helger.xsds.bdxr.smp1.ServiceMetadataReferenceType aSMR : aSG.getServiceMetadataReferenceCollection().getServiceMetadataReference()) {
// Decoded href is important for unification
final String sHref = CIdentifier.createPercentDecoded(aSMR.getHref());
if (aSGHrefs.put(sHref, aSMR.getHref()) != null)
LOGGER.warn(sLogPrefix + "The ServiceGroup list contains the duplicate URL '" + sHref + "'");
}
}
break;
}
}
IJsonObject aJson = null;
if (aSGHrefs != null)
aJson = SMPJsonResponse.convert(eAPIType, aParticipantID, aSGHrefs, aIF);
if (bQueryBusinessCard) {
final String sBCURL = aQueryParams.getSMPHostURI().toString() + "/businesscard/" + aParticipantID.getURIEncoded();
LOGGER.info(sLogPrefix + "Querying BC from '" + sBCURL + "'");
byte[] aData;
try (HttpClientManager aHttpClientMgr = new HttpClientManager()) {
final HttpGet aGet = new HttpGet(sBCURL);
aData = aHttpClientMgr.execute(aGet, new ResponseHandlerByteArray());
} catch (final Exception ex) {
aData = null;
}
if (aData == null)
LOGGER.warn(sLogPrefix + "No Business Card is available for that participant.");
else {
final PDBusinessCard aBC = PDBusinessCardHelper.parseBusinessCard(aData, (Charset) null);
if (aBC == null) {
LOGGER.error(sLogPrefix + "Failed to parse BC:\n" + new String(aData, StandardCharsets.UTF_8));
} else {
// Business Card found
if (aJson == null)
aJson = new JsonObject();
aJson.addJson("businessCard", aBC.getAsJson());
}
}
}
aSW.stop();
if (aJson == null) {
LOGGER.error(sLogPrefix + "Failed to perform the SMP lookup");
aUnifiedResponse.setStatus(CHttp.HTTP_NOT_FOUND);
} else {
LOGGER.info(sLogPrefix + "Succesfully finished lookup lookup after " + aSW.getMillis() + " milliseconds");
aJson.add("queryDateTime", DateTimeFormatter.ISO_ZONED_DATE_TIME.format(aQueryDT));
aJson.add("queryDurationMillis", aSW.getMillis());
final String sRet = new JsonWriter(JsonWriterSettings.DEFAULT_SETTINGS_FORMATTED).writeAsString(aJson);
aUnifiedResponse.setContentAndCharset(sRet, StandardCharsets.UTF_8).setMimeType(CMimeType.APPLICATION_JSON).enableCaching(1 * CGlobal.SECONDS_PER_HOUR);
}
}
use of com.helger.httpclient.response.ResponseHandlerByteArray in project phase4 by phax.
the class DropFolderUserMessage method _send.
private static void _send(@Nonnull final IAS4CryptoFactory aCF, final Path aSendFile, final Path aIncomingDir) {
final StopWatch aSW = StopWatch.createdStarted();
boolean bSuccess = false;
LOGGER.info("Trying to send " + aSendFile.toString());
try (final AS4ResourceHelper aResHelper = new AS4ResourceHelper()) {
// Read generic SBD
final StandardBusinessDocument aSBD = SBDHReader.standardBusinessDocument().read(Files.newInputStream(aSendFile));
if (aSBD == null) {
LOGGER.error("Failed to read " + aSendFile.toString() + " as SBDH document!");
} else {
// Extract Peppol specific data
final PeppolSBDHDocument aSBDH = new PeppolSBDHDocumentReader(IF).extractData(aSBD);
final ISMPServiceMetadataProvider aSMPClient = new SMPClient(UP, aSBDH.getReceiverAsIdentifier(), ESML.DIGIT_TEST);
final EndpointType aEndpoint = aSMPClient.getEndpoint(aSBDH.getReceiverAsIdentifier(), aSBDH.getDocumentTypeAsIdentifier(), aSBDH.getProcessAsIdentifier(), ESMPTransportProfile.TRANSPORT_PROFILE_BDXR_AS4);
if (aEndpoint == null) {
LOGGER.error("Found no endpoint for:\n Receiver ID: " + aSBDH.getReceiverAsIdentifier().getURIEncoded() + "\n Document type ID: " + aSBDH.getDocumentTypeAsIdentifier().getURIEncoded() + "\n Process ID: " + aSBDH.getProcessAsIdentifier().getURIEncoded());
} else {
final KeyStore.PrivateKeyEntry aOurCert = aCF.getPrivateKeyEntry();
final X509Certificate aTheirCert = CertificateHelper.convertStringToCertficate(aEndpoint.getCertificate());
final AS4ClientUserMessage aClient = new AS4ClientUserMessage(aResHelper);
aClient.setSoapVersion(ESoapVersion.SOAP_12);
// Keystore data
aClient.setAS4CryptoFactory(aCF);
aClient.signingParams().setAlgorithmSign(ECryptoAlgorithmSign.RSA_SHA_512);
aClient.signingParams().setAlgorithmSignDigest(ECryptoAlgorithmSignDigest.DIGEST_SHA_512);
// FIXME Action, Service etc. are missing
aClient.setAction("xxx");
aClient.setServiceType("xxx");
aClient.setServiceValue("xxx");
aClient.setConversationID(MessageHelperMethods.createRandomConversationID());
aClient.setAgreementRefValue("xxx");
aClient.setFromRole(CAS4.DEFAULT_ROLE);
aClient.setFromPartyID(PeppolCertificateHelper.getSubjectCN((X509Certificate) aOurCert.getCertificate()));
aClient.setToRole(CAS4.DEFAULT_ROLE);
aClient.setToPartyID(PeppolCertificateHelper.getSubjectCN(aTheirCert));
aClient.ebms3Properties().setAll(MessageHelperMethods.createEbms3Property(CAS4.ORIGINAL_SENDER, aSBDH.getSenderScheme(), aSBDH.getSenderValue()), MessageHelperMethods.createEbms3Property(CAS4.FINAL_RECIPIENT, aSBDH.getReceiverScheme(), aSBDH.getReceiverValue()));
aClient.setPayload(SBDHWriter.standardBusinessDocument().getAsDocument(aSBD));
final IAS4ClientBuildMessageCallback aCallback = null;
final IAS4OutgoingDumper aOutgoingDumper = null;
final IAS4RetryCallback aRetryCallback = null;
final AS4ClientSentMessage<byte[]> aResponseEntity = aClient.sendMessageWithRetries(W3CEndpointReferenceHelper.getAddress(aEndpoint.getEndpointReference()), new ResponseHandlerByteArray(), aCallback, aOutgoingDumper, aRetryCallback);
LOGGER.info("Successfully transmitted document with message ID '" + aResponseEntity.getMessageID() + "' for '" + aSBDH.getReceiverAsIdentifier().getURIEncoded() + "' to '" + W3CEndpointReferenceHelper.getAddress(aEndpoint.getEndpointReference()) + "' in " + aSW.stopAndGetMillis() + " ms");
if (aResponseEntity.hasResponse()) {
final String sMessageID = aResponseEntity.getMessageID();
final String sFilename = FilenameHelper.getAsSecureValidASCIIFilename(sMessageID) + "-response.xml";
final File aResponseFile = aIncomingDir.resolve(sFilename).toFile();
if (SimpleFileIO.writeFile(aResponseFile, aResponseEntity.getResponse()).isSuccess())
LOGGER.info("Response file was written to '" + aResponseFile.getAbsolutePath() + "'");
else
LOGGER.error("Error writing response file to '" + aResponseFile.getAbsolutePath() + "'");
}
bSuccess = true;
}
}
} catch (final Exception ex) {
LOGGER.error("Error sending " + aSendFile.toString(), ex);
}
// After the exception handler!
{
// Move to done or error directory?
final Path aDest = aSendFile.resolveSibling(bSuccess ? PATH_DONE : PATH_ERROR).resolve(aSendFile.getFileName());
try {
Files.move(aSendFile, aDest);
} catch (final IOException ex) {
LOGGER.error("Error moving from '" + aSendFile.toString() + "' to '" + aDest + "'", ex);
}
}
}
Aggregations