Example usage for org.apache.cassandra.io.util FileUtils closeQuietly

List of usage examples for org.apache.cassandra.io.util FileUtils closeQuietly

Introduction

In this page you can find the example usage for org.apache.cassandra.io.util FileUtils closeQuietly.

Prototype

public static void closeQuietly(Iterable<? extends AutoCloseable> cs) 

Source Link

Usage

From source file:brooklyn.entity.nosql.cassandra.customsnitch.MultiCloudSnitch.java

License:Apache License

public void reloadConfiguration() throws ConfigurationException {
    HashMap<InetAddress, String[]> reloadedMap = new HashMap<InetAddress, String[]>();
    String DC_PROPERTY = "dc";
    String RACK_PROPERTY = "rack";
    String PUBLIC_IP_PROPERTY = "publicip";
    String PRIVATE_IP_PROPERTY = "privateip";

    Properties properties = new Properties();
    InputStream stream = null;//from  w w  w.  jav a2 s .  c  o  m
    try {
        stream = getClass().getClassLoader().getResourceAsStream(SNITCH_PROPERTIES_FILENAME);
        properties.load(stream);
    } catch (Exception e) {
        throw new ConfigurationException("Unable to read " + SNITCH_PROPERTIES_FILENAME, e);
    } finally {
        FileUtils.closeQuietly(stream);
    }

    datacenter = properties.getProperty(DC_PROPERTY);
    rack = properties.getProperty(RACK_PROPERTY);
    private_ip = checkNotNull(properties.getProperty(PRIVATE_IP_PROPERTY), "%s in %s", PRIVATE_IP_PROPERTY,
            SNITCH_PROPERTIES_FILENAME);
    String public_ip_str = checkNotNull(properties.getProperty(PUBLIC_IP_PROPERTY), "%s in %s",
            PUBLIC_IP_PROPERTY, SNITCH_PROPERTIES_FILENAME);
    try {
        public_ip = InetAddress.getByName(public_ip_str);
    } catch (UnknownHostException e) {
        throw new ConfigurationException("Unknown host " + public_ip_str, e);
    }

    logger.debug("CustomSnitch reloaded, using datacenter: " + datacenter + ", rack: " + rack + ", publicip: "
            + public_ip + ", privateip: " + private_ip);

    if (StorageService.instance != null) // null check tolerates circular dependency; see CASSANDRA-4145
        StorageService.instance.getTokenMetadata().invalidateCaches();

    if (gossipStarted)
        StorageService.instance.gossipSnitchInfo();
}

From source file:c3.ops.priam.cli.StaticMembership.java

License:Apache License

public StaticMembership() throws IOException {
    Properties config = new Properties();
    FileInputStream fis = null;//ww  w . j a  v  a  2s  . co m
    try {
        fis = new FileInputStream(DEFAULT_PROP_PATH);
        config.load(fis);
    } catch (Exception e) {
        logger.error("Exception with static membership file ", e);
        throw new RuntimeException("Problem reading static membership file. Cannot start.", e);
    } finally {
        FileUtils.closeQuietly(fis);
    }
    racName = config.getProperty(RAC_NAME);
    racCount = 0;
    for (String name : config.stringPropertyNames()) {
        if (name.startsWith(INSTANCES_PRE)) {
            racCount += 1;
            if (name == INSTANCES_PRE + racName)
                racMembership = Arrays.asList(config.getProperty(name).split(","));
        }
    }
}

From source file:c3.ops.priam.defaultimpl.ClearCredential.java

License:Apache License

public ClearCredential() {
    FileInputStream fis = null;//from www . java 2 s  .  co  m
    try {
        fis = new FileInputStream(CRED_FILE);
        final Properties props = new Properties();
        props.load(fis);
        AWS_ACCESS_ID = props.getProperty("AWSACCESSID") != null ? props.getProperty("AWSACCESSID").trim() : "";
        AWS_KEY = props.getProperty("AWSKEY") != null ? props.getProperty("AWSKEY").trim() : "";
    } catch (Exception e) {
        logger.error("Exception with credential file ", e);
        throw new RuntimeException("Problem reading credential file. Cannot start.", e);
    } finally {
        FileUtils.closeQuietly(fis);
    }
}

From source file:com.datastax.brisk.BriskServer.java

License:Apache License

/**
 * Retrieves a local subBlock/*from   ww  w. j a va  2 s .c o m*/
 * 
 * @param blockId row key
 * @param sblockId SubBlock column name
 * @param offset inside the sblock
 * @return a local sublock
 * @throws TException
 */
private LocalBlock getLocalSubBlock(String subBlockCFName, ByteBuffer blockId, ByteBuffer sblockId, int offset)
        throws TException {
    DecoratedKey<Token<?>> decoratedKey = new DecoratedKey<Token<?>>(
            StorageService.getPartitioner().getToken(blockId), blockId);

    Table table = Table.open(cfsKeyspace);
    ColumnFamilyStore sblockStore = table.getColumnFamilyStore(subBlockCFName);

    Collection<SSTableReader> sstables = sblockStore.getSSTables();

    for (SSTableReader sstable : sstables) {

        long position = sstable.getPosition(decoratedKey, Operator.EQ);

        if (position == -1)
            continue;

        String filename = sstable.descriptor.filenameFor(Component.DATA);
        RandomAccessFile raf = null;
        int mappedLength = -1;
        MappedByteBuffer mappedData = null;
        MappedFileDataInput file = null;
        try {
            raf = new RandomAccessFile(filename, "r");
            assert position < raf.length();

            mappedLength = (raf.length() - position) < Integer.MAX_VALUE ? (int) (raf.length() - position)
                    : Integer.MAX_VALUE;

            mappedData = raf.getChannel().map(FileChannel.MapMode.READ_ONLY, position, mappedLength);

            file = new MappedFileDataInput(mappedData, filename, 0);

            if (file == null)
                continue;

            //Verify key was found in data file
            DecoratedKey keyInDisk = SSTableReader.decodeKey(sstable.partitioner, sstable.descriptor,
                    ByteBufferUtil.readWithShortLength(file));
            assert keyInDisk.equals(decoratedKey) : String.format("%s != %s in %s", keyInDisk, decoratedKey,
                    file.getPath());

            long rowSize = SSTableReader.readRowSize(file, sstable.descriptor);

            assert rowSize > 0;
            assert rowSize < mappedLength;

            Filter bf = IndexHelper.defreezeBloomFilter(file, sstable.descriptor.usesOldBloomFilter);

            //verify this column in in this version of the row.
            if (!bf.isPresent(sblockId))
                continue;

            List<IndexHelper.IndexInfo> indexList = IndexHelper.deserializeIndex(file);

            // we can stop early if bloom filter says none of the
            // columns actually exist -- but,
            // we can't stop before initializing the cf above, in
            // case there's a relevant tombstone
            ColumnFamilySerializer serializer = ColumnFamily.serializer();
            try {
                ColumnFamily cf = serializer
                        .deserializeFromSSTableNoColumns(ColumnFamily.create(sstable.metadata), file);

                if (cf.isMarkedForDelete())
                    continue;

            } catch (Exception e) {
                e.printStackTrace();

                throw new IOException(serializer + " failed to deserialize " + sstable.getColumnFamilyName()
                        + " with " + sstable.metadata + " from " + file, e);
            }

            Integer sblockLength = null;

            if (indexList == null)
                sblockLength = seekToSubColumn(sstable.metadata, file, sblockId);
            else
                sblockLength = seekToSubColumn(sstable.metadata, file, sblockId, indexList);

            if (sblockLength == null || sblockLength < 0)
                continue;

            int bytesReadFromStart = mappedLength - (int) file.bytesRemaining();

            if (logger.isDebugEnabled())
                logger.debug("BlockLength = " + sblockLength + " Availible " + file.bytesRemaining());

            assert offset <= sblockLength : String.format("%d > %d", offset, sblockLength);

            long dataOffset = position + bytesReadFromStart;

            if (file.bytesRemaining() == 0 || sblockLength == 0)
                continue;

            return new LocalBlock(file.getPath(), dataOffset + offset, sblockLength - offset);

        } catch (IOException e) {
            throw new TException(e);
        } finally {
            FileUtils.closeQuietly(raf);
        }
    }

    return null;
}

From source file:com.netflix.aegisthus.io.sstable.compression.CompressionMetadata.java

License:Apache License

public CompressionMetadata(InputStream compressionInput, long compressedLength) throws IOException {
    DataInputStream stream = new DataInputStream(compressionInput);

    String compressorName = stream.readUTF();
    int optionCount = stream.readInt();
    Map<String, String> options = Maps.newHashMap();
    for (int i = 0; i < optionCount; ++i) {
        String key = stream.readUTF();
        String value = stream.readUTF();
        options.put(key, value);/*from   w w w . j a  va  2  s  . co m*/
    }
    int chunkLength = stream.readInt();
    try {
        parameters = new CompressionParameters(compressorName, chunkLength, options);
    } catch (ConfigurationException e) {
        throw new RuntimeException("Cannot create CompressionParameters for stored parameters", e);
    }

    setDataLength(stream.readLong());
    chunkLengths = readChunkLengths(stream, compressedLength);
    current = 0;

    FileUtils.closeQuietly(stream);
}

From source file:com.netflix.priam.defaultimpl.ClearCredential.java

License:Apache License

public ClearCredential() {
    FileInputStream fis = null;/*from w ww. ja  v  a2s  .  c o m*/
    try {
        fis = new FileInputStream(CRED_FILE);
        props = new Properties();
        props.load(fis);
        AWS_ACCESS_ID = props.getProperty("AWSACCESSID") != null ? props.getProperty("AWSACCESSID").trim() : "";
        AWS_KEY = props.getProperty("AWSKEY") != null ? props.getProperty("AWSKEY").trim() : "";
    } catch (Exception e) {
        logger.error("Exception with credential file ", e);
        throw new RuntimeException("Problem reading credential file. Cannot start.", e);
    } finally {
        FileUtils.closeQuietly(fis);
    }

}

From source file:com.perpetumobile.bit.orm.cassandra.CliMain.java

License:Apache License

private CliUserHelp loadHelp() {
    final InputStream is = CliClient.class.getClassLoader()
            .getResourceAsStream("org/apache/cassandra/cli/CliHelp.yaml");
    assert is != null;

    try {/* w  w w. j a v  a  2s  . co  m*/
        final Constructor constructor = new Constructor(CliUserHelp.class);
        TypeDescription desc = new TypeDescription(CliUserHelp.class);
        desc.putListPropertyType("commands", CliCommandHelp.class);
        final Yaml yaml = new Yaml(new Loader(constructor));
        return (CliUserHelp) yaml.load(is);
    } finally {
        FileUtils.closeQuietly(is);
    }
}

From source file:com.tuplejump.calliope.hadoop.cql3.CqlConfigHelper.java

License:Apache License

private static SSLContext getSSLContext(String truststorePath, String truststorePassword, String keystorePath,
        String keystorePassword) throws NoSuchAlgorithmException, KeyStoreException, CertificateException,
        IOException, UnrecoverableKeyException, KeyManagementException {
    FileInputStream tsf = null;//from   www  .  j  av a2  s  .co  m
    FileInputStream ksf = null;
    SSLContext ctx = null;
    try {
        tsf = new FileInputStream(truststorePath);
        ksf = new FileInputStream(keystorePath);
        ctx = SSLContext.getInstance("SSL");

        KeyStore ts = KeyStore.getInstance("JKS");
        ts.load(tsf, truststorePassword.toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ts);

        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(ksf, keystorePassword.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, keystorePassword.toCharArray());

        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
    } finally {
        FileUtils.closeQuietly(tsf);
        FileUtils.closeQuietly(ksf);
    }
    return ctx;
}

From source file:org.apache.lucene.cassandra.fs.CassandraFileSystemThriftStore.java

License:Apache License

private InputStream readLocalBlock(LocalBlock blockInfo) throws IOException {

    if (blockInfo.file == null)
        throw new RuntimeException("Local file name is not defined");

    if (blockInfo.length == 0)
        return ByteBufferUtil.inputStream(ByteBufferUtil.EMPTY_BYTE_BUFFER);

    RandomAccessFile raf = null;/*from   w  ww. j  av a2 s  . c  o  m*/
    try {
        raf = new RandomAccessFile(blockInfo.file, "r");

        if (logger.isDebugEnabled())
            logger.debug("Mmapping " + blockInfo.length + " bytes");

        MappedByteBuffer bb = raf.getChannel().map(FileChannel.MapMode.READ_ONLY, blockInfo.offset,
                blockInfo.length);

        return getInputStream(bb);

    } catch (FileNotFoundException e) {
        throw new RuntimeException("Local file does not exist: " + blockInfo.file);
    } catch (IOException e) {
        throw new RuntimeException(String.format("Unable to mmap block %s[%d,%d]", blockInfo.file,
                blockInfo.length, blockInfo.offset), e);
    } finally {
        FileUtils.closeQuietly(raf);
    }

}