Java tutorial
/* * Mail Attachment Gateway * Copyright (c) 2016-2017 Carsten Rambow * mailto:developer AT elomagic DOT de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.elomagic.mag; import java.io.IOException; import java.io.InputStream; import java.net.InetSocketAddress; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.Part; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import com.icegreen.greenmail.user.GreenMailUser; import com.icegreen.greenmail.util.GreenMail; import com.icegreen.greenmail.util.ServerSetupTest; import org.apache.commons.io.IOUtils; import org.eclipse.jetty.security.ConstraintMapping; import org.eclipse.jetty.security.ConstraintSecurityHandler; import org.eclipse.jetty.security.HashLoginService; import org.eclipse.jetty.security.authentication.BasicAuthenticator; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.util.security.Constraint; import org.eclipse.jetty.util.security.Credential; import org.junit.After; /** * * @author Carsten Rambow */ public abstract class AbstractTest { protected MAG main; protected Server webserver; protected GreenMail greenMail; protected GreenMailUser greeUser; protected ServletMock putServlet; @After public void afterAbstractTest() throws Exception { if (main != null) { System.out.println("Shutting Main class..."); main.stop(); } if (greenMail != null) { System.out.println("Shutting E-Mail server..."); greenMail.stop(); } try { if (webserver != null) { System.out.println("Shutting web server server..."); webserver.stop(); } } catch (Exception e) { e.printStackTrace(System.err); } } protected void startEMailServer() throws Exception { System.setProperty("greenmail.auth.disabled", ""); greenMail = new GreenMail(ServerSetupTest.SMTP_IMAP); greenMail.start(); greeUser = greenMail.setUser("mailuser@localhost.com", "mailuser", "secret"); } protected void startHttpServer() throws Exception { putServlet = new ServletMock(); ServletHolder defaultServ = new ServletHolder("default", putServlet); defaultServ.setInitParameter("resourceBase", System.getProperty("user.dir")); defaultServ.setInitParameter("dirAllowed", "true"); ServletContextHandler handler = new ServletContextHandler(); handler.addServlet(defaultServ, "/"); // Enable BASIC authentication handler.setSecurityHandler(createSecurityHandler()); webserver = new Server(InetSocketAddress.createUnresolved("127.0.0.1", 8180)); webserver.setHandler(handler); // Start Server webserver.start(); } protected ConstraintSecurityHandler createSecurityHandler() { String[] roles = new String[] { "user" }; Constraint constraint = new Constraint(); constraint.setName(Constraint.__BASIC_AUTH); constraint.setRoles(roles); constraint.setAuthenticate(true); ConstraintMapping mapping = new ConstraintMapping(); mapping.setConstraint(constraint); mapping.setPathSpec("/*"); HashLoginService loginService = new HashLoginService(); loginService.putUser("john.doe", Credential.getCredential("secret"), roles); ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler(); securityHandler.addConstraintMapping(mapping); securityHandler.setLoginService(loginService); securityHandler.setAuthenticator(new BasicAuthenticator()); return securityHandler; } protected MimeMessage createMimeMessage(String filename) throws Exception { MimeBodyPart textPart = new MimeBodyPart(); textPart.setContent("This is some text to be displayed inline", "text/plain"); textPart.setDisposition(Part.INLINE); MimeBodyPart binaryPart = new MimeBodyPart(); InputStream in = getClass().getResourceAsStream("/TestFile.pdf"); binaryPart.setContent(getOriginalMailAttachment(), "application/pdf"); binaryPart.setDisposition(Part.ATTACHMENT); binaryPart.setFileName(filename); Multipart mp = new MimeMultipart(); mp.addBodyPart(textPart); mp.addBodyPart(binaryPart); MimeMessage message = new MimeMessage(greenMail.getImap().createSession()); message.setRecipients(Message.RecipientType.TO, new InternetAddress[] { new InternetAddress("mailuser@localhost.com") }); message.setSubject("Another test mail subject"); message.setContent(mp); // return message; // GreenMailUtil.createTextEmail("to@localhost.com", "from@localhost.com", "subject", "body", greenMail.getImap().getServerSetup()); } protected byte[] getOriginalMailAttachment() throws IOException { InputStream in = getClass().getResourceAsStream("/TestFile.pdf"); return IOUtils.readFully(in, in.available()); } protected Future<byte[]> createFileExistsFuture(Path file) { ExecutorService executor = Executors.newFixedThreadPool(2); FutureTask<byte[]> futureTask = new FutureTask<>(() -> { byte[] result = null; do { if (Files.exists(file)) { InputStream in = Files.newInputStream(file, StandardOpenOption.READ); result = IOUtils.readFully(in, in.available()); } Thread.sleep(100); } while (result == null); return result; }); executor.execute(futureTask); return futureTask; } protected Future<Boolean> createPutServletFuture(ServletMock putServlet) { ExecutorService executor = Executors.newFixedThreadPool(2); FutureTask<Boolean> futureTask = new FutureTask<>(() -> { while (!putServlet.received) { Thread.sleep(100); } return putServlet.received; }); executor.execute(futureTask); return futureTask; } }