1 /* 2 * Copyright (C) 2017 The Android Open Source Project 3 * 4 * 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 */ 16 17 package com.android.layout.remote.util; 18 19 import com.android.layout.remote.util.RemoteInputStream.EndOfStreamException; 20 import com.android.tools.layoutlib.annotations.NotNull; 21 22 import java.io.IOException; 23 import java.io.InputStream; 24 import java.rmi.RemoteException; 25 26 public class StreamUtil { 27 /** 28 * Returns a local {@link InputStream} from a {@link RemoteInputStream} 29 */ 30 @NotNull getInputStream(@otNull RemoteInputStream is)31 public static InputStream getInputStream(@NotNull RemoteInputStream is) { 32 return new InputStream() { 33 @Override 34 public int read() throws IOException { 35 return is.read(); 36 } 37 38 @SuppressWarnings("NullableProblems") 39 @Override 40 public int read(byte[] b) throws IOException { 41 return read(b, 0, b.length); 42 } 43 44 @SuppressWarnings("NullableProblems") 45 @Override 46 public int read(byte[] b, int off, int len) throws IOException { 47 try { 48 byte[] read = is.read(off, len); 49 int actualLength = Math.min(len, read.length); 50 System.arraycopy(read, 0, b, off, actualLength); 51 return actualLength; 52 } catch (EndOfStreamException e) { 53 return -1; 54 } 55 } 56 57 @Override 58 public long skip(long n) throws IOException { 59 return is.skip(n); 60 } 61 62 @Override 63 public int available() throws IOException { 64 return is.available(); 65 } 66 67 @Override 68 public void close() throws IOException { 69 is.close(); 70 } 71 72 @Override 73 public synchronized void mark(int readlimit) { 74 try { 75 is.mark(readlimit); 76 } catch (RemoteException e) { 77 throw new RuntimeException(e); 78 } 79 } 80 81 @Override 82 public synchronized void reset() throws IOException { 83 is.reset(); 84 } 85 86 @Override 87 public boolean markSupported() { 88 try { 89 return is.markSupported(); 90 } catch (RemoteException e) { 91 throw new RuntimeException(e); 92 } 93 } 94 }; 95 } 96 } 97