diff --git a/network/src/main/java/de/muehlencord/shared/network/http/HttpLayer.java b/network/src/main/java/de/muehlencord/shared/network/http/HttpLayer.java index dbd0c72..4c691d5 100644 --- a/network/src/main/java/de/muehlencord/shared/network/http/HttpLayer.java +++ b/network/src/main/java/de/muehlencord/shared/network/http/HttpLayer.java @@ -10,256 +10,212 @@ 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 - * + * * @author joern@muehlencord.de */ public class HttpLayer { - private static final Logger logger = getLogger(HttpLayer.class); - /** the url to post to */ - private String destinationUrlString; - /** the encoding to use */ - private String encoding; + private static final Logger LOGGER = Logger.getLogger(HttpLayer.class); + /** the url to post to */ + private final String destinationUrlString; + /** the encoding to use */ + private final String encoding; - /** - * creates a new http layer which can communicate with the given url - * - * @param urlString - * the url to communicate with - */ - public HttpLayer(String urlString) { - this.destinationUrlString = urlString; - 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 parameterMap = new HashMap<>(); - String[] valueArray = { message }; - parameterMap.put(parameter, valueArray); - post(parameterMap); - } - - public void post(List> 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 parameterMap) throws MessageNotSendException { - List> parameterList = new LinkedList<>(); - parameterList.add(parameterMap); - String content = getDataString(parameterList); - post (content); + /** + * creates a new http layer which can communicate with the given url + * + * @param urlString the url to communicate with + */ + public HttpLayer(String urlString) { + this.destinationUrlString = urlString; + this.encoding = "UTF-8"; } - private void post(String messageString) throws MessageNotSendException { - // check URL string and return URL object if valid; otherwise - // MessageNotSendException is thrown - URLConnection urlConn = getUrlConnection(); + /** + * 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 parameterMap = new HashMap<>(); + String[] valueArray = {message}; + parameterMap.put(parameter, valueArray); + post(parameterMap); + } - // post data - IOException exceptionDuringPost = null; - OutputStream outputStream = null; - DataOutputStream printout = null; - try { - outputStream = urlConn.getOutputStream(); - printout = new DataOutputStream(outputStream); - printout.writeBytes(messageString); - printout.flush(); - logger.info("Message sent successfully"); - } 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); - } - } - } + /** + * 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> parameterMap) + throws MessageNotSendException { + // construct string to post + String content = getDataString(parameterMap); + post(content); - if (printout != null) { - try { - printout.close(); + } - } catch (IOException ex) { - if (logger.isDebugEnabled()) { - logger.debug(ex); - } - } - } - } + /** + * 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 parameterMap) throws MessageNotSendException { + List> parameterList = new LinkedList<>(); + parameterList.add(parameterMap); + String content = getDataString(parameterList); + post(content); + } - // Get response message - StringBuilder sb = new StringBuilder(); - InputStreamReader inputStreamReader = null; - BufferedReader bufferedReader = null; - try { - inputStreamReader = new InputStreamReader(urlConn.getInputStream()); - bufferedReader = new BufferedReader(inputStreamReader); - while (bufferedReader.ready()) { - sb.append(bufferedReader.readLine()); - } + private void post(String messageString) throws MessageNotSendException { + // check URL string and return URL object if valid; otherwise + // MessageNotSendException is thrown + URLConnection urlConn = getUrlConnection(); - if (logger.isDebugEnabled()) { - logger.debug("Response from server"); - logger.debug(sb.toString()); - } + // post data + IOException exceptionDuringPost = null; - } catch (IOException 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()); - } - } - } + try (OutputStream outputStream = urlConn.getOutputStream(); + DataOutputStream printout = new DataOutputStream(outputStream)) { + printout.writeBytes(messageString); + printout.flush(); + LOGGER.info("Message sent successfully"); + } catch (IOException ioex) { + // store received exception but first get output and + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(ioex); + } + exceptionDuringPost = ioex; + } - if (exceptionDuringPost != null) { - String hint = "Error while sending message. Reason: " - + exceptionDuringPost.getMessage(); - logger.error(hint); - throw new MessageNotSendException(hint, exceptionDuringPost); - } + // Get response message + StringBuilder sb = new StringBuilder(); + 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()); + } - /** - * - * @param urlString - * 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); - } + } catch (IOException ioex) { + LOGGER.error(ioex); + exceptionDuringPost = ioex; + } - // 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); - } + if (exceptionDuringPost != null) { + String hint = "Error while sending message. Reason: " + + exceptionDuringPost.getMessage(); + LOGGER.error(hint); + throw new MessageNotSendException(hint, exceptionDuringPost); + } - return urlConn; - } + } - /** - * returns the data string to post based on the given parameter map - * - * @param parameterMap - * 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> parameterList) - throws MessageNotSendException { - // perpare data - String data = ""; - for (Map parameterMap : parameterList) { - try { - Iterator keyIterator = parameterMap.keySet().iterator(); - while (keyIterator.hasNext()) { - String key = keyIterator.next(); - String[] valueArray = parameterMap.get(key); - for (String currentValue : valueArray) { - if (!data.equals("")) { - data += "&"; - } - 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 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); + } - 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> parameterList) + throws MessageNotSendException { + // perpare data + StringBuilder sb = new StringBuilder(); + for (Map parameterMap : parameterList) { + try { + Iterator> parameterIterator = parameterMap.entrySet().iterator(); + while (parameterIterator.hasNext()) { + Map.Entry 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(); + } } diff --git a/network/src/main/java/de/muehlencord/shared/network/mail/DefaultMailReader.java b/network/src/main/java/de/muehlencord/shared/network/mail/DefaultMailReader.java index 798f02b..4f8332d 100644 --- a/network/src/main/java/de/muehlencord/shared/network/mail/DefaultMailReader.java +++ b/network/src/main/java/de/muehlencord/shared/network/mail/DefaultMailReader.java @@ -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; } }