Extracting inline images coming in mail body using java Mail API - java

I have written two methods one for attachments and one email body content. I need to extract the images from email body. These two methods are working fine but when images are coming in email body it is should be saved in database. So it can be used later.
For attachmnents:-
public static List getAttachments(MimeMultipart multipart, List existingAttachments) {
if (multipart != null) {
try {
if (existingAttachments == null) {
existingAttachments = new ArrayList<MimeBodyPart>();
}
for (int i = 0; i < multipart.getCount(); i++) {
if (multipart.getBodyPart(i) instanceof MimeBodyPart) {
MimeBodyPart currentPart = (MimeBodyPart) multipart.getBodyPart(i);
if (Part.ATTACHMENT.equalsIgnoreCase(currentPart.getDisposition())) {
if (!existingAttachments.contains(currentPart)) {
existingAttachments.add(currentPart);
System.out.println(currentPart.getFileName());
}
} else if (currentPart.getContent() instanceof MimeMultipart) {
existingAttachments = getAttachments((MimeMultipart) currentPart.getContent(), existingAttachments);
}
}
}
} catch (MessagingException ex) {
LoggerFactory.getLogger(EmailUtil.class.getName()).error(ex.getMessage());
} catch (IOException ex) {
LoggerFactory.getLogger(EmailUtil.class.getName()).error(ex.getMessage());
}
}
return existingAttachments;
}
for email Body ContentThis method is extracting email body content
public static String getContent(MimeMultipart multipart) {
String emailContent = null;
if (multipart != null) {
try {
for (int i = 0; i < multipart.getCount(); i++) {
if (multipart.getBodyPart(i) instanceof MimeBodyPart) {
MimeBodyPart currentPart = (MimeBodyPart) multipart.getBodyPart(i);
if (Part.INLINE.equalsIgnoreCase(currentPart.getDisposition())) {
LoggerFactory.getLogger(EmailUtil.class.getName()).info("Content dispo is inline");
emailContent = (String) currentPart.getContent();
} else if (currentPart.getDisposition() == null && currentPart.getContentType().toLowerCase().contains("text")) {
LoggerFactory.getLogger(EmailUtil.class.getName()).info("Content dispo is null and type is text/*");
try {
emailContent = (String) currentPart.getContent();
} catch (ClassCastException ex) {
LoggerFactory.getLogger(EmailUtil.class.getName()).warn("Classcast exception caught and managed");
try {
InputStream is = currentPart.getInputStream();
emailContent = IOUtils.toString(is, currentPart.getEncoding());
Document doc=Jsoup.parse(emailContent);
Elements elements =doc.getElementsByTag("img");
System.out.println(elements);
int htmlCloseIndex = emailContent.indexOf("</html>");
emailContent = emailContent.substring(0, htmlCloseIndex);
emailContent+="</html>";
} catch (Exception e) {
LoggerFactory.getLogger(EmailUtil.class.getName()).error("Exception rebound caught and managed, email content will not read");
//emailContent = "Unable to read email content";
e.printStackTrace();
}
}
}else if (currentPart.getDisposition() == null && currentPart.getContentType().contains("TEXT")) {
LoggerFactory.getLogger(EmailUtil.class.getName()).info("Content dispo is null and type is TEXT/*");
try {
emailContent = (String) currentPart.getContent();
} catch (ClassCastException ex) {
LoggerFactory.getLogger(EmailUtil.class.getName()).warn("Classcast exception caught and managed");
try {
InputStream is = currentPart.getInputStream();
emailContent = IOUtils.toString(is, currentPart.getEncoding());
int htmlCloseIndex = emailContent.indexOf("</html>");
emailContent = emailContent.substring(0, htmlCloseIndex);
emailContent+="</html>";
} catch (Exception e) {
LoggerFactory.getLogger(EmailUtil.class.getName()).error("Exception rebound caught and managed, email content will not read");
//emailContent = "Unable to read email content";
e.printStackTrace();
}
}
}
else if (currentPart.getContent() instanceof MimeMultipart) {
emailContent = getContent((MimeMultipart) currentPart.getContent());
}
}
}
} catch (MessagingException ex) {
LoggerFactory.getLogger(EmailUtil.class.getName()).error(ex.getMessage());
LoggerFactory.getLogger(EmailUtil.class.getName()).warn("email content will not read");
//emailContent = "Unable to read email content";
} catch (IOException ex) {
LoggerFactory.getLogger(EmailUtil.class.getName()).error(ex.getMessage());
LoggerFactory.getLogger(EmailUtil.class.getName()).warn("email content will not read");
// emailContent = "Unable to read email content";
} catch (ClassCastException ex) {
LoggerFactory.getLogger(EmailUtil.class.getName()).warn("Classcast exception caught and managed");
// emailContent = "Unable to read email content";
}
}
return emailContent;
}

Okay one starts with the <img src="..."> tags, you already took:
Elements elements = doc.getElementsByTag("img");
An img tag for an embedded image looks like:
<img src="data:image/jpeg;base64,..." ...>
So having the src attribute do:
String src = ...
if (src.startsWith("data:")) { // Embedded image data.
int p = src.indexOf(';'); // Or better ";base64,"
if (p == -1) {
throw new IllegalArgumentException();
}
String mimeType = src.substring(5, p);
String base64Data = src.substring(p + 1 + 6 + 1); // ";base64,"
byte[] data = Base64.getDecoder().decode(base64Data);
String file = "test." + mimeType.replaceFirst("^.*/(.*)$", "$1");
Path path = Paths.get(file);
Files.write(path, data);
}

Related

how can i replace the try catch to not get the error exception when i am not sending the file?

I am sending variables from ajax to java! in my ajax method I am sending 2 variables: idtabPrest and idPolice!
I am getting an error exception because I am not passing the File ! how can I make this function work and read the variables even if i am not sending the File.
I commented the Try/catch of the file to pass the variables! but in some ajax methods I am using the file.
public String upload_via_ajax() {
try {
String property = "java.io.tmpdir";
String tempDir = System.getProperty(property);
String html = "inside upload via ajax";
// try {
// File destFile = new File(tempDir, myFileFileName.substring(0,
// myFileFileName.lastIndexOf(".")) + ".csv");
// FileUtils.copyFile(myFile, destFile);
//
// getRequest().getSession().setAttribute("filePath",
// destFile.getPath());
//POUR REFERENCE DECLARATION
if(annee != null) {
TableReferentielDto tableReferentielDto = new TableReferentielDto();
tableReferentielDto.setId(Long.parseLong(annee));
TableReferentielDto anneeLabel =(TableReferentielDto) tableReferentielGetByIdCmd
.execute(tableReferentielDto);
getRequest().getSession().setAttribute("annee",
anneeLabel.getLibelle());
}
//POUR DATE DEBUT DECLARATION
if(moisDebutDeclaration != null){
getRequest().getSession().setAttribute("moisDebutDeclaration",
moisDebutDeclaration);
}
//POUR DATE FIN DECLARATION
if(moisFinDeclaration != null){
getRequest().getSession().setAttribute("moisFinDeclaration",
moisFinDeclaration);
}
//ID POLICE
if(idPolice != null){
getRequest().getSession().setAttribute("idPolice",
idPolice);
}
if(idTabPrest != null) {
getRequest().getSession().setAttribute("idTabPrest",
idTabPrest);
}
if(idTabTarif != null){
getRequest().getSession().setAttribute("idTabTarif",
idTabTarif);
}
html = "file uploaded";
// } catch (IOException e) {
//
// html = "error in uploading file";
// e.printStackTrace();
// }
return SUCCESS;
} catch (Exception e) {
return SUCCESS;
}
}

Android - Zip Path Traversal in play store

I am uploading my App on play store but get me bellow error:
Zip Path Traversal Your app contains an unsafe unzipping pattern that
may lead to a Path Traversal vulnerability. Please see this Google
Help Center article to learn how to fix the issue.
org.apache.cordova.Zip.unzipSync
I edited my source code like this LINK, but get me error.
Here is my source code changed:
public class Zip extends CordovaPlugin {
private static final String LOG_TAG = "Zip";
// Can't use DataInputStream because it has the wrong endian-ness.
private static int readInt(InputStream is) throws IOException {
int a = is.read();
int b = is.read();
int c = is.read();
int d = is.read();
return a | b << 8 | c << 16 | d << 24;
}
#Override
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException {
if ("unzip".equals(action)) {
unzip(args, callbackContext);
return true;
}
return false;
}
private void unzip(final CordovaArgs args, final CallbackContext callbackContext) {
this.cordova.getThreadPool().execute(new Runnable() {
public void run() {
unzipSync(args, callbackContext);
}
});
}
private void unzipSync(CordovaArgs args, CallbackContext callbackContext) {
InputStream inputStream = null;
try {
String zipFileName = args.getString(0);
String outputDirectory = args.getString(1);
// Since Cordova 3.3.0 and release of File plugins, files are accessed via cdvfile://
// Accept a path or a URI for the source zip.
Uri zipUri = getUriForArg(zipFileName);
Uri outputUri = getUriForArg(outputDirectory);
CordovaResourceApi resourceApi = webView.getResourceApi();
File tempFile = resourceApi.mapUriToFile(zipUri);
if (tempFile == null || !tempFile.exists()) {
String errorMessage = "Zip file does not exist";
callbackContext.error(errorMessage);
Log.e(LOG_TAG, errorMessage);
return;
}
File outputDir = resourceApi.mapUriToFile(outputUri);
outputDirectory = outputDir.getAbsolutePath();
outputDirectory += outputDirectory.endsWith(File.separator) ? "" : File.separator;
if (outputDir == null || (!outputDir.exists() && !outputDir.mkdirs())) {
String errorMessage = "Could not create output directory";
callbackContext.error(errorMessage);
Log.e(LOG_TAG, errorMessage);
return;
}
OpenForReadResult zipFile = resourceApi.openForRead(zipUri);
ProgressEvent progress = new ProgressEvent();
progress.setTotal(zipFile.length);
inputStream = new BufferedInputStream(zipFile.inputStream);
inputStream.mark(10);
int magic = readInt(inputStream);
if (magic != 875721283) { // CRX identifier
inputStream.reset();
} else {
// CRX files contain a header. This header consists of:
// * 4 bytes of magic number
// * 4 bytes of CRX format version,
// * 4 bytes of public key length
// * 4 bytes of signature length
// * the public key
// * the signature
// and then the ordinary zip data follows. We skip over the header before creating the ZipInputStream.
readInt(inputStream); // version == 2.
int pubkeyLength = readInt(inputStream);
int signatureLength = readInt(inputStream);
inputStream.skip(pubkeyLength + signatureLength);
progress.setLoaded(16 + pubkeyLength + signatureLength);
}
// The inputstream is now pointing at the start of the actual zip file content.
ZipInputStream zis = new ZipInputStream(inputStream);
inputStream = zis;
ZipEntry ze;
byte[] buffer = new byte[32 * 1024];
boolean anyEntries = false;
while ((ze = zis.getNextEntry()) != null) {
try {
anyEntries = true;
String compressedName = ze.getName();
if (ze.isDirectory()) {
try {
File dir = new File(outputDirectory + compressedName);
File f = new File(dir, ze.getName());
String canonicalPath = f.getCanonicalPath();
if (!canonicalPath.startsWith(dir.toString())){
dir.mkdirs();
}else {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
}
} catch (Exception e) {
String errorMessage = "An error occurred while unzipping.";
callbackContext.error(errorMessage);
Log.e(LOG_TAG, errorMessage, e);
}
} else {
File file = new File(outputDirectory + compressedName);
File f = new File(file, ze.getName());
String canonicalPath = f.getCanonicalPath();
if (!canonicalPath.startsWith(file.toString())) {
file.getParentFile().mkdirs();
if (file.exists() || file.createNewFile()) {
try {
Log.w("Zip", "extracting: " + file.getPath());
FileOutputStream fout = new FileOutputStream(file);
int count;
while ((count = zis.read(buffer)) != -1) {
fout.write(buffer, 0, count);
}
fout.close();
} catch (Exception e) {
String errorMessage = "An error occurred while unzipping.";
callbackContext.error(errorMessage);
Log.e(LOG_TAG, errorMessage, e);
}
}
}else {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
}
}
progress.addLoaded(ze.getCompressedSize());
updateProgress(callbackContext, progress);
zis.closeEntry();
} catch (Exception e) {
String errorMessage = "An error occurred while unzipping.";
callbackContext.error(errorMessage);
Log.e(LOG_TAG, errorMessage, e);
}
}
// final progress = 100%
progress.setLoaded(progress.getTotal());
updateProgress(callbackContext, progress);
if (anyEntries)
callbackContext.success();
else
callbackContext.error("Bad zip file");
} catch (Exception e) {
String errorMessage = "An error occurred while unzipping.";
callbackContext.error(errorMessage);
Log.e(LOG_TAG, errorMessage, e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
}
}
private void updateProgress(CallbackContext callbackContext, ProgressEvent progress) throws JSONException {
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject());
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
}
private Uri getUriForArg(String arg) {
CordovaResourceApi resourceApi = webView.getResourceApi();
Uri tmpTarget = Uri.parse(arg);
return resourceApi.remapUri(
tmpTarget.getScheme() != null ? tmpTarget : Uri.fromFile(new File(arg)));
}
private static class ProgressEvent {
private long loaded;
private long total;
public long getLoaded() {
return loaded;
}
public void setLoaded(long loaded) {
this.loaded = loaded;
}
public void addLoaded(long add) {
this.loaded += add;
}
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
public JSONObject toJSONObject() throws JSONException {
return new JSONObject(
"{loaded:" + loaded +
",total:" + total + "}");
}
}
}

Parsing JSON Objects with Different Keys

I created an Android application which uses the Google Books API. When I get the JSON response from the server, I parse the response and retrieve the title, authors, category, publisher, page count, thumbnail and some more information about the book. The problem is that some books in the JSON response don't have the thumbnail key or category key. When I try to get those JSON key values the program throws an error and consequently skips the code of adding other books after the error occurred.
I solved that with nested try catch blocks. For example, if there isn't a publisher key in the response, then I would return null.
String publisher;
try {
publisher = volumeInfo.getString("publisher");
} catch (JSONException e) {
publisher = null;
}
Here is how the whole method for parsing the JSON response looks like:
private List<BookData> parseJsonResponse(String jsonResponse) {
List<BookData> bookData = new ArrayList<>();
try {
JSONObject rootObject = new JSONObject(jsonResponse);
JSONArray itemsArray = rootObject.getJSONArray("items");
for (int i = 0; i < itemsArray.length(); i++) {
JSONObject itemObject = itemsArray.getJSONObject(i);
JSONObject volumeInfo =
itemObject.getJSONObject("volumeInfo");
String title;
try {
title = volumeInfo.getString("title");
} catch (JSONException e) {
title = null;
}
ArrayList<String> authors;
try {
JSONArray authorsArray =
volumeInfo.getJSONArray("authors");
authors = new ArrayList<>();
for (int j = 0; j < authorsArray.length(); j++) {
authors.add(authorsArray.getString(j));
}
} catch (JSONException e) {
authors = null;
}
ArrayList<String> categories;
try {
JSONArray categoriesArray =
volumeInfo.getJSONArray("categories");
categories = new ArrayList<>();
for (int k = 0; k < categoriesArray.length(); k++) {
categories.add(categoriesArray.getString(k));
}
} catch (JSONException e) {
categories = null;
}
String publisher;
try {
publisher = volumeInfo.getString("publisher");
} catch (JSONException e) {
publisher = null;
}
String publishedDate;
try {
publishedDate =
volumeInfo.getString("publishedDate");
} catch (JSONException e) {
publishedDate = null;
}
int pageCount;
try {
pageCount = volumeInfo.getInt("pageCount");
} catch (JSONException e) {
pageCount = 0;
}
String language;
try {
language = volumeInfo.getString("language");
} catch (JSONException e) {
language = null;
}
String description;
try {
description = volumeInfo.getString("description");
} catch (JSONException e) {
description = null;
}
String bookWebsite;
try {
bookWebsite = volumeInfo.getString("infoLink");
} catch (JSONException e) {
bookWebsite = null;
}
Bitmap thumbnail;
try {
JSONObject imageLink =
volumeInfo.getJSONObject("imageLinks");
String thumbnailUrl =
imageLink.getString("thumbnail");
thumbnail = getThumbnailBitmap(thumbnailUrl);
} catch (JSONException e) {
thumbnail = null;
}
// Add a new BookData object to the list
bookData.add(new BookData(title, thumbnail, authors,
categories, publisher, publishedDate,
pageCount, language, description,
bookWebsite));
}
} catch (JSONException e) {
Log.e(LOG_TAG, null, e);
}
return bookData;
}
After I complete my parsing, I have to update my views. I am using a list view, so the adapter needs to handle the views inflation.
I had to add an if statement to check if the variable is not null, then for example set the text of the text view. Else I set the text to "Publisher not available".
TextView publisher = listView.findViewById(R.id.book_publisher);
if (bookData.getPublisher() != null) {
publisher.setText(bookData.getPublisher());
} else {
publisher.setText("Publisher not available");
}
Here is how the whole adapter looks like:
public class BookDataAdapter extends ArrayAdapter<BookData> {
public BookDataAdapter(#NonNull Context context, #NonNull
List<BookData> bookDatas) {
super(context, 0, bookDatas);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView,
#NonNull ViewGroup parent) {
View listView = convertView;
if (listView == null) {
listView = LayoutInflater.from(getContext())
.inflate(R.layout.book_list_item, parent, false);
}
// Get current BookData object
BookData bookData = getItem(position);
ImageView thumbnail = listView.findViewById(R.id.book_thumbnail);
if (bookData.getThumbnail() != null) {
thumbnail.setImageBitmap(bookData.getThumbnail());
} else {
// Set default thumbnail
thumbnail.setImageResource(R.drawable.default_thumbnail);
}
TextView title = listView.findViewById(R.id.book_title);
if (bookData.getTitle() != null) {
title.setText(bookData.getTitle());
} else {
title.setText("Title not available");
}
TextView author = listView.findViewById(R.id.book_author);
if (bookData.getAuthors() != null) {
author.setText(listToString(bookData.getAuthors()));
} else {
author.setText("Authors not available");
}
TextView category = listView.findViewById(R.id.book_category);
if (bookData.getCategories() != null) {
category.setText("Category: " +
listToString(bookData.getCategories()));
} else {
category.setText("Category not available ");
}
TextView publisher = listView.findViewById(R.id.book_publisher);
if (bookData.getPublisher() != null) {
publisher.setText(bookData.getPublisher() + ", ");
} else {
publisher.setText("Publisher not available, ");
}
TextView publishedDate =
listView.findViewById(R.id.book_published_date);
if (bookData.getPublishedDate() != null) {
publishedDate.setText(bookData.getPublishedDate());
} else {
publishedDate.setText("Published date not available");
}
TextView pageCount = listView.findViewById(R.id.book_page_count);
if (bookData.getPageCount() != 0) {
pageCount.setText("Pages: " + bookData.getPageCount());
} else {
pageCount.setText("Page count not available");
}
TextView language = listView.findViewById(R.id.book_language);
if (bookData.getLanguage() != null) {
language.setText(bookData.getLanguage());
} else {
language.setText("Language not available");
}
TextView description =
listView.findViewById(R.id.book_description);
if (bookData.getDescription() != null) {
description.setText(bookData.getDescription());
} else {
description.setText("Description not available");
}
return listView;
}
private String listToString(List<String> list) {
if (list == null || list.size() == 0) {
return null;
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
builder.append(list.get(i));
if (i == (list.size() - 1)) {
break;
}
builder.append(", ");
}
return builder.toString();
}
}
And lastly I want to ask a question. Is there a better way or more efficient way of parsing the JSON response with different keys, because some people say that nested try catch statements are not a good practice?
Thank you very much!!
You have two options:
Using .has():
String publisher = null;
if(volumeInfo.has("publisher")){
publisher = volumeInfo.getString("publisher");
}
Using opt instead of get (better, IMO):
String publisher = volumeInfo.optString("publisher");
opt### methods default to null for objects and 0/false for primitives, so you don't have to write try/catch blocks or if conditions. You can also specify a second parameter as default value:
String publisher = volumeInfo.optString("publisher", "no publisher");
// if publisher is not a valid key, "no publisher" will be returned
Use can you .has() property of JSONObject
if(volumeInfo.has("publisher")){
volumeInfo.getString("publisher");
}
You don't need to wrap json operations in individual try/catch blocks.
There is a method in the json library to handle this problem:
jsonObject.isNull(key);
When you attempt to grab a value by key write it like this:
if (!volumeInfo.isNull("categories")) {
JSONArray categoryArray = volumeInfo.getJSONArray("categories");
}

read message text without getting all the content

public void getMessageById(
#PathParam("folderName") String folderName,
#PathParam("id") String id) {
MailMessage mailMessage = new MailMessage();
MimeMessage mimeMessage = null;
try {
Store store = mailSession.getStore();
store.connect("localhost", email, password);
Folder folder = store.getDefaultFolder();
folder = folder.getFolder(folderName.toUpperCase());
folder.open(Folder.READ_ONLY);
SearchTerm searchTerm = new MessageIDTerm(id);
Message[] messages = folder.search(searchTerm);
if (messages.length > 0) {
mimeMessage = (MimeMessage) messages[0];
}
if (mimeMessage != null) {
Object objRef = mimeMessage.getContent();
if (objRef != null) {
// if message content is not multipart
if (!(objRef instanceof Multipart)) {
//get message text here
System.out.println(mimeMessage.getContent().toString())
} else {
Multipart multipart = (Multipart) objRef;
for (int i = 0; i < multipart.getCount(); i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
if (bodyPart.isMimeType("text/*")) {
//get message text here
System.out.println(bodyPart.getContent()
.toString())
}
if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart
.getDisposition())) {
continue; // dealing with attachments only
}
if (bodyPart.isMimeType("image/*")) {
}
}
}
}
}
folder.close(false);
store.close();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The problem is that it take long time to fetch message text .
Is Object objRef = mimeMessage.getContent(); fetching all the content , if so is there any way to avoid fetching all the contents
Thanks for help ...
Rather than calling getContent and switching on whether it's a Multipart or not, use mimeMessage.isMimeType("multipart/") and mimeMessage.isMimeType("text/"). See the msgshow.java sample program.
Instead of fetching the text content all at once, you can use bodyPart.getInputStream to read it incrementally, which might help depending on what you're doing with it once you read it.
And of course you can use the Folder.fetch method to prefetch message metadata to speed up other parts of processing the messages. See the msgshow.java program again for an example.

How to make this code RESTful? (no HttpSessions)

I was wondering, I have the following snippets of code that I would like to eliminate the use of sessions and make it RESTful. I have a controller servlet that uses several handlers, which are used to determine the page to return to. For example, here are two of my handlers:
public class ReporterLoginHandler implements ActionHandler {
public String handleIt(Map params, HttpSession session) {
String reporterId = null;
String passwd = null;
String errMsg = null;
ReporterBean reporterBean = null;
String returnPage = "home";
try {
reporterId = ((String[]) params.get("reporterid"))[0];
passwd = ((String[]) params.get("passwd"))[0];
} catch (Exception ex) {
System.out.println("Oops, couldn't parse the parameters for login!");
}
if (reporterId == null || reporterId.length() == 0 || passwd == null || passwd.length() == 0) {
errMsg = "The reporterID or password cannot be empty";
} else if ((reporterBean = ReporterBeanFactory.getReporter(reporterId, passwd)) == null) {
errMsg = "The reporterID or password is not valid";
}
if (errMsg != null) {
session.setAttribute("msg", errMsg); //should be removed and replaced by a RESTful API
} else }
returnPage = "reporter_home";
session.setAttribute("reporterBean", reporterBean);
}
return returnPage;
}
}
public class PostItemHandler implements ActionHandler {
#Override
public String handleIt(Map<String, String[]> params, HttpSession session) {
String title = params.get("title")[0];
String story = params.get("story")[0];
String itemId = null;
String returnPage = "home";
if (params.containsKey("item")) {
itemId = params.get("item")[0];
}
ReporterBean rBean = (ReporterBean) session.getAttribute("reporterBean"); // needs to be replaced by a RESTful API
String msg = "";
int id = 0;
String filename = session.getAttribute("newsfile").toString();
if (title != null && title.length() > 0 && story != null && story.length() > 0) {
if (itemId != null && itemId.length() > 0) {
try {
id = Integer.parseInt(itemId);
} catch (Exception exc) {
msg = "Invalid format for news item ID";
}
if (rBean != null) {
if (msg.equals("") && NewsItemBeanFactory.editNewsItem(id, title, story, rBean.getReporterId())) {
msg = "News item " + id + " successfully edited!";
returnPage = "reporter_home";
try {
NewsItemBeanFactory.saveNewsItems(filename);
} catch (IOException ex) {
Logger.getLogger(PostItemHandler.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
msg = "News item " + id + " could not be edited!";
}
} else }
msg = "Error: please log in before adding or editing an item.";
}
} else {
if (rBean != null) {
NewsItemBeanFactory.addNewsItem(title, story, rBean.getReporterId());
msg = "News item successfully added!";
returnPage = "reporter_home";
try {
NewsItemBeanFactory.saveNewsItems(filename);
} catch (IOException ex) {
Logger.getLogger(PostItemHandler.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
msg = "Error: please log in before adding a new item.";
}
}
}
if (params.get("returnpage") != null) {
if (params.get("returnpage")[0].toString().equals("mynews")) {
Collection<NewsItemBean> newsItems = NewsItemBeanFactory.getAllItems();
ArrayList<NewsItemBean> myNewsItems = new ArrayList<NewsItemBean>();
for (NewsItemBean item : newsItems) {
if (rBean != null && rBean.getReporterId().equals(item.getReporterId())) {
myNewsItems.add(item);
}
}
session.setAttribute("mynews", myNewsItems); //needs to be replaced by a RESTful API
returnPage = "mynews";
}
}
session.setAttribute("msg", msg); //needs to be replaced by a RESTful API
return returnPage;
}
}
Specifically, I would like to eliminate the use of all sessions from my handlers (as well as from my controller servlet) and would like to create a RESTful API where the java beans are represented with JSON.
I would prefer not to use an external REST API creator such as Spring or Jersey, however, I am open to using Google's Gson to convert my beans to and from JSON.
EDIT: Also, I would like the login to return an authorization token when successful.
Could anyone help me here?

Categories

Resources