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,17 +25,16 @@ 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;
@ -46,21 +44,23 @@ public class HttpLayer {
/** /**
* posts the value of message into the varialbe parameter * posts the value of message into the varialbe parameter
* *
* @param parameter * @param parameter the parameter to write the message to
* the parameter to write the message to * @param message the message to post
* @param message * @throws MessageNotSendException if the message cannot be sent
* the message to post
* @throws MessageNotSendException
* if the message cannot be sent
*/ */
public void post(String parameter, String message) public void post(String parameter, String message)
throws MessageNotSendException { throws MessageNotSendException {
Map<String, String[]> parameterMap = new HashMap<>(); Map<String, String[]> parameterMap = new HashMap<>();
String[] valueArray = { message }; String[] valueArray = {message};
parameterMap.put(parameter, valueArray); parameterMap.put(parameter, valueArray);
post(parameterMap); post(parameterMap);
} }
/**
* posts a message using the given (additional) parameters.
* @param parameterMap the parameters to use
* @throws MessageNotSendException if the message could not be sent.
*/
public void post(List<Map<String, String[]>> parameterMap) public void post(List<Map<String, String[]>> parameterMap)
throws MessageNotSendException { throws MessageNotSendException {
// construct string to post // construct string to post
@ -70,21 +70,18 @@ public class HttpLayer {
} }
/** /**
* posts the parameters and values specified by the parameter map to the * posts the parameters and values specified by the parameter map to the configured url
* configured url
* *
* @param parameterMap * @param parameterMap the parameter map to post
* the parameter map to post * @throws MessageNotSendException if the http / post request cannot be executed
* @throws MessageNotSendException
* if the http / post request cannot be executed
* *
* TODO add https support * TODO add https support
*/ */
public void post(Map<String, String[]> parameterMap) throws MessageNotSendException { public void post(Map<String, String[]> parameterMap) throws MessageNotSendException {
List<Map<String,String[]>> parameterList = new LinkedList<>(); List<Map<String, String[]>> parameterList = new LinkedList<>();
parameterList.add(parameterMap); parameterList.add(parameterMap);
String content = getDataString(parameterList); String content = getDataString(parameterList);
post (content); post(content);
} }
private void post(String messageString) throws MessageNotSendException { private void post(String messageString) throws MessageNotSendException {
@ -94,83 +91,42 @@ public class HttpLayer {
// post data // post data
IOException exceptionDuringPost = null; IOException exceptionDuringPost = null;
OutputStream outputStream = null;
DataOutputStream printout = null; try (OutputStream outputStream = urlConn.getOutputStream();
try { DataOutputStream printout = new DataOutputStream(outputStream)) {
outputStream = urlConn.getOutputStream();
printout = new DataOutputStream(outputStream);
printout.writeBytes(messageString); printout.writeBytes(messageString);
printout.flush(); printout.flush();
logger.info("Message sent successfully"); LOGGER.info("Message sent successfully");
} catch (IOException ioex) { } catch (IOException ioex) {
// store received exception but first get output and // store received exception but first get output and
if (logger.isDebugEnabled()) { if (LOGGER.isDebugEnabled()) {
logger.debug(ioex); LOGGER.debug(ioex);
} }
exceptionDuringPost = 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()) {
logger.debug(ex);
}
}
}
} }
// Get response message // Get response message
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
InputStreamReader inputStreamReader = null; try (InputStreamReader inputStreamReader = new InputStreamReader(urlConn.getInputStream());
BufferedReader bufferedReader = null; BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
try {
inputStreamReader = new InputStreamReader(urlConn.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
while (bufferedReader.ready()) { while (bufferedReader.ready()) {
sb.append(bufferedReader.readLine()); sb.append(bufferedReader.readLine());
} }
if (logger.isDebugEnabled()) { if (LOGGER.isDebugEnabled()) {
logger.debug("Response from server"); LOGGER.debug("Response from server");
logger.debug(sb.toString()); LOGGER.debug(sb.toString());
} }
} catch (IOException ioex) { } catch (IOException ioex) {
logger.error(ioex); LOGGER.error(ioex);
exceptionDuringPost = ioex; exceptionDuringPost = ioex;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
logger.error(ex.getMessage());
}
}
if (inputStreamReader != null) {
try {
inputStreamReader.close();
} catch (IOException ex) {
logger.error(ex.getMessage());
}
}
} }
if (exceptionDuringPost != null) { if (exceptionDuringPost != null) {
String hint = "Error while sending message. Reason: " String hint = "Error while sending message. Reason: "
+ exceptionDuringPost.getMessage(); + exceptionDuringPost.getMessage();
logger.error(hint); LOGGER.error(hint);
throw new MessageNotSendException(hint, exceptionDuringPost); throw new MessageNotSendException(hint, exceptionDuringPost);
} }
@ -178,11 +134,9 @@ public class HttpLayer {
/** /**
* *
* @param urlString * @return a URl object created from the given urlString.
* the url to check *
* @return a URl object created from the given urlString * @throws MessageNotSendException if the url is invalid.
* @throws MessageNotSendException
* if the url is invalid
*/ */
private URLConnection getUrlConnection() throws MessageNotSendException { private URLConnection getUrlConnection() throws MessageNotSendException {
URLConnection urlConn; URLConnection urlConn;
@ -192,13 +146,13 @@ public class HttpLayer {
} catch (MalformedURLException ex) { } catch (MalformedURLException ex) {
String hint = "Cannot send message to url - invalid url " String hint = "Cannot send message to url - invalid url "
+ destinationUrlString; + destinationUrlString;
logger.error(hint); LOGGER.error(hint);
throw new MessageNotSendException(hint, ex); throw new MessageNotSendException(hint, ex);
} }
String protocol = url.getProtocol().toLowerCase(); String protocol = url.getProtocol().toLowerCase();
if (!protocol.equals("http")) { if (!protocol.equals("http")) {
String hint = "protocol " + protocol + " not supported"; String hint = "protocol " + protocol + " not supported";
logger.error(hint); LOGGER.error(hint);
throw new MessageNotSendException(hint); throw new MessageNotSendException(hint);
} }
@ -218,7 +172,7 @@ public class HttpLayer {
} catch (IOException ioex) { } catch (IOException ioex) {
String hint = "Error while setting up connection. Reason: " String hint = "Error while setting up connection. Reason: "
+ ioex.getMessage(); + ioex.getMessage();
logger.error(hint); LOGGER.error(hint);
throw new MessageNotSendException(hint, ioex); throw new MessageNotSendException(hint, ioex);
} }
@ -228,38 +182,40 @@ public class HttpLayer {
/** /**
* returns the data string to post based on the given parameter map * returns the data string to post based on the given parameter map
* *
* @param parameterMap * @param parameterList the parameter map to construct the data string from
* the parameter map to construct the data string from
* @return the data string to post * @return the data string to post
* @throws MessageNotSendException *
* if the datastring cannot be constructed * @throws MessageNotSendException if the datastring cannot be constructed
*/ */
private String getDataString(List<Map<String, String[]>> parameterList) private String getDataString(List<Map<String, String[]>> parameterList)
throws MessageNotSendException { throws MessageNotSendException {
// perpare data // perpare data
String data = ""; StringBuilder sb = new StringBuilder();
for (Map<String,String[]> parameterMap : parameterList) { for (Map<String, String[]> parameterMap : parameterList) {
try { try {
Iterator<String> keyIterator = parameterMap.keySet().iterator(); Iterator<Map.Entry<String, String[]>> parameterIterator = parameterMap.entrySet().iterator();
while (keyIterator.hasNext()) { while (parameterIterator.hasNext()) {
String key = keyIterator.next(); Map.Entry<String, String[]> nextParameter = parameterIterator.next();
String[] valueArray = parameterMap.get(key); String key = nextParameter.getKey();
String[] valueArray = nextParameter.getValue();
for (String currentValue : valueArray) { for (String currentValue : valueArray) {
if (!data.equals("")) { if (sb.toString().equals("")) {
data += "&"; sb.append("&");
} }
data += key.toLowerCase() + "=" sb.append(key.toLowerCase(Locale.US));
+ encode(currentValue, encoding); sb.append("=");
sb.append(URLEncoder.encode(currentValue, encoding));
} }
} }
} catch (UnsupportedEncodingException ex) { } catch (UnsupportedEncodingException ex) {
String hint = "Error while preparing data for message. Unknown encoding " String hint = "Error while preparing data for message. Unknown encoding "
+ encoding; + encoding;
logger.error(hint); LOGGER.error(hint);
throw new MessageNotSendException(hint, ex); throw new MessageNotSendException(hint, ex);
} }
} }
return data; 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;
} }
} }