Package org.structr.rest.resource

Examples of org.structr.rest.resource.Resource


        boolean found = false;
       
        // check views first
        if (propertyViews.contains(part)) {
       
          Resource resource = new ViewFilterResource();
          resource.checkAndConfigure(part, securityContext, request);
          resource.configureIdProperty(defaultIdProperty);
          resource.configurePropertyView(propertyView);
         
          resourceChain.add(resource);
         
          // mark this part as successfully parsed
          found = true;
         
        } else {

          // look for matching pattern
          for (Map.Entry<Pattern, Class<? extends Resource>> entry : resourceMap.entrySet()) {

            Pattern pattern = entry.getKey();
            Matcher matcher = pattern.matcher(pathParts[i]);

            if (matcher.matches()) {

              Class<? extends Resource> type = entry.getValue();
              Resource resource              = null;

              try {

                // instantiate resource constraint
                resource = type.newInstance();
              } catch (Throwable t) {

                logger.log(Level.WARNING, "Error instantiating resource class", t);

              }

              if (resource != null) {

                // set security context
                resource.setSecurityContext(securityContext);

                if (resource.checkAndConfigure(part, securityContext, request)) {

                  logger.log(Level.FINE, "{0} matched, adding resource of type {1} for part {2}", new Object[] { matcher.pattern(), type.getName(),
                    part });

                  // allow constraint to modify context
                  resource.configurePropertyView(propertyView);
                  resource.configureIdProperty(defaultIdProperty);

                  // add constraint and go on
                  resourceChain.add(resource);

                  found = true;
View Full Code Here


  protected void doDelete(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {

    SecurityContext securityContext = null;
    Authenticator authenticator     = null;
    RestMethodResult result         = null;
    Resource resource               = null;

    try {

      // first thing to do!
      request.setCharacterEncoding("UTF-8");
      response.setCharacterEncoding("UTF-8");
      response.setContentType("application/json; charset=utf-8");

      // isolate request authentication in a transaction
      try (final Tx tx = StructrApp.getInstance().tx()) {
        authenticator = config.getAuthenticator();
        securityContext = authenticator.initializeAndExamineRequest(request, response);
        tx.success();
      }

      final App app = StructrApp.getInstance(securityContext);

      // isolate resource authentication
      try (final Tx tx = app.tx()) {

        resource = ResourceHelper.optimizeNestedResourceChain(ResourceHelper.parsePath(securityContext, request, resourceMap, propertyView, config.getDefaultIdProperty()), config.getDefaultIdProperty());
        authenticator.checkResourceAccess(request, resource.getResourceSignature(), propertyView.get(securityContext));

        tx.success();
      }

      // isolate doDelete
      boolean retry = true;
      while (retry) {

        try (final Tx tx = app.tx()) {
          result = resource.doDelete();
          tx.success();
          retry = false;

        } catch (DeadlockDetectedException ddex) {
          retry = true;
View Full Code Here

  protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {

    SecurityContext securityContext = null;
    Authenticator authenticator     = null;
    Result result                   = null;
    Resource resource               = null;

    try {

      // first thing to do!
      request.setCharacterEncoding("UTF-8");
      response.setCharacterEncoding("UTF-8");
      response.setContentType("application/json; charset=utf-8");

      // isolate request authentication in a transaction
      try (final Tx tx = StructrApp.getInstance().tx()) {
        authenticator = config.getAuthenticator();
        securityContext = authenticator.initializeAndExamineRequest(request, response);
        tx.success();
      }

      final App app = StructrApp.getInstance(securityContext);

      // set default value for property view
      propertyView.set(securityContext, config.getDefaultPropertyView());

      // evaluate constraints and measure query time
      double queryTimeStart    = System.nanoTime();

      // isolate resource authentication
      try (final Tx tx = app.tx()) {

        resource = ResourceHelper.applyViewTransformation(request, securityContext,
          ResourceHelper.optimizeNestedResourceChain(
            ResourceHelper.parsePath(securityContext, request, resourceMap, propertyView,
              config.getDefaultIdProperty()), config.getDefaultIdProperty()), propertyView);
        authenticator.checkResourceAccess(request, resource.getResourceSignature(), propertyView.get(securityContext));
        tx.success();
      }

      // add sorting & paging
      String pageSizeParameter = request.getParameter(REQUEST_PARAMETER_PAGE_SIZE);
      String pageParameter     = request.getParameter(REQUEST_PARAMETER_PAGE_NUMBER);
      String offsetId          = request.getParameter(REQUEST_PARAMETER_OFFSET_ID);
      String sortOrder         = request.getParameter(REQUEST_PARAMETER_SORT_ORDER);
      String sortKeyName       = request.getParameter(REQUEST_PARAMETER_SORT_KEY);
      boolean sortDescending   = (sortOrder != null && "desc".equals(sortOrder.toLowerCase()));
      int pageSize     = HttpService.parseInt(pageSizeParameter, NodeFactory.DEFAULT_PAGE_SIZE);
      int page                 = HttpService.parseInt(pageParameter, NodeFactory.DEFAULT_PAGE);
      String baseUrl           = request.getRequestURI();
      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);
      }

      // isolate doGet
      boolean retry = true;
      while (retry) {

        try (final Tx tx = app.tx()) {
          result = resource.doGet(sortKey, sortDescending, pageSize, page, offsetId);
          tx.success();
          retry = false;

        } catch (DeadlockDetectedException ddex) {
          retry = true;
        }
      }

      result.setIsCollection(resource.isCollectionResource());
      result.setIsPrimitiveArray(resource.isPrimitiveArray());

      PagingHelper.addPagingParameter(result, pageSize, page);

      // timing..
      double queryTimeEnd = System.nanoTime();

      // store property view that will be used to render the results
      result.setPropertyView(propertyView.get(securityContext));

      // allow resource to modify result set
      resource.postProcessResultSet(result);

      DecimalFormat decimalFormat = new DecimalFormat("0.000000000", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
      result.setQueryTime(decimalFormat.format((queryTimeEnd - queryTimeStart) / 1000000000.0));

      String accept = request.getHeader("Accept");
View Full Code Here

  @Override
  protected void doHead(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    SecurityContext securityContext = null;
    Authenticator authenticator     = null;
    Resource resource               = null;

    try {

      // first thing to do!
      request.setCharacterEncoding("UTF-8");
      response.setCharacterEncoding("UTF-8");
      response.setContentType("application/json; charset=utf-8");

      // isolate request authentication in a transaction
      try (final Tx tx = StructrApp.getInstance().tx()) {
        authenticator = config.getAuthenticator();
        securityContext = authenticator.initializeAndExamineRequest(request, response);
        tx.success();
      }

      final App app = StructrApp.getInstance(securityContext);

      // set default value for property view
      propertyView.set(securityContext, config.getDefaultPropertyView());

      // isolate resource authentication
      try (final Tx tx = app.tx()) {

        resource = ResourceHelper.applyViewTransformation(request, securityContext,
          ResourceHelper.optimizeNestedResourceChain(
            ResourceHelper.parsePath(securityContext, request, resourceMap, propertyView,
              config.getDefaultIdProperty()), config.getDefaultIdProperty()), propertyView);
        authenticator.checkResourceAccess(request, resource.getResourceSignature(), propertyView.get(securityContext));
        tx.success();
      }

      // add sorting & paging
      String pageSizeParameter = request.getParameter(REQUEST_PARAMETER_PAGE_SIZE);
      String pageParameter     = request.getParameter(REQUEST_PARAMETER_PAGE_NUMBER);
      String offsetId          = request.getParameter(REQUEST_PARAMETER_OFFSET_ID);
      String sortOrder         = request.getParameter(REQUEST_PARAMETER_SORT_ORDER);
      String sortKeyName       = request.getParameter(REQUEST_PARAMETER_SORT_KEY);
      boolean sortDescending   = (sortOrder != null && "desc".equals(sortOrder.toLowerCase()));
      int pageSize     = HttpService.parseInt(pageSizeParameter, NodeFactory.DEFAULT_PAGE_SIZE);
      int page                 = HttpService.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);
      }

      // isolate doGet
      boolean retry = true;
      while (retry) {

        try (final Tx tx = app.tx()) {
          resource.doGet(sortKey, sortDescending, pageSize, page, offsetId);
          tx.success();
          retry = false;

        } catch (DeadlockDetectedException ddex) {
          retry = true;
View Full Code Here

  protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    SecurityContext securityContext = null;
    Authenticator authenticator     = null;
    RestMethodResult result         = null;
    Resource resource               = null;

    try {

      // first thing to do!
      request.setCharacterEncoding("UTF-8");
      response.setCharacterEncoding("UTF-8");
      response.setContentType("application/json; charset=utf-8");

      // isolate request authentication in a transaction
      try (final Tx tx = StructrApp.getInstance().tx()) {
        authenticator = config.getAuthenticator();
        securityContext = authenticator.initializeAndExamineRequest(request, response);
        tx.success();
      }

      final App app = StructrApp.getInstance(securityContext);

      // isolate resource authentication
      try (final Tx tx = app.tx()) {

        resource = ResourceHelper.applyViewTransformation(request, securityContext,
          ResourceHelper.optimizeNestedResourceChain(ResourceHelper.parsePath(securityContext, request, resourceMap, propertyView,
            config.getDefaultIdProperty()), config.getDefaultIdProperty()), propertyView);
        authenticator.checkResourceAccess(request, resource.getResourceSignature(), propertyView.get(securityContext));
        tx.success();
      }

      // isolate doOptions
      boolean retry = true;
      while (retry) {

        try (final Tx tx = app.tx()) {

          result = resource.doOptions();
          tx.success();
          retry = false;

        } catch (DeadlockDetectedException ddex) {
          retry = true;
View Full Code Here

    final List<RestMethodResult> results = new LinkedList<>();
    SecurityContext securityContext      = null;
    Authenticator authenticator          = null;
    IJsonInput jsonInput          = null;
    Resource resource                    = null;

    try {


      // first thing to do!
      request.setCharacterEncoding("UTF-8");
      response.setCharacterEncoding("UTF-8");
      response.setContentType("application/json; charset=utf-8");

      // isolate request authentication in a transaction
      try (final Tx tx = StructrApp.getInstance().tx()) {
        authenticator = config.getAuthenticator();
        securityContext = authenticator.initializeAndExamineRequest(request, response);
        tx.success();
      }

      final App app = StructrApp.getInstance(securityContext);

      String input = IOUtils.toString(request.getReader());
      if (StringUtils.isBlank(input)) {
        input = "{}";
      }

      // isolate input parsing (will include read and write operations)
      try (final Tx tx = app.tx()) {
        jsonInput   = gson.get().fromJson(input, IJsonInput.class);
        tx.success();
      }

      if (securityContext != null) {

        // isolate resource authentication
        try (final Tx tx = app.tx()) {

          resource = ResourceHelper.applyViewTransformation(request, securityContext,
              ResourceHelper.optimizeNestedResourceChain(ResourceHelper.parsePath(securityContext, request, resourceMap, propertyView,
              config.getDefaultIdProperty()), config.getDefaultIdProperty()), propertyView);
          authenticator.checkResourceAccess(request, resource.getResourceSignature(), propertyView.get(securityContext));
          tx.success();
        }

        // isolate doPost
        boolean retry = true;
        while (retry) {

          if (resource.createPostTransaction()) {

            try (final Tx tx = app.tx()) {

              for (JsonInput propertySet : jsonInput.getJsonInputs()) {

                results.add(resource.doPost(convertPropertySetToMap(propertySet)));
              }

              tx.success();
              retry = false;

            } catch (DeadlockDetectedException ddex) {
              retry = true;
            }

          } else {

            try {

              for (JsonInput propertySet : jsonInput.getJsonInputs()) {

                results.add(resource.doPost(convertPropertySetToMap(propertySet)));
              }

              retry = false;

            } catch (DeadlockDetectedException ddex) {
View Full Code Here

    SecurityContext securityContext = null;
    Authenticator authenticator     = null;
    RestMethodResult result         = null;
    IJsonInput jsonInput            = null;
    Resource resource               = null;

    try {

      // first thing to do!
      request.setCharacterEncoding("UTF-8");
      response.setCharacterEncoding("UTF-8");
      response.setContentType("application/json; charset=utf-8");

      // isolate request authentication in a transaction
      try (final Tx tx = StructrApp.getInstance().tx()) {
        authenticator = config.getAuthenticator();
        securityContext = authenticator.initializeAndExamineRequest(request, response);
        tx.success();
      }

      final App app = StructrApp.getInstance(securityContext);

      String input = IOUtils.toString(request.getReader());
      if (StringUtils.isBlank(input)) {
        input = "{}";
      }

      // isolate input parsing (will include read and write operations)
      try (final Tx tx = app.tx()) {
        jsonInput   = gson.get().fromJson(input, IJsonInput.class);
        tx.success();
      }

      if (securityContext != null) {

        // isolate resource authentication
        try (final Tx tx = app.tx()) {

          // evaluate constraint chain
          resource = ResourceHelper.applyViewTransformation(request, securityContext,
            ResourceHelper.optimizeNestedResourceChain(ResourceHelper.parsePath(securityContext, request, resourceMap, propertyView,
              config.getDefaultIdProperty()), config.getDefaultIdProperty()), propertyView);
          authenticator.checkResourceAccess(request, resource.getResourceSignature(), propertyView.get(securityContext));
          tx.success();
        }

        // isolate doPut
        boolean retry = true;
        while (retry) {

          try (final Tx tx = app.tx()) {
            result = resource.doPut(convertPropertySetToMap(jsonInput.getJsonInputs().get(0)));
            tx.success();
            retry = false;

          } catch (DeadlockDetectedException ddex) {
            retry = true;
View Full Code Here

    // 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();
View Full Code Here

    do {

      for (Iterator<Resource> it = resourceChain.iterator(); it.hasNext(); ) {

        Resource constr = it.next();

        if (constr instanceof ViewFilterResource) {

          view = (ViewFilterResource) constr;

          it.remove();

        }

      }

      found = false;

      try {

        for (int i = 0; i < num; i++) {

          Resource firstElement       = resourceChain.get(i);
          Resource secondElement      = resourceChain.get(i + 1);
          Resource combinedConstraint = firstElement.tryCombineWith(secondElement);

          if (combinedConstraint != null) {

            // remove source constraints
            resourceChain.remove(firstElement);
            resourceChain.remove(secondElement);

            // add combined constraint
            resourceChain.add(i, combinedConstraint);

            // signal success
            found = true;

          }

        }

      } catch (Throwable t) {

        // ignore exceptions thrown here
      }

    } while (found);

    if (resourceChain.size() == 1) {

      Resource finalResource = resourceChain.get(0);

      if (view != null) {

        finalResource = finalResource.tryCombineWith(view);
      }
     
      if (finalResource == null) {
        // fall back to original resource
        finalResource = resourceChain.get(0);
      }

      // inform final constraint about the configured ID property
      finalResource.configureIdProperty(defaultIdProperty);

      return finalResource;

    }
View Full Code Here

   * @return transformedResource
   * @throws FrameworkException
   */
  public static Resource applyViewTransformation(final HttpServletRequest request, final SecurityContext securityContext, final Resource finalResource, final Value<String> propertyView) throws FrameworkException {

    Resource transformedResource = finalResource;

    // add view transformation
    Class type = finalResource.getEntityClass();
    if (type != null) {
     
      ViewTransformation transformation = StructrApp.getConfiguration().getViewTransformation(type, propertyView.get(securityContext));
      if (transformation != null) {
       
        transformedResource = transformedResource.tryCombineWith(new TransformationResource(securityContext, transformation));
      }
    }

    return transformedResource;
  }
View Full Code Here

TOP

Related Classes of org.structr.rest.resource.Resource

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.