fixed sonar bugs

This commit is contained in:
jomu
2015-02-21 14:01:26 +00:00
parent 3444384013
commit de31fa5898
2 changed files with 198 additions and 249 deletions

View File

@ -10,14 +10,13 @@ import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
import java.net.URLEncoder; import java.net.URLEncoder;
import static java.net.URLEncoder.encode;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.Map; import java.util.Map;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import static org.apache.log4j.Logger.getLogger;
/** /**
* Communication endpoint for posting a messages * Communication endpoint for posting a messages
@ -26,240 +25,197 @@ import static org.apache.log4j.Logger.getLogger;
*/ */
public class HttpLayer { public class HttpLayer {
private static final Logger logger = getLogger(HttpLayer.class); private static final Logger LOGGER = Logger.getLogger(HttpLayer.class);
/** the url to post to */ /** the url to post to */
private String destinationUrlString; private final String destinationUrlString;
/** the encoding to use */ /** the encoding to use */
private String encoding; private final String encoding;
/** /**
* creates a new http layer which can communicate with the given url * creates a new http layer which can communicate with the given url
* *
* @param urlString * @param urlString the url to communicate with
* the url to communicate with */
*/ public HttpLayer(String urlString) {
public HttpLayer(String urlString) { this.destinationUrlString = urlString;
this.destinationUrlString = urlString; this.encoding = "UTF-8";
this.encoding = "UTF-8";
}
/**
* posts the value of message into the varialbe parameter
*
* @param parameter
* the parameter to write the message to
* @param message
* the message to post
* @throws MessageNotSendException
* if the message cannot be sent
*/
public void post(String parameter, String message)
throws MessageNotSendException {
Map<String, String[]> parameterMap = new HashMap<>();
String[] valueArray = { message };
parameterMap.put(parameter, valueArray);
post(parameterMap);
}
public void post(List<Map<String, String[]>> parameterMap)
throws MessageNotSendException {
// construct string to post
String content = getDataString(parameterMap);
post(content);
}
/**
* posts the parameters and values specified by the parameter map to the
* configured url
*
* @param parameterMap
* the parameter map to post
* @throws MessageNotSendException
* if the http / post request cannot be executed
*
* TODO add https support
*/
public void post(Map<String, String[]> parameterMap) throws MessageNotSendException {
List<Map<String,String[]>> parameterList = new LinkedList<>();
parameterList.add(parameterMap);
String content = getDataString(parameterList);
post (content);
} }
private void post(String messageString) throws MessageNotSendException { /**
// check URL string and return URL object if valid; otherwise * posts the value of message into the varialbe parameter
// MessageNotSendException is thrown *
URLConnection urlConn = getUrlConnection(); * @param parameter the parameter to write the message to
* @param message the message to post
* @throws MessageNotSendException if the message cannot be sent
*/
public void post(String parameter, String message)
throws MessageNotSendException {
Map<String, String[]> parameterMap = new HashMap<>();
String[] valueArray = {message};
parameterMap.put(parameter, valueArray);
post(parameterMap);
}
// post data /**
IOException exceptionDuringPost = null; * posts a message using the given (additional) parameters.
OutputStream outputStream = null; * @param parameterMap the parameters to use
DataOutputStream printout = null; * @throws MessageNotSendException if the message could not be sent.
try { */
outputStream = urlConn.getOutputStream(); public void post(List<Map<String, String[]>> parameterMap)
printout = new DataOutputStream(outputStream); throws MessageNotSendException {
printout.writeBytes(messageString); // construct string to post
printout.flush(); String content = getDataString(parameterMap);
logger.info("Message sent successfully"); post(content);
} catch (IOException ioex) {
// store received exception but first get output and
if (logger.isDebugEnabled()) {
logger.debug(ioex);
}
exceptionDuringPost = ioex;
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException ex) {
if (logger.isDebugEnabled()) {
logger.debug(ex);
}
}
}
if (printout != null) { }
try {
printout.close();
} catch (IOException ex) { /**
if (logger.isDebugEnabled()) { * posts the parameters and values specified by the parameter map to the configured url
logger.debug(ex); *
} * @param parameterMap the parameter map to post
} * @throws MessageNotSendException if the http / post request cannot be executed
} *
} * TODO add https support
*/
public void post(Map<String, String[]> parameterMap) throws MessageNotSendException {
List<Map<String, String[]>> parameterList = new LinkedList<>();
parameterList.add(parameterMap);
String content = getDataString(parameterList);
post(content);
}
// Get response message private void post(String messageString) throws MessageNotSendException {
StringBuilder sb = new StringBuilder(); // check URL string and return URL object if valid; otherwise
InputStreamReader inputStreamReader = null; // MessageNotSendException is thrown
BufferedReader bufferedReader = null; URLConnection urlConn = getUrlConnection();
try {
inputStreamReader = new InputStreamReader(urlConn.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
while (bufferedReader.ready()) {
sb.append(bufferedReader.readLine());
}
if (logger.isDebugEnabled()) { // post data
logger.debug("Response from server"); IOException exceptionDuringPost = null;
logger.debug(sb.toString());
}
} catch (IOException ioex) { try (OutputStream outputStream = urlConn.getOutputStream();
logger.error(ioex); DataOutputStream printout = new DataOutputStream(outputStream)) {
exceptionDuringPost = ioex; printout.writeBytes(messageString);
} finally { printout.flush();
if (bufferedReader != null) { LOGGER.info("Message sent successfully");
try { } catch (IOException ioex) {
bufferedReader.close(); // store received exception but first get output and
} catch (IOException ex) { if (LOGGER.isDebugEnabled()) {
logger.error(ex.getMessage()); LOGGER.debug(ioex);
} }
} exceptionDuringPost = ioex;
if (inputStreamReader != null) { }
try {
inputStreamReader.close();
} catch (IOException ex) {
logger.error(ex.getMessage());
}
}
}
if (exceptionDuringPost != null) { // Get response message
String hint = "Error while sending message. Reason: " StringBuilder sb = new StringBuilder();
+ exceptionDuringPost.getMessage(); try (InputStreamReader inputStreamReader = new InputStreamReader(urlConn.getInputStream());
logger.error(hint); BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
throw new MessageNotSendException(hint, exceptionDuringPost); while (bufferedReader.ready()) {
} sb.append(bufferedReader.readLine());
}
} if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Response from server");
LOGGER.debug(sb.toString());
}
/** } catch (IOException ioex) {
* LOGGER.error(ioex);
* @param urlString exceptionDuringPost = ioex;
* the url to check }
* @return a URl object created from the given urlString
* @throws MessageNotSendException
* if the url is invalid
*/
private URLConnection getUrlConnection() throws MessageNotSendException {
URLConnection urlConn;
URL url;
try {
url = new URL(destinationUrlString);
} catch (MalformedURLException ex) {
String hint = "Cannot send message to url - invalid url "
+ destinationUrlString;
logger.error(hint);
throw new MessageNotSendException(hint, ex);
}
String protocol = url.getProtocol().toLowerCase();
if (!protocol.equals("http")) {
String hint = "protocol " + protocol + " not supported";
logger.error(hint);
throw new MessageNotSendException(hint);
}
// setup url connection if (exceptionDuringPost != null) {
try { String hint = "Error while sending message. Reason: "
// URL connection channel. + exceptionDuringPost.getMessage();
urlConn = url.openConnection(); LOGGER.error(hint);
// Let the run-time system (RTS) know that we want input. throw new MessageNotSendException(hint, exceptionDuringPost);
urlConn.setDoInput(true); }
// Let the RTS know that we want to do output.
urlConn.setDoOutput(true);
// No caching, we want the real thing.
urlConn.setUseCaches(false);
// Specify the content type.
urlConn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
} catch (IOException ioex) {
String hint = "Error while setting up connection. Reason: "
+ ioex.getMessage();
logger.error(hint);
throw new MessageNotSendException(hint, ioex);
}
return urlConn; }
}
/** /**
* returns the data string to post based on the given parameter map *
* * @return a URl object created from the given urlString.
* @param parameterMap *
* the parameter map to construct the data string from * @throws MessageNotSendException if the url is invalid.
* @return the data string to post */
* @throws MessageNotSendException private URLConnection getUrlConnection() throws MessageNotSendException {
* if the datastring cannot be constructed URLConnection urlConn;
*/ URL url;
private String getDataString(List<Map<String, String[]>> parameterList) try {
throws MessageNotSendException { url = new URL(destinationUrlString);
// perpare data } catch (MalformedURLException ex) {
String data = ""; String hint = "Cannot send message to url - invalid url "
for (Map<String,String[]> parameterMap : parameterList) { + destinationUrlString;
try { LOGGER.error(hint);
Iterator<String> keyIterator = parameterMap.keySet().iterator(); throw new MessageNotSendException(hint, ex);
while (keyIterator.hasNext()) { }
String key = keyIterator.next(); String protocol = url.getProtocol().toLowerCase();
String[] valueArray = parameterMap.get(key); if (!protocol.equals("http")) {
for (String currentValue : valueArray) { String hint = "protocol " + protocol + " not supported";
if (!data.equals("")) { LOGGER.error(hint);
data += "&"; throw new MessageNotSendException(hint);
} }
data += key.toLowerCase() + "="
+ encode(currentValue, encoding);
}
}
} catch (UnsupportedEncodingException ex) {
String hint = "Error while preparing data for message. Unknown encoding "
+ encoding;
logger.error(hint);
throw new MessageNotSendException(hint, ex);
}
}
return data; // setup url connection
} try {
// URL connection channel.
urlConn = url.openConnection();
// Let the run-time system (RTS) know that we want input.
urlConn.setDoInput(true);
// Let the RTS know that we want to do output.
urlConn.setDoOutput(true);
// No caching, we want the real thing.
urlConn.setUseCaches(false);
// Specify the content type.
urlConn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
} catch (IOException ioex) {
String hint = "Error while setting up connection. Reason: "
+ ioex.getMessage();
LOGGER.error(hint);
throw new MessageNotSendException(hint, ioex);
}
return urlConn;
}
/**
* returns the data string to post based on the given parameter map
*
* @param parameterList the parameter map to construct the data string from
* @return the data string to post
*
* @throws MessageNotSendException if the datastring cannot be constructed
*/
private String getDataString(List<Map<String, String[]>> parameterList)
throws MessageNotSendException {
// perpare data
StringBuilder sb = new StringBuilder();
for (Map<String, String[]> parameterMap : parameterList) {
try {
Iterator<Map.Entry<String, String[]>> parameterIterator = parameterMap.entrySet().iterator();
while (parameterIterator.hasNext()) {
Map.Entry<String, String[]> nextParameter = parameterIterator.next();
String key = nextParameter.getKey();
String[] valueArray = nextParameter.getValue();
for (String currentValue : valueArray) {
if (sb.toString().equals("")) {
sb.append("&");
}
sb.append(key.toLowerCase(Locale.US));
sb.append("=");
sb.append(URLEncoder.encode(currentValue, encoding));
}
}
} catch (UnsupportedEncodingException ex) {
String hint = "Error while preparing data for message. Unknown encoding "
+ encoding;
LOGGER.error(hint);
throw new MessageNotSendException(hint, ex);
}
}
return sb.toString();
}
} }

View File

@ -1,27 +1,21 @@
package de.muehlencord.shared.network.mail; package de.muehlencord.shared.network.mail;
import static de.muehlencord.shared.network.mail.MailMessageUtils.getInstance;
import de.muehlencord.shared.util.StringUtil; import de.muehlencord.shared.util.StringUtil;
import static de.muehlencord.shared.util.StringUtil.getStackTraceString;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import static java.lang.System.getProperties;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Properties; import java.util.Properties;
import java.util.logging.Level;
import javax.mail.Flags; import javax.mail.Flags;
import javax.mail.Folder; import javax.mail.Folder;
import javax.mail.Message; import javax.mail.Message;
import javax.mail.MessagingException; import javax.mail.MessagingException;
import javax.mail.Session; import javax.mail.Session;
import static javax.mail.Session.getInstance;
import javax.mail.Store; import javax.mail.Store;
import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMessage;
import javax.mail.search.MessageIDTerm; import javax.mail.search.MessageIDTerm;
import javax.mail.search.SearchTerm; import javax.mail.search.SearchTerm;
import javax.mail.util.SharedByteArrayInputStream; import javax.mail.util.SharedByteArrayInputStream;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import static org.apache.log4j.Logger.getLogger;
/** /**
* MailReader to connect and work with IMAP mailboxes. Also works with exchange servers. * MailReader to connect and work with IMAP mailboxes. Also works with exchange servers.
@ -31,7 +25,7 @@ import static org.apache.log4j.Logger.getLogger;
public abstract class DefaultMailReader implements MailReader { public abstract class DefaultMailReader implements MailReader {
/** the logging object */ /** the logging object */
private final static Logger logger = getLogger(DefaultMailReader.class); private final static Logger LOGGER = Logger.getLogger(DefaultMailReader.class);
/** the store to connect with */ /** the store to connect with */
private Store store = null; private Store store = null;
/** the smtp host to work with */ /** the smtp host to work with */
@ -61,10 +55,10 @@ public abstract class DefaultMailReader implements MailReader {
try { try {
getStore().close(); getStore().close();
} catch (MessagingException ex) { } catch (MessagingException ex) {
logger.error("Cannot disconnect from mailbox"); LOGGER.error("Cannot disconnect from mailbox");
logger.debug(getStackTraceString(ex)); LOGGER.debug(StringUtil.getStackTraceString(ex));
} finally { } finally {
logger.info("Connection closed"); LOGGER.info("Connection closed");
setStore(null); setStore(null);
} }
} }
@ -82,7 +76,7 @@ public abstract class DefaultMailReader implements MailReader {
try { try {
return getStore().getDefaultFolder().getFullName(); return getStore().getDefaultFolder().getFullName();
} catch (Exception ex) { } catch (Exception ex) {
logger.debug(getStackTraceString(ex)); LOGGER.debug(StringUtil.getStackTraceString(ex));
throw new MailReaderException("Error while retrieving default folder. Reason: " + ex.getMessage(), ex); throw new MailReaderException("Error while retrieving default folder. Reason: " + ex.getMessage(), ex);
} }
} }
@ -103,7 +97,7 @@ public abstract class DefaultMailReader implements MailReader {
returnValue.add(folder.getFullName()); returnValue.add(folder.getFullName());
} }
} catch (Exception ex) { } catch (Exception ex) {
logger.debug(getStackTraceString(ex)); LOGGER.debug(StringUtil.getStackTraceString(ex));
throw new MailReaderException("Cannot retrieve folder list. Reason: " + ex.getMessage(), ex); throw new MailReaderException("Cannot retrieve folder list. Reason: " + ex.getMessage(), ex);
} }
return returnValue; return returnValue;
@ -115,11 +109,11 @@ public abstract class DefaultMailReader implements MailReader {
* @return the session object to use * @return the session object to use
*/ */
protected Session getDefaultSession() { protected Session getDefaultSession() {
Properties props = (Properties) getProperties().clone(); Properties props = (Properties) System.getProperties().clone();
props.put("mail.smtp.host", configuration.getSmtpHost()); props.put("mail.smtp.host", configuration.getSmtpHost());
// TODO - add needed properties - only valid for session, do not overwrite properites // TODO - add needed properties - only valid for session, do not overwrite properites
// TODO - add chained properties // TODO - add chained properties
return getInstance(props, null); return Session.getInstance(props, null);
} }
/** /**
@ -236,7 +230,7 @@ public abstract class DefaultMailReader implements MailReader {
try { try {
folder.close(false); folder.close(false);
} catch (MessagingException ex) { } catch (MessagingException ex) {
logger.debug(getStackTraceString(ex)); LOGGER.debug(StringUtil.getStackTraceString(ex));
} }
} }
} }
@ -267,7 +261,7 @@ public abstract class DefaultMailReader implements MailReader {
try { try {
folder.close(false); folder.close(false);
} catch (MessagingException ex) { } catch (MessagingException ex) {
logger.debug(getStackTraceString(ex)); LOGGER.debug(StringUtil.getStackTraceString(ex));
} }
} }
} }
@ -291,7 +285,7 @@ public abstract class DefaultMailReader implements MailReader {
folder.open(Folder.READ_ONLY); folder.open(Folder.READ_ONLY);
Message[] messages = folder.getMessages(); Message[] messages = folder.getMessages();
for (Message msg : messages) { for (Message msg : messages) {
returnValue.add(getInstance(getValidMessage(msg))); returnValue.add(MailMessageUtils.getInstance(getValidMessage(msg)));
} }
} catch (Exception ex) { } catch (Exception ex) {
throw new MailReaderException("Cannot fetch email from folder " + folder.getFullName() + ". Reason: " + ex.getMessage(), ex); throw new MailReaderException("Cannot fetch email from folder " + folder.getFullName() + ". Reason: " + ex.getMessage(), ex);
@ -301,7 +295,7 @@ public abstract class DefaultMailReader implements MailReader {
try { try {
folder.close(false); folder.close(false);
} catch (MessagingException ex) { } catch (MessagingException ex) {
logger.debug(getStackTraceString(ex)); LOGGER.debug(StringUtil.getStackTraceString(ex));
} }
} }
} }
@ -360,7 +354,7 @@ public abstract class DefaultMailReader implements MailReader {
try { try {
folder.close(false); folder.close(false);
} catch (MessagingException ex) { } catch (MessagingException ex) {
logger.debug("Error while closing folder", ex); LOGGER.debug("Error while closing folder", ex);
} }
} }
} }
@ -419,7 +413,7 @@ public abstract class DefaultMailReader implements MailReader {
try { try {
df.close(false); df.close(false);
} catch (MessagingException ex) { } catch (MessagingException ex) {
logger.debug("Error while closing destination folder", ex); LOGGER.debug("Error while closing destination folder", ex);
} }
} }
@ -427,7 +421,7 @@ public abstract class DefaultMailReader implements MailReader {
try { try {
sf.close(true); sf.close(true);
} catch (MessagingException ex) { } catch (MessagingException ex) {
logger.debug("Error while closing source folder", ex); LOGGER.debug("Error while closing source folder", ex);
} }
} }
} }
@ -452,7 +446,7 @@ public abstract class DefaultMailReader implements MailReader {
return msg; return msg;
} catch (MessagingException ex) { } catch (MessagingException ex) {
initialException = ex; initialException = ex;
logger.debug("Direct access failed - trying workaround copy constructor"); LOGGER.debug("Direct access failed - trying workaround copy constructor");
} }
try { try {
@ -464,7 +458,7 @@ public abstract class DefaultMailReader implements MailReader {
cmsg.getContentType(); cmsg.getContentType();
return cmsg; return cmsg;
} catch (MessagingException ex) { } catch (MessagingException ex) {
logger.debug("Access via copy constructor failed, trying byte array constructor"); LOGGER.debug("Access via copy constructor failed, trying byte array constructor");
} }
try { try {
@ -476,14 +470,13 @@ public abstract class DefaultMailReader implements MailReader {
ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream();
msg.writeTo(bos); msg.writeTo(bos);
bos.close(); bos.close();
SharedByteArrayInputStream bis = SharedByteArrayInputStream bis = new SharedByteArrayInputStream(bos.toByteArray());
new SharedByteArrayInputStream(bos.toByteArray());
MimeMessage cmsg = new MimeMessage(session, bis); MimeMessage cmsg = new MimeMessage(session, bis);
bis.close(); bis.close();
return cmsg; return cmsg;
} catch (Exception ex) { } catch (Exception ex) {
logger.debug("Also fallback solution did not work"); LOGGER.debug("Also fallback solution did not work");
throw initialException; throw initialException;
} }
} }