Example usage for com.google.common.collect Multimap containsKey

List of usage examples for com.google.common.collect Multimap containsKey

Introduction

In this page you can find the example usage for com.google.common.collect Multimap containsKey.

Prototype

boolean containsKey(@Nullable Object key);

Source Link

Document

Returns true if this multimap contains at least one key-value pair with the key key .

Usage

From source file:com.qcadoo.mes.materialFlowResources.service.ResourceManagementServiceImpl.java

public Multimap<Long, BigDecimal> getQuantitiesInWarehouse(final Entity warehouse,
        Multimap<Entity, Entity> productsAndPositions) {

    Multimap<Long, BigDecimal> result = ArrayListMultimap.create();
    String algorithm = warehouse.getStringField(LocationFieldsMFR.ALGORITHM);
    for (Map.Entry<Entity, Entity> productAndPosition : productsAndPositions.entries()) {
        Entity resource = productAndPosition.getValue().getBelongsToField(PositionFields.RESOURCE);

        if (algorithm.equalsIgnoreCase(WarehouseAlgorithm.MANUAL.getStringValue()) && resource != null) {
            result.put(productAndPosition.getKey().getId(), resource.getDecimalField(ResourceFields.QUANTITY));
        } else {/*from w ww  .  j a  va  2s  . co m*/

            List<Entity> resources = dataDefinitionService
                    .get(MaterialFlowResourcesConstants.PLUGIN_IDENTIFIER,
                            MaterialFlowResourcesConstants.MODEL_RESOURCE)
                    .find().add(SearchRestrictions.belongsTo(ResourceFields.LOCATION, warehouse))
                    .add(SearchRestrictions.belongsTo(ResourceFields.PRODUCT, productAndPosition.getKey()))
                    .list().getEntities();
            if (result.containsKey(productAndPosition.getKey().getId())) {
                BigDecimal currentQuantity = result.get(productAndPosition.getKey().getId()).stream()
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                result.put(productAndPosition.getKey().getId(),
                        (resources.stream().map(res -> res.getDecimalField(ResourceFields.QUANTITY))
                                .reduce(BigDecimal.ZERO, BigDecimal::add)).add(currentQuantity));
            } else {
                result.put(productAndPosition.getKey().getId(),
                        resources.stream().map(res -> res.getDecimalField(ResourceFields.QUANTITY))
                                .reduce(BigDecimal.ZERO, BigDecimal::add));
            }
        }
    }
    return result;
}

From source file:org.computer.whunter.rpm.parser.RpmSpecParser.java

/**
 * Parse the RPM spec file. Each of the supported fields is placed into the {@link Properties} returned.
 * @return the {@link Properties} of the spec file. 
 * @throws FileNotFoundException if the path of the spec file could not be opened for reading.
 *//*from   ww  w.j a va 2s. c  o m*/
public Multimap<String, String> parse() throws FileNotFoundException {
    Multimap<String, String> properties = ArrayListMultimap.create();
    Scanner scanner = new Scanner(new File(m_specFilePath));
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine().trim();
        if (line.startsWith("#")) {
            // Discard comments
            continue;
        }

        // Examine the line to see if it's a field 
        for (Map.Entry<Pattern, String> entry : m_fieldPatterns.entrySet()) {
            Matcher matcher = entry.getKey().matcher(line);
            if (matcher.matches() && matcher.groupCount() > 1) {
                // TODO handle multiple values
                properties.put(matcher.group(1).toLowerCase(), matcher.group(2).trim());
            }
        }
        // Examine the line to see if it's a macro definition 
        if (line.matches(MACRO_DEFINITION_PATTERN)) {
            String[] words = line.split("\\s");
            if (words != null && words.length > 2) {
                StringBuilder value = new StringBuilder();
                for (int i = 2; i < words.length; ++i) {
                    if (i != 2) {
                        value.append(" ");
                    }
                    value.append(words[i]);
                }
                assert !properties.containsKey(words[1]);
                properties.put(words[1], value.toString().trim());
                // Add a matcher pattern for it so that any references to it can be expanded
                StringBuilder macroMatchRegex = new StringBuilder(".*%\\{");
                StringBuilder macroReplaceRegex = new StringBuilder("%\\{");
                for (int i = 0; i < words[1].length(); ++i) {
                    char ch = words[1].charAt(i);
                    if (Character.isLetter(ch)) {
                        String regex = String.format("[%c%c]", Character.toLowerCase(ch),
                                Character.toUpperCase(ch));
                        macroMatchRegex.append(regex);
                        macroReplaceRegex.append(regex);
                    } else {
                        macroMatchRegex.append(ch);
                        macroReplaceRegex.append(ch);
                    }
                }
                macroMatchRegex.append("\\}.*");
                macroReplaceRegex.append("\\}");
                m_macroReferenceMatcherPatterns.put(Pattern.compile(macroMatchRegex.toString()), words[1]);
                m_macroReferenceReplacePatterns.put(macroMatchRegex.toString(),
                        Pattern.compile(macroReplaceRegex.toString()));
            }
        }
    }
    expandReferences(properties);
    return properties;
}

From source file:hku.fyp14017.blencode.stage.StageListener.java

public void precomputeActionsForBroadcastEvents(Map<String, List<String>> currentActions) {
    Multimap<String, String> actionsToRestartMap = BroadcastHandler.getActionsToRestartMap();
    if (!actionsToRestartMap.isEmpty()) {
        return;/*from  www  .j  av a2s .co  m*/
    }
    List<String> actions = new ArrayList<String>();
    if (currentActions.get(Constants.START_SCRIPT) != null) {
        actions.addAll(currentActions.get(Constants.START_SCRIPT));
    }
    if (currentActions.get(Constants.BROADCAST_SCRIPT) != null) {
        actions.addAll(currentActions.get(Constants.BROADCAST_SCRIPT));
    }
    if (currentActions.get(Constants.BROADCAST_NOTIFY_ACTION) != null) {
        actions.addAll(currentActions.get(Constants.BROADCAST_NOTIFY_ACTION));
    }
    for (String action : actions) {
        for (String actionOfLook : actions) {
            if (action.equals(actionOfLook) || isFirstSequenceActionAndEqualsSecond(action, actionOfLook)
                    || isFirstSequenceActionAndEqualsSecond(actionOfLook, action)) {
                if (!actionsToRestartMap.containsKey(action)) {
                    actionsToRestartMap.put(action, actionOfLook);
                } else {
                    actionsToRestartMap.get(action).add(actionOfLook);
                }
            }
        }
    }
}

From source file:org.dllearner.algorithms.qtl.qald.QALDExperiment.java

private Query removeUnboundObjectVarTriples(Query query) {
    QueryUtils queryUtils = new QueryUtils();
    Set<Triple> triplePatterns = queryUtils.extractTriplePattern(query);

    Multimap<Var, Triple> var2TriplePatterns = HashMultimap.create();
    for (Triple tp : triplePatterns) {
        var2TriplePatterns.put(Var.alloc(tp.getSubject()), tp);
    }//  w  w w . j a va2s .co m

    Iterator<Triple> iterator = triplePatterns.iterator();
    while (iterator.hasNext()) {
        Triple triple = iterator.next();
        Node object = triple.getObject();
        if (object.isVariable() && !var2TriplePatterns.containsKey(Var.alloc(object))) {
            iterator.remove();
        }
    }

    Query newQuery = new Query();
    newQuery.addProjectVars(query.getProjectVars());
    ElementTriplesBlock el = new ElementTriplesBlock();
    for (Triple triple : triplePatterns) {
        el.addTriple(triple);
    }
    newQuery.setQuerySelectType();
    newQuery.setDistinct(true);
    newQuery.setQueryPattern(el);

    return newQuery;
}

From source file:com.metamx.http.client.NettyHttpClient.java

@Override
public <Intermediate, Final> ListenableFuture<Final> go(final Request request,
        final HttpResponseHandler<Intermediate, Final> handler, final Duration requestReadTimeout) {
    final HttpMethod method = request.getMethod();
    final URL url = request.getUrl();
    final Multimap<String, String> headers = request.getHeaders();

    final String requestDesc = String.format("%s %s", method, url);
    if (log.isDebugEnabled()) {
        log.debug("[%s] starting", requestDesc);
    }//from w w  w .  j av a  2  s  . com

    // Block while acquiring a channel from the pool, then complete the request asynchronously.
    final Channel channel;
    final String hostKey = getPoolKey(url);
    final ResourceContainer<ChannelFuture> channelResourceContainer = pool.take(hostKey);
    final ChannelFuture channelFuture = channelResourceContainer.get().awaitUninterruptibly();
    if (!channelFuture.isSuccess()) {
        channelResourceContainer.returnResource(); // Some other poor sap will have to deal with it...
        return Futures.immediateFailedFuture(
                new ChannelException("Faulty channel in resource pool", channelFuture.getCause()));
    } else {
        channel = channelFuture.getChannel();
    }

    final String urlFile = Strings.nullToEmpty(url.getFile());
    final HttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, method,
            urlFile.isEmpty() ? "/" : urlFile);

    if (!headers.containsKey(HttpHeaders.Names.HOST)) {
        httpRequest.headers().add(HttpHeaders.Names.HOST, getHost(url));
    }

    httpRequest.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);

    for (Map.Entry<String, Collection<String>> entry : headers.asMap().entrySet()) {
        String key = entry.getKey();

        for (String obj : entry.getValue()) {
            httpRequest.headers().add(key, obj);
        }
    }

    if (request.hasContent()) {
        httpRequest.setContent(request.getContent());
    }

    final long readTimeout = getReadTimeout(requestReadTimeout);
    final SettableFuture<Final> retVal = SettableFuture.create();

    if (readTimeout > 0) {
        channel.getPipeline().addLast(READ_TIMEOUT_HANDLER_NAME,
                new ReadTimeoutHandler(timer, readTimeout, TimeUnit.MILLISECONDS));
    }

    channel.getPipeline().addLast(LAST_HANDLER_NAME, new SimpleChannelUpstreamHandler() {
        private volatile ClientResponse<Intermediate> response = null;

        @Override
        public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
            if (log.isDebugEnabled()) {
                log.debug("[%s] messageReceived: %s", requestDesc, e.getMessage());
            }
            try {
                Object msg = e.getMessage();

                if (msg instanceof HttpResponse) {
                    HttpResponse httpResponse = (HttpResponse) msg;
                    if (log.isDebugEnabled()) {
                        log.debug("[%s] Got response: %s", requestDesc, httpResponse.getStatus());
                    }

                    response = handler.handleResponse(httpResponse);
                    if (response.isFinished()) {
                        retVal.set((Final) response.getObj());
                    }

                    if (!httpResponse.isChunked()) {
                        finishRequest();
                    }
                } else if (msg instanceof HttpChunk) {
                    HttpChunk httpChunk = (HttpChunk) msg;
                    if (log.isDebugEnabled()) {
                        log.debug("[%s] Got chunk: %sB, last=%s", requestDesc,
                                httpChunk.getContent().readableBytes(), httpChunk.isLast());
                    }

                    if (httpChunk.isLast()) {
                        finishRequest();
                    } else {
                        response = handler.handleChunk(response, httpChunk);
                        if (response.isFinished() && !retVal.isDone()) {
                            retVal.set((Final) response.getObj());
                        }
                    }
                } else {
                    throw new IllegalStateException(String.format("Unknown message type[%s]", msg.getClass()));
                }
            } catch (Exception ex) {
                log.warn(ex, "[%s] Exception thrown while processing message, closing channel.", requestDesc);

                if (!retVal.isDone()) {
                    retVal.set(null);
                }
                channel.close();
                channelResourceContainer.returnResource();

                throw ex;
            }
        }

        private void finishRequest() {
            ClientResponse<Final> finalResponse = handler.done(response);
            if (!finalResponse.isFinished()) {
                throw new IllegalStateException(
                        String.format("[%s] Didn't get a completed ClientResponse Object from [%s]",
                                requestDesc, handler.getClass()));
            }
            if (!retVal.isDone()) {
                retVal.set(finalResponse.getObj());
            }
            removeHandlers();
            channelResourceContainer.returnResource();
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext context, ExceptionEvent event) throws Exception {
            if (log.isDebugEnabled()) {
                final Throwable cause = event.getCause();
                if (cause == null) {
                    log.debug("[%s] Caught exception", requestDesc);
                } else {
                    log.debug(cause, "[%s] Caught exception", requestDesc);
                }
            }

            retVal.setException(event.getCause());
            // response is non-null if we received initial chunk and then exception occurs
            if (response != null) {
                handler.exceptionCaught(response, event.getCause());
            }
            removeHandlers();
            try {
                channel.close();
            } catch (Exception e) {
                // ignore
            } finally {
                channelResourceContainer.returnResource();
            }

            context.sendUpstream(event);
        }

        @Override
        public void channelDisconnected(ChannelHandlerContext context, ChannelStateEvent event)
                throws Exception {
            if (log.isDebugEnabled()) {
                log.debug("[%s] Channel disconnected", requestDesc);
            }
            // response is non-null if we received initial chunk and then exception occurs
            if (response != null) {
                handler.exceptionCaught(response, new ChannelException("Channel disconnected"));
            }
            channel.close();
            channelResourceContainer.returnResource();
            if (!retVal.isDone()) {
                log.warn("[%s] Channel disconnected before response complete", requestDesc);
                retVal.setException(new ChannelException("Channel disconnected"));
            }
            context.sendUpstream(event);
        }

        private void removeHandlers() {
            if (readTimeout > 0) {
                channel.getPipeline().remove(READ_TIMEOUT_HANDLER_NAME);
            }
            channel.getPipeline().remove(LAST_HANDLER_NAME);
        }
    });

    channel.write(httpRequest).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                channel.close();
                channelResourceContainer.returnResource();
                if (!retVal.isDone()) {
                    retVal.setException(new ChannelException(
                            String.format("[%s] Failed to write request to channel", requestDesc),
                            future.getCause()));
                }
            }
        }
    });

    return retVal;
}

From source file:com.cloudera.oryx.kmeans.serving.generation.VectorFactory.java

public static VectorFactory create(MiningSchema schema, LocalTransformations transforms,
        List<ClusteringField> fields) {
    Map<FieldName, DerivedField> derived = Maps
            .newHashMapWithExpectedSize(transforms.getDerivedFields().size());
    for (DerivedField df : transforms.getDerivedFields()) {
        derived.put(df.getName(), df);/*from  w w  w.  ja  v  a 2s .c om*/
    }

    Multimap<FieldName, NumericUpdate> numeric = HashMultimap.create();
    Map<FieldName, Map<String, Update>> categorical = Maps.newHashMap();
    for (int j = 0; j < fields.size(); j++) {
        ClusteringField cf = fields.get(j);
        FieldName fn = cf.getField();
        if (derived.containsKey(fn)) {
            DerivedField df = derived.get(fn);
            Expression e = df.getExpression();
            if (e instanceof NormDiscrete) {
                NormDiscrete nd = (NormDiscrete) e;
                Map<String, Update> m = categorical.get(nd.getField());
                if (m == null) {
                    m = Maps.newHashMap();
                    categorical.put(nd.getField(), m);
                }
                m.put(nd.getValue(), new NumericUpdate(ONE, j, cf.getFieldWeight()));
            } else if (e instanceof Apply) {
                Apply apply = (Apply) e;
                if (!"ln".equals(apply.getFunction())) {
                    throw new UnsupportedOperationException(
                            "Unsupported function type: " + apply.getFunction());
                }
                FieldName f = ((FieldRef) apply.getExpressions().get(0)).getField();
                numeric.put(f, new NumericUpdate(LOG_VALUE, j, cf.getFieldWeight()));
            } else if (e instanceof NormContinuous) {
                NormContinuous nc = (NormContinuous) e;
                FieldName f = nc.getField();
                LinearNorm l1 = nc.getLinearNorms().get(0);
                LinearNorm l2 = nc.getLinearNorms().get(1);
                InterpolateFunction ifunc = new InterpolateFunction(l1.getOrig(), l1.getNorm(), l2.getOrig(),
                        l2.getNorm());
                numeric.put(f, new NumericUpdate(ifunc, j, cf.getFieldWeight()));
            } else {
                throw new UnsupportedOperationException("Unsupported expression type: " + e);
            }
        } else {
            numeric.put(fn, new NumericUpdate(VALUE, j, cf.getFieldWeight()));
        }
    }

    boolean sparse = 2 * schema.getMiningFields().size() <= fields.size();
    List<Set<Update>> updates = Lists.newArrayListWithExpectedSize(schema.getMiningFields().size());
    for (MiningField mf : schema.getMiningFields()) {
        FieldName fn = mf.getName();
        if (numeric.containsKey(fn)) {
            updates.add(ImmutableSet.<Update>copyOf(numeric.get(fn)));
        } else if (categorical.containsKey(fn)) {
            CategoricalUpdate u = new CategoricalUpdate(categorical.get(fn));
            updates.add(ImmutableSet.<Update>of(u));
        }
    }
    return new VectorFactory(sparse, fields.size(), updates);
}

From source file:io.druid.java.util.http.client.NettyHttpClient.java

@Override
public <Intermediate, Final> ListenableFuture<Final> go(final Request request,
        final HttpResponseHandler<Intermediate, Final> handler, final Duration requestReadTimeout) {
    final HttpMethod method = request.getMethod();
    final URL url = request.getUrl();
    final Multimap<String, String> headers = request.getHeaders();

    final String requestDesc = StringUtils.format("%s %s", method, url);
    if (log.isDebugEnabled()) {
        log.debug("[%s] starting", requestDesc);
    }/*from   w  ww .j av  a  2s.co m*/

    // Block while acquiring a channel from the pool, then complete the request asynchronously.
    final Channel channel;
    final String hostKey = getPoolKey(url);
    final ResourceContainer<ChannelFuture> channelResourceContainer = pool.take(hostKey);
    final ChannelFuture channelFuture = channelResourceContainer.get().awaitUninterruptibly();
    if (!channelFuture.isSuccess()) {
        channelResourceContainer.returnResource(); // Some other poor sap will have to deal with it...
        return Futures.immediateFailedFuture(
                new ChannelException("Faulty channel in resource pool", channelFuture.getCause()));
    } else {
        channel = channelFuture.getChannel();
    }

    final String urlFile = Strings.nullToEmpty(url.getFile());
    final HttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, method,
            urlFile.isEmpty() ? "/" : urlFile);

    if (!headers.containsKey(HttpHeaders.Names.HOST)) {
        httpRequest.headers().add(HttpHeaders.Names.HOST, getHost(url));
    }

    // If Accept-Encoding is set in the Request, use that. Otherwise use the default from "compressionCodec".
    if (!headers.containsKey(HttpHeaders.Names.ACCEPT_ENCODING)) {
        httpRequest.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, compressionCodec.getEncodingString());
    }

    for (Map.Entry<String, Collection<String>> entry : headers.asMap().entrySet()) {
        String key = entry.getKey();

        for (String obj : entry.getValue()) {
            httpRequest.headers().add(key, obj);
        }
    }

    if (request.hasContent()) {
        httpRequest.setContent(request.getContent());
    }

    final long readTimeout = getReadTimeout(requestReadTimeout);
    final SettableFuture<Final> retVal = SettableFuture.create();

    if (readTimeout > 0) {
        channel.getPipeline().addLast(READ_TIMEOUT_HANDLER_NAME,
                new ReadTimeoutHandler(timer, readTimeout, TimeUnit.MILLISECONDS));
    }

    channel.getPipeline().addLast(LAST_HANDLER_NAME, new SimpleChannelUpstreamHandler() {
        private volatile ClientResponse<Intermediate> response = null;

        @Override
        public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
            if (log.isDebugEnabled()) {
                log.debug("[%s] messageReceived: %s", requestDesc, e.getMessage());
            }
            try {
                Object msg = e.getMessage();

                if (msg instanceof HttpResponse) {
                    HttpResponse httpResponse = (HttpResponse) msg;
                    if (log.isDebugEnabled()) {
                        log.debug("[%s] Got response: %s", requestDesc, httpResponse.getStatus());
                    }

                    response = handler.handleResponse(httpResponse);
                    if (response.isFinished()) {
                        retVal.set((Final) response.getObj());
                    }

                    if (!httpResponse.isChunked()) {
                        finishRequest();
                    }
                } else if (msg instanceof HttpChunk) {
                    HttpChunk httpChunk = (HttpChunk) msg;
                    if (log.isDebugEnabled()) {
                        log.debug("[%s] Got chunk: %sB, last=%s", requestDesc,
                                httpChunk.getContent().readableBytes(), httpChunk.isLast());
                    }

                    if (httpChunk.isLast()) {
                        finishRequest();
                    } else {
                        response = handler.handleChunk(response, httpChunk);
                        if (response.isFinished() && !retVal.isDone()) {
                            retVal.set((Final) response.getObj());
                        }
                    }
                } else {
                    throw new IllegalStateException(
                            StringUtils.format("Unknown message type[%s]", msg.getClass()));
                }
            } catch (Exception ex) {
                log.warn(ex, "[%s] Exception thrown while processing message, closing channel.", requestDesc);

                if (!retVal.isDone()) {
                    retVal.set(null);
                }
                channel.close();
                channelResourceContainer.returnResource();

                throw ex;
            }
        }

        private void finishRequest() {
            ClientResponse<Final> finalResponse = handler.done(response);
            if (!finalResponse.isFinished()) {
                throw new IllegalStateException(
                        StringUtils.format("[%s] Didn't get a completed ClientResponse Object from [%s]",
                                requestDesc, handler.getClass()));
            }
            if (!retVal.isDone()) {
                retVal.set(finalResponse.getObj());
            }
            removeHandlers();
            channelResourceContainer.returnResource();
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext context, ExceptionEvent event) {
            if (log.isDebugEnabled()) {
                final Throwable cause = event.getCause();
                if (cause == null) {
                    log.debug("[%s] Caught exception", requestDesc);
                } else {
                    log.debug(cause, "[%s] Caught exception", requestDesc);
                }
            }

            retVal.setException(event.getCause());
            // response is non-null if we received initial chunk and then exception occurs
            if (response != null) {
                handler.exceptionCaught(response, event.getCause());
            }
            removeHandlers();
            try {
                channel.close();
            } catch (Exception e) {
                // ignore
            } finally {
                channelResourceContainer.returnResource();
            }

            context.sendUpstream(event);
        }

        @Override
        public void channelDisconnected(ChannelHandlerContext context, ChannelStateEvent event) {
            if (log.isDebugEnabled()) {
                log.debug("[%s] Channel disconnected", requestDesc);
            }
            // response is non-null if we received initial chunk and then exception occurs
            if (response != null) {
                handler.exceptionCaught(response, new ChannelException("Channel disconnected"));
            }
            channel.close();
            channelResourceContainer.returnResource();
            if (!retVal.isDone()) {
                log.warn("[%s] Channel disconnected before response complete", requestDesc);
                retVal.setException(new ChannelException("Channel disconnected"));
            }
            context.sendUpstream(event);
        }

        private void removeHandlers() {
            if (readTimeout > 0) {
                channel.getPipeline().remove(READ_TIMEOUT_HANDLER_NAME);
            }
            channel.getPipeline().remove(LAST_HANDLER_NAME);
        }
    });

    channel.write(httpRequest).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (!future.isSuccess()) {
                channel.close();
                channelResourceContainer.returnResource();
                if (!retVal.isDone()) {
                    retVal.setException(new ChannelException(
                            StringUtils.format("[%s] Failed to write request to channel", requestDesc),
                            future.getCause()));
                }
            }
        }
    });

    return retVal;
}

From source file:org.kitesdk.data.hbase.tool.SchemaTool.java

/**
 * Create the tables asynchronously with the HBase
 *//*from  w ww  .  ja v  a2s.c o  m*/
private void createTables(Collection<HTableDescriptor> tableDescriptors) throws InterruptedException {
    try {
        Set<String> tablesCreated = Sets.newHashSet();
        Multimap<String, HTableDescriptor> pendingTableUpdates = ArrayListMultimap.create();
        for (HTableDescriptor tableDescriptor : tableDescriptors) {
            String tableName = Bytes.toString(tableDescriptor.getName());
            if (tablesCreated.contains(tableName)) {
                // We have to wait for the table async creation to modify
                // Just add the required columns to be added
                pendingTableUpdates.put(tableName, tableDescriptor);
            } else {
                LOG.info("Creating table " + tableName);
                hbaseAdmin.createTableAsync(tableDescriptor, new byte[][] {});
                tablesCreated.add(tableName);
            }
        }

        // Wait for the tables to be online
        for (int waitCount = 0; waitCount < MAX_SECOND_WAIT_FOR_TABLE_CREATION; waitCount++) {
            Iterator<String> iterator = tablesCreated.iterator();
            while (iterator.hasNext()) {
                String table = iterator.next();
                if (hbaseAdmin.isTableAvailable(table)) {
                    // Perform any updates scheduled on the table
                    if (pendingTableUpdates.containsKey(table)) {
                        for (HTableDescriptor tableDescriptor : pendingTableUpdates.get(table)) {
                            // Add the new columns - synchronous calls
                            modifyTable(table, tableDescriptor);
                        }
                    }
                    iterator.remove();
                }
            }
            // If all tables are available, then break
            if (tablesCreated.isEmpty()) {
                break;
            }
            // Sleep for a second before checking again
            Thread.sleep(1000);
        }
    } catch (IOException e) {
        throw new DatasetException(e);
    }
}

From source file:com.clarkparsia.sbol.editor.SBOLDesign.java

private void computePrecedesTransitive(SequenceAnnotation ann,
        Multimap<SequenceAnnotation, SequenceAnnotation> precedes, Set<SequenceAnnotation> visited) {
    if (!visited.add(ann)) {
        LOGGER.warn("Circular precedes relation: " + Iterators
                .toString(Iterators.transform(visited.iterator(), new Function<SequenceAnnotation, String>() {
                    public String apply(SequenceAnnotation ann) {
                        return ann.getURI().toString();
                    }//from  w  ww  .j ava2  s  .com
                })));
        return;
    }

    if (!precedes.containsKey(ann)) {
        for (SequenceAnnotation nextAnn : ann.getPrecedes()) {
            computePrecedesTransitive(nextAnn, precedes, visited);
            precedes.put(ann, nextAnn);
            precedes.putAll(ann, precedes.get(nextAnn));
        }
    }

    visited.remove(ann);
}

From source file:com.b2international.snowowl.snomed.datastore.request.SnomedAssociationTargetUpdateRequest.java

private void updateAssociationTargets(final TransactionContext context, final Inactivatable component) {
    final List<SnomedAssociationRefSetMember> existingMembers = Lists
            .newArrayList(component.getAssociationRefSetMembers());
    final Multimap<AssociationType, String> newAssociationTargetsToCreate = HashMultimap
            .create(newAssociationTargets);

    final Iterator<SnomedAssociationRefSetMember> memberIterator = existingMembers.iterator();
    while (memberIterator.hasNext()) {

        final SnomedAssociationRefSetMember existingMember = memberIterator.next();
        final AssociationType associationType = AssociationType
                .getByConceptId(existingMember.getRefSetIdentifierId());

        if (null == associationType) {
            continue;
        }/*from ww w. ja v  a2 s . c  o m*/

        final String existingTargetId = existingMember.getTargetComponentId();

        if (newAssociationTargetsToCreate.remove(associationType, existingTargetId)) {

            // Exact match, just make sure that the member is active and remove it from the working list
            if (ensureMemberActive(context, existingMember)) {
                updateEffectiveTime(context, getLatestReleaseBranch(context), existingMember);
            }
            memberIterator.remove();
        }
    }

    for (final SnomedAssociationRefSetMember existingMember : existingMembers) {

        final AssociationType associationType = AssociationType
                .getByConceptId(existingMember.getRefSetIdentifierId());
        if (null == associationType) {
            continue;
        }

        if (newAssociationTargetsToCreate.containsKey(associationType)) {

            // We can re-use the member by changing the target component identifier, and checking that it is active
            final Iterator<String> targetIterator = newAssociationTargetsToCreate.get(associationType)
                    .iterator();
            final String newTargetId = targetIterator.next();
            targetIterator.remove();

            if (LOG.isDebugEnabled()) {
                LOG.debug(
                        "Changing association member {} with type {} and target component identifier from {} to {}.",
                        existingMember.getUuid(), associationType, existingMember.getTargetComponentId(),
                        newTargetId);
            }

            ensureMemberActive(context, existingMember);
            existingMember.setTargetComponentId(newTargetId);
            updateEffectiveTime(context, getLatestReleaseBranch(context), existingMember); // Always check; we know that targetComponentId has changed

        } else {

            // We have no use for this member -- remove or inactivate if already released
            removeOrDeactivate(context, existingMember);
        }
    }

    // With all existing members processed, any remaining entries in the multimap will need to be added as members
    for (final Entry<AssociationType, String> newAssociationEntry : newAssociationTargetsToCreate.entries()) {

        final SnomedAssociationRefSetMember member = SnomedComponents.newAssociationMember()
                .withRefSet(newAssociationEntry.getKey().getConceptId())
                .withTargetComponentId(newAssociationEntry.getValue())
                .withReferencedComponent(((Component) component).getId())
                .withModule(((Component) component).getModule().getId()).addTo(context);

        component.getAssociationRefSetMembers().add(member);
    }
}