use of com.helger.phoss.smp.exception.SMPBadRequestException in project phoss-smp by phax.
the class APIExecutorMigrationOutboundFinalizePut 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 sServiceGroupID = aPathVariables.get(SMPRestFilter.PARAM_SERVICE_GROUP_ID);
final ISMPServerAPIDataProvider aDataProvider = new SMPRestDataProvider(aRequestScope, sServiceGroupID);
// Is the writable API disabled?
if (SMPMetaManager.getSettings().isRESTWritableAPIDisabled()) {
throw new SMPPreconditionFailedException("The writable REST API is disabled. migrationOutboundFinalize will not be executed", aDataProvider.getCurrentURI());
}
final String sLogPrefix = "[REST API Migration-Outbound-Finalize] ";
LOGGER.info(sLogPrefix + "Finalizing outbound migration for Service Group ID '" + sServiceGroupID + "'");
// Only authenticated user may do so
final BasicAuthClientCredentials aBasicAuth = getMandatoryAuth(aRequestScope.headers());
SMPUserManagerPhoton.validateUserCredentials(aBasicAuth);
final ISMPParticipantMigrationManager aParticipantMigrationMgr = SMPMetaManager.getParticipantMigrationMgr();
final ISMPServiceGroupManager aServiceGroupMgr = SMPMetaManager.getServiceGroupMgr();
final IIdentifierFactory aIdentifierFactory = SMPMetaManager.getIdentifierFactory();
final IParticipantIdentifier aServiceGroupID = aIdentifierFactory.parseParticipantIdentifier(sServiceGroupID);
if (aServiceGroupID == null) {
// Invalid identifier
throw SMPBadRequestException.failedToParseSG(sServiceGroupID, aDataProvider.getCurrentURI());
}
// Find matching migration object
final ISMPParticipantMigration aMigration = aParticipantMigrationMgr.getParticipantMigrationOfParticipantID(EParticipantMigrationDirection.OUTBOUND, EParticipantMigrationState.IN_PROGRESS, aServiceGroupID);
if (aMigration == null) {
throw new SMPBadRequestException("Failed to resolve outbound participant migration for Service Group ID '" + sServiceGroupID + "'", aDataProvider.getCurrentURI());
}
// Remember the old state
final String sMigrationID = aMigration.getID();
final EParticipantMigrationState eOldState = aMigration.getState();
// Migrate state
if (aParticipantMigrationMgr.setParticipantMigrationState(sMigrationID, EParticipantMigrationState.MIGRATED).isUnchanged()) {
throw new SMPBadRequestException("The participant migration with ID '" + sMigrationID + "' is already finalized", aDataProvider.getCurrentURI());
}
LOGGER.info(sLogPrefix + "The outbound Participant Migration with ID '" + sMigrationID + "' for '" + sServiceGroupID + "' was successfully finalized!");
try {
// in the SML
if (aServiceGroupMgr.deleteSMPServiceGroup(aServiceGroupID, false).isChanged()) {
LOGGER.info(sLogPrefix + "The SMP Service Group for participant '" + sServiceGroupID + "' was successfully deleted from this SMP (without SML)!");
} else {
throw new SMPBadRequestException("The SMP Service Group for participant '" + sServiceGroupID + "' could not be deleted", aDataProvider.getCurrentURI());
}
} catch (final SMPServerException ex) {
// manager
if (aParticipantMigrationMgr.setParticipantMigrationState(sMigrationID, eOldState).isChanged()) {
LOGGER.warn(sLogPrefix + "Successfully reverted the state of the outbound Participant Migration for '" + sServiceGroupID + "' to " + eOldState + "!");
} else {
// Error in error handling. Yeah
LOGGER.error(sLogPrefix + "Failed to revert the state of the outbound Participant Migration for '" + sServiceGroupID + "' to " + eOldState + "!");
}
throw ex;
}
aUnifiedResponse.setStatus(CHttp.HTTP_OK).disableCaching();
}
use of com.helger.phoss.smp.exception.SMPBadRequestException in project phoss-smp by phax.
the class APIExecutorMigrationOutboundStartPut 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 sServiceGroupID = aPathVariables.get(SMPRestFilter.PARAM_SERVICE_GROUP_ID);
final ISMPServerAPIDataProvider aDataProvider = new SMPRestDataProvider(aRequestScope, sServiceGroupID);
// Is the writable API disabled?
if (SMPMetaManager.getSettings().isRESTWritableAPIDisabled()) {
throw new SMPPreconditionFailedException("The writable REST API is disabled. migrationOutboundStart will not be executed", aDataProvider.getCurrentURI());
}
final String sLogPrefix = "[REST API Migration-Outbound-Start] ";
LOGGER.info(sLogPrefix + "Starting outbound migration for Service Group ID '" + sServiceGroupID + "'");
// Only authenticated user may do so
final BasicAuthClientCredentials aBasicAuth = getMandatoryAuth(aRequestScope.headers());
SMPUserManagerPhoton.validateUserCredentials(aBasicAuth);
final ISMPSettings aSettings = SMPMetaManager.getSettings();
final ISMLInfo aSMLInfo = aSettings.getSMLInfo();
final IIdentifierFactory aIdentifierFactory = SMPMetaManager.getIdentifierFactory();
final ISMPServiceGroupManager aServiceGroupMgr = SMPMetaManager.getServiceGroupMgr();
final ISMPParticipantMigrationManager aParticipantMigrationMgr = SMPMetaManager.getParticipantMigrationMgr();
if (aSMLInfo == null) {
throw new SMPPreconditionFailedException("Currently no SML is available. Please select it in the UI at the 'SMP Settings' page", aDataProvider.getCurrentURI());
}
if (!aSettings.isSMLEnabled()) {
throw new SMPPreconditionFailedException("SML Connection is not enabled hence no participant can be migrated", aDataProvider.getCurrentURI());
}
final IParticipantIdentifier aServiceGroupID = aIdentifierFactory.parseParticipantIdentifier(sServiceGroupID);
if (aServiceGroupID == null) {
// Invalid identifier
throw SMPBadRequestException.failedToParseSG(sServiceGroupID, aDataProvider.getCurrentURI());
}
// Check that service group exists
if (!aServiceGroupMgr.containsSMPServiceGroupWithID(aServiceGroupID)) {
throw new SMPBadRequestException("The Service Group '" + sServiceGroupID + "' does not exist", aDataProvider.getCurrentURI());
}
// Ensure no existing migration is in process
if (aParticipantMigrationMgr.containsOutboundMigrationInProgress(aServiceGroupID)) {
throw new SMPBadRequestException("The outbound Participant Migration of the Service Group '" + sServiceGroupID + "' is already in progress", aDataProvider.getCurrentURI());
}
String sMigrationKey = null;
try {
final ManageParticipantIdentifierServiceCaller aCaller = new ManageParticipantIdentifierServiceCaller(aSMLInfo);
aCaller.setSSLSocketFactory(SMPKeyManager.getInstance().createSSLContext().getSocketFactory());
// Create a random migration key,
// Than call SML
sMigrationKey = aCaller.prepareToMigrate(aServiceGroupID, SMPServerConfiguration.getSMLSMPID());
LOGGER.info(sLogPrefix + "Successfully called prepareToMigrate on SML. Created migration key is '" + sMigrationKey + "'");
} catch (final BadRequestFault | InternalErrorFault | NotFoundFault | UnauthorizedFault | ClientTransportException ex) {
throw new SMPSMLException("Failed to call prepareToMigrate on SML for Service Group '" + sServiceGroupID + "'", ex);
}
// Remember internally
final ISMPParticipantMigration aMigration = aParticipantMigrationMgr.createOutboundParticipantMigration(aServiceGroupID, sMigrationKey);
if (aMigration == null) {
throw new SMPInternalErrorException("Failed to create outbound Participant Migration for '" + sServiceGroupID + "' internally");
}
LOGGER.info(sLogPrefix + "Successfully created outbound Participant Migration with ID '" + aMigration.getID() + "' internally.");
// Build result
final IMicroDocument aResponseDoc = new MicroDocument();
final IMicroElement eRoot = aResponseDoc.appendElement("migrationOutboundResponse");
eRoot.setAttribute("success", true);
eRoot.appendElement(XML_ELEMENT_PARTICIPANT_ID).appendText(sServiceGroupID);
eRoot.appendElement(XML_ELEMENT_MIGRATION_KEY).appendText(sMigrationKey);
final XMLWriterSettings aXWS = new XMLWriterSettings().setIndent(EXMLSerializeIndent.INDENT_AND_ALIGN);
aUnifiedResponse.setContentAndCharset(MicroWriter.getNodeAsString(aResponseDoc, aXWS), aXWS.getCharset()).setMimeType(new MimeType(CMimeType.APPLICATION_XML).addParameter(CMimeType.PARAMETER_NAME_CHARSET, aXWS.getCharset().name())).disableCaching();
}
use of com.helger.phoss.smp.exception.SMPBadRequestException in project phoss-smp by phax.
the class APIExecutorServiceMetadataPut 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 writable API disabled?
if (SMPMetaManager.getSettings().isRESTWritableAPIDisabled()) {
throw new SMPPreconditionFailedException("The writable REST API is disabled. saveServiceRegistration will not be executed", aDataProvider.getCurrentURI());
}
// Parse main payload
final byte[] aPayload = StreamHelper.getAllBytes(aRequestScope.getRequest().getInputStream());
final Document aServiceMetadataDoc = DOMReader.readXMLDOM(aPayload);
if (aServiceMetadataDoc == null) {
throw new SMPBadRequestException("Failed to parse provided payload as XML", aDataProvider.getCurrentURI());
}
final String sDocumentTypeID = aPathVariables.get(SMPRestFilter.PARAM_DOCUMENT_TYPE_ID);
final BasicAuthClientCredentials aBasicAuth = getMandatoryAuth(aRequestScope.headers());
ESuccess eSuccess = ESuccess.FAILURE;
switch(SMPServerConfiguration.getRESTType()) {
case PEPPOL:
{
final com.helger.xsds.peppol.smp1.ServiceMetadataType aServiceMetadata = new SMPMarshallerServiceMetadataType(XML_SCHEMA_VALIDATION).read(aServiceMetadataDoc);
if (aServiceMetadata != null) {
eSuccess = new SMPServerAPI(aDataProvider).saveServiceRegistration(sPathServiceGroupID, sDocumentTypeID, aServiceMetadata, aBasicAuth);
}
break;
}
case OASIS_BDXR_V1:
{
final com.helger.xsds.bdxr.smp1.ServiceMetadataType aServiceMetadata = new BDXR1MarshallerServiceMetadataType(XML_SCHEMA_VALIDATION).read(aServiceMetadataDoc);
if (aServiceMetadata != null) {
eSuccess = new BDXR1ServerAPI(aDataProvider).saveServiceRegistration(sPathServiceGroupID, sDocumentTypeID, aServiceMetadata, aBasicAuth);
}
break;
}
default:
throw new UnsupportedOperationException("Unsupported REST type specified!");
}
if (eSuccess.isFailure())
aUnifiedResponse.setStatus(CHttp.HTTP_INTERNAL_SERVER_ERROR);
else
aUnifiedResponse.setStatus(CHttp.HTTP_OK).disableCaching();
}
use of com.helger.phoss.smp.exception.SMPBadRequestException in project phoss-smp by phax.
the class BusinessCardServerAPI method createBusinessCard.
@Nonnull
public ESuccess createBusinessCard(@Nonnull final String sServiceGroupID, @Nonnull final PDBusinessCard aBusinessCard, @Nonnull final BasicAuthClientCredentials aCredentials) throws SMPServerException {
final String sLog = LOG_PREFIX + "PUT /businesscard/" + sServiceGroupID;
final String sAction = "createBusinessCard";
if (LOGGER.isInfoEnabled())
LOGGER.info(sLog + " ==> " + aBusinessCard);
STATS_COUNTER_INVOCATION.increment(sAction);
try {
// Parse and validate identifier
final IIdentifierFactory aIdentifierFactory = SMPMetaManager.getIdentifierFactory();
final IParticipantIdentifier aServiceGroupID = aIdentifierFactory.parseParticipantIdentifier(sServiceGroupID);
if (aServiceGroupID == null) {
// Invalid identifier
throw SMPBadRequestException.failedToParseSG(sServiceGroupID, m_aAPIProvider.getCurrentURI());
}
final IParticipantIdentifier aPayloadServiceGroupID = aIdentifierFactory.createParticipantIdentifier(aBusinessCard.getParticipantIdentifier().getScheme(), aBusinessCard.getParticipantIdentifier().getValue());
if (!aServiceGroupID.hasSameContent(aPayloadServiceGroupID)) {
// Business identifiers must be equal
throw new SMPBadRequestException("Participant Inconsistency. The URL points to '" + aServiceGroupID.getURIEncoded() + "' whereas the BusinessCard contains '" + aPayloadServiceGroupID.getURIEncoded() + "'", m_aAPIProvider.getCurrentURI());
}
// Retrieve the service group
final ISMPServiceGroupManager aServiceGroupMgr = SMPMetaManager.getServiceGroupMgr();
final ISMPServiceGroup aServiceGroup = aServiceGroupMgr.getSMPServiceGroupOfID(aServiceGroupID);
if (aServiceGroup == null) {
// No such service group (on this server)
throw new SMPNotFoundException("Unknown serviceGroup '" + sServiceGroupID + "'", m_aAPIProvider.getCurrentURI());
}
// Check credentials and verify service group is owned by provided user
final IUser aSMPUser = SMPUserManagerPhoton.validateUserCredentials(aCredentials);
SMPUserManagerPhoton.verifyOwnership(aServiceGroupID, aSMPUser);
final ISMPBusinessCardManager aBusinessCardMgr = SMPMetaManager.getBusinessCardMgr();
if (aBusinessCardMgr == null) {
throw new SMPBadRequestException("This SMP server does not support the BusinessCard API", m_aAPIProvider.getCurrentURI());
}
final ICommonsList<SMPBusinessCardEntity> aEntities = new CommonsArrayList<>();
for (final PDBusinessEntity aEntity : aBusinessCard.businessEntities()) aEntities.add(SMPBusinessCardEntity.createFromGenericObject(aEntity));
if (aBusinessCardMgr.createOrUpdateSMPBusinessCard(aServiceGroup.getParticipantIdentifier(), aEntities) == null) {
if (LOGGER.isWarnEnabled())
LOGGER.warn(sLog + " ERROR");
STATS_COUNTER_ERROR.increment(sAction);
return ESuccess.FAILURE;
}
if (LOGGER.isInfoEnabled())
LOGGER.info(sLog + " SUCCESS");
STATS_COUNTER_SUCCESS.increment(sAction);
return ESuccess.SUCCESS;
} catch (final SMPServerException ex) {
if (LOGGER.isWarnEnabled())
LOGGER.warn(sLog + " ERROR - " + ex.getMessage());
STATS_COUNTER_ERROR.increment(sAction);
throw ex;
}
}
use of com.helger.phoss.smp.exception.SMPBadRequestException in project phoss-smp by phax.
the class SMPServerAPI method saveServiceRegistration.
@Nonnull
public ESuccess saveServiceRegistration(@Nonnull final String sPathServiceGroupID, @Nonnull final String sPathDocumentTypeID, @Nonnull final ServiceMetadataType aServiceMetadata, @Nonnull final BasicAuthClientCredentials aCredentials) throws SMPServerException {
final String sLog = LOG_PREFIX + "PUT /" + sPathServiceGroupID + "/services/" + sPathDocumentTypeID;
final String sAction = "saveServiceRegistration";
if (LOGGER.isInfoEnabled())
LOGGER.info(sLog + " ==> " + aServiceMetadata);
STATS_COUNTER_INVOCATION.increment(sAction);
try {
// Parse provided identifiers
final IIdentifierFactory aIdentifierFactory = SMPMetaManager.getIdentifierFactory();
final IParticipantIdentifier aPathServiceGroupID = aIdentifierFactory.parseParticipantIdentifier(sPathServiceGroupID);
if (aPathServiceGroupID == null) {
// Invalid identifier
throw SMPBadRequestException.failedToParseSG(sPathServiceGroupID, m_aAPIDataProvider.getCurrentURI());
}
final IDocumentTypeIdentifier aPathDocTypeID = aIdentifierFactory.parseDocumentTypeIdentifier(sPathDocumentTypeID);
if (aPathDocTypeID == null) {
// Invalid identifier
throw SMPBadRequestException.failedToParseDocType(sPathDocumentTypeID, m_aAPIDataProvider.getCurrentURI());
}
// May be null for a Redirect!
final ServiceInformationType aServiceInformation = aServiceMetadata.getServiceInformation();
if (aServiceInformation != null) {
// metadata (body) must equal path
if (aServiceInformation.getParticipantIdentifier() == null) {
throw new SMPBadRequestException("Save Service Metadata has inconsistent values.\n" + "Service Information Participant ID: <none>\n" + "URL Parameter value: '" + aPathServiceGroupID.getURIEncoded() + "'", m_aAPIDataProvider.getCurrentURI());
}
final IParticipantIdentifier aPayloadServiceGroupID;
if (aServiceInformation.getParticipantIdentifier() == null) {
// Can happen when tampering with the input data
aPayloadServiceGroupID = null;
} else {
aPayloadServiceGroupID = aIdentifierFactory.createParticipantIdentifier(aServiceInformation.getParticipantIdentifier().getScheme(), aServiceInformation.getParticipantIdentifier().getValue());
}
if (!aPathServiceGroupID.hasSameContent(aPayloadServiceGroupID)) {
// Participant ID in URL must match the one in XML structure
throw new SMPBadRequestException("Save Service Metadata was called with inconsistent values.\n" + "Service Infoformation Participant ID: " + (aPayloadServiceGroupID == null ? "<none>" : "'" + aPayloadServiceGroupID.getURIEncoded() + "'") + "\n" + "URL parameter value: '" + aPathServiceGroupID.getURIEncoded() + "'", m_aAPIDataProvider.getCurrentURI());
}
if (aServiceInformation.getDocumentIdentifier() == null) {
throw new SMPBadRequestException("Save Service Metadata was called with inconsistent values.\n" + "Service Information Document Type ID: <none>\n" + "URL parameter value: '" + aPathDocTypeID.getURIEncoded() + "'", m_aAPIDataProvider.getCurrentURI());
}
final IDocumentTypeIdentifier aPayloadDocTypeID = aIdentifierFactory.createDocumentTypeIdentifier(aServiceInformation.getDocumentIdentifier().getScheme(), aServiceInformation.getDocumentIdentifier().getValue());
if (!aPathDocTypeID.hasSameContent(aPayloadDocTypeID)) {
// Document type ID in URL must match the one in XML structure
throw new SMPBadRequestException("Save Service Metadata was called with inconsistent values.\n" + "Service Information Document Type ID: '" + aPayloadDocTypeID.getURIEncoded() + "'\n" + "URL parameter value: '" + aPathDocTypeID.getURIEncoded() + "'", m_aAPIDataProvider.getCurrentURI());
}
}
// Main save
final IUser aDataUser = SMPUserManagerPhoton.validateUserCredentials(aCredentials);
SMPUserManagerPhoton.verifyOwnership(aPathServiceGroupID, aDataUser);
final ISMPServiceGroupManager aServiceGroupMgr = SMPMetaManager.getServiceGroupMgr();
final ISMPServiceGroup aPathServiceGroup = aServiceGroupMgr.getSMPServiceGroupOfID(aPathServiceGroupID);
if (aPathServiceGroup == null) {
// Service group not found
throw new SMPNotFoundException("Service Group '" + sPathServiceGroupID + "' is not on this SMP", m_aAPIDataProvider.getCurrentURI());
}
if (aServiceMetadata.getRedirect() != null) {
// Handle redirect
final ISMPRedirectManager aRedirectMgr = SMPMetaManager.getRedirectMgr();
// not available in Peppol mode
final X509Certificate aCertificate = null;
if (aRedirectMgr.createOrUpdateSMPRedirect(aPathServiceGroup, aPathDocTypeID, aServiceMetadata.getRedirect().getHref(), aServiceMetadata.getRedirect().getCertificateUID(), aCertificate, SMPExtensionConverter.convertToString(aServiceMetadata.getRedirect().getExtension())) == null) {
if (LOGGER.isErrorEnabled())
LOGGER.error(sLog + " - ERROR - Redirect");
STATS_COUNTER_ERROR.increment(sAction);
return ESuccess.FAILURE;
}
if (LOGGER.isInfoEnabled())
LOGGER.info(sLog + " SUCCESS - Redirect");
} else if (aServiceInformation != null) {
// Handle service information
final ProcessListType aJAXBProcesses = aServiceInformation.getProcessList();
final ICommonsList<SMPProcess> aProcesses = new CommonsArrayList<>();
for (final ProcessType aJAXBProcess : aJAXBProcesses.getProcess()) {
final ICommonsList<SMPEndpoint> aEndpoints = new CommonsArrayList<>();
for (final EndpointType aJAXBEndpoint : aJAXBProcess.getServiceEndpointList().getEndpoint()) {
final SMPEndpoint aEndpoint = new SMPEndpoint(aJAXBEndpoint.getTransportProfile(), W3CEndpointReferenceHelper.getAddress(aJAXBEndpoint.getEndpointReference()), aJAXBEndpoint.isRequireBusinessLevelSignature(), aJAXBEndpoint.getMinimumAuthenticationLevel(), aJAXBEndpoint.getServiceActivationDate(), aJAXBEndpoint.getServiceExpirationDate(), aJAXBEndpoint.getCertificate(), aJAXBEndpoint.getServiceDescription(), aJAXBEndpoint.getTechnicalContactUrl(), aJAXBEndpoint.getTechnicalInformationUrl(), SMPExtensionConverter.convertToString(aJAXBEndpoint.getExtension()));
aEndpoints.add(aEndpoint);
}
final SMPProcess aProcess = new SMPProcess(SimpleProcessIdentifier.wrap(aJAXBProcess.getProcessIdentifier()), aEndpoints, SMPExtensionConverter.convertToString(aJAXBProcess.getExtension()));
aProcesses.add(aProcess);
}
final ISMPServiceInformationManager aServiceInfoMgr = SMPMetaManager.getServiceInformationMgr();
final String sExtensionXML = SMPExtensionConverter.convertToString(aServiceInformation.getExtension());
if (aServiceInfoMgr.mergeSMPServiceInformation(new SMPServiceInformation(aPathServiceGroup, aPathDocTypeID, aProcesses, sExtensionXML)).isFailure()) {
if (LOGGER.isErrorEnabled())
LOGGER.error(sLog + " - ERROR - ServiceInformation");
STATS_COUNTER_ERROR.increment(sAction);
return ESuccess.FAILURE;
}
if (LOGGER.isInfoEnabled())
LOGGER.info(sLog + " SUCCESS - ServiceInformation");
} else {
throw new SMPBadRequestException("Save Service Metadata was called with neither a Redirect nor a ServiceInformation", m_aAPIDataProvider.getCurrentURI());
}
if (false)
if (LOGGER.isInfoEnabled())
LOGGER.info(sLog + " SUCCESS");
STATS_COUNTER_SUCCESS.increment(sAction);
return ESuccess.SUCCESS;
} catch (final SMPServerException ex) {
if (LOGGER.isWarnEnabled())
LOGGER.warn(sLog + " ERROR - " + ex.getMessage());
STATS_COUNTER_ERROR.increment(sAction);
throw ex;
}
}
Aggregations