Search in sources :

Example 76 with Closeable

use of java.io.Closeable in project phoenix by apache.

the class ServerCacheClient method addServerCache.

public ServerCache addServerCache(ScanRanges keyRanges, final ImmutableBytesWritable cachePtr, final byte[] txState, final ServerCacheFactory cacheFactory, final TableRef cacheUsingTableRef) throws SQLException {
    ConnectionQueryServices services = connection.getQueryServices();
    MemoryChunk chunk = services.getMemoryManager().allocate(cachePtr.getLength());
    List<Closeable> closeables = new ArrayList<Closeable>();
    closeables.add(chunk);
    ServerCache hashCacheSpec = null;
    SQLException firstException = null;
    final byte[] cacheId = generateId();
    /**
         * Execute EndPoint in parallel on each server to send compressed hash cache 
         */
    // TODO: generalize and package as a per region server EndPoint caller
    // (ideally this would be functionality provided by the coprocessor framework)
    boolean success = false;
    ExecutorService executor = services.getExecutor();
    List<Future<Boolean>> futures = Collections.emptyList();
    try {
        final PTable cacheUsingTable = cacheUsingTableRef.getTable();
        List<HRegionLocation> locations = services.getAllTableRegions(cacheUsingTable.getPhysicalName().getBytes());
        int nRegions = locations.size();
        // Size these based on worst case
        futures = new ArrayList<Future<Boolean>>(nRegions);
        Set<HRegionLocation> servers = new HashSet<HRegionLocation>(nRegions);
        for (HRegionLocation entry : locations) {
            // Keep track of servers we've sent to and only send once
            byte[] regionStartKey = entry.getRegionInfo().getStartKey();
            byte[] regionEndKey = entry.getRegionInfo().getEndKey();
            if (!servers.contains(entry) && keyRanges.intersectRegion(regionStartKey, regionEndKey, cacheUsingTable.getIndexType() == IndexType.LOCAL)) {
                // Call RPC once per server
                servers.add(entry);
                if (LOG.isDebugEnabled()) {
                    LOG.debug(addCustomAnnotations("Adding cache entry to be sent for " + entry, connection));
                }
                final byte[] key = getKeyInRegion(entry.getRegionInfo().getStartKey());
                final HTableInterface htable = services.getTable(cacheUsingTableRef.getTable().getPhysicalName().getBytes());
                closeables.add(htable);
                futures.add(executor.submit(new JobCallable<Boolean>() {

                    @Override
                    public Boolean call() throws Exception {
                        final Map<byte[], AddServerCacheResponse> results;
                        try {
                            results = htable.coprocessorService(ServerCachingService.class, key, key, new Batch.Call<ServerCachingService, AddServerCacheResponse>() {

                                @Override
                                public AddServerCacheResponse call(ServerCachingService instance) throws IOException {
                                    ServerRpcController controller = new ServerRpcController();
                                    BlockingRpcCallback<AddServerCacheResponse> rpcCallback = new BlockingRpcCallback<AddServerCacheResponse>();
                                    AddServerCacheRequest.Builder builder = AddServerCacheRequest.newBuilder();
                                    final byte[] tenantIdBytes;
                                    if (cacheUsingTable.isMultiTenant()) {
                                        try {
                                            tenantIdBytes = connection.getTenantId() == null ? null : ScanUtil.getTenantIdBytes(cacheUsingTable.getRowKeySchema(), cacheUsingTable.getBucketNum() != null, connection.getTenantId(), cacheUsingTable.getViewIndexId() != null);
                                        } catch (SQLException e) {
                                            throw new IOException(e);
                                        }
                                    } else {
                                        tenantIdBytes = connection.getTenantId() == null ? null : connection.getTenantId().getBytes();
                                    }
                                    if (tenantIdBytes != null) {
                                        builder.setTenantId(ByteStringer.wrap(tenantIdBytes));
                                    }
                                    builder.setCacheId(ByteStringer.wrap(cacheId));
                                    builder.setCachePtr(org.apache.phoenix.protobuf.ProtobufUtil.toProto(cachePtr));
                                    builder.setHasProtoBufIndexMaintainer(true);
                                    ServerCacheFactoryProtos.ServerCacheFactory.Builder svrCacheFactoryBuider = ServerCacheFactoryProtos.ServerCacheFactory.newBuilder();
                                    svrCacheFactoryBuider.setClassName(cacheFactory.getClass().getName());
                                    builder.setCacheFactory(svrCacheFactoryBuider.build());
                                    builder.setTxState(ByteStringer.wrap(txState));
                                    instance.addServerCache(controller, builder.build(), rpcCallback);
                                    if (controller.getFailedOn() != null) {
                                        throw controller.getFailedOn();
                                    }
                                    return rpcCallback.get();
                                }
                            });
                        } catch (Throwable t) {
                            throw new Exception(t);
                        }
                        if (results != null && results.size() == 1) {
                            return results.values().iterator().next().getReturn();
                        }
                        return false;
                    }

                    /**
                         * Defines the grouping for round robin behavior.  All threads spawned to process
                         * this scan will be grouped together and time sliced with other simultaneously
                         * executing parallel scans.
                         */
                    @Override
                    public Object getJobId() {
                        return ServerCacheClient.this;
                    }

                    @Override
                    public TaskExecutionMetricsHolder getTaskExecutionMetric() {
                        return NO_OP_INSTANCE;
                    }
                }));
            } else {
                if (LOG.isDebugEnabled()) {
                    LOG.debug(addCustomAnnotations("NOT adding cache entry to be sent for " + entry + " since one already exists for that entry", connection));
                }
            }
        }
        hashCacheSpec = new ServerCache(cacheId, servers, cachePtr.getLength());
        // Execute in parallel
        int timeoutMs = services.getProps().getInt(QueryServices.THREAD_TIMEOUT_MS_ATTRIB, QueryServicesOptions.DEFAULT_THREAD_TIMEOUT_MS);
        for (Future<Boolean> future : futures) {
            future.get(timeoutMs, TimeUnit.MILLISECONDS);
        }
        cacheUsingTableRefMap.put(Bytes.mapKey(cacheId), cacheUsingTableRef);
        success = true;
    } catch (SQLException e) {
        firstException = e;
    } catch (Exception e) {
        firstException = new SQLException(e);
    } finally {
        try {
            if (!success) {
                SQLCloseables.closeAllQuietly(Collections.singletonList(hashCacheSpec));
                for (Future<Boolean> future : futures) {
                    future.cancel(true);
                }
            }
        } finally {
            try {
                Closeables.closeAll(closeables);
            } catch (IOException e) {
                if (firstException == null) {
                    firstException = new SQLException(e);
                }
            } finally {
                if (firstException != null) {
                    throw firstException;
                }
            }
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug(addCustomAnnotations("Cache " + cacheId + " successfully added to servers.", connection));
    }
    return hashCacheSpec;
}
Also used : SQLException(java.sql.SQLException) SQLCloseable(org.apache.phoenix.util.SQLCloseable) Closeable(java.io.Closeable) ArrayList(java.util.ArrayList) JobCallable(org.apache.phoenix.job.JobManager.JobCallable) HTableInterface(org.apache.hadoop.hbase.client.HTableInterface) ServerRpcController(org.apache.hadoop.hbase.ipc.ServerRpcController) PTable(org.apache.phoenix.schema.PTable) HRegionLocation(org.apache.hadoop.hbase.HRegionLocation) BlockingRpcCallback(org.apache.hadoop.hbase.ipc.BlockingRpcCallback) HashSet(java.util.HashSet) ServerCachingService(org.apache.phoenix.coprocessor.generated.ServerCachingProtos.ServerCachingService) MemoryChunk(org.apache.phoenix.memory.MemoryManager.MemoryChunk) AddServerCacheRequest(org.apache.phoenix.coprocessor.generated.ServerCachingProtos.AddServerCacheRequest) IOException(java.io.IOException) SQLException(java.sql.SQLException) IOException(java.io.IOException) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) ServerCacheFactory(org.apache.phoenix.coprocessor.ServerCachingProtocol.ServerCacheFactory) ConnectionQueryServices(org.apache.phoenix.query.ConnectionQueryServices) AddServerCacheResponse(org.apache.phoenix.coprocessor.generated.ServerCachingProtos.AddServerCacheResponse)

Example 77 with Closeable

use of java.io.Closeable in project phoenix by apache.

the class TenantCacheImpl method addServerCache.

@Override
public Closeable addServerCache(ImmutableBytesPtr cacheId, ImmutableBytesWritable cachePtr, byte[] txState, ServerCacheFactory cacheFactory, boolean useProtoForIndexMaintainer) throws SQLException {
    MemoryChunk chunk = this.getMemoryManager().allocate(cachePtr.getLength() + txState.length);
    boolean success = false;
    try {
        Closeable element = cacheFactory.newCache(cachePtr, txState, chunk, useProtoForIndexMaintainer);
        getServerCaches().put(cacheId, element);
        success = true;
        return element;
    } finally {
        if (!success) {
            Closeables.closeAllQuietly(Collections.singletonList(chunk));
        }
    }
}
Also used : MemoryChunk(org.apache.phoenix.memory.MemoryManager.MemoryChunk) Closeable(java.io.Closeable)

Example 78 with Closeable

use of java.io.Closeable in project poi by apache.

the class EmbeddedObjects method main.

@SuppressWarnings("unused")
public static void main(String[] args) throws Exception {
    POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(args[0]));
    HSSFWorkbook workbook = new HSSFWorkbook(fs);
    for (HSSFObjectData obj : workbook.getAllEmbeddedObjects()) {
        //the OLE2 Class Name of the object
        String oleName = obj.getOLE2ClassName();
        DirectoryNode dn = (obj.hasDirectoryEntry()) ? (DirectoryNode) obj.getDirectory() : null;
        Closeable document = null;
        if (oleName.equals("Worksheet")) {
            document = new HSSFWorkbook(dn, fs, false);
        } else if (oleName.equals("Document")) {
            document = new HWPFDocument(dn);
        } else if (oleName.equals("Presentation")) {
            document = new HSLFSlideShow(dn);
        } else {
            if (dn != null) {
                // The DirectoryEntry is a DocumentNode. Examine its entries to find out what it is
                for (Entry entry : dn) {
                    String name = entry.getName();
                }
            } else {
                // There is no DirectoryEntry
                // Recover the object's data from the HSSFObjectData instance.
                byte[] objectData = obj.getObjectData();
            }
        }
        if (document != null) {
            document.close();
        }
    }
    workbook.close();
}
Also used : HWPFDocument(org.apache.poi.hwpf.HWPFDocument) Entry(org.apache.poi.poifs.filesystem.Entry) POIFSFileSystem(org.apache.poi.poifs.filesystem.POIFSFileSystem) Closeable(java.io.Closeable) HSSFObjectData(org.apache.poi.hssf.usermodel.HSSFObjectData) DirectoryNode(org.apache.poi.poifs.filesystem.DirectoryNode) HSLFSlideShow(org.apache.poi.hslf.usermodel.HSLFSlideShow) FileInputStream(java.io.FileInputStream) HSSFWorkbook(org.apache.poi.hssf.usermodel.HSSFWorkbook)

Example 79 with Closeable

use of java.io.Closeable in project phoenix by apache.

the class Closeables method closeAllQuietly.

public static IOException closeAllQuietly(Iterable<? extends Closeable> iterable) {
    if (iterable == null)
        return null;
    LinkedList<IOException> exceptions = null;
    for (Closeable closeable : iterable) {
        IOException ioe = closeQuietly(closeable);
        if (ioe != null) {
            if (exceptions == null)
                exceptions = new LinkedList<IOException>();
            exceptions.add(ioe);
        }
    }
    IOException ex = MultipleCausesIOException.fromIOExceptions(exceptions);
    return ex;
}
Also used : Closeable(java.io.Closeable) IOException(java.io.IOException) LinkedList(java.util.LinkedList)

Example 80 with Closeable

use of java.io.Closeable in project poi by apache.

the class EmbeddedObjects method main.

public static void main(String[] args) throws Exception {
    XSSFWorkbook workbook = new XSSFWorkbook(args[0]);
    for (PackagePart pPart : workbook.getAllEmbedds()) {
        String contentType = pPart.getContentType();
        InputStream is = pPart.getInputStream();
        Closeable document;
        if (contentType.equals("application/vnd.ms-excel")) {
            // Excel Workbook - either binary or OpenXML
            document = new HSSFWorkbook(is);
        } else if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
            // Excel Workbook - OpenXML file format
            document = new XSSFWorkbook(is);
        } else if (contentType.equals("application/msword")) {
            // Word Document - binary (OLE2CDF) file format
            document = new HWPFDocument(is);
        } else if (contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) {
            // Word Document - OpenXML file format
            document = new XWPFDocument(is);
        } else if (contentType.equals("application/vnd.ms-powerpoint")) {
            // PowerPoint Document - binary file format
            document = new HSLFSlideShow(is);
        } else if (contentType.equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")) {
            // PowerPoint Document - OpenXML file format
            document = new XMLSlideShow(is);
        } else {
            // Any other type of embedded object.
            document = is;
        }
        document.close();
        is.close();
    }
    workbook.close();
}
Also used : HWPFDocument(org.apache.poi.hwpf.HWPFDocument) InputStream(java.io.InputStream) Closeable(java.io.Closeable) XMLSlideShow(org.apache.poi.xslf.usermodel.XMLSlideShow) XSSFWorkbook(org.apache.poi.xssf.usermodel.XSSFWorkbook) XWPFDocument(org.apache.poi.xwpf.usermodel.XWPFDocument) PackagePart(org.apache.poi.openxml4j.opc.PackagePart) HSLFSlideShow(org.apache.poi.hslf.usermodel.HSLFSlideShow) HSSFWorkbook(org.apache.poi.hssf.usermodel.HSSFWorkbook)

Aggregations

Closeable (java.io.Closeable)216 IOException (java.io.IOException)88 Test (org.junit.Test)56 ArrayList (java.util.ArrayList)29 File (java.io.File)26 HashMap (java.util.HashMap)12 VirtualFile (org.jboss.vfs.VirtualFile)12 URL (java.net.URL)9 Path (java.nio.file.Path)9 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)8 Map (java.util.Map)7 ISE (io.druid.java.util.common.ISE)6 InputStream (java.io.InputStream)6 MountHandle (org.jboss.as.server.deployment.module.MountHandle)6 ResourceRoot (org.jboss.as.server.deployment.module.ResourceRoot)6 ProgramController (co.cask.cdap.app.runtime.ProgramController)5 ProgramType (co.cask.cdap.proto.ProgramType)4 ProgramId (co.cask.cdap.proto.id.ProgramId)4 Pair (io.druid.java.util.common.Pair)4 FileOutputStream (java.io.FileOutputStream)4