001/*
002 * (C) Copyright 2018 Nuxeo (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     pierre
018 */
019package org.nuxeo.ecm.automation.core.operations.services.bulk;
020
021import java.io.IOException;
022import java.util.Collections;
023import java.util.HashMap;
024import java.util.Map;
025
026import org.nuxeo.ecm.automation.core.Constants;
027import org.nuxeo.ecm.automation.core.annotations.Context;
028import org.nuxeo.ecm.automation.core.annotations.Operation;
029import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
030import org.nuxeo.ecm.automation.core.annotations.Param;
031import org.nuxeo.ecm.core.api.Blob;
032import org.nuxeo.ecm.core.api.Blobs;
033import org.nuxeo.ecm.core.api.CoreSession;
034import org.nuxeo.ecm.core.bulk.BulkCommand;
035import org.nuxeo.ecm.core.bulk.BulkService;
036
037/**
038 * @since 10.2
039 */
040@Operation(id = RunBulkAction.ID, category = Constants.CAT_SERVICES, label = "Run a bulk", addToStudio = true, description = "Run a bulk on a set of documents expressed by a NXQL.")
041public class RunBulkAction {
042
043    public static final String ID = "Bulk.RunAction";
044
045    @Context
046    protected BulkService service;
047
048    @Context
049    protected CoreSession session;
050
051    @Param(name = "query", required = true)
052    protected String query;
053
054    @Param(name = "action", required = true)
055    protected String action;
056
057    @Param(name = "parameters", required = false)
058    protected Map<String, String> parameters = new HashMap<>();
059
060    @OperationMethod
061    public Blob run() throws IOException {
062        String repositoryName = session.getRepositoryName();
063        String userName = session.getPrincipal().getName();
064
065        BulkCommand command = new BulkCommand().withRepository(repositoryName)
066                                               .withAction(action)
067                                               .withUsername(userName)
068                                               .withQuery(query)
069                                               .withParams(parameters);
070        String commandId = service.submit(command);
071        return Blobs.createJSONBlobFromValue(Collections.singletonMap("commandId", commandId));
072    }
073
074}