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.URLConnection;
import java.net.URLEncoder;
import static java.net.URLEncoder.encode;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.log4j.Logger;
import static org.apache.log4j.Logger.getLogger;
/**
* Communication endpoint for posting a messages
@ -26,17 +25,16 @@ import static org.apache.log4j.Logger.getLogger;
*/
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 */
private String destinationUrlString;
private final String destinationUrlString;
/** the encoding to use */
private String encoding;
private final String encoding;
/**
* creates a new http layer which can communicate with the given url
*
* @param urlString
* the url to communicate with
* @param urlString the url to communicate with
*/
public HttpLayer(String urlString) {
this.destinationUrlString = urlString;
@ -46,21 +44,23 @@ public class HttpLayer {
/**
* 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
* @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 };
String[] valueArray = {message};
parameterMap.put(parameter, valueArray);
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)
throws MessageNotSendException {
// construct string to post
@ -70,21 +70,18 @@ public class HttpLayer {
}
/**
* posts the parameters and values specified by the parameter map to the
* configured url
* 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
* @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<>();
List<Map<String, String[]>> parameterList = new LinkedList<>();
parameterList.add(parameterMap);
String content = getDataString(parameterList);
post (content);
post(content);
}
private void post(String messageString) throws MessageNotSendException {
@ -94,83 +91,42 @@ public class HttpLayer {
// post data
IOException exceptionDuringPost = null;
OutputStream outputStream = null;
DataOutputStream printout = null;
try {
outputStream = urlConn.getOutputStream();
printout = new DataOutputStream(outputStream);
try (OutputStream outputStream = urlConn.getOutputStream();
DataOutputStream printout = new DataOutputStream(outputStream)) {
printout.writeBytes(messageString);
printout.flush();
logger.info("Message sent successfully");
LOGGER.info("Message sent successfully");
} catch (IOException ioex) {
// store received exception but first get output and
if (logger.isDebugEnabled()) {
logger.debug(ioex);
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()) {
logger.debug(ex);
}
}
}
}
// Get response message
StringBuilder sb = new StringBuilder();
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
try {
inputStreamReader = new InputStreamReader(urlConn.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
try (InputStreamReader inputStreamReader = new InputStreamReader(urlConn.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
while (bufferedReader.ready()) {
sb.append(bufferedReader.readLine());
}
if (logger.isDebugEnabled()) {
logger.debug("Response from server");
logger.debug(sb.toString());
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Response from server");
LOGGER.debug(sb.toString());
}
} catch (IOException ioex) {
logger.error(ioex);
LOGGER.error(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) {
String hint = "Error while sending message. Reason: "
+ exceptionDuringPost.getMessage();
logger.error(hint);
LOGGER.error(hint);
throw new MessageNotSendException(hint, exceptionDuringPost);
}
@ -178,11 +134,9 @@ public class HttpLayer {
/**
*
* @param urlString
* the url to check
* @return a URl object created from the given urlString
* @throws MessageNotSendException
* if the url is invalid
* @return a URl object created from the given urlString.
*
* @throws MessageNotSendException if the url is invalid.
*/
private URLConnection getUrlConnection() throws MessageNotSendException {
URLConnection urlConn;
@ -192,13 +146,13 @@ public class HttpLayer {
} catch (MalformedURLException ex) {
String hint = "Cannot send message to url - invalid url "
+ destinationUrlString;
logger.error(hint);
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);
LOGGER.error(hint);
throw new MessageNotSendException(hint);
}
@ -218,7 +172,7 @@ public class HttpLayer {
} catch (IOException ioex) {
String hint = "Error while setting up connection. Reason: "
+ ioex.getMessage();
logger.error(hint);
LOGGER.error(hint);
throw new MessageNotSendException(hint, ioex);
}
@ -228,38 +182,40 @@ public class HttpLayer {
/**
* returns the data string to post based on the given parameter map
*
* @param parameterMap
* the parameter map to construct the data string from
* @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
*
* @throws MessageNotSendException if the datastring cannot be constructed
*/
private String getDataString(List<Map<String, String[]>> parameterList)
throws MessageNotSendException {
// perpare data
String data = "";
for (Map<String,String[]> parameterMap : parameterList) {
StringBuilder sb = new StringBuilder();
for (Map<String, String[]> parameterMap : parameterList) {
try {
Iterator<String> keyIterator = parameterMap.keySet().iterator();
while (keyIterator.hasNext()) {
String key = keyIterator.next();
String[] valueArray = parameterMap.get(key);
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 (!data.equals("")) {
data += "&";
if (sb.toString().equals("")) {
sb.append("&");
}
data += key.toLowerCase() + "="
+ encode(currentValue, encoding);
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);
LOGGER.error(hint);
throw new MessageNotSendException(hint, ex);
}
}
return data;
return sb.toString();
}
}

View File

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