List of usage examples for javax.activation FileDataSource FileDataSource
public FileDataSource(String name)
From source file:org.freebxml.omar.server.repository.filesystem.FileSystemRepositoryManager.java
/** * Returns the RepositoryItem with the given unique ID. * * @param id Unique id for repository item * @return RepositoryItem instance/*from w w w. j a va2 s. co m*/ * @exception RegistryException */ public RepositoryItem getRepositoryItem(String id) throws RegistryException { RepositoryItem repositoryItem = null; String origId = id; // Strip off the "urn:uuid:" id = Utility.getInstance().stripId(id); try { String path = getRepositoryItemPath(id); File riFile = new File(path); if (!riFile.exists()) { String errmsg = ServerResourceBundle.getInstance().getString("message.RepositoryItemDoesNotExist", new Object[] { id }); log.error(errmsg); throw new RegistryException(errmsg); } DataHandler contentDataHandler = new DataHandler(new FileDataSource(riFile)); Element sigElement = null; path += ".sig"; File sigFile = new File(path); if (!sigFile.exists()) { String errmsg = "Payload signature for repository item id=\"" + id + "\" does not exist!"; //log.error(errmsg); throw new RegistryException(errmsg); } else { javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory .newInstance(); dbf.setNamespaceAware(true); javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document sigDoc = db.parse(new FileInputStream(sigFile)); repositoryItem = new RepositoryItemImpl(id, sigDoc.getDocumentElement(), contentDataHandler); } } catch (RegistryException e) { throw e; } catch (Exception e) { throw new RegistryException(e); } return repositoryItem; }
From source file:it.cnr.icar.eric.common.Utility.java
/** * Create a RepositoryItem containing provided content. * * @param id the id of the created ExtrinsicObject created for the RepositoryItem * @param content contents of the created RepositoryItem * * @return a <code>RepositoryItem</code> value * @throws IOException encountered during IO operations *//*from ww w. j a v a2 s . c o m*/ public RepositoryItem createRepositoryItem(String id, String content) throws IOException { File file = createTempFile(content, true); DataHandler dh = new DataHandler(new FileDataSource(file)); RepositoryItem ri = new RepositoryItemImpl(id, dh); return ri; }
From source file:org.wso2.identity.integration.test.user.mgt.UserImportLoggingTestCase.java
@Test(description = "Method to test the bulk user import error scenario. The test checks for the RemoteException " + "which is thrown by the bulkImportUser method", dependsOnMethods = { "testBulkUserImportLogFileIsPresent" }) public void testBulkImportWithUserAdminException() throws UserAdminUserAdminException { String errorMessage = ""; File bulkUserFile = new File(BULK_USER_FILE + BULK_USER_IMPORT_ERROR_FILE); DataHandler handler = new DataHandler(new FileDataSource(bulkUserFile)); try {//from ww w . jav a 2 s.c om userMgtClient.bulkImportUsers(USER_STORE_DOMAIN, BULK_USER_IMPORT_ERROR_FILE, handler, null); } catch (RemoteException e) { errorMessage = e.getMessage(); assertEquals(errorMessage, ERROR_MESSAGE); } if (StringUtils.isNotBlank(errorMessage)) { errorMessage = errorMessage.replaceAll(" ", "").replaceAll("\\.", ""); String[] segments = errorMessage.split(","); String errorSegment = segments[1]; String duplicateUserSegment = segments[2]; assertEquals(Integer.valueOf(errorSegment.split(":")[1]).intValue(), FAILED_USER_COUNT); assertEquals(Integer.valueOf(duplicateUserSegment.split(":")[1]).intValue(), DUPLICATE_USER_COUNT); } }
From source file:com.github.thorqin.webapi.mail.MailService.java
private void doSendMail(Mail mail) { long beginTime = System.currentTimeMillis(); Properties props = new Properties(); Session session;//from www . ja v a 2 s .c o m props.put("mail.smtp.auth", String.valueOf(serverConfig.useAuthentication())); // If want to display SMTP protocol detail then uncomment following statement // props.put("mail.debug", "true"); props.put("mail.smtp.host", serverConfig.getHost()); if (serverConfig.getPort() != null) { props.put("mail.smtp.port", serverConfig.getPort()); } if (serverConfig.getSecure().equals(MailConfig.SECURE_STARTTLS)) { props.put("mail.smtp.starttls.enable", "true"); if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } else if (serverConfig.getSecure().equals(MailConfig.SECURE_SSL)) { props.put("mail.smtp.socketFactory.port", serverConfig.getPort()); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } else { if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } // Uncomment to show SMTP protocal // session.setDebug(true); MimeMessage message = new MimeMessage(session); StringBuilder mailTo = new StringBuilder(); try { if (mail.from != null) message.setFrom(new InternetAddress(mail.from)); else if (serverConfig.getFrom() != null) message.setFrom(new InternetAddress(serverConfig.getFrom())); if (mail.to != null) { for (String to : mail.to) { if (mailTo.length() > 0) mailTo.append(","); mailTo.append(to); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); } } if (mail.subject != null) message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?="); message.setSentDate(new Date()); BodyPart bodyPart = new MimeBodyPart(); if (mail.htmlBody != null) bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8"); else if (mail.textBody != null) bodyPart.setText(mail.textBody); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); if (mail.attachments != null) { for (String attachment : mail.attachments) { BodyPart attachedBody = new MimeBodyPart(); File attachedFile = new File(attachment); DataSource source = new FileDataSource(attachedFile); attachedBody.setDataHandler(new DataHandler(source)); attachedBody.setDisposition(MimeBodyPart.ATTACHMENT); String filename = attachedFile.getName(); attachedBody.setFileName( "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?="); multipart.addBodyPart(attachedBody); } } message.setContent(multipart); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); if (serverConfig.enableTrace()) { MailInfo info = new MailInfo(); info.recipients = mail.to; info.sender = StringUtil.join(message.getFrom()); info.smtpServer = serverConfig.getHost(); info.smtpUser = serverConfig.getUsername(); info.subject = mail.subject; info.startTime = beginTime; info.runningTime = System.currentTimeMillis() - beginTime; MonitorService.record(info); } } catch (Exception ex) { logger.log(Level.SEVERE, "Send mail failed!", ex); } }
From source file:org.wso2.appserver.integration.common.utils.SpringServiceMaker.java
public void createAndUploadSpringBean(String springContextFilePath, String springBeanFilePath, String sessionCookie, String backendURL) throws Exception { SpringBeansData data = getSpringBeanNames(springContextFilePath, springBeanFilePath, this.getClass().getClassLoader()); String beanClasses[] = data.getBeans(); if (springBeanFilePath == null) { String msg = "spring.non.existent.file"; log.warn(msg);// ww w .j ava 2 s .c o m throw new AxisFault(msg); } int endIndex = springBeanFilePath.lastIndexOf(File.separator); String filePath = springBeanFilePath.substring(0, endIndex); String archiveFileName = springBeanFilePath.substring(endIndex); archiveFileName = archiveFileName.substring(1, archiveFileName.lastIndexOf(".")); ArchiveManipulator archiveManipulator = new ArchiveManipulator(); // ----------------- Unzip the file ------------------------------------ String unzippeDir = filePath + File.separator + "springTemp"; File unzipped = new File(unzippeDir); unzipped.mkdirs(); try { archiveManipulator.extract(springBeanFilePath, unzippeDir); } catch (IOException e) { String msg = "spring.cannot.extract.archive"; handleException(msg, e); } // TODO copy the spring xml String springContextRelLocation = "spring/context.xml"; try { File springContextRelDir = new File(unzippeDir + File.separator + "spring"); springContextRelDir.mkdirs(); File absFile = new File(springContextRelDir, "context.xml"); if (!absFile.exists()) { absFile.createNewFile(); } File file = new File(springContextFilePath); FileInputStream in = new FileInputStream(file); FileOutputStream out = new FileOutputStream(absFile); // Transfer bytes from in to out byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } catch (FileNotFoundException e) { throw AxisFault.makeFault(e); } catch (IOException e) { throw AxisFault.makeFault(e); } // ---- Generate the services.xml and place it in META-INF ----- File file = new File(unzippeDir + File.separator + "META-INF" + File.separator + "services.xml"); file.mkdirs(); try { File absoluteFile = file.getAbsoluteFile(); if (absoluteFile.exists()) { absoluteFile.delete(); } absoluteFile.createNewFile(); OutputStream os = new FileOutputStream(file); OMElement servicesXML = createServicesXMLFromSpringBeans(beanClasses, springContextRelLocation); servicesXML.build(); servicesXML.serialize(os); } catch (Exception e) { String msg = "spring.cannot.write.services.xml"; handleException(msg, e); } // ----------------- Create the AAR ------------------------------------ // These are the files to include in the ZIP file String outAARFilename = filePath + File.separator + archiveFileName + ".aar"; try { archiveManipulator.archiveDir(outAARFilename, unzipped.getPath()); } catch (IOException e) { String msg = "Spring cannot create new aar archive"; handleException(msg, e); } File fileToUpload = new File(outAARFilename); FileDataSource fileDataSource = new FileDataSource(fileToUpload); DataHandler dataHandler = new DataHandler(fileDataSource); try { SpringServiceUploaderClient uploaderClient = new SpringServiceUploaderClient(backendURL, sessionCookie); uploaderClient.uploadSpringServiceFile(archiveFileName + ".aar", dataHandler); } catch (Exception e) { String msg = "spring.unable.to.upload"; handleException(msg, e); } }
From source file:org.wso2.carbon.attachment.mgt.test.AttachmentMgtDAOBasicOperationsTest.java
/** * Creates an attachment stub bean which is consumable by the Back-End server interface * {@link org.wso2.carbon.attachment.mgt.skeleton.AttachmentMgtServiceSkeletonInterface} * * @return an attachment stub bean which is consumable by the Back-End server interface *//*from w w w . j a v a 2s .c o m*/ private TAttachment createAttachment() { dummyAttachment = new TAttachment(); dummyAttachment.setName("DummyName"); dummyAttachment.setContentType("DummyContentType"); dummyAttachment.setCreatedBy("DummyUser"); DataHandler handler = new DataHandler(new FileDataSource(new File( "src" + File.separator + "test" + File.separator + "resources" + File.separator + "dbConfig.xml"))); dummyAttachment.setContent(handler); return dummyAttachment; }
From source file:org.onesec.raven.ivr.vmail.impl.VMailManagerNodeTest.java
@Test public void pushNewMessageTest() throws Exception { File testFile = createTestFile(); VMailBoxNode vbox = createVBox(manager, "vbox1", true); createVBoxNumber(vbox, "111", true); assertTrue(manager.start());//from w w w .j a v a 2 s. co m assertEquals(0, vbox.getNewMessagesCount()); ds.pushData(new NewVMailMessageImpl("111", "222", new Date(), new FileDataSource(testFile))); assertEquals(1, vbox.getNewMessagesCount()); }
From source file:ste.xtest.mail.BugFreeFileTransport.java
@Test public void send_multipart_message() throws Exception { Session session = Session.getInstance(config); Message message = new MimeMessage(Session.getInstance(config)); message.setFrom(new InternetAddress("from@domain.com")); message.addRecipient(Message.RecipientType.TO, new InternetAddress("to@domain.com")); message.setSubject("the subject"); MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); String htmlText = "<H1>hello world</H1><img src=\"cid:image\">"; messageBodyPart.setContent(htmlText, "text/html"); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); DataSource fds = new FileDataSource("src/test/resources/images/6096.png"); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setHeader("Content-ID", "<image>"); multipart.addBodyPart(messageBodyPart); message.setContent(multipart);//from www . j ava 2 s .co m session.getTransport().sendMessage(message, message.getAllRecipients()); then(FileUtils.readFileToString(new File(TMP.getRoot(), "message"))).contains("From: from@domain.com\r") .contains("To: to@domain.com\r").contains("Subject: the subject\r").contains("hello world") .contains("Content-ID: <image>"); }
From source file:com.enonic.esl.net.Mail.java
/** * <p/> Send the mail. The SMTP host is contacted and the mail is sent according to the parameters set. </p> <p/> If it fails, it is * considered a runtime exception. Note that this doesn't make it very failsafe, so care should be taken when one wants fault tolerance. * One solution could be to catch the exception thrown. Another solution could be to use the JavaMail API directly. </p> *///from www . ja va 2s. co m public void send() throws ESLException { // smtp server Properties smtpProperties = new Properties(); if (smtpHost != null) { smtpProperties.put("mail.smtp.host", smtpHost); System.setProperty("mail.smtp.host", smtpHost); } else { smtpProperties.put("mail.smtp.host", DEFAULT_SMTPHOST); System.setProperty("mail.smtp.host", DEFAULT_SMTPHOST); } Session session = Session.getDefaultInstance(smtpProperties, null); try { // create message Message msg = new MimeMessage(session); // set from address InternetAddress addressFrom = new InternetAddress(); if (from_email != null) { addressFrom.setAddress(from_email); } if (from_name != null) { addressFrom.setPersonal(from_name, ENCODING); } ((MimeMessage) msg).setFrom(addressFrom); if ((to.size() == 0 && bcc.size() == 0) || subject == null || (message == null && htmlMessage == null)) { LOG.error("Missing data. Unable to send mail."); throw new ESLException("Missing data. Unable to send mail."); } // set to: for (int i = 0; i < to.size(); ++i) { String[] recipient = to.get(i); InternetAddress addressTo = new InternetAddress(recipient[1]); if (recipient[0] != null) { addressTo.setPersonal(recipient[0], ENCODING); } ((MimeMessage) msg).addRecipient(Message.RecipientType.TO, addressTo); } // set bcc: for (int i = 0; i < bcc.size(); ++i) { String[] recipient = bcc.get(i); InternetAddress addressTo = null; try { addressTo = new InternetAddress(recipient[1]); } catch (Exception e) { System.err.println("exception on address: " + recipient[1]); continue; } if (recipient[0] != null) { addressTo.setPersonal(recipient[0], ENCODING); } ((MimeMessage) msg).addRecipient(Message.RecipientType.BCC, addressTo); } // set cc: for (int i = 0; i < cc.size(); ++i) { String[] recipient = cc.get(i); InternetAddress addressTo = new InternetAddress(recipient[1]); if (recipient[0] != null) { addressTo.setPersonal(recipient[0], ENCODING); } ((MimeMessage) msg).addRecipient(Message.RecipientType.CC, addressTo); } // Setting subject and content type ((MimeMessage) msg).setSubject(subject, ENCODING); if (message != null) { message = RegexpUtil.substituteAll("\\\\n", "\n", message); } // if there are any attachments, treat this as a multipart message. if (attachments.size() > 0) { BodyPart messageBodyPart = new MimeBodyPart(); if (message != null) { ((MimeBodyPart) messageBodyPart).setText(message, ENCODING); } else { DataHandler dataHandler = new DataHandler( new ByteArrayDataSource(htmlMessage, "text/html", ENCODING)); ((MimeBodyPart) messageBodyPart).setDataHandler(dataHandler); } Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // add all attachments for (int i = 0; i < attachments.size(); ++i) { Object obj = attachments.get(i); if (obj instanceof String) { System.err.println("attachment is String"); messageBodyPart = new MimeBodyPart(); ((MimeBodyPart) messageBodyPart).setText((String) obj, ENCODING); multipart.addBodyPart(messageBodyPart); } else if (obj instanceof File) { messageBodyPart = new MimeBodyPart(); FileDataSource fds = new FileDataSource((File) obj); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setFileName(fds.getName()); multipart.addBodyPart(messageBodyPart); } else if (obj instanceof FileItem) { FileItem fileItem = (FileItem) obj; messageBodyPart = new MimeBodyPart(); FileItemDataSource fds = new FileItemDataSource(fileItem); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setFileName(fds.getName()); multipart.addBodyPart(messageBodyPart); } else { // byte array messageBodyPart = new MimeBodyPart(); ByteArrayDataSource bads = new ByteArrayDataSource((byte[]) obj, "text/html", ENCODING); messageBodyPart.setDataHandler(new DataHandler(bads)); messageBodyPart.setFileName(bads.getName()); multipart.addBodyPart(messageBodyPart); } } msg.setContent(multipart); } else { if (message != null) { ((MimeMessage) msg).setText(message, ENCODING); } else { DataHandler dataHandler = new DataHandler( new ByteArrayDataSource(htmlMessage, "text/html", ENCODING)); ((MimeMessage) msg).setDataHandler(dataHandler); } } // send message Transport.send(msg); } catch (AddressException e) { String MESSAGE_30 = "Error in email address: " + e.getMessage(); LOG.warn(MESSAGE_30); throw new ESLException(MESSAGE_30, e); } catch (UnsupportedEncodingException e) { String MESSAGE_40 = "Unsupported encoding: " + e.getMessage(); LOG.error(MESSAGE_40, e); throw new ESLException(MESSAGE_40, e); } catch (SendFailedException sfe) { Throwable t = null; Exception e = sfe.getNextException(); while (e != null) { t = e; if (t instanceof SendFailedException) { e = ((SendFailedException) e).getNextException(); } else { e = null; } } if (t != null) { String MESSAGE_50 = "Error sending mail: " + t.getMessage(); throw new ESLException(MESSAGE_50, t); } else { String MESSAGE_50 = "Error sending mail: " + sfe.getMessage(); throw new ESLException(MESSAGE_50, sfe); } } catch (MessagingException e) { String MESSAGE_50 = "Error sending mail: " + e.getMessage(); LOG.error(MESSAGE_50, e); throw new ESLException(MESSAGE_50, e); } }
From source file:it.cnr.icar.eric.server.security.authentication.CertificateAuthority.java
/** Extension request to sign specified cert and return the signed cert. */ @SuppressWarnings("static-access") public RegistryResponseHolder signCertificateRequest(UserType user, RegistryRequestType req, Map<?, ?> idToRepositoryItemMap) throws RegistryException { RegistryResponseHolder respHolder = null; RegistryResponseType ebRegistryResponseType = null; ServerRequestContext context = null; try {/*w w w . j a v a2 s.c o m*/ context = new ServerRequestContext("CertificateAUthority.signCertificateRequest", req); context.setUser(user); if (idToRepositoryItemMap.keySet().size() == 0) { throw new MissingRepositoryItemException( ServerResourceBundle.getInstance().getString("message.KSRepItemNotFound")); } String id = (String) idToRepositoryItemMap.keySet().iterator().next(); Object obj = idToRepositoryItemMap.get(id); if (!(obj instanceof RepositoryItem)) { throw new InvalidContentException(); } RepositoryItem ri = (RepositoryItem) obj; //This is the JKS keystore containing cert to be signed //Read original cert from keystore InputStream is = ri.getDataHandler().getInputStream(); KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(is, bu.FREEBXML_REGISTRY_KS_PASS_REQ.toCharArray()); is.close(); X509Certificate cert = (X509Certificate) keyStore .getCertificate(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_REQ); //Sign the cert cert = signCertificate(cert); //Replace cert with signed cert in keystore keyStore.deleteEntry(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_REQ); keyStore.setCertificateEntry(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_RESP, cert); //Add CA root cert (RegistryOPerator's cert) to keystore. keyStore.setCertificateEntry(bu.FREEBXML_REGISTRY_CACERT_ALIAS, getCACertificate()); Certificate[] certChain = new Certificate[2]; certChain[0] = cert; certChain[1] = getCACertificate(); validateChain(certChain); File repositoryItemFile = File.createTempFile(".eric-ca-resp", ".jks"); repositoryItemFile.deleteOnExit(); FileOutputStream fos = new java.io.FileOutputStream(repositoryItemFile); keyStore.store(fos, bu.FREEBXML_REGISTRY_KS_PASS_RESP.toCharArray()); fos.flush(); fos.close(); DataHandler dh = new DataHandler(new FileDataSource(repositoryItemFile)); RepositoryItemImpl riNew = new RepositoryItemImpl(id, dh); ebRegistryResponseType = bu.rsFac.createRegistryResponseType(); ebRegistryResponseType.setStatus(BindingUtility.CANONICAL_RESPONSE_STATUS_TYPE_ID_Success); HashMap<String, Object> respIdToRepositoryItemMap = new HashMap<String, Object>(); respIdToRepositoryItemMap.put(id, riNew); respHolder = new RegistryResponseHolder(ebRegistryResponseType, respIdToRepositoryItemMap); } catch (RegistryException e) { context.rollback(); throw e; } catch (Exception e) { context.rollback(); throw new RegistryException(e); } context.commit(); return respHolder; }