Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 0 additions & 8 deletions portfolio/README.md

This file was deleted.

14 changes: 13 additions & 1 deletion portfolio/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,18 @@
<version>4.0.1</version>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-api-1.0-sdk</artifactId>
<version>1.9.59</version>
</dependency>

</dependencies>

<build>
Expand All @@ -35,7 +47,7 @@
<version>2.2.0</version>
<configuration>
<!-- TODO: set project ID. -->
<deploy.projectId>qnn-step-2020</deploy.projectId>
<deploy.projectId>qnn-step-v2-2020</deploy.projectId>
<deploy.version>1</deploy.version>
</configuration>
</plugin>
Expand Down
56 changes: 56 additions & 0 deletions portfolio/src/main/java/com/google/sps/data/Comment.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.sps.data;
import java.util.Date;

public final class Comment{
private final Object user;
private final Object content;
private final Object timestamp;
private final Object fileUrl;
public Comment(Object _user, Object _content){
this.user = _user;
this.content = _content;
this.timestamp = new Date();
this.fileUrl = null;
}
public Comment(Object _user, Object _content, Object _fileUrl){
this.user = _user;
this.content = _content;
this.fileUrl = _fileUrl;
this.timestamp = new Date();
}
public Comment(Object _user, Object _content, Object _fileUrl, Object _timestamp){
this.user = _user;
this.content = _content;
this.fileUrl = _fileUrl;
this.timestamp = _timestamp;
}

public Object getUser(){
return this.user;
}

public Object getContent(){
return this.content;
}

public Object getFileURL(){
return this.fileUrl;
}

public Object getTimestamp(){
return this.timestamp;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.sps.servlets;

import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* When the fetch() function requests the /blobstore-upload-url URL, the content of the response is
* the URL that allows a user to upload a file to Blobstore. If this sounds confusing, try running a
* dev server and navigating to /blobstore-upload-url to see the Blobstore URL.
*/
@WebServlet("/bsupload-url")
public class BlobstoreUploadUrlServlet extends HttpServlet {

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
String uploadUrl = blobstoreService.createUploadUrl("/comment-handler");

response.setContentType("text/html");
response.getWriter().println(uploadUrl);
}
}
115 changes: 112 additions & 3 deletions portfolio/src/main/java/com/google/sps/servlets/DataServlet.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,25 @@
// limitations under the License.

package com.google.sps.servlets;
import com.google.sps.data.Comment;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;

import java.lang.Integer;

import com.google.appengine.api.datastore.Cursor;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.SortDirection;
import com.google.appengine.api.datastore.QueryResultList;

import java.io.IOException;
import javax.servlet.annotation.WebServlet;
Expand All @@ -23,10 +42,100 @@
/** Servlet that returns some example content. TODO: modify this file to handle comments data */
@WebServlet("/data")
public class DataServlet extends HttpServlet {

HashMap<Integer, String> cursors = new HashMap<Integer, String>();
int pageCount = 0;

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html;");
response.getWriter().println("<h1>Hello world!</h1>");
ArrayList<String> messages = new ArrayList<>();

String nextPage = request.getParameter("next");
String cursor = request.getParameter("cursor");
pageCount += 1;
if(cursor != null && nextPage.equals("false")){
pageCount -= 2;
cursor = cursors.get(pageCount);
}

FetchOptions fetchOptions = FetchOptions.Builder.withLimit(5);
if(cursor != null){

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NIT: Remove empty line.

fetchOptions.startCursor(Cursor.fromWebSafeString(cursor));
} else {
cursors.put(pageCount, "");
}

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NIT: Remove empty lines.



DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

Query query = new Query("Comment").addSort("timestamp", SortDirection.DESCENDING);
if(nextPage == "false"){
query = new Query("Comment").addSort("timestamp", SortDirection.ASCENDING);
}
PreparedQuery resultsPQ = datastore.prepare(query);

QueryResultList<Entity> results;
try {
results = resultsPQ.asQueryResultList(fetchOptions);
} catch (IllegalArgumentException e) {
response.sendRedirect("/");
return;
}
for (Entity entity : results) {
Object user = entity.getProperty("user");
Object content = entity.getProperty("content");
Object timestamp = entity.getProperty("timestamp");
Object fileUrl = entity.getProperty("fileUrl");
Comment c = new Comment(user, content, fileUrl, timestamp);
messages.add(commentToJson(c));
}
String cursorString = results.getCursor().toWebSafeString();
cursors.put(pageCount, cursorString);
messages.add(cursorString);
Gson gson = new Gson();
String json = gson.toJson(messages);
response.setContentType("application/json;");
response.getWriter().println(json);
}

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
// Get the input from the form.
String user = "None";
String text = getParameter(request, "comment-input", "");

Entity comment = commentToEntity("None", text);

DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
datastore.put(comment);
response.sendRedirect("/index.html");

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NIT: Remove empty line.

}


private String commentToJson(Comment comment) {
Gson gson = new Gson();

String json = gson.toJson(comment);
return json;
}

private String getParameter(HttpServletRequest request, String name, String defaultValue) {
String value = request.getParameter(name);
if (value == null) {
return defaultValue;
}
return value;
}

private Entity commentToEntity(String user, String content){
Entity commentEntity = new Entity("Comment");
long current_time = System.currentTimeMillis();
commentEntity.setProperty("user", user);
commentEntity.setProperty("timestamp", current_time);
commentEntity.setProperty("content", content);
return commentEntity;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.sps.servlets;

import com.google.sps.data.Comment;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;

import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.ServingUrlOptions;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
* When the user submits the form, Blobstore processes the file upload and then forwards the request
* to this servlet. This servlet can then process the request using the file URL we get from
* Blobstore.
*/
@WebServlet("/comment-handler")
public class FormHandlerServlet extends HttpServlet {

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {

// Get the message entered by the user.
String message = request.getParameter("comment-input");

// Get the URL of the image that the user uploaded to Blobstore.
String imageUrl = getUploadedFileUrl(request, "image");


// A real codebase would probably store these in Datastore.
UserService userService = UserServiceFactory.getUserService();

Comment c = new Comment(userService.getCurrentUser().getEmail(), message, imageUrl);
Entity comment = commentToEntity(c);
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
datastore.put(comment);
response.sendRedirect("/");

}

/** Returns a URL that points to the uploaded file, or null if the user didn't upload a file. */
private String getUploadedFileUrl(HttpServletRequest request, String formInputElementName) {
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(request);
List<BlobKey> blobKeys = blobs.get("image");

// User submitted form without selecting a file, so we can't get a URL. (dev server)
if (blobKeys == null || blobKeys.isEmpty()) {
return null;
}

// Our form only contains a single file input, so get the first index.
BlobKey blobKey = blobKeys.get(0);

// User submitted form without selecting a file, so we can't get a URL. (live server)
BlobInfo blobInfo = new BlobInfoFactory().loadBlobInfo(blobKey);
if (blobInfo.getSize() == 0) {
blobstoreService.delete(blobKey);
return null;
}

// We could check the validity of the file here, e.g. to make sure it's an image file
// https://stackoverflow.com/q/10779564/873165

// Use ImagesService to get a URL that points to the uploaded file.
ImagesService imagesService = ImagesServiceFactory.getImagesService();
ServingUrlOptions options = ServingUrlOptions.Builder.withBlobKey(blobKey);

// To support running in Google Cloud Shell with AppEngine's devserver, we must use the relative
// path to the image, rather than the path returned by imagesService which contains a host.
try {
URL url = new URL(imagesService.getServingUrl(options));
return url.getPath();
} catch (MalformedURLException e) {
return imagesService.getServingUrl(options);
}
}
private Entity commentToEntity(Comment comment){
Entity commentEntity = new Entity("Comment");

commentEntity.setProperty("user", comment.getUser());
commentEntity.setProperty("timestamp", comment.getTimestamp());
commentEntity.setProperty("content", comment.getContent());
commentEntity.setProperty("fileUrl", comment.getFileURL());
return commentEntity;
}

}
Loading