blob: 7db07739caf956506dacefe96547612ca76c66eb [file] [log] [blame]
Shuyi Chend7955ce2013-05-22 14:51:55 -07001/**
2 * Copyright 2013 Florian Schmaus
3 *
4 * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.jivesoftware.smack.compression;
17
18import java.io.InputStream;
19import java.io.OutputStream;
20import java.lang.reflect.Constructor;
21import java.lang.reflect.InvocationTargetException;
22import java.lang.reflect.Method;
23
24/**
25 * This class provides XMPP "zlib" compression with the help of JZLib. Note that jzlib-1.0.7 must be used (i.e. in the
26 * classpath), newer versions won't work!
27 *
28 * @author Florian Schmaus
29 * @see <a href="http://www.jcraft.com/jzlib/">JZLib</a>
30 *
31 */
32public class JzlibInputOutputStream extends XMPPInputOutputStream {
33
34 private static Class<?> zoClass = null;
35 private static Class<?> ziClass = null;
36
37 static {
38 try {
39 zoClass = Class.forName("com.jcraft.jzlib.ZOutputStream");
40 ziClass = Class.forName("com.jcraft.jzlib.ZInputStream");
41 } catch (ClassNotFoundException e) {
42 }
43 }
44
45 public JzlibInputOutputStream() {
46 compressionMethod = "zlib";
47 }
48
49 @Override
50 public boolean isSupported() {
51 return (zoClass != null && ziClass != null);
52 }
53
54 @Override
55 public InputStream getInputStream(InputStream inputStream) throws SecurityException, NoSuchMethodException,
56 IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException {
57 Constructor<?> constructor = ziClass.getConstructor(InputStream.class);
58 Object in = constructor.newInstance(inputStream);
59
60 Method method = ziClass.getMethod("setFlushMode", Integer.TYPE);
61 method.invoke(in, 2);
62 return (InputStream) in;
63 }
64
65 @Override
66 public OutputStream getOutputStream(OutputStream outputStream) throws SecurityException, NoSuchMethodException,
67 IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {
68 Constructor<?> constructor = zoClass.getConstructor(OutputStream.class, Integer.TYPE);
69 Object out = constructor.newInstance(outputStream, 9);
70
71 Method method = zoClass.getMethod("setFlushMode", Integer.TYPE);
72 method.invoke(out, 2);
73 return (OutputStream) out;
74 }
75}