Java Code Examples for java.io.InputStream#close()

The following examples show how to use java.io.InputStream#close() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
public void setup() throws UserStoreException {

        try {
            RealmConfigXMLProcessor builder = new RealmConfigXMLProcessor();
            InputStream inStream = this.getClass().getResourceAsStream("/users/user-mgt-users.xml");

            try {
                this.bootstrapRealmConfig = builder.buildRealmConfiguration(inStream);
            } finally {
                inStream.close();
            }
        } catch (Exception e) {
            String msg = "Failed to initialize the user manager. ";
            throw new UserStoreException(msg, e);
        }

        this.tenantManager = new InMemoryTenantManager();
    }
 
Example 2
Source Project: olat   File: DefaultServlet.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are closed before returning (even in the face of an
 * exception).
 * 
 * @param istream
 *            The input stream to read from
 * @param ostream
 *            The output stream to write to
 * @exception IOException
 *                if an input/output error occurs
 */
private void copy(ResourceInfo resourceInfo, ServletOutputStream ostream) throws IOException {

    IOException exception = null;

    // FIXME:ms: i18n ?
    InputStream resourceInputStream = resourceInfo.getStream();
    InputStream istream = new BufferedInputStream(resourceInputStream, input);

    // Copy the input stream to the output stream
    exception = copyRange(istream, ostream);

    // Clean up the input stream
    try {
        istream.close();
    } catch (Throwable t) {

    }

    // Rethrow any exception that has occurred
    if (exception != null)
        throw exception;

}
 
Example 3
Source Project: Cubert   File: AvroStorage.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This method is called to return the schema of an avro schema file. This
 * method is different than {@link #getSchema}, which returns the schema
 * from a data file.
 *
 * @param path  path of a file or first level directory
 * @param fs  file system
 * @return avro schema
 * @throws IOException
 */
protected Schema getSchemaFromFile(Path path, FileSystem fs) throws IOException {
    /* get path of the last file */
    Path lastFile = AvroStorageUtils.getLast(path, fs);
    if (lastFile == null) {
        return null;
    }

    /* read in file and obtain schema */
    GenericDatumReader<Object> avroReader = new GenericDatumReader<Object>();
    InputStream hdfsInputStream = fs.open(lastFile);
    Schema ret = Schema.parse(hdfsInputStream);
    hdfsInputStream.close();

    return ret;
}
 
Example 4
Source Project: cloud-espm-v2   File: StreamHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Read File content
 * 
 * @param fileName
 * @return file content as String
 * @throws IOException
 */
public static String readFromFile(String fileName) {
	InputStream in = null;
	String result = null;
	ClassLoader cLoader = RequestExecutionHelper.class.getClassLoader();
	if (cLoader != null) {
		try {
			in = cLoader.getResourceAsStream(fileName);
			result = StreamHelper.readStreamContent(in);

		} catch (IOException ex) {
			LOGGER.error(ex.getMessage());
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				LOGGER.error(e.getMessage());

			}
		}

	}
	return result;

}
 
Example 5
static byte[] readBytes(final InputStream is) throws IOException {
    final byte[] arr = new byte[BUF_SIZE];
    try {
        try (ByteArrayOutputStream buf = new ByteArrayOutputStream()) {
            int numBytes;
            while ((numBytes = is.read(arr, 0, arr.length)) > 0) {
                buf.write(arr, 0, numBytes);
            }
            return buf.toByteArray();
        }
    } finally {
        is.close();
    }
}
 
Example 6
Source Project: hadoop   File: CryptoStreamsTestBase.java    License: Apache License 2.0 5 votes vote down vote up
private void cryptoCheck(byte[] iv) throws Exception {
  OutputStream out = getOutputStream(defaultBufferSize, key, iv);
  writeData(out);
  
  InputStream in = getInputStream(defaultBufferSize, key, iv);
  readCheck(in);
  in.close();
}
 
Example 7
public static boolean downloadFile(String uri, File file){
    HTTPSTrustManager.allowAllSSL();
    try {
        URL url = new URL(uri);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "text/html, application/xhtml+xml, image/jxr, */*");
        conn.setRequestProperty("Accept-Encoding", "identity");
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");

        int code = conn.getResponseCode();
        if (code == 200) {
            InputStream instream = conn.getInputStream();
            FileOutputStream fos = new FileOutputStream(file);
            try {
                byte[] tmp = new byte[4096];

                int l;
                while((l = instream.read(tmp)) != -1) {
                    fos.write(tmp, 0, l);
                }
                return true;
            } finally {
                instream.close();
                fos.close();
            }
        } else {
            return false;
        }
    } catch (Exception e) {
        Log.e("HTTPGet", "downloadFile", e);
    }
    return false;
}
 
Example 8
Source Project: jobcacher-plugin   File: Uploads.java    License: MIT License 5 votes vote down vote up
private void closeStream(File file, InputStream inputStream) {
    try {
        if (inputStream != null) {
            inputStream.close();
        }
    } catch (IOException e) {
        LOGGER.warning("Failed to close stream for file:" + file);
    }
}
 
Example 9
private void safeClose(InputStream fis)
{
   try
   {
      if(fis != null)
      {
         fis.close();
      }
   }
   catch(Exception e)
   {}
}
 
Example 10
Source Project: justtestlah   File: LocatorPlaceholders.java    License: Apache License 2.0 5 votes vote down vote up
private Properties loadProperties(InputStream input) {
  Properties props = new Properties();
  if (input == null) {
    LOG.warn("Could not load placeholders");
    return props;
  }
  try {
    props.load(input);
    input.close();
  } catch (IOException exception) {
    LOG.warn("Could not load placeholders");
  }
  return props;
}
 
Example 11
/**
 * Closes input stream regardless of thrown exception
 */
public static void closeHard(final InputStream is) {

   if (is != null) {
      try {
         is.close();
      } catch (final IOException e) {
         logCloseWarning(e);
      }
   }
}
 
Example 12
@Override
public Object load(AssetInfo info) throws IOException {
    assetManager = info.getManager();
    InputStream in = info.openStream();
    try {
        return load(in);
    } finally {
        if (in != null)
            in.close();
    }
}
 
Example 13
Source Project: jparsec   File: IoUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static String read(URL url) throws IOException {
  InputStream in = url.openStream();
  try {
    return read(new InputStreamReader(in, Charset.forName("UTF-8")));
  } finally {
    in.close();
  }
}
 
Example 14
Source Project: gemfirexd-oss   File: QueryPerfClient.java    License: Apache License 2.0 5 votes vote down vote up
public static byte[] getBytesFromFile(File file) throws IOException {
  InputStream is = new FileInputStream(file);

  // Get the size of the file
  long length = file.length();
  if (length > Integer.MAX_VALUE)
    throw new TestException("input file is too long");

  byte[] bytes = new byte[(int)length];

  // Read in the bytes
  int offset = 0;
  int numRead = 0;
  while (offset < bytes.length
         && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
      offset += numRead;
  }

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

  // Close the input stream and return bytes
  is.close();
  return bytes;
}
 
Example 15
Source Project: ermasterr   File: IOUtils.java    License: Apache License 2.0 4 votes vote down vote up
public static void closeQuietly(final InputStream input) {
    try {
        if (input != null)
            input.close();
    } catch (final IOException ioe) {}
}
 
Example 16
@SuppressWarnings( "unchecked" )
private RowMetaAndData[] doScan( IProgressMonitor monitor ) throws Exception {
  monitor.beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.ScanningFile",
      filename ), 1 );

  SAXReader reader = XmlParserFactoryProducer.getSAXReader( null );
  monitor.worked( 1 );
  if ( monitor.isCanceled() ) {
    return null;
  }
  // Validate XML against specified schema?
  if ( meta.isValidating() ) {
    reader.setValidation( true );
    reader.setFeature( "http://apache.org/xml/features/validation/schema", true );
  } else {
    // Ignore DTD
    reader.setEntityResolver( new IgnoreDtdEntityResolver() );
  }
  monitor.worked( 1 );
  monitor
      .beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.ReadingDocument" ), 1 );
  if ( monitor.isCanceled() ) {
    return null;
  }
  InputStream is = null;
  try {

    Document document = null;
    if ( !Utils.isEmpty( filename ) ) {
      is = HopVfs.getInputStream( filename );
      document = reader.read( is, encoding );
    } else {
      if ( !Utils.isEmpty( xml ) ) {
        document = reader.read( new StringReader( xml ) );
      } else {
        document = reader.read( new URL( url ) );
      }
    }

    monitor.worked( 1 );
    monitor.beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.DocumentOpened" ),
        1 );
    monitor.worked( 1 );
    monitor.beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.ReadingNode" ), 1 );

    if ( monitor.isCanceled() ) {
      return null;
    }
    List<Node> nodes = document.selectNodes( this.loopXPath );
    monitor.worked( 1 );
    monitor.subTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.FetchNodes" ) );

    if ( monitor.isCanceled() ) {
      return null;
    }
    for ( Node node : nodes ) {
      if ( monitor.isCanceled() ) {
        return null;
      }

      nr++;
      monitor.subTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.FetchNodes", String
          .valueOf( nr ) ) );
      monitor.subTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.FetchNodes", node
          .getPath() ) );
      setNodeField( node, monitor );
      childNode( node, monitor );

    }
    monitor.worked( 1 );
  } finally {
    try {
      if ( is != null ) {
        is.close();
      }
    } catch ( Exception e ) { /* Ignore */
    }
  }

  RowMetaAndData[] listFields = fieldsList.toArray( new RowMetaAndData[fieldsList.size()] );

  monitor.setTaskName( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.NodesReturned" ) );

  monitor.done();

  return listFields;

}
 
Example 17
Source Project: cuba   File: CubaWebJarsHandler.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public boolean handleRequest(VaadinSession session, VaadinRequest request, VaadinResponse response) throws IOException {
    String path = request.getPathInfo();
    if (StringUtils.isEmpty(path)
            || !path.startsWith(VAADIN_WEBJARS_PATH_PREFIX)) {
        return false;
    }

    log.trace("WebJar resource requested: {}", path.replace(VAADIN_WEBJARS_PATH_PREFIX, ""));

    String errorMessage = checkResourcePath(path);
    if (StringUtils.isNotEmpty(errorMessage)) {
        log.warn(errorMessage);
        response.sendError(HttpServletResponse.SC_FORBIDDEN, errorMessage);
        return false;
    }

    URL resourceUrl = getStaticResourceUrl(path);

    if (resourceUrl == null) {
        resourceUrl = getClassPathResourceUrl(path);
    }

    if (resourceUrl == null) {
        String msg = String.format("Requested WebJar resource is not found: %s", path);
        response.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
        log.warn(msg);
        return false;
    }

    String resourceName = getResourceName(path);
    String mimeType = servletContext.getMimeType(resourceName);
    response.setContentType(mimeType != null ? mimeType : FileTypesHelper.DEFAULT_MIME_TYPE);

    long resourceCacheTime = getCacheTime();

    String cacheControl = resourceCacheTime > 0
            ? "max-age=" + String.valueOf(resourceCacheTime)
            : "public, max-age=0, no-cache, no-store, must-revalidate";
    response.setHeader("Cache-Control", cacheControl);

    long expires = resourceCacheTime > 0
            ? System.currentTimeMillis() + (resourceCacheTime * 1000)
            : 0;
    response.setDateHeader("Expires", expires);

    InputStream inputStream = null;
    try {
        URLConnection connection = resourceUrl.openConnection();
        long lastModifiedTime = connection.getLastModified();
        // Remove milliseconds to avoid comparison problems (milliseconds
        // are not returned by the browser in the "If-Modified-Since"
        // header).
        lastModifiedTime = lastModifiedTime - lastModifiedTime % 1000;
        response.setDateHeader("Last-Modified", lastModifiedTime);

        if (browserHasNewestVersion(request, lastModifiedTime)) {
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            return true;
        }

        inputStream = connection.getInputStream();

        copy(inputStream, response.getOutputStream());

        return true;
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }
}
 
Example 18
Source Project: gemfirexd-oss   File: LobStreamsTest.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Tests the ClobOutputStream.write(byte  b[], int off, int len) method
 **/
public void testClobAsciiWrite3Param() throws Exception {
    InputStream streamIn = new LoopingAlphabetStream(streamSize[0]);
    assertTrue("FAIL -- file not found", streamIn != null);

    PreparedStatement stmt3 = prepareStatement(
        "SELECT c FROM testBlobX1 WHERE a = 1");
    ResultSet rs3 = stmt3.executeQuery();
    rs3.next();
    Clob clob = rs3.getClob(1);

    assertTrue("FAIL -- clob is NULL", clob != null);

    int count = 0;
    byte[] buffer = new byte[1024];
    OutputStream outstream = clob.setAsciiStream(1L);
    while ((count = streamIn.read(buffer)) != -1) {
        outstream.write(buffer, 0, count);
    }
    outstream.close();
    streamIn.close();

    PreparedStatement stmt4 = prepareStatement(
        "UPDATE testBlobX1 SET c = ? WHERE a = 1");
    stmt4.setClob(1,  clob);
    stmt4.executeUpdate();
    stmt4.close();

    rs3.close();
    rs3 = stmt3.executeQuery();

    assertTrue("FAIL -- clob not found", rs3.next());

    long new_length = rs3.getClob(1).length();
    assertEquals("FAIL -- wrong clob length",
            streamSize[0], new_length);
    // Check contents ...
    InputStream fStream = new LoopingAlphabetStream(streamSize[0]);
    InputStream lStream = rs3.getClob(1).getAsciiStream();
    assertTrue("FAIL - Clob and file contents do not match",
            compareLob2File(fStream, lStream));

    fStream.close();
    lStream.close();
    rs3.close();
    stmt3.close();
}
 
Example 19
protected ClientConfiguration(String resourceName) {
  this.resourceName = resourceName;

  Properties props = new Properties();
  InputStream is = getClass().getClassLoader().getResourceAsStream(
      resourceName);
  if (is == null) {
    is = ClassLoader.getSystemResourceAsStream(resourceName);
  }
  if (is == null) {
    this.error = "<Could not find resource " + resourceName + '>';
    return;
  }
  else {
    try {
      props.load(is);
      is.close();
    } catch (Exception ex) {
      this.error = "<Could not read properties from resource "
          + resourceName + " because: " + ex + '>';
      return;
    }
  }

  this.productName = props.getProperty(PRODUCT_NAME);
  this.productVersion = props.getProperty(GEMFIRE_VERSION);
  // below setting for GemFireXD is to indicate the underlying GemFire
  // version being used in GemFireXD product; for GemFire this will not
  // be set and instead this.productVersion is used where required
  String gfVersion = props.getProperty(UNDERLYING_GEMFIRE_VERSION);
  // special token "NOT SET" might be present that indicates no separate
  // GemFire version
  if (gfVersion != null && gfVersion.startsWith("NOT SET")) {
    gfVersion = null;
  }
  this.gemfireVersion = gfVersion;

  this.sourceDate = props.getProperty(SOURCE_DATE);
  this.sourceRevision = props.getProperty(SOURCE_REVISION);
  this.sourceRepository = props.getProperty(SOURCE_REPOSITORY);
  this.buildDate = props.getProperty(BUILD_DATE);
  this.buildId = props.getProperty(BUILD_ID);
  this.buildPlatform = props.getProperty(BUILD_PLATFORM);
  this.buildJavaVersion = props.getProperty(BUILD_JAVA_VERSION);
}
 
Example 20
/**
 * Loads all of the properties represented by the XML document on the
 * specified input stream into this properties table.
 *
 * <p>The XML document must have the following DOCTYPE declaration:
 * <pre>
 * &lt;!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"&gt;
 * </pre>
 * Furthermore, the document must satisfy the properties DTD described
 * above.
 *
 * <p> An implementation is required to read XML documents that use the
 * "{@code UTF-8}" or "{@code UTF-16}" encoding. An implementation may
 * support additional encodings.
 *
 * <p>The specified stream is closed after this method returns.
 *
 * @param in the input stream from which to read the XML document.
 * @throws IOException if reading from the specified input stream
 *         results in an <tt>IOException</tt>.
 * @throws java.io.UnsupportedEncodingException if the document's encoding
 *         declaration can be read and it specifies an encoding that is not
 *         supported
 * @throws InvalidPropertiesFormatException Data on input stream does not
 *         constitute a valid XML document with the mandated document type.
 * @throws NullPointerException if {@code in} is null.
 * @see    #storeToXML(OutputStream, String, String)
 * @see    <a href="http://www.w3.org/TR/REC-xml/#charencoding">Character
 *         Encoding in Entities</a>
 * @since 1.5
 */
public synchronized void loadFromXML(InputStream in)
    throws IOException, InvalidPropertiesFormatException
{
    XmlSupport.load(this, Objects.requireNonNull(in));
    in.close();
}