Ejemplo n.º 1
0
  private JSONArray getPublishableLayers(final JSONArray selectedLayers, final User user)
      throws ActionException {
    if (selectedLayers == null || user == null) {
      throw new ActionParamsException("Could not get selected layers");
    }
    final JSONArray filteredList = new JSONArray();
    log.debug("Selected layers:", selectedLayers);

    String userUuid = user.getUuid();
    try {
      for (int i = 0; i < selectedLayers.length(); ++i) {
        JSONObject layer = selectedLayers.getJSONObject(i);
        String layerId = layer.getString("id");
        if (layerId.startsWith(PREFIX_MYPLACES)) {
          // check publish right for published myplaces layer
          if (hasRightToPublishMyPlaceLayer(layerId, userUuid, user.getScreenname())) {
            filteredList.put(layer);
          }
        } else if (layerId.startsWith(PREFIX_BASELAYER)) {
          // check publish right for base layer
          if (hasRightToPublishBaseLayer(layerId, user)) {
            filteredList.put(layer);
          }
        }
        // check publish right for normal layer
        else if (hasRightToPublishLayer(layerId, user)) {
          filteredList.put(layer);
        }
      }
    } catch (Exception e) {
      log.error(e, "Error parsing myplaces layers from published layers", selectedLayers);
    }
    log.debug("Filtered layers:", filteredList);
    return filteredList;
  }
Ejemplo n.º 2
0
 private boolean hasRightToPublishMyPlaceLayer(
     final String layerId, final String userUuid, final String publisherName) {
   final long categoryId =
       ConversionHelper.getLong(layerId.substring(PREFIX_MYPLACES.length()), -1);
   if (categoryId == -1) {
     log.warn("Error parsing layerId:", layerId);
     return false;
   }
   final List<Long> publishedMyPlaces = new ArrayList<Long>();
   publishedMyPlaces.add(categoryId);
   final List<MyPlaceCategory> myPlacesLayers =
       myPlaceService.getMyPlaceLayersById(publishedMyPlaces);
   for (MyPlaceCategory place : myPlacesLayers) {
     if (place.getUuid().equals(userUuid)) {
       myPlaceService.updatePublisherName(categoryId, userUuid, publisherName); // make it public
       return true;
     }
   }
   log.warn(
       "Found my places layer in selected that isn't users own or isnt published any more! LayerId:",
       layerId,
       "User UUID:",
       userUuid);
   return false;
 }
Ejemplo n.º 3
0
  /**
   * Creates SLD style
   *
   * @param layer
   * @param styleName
   * @return style
   */
  private Style getSLDStyle(WFSLayerStore layer, String styleName) {
    Style style = null;
    log.debug("Trying to get style with name:", styleName);
    if (layer.getStyles().containsKey(styleName)) {
      style = createSLDStyle(layer.getStyles().get(styleName).getSLDStyle());
    } else if (STYLE_HIGHLIGHT.equals(styleName)) {
      style = createSLDStyle(layer.getSelectionSLDStyle());
    } else if (layer.getStyles().containsKey(STYLE_DEFAULT)) {
      style = createSLDStyle(layer.getStyles().get(STYLE_DEFAULT).getSLDStyle());
    }

    // if styles couldn't be parsed, use defaults
    if (style == null) {
      log.info("Layer style not customized or parsing failed. Using defaults.");
      if (STYLE_HIGHLIGHT.equals(styleName)) {
        // style = createDefaultHighlightSLDStyle(layer.getGMLGeometryProperty());
        // TODO: check if we really always want to use without namespace
        style = createDefaultHighlightSLDStyle(layer.getGMLGeometryPropertyNoNamespace());
      } else {
        style =
            createSLDStyle(
                WFSImage.class.getResourceAsStream(DEFAULT_SLD)); // getClass() (non-static)
      }
    }
    if (style == null) {
      // something is seriously wrong, even default styles can't be parsed
      log.error("Failed to get SLD style (even default failed)!!");
    }

    return style;
  }
Ejemplo n.º 4
0
  @Override
  public void type(
      Resource type,
      List<Pair<Resource, XSDDatatype>> simpleProperties,
      List<Pair<Resource, Object>> linkProperties,
      List<Pair<Resource, String>> geometryProperties)
      throws IOException {
    requestResponse.setFeatureIri(type);

    log.debug("[fe] registering (generic) output type for " + type);

    /*
     * List<String> layerSelectedProperties = layer
     * .getSelectedFeatureParams(session.getLanguage());
     */
    selectedProperties.add(0, "__fid");
    log.debug("- Property:" + "__fid" + " as 0");
    for (Pair<Resource, XSDDatatype> prop : simpleProperties) {

      log.debug("- Property:" + prop.getKey() + " as " + selectedProperties.size());
      selectedPropertiesIndex.put(prop.getKey(), selectedProperties.size());
      selectedProperties.add(prop.getKey().getLocalPart());
    }
    selectedProperties.add("__centerX");
    log.debug("- Property:" + "__centerX" + " as " + selectedProperties.size());
    selectedProperties.add("__centerY");
    log.debug("- Property:" + "__centerY" + " as " + selectedProperties.size());
  }
Ejemplo n.º 5
0
  public static JSONObject getConfiguration(final View view) throws ViewException {
    final JSONObject configuration = new JSONObject();
    final List<Bundle> bundles = view.getBundles();
    for (Bundle s : bundles) {
      final String conf = s.getConfig();
      final String state = s.getState();
      final String name = s.getBundleinstance();
      try {
        // setup bundle node in config
        JSONObject bundle = new JSONObject();
        configuration.put(name, bundle);

        // setup conf for bundle
        if (conf != null) {
          bundle.put("conf", new JSONObject(conf));
        } else {
          log.warn("Could not get configuration fragment for bundle '", name, "'");
        }
        // setup state for bundle
        if (state != null) {
          bundle.put("state", new JSONObject(state));
        } else {
          log.warn("Could not get state fragment for bundle '", name, "'");
        }
      } catch (Exception ex) {
        log.error("Malformed JSON in configuration fragment for bundle", name, conf);
      }
    }
    return configuration;
  }
  /**
   * Process of the job
   *
   * <p>Worker calls this when starts the job.
   */
  public String run() {

    log.debug(PROCESS_STARTED + " " + getKey());
    setResourceSending();

    // if different SRS, create transforms for geometries
    if (!this.session.getLocation().getSrs().equals(this.layer.getSRSName())) {
      this.transformService =
          this.session.getLocation().getTransformForService(this.layer.getCrs(), true);
      this.transformClient =
          this.session.getLocation().getTransformForClient(this.layer.getCrs(), true);
    }

    // check that the job isn't canceled
    if (!goNext()) {
      log.debug("[fe] Cancelled");
      return STATUS_CANCELED;
    }
    // run job specific tasks
    boolean completed = runRequestedJob();
    if (!completed) {
      log.debug("[fe] Cancelled");
      return STATUS_CANCELED;
    }
    log.debug("[fe] " + PROCESS_ENDED + " " + getKey());
    return "success";
  }
Ejemplo n.º 7
0
 public static JSONArray getStartupSequence(final View view) throws ViewException {
   final JSONArray startupSequence = new JSONArray();
   final List<Bundle> bundles = view.getBundles();
   log.debug("Got", bundles.size(), "states for view", view.getId());
   for (Bundle s : bundles) {
     final String startup = s.getStartup();
     final String name = s.getName();
     if (startup != null) {
       try {
         startupSequence.put(new JSONObject(startup));
       } catch (JSONException jsonex) {
         log.error(
             jsonex,
             "Malformed JSON in startup sequence fragment for bundle:",
             name,
             "- JSON:",
             startup);
       }
     } else {
       throw new ViewException(
           "Could not get startup sequence fragment for bundle '" + name + "'");
     }
   }
   return startupSequence;
 }
Ejemplo n.º 8
0
  @Override
  public void handleGet(ActionParameters params) throws ActionException {
    log.info("handleGet");
    final JSONObject response;
    long id = getId(params);
    try {
      if (id > -1) {
        log.info("handleGet: has id");
        User user = userService.getUser(id);
        response = user2Json(user);
      } else {
        log.info("handleGet: no id");
        List<User> users = userService.getUsers();

        log.info("found: " + users.size() + "users");
        response = new JSONObject();
        JSONArray arr = new JSONArray();
        response.put("users", arr);

        List<User> newUsers = userService.getUsersWithRoles();

        for (User user : newUsers) {
          arr.put(user2Json(user));
        }
      }
    } catch (ServiceException se) {
      throw new ActionException(se.getMessage(), se);
    } catch (JSONException je) {
      throw new ActionException(je.getMessage(), je);
    }
    log.info(response);
    ResponseHelper.writeResponse(params, response);
  }
Ejemplo n.º 9
0
  private boolean hasRightToPublishBaseLayer(final String layerId, final User user) {

    final long id = ConversionHelper.getLong(layerId.substring(PREFIX_BASELAYER.length()), -1);
    if (id == -1) {
      log.warn("Error parsing layerId:", layerId);
      return false;
    }
    List<Long> list = new ArrayList<Long>();
    list.add(id);
    Map<Long, List<Permissions>> map =
        permissionsService.getPermissionsForBaseLayers(list, Permissions.PERMISSION_TYPE_PUBLISH);
    List<Permissions> permissions = map.get(id);

    boolean hasPermission = false;
    hasPermission =
        permissionsService.permissionGrantedForRolesOrUser(
            user, permissions, Permissions.PERMISSION_TYPE_PUBLISH);
    if (!hasPermission) {
      log.warn(
          "User tried to publish layer with no publish permission. LayerID:",
          layerId,
          "- User:",
          user);
    }
    return hasPermission;
  }
  public void handleAction(final ActionParameters params) throws ActionException {
    log.debug("in handle action");

    final String term = params.getHttpParam(PARAM_TERM);
    if (term == null || term.equals("")) {
      throw new ActionParamsException("Search string was null");
    }

    final String error = SearchWorker.checkLegalSearch(term);

    if (!SearchWorker.STR_TRUE.equals(error)) {
      // write error message key
      ResponseHelper.writeResponse(params, error);
    } else {
      final Locale locale = params.getLocale();
      final SearchCriteria sc = new SearchCriteria();

      final String geographical_names = params.getHttpParam(PARAM_GEO_NAMES);
      final String addresses = params.getHttpParam(PARAM_ADDRESSES);
      final String epsg = params.getHttpParam(PARAM_EPSG_KEY);

      sc.setSearchString(term);
      sc.setSRS(epsg); // eg. EPSG:3067
      sc.setLocale(locale.getLanguage());

      sc.addParam(PARAM_REGION, params.getHttpParam(PARAM_REGION, ""));
      sc.addParam(PARAM_COUNTRY, params.getHttpParam(PARAM_COUNTRY, ""));
      sc.addParam(PARAM_FILTER, params.getHttpParam(PARAM_FILTER, "false"));
      sc.addParam(PARAM_NORMAL, params.getHttpParam(PARAM_NORMAL, "false"));
      sc.addParam(PARAM_LON, params.getHttpParam(PARAM_LON, ""));
      sc.addParam(PARAM_LAT, params.getHttpParam(PARAM_LAT, ""));
      sc.addParam(PARAM_ADDRESSES, params.getHttpParam(PARAM_ADDRESSES));
      sc.addParam(PARAM_LOCATION_TYPE, params.getHttpParam(PARAM_LOCATION_TYPE, ""));
      sc.addParam(PARAM_NAME_LANG, params.getHttpParam(PARAM_NAME_LANG, ""));
      sc.addParam(PARAM_NEAREST, params.getHttpParam(PARAM_NEAREST, ""));

      if (isFuzzy(sc)) {
        sc.addParam(PARAM_FUZZY, "true");
      }

      for (String channelId : channels) {
        if (geographical_names != null
            && geographical_names.equals("true")
            && channelId.equals(ELFGEOLOCATOR_CHANNEL)) {
          log.debug("adding channel: ELFGEOLOCATOR_CHANNEL");
          sc.addChannel(channelId);
        }
        if (addresses != null
            && addresses.equals("true")
            && channelId.equals(ELFADDRESSLOCATOR_CHANNEL)) {
          log.debug("adding channel: ELFADDRESSLOCATOR_CHANNEL");
          sc.addChannel(channelId);
        }
      }

      final JSONObject result = SearchWorker.doSearch(sc);
      ResponseHelper.writeResponse(params, result);
    }
  }
Ejemplo n.º 11
0
  public void handleAction(final FlowModel flowModel) throws OgcFlowException {

    WFSLayer wfsLayer = findWFSLayer(flowModel);
    log.debug("Drawing image for wfs layer '" + wfsLayer.getName(locale) + "'");
    List<Future<WFSResponseCapsule>> futures = new ArrayList<Future<WFSResponseCapsule>>();
    /* Create workers */
    log.debug("We have " + wfsLayer.getSelectedFeatureTypes().size() + " selected feature types");
    for (SelectedFeatureType sft : wfsLayer.getSelectedFeatureTypes()) {
      FeatureType ft = sft.getFeatureType();
      log.debug("Processing featuretype '", ft.getTitle(locale), "'...");

      /* Create filter */
      String geomName = ft.getBboxParameterName();
      FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(GeoTools.getDefaultHints());

      GetFeaturesWorker worker =
          new GetFeaturesWorker(sft, getExtendedMapViewBbox(ff, geomName, flowModel), false);
      Future<WFSResponseCapsule> future = WfsExecutorService.schedule(worker);
      futures.add(future);
    }

    /* collect results */
    FeatureCollection<SimpleFeatureType, SimpleFeature> features =
        WfsExecutorService.collectFeaturesFromFutures(futures);
    String[] bbox = getBbox(flowModel);
    Double bboxMinX = Double.parseDouble(bbox[0]);
    Double bboxMinY = Double.parseDouble(bbox[1]);
    Double bboxMaxX = Double.parseDouble(bbox[2]);
    Double bboxMaxY = Double.parseDouble(bbox[3]);

    MapContext mapContext = buildMapContext();
    ReferencedEnvelope bounds =
        new ReferencedEnvelope(
            bboxMaxX, bboxMinX, bboxMaxY, bboxMinY, mapContext.getCoordinateReferenceSystem());

    /* Add all found features */
    if (features != null && features.size() > 0) {
      log.debug("Parsing found " + features.size() + " features.");
      String styleString = wfsLayer.getStyle();

      // TODO: sld styles should be stored in the database
      if (styleString == null || "".equals(styleString)) {
        styleString =
            SLDStore.getSLD(
                wfsLayer
                    .getWmsName()); // MapLayerServiceNoDbImpl.getSldStyle(wfsLayer.getWmsName());
      }

      Style style = SLD.styles(createSLDStyle(styleString))[0];
      mapContext.addLayer(features, style);
    } else {
      log.debug("Parsing found no features.");
    }

    BufferedImage image = renderImageFromFeatures(flowModel, mapContext, bounds);
    /*image.getGraphics().setColor(new Color(1f, 0, 0));
    image.getGraphics().drawRect(1, 1, image.getWidth()-1, image.getHeight()-1);*/
    flowModel.put("image", image);
  }
  public void handleAction(ActionParameters params) throws ActionException {

    final JSONObject root = new JSONObject();

    // Because of analysis layers
    String sid = params.getHttpParam(ID, "n/a");
    final int id = ConversionHelper.getInt(getBaseLayerId(sid), 0);

    final HttpServletResponse response = params.getResponse();
    response.setContentType("application/json");

    if (id == 0) {
      JSONHelper.putValue(root, ERROR, ERROR_NO_ID);
      ResponseHelper.writeResponse(params, root);
      // FIXME: throw ActionParamsException instead and modify client
      // response parsing
      return;
    }

    String json = WFSLayerConfiguration.getCache(id + "");
    if (json == null) {
      WFSLayerConfiguration lc = layerConfigurationService.findConfiguration(id);

      log.warn("id", id);
      log.warn(lc);

      // Extra manage for analysis
      if (sid.indexOf(ANALYSIS_PREFIX) > -1) {
        log.warn("sid", sid);
        // set id to original analysis layer id
        lc.setLayerId(sid);
        // Set analysis layer fields as id based
        lc.setSelectedFeatureParams(getAnalysisFeatureProperties(sid));
      }
      // Extra manage for analysis
      else if (sid.indexOf(MYPLACES_PREFIX) > -1) {
        log.warn("sid", sid);
        // set id to original my places layer id
        lc.setLayerId(sid);
      } else if (sid.indexOf(USERLAYER_PREFIX) > -1) {
        log.warn("sid", sid);
        // set id to original user layer id
        lc.setLayerId(sid);
      }
      if (lc == null) {
        JSONHelper.putValue(root, ERROR, ERROR_NOT_FOUND);
        ResponseHelper.writeResponse(params, root);
        // FIXME: throw ActionParamsException instead and modify client
        // response parsing
        return;
      }
      lc.save();
    }
    JSONHelper.putValue(root, RESULT, RESULT_SUCCESS);
    ResponseHelper.writeResponse(params, root);
  }
 public List<Keyword> findKeywordsMatching(final String name) {
   if (name == null) {
     return Collections.emptyList();
   }
   log.debug("Finding keywords matching:", name);
   final List<Keyword> keyword =
       queryForList(getNameSpace() + ".find-by-name", name.toLowerCase());
   log.debug("Found keywords:", keyword);
   return keyword;
 }
Ejemplo n.º 14
0
 /**
  * Parses SLD style from a String (XML)
  *
  * @param xml
  * @return sld
  */
 private Style createSLDStyle(String xml) {
   if (xml == null) {
     log.info("Trying to create style from <null> String!");
     return null;
   }
   final Style style = createSLDStyle(new ByteArrayInputStream(xml.getBytes()));
   if (style == null) {
     log.warn("Couldn't create style from XML:", xml);
   }
   return style;
 }
 public List<Keyword> findKeywordsMatching(final String name, final String lang) {
   if (name == null) {
     return Collections.emptyList();
   }
   log.debug("Finding keywords matching:", name);
   final Keyword param = new Keyword();
   param.setValue(name.toLowerCase());
   param.setLang(lang);
   final List<Keyword> keyword = queryForList(getNameSpace() + ".find-by-name-and-lang", param);
   log.debug("Found keywords:", keyword);
   return keyword;
 }
  private String transformResponse(final String xslt, final String response) {

    if (xslt == null || "".equals(xslt)) {
      // if not found, return as is
      return response;
    }

    ByteArrayInputStream respInStream = null;
    ByteArrayInputStream xsltInStream = null;
    Writer outWriter = null;
    try {
      final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      factory.setValidating(false);
      factory.setNamespaceAware(true);
      final DocumentBuilder builder = factory.newDocumentBuilder();

      respInStream = new ByteArrayInputStream(response.getBytes("UTF-8"));
      final Document document = builder.parse(respInStream);
      xsltInStream = new ByteArrayInputStream(xslt.getBytes());
      final StreamSource stylesource = new StreamSource(xsltInStream);
      final String transformedResponse = getFormatedJSONString(document, stylesource);

      if (transformedResponse == null || transformedResponse.isEmpty()) {
        log.info("got empty result from transform with:", xslt, " - Response:", response);
        return response;
      }

      return transformedResponse;
    } catch (Exception e) {
      log.error(e, "Error transforming GFI response: ", response, "- with XSLT:", xslt);
    } finally {
      if (respInStream != null) {
        try {
          respInStream.close();
        } catch (Exception ignored) {
        }
      }
      if (xsltInStream != null) {
        try {
          xsltInStream.close();
        } catch (Exception ignored) {
        }
      }
      if (outWriter != null) {
        try {
          outWriter.close();
        } catch (Exception ignored) {
        }
      }
    }
    // Sanitize response
    return Jsoup.clean(response, Whitelist.relaxed());
  }
Ejemplo n.º 17
0
 public static void teardown() {
   if (schedulerService != null) {
     try {
       schedulerService.shutdownScheduler();
     } catch (final SchedulerException e) {
       log.error(e, "Failed to shut down the Oskari scheduler");
     }
   }
   DS_HELPER.teardown();
   JedisManager.shutdown();
   log.info("Context destroy");
 }
Ejemplo n.º 18
0
 /**
  * Parses SLD style from an InputStream (XML)
  *
  * @param xml
  * @return sld
  */
 private Style createSLDStyle(InputStream xml) {
   Configuration config = new SLDConfiguration();
   Parser parser = new Parser(config);
   StyledLayerDescriptor sld = null;
   try {
     sld = (StyledLayerDescriptor) parser.parse(xml);
   } catch (Exception e) {
     log.error(e, "Failed to create SLD Style");
     log.error(xml);
     return null;
   }
   return SLD.styles(sld)[0];
 }
Ejemplo n.º 19
0
 /**
  * Creates own sld style by replacing
  *
  * @return sld
  */
 public Style createCustomSLDStyle() {
   InputStream resource = WFSImage.class.getResourceAsStream(OSKARI_CUSTOM_SLD);
   try {
     String xml = IOHelper.readString(resource, "ISO-8859-1");
     customStyle.replaceValues(xml, isHighlight);
     xml = customStyle.getSld();
     return createSLDStyle(xml);
   } catch (Exception e) {
     log.error(e, "Failed to get Own SLD Style");
     log.error(resource);
   }
   return null;
 }
  /**
   * Sends list of feature geometries
   *
   * @param geometries
   * @param channel
   */
  protected void sendWFSFeatureGeometries(List<List<Object>> geometries, String channel) {
    if (geometries == null || geometries.size() == 0) {
      log.warn("Failed to send feature geometries");
      return;
    }
    Map<String, Object> output = new HashMap<String, Object>();
    output.put(OUTPUT_LAYER_ID, this.layerId);
    output.put(OUTPUT_GEOMETRIES, geometries);
    output.put(OUTPUT_KEEP_PREVIOUS, this.session.isKeepPrevious());

    log.debug("Sending", geometries.size(), "geometries");
    this.service.addResults(this.session.getClient(), channel, output);
  }
Ejemplo n.º 21
0
 /**
  * Creates default highlight sld style by replacing geomtype
  *
  * @return sld
  */
 public Style createDefaultHighlightSLDStyle(String geom_type) {
   log.debug("Creating default highlight SLD for:", geom_type);
   InputStream resource = WFSImage.class.getResourceAsStream(HIGHLIGHT_SLD);
   try {
     String xml = IOHelper.readString(resource, "ISO-8859-1");
     xml = xml.replaceAll(GEOM_TYPE_PLACEHOLDER, geom_type);
     return createSLDStyle(xml);
   } catch (Exception e) {
     log.error(e, "Failed to get Default highlight SLD Style - geom type ", geom_type);
     log.error(resource);
   }
   return null;
 }
Ejemplo n.º 22
0
 private Bundle addBundle(final View view, final String bundleid) {
   Bundle bundle = view.getBundleByName(bundleid);
   if (bundle == null) {
     log.info("Bundle with id:", bundleid, "not found in currentView - adding");
     if (!bundleCache.containsKey(bundleid)) {
       log.warn("Trying to add bundle that isn't loaded:", bundleid, "- Skipping it!");
       return null;
     }
     bundle = bundleCache.get(bundleid).clone();
     view.addBundle(bundle);
   }
   return bundle;
 }
Ejemplo n.º 23
0
  /**
   * Constructor for image of certain layer and style
   *
   * @param layer
   * @param styleName
   */
  public WFSImage(WFSLayerStore layer, String client, String styleName, String highlightStyleName) {
    if (layer == null || styleName == null) {
      log.error("Failed to construct image (undefined params)");
      return;
    }

    // check if tile buffer is given
    String tileBufferKey;
    if (styleName.startsWith(PREFIX_CUSTOM_STYLE)) {
      tileBufferKey = PREFIX_CUSTOM_STYLE;
    } else {
      tileBufferKey = styleName;
    }
    if (layer.getTileBuffer() != null && layer.getTileBuffer().containsKey(tileBufferKey)) {
      bufferSize = layer.getTileBuffer().get(tileBufferKey);
    }
    log.debug(tileBufferKey, "=", bufferSize);

    // TODO: possibility to change the custom style store key to sessionID (it is hard without
    // connection to get client)
    if (styleName.startsWith(PREFIX_CUSTOM_STYLE) && client != null) {
      try {
        this.customStyle = WFSCustomStyleStore.create(client, layer.getLayerId());
        if (this.customStyle == null) {
          this.style = null;
          log.error("WFSCustomStyleStore not created", client, layer.getLayerId());
          return;
        }
        this.customStyle.setGeometry(
            layer.getGMLGeometryProperty().replaceAll("^[^_]*:", "")); // set the geometry name
        log.debug(this.customStyle.getGeometry());

        if (highlightStyleName == null) {
          this.style = createCustomSLDStyle();
        } else {
          isHighlight = true;
          this.style = createCustomSLDStyle();
        }
      } catch (Exception e) {
        this.style = null;
        log.error(e, "JSON parsing failed for WFSCustomStyleStore");
        return;
      }
    } else if (highlightStyleName == null) {
      this.style = getSLDStyle(layer, styleName);
    } else {
      isHighlight = true;
      this.style = getSLDStyle(layer, highlightStyleName);
    }
  }
 public long addKeyword(final Keyword keyword) {
   // check if keyword is already inserted with matching language and return the id without
   // inserting!
   final Keyword dbKey = findExactKeyword(keyword.getValue(), keyword.getLang());
   if (dbKey != null) {
     log.warn("Keyword already saved:", keyword, "->", dbKey);
     keyword.setId(dbKey.getId());
     return dbKey.getId();
   }
   log.warn("Adding keyword:", keyword);
   final Long id = queryForObject(getNameSpace() + ".add-keyword", keyword);
   keyword.setId(id);
   log.warn("Got keyword id:", id);
   return id;
 }
Ejemplo n.º 25
0
  private void setupBundle(final View view, final JSONObject publisherData, final String bundleid) {

    final JSONObject bundleData = publisherData.optJSONObject(bundleid);
    if (bundleData != null && bundleData.names().length() > 0) {
      log.info("config found for", bundleid);
      final Bundle bundle = addBundle(view, bundleid);
      mergeBundleConfiguration(bundle, bundleData, null);
    } else {
      log.warn("config not found for", bundleid, "- removing bundle.");
      // We have to remove the bundle...
      // TODO: check if we really want to remove the bundle from view since it could be template
      // view???
      view.removeBundle(bundleid);
    }
  }
  public JSONObject getWMSFeatureInfo(final GFIRequestParams params) {

    final Map<String, String> headers = new HashMap<String, String>();
    headers.put(
        "User-Agent",
        "Mozilla/5.0 "
            + "(Windows; U; Windows NT 6.0; pl; rv:1.9.1.2) "
            + "Gecko/20090729 Firefox/3.5.2");
    headers.put("Referer", "/");
    headers.put("Cookie", "_ptifiut_");

    String gfiResponse;
    try {
      final String url = params.getGFIUrl();
      log.debug("Calling GFI url:", url);
      gfiResponse = IOHelper.getURL(url, headers);
      log.debug("Got GFI response:", gfiResponse);
    } catch (IOException e) {
      log.error(e, "Couldn't call GFI URL with params:", params);
      return null;
    }
    if (gfiResponse != null && !gfiResponse.isEmpty()) {
      final JSONObject response = new JSONObject();
      try {
        response.put(GetGeoPointDataService.TYPE, params.getLayer().getType());
        response.put(GetGeoPointDataService.LAYER_ID, params.getLayer().getId());
        final String xslt = params.getLayer().getXslt();
        if (xslt == null || xslt.isEmpty()) {
          response.put(
              GetGeoPointDataService.PRESENTATION_TYPE,
              GetGeoPointDataService.PRESENTATION_TYPE_TEXT);
          response.put(GetGeoPointDataService.CONTENT, gfiResponse);
        } else {
          final String transformedResult = transformResponse(xslt, gfiResponse);
          JSONObject respObj = new JSONObject(transformedResult);
          response.put(
              GetGeoPointDataService.PRESENTATION_TYPE,
              GetGeoPointDataService.PRESENTATION_TYPE_JSON);
          response.put(GetGeoPointDataService.CONTENT, respObj);
        }
      } catch (JSONException je) {
        log.error(je, "Couldn't construct GFI response from:", gfiResponse, "- params:", params);
        return null;
      }
      return response;
    }
    return null;
  }
Ejemplo n.º 27
0
  /**
   * Transforms bufferedImage to byte[]
   *
   * @param bufferedImage
   * @return image
   */
  public static byte[] imageToBytes(BufferedImage bufferedImage) {
    if (bufferedImage == null) {
      log.error("No image given");
      return null;
    }

    ByteArrayOutputStream byteaOutput = new ByteArrayOutputStream();
    try {
      ImageIO.write(bufferedImage, "png", byteaOutput);
      byteaOutput.flush();
      byteaOutput.close();
    } catch (Exception e) {
      log.error(e, "Image could not be written into stream");
    }
    return byteaOutput.toByteArray();
  }
Ejemplo n.º 28
0
  /**
   * Sets bufferedImage to cache
   *
   * @param layerId
   * @param srs
   * @param bbox
   * @param zoom
   * @param persistent
   * @return buffered image from cache
   */
  public static void setCache(
      BufferedImage bufferedImage,
      String layerId,
      String styleName,
      String srs,
      Double[] bbox,
      long zoom,
      boolean persistent) {
    if (layerId == null || styleName == null || srs == null || bbox.length != 4) {
      log.error("Cache key couldn't be created");
      return;
    }

    // no persistent cache for custom styles
    if (styleName.startsWith(PREFIX_CUSTOM_STYLE)) {
      persistent = false;
    }

    byte[] byteImage = imageToBytes(bufferedImage);
    String sBbox = bbox[0] + "-" + bbox[1] + "-" + bbox[2] + "-" + bbox[3];
    String sKey = KEY + layerId + "_" + styleName + "_" + srs + "_" + sBbox + "_" + zoom;
    if (!persistent) {
      sKey = sKey + "_temp";
    }

    byte[] key = sKey.getBytes();

    JedisManager.setex(key, 86400, byteImage);
  }
Ejemplo n.º 29
0
  public SimpleFeatureBuilder getAndSetFeatureBuilder(Resource type) {

    SimpleFeatureBuilder sfb = responseBuilders.get(type);
    if (sfb == null) {

      SimpleFeatureTypeBuilder ftb = new SimpleFeatureTypeBuilder();
      ftb.setName(type.getLocalPart());
      ftb.setNamespaceURI(type.getNs());

      // add a geometry property

      ftb.setCRS(crs); // set crs first
      ftb.add("geometry", Geometry.class, crs); // then add
      // geometry

      SimpleFeatureType schema = ftb.buildFeatureType();

      sfb = new SimpleFeatureBuilder(schema);

      responseBuilders.put(type, sfb);

      log.debug("[fe] creating featurebuilder for : " + type);
    }
    return sfb;
  }
Ejemplo n.º 30
0
  /**
   * Merge href sub features to main features
   *
   * @param jlist addtional features to where local hrefs point
   * @param res href property resourse
   */
  public void merge(List<JSONObject> jlist, Resource res) {
    // Get index of resource
    Integer keyInd = selectedPropertiesIndex.get(res);
    if (keyInd == null) return;

    try {
      // Loop features
      for (List lis : list) {
        // Href key
        Object val = lis.get(keyInd);
        if (val instanceof List) {
          ArrayList<String> vallist = (ArrayList<String>) val;
          List<Map<String, Object>> hrefFeas = new ArrayList<Map<String, Object>>();
          for (String lval : vallist) {
            if (lval == null) continue;
            lval = lval.replace("#", "");
            for (JSONObject js : jlist) {
              if (JSONHelper.getStringFromJSON(js, "id", "").equals(lval)) {
                hrefFeas.add(JSONHelper.getObjectAsMap(js));
                break;
              }
            }
          }
          // Replace refs with objects
          if (hrefFeas.size() > 0) lis.set(keyInd, hrefFeas);
        }
      }

    } catch (Exception ee) {
      log.debug("Local href subfeature merge failed:", ee);
    }
  }