throw new IllegalArgumentException("Argument is null"); //if sth is null, throw exception
User u = entityManager.find(User.class, userId);
if (u == null)
throw new IllegalArgumentException("User with specified ID was not found."); //if user not found, throw error
Attachment a = new Attachment();
a.setDateAdded(new Date());
a.setUser(u);
a.setFilename(filename);
a.setSize(0L);
entityManager.persist(a);
entityManager.flush(); //if the file was successfully put into the database, continue with saving the file on the disc
File f = new File(computePath(a));
f.getParentFile().mkdirs();
long bytes = FileCopyUtils.copy(new BufferedInputStream(stream), new BufferedOutputStream(new FileOutputStream(f)));
a.setSize(bytes);
}