Java Code Examples for java.io.FileInputStream

The following are top voted examples for showing how to use java.io.FileInputStream. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: jentrata-msh   File: Zip.java View source code 12 votes vote down vote up
/**
 * Compresses a set of files contained in a directory into a zip file.
 * 
 * @param toFile the zip file.
 * @param dir the directory which contains the files to be compressed.
 * @throws UtilitiesException if there is any error in the compression.
 */
public static void compress(File toFile, File dir)
        throws UtilitiesException {
    try {
        if (dir == null || !dir.exists() || !dir.isDirectory()) {
            throw new UtilitiesException("Invalid input directory: " + dir);
        }

        FileOutputStream fos = new FileOutputStream(toFile);
        ZipOutputStream outs = new ZipOutputStream(fos);

        FileSystem fs = new FileSystem(dir);
        Iterator allFiles = fs.getFiles(true).iterator();

        while (allFiles.hasNext()) {
            File srcFile = (File) allFiles.next();
            String filepath = srcFile.getAbsolutePath();
            String dirpath = dir.getAbsolutePath();
            String entryName = filepath.substring(dirpath.length() + 1)
                    .replace('\\', '/');
            ZipEntry zipEntry = new ZipEntry(entryName);
            zipEntry.setTime(srcFile.lastModified());
            FileInputStream ins = new FileInputStream(srcFile);
            outs.putNextEntry(zipEntry);
            IOHandler.pipe(ins, outs);
            outs.closeEntry();
            ins.close();
        }

        outs.close();

    }
    catch (Exception e) {
        throw new UtilitiesException("Unable to compress zip file: "
                + toFile, e);
    }
}
 
Example 2
Project: my-ministry-assistant   File: FileUtils.java View source code 9 votes vote down vote up
public static void copyFile(File fromFile, File toFile) throws IOException {
	FileInputStream fromFileStream = new FileInputStream(fromFile);
	FileOutputStream toFileStream = new FileOutputStream(toFile);
	FileChannel fromChannel = fromFileStream.getChannel();
	FileChannel toChannel = toFileStream.getChannel();
	try {
		fromChannel.transferTo(0, fromChannel.size(), toChannel);
	} finally {
		if (fromChannel != null)
			fromChannel.close();
		if (toChannel != null)
			toChannel.close();

		fromFileStream.close();
		toFileStream.close();
	}
}
 
Example 3
Project: aws-toolkit-eclipse   File: TestToolManager.java View source code 9 votes vote down vote up
/**
 * Parse a manifest file describing a list of test tool versions.
 *
 * @param file The file to parse.
 * @return The parsed list of versions.
 * @throws IOException on error.
 */
private List<TestToolVersion> parseManifest(final File file)
        throws IOException {

    FileInputStream stream = null;
    try {

        stream = new FileInputStream(file);
        BufferedReader buffer = new BufferedReader(
            new InputStreamReader(stream)
        );

        ManifestContentHandler handler = new ManifestContentHandler();

        XMLReader reader = XMLReaderFactory.createXMLReader();
        reader.setContentHandler(handler);
        reader.setErrorHandler(handler);
        reader.parse(new InputSource(buffer));

        return handler.getResult();

    } catch (SAXException exception) {
        throw new IOException("Error parsing DynamoDB Local manifest file",
                              exception);
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
}
 
Example 4
Project: hacktoolkit-android_lib   File: FileUtils.java View source code 8 votes vote down vote up
public static ArrayList<String> readLines(Activity activity, String filename) throws IOException {
	Context context = activity.getApplicationContext();
	ArrayList<String> lines = new ArrayList<String>();
	try {
		FileInputStream fin = context.openFileInput(filename);
		if (fin != null) {
			InputStreamReader inputStreamReader = new InputStreamReader(fin);
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String line;
			while (( line = bufferedReader.readLine() ) != null) {
				lines.add(line);
			}
			fin.close();
		}
	} catch (FileNotFoundException fnfe) {
		fnfe.printStackTrace();
	}
	return lines;
}
 
Example 5
Project: sslcertx   File: MySQLProtocol.java View source code 7 votes vote down vote up
public MyX509TrustManager(Properties props) throws Exception{
    boolean trustServerCertificate  =  props.getProperty("trustServerCertificate") != null;
    if (trustServerCertificate)
        return;

    serverCertFile =  props.getProperty("serverSslCert");
    InputStream inStream;

    if (serverCertFile.startsWith("-----BEGIN CERTIFICATE-----")) {
        inStream = new ByteArrayInputStream(serverCertFile.getBytes());
    } else if (serverCertFile.startsWith("classpath:")) {
        // Load it from a classpath relative file
        String classpathFile = serverCertFile.substring("classpath:".length());
        inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(classpathFile);
    } else {
        inStream = new FileInputStream(serverCertFile);
    }

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate ca = (X509Certificate) cf.generateCertificate(inStream);
    inStream.close();
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    try {
        // Note: KeyStore requires it be loaded even if you don't load anything into it:
        ks.load(null);
    } catch (Exception e) {

    }
    ks.setCertificateEntry(UUID.randomUUID().toString(), ca);
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    for(TrustManager tm : tmf.getTrustManagers()) {
    	if (tm instanceof X509TrustManager) {
  	        trustManager = (X509TrustManager) tm;
  		    break;
        }
    }
    if (trustManager == null) {
        throw new RuntimeException("No X509TrustManager found");
    }
}
 
Example 6
Project: dlna   File: FileHelper.java View source code 7 votes vote down vote up
private static boolean fileToZip(String baseDirPath, File file, ZipOutputStream out) throws IOException {
    FileInputStream in = null;
    ZipEntry entry = null;

    byte[] buffer = new byte[FILE_BUFFER_SIZE];
    int bytes_read;
    try {
        in = new FileInputStream(file);
        entry = new ZipEntry(getEntryName(baseDirPath, file));
        out.putNextEntry(entry);
        
        while ((bytes_read = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytes_read);
        }
        out.closeEntry();
        in.close();
    } catch (IOException e) {
 	   log.e("Exception, ex: " + e.toString());
 	   return false;
    } finally {
        if (out != null) {
            out.closeEntry();
        }

        if (in != null) {
            in.close();
        }
    }
    return true;
}
 
Example 7
Project: iot-server-appliances   File: AgentConstants.java View source code 6 votes vote down vote up
AgentConstants(){
    InputStream input = null;

    try {

        input = new FileInputStream("agent.properties");
        prop.load(input);

    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
 
Example 8
Project: JAME   File: ChunkedFileInputStream.java View source code 6 votes vote down vote up
/**
 * @see java.io.InputStream#read()
 */
@Override
public int read() throws IOException {
	if (is == null) {
		is = new FileInputStream(new File(path, prefix + chunk + suffix));
	}
	int value = -1;
	if (is != null) {
		value = is.read();
		length += 1;
		if ((length % chunkLength) == 0) {
			chunk += 1;
			is.close();
			is = null;
		}
	}
	return value;
}
 
Example 9
Project: jbosgi   File: ModuleIdentityRepositoryIntegration.java View source code 6 votes vote down vote up
@Override
public OSGiMetaData getOSGiMetaData(XResource resource) throws IOException {

    OSGiMetaData result = null;

    // Check for a jbosgi-xservice.properties in the root of a module directory under $JBOSS_HOME/modules/system/layers/base
    ModuleIdentifier moduleId = getModuleIdentifier(resource);
    Path basePath = FileSystems.getDefault().getPath(modulesDir.getAbsolutePath(), "system", "layers", "base");
    String identifierPath = moduleId.getName().replace('.', File.separatorChar) + File.separator + moduleId.getSlot();
    File entryFile = FileSystems.getDefault().getPath(basePath.toString(), identifierPath, "jbosgi-xservice.properties").toFile();
    if (entryFile.exists()) {
        try {
            FileInputStream input = new FileInputStream(entryFile);
            try {
                Properties props = new Properties();
                props.load(input);
                result = OSGiMetaDataBuilder.load(props);
            } finally {
                input.close();
            }
        } catch (IOException ex) {
            LOGGER.debugf("Cannot load OSGi metadata from: %s", entryFile);
        }
    }

    // Use the original metadata from the manifest
    if (result == null) {
        result = getOSGiMetaDataFromManifest(resource);
    }

    // Generate the OSGiMetaData by scanning the module
    if (result == null) {
        Module module = loadModule(moduleId);
        result = getOSGiMetaDataFromModule(module);
    }

    return result;
}
 
Example 10
Project: speechalyzer   File: Util.java View source code 6 votes vote down vote up
/**
 * <pre>
 * file 1 in 2 kopieren.
 * </pre>
 * 
 * @param in
 * @param out
 * @throws Exception
 */
public static void copyFile(File in, File out) throws Exception {
	FileInputStream fis = new FileInputStream(in);
	FileOutputStream fos = new FileOutputStream(out);
	byte[] buf = new byte[1024];
	int i = 0;
	while ((i = fis.read(buf)) != -1) {
		fos.write(buf, 0, i);
	}
	fis.close();
	fos.close();
}
 
Example 11
Project: richfaces   File: ImageLoader.java View source code 6 votes vote down vote up
private void paintImageToBrowser(OutputStream out, File imageResource) throws IOException {

        if (imageResource != null && imageResource.exists()) {

            byte[] toWrite = new byte[Constants.DEFAULT_BUFFER_SIZE];

            FileInputStream in = new FileInputStream(imageResource);

            try {
                while (in.read(toWrite) != -1) {
                    out.write(toWrite);
                }
            } finally {
                in.close();
            }

        } else {
            String suffix = excludeFilePrefix(imageResource.getPath());
            paintImage(out, fileManager.transformPath(Constants.DEFAULT_ORIGINAL_PICTURE, suffix));
            return;
        }
    }
 
Example 12
Project: javalang   File: JavaParser.java View source code 6 votes vote down vote up
/**
 * Parses the Java code contained in a [email protected] File} and returns a
 * [email protected] CompilationUnit} that represents it.
 * 
 * @param file
 *            [email protected] File} containing Java source code
 * @param encoding
 *            encoding of the source code
 * @return CompilationUnit representing the Java source code
 * @throws ParseException
 *             if the source code has parser errors
 * @throws IOException
 */
public static CompilationUnit parse(File file, String encoding)
		throws ParseException, IOException {
	FileInputStream in = new FileInputStream(file);
	try {
		return parse(in, encoding);
	} finally {
		in.close();
	}
}
 
Example 13
Project: jena   File: StAX2ModelTest.java View source code 6 votes vote down vote up
@Override
public void runTest() throws Exception {
    Model expected = ModelFactory.createDefaultModel();
    Model got = ModelFactory.createDefaultModel();
    
    InputStream in;
    
    // Load expected using normal mechanism
    try {
        in = new FileInputStream(file);
        expected.read(in, base);
        in.close();
    } catch (Exception e) { return; }

    in = new FileInputStream(file);
    XMLEventReader eventStream = inputFactory.createXMLEventReader(base, in);
    StAX2Model.read(eventStream, got, base);
    in.close();
    
    boolean result = expected.isIsomorphicWith(got);
    
    /*if (!result) {
        System.err.println("\n\n==== Expected ====");
        expected.write(System.err, "TTL");
        System.err.println("\n\n==== Got ====");
        got.write(System.err, "TTL");
    }*/
            
    assertTrue(file + " matches", result);
}
 
Example 14
Project: aws-toolkit-eclipse   File: RemoteCommandUtils.java View source code 6 votes vote down vote up
/**
 * Writes the contents of the specified file to the specified output stream.
 *
 * @param localFile
 *            The file to write to the output stream.
 * @param out
 *            The output stream to write to.
 *
 * @throws FileNotFoundException
 * @throws IOException
 *             If any problems writing the file contents.
 */
private void sendFileData(String localFile, OutputStream out)
        throws FileNotFoundException, IOException {
    FileInputStream fis = new FileInputStream(localFile);

    try {
        byte[] buf = new byte[1024];
        while (true) {
            int len = fis.read(buf, 0, buf.length);
            if (len <= 0)
                break;
            out.write(buf, 0, len);
        }
    } finally {
        fis.close();
    }

    out.write('\0');
    out.flush();
}
 
Example 15
Project: dlna   File: FileHelper.java View source code 6 votes vote down vote up
public static byte[] readGZipFile (String zipFileName) {
	if (fileIsExist(zipFileName)) {
		log.i("zipFileName: " + zipFileName);
		try {
			FileInputStream fin = new FileInputStream(zipFileName);
			int size;
			byte[] buffer = new byte[1024];
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			while ((size = fin.read(buffer, 0, buffer.length)) != -1) {
				baos.write(buffer, 0, size);
			}
			return baos.toByteArray();
		} catch (Exception ex) {
			log.i("read zipRecorder file error");
		}
	}
	return null;
}
 
Example 16
Project: nfc-smime   File: MainActivity.java View source code 6 votes vote down vote up
private static byte[] readFile(String filename) throws Exception {
    File f = new File(Environment.getExternalStorageDirectory(), filename);
    byte[] result = new byte[(int) f.length()];
    FileInputStream in = new FileInputStream(f);
    in.read(result);
    in.close();

    return result;
}
 
Example 17
Project: redu-android   File: ScribeHttpClient.java View source code 6 votes vote down vote up
public byte[] read(File file) throws IOException {

		/*
		 * if ( file.length() > MAX_FILE_SIZE ) { throw new
		 * FileTooBigException(file); }
		 */

		byte[] buffer = new byte[(int) file.length()];
		InputStream ios = null;
		try {
			ios = new FileInputStream(file);
			if (ios.read(buffer) == -1) {
				throw new IOException("EOF reached while trying to read the whole file");
			}
		} finally {
			try {
				if (ios != null)
					ios.close();
			} catch (IOException e) {
			}
		}

		return buffer;
	}
 
Example 18
Project: Todayinformation   File: FileUtils.java View source code 6 votes vote down vote up
/**
 * encodeBase64File:(?????base64 ???).
 * 
 * @param path
 *            ????
 * @return
 * @throws Exception
 */

public static String encodeBase64File(String path) throws Exception {
	File file = new File(path);
	FileInputStream inputFile = new FileInputStream(file);
	byte[] buffer = new byte[(int) file.length()];
	inputFile.read(buffer);
	inputFile.close();
	return Base64.encodeToString(buffer, Base64.DEFAULT);
}
 
Example 19
Project: ndogen_stalled   File: FileUtils.java View source code 6 votes vote down vote up
public static String readFile(String file) throws IOException {
	int len = (int) (new File(file)).length();
	FileInputStream fis = new FileInputStream(file);
	byte buf[] = new byte[len];
	fis.read(buf);
	fis.close();

	return new String(buf);
}
 
Example 20
Project: eclipse-commons   File: StutterRead.java View source code 6 votes vote down vote up
public boolean execute( HttpServletRequest request, HttpServletResponse response, Map<Object, Object> ctx )
    throws Exception
{
    boolean handled = false;

    int code = 200;
    if ( !fs( request.getPathInfo() ).exists() )
    {
        code = 404;
    }
    if ( "HEAD".equals( request.getMethod() ) )
    {
        handled = true;
    }
    else if ( "GET".equals( request.getMethod() ) )
    {
        handled = true;
        if ( fs( request.getPathInfo() ).canRead() )
        {
            FileInputStream in = null;
            try
            {
                in = new FileInputStream( fs( request.getPathInfo() ) );
                ServletOutputStream out = response.getOutputStream();
                int b = -1;
                while ( ( b = in.read() ) != -1 )
                {
                    out.write( b );
                    Thread.sleep( pause );
                }
            }

            finally
            {
                if ( in != null )
                {
                    in.close();
                }
            }
        }

    }

    if ( handled )
    {
        response.setStatus( code );
    }

    return !handled;
}
 
Example 21
Project: fiji   File: LSS16_Reader.java View source code 6 votes vote down vote up
public static int readIntLE(FileInputStream in) throws IOException {
	byte[] buffer = new byte[4];
	in.read(buffer);
	return (buffer[3] & 0xff) << 24 |
		(buffer[2] & 0xff) << 16 |
		(buffer[1] & 0xff) << 8 |
		(buffer[0] & 0xff);
}
 
Example 22
Project: android-simple-storage   File: AbstractDiskStorage.java View source code 6 votes vote down vote up
@Override
public void copy(File file, String directoryName, String fileName) {
	if (!file.isFile()) {
		return;
	}
	
	FileInputStream inStream = null;
	FileOutputStream outStream = null;
	try {
		inStream = new FileInputStream(file);
		outStream = new FileOutputStream(new File(buildPath(directoryName, fileName)));
		FileChannel inChannel = inStream.getChannel();
		FileChannel outChannel = outStream.getChannel();
		inChannel.transferTo(0, inChannel.size(), outChannel);
	} catch (Exception e) {
		throw new StorageException(e);
	} finally {
		closeQuietly(inStream);
		closeQuietly(outStream);
	}
}
 
Example 23
Project: afwall   File: MultiProfilePreferenceFragment.java View source code 6 votes vote down vote up
public void copy(File src, File dst) throws IOException {
	FileInputStream inStream = new FileInputStream(src);
	FileOutputStream outStream = new FileOutputStream(dst);
	FileChannel inChannel = inStream.getChannel();
	FileChannel outChannel = outStream.getChannel();
	inChannel.transferTo(0, inChannel.size(), outChannel);
	inStream.close();
	outStream.close();
}
 
Example 24
Project: eclipse-integration-commons   File: FileUtil.java View source code 6 votes vote down vote up
public static void copy(File source, File target) throws IOException {
	FileInputStream sourceOutStream = new FileInputStream(source);
	FileOutputStream targetOutStream = new FileOutputStream(target);
	FileChannel sourceChannel = sourceOutStream.getChannel();
	FileChannel targetChannel = targetOutStream.getChannel();
	sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);
	sourceChannel.close();
	targetChannel.close();
	sourceOutStream.close();
	targetOutStream.close();
}
 
Example 25
Project: daap   File: DaapAudioResponseNIO.java View source code 6 votes vote down vote up
/** Creates a new instance of DaapAudioResponse */
public DaapAudioResponseNIO(DaapRequest request, Song song,
        FileInputStream in, long pos, long end) {
    super(request, song, in, pos, end);

    headerBuffer = ByteBuffer.wrap(header);
    this.connection = (DaapConnectionNIO) request.getConnection();

    fileChannel = in.getChannel();
}
 
Example 26
Project: OSM2World   File: SRTMTile.java View source code 6 votes vote down vote up
private static ShortBuffer loadDataFromFile(File file) throws IOException {

		FileInputStream fis = new FileInputStream(file);
		FileChannel fc = fis.getChannel();
		ByteBuffer bb = ByteBuffer.allocateDirect((int) fc.size());
		while (bb.remaining() > 0) fc.read(bb);
		fc.close();
		fis.close();
		
		bb.flip();
		
		// choose the right endianness
		return bb.order(ByteOrder.BIG_ENDIAN).asShortBuffer();
		
	}
 
Example 27
Project: android-platform-tools-base   File: ByteBufferUtil.java View source code 6 votes vote down vote up
@NonNull
public static ByteBuffer mapFile(@NonNull File f, long offset, @NonNull ByteOrder byteOrder) throws IOException {
  FileInputStream dataFile = new FileInputStream(f);
  try {
    FileChannel fc = dataFile.getChannel();
    MappedByteBuffer buffer = fc.map(FileChannel.MapMode.READ_ONLY, offset, f.length() - offset);
    buffer.order(byteOrder);
    return buffer;
  } finally {
    dataFile.close(); // this *also* closes the associated channel, fc
  }
}
 
Example 28
Project: hank   File: CueballStreamBuffer.java View source code 6 votes vote down vote up
public CueballStreamBuffer(String filePath,
                           int relativeIndex,
                           int keyHashSize,
                           int valueSize,
                           int hashIndexBits,
                           CueballCompressionCodec compressionCodec)
    throws IOException {
  this.relativeIndex = relativeIndex;
  this.compressionCodec = compressionCodec;
  FileInputStream fileInputStream = new FileInputStream(filePath);
  this.stream = new BufferedInputStream(fileInputStream, IOStreamUtils.DEFAULT_BUFFER_SIZE);

  this.keyHashSize = keyHashSize;
  this.fullRecordSize = valueSize + keyHashSize;

  Footer footer = new Footer(fileInputStream.getChannel(), hashIndexBits);
  dataLength = footer.getDataLength();
  hashIndex = footer.getHashIndex();
  uncompressedBuffer = new byte[footer.getMaxUncompressedBufferSize()];
  compressedBuffer = new byte[footer.getMaxCompressedBufferSize()];
}
 
Example 29
Project: jaamsim   File: DecoderTester.java View source code 6 votes vote down vote up
public static void main(String[] args) {
	try {
		Decoder dec = new Decoder();

		File f = new File(args[0]);
		FileInputStream inStream = new FileInputStream(f);
		FileChannel fc = inStream.getChannel();
		ByteBuffer frame = ByteBuffer.allocate((int)fc.size());
		fc.read(frame);
		frame.flip();

		dec.decodeFrame(frame);

		dec.currentFrame.show(1, true, "");

		inStream.close();

	} catch (Throwable t) {
		t.printStackTrace();
		throw new RuntimeException(t);
	}
}
 
Example 30
Project: friendica-for-android   File: Max.java View source code 6 votes vote down vote up
public static String readFile(String path) throws IOException {
	FileInputStream stream = new FileInputStream(new File(path));
	try {
		FileChannel fc = stream.getChannel();
		MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
		/* Instead of using default, pass in a decoder. */
		return Charset.defaultCharset().decode(bb).toString();
	}
	finally {
		stream.close();
	}
}
 
Example 31
Project: Java-Device-Detection   File: SourceFile.java View source code 6 votes vote down vote up
/**
 * Constructs a new instance of FileHandle connected to the file
 * provided.
 * @param file to create the handle from
 * @throws FileNotFoundException
 * @throws IOException 
 */
FileHandle(File file) throws FileNotFoundException, IOException {
    fileInputStream = new FileInputStream(file);
    channel = fileInputStream.getChannel();
    byteBuffer = channel.map(
            FileChannel.MapMode.READ_ONLY,
            0,
            channel.size());
    byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
}
 
Example 32
Project: Field-Book   File: DataHelper.java View source code 6 votes vote down vote up
/**
 * Helper function to copy database
 */
public static void copyFileCall(FileInputStream fromFile, FileOutputStream toFile) throws IOException {
    FileChannel fromChannel = null;
    FileChannel toChannel = null;

    try {
        fromChannel = fromFile.getChannel();
        toChannel = toFile.getChannel();
        fromChannel.transferTo(0, fromChannel.size(), toChannel);
    } finally {
        try {
            if (fromChannel != null) {
                fromChannel.close();
            }
        } finally {
            if (toChannel != null) {
                toChannel.close();
            }
        }
    }
}
 
Example 33
Project: ambrose   File: JSONUtil.java View source code 6 votes vote down vote up
public static String readFile(String path) throws IOException {
  FileInputStream stream = new FileInputStream(new File(path));
  try {
    FileChannel fc = stream.getChannel();
    MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
    return Charset.defaultCharset().decode(bb).toString();
  } finally {
    stream.close();
  }
}
 
Example 34
Project: dataverse   File: FileAccessIO.java View source code 6 votes vote down vote up
@Override
public Channel openAuxChannel(String auxItemTag, DataAccessOption... options) throws IOException {

    Path auxPath = getAuxFilePath(auxItemTag);

    if (isWriteAccessRequested(options)) {
        FileOutputStream auxOut = new FileOutputStream(auxPath.toFile());

        if (auxOut == null) {
            throw new IOException("Failed to open Auxiliary File " + this.getDataFile().getStorageIdentifier() + "." + auxItemTag + " for writing.");
        }

        return auxOut.getChannel();
    }
    
    // Read access requested.
    // Check if this Aux object is cached; and if so, open for reading:

    if (!auxPath.toFile().exists()) {
        throw new FileNotFoundException("Auxiliary File " + this.getDataFile().getStorageIdentifier() + "." + auxItemTag + " does not exist.");
    }

    FileInputStream auxIn = new FileInputStream(auxPath.toFile());

    if (auxIn == null) {
        throw new IOException("Failed to open Auxiliary File " + this.getDataFile().getStorageIdentifier() + "." + auxItemTag + " for reading");
    }

    return auxIn.getChannel();

}
 
Example 35
Project: Hungry   File: FileUtils.java View source code 6 votes vote down vote up
/**
 * Internal copy file method.
 * 
 * @param srcFile  the validated source file, must not be <code>null</code>
 * @param destFile  the validated destination file, must not be <code>null</code>
 * @param preserveFileDate  whether to preserve the file date
 * @throws IOException if an error occurs
 */
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {
    if (destFile.exists() && destFile.isDirectory()) {
        throw new IOException("Destination '" + destFile + "' exists but is a directory");
    }

    FileInputStream fis = null;
    FileOutputStream fos = null;
    FileChannel input = null;
    FileChannel output = null;
    try {
        fis = new FileInputStream(srcFile);
        fos = new FileOutputStream(destFile);
        input  = fis.getChannel();
        output = fos.getChannel();
        long size = input.size();
        long pos = 0;
        long count = 0;
        while (pos < size) {
            count = (size - pos) > FIFTY_MB ? FIFTY_MB : (size - pos);
            pos += output.transferFrom(input, pos, count);
        }
    } finally {
        IOUtils.closeQuietly(output);
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(fis);
    }

    if (srcFile.length() != destFile.length()) {
        throw new IOException("Failed to copy full contents from '" +
                srcFile + "' to '" + destFile + "'");
    }
    if (preserveFileDate) {
        destFile.setLastModified(srcFile.lastModified());
    }
}
 
Example 36
Project: TweetTopics2.0   File: FileUtils.java View source code 6 votes vote down vote up
public static void copy(String source, String destiny) throws IOException {
    try
    {
        FileInputStream fis = new FileInputStream(source);
        FileOutputStream fos = new FileOutputStream(destiny);
        FileChannel channelSource = fis.getChannel();
        FileChannel channelDestiny = fos.getChannel();
        channelSource.transferTo(0, channelSource.size(), channelDestiny);
        fis.close();
        fos.close();
    }
    catch(Exception e)
    {
        Log.d(Utils.TAG, e.getClass().getName());
    }
}
 
Example 37
Project: netty3.9-note   File: AbstractMemoryHttpData.java View source code 6 votes vote down vote up
public void setContent(File file) throws IOException {
    if (file == null) {
        throw new NullPointerException("file");
    }
    long newsize = file.length();
    if (newsize > Integer.MAX_VALUE) {
        throw new IllegalArgumentException(
                "File too big to be loaded in memory");
    }
    checkSize(newsize);
    FileInputStream inputStream = new FileInputStream(file);
    FileChannel fileChannel = inputStream.getChannel();
    byte[] array = new byte[(int) newsize];
    ByteBuffer byteBuffer = ByteBuffer.wrap(array);
    int read = 0;
    while (read < newsize) {
        read += fileChannel.read(byteBuffer);
    }
    fileChannel.close();
    inputStream.close();
    byteBuffer.flip();
    channelBuffer = ChannelBuffers.wrappedBuffer(byteBuffer);
    size = newsize;
    completed = true;
}
 
Example 38
Project: FrameCode   File: FileUtil.java View source code 6 votes vote down vote up
public byte[] readFileFromSys(String fileName) throws IOException {
    byte[] buffer = null;
    try {
        FileInputStream fin = mContext.openFileInput(fileName);
        int length = fin.available();
        buffer = new byte[length];
        fin.read(buffer);
        fin.close();
        return buffer;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;

}
 
Example 39
Project: codemap   File: Project.java View source code 6 votes vote down vote up
public static Project readProject(String name, Context context)
		throws IOException {
	FileInputStream fis = context.openFileInput(getFilename(name));
	byte[] serializedObject = new byte[fis.available()];
	fis.read(serializedObject);
	fis.close();

	Project result = (Project) Utils.deserializeObject(serializedObject);
	return result;
}
 
Example 40
Project: NewsSpeakServer   File: CharacterTranslationTest.java View source code 6 votes vote down vote up
public synchronized Class loadClass (String className, boolean resolveIt)
    throws
        ClassNotFoundException
{
    byte data[];
    FileInputStream in;
    Class ret;
    
    try
    {
        // try system class loader
        ret = super.findSystemClass (className);
    }
    catch (ClassNotFoundException e)
    {
        try
        {
            in = new FileInputStream (mRoot + className + ".class");
            data = new byte[in.available ()];
            in.read (data);
            in.close ();
            ret = defineClass (className, data, 0, data.length);
            if (null == ret)
                throw new ClassFormatError ();
            if (resolveIt)
                resolveClass (ret);
        }
        catch (IOException ioe)
        {
            throw new ClassNotFoundException ();
        }
    }
    
    return (ret);
}
 
Example 41
Project: eclipse-license-management-tools   File: Utils.java View source code 6 votes vote down vote up
public static byte[] readFile(String fileName) throws IOException {
	FileInputStream in = new FileInputStream(fileName);
	byte[] bytes = new byte[in.available()];
	in.read(bytes);

	in.close();

	return bytes;
}
 
Example 42
Project: tuberun_android   File: TubeMapContentProvider.java View source code 6 votes vote down vote up
@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		try {
			Context context=getContext();
			FileInputStream fis=context.openFileInput(FILENAME);
			byte[] buffer = new byte[1024];
			byte[] fullFile = new byte[fis.available()];
			int bufferLength = 0; // used to store a temporary size of the
//									// buffer
			int i=0;
			while ((bufferLength = fis.read(buffer)) > 0) {
				int k=0;
				for (int j=i;j<i+bufferLength;j++) {
					fullFile[j]=buffer[k++];
				}
				i+=bufferLength;
			}
			MatrixCursor res=new MatrixCursor(new String[]{"map"});
			res.addRow(new Object[]{fullFile});
			return res;
		
		}
		catch (Exception e) {
			Log.w("MapProvider",e);
		}
		return null;
		
	}
 
Example 43
Project: friendica-for-android   File: TwAjax.java View source code 6 votes vote down vote up
public void writeToStream(DataOutputStream outputStream, String boundary) throws IOException {
	outputStream.writeBytes("--" + boundary + "\r\n");
	outputStream.writeBytes("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + remoteFilename +"\"" + "\r\n");
	outputStream.writeBytes("\r\n");

	FileInputStream fileInputStream = new FileInputStream(file);
	int bytesAvailable = fileInputStream.available();
	int bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE);
	byte[] buffer = new byte[bufferSize];

	int bytesRead = fileInputStream.read(buffer, 0, bufferSize); // Read file

	while (bytesRead > 0) {
		outputStream.write(buffer, 0, bufferSize);
		bytesAvailable = fileInputStream.available();
		bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE);
		bytesRead = fileInputStream.read(buffer, 0, bufferSize);
	}

	outputStream.writeBytes("\r\n");
	fileInputStream.close();
}
 
Example 44
Project: vmrc   File: VMIDescriptor.java View source code 6 votes vote down vote up
private String loadFromFile(String textFilePath) throws IOException {
	String result;

	FileInputStream fis = new FileInputStream(textFilePath);
	byte[] b = new byte[fis.available()];
	fis.read(b);
	fis.close();
	result = new String(b);

	return result;
}
 
Example 45
Project: jSLP   File: SLPConfiguration.java View source code 6 votes vote down vote up
/**
 * get the public key for a certain SPI.
 * 
 * @param spi
 *            the SPI.
 * @return the location of the public key.
 * @throws IOException
 * @throws GeneralSecurityException
 */
PublicKey getPublicKey(final String spi) throws IOException,
		GeneralSecurityException {
	PublicKey key = (PublicKey) PUBLIC_KEY_CACHE.get(spi);
	if (key != null) {
		return key;
	}
	FileInputStream keyfis = new FileInputStream(System
			.getProperty(PUBLIC_KEY_PROP + spi));
	byte[] encKey = new byte[keyfis.available()];
	keyfis.read(encKey);
	keyfis.close();
	X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encKey);
	KeyFactory keyFactory = KeyFactory.getInstance("DSA");
	key = keyFactory.generatePublic(pubKeySpec);
	PUBLIC_KEY_CACHE.put(spi, key);
	return key;
}
 
Example 46
Project: TestingStaff   File: EpubManipulator.java View source code 6 votes vote down vote up
private String readPage(String path) {
	try {
		FileInputStream input = new FileInputStream(path);
		byte[] fileData = new byte[input.available()];

		input.read(fileData);
		input.close();

		String xhtml = new String(fileData);
		return xhtml;
	} catch (IOException e) {
		return "";
	}
}
 
Example 47
Project: CReader   File: FileUtil.java View source code 6 votes vote down vote up
public long getFileSizes(File f) throws Exception {// ???
	long s = 0;
	if (f.exists()) {
		FileInputStream fis = null;
		fis = new FileInputStream(f);
		s = fis.available();
		fis.close();
	} else {
		f.createNewFile();
		System.out.println("?");
	}
	return s;
}
 
Example 48
Project: roboyuddh   File: JarCreator.java View source code 6 votes vote down vote up
private static void copy(File inFile, JarOutputStream out) throws IOException {
	FileInputStream in = null;

	try {
		in = new FileInputStream(inFile);
		final byte[] buf = new byte[4096];

		while (in.available() > 0) {
			int count = in.read(buf, 0, 4096);

			out.write(buf, 0, count);
		}
	} finally {
		FileUtil.cleanupStream(in);
	}
}
 
Example 49
Project: openmap   File: FileListener.java View source code 6 votes vote down vote up
/**
 * Reverse the input and send it back to the client.
 */
public void httpRequest(HttpRequestEvent e) throws IOException {
    String filename = e.getRequest().substring(1);
    if (Debug.debugging("http")) {
        Debug.output("FileListener: Looking for file " + filename);
    }

    FileInputStream requestedfile;
    try {
        requestedfile = new FileInputStream(filename);
    } catch (java.io.FileNotFoundException exception) {
        Debug.error("FileListener: Unable to find file " + filename);
        return;
        // Need a return value here
    }

    // Read in the file's bytes. This doesn't seem super efficient
    int bytes = requestedfile.available();
    byte[] b = new byte[bytes];
    int bytes_read = requestedfile.read(b);
    if (bytes_read != bytes) {
        Debug.error("FileListener: Did not read the correct number of bytes for "
                + filename);
    }
    // and write out the raw bytes
    e.getWriter().write(new String(b));
}
 
Example 50
Project: SRE-RoboCode   File: JarCreator.java View source code 6 votes vote down vote up
private static void copy(File inFile, JarOutputStream out) throws IOException {
	FileInputStream in = null;

	try {
		in = new FileInputStream(inFile);
		final byte[] buf = new byte[4096];

		while (in.available() > 0) {
			int count = in.read(buf, 0, 4096);

			out.write(buf, 0, count);
		}
	} finally {
		FileUtil.cleanupStream(in);
	}
}
 
Example 51
Project: FireflowEngine20   File: FileReaderImpl.java View source code 6 votes vote down vote up
private byte[] readFile(File f){
	try{
        int byteread = 0;
        int totalRead = 0;
        FileInputStream fIn = new FileInputStream(f);
        byte[] content = new byte[fIn.available()];
        int offset = 0;
        int numRead = 0;
        while (offset < content.length
               && (numRead=fIn.read(content, offset, content.length-offset)) >= 0) {
            offset += numRead;
        }

        // Ensure all the bytes have been read in
        if (offset < content.length) {
            throw new IOException("Could not completely read file "+f.getName());
        }

        fIn.close();
		return content;
	}catch(IOException e){
		log.error(e);
		return null;
	}

}
 
Example 52
Project: RoboCode-Robots   File: JarCreator.java View source code 6 votes vote down vote up
private static void copy(File inFile, JarOutputStream out) throws IOException {
	FileInputStream in = null;

	try {
		in = new FileInputStream(inFile);
		final byte[] buf = new byte[4096];

		while (in.available() > 0) {
			int count = in.read(buf, 0, 4096);

			out.write(buf, 0, count);
		}
	} finally {
		FileUtil.cleanupStream(in);
	}
}
 
Example 53
Project: andlytics   File: FileUtils.java View source code 6 votes vote down vote up
public static String readFileAsString(String filename) {
	FileInputStream in = null;
	try {
		in = new FileInputStream(filename);
		byte[] data = new byte[in.available()];
		in.read(data);

		return new String(data, "UTF-8");
	} catch (IOException e) {
		throw new RuntimeException(e);
	} finally {
		if (in != null) {
			FileUtils.closeSilently(in);
		}
	}
}
 
Example 54
Project: fiji   File: SPIMExperiment.java View source code 6 votes vote down vote up
public static ImageProcessor openRaw(String path, int orgW, int orgH, int xMin, int xMax, int yMin, int yMax) {
	if(xMin == 0 && xMax == orgW - 1 && yMin == 0 && yMax == orgH - 1)
		return openRaw(path, orgW, orgH);
	int ws = xMax - xMin + 1;
	int hs = yMax - yMin + 1;

	byte[] bytes = new byte[ws * hs * 2];
	short[] pixels = new short[ws * hs];

	FileInputStream in = null;
	try {
		in = new FileInputStream(path);

		// skip the top
		int toSkip = 2 * (yMin * orgW + xMin);
		while(toSkip > 0)
			toSkip -= in.skip(toSkip);

		// read through it line by line
		int offs = 0;
		for(int r = 0; r < hs; r++) {
			// read the data
			int read = 0;
			while(read < ws)
				read += in.read(bytes, offs + read, 2 * ws - read);
			offs += 2 * ws;

			// skip to next line
			toSkip = 2 * (orgW - xMax - 1 + xMin);
			while(toSkip > 0)
				toSkip -= in.skip(toSkip);
		}
		in.close();
	} catch(IOException e) {
		throw new RuntimeException("Cannot load " + path, e);
	}

	for(int i = 0; i < pixels.length; i++) {
		int low  = 0xff & bytes[2 * i];
		int high = 0xff & bytes[2 * i + 1];
		pixels[i] = (short)((high << 8) | low);
	}

	return new ShortProcessor(ws, hs, pixels, null);
}
 
Example 55
Project: daap   File: ContentCodesAnalyzer.java View source code 6 votes vote down vote up
private static HashMap readNewChunks(File file) throws IOException {
    HashMap map = new HashMap();

    FileInputStream in = new FileInputStream(file);

    try {
        in.skip(0x14); // skip header
        in.skip(0x04); // skip 'mdcl'

        byte[] lenBuf = new byte[4];

        while (in.read(lenBuf, 0, lenBuf.length) != -1) {
            int len = ByteUtil.toIntBE(lenBuf, 0);
            byte[] buf = new byte[len];
            if (in.read(buf, 0, buf.length) == -1)
                break;

            int pos = 0;

            pos += 4; // skip 'mcnm'
            len = ByteUtil.toIntBE(buf, pos);
            pos += 4;
            String contentCode = new String(buf, pos, len);
            pos += len;

            pos += 4; // skip 'mcna'
            len = ByteUtil.toIntBE(buf, pos);
            pos += 4;
            String name = new String(buf, pos, len);
            pos += len;

            pos += 4; // skip 'mcty'
            len = ByteUtil.toIntBE(buf, pos);
            pos += 4;
            int type = ByteUtil.toInt16BE(buf, pos);
            pos += len;

            map.put(contentCode, new ContentCode(contentCode, name, type));

            in.skip(0x04); // skip 'mdcl' of the next chunk
        }

    } finally {
        in.close();
    }

    return map;
}
 
Example 56
Project: hadoop_ekg   File: TaskLog.java View source code 6 votes vote down vote up
/**
 * Read a log file from start to end positions. The offsets may be negative,
 * in which case they are relative to the end of the file. For example,
 * Reader(taskid, kind, 0, -1) is the entire file and 
 * Reader(taskid, kind, -4197, -1) is the last 4196 bytes. 
 * @param taskid the id of the task to read the log file for
 * @param kind the kind of log to read
 * @param start the offset to read from (negative is relative to tail)
 * @param end the offset to read upto (negative is relative to tail)
 * @param isCleanup whether the attempt is cleanup attempt or not
 * @throws IOException
 */
public Reader(TaskAttemptID taskid, LogName kind, 
              long start, long end, boolean isCleanup) throws IOException {
  // find the right log file
  LogFileDetail fileDetail = getLogFileDetail(taskid, kind, isCleanup);
  // calculate the start and stop
  long size = fileDetail.length;
  if (start < 0) {
    start += size + 1;
  }
  if (end < 0) {
    end += size + 1;
  }
  start = Math.max(0, Math.min(start, size));
  end = Math.max(0, Math.min(end, size));
  start += fileDetail.start;
  end += fileDetail.start;
  bytesRemaining = end - start;
  file = new FileInputStream(new File(getBaseDir(fileDetail.location), 
      kind.toString()));
  // skip upto start
  long pos = 0;
  while (pos < start) {
    long result = file.skip(start - pos);
    if (result < 0) {
      bytesRemaining = 0;
      break;
    }
    pos += result;
  }
}
 
Example 57
Project: erlide   File: RuntimeVersion.java View source code 6 votes vote down vote up
public static String getRuntimeVersion(final String path) {
    if (path == null) {
        return null;
    }
    String result = null;
    final File boot = new File(path + "/bin/start.boot");
    try {
        final FileInputStream is = new FileInputStream(boot);
        try {
            is.skip(14);
            readstring(is);
            result = readstring(is);
        } finally {
            is.close();
        }
    } catch (final IOException e) {
    }
    return result;
}
 
Example 58
Project: aws-sdk-android   File: AwsChunkedEncodingInputStreamTest.java View source code 6 votes vote down vote up
@Test
public void testSkip() throws IOException {
    // Get the output created
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // Skip the first 100 bytes
    aceis.skip(100);

    // Consume remaining
    byte[] buf = new byte[2048];
    int read = -1;
    while ((read = aceis.read(buf)) != -1) {
        baos.write(buf, 0, read);
    }
    aceis.close();
    baos.flush();

    // Get the output we expect
    File written = new File(getClass().getResource("/com/amazonaws/auth/SignedTestData.txt")
            .getPath());
    ByteArrayOutputStream expected = new ByteArrayOutputStream();
    FileInputStream writtenFis = new FileInputStream(written);

    // Skip 100 bytes
    writtenFis.skip(100);
    int transferred = -1;
    byte[] transferBuf = new byte[2048];
    while ((transferred = writtenFis.read(transferBuf)) != -1) {
        expected.write(transferBuf, 0, transferred);
    }
    expected.flush();
    writtenFis.close();

    assertArrayEquals(expected.toByteArray(), baos.toByteArray());
}
 
Example 59
Project: bigpetstore   File: BlockReaderLocal.java View source code 6 votes vote down vote up
private BlockReaderLocal(Configuration conf, String hdfsfile, Block block,
    Token<BlockTokenIdentifier> token, long startOffset, long length,
    BlockLocalPathInfo pathinfo, FileInputStream dataIn) throws IOException {
  super(
      new Path("/blk_" + block.getBlockId() + ":of:" + hdfsfile) /*too non path-like?*/,
      1);
  this.startOffset = startOffset;
  this.dataIn = dataIn;
  long toSkip = startOffset;
  while (toSkip > 0) {
    long skipped = dataIn.skip(toSkip);
    if (skipped == 0) {
      throw new IOException("Couldn't initialize input stream");
    }
    toSkip -= skipped;
  }
}
 
Example 60
Project: brut.apktool   File: FileUtils.java View source code 6 votes vote down vote up
/**
 * Reads the specified block from the given file, translating
 * [email protected] IOException} to a [email protected] RuntimeException} of some sort.
 *
 * @param file non-null; the file to read
 * @param offset the offset to begin reading
 * @param length the number of bytes to read, or -1 to read to the
 * end of the file
 * @return non-null; contents of the file
 */
public static byte[] readFile(File file, int offset, int length)
        throws IOException {
    if (!file.exists()) {
        throw new RuntimeException(file + ": file not found");
    }

    if (!file.isFile()) {
        throw new RuntimeException(file + ": not a file");
    }

    if (!file.canRead()) {
        throw new RuntimeException(file + ": file not readable");
    }

    long longLength = file.length();
    int fileLength = (int) longLength;
    if (fileLength != longLength) {
        throw new RuntimeException(file + ": file too long");
    }

    if (length == -1) {
        length = fileLength - offset;
    }

    if (offset + length > fileLength) {
        throw new RuntimeException(file + ": file too short");
    }

    FileInputStream in = new FileInputStream(file);

    int at = offset;
    while(at > 0) {
        long amt = in.skip(at);
        if (amt == -1) {
            throw new RuntimeException(file + ": unexpected EOF");
        }
        at -= amt;
    }

    byte[] result = readStream(in, length);

    in.close();

    return result;
}
 
Example 61
Project: picard-tools   File: BamFileIoUtils.java View source code 6 votes vote down vote up
/**
 * Copy data from a BAM file to an OutputStream by directly copying the gzip blocks
 *
 * @param inputFile The file to be copied
 * @param outputStream The stream to write the copied data to
 * @param skipHeader If true, the header of the input file will not be copied to the output stream
 * @param skipTerminator If true, the terminator block of the input file will not be written to the output stream
 */
public static void blockCopyBamFile(final File inputFile, final OutputStream outputStream, final boolean skipHeader, final boolean skipTerminator) {
    FileInputStream in = null;
    try {
        in = new FileInputStream(inputFile);

        // a) It's good to check that the end of the file is valid and b) we need to know if there's a terminator block and not copy it if skipTerminator is true
        final BlockCompressedInputStream.FileTermination term = BlockCompressedInputStream.checkTermination(inputFile);
        if (term == BlockCompressedInputStream.FileTermination.DEFECTIVE)
            throw new SAMException(inputFile.getAbsolutePath() + " does not have a valid GZIP block at the end of the file.");

        if (skipHeader) {
            final long vOffsetOfFirstRecord = SAMUtils.findVirtualOffsetOfFirstRecordInBam(inputFile);
            final BlockCompressedInputStream blockIn = new BlockCompressedInputStream(inputFile);
            blockIn.seek(vOffsetOfFirstRecord);
            final long remainingInBlock = blockIn.available();

            // If we found the end of the header then write the remainder of this block out as a
            // new gzip block and then break out of the while loop
            if (remainingInBlock >= 0) {
                final BlockCompressedOutputStream blockOut = new BlockCompressedOutputStream(outputStream, null);
                IOUtil.transferByStream(blockIn, blockOut, remainingInBlock);
                blockOut.flush();
                // Don't close blockOut because closing underlying stream would break everything
            }

            long pos = BlockCompressedFilePointerUtil.getBlockAddress(blockIn.getFilePointer());
            blockIn.close();
            while (pos > 0) {
                pos -= in.skip(pos);
            }
        }

        // Copy remainder of input stream into output stream
        final long currentPos = in.getChannel().position();
        final long length = inputFile.length();
        final long skipLast = ((term == BlockCompressedInputStream.FileTermination.HAS_TERMINATOR_BLOCK) && skipTerminator) ?
                BlockCompressedStreamConstants.EMPTY_GZIP_BLOCK.length : 0;
        final long bytesToWrite = length - skipLast - currentPos;

        IOUtil.transferByStream(in, outputStream, bytesToWrite);
    } catch (final IOException ioe) {
        throw new RuntimeIOException(ioe);
    } finally {
        CloserUtil.close(in);
    }
}
 
Example 62
Project: sonar-java   File: IgnoredStreamReturnValueCheck.java View source code 6 votes vote down vote up
public void foo() throws Exception {
  FileInputStream is = new FileInputStream("");
  byte[] buffer = new byte[1000];
  long skipValue = 12L;

  is.read(buffer); // Noncompliant {{Check the return value of the "read" call to see how many bytes were read.}}
  is.skip(skipValue); // Noncompliant
  getInputStream().read(buffer); // Noncompliant
  getInputStream().skip(skipValue); // Noncompliant

  // return values are used
  int i;
  int l;
  i= is.read(buffer); // Compliant
  l = is.skip(skipValue); // Compliant

  // methods not overriding the skip/read from InputStream
  MyInputStream mis = new MyInputStream();
  mis.skip(); // compliant
  mis.skip(true); // compliant
  mis.skip('c'); // compliant
  mis.skip(0L, 0L); // Compliant
  mis.read(0L); // Compliant
  mis.read(buffer, null); // Compliant
  mis.read(buffer, 0, 0); // Compliant

  // same signature but no subtype of InputStream
  MyClass mc = new MyClass();
  mc.read(buffer); // Compliant 
  mc.skip(skipValue); // Complian
  read(buffer); // compliant
  skip(skipValue); // compliant
  
  MyUnknownClass.unknownMethod(); // Compliant
}
 
Example 63
Project: CodingSpectator   File: DiskIndex.java View source code 6 votes vote down vote up
private void cacheDocumentNames() throws IOException {
	// will need all document names so get them now
	this.cachedChunks= new String[this.numberOfChunks][];
	FileInputStream stream= new FileInputStream(this.indexFile);
	try {
		if (this.numberOfChunks > 5)
			BUFFER_READ_SIZE<<= 1;
		int offset= this.chunkOffsets[0];
		stream.skip(offset);
		this.streamBuffer= new byte[BUFFER_READ_SIZE];
		this.bufferIndex= 0;
		this.bufferEnd= stream.read(this.streamBuffer, 0, this.streamBuffer.length);
		for (int i= 0; i < this.numberOfChunks; i++) {
			int size= i == this.numberOfChunks - 1 ? this.sizeOfLastChunk : CHUNK_SIZE;
			readChunk(this.cachedChunks[i]= new String[size], stream, 0, size);
		}
	} catch (IOException e) {
		this.cachedChunks= null;
		throw e;
	} finally {
		stream.close();
		this.streamBuffer= null;
		BUFFER_READ_SIZE= DEFAULT_BUFFER_SIZE;
	}
}
 
Example 64
Project: BambooPlayer   File: MediaPlayer.java View source code 6 votes vote down vote up
/**
  * Sets the data source (file-path or http/rtsp URL) to use.
  *
  * @param path the path of the file, or the http/rtsp URL of the stream you want to play
  * @param keys   AVOption key
  * @param values AVOption value
  * @throws IllegalStateException if it is called in an invalid state
  */
public void setDataSource(String path, String[] keys, String[] values) throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
	final Uri uri = Uri.parse(path);
	if ("file".equals(uri.getScheme())) {
		path = uri.getPath();
	}

	final File file = new File(path);
	if (file.exists()) {
		FileInputStream is = new FileInputStream(file);
		FileDescriptor fd = is.getFD();
		setDataSource(fd);
		is.close();
	} else {
		_setDataSource(path, keys, values);
	}
}
 
Example 65
Project: Earmouse   File: Module.java View source code 6 votes vote down vote up
/**
 * Constructs a Module by reading a JSON from the given filename
 * @param context The application context
 * @param moduleFile The File from which to read the JSON data
 */
public Module (Context context, File moduleFile) {
	mCtx = context;
	try {
		FileInputStream fis = new FileInputStream(moduleFile);
		FileReader filereader = new FileReader(fis.getFD());
		initModuleFromJson(filereader);
		filereader.close();
		fis.close();
	} catch (IOException e) {
		e.printStackTrace();

       }
	stats = new ModuleStats(mCtx, id);
}
 
Example 66
Project: Zyy360   File: MediaPlayer.java View source code 6 votes vote down vote up
/**
  * Sets the data source (file-path or http/rtsp URL) to use.
  *
  * @param path the path of the file, or the http/rtsp URL of the stream you want to play
  * @param keys   AVOption key
  * @param values AVOption value
  * @throws IllegalStateException if it is called in an invalid state
  */
public void setDataSource(String path, String[] keys, String[] values) throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
	final Uri uri = Uri.parse(path);
	if ("file".equals(uri.getScheme())) {
		path = uri.getPath();
	}

	final File file = new File(path);
	if (file.exists()) {
		FileInputStream is = new FileInputStream(file);
		FileDescriptor fd = is.getFD();
		setDataSource(fd);
		is.close();
	} else {
		_setDataSource(path, keys, values);
	}
}
 
Example 67
Project: androidquery   File: BitmapAjaxCallback.java View source code 6 votes vote down vote up
private static Bitmap decodeFile(String path, BitmapFactory.Options options, boolean rotate){
	
	Bitmap result = null;
	
	if(options == null){
		options = new Options();
	}
	
	options.inInputShareable = isInputSharable();
	options.inPurgeable = true;
	
	FileInputStream fis = null;
	
	try{
	
		fis = new FileInputStream(path);
		FileDescriptor fd = fis.getFD();
		result = BitmapFactory.decodeFileDescriptor(fd, null, options);

		if(result != null && rotate){
			result = rotate(path, result);
		}
		
		
	}catch(IOException e){
		AQUtility.report(e);
	}finally{
		AQUtility.close(fis);
	}
	
	return result;
	
}
 
Example 68
Project: FasterGallery   File: DecodeUtils.java View source code 6 votes vote down vote up
public static Bitmap decodeThumbnail(JobContext jc, String filePath,
		Options options, int targetSize, int type) {
	FileInputStream fis = null;
	try {
		fis = new FileInputStream(filePath);
		FileDescriptor fd = fis.getFD();
		return decodeThumbnail(jc, fd, options, targetSize, type);
	} catch (Exception ex) {
		Log.w(TAG, ex);
		return null;
	} finally {
		Utils.closeSilently(fis);
	}
}
 
Example 69
Project: O2OMobile_Android   File: BitmapAjaxCallback.java View source code 6 votes vote down vote up
private static Bitmap decodeFile(String path, Options options, boolean rotate){
	
	Bitmap result = null;
	
	if(options == null){
		options = new Options();
	}
	
	options.inInputShareable = true;
	options.inPurgeable = true;
	
	FileInputStream fis = null;
	
	try{
	
		fis = new FileInputStream(path);
		FileDescriptor fd = fis.getFD();
		result = BitmapFactory.decodeFileDescriptor(fd, null, options);

		if(result != null && rotate){
			result = rotate(path, result);
		}
		
	}catch(IOException e){
		AQUtility.report(e);
	}finally{
		AQUtility.close(fis);
	}
	
	return result;
	
}
 
Example 70
Project: servestream   File: FFmpegPlayer.java View source code 6 votes vote down vote up
/**
 * Adds an external timed text source file.
 *
 * Currently supported format is SubRip with the file extension .srt, case insensitive.
 * Note that a single external timed text source may contain multiple tracks in it.
 * One can find the total number of available tracks using [email protected] #getTrackInfo()} to see what
 * additional tracks become available after this method call.
 *
 * @param path The file path of external timed text source file.
 * @param mimeType The mime type of the file. Must be one of the mime types listed above.
 * @throws IOException if the file cannot be accessed or is corrupted.
 * @throws IllegalArgumentException if the mimeType is not supported.
 * @throws IllegalStateException if called in an invalid state.
 */
public void addTimedTextSource(String path, String mimeType)
        throws IOException, IllegalArgumentException, IllegalStateException {
    if (!availableMimeTypeForExternalSource(mimeType)) {
        final String msg = "Illegal mimeType for timed text source: " + mimeType;
        throw new IllegalArgumentException(msg);
    }

    File file = new File(path);
    if (file.exists()) {
        FileInputStream is = new FileInputStream(file);
        FileDescriptor fd = is.getFD();
        addTimedTextSource(fd, mimeType);
        is.close();
    } else {
        // We do not support the case where the path is not a file.
        throw new IOException(path);
    }
}
 
Example 71
Project: property-db   File: BackupTestActivity.java View source code 6 votes vote down vote up
void run() {
    try {
        BackupHelperDispatcher dispatch = new BackupHelperDispatcher();
        dispatch.addHelper("", new FileBackupHelper(BackupTestActivity.this,
                new String[] { "a", "empty" }));
        FileInputStream dataFile = openFileInput("backup_test");
        BackupDataInput data = new BackupDataInput(dataFile.getFD());
        ParcelFileDescriptor state = ParcelFileDescriptor.open(
                new File(getFilesDir(), "restore_state"),
                ParcelFileDescriptor.MODE_READ_WRITE|ParcelFileDescriptor.MODE_CREATE|
                ParcelFileDescriptor.MODE_TRUNCATE);
        // TODO: a more plausable synthetic stored-data version number
        dispatch.performRestore(data, 0, state);
        dataFile.close();
        state.close();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 72
Project: umeng_shake_demo   File: MediaPlayer.java View source code 6 votes vote down vote up
/**
  * Sets the data source (file-path or http/rtsp URL) to use.
  *
  * @param path the path of the file, or the http/rtsp URL of the stream you want to play
  * @param keys   AVOption key
  * @param values AVOption value
  * @throws IllegalStateException if it is called in an invalid state
  */
public void setDataSource(String path, String[] keys, String[] values) throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
	final Uri uri = Uri.parse(path);
	if ("file".equals(uri.getScheme())) {
		path = uri.getPath();
	}

	final File file = new File(path);
	if (file.exists()) {
		FileInputStream is = new FileInputStream(file);
		FileDescriptor fd = is.getFD();
		setDataSource(fd);
		is.close();
	} else {
		_setDataSource(path, keys, values);
	}
}
 
Example 73
Project: ijoyplus-android   File: DecodeUtils.java View source code 6 votes vote down vote up
public static Bitmap requestDecode(JobContext jc, final String filePath,
        Options options, int targetSize) {
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(filePath);
        FileDescriptor fd = fis.getFD();
        return requestDecode(jc, fd, options, targetSize);
    } catch (Exception ex) {
        Log.w(TAG, ex);
        return null;
    } finally {
    	JoylinkUtils.closeSilently(fis);
    }
}
 
Example 74
Project: hadoop-on-lustre2   File: TestSharedFileDescriptorFactory.java View source code 6 votes vote down vote up
@Test(timeout=10000)
public void testReadAndWrite() throws Exception {
  File path = new File(TEST_BASE, "testReadAndWrite");
  path.mkdirs();
  SharedFileDescriptorFactory factory =
      SharedFileDescriptorFactory.create("woot_",
          new String[] { path.getAbsolutePath() });
  FileInputStream inStream =
      factory.createDescriptor("testReadAndWrite", 4096);
  FileOutputStream outStream = new FileOutputStream(inStream.getFD());
  outStream.write(101);
  inStream.getChannel().position(0);
  Assert.assertEquals(101, inStream.read());
  inStream.close();
  outStream.close();
  FileUtil.fullyDelete(path);
}
 
Example 75
Project: gallery3d   File: DecodeUtils.java View source code 6 votes vote down vote up
public static Bitmap decodeThumbnail(
        JobContext jc, String filePath, Options options, int targetSize, int type) {
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(filePath);
        FileDescriptor fd = fis.getFD();
        return decodeThumbnail(jc, fd, options, targetSize, type);
    } catch (Exception ex) {
        Log.w(TAG, ex);
        return null;
    } finally {
        Utils.closeSilently(fis);
    }
}
 
Example 76
Project: android-ssl   File: SocketUtils.java View source code 6 votes vote down vote up
public static int getFileDescriptor(Socket socket) throws IOException {
	try {
		Object in;
		if (socket instanceof SSLSocket) {
			/*
			 * Socket.getInputStream() on an SSLSocket returns the
			 * InputStream which reads the decrypted data from a buffer in
			 * memory - in this case, we read the private
			 * SSLSocketImpl.sockInput field with reflection to get at the
			 * InputStream which is backed by a file descriptor.
			 */
			in = SSL_SOCKET_INPUT.get(socket);
		} else {
			in = socket.getInputStream();
		}

		if (!(in instanceof FileInputStream))
			throw new IOException("sockInput is not an instance of FileInputStream");

		FileInputStream fin = (FileInputStream) in;
		FileDescriptor fd = fin.getFD();

		return FD.getInt(fd);
	} catch (IllegalAccessException ex) {
		throw new IOException(ex);
	}
}
 
Example 77
Project: luper   File: AudioFile.java View source code 6 votes vote down vote up
public int calcDuration() { //FIXME update database with current duration , refactor
  try {
    MediaPlayer mp = new MediaPlayer();
    FileInputStream fs;
    FileDescriptor fd;
    fs = new FileInputStream(this.getClientFilePath());
    fd = fs.getFD();
    mp.setDataSource(fd);
    mp.prepare();
    int length = mp.getDuration();
    mp.release();
    return length;
  } catch (Exception e) {
    e.printStackTrace();
    return 0;
  }
}
 
Example 78
Project: SmartAndroidSource   File: BitmapAjaxCallback.java View source code 6 votes vote down vote up
private static Bitmap decodeFile(String path, BitmapFactory.Options options){
	
	Bitmap result = null;
	
	if(options == null){
		options = new Options();
	}
	
	options.inInputShareable = true;
	options.inPurgeable = true;
	
	
	
	FileInputStream fis = null;
	
	try{
	
		fis = new FileInputStream(path);
		
		FileDescriptor fd = fis.getFD();
		
		//AQUtility.debug("decoding file");
		//AQUtility.time("decode file");
		
		result = BitmapFactory.decodeFileDescriptor(fd, null, options);
		
		//AQUtility.timeEnd("decode file", 0);
	}catch(IOException e){
		AQUtility.report(e);
	}finally{
		AQUtility.close(fis);
	}
	
	return result;
	
}
 
Example 79
Project: word2vec-query-expansion   File: IndexFiles.java View source code 5 votes vote down vote up
/**
 * Indexes the given file using the given writer, or if a directory is given,
 * recurses over files and directories found under the given directory.
 * 
 * NOTE: This method indexes one document per input file.  This is slow.  For good
 * throughput, put multiple documents into your input file(s).  An example of this is
 * in the benchmark module, which can create "line doc" files, one document per line,
 * using the
 * <a href="../../../../../contrib-benchmark/org/apache/lucene/benchmark/byTask/tasks/WriteLineDocTask.html"
 * >WriteLineDocTask</a>.
 *  
 * @param writer Writer to the index where the given file/dir info will be stored
 * @param file The file to index, or the directory to recurse into to find files to index
 * @throws IOException If there is a low-level I/O error
 */
static void indexDocs(IndexWriter writer, File file)
  throws IOException {
  // do not try to index files that cannot be read
  if (file.canRead()) {
    if (file.isDirectory()) {
      String[] files = file.list();
      // an IO error could occur
      if (files != null) {
        for (int i = 0; i < files.length; i++) {
          indexDocs(writer, new File(file, files[i]));
        }
      }
    } else {

      FileInputStream fis;
      try {
        fis = new FileInputStream(file);
      } catch (FileNotFoundException fnfe) {
        // at least on windows, some temporary files raise this exception with an "access denied" message
        // checking if the file can be read doesn't help
        return;
      }

      try {

        // make a new, empty document
        Document doc = new Document();

        // Add the path of the file as a field named "path".  Use a
        // field that is indexed (i.e. searchable), but don't tokenize 
        // the field into separate words and don't index term frequency
        // or positional information:
        Field pathField = new StringField("path", file.getPath(), Field.Store.YES);
        doc.add(pathField);

        // Add the last modified date of the file a field named "modified".
        // Use a LongField that is indexed (i.e. efficiently filterable with
        // NumericRangeFilter).  This indexes to milli-second resolution, which
        // is often too fine.  You could instead create a number based on
        // year/month/day/hour/minutes/seconds, down the resolution you require.
        // For example the long value 2011021714 would mean
        // February 17, 2011, 2-3 PM.
        doc.add(new LongField("modified", file.lastModified(), Field.Store.NO));

        // Add the contents of the file to a field named "contents".  Specify a Reader,
        // so that the text of the file is tokenized and indexed, but not stored.
        // Note that FileReader expects the file to be in UTF-8 encoding.
        // If that's not the case searching for special characters will fail.
        doc.add(new TextField("contents", new BufferedReader(new InputStreamReader(fis, "UTF-8"))));

        if (writer.getConfig().getOpenMode() == OpenMode.CREATE) {
          // New index, so we just add the document (no old document can be there):
          System.out.println("adding " + file);
          writer.addDocument(doc);
        } else {
          // Existing index (an old copy of this document may have been indexed) so 
          // we use updateDocument instead to replace the old one matching the exact 
          // path, if present:
          System.out.println("updating " + file);
          writer.updateDocument(new Term("path", file.getPath()), doc);
        }
        
      } finally {
        fis.close();
      }
    }
  }
}
 
Example 80
Project: word2vec-query-expansion   File: ConvertVectors.java View source code 5 votes vote down vote up
/**
 * @param args
 *            the input C vectors file, output Java vectors file
 */
public static void main(String[] args) throws VectorsException, IOException {
    float[][] vectors;
    String[] vocabVects;
    int words;
    int size;

    File vectorFile = new File(args[0]);
    File outputFile = new File(args[1]);

    double len;

    if (!vectorFile.exists())
        throw new VectorsException("Vectors file not found");

    FileInputStream fis = new FileInputStream(vectorFile);

    StringBuilder sb = new StringBuilder();
    char ch = (char) fis.read();
    while (ch != '\n') {
        sb.append(ch);
        ch = (char) fis.read();
    }

    String line = sb.toString();
    String[] parts = line.split("\\s+");
    words = (int) Long.parseLong(parts[0]);
    size = (int) Long.parseLong(parts[1]);
    vectors = new float[words][];
    vocabVects = new String[words];

    System.out.println("" + words + " words with size " + size + " per vector.");

    byte[] orig = new byte[4];
    byte[] buf = new byte[4];
    for (int w = 0; w < words; w++) {
        if (w % (words / 10) == 0) {
            System.out.println("Read " + w + " words");
        }

        sb.setLength(0);
        ch = (char) fis.read();
        while (!Character.isWhitespace(ch) && ch >= 0 && ch <= 256) {
            sb.append((char) ch);
            ch = (char) fis.read();
        }
        ch = (char) fis.read();
        String st = sb.toString();

        vocabVects[w] = st;
        float[] m = new float[size];
        for (int i = 0; i < size; i++) {
            // read a little endian floating point number and interpret it as a big endian one, see
            // http://stackoverflow.com/questions/2782725/converting-float-values-from-big-endian-to-little-endian/2782742#2782742
            // NB: this code assumes amd64 architecture
            for (int j = 0; j < 4; j++)
                orig[j] = (byte) fis.read();
            buf[2] = orig[0];
            buf[1] = orig[1];
            buf[0] = orig[2];
            buf[3] = orig[3];
            // this code can be made more efficient by reusing the ByteArrayInputStream
            DataInputStream dis = new DataInputStream(new ByteArrayInputStream(buf));
            m[i] = dis.readFloat();
            dis.close();
        }
        len = 0;
        for (int i = 0; i < size; i++)
            len += m[i] * m[i];
        len = (float) Math.sqrt(len);
        for (int i = 0; i < size; i++)
            m[i] /= len;
        vectors[w] = m;
    }
    fis.close();

    FileOutputStream fos = new FileOutputStream(outputFile);
    Vectors instance = new Vectors(vectors, vocabVects);
    instance.writeTo(fos);
}
 
Example 81
Project: tio_patinhas   File: ImageProcessor.java View source code 5 votes vote down vote up
/**
loadbitmap() method converted from Windows C code.
Reads only uncompressed 24- and 8-bit images.  Tested with
images saved using Microsoft Paint in Windows 95.  If the image
is not a 24- or 8-bit image, the program refuses to even try.
I guess one could include 4-bit images by masking the byte
by first 1100 and then 0011.  I am not really 
interested in such images.  If a compressed image is attempted,
the routine will probably fail by generating an IOException.
Look for variable ncompression to be different from 0 to indicate
compression is present.
Arguments:
sdir and sfile are the result of the FileDialog()
getDirectory() and getFile() methods.
Returns:
Image Object, be sure to check for (Image)null !!!!
 */
public Image loadbitmap(String str_file) {

    Image image;
    //System.out.println("loading:" + str_file);
    try {
        FileInputStream fs = new FileInputStream(str_file);
        int bflen = 14;  // 14 byte BITMAPFILEHEADER

        byte bf[] = new byte[bflen];
        fs.read(bf, 0, bflen);
        int bilen = 40; // 40-byte BITMAPINFOHEADER

        byte bi[] = new byte[bilen];
        fs.read(bi, 0, bilen);
        // Interperet data.
        int nsize = (((int) bf[5] & 0xff) << 24) | (((int) bf[4] & 0xff) << 16) | (((int) bf[3] & 0xff) << 8) | (int) bf[2] & 0xff;
        //System.out.println("File type is :" + (char) bf[0] + (char) bf[1]);
        //System.out.println("Size of file is :" + nsize);
        int nbisize = (((int) bi[3] & 0xff) << 24) | (((int) bi[2] & 0xff) << 16) | (((int) bi[1] & 0xff) << 8) | (int) bi[0] & 0xff;
        //System.out.println("Size of bitmapinfoheader is :" + nbisize);
        int nwidth = (((int) bi[7] & 0xff) << 24) | (((int) bi[6] & 0xff) << 16) | (((int) bi[5] & 0xff) << 8) | (int) bi[4] & 0xff;
        //System.out.println("Width is :" + nwidth);
        int nheight = (((int) bi[11] & 0xff) << 24) | (((int) bi[10] & 0xff) << 16) | (((int) bi[9] & 0xff) << 8) | (int) bi[8] & 0xff;
        //System.out.println("Height is :" + nheight);
        int nplanes = (((int) bi[13] & 0xff) << 8) | (int) bi[12] & 0xff;
        //System.out.println("Planes is :" + nplanes);
        int nbitcount = (((int) bi[15] & 0xff) << 8) | (int) bi[14] & 0xff;
        //System.out.println("BitCount is :" + nbitcount);
        // Look for non-zero values to indicate compression
        int ncompression = (((int) bi[19]) << 24) | (((int) bi[18]) << 16) | (((int) bi[17]) << 8) | (int) bi[16];
        //System.out.println("Compression is :" + ncompression);
        int nsizeimage = (((int) bi[23] & 0xff) << 24) | (((int) bi[22] & 0xff) << 16) | (((int) bi[21] & 0xff) << 8) | (int) bi[20] & 0xff;
        //System.out.println("SizeImage is :" + nsizeimage);
        int nxpm = (((int) bi[27] & 0xff) << 24) | (((int) bi[26] & 0xff) << 16) | (((int) bi[25] & 0xff) << 8) | (int) bi[24] & 0xff;
        //System.out.println("X-Pixels per meter is :" + nxpm);
        int nypm = (((int) bi[31] & 0xff) << 24) | (((int) bi[30] & 0xff) << 16) | (((int) bi[29] & 0xff) << 8) | (int) bi[28] & 0xff;
        //System.out.println("Y-Pixels per meter is :" + nypm);
        int nclrused = (((int) bi[35] & 0xff) << 24) | (((int) bi[34] & 0xff) << 16) | (((int) bi[33] & 0xff) << 8) | (int) bi[32] & 0xff;
        //System.out.println("Colors used are :" + nclrused);
        int nclrimp = (((int) bi[39] & 0xff) << 24) | (((int) bi[38] & 0xff) << 16) | (((int) bi[37] & 0xff) << 8) | (int) bi[36] & 0xff;
        //System.out.println("Colors important are :" + nclrimp);
        if (nbitcount == 24) {
            // No Palatte data for 24-bit format but scan lines are
            // padded out to even 4-byte boundaries.
            int npad = (nsizeimage / nheight) - nwidth * 3;
            int ndata[] = new int[nheight * nwidth];
            byte brgb[] = new byte[(nwidth + npad) * 3 * nheight];
            fs.read(brgb, 0, (nwidth + npad) * 3 * nheight);
            int nindex = 0;
            for (int j = 0; j < nheight; j++) {
                for (int i = 0; i < nwidth; i++) {
                    ndata[nwidth * (nheight - j - 1) + i] =
                            (255 & 0xff) << 24 | (((int) brgb[nindex + 2] & 0xff) << 16) | (((int) brgb[nindex + 1] & 0xff) << 8) | (int) brgb[nindex] & 0xff;
                    nindex += 3;
                }
                nindex += npad;
            }
            image = createImage(new MemoryImageSource(nwidth, nheight, ndata, 0, nwidth));

        } else if (nbitcount == 8) {
            // Have to determine the number of colors, the clrsused
            // parameter is dominant if it is greater than zero.  If
            // zero, calculate colors based on bitsperpixel.
            int nNumColors = 0;
            if (nclrused > 0) {
                nNumColors = nclrused;
            } else {
                nNumColors = (1 & 0xff) << nbitcount;
            }
            //System.out.println("The number of Colors is" + nNumColors);
            // Some bitmaps do not have the sizeimage field calculated
            // Ferret out these cases and fix 'em.
            if (nsizeimage == 0) {
                nsizeimage = ((((nwidth * nbitcount) + 31) & 31) >> 3);
                nsizeimage *= nheight;
                //System.out.println("nsizeimage (backup) is" + nsizeimage);
            }
            // Read the palatte colors.
            int npalette[] = new int[nNumColors];
            byte bpalette[] = new byte[nNumColors * 4];
            fs.read(bpalette, 0, nNumColors * 4);
            int nindex8 = 0;
            for (int n = 0; n < nNumColors; n++) {
                npalette[n] = (255 & 0xff) << 24 | (((int) bpalette[nindex8 + 2] & 0xff) << 16) | (((int) bpalette[nindex8 + 1] & 0xff) << 8) | (int) bpalette[nindex8] & 0xff;
                nindex8 += 4;
            }
            // Read the image data (actually indices into the palette)
            // Scan lines are still padded out to even 4-byte
            // boundaries.
            int npad8 = (nsizeimage / nheight) - nwidth;
            //System.out.println("nPad is:" + npad8);
            int ndata8[] = new int[nwidth * nheight];
            byte bdata[] = new byte[(nwidth + npad8) * nheight];
            fs.read(bdata, 0, (nwidth + npad8) * nheight);
            nindex8 = 0;
            for (int j8 = 0; j8 < nheight; j8++) {
                for (int i8 = 0; i8 < nwidth; i8++) {
                    ndata8[nwidth * (nheight - j8 - 1) + i8] =
                            npalette[((int) bdata[nindex8] & 0xff)];
                    nindex8++;
                }
                nindex8 += npad8;
            }
            image = createImage(new MemoryImageSource(nwidth, nheight, ndata8, 0, nwidth));
        } else {
            //System.out.println("Not a 24-bit or 8-bit Windows Bitmap, aborting...");
            image = (Image) null;
        }
        fs.close();
        return image;
    } catch (Exception e) {
        //System.out.println("Caught exception in loadbitmap!");
    }
    return (Image) null;
}
 
Example 82
Project: dlna   File: HttpServer.java View source code 5 votes vote down vote up
/**
 * Serves file from homeDir and its' subdirectories (only).
 * Uses only URI, ignores all headers and HTTP parameters.
 */
public Response serveFile( String uri, Properties header, File homeDir,
						   boolean allowDirectoryListing )
{
	Response res = null;

	// Make sure we won't die of an exception later
	if ( !homeDir.isDirectory())
		res = new Response( HTTP_INTERNALERROR, MIME_PLAINTEXT,
			"INTERNAL ERRROR: serveFile(): given homeDir is not a directory." );

	if ( res == null )
	{
		// Remove URL arguments
		uri = uri.trim().replace( File.separatorChar, '/' );
		if ( uri.indexOf( '?' ) >= 0 )
			uri = uri.substring(0, uri.indexOf( '?' ));

		// Prohibit getting out of current directory
		if ( uri.startsWith( ".." ) || uri.endsWith( ".." ) || uri.indexOf( "../" ) >= 0 )
			res = new Response( HTTP_FORBIDDEN, MIME_PLAINTEXT,
				"FORBIDDEN: Won't serve ../ for security reasons." );
	}

	File f = new File( homeDir, uri );
	if ( res == null && !f.exists())
		res = new Response( HTTP_NOTFOUND, MIME_PLAINTEXT,
			"Error 404, file not found." );

	// List the directory, if necessary
	if ( res == null && f.isDirectory())
	{
		// Browsers get confused without '/' after the
		// directory, send a redirect.
		if ( !uri.endsWith( "/" ))
		{
			uri += "/";
			res = new Response( HTTP_REDIRECT, MIME_HTML,
				"<html><body>Redirected: <a href=\"" + uri + "\">" +
				uri + "</a></body></html>");
			res.addHeader( "Location", uri );
		}

		if ( res == null )
		{
			// First try index.html and index.htm
			if ( new File( f, "index.html" ).exists())
				f = new File( homeDir, uri + "/index.html" );
			else if ( new File( f, "index.htm" ).exists())
				f = new File( homeDir, uri + "/index.htm" );
			// No index file, list the directory if it is readable
			else if ( allowDirectoryListing && f.canRead() )
			{
				String[] files = f.list();
				String msg = "<html><body><h1>Directory " + uri + "</h1><br/>";

				if ( uri.length() > 1 )
				{
					String u = uri.substring( 0, uri.length()-1 );
					int slash = u.lastIndexOf( '/' );
					if ( slash >= 0 && slash  < u.length())
						msg += "<b><a href=\"" + uri.substring(0, slash+1) + "\">..</a></b><br/>";
				}

				if (files!=null)
				{
					for ( int i=0; i<files.length; ++i )
					{
						File curFile = new File( f, files[i] );
						boolean dir = curFile.isDirectory();
						if ( dir )
						{
							msg += "<b>";
							files[i] += "/";
						}

						msg += "<a href=\"" + encodeUri( uri + files[i] ) + "\">" +
							  files[i] + "</a>";

						// Show file size
						if ( curFile.isFile())
						{
							long len = curFile.length();
							msg += " &nbsp;<font size=2>(";
							if ( len < 1024 )
								msg += len + " bytes";
							else if ( len < 1024 * 1024 )
								msg += len/1024 + "." + (len%1024/10%100) + " KB";
							else
								msg += len/(1024*1024) + "." + len%(1024*1024)/10%100 + " MB";

							msg += ")</font>";
						}
						msg += "<br/>";
						if ( dir ) msg += "</b>";
					}
				}
				msg += "</body></html>";
				res = new Response( HTTP_OK, MIME_HTML, msg );
			}
			else
			{
				res = new Response( HTTP_FORBIDDEN, MIME_PLAINTEXT,
					"FORBIDDEN: No directory listing." );
			}
		}
	}

	try
	{
		if ( res == null )
		{
			// Get MIME type from file name extension, if possible
			String mime = null;
			int dot = f.getCanonicalPath().lastIndexOf( '.' );
			if ( dot >= 0 )
				mime = (String)theMimeTypes.get( f.getCanonicalPath().substring( dot + 1 ).toLowerCase());
			if ( mime == null )
				mime = MIME_DEFAULT_BINARY;

			// Support (simple) skipping:
			long startFrom = 0;
			long endAt = -1;
			String range = header.getProperty( "range" );
			if ( range != null )
			{
				if ( range.startsWith( "bytes=" ))
				{
					range = range.substring( "bytes=".length());
					int minus = range.indexOf( '-' );
					try {
						if ( minus > 0 )
						{
							startFrom = Long.parseLong( range.substring( 0, minus ));
							endAt = Long.parseLong( range.substring( minus+1 ));
						}
					}
					catch ( NumberFormatException nfe ) {}
				}
			}

			// Change return code and add Content-Range header when skipping is requested
			long fileLen = f.length();
			if (range != null && startFrom >= 0)
			{
				if ( startFrom >= fileLen)
				{
					res = new Response( HTTP_RANGE_NOT_SATISFIABLE, MIME_PLAINTEXT, "" );
					res.addHeader( "Content-Range", "bytes 0-0/" + fileLen);
				}
				else
				{
					if ( endAt < 0 )
						endAt = fileLen-1;
					long newLen = endAt - startFrom + 1;
					if ( newLen < 0 ) newLen = 0;

					final long dataLen = newLen;
					FileInputStream fis = new FileInputStream( f ) {
						public int available() throws IOException { return (int)dataLen; }
					};
					fis.skip( startFrom );

					res = new Response( HTTP_PARTIALCONTENT, mime, fis );
					res.addHeader( "Content-Length", "" + dataLen);
					res.addHeader( "Content-Range", "bytes " + startFrom + "-" + endAt + "/" + fileLen);
				}
			}
			else
			{
				res = new Response( HTTP_OK, mime, new FileInputStream( f ));
				res.addHeader( "Content-Length", "" + fileLen);
			}
		}
	}
	catch( IOException ioe )
	{
		res = new Response( HTTP_FORBIDDEN, MIME_PLAINTEXT, "FORBIDDEN: Reading file failed." );
	}

	res.addHeader( "Accept-Ranges", "bytes"); // Announce that the file server accepts partial content requestes
	return res;
}
 
Example 83
Project: Yarrn   File: NanoHTTPD.java View source code 5 votes vote down vote up
/**
 * Serves file from homeDir and its' subdirectories (only). Uses only URI,
 * ignores all headers and HTTP parameters.
 */
public Response serveFile(String uri, final Properties header,
                          final File homeDir, final boolean allowDirectoryListing) {
    Response res = null;

    // Make sure we won't die of an exception later
    if (!homeDir.isDirectory()) {
        res = new Response(HTTP_INTERNALERROR, MIME_PLAINTEXT,
                "INTERNAL ERRROR: serveFile(): given homeDir is not a directory.");
    }

    if (res == null) {
        // Remove URL arguments
        uri = uri.trim().replace(File.separatorChar, '/');
        if (uri.indexOf('?') >= 0) {
            uri = uri.substring(0, uri.indexOf('?'));
        }

        // Prohibit getting out of current directory
        if (uri.startsWith("..") || uri.endsWith("..")
                || uri.indexOf("../") >= 0) {
            res = new Response(HTTP_FORBIDDEN, MIME_PLAINTEXT,
                    "FORBIDDEN: Won't serve ../ for security reasons.");
        }
    }

    File f = new File(homeDir, uri);
    if (res == null && !f.exists()) {
        res = new Response(HTTP_NOTFOUND, MIME_PLAINTEXT,
                "Error 404, file not found.");
    }

    // List the directory, if necessary
    if (res == null && f.isDirectory()) {
        // Browsers get confused without '/' after the
        // directory, send a redirect.
        if (!uri.endsWith("/")) {
            uri += "/";
            res = new Response(HTTP_REDIRECT, MIME_HTML,
                    "<html><body>Redirected: <a href=\"" + uri + "\">"
                            + uri + "</a></body></html>");
            res.addHeader("Location", uri);
        }

        if (res == null) {
            // First try index.html and index.htm
            if (new File(f, "index.html").exists()) {
                f = new File(homeDir, uri + "/index.html");
            } else if (new File(f, "index.htm").exists()) {
                f = new File(homeDir, uri + "/index.htm");
            } else if (allowDirectoryListing && f.canRead()) {
                final String[] files = f.list();
                String msg = "<html><body><h1>Directory " + uri
                        + "</h1><br/>";

                if (uri.length() > 1) {
                    final String u = uri.substring(0, uri.length() - 1);
                    final int slash = u.lastIndexOf('/');
                    if (slash >= 0 && slash < u.length()) {
                        msg += "<b><a href=\""
                                + uri.substring(0, slash + 1)
                                + "\">..</a></b><br/>";
                    }
                }

                if (files != null) {
                    for (int i = 0; i < files.length; ++i) {
                        final File curFile = new File(f, files[i]);
                        final boolean dir = curFile.isDirectory();
                        if (dir) {
                            msg += "<b>";
                            files[i] += "/";
                        }

                        msg += "<a href=\"" + encodeUri(uri + files[i])
                                + "\">" + files[i] + "</a>";

                        // Show file size
                        if (curFile.isFile()) {
                            final long len = curFile.length();
                            msg += " &nbsp;<font size=2>(";
                            if (len < 1024) {
                                msg += len + " bytes";
                            } else if (len < 1024 * 1024) {
                                msg += len / 1024 + "." + len % 1024 / 10
                                        % 100 + " KB";
                            } else {
                                msg += len / (1024 * 1024) + "." + len
                                        % (1024 * 1024) / 10 % 100 + " MB";
                            }

                            msg += ")</font>";
                        }
                        msg += "<br/>";
                        if (dir) {
                            msg += "</b>";
                        }
                    }
                }
                msg += "</body></html>";
                res = new Response(HTTP_OK, MIME_HTML, msg);
            } else {
                res = new Response(HTTP_FORBIDDEN, MIME_PLAINTEXT,
                        "FORBIDDEN: No directory listing.");
            }
        }
    }

    try {
        if (res == null) {
            // Get MIME type from file name extension, if possible
            String mime = null;
            final int dot = f.getCanonicalPath().lastIndexOf('.');
            if (dot >= 0) {
                mime = (String) theMimeTypes.get(f.getCanonicalPath()
                        .substring(dot + 1).toLowerCase(Locale.ENGLISH));
            }
            if (mime == null) {
                mime = MIME_DEFAULT_BINARY;
            }

            // Calculate etag
            final String etag = Integer.toHexString((f.getAbsolutePath()
                    + f.lastModified() + "" + f.length()).hashCode());

            // Support (simple) skipping:
            long startFrom = 0;
            long endAt = -1;
            String range = header.getProperty("range");
            if (range != null) {
                if (range.startsWith("bytes=")) {
                    range = range.substring("bytes=".length());
                    final int minus = range.indexOf('-');
                    try {
                        if (minus > 0) {
                            startFrom = Long.parseLong(range.substring(0,
                                    minus));
                            endAt = Long.parseLong(range
                                    .substring(minus + 1));
                        }
                    } catch (final NumberFormatException nfe) {
                    }
                }
            }

            // Change return code and add Content-Range header when skipping
            // is requested
            final long fileLen = f.length();
            if (range != null && startFrom >= 0) {
                if (startFrom >= fileLen) {
                    res = new Response(HTTP_RANGE_NOT_SATISFIABLE,
                            MIME_PLAINTEXT, "");
                    res.addHeader("Content-Range", "bytes 0-0/" + fileLen);
                    if (mime.startsWith("application/")) {
                        res.addHeader("Content-Disposition",
                                "attachment; filename=\"" + f.getName()
                                        + "\"");
                    }
                    res.addHeader("ETag", etag);
                } else {
                    if (endAt < 0) {
                        endAt = fileLen - 1;
                    }
                    long newLen = endAt - startFrom + 1;
                    if (newLen < 0) {
                        newLen = 0;
                    }

                    final long dataLen = newLen;
                    final FileInputStream fis = new FileInputStream(f) {
                        @Override
                        public int available() throws IOException {
                            return (int) dataLen;
                        }
                    };
                    fis.skip(startFrom);

                    res = new Response(HTTP_PARTIALCONTENT, mime, fis);
                    res.addHeader("Content-Length", "" + dataLen);
                    res.addHeader("Content-Range", "bytes " + startFrom
                            + "-" + endAt + "/" + fileLen);
                    if (mime.startsWith("application/")) {
                        res.addHeader("Content-Disposition",
                                "attachment; filename=\"" + f.getName()
                                        + "\"");
                    }
                    res.addHeader("ETag", etag);
                }
            } else {
                if (etag.equals(header.getProperty("if-none-match"))) {
                    res = new Response(HTTP_NOTMODIFIED, mime, "");
                } else {
                    res = new Response(HTTP_OK, mime,
                            new FileInputStream(f));
                    res.addHeader("Content-Length", "" + fileLen);
                    if (mime.startsWith("application/")) {
                        res.addHeader("Content-Disposition",
                                "attachment; filename=\"" + f.getName()
                                        + "\"");
                    }
                    res.addHeader("ETag", etag);
                }
            }
        }
    } catch (final IOException ioe) {
        res = new Response(HTTP_FORBIDDEN, MIME_PLAINTEXT,
                "FORBIDDEN: Reading file failed.");
    }

    res.addHeader("Accept-Ranges", "bytes"); // Announce that the file
    // server accepts partial
    // content requestes
    return res;
}
 
Example 84
Project: HDP-2.2-Patched   File: TestConcatenatedCompressedInput.java View source code 5 votes vote down vote up
/**
 * Test using the raw Inflater codec for reading gzip files.
 */
@Test
public void testPrototypeInflaterGzip() throws IOException {
  CompressionCodec gzip = new GzipCodec();  // used only for file extension
  localFs.delete(workDir, true);            // localFs = FileSystem instance

  System.out.println(COLOR_BR_BLUE + "testPrototypeInflaterGzip() using " +
    "non-native/Java Inflater and manual gzip header/trailer parsing" +
    COLOR_NORMAL);

  // copy prebuilt (correct!) version of concat.gz to HDFS
  final String fn = "concat" + gzip.getDefaultExtension();
  Path fnLocal = new Path(System.getProperty("test.concat.data", "/tmp"), fn);
  Path fnHDFS  = new Path(workDir, fn);
  localFs.copyFromLocalFile(fnLocal, fnHDFS);

  final FileInputStream in = new FileInputStream(fnLocal.toString());
  assertEquals("concat bytes available", 148, in.available());

  // should wrap all of this header-reading stuff in a running-CRC wrapper
  // (did so in BuiltInGzipDecompressor; see below)

  byte[] compressedBuf = new byte[256];
  int numBytesRead = in.read(compressedBuf, 0, 10);
  assertEquals("header bytes read", 10, numBytesRead);
  assertEquals("1st byte", 0x1f, compressedBuf[0] & 0xff);
  assertEquals("2nd byte", 0x8b, compressedBuf[1] & 0xff);
  assertEquals("3rd byte (compression method)", 8, compressedBuf[2] & 0xff);

  byte flags = (byte)(compressedBuf[3] & 0xff);
  if ((flags & 0x04) != 0) {   // FEXTRA
    numBytesRead = in.read(compressedBuf, 0, 2);
    assertEquals("XLEN bytes read", 2, numBytesRead);
    int xlen = ((compressedBuf[1] << 8) | compressedBuf[0]) & 0xffff;
    in.skip(xlen);
  }
  if ((flags & 0x08) != 0) {   // FNAME
    while ((numBytesRead = in.read()) != 0) {
      assertFalse("unexpected end-of-file while reading filename",
                  numBytesRead == -1);
    }
  }
  if ((flags & 0x10) != 0) {   // FCOMMENT
    while ((numBytesRead = in.read()) != 0) {
      assertFalse("unexpected end-of-file while reading comment",
                  numBytesRead == -1);
    }
  }
  if ((flags & 0xe0) != 0) {   // reserved
    assertTrue("reserved bits are set??", (flags & 0xe0) == 0);
  }
  if ((flags & 0x02) != 0) {   // FHCRC
    numBytesRead = in.read(compressedBuf, 0, 2);
    assertEquals("CRC16 bytes read", 2, numBytesRead);
    int crc16 = ((compressedBuf[1] << 8) | compressedBuf[0]) & 0xffff;
  }

  // ready to go!  next bytes should be start of deflated stream, suitable
  // for Inflater
  numBytesRead = in.read(compressedBuf);

  // Inflater docs refer to a "dummy byte":  no clue what that's about;
  // appears to work fine without one
  byte[] uncompressedBuf = new byte[256];
  Inflater inflater = new Inflater(true);

  inflater.setInput(compressedBuf, 0, numBytesRead);
  try {
    int numBytesUncompressed = inflater.inflate(uncompressedBuf);
    String outString =
      new String(uncompressedBuf, 0, numBytesUncompressed, "UTF-8");
    System.out.println("uncompressed data of first gzip member = [" +
                       outString + "]");
  } catch (java.util.zip.DataFormatException ex) {
    throw new IOException(ex.getMessage());
  }

  in.close();
}
 
Example 85
Project: Wifi-File-Manager-Android   File: HttpServer.java View source code 5 votes vote down vote up
public Response serveFile( String uri, Properties header, File homeDir,
		boolean allowDirectoryListing )
{
	Response res = null;

	// Make sure we won't die of an exception later
	if ( !homeDir.isDirectory())
		res = new Response( HTTP_INTERNALERROR, MIME_PLAINTEXT,
			"INTERNAL ERRROR: serveFile(): given homeDir is not a directory." );

	if ( res == null )
	{
		// Remove URL arguments
		uri = uri.trim().replace( File.separatorChar, '/' );
		if ( uri.indexOf( '?' ) >= 0 )
			uri = uri.substring(0, uri.indexOf( '?' ));

		// Prohibit getting out of current directory
		if ( uri.startsWith( ".." ) || uri.endsWith( ".." ) || uri.indexOf( "../" ) >= 0 )
			res = new Response( HTTP_FORBIDDEN, MIME_PLAINTEXT,
				"FORBIDDEN: Won't serve ../ for security reasons." );
	}

	File f = new File( homeDir, uri );
	if ( res == null && !f.exists())
		res = new Response( HTTP_NOTFOUND, MIME_PLAINTEXT,
			"Error 404, file not found." );

	// List the directory, if necessary
	if ( res == null && f.isDirectory())
	{
		// Browsers get confused without '/' after the
		// directory, send a redirect.
		if ( !uri.endsWith( "/" ))
		{
			uri += "/";
			res = new Response( HTTP_REDIRECT, MIME_HTML,
				"<html><body>Redirected: <a href=\"" + uri + "\">" +
				uri + "</a></body></html>");
			res.addHeader( "Location", uri );
		}

		if ( res == null )
		{
			// First try index.html and index.htm
			if ( new File( f, "index.html" ).exists())
				f = new File( homeDir, uri + "/index.html" );
			else if ( new File( f, "index.htm" ).exists())
				f = new File( homeDir, uri + "/index.htm" );
			// No index file, list the directory if it is readable
			else if ( allowDirectoryListing && f.canRead() )
			{
				Hashtable<String, Hashtable<String, String>> styles = new Hashtable<String, Hashtable<String, String>>();
				Hashtable<String, String> style;
				
				style = new Hashtable<String, String>();
				style.put("background", "#150517");
				style.put("color", "#ffffff");
				style.put("face", "verdana");
				style.put("padding-top", "10px");
				styles.put(".localhttpd", style);
				
				String header_block = "<head><style>";
				for (Enumeration<String> e = styles.keys(); e.hasMoreElements();) {
				String key = (String) e.nextElement();
				Hashtable<?, ?> item = (Hashtable<?, ?>) styles.get(key);
				header_block += key + "{\n";
				for (Enumeration<?> e2 = item.keys(); e2.hasMoreElements();) {
				     String skey = (String) e2.nextElement();
				     header_block += skey + ":" + item.get(skey) + ";\n";
				}
				header_block += key + "}\n";
				}
				header_block += "</style>" +
								"<SCRIPT language=Javascript>"+
							       "function isEnglishKey(event)"+
							       "{"+
							       "var ew = event.which;"+
							       "if(ew == 32)return true;"+
							       "if(ew == 46)return true;"+
							       "if(48 <= ew && ew <= 57)return true;"+
							       "if(65 <= ew && ew <= 90)return true;"+
							       "if(97 <= ew && ew <= 122)return true;"+
							       "return false;"+
							       "}"+						       
					    		"</SCRIPT>"+
					    		"</head>";
				String[] files = f.list();
				String msg = "<html>" + header_block +                         		
			       		"<body class=\"localhttpd\">"+ 
			       	    "<div><div style=\"margin-left:20px\">"+
			       		"<table bgcolor=\"#41627E\" align=\"left\" border=\"0\">"+ 
			       		"<form action=\".\" method=\"post\" enctype=\"multipart/form-data\">"+  
			       		"<tr bgcolor=\"#A52A2A\" align=\"left\">"+				       		
			            "<th><input type=\"file\" name=\"sentFile\" size=\"40\" />" +
			            "<input type=\"submit\" name=\"submit\" value=\"Upload File\" /></th>"+
			            "</form>" + 
			            "<form method=\"get\">"+				           
			            "<th colspan=\"4\"><input type=\"text\" name=\"createFolder\" onkeypress=\"return isEnglishKey(event)\" />"+    
			            "<input type=\"submit\" value=\"New Folder\" /></th>" +
			            "</form>"+					          
				        "</tr>";		
			       if ( uri.length() > 1 )
			       {
			               String u = uri.substring( 0, uri.length()-1 );
			               int slash = u.lastIndexOf( '/' );
			               if ( slash >= 0 && slash  < u.length())
			            	   msg += "<tr bgcolor=\"#008000\" align=\"left\">";	
			                   msg += "<td colspan=\"4\"><b><a href=\"" + uri.substring(0, slash+1) +"\">";
			                   msg +="<font size=\"4\" face=\"verdana\" color=\"#FFFF00\">Back</font></a>&nbsp;&nbsp;&nbsp;"; 		                
			                   msg +="<font size=\"4\" face=\"verdana\" color=\"white\">";
			                   msg +="Directory: </font>";
			                   msg +="<font size=\"4\" face=\"verdana\" color=\"white\">";
			                   msg += uri + " -- "+ test+"</font></b></td>"; 
			                   msg +="</tr>";
			       }
			       msg +="<form method=\"get\"><tr bgcolor=\"#FFF000\" align=\"left\">";				      
			       msg +="<td colspan=\"4\"><font size=\"3\" face=\"verdana\">";
			       msg +="<input type=\"submit\" name=\"delete\" value=\"Delete Items\"/></font>" ;	
			       msg +="<input type=\"text\" name=\"renamefile\" onkeypress=\"return isEnglishKey(event)\" />";   
			       msg +="<input type=\"submit\" value=\"Rename\" />" ;
			       msg +="</td></tr>";					      
			       msg +="<tr bgcolor=\"#A52A2A\" align=\"left\">";
			       msg +="<th><font size=\"3\" face=\"verdana\" color=\"white\">Name</th>";		
			       msg +="<th><font size=\"3\" face=\"verdana\" color=\"white\">Size</th>";	
			       msg +="<th><font size=\"3\" face=\"verdana\" color=\"white\">Date</th>";	
			       msg +="<th><input type=\"checkbox\" name=\"chkallfile\"/></th>";
                   msg +="</tr>";	                  
			       msg +=listfolders(files, f,uri);
			       msg +=listfiles(files, f,uri);		
			       msg +="</form>"; 
			       msg += "</b>";
			       msg +="<tr bgcolor=\"#A52A2A\" align=\"left\">";
			       msg +="<th colspan=\"4\"><font size=\"2\" face=\"verdana\" color=\"white\">";					     
                   msg +="Wifi File Manager for android V1.0 by Turkay Biliyor</th></tr>";	                  
			       msg +="</table></div></div>";				        
				res = new Response( HTTP_OK, MIME_HTML, msg );
			}
			else
			{
				res = new Response( HTTP_FORBIDDEN, MIME_PLAINTEXT,
					"FORBIDDEN: No directory listing." );
			}
		}
	}

	try
	{
		if ( res == null )
		{
			// Get MIME type from file name extension, if possible
			String mime = null;
			int dot = f.getCanonicalPath().lastIndexOf( '.' );
			if ( dot >= 0 )
				mime = (String)theMimeTypes.get( f.getCanonicalPath().substring( dot + 1 ).toLowerCase());
			if ( mime == null )
				mime = MIME_DEFAULT_BINARY;

			// Calculate etag
			String etag = Integer.toHexString((f.getAbsolutePath() + f.lastModified() + "" + f.length()).hashCode());

			// Support (simple) skipping:
			long startFrom = 0;
			long endAt = -1;
			String range = header.getProperty( "range" );
			if ( range != null )
			{
				if ( range.startsWith( "bytes=" ))
				{
					range = range.substring( "bytes=".length());
					int minus = range.indexOf( '-' );
					try {
						if ( minus > 0 )
						{
							startFrom = Long.parseLong( range.substring( 0, minus ));
							endAt = Long.parseLong( range.substring( minus+1 ));
						}
					}
					catch ( NumberFormatException nfe ) {}
				}
			}

			// Change return code and add Content-Range header when skipping is requested
			long fileLen = f.length();
			if (range != null && startFrom >= 0)
			{
				if ( startFrom >= fileLen)
				{
					res = new Response( HTTP_RANGE_NOT_SATISFIABLE, MIME_PLAINTEXT, "" );
					res.addHeader( "Content-Range", "bytes 0-0/" + fileLen);
					res.addHeader( "ETag", etag);
				}
				else
				{
					if ( endAt < 0 )
						endAt = fileLen-1;
					long newLen = endAt - startFrom + 1;
					if ( newLen < 0 ) newLen = 0;

					final long dataLen = newLen;
					FileInputStream fis = new FileInputStream( f ) {
						public int available() throws IOException { return (int)dataLen; }
					};
					fis.skip( startFrom );

					res = new Response( HTTP_PARTIALCONTENT, mime, fis );
					res.addHeader( "Content-Length", "" + dataLen);
					res.addHeader( "Content-Range", "bytes " + startFrom + "-" + endAt + "/" + fileLen);
					res.addHeader( "ETag", etag);
				}
			}
			else
			{
				res = new Response( HTTP_OK, mime, new FileInputStream( f ));
				res.addHeader( "Content-Length", "" + fileLen);
				res.addHeader( "ETag", etag);
			}
		}
	}
	catch( IOException ioe )
	{
		res = new Response( HTTP_FORBIDDEN, MIME_PLAINTEXT, "FORBIDDEN: Reading file failed." );
	}

	res.addHeader( "Accept-Ranges", "bytes"); // Announce that the file server accepts partial content requestes
	return res;
}
 
Example 86
Project: java-thumbnailer   File: DWGThumbnailer.java View source code 5 votes vote down vote up
public void generateThumbnail(File input, File output) throws IOException, de.uni_siegen.wineme.come_in.thumbnailer.ThumbnailerException {
	//GENERATE FROM EXISTING BITMAP IN DWG
	byte[] outputByte = new byte[4096];
	
	FileInputStream fis = null;
	
	try {
		fis = new FileInputStream(input);
		fis.skip(0x0D);
		fis.read(outputByte, 0, 4);
		int PosSentinel = (((outputByte[3])&0xFF)*256*256*256)+(((outputByte[2])&0xFF)*256*256)+(((outputByte[1])&0xFF)*256)+((outputByte[0])&0xFF);
		fis.skip(PosSentinel-0x0D-4+30);
		outputByte[1]=0;
		fis.read(outputByte, 0, 1);
		int TypePreview = ((outputByte[0])&0xFF);
		if (TypePreview==2) {
			fis.read(outputByte, 0, 4);
			int PosBMP = (((outputByte[3])&0xFF)*256*256*256)+(((outputByte[2])&0xFF)*256*256)+(((outputByte[1])&0xFF)*256)+((outputByte[0])&0xFF);
			fis.read(outputByte, 0, 4);
			int LenBMP = (((outputByte[3])&0xFF)*256*256*256)+(((outputByte[2])&0xFF)*256*256)+(((outputByte[1])&0xFF)*256)+((outputByte[0])&0xFF);
			fis.skip(PosBMP-(PosSentinel+30)-1-4-4+14);
			fis.read(outputByte, 0, 2);
			int biBitCount = (((outputByte[1])&0xFF)*256)+((outputByte[0])&0xFF);
			fis.skip(-16);
			int bisSize=0;
			int bfSize = 0;
			if (biBitCount<9)
				bfSize = 54 + 4 * ((int) (Math.pow(2,biBitCount))) + LenBMP ;
			else bfSize = 54 + LenBMP ;
			//WORD "BM"
			outputByte[0]=0x42;outputByte[1]=0x4D;
			//DWORD bfSize
			outputByte[2]=(byte)(bfSize&0xff);outputByte[3]=(byte)(bfSize>>8&0xff);
			outputByte[4]=(byte)(bfSize>>16&0xff);outputByte[5]=(byte)(bfSize>>>24);
			//WORD bfReserved1
			outputByte[6]=0x00;outputByte[7]=0x00;
			//WORD bfReserved2
			outputByte[8]=0x00;outputByte[9]=0x00;
			//DWORD bfOffBits
			outputByte[10]=0x36;outputByte[11]=0x04;outputByte[12]=0x00;outputByte[13]=0x00;

			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			baos.write(outputByte,0,14);
			while((LenBMP>0) && ((bisSize=fis.read(outputByte, 0, (LenBMP>4096?4096:LenBMP))) != -1)) {
				baos.write(outputByte, 0, bisSize);
				LenBMP-=bisSize;
			}
			
			ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());

			BufferedImage originalImage = ImageIO.read(bais);
			
			ResizeImage resizer = new ResizeImage(thumbWidth, thumbHeight);
			resizer.setInputImage(originalImage);
			resizer.writeOutput(output);
		}
	} finally {
		IOUtil.quietlyClose(fis);
	}
}
 
Example 87
Project: Fling   File: HttpServer.java View source code 5 votes vote down vote up
/**
 * Serves file from homeDir and its' subdirectories (only). Uses only URI,
 * ignores all headers and HTTP parameters.
 */
public Response serveFile(String uri, Properties header, File homeDir,
		boolean allowDirectoryListing) {
	Response res = null;

	// Make sure we won't die of an exception later
	if (!homeDir.isDirectory())
		res = new Response(HTTP_INTERNALERROR, MIME_PLAINTEXT,
				"INTERNAL ERRROR: serveFile(): given homeDir is not a directory.");

	if (res == null) {
		// Remove URL arguments
		uri = uri.trim().replace(File.separatorChar, '/');
		if (uri.indexOf('?') >= 0)
			uri = uri.substring(0, uri.indexOf('?'));

		// Prohibit getting out of current directory
		if (uri.startsWith("..") || uri.endsWith("..")
				|| uri.indexOf("../") >= 0)
			res = new Response(HTTP_FORBIDDEN, MIME_PLAINTEXT,
					"FORBIDDEN: Won't serve ../ for security reasons.");
	}

	File f = new File(homeDir, uri);
	if (res == null && !f.exists())
		res = new Response(HTTP_NOTFOUND, MIME_PLAINTEXT,
				"Error 404, file not found.");

	// List the directory, if necessary
	if (res == null && f.isDirectory()) {
		// Browsers get confused without '/' after the
		// directory, send a redirect.
		if (!uri.endsWith("/")) {
			uri += "/";
			res = new Response(HTTP_REDIRECT, MIME_HTML,
					"<html><body>Redirected: <a href=\"" + uri + "\">"
							+ uri + "</a></body></html>");
			res.addHeader("Location", uri);
		}

		if (res == null) {
			// First try index.html and index.htm
			if (new File(f, "index.html").exists())
				f = new File(homeDir, uri + "/index.html");
			else if (new File(f, "index.htm").exists())
				f = new File(homeDir, uri + "/index.htm");
			// No index file, list the directory if it is readable
			else if (allowDirectoryListing && f.canRead()) {
				String[] files = f.list();
				String msg = "<html><body><h1>Directory " + uri
						+ "</h1><br/>";

				if (uri.length() > 1) {
					String u = uri.substring(0, uri.length() - 1);
					int slash = u.lastIndexOf('/');
					if (slash >= 0 && slash < u.length())
						msg += "<b><a href=\""
								+ uri.substring(0, slash + 1)
								+ "\">..</a></b><br/>";
				}

				if (files != null) {
					for (int i = 0; i < files.length; ++i) {
						File curFile = new File(f, files[i]);
						boolean dir = curFile.isDirectory();
						if (dir) {
							msg += "<b>";
							files[i] += "/";
						}

						msg += "<a href=\"" + encodeUri(uri + files[i])
								+ "\">" + files[i] + "</a>";

						// Show file size
						if (curFile.isFile()) {
							long len = curFile.length();
							msg += " &nbsp;<font size=2>(";
							if (len < 1024)
								msg += len + " bytes";
							else if (len < 1024 * 1024)
								msg += len / 1024 + "."
										+ (len % 1024 / 10 % 100) + " KB";
							else
								msg += len / (1024 * 1024) + "." + len
										% (1024 * 1024) / 10 % 100 + " MB";

							msg += ")</font>";
						}
						msg += "<br/>";
						if (dir)
							msg += "</b>";
					}
				}
				msg += "</body></html>";
				res = new Response(HTTP_OK, MIME_HTML, msg);
			} else {
				res = new Response(HTTP_FORBIDDEN, MIME_PLAINTEXT,
						"FORBIDDEN: No directory listing.");
			}
		}
	}

	try {
		if (res == null) {
			// Get MIME type from file name extension, if possible
			String mime = null;
			int dot = f.getCanonicalPath().lastIndexOf('.');
			if (dot >= 0)
				mime = (String) theMimeTypes.get(f.getCanonicalPath()
						.substring(dot + 1).toLowerCase());
			if (mime == null)
				mime = MIME_DEFAULT_BINARY;

			// Support (simple) skipping:
			long startFrom = 0;
			long endAt = -1;
			String range = header.getProperty("range");
			if (range != null) {
				if (range.startsWith("bytes=")) {
					range = range.substring("bytes=".length());
					int minus = range.indexOf('-');
					try {
						if (minus > 0) {
							startFrom = Long.parseLong(range.substring(0,
									minus));
							endAt = Long.parseLong(range
									.substring(minus + 1));
						}
					} catch (NumberFormatException nfe) {
					}
				}
			}

			// Change return code and add Content-Range header when skipping
			// is requested
			long fileLen = f.length();
			if (range != null && startFrom >= 0) {
				if (startFrom >= fileLen) {
					res = new Response(HTTP_RANGE_NOT_SATISFIABLE,
							MIME_PLAINTEXT, "");
					res.addHeader("Content-Range", "bytes 0-0/" + fileLen);
				} else {
					if (endAt < 0)
						endAt = fileLen - 1;
					long newLen = endAt - startFrom + 1;
					if (newLen < 0)
						newLen = 0;

					final long dataLen = newLen;
					FileInputStream fis = new FileInputStream(f) {
						public int available() throws IOException {
							return (int) dataLen;
						}
					};
					fis.skip(startFrom);

					res = new Response(HTTP_PARTIALCONTENT, mime, fis);
					res.addHeader("Content-Length", "" + dataLen);
					res.addHeader("Content-Range", "bytes " + startFrom
							+ "-" + endAt + "/" + fileLen);
				}
			} else {
				res = new Response(HTTP_OK, mime, new FileInputStream(f));
				res.addHeader("Content-Length", "" + fileLen);
			}
		}
	} catch (IOException ioe) {
		res = new Response(HTTP_FORBIDDEN, MIME_PLAINTEXT,
				"FORBIDDEN: Reading file failed.");
	}

	res.addHeader("Accept-Ranges", "bytes"); // Announce that the file
												// server accepts partial
												// content requestes
	return res;
}
 
Example 88
Project: yarn-comment   File: TestConcatenatedCompressedInput.java View source code 5 votes vote down vote up
/**
 * Test using the raw Inflater codec for reading gzip files.
 */
@Test
public void testPrototypeInflaterGzip() throws IOException {
  CompressionCodec gzip = new GzipCodec();  // used only for file extension
  localFs.delete(workDir, true);            // localFs = FileSystem instance

  System.out.println(COLOR_BR_BLUE + "testPrototypeInflaterGzip() using " +
    "non-native/Java Inflater and manual gzip header/trailer parsing" +
    COLOR_NORMAL);

  // copy prebuilt (correct!) version of concat.gz to HDFS
  final String fn = "concat" + gzip.getDefaultExtension();
  Path fnLocal = new Path(System.getProperty("test.concat.data", "/tmp"), fn);
  Path fnHDFS  = new Path(workDir, fn);
  localFs.copyFromLocalFile(fnLocal, fnHDFS);

  final FileInputStream in = new FileInputStream(fnLocal.toString());
  assertEquals("concat bytes available", 148, in.available());

  // should wrap all of this header-reading stuff in a running-CRC wrapper
  // (did so in BuiltInGzipDecompressor; see below)

  byte[] compressedBuf = new byte[256];
  int numBytesRead = in.read(compressedBuf, 0, 10);
  assertEquals("header bytes read", 10, numBytesRead);
  assertEquals("1st byte", 0x1f, compressedBuf[0] & 0xff);
  assertEquals("2nd byte", 0x8b, compressedBuf[1] & 0xff);
  assertEquals("3rd byte (compression method)", 8, compressedBuf[2] & 0xff);

  byte flags = (byte)(compressedBuf[3] & 0xff);
  if ((flags & 0x04) != 0) {   // FEXTRA
    numBytesRead = in.read(compressedBuf, 0, 2);
    assertEquals("XLEN bytes read", 2, numBytesRead);
    int xlen = ((compressedBuf[1] << 8) | compressedBuf[0]) & 0xffff;
    in.skip(xlen);
  }
  if ((flags & 0x08) != 0) {   // FNAME
    while ((numBytesRead = in.read()) != 0) {
      assertFalse("unexpected end-of-file while reading filename",
                  numBytesRead == -1);
    }
  }
  if ((flags & 0x10) != 0) {   // FCOMMENT
    while ((numBytesRead = in.read()) != 0) {
      assertFalse("unexpected end-of-file while reading comment",
                  numBytesRead == -1);
    }
  }
  if ((flags & 0xe0) != 0) {   // reserved
    assertTrue("reserved bits are set??", (flags & 0xe0) == 0);
  }
  if ((flags & 0x02) != 0) {   // FHCRC
    numBytesRead = in.read(compressedBuf, 0, 2);
    assertEquals("CRC16 bytes read", 2, numBytesRead);
    int crc16 = ((compressedBuf[1] << 8) | compressedBuf[0]) & 0xffff;
  }

  // ready to go!  next bytes should be start of deflated stream, suitable
  // for Inflater
  numBytesRead = in.read(compressedBuf);

  // Inflater docs refer to a "dummy byte":  no clue what that's about;
  // appears to work fine without one
  byte[] uncompressedBuf = new byte[256];
  Inflater inflater = new Inflater(true);

  inflater.setInput(compressedBuf, 0, numBytesRead);
  try {
    int numBytesUncompressed = inflater.inflate(uncompressedBuf);
    String outString =
      new String(uncompressedBuf, 0, numBytesUncompressed, "UTF-8");
    System.out.println("uncompressed data of first gzip member = [" +
                       outString + "]");
  } catch (java.util.zip.DataFormatException ex) {
    throw new IOException(ex.getMessage());
  }

  in.close();
}