Mule Zip文件并将压缩文件发送到FTP服务器

编程入门 行业动态 更新时间:2024-10-11 23:26:02
本文介绍了Mule Zip文件并将压缩文件发送到FTP服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我知道Mule非常支持gzip压缩的数据使用元素。然而,客户端现在想要zip压缩,因为该文件必须作为zip压缩文件放在FTP上:(

我遇到以下情况中的困难: p>

我创建了一个Spring bean,其中有一个文件。我想使用ZipOutputStream类压缩这个文件,并将它传递给我们的ftp。

这是我的流程配置:

< flow name =testFlowinitialState =stopped ; < file:inbound-endpoint path =$ {home.dir} / outmoveToDirectory =$ {hip.dir} / out / histfileAge =10000responseTimeout = ref =input/> < component> < spring-object bean =zipCompressor/> < / component> &变量值=#[message.inboundProperties.originalFilename]variableName =originalFilename/> < ftp:outbound-endpoint host =$ {ftp.host}port =$ {ftp.port }user =$ {ftp.username}password =$ {ftp.password}path =$ {ftp.root.out}outputPattern =#[flowVars ['originalFilename']] .zip > < / flow>

这是我的zipCompressor的代码:

@Component public class ZipCompressor implements Callable { private static final Logger LOG = LogManager.getLogger(ZipCompressor.class.getName()); @Override @Transactional public Object onCall(MuleEventContext eventContext)throws Exception { if(eventContext.getMessage()。getPayload()instanceof文件){ final File srcFile =(File)eventContext.getMessage()。getPayload(); final String fileName = srcFile.getName(); final文件zipFile =新文件(fileName +.zip); try { //创建字节缓冲区 byte [] buffer = new byte [1024] FileOutputStream fos = new FileOutputStream(zipFile); ZipOutputStream zos = new ZipOutputStream(fos); FileInputStream fis = new FileInputStream(srcFile); //开始写一个新的ZIP条目,将流定位到条目数据的开始 zos.putNextEntry(new ZipEntry(srcFile.getName())); int length; while((length = fis.read(buffer))> 0){ zos.write(buffer,0,length); } zos.closeEntry(); //关闭InputStream fis.close(); //关闭ZipOutputStream zos.close(); } catch(IOException ioe){ LOG.error(创建zip文件时出错+ ioe); } eventContext.getMessage()。setPayload(zipFile); } return eventContext.getMessage(); } }

我写了一个单元测试和压缩工作。文件确实以正确的名称传输到FTP,但是zip文件无效,并通过在NotePad ++中打开它,它只包含原始文件名。

I认为我在将zip文件传回骡子流时做错了事,但我现在被困住了,所以任何帮助都会非常感激。

解决方案

我已经为此实现了变压器

package com.test.transformer; import java.io.IOException; import java.io.InputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.apachemons.io.IOUtils; import org.apachemons.io.output.ByteArrayOutputStream; import org.mule.api.MuleMessage; import org.mule.api.transformer.TransformerException; import org.mule.transformer.AbstractMessageTransformer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ZipTransformer extends AbstractMessageTransformer { private static final Logger log = LoggerFactory.getLogger(ZipTransformer.class); public static final int DEFAULT_BUFFER_SIZE = 32768; public static byte [] MAGIC = {'P','K',0x3,0x4}; public ZipTransformer() { registerSourceType(InputStream.class); registerSourceType(byte []。class); } public Object transformMessage(MuleMessage message,String outputEncoding) throws TransformerException { Object payload = message.getPayload(); try { byte [] data; if(payload instanceof byte []) { data =(byte [])payload; } else if(payload instanceof InputStream){ data = IOUtils.toByteArray((InputStream)payload); } else if(payload instanceof String) { data =((String)payload).getBytes(outputEncoding); } else { data = muleContext.getObjectSerializer()。serialize(payload); } return compressByteArray(data); } catch(Exception ioex) { throw new TransformerException(this,ioex); } } public Object compressByteArray(byte [] bytes)throws IOException { if(bytes == null || isCompressed(bytes) ) { if(logger.isDebugEnabled()) { logger.debug(Data already compressed; do nothing); } return bytes; } if(logger.isDebugEnabled()) { logger.debug(压缩消息大小:+ bytes.length); } ByteArrayOutputStream baos = null; ZipOutputStream zos = null; try { baos = new ByteArrayOutputStream(DEFAULT_BUFFER_SIZE); zos = new ZipOutputStream(baos); zos.putNextEntry(new ZipEntry(test.txt)); zos.write(bytes,0,bytes.length); zos.finish(); zos.close(); byte [] compressedByteArray = baos.toByteArray(); baos.close(); if(logger.isDebugEnabled()) { logger.debug(Compressed message to size:+ compressedByteArray.length); } return compressedByteArray; } catch(IOException ioex) { throw ioex; } finally { IOUtils.closeQuietly(zos); IOUtils.closeQuietly(baos); } } public boolean isCompressed(byte [] bytes)throws IOException { if((bytes == null)|| .length <4)) { return false; } else { for(int i = 0; i 使用它

< custom-transformer class =com.test.transformer.ZipTransformerdoc:name =文件zip变换器/>

现在将文件名设置为test.txt。您可以更改是使用任何属性或变量。

希望这有助于。

I know Mule has great support for gzip compression of data using the element. However the client now wants zip compression since the file has to be placed on an FTP as a zip compressed file :(

I encounter difficulties in mule with following scenario:

I created a Spring bean where a file comes in. I want to compress this file using the ZipOutputStream class and pass it towards our ftp.

This is my flow configuration:

<flow name="testFlow" initialState="stopped"> <file:inbound-endpoint path="${home.dir}/out" moveToDirectory="${hip.dir}/out/hist" fileAge="10000" responseTimeout="10000" connector-ref="input"/> <component> <spring-object bean="zipCompressor"/> </component> <set-variable value="#[message.inboundProperties.originalFilename]" variableName="originalFilename" /> <ftp:outbound-endpoint host="${ftp.host}" port="${ftp.port}" user="${ftp.username}" password="${ftp.password}" path="${ftp.root.out}" outputPattern="#[flowVars['originalFilename']].zip" /> </flow>

This is the code of my zipCompressor:

@Component public class ZipCompressor implements Callable { private static final Logger LOG = LogManager.getLogger(ZipCompressor.class.getName()); @Override @Transactional public Object onCall(MuleEventContext eventContext) throws Exception { if (eventContext.getMessage().getPayload() instanceof File) { final File srcFile = (File) eventContext.getMessage().getPayload(); final String fileName = srcFile.getName(); final File zipFile = new File(fileName + ".zip"); try { // create byte buffer byte[] buffer = new byte[1024]; FileOutputStream fos = new FileOutputStream(zipFile); ZipOutputStream zos = new ZipOutputStream(fos); FileInputStream fis = new FileInputStream(srcFile); // begin writing a new ZIP entry, positions the stream to the start of the entry data zos.putNextEntry(new ZipEntry(srcFile.getName())); int length; while ((length = fis.read(buffer)) > 0) { zos.write(buffer, 0, length); } zos.closeEntry(); // close the InputStream fis.close(); // close the ZipOutputStream zos.close(); } catch (IOException ioe) { LOG.error("Error creating zip file" + ioe); } eventContext.getMessage().setPayload(zipFile); } return eventContext.getMessage(); } }

I wrote a unit test and the compression works great. A file is indeed transferred to the FTP with the correct name, but the zip file is invalid and by opening it in NotePad++, it contains just the original file name.

I think I'm doing something wrong with passing the zip file back to the mule flow, but I'm stuck at the moment so any help would be greatly appreciated!

解决方案

I have implemented the transformer for this

package com.test.transformer; import java.io.IOException; import java.io.InputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.apachemons.io.IOUtils; import org.apachemons.io.output.ByteArrayOutputStream; import org.mule.api.MuleMessage; import org.mule.api.transformer.TransformerException; import org.mule.transformer.AbstractMessageTransformer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ZipTransformer extends AbstractMessageTransformer { private static final Logger log = LoggerFactory.getLogger(ZipTransformer.class); public static final int DEFAULT_BUFFER_SIZE = 32768; public static byte[] MAGIC = { 'P', 'K', 0x3, 0x4 }; public ZipTransformer() { registerSourceType(InputStream.class); registerSourceType(byte[].class); } public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException { Object payload = message.getPayload(); try{ byte[] data; if (payload instanceof byte[]) { data = (byte[]) payload; } else if (payload instanceof InputStream) { data = IOUtils.toByteArray((InputStream)payload); } else if (payload instanceof String) { data = ((String) payload).getBytes(outputEncoding); } else { data = muleContext.getObjectSerializer().serialize(payload); } return compressByteArray(data); }catch (Exception ioex) { throw new TransformerException(this, ioex); } } public Object compressByteArray(byte[] bytes) throws IOException { if (bytes == null || isCompressed(bytes)) { if (logger.isDebugEnabled()) { logger.debug("Data already compressed; doing nothing"); } return bytes; } if (logger.isDebugEnabled()) { logger.debug("Compressing message of size: " + bytes.length); } ByteArrayOutputStream baos = null; ZipOutputStream zos = null; try { baos = new ByteArrayOutputStream(DEFAULT_BUFFER_SIZE); zos = new ZipOutputStream(baos); zos.putNextEntry(new ZipEntry("test.txt")); zos.write(bytes, 0, bytes.length); zos.finish(); zos.close(); byte[] compressedByteArray = baos.toByteArray(); baos.close(); if (logger.isDebugEnabled()) { logger.debug("Compressed message to size: " + compressedByteArray.length); } return compressedByteArray; } catch (IOException ioex) { throw ioex; } finally { IOUtils.closeQuietly(zos); IOUtils.closeQuietly(baos); } } public boolean isCompressed(byte[] bytes) throws IOException { if ((bytes == null) || (bytes.length < 4 )) { return false; } else { for (int i = 0; i < MAGIC.length; i++) { if (bytes[i] != MAGIC[i]) { return false; } } return true; } } }

Used it as

<custom-transformer class="com.test.transformer.ZipTransformer" doc:name="file zip transformer"/>

As of now sets file name as test.txt. you can change is using any property or variable.

Hope this helps.

更多推荐

Mule Zip文件并将压缩文件发送到FTP服务器

本文发布于:2023-10-10 22:24:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1479919.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:并将   发送到   压缩文件   服务器   文件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!