<commit_before>package fi.nls.oskari.control.admin;

import static fi.nls.oskari.control.ActionConstants.KEY_ID;
import static fi.nls.oskari.control.ActionConstants.KEY_NAME;

import java.util.LinkedHashSet;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.oskari.permissions.PermissionService;
import org.oskari.permissions.model.PermissionType;

import fi.nls.oskari.annotation.OskariActionRoute;
import fi.nls.oskari.control.ActionException;
import fi.nls.oskari.control.ActionParameters;
import fi.nls.oskari.control.ActionParamsException;
import fi.nls.oskari.control.RestActionHandler;
import fi.nls.oskari.domain.Role;
import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;
import fi.nls.oskari.service.OskariComponentManager;
import fi.nls.oskari.service.ServiceException;
import fi.nls.oskari.service.UserService;
import fi.nls.oskari.util.JSONHelper;
import fi.nls.oskari.util.ResponseHelper;

@OskariActionRoute("GetAllRolesAndPermissionTypes")
public class GetAllRolesAndPermissionTypesHandler extends RestActionHandler {
    
    private Logger log = LogFactory.getLogger(GetAllRolesAndPermissionTypesHandler.class);
    private UserService userService = null;
    private PermissionService permissionsService = null;

    private final static String JSKEY_ID = "id";
    private final static String JSKEY_NAME = "name";
    private final static String JSKEY_ROLES = "roles";
    private final static String JSKEY_PERMISSION_TYPES = "permissionTypes";

    @Override
    public void init() {
        try {
            userService = UserService.getInstance();
        } catch (Exception ex) {
            log.error(ex, "Unable to initialize User service!");
        }
        try {
            permissionsService = OskariComponentManager.getComponentOfType(PermissionService.class);
        } catch (Exception ex) {
            log.error(ex, "Unable to initialize permission service!");
        }
    }

    @Override
    public void preProcess(ActionParameters params) throws ActionException {
        params.requireAdminUser();

        if (userService == null) {
            throw new ActionParamsException("User service not initialized");
        }
        if (permissionsService == null) {
            throw new ActionParamsException("PermissionsService service not initialized");
        }
    }

    @Override
    public void handleGet(ActionParameters params) throws ActionException {
        try {
            
            final JSONObject root = new JSONObject();
            getRoles(root);
            getPermissionTypes(root,params.getLocale().getLanguage());
            ResponseHelper.writeResponse(params, root);
        } catch (Exception e) {
            throw new ActionException("Something went wrong getting roles and permission types from the platform", e);
        }
    }

    private void getRoles(final JSONObject root) throws ServiceException, JSONException  {
        final Role[] roles = userService.getRoles();

        final JSONArray rolesJSON = new JSONArray();

        for (Role role : roles) {
            JSONObject external = new JSONObject();
            external.put(JSKEY_ID, role.getId());
            external.put(JSKEY_NAME, role.getName());
            rolesJSON.put(external);
        }

        
        root.put(JSKEY_ROLES, rolesJSON);
    }  
    
    private void getPermissionTypes(JSONObject root, String language) {
        
        final JSONArray permissionNames = new JSONArray();
        for (String id : getAvailablePermissions()) {
            JSONObject perm = new JSONObject();
            JSONHelper.putValue(perm, KEY_ID, id);
            JSONHelper.putValue(perm, KEY_NAME, permissionsService.getPermissionName(id, language));
            permissionNames.put(perm);
        }
        JSONHelper.putValue(root, JSKEY_PERMISSION_TYPES, permissionNames);
        
    }
    
    private Set<String> getAvailablePermissions() {
        
        Set<String> availablePermissionTypes = new LinkedHashSet <>();
        for (PermissionType type : PermissionType.values()) {
            if (type.isLayerSpecific()) {<commit_msg>Fix exception handling in service initialization and change json response construction<commit_after>package fi.nls.oskari.control.admin;

import static fi.nls.oskari.control.ActionConstants.KEY_ID;
import static fi.nls.oskari.control.ActionConstants.KEY_NAME;

import java.util.LinkedHashSet;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.oskari.permissions.PermissionService;
import org.oskari.permissions.model.PermissionType;

import fi.nls.oskari.annotation.OskariActionRoute;
import fi.nls.oskari.control.ActionException;
import fi.nls.oskari.control.ActionParameters;
import fi.nls.oskari.control.RestActionHandler;
import fi.nls.oskari.domain.Role;
import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;
import fi.nls.oskari.service.OskariComponentManager;
import fi.nls.oskari.service.ServiceException;
import fi.nls.oskari.service.UserService;
import fi.nls.oskari.util.JSONHelper;
import fi.nls.oskari.util.ResponseHelper;

@OskariActionRoute("GetAllRolesAndPermissionTypes")
public class GetAllRolesAndPermissionTypesHandler extends RestActionHandler {
    
    private Logger log = LogFactory.getLogger(GetAllRolesAndPermissionTypesHandler.class);
    private UserService userService = null;
    private PermissionService permissionsService = null;

    private final static String JSKEY_ID = "id";
    private final static String JSKEY_NAME = "name";
    private final static String JSKEY_ROLES = "roles";
    private final static String JSKEY_PERMISSION_TYPES = "permissionTypes";

    @Override
    public void init() {
        try {
            userService = UserService.getInstance();
        } catch (ServiceException ex) {
            log.error(ex, "Unable to initialize User service!");
            throw new RuntimeException(ex);
        }
        
        try {
            permissionsService = OskariComponentManager.getComponentOfType(PermissionService.class);
        } catch (Exception ex) {
            log.error(ex, "Unable to initialize permission service!");
            throw new RuntimeException(ex);
        }
    }

    @Override
    public void preProcess(ActionParameters params) throws ActionException {
        params.requireAdminUser();
    }

    @Override
    public void handleGet(ActionParameters params) throws ActionException {
        try {
            final JSONObject root = new JSONObject();
            JSONHelper.putValue(root, JSKEY_ROLES, getRoles());
            JSONHelper.putValue(root, JSKEY_PERMISSION_TYPES, getPermissionTypes(params.getLocale().getLanguage()));
            ResponseHelper.writeResponse(params, root);
        } catch (Exception e) {
            throw new ActionException("Something went wrong getting roles and permission types from the platform", e);
        }
    }

    private JSONArray getRoles() throws ServiceException, JSONException  {
        final Role[] roles = userService.getRoles();
        final JSONArray rolesJSON = new JSONArray();

        for (Role role : roles) {
            JSONObject external = new JSONObject();
            external.put(JSKEY_ID, role.getId());
            external.put(JSKEY_NAME, role.getName());
            rolesJSON.put(external);
        }
        return rolesJSON;
    }  
    
    private JSONArray getPermissionTypes(String language) {
        
        final JSONArray permissionNames = new JSONArray();
        for (String id : getAvailablePermissions()) {
            JSONObject perm = new JSONObject();
            JSONHelper.putValue(perm, KEY_ID, id);
            JSONHelper.putValue(perm, KEY_NAME, permissionsService.getPermissionName(id, language));
            permissionNames.put(perm);
        }
       return permissionNames;
    }
    
    private Set<String> getAvailablePermissions() {
        
        Set<String> availablePermissionTypes = new LinkedHashSet <>();
        for (PermissionType type : PermissionType.values()) {
            if (type.isLayerSpecific()) {
{'fraction_non_alphanumeric': 0.08945374557008431, 'fraction_numerical': 0.0, 'mean_word_length': 3.1543147208121827, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5330637', 'n_tokens_mistral': 2211, 'n_tokens_neox': 2208, 'n_words': 501}