@Override
  public void handleAction(ActionParameters params) throws ActionException {
    String jsessionid = params.getRequest().getSession().getId();

    // remove cache
    log.debug("deleting session:", jsessionid);
    WFSLayerPermissionsStore.destroy(jsessionid);
  }
  /**
   * Parses WPS Proxy url via Oskari action route
   *
   * @param params Action parameters
   * @return String baseurl for Geoserver WPS reference WFS data input
   *     **********************************************************************
   */
  public String getBaseProxyUrl(ActionParameters params) {
    String baseurl = GEOSERVER_PROXY_BASE_URL;
    if (baseurl == null) {
      try {
        final URL url = new URL(params.getRequest().getRequestURL().toString());
        baseurl = url.getProtocol() + "://" + url.getHost() + ":" + url.getPort();
      } catch (Exception ignored) {
      }
    }

    final String baseAjaxUrl =
        PropertyUtil.get(params.getLocale(), GetAppSetupHandler.PROPERTY_AJAXURL);
    baseurl = baseurl + baseAjaxUrl + PARAMS_PROXY;
    log.debug("Analysis baseURL:", baseurl);
    return baseurl;
  }
  public void handleAction(ActionParameters params) throws ActionException {

    final HttpServletResponse response = params.getResponse();
    final HttpServletRequest httpRequest = params.getRequest();
    // default print format is application/pdf
    final String pformat = params.getHttpParam(PARM_FORMAT, "application/pdf");
    final JSONObject jsonprint = getPrintJSON(params);
    String file_save = params.getHttpParam(PARM_SAVE, "");
    boolean geojsCase = false;
    if (!params.getHttpParam(PARM_GEOJSON, "").isEmpty()) geojsCase = true;

    final HttpURLConnection con = getConnection(pformat, geojsCase);
    for (Enumeration<String> e = httpRequest.getHeaderNames(); e.hasMoreElements(); ) {
      final String key = e.nextElement();
      final String value = httpRequest.getHeader(key);
      con.setRequestProperty(key, value);
    }
    try {
      con.setRequestMethod("POST");
      con.setDoOutput(true);
      con.setDoInput(true);
      HttpURLConnection.setFollowRedirects(false);
      con.setUseCaches(false);
      con.setRequestProperty(HEADER_CONTENT_TYPE, "application/json");
      con.connect();
      if (log.isDebugEnabled()) {
        log.debug(jsonprint.toString(2));
      }

      IOHelper.writeToConnection(con, jsonprint.toString());

      final byte[] presponse = IOHelper.readBytes(con.getInputStream());
      // Save plot for future use
      if (!file_save.isEmpty()) savePdfPng(presponse, file_save, pformat);

      final String contentType = con.getHeaderField(HEADER_CONTENT_TYPE);
      response.addHeader(HEADER_CONTENT_TYPE, contentType);

      response.getOutputStream().write(presponse, 0, presponse.length);
      response.getOutputStream().flush();
      response.getOutputStream().close();
    } catch (Exception e) {
      throw new ActionException("Couldn't proxy request to print server", e);
    } finally {
      con.disconnect();
    }
  }
 @Override
 public void handlePut(ActionParameters params) throws ActionException {
   log.debug("handlePut");
   User user = new User();
   getUserParams(user, params);
   String password = params.getRequiredParam(PARAM_PASSWORD);
   String[] roles = params.getRequest().getParameterValues("roles");
   User retUser = null;
   try {
     retUser = userService.createUser(user, roles);
     userService.setUserPassword(retUser.getScreenname(), password);
   } catch (ServiceException se) {
     throw new ActionException(se.getMessage(), se);
   }
   JSONObject response = null;
   try {
     response = user2Json(retUser);
   } catch (JSONException je) {
     throw new ActionException(je.getMessage(), je);
   }
   ResponseHelper.writeResponse(params, response);
 }
  @Override
  public void handlePost(ActionParameters params) throws ActionException {
    log.debug("handlePost");
    User user = new User();
    getUserParams(user, params);
    String[] roles = params.getRequest().getParameterValues("roles");
    String password = params.getHttpParam(PARAM_PASSWORD);
    User retUser = null;
    try {
      if (user.getId() > -1) {
        // retUser = userService.modifyUser(user);
        log.debug("roles size: " + roles.length);
        retUser = userService.modifyUserwithRoles(user, roles);
        log.debug("done modifying user");
        if (password != null && !"".equals(password.trim())) {
          userService.updateUserPassword(retUser.getScreenname(), password);
        }
      } else {
        log.debug("NOW IN POST and creating a new user!!!!!!!!!!!!!");
        if (password == null || password.trim().isEmpty()) {
          throw new ActionException("Parameter 'password' not found.");
        }
        retUser = userService.createUser(user);
        userService.setUserPassword(retUser.getScreenname(), password);
      }

    } catch (ServiceException se) {
      throw new ActionException(se.getMessage(), se);
    }
    JSONObject response = null;
    try {
      response = user2Json(retUser);
    } catch (JSONException je) {
      throw new ActionException(je.getMessage(), je);
    }
    ResponseHelper.writeResponse(params, response);
  }
  @Override
  public void handleAction(ActionParameters params) throws ActionException {

    final HttpServletRequest request = params.getRequest();
    try {
      final int groupId = params.getHttpParam(PARAM_ID, -1);
      final LayerGroup group = new LayerGroup();
      group.setId(groupId);
      handleLocalizations(group, PARAM_NAME_PREFIX, request);
      if (group.getLocale() == null) {
        throw new ActionParamsException("Missing names for group!");
      }

      // ************** UPDATE ************************
      if (groupId != -1) {
        if (!layerGroupService.hasPermissionToUpdate(params.getUser(), groupId)) {
          throw new ActionDeniedException(
              "Unauthorized user tried to update layer group - id=" + groupId);
        }
        layerGroupService.update(group);
        ResponseHelper.writeResponse(params, group.getAsJSON());
      }
      // ************** INSERT ************************
      else if (params.getUser().isAdmin()) {
        final int id = layerGroupService.insert(group);
        group.setId(id);
        ResponseHelper.writeResponse(params, group.getAsJSON());
      } else {
        throw new ActionDeniedException(
            "Unauthorized user tried to update layer group - id=" + groupId);
      }

    } catch (Exception e) {
      throw new ActionException("Couldn't update/insert map layer group", e);
    }
  }
  private JSONObject getPrintJSON(ActionParameters params) throws ActionException {
    final JSONObject jsonprint = new JSONObject();
    try {
      final HttpServletRequest httpRequest = params.getRequest();

      // copy parameters
      JSONObject jsparamdata = new JSONObject();
      for (Object key : httpRequest.getParameterMap().keySet()) {
        String keyStr = (String) key;
        // not geojson, tiles, tabledata param ..
        if (!EXTRA_PARAMS.contains(keyStr)) {
          jsparamdata.put(keyStr, params.getHttpParam(keyStr));
        }
      }
      jsonprint.put(KEY_MAPLINK, jsparamdata);

      // Table data
      final JSONObject jsTableData = this.populateTableData(params);
      if (jsTableData != null) jsonprint.put(KEY_PRINTOUT, jsTableData);

      // construct state
      final JSONObject jsonstatedata = new JSONObject();

      final String[] coords = CoordinateParamHandler.parseParam(params.getHttpParam(PARM_COORD));
      if (coords.length == 2) {
        try {
          final double east = ConversionHelper.getDouble(coords[0], -1);
          final double north = ConversionHelper.getDouble(coords[1], -1);
          if (east == -1 || north == -1) {
            throw new IllegalArgumentException(
                "Coordinates not set: " + params.getHttpParam(PARM_COORD));
          }
          jsonstatedata.put(ViewModifier.KEY_EAST, east);
          jsonstatedata.put(ViewModifier.KEY_NORTH, north);
        } catch (Exception ex) {
          throw new ActionException("Could not set coordinates from URL param.", ex);
        }
      }
      jsonstatedata.put(
          ViewModifier.KEY_ZOOM, ConversionHelper.getInt(params.getHttpParam(PARM_ZOOMLEVEL), 10));

      final String[] layers = params.getHttpParam(PARM_MAPLAYERS).split(",");
      final JSONArray configLayers = new JSONArray();
      final JSONArray selectedlayers = new JSONArray();

      // final String referer =
      // RequestHelper.getDomainFromReferer(params.getHttpHeader("Referer"));
      for (String layerString : layers) {
        final String[] layerProps = layerString.split(" ");
        final JSONObject layer =
            LayersParamHandler.getLayerJson(layerProps, "paikkatietoikkuna.fi");
        if (layer != null) {
          selectedlayers.put(layer);
          configLayers.put(layer);
        }
      }

      // GeoJson graphics layers to selected layers
      final String geojs64 = params.getHttpParam(PARM_GEOJSON, "");

      JSONArray geojs = null;
      if (!geojs64.isEmpty()) {
        // decoding geojson
        byte[] decoded = Base64.decodeBase64(geojs64.getBytes());

        geojs = new JSONArray(new String(decoded));

        JSONArray jslays = getGeojsonLayers(geojs);
        for (int i = 0; i < jslays.length(); i++) {
          selectedlayers.put(jslays.getJSONObject(i));
        }
      }
      jsonstatedata.put(ViewModifier.KEY_SELECTEDLAYERS, selectedlayers);
      jsonprint.put(ViewModifier.KEY_STATE, jsonstatedata);

      // printservice uses direct urls to myplaces instead of servletfilter/actionroute proxy
      final boolean useDirectURLForMyplaces = true;
      // populate layer details
      final JSONArray fullLayersConfigJson =
          MapfullHandler.getFullLayerConfig(
              configLayers,
              params.getUser(),
              params.getLocale().getLanguage(),
              PRINT_VIEW,
              ViewTypes.PRINT,
              Collections.EMPTY_SET,
              useDirectURLForMyplaces);

      // GeoJson graphics layers + styles
      if (geojs != null) {
        // Add geojson geometry and styles to layers section
        for (int i = 0; i < geojs.length(); i++) {
          fullLayersConfigJson.put(geojs.getJSONObject(i));
        }
      }

      // Add tiles, (statslayer, wfs)
      //      if (fullLayersConfigJson.toString().contains(VALUE_STATSLAYER)) {
      // Tiles in params ?
      if (!params.getHttpParam(PARM_TILES, "").isEmpty()) {

        JSONArray tiles = getTilesJSON(params);
        addTiles2Layers(fullLayersConfigJson, tiles);
      }
      //    }

      jsonprint.put(KEY_LAYERS, fullLayersConfigJson);

    } catch (Exception e) {
      throw new ActionException("Failed to create image", e);
    }

    return jsonprint;
  }