Exemplo n.º 1
0
  @Override
  public List<GraphObject> getData(
      final SecurityContext securityContext,
      final RenderContext renderContext,
      final String restQuery)
      throws FrameworkException {

    Map<Pattern, Class<? extends Resource>> resourceMap = new LinkedHashMap<>();

    ResourceProvider resourceProvider =
        renderContext == null ? null : renderContext.getResourceProvider();
    if (resourceProvider == null) {
      try {
        resourceProvider = UiResourceProvider.class.newInstance();
      } catch (Throwable t) {
        logger.log(Level.SEVERE, "Couldn't establish a resource provider", t);
        return Collections.EMPTY_LIST;
      }
    }

    // inject resources
    resourceMap.putAll(resourceProvider.getResources());

    Value<String> propertyView = new ThreadLocalPropertyView();
    propertyView.set(securityContext, PropertyView.Ui);

    // initialize variables
    // mimic HTTP request
    HttpServletRequest request =
        new HttpServletRequestWrapper(
            renderContext == null ? securityContext.getRequest() : renderContext.getRequest()) {

          @Override
          public Enumeration<String> getParameterNames() {
            return new IteratorEnumeration(getParameterMap().keySet().iterator());
          }

          @Override
          public String getParameter(String key) {
            String[] p = getParameterMap().get(key);
            return p != null ? p[0] : null;
          }

          @Override
          public Map<String, String[]> getParameterMap() {
            String[] parts = StringUtils.split(getQueryString(), "&");
            Map<String, String[]> parameterMap = new HashMap();
            for (String p : parts) {
              String[] kv = StringUtils.split(p, "=");
              if (kv.length > 1) {
                parameterMap.put(kv[0], new String[] {kv[1]});
              }
            }
            return parameterMap;
          }

          @Override
          public String getQueryString() {
            return StringUtils.substringAfter(restQuery, "?");
          }

          @Override
          public String getPathInfo() {
            return StringUtils.substringBefore(restQuery, "?");
          }

          @Override
          public StringBuffer getRequestURL() {
            return new StringBuffer(restQuery);
          }
        };

    // update request in security context
    securityContext.setRequest(request);

    // HttpServletResponse response = renderContext.getResponse();
    Resource resource =
        ResourceHelper.applyViewTransformation(
            request,
            securityContext,
            ResourceHelper.optimizeNestedResourceChain(
                ResourceHelper.parsePath(
                    securityContext, request, resourceMap, propertyView, GraphObject.id),
                GraphObject.id),
            propertyView);

    // TODO: decide if we need to rest the REST request here
    // securityContext.checkResourceAccess(request, resource.getResourceSignature(),
    // resource.getGrant(request, response), PropertyView.Ui);
    // add sorting & paging
    String pageSizeParameter = request.getParameter(JsonRestServlet.REQUEST_PARAMETER_PAGE_SIZE);
    String pageParameter = request.getParameter(JsonRestServlet.REQUEST_PARAMETER_PAGE_NUMBER);
    String offsetId = request.getParameter(JsonRestServlet.REQUEST_PARAMETER_OFFSET_ID);
    String sortOrder = request.getParameter(JsonRestServlet.REQUEST_PARAMETER_SORT_ORDER);
    String sortKeyName = request.getParameter(JsonRestServlet.REQUEST_PARAMETER_SORT_KEY);
    boolean sortDescending = (sortOrder != null && "desc".equals(sortOrder.toLowerCase()));
    int pageSize = parseInt(pageSizeParameter, NodeFactory.DEFAULT_PAGE_SIZE);
    int page = parseInt(pageParameter, NodeFactory.DEFAULT_PAGE);
    PropertyKey sortKey = null;

    // set sort key
    if (sortKeyName != null) {

      Class<? extends GraphObject> type = resource.getEntityClass();
      if (type == null) {

        // fallback to default implementation
        // if no type can be determined
        type = AbstractNode.class;
      }
      sortKey = StructrApp.getConfiguration().getPropertyKeyForDatabaseName(type, sortKeyName);
    }

    // do action
    Result result = resource.doGet(sortKey, sortDescending, pageSize, page, offsetId);
    result.setIsCollection(resource.isCollectionResource());
    result.setIsPrimitiveArray(resource.isPrimitiveArray());

    // Integer rawResultCount = (Integer) Services.getAttribute(NodeFactory.RAW_RESULT_COUNT +
    // Thread.currentThread().getId());
    PagingHelper.addPagingParameter(result, pageSize, page);

    List<GraphObject> res = result.getResults();

    if (renderContext != null) {
      renderContext.setResult(result);
    }

    return res != null ? res : Collections.EMPTY_LIST;
  }
Exemplo n.º 2
0
  @Override
  public JsonElement serialize(
      WebSocketMessage src, Type typeOfSrc, JsonSerializationContext context) {

    JsonObject root = new JsonObject();
    JsonObject jsonNodeData = new JsonObject();
    JsonObject jsonRelData = new JsonObject();
    JsonArray removedProperties = new JsonArray();
    JsonArray modifiedProperties = new JsonArray();

    if (src.getCommand() != null) {

      root.add("command", new JsonPrimitive(src.getCommand()));
    }

    if (src.getId() != null) {

      root.add("id", new JsonPrimitive(src.getId()));
    }

    if (src.getPageId() != null) {

      root.add("pageId", new JsonPrimitive(src.getPageId()));
    }

    if (src.getMessage() != null) {

      root.add("message", new JsonPrimitive(src.getMessage()));
    }

    if (src.getCode() != 0) {

      root.add("code", new JsonPrimitive(src.getCode()));
    }

    if (src.getSessionId() != null) {

      root.add("sessionId", new JsonPrimitive(src.getSessionId()));
    }

    if (src.getToken() != null) {

      root.add("token", new JsonPrimitive(src.getToken()));
    }

    if (src.getCallback() != null) {

      root.add("callback", new JsonPrimitive(src.getCallback()));
    }

    if (src.getButton() != null) {

      root.add("button", new JsonPrimitive(src.getButton()));
    }

    if (src.getParent() != null) {

      root.add("parent", new JsonPrimitive(src.getParent()));
    }

    if (src.getView() != null) {

      root.add("view", new JsonPrimitive(src.getView()));
    }

    if (src.getSortKey() != null) {

      root.add("sort", new JsonPrimitive(src.getSortKey()));
    }

    if (src.getSortOrder() != null) {

      root.add("order", new JsonPrimitive(src.getSortOrder()));
    }

    if (src.getPageSize() > 0) {

      root.add("pageSize", new JsonPrimitive(src.getPageSize()));
    }

    if (src.getPage() > 0) {

      root.add("page", new JsonPrimitive(src.getPage()));
    }

    JsonArray nodesWithChildren = new JsonArray();
    Set<String> nwc = src.getNodesWithChildren();

    if ((nwc != null) && !src.getNodesWithChildren().isEmpty()) {

      for (String nodeId : nwc) {

        nodesWithChildren.add(new JsonPrimitive(nodeId));
      }

      root.add("nodesWithChildren", nodesWithChildren);
    }

    // serialize session valid flag (output only)
    root.add("sessionValid", new JsonPrimitive(src.isSessionValid()));

    // UPDATE only, serialize only removed and modified properties and use the correct values
    if ((src.getGraphObject() != null)) {

      GraphObject graphObject = src.getGraphObject();

      if (!src.getModifiedProperties().isEmpty()) {

        for (PropertyKey modifiedKey : src.getModifiedProperties()) {

          modifiedProperties.add(toJsonPrimitive(modifiedKey));

          //					Object newValue = graphObject.getProperty(modifiedKey);
          //
          //					if (newValue != null) {
          //
          //						if (graphObject instanceof AbstractNode) {
          //
          //							src.getNodeData().put(modifiedKey.jsonName(), newValue);
          //						} else {
          //
          //							src.getRelData().put(modifiedKey.jsonName(), newValue);
          //						}
          //
          //					}

        }

        root.add("modifiedProperties", modifiedProperties);
      }

      if (!src.getRemovedProperties().isEmpty()) {

        for (PropertyKey removedKey : src.getRemovedProperties()) {

          removedProperties.add(toJsonPrimitive(removedKey));
        }

        root.add("removedProperties", removedProperties);
      }
    }

    // serialize node data
    if (src.getNodeData() != null) {

      for (Entry<String, Object> entry : src.getNodeData().entrySet()) {

        Object value = entry.getValue();
        String key = entry.getKey();

        if (value != null) {

          jsonNodeData.add(key, toJsonPrimitive(value));
        }
      }

      root.add("data", jsonNodeData);
    }

    // serialize relationship data
    if (src.getRelData() != null) {

      for (Entry<String, Object> entry : src.getRelData().entrySet()) {

        Object value = entry.getValue();
        String key = entry.getKey();

        if (value != null) {

          jsonRelData.add(key, toJsonPrimitive(value));
        }
      }

      root.add("relData", jsonRelData);
    }

    // serialize result list
    if (src.getResult() != null) {

      if (src.getView() != null) {

        try {
          propertyView.set(null, src.getView());

        } catch (FrameworkException fex) {

          logger.log(Level.WARNING, "Unable to set property view", fex);
        }

      } else {

        try {
          propertyView.set(null, PropertyView.Ui);

        } catch (FrameworkException fex) {

          logger.log(Level.WARNING, "Unable to set property view", fex);
        }
      }

      JsonArray result = new JsonArray();

      for (GraphObject obj : src.getResult()) {

        result.add(graphObjectSerializer.serialize(obj, System.currentTimeMillis()));
      }

      root.add("result", result);
      root.add("rawResultCount", toJsonPrimitive(src.getRawResultCount()));
    }

    // serialize result tree
    //		if (src.getResultTree() != null) {
    //
    //			TreeNode node = src.getResultTree();
    //
    //			root.add("root", buildTree(node, context));
    //
    //		}

    return root;
  }