use of com.helger.phoss.smp.exchange.ImportActionItem in project phoss-smp by phax.
the class PageSecureServiceGroupImport method fillContent.
@Override
protected void fillContent(@Nonnull final WebPageExecutionContext aWPEC) {
final HCNodeList aNodeList = aWPEC.getNodeList();
final Locale aDisplayLocale = aWPEC.getDisplayLocale();
final ISMPSettings aSettings = SMPMetaManager.getSettings();
final ISMPServiceGroupManager aServiceGroupMgr = SMPMetaManager.getServiceGroupMgr();
final ISMPBusinessCardManager aBusinessCardMgr = SMPMetaManager.getBusinessCardMgr();
final IUserManager aUserMgr = PhotonSecurityManager.getUserMgr();
final ICommonsSet<String> aAllServiceGroupIDs = aServiceGroupMgr.getAllSMPServiceGroupIDs();
final ICommonsSet<String> aAllBusinessCardIDs = aBusinessCardMgr.getAllSMPBusinessCardIDs();
final FormErrorList aFormErrors = new FormErrorList();
final HCUL aImportResultUL = new HCUL();
if (aWPEC.hasAction(CPageParam.ACTION_PERFORM)) {
// Start import
final IFileItem aImportFile = aWPEC.params().getAsFileItem(FIELD_IMPORT_FILE);
final boolean bOverwriteExisting = aWPEC.params().isCheckBoxChecked(FIELD_OVERWRITE_EXISTING, DEFAULT_OVERWRITE_EXISTING);
final String sDefaultOwnerID = aWPEC.params().getAsString(FIELD_DEFAULT_OWNER);
final IUser aDefaultOwner = aUserMgr.getActiveUserOfID(sDefaultOwnerID);
if (aImportFile == null || aImportFile.getSize() == 0)
aFormErrors.addFieldError(FIELD_IMPORT_FILE, "A file to import must be selected!");
if (StringHelper.hasNoText(sDefaultOwnerID))
aFormErrors.addFieldError(FIELD_DEFAULT_OWNER, "A default owner must be selected!");
else if (aDefaultOwner == null)
aFormErrors.addFieldError(FIELD_DEFAULT_OWNER, "A valid default owner must be selected!");
if (aFormErrors.isEmpty()) {
final SAXReaderSettings aSRS = new SAXReaderSettings();
final IMicroDocument aDoc = MicroReader.readMicroXML(aImportFile, aSRS);
if (aDoc == null || aDoc.getDocumentElement() == null)
aFormErrors.addFieldError(FIELD_IMPORT_FILE, "The provided file is not a valid XML file!");
else {
// Start interpreting
final String sVersion = aDoc.getDocumentElement().getAttributeValue(CSMPExchange.ATTR_VERSION);
if (CSMPExchange.VERSION_10.equals(sVersion)) {
// Version 1.0
final ICommonsList<ImportActionItem> aActionList = new CommonsArrayList<>();
final ImportSummary aImportSummary = new ImportSummary();
ServiceGroupImport.importXMLVer10(aDoc.getDocumentElement(), bOverwriteExisting, aDefaultOwner, aAllServiceGroupIDs, aAllBusinessCardIDs, aActionList, aImportSummary);
for (final ImportActionItem aAction : aActionList) {
final IErrorLevel aErrorLevel = aAction.getErrorLevel();
final EBootstrapBadgeType eBadgeType;
if (aErrorLevel.isGE(EErrorLevel.ERROR))
eBadgeType = EBootstrapBadgeType.DANGER;
else if (aErrorLevel.isGE(EErrorLevel.WARN))
eBadgeType = EBootstrapBadgeType.WARNING;
else if (aErrorLevel.isGE(EErrorLevel.INFO))
eBadgeType = EBootstrapBadgeType.INFO;
else
eBadgeType = EBootstrapBadgeType.SUCCESS;
// By default is is centered
aImportResultUL.addItem(new BootstrapBadge(eBadgeType).addChild((aAction.hasParticipantID() ? "[" + aAction.getParticipantID() + "] " : "") + aAction.getMessage()).addChild(SMPCommonUI.getTechnicalDetailsUI(aAction.getLinkedException())).addClass(CBootstrapCSS.TEXT_LEFT));
}
} else {
// Unsupported or no version present
if (sVersion == null)
aFormErrors.addFieldError(FIELD_IMPORT_FILE, "The provided file cannot be imported because it has the wrong layout.");
else
aFormErrors.addFieldError(FIELD_IMPORT_FILE, "The provided file contains the unsupported version '" + sVersion + "'.");
}
}
}
}
final boolean bHandleBusinessCards = aSettings.isDirectoryIntegrationEnabled();
if (aImportResultUL.hasChildren()) {
final BootstrapCard aPanel = new BootstrapCard();
aPanel.createAndAddHeader().addChild("Import results");
aPanel.createAndAddBody().addChild(aImportResultUL);
aNodeList.addChild(aPanel);
}
aNodeList.addChild(info("Import service groups incl. all endpoints" + (bHandleBusinessCards ? " and business cards" : "") + " from a file."));
final BootstrapForm aForm = aNodeList.addAndReturnChild(getUIHandler().createFormFileUploadSelf(aWPEC));
aForm.addFormGroup(new BootstrapFormGroup().setLabelMandatory("File to import").setCtrl(new BootstrapFileUpload(FIELD_IMPORT_FILE, aDisplayLocale)).setErrorList(aFormErrors.getListOfField(FIELD_IMPORT_FILE)));
aForm.addFormGroup(new BootstrapFormGroup().setLabel("Overwrite existing elements").setCtrl(new HCCheckBox(new RequestFieldBoolean(FIELD_OVERWRITE_EXISTING, DEFAULT_OVERWRITE_EXISTING))).setHelpText("If this box is checked, all existing endpoints etc. of a service group are deleted and new endpoints are created! If the " + SMPWebAppConfiguration.getDirectoryName() + " integration is enabled, existing business cards contained in the import are also overwritten!").setErrorList(aFormErrors.getListOfField(FIELD_OVERWRITE_EXISTING)));
aForm.addFormGroup(new BootstrapFormGroup().setLabelMandatory("Owner of the new service groups").setCtrl(new HCUserSelect(new RequestField(FIELD_DEFAULT_OWNER), aDisplayLocale)).setHelpText("This owner is only selected, if the owner contained in the import file is unknown.").setErrorList(aFormErrors.getListOfField(FIELD_DEFAULT_OWNER)));
final BootstrapButtonToolbar aToolbar = aForm.addAndReturnChild(getUIHandler().createToolbar(aWPEC));
aToolbar.addHiddenField(CPageParam.PARAM_ACTION, CPageParam.ACTION_PERFORM);
aToolbar.addChild(new BootstrapSubmitButton().addChild("Import Service Groups").setIcon(EDefaultIcon.ADD));
}
use of com.helger.phoss.smp.exchange.ImportActionItem in project phoss-smp by phax.
the class APIExecutorImportXMLVer1 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 ISMPServerAPIDataProvider aDataProvider = new SMPRestDataProvider(aRequestScope, null);
// Is the writable API disabled?
if (SMPMetaManager.getSettings().isRESTWritableAPIDisabled()) {
throw new SMPPreconditionFailedException("The writable REST API is disabled. importServiceGroups will not be executed", aDataProvider.getCurrentURI());
}
final String sLogPrefix = "[REST API Import-XML-V1] ";
final String sPathUserLoginName = aPathVariables.get(SMPRestFilter.PARAM_USER_ID);
LOGGER.info(sLogPrefix + "Starting Import");
// Only authenticated user may do so
final BasicAuthClientCredentials aBasicAuth = getMandatoryAuth(aRequestScope.headers());
SMPUserManagerPhoton.validateUserCredentials(aBasicAuth);
// Start action after authentication
final ISMPServiceGroupManager aServiceGroupMgr = SMPMetaManager.getServiceGroupMgr();
final ISMPBusinessCardManager aBusinessCardMgr = SMPMetaManager.getBusinessCardMgr();
final IUserManager aUserMgr = PhotonSecurityManager.getUserMgr();
final ICommonsSet<String> aAllServiceGroupIDs = aServiceGroupMgr.getAllSMPServiceGroupIDs();
final ICommonsSet<String> aAllBusinessCardIDs = aBusinessCardMgr.getAllSMPBusinessCardIDs();
// Try to use ID or login name
IUser aDefaultOwner = aUserMgr.getUserOfID(sPathUserLoginName);
if (aDefaultOwner == null)
aDefaultOwner = aUserMgr.getUserOfLoginName(sPathUserLoginName);
if (aDefaultOwner == null || aDefaultOwner.isDeleted()) {
// Setting the owner to a disabled user might make sense
throw new SMPBadRequestException(sLogPrefix + "The user ID or login name '" + sPathUserLoginName + "' does not exist", aDataProvider.getCurrentURI());
}
LOGGER.info(sLogPrefix + "Using '" + aDefaultOwner.getID() + "' / '" + aDefaultOwner.getLoginName() + "' as the default owner");
final boolean bOverwriteExisting = aRequestScope.params().getAsBoolean(PARAM_OVERVWRITE_EXISTING, DEFAULT_OVERWRITE_EXISTING);
final byte[] aPayload = StreamHelper.getAllBytes(aRequestScope.getRequest().getInputStream());
final IMicroDocument aDoc = MicroReader.readMicroXML(aPayload);
if (aDoc == null || aDoc.getDocumentElement() == null) {
// Cannot parse
throw new SMPBadRequestException("Failed to parse XML payload", aDataProvider.getCurrentURI());
}
final String sVersion = aDoc.getDocumentElement().getAttributeValue(CSMPExchange.ATTR_VERSION);
if (!CSMPExchange.VERSION_10.equals(sVersion)) {
throw new SMPBadRequestException("The provided payload is not an XML file version 1.0", aDataProvider.getCurrentURI());
}
// Version 1.0
LOGGER.info(sLogPrefix + "The provided payload is an XML file version 1.0");
final ZonedDateTime aQueryDT = PDTFactory.getCurrentZonedDateTimeUTC();
final StopWatch aSW = StopWatch.createdStarted();
// Start the import
final ICommonsList<ImportActionItem> aActionList = new CommonsArrayList<>();
final ImportSummary aImportSummary = new ImportSummary();
ServiceGroupImport.importXMLVer10(aDoc.getDocumentElement(), bOverwriteExisting, aDefaultOwner, aAllServiceGroupIDs, aAllBusinessCardIDs, aActionList, aImportSummary);
aSW.stop();
LOGGER.info(sLogPrefix + "Finished import after " + aSW.getMillis() + " milliseconds");
// Everything added to the action list is already logged
final boolean bResponseAsXML = true;
if (bResponseAsXML) {
// Create XML version
final IMicroDocument aResponseDoc = new MicroDocument();
final IMicroElement eRoot = aResponseDoc.appendElement("importResult");
eRoot.setAttribute("version", "1");
eRoot.setAttribute("importStartDateTime", PDTWebDateHelper.getAsStringXSD(aQueryDT));
final IMicroElement eSettings = eRoot.appendElement("settings");
eSettings.setAttribute("overwriteExisting", bOverwriteExisting);
eSettings.setAttribute("defaultOwnerID", aDefaultOwner.getID());
eSettings.setAttribute("defaultOwnerLoginName", aDefaultOwner.getLoginName());
final ICommonsMap<String, MutableInt> aErrorLevelCount = new CommonsTreeMap<>();
for (final ImportActionItem aAction : aActionList) {
eRoot.appendChild(aAction.getAsMicroElement("action"));
aErrorLevelCount.computeIfAbsent(aAction.getErrorLevelName(), k -> new MutableInt(0)).inc();
}
{
final IMicroElement eSummary = eRoot.appendElement("summary");
eSummary.setAttribute("durationMillis", aSW.getMillis());
for (final Map.Entry<String, MutableInt> aEntry : aErrorLevelCount.entrySet()) eSummary.appendElement("errorlevel").setAttribute("id", aEntry.getKey()).setAttribute("count", aEntry.getValue().intValue());
aImportSummary.appendTo(eSummary);
}
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()));
} else {
// Create JSON version
final IJsonObject aJson = new JsonObject();
aJson.add("version", "1");
aJson.add("importStartDateTime", DateTimeFormatter.ISO_ZONED_DATE_TIME.format(aQueryDT));
aJson.addJson("settings", new JsonObject().add("overwriteExisting", bOverwriteExisting).add("defaultOwnerID", aDefaultOwner.getID()).add("defaultOwnerLoginName", aDefaultOwner.getLoginName()));
final IJsonArray aActions = new JsonArray();
final ICommonsMap<String, MutableInt> aLevelCount = new CommonsTreeMap<>();
for (final ImportActionItem aAction : aActionList) {
aActions.add(aAction.getAsJsonObject());
aLevelCount.computeIfAbsent(aAction.getErrorLevelName(), k -> new MutableInt(0)).inc();
}
aJson.addJson("actions", aActions);
{
final IJsonObject aSummary = new JsonObject();
aSummary.add("durationMillis", aSW.getMillis());
final IJsonArray aLevels = new JsonArray();
for (final Map.Entry<String, MutableInt> aEntry : aLevelCount.entrySet()) aLevels.add(new JsonObject().add("id", aEntry.getKey()).add("count", aEntry.getValue().intValue()));
aSummary.addJson("errorlevels", aLevels);
aImportSummary.appendTo(aSummary);
aJson.addJson("summary", aSummary);
}
final String sRet = new JsonWriter(JsonWriterSettings.DEFAULT_SETTINGS_FORMATTED).writeAsString(aJson);
aUnifiedResponse.setContentAndCharset(sRet, StandardCharsets.UTF_8).setMimeType(CMimeType.APPLICATION_JSON);
}
aUnifiedResponse.disableCaching();
}
Aggregations