1 17 package org.alfresco.webservice.util; 18 19 import java.io.File ; 20 import java.io.FileOutputStream ; 21 import java.io.IOException ; 22 import java.io.InputStream ; 23 import java.io.OutputStream ; 24 import java.net.URL ; 25 import java.net.URLConnection ; 26 27 import org.alfresco.webservice.content.Content; 28 import org.springframework.util.FileCopyUtils; 29 30 35 public class ContentUtils 36 { 37 public static final int BUFFER_SIZE = 4096; 38 39 46 public static byte[] convertToByteArray(InputStream inputStream) throws Exception 47 { 48 byte[] result = null; 49 50 if (inputStream.available() > 0) 51 { 52 result = new byte[inputStream.available()]; 53 inputStream.read(result);; 54 } 55 56 return result; 57 } 58 59 65 public static String getContentAsString(Content content) 66 { 67 String ticket = AuthenticationUtils.getCurrentTicket(); 69 String strUrl = content.getUrl() + "?ticket=" + ticket; 70 71 StringBuilder readContent = new StringBuilder (); 72 try 73 { 74 URL url = new URL (strUrl); 76 URLConnection conn = url.openConnection(); 77 InputStream is = conn.getInputStream(); 78 int read = is.read(); 79 while (read != -1) 80 { 81 readContent.append((char)read); 82 read = is.read(); 83 } 84 } 85 catch (Exception exception) 86 { 87 throw new WebServiceException("Unable to get content as string.", exception); 88 } 89 90 return readContent.toString(); 92 } 93 94 100 public static InputStream getContentAsInputStream(Content content) 101 { 102 String ticket = AuthenticationUtils.getCurrentTicket(); 104 String strUrl = content.getUrl() + "?ticket=" + ticket; 105 106 try 107 { 108 URL url = new URL (strUrl); 110 URLConnection conn = url.openConnection(); 111 return conn.getInputStream(); 112 } 113 catch (Exception exception) 114 { 115 throw new WebServiceException("Unable to get content as inputStream.", exception); 116 } 117 } 118 119 125 public static void copyContentToFile(Content content, File file) 126 { 127 try 128 { 129 FileOutputStream os = new FileOutputStream (file); 130 FileCopyUtils.copy(getContentAsInputStream(content), os); 131 } 132 catch (IOException exception) 133 { 134 throw new WebServiceException("Unable to copy content into file.", exception); 135 } 136 } 137 138 146 public static int copy(InputStream in, OutputStream out) throws IOException 147 { 148 try 149 { 150 int byteCount = 0; 151 byte[] buffer = new byte[BUFFER_SIZE]; 152 int bytesRead = -1; 153 while ((bytesRead = in.read(buffer)) != -1) 154 { 155 out.write(buffer, 0, bytesRead); 156 byteCount += bytesRead; 157 } 158 out.flush(); 159 return byteCount; 160 } 161 finally 162 { 163 try 164 { 165 in.close(); 166 } 167 catch (IOException ex) 168 { 169 } 171 try 172 { 173 out.close(); 174 } 175 catch (IOException ex) 176 { 177 } 179 } 180 } 181 } 182 | Popular Tags |