@Transactional
  public static Result uploadImage() {
    final String loggedInUser = Application.getLoggedInUser();
    if (loggedInUser == null) {
      return ok(views.html.login.render());
    }

    FilePart picture = request().body().asMultipartFormData().getFile("url-photo0");
    String fileName = picture.getFilename();
    logger.underlyingLogger().info("uploadImage. fileName=" + fileName);

    DateTime now = new DateTime();
    File file = picture.getFile();
    try {
      String imagePath = imageUploadUtil.getImagePath(now, fileName);
      FileUtils.copyFile(file, new File(imagePath));
    } catch (IOException e) {
      logger.underlyingLogger().error(loggedInUser + " failed to upload photo", e);
      return status(500);
    }

    String imageUrl = imageUploadUtil.getImageUrl(now, fileName);
    logger.underlyingLogger().info("uploadImage. imageUrl=" + imageUrl);

    Map<String, String> map = new HashMap<>();
    map.put("URL", imageUrl);
    logger.underlyingLogger().info(loggedInUser + " uploaded photo - " + imageUrl);
    return ok(Json.toJson(map));
  }
  @Subscribe
  public void recordUnFollowEvent(UnFollowEvent map) {
    try {
      final User localUser = (User) map.get("localUser");
      final User user = (User) map.get("user");

      if (localUser.onUnFollow(user)) {
        CalcServer.instance().removeFromUserFollowingsFollowersQueue(localUser.id, user.id);
      }
    } catch (Exception e) {
      logger.underlyingLogger().error(e.getMessage(), e);
    }
  }
 public static Object deserialize(byte[] bytes) {
   ByteArrayInputStream bais = null;
   try {
     bais = new ByteArrayInputStream(bytes);
     ObjectInputStream ois = new ObjectInputStream(bais);
     return ois.readObject();
   } catch (Exception e) {
     logger.underlyingLogger().error(ExceptionUtils.getStackTrace(e));
   } finally {
     try {
       if (bais != null) bais.close();
     } catch (IOException ioe) {
     }
   }
   return null;
 }
  @Subscribe
  public void recordFollowEvent(FollowEvent map) {
    try {
      final User localUser = (User) map.get("localUser");
      final User user = (User) map.get("user");

      // why we require this, if we are renewing HOME_FOLLOWING feed after every 2 mins
      if (localUser.onFollow(user)) {
        // ideally use FollowSocialRelation.CREATED_DATE
        Long score = new Date().getTime();
        CalcServer.instance()
            .addToUserFollowingsFollowersQueue(localUser.id, user.id, score.doubleValue());

        executeAsync(
            new TransactionalRunnableTask() {
              @Override
              public void execute() {
                // game badge
                if (localUser.numFollowings == 3) {
                  GameBadgeAwarded.recordGameBadge(localUser, BadgeType.FOLLOW_3);
                } else if (localUser.numFollowings == 10) {
                  GameBadgeAwarded.recordGameBadge(localUser, BadgeType.FOLLOW_10);
                }

                // activity
                Activity activity =
                    new Activity(
                        ActivityType.FOLLOWED,
                        user.id,
                        false,
                        localUser.id,
                        localUser.id,
                        localUser.displayName,
                        user.id,
                        user.id,
                        user.displayName);
                activity.ensureUniqueAndCreate();

                // Push notification
                PushNotificationSender.sendNewFollowNotification(user.id, localUser.displayName);
              }
            });
      }
    } catch (Exception e) {
      logger.underlyingLogger().error(e.getMessage(), e);
    }
  }
 public static byte[] serialize(Object object) {
   ObjectOutputStream oos = null;
   ByteArrayOutputStream baos = null;
   try {
     baos = new ByteArrayOutputStream();
     oos = new ObjectOutputStream(baos);
     oos.writeObject(object);
     byte[] bytes = baos.toByteArray();
     return bytes;
   } catch (Exception e) {
     logger.underlyingLogger().error(ExceptionUtils.getStackTrace(e));
   } finally {
     try {
       if (oos != null) oos.close();
       if (baos != null) baos.close();
     } catch (IOException ioe) {
     }
   }
   return null;
 }
public class SimpleSerializer {
  private static play.api.Logger logger = play.api.Logger.apply(SimpleSerializer.class);

  public static byte[] serialize(Object object) {
    ObjectOutputStream oos = null;
    ByteArrayOutputStream baos = null;
    try {
      baos = new ByteArrayOutputStream();
      oos = new ObjectOutputStream(baos);
      oos.writeObject(object);
      byte[] bytes = baos.toByteArray();
      return bytes;
    } catch (Exception e) {
      logger.underlyingLogger().error(ExceptionUtils.getStackTrace(e));
    } finally {
      try {
        if (oos != null) oos.close();
        if (baos != null) baos.close();
      } catch (IOException ioe) {
      }
    }
    return null;
  }

  public static Object deserialize(byte[] bytes) {
    ByteArrayInputStream bais = null;
    try {
      bais = new ByteArrayInputStream(bytes);
      ObjectInputStream ois = new ObjectInputStream(bais);
      return ois.readObject();
    } catch (Exception e) {
      logger.underlyingLogger().error(ExceptionUtils.getStackTrace(e));
    } finally {
      try {
        if (bais != null) bais.close();
      } catch (IOException ioe) {
      }
    }
    return null;
  }
}
  public static ConversationOrder getActiveOrder(Conversation conversation) {
    Query q =
        JPA.em()
            .createQuery(
                "SELECT o from ConversationOrder o where conversation = ?1 and active = ?2 and deleted = false");
    q.setParameter(1, conversation);
    q.setParameter(2, true);
    q.setMaxResults(1);

    if (q.getMaxResults() > 1) {
      logger
          .underlyingLogger()
          .error("[conv=" + conversation.id + "] has " + q.getMaxResults() + " active orders!!");
    }

    try {
      return (ConversationOrder) q.getSingleResult();
    } catch (NoResultException e) {
      return null;
    }
  }
Example #8
0
  /** @param filePath */
  public void read(String filePath) throws Exception {
    BufferedReader br = new BufferedReader(new FileReader(filePath));

    Map<Integer, String> headerMap = parseHeaderLine(br.readLine());

    String line;
    PostEntry lastPost = null;

    while ((line = br.readLine()) != null) {
      String[] row = line.split(DELIM);

      Long userId = null;
      String commName = null, title = null, body = null;
      DateTime dateTime = null;

      for (int i = 0; i < row.length; i++) {
        String header = headerMap.get(i);
        if (header == null) {
          logger.underlyingLogger().error("Error in PostEntry, can't find header");
        } else {
          String value = row[i];
          if (value != null && !"".equals(value)) {
            value = value.trim();

            if (header.equals(COMM_KEY)) {
              commName = value;
            } else if (header.equals(TITLE_KEY)) {
              title = value;
            } else if (header.equals(BODY_KEY)) {
              body = value;
            } else if (header.equals(DATETIME_KEY)) {
              try {
                dateTime = dtFmt.parseDateTime(value);
              } catch (Exception e) {
                logger.underlyingLogger().error("ParseDateException: " + value);
              }
            } else if (header.equals(USERID_KEY)) {
              try {
                userId = Long.parseLong(value);
              } catch (NumberFormatException e) {
                logger.underlyingLogger().error("NumberFormatException: " + value);
              }
            }
          }
        }
      }

      // comment
      if (title == null && body != null) {
        Comment comment = new Comment();
        comment.body = body;
        comment.userId = userId;
        comment.dateTime = dateTime;
        lastPost.comments.add(comment);
      } else if (body == null && userId == null) {
        if (lastPost != null) {
          posts.add(lastPost);
        }
        lastPost = null;
        continue; // skip
      }
      // new post
      else {
        lastPost = new PostEntry();
        lastPost.commName = commName;
        lastPost.title = title;
        lastPost.body = body;
        lastPost.userId = userId;
        lastPost.dateTime = dateTime;
      }
    }
    br.close();

    if (lastPost != null) {
      posts.add(lastPost);
    }
  }
Example #9
0
/**
 * Created by IntelliJ IDEA. Date: 16/3/15 Time: 11:47 PM To change this template use File |
 * Settings | File Templates.
 */
public class PostsFileReader {
  private static final play.api.Logger logger = play.api.Logger.apply(PostsFileReader.class);

  public static final String COMM_KEY = "Community Name";
  public static final String TITLE_KEY = "Post Title";
  public static final String BODY_KEY = "Post Body";
  public static final String DATETIME_KEY = "DateTime";
  public static final String USERID_KEY = "UserId";

  private static final String DELIM = "\t";
  private static final DateTimeFormatter dtFmt = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");

  private List<PostEntry> posts = new ArrayList<>();

  /** @return */
  public List<PostEntry> getPosts() {
    return posts;
  }

  /** @param filePath */
  public void read(String filePath) throws Exception {
    BufferedReader br = new BufferedReader(new FileReader(filePath));

    Map<Integer, String> headerMap = parseHeaderLine(br.readLine());

    String line;
    PostEntry lastPost = null;

    while ((line = br.readLine()) != null) {
      String[] row = line.split(DELIM);

      Long userId = null;
      String commName = null, title = null, body = null;
      DateTime dateTime = null;

      for (int i = 0; i < row.length; i++) {
        String header = headerMap.get(i);
        if (header == null) {
          logger.underlyingLogger().error("Error in PostEntry, can't find header");
        } else {
          String value = row[i];
          if (value != null && !"".equals(value)) {
            value = value.trim();

            if (header.equals(COMM_KEY)) {
              commName = value;
            } else if (header.equals(TITLE_KEY)) {
              title = value;
            } else if (header.equals(BODY_KEY)) {
              body = value;
            } else if (header.equals(DATETIME_KEY)) {
              try {
                dateTime = dtFmt.parseDateTime(value);
              } catch (Exception e) {
                logger.underlyingLogger().error("ParseDateException: " + value);
              }
            } else if (header.equals(USERID_KEY)) {
              try {
                userId = Long.parseLong(value);
              } catch (NumberFormatException e) {
                logger.underlyingLogger().error("NumberFormatException: " + value);
              }
            }
          }
        }
      }

      // comment
      if (title == null && body != null) {
        Comment comment = new Comment();
        comment.body = body;
        comment.userId = userId;
        comment.dateTime = dateTime;
        lastPost.comments.add(comment);
      } else if (body == null && userId == null) {
        if (lastPost != null) {
          posts.add(lastPost);
        }
        lastPost = null;
        continue; // skip
      }
      // new post
      else {
        lastPost = new PostEntry();
        lastPost.commName = commName;
        lastPost.title = title;
        lastPost.body = body;
        lastPost.userId = userId;
        lastPost.dateTime = dateTime;
      }
    }
    br.close();

    if (lastPost != null) {
      posts.add(lastPost);
    }
  }

  private static Map<Integer, String> parseHeaderLine(String headerLine) {
    if (headerLine == null) {
      throw new IllegalStateException("Missing header");
    }

    Map<Integer, String> headerMap = new HashMap<>();
    String[] headers = headerLine.split(DELIM);
    for (int i = 0; i < headers.length; i++) {
      headerMap.put(i, headers[i]);
    }
    return headerMap;
  }

  public static class PostEntry {
    public String commName;
    public String title;
    public String body;
    public DateTime dateTime;
    public Long userId;
    public List<Comment> comments = new ArrayList<>();

    public boolean isCompleted() {
      return commName != null
          && title != null
          && body != null
          && dateTime != null
          && userId != null;
    }

    @Override
    public String toString() {
      return "PostEntry{"
          + "commName='"
          + commName
          + '\''
          + ", title='"
          + title
          + '\''
          + ", body='"
          + body
          + '\''
          + ", dateTime="
          + dateTime
          + ", userId="
          + userId
          + ", comments="
          + comments
          + '}';
    }
  }

  public static class Comment {
    public String body;
    public DateTime dateTime;
    public Long userId;

    public boolean isCompleted() {
      return body != null && dateTime != null && userId != null;
    }

    @Override
    public String toString() {
      return "Comment{"
          + ", body='"
          + body
          + '\''
          + ", dateTime="
          + dateTime
          + ", userId="
          + userId
          + '}';
    }
  }
}
/**
 * 1. No unclosed order record Buyer action: Offer Seller action: NA
 *
 * <p>2. Buyer offered: Buyer action: Cancel Offer Seller action: Accept / Decline
 *
 * <p>[If offer not yet accepted by Seller] 3. Buyer cancelled offer: Buyer action: Offer Seller
 * action: NA (Message: Buyer cancelled offer)
 *
 * <p>[If offer by Buyer] 4. Seller accepted offer: Buyer action: Offer Again (Message: Seller
 * accepted your offer) TODO: Leave feedback Seller action: NA (Message: You accepted offer from
 * buyer) TODO: Leave feedback
 *
 * <p>[If offer by Buyer] 5. Seller declined offer: Buyer action: Offer (Message: Seller declined
 * your offer) Seller action: NA (Message: You declined offer from buyer)
 *
 * @author keithlei
 */
@Entity
@EntityListeners(AuditListener.class)
public class ConversationOrder extends domain.Entity implements Serializable, Creatable, Updatable {
  private static final play.api.Logger logger = play.api.Logger.apply(ConversationOrder.class);

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  public Long id;

  @Required @ManyToOne public Conversation conversation;

  @Required @ManyToOne public User user1; // buyer

  @Required @ManyToOne public User user2; // seller

  public Boolean cancelled = false; // by buyer

  @Temporal(TemporalType.TIMESTAMP)
  public Date cancelDate;

  public Boolean accepted = false; // by seller

  @Temporal(TemporalType.TIMESTAMP)
  public Date acceptDate;

  public Boolean declined = false; // by seller

  @Temporal(TemporalType.TIMESTAMP)
  public Date declineDate;

  public Boolean active = true;

  public Boolean deleted = false;

  public ConversationOrder() {}

  public ConversationOrder(Conversation conversation) {
    this.conversation = conversation;
    this.user1 = conversation.user1;
    this.user2 = conversation.user2;
    this.active = true;
  }

  @Override
  public void preSave() {}

  public boolean isOrderClosed() {
    return this.cancelled || this.accepted || this.declined;
  }

  public static ConversationOrder findById(Long id) {
    try {
      Query q =
          JPA.em()
              .createQuery("SELECT o from ConversationOrder o where id = ?1 and deleted = false");
      q.setParameter(1, id);
      return (ConversationOrder) q.getSingleResult();
    } catch (NoResultException e) {
      return null;
    }
  }

  public static ConversationOrder getActiveOrder(Conversation conversation) {
    Query q =
        JPA.em()
            .createQuery(
                "SELECT o from ConversationOrder o where conversation = ?1 and active = ?2 and deleted = false");
    q.setParameter(1, conversation);
    q.setParameter(2, true);
    q.setMaxResults(1);

    if (q.getMaxResults() > 1) {
      logger
          .underlyingLogger()
          .error("[conv=" + conversation.id + "] has " + q.getMaxResults() + " active orders!!");
    }

    try {
      return (ConversationOrder) q.getSingleResult();
    } catch (NoResultException e) {
      return null;
    }
  }
}
public class ImageUploadController extends Controller {
  private static play.api.Logger logger = play.api.Logger.apply(ImageUploadController.class);

  protected static ImageUploadUtil imageUploadUtil;

  protected static void setImageUploadUtil(ImageUploadUtil util) {
    imageUploadUtil = util;
  }

  @Transactional
  public static Result uploadPhoto() {
    final String loggedInUser = Application.getLoggedInUser();
    if (loggedInUser == null) {
      return ok(views.html.login.render());
    }

    DynamicForm form = DynamicForm.form().bindFromRequest();
    boolean fullSize = Boolean.parseBoolean(form.get("fullSize"));
    boolean thumbnail = Boolean.parseBoolean(form.get("thumbnail"));
    boolean miniThumbnail = Boolean.parseBoolean(form.get("miniThumbnail"));
    boolean mobile = Boolean.parseBoolean(form.get("mobile"));
    String category = form.get("category");
    ImageUploadUtil imageUploadUtil = new ImageUploadUtil(category);
    FilePart picture = request().body().asMultipartFormData().getFile("cover-photo");
    String fileName = picture.getFilename();
    DateTime now = new DateTime();
    File file = picture.getFile();
    String imageUrl;
    String imagePath;
    try {
      imageUrl = imageUploadUtil.getImageUrl(now, fileName);
      imagePath = imageUploadUtil.getImagePath(now, fileName);
      FileUtils.copyFile(file, new File(imagePath));
    } catch (IOException e) {
      return status(500);
    }

    if (thumbnail == true) {
      StringBuffer sb = new StringBuffer(fileName);
      sb.insert(fileName.indexOf("."), "_thumb");
      String name = sb.toString();
      try {
        String imagePath2 = imageUploadUtil.getImagePath(now, name);
        BufferedImage originalImage = ImageIO.read(file);
        File file2 = new File(imagePath2);
        Thumbnails.of(originalImage).size(200, 200).toFile(file2);

      } catch (IOException e) {
        return status(500);
      }
    }

    if (miniThumbnail == true) {
      StringBuffer sb = new StringBuffer(fileName);
      sb.insert(fileName.indexOf("."), "_minithumb");
      String name = sb.toString();
      try {
        String imagePath2 = imageUploadUtil.getImagePath(now, name);
        BufferedImage originalImage = ImageIO.read(file);
        File file2 = new File(imagePath2);
        Thumbnails.of(originalImage).size(150, 150).toFile(file2);
      } catch (IOException e) {
        return status(500);
      }
    }

    if (mobile == true) {
      StringBuffer sb = new StringBuffer(fileName);
      sb.insert(fileName.indexOf("."), "_m");
      String name = sb.toString();
      try {
        String imagePath2 = imageUploadUtil.getImagePath(now, name);
        BufferedImage originalImage = ImageIO.read(file);
        File file2 = new File(imagePath2);
        Thumbnails.of(originalImage).size(100, 100).toFile(file2);
      } catch (IOException e) {
        return status(500);
      }

      if (thumbnail == true) {
        StringBuffer sb1 = new StringBuffer(fileName);
        sb1.insert(fileName.indexOf("."), "_thumb_m");
        String name1 = sb1.toString();
        try {
          String imagePath2 = imageUploadUtil.getImagePath(now, name1);
          BufferedImage originalImage = ImageIO.read(file);
          File file2 = new File(imagePath2);
          Thumbnails.of(originalImage).size(80, 80).toFile(file2);
        } catch (IOException e) {
          return status(500);
        }
      }

      if (miniThumbnail == true) {
        StringBuffer sb1 = new StringBuffer(fileName);
        sb1.insert(fileName.indexOf("."), "_minithumb_m");
        String name1 = sb1.toString();
        try {
          String imagePath2 = imageUploadUtil.getImagePath(now, name1);
          BufferedImage originalImage = ImageIO.read(file);
          File file2 = new File(imagePath2);
          Thumbnails.of(originalImage).size(50, 50).toFile(file2);
        } catch (IOException e) {
          return status(500);
        }
      }
    }

    Map<String, String> map = new HashMap<>();
    map.put("URL", Application.APPLICATION_BASE_URL + imageUrl);
    return ok(Json.toJson(map));
  }

  @Transactional
  public static Result uploadImage() {
    final String loggedInUser = Application.getLoggedInUser();
    if (loggedInUser == null) {
      return ok(views.html.login.render());
    }

    FilePart picture = request().body().asMultipartFormData().getFile("url-photo0");
    String fileName = picture.getFilename();
    logger.underlyingLogger().info("uploadImage. fileName=" + fileName);

    DateTime now = new DateTime();
    File file = picture.getFile();
    try {
      String imagePath = imageUploadUtil.getImagePath(now, fileName);
      FileUtils.copyFile(file, new File(imagePath));
    } catch (IOException e) {
      logger.underlyingLogger().error(loggedInUser + " failed to upload photo", e);
      return status(500);
    }

    String imageUrl = imageUploadUtil.getImageUrl(now, fileName);
    logger.underlyingLogger().info("uploadImage. imageUrl=" + imageUrl);

    Map<String, String> map = new HashMap<>();
    map.put("URL", imageUrl);
    logger.underlyingLogger().info(loggedInUser + " uploaded photo - " + imageUrl);
    return ok(Json.toJson(map));
  }

  @Transactional
  public static Result getImage(Long year, Long month, Long date, String name) {
    response().setHeader("Cache-Control", "max-age=604800");
    String path = imageUploadUtil.getImagePath(year, month, date, name);
    return ok(new File(path));
  }
}