<commit_before>/*
 * Copyright (C) 2000 - 2019 Silverpeas
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * As a special exception to the terms and conditions of version 3.0 of
 * the GPL, you may redistribute this Program in connection with Free/Libre
 * Open Source Software ("FLOSS") applications as described in Silverpeas's
 * FLOSS exception.  You should have received a copy of the text describing
 * the FLOSS exception, and it is also available here:
 * "https://www.silverpeas.org/legal/floss_exception.html"
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.silverpeas.web.look;

import org.silverpeas.core.SilverpeasRuntimeException;
import org.silverpeas.core.admin.component.model.ComponentInst;
import org.silverpeas.core.admin.component.model.PersonalComponent;
import org.silverpeas.core.admin.component.model.PersonalComponentInstance;
import org.silverpeas.core.admin.component.model.SilverpeasComponentInstance;
import org.silverpeas.core.admin.component.model.WAComponent;
import org.silverpeas.core.admin.service.AdminException;
import org.silverpeas.core.admin.service.OrganizationController;
import org.silverpeas.core.admin.space.PersonalSpaceManager;
import org.silverpeas.core.admin.space.SpaceInst;
import org.silverpeas.core.admin.user.model.User;
import org.silverpeas.core.admin.user.model.UserDetail;
import org.silverpeas.core.notification.user.UserNotificationServerEvent;
import org.silverpeas.core.sharing.services.SharingServiceProvider;
import org.silverpeas.core.sharing.services.SharingTicketService;
import org.silverpeas.core.util.JSONCodec;
import org.silverpeas.core.util.JSONCodec.JSONArray;
import org.silverpeas.core.util.JSONCodec.JSONObject;
import org.silverpeas.core.util.LocalizationBundle;
import org.silverpeas.core.util.ResourceLocator;
import org.silverpeas.core.util.StringUtil;
import org.silverpeas.core.util.URLUtil;
import org.silverpeas.core.util.logging.SilverLogger;
import org.silverpeas.core.web.external.webconnections.model.WebConnectionsInterface;
import org.silverpeas.core.web.look.LookHelper;
import org.silverpeas.core.web.mvc.webcomponent.SilverpeasAuthenticatedHttpServlet;

import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.Writer;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.MissingResourceException;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;

import static java.util.Comparator.comparing;

public class PersonalSpaceJSONServlet extends SilverpeasAuthenticatedHttpServlet {

  private static final long serialVersionUID = 8565616592829678418L;
  private static final String DESCRIPTION = "description";
  private static final String LABEL = "label";

  @Inject
  private OrganizationController organizationController;
  @Inject
  private PersonalSpaceManager personalSpaceManager;

  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    doPost(req, res);
  }

  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {

    HttpSession session = req.getSession(true);
    LookHelper helper = LookHelper.getLookHelper(session);
    User user = UserDetail.getCurrentRequester();
    String userId = user.getId();

    res.setContentType("application/json");

    String action = req.getParameter("Action");

    Writer writer = res.getWriter();
    if ("GetAvailableComponents".equals(action)) {
      Collection<WAComponent> components = personalSpaceManager.getVisibleComponents();
      SpaceInst space = personalSpaceManager.getPersonalSpace(userId);
      if (space != null) {
        writer.write(getWAComponentsAsJSONArray(getNotUsedComponents(components, space), helper));
      } else {
        writer.write(getWAComponentsAsJSONArray(components, helper));
      }
    } else if ("GetComponents".equals(action)) {
      SpaceInst space = personalSpaceManager.getPersonalSpace(userId);
      if (space == null) {
        // Creating a dummy personal space instance which does not exist in database
        space = new SpaceInst();
        space.setPersonalSpace(true);
        space.setCreatorUserId(userId);
      }
      final List<SilverpeasComponentInstance> allComponentInstances = space.getAllComponentInstances().stream()
          .filter(i -> !i.isPersonal() || PersonalComponent.getByName(i.getName()).filter(PersonalComponent::isVisible).isPresent())
          .sorted(comparing((SilverpeasComponentInstance i) -> !i.isPersonal())
                  .thenComparing(SilverpeasComponentInstance::getId))
          .collect(Collectors.toList());
      writer.write(getComponentsAsJSONArray(allComponentInstances, helper));
    } else if ("AddComponent".equals(action)) {
      String componentName = req.getParameter("ComponentName");
      try {
        String componentId = personalSpaceManager.addComponent(user, componentName);
        writer.write(getResult(componentName, componentId, null, helper));
      } catch (Exception e) {
        writer.write(getResult(componentName, null, e, helper));
        SilverLogger.getLogger(this).error(e);
      }
    } else if ("RemoveComponent".equals(action)) {
      String componentId = req.getParameter("ComponentId");
      try {
        String componentName = personalSpaceManager.removeComponent(userId, componentId);
        writer.write(getResult(componentName, componentId, null, helper));
      } catch (AdminException e) {
        writer.write(getResult(null, componentId, e, helper));
        SilverLogger.getLogger(this).error(e);
      }
    } else if ("GetTools".equals(action)) {
      writer.write(getToolsAsJSONArray(helper));
    }
  }<commit_msg>Refine PersonalSpaceJSONServlet to take in charge unexpected exceptions<commit_after>/*
 * Copyright (C) 2000 - 2019 Silverpeas
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * As a special exception to the terms and conditions of version 3.0 of
 * the GPL, you may redistribute this Program in connection with Free/Libre
 * Open Source Software ("FLOSS") applications as described in Silverpeas's
 * FLOSS exception.  You should have received a copy of the text describing
 * the FLOSS exception, and it is also available here:
 * "https://www.silverpeas.org/legal/floss_exception.html"
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.silverpeas.web.look;

import org.silverpeas.core.SilverpeasRuntimeException;
import org.silverpeas.core.admin.component.model.ComponentInst;
import org.silverpeas.core.admin.component.model.PersonalComponent;
import org.silverpeas.core.admin.component.model.PersonalComponentInstance;
import org.silverpeas.core.admin.component.model.SilverpeasComponentInstance;
import org.silverpeas.core.admin.component.model.WAComponent;
import org.silverpeas.core.admin.service.AdminException;
import org.silverpeas.core.admin.service.OrganizationController;
import org.silverpeas.core.admin.space.PersonalSpaceManager;
import org.silverpeas.core.admin.space.SpaceInst;
import org.silverpeas.core.admin.user.model.User;
import org.silverpeas.core.admin.user.model.UserDetail;
import org.silverpeas.core.notification.user.UserNotificationServerEvent;
import org.silverpeas.core.sharing.services.SharingServiceProvider;
import org.silverpeas.core.sharing.services.SharingTicketService;
import org.silverpeas.core.util.JSONCodec;
import org.silverpeas.core.util.JSONCodec.JSONArray;
import org.silverpeas.core.util.JSONCodec.JSONObject;
import org.silverpeas.core.util.LocalizationBundle;
import org.silverpeas.core.util.ResourceLocator;
import org.silverpeas.core.util.StringUtil;
import org.silverpeas.core.util.URLUtil;
import org.silverpeas.core.util.logging.SilverLogger;
import org.silverpeas.core.web.external.webconnections.model.WebConnectionsInterface;
import org.silverpeas.core.web.look.LookHelper;
import org.silverpeas.core.web.mvc.webcomponent.SilverpeasAuthenticatedHttpServlet;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.Writer;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.MissingResourceException;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;

import static java.util.Comparator.comparing;

public class PersonalSpaceJSONServlet extends SilverpeasAuthenticatedHttpServlet {

  private static final long serialVersionUID = 8565616592829678418L;
  private static final String DESCRIPTION = "description";
  private static final String LABEL = "label";

  @Inject
  private OrganizationController organizationController;
  @Inject
  private PersonalSpaceManager personalSpaceManager;

  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse res) {
    doPost(req, res);
  }

  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse res) {
    HttpSession session = req.getSession(true);
    LookHelper helper = LookHelper.getLookHelper(session);
    User user = UserDetail.getCurrentRequester();
    String userId = user.getId();

    res.setContentType("application/json");

    String action = req.getParameter("Action");

    try {
      Writer writer = res.getWriter();
      if ("GetAvailableComponents".equals(action)) {
        Collection<WAComponent> components = personalSpaceManager.getVisibleComponents();
        SpaceInst space = personalSpaceManager.getPersonalSpace(userId);
        if (space != null) {
          writer.write(getWAComponentsAsJSONArray(getNotUsedComponents(components, space), helper));
        } else {
          writer.write(getWAComponentsAsJSONArray(components, helper));
        }
      } else if ("GetComponents".equals(action)) {
        SpaceInst space = personalSpaceManager.getPersonalSpace(userId);
        if (space == null) {
          // Creating a dummy personal space instance which does not exist in database
          space = new SpaceInst();
          space.setPersonalSpace(true);
          space.setCreatorUserId(userId);
        }
        final List<SilverpeasComponentInstance> allComponentInstances = space.getAllComponentInstances()
            .stream()
            .filter(i -> !i.isPersonal() || PersonalComponent.getByName(i.getName())
                .filter(PersonalComponent::isVisible)
                .isPresent())
            .sorted(comparing((SilverpeasComponentInstance i) -> !i.isPersonal()).thenComparing(
                SilverpeasComponentInstance::getId))
            .collect(Collectors.toList());
        writer.write(getComponentsAsJSONArray(allComponentInstances, helper));
      } else if ("AddComponent".equals(action)) {
        addComponent(req, writer, helper, user);
      } else if ("RemoveComponent".equals(action)) {
        removeComponent(req, writer, helper, userId);
      } else if ("GetTools".equals(action)) {
        writer.write(getToolsAsJSONArray(helper));
      }
    } catch (Exception e) {
      SilverLogger.getLogger(this).error(e);
      res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
  }

  private void removeComponent(final HttpServletRequest req, final Writer writer,
      final LookHelper helper, final String userId) throws IOException {
    String componentId = req.getParameter("ComponentId");
    try {
      String componentName = personalSpaceManager.removeComponent(userId, componentId);
      writer.write(getResult(componentName, componentId, null, helper));
    } catch (AdminException e) {
      writer.write(getResult(null, componentId, e, helper));
      SilverLogger.getLogger(this).error(e);
    }
  }

  private void addComponent(final HttpServletRequest req, final Writer writer,
      final LookHelper helper, final User user) throws IOException {
    String componentName = req.getParameter("ComponentName");
    try {
      String componentId = personalSpaceManager.addComponent(user, componentName);
      writer.write(getResult(componentName, componentId, null, helper));
    } catch (Exception e) {
      writer.write(getResult(componentName, null, e, helper));
      SilverLogger.getLogger(this).error(e);
    }
  }
{'fraction_non_alphanumeric': 0.09474452554744525, 'fraction_numerical': 0.004379562043795621, 'mean_word_length': 4.511263073209975, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 13, 'https://': 2, 'lorem ipsum': 0, 'www.': 4, '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': '6442545', 'n_tokens_mistral': 3808, 'n_tokens_neox': 3756, 'n_words': 904}