use of com.helger.commons.collection.impl.ICommonsOrderedSet in project ph-web by phax.
the class MailTransport method send.
/**
* Actually send the given array of MimeMessages via JavaMail.
*
* @param aAllMessages
* Email data objects to send. May be <code>null</code>.
* @return A non-<code>null</code> map of the failed messages
*/
@Nonnull
public ICommonsOrderedMap<IMutableEmailData, MailTransportError> send(@Nullable final Collection<IMutableEmailData> aAllMessages) {
final ICommonsOrderedMap<IMutableEmailData, MailTransportError> aFailedMessages = new CommonsLinkedHashMap<>();
if (aAllMessages != null) {
final ICommonsList<IMutableEmailData> aRemainingMessages = new CommonsArrayList<>(aAllMessages);
MailSendException aExceptionToBeRemembered = null;
try (final Transport aTransport = m_aSession.getTransport(m_bSMTPS ? SMTPS_PROTOCOL : SMTP_PROTOCOL)) {
// Add global listeners (if present)
for (final ConnectionListener aConnectionListener : EmailGlobalSettings.getAllConnectionListeners()) aTransport.addConnectionListener(aConnectionListener);
// Check if a detailed listener is present
final ICommonsList<IEmailDataTransportListener> aEmailDataTransportListeners = EmailGlobalSettings.getAllEmailDataTransportListeners();
// Connect
aTransport.connect(m_aSMTPSettings.getHostName(), m_aSMTPSettings.getPort(), m_aSMTPSettings.getUserName(), m_aSMTPSettings.getPassword());
// For all messages
for (final IMutableEmailData aEmailData : aAllMessages) {
final MimeMessage aMimeMessage = new MimeMessage(m_aSession);
try {
// convert from IEmailData to MimeMessage
MailConverter.fillMimeMessage(aMimeMessage, aEmailData, m_aSMTPSettings.getCharsetObj());
// Ensure a sent date is present
if (aMimeMessage.getSentDate() == null)
aMimeMessage.setSentDate(new Date());
// Get an explicitly specified message ID
final String sMessageID = aMimeMessage.getMessageID();
// This creates a new message ID (besides other things)
aMimeMessage.saveChanges();
if (sMessageID != null) {
// Preserve explicitly specified message id...
aMimeMessage.setHeader(HEADER_MESSAGE_ID, sMessageID);
}
aMimeMessage.setHeader(HEADER_X_MAILER, X_MAILER);
if (LOGGER.isInfoEnabled())
LOGGER.info("Delivering mail from " + Arrays.toString(aMimeMessage.getFrom()) + " to " + Arrays.toString(aMimeMessage.getAllRecipients()) + " with subject '" + aMimeMessage.getSubject() + "' and message ID '" + aMimeMessage.getMessageID() + "'");
// Main transmit - always throws an exception
aTransport.sendMessage(aMimeMessage, aMimeMessage.getAllRecipients());
throw new IllegalStateException("Never expected to come beyong sendMessage!");
} catch (final SendFailedException ex) {
if (EmailGlobalSettings.isDebugSMTP())
LOGGER.error("Error send mail - SendFailedException", ex);
/*
* Extract all addresses: the valid addresses to which the message
* was sent, the valid address to which the message was not sent and
* the invalid addresses
*/
final ICommonsSet<String> aValidSent = new CommonsHashSet<>(ex.getValidSentAddresses(), Address::toString);
final ICommonsSet<String> aValidUnsent = new CommonsHashSet<>(ex.getValidUnsentAddresses(), Address::toString);
final ICommonsSet<String> aInvalid = new CommonsHashSet<>(ex.getInvalidAddresses(), Address::toString);
final ICommonsList<MailSendDetails> aDetails = new CommonsArrayList<>();
Exception ex2;
MessagingException bex = ex;
while ((ex2 = bex.getNextException()) != null && ex2 instanceof MessagingException) {
if (ex2 instanceof SMTPAddressFailedException) {
final SMTPAddressFailedException ssfe = (SMTPAddressFailedException) ex2;
aDetails.add(new MailSendDetails(false, ssfe.getAddress().toString(), ssfe.getCommand(), ssfe.getMessage().trim(), ESMTPErrorCode.getFromIDOrDefault(ssfe.getReturnCode(), ESMTPErrorCode.FALLBACK)));
} else if (ex2 instanceof SMTPAddressSucceededException) {
final SMTPAddressSucceededException ssfe = (SMTPAddressSucceededException) ex2;
aDetails.add(new MailSendDetails(true, ssfe.getAddress().toString(), ssfe.getCommand(), ssfe.getMessage().trim(), ESMTPErrorCode.getFromIDOrDefault(ssfe.getReturnCode(), ESMTPErrorCode.FALLBACK)));
}
bex = (MessagingException) ex2;
}
// Map addresses to details
final ICommonsOrderedSet<MailSendDetails> aValidSentExt = new CommonsLinkedHashSet<>();
final ICommonsOrderedSet<MailSendDetails> aValidUnsentExt = new CommonsLinkedHashSet<>();
final ICommonsOrderedSet<MailSendDetails> aInvalidExt = new CommonsLinkedHashSet<>();
for (final MailSendDetails aFailure : aDetails) {
final String sAddress = aFailure.getAddress();
if (aValidSent.contains(sAddress))
aValidSentExt.add(aFailure);
else if (aValidUnsent.contains(sAddress))
aValidUnsentExt.add(aFailure);
else
aInvalidExt.add(aFailure);
}
final EmailDataTransportEvent aEvent = new EmailDataTransportEvent(m_aSMTPSettings, aEmailData, aMimeMessage, aValidSentExt, aValidUnsentExt, aInvalidExt);
if (aValidUnsent.isEmpty() && aInvalid.isEmpty() && aValidSent.isNotEmpty()) {
// Message delivered
for (final IEmailDataTransportListener aEmailDataTransportListener : aEmailDataTransportListeners) aEmailDataTransportListener.messageDelivered(aEvent);
// Remove message from list of remaining
STATS_SEND_SUCCESS.increment();
} else {
// Message not delivered
for (final IEmailDataTransportListener aEmailDataTransportListener : aEmailDataTransportListeners) aEmailDataTransportListener.messageNotDelivered(aEvent);
// Sending exactly this message failed
aFailedMessages.put(aEmailData, new MailTransportError(ex, aDetails));
STATS_SEND_FAILURE.increment();
}
// Remove message from list of remaining as we put it in the
// failed message list manually in case of error
aRemainingMessages.remove(aEmailData);
} catch (final MessagingException ex) {
if (EmailGlobalSettings.isDebugSMTP())
LOGGER.error("Error send mail - MessagingException", ex);
final ICommonsOrderedSet<MailSendDetails> aInvalid = new CommonsLinkedHashSet<>();
final Consumer<IEmailAddress> aConsumer = a -> aInvalid.add(new MailSendDetails(false, a.getAddress(), "<generic error>", ex.getMessage(), ESMTPErrorCode.FALLBACK));
aEmailData.to().forEach(aConsumer);
aEmailData.cc().forEach(aConsumer);
aEmailData.bcc().forEach(aConsumer);
final EmailDataTransportEvent aEvent = new EmailDataTransportEvent(m_aSMTPSettings, aEmailData, aMimeMessage, new CommonsArrayList<>(), new CommonsArrayList<>(), aInvalid);
// Message not delivered
for (final IEmailDataTransportListener aEmailDataTransportListener : aEmailDataTransportListeners) aEmailDataTransportListener.messageNotDelivered(aEvent);
// Sending exactly this message failed
aFailedMessages.put(aEmailData, new MailTransportError(ex));
// Remove message from list of remaining as we put it in the
// failed message list manually
aRemainingMessages.remove(aEmailData);
STATS_SEND_FAILURE.increment();
}
}
// for all messages
} catch (final AuthenticationFailedException ex) {
// problem with the credentials
aExceptionToBeRemembered = new MailSendException("Mail server authentication failed", ex);
} catch (final MessagingException ex) {
if (WebExceptionHelper.isServerNotReachableConnection(ex.getCause()))
aExceptionToBeRemembered = new MailSendException("Failed to connect to mail server: " + ex.getCause().getMessage());
else
aExceptionToBeRemembered = new MailSendException("Mail server connection failed", ex);
} catch (final Exception ex) {
// E.g. IllegalState from SMTPTransport ("Not connected")
aExceptionToBeRemembered = new MailSendException("Internal error sending mail", ex);
} finally {
// Was any message not sent
if (aRemainingMessages.isNotEmpty()) {
if (aExceptionToBeRemembered == null)
aExceptionToBeRemembered = new MailSendException("Internal error - messages are remaining but no Exception occurred!");
for (final IMutableEmailData aRemainingMessage : aRemainingMessages) aFailedMessages.put(aRemainingMessage, new MailTransportError(aExceptionToBeRemembered));
}
}
}
return aFailedMessages;
}
use of com.helger.commons.collection.impl.ICommonsOrderedSet in project ph-web by phax.
the class MainCreateMimeTypesFileNameMapForJavaxActivation method main.
/**
* Create the mime.types file that is read by javax.activation. See class
* javax.annotation.MimetypesFileTypeMap
*
* @param args
* ignore
* @throws Exception
* if anything goes wrong
*/
public static void main(final String[] args) throws Exception {
final String sDestPath = "src/main/resources/META-INF/mime.types";
Writer w = null;
try {
// build map from MimeType to list of extensions
final ICommonsMap<String, ICommonsOrderedSet<String>> aMap = new CommonsHashMap<>();
for (final MimeTypeInfo aInfo : MimeTypeInfoManager.getDefaultInstance().getAllMimeTypeInfos()) for (final String sExt : aInfo.getAllExtensions()) {
// Skip the one empty extension!
if (sExt.length() > 0)
for (final String sMimeType : aInfo.getAllMimeTypeStrings()) aMap.computeIfAbsent(sMimeType, k -> new CommonsLinkedHashSet<>()).add(sExt);
}
// write file in format iso-8859-1!
w = new PrintWriter(new File(sDestPath), StandardCharsets.ISO_8859_1.name());
// write header
for (final String sLine : VendorInfo.getFileHeaderLines()) w.write("# " + sLine + '\n');
w.write("#\n");
w.write("# Created on: " + ZonedDateTime.now(Clock.systemUTC()).toString() + "\n");
w.write("# Created by: " + MainCreateMimeTypesFileNameMapForJavaxActivation.class.getName() + "\n");
w.write("#\n");
// write MIME type mapping
for (final Map.Entry<String, ICommonsOrderedSet<String>> aEntry : aMap.getSortedByKey(Comparator.naturalOrder()).entrySet()) w.write("type=" + aEntry.getKey() + " exts=" + StringHelper.getImploded(',', aEntry.getValue()) + "\n");
// done
w.flush();
w.close();
LOGGER.info("Done creating " + sDestPath);
} finally {
StreamHelper.close(w);
}
}
use of com.helger.commons.collection.impl.ICommonsOrderedSet in project phoss-smp by phax.
the class ServiceGroupImport method importXMLVer10.
public static void importXMLVer10(@Nonnull final IMicroElement eRoot, final boolean bOverwriteExisting, @Nonnull final IUser aDefaultOwner, @Nonnull final ICommonsSet<String> aAllExistingServiceGroupIDs, @Nonnull final ICommonsSet<String> aAllExistingBusinessCardIDs, @Nonnull final ICommonsList<ImportActionItem> aActionList, @Nonnull final ImportSummary aSummary) {
ValueEnforcer.notNull(eRoot, "Root");
ValueEnforcer.notNull(aDefaultOwner, "DefaultOwner");
ValueEnforcer.notNull(aAllExistingServiceGroupIDs, "AllExistingServiceGroupIDs");
ValueEnforcer.notNull(aAllExistingBusinessCardIDs, "AllExistingBusinessCardIDs");
ValueEnforcer.notNull(aActionList, "ActionList");
ValueEnforcer.notNull(aSummary, "Summary");
final String sLogPrefix = "[SG-IMPORT-" + COUNTER.incrementAndGet() + "] ";
final BiConsumer<String, String> aLoggerSuccess = (pi, msg) -> {
LOGGER.info(sLogPrefix + "[" + pi + "] " + msg);
aActionList.add(ImportActionItem.createSuccess(pi, msg));
};
final BiConsumer<String, String> aLoggerInfo = (pi, msg) -> {
LOGGER.info(sLogPrefix + (pi == null ? "" : "[" + pi + "] ") + msg);
aActionList.add(ImportActionItem.createInfo(pi, msg));
};
final BiConsumer<String, String> aLoggerWarn = (pi, msg) -> {
LOGGER.info(sLogPrefix + (pi == null ? "" : "[" + pi + "] ") + msg);
aActionList.add(ImportActionItem.createWarning(pi, msg));
};
final Consumer<String> aLoggerError = msg -> {
LOGGER.error(sLogPrefix + msg);
aActionList.add(ImportActionItem.createError(null, msg, null));
};
final BiConsumer<String, Exception> aLoggerErrorEx = (msg, ex) -> {
LOGGER.error(sLogPrefix + msg, ex);
aActionList.add(ImportActionItem.createError(null, msg, ex));
};
final BiConsumer<String, String> aLoggerErrorPI = (pi, msg) -> {
LOGGER.error(sLogPrefix + "[" + pi + "] " + msg);
aActionList.add(ImportActionItem.createError(pi, msg, null));
};
final ITriConsumer<String, String, Exception> aLoggerErrorPIEx = (pi, msg, ex) -> {
LOGGER.error(sLogPrefix + "[" + pi + "] " + msg, ex);
aActionList.add(ImportActionItem.createError(pi, msg, ex));
};
if (LOGGER.isInfoEnabled())
LOGGER.info("Starting import of Service Groups from XML v1.0, overwrite is " + (bOverwriteExisting ? "enabled" : "disabled"));
final ISMPSettings aSettings = SMPMetaManager.getSettings();
final IUserManager aUserMgr = PhotonSecurityManager.getUserMgr();
final ICommonsOrderedMap<ISMPServiceGroup, InternalImportData> aImportServiceGroups = new CommonsLinkedHashMap<>();
final ICommonsMap<String, ISMPServiceGroup> aDeleteServiceGroups = new CommonsHashMap<>();
// First read all service groups as they are dependents of the
// business cards
int nSGIndex = 0;
for (final IMicroElement eServiceGroup : eRoot.getAllChildElements(CSMPExchange.ELEMENT_SERVICEGROUP)) {
// Read service group and service information
final ISMPServiceGroup aServiceGroup;
try {
aServiceGroup = SMPServiceGroupMicroTypeConverter.convertToNative(eServiceGroup, x -> {
IUser aOwner = aUserMgr.getUserOfID(x);
if (aOwner == null) {
// Select the default owner if an unknown user is contained
aOwner = aDefaultOwner;
LOGGER.warn("Failed to resolve stored owner '" + x + "' - using default owner '" + aDefaultOwner.getID() + "'");
}
// If the user is deleted, but existing - keep the deleted user
return aOwner;
});
} catch (final RuntimeException ex) {
aLoggerErrorEx.accept("Error parsing the Service Group at index " + nSGIndex + ". Ignoring this Service Group.", ex);
continue;
}
final String sServiceGroupID = aServiceGroup.getID();
final boolean bIsServiceGroupContained = aAllExistingServiceGroupIDs.contains(sServiceGroupID);
if (!bIsServiceGroupContained || bOverwriteExisting) {
if (aImportServiceGroups.containsKey(aServiceGroup)) {
aLoggerErrorPI.accept(sServiceGroupID, "The Service Group at index " + nSGIndex + " is already contained in the file. Will overwrite the previous definition.");
}
// Remember to create/overwrite the service group
final InternalImportData aImportData = new InternalImportData();
aImportServiceGroups.put(aServiceGroup, aImportData);
if (bIsServiceGroupContained)
aDeleteServiceGroups.put(sServiceGroupID, aServiceGroup);
aLoggerSuccess.accept(sServiceGroupID, "Will " + (bIsServiceGroupContained ? "overwrite" : "import") + " Service Group");
// read all contained service information
{
int nSICount = 0;
for (final IMicroElement eServiceInfo : eServiceGroup.getAllChildElements(CSMPExchange.ELEMENT_SERVICEINFO)) {
final ISMPServiceInformation aServiceInfo = SMPServiceInformationMicroTypeConverter.convertToNative(eServiceInfo, x -> aServiceGroup);
aImportData.addServiceInfo(aServiceInfo);
++nSICount;
}
aLoggerInfo.accept(sServiceGroupID, "Read " + nSICount + " Service Information " + (nSICount == 1 ? "element" : "elements") + " of Service Group");
}
// read all contained redirects
{
int nRDCount = 0;
for (final IMicroElement eRedirect : eServiceGroup.getAllChildElements(CSMPExchange.ELEMENT_REDIRECT)) {
final ISMPRedirect aRedirect = SMPRedirectMicroTypeConverter.convertToNative(eRedirect, x -> aServiceGroup);
aImportData.addRedirect(aRedirect);
++nRDCount;
}
aLoggerInfo.accept(sServiceGroupID, "Read " + nRDCount + " Redirect " + (nRDCount == 1 ? "element" : "elements") + " of Service Group");
}
} else {
aLoggerWarn.accept(sServiceGroupID, "Ignoring already existing Service Group");
}
++nSGIndex;
}
// Now read the business cards
final ICommonsOrderedSet<ISMPBusinessCard> aImportBusinessCards = new CommonsLinkedHashSet<>();
final ICommonsMap<String, ISMPBusinessCard> aDeleteBusinessCards = new CommonsHashMap<>();
if (aSettings.isDirectoryIntegrationEnabled()) {
// Read them only if the Peppol Directory integration is enabled
int nBCIndex = 0;
for (final IMicroElement eBusinessCard : eRoot.getAllChildElements(CSMPExchange.ELEMENT_BUSINESSCARD)) {
// Read business card
ISMPBusinessCard aBusinessCard = null;
try {
aBusinessCard = new SMPBusinessCardMicroTypeConverter().convertToNative(eBusinessCard);
} catch (final RuntimeException ex) {
// Service group not found
aLoggerError.accept("Business Card at index " + nBCIndex + " contains an invalid/unknown Service Group!");
}
if (aBusinessCard == null) {
aLoggerError.accept("Failed to read Business Card at index " + nBCIndex);
} else {
final String sBusinessCardID = aBusinessCard.getID();
final boolean bIsBusinessCardContained = aAllExistingBusinessCardIDs.contains(sBusinessCardID);
if (!bIsBusinessCardContained || bOverwriteExisting) {
if (aImportBusinessCards.removeIf(x -> x.getID().equals(sBusinessCardID))) {
aLoggerErrorPI.accept(sBusinessCardID, "The Business Card already contained in the file. Will overwrite the previous definition.");
}
aImportBusinessCards.add(aBusinessCard);
if (bIsBusinessCardContained) {
// BCs are deleted when the SGs are deleted
if (!aDeleteServiceGroups.containsKey(sBusinessCardID))
aDeleteBusinessCards.put(sBusinessCardID, aBusinessCard);
}
aLoggerSuccess.accept(sBusinessCardID, "Will " + (bIsBusinessCardContained ? "overwrite" : "import") + " Business Card");
} else {
aLoggerWarn.accept(sBusinessCardID, "Ignoring already existing Business Card");
}
}
++nBCIndex;
}
}
if (aImportServiceGroups.isEmpty() && aImportBusinessCards.isEmpty()) {
aLoggerWarn.accept(null, aSettings.isDirectoryIntegrationEnabled() ? "Found neither a Service Group nor a Business Card to import." : "Found no Service Group to import.");
} else if (aActionList.containsAny(ImportActionItem::isError)) {
aLoggerError.accept("Nothing will be imported because of the previous errors.");
} else {
// Start importing
aLoggerInfo.accept(null, "Import is performed!");
final ISMPServiceGroupManager aServiceGroupMgr = SMPMetaManager.getServiceGroupMgr();
final ISMPServiceInformationManager aServiceInfoMgr = SMPMetaManager.getServiceInformationMgr();
final ISMPRedirectManager aRedirectMgr = SMPMetaManager.getRedirectMgr();
final ISMPBusinessCardManager aBusinessCardMgr = SMPMetaManager.getBusinessCardMgr();
// 1. delete all existing service groups to be imported (if overwrite);
// this may implicitly delete business cards
final ICommonsSet<IParticipantIdentifier> aDeletedServiceGroups = new CommonsHashSet<>();
for (final Map.Entry<String, ISMPServiceGroup> aEntry : aDeleteServiceGroups.entrySet()) {
final String sServiceGroupID = aEntry.getKey();
final ISMPServiceGroup aDeleteServiceGroup = aEntry.getValue();
final IParticipantIdentifier aPI = aDeleteServiceGroup.getParticipantIdentifier();
try {
// Delete locally only
if (aServiceGroupMgr.deleteSMPServiceGroup(aPI, false).isChanged()) {
aLoggerSuccess.accept(sServiceGroupID, "Successfully deleted Service Group");
aDeletedServiceGroups.add(aPI);
aSummary.onSuccess(EImportSummaryAction.DELETE_SG);
} else {
aLoggerErrorPI.accept(sServiceGroupID, "Failed to delete Service Group");
aSummary.onError(EImportSummaryAction.DELETE_SG);
}
} catch (final SMPServerException ex) {
aLoggerErrorPIEx.accept(sServiceGroupID, "Failed to delete Service Group", ex);
aSummary.onError(EImportSummaryAction.DELETE_SG);
}
}
// 2. create all service groups
for (final Map.Entry<ISMPServiceGroup, InternalImportData> aEntry : aImportServiceGroups.entrySet()) {
final ISMPServiceGroup aImportServiceGroup = aEntry.getKey();
final String sServiceGroupID = aImportServiceGroup.getID();
ISMPServiceGroup aNewServiceGroup = null;
try {
final boolean bIsOverwrite = aDeleteServiceGroups.containsKey(sServiceGroupID);
// Create in SML only for newly created entries
aNewServiceGroup = aServiceGroupMgr.createSMPServiceGroup(aImportServiceGroup.getOwnerID(), aImportServiceGroup.getParticipantIdentifier(), aImportServiceGroup.getExtensionsAsString(), !bIsOverwrite);
aLoggerSuccess.accept(sServiceGroupID, "Successfully created Service Group");
aSummary.onSuccess(EImportSummaryAction.CREATE_SG);
} catch (final Exception ex) {
// E.g. if SML connection failed
aLoggerErrorPIEx.accept(sServiceGroupID, "Error creating the new Service Group", ex);
// Delete Business Card again, if already present
aImportBusinessCards.removeIf(x -> x.getID().equals(sServiceGroupID));
aSummary.onError(EImportSummaryAction.CREATE_SG);
}
if (aNewServiceGroup != null) {
// 3a. create all endpoints
for (final ISMPServiceInformation aImportServiceInfo : aEntry.getValue().getServiceInfo()) {
try {
if (aServiceInfoMgr.mergeSMPServiceInformation(aImportServiceInfo).isSuccess()) {
aLoggerSuccess.accept(sServiceGroupID, "Successfully created Service Information");
aSummary.onSuccess(EImportSummaryAction.CREATE_SI);
} else {
aLoggerErrorPI.accept(sServiceGroupID, "Error creating the new Service Information");
aSummary.onError(EImportSummaryAction.CREATE_SI);
}
} catch (final Exception ex) {
aLoggerErrorPIEx.accept(sServiceGroupID, "Error creating the new Service Information", ex);
aSummary.onError(EImportSummaryAction.CREATE_SI);
}
}
// 3b. create all redirects
for (final ISMPRedirect aImportRedirect : aEntry.getValue().getRedirects()) {
try {
if (aRedirectMgr.createOrUpdateSMPRedirect(aNewServiceGroup, aImportRedirect.getDocumentTypeIdentifier(), aImportRedirect.getTargetHref(), aImportRedirect.getSubjectUniqueIdentifier(), aImportRedirect.getCertificate(), aImportRedirect.getExtensionsAsString()) != null) {
aLoggerSuccess.accept(sServiceGroupID, "Successfully created Redirect");
aSummary.onSuccess(EImportSummaryAction.CREATE_REDIRECT);
} else {
aLoggerErrorPI.accept(sServiceGroupID, "Error creating the new Redirect");
aSummary.onError(EImportSummaryAction.CREATE_REDIRECT);
}
} catch (final Exception ex) {
aLoggerErrorPIEx.accept(sServiceGroupID, "Error creating the new Redirect", ex);
aSummary.onError(EImportSummaryAction.CREATE_REDIRECT);
}
}
}
}
// Note: if PD integration is disabled, the list is empty
for (final Map.Entry<String, ISMPBusinessCard> aEntry : aDeleteBusinessCards.entrySet()) {
final String sServiceGroupID = aEntry.getKey();
final ISMPBusinessCard aDeleteBusinessCard = aEntry.getValue();
try {
if (aBusinessCardMgr.deleteSMPBusinessCard(aDeleteBusinessCard).isChanged()) {
aLoggerSuccess.accept(sServiceGroupID, "Successfully deleted Business Card");
aSummary.onSuccess(EImportSummaryAction.DELETE_BC);
} else {
aSummary.onError(EImportSummaryAction.DELETE_BC);
// was automatically deleted afterwards
if (!aDeletedServiceGroups.contains(aDeleteBusinessCard.getParticipantIdentifier()))
aLoggerErrorPI.accept(sServiceGroupID, "Failed to delete Business Card");
}
} catch (final Exception ex) {
aLoggerErrorPIEx.accept(sServiceGroupID, "Failed to delete Business Card", ex);
aSummary.onError(EImportSummaryAction.DELETE_BC);
}
}
// Note: if PD integration is disabled, the list is empty
for (final ISMPBusinessCard aImportBusinessCard : aImportBusinessCards) {
final String sBusinessCardID = aImportBusinessCard.getID();
try {
if (aBusinessCardMgr.createOrUpdateSMPBusinessCard(aImportBusinessCard.getParticipantIdentifier(), aImportBusinessCard.getAllEntities()) != null) {
aLoggerSuccess.accept(sBusinessCardID, "Successfully created Business Card");
aSummary.onSuccess(EImportSummaryAction.CREATE_BC);
} else {
aLoggerErrorPI.accept(sBusinessCardID, "Failed to create Business Card");
aSummary.onError(EImportSummaryAction.CREATE_BC);
}
} catch (final Exception ex) {
aLoggerErrorPIEx.accept(sBusinessCardID, "Failed to create Business Card", ex);
aSummary.onError(EImportSummaryAction.CREATE_BC);
}
}
}
}
use of com.helger.commons.collection.impl.ICommonsOrderedSet in project peppol-practical by phax.
the class PagePublicToolsParticipantInformation method _queryParticipant.
private void _queryParticipant(@Nonnull final WebPageExecutionContext aWPEC, final String sParticipantIDScheme, final String sParticipantIDValue, final ISMLConfiguration aSMLConfiguration, final boolean bSMLAutoDetect, final boolean bQueryBusinessCard, final boolean bShowTime, final boolean bXSDValidation, final boolean bVerifySignatures) {
final HCNodeList aNodeList = aWPEC.getNodeList();
final Locale aDisplayLocale = aWPEC.getDisplayLocale();
final IRequestWebScopeWithoutResponse aRequestScope = aWPEC.getRequestScope();
final ISMLConfigurationManager aSMLConfigurationMgr = PPMetaManager.getSMLConfigurationMgr();
final String sParticipantIDUriEncoded = CIdentifier.getURIEncoded(sParticipantIDScheme, sParticipantIDValue);
LOGGER.info("Start querying the Participant information of '" + sParticipantIDUriEncoded + "'");
// Try to print the basic information before an error occurs
aNodeList.addChild(div("Querying the following SMP for ").addChild(code(sParticipantIDUriEncoded)).addChild(":"));
final ICommonsList<JAXBException> aSMPExceptions = new CommonsArrayList<>();
try {
SMPQueryParams aQueryParams = null;
ISMLConfiguration aRealSMLConfiguration = aSMLConfiguration;
if (bSMLAutoDetect) {
final ICommonsList<ISMLConfiguration> aSortedList = aSMLConfigurationMgr.getAllSorted();
if (LOGGER.isDebugEnabled())
LOGGER.debug("Sorted SML Configs: " + StringHelper.getImplodedMapped(", ", aSortedList, ISMLConfiguration::getID));
for (final ISMLConfiguration aCurSML : aSortedList) {
aQueryParams = SMPQueryParams.createForSML(aCurSML, sParticipantIDScheme, sParticipantIDValue, false);
if (aQueryParams == null)
continue;
try {
InetAddress.getByName(aQueryParams.getSMPHostURI().getHost());
// Found it
aRealSMLConfiguration = aCurSML;
break;
} catch (final UnknownHostException ex) {
// continue
}
}
// Ensure to go into the exception handler
if (aRealSMLConfiguration == null) {
LOGGER.error("Failed to autodetect a matching SML for '" + sParticipantIDUriEncoded + "'");
aNodeList.addChild(error(div("Seems like the participant ID " + sParticipantIDUriEncoded + " is not known in any of the configured networks.")));
// Audit failure
AuditHelper.onAuditExecuteFailure("participant-information", sParticipantIDUriEncoded, "no-sml-found");
return;
}
LOGGER.info("Participant ID '" + sParticipantIDUriEncoded + "': auto detected SML " + aRealSMLConfiguration.getID());
} else {
// SML configuration is not null
aQueryParams = SMPQueryParams.createForSML(aRealSMLConfiguration, sParticipantIDScheme, sParticipantIDValue, true);
}
if (aQueryParams == null) {
LOGGER.error("Participant ID '" + sParticipantIDUriEncoded + "': failed to resolve SMP query parameters for SML '" + aRealSMLConfiguration.getID() + "'");
aNodeList.addChild(error(div("Failed to resolve participant ID " + sParticipantIDUriEncoded + " for the provided network.")).addChild(bSMLAutoDetect ? null : div("Try selecting a different SML - maybe this helps")));
// Audit failure
AuditHelper.onAuditExecuteFailure("participant-information", sParticipantIDUriEncoded, "smp-query-params-null");
return;
}
LOGGER.info("Participant information of '" + sParticipantIDUriEncoded + "' is queried using SMP API '" + aQueryParams.getSMPAPIType() + "' from '" + aQueryParams.getSMPHostURI() + "' using SML '" + aRealSMLConfiguration + "'; XSD validation=" + bXSDValidation + "; verify signatures=" + bVerifySignatures);
final IParticipantIdentifier aParticipantID = aQueryParams.getParticipantID();
final URL aSMPHost = URLHelper.getAsURL(aQueryParams.getSMPHostURI());
{
if (LOGGER.isDebugEnabled())
LOGGER.debug("Trying to resolve SMP '" + aSMPHost.getHost() + "' by DNS");
final HCUL aUL = new HCUL();
aNodeList.addChild(aUL);
aUL.addItem(div("SML used: ").addChild(code(aRealSMLConfiguration.getDisplayName() + " / " + aRealSMLConfiguration.getDNSZone())).addChild(" ").addChild(aRealSMLConfiguration.isProduction() ? badgeSuccess("production SML") : badgeWarn("test SML")));
aUL.addItem(div("Query API: " + aRealSMLConfiguration.getSMPAPIType().getDisplayName()));
final String sURL1 = aSMPHost.toExternalForm();
aUL.addItem(div("Resolved name: ").addChild(code(sURL1)), div(_createOpenInBrowser(sURL1)));
if (aWPEC.params().hasStringValue("dnsjava", "true")) {
LOGGER.info("Start DNSJava lookup");
Record[] aRecords = null;
try {
aRecords = new Lookup(aSMPHost.getHost(), Type.A).run();
} catch (final TextParseException ex) {
// Ignore
}
if (aRecords != null)
for (final Record aRecord : aRecords) {
final ARecord aARec = (ARecord) aRecord;
final String sURL2 = aARec.rdataToString();
final InetAddress aNice = aARec.getAddress();
final String sURL3 = aNice != null ? aNice.getCanonicalHostName() : null;
final HCDiv aDiv1 = div("[dnsjava] IP addressX: ").addChild(code(sURL2));
if (sURL3 != null)
aDiv1.addChild(" - reverse lookup: ").addChild(code(sURL3));
else
aDiv1.addChild(" - reverse lookup failed");
final HCDiv aDiv2 = div(_createOpenInBrowser("http://" + sURL2, "Open IP in browser"));
if (sURL3 != null)
aDiv2.addChild(" ").addChild(_createOpenInBrowser("http://" + sURL3, "Open name in browser"));
aUL.addItem(aDiv1, aDiv2);
}
LOGGER.info("Finished DNSJava lookup - " + (aRecords == null ? "no results" : aRecords.length + " result records"));
}
try {
final InetAddress[] aInetAddresses = InetAddress.getAllByName(aSMPHost.getHost());
for (final InetAddress aInetAddress : aInetAddresses) {
final String sURL2 = new IPV4Addr(aInetAddress).getAsString();
final InetAddress aNice = InetAddress.getByAddress(aInetAddress.getAddress());
final String sURL3 = aNice.getCanonicalHostName();
aUL.addItem(div("IP address: ").addChild(code(sURL2)).addChild(" - reverse lookup: ").addChild(code(sURL3)), div(_createOpenInBrowser("http://" + sURL2, "Open IP in browser")).addChild(" ").addChild(_createOpenInBrowser("http://" + sURL3, "Open name in browser")));
}
// Show only once
final String sURL4 = sURL1 + (sURL1.endsWith("/") ? "" : "/") + sParticipantIDUriEncoded;
aUL.addItem(div("Query base URL: ").addChild(code(sURL4)), div(_createOpenInBrowser(sURL4)));
if (!bXSDValidation)
aUL.addItem(badgeWarn("XML Schema validation of SMP responses is disabled."));
if (!bVerifySignatures)
aUL.addItem(badgeDanger("Signature verification of SMP responses is disabled."));
} catch (final UnknownHostException ex) {
LOGGER.error("Failed to resolve SMP host '" + aSMPHost.getHost() + "' for the participant ID '" + sParticipantIDUriEncoded + "'");
aNodeList.addChild(error(div("Seems like the participant ID " + sParticipantIDUriEncoded + " is not registered to the selected network.")).addChild(AppCommonUI.getTechnicalDetailsUI(ex, false)).addChild(bSMLAutoDetect ? null : div("Try selecting a different SML - maybe this helps")));
// Audit failure
AuditHelper.onAuditExecuteFailure("participant-information", sParticipantIDUriEncoded, "unknown-host", ex.getMessage());
return;
}
}
// Determine all document types
final ICommonsList<IDocumentTypeIdentifier> aDocTypeIDs = new CommonsArrayList<>();
SMPClientReadOnly aSMPClient = null;
BDXRClientReadOnly aBDXR1Client = null;
final Consumer<GenericJAXBMarshaller<?>> aSMPMarshallerCustomizer = m -> {
aSMPExceptions.clear();
// Remember exceptions
m.readExceptionCallbacks().add(aSMPExceptions::add);
};
try {
final StopWatch aSWGetDocTypes = StopWatch.createdStarted();
final HCUL aSGUL = new HCUL();
final ICommonsSortedMap<String, String> aSGHrefs = new CommonsTreeMap<>();
IHCNode aSGExtension = null;
switch(aQueryParams.getSMPAPIType()) {
case PEPPOL:
{
aSMPClient = new SMPClientReadOnly(aQueryParams.getSMPHostURI());
aSMPClient.setXMLSchemaValidation(bXSDValidation);
aSMPClient.setVerifySignature(bVerifySignatures);
aSMPClient.setMarshallerCustomizer(aSMPMarshallerCustomizer);
// Get all HRefs and sort them by decoded URL
final com.helger.xsds.peppol.smp1.ServiceGroupType aSG = aSMPClient.getServiceGroupOrNull(aParticipantID);
if (aSG != null) {
// Map from cleaned URL to original URL
if (aSG.getServiceMetadataReferenceCollection() != null)
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)
aSGUL.addItem(warn("The ServiceGroup list contains the duplicate URL ").addChild(code(sHref)));
}
if (aSG.getExtension() != null && aSG.getExtension().getAny() != null) {
aSGExtension = new HCPrismJS(EPrismLanguage.MARKUP).addChild(XMLWriter.getNodeAsString(aSG.getExtension().getAny()));
}
}
break;
}
case OASIS_BDXR_V1:
{
aBDXR1Client = new BDXRClientReadOnly(aQueryParams.getSMPHostURI());
aBDXR1Client.setXMLSchemaValidation(bXSDValidation);
aBDXR1Client.setVerifySignature(bVerifySignatures);
aBDXR1Client.setMarshallerCustomizer(aSMPMarshallerCustomizer);
// 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) {
if (aSG.getServiceMetadataReferenceCollection() != null)
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)
aSGUL.addItem(warn("The ServiceGroup list contains the duplicate URL ").addChild(code(sHref)));
}
if (aSG.getExtensionCount() > 0) {
final HCUL aNL2 = new HCUL();
for (final com.helger.xsds.bdxr.smp1.ExtensionType aExt : aSG.getExtension()) if (aExt.getAny() != null) {
if (aExt.getAny() instanceof Element)
aNL2.addItem(new HCPrismJS(EPrismLanguage.MARKUP).addChild(XMLWriter.getNodeAsString((Element) aExt.getAny())));
else
aNL2.addItem(code(aExt.getAny().toString()));
}
if (aNL2.hasChildren())
aSGExtension = aNL2;
}
}
break;
}
}
aSWGetDocTypes.stop();
LOGGER.info("Participant information of '" + aParticipantID.getURIEncoded() + "' returned " + aSGHrefs.size() + " entries");
final HCH3 aH3 = h3("ServiceGroup contents");
if (bShowTime)
aH3.addChild(" ").addChild(_createTimingNode(aSWGetDocTypes.getMillis()));
aNodeList.addChild(aH3);
final String sPathStart = "/" + aParticipantID.getURIEncoded() + "/services/";
// Show all ServiceGroup hrefs
for (final Map.Entry<String, String> aEntry : aSGHrefs.entrySet()) {
final String sHref = aEntry.getKey();
final String sOriginalHref = aEntry.getValue();
final IHCLI<?> aLI = aSGUL.addAndReturnItem(div(code(sHref)));
// Should be case insensitive "indexOf" here
final int nPathStart = sHref.toLowerCase(Locale.US).indexOf(sPathStart.toLowerCase(Locale.US));
if (nPathStart >= 0) {
final String sDocType = sHref.substring(nPathStart + sPathStart.length());
final IDocumentTypeIdentifier aDocType = aQueryParams.getIF().parseDocumentTypeIdentifier(sDocType);
if (aDocType != null) {
aDocTypeIDs.add(aDocType);
aLI.addChild(div(EFontAwesome4Icon.ARROW_RIGHT.getAsNode()).addChild(" ").addChild(AppCommonUI.createDocTypeID(aDocType, false)));
aLI.addChild(div(EFontAwesome4Icon.ARROW_RIGHT.getAsNode()).addChild(" ").addChild(_createOpenInBrowser(sOriginalHref)));
} else {
aLI.addChild(error("The document type ").addChild(code(sDocType)).addChild(" could not be interpreted as a structured document type!"));
}
} else {
aLI.addChild(error().addChildren(div("Contained href does not match the rules!"), div("Found href: ").addChild(code(sHref)), div("Expected path part: ").addChild(code(sPathStart))));
}
}
if (!aSGUL.hasChildren())
aSGUL.addItem(warn("No service group entries were found for " + aParticipantID.getURIEncoded()));
if (aSGExtension != null)
aSGUL.addAndReturnItem(div("Extension:")).addChild(aSGExtension);
aNodeList.addChild(aSGUL);
} catch (final SMPClientException ex) {
if (LOGGER.isDebugEnabled())
LOGGER.debug("Participant DocTypes Error", ex);
else if (LOGGER.isWarnEnabled())
LOGGER.warn("Participant DocTypes Error: " + ex.getClass().getName() + " - " + ex.getMessage());
final BootstrapErrorBox aErrorBox = error(div("Error querying SMP.")).addChild(AppCommonUI.getTechnicalDetailsUI(ex, false));
for (final JAXBException aItem : aSMPExceptions) aErrorBox.addChild(AppCommonUI.getTechnicalDetailsUI(aItem, false));
aNodeList.addChild(aErrorBox);
// Audit failure
AuditHelper.onAuditExecuteFailure("participant-doctypes", sParticipantIDUriEncoded, ex.getClass(), ex.getMessage());
}
// List document type details
if (aDocTypeIDs.isNotEmpty()) {
final OffsetDateTime aNowDateTime = PDTFactory.getCurrentOffsetDateTime();
final ICommonsOrderedSet<X509Certificate> aAllUsedEndpointCertifiactes = new CommonsLinkedHashSet<>();
long nTotalDurationMillis = 0;
aNodeList.addChild(h3("Document type details"));
final HCUL aULDocTypeIDs = new HCUL();
for (final IDocumentTypeIdentifier aDocTypeID : aDocTypeIDs.getSortedInline(IDocumentTypeIdentifier.comparator())) {
final HCDiv aDocTypeDiv = div(AppCommonUI.createDocTypeID(aDocTypeID, true));
final IHCLI<?> aLIDocTypeID = aULDocTypeIDs.addAndReturnItem(aDocTypeDiv);
LOGGER.info("Now SMP querying '" + aParticipantID.getURIEncoded() + "' / '" + aDocTypeID.getURIEncoded() + "'");
final StopWatch aSWGetDetails = StopWatch.createdStarted();
try {
switch(aQueryParams.getSMPAPIType()) {
case PEPPOL:
{
final com.helger.xsds.peppol.smp1.SignedServiceMetadataType aSSM = aSMPClient.getServiceMetadataOrNull(aParticipantID, aDocTypeID);
aSWGetDetails.stop();
if (aSSM != null) {
final com.helger.xsds.peppol.smp1.ServiceMetadataType aSM = aSSM.getServiceMetadata();
if (aSM.getRedirect() != null)
aLIDocTypeID.addChild(div("Redirect to " + aSM.getRedirect().getHref()));
else {
// For all processes
final HCUL aULProcessID = new HCUL();
for (final com.helger.xsds.peppol.smp1.ProcessType aProcess : aSM.getServiceInformation().getProcessList().getProcess()) if (aProcess.getProcessIdentifier() != null) {
final IHCLI<?> aLIProcessID = aULProcessID.addItem();
aLIProcessID.addChild(div("Process ID: ").addChild(AppCommonUI.createProcessID(aDocTypeID, SimpleProcessIdentifier.wrap(aProcess.getProcessIdentifier()))));
final HCUL aULEndpoint = new HCUL();
// For all endpoints of the process
for (final com.helger.xsds.peppol.smp1.EndpointType aEndpoint : aProcess.getServiceEndpointList().getEndpoint()) {
final IHCLI<?> aLIEndpoint = aULEndpoint.addItem();
// Endpoint URL
final String sEndpointRef = aEndpoint.getEndpointReference() == null ? null : W3CEndpointReferenceHelper.getAddress(aEndpoint.getEndpointReference());
_printEndpointURL(aLIEndpoint, sEndpointRef);
// Valid from
_printActivationDate(aLIEndpoint, aEndpoint.getServiceActivationDate(), aDisplayLocale);
// Valid to
_printExpirationDate(aLIEndpoint, aEndpoint.getServiceExpirationDate(), aDisplayLocale);
// Transport profile
_printTransportProfile(aLIEndpoint, aEndpoint.getTransportProfile());
// Technical infos
_printTecInfo(aLIEndpoint, aEndpoint.getTechnicalInformationUrl(), aEndpoint.getTechnicalContactUrl());
// Certificate (also add null values)
final X509Certificate aCert = CertificateHelper.convertStringToCertficateOrNull(aEndpoint.getCertificate());
aAllUsedEndpointCertifiactes.add(aCert);
}
aLIProcessID.addChild(aULEndpoint);
}
aLIDocTypeID.addChild(aULProcessID);
}
} else {
aLIDocTypeID.addChild(error("Failed to read service metadata from SMP (not found)"));
}
break;
}
case OASIS_BDXR_V1:
{
final com.helger.xsds.bdxr.smp1.SignedServiceMetadataType aSSM = aBDXR1Client.getServiceMetadataOrNull(aParticipantID, aDocTypeID);
aSWGetDetails.stop();
if (aSSM != null) {
final com.helger.xsds.bdxr.smp1.ServiceMetadataType aSM = aSSM.getServiceMetadata();
if (aSM.getRedirect() != null)
aLIDocTypeID.addChild(div("Redirect to " + aSM.getRedirect().getHref()));
else {
// For all processes
final HCUL aULProcessID = new HCUL();
for (final com.helger.xsds.bdxr.smp1.ProcessType aProcess : aSM.getServiceInformation().getProcessList().getProcess()) if (aProcess.getProcessIdentifier() != null) {
final IHCLI<?> aLIProcessID = aULProcessID.addItem();
aLIProcessID.addChild(div("Process ID: ").addChild(AppCommonUI.createProcessID(aDocTypeID, SimpleProcessIdentifier.wrap(aProcess.getProcessIdentifier()))));
final HCUL aULEndpoint = new HCUL();
// For all endpoints of the process
for (final com.helger.xsds.bdxr.smp1.EndpointType aEndpoint : aProcess.getServiceEndpointList().getEndpoint()) {
final IHCLI<?> aLIEndpoint = aULEndpoint.addItem();
// Endpoint URL
_printEndpointURL(aLIEndpoint, aEndpoint.getEndpointURI());
// Valid from
_printActivationDate(aLIEndpoint, aEndpoint.getServiceActivationDate(), aDisplayLocale);
// Valid to
_printExpirationDate(aLIEndpoint, aEndpoint.getServiceExpirationDate(), aDisplayLocale);
// Transport profile
_printTransportProfile(aLIEndpoint, aEndpoint.getTransportProfile());
// Technical infos
_printTecInfo(aLIEndpoint, aEndpoint.getTechnicalInformationUrl(), aEndpoint.getTechnicalContactUrl());
// Certificate (also add null values)
try {
final X509Certificate aCert = CertificateHelper.convertByteArrayToCertficateDirect(aEndpoint.getCertificate());
aAllUsedEndpointCertifiactes.add(aCert);
} catch (final CertificateException ex) {
aAllUsedEndpointCertifiactes.add(null);
}
}
aLIProcessID.addChild(aULEndpoint);
}
aLIDocTypeID.addChild(aULProcessID);
}
} else {
aLIDocTypeID.addChild(error("Failed to read service metadata from SMP (not found)"));
}
break;
}
}
} catch (final SMPClientBadResponseException ex) {
if (LOGGER.isDebugEnabled())
LOGGER.debug("Participant Information Error", ex);
else if (LOGGER.isWarnEnabled())
LOGGER.warn("Participant Information Error: " + ex.getClass().getName() + " - " + ex.getMessage());
final BootstrapErrorBox aErrorBox = error(div("Error querying SMP. Try disabling 'XML Schema validation'.")).addChild(AppCommonUI.getTechnicalDetailsUI(ex, false));
for (final JAXBException aItem : aSMPExceptions) aErrorBox.addChild(AppCommonUI.getTechnicalDetailsUI(aItem, false));
aLIDocTypeID.addChild(aErrorBox);
// Audit failure
AuditHelper.onAuditExecuteFailure("participant-information", sParticipantIDUriEncoded, ex.getClass(), ex.getMessage());
} catch (final SMPClientException ex) {
if (LOGGER.isDebugEnabled())
LOGGER.debug("Participant Information Error", ex);
else if (LOGGER.isWarnEnabled())
LOGGER.warn("Participant Information Error: " + ex.getClass().getName() + " - " + ex.getMessage());
final BootstrapErrorBox aErrorBox = error(div("Error querying SMP.")).addChild(AppCommonUI.getTechnicalDetailsUI(ex, false));
for (final JAXBException aItem : aSMPExceptions) aErrorBox.addChild(AppCommonUI.getTechnicalDetailsUI(aItem, false));
aLIDocTypeID.addChild(aErrorBox);
// Audit failure
AuditHelper.onAuditExecuteFailure("participant-information", sParticipantIDUriEncoded, ex.getClass(), ex.getMessage());
}
if (bShowTime)
aDocTypeDiv.addChild(" ").addChild(_createTimingNode(aSWGetDetails.getMillis()));
nTotalDurationMillis += aSWGetDetails.getMillis();
}
aNodeList.addChild(aULDocTypeIDs);
if (bShowTime)
aNodeList.addChild(div("Overall time: ").addChild(_createTimingNode(nTotalDurationMillis)));
aNodeList.addChild(h3("Endpoint Certificate details"));
if (aAllUsedEndpointCertifiactes.isEmpty()) {
aNodeList.addChild(warn("No Endpoint Certificate information was found."));
} else {
final HCUL aULCerts = new HCUL();
for (final X509Certificate aEndpointCert : aAllUsedEndpointCertifiactes) {
final IHCLI<?> aLICert = aULCerts.addItem();
if (aEndpointCert != null) {
aLICert.addChild(div("Subject: " + aEndpointCert.getSubjectX500Principal().getName()));
aLICert.addChild(div("Issuer: " + aEndpointCert.getIssuerX500Principal().getName()));
final OffsetDateTime aNotBefore = PDTFactory.createOffsetDateTime(aEndpointCert.getNotBefore());
aLICert.addChild(div("Not before: " + PDTToString.getAsString(aNotBefore, aDisplayLocale)));
if (aNotBefore.isAfter(aNowDateTime))
aLICert.addChild(error("This Endpoint Certificate is not yet valid!"));
final OffsetDateTime aNotAfter = PDTFactory.createOffsetDateTime(aEndpointCert.getNotAfter());
aLICert.addChild(div("Not after: " + PDTToString.getAsString(aNotAfter, aDisplayLocale)));
if (aNotAfter.isBefore(aNowDateTime))
aLICert.addChild(error("This Endpoint Certificate is no longer valid!"));
aLICert.addChild(div("Serial number: " + aEndpointCert.getSerialNumber().toString() + " / 0x" + _inGroupsOf(aEndpointCert.getSerialNumber().toString(16), 4)));
if (aQueryParams.getSMPAPIType() == ESMPAPIType.PEPPOL) {
// Check Peppol certificate status
final EPeppolCertificateCheckResult eCertStatus = PeppolCertificateChecker.checkPeppolAPCertificate(aEndpointCert, aNowDateTime, ETriState.FALSE, null);
if (eCertStatus.isValid())
aLICert.addChild(success("The Endpoint Certificate appears to be a valid Peppol certificate."));
else {
aLICert.addChild(error().addChild(div("The Endpoint Certificate appears to be an invalid Peppol certificate. Reason: " + eCertStatus.getReason())));
}
}
final HCTextArea aTextArea = new HCTextArea().setReadOnly(true).setRows(4).setValue(CertificateHelper.getPEMEncodedCertificate(aEndpointCert)).addStyle(CCSSProperties.FONT_FAMILY.newValue(CCSSValue.FONT_MONOSPACE));
BootstrapFormHelper.markAsFormControl(aTextArea);
aLICert.addChild(div(aTextArea));
} else {
aLICert.addChild(error("Failed to interpret the data as a X509 certificate"));
}
}
aNodeList.addChild(aULCerts);
}
}
if (bQueryBusinessCard) {
final StopWatch aSWGetBC = StopWatch.createdStarted();
aNodeList.addChild(h3("Business Card details"));
EFamFamFlagIcon.registerResourcesForThisRequest();
final String sBCURL = aSMPHost.toExternalForm() + "/businesscard/" + aParticipantID.getURIEncoded();
LOGGER.info("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;
}
aSWGetBC.stop();
if (aData == null)
aNodeList.addChild(warn("No Business Card is available for that participant."));
else {
final ICommonsList<JAXBException> aPDExceptions = new CommonsArrayList<>();
final Consumer<GenericJAXBMarshaller<?>> aPMarshallerCustomizer = m -> {
aPDExceptions.clear();
// Remember errors
m.readExceptionCallbacks().add(aPDExceptions::add);
m.setCharset(StandardCharsets.UTF_8);
};
final PDBusinessCard aBC = PDBusinessCardHelper.parseBusinessCard(aData, aPMarshallerCustomizer);
if (aBC == null) {
final BootstrapErrorBox aError = error("Failed to parse the response data as a Business Card.");
for (final JAXBException aItem : aPDExceptions) aError.addChild(AppCommonUI.getTechnicalDetailsUI(aItem, false));
aNodeList.addChild(aError);
final String sBC = new String(aData, StandardCharsets.UTF_8);
if (StringHelper.hasText(sBC))
aNodeList.addChild(new HCPrismJS(EPrismLanguage.MARKUP).addChild(sBC));
LOGGER.error("Failed to parse BC:\n" + sBC);
} else {
final HCH4 aH4 = h4("Business Card contains " + (aBC.businessEntities().size() == 1 ? "1 entity" : aBC.businessEntities().size() + " entities"));
if (bShowTime)
aH4.addChild(" ").addChild(_createTimingNode(aSWGetBC.getMillis()));
aNodeList.addChild(aH4);
aNodeList.addChild(div(_createOpenInBrowser(sBCURL)));
final HCUL aUL = new HCUL();
for (final PDBusinessEntity aEntity : aBC.businessEntities()) {
final HCLI aLI = aUL.addItem();
// Name
for (final PDName aName : aEntity.names()) {
final Locale aLanguage = LanguageCache.getInstance().getLanguage(aName.getLanguageCode());
final String sLanguageName = aLanguage == null ? "" : " (" + aLanguage.getDisplayLanguage(aDisplayLocale) + ")";
aLI.addChild(div(aName.getName() + sLanguageName));
}
// Country
{
final String sCountryCode = aEntity.getCountryCode();
final Locale aCountryCode = CountryCache.getInstance().getCountry(sCountryCode);
final String sCountryName = aCountryCode == null ? sCountryCode : aCountryCode.getDisplayCountry(aDisplayLocale) + " (" + sCountryCode + ")";
final EFamFamFlagIcon eIcon = EFamFamFlagIcon.getFromIDOrNull(sCountryCode);
aLI.addChild(div("Country: " + sCountryName + " ").addChild(eIcon == null ? null : eIcon.getAsNode()));
}
// Geo info
if (aEntity.hasGeoInfo()) {
aLI.addChild(div("Geographical information: ").addChildren(HCExtHelper.nl2brList(aEntity.getGeoInfo())));
}
// Additional IDs
if (aEntity.identifiers().isNotEmpty()) {
final BootstrapTable aIDTab = new BootstrapTable().setCondensed(true);
aIDTab.addHeaderRow().addCells("Scheme", "Value");
for (final PDIdentifier aItem : aEntity.identifiers()) {
// Avoid empty rows
if (StringHelper.hasText(aItem.getScheme()) || StringHelper.hasText(aItem.getValue()))
aIDTab.addBodyRow().addCells(aItem.getScheme(), aItem.getValue());
}
if (aIDTab.hasBodyRows())
aLI.addChild(div("Additional identifiers: ").addChild(aIDTab));
}
// Website URLs
if (aEntity.websiteURIs().isNotEmpty()) {
final HCNodeList aWebsites = new HCNodeList();
for (final String sItem : aEntity.websiteURIs()) if (StringHelper.hasText(sItem))
aWebsites.addChild(div(HCA.createLinkedWebsite(sItem)));
if (aWebsites.hasChildren())
aLI.addChild(div("Website URLs: ").addChild(aWebsites));
}
// Contacts
if (aEntity.contacts().isNotEmpty()) {
final BootstrapTable aContactTab = new BootstrapTable().setCondensed(true);
aContactTab.addHeaderRow().addCells("Type", "Name", "Phone", "Email");
for (final PDContact aItem : aEntity.contacts()) {
// Avoid empty rows
if (StringHelper.hasText(aItem.getType()) || StringHelper.hasText(aItem.getName()) || StringHelper.hasText(aItem.getPhoneNumber()) || StringHelper.hasText(aItem.getEmail()))
aContactTab.addBodyRow().addCell(aItem.getType()).addCell(aItem.getName()).addCell(aItem.getPhoneNumber()).addCell(HCA_MailTo.createLinkedEmail(aItem.getEmail()));
}
if (aContactTab.hasBodyRows())
aLI.addChild(div("Contact points: ").addChild(aContactTab));
}
if (aEntity.hasAdditionalInfo()) {
aLI.addChild(div("Additional information: ").addChildren(HCExtHelper.nl2brList(aEntity.getAdditionalInfo())));
}
if (aEntity.hasRegistrationDate()) {
aLI.addChild(div("Registration date: ").addChild(PDTToString.getAsString(aEntity.getRegistrationDate(), aDisplayLocale)));
}
}
aNodeList.addChild(aUL);
}
}
}
// Audit success
AuditHelper.onAuditExecuteSuccess("participant-information", aParticipantID.getURIEncoded());
} catch (final RuntimeException ex) {
if (LOGGER.isDebugEnabled())
LOGGER.debug("Participant Information Error", ex);
else if (LOGGER.isWarnEnabled())
LOGGER.warn("Participant Information Error: " + ex.getClass().getName() + " - " + ex.getMessage());
new InternalErrorBuilder().setRequestScope(aRequestScope).setDisplayLocale(aDisplayLocale).setThrowable(ex).handle();
aNodeList.addChild(error(div("Error querying participant information.")).addChild(AppCommonUI.getTechnicalDetailsUI(ex, true)));
// Audit failure
AuditHelper.onAuditExecuteFailure("participant-information", sParticipantIDUriEncoded, ex.getClass(), ex.getMessage());
}
aNodeList.addChild(new HCHR());
}
Aggregations