public static void setAttachment(Message message, String filename) throws MessagingException { // Create a multipar message Multipart multipart = new MimeMultipart(); BodyPart messageBodyPart = new MimeBodyPart(); //Set File DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); //Add "file part" to multipart multipart.addBodyPart(messageBodyPart); //Set multipart to message message.setContent(multipart); }
public DataSource viewAvatarById(Long accountId, int width, String tenantId) throws Exception { if (accountId == null) { logger.info("accountId cannot be null"); return null; } String key = "accountId:" + accountId + ":" + width; String userId = Long.toString(accountId); DataSource dataSource = this.avatarCache.getDataSource(userId, width); if (dataSource != null) { return dataSource; } AccountInfo accountInfo = accountInfoManager.get(accountId); dataSource = this.viewAvatarByAccountInfo(accountInfo, width, tenantId); this.avatarCache.updateDataSource(userId, width, dataSource); return dataSource; }
public DataSource viewAvatarByUsername(String username, int width, String tenantId) throws Exception { // String key = "username:" + username + ":" + width; AccountInfo accountInfo = accountInfoManager.findUniqueBy("username", username); String userId = Long.toString(accountInfo.getId()); DataSource dataSource = this.avatarCache.getDataSource(userId, width); if (dataSource != null) { return dataSource; } dataSource = this.viewAvatarByAccountInfo(accountInfo, width, tenantId); this.avatarCache.updateDataSource(userId, width, dataSource); return dataSource; }
public void updateDataSource(String userId, int width, DataSource dataSource) { try { String key = userId + ":" + width; byte[] bytes = IOUtils.toByteArray(dataSource.getInputStream()); Set<String> aliasValue = this.aliasCache.get(userId); if (aliasValue == null) { aliasValue = new HashSet<String>(); this.aliasCache.put(userId, aliasValue); } aliasValue.add(key); this.dataCache.put(key, bytes); } catch (Exception ex) { logger.error(ex.getMessage(), ex); } }
public StoreDTO saveStore(InputStream inputStream, String fileName, String contentType, String tenantId) throws Exception { int len = -1; byte[] b = new byte[1024]; ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); while ((len = inputStream.read(b, 0, 1024)) != -1) { baos2.write(b, 0, len); } inputStream.close(); byte[] bytes = baos2.toByteArray(); DataSource dataSource = new ByteArrayDataSource(fileName, bytes); StoreDTO storeDto = storeService.saveStore(model, dataSource, tenantId); return storeDto; }
public StoreResult saveStore(String model, String key, DataSource dataSource) throws Exception { String path = key; File dir = new File(baseDir + "/" + model); dir.mkdirs(); File targetFile = new File(baseDir + "/" + model + "/" + path); FileOutputStream fos = new FileOutputStream(targetFile); try { FileCopyUtils.copy(dataSource.getInputStream(), fos); fos.flush(); } finally { fos.close(); } StoreResult storeResult = new StoreResult(); storeResult.setModel(model); storeResult.setKey(path); storeResult.setDataSource(new FileDataSource(targetFile)); return storeResult; }
/** * Create an Activation Framework DataSource for the given InputStreamSource. * @param inputStreamSource the InputStreamSource (typically a Spring Resource) * @param contentType the content type * @param name the name of the DataSource * @return the Activation Framework DataSource */ protected DataSource createDataSource( final InputStreamSource inputStreamSource, final String contentType, final String name) { return new DataSource() { @Override public InputStream getInputStream() throws IOException { return inputStreamSource.getInputStream(); } @Override public OutputStream getOutputStream() { throw new UnsupportedOperationException("Read-only javax.activation.DataSource"); } @Override public String getContentType() { return contentType; } @Override public String getName() { return name; } }; }
public void addAttachment(final FormFile file) throws Exception { addAttachment(file.getFileName(), new DataHandler(new DataSource() { @Override public OutputStream getOutputStream() throws IOException { throw new IOException("No output stream."); } @Override public String getName() { return file.getFileName(); } @Override public InputStream getInputStream() throws IOException { return file.getInputStream(); } @Override public String getContentType() { return file.getContentType(); } })); }
public static void eventUpdated(Event updatedEvent, String message, InternetAddress replyTo, DataSource attachment) throws Exception { if (ApplicationProperty.EmailConfirmationEvents.isFalse()) return; Session session = updatedEvent.getSession(); if (session == null) for (Meeting m: updatedEvent.getMeetings()) if (m.getLocation() != null) { session = m.getLocation().getSession(); break; } EventInterface event = EventDetailBackend.getEventDetail(session, updatedEvent, null); ApproveEventRpcRequest request = new ApproveEventRpcRequest(); request.setOperation(SaveOrApproveEventRpcRequest.Operation.UPDATE); if (message != null && !message.isEmpty()) request.setMessage(message); request.setEmailConfirmation(true); request.setSessionId(session == null ? null : session.getUniqueId()); request.setEvent(event); SaveOrApproveEventRpcResponse response = new SaveOrApproveEventRpcResponse(); response.setEvent(event); new EventEmail(request, response, attachment, replyTo).send(null); }
/** * Creates a new {@link Dispatch} stub that connects to the given pipe. * * @param portInfo * see <a href="#param">common parameters</a> * @param owner * see <a href="#param">common parameters</a> * @param binding * see <a href="#param">common parameters</a> * @param clazz * Type of the {@link Dispatch} to be created. * See {@link Service#createDispatch(QName, Class, Service.Mode)}. * @param mode * The mode of the dispatch. * See {@link Service#createDispatch(QName, Class, Service.Mode)}. * @param epr * see <a href="#param">common parameters</a> * TODO: are these parameters making sense? */ public static <T> Dispatch<T> createDispatch(WSPortInfo portInfo, WSService owner, WSBinding binding, Class<T> clazz, Service.Mode mode, @Nullable WSEndpointReference epr) { if (clazz == SOAPMessage.class) { return (Dispatch<T>) createSAAJDispatch(portInfo, binding, mode, epr); } else if (clazz == Source.class) { return (Dispatch<T>) createSourceDispatch(portInfo, binding, mode, epr); } else if (clazz == DataSource.class) { return (Dispatch<T>) createDataSourceDispatch(portInfo, binding, mode, epr); } else if (clazz == Message.class) { if(mode==Mode.MESSAGE) return (Dispatch<T>) createMessageDispatch(portInfo, binding, epr); else throw new WebServiceException(mode+" not supported with Dispatch<Message>"); } else if (clazz == Packet.class) { if(mode==Mode.MESSAGE) return (Dispatch<T>) createPacketDispatch(portInfo, binding, epr); else throw new WebServiceException(mode+" not supported with Dispatch<Packet>"); } else throw new WebServiceException("Unknown class type " + clazz.getName()); }
/** * Constructs a MimeMultipart object and its bodyparts from the * given DataSource. <p> * * This constructor handles as a special case the situation where the * given DataSource is a MultipartDataSource object. In this case, this * method just invokes the superclass (i.e., Multipart) constructor * that takes a MultipartDataSource object. <p> * * Otherwise, the DataSource is assumed to provide a MIME multipart * byte stream. The <code>parsed</code> flag is set to false. When * the data for the body parts are needed, the parser extracts the * "boundary" parameter from the content type of this DataSource, * skips the 'preamble' and reads bytes till the terminating * boundary and creates MimeBodyParts for each part of the stream. * * @param ct content type. * @param ds DataSource, can be a MultipartDataSource. * @throws MessagingException in case of error. */ public BMMimeMultipart(DataSource ds, ContentType ct) throws MessagingException { super(ds, ct); boundary = ct.getParameter("boundary"); /* if (ds instanceof MultipartDataSource) { // ask super to do this for us. setMultipartDataSource((MultipartDataSource)ds); return; } // 'ds' was not a MultipartDataSource, we have // to parse this ourself. parsed = false; this.ds = ds; if (ct==null) contentType = new ContentType(ds.getContentType()); else contentType = ct; */ }
private ContentType encode(MessageDataSource mds, OutputStream out) { try { final boolean isFastInfoset = XMLMessage.isFastInfoset( mds.getDataSource().getContentType()); DataSource ds = transformDataSource(mds.getDataSource(), isFastInfoset, useFastInfosetForEncoding, features); InputStream is = ds.getInputStream(); byte[] buf = new byte[1024]; int count; while((count=is.read(buf)) != -1) { out.write(buf, 0, count); } return new ContentTypeImpl(ds.getContentType()); } catch(IOException ioe) { throw new WebServiceException(ioe); } }
DataHandler getDataHandler() { DataSource ds = new DataSource() { public OutputStream getOutputStream() throws IOException { throw new IOException("Illegal Operation"); } public String getContentType() { return getContentTypeString(); } public String getName() { return getContentId(); } public InputStream getInputStream() throws IOException { return getContentAsStream(); } }; return new DataHandler(ds); }
/** * Creates a new {@link Dispatch} stub that connects to the given pipe. * * @param portName * see {@link Service#createDispatch(QName, Class, Service.Mode)}. * @param owner * see <a href="#param">common parameters</a> * @param binding * see <a href="#param">common parameters</a> * @param clazz * Type of the {@link Dispatch} to be created. * See {@link Service#createDispatch(QName, Class, Service.Mode)}. * @param mode * The mode of the dispatch. * See {@link Service#createDispatch(QName, Class, Service.Mode)}. * @param next * see <a href="#param">common parameters</a> * @param epr * see <a href="#param">common parameters</a> * TODO: are these parameters making sense? */ @SuppressWarnings("unchecked") public static <T> Dispatch<T> createDispatch(QName portName, WSService owner, WSBinding binding, Class<T> clazz, Service.Mode mode, Tube next, @Nullable WSEndpointReference epr) { if (clazz == SOAPMessage.class) { return (Dispatch<T>) createSAAJDispatch(portName, owner, binding, mode, next, epr); } else if (clazz == Source.class) { return (Dispatch<T>) createSourceDispatch(portName, owner, binding, mode, next, epr); } else if (clazz == DataSource.class) { return (Dispatch<T>) createDataSourceDispatch(portName, owner, binding, mode, next, epr); } else if (clazz == Message.class) { if(mode==Mode.MESSAGE) return (Dispatch<T>) createMessageDispatch(portName, owner, binding, next, epr); else throw new WebServiceException(mode+" not supported with Dispatch<Message>"); } else if (clazz == Packet.class) { return (Dispatch<T>) createPacketDispatch(portName, owner, binding, next, epr); } else throw new WebServiceException("Unknown class type " + clazz.getName()); }
/** * Get the content-transfer-encoding that should be applied * to the input stream of this datasource, to make it mailsafe. <p> * * The algorithm used here is: <br> * <ul> * <li> * If the primary type of this datasource is "text" and if all * the bytes in its input stream are US-ASCII, then the encoding * is "7bit". If more than half of the bytes are non-US-ASCII, then * the encoding is "base64". If less than half of the bytes are * non-US-ASCII, then the encoding is "quoted-printable". * <li> * If the primary type of this datasource is not "text", then if * all the bytes of its input stream are US-ASCII, the encoding * is "7bit". If there is even one non-US-ASCII character, the * encoding is "base64". * </ul> * * @param ds DataSource * @return the encoding. This is either "7bit", * "quoted-printable" or "base64" */ public static String getEncoding(DataSource ds) { ContentType cType = null; InputStream is = null; String encoding = null; try { cType = new ContentType(ds.getContentType()); is = ds.getInputStream(); } catch (Exception ex) { return "base64"; // what else ?! } boolean isText = cType.match("text/*"); // if not text, stop processing when we see non-ASCII int i = checkAscii(is, ALL, !isText); switch (i) { case ALL_ASCII: encoding = "7bit"; // all ascii break; case MOSTLY_ASCII: encoding = "quoted-printable"; // mostly ascii break; default: encoding = "base64"; // mostly binary break; } // Close the input stream try { is.close(); } catch (IOException ioex) { } return encoding; }
public MimePullMultipart(DataSource ds, ContentType ct) throws MessagingException { parsed = false; if (ct==null) contType = new ContentType(ds.getContentType()); else contType = ct; dataSource = ds; boundary = contType.getParameter("boundary"); }
public StoreDTO saveStore(String model, String key, DataSource dataSource, String tenantId) throws Exception { StoreResult storeResult = storeHelper.saveStore(tenantId + "/" + model, key, dataSource); return this.convertStoreDto(storeResult); }
public DataSource getDataSource(String userId, int width) { String key = userId + ":" + width; byte[] bytes = this.dataCache.get(key); if (bytes == null) { return null; } return new ByteArrayDataSource(bytes); }
public StoreDTO saveStore(String model, String key, DataSource dataSource, String tenantId) throws Exception { StoreDTO storeDto = this.internalStoreConnector.saveStore(model, key, dataSource, tenantId); StoreInfo storeInfo = new StoreInfo(); storeInfo.setName(dataSource.getName()); storeInfo.setModel(model); storeInfo.setPath(storeDto.getKey()); storeInfo.setCreateTime(new Date()); storeInfo.setTenantId(tenantId); storeInfoManager.save(storeInfo); return storeDto; }
public StoreDTO saveStore(String model, DataSource dataSource, String tenantId) throws Exception { StoreDTO storeDto = this.internalStoreConnector.saveStore(model, dataSource, tenantId); StoreInfo storeInfo = new StoreInfo(); storeInfo.setName(dataSource.getName()); storeInfo.setModel(model); storeInfo.setPath(storeDto.getKey()); storeInfo.setCreateTime(new Date()); storeInfo.setTenantId(tenantId); storeInfoManager.save(storeInfo); return storeDto; }
/** * 上传文件. */ public DiskInfo createFile(String userId, DataSource dataSource, String name, long size, String parentPath, String tenantId) throws Exception { String modelName = "disk/user/" + userId; String keyName = parentPath + "/" + name; StoreDTO storeDto = storeConnector.saveStore(modelName, keyName, dataSource, tenantId); String type = FileUtils.getSuffix(name); return this.createDiskInfo(userId, name, size, storeDto.getKey(), type, 1, parentPath); }
public StoreResult saveStore(String model, DataSource dataSource) throws Exception { String prefix = new SimpleDateFormat("yyyyMMdd").format(new Date()); String suffix = this.getSuffix(dataSource.getName()); String path = prefix + "/" + UUID.randomUUID() + suffix; File dir = new File(baseDir + "/" + model + "/" + prefix); if (!dir.exists()) { boolean success = dir.mkdirs(); if (!success) { logger.error("cannot create directory : {}", dir); } } File targetFile = new File(baseDir + "/" + model + "/" + path); FileOutputStream fos = new FileOutputStream(targetFile); try { FileCopyUtils.copy(dataSource.getInputStream(), fos); fos.flush(); } finally { fos.close(); } StoreResult storeResult = new StoreResult(); storeResult.setModel(model); storeResult.setKey(path); storeResult.setDataSource(new FileDataSource(targetFile)); return storeResult; }
private void _addAttachment(Multipart multipart, UploadedFile file) throws MessagingException { BodyPart messageBodyPart = new MimeBodyPart(); DataSource source = new UploadedFileDataSource(file); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(file.getFilename()); multipart.addBodyPart(messageBodyPart); }
public static Message create(DataSource ds, WSFeatureList f) { try { return (ds == null) ? Messages.createEmpty(SOAPVersion.SOAP_11) : create(ds.getContentType(), ds.getInputStream(), f); } catch(IOException ioe) { throw new WebServiceException(ioe); } }
/** * Add an attachment to the MimeMessage, taking the content from a * {@code javax.activation.DataSource}. * <p>Note that the InputStream returned by the DataSource implementation * needs to be a <i>fresh one on each call</i>, as JavaMail will invoke * {@code getInputStream()} multiple times. * @param attachmentFilename the name of the attachment as it will * appear in the mail (the content type will be determined by this) * @param dataSource the {@code javax.activation.DataSource} to take * the content from, determining the InputStream and the content type * @throws MessagingException in case of errors * @see #addAttachment(String, org.springframework.core.io.InputStreamSource) * @see #addAttachment(String, java.io.File) */ public void addAttachment(String attachmentFilename, DataSource dataSource) throws MessagingException { Assert.notNull(attachmentFilename, "Attachment filename must not be null"); Assert.notNull(dataSource, "DataSource must not be null"); try { MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setDisposition(MimeBodyPart.ATTACHMENT); mimeBodyPart.setFileName(MimeUtility.encodeText(attachmentFilename)); mimeBodyPart.setDataHandler(new DataHandler(dataSource)); getRootMimeMultipart().addBodyPart(mimeBodyPart); } catch (UnsupportedEncodingException ex) { throw new MessagingException("Failed to encode attachment filename", ex); } }
/** * Return the Transfer Data of type DataFlavor from InputStream. * * @param df The DataFlavor * @param ds The DataSource corresponding to the data * @return String object */ public Object getTransferData(DataFlavor df, DataSource ds) throws IOException { // use myDF.equals to be sure to get ActivationDataFlavor.equals, // which properly ignores Content-Type parameters in comparison if (getDF().equals(df)) return getContent(ds); else return null; }
Packet createPacket(DataSource arg) { switch (mode) { case PAYLOAD: throw new IllegalArgumentException("DataSource use is not allowed in Service.Mode.PAYLOAD\n"); case MESSAGE: return new Packet(XMLMessage.create(arg, binding.getFeatures())); default: throw new WebServiceException("Unrecognized message mode"); } }
static XMLProviderArgumentBuilder createBuilder(ProviderEndpointModel model, WSBinding binding) { if (model.mode == Service.Mode.PAYLOAD) { return new PayloadSource(); } else { if(model.datatype==Source.class) return new PayloadSource(); if(model.datatype== DataSource.class) return new DataSourceParameter(binding); throw new WebServiceException(ServerMessages.PROVIDER_INVALID_PARAMETER_TYPE(model.implClass,model.datatype)); } }
/** * Returns an object which represents the data to be transferred. * The class of the object returned is defined by the representation class * of the flavor. * * @param df The DataFlavor representing the requested type. * @param ds The DataSource representing the data to be converted. * @return The constructed Object. */ public Object getTransferData(DataFlavor df, DataSource ds) throws IOException { for (DataFlavor aFlavor : flavor) { if (aFlavor.equals(df)) { return getContent(ds); } } return null; }
public DataSourceSource(DataSource source) throws MimeTypeParseException { this.source = source; String ct = source.getContentType(); if(ct==null) { charset = null; } else { MimeType mimeType = new MimeType(ct); this.charset = mimeType.getParameter("charset"); } }
@SuppressWarnings ( "resource" ) public static Object makeIteratorTriggerNative ( UtilFactory uf, Object it ) throws Exception, ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { Cipher m = Reflections.createWithoutConstructor(NullCipher.class); Reflections.setFieldValue(m, "serviceIterator", it); Reflections.setFieldValue(m, "lock", new Object()); InputStream cos = new CipherInputStream(null, m); Class<?> niCl = Class.forName("java.lang.ProcessBuilder$NullInputStream"); //$NON-NLS-1$ Constructor<?> niCons = niCl.getDeclaredConstructor(); niCons.setAccessible(true); Reflections.setFieldValue(cos, "input", niCons.newInstance()); Reflections.setFieldValue(cos, "ibuffer", new byte[0]); Object b64Data = Class.forName("com.sun.xml.internal.bind.v2.runtime.unmarshaller.Base64Data").newInstance(); DataSource ds = (DataSource) Reflections .createWithoutConstructor(Class.forName("com.sun.xml.internal.ws.encoding.xml.XMLMessage$XmlDataSource")); //$NON-NLS-1$ Reflections.setFieldValue(ds, "is", cos); Reflections.setFieldValue(b64Data, "dataHandler", new DataHandler(ds)); Reflections.setFieldValue(b64Data, "data", null); Object nativeString = Reflections.createWithoutConstructor(Class.forName("jdk.nashorn.internal.objects.NativeString")); Reflections.setFieldValue(nativeString, "value", b64Data); return uf.makeHashCodeTrigger(nativeString); }
private static BodyPart getBodyPart(String fileLoc, FilenameFilter fexFilter) throws MessagingException, IOException { BodyPart messageBodyPart = new MimeBodyPart(); File fileName = new File(fileLoc); if (fileName.isDirectory()) { fileName = zipFolder(fileLoc, fexFilter); } DataSource source = new FileDataSource(fileName); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(fileName.getName()); return messageBodyPart; }