diff --git a/.github/workflows/githubactions.yml b/.github/workflows/githubactions.yml index 948265dd03..8ab0c56a54 100644 --- a/.github/workflows/githubactions.yml +++ b/.github/workflows/githubactions.yml @@ -1,22 +1,12 @@ -# ----------------------------------------------------------------------------- -# Copyright Siemens AG, 2021. -# Part of the SW360 Portal Project. -# -# This program and the accompanying materials are made -# available under the terms of the Eclipse Public License 2.0 -# which is available at https://www.eclipse.org/legal/epl-2.0/ -# -# SPDX-License-Identifier: EPL-2.0 -# -# ----------------------------------------------------------------------------- +name: SW360 -name: SW360 - -on: +on: push: - branches: [ master ] - pull_request: - branches: [ master ] + branches: [ dev/feature-edit_and_clone_obligation ] + + #UTC + schedule: + - cron: '0 0 * * *' env: COUCHDB_USER: admin @@ -28,11 +18,7 @@ jobs: steps: - uses: actions/checkout@v2 - - name: Set up JDK 11 - uses: actions/setup-java@v2 - with: - java-version: '11' - distribution: 'adopt' + - name: Setup CouchDB uses: iamssen/couchdb-github-action@master with: @@ -46,10 +32,22 @@ jobs: sudo mkdir /etc/sw360 sudo cp ./scripts/sw360BackendRestDockerConfig/etc_sw360/couchdb-test.properties /etc/sw360/ - - name: Verify license headers + - name: Check property file + run: cat build-configuration/test-resources/couchdb-test.properties + + - name: Test endpoint run: | - chmod +x .github/testForLicenseHeaders.sh - bash .github/testForLicenseHeaders.sh + curl -f http://127.0.0.1:5984/ + + - name: Test auth + run: | + curl -X POST -H "Content-Type: application/json; charset=utf-8" -d '{"name": "${COUCHDB_USER}", "password": "${COUCHDB_PASSWORD}"}' http://127.0.0.1:5984/_session + + - name: Set up JDK 11 + uses: actions/setup-java@v2 + with: + java-version: '11' + distribution: 'adopt' - name: Install Thrift and mkdocs run: | diff --git a/backend/src-common/src/main/java/org/eclipse/sw360/datahandler/db/ChangeLogsDatabaseHandler.java b/backend/src-common/src/main/java/org/eclipse/sw360/datahandler/db/ChangeLogsDatabaseHandler.java index d522197740..13eb4b284c 100644 --- a/backend/src-common/src/main/java/org/eclipse/sw360/datahandler/db/ChangeLogsDatabaseHandler.java +++ b/backend/src-common/src/main/java/org/eclipse/sw360/datahandler/db/ChangeLogsDatabaseHandler.java @@ -27,6 +27,7 @@ import org.eclipse.sw360.datahandler.thrift.changelogs.ChangedFields; import org.eclipse.sw360.datahandler.thrift.changelogs.Operation; import org.eclipse.sw360.datahandler.thrift.users.User; +import org.eclipse.sw360.datahandler.thrift.RequestStatus; import com.cloudant.client.api.CloudantClient; import com.google.common.collect.ImmutableSet; @@ -70,6 +71,17 @@ public ChangeLogs getChangeLogsById(String id) throws SW360Exception { return changeLogs; } + public RequestStatus deleteChangeLogsByDocumentId(String docId, User user) { + try { + for (ChangeLogs changeLog: getChangeLogsByDocumentId(user, docId)) { + changeLogsRepository.remove(changeLog); + } + return RequestStatus.SUCCESS; + } catch (Exception e) { + return RequestStatus.FAILURE; + } + } + private ChangeLogs removeNullToEmtpyChanges(ChangeLogs changeLog) { Set changes = changeLog.getChanges(); if (CommonUtils.isNotEmpty(changes)) { diff --git a/backend/src-common/src/main/java/org/eclipse/sw360/datahandler/db/DatabaseHandlerUtil.java b/backend/src-common/src/main/java/org/eclipse/sw360/datahandler/db/DatabaseHandlerUtil.java index 70172254cf..37a24af415 100644 --- a/backend/src-common/src/main/java/org/eclipse/sw360/datahandler/db/DatabaseHandlerUtil.java +++ b/backend/src-common/src/main/java/org/eclipse/sw360/datahandler/db/DatabaseHandlerUtil.java @@ -74,6 +74,7 @@ import org.eclipse.sw360.datahandler.couchdb.DatabaseMixInForChangeLog.ProjectReleaseRelationshipMixin; import org.eclipse.sw360.datahandler.couchdb.DatabaseMixInForChangeLog.RepositoryMixin; import org.eclipse.sw360.datahandler.couchdb.DatabaseMixInForChangeLog.VendorMixin; +import org.eclipse.sw360.datahandler.couchdb.DatabaseMixInForChangeLog.ObligationMixin; import org.eclipse.sw360.datahandler.thrift.ProjectReleaseRelationship; import org.eclipse.sw360.datahandler.thrift.RequestStatus; import org.eclipse.sw360.datahandler.thrift.SW360Exception; @@ -98,6 +99,7 @@ import org.eclipse.sw360.datahandler.thrift.users.RequestedAction; import org.eclipse.sw360.datahandler.thrift.users.User; import org.eclipse.sw360.datahandler.thrift.vendors.Vendor; +import org.eclipse.sw360.datahandler.thrift.licenses.Obligation; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; @@ -402,6 +404,11 @@ public static void trimStringFields(T obj, List listOfStrFields) { changeLog.setDocumentId(newProjVer.getId()); changeLog.setDocumentType(newProjVer.getType()); changeLog.setDbName(DatabaseSettings.COUCH_DB_DATABASE); + } else if (newDocVersion instanceof Obligation) { + Obligation newProjVer = (Obligation) newDocVersion; + changeLog.setDocumentId(newProjVer.getId()); + changeLog.setDocumentType(newProjVer.getType()); + changeLog.setDbName(DatabaseSettings.COUCH_DB_DATABASE); } log.info("Initialize ChangeLogs for Document Id : " + changeLog.getDocumentId()); @@ -574,6 +581,8 @@ private static void changeLogsForNewlyCreatedOrDeleted(T newor fields = Release._Fields.values(); } else if (neworDeletedVersion instanceof ModerationRequest) { fields = ModerationRequest._Fields.values(); + } else if (neworDeletedVersion instanceof Obligation) { + fields = Obligation._Fields.values(); } else { return; } @@ -598,6 +607,8 @@ private static void changeLogsForNewlyCreatedOrDeleted(T newor fields = Release._Fields.values(); } else if (newVersion instanceof ModerationRequest) { fields = ModerationRequest._Fields.values(); + } else if (newVersion instanceof Obligation) { + fields = Obligation._Fields.values(); } else { return; } @@ -812,6 +823,7 @@ private static ObjectMapper initAndGetObjectMapper() { mapper.addMixInAnnotations(Repository.class, RepositoryMixin.class); mapper.addMixInAnnotations(ProjectProjectRelationship.class, ProjectProjectRelationshipMixin.class); mapper.addMixInAnnotations(ProjectReleaseRelationship.class, ProjectReleaseRelationshipMixin.class); + mapper.addMixInAnnotations(Obligation.class, ObligationMixin.class); } return mapper; } diff --git a/backend/src/src-changelogs/src/main/java/org/eclipse/sw360/changelogs/ChangeLogsHandler.java b/backend/src/src-changelogs/src/main/java/org/eclipse/sw360/changelogs/ChangeLogsHandler.java index 03408fffe8..89d4485ba1 100644 --- a/backend/src/src-changelogs/src/main/java/org/eclipse/sw360/changelogs/ChangeLogsHandler.java +++ b/backend/src/src-changelogs/src/main/java/org/eclipse/sw360/changelogs/ChangeLogsHandler.java @@ -24,6 +24,7 @@ import org.eclipse.sw360.datahandler.thrift.changelogs.ChangeLogs; import org.eclipse.sw360.datahandler.thrift.changelogs.ChangeLogsService; import org.eclipse.sw360.datahandler.thrift.users.User; +import org.eclipse.sw360.datahandler.thrift.RequestStatus; import com.cloudant.client.api.CloudantClient; @@ -56,4 +57,11 @@ public ChangeLogs getChangeLogsById(String id) throws SW360Exception { assertNotEmpty(id); return handler.getChangeLogsById(id); } + + @Override + public RequestStatus deleteChangeLogsByDocumentId(String docId, User user) throws SW360Exception { + assertNotEmpty(docId); + assertUser(user); + return handler.deleteChangeLogsByDocumentId(docId, user); + } } \ No newline at end of file diff --git a/backend/src/src-licenses/src/main/java/org/eclipse/sw360/licenses/LicenseHandler.java b/backend/src/src-licenses/src/main/java/org/eclipse/sw360/licenses/LicenseHandler.java index 94bb08567d..3d8bbd3d7b 100644 --- a/backend/src/src-licenses/src/main/java/org/eclipse/sw360/licenses/LicenseHandler.java +++ b/backend/src/src-licenses/src/main/java/org/eclipse/sw360/licenses/LicenseHandler.java @@ -356,4 +356,14 @@ public List searchObligationElement(String text) throws TExce return searchHandler.search(text); } + @Override + public String convertTextToNode(Obligation obligation, User user) throws TException { + String node= handler.convertTextToNodes(obligation,user); + return node; + } + + @Override + public String updateObligation(Obligation oblig, User user) throws TException { + return handler.updateObligation(oblig, user); + } } diff --git a/backend/src/src-licenses/src/main/java/org/eclipse/sw360/licenses/db/LicenseDatabaseHandler.java b/backend/src/src-licenses/src/main/java/org/eclipse/sw360/licenses/db/LicenseDatabaseHandler.java index b145dbfb3e..71d8ffdcc3 100644 --- a/backend/src/src-licenses/src/main/java/org/eclipse/sw360/licenses/db/LicenseDatabaseHandler.java +++ b/backend/src/src-licenses/src/main/java/org/eclipse/sw360/licenses/db/LicenseDatabaseHandler.java @@ -10,6 +10,7 @@ */ package org.eclipse.sw360.licenses.db; +import org.apache.xmlbeans.impl.xb.xsdschema.Attribute; import org.eclipse.sw360.components.summary.SummaryType; import org.eclipse.sw360.datahandler.cloudantclient.DatabaseConnectorCloudant; import org.eclipse.sw360.datahandler.cloudantclient.DatabaseRepositoryCloudantClient; @@ -39,6 +40,7 @@ import com.cloudant.client.api.CloudantClient; import com.cloudant.client.api.model.Response; import com.google.common.collect.Sets; +import static com.google.common.base.Strings.isNullOrEmpty; import java.net.MalformedURLException; import java.sql.Timestamp; @@ -54,6 +56,11 @@ import com.liferay.portal.kernel.json.JSONFactoryUtil; import com.liferay.portal.kernel.json.JSONArray; +import org.eclipse.sw360.datahandler.db.DatabaseHandlerUtil; +import org.eclipse.sw360.datahandler.thrift.changelogs.Operation; +import com.google.common.collect.Lists; +import org.eclipse.sw360.datahandler.common.DatabaseSettings; + /** * Class for accessing the CouchDB database * @@ -77,6 +84,7 @@ public class LicenseDatabaseHandler { private final LicenseModerator moderator; private final CustomPropertiesRepository customPropertiesRepository; private final DatabaseRepositoryCloudantClient[] repositories; + private DatabaseHandlerUtil dbHandlerUtil; private static boolean IMPORT_STATUS = false; private static long IMPORT_TIME = 0; @@ -87,6 +95,8 @@ public class LicenseDatabaseHandler { public LicenseDatabaseHandler(Supplier httpClient, String dbName) throws MalformedURLException { // Create the connector db = new DatabaseConnectorCloudant(httpClient, dbName); + DatabaseConnectorCloudant dbChangelogs = new DatabaseConnectorCloudant(httpClient, DatabaseSettings.COUCH_DB_CHANGE_LOGS); + dbHandlerUtil = new DatabaseHandlerUtil(dbChangelogs); // Create the repository licenseRepository = new LicenseRepository(db); @@ -217,11 +227,43 @@ public String addObligations(@NotNull Obligation obligs, User user) throws SW360 return null; } prepareTodo(obligs); + List obligations = getObligations(); + for (Obligation obligation : obligations) { + if (obligation.getTitle().equals(obligs.getTitle())) { + log.error("An Obligation with the same title already exists."); + return null; + } + } obligRepository.add(obligs); + obligs.setNode(null); + Obligation obligTmp = new Obligation(); + obligTmp.setDevelopment(false) + .setDistribution(false) + .setId(obligs.getId()); + dbHandlerUtil.addChangeLogs(obligs, obligTmp, user.getEmail(), Operation.CREATE, null, Lists.newArrayList(), null, null); return obligs.getId(); } + /** + * Update a existed obligation to the database. + * + * @return ID of the added obligations. + */ + public String updateObligation(@NotNull Obligation oblig, User user) throws SW360Exception { + if (!PermissionUtils.isUserAtLeast(UserGroup.CLEARING_ADMIN, user)){ + return null; + } + Obligation oldObligation = getObligationsById(oblig.getId()); + prepareTodo(oblig); + obligRepository.update(oblig); + oblig.setNode(null); + oldObligation.setNode(null); + dbHandlerUtil.addChangeLogs(oblig, oldObligation, user.getEmail(), Operation.UPDATE, null, Lists.newArrayList(), null, null); + + return oblig.getId(); + } + /** * Adds a new obligation element to the database. * @@ -756,6 +798,16 @@ private List isExistedObligationElement(ObligationElement obl if (existedObligationElement.isEmpty()) { return Collections.emptyList(); } + + if (isNullOrEmpty(lang) || isNullOrEmpty(action) || isNullOrEmpty(object)) { + log.info("Obligation Element have empty field"); + List existedElement = existedObligationElement.stream().filter(el -> lang.equals(el.getLangElement()) && action.equals(el.getAction()) && object.equals(el.getObject())).collect(Collectors.toList()); + if (CommonUtils.isNullOrEmptyCollection(existedElement)) { + return Collections.emptyList(); + } else { + return existedElement; + } + } return existedObligationElement; } @@ -938,6 +990,12 @@ public RequestSummary importAllOSADLLicenses(User user) { return requestSummary; } + public String convertTextToNodes(Obligation obligation, User user) throws SW360Exception { + OSADLObligationConnector osadlConnector = new OSADLObligationConnector(); + String obligNode = addNodes(osadlConnector.parseText(obligation.getText()), user); + return obligNode; + } + public RequestStatus deleteObligations(String id, User user) throws SW360Exception { Obligation oblig = obligRepository.get(id); assertNotNull(oblig); diff --git a/frontend/sw360-portlet/src/main/java/org/eclipse/sw360/portal/common/ErrorMessages.java b/frontend/sw360-portlet/src/main/java/org/eclipse/sw360/portal/common/ErrorMessages.java index 91bcad03b5..bd5505bcb0 100644 --- a/frontend/sw360-portlet/src/main/java/org/eclipse/sw360/portal/common/ErrorMessages.java +++ b/frontend/sw360-portlet/src/main/java/org/eclipse/sw360/portal/common/ErrorMessages.java @@ -61,6 +61,8 @@ public class ErrorMessages { public static final String ERROR_GETTING_CLEARING_REQUEST = "Error fetching clearing request from backend."; public static final String LICENSE_TYPE_DUPLICATE = "This license type already exists."; public static final String LICENSE_TYPE_ACCESS_DENIED = "User does not have the permission to add license type."; + public static final String OBLIGATION_NOT_ADDED = "Obligation could not be added."; + public static final String OBLIGATION_NOT_UPDATED = "Obligation could not be updated."; //this map is used in errorKeyToMessage.jspf to generate key-value pairs for the liferay-ui error tag public static final ImmutableList allErrorMessages = ImmutableList.builder() @@ -109,6 +111,8 @@ public class ErrorMessages { .add(ERROR_USER_CREATE) .add(ERROR_USER_UPDATE) .add(ERROR_USER_ACTIVATE_DEACTIVATE) + .add(OBLIGATION_NOT_ADDED) + .add(OBLIGATION_NOT_UPDATED) .build(); private ErrorMessages() { diff --git a/frontend/sw360-portlet/src/main/java/org/eclipse/sw360/portal/common/PortalConstants.java b/frontend/sw360-portlet/src/main/java/org/eclipse/sw360/portal/common/PortalConstants.java index 225ad39a44..04160c8d22 100644 --- a/frontend/sw360-portlet/src/main/java/org/eclipse/sw360/portal/common/PortalConstants.java +++ b/frontend/sw360-portlet/src/main/java/org/eclipse/sw360/portal/common/PortalConstants.java @@ -213,6 +213,8 @@ public class PortalConstants { public static final String LOAD_OBLIGATIONS_EDIT = "load_obligations_edit"; public static final String LOAD_LICENSE_OBLIGATIONS = "load_license_obligations"; public static final String UNUSED_RELEASES = "unusedReleases"; + public static final String OBLIGATION_EDIT = "obligationEdit"; + public static final String OBLIGATION_CHANGELOG = "obligation_changelog"; //! Specialized keys for license types public static final String LICENSE_TYPE_LIST = "licenseTypeList"; diff --git a/frontend/sw360-portlet/src/main/java/org/eclipse/sw360/portal/portlets/admin/TodoPortlet.java b/frontend/sw360-portlet/src/main/java/org/eclipse/sw360/portal/portlets/admin/TodoPortlet.java index fe0500fdfd..30cfe231c1 100644 --- a/frontend/sw360-portlet/src/main/java/org/eclipse/sw360/portal/portlets/admin/TodoPortlet.java +++ b/frontend/sw360-portlet/src/main/java/org/eclipse/sw360/portal/portlets/admin/TodoPortlet.java @@ -12,19 +12,19 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.thrift.TException; -import org.eclipse.sw360.datahandler.permissions.PermissionUtils; import org.eclipse.sw360.datahandler.thrift.RequestStatus; import org.eclipse.sw360.datahandler.thrift.licenses.LicenseService; +import org.eclipse.sw360.datahandler.thrift.changelogs.ChangeLogsService; import org.eclipse.sw360.datahandler.thrift.licenses.Obligation; import org.eclipse.sw360.datahandler.thrift.licenses.ObligationElement; import org.eclipse.sw360.datahandler.thrift.licenses.ObligationNode; import org.eclipse.sw360.datahandler.thrift.users.User; -import org.eclipse.sw360.datahandler.thrift.users.UserGroup; import org.eclipse.sw360.portal.common.UsedAsLiferayAction; import org.eclipse.sw360.portal.portlets.Sw360Portlet; import org.eclipse.sw360.portal.portlets.components.ComponentPortletUtils; import org.eclipse.sw360.portal.users.UserCacheHolder; import org.osgi.service.component.annotations.ConfigurationPolicy; +import com.fasterxml.jackson.databind.ObjectMapper; import javax.portlet.*; import java.io.IOException; @@ -33,6 +33,12 @@ import static com.google.common.base.Strings.isNullOrEmpty; import static org.eclipse.sw360.portal.common.PortalConstants.*; +import org.eclipse.sw360.portal.common.*; +import com.liferay.portal.kernel.json.*; +import com.liferay.portal.kernel.portlet.LiferayPortletURL; +import com.liferay.portal.kernel.portlet.PortletURLFactoryUtil; +import com.liferay.portal.kernel.theme.ThemeDisplay; +import com.liferay.portal.kernel.util.WebKeys; @org.osgi.service.component.annotations.Component( immediate = true, @@ -55,7 +61,7 @@ public class TodoPortlet extends Sw360Portlet { private static final Logger log = LogManager.getLogger(TodoPortlet.class); - + private static final ObjectMapper objectMapper = new ObjectMapper(); //! Serve resource and helpers @Override @@ -67,10 +73,12 @@ public void serveResource(ResourceRequest request, ResourceResponse response) th final User user = UserCacheHolder.getUserFromRequest(request); LicenseService.Iface licenseClient = thriftClients.makeLicenseClient(); + ChangeLogsService.Iface changeLogsClient = thriftClients.makeChangeLogsClient(); if (REMOVE_TODO.equals(action)) { try { - RequestStatus status = licenseClient.deleteObligations(id, user); + RequestStatus status = changeLogsClient.deleteChangeLogsByDocumentId(id, user); + status = licenseClient.deleteObligations(id, user); renderRequestStatus(request,response, status); } catch (TException e) { log.error("Error deleting oblig", e); @@ -78,6 +86,10 @@ public void serveResource(ResourceRequest request, ResourceResponse response) th } } else if (VIEW_IMPORT_OBLIGATION_ELEMENTS.equals(action)) { serveObligationElementSearchResults(request, response, where); + } else if (LOAD_CHANGE_LOGS.equals(action) || VIEW_CHANGE_LOGS.equals(action)) { + ChangeLogsPortletUtils changeLogsPortletUtilsPortletUtils = PortletUtils.getChangeLogsPortletUtils(thriftClients); + JSONObject dataForChangeLogs = changeLogsPortletUtilsPortletUtils.serveResourceForChangeLogs(request, response, action); + writeJSON(request, response, dataForChangeLogs); } } @@ -98,32 +110,39 @@ private void serveObligationElementSearchResults(ResourceRequest request, Resour include("/html/admin/obligations/ajax/searchObligationElementsAjax.jsp", request, response, PortletRequest.RESOURCE_PHASE); } - //! VIEW and helpers @Override public void doView(RenderRequest request, RenderResponse response) throws IOException, PortletException { - String pageName = request.getParameter(PAGENAME); + String obligationId = request.getParameter(DOCUMENT_ID); if (PAGENAME_ADD.equals(pageName)) { - List obligationNodeList; - List obligationElementList; - List obligationList; + prepareStandardAdd(request); + request.setAttribute(OBLIGATION_ACTION, PAGENAME_ADD); + include("/html/admin/obligations/add.jsp", request, response); + } else if (PAGENAME_EDIT.equals(pageName)) { + prepareStandardEdit(request); + request.setAttribute(OBLIGATION_ACTION, PAGENAME_EDIT); + include("/html/admin/obligations/add.jsp", request, response); + } else if (PAGENAME_DUPLICATE.equals(pageName)) { + prepareStandardEdit(request); + request.setAttribute(OBLIGATION_ACTION, PAGENAME_DUPLICATE); + include("/html/admin/obligations/add.jsp", request, response); + } else if (OBLIGATION_CHANGELOG.equals(pageName)) { try { LicenseService.Iface licenseClient = thriftClients.makeLicenseClient(); - obligationNodeList = licenseClient.getObligationNodes(); - obligationElementList = licenseClient.getObligationElements(); - obligationList = licenseClient.getObligations(); - } catch (Exception e) { - log.error("Could not get Obligation node from backend ", e); - obligationNodeList = Collections.emptyList(); - obligationElementList = Collections.emptyList(); - obligationList = Collections.emptyList(); + Obligation obligation = licenseClient.getObligationsById(obligationId); + request.setAttribute("obligationName", obligation.getTitle()); + } catch (TException e) { + log.error("Could not get Obligation from backend", e); + request.setAttribute("obligationName", null); } - request.setAttribute(OBLIGATION_NODE_LIST, obligationNodeList); - request.setAttribute(OBLIGATION_ELEMENT_LIST, obligationElementList); - request.setAttribute(TODO_LIST, obligationList); - include("/html/admin/obligations/add.jsp", request, response); + String portletId = (String) request.getAttribute(WebKeys.PORTLET_ID); + ThemeDisplay tD = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); + long plid = tD.getPlid(); + LiferayPortletURL redirectUrl = PortletURLFactoryUtil.create(request, portletId, plid, PortletRequest.RENDER_PART); + request.setAttribute("baseUrl", redirectUrl.toString()); + include("/html/admin/obligations/includes/obligationChangelog.jsp", request, response); } else { prepareStandardView(request); super.doView(request, response); @@ -135,33 +154,172 @@ private void prepareStandardView(RenderRequest request) { try { final User user = UserCacheHolder.getUserFromRequest(request); LicenseService.Iface licenseClient = thriftClients.makeLicenseClient(); - obligList = licenseClient.getObligations(); - } catch (TException e) { - log.error("Could not get Obligation from backend ", e); + log.error("Could not get Obligation from backend", e); obligList = Collections.emptyList(); } - request.setAttribute(TODO_LIST, obligList); } + private void prepareStandardAdd(RenderRequest request) { + prepareStandardAction(request); + request.setAttribute(OBLIGATION_ID, ""); + } + + private void prepareStandardEdit(RenderRequest request) { + prepareStandardAction(request); + try { + LicenseService.Iface licenseClient = thriftClients.makeLicenseClient(); + String obligationId = request.getParameter(DOCUMENT_ID); + Obligation obligation = licenseClient.getObligationsById(obligationId); + if (!obligation.isSetNode()) { + final User user = UserCacheHolder.getUserFromRequest(request); + String node = licenseClient.convertTextToNode(obligation, user); + obligation.setNode(node); + } + String obligationJson = objectMapper.writeValueAsString(obligation); + request.setAttribute(OBLIGATION_ID, obligationId); + request.setAttribute("obligationJson", obligationJson); + request.setAttribute("obligationTextJson", generateJsonObligationText(obligation.getNode())); + } catch (Exception e) { + log.error("Could not get Obligation from backend", e); + request.setAttribute(OBLIGATION_ID, null); + } + } + + private void prepareStandardAction(RenderRequest request) { + String obligationJson = "{\"text\" : \"\", \"title\": \"\"}"; + String obligationNodeListJson = "{}"; + String obligationElementListJson = "{}"; + String obligationListJson = "{}"; + + try { + LicenseService.Iface licenseClient = thriftClients.makeLicenseClient(); + List obligationNodeList = licenseClient.getObligationNodes(); + List obligationElementList = licenseClient.getObligationElements(); + List obligationList = licenseClient.getObligations(); + obligationNodeListJson = objectMapper.writeValueAsString(obligationNodeList); + obligationElementListJson = objectMapper.writeValueAsString(obligationElementList); + obligationListJson = objectMapper.writeValueAsString(obligationList); + } catch (Exception e) { + log.error("Could not get Obligation from backend", e); + } + + request.setAttribute("obligationJson", obligationJson); + request.setAttribute("obligationNodeListJson", obligationNodeListJson); + request.setAttribute("obligationElementListJson", obligationElementListJson); + request.setAttribute("obligationListJson", obligationListJson); + request.setAttribute("obligationTextJson", "{}"); + } + @UsedAsLiferayAction public void addObligations(ActionRequest request, ActionResponse response) { + LicenseService.Iface licenseClient = thriftClients.makeLicenseClient(); + final User user = UserCacheHolder.getUserFromRequest(request); - final Obligation oblig = new Obligation(); - ComponentPortletUtils.updateTodoFromRequest(request, oblig); + String action = request.getParameter(PortalConstants.OBLIGATION_ACTION); + String obligationEditedId = request.getParameter(PortalConstants.OBLIGATION_ID); + if (isNullOrEmpty(obligationEditedId) || !action.equals(PortalConstants.PAGENAME_EDIT)) { + try { + final Obligation oblig = new Obligation(); + setObligationValues(request, oblig); + String obligId = licenseClient.addObligations(oblig, user); + if (isNullOrEmpty(obligId)) { + setSW360SessionError(request, ErrorMessages.OBLIGATION_NOT_ADDED); + } else { + setSessionMessage(request, RequestStatus.SUCCESS, "Obligation", "adde", oblig.getTitle()); + } + } catch (Exception e) { + setSW360SessionError(request, ErrorMessages.OBLIGATION_NOT_ADDED); + log.error("Error adding oblig", e); + } + } else { + try { + final Obligation oblig = licenseClient.getObligationsById(obligationEditedId); + setObligationValues(request, oblig); + String obligId = licenseClient.updateObligation(oblig, user); + if (isNullOrEmpty(obligId)) { + setSW360SessionError(request, ErrorMessages.OBLIGATION_NOT_UPDATED); + } else { + setSessionMessage(request, RequestStatus.SUCCESS, "Obligation", "update", oblig.getTitle()); + } + } catch (Exception e) { + setSW360SessionError(request, ErrorMessages.OBLIGATION_NOT_UPDATED); + log.error("Error editing oblig", e); + } + } + + try { + String portletId = (String) request.getAttribute(WebKeys.PORTLET_ID); + ThemeDisplay tD = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); + long plid = tD.getPlid(); + LiferayPortletURL redirectUrl = PortletURLFactoryUtil.create(request, portletId, plid, PortletRequest.RENDER_PART); + request.setAttribute(WebKeys.REDIRECT, redirectUrl.toString()); + response.sendRedirect(redirectUrl.toString()); + } catch (IOException e) { + log.error("Error when send redirect url", e); + } + } + + private Obligation setObligationValues(ActionRequest request, Obligation oblig) throws TException { LicenseService.Iface licenseClient = thriftClients.makeLicenseClient(); final User user = UserCacheHolder.getUserFromRequest(request); + + ComponentPortletUtils.updateTodoFromRequest(request, oblig); String jsonString = request.getParameter(Obligation._Fields.TEXT.toString()); + String obligationType = request.getParameter(Obligation._Fields.OBLIGATION_TYPE.toString()); + String obligationNode = licenseClient.addNodes(jsonString, user); + String obligationText = licenseClient.buildObligationText(obligationNode, "0"); + oblig.setText(obligationText); + oblig.setNode(obligationNode); + oblig.setTitle(oblig.getTitle().trim()); + if (isNullOrEmpty(obligationType)) { + oblig.setObligationType(null); + } + return oblig; + } + + private String generateJsonObligationText(String obligationNode) { try { - String obligationNode = licenseClient.addNodes(jsonString, user); - String obligationText = licenseClient.buildObligationText(obligationNode, "0"); - oblig.setText(obligationText); - oblig.setNode(obligationNode); - licenseClient.addObligations(oblig, user); - } catch (TException e) { - log.error("Error adding oblig", e); + com.liferay.portal.kernel.json.JSONObject jsonObject = JSONFactoryUtil.createJSONObject(obligationNode); + return buildJsonObligationText(jsonObject, 0); + } + catch (Exception e) { + log.error("Can not build obligation text from node: " + obligationNode); + return null; + } + } + + private String buildJsonObligationText(com.liferay.portal.kernel.json.JSONObject jsonObject, int level) { + LicenseService.Iface client = thriftClients.makeLicenseClient(); + + try { + ObligationNode obligationNode = client.getObligationNodeById(jsonObject.get("id").toString()); + if (!obligationNode.getNodeType().equals("ROOT")) { + if (obligationNode.getNodeType().equals("Obligation")) { + ObligationElement obligationElement = client.getObligationElementById(obligationNode.getOblElementId()); + jsonObject.put("type", obligationElement.getType()); + jsonObject.put("langElement", obligationElement.getLangElement()); + jsonObject.put("action", obligationElement.getAction()); + jsonObject.put("object", obligationElement.getObject()); + } else { + jsonObject.put("type", obligationNode.getNodeType()); + jsonObject.put("text", obligationNode.getNodeText()); + } + } + } catch (Exception e) { + log.error("Can not build json obligation text" + e); + return null; } + + if (jsonObject.getJSONArray("children").length() != 0) { + for (int i = 0; i < jsonObject.getJSONArray("children").length(); i++) { + com.liferay.portal.kernel.json.JSONObject contactObject = jsonObject.getJSONArray("children").getJSONObject(i); + buildJsonObligationText(contactObject, level + 1); + } + } + + return jsonObject.toJSONString(); } } diff --git a/frontend/sw360-portlet/src/main/resources/META-INF/resources/html/admin/obligations/add.jsp b/frontend/sw360-portlet/src/main/resources/META-INF/resources/html/admin/obligations/add.jsp index b69c88072a..58047fb72e 100644 --- a/frontend/sw360-portlet/src/main/resources/META-INF/resources/html/admin/obligations/add.jsp +++ b/frontend/sw360-portlet/src/main/resources/META-INF/resources/html/admin/obligations/add.jsp @@ -28,9 +28,12 @@ <%@ page import="org.eclipse.sw360.datahandler.thrift.licenses.ObligationNode" %> - + + + +
@@ -40,7 +43,12 @@