Examples of Persistable


Examples of org.persvr.data.Persistable

                  }
                }
                Persevere.createNewTable(path, "Object");
                return null;
              }
              Persistable datedTarget = null;
              if ("POST".equals(method)) // This is a hack to get POSTs to work on slice operator
                path = path.replaceAll("\\[.*\\:.*\\]", "");
              target = Client.getCurrentObjectResponse().requestData(path, "PUT".equals(method));
              if (targetId instanceof ObjectPath) {
                datedTarget = ((ObjectPath) targetId).getSecondToLastTarget();
              } else if (target instanceof Persistable)
                datedTarget = (Persistable) target;
              String subscribe = getParameter(request, "Subscribe");
              if (subscribe == null)
                subscribe = getParameterFromQueryString(request, "subscribe");
              // handle subscription requests
              if (null != subscribe) {
                final Identification<? extends Object> id = Identification.idForString(path);
                if (datedTarget != null) {
                  if (target instanceof ObservablePersistable)
                    ((ObservablePersistable) target).subscribe();

                  // TODO: Only do this if the range references "now"
                  request.setAttribute("org.persvr.servletNow", new Date());
                  Map<String, String> headers = new HashMap<String, String>();
                  Enumeration headerEnum = request.getHeaderNames();
                  while (headerEnum.hasMoreElements()) {
                    String headerName = (String) headerEnum.nextElement();
                    String value = request.getHeader(headerName);
                    headerName = headerName.toLowerCase();
                    if ("opera-range".equals(headerName))
                      headerName = "range";
                    headers.put(headerName, value);
                  }
                  headers.put("__now__", new Date().getTime() + "");
                  headers.put("__pathInfo__", path);
                  if (connectionId == null) {

                  } else {
                    if ("none".equals(subscribe)) {// far future, unsubscribe
                      requestHelper.connection.removeSubscription(headers);
                    } else if ("*".equals(subscribe)) {
                      requestHelper.connection.addSubscription(headers);
                      PersistableObject.addListener(requestHelper.connection);
                    }
                  }
                  setHeader("Subscribed", "OK", headerTarget);

                }
              }
              byte[] postBytes = null;
              String embeddedContent = null;
              if ("application/x-www-form-urlencoded".equals(request.getContentType())) {
                // if it was POSTed from cross-domain, it may specify it's content in the http-content parameter in the entity
                if (postBytes == null)
                  postBytes = IOUtils.toByteArray(request.getInputStream());
                String postBody = new String(postBytes, "UTF-8");
                embeddedContent = getParameterFromUrlEncoded(postBody, "http-content");
                if (embeddedContent == null)
                  embeddedContent = getParameterFromQueryString(request, "http_content");
                if (embeddedContent != null)
                  request.setAttribute("cross-site", true);
              } else if (!"GET".equals(method)) {
                // if it was a GET (that specifies a method beside GET with http-method) from cross-domain,
                //  it may specify it's content in the http-content parameter in the URL
                embeddedContent = getParameterFromQueryString(request, "http-content");
                if (embeddedContent == null)
                  embeddedContent = getParameterFromQueryString(request, "http_content");
                if (embeddedContent != null)
                  request.setAttribute("cross-site", true);
              }
              if (embeddedContent != null) {
                postBytes = embeddedContent.getBytes("UTF-8");
              }
              // Restart here
              String precondition = getParameter(request, "If");
              //TODO: Handle relative expressions
              if (precondition != null && !ScriptRuntime.toBoolean(Identification.idForString(precondition).getTarget()))
                throw new ConditionFailedException("Condition " + precondition + " was not satisfied");
              contentType = contentType == null ? null : contentType.split(";")[0];
              if ("POST".equals(method)) {
                Object postObject = null;
                boolean isJson = false;
                boolean safeContentType = false;
                if (couldBeJson(contentType)) {
                  try {
                    // this means that the content may be JSON, we are forgiving if URL encoding is used as it is
                    // the default for Ajax requests
                    if (postBytes == null)
                      postBytes = IOUtils.toByteArray(request.getInputStream());
                    String postBody = new String(postBytes, "UTF-8");
                    postObject = requestHelper.parseJsponString(postBody); // TODO: Shouldn't do this twice
                    // If it parsed we can be assured that it wasn't cross-site browser generated
                    requestHelper.authorizeCookieAuthentication();
                    // detect JSON-RPC calls
                    if (postObject instanceof Map && ((Map) postObject).containsKey("id")
                        && ((Map) postObject).containsKey("method") && ((Map) postObject).containsKey("params")
                        && ((Map) postObject).get("params") instanceof List) {
                      // It looks like a JSON-RPC request, treat it as a method call
                      requestHelper.handleRPC(target, (Map) postObject);
                      // we set the username again because it may have changed during the RPC
                      username = UserSecurity.getUserName(UserSecurity.currentUser());
                      // we set the username so the client side can access it
                      setHeader("Username", "public".equals(username) ? null : username, headerTarget);
                      // write out the response (this could actually be a request from the server)
                      Client.getCurrentObjectResponse().writeWaitingRPCs();
                      return null;
                    }
                    Object bodyData = requestHelper.convertParsedToObject(postObject);
                    String newLocation = request.getHeader("Content-ID");
                    // this indicates that the request has a client-assigned id to use temporarily
                    if (newLocation != null) {
                      // get rid of the brackets and the contextPath
                      newLocation = newLocation.substring(request.getContextPath().length() + 2, newLocation.length() - 1);
                      Client client = Client.getCurrentObjectResponse().getConnection();
                      Persistable createdObject = client.getClientSideObject(newLocation);
                      if (createdObject == null)
                        client.clientSideObject(newLocation, createdObject = Persevere.newObject(((Persistable) target)
                            .getId()));
                      target = createdObject;
                      for (Map.Entry<String, Object> entry : ((Persistable) bodyData).entrySet(0)) {
                        createdObject.set(entry.getKey(), entry.getValue());
                      }
                    } else {
                      target = postObject((Persistable) target, bodyData);
                    }
                    newContent = true;
                    isJson = true;
                  } catch (JSONParser.JSONException e) {
                    // if the content type explicity said it was JSON or JavaScript we will throw an error
                    if (contentType == null || contentType.indexOf("json") > 0 || contentType.indexOf("javascript") > 0) {
                      throw e;
                    }
                  }

                } else
                  safeContentType = true;
                if (!isJson) {
                  // it wasn't JSON (couldn't be parsed) and so we treat it as a file
                  if (ServletFileUpload.isMultipartContent(request)) {
                    if(target instanceof List){
                      target = Persevere.newObject(((Persistable) target).getId());
                    }
                    // Create a factory for disk-based file items
                    FileItemFactory factory = new DiskFileItemFactory();

                    // Create a new file upload handler
                    ServletFileUpload upload = new ServletFileUpload(factory);

                    // Parse the request
                    List<FileItem> items = upload.parseRequest(request);
                    for (FileItem item : items) {
                      if (item.isFormField()) {
                        ((Persistable) target).set(item.getFieldName(), item.getString());
                      } else {
                        Persistable fileTarget = createFile(item.getContentType(), null, item.getInputStream());
                        fileTarget.set("name", item.getName());
                        if (!(target instanceof List)) {
                          ((Persistable) target).set(item.getFieldName(), fileTarget);
                        }
                      }
                    }
                  } else {
                    if (safeContentType)
                      requestHelper.authorizeCookieAuthentication();
                    DataSource source = ((Persistable) target).getId().source;
                    String contentDisposition = request.getHeader("Content-Disposition");
                    if (postBytes == null)
                      postBytes = IOUtils.toByteArray(request.getInputStream());
                    // create a File using the provided file/binary data
                    Persistable fileTarget = createFile(contentType, contentDisposition, postBytes);
                    if (!(source instanceof DynaFileDBSource)) {
                      Persistable resourceTarget = Persevere.newObject(((Persistable) target).getId());
                      resourceTarget.put("representation:" + contentType, resourceTarget, fileTarget);
                      ((PersistableObject) resourceTarget).setAttributes("representation:" + contentType,
                          ScriptableObject.DONTENUM);
                    }
                    target = fileTarget;
                    newContent = true;
                    force204 = true;
                  }
                }

                response.setStatus(201);
              } else if ("PUT".equals(method)) {
                boolean isJson = false;
                Identification<? extends Object> id = Identification.idForString(path);
                try {
                  if (couldBeJson(contentType)) {
                    if (postBytes == null)
                      postBytes = IOUtils.toByteArray(request.getInputStream());

                    String postBody = new String(postBytes, "UTF-8");
                    if (id instanceof ObjectPath) {
                      Object value = id.getTarget();
                      if (value instanceof Persistable) {
                        id = ((Persistable) value).getId();
                      }
                    }
                    target = requestHelper.convertWithKnownId(postBody, id);

                    isJson = true;
                  }
                } catch (JSONParser.JSONException e) {
                  if (contentType == null || contentType.indexOf("json") > 0 || contentType.indexOf("javascript") > 0) {
                    throw e;
                  }
                }
                if (!isJson) {
                  // create an alternate representation for the target object using the provided file/binary data
                  DataSource source = target instanceof Persistable ? ((Persistable) target).getId().source : null;
                  String contentDisposition = request.getHeader("Content-Disposition");
                  if (postBytes == null)
                    postBytes = IOUtils.toByteArray(request.getInputStream());
                  Persistable fileTarget = createFile(contentType, contentDisposition, postBytes);
                  if (!(source instanceof DynaFileDBSource) && !(id instanceof ObjectPath)) {
                    if (target instanceof Persistable) {
                      ((Persistable) target).set("representation:" + contentType, fileTarget);
                      ((PersistableObject) target).setAttributes("representation:" + contentType, ScriptableObject.DONTENUM);
                    }
                  }
                  newContent = true;
                  force204 = true;
                  target = fileTarget;
                }
                if (id instanceof ObjectPath) {
                  // if it is a path we set the value of the property
                  Object key = ((ObjectPath) id).getLastPath();
                  Persistable secondToLastTarget = (Persistable) ((ObjectPath) id).getSecondToLastTarget();
                  if (key instanceof Integer)
                    secondToLastTarget.put((Integer) key, secondToLastTarget, target);
                  else {
                    secondToLastTarget.set((String) key, target);
                  }
                } else if (!(target instanceof Persistable))
                  //TODO: This should be allowed if an ObjectPath is used
                  throw new RuntimeException("Can not replace an identified object with a primitive value");
                if (!isJson) {
                  target = Undefined.instance;// no need to return the file just uploaded
                }

              } else if ("DELETE".equals(method)) {
                // delete the target object or property
                Identification<? extends Object> id = Identification.idForString(path);
                if (id instanceof ObjectPath) {
                  // it is a property
                  Object key = ((ObjectPath) id).getLastPath();
                  Persistable secondToLastTarget = (Persistable) ((ObjectPath) id).getSecondToLastTarget();
                  if (key instanceof Integer)
                    secondToLastTarget.delete((Integer) key);
                  else
                    secondToLastTarget.delete((String) key);
                  return null;
                } else if (id instanceof JsonPath) {
                  //TODO: Needs to be a way to do delete items from JSONPath queries
                  for (int i = ((List) target).size(); i > 0;) {
                    i--;
                    Persistable item = ((Persistable) ((List) target).get(i));
                    item.delete();
                  }
                  return null;
                }
                if (target instanceof Persistable) {
                  ((Persistable) target).delete();
View Full Code Here

Examples of org.persvr.data.Persistable

      //export.excludedObjects.add((DataObject)DataSourceManager.getRootObject().getById(new Id("226")));
      export.excludedObjects.add((Persistable)DataSourceManager.getById("dyna/1709"));
      export.excludedObjects.add((Persistable)DataSourceManager.getById("dyna/3"));
      export.topLevelObjects.add((Persistable)DataSourceManager.getRootObject());
      while(!export.topLevelObjects.isEmpty()) {
        Persistable objectToExport = export.topLevelObjects.iterator().next();
        export.export(objectToExport,false);
        export.topLevelObjects.remove(objectToExport);
      }
      export.write("{}]}");
      export.out.close();
View Full Code Here

Examples of org.persvr.data.Persistable

     
      //if (newObject.getId().toString().equals("284"))
        //System.err.println(newObject.getId());
      if (!visitedObjects.contains(newObject) && newObject.getId().getSource() == newSource) {
        visitedObjects.add(newObject);
        Persistable oldObject = (Persistable) ObjectId.idForObject(oldSource,newObject.getId().subObjectId).getTarget();
        for (Map.Entry<String,Object> entry: newObject.entrySet(0)) {
          String key = entry.getKey();
          Object value = entry.getValue();
          if (!key.equals(":importMaps")
              && !key.equals("history")
              && !key.equals("version")
              //&& !key.equals(GlobalData.IN_GROUPS_FIELD)
              && !compareValues(oldObject.get(key),value)
              && !excludedObjects.contains(value)) {
            if (!identified) {
              write("\n{\"id\":\"" + newObject.getId().toString(newSource,null) + "\"");
              identified = true;
            }           
View Full Code Here

Examples of org.persvr.data.Persistable

  }
  public Persistable clientSideObject(String id,Persistable newObject) {
    synchronized (clientObjectsChangeIdNeeded) {
      if(clientSideObjects == null)
        clientSideObjects = new HashMap<String,Persistable>();
      Persistable value = clientSideObjects.get(id);
      if (value != null) {
        clientObjectsChangeIdNeeded.put(id,value);
        return value;
      }
      value = newObject;
View Full Code Here

Examples of org.persvr.data.Persistable

      noVersionObjectId = Long.parseLong((String) noVersionObjectId);
    }catch(NumberFormatException e){
    }
    traverser.minKey = noVersionObjectId;
    traverser.maxKey = noVersionObjectId;
    Persistable object;
    // this should trigger the loading of the object
    if((object = (Persistable) traverser.nextObject()) == null){
      throw new ObjectNotFoundException(this, objectId);
    }
    //FIXME: remove this
/*    if((Persistable) traverser.nextObject() != null){
      throw new IllegalStateException("shouldn't be duplicate ids");
    }*/
   
    // if a version was specified, we need to make sure we load it
    if(version > -1){
      while(((ObjectVersion) object.getVersion()).versionNumber > version){
        object = getDatabase().getVersionByReference(((ObjectVersion) object.getVersion()).previousVersionReference);
      }
      if(((ObjectVersion) object.getVersion()).versionNumber != version)
        throw new ObjectNotFoundException(this, objectId);
    }
  }
View Full Code Here

Examples of org.persvr.data.Persistable

   * @param data
   * @return
   * @throws IOException
   */
  private static Persistable createFile(String contentType, String contentDisposition, Object data) throws IOException {
    Persistable fileTarget = Persevere.newObject("File");
    String charSet = null;

    if (contentType != null) {
      String[] contentTypeParts = contentType.split(";\\s*");
      contentType = contentTypeParts[0];
      for (String part : contentTypeParts) {
        if (part.startsWith("charset")) {
          charSet = part.split("=")[1];
        }
      }
    }
    fileTarget.set("contentType", contentType);
    if(contentDisposition != null)
      fileTarget.set("contentDisposition", contentDisposition);
    contentType = contentType == null ? null : contentType.split(";")[0];
    if (contentType != null && (contentType.startsWith("text/") || charSet != null)) {
      if (data instanceof InputStream)
        fileTarget.set("content", IOUtils.toString(new InputStreamReader((InputStream) data, charSet == null ? "UTF-8" : charSet)));
      else
        fileTarget.set("content", new String((byte[]) data, charSet == null ? "UTF-8" : charSet));
    } else {
      if (data instanceof InputStream)
        fileTarget.set("content", new BinaryData((InputStream) data));
      else
        fileTarget.set("content", new BinaryData((byte[]) data));
    }
    return fileTarget;
  }
View Full Code Here

Examples of org.persvr.data.Persistable

    public Persistable next() {
      try {
        if(next == null && count++ < maxLength)
          next = traverser.nextObject();
        Persistable value = next;
        next = null;
        return value;
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
View Full Code Here

Examples of org.persvr.data.Persistable

    if (target instanceof PersistableClass) {
      // if we post to a schema, we can just consider this a post to the table
      target = (Persistable) Identification.idForString(((PersistableClass) target).getId().toString() + "/").getTarget();
    }
    if (bodyData instanceof Persistable) {
      Persistable newObject = (Persistable) bodyData;
      ScriptableObject arrayProto = (ScriptableObject) ScriptableObject.getClassPrototype(GlobalData.getGlobalScope(), "Array");
      ScriptableObject objectProto = (ScriptableObject) ScriptableObject.getClassPrototype(GlobalData.getGlobalScope(), "Object");

      if ("".equals(((Persistable) target).getId().subObjectId)
          && (((Persistable) bodyData).getPrototype() == objectProto || ((Persistable) bodyData).getPrototype() == arrayProto)) {
        // this means it is a generic object or list, we need to make it be the right class
        DataSource thisSource = ((Persistable) target).getId().source;
        Class targetClass = DataSourceManager.getObjectsClass(thisSource).objectsClass;
        if (bodyData instanceof List) {
          // this means that an array was provided for a data source that takes objects; we
          //  will assume this means that the user wants to create multiple objects
          int i = 0;
          for (Object obj : (List) bodyData) {
            if (obj instanceof Persistable) {
              newObject = Persevere.newObject(((Persistable) target).getId());
              for (Map.Entry<String, Object> entry : ((Persistable) obj).entrySet(0)) {
                newObject.set(entry.getKey(), entry.getValue());
              }
              ((List) bodyData).set(i++, newObject);
            } else
              throw new RuntimeException("Bulk update arrays should only include objects");
          }
          return bodyData;
        } else {
          newObject = bodyData instanceof List ? Persevere.newArray(((Persistable) target).getId()) : Persevere
              .newObject(((Persistable) target).getId());
          for (Map.Entry<String, Object> entry : ((Persistable) bodyData).entrySet(0)) {
            newObject.set(entry.getKey(), entry.getValue());
          }
        }
      }
      Client.getCurrentObjectResponse().getConnection().changeClientSideObject((Persistable) bodyData, newObject);
      bodyData = newObject;
View Full Code Here

Examples of org.persvr.data.Persistable

    public long estimatedSize(long exactWithin) throws IOException {
      // estimate the size based on the number that has been processed
      return included * small.estimatedSize(exactWithin) / smallTraversed;
    }
    public Persistable nextObject() throws IOException {
      Persistable potential;
      do{
        potential = small.nextObject();
        if(potential == null)
          return null;
        smallTraversed++;
View Full Code Here

Examples of org.persvr.data.Persistable

    }
    public long size() throws IOException{
      return small.size() + big.size();
    }
    public Persistable nextObject() throws IOException {
      Persistable potential;
      if(processingBig){
        potential = big.nextObject();
        if(potential != null)
          return potential;
        processingBig = false;
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. 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.