Skip to content

Commit

Permalink
Merge pull request #430 from wttech/fix-delete-items
Browse files Browse the repository at this point in the history
fixed script, history delete
  • Loading branch information
dprzybyl authored Nov 4, 2023
2 parents a306b14 + 77faf4b commit e2af52b
Show file tree
Hide file tree
Showing 9 changed files with 228 additions and 7 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* ========================LICENSE_START=================================
* AEM Permission Management
* %%
* Copyright (C) 2013 Wunderman Thompson Technology
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =========================LICENSE_END==================================
*/

package com.cognifide.apm.core.endpoints;

import com.cognifide.apm.core.endpoints.params.RequestParameter;
import javax.inject.Inject;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.models.annotations.Model;

@Model(adaptables = SlingHttpServletRequest.class)
public class ScriptDeleteForm {

@Inject
@RequestParameter("paths")
private String[] paths;

public String[] getPaths() {
return paths;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
* ========================LICENSE_START=================================
* AEM Permission Management
* %%
* Copyright (C) 2013 Wunderman Thompson Technology
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =========================LICENSE_END==================================
*/
package com.cognifide.apm.core.endpoints;

import com.cognifide.apm.core.Property;
import com.cognifide.apm.core.endpoints.response.ResponseEntity;
import com.cognifide.apm.core.endpoints.utils.RequestProcessor;
import java.io.IOException;
import javax.jcr.Session;
import javax.servlet.Servlet;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.models.factory.ModelFactory;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(
service = Servlet.class,
property = {
Property.PATH + "/bin/apm/scripts/delete",
Property.METHOD + "POST",
Property.DESCRIPTION + "APM Script Delete Servlet",
Property.VENDOR
}
)
public class ScriptDeleteServlet extends SlingAllMethodsServlet {

private static final Logger LOGGER = LoggerFactory.getLogger(ScriptDeleteServlet.class);

@Reference
private ModelFactory modelFactory;

@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
RequestProcessor.process(modelFactory, ScriptDeleteForm.class, request, response, (form, resourceResolver) -> {
try {
Session session = resourceResolver.adaptTo(Session.class);
for (String path : form.getPaths()) {
if (session.nodeExists(path)) {
session.removeItem(path);
LOGGER.info("Item {} successfully deleted", path);
}
}
session.save();
return ResponseEntity.ok("Item(s) successfully deleted");
} catch (Exception e) {
LOGGER.error("Error while deleting item(s)", e);
return ResponseEntity.badRequest(StringUtils.defaultString(e.getMessage(), "Errors while deleting item(s)"));
}
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,13 @@ private Object getValue(SlingHttpServletRequest request, Class<?> type, String p
} else if (type.isEnum()) {
return toEnum(type, parameterValue);
} else if (type == String[].class) {
return parameterValue.getString().split(",");
if (parameterValue.getString().contains(",")) {
return parameterValue.getString().split(",");
} else {
return Arrays.stream(request.getRequestParameters(parameterName))
.map(org.apache.sling.api.request.RequestParameter::getString)
.toArray(String[]::new);
}
}
return parameterValue.getString();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,11 @@

package com.cognifide.apm.core.history;

import com.cognifide.apm.api.services.ExecutionMode;
import java.util.Comparator;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.annotations.DefaultInjectionStrategy;
import org.apache.sling.models.annotations.Model;
Expand Down Expand Up @@ -72,20 +75,28 @@ public static ScriptHistoryImpl empty(String scriptPath) {

@Override
public HistoryEntry getLastLocalRun() {
lastLocalRun = getHistoryEntry(lastLocalRun, lastLocalRunPath);
lastLocalRun = getHistoryEntry(lastLocalRun, lastLocalRunPath, ExecutionMode.RUN);
return lastLocalRun;
}

@Override
public HistoryEntry getLastLocalDryRun() {
lastLocalDryRun = getHistoryEntry(lastLocalDryRun, lastLocalDryRunPath);
lastLocalDryRun = getHistoryEntry(lastLocalDryRun, lastLocalDryRunPath, ExecutionMode.DRY_RUN);
return lastLocalDryRun;
}

private HistoryEntry getHistoryEntry(HistoryEntry entry, String historyEntryPath) {
private HistoryEntry getHistoryEntry(HistoryEntry entry, String historyEntryPath, ExecutionMode mode) {
HistoryEntry historyEntry = entry;
if (historyEntry == null && resource != null && historyEntryPath != null) {
historyEntry = history.findHistoryEntry(resource.getResourceResolver(), historyEntryPath);
if (historyEntry == null) {
historyEntry = history.findAllHistoryEntries(resource.getResourceResolver())
.stream()
.filter(it -> StringUtils.equals(it.getScriptPath(), scriptPath)
&& StringUtils.equals(it.getMode(), mode.toString()))
.max(Comparator.comparing(HistoryEntry::getExecutionTime))
.orElse(new HistoryEntryImpl());
}
}
return historyEntry;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#base=js
apm-scripts.js
fileupload.js
view-mode.js
view-mode.js
deleteitem.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/*-
* ========================LICENSE_START=================================
* AEM Permission Management
* %%
* Copyright (C) 2013 - 2016 Wunderman Thompson Technology
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =========================LICENSE_END==================================
*/
(function (window, document, $) {
function deletePages(collection, paths) {
const ui = $(window).adaptTo('foundation-ui');
ui.wait();
$.ajax({
url: '/bin/apm/scripts/delete',
type: 'POST',
data: {
paths: paths
},
dataType: 'json',
success: function () {
ui.clearWait();
const api = collection.adaptTo('foundation-collection');
if (api && 'reload' in api) {
api.reload();
return
}
const contentApi = $('.foundation-content').adaptTo('foundation-content');
if (contentApi) {
contentApi.refresh();
}
},
error: function () {
ui.clearWait();
ui.alert('Error', 'Errors while deleting item(s)', 'error');
}
});
}

function createEl(name) {
return $(document.createElement(name));
}

$(window).adaptTo('foundation-registry').register('foundation.collection.action.action', {
name: 'com.cognifide.apm.delete',
handler: function (name, el, config, collection, selections) {
const message = createEl('div');
const intro = createEl('p').appendTo(message);
if (selections.length === 1) {
intro.text('You are going to delete the following item:');
} else {
intro.text('You are going to delete the following ' + selections.length + ' items:');
}
let list = [];
const maxCount = Math.min(selections.length, 12);
for (let i = 0; i < maxCount; i++) {
const title = $(selections[i]).find('.foundation-collection-item-title').text();
const time = $(selections[i]).find('.foundation-collection-item-time').text();
list.push(createEl('b').text(time ? title + ' (' + time.trim() + ')' : title).prop('outerHTML'))
}
if (selections.length > maxCount) {
list.push('\x26#8230;');
}
createEl('p').html(list.join('\x3cbr\x3e')).appendTo(message);
const ui = $(window).adaptTo('foundation-ui');
ui.prompt('Delete', message.html(), 'notice', [{
text: 'Cancel'
}, {
text: 'Delete',
warning: true,
handler: function () {
const paths = selections.map(function (value) {
return $(value).data('foundationCollectionItemId');
});
deletePages($(collection), paths);
}
}]);
}
});
})(window, document, Granite.$);
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,12 @@
</td>
<td is="coral-table-cell" value="${item.scriptName}">
<a href="${item.scriptContentPath}" download="${item.scriptName}"
class="foundation-collection-item-title"
style="text-decoration:none; color:#4b4b4b">${item.scriptName}</a>
</td>
<td is="coral-table-cell" value="${item.executionTime.timeInMillis || 0}">
<time data-sly-test="${item.executionTime}" datetime="${item.executionTime.timeInMillis || 0}"
class="foundation-collection-item-time"
data-sly-use.execLast="${'com.adobe.cq.xf.ui.DateFormatter' @ date=item.executionTimeCalendar, simpleFormat='yyyy-MM-dd HH:mm:ss'}">
${execLast.date}
</time>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@
granite:rel="cq-siteadmin-admin-actions-delete-activator"
jcr:primaryType="nt:unstructured"
sling:resourceType="granite/ui/components/coral/foundation/collection/action"
action="cq.wcm.delete"
action="com.cognifide.apm.delete"
icon="delete"
relScope="collection"
target=".cq-experience-fragments-admin-childpages"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@
granite:rel="cq-siteadmin-admin-actions-delete-activator"
jcr:primaryType="nt:unstructured"
sling:resourceType="granite/ui/components/coral/foundation/collection/action"
action="cq.wcm.delete"
action="com.cognifide.apm.delete"
icon="delete"
relScope="collection"
target=".cq-experience-fragments-admin-childpages"
Expand Down

0 comments on commit e2af52b

Please sign in to comment.