Ejemplo n.º 1
0
 protected Key getMetadataKeyForBlobKey(BlobKey blobKey) {
   String origNamespace = NamespaceManager.get();
   NamespaceManager.set("");
   try {
     return KeyFactory.createKey(null, BlobInfoFactory.KIND, blobKey.getKeyString());
   } finally {
     NamespaceManager.set(origNamespace);
   }
 }
Ejemplo n.º 2
0
 private Entity getBlobInfoEntity(String creationHandle) {
   String origNamespace = NamespaceManager.get();
   NamespaceManager.set("");
   try {
     try {
       return getBlobInfoEntityDirectly(creationHandle);
     } catch (EntityNotFoundException ex) {
       return getBlobInfoEntityThroughQuery(creationHandle);
     }
   } finally {
     NamespaceManager.set(origNamespace);
   }
 }
Ejemplo n.º 3
0
  @Override
  public void importEntities(List<Entity> entities) {
    String defaultNamespace = NamespaceManager.get();
    List<Entity> copies = Lists.newArrayList();

    for (Entity entity : entities) {
      // Entities imported might not have the correct appId, we need to make a copy
      copies.add(createEntityCopy(entity));
    }

    entitiesService.putAsync(copies);

    NamespaceManager.set(defaultNamespace);
  }
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Node handler)
      throws ServletException, IOException {
    final String uri = request.getRequestURI();
    final String domain = DomainNamespaceFilter.getDomainNamespace(uri);
    LOG.info("Switching namespace to {}, {} {}", new Object[] {domain, request.getMethod(), uri});

    final String entry = NamespaceManager.get();
    request.setAttribute(ATTR_NAME_ENTRY_NAMESPACE, entry);

    NamespaceManager.set(domain);
    request.setAttribute(ATTR_NAME_DOMAIN_NAMESPACE, domain);

    return true;
  }
 @Override
 public void afterCompletion(
     HttpServletRequest request, HttpServletResponse response, Node handler, Exception ex)
     throws ServletException, IOException {
   final String entry = (String) request.getAttribute(ATTR_NAME_ENTRY_NAMESPACE);
   NamespaceManager.set(entry);
   request.removeAttribute(ATTR_NAME_DOMAIN_NAMESPACE);
 }
Ejemplo n.º 6
0
 @PostConstruct
 private void loadRows() {
   rows = new ArrayList<Row>();
   try {
     NamespaceManager.validateNamespace(namespace);
   } catch (Exception e) {
     errorMessage = e.getMessage();
     return;
   }
   NamespaceManager.set(namespace);
   try {
     SearchService search = SearchServiceFactory.getSearchService(namespace);
     GetResponse<Index> response =
         search.getIndexes(
             GetIndexesRequest.newBuilder().setIndexNamePrefix(indexNamePrefix).build());
     for (Index index : response.getResults()) {
       rows.add(new Row(index));
     }
   } finally {
     NamespaceManager.set("");
   }
 }
Ejemplo n.º 7
0
 private void sendMail(
     HttpServletRequest request, BlogAuthor blogAuthor, Entity blog, Settings settings)
     throws IOException {
   if (settings.dontSendEmail()) {
     return;
   }
   try {
     String digest = DS.getBlogDigest(blog);
     MailService mailService = MailServiceFactory.getMailService();
     Message reply = new Message();
     reply.setSender(blogAuthor.toString());
     Email sender = (Email) blog.getProperty(SenderProperty);
     reply.setTo(sender.getEmail());
     String subject = (String) blog.getProperty(SubjectProperty);
     reply.setSubject("Blog: " + subject + " received");
     StringBuilder sb = new StringBuilder();
     URI reqUri = new URI(request.getScheme(), NamespaceManager.get(), "", "");
     if (!settings.isPublishImmediately()) {
       sb.append("<div>");
       sb.append(
           "<p>Blog is not yet published because it was sent from untrusted email address "
               + sender.getEmail()
               + ". </p>");
       URI publishUri =
           reqUri.resolve(
               "/blog?action=publish&blog="
                   + KeyFactory.keyToString(blog.getKey())
                   + "&auth="
                   + digest);
       sb.append("<a href=\"" + publishUri.toASCIIString() + "\">Publish Blog</a>");
       sb.append("</div>");
     }
     sb.append("<div>");
     sb.append("<p>If blog is not ok, you can delete and then resend it.</p>");
     URI deleteUri =
         reqUri.resolve(
             "/blog?action=remove&blog="
                 + KeyFactory.keyToString(blog.getKey())
                 + "&auth="
                 + digest);
     sb.append("<a href=\"" + deleteUri.toASCIIString() + "\">Delete Blog</a>");
     sb.append("</div>");
     reply.setHtmlBody(sb.toString());
     mailService.send(reply);
   } catch (URISyntaxException ex) {
     throw new IOException(ex);
   }
 }
Ejemplo n.º 8
0
  private Entity createEntityCopy(Entity entity) {
    Key key = entity.getKey();
    NamespaceManager.set(key.getNamespace());

    Key newKey;
    if (key.getId() == 0) {
      newKey = KeyFactory.createKey(key.getKind(), key.getName());
    } else {
      newKey = KeyFactory.createKey(key.getKind(), key.getId());
    }

    Entity newEntity = new Entity(newKey);
    newEntity.setPropertiesFrom(entity);

    return newEntity;
  }
Ejemplo n.º 9
0
 private BlogAuthor setNamespace(HttpServletRequest request, HttpServletResponse response)
     throws IOException {
   String pathInfo = request.getPathInfo();
   log("pathInfo=" + pathInfo);
   if (pathInfo == null) {
     log("pathInfo=null");
     response.sendError(HttpServletResponse.SC_FORBIDDEN);
     return null;
   }
   int idx = pathInfo.indexOf('@');
   if (idx == -1) {
     log("pathInfo doesn't contain @");
     response.sendError(HttpServletResponse.SC_FORBIDDEN);
     return null;
   }
   String namespace = pathInfo.substring(1, idx);
   NamespaceManager.set(namespace);
   log("namespace set to " + namespace);
   String address = pathInfo.substring(idx + 1);
   return new BlogAuthor(namespace, address);
 }
 public String getRequestNamespace() {
   return NamespaceManager.getGoogleAppsNamespace();
 }
Ejemplo n.º 11
0
  public void run() throws IOException {
    if (verbose) {
      System.out.println(
          String.format(
              "Connected to https://appengine.google.com/dashboard?&app_id=%s as %s",
              app_id, email, password));
    }
    Interpreter inter = new Interpreter();
    BufferedReader script = new BufferedReader(new InputStreamReader(System.in));
    DatastoreConnection conn;
    if (isLocalhost) {
      conn = new DatastoreConnection("localhost", 8080, email, password);
    } else {
      conn = new DatastoreConnection(app_id + ".appspot.com", 443, email, password);
    }

    boolean needp = true;
    for (String l = ""; l != null; ) {

      // print prompt
      String namespace = NamespaceManager.get();
      if (namespace == null) namespace = "";
      if (needp) System.out.print(namespace + "> ");

      // read line
      l = script.readLine();
      inter.addLine(l);

      // interpret the line
      try {

        String scommand = inter.popCommand();
        needp = scommand != null;
        if (scommand == null) {
          continue;
        }
        Parser p = new Parser(new StringReader(scommand));
        Object o = null;
        try {
          o = p.parse();
        } catch (com.inpun.json.ParseException e) {
          for (int i = 0; i < p.getPosition() + 1 + namespace.length(); ++i) {
            System.err.print(' ');
          }
          System.err.println('^');
          System.err.println("Error in position " + p.getPosition());
          continue;
        }

        if (o == null || !(o instanceof VerifiedCommand)) {
          // empty command
          continue;
        }

        VerifiedCommand vc = (VerifiedCommand) o;
        ExecutionResult er = vc.execute(conn);
        if (er.getError() != 0) {
          System.out.println("Error: " + er.getMessage());
        } else if (er.getObject() != null) {
          System.out.println(er.getObject().toPrettyString());
        } else if (er.getArray() != null) {
          JsonArray a = er.getArray();
          if (a.isEmpty()) {
            System.out.println("[]");
            continue;
          }
          System.out.println("[");
          Iterator<?> i = a.iterator();
          while (i.hasNext()) {
            String s = ((JsonObject) i.next()).toString();
            if (i.hasNext()) System.out.println(s + ",");
            else System.out.println(s);
          }
          System.out.println("]");
        } else if (er.getMessage() != null) {
          System.out.println(er.getMessage());
        }
      } catch (InterpreterException e) {
        System.err.println(e.getMessage());
      }
    }
  }
Ejemplo n.º 12
0
 private Future<HTTPResponse> postBlobs(
     String filename,
     String contentType,
     String sha1,
     byte[] data,
     String metadataSize,
     HttpServletRequest request,
     int width,
     int height)
     throws MessagingException, IOException {
   try {
     URLFetchService fetchService = URLFetchServiceFactory.getURLFetchService();
     BlobstoreService blobstore = BlobstoreServiceFactory.getBlobstoreService();
     URI reqUri = new URI(request.getScheme(), request.getServerName(), "", "");
     URI uri =
         reqUri.resolve(
             "/blob?"
                 + NamespaceParameter
                 + "="
                 + NamespaceManager.get()
                 + "&"
                 + SizeParameter
                 + "="
                 + metadataSize
                 + "&"
                 + WidthParameter
                 + "="
                 + width
                 + "&"
                 + HeightParameter
                 + "="
                 + height);
     URL uploadUrl = new URL(blobstore.createUploadUrl(uri.toASCIIString()));
     log("post blob to " + uploadUrl);
     HTTPRequest httpRequest =
         new HTTPRequest(uploadUrl, HTTPMethod.POST, FetchOptions.Builder.withDeadline(60));
     String uid = UUID.randomUUID().toString();
     httpRequest.addHeader(new HTTPHeader("Content-Type", "multipart/form-data; boundary=" + uid));
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     PrintStream ps = new PrintStream(baos);
     ps.append("--" + uid);
     ps.append(CRLF);
     ps.append(
         "Content-Disposition: form-data; name=\"" + sha1 + "\"; filename=\"" + filename + "\"");
     ps.append(CRLF);
     ps.append("Content-Type: " + contentType);
     ps.append(CRLF);
     ps.append("Content-Transfer-Encoding: binary");
     ps.append(CRLF);
     ps.append(CRLF);
     ps.write(data);
     ps.append(CRLF);
     ps.append("--" + uid + "--");
     ps.append(CRLF);
     ps.close();
     log("sending blob size=" + baos.size());
     httpRequest.setPayload(baos.toByteArray());
     return fetchService.fetchAsync(httpRequest);
   } catch (URISyntaxException ex) {
     throw new IOException(ex);
   }
 }