Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

updated web app to demonstrate uploads.

  • Loading branch information...
commit e0fe3abace9e98c1da5330107c59d9c89c4a19b7 1 parent bd8c0e0
@joshlong joshlong authored
View
118 web/src/main/java/org/springframework/social/flickr/HomeController.java
@@ -15,22 +15,23 @@
*/
package org.springframework.social.flickr;
+import org.apache.commons.io.IOUtils;
import org.springframework.social.flickr.api.Flickr;
import org.springframework.social.flickr.api.impl.FlickrException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
-import org.springframework.validation.BindingResult;
-import org.springframework.validation.ObjectError;
-import org.springframework.web.bind.annotation.*;
+import org.springframework.util.Assert;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import javax.inject.Inject;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
+import java.io.File;
+import java.io.FileOutputStream;
import java.io.InputStream;
-import java.util.concurrent.Callable;
+import java.io.OutputStream;
@Controller
public class HomeController {
@@ -43,105 +44,54 @@ public HomeController(CommonsMultipartResolver multipartResolver, Flickr flickr)
this.flickr = flickr;
this.multipartResolver = multipartResolver;
}
+
@RequestMapping(value = "/welcome", method = RequestMethod.GET)
- public String welcome (Model m) {
- m.addAttribute("flickrUser", flickr.peopleOperations().getPersonProfile().getUserName()) ;
- return "welcome" ;
+ public String welcome(Model m) {
+ m.addAttribute("flickrUser", flickr.peopleOperations().getPersonProfile().getUserName());
+ return "welcome";
}
@RequestMapping(value = "/addtags", method = RequestMethod.POST)
public String addTagsToPhotos(@RequestParam("photoid") String photoId, @RequestParam("tags") String tags, Model model) {
flickr.photoOperations().addTags(photoId, tags);
model.addAttribute("messages", "tags : " + tags + " Added successfully..");
- return "welcomePage";
+ return "welcome";
}
@RequestMapping(value = "/deletephoto", method = RequestMethod.POST)
public String deletePhoto(@RequestParam("photoid") String photoId, Model model) {
try {
flickr.photoOperations().delete(photoId);
+ model.addAttribute("messages", "Photo Id : " + photoId + " delete successfully..");
} catch (FlickrException e) {
model.addAttribute("messages", e.getMessage());
- return "welcomePage";
}
- model.addAttribute("messages", "Photo Id : " + photoId + " delete successfully..");
- return "welcomePage";
+ return "welcome";
}
-
- /* // more correct
- @RequestMapping(value = "/uploadphoto", method = RequestMethod.POST)
- @ResponseBody
- public String uploadPhoto ( @RequestParam("file") MultipartFile file) {
-
-// flickr.photoOperations().upload()
-
- return "welcome" ;
- }*/
-
@RequestMapping(value = "/uploadphoto", method = RequestMethod.POST)
- public String create(UploadItem uploadItem, BindingResult result,
- HttpServletRequest request, HttpServletResponse response,
- HttpSession session) {
- if (result.hasErrors()) {
- for (ObjectError error : result.getAllErrors()) {
- System.err.println("Error: " + error.getCode() + " - "
- + error.getDefaultMessage());
- }
- return "/uploadfile";
- }
-
- // Some type of file processing...
- System.err.println("-------------------------------------------");
+ public String create(
+ @RequestParam(value = "title", required = false) String title,
+ @RequestParam(value = "description", required = false) String description,
+ @RequestParam("photo") MultipartFile photo,
+ Model model) throws Throwable {
+
+ File tmpFile = File.createTempFile("tmp", photo.getOriginalFilename());
+ OutputStream outputStream = null;
+ InputStream inputStream = null;
try {
- MultipartFile file = uploadItem.getFileData();
- String fileName = null;
- InputStream inputStream = null;
-
- if (file.getSize() > 0) {
- inputStream = file.getInputStream();
- if (file.getSize() > 100000) {
- System.out.println("File Size:::" + file.getSize());
- return "/uploadfile";
- }
- System.out.println("size::" + file.getSize());
-
-
- System.out.println("fileName:" + file.getOriginalFilename());
-
- int readBytes = 0;
- byte[] buffer = new byte[10000];
- while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
- System.out.println(readBytes);
- }
- //Object obj = flickr.photoOperations().upload(photo , title, null , null , null , null , null )
- inputStream.close();
- }
-
- // ..........................................
- session.setAttribute("uploadFile", file.getOriginalFilename());
- } catch (Exception e) {
- e.printStackTrace();
+ outputStream = new FileOutputStream(tmpFile);
+ IOUtils.copy(photo.getInputStream(), outputStream);
+ Assert.isTrue(tmpFile.exists() && tmpFile.length() > 0, "there must be a file to read from!");
+ String photoId = flickr.photoOperations().upload(tmpFile, title, description, null, null, null, null);
+ model.addAttribute("photoId", photoId);
+ } finally {
+ IOUtils.closeQuietly(outputStream);
+ IOUtils.closeQuietly(inputStream);
+ tmpFile.delete();
}
- return "welcomePage";
+ return "welcome";
}
- /*Pending
- @RequestMapping(value = "/uploadphoto", method = RequestMethod.POST, headers={"content-type=multipart/form-data"})
- public String deletePhoto(@RequestParam("photo") byte[] photo ,@RequestParam("title") String title, Model model ) {
- Object obj =null;
- try{
- //System.out.println(c);
- System.out.println(photo);
- //obj = flickr.photoOperations().upload(photo , title, null , null , null , null , null );
- }catch(FlickrException e){
- model.addAttribute("messages",e.getMessage());
- return "welcomePage";
- }
- if(obj!=null)
- model.addAttribute("messages","Photo Id : "+obj.toString()+" added successfully..");
- return "welcomePage";
- }
- */
}
View
15 web/src/main/java/org/springframework/social/flickr/config/SocialConfig.java
@@ -1,6 +1,7 @@
package org.springframework.social.flickr.config;
import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
@@ -50,10 +51,11 @@ public ConnectionFactoryLocator connectionFactoryLocator() {
}
@Bean
+ @Inject
@Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)
- public ConnectionRepository connectionRepository(){
+ public ConnectionRepository connectionRepository( HttpServletRequest request){
logger.debug("inside the connectionRepository");
- User user = SecurityContext.getCurrentUser();
+ User user = SecurityContext.getCurrentUser( request);
return usersConnectionRepository().createConnectionRepository(user.getId());
}
@@ -69,19 +71,22 @@ public UsersConnectionRepository usersConnectionRepository() {
@Bean
+ @Inject
@Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)
- public Flickr flickr() {
+ public Flickr flickr(HttpServletRequest request) {
logger.debug("inside the flickr");
- return connectionRepository().getPrimaryConnection(Flickr.class).getApi();
+ return connectionRepository(request).getPrimaryConnection(Flickr.class).getApi();
}
@Bean
public ProviderSignInController providerSignInController() {
logger.debug("inside the providerSignInController");
- return new ProviderSignInController(
+ ProviderSignInController providerSignInController = new ProviderSignInController(
connectionFactoryLocator(),
usersConnectionRepository(),
new SimpleSignInAdapter());
+ providerSignInController.setPostSignInUrl("/welcome");
+ return providerSignInController;
}
View
41 web/src/main/java/org/springframework/social/flickr/user/SecurityContext.java
@@ -1,28 +1,33 @@
-
package org.springframework.social.flickr.user;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
public final class SecurityContext {
- private static final ThreadLocal<User> currentUser = new ThreadLocal<User>();
+ private static Map<String, User> mapOfSessionsToUsers = new ConcurrentHashMap<String, User>();
+
+ public static User getCurrentUser(HttpServletRequest r) {
+ String sessionId = r.getSession(true).getId();
+ return mapOfSessionsToUsers.get(sessionId);
+ }
- public static User getCurrentUser() {
- User user = currentUser.get();
- if (user == null) {
- throw new IllegalStateException("No user is currently signed in");
- }
- return user;
- }
+ public static void setCurrentUser(HttpServletRequest r, User user) {
+ mapOfSessionsToUsers.put(session(r).getId(), user);
+ }
- public static void setCurrentUser(User user) {
- currentUser.set(user);
- }
+ private static HttpSession session(HttpServletRequest request) {
+ return request.getSession(true);
+ }
- public static boolean userSignedIn() {
- return currentUser.get() != null;
- }
+ public static boolean userSignedIn(HttpServletRequest request) {
+ return getCurrentUser(request) != null;
+ }
- public static void remove() {
- currentUser.remove();
- }
+ public static void remove(HttpServletRequest request) {
+ mapOfSessionsToUsers.remove(session(request).getId());
+ }
}
View
2  web/src/main/java/org/springframework/social/flickr/user/SimpleSignInAdapter.java
@@ -11,7 +11,7 @@
private final UserCookieGenerator userCookieGenerator = new UserCookieGenerator();
public String signIn(String userId, Connection<?> connection, NativeWebRequest request) {
- SecurityContext.setCurrentUser(new User(userId));
+ SecurityContext.setCurrentUser( request.getNativeRequest(HttpServletRequest.class),new User(userId));
userCookieGenerator.addCookie(userId, request.getNativeResponse(HttpServletResponse.class));
return null;
}
View
120 web/src/main/java/org/springframework/social/flickr/user/UserInterceptor.java
@@ -15,78 +15,76 @@
*/
package org.springframework.social.flickr.user;
+import org.springframework.social.connect.UsersConnectionRepository;
+import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
+import org.springframework.web.servlet.view.RedirectView;
+
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import org.springframework.social.connect.UsersConnectionRepository;
//import org.springframework.social.facebook.api.Facebook;
-import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
-import org.springframework.web.servlet.view.RedirectView;
/**
* Before a request is handled:
* 1. sets the current User in the {@link SecurityContext} from a cookie, if present and the user is still connected to Facebook.
* 2. requires that the user sign-in if he or she hasn't already.
+ *
* @author Keith Donald
*/
public final class UserInterceptor extends HandlerInterceptorAdapter {
- private final UsersConnectionRepository connectionRepository;
-
- private final UserCookieGenerator userCookieGenerator = new UserCookieGenerator();
-
- public UserInterceptor(UsersConnectionRepository connectionRepository) {
- this.connectionRepository = connectionRepository;
- }
-
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
- rememberUser(request, response);
- handleSignOut(request, response);
- if (SecurityContext.userSignedIn() || requestForSignIn(request)) {
- return true;
- } else {
- return requireSignIn(request, response);
- }
- }
-
- public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
- SecurityContext.remove();
- }
-
- // internal helpers
-
- private void rememberUser(HttpServletRequest request, HttpServletResponse response) {
- String userId = userCookieGenerator.readCookieValue(request);
- if (userId == null) {
- return;
- }
- if (!userNotFound(userId)) {
- userCookieGenerator.removeCookie(response);
- return;
- }
- SecurityContext.setCurrentUser(new User(userId));
- }
-
- private void handleSignOut(HttpServletRequest request, HttpServletResponse response) {
- if (SecurityContext.userSignedIn() && request.getServletPath().startsWith("/signout")) {
- connectionRepository.createConnectionRepository(SecurityContext.getCurrentUser().getId()).removeConnections("facebook");
- userCookieGenerator.removeCookie(response);
- SecurityContext.remove();
- }
- }
-
- private boolean requestForSignIn(HttpServletRequest request) {
- return request.getServletPath().startsWith("/signin");
- }
-
- private boolean requireSignIn(HttpServletRequest request, HttpServletResponse response) throws Exception {
- new RedirectView("/signin", true).render(null, request, response);
- return false;
- }
-
- private boolean userNotFound(String userId) {
- //return connectionRepository.createConnectionRepository(userId).findPrimaryConnection(Facebook.class) != null;
- return false;
- }
-
+ private final UsersConnectionRepository connectionRepository;
+
+ private final UserCookieGenerator userCookieGenerator = new UserCookieGenerator();
+
+ public UserInterceptor(UsersConnectionRepository connectionRepository) {
+ this.connectionRepository = connectionRepository;
+ }
+
+ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
+ rememberUser(request, response);
+ handleSignOut(request, response);
+ return SecurityContext.userSignedIn(request) || requestForSignIn(request) || requireSignIn(request, response);
+ }
+
+ public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
+ SecurityContext.remove(request);
+ }
+
+ // internal helpers
+
+ private void rememberUser(HttpServletRequest request, HttpServletResponse response) {
+ String userId = userCookieGenerator.readCookieValue(request);
+ if (userId == null) {
+ return;
+ }
+ if (!userNotFound(userId)) {
+ userCookieGenerator.removeCookie(response);
+ return;
+ }
+ SecurityContext.setCurrentUser(request, new User(userId));
+ }
+
+ private void handleSignOut(HttpServletRequest request, HttpServletResponse response) {
+ if (SecurityContext.userSignedIn(request) && request.getServletPath().startsWith("/signout")) {
+ connectionRepository.createConnectionRepository(SecurityContext.getCurrentUser(request).getId()).removeConnections("facebook");
+ userCookieGenerator.removeCookie(response);
+ SecurityContext.remove(request);
+ }
+ }
+
+ private boolean requestForSignIn(HttpServletRequest request) {
+ return request.getServletPath().startsWith("/signin");
+ }
+
+ private boolean requireSignIn(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ new RedirectView("/signin", true).render(null, request, response);
+ return false;
+ }
+
+ private boolean userNotFound(String userId) {
+ //return connectionRepository.createConnectionRepository(userId).findPrimaryConnection(Facebook.class) != null;
+ return false;
+ }
+
}
View
6 web/src/main/webapp/WEB-INF/jsp/welcome.jsp
@@ -31,8 +31,12 @@ ${messages}
<form action="uploadphoto" method="POST" enctype="multipart/form-data">
<label>Photo : </label>
<input type="file" name="photo"/>
- <input type="text" name="title"/>
+ title: <input type="text" name="title"/> <br/>
+ description: <textarea rows="10" name="description"></textarea> <br/>
<input type="submit" value="upload photo"/>
+
+ <b>${photoId}</b>
+
</form>
</body>
Please sign in to comment.
Something went wrong with that request. Please try again.