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

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

Introduction

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

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this multimap contains no key-value pairs.

Usage

From source file:jef.tools.IOUtils.java

/**
 * Map???properties//  w  w  w  .  j a  v a2  s .com
 * 
 * @param writer
 *            ??
 * @param map
 *            ???
 * @param closeWriter
 *            true???false????
 * @param sectionSupport
 *            ?
 * @param ?1KV??
 *            0KEY?value?? -1 KV???
 * 
 */
public static void storeProperties(Writer writer, Map<String, String> map, boolean closeWriter,
        Boolean sectionSupport, int saveConvert) {

    if (sectionSupport == null) {
        int limit = 3;
        sectionSupport = true;
        for (Entry<String, String> entry : map.entrySet()) {
            limit--;
            String key = entry.getKey();
            if (key.indexOf('|') == -1) {
                sectionSupport = false;
                break;
            }
            if (limit < 0) {
                break;
            }
        }
    }
    try {

        if (sectionSupport) {
            Multimap<String, Map.Entry<String, String>> sections = CollectionUtils.group(map.entrySet(),
                    new Function<Map.Entry<String, String>, String>() {
                        public String apply(Entry<String, String> input) {
                            int sectionLen = input.getKey().indexOf('|');
                            return sectionLen == -1 ? "" : input.getKey().substring(0, sectionLen);
                        }
                    });
            boolean hasNoSecLine = false;
            for (Map.Entry<String, String> entry : sections.removeAll("")) {
                writer.write(saveConvert(entry.getKey(), true, saveConvert));
                writer.write('=');
                writer.write(saveConvert(entry.getValue(), false, saveConvert));
                writer.write(StringUtils.CRLF_STR);
                hasNoSecLine = true;
            }
            if (!sections.isEmpty()) {
                if (hasNoSecLine)
                    writer.write(StringUtils.CRLF_STR);
                for (String section : sections.keySet()) {
                    writer.write("[" + section + "]\r\n");
                    for (Map.Entry<String, String> entry : sections.get(section)) {
                        writer.write(
                                saveConvert(entry.getKey().substring(section.length() + 1), true, saveConvert));
                        writer.write('=');
                        writer.write(saveConvert(entry.getValue(), false, saveConvert));
                        writer.write(StringUtils.CRLF_STR);
                    }
                    writer.write(StringUtils.CRLF_STR);
                }
            }
        } else {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                writer.write(saveConvert(entry.getKey(), true, saveConvert));
                writer.write('=');
                writer.write(saveConvert(entry.getValue(), false, saveConvert));
                writer.write(StringUtils.CRLF_STR);
            }
        }
        writer.flush();
    } catch (IOException e1) {
        LogUtil.exception(e1);
    } finally {
        if (closeWriter)
            closeQuietly(writer);
    }
}

From source file:org.apache.cassandra.service.StorageService.java

/**
 * Called when an endpoint is removed from the ring. This function checks
 * whether this node becomes responsible for new ranges as a
 * consequence and streams data if needed.
 *
 * This is rather ineffective, but it does not matter so much
 * since this is called very seldom/*from   w w w  .  j  a v a2s .co m*/
 *
 * @param endpoint the node that left
 */
private void restoreReplicaCount(InetAddress endpoint, final InetAddress notifyEndpoint) {
    final Multimap<InetAddress, String> fetchSources = HashMultimap.create();
    Multimap<String, Map.Entry<InetAddress, Collection<Range>>> rangesToFetch = HashMultimap.create();

    final InetAddress myAddress = FBUtilities.getLocalAddress();

    for (String table : DatabaseDescriptor.getNonSystemTables()) {
        Multimap<Range, InetAddress> changedRanges = getChangedRangesForLeaving(table, endpoint);
        Set<Range> myNewRanges = new HashSet<Range>();
        for (Map.Entry<Range, InetAddress> entry : changedRanges.entries()) {
            if (entry.getValue().equals(myAddress))
                myNewRanges.add(entry.getKey());
        }
        Multimap<InetAddress, Range> sourceRanges = getNewSourceRanges(table, myNewRanges);
        for (Map.Entry<InetAddress, Collection<Range>> entry : sourceRanges.asMap().entrySet()) {
            fetchSources.put(entry.getKey(), table);
            rangesToFetch.put(table, entry);
        }
    }

    for (final String table : rangesToFetch.keySet()) {
        for (Map.Entry<InetAddress, Collection<Range>> entry : rangesToFetch.get(table)) {
            final InetAddress source = entry.getKey();
            Collection<Range> ranges = entry.getValue();
            final Runnable callback = new Runnable() {
                public void run() {
                    synchronized (fetchSources) {
                        fetchSources.remove(source, table);
                        if (fetchSources.isEmpty())
                            sendReplicationNotification(myAddress, notifyEndpoint);
                    }
                }
            };
            if (logger_.isDebugEnabled())
                logger_.debug("Requesting from " + source + " ranges " + StringUtils.join(ranges, ", "));
            StreamIn.requestRanges(source, table, ranges, callback, OperationType.RESTORE_REPLICA_COUNT);
        }
    }
}

From source file:com.flexive.core.storage.genericSQL.GenericHierarchicalStorage.java

/**
 * Build the GROUP_POS entry for FX_CONTENT.
 *
 * @param content    the content instance
 * @return           the positions of all groups
 *//*from ww w . j  a va2 s .c  o  m*/
private String getGroupPositions(FxContent content) {
    final Multimap<Long, FxGroupData> positions = HashMultimap.create();
    collectGroupChildren(positions, content.getRootGroup());
    if (positions.isEmpty()) {
        return null;
    } else {
        final GroupPositionsProvider.Builder builder = GroupPositionsProvider.builder();
        for (Map.Entry<Long, Collection<FxGroupData>> entry : positions.asMap().entrySet()) {
            builder.startAssignment(entry.getKey());
            for (FxGroupData groupData : entry.getValue()) {
                builder.addPos(groupData.getIndices(), groupData.getPos());
            }
        }
        return builder.build();
    }
}

From source file:org.apache.cassandra.service.StorageService.java

public static void calculatePendingRanges(AbstractReplicationStrategy strategy, String table) {
    TokenMetadata tm = StorageService.instance.getTokenMetadata();
    Multimap<Range, InetAddress> pendingRanges = HashMultimap.create();
    Map<Token, InetAddress> bootstrapTokens = tm.getBootstrapTokens();
    Set<InetAddress> leavingEndpoints = tm.getLeavingEndpoints();

    if (bootstrapTokens.isEmpty() && leavingEndpoints.isEmpty() && tm.getMovingEndpoints().isEmpty()) {
        if (logger_.isDebugEnabled())
            logger_.debug("No bootstrapping, leaving or moving nodes -> empty pending ranges for {}", table);
        tm.setPendingRanges(table, pendingRanges);
        return;/*from www  .  ja  v a 2  s . com*/
    }

    Multimap<InetAddress, Range> addressRanges = strategy.getAddressRanges();

    // Copy of metadata reflecting the situation after all leave operations are finished.
    TokenMetadata allLeftMetadata = tm.cloneAfterAllLeft();

    // get all ranges that will be affected by leaving nodes
    Set<Range> affectedRanges = new HashSet<Range>();
    for (InetAddress endpoint : leavingEndpoints)
        affectedRanges.addAll(addressRanges.get(endpoint));

    // for each of those ranges, find what new nodes will be responsible for the range when
    // all leaving nodes are gone.
    for (Range range : affectedRanges) {
        Collection<InetAddress> currentEndpoints = strategy.calculateNaturalEndpoints(range.right, tm);
        Collection<InetAddress> newEndpoints = strategy.calculateNaturalEndpoints(range.right, allLeftMetadata);
        newEndpoints.removeAll(currentEndpoints);
        pendingRanges.putAll(range, newEndpoints);
    }

    // At this stage pendingRanges has been updated according to leave operations. We can
    // now continue the calculation by checking bootstrapping nodes.

    // For each of the bootstrapping nodes, simply add and remove them one by one to
    // allLeftMetadata and check in between what their ranges would be.
    for (Map.Entry<Token, InetAddress> entry : bootstrapTokens.entrySet()) {
        InetAddress endpoint = entry.getValue();

        allLeftMetadata.updateNormalToken(entry.getKey(), endpoint);
        for (Range range : strategy.getAddressRanges(allLeftMetadata).get(endpoint))
            pendingRanges.put(range, endpoint);
        allLeftMetadata.removeEndpoint(endpoint);
    }

    // At this stage pendingRanges has been updated according to leaving and bootstrapping nodes.
    // We can now finish the calculation by checking moving nodes.

    // For each of the moving nodes, we do the same thing we did for bootstrapping:
    // simply add and remove them one by one to allLeftMetadata and check in between what their ranges would be.
    for (Pair<Token, InetAddress> moving : tm.getMovingEndpoints()) {
        InetAddress endpoint = moving.right; // address of the moving node

        //  moving.left is a new token of the endpoint
        allLeftMetadata.updateNormalToken(moving.left, endpoint);

        for (Range range : strategy.getAddressRanges(allLeftMetadata).get(endpoint)) {
            pendingRanges.put(range, endpoint);
        }

        allLeftMetadata.removeEndpoint(endpoint);
    }

    tm.setPendingRanges(table, pendingRanges);

    if (logger_.isDebugEnabled())
        logger_.debug("Pending ranges:\n" + (pendingRanges.isEmpty() ? "<empty>" : tm.printPendingRanges()));
}

From source file:com.github.yongchristophertang.engine.web.request.RequestProxy.java

@Override
@SuppressWarnings("unchecked")
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    // if the method is a default method, process with the default implementation
    if (method.isDefault()) {
        return LOOKUP_CONSTRUCTOR.newInstance(method.getDeclaringClass(), MethodHandles.Lookup.PRIVATE)
                .unreflectSpecial(method, method.getDeclaringClass()).bindTo(proxy).invokeWithArguments(args);
    }//from  w  w w  .  j a v a2 s.co  m

    Multimap<String, String> queryParams = ArrayListMultimap.create();
    Multimap<String, String> bodyParams = ArrayListMultimap.create();
    Map<String, String> pathParams = new HashMap<>();
    Multimap<String, String> fileParams = ArrayListMultimap.create();
    Map<String, String> headerParams = new HashMap<>();

    /* Handle the class level annotations: Host and Path */
    // The url will be the URL path for the request
    String url = getHost(method.getDeclaringClass().getAnnotation(Host.class));

    /* Handle the method level annotations: Path, HTTPMethod, Produce and Consume */
    url += getPath(method.getDeclaringClass().getAnnotation(Path.class))
            + getPath(method.getAnnotation(Path.class));

    /* Fill out the api's description */
    String description = Optional.ofNullable(method.getAnnotation(Description.class)).map(Description::value)
            .orElse(method.getName());

    // Handle Produce and Consume
    String contentType = Optional.ofNullable(method.getAnnotation(Produce.class)).map(Produce::value)
            .orElse(null);
    String accept = Optional.ofNullable(method.getAnnotation(Consume.class)).map(Consume::value).orElse(null);

    // Handle HTTPMethod, only ONE HTTPMethod can be annotated with one method
    List<HTTPMethod> httpMethods = Arrays.asList(method.getAnnotations()).stream()
            .map(a -> a.annotationType().getAnnotation(HTTPMethod.class)).filter(m -> m != null)
            .collect(Collectors.toList());
    if (httpMethods.size() != 1) {
        throw new IllegalArgumentException("HTTPMethod annotation must be annotated once, no more and no less");
    }

    notNull(httpMethods.get(0).value(), "Http Method is not defined");
    HttpMethod httpMethod = HttpMethod.valueOf(httpMethods.get(0).value());

    /*
    Handle the field level annotations: PathParam, BodyParam, QueryParam and HeaderParam.
    Noted that only the first annotation will be processed.
     */
    Field[] fields = method.getDeclaringClass().getFields();
    try {
        for (Field f : fields) {
            Object value = f.get(null);
            if (value != null) {
                Class<? extends Annotation> annotationType = f.getAnnotations()[0].annotationType();
                if (annotationType == PathParam.class) {
                    PathParam a = f.getAnnotation(PathParam.class);
                    pathParams.put(a.value(), a.converter().newInstance().convert(value));
                } else if (annotationType == BodyParam.class) {
                    BodyParam a = f.getAnnotation(BodyParam.class);
                    if (value instanceof Collection) {
                        bodyParams.putAll(a.value(),
                                (Iterable<? extends String>) ((Collection) value).stream().map(
                                        v -> Try.of(() -> a.converter().newInstance().convert(v)).orElse(""))
                                        .collect(Collectors.toList()));
                    } else if (value instanceof Map) {
                        ((Map<String, Object>) value).entrySet().parallelStream()
                                .forEach(e -> bodyParams.put(e.getKey(), e.getValue().toString()));
                    } else {
                        bodyParams.put(a.value(), a.converter().newInstance().convert(value));
                    }
                } else if (annotationType == QueryParam.class) {
                    QueryParam a = f.getAnnotation(QueryParam.class);
                    if (value instanceof Collection) {
                        queryParams.putAll(a.value(),
                                (Iterable<? extends String>) ((Collection) value).stream().map(
                                        v -> Try.of(() -> a.converter().newInstance().convert(v)).orElse(""))
                                        .collect(Collectors.toList()));
                    } else {
                        queryParams.put(a.value(), a.converter().newInstance().convert(value));
                    }
                } else if (annotationType == HeaderParam.class) {
                    HeaderParam a = f.getAnnotation(HeaderParam.class);
                    headerParams.put(a.value(), a.converter().newInstance().convert(value));
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error("Cannot process filed level annotations");
    }
    //        Stream.of(method.getDeclaringClass().getFields()).filter(f -> Try.of(() -> Optional.of(f.get(null)).isPresent()).orElse(false)).forEach(f ->
    //                Optional.ofNullable(f.getAnnotations()[0]).map(Match.as(String.class)
    //                        .whenType(PathParam.class).then(anno -> Try.of(() -> anno.converter().newInstance().convert(f.get(null)))
    //                            .onSuccess(p -> pathParams.put(anno.value(), p)).orElse(""))
    //                        .whenType(BodyParam.class).then(anno -> Try.of(() -> {
    //                                Object object = f.get(null);
    //                                if (object instanceof Collection) {
    //                                    return ((Collection) object).stream().map(e -> Try.of(() -> anno.converter().newInstance().convert(e)).orElse("")).collect(Collectors.toList());
    //                                } else {
    //                                    return anno.converter().newInstance().convert(object);
    //                                }
    //                            }).onSuccess(p -> {
    //                                if (p instanceof Collection) {
    //                                    bodyParams.putAll(anno.value(), (Iterable<String>) p);
    //                                } else {
    //                                    bodyParams.put(anno.value(), String.valueOf(p));
    //                                }
    //                            }).orElse(""))
    //                        .whenType(QueryParam.class).then(anno -> Try.of(() -> anno.converter().newInstance().convert(f.get(null)))
    //                            .onSuccess(p -> queryParams.put(anno.value(), p)).orElse(""))
    //                        .whenType(HeaderParam.class).then(anno -> Try.of(() -> anno.converter().newInstance().convert(f.get(null)))
    //                            .onSuccess(p -> headerParams.put(anno.value(), p)).orElse(""))));

    /*
    Handle the method parameter level annotations: PathParam, BodyParam, QueryParam, HeaderParam and FileParam.
    Noted that only the first annotation will be processed.
    */
    Parameter[] parameters = method.getParameters();
    try {
        for (int i = 0; i < args.length; i++) {
            if (args[i] != null && parameters[i].getAnnotations() != null) {
                Class<? extends Annotation> annotationType = parameters[i].getAnnotations()[0].annotationType();
                if (annotationType == PathParam.class) {
                    PathParam a = parameters[i].getAnnotation(PathParam.class);
                    pathParams.put(a.value(), a.converter().newInstance().convert(args[i]));
                } else if (annotationType == BodyParam.class) {
                    BodyParam a = parameters[i].getAnnotation(BodyParam.class);
                    if (args[i] instanceof Collection) {
                        bodyParams.putAll(a.value(),
                                (Iterable<? extends String>) ((Collection) args[i]).stream().map(
                                        v -> Try.of(() -> a.converter().newInstance().convert(v)).orElse(""))
                                        .collect(Collectors.toList()));
                    } else if (args[i] instanceof Map) {
                        ((Map<String, Object>) args[i]).entrySet().parallelStream()
                                .forEach(e -> bodyParams.put(e.getKey(), e.getValue().toString()));
                    } else {
                        bodyParams.put(a.value(), a.converter().newInstance().convert(args[i]));
                    }
                } else if (annotationType == QueryParam.class) {
                    QueryParam a = parameters[i].getAnnotation(QueryParam.class);
                    if (args[i] instanceof Collection) {
                        queryParams.putAll(a.value(),
                                (Iterable<? extends String>) ((Collection) args[i]).stream().map(
                                        v -> Try.of(() -> a.converter().newInstance().convert(v)).orElse(""))
                                        .collect(Collectors.toList()));
                    } else if (args[i] instanceof Map) {
                        ((Map<String, Object>) args[i]).entrySet().parallelStream()
                                .forEach(e -> queryParams.put(e.getKey(), e.getValue().toString()));
                    } else {
                        queryParams.put(a.value(), a.converter().newInstance().convert(args[i]));
                    }
                } else if (annotationType == HeaderParam.class) {
                    HeaderParam a = parameters[i].getAnnotation(HeaderParam.class);
                    headerParams.put(a.value(), a.converter().newInstance().convert(args[i]));
                } else if (annotationType == FileParam.class) {
                    FileParam a = parameters[i].getAnnotation(FileParam.class);
                    fileParams.put(a.value(), args[i].toString());
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error("Cannot process parameter level annotations");
    }

    //        Stream.range(0, parameters.length).filter(
    //            i -> args[i] != null & parameters[i].getAnnotations() != null).map(
    //            i -> new Tuple2<>(parameters[i].getAnnotations()[0], args[i])).forEach(t -> Option.of(t._1).map(Match.as(String.class)
    //                .whenType(PathParam.class).then(p -> Try.of(() -> p.converter().newInstance().convert(t._2))
    //                    .onSuccess(v -> pathParams.put(p.value(), v)).orElse(""))
    //                .whenType(BodyParam.class).then(p -> Try.of(() -> p.converter().newInstance().convert(t._2))
    //                    .onSuccess(v -> bodyParams.put(p.value(), v)).orElse(""))
    //                .whenType(QueryParam.class).then(p -> Try.of(() -> p.converter().newInstance().convert(t._2))
    //                    .onSuccess(v -> queryParams.put(p.value(), v)).orElse(""))
    //                .whenType(HeaderParam.class).then(p -> Try.of(() -> p.converter().newInstance().convert(t._2))
    //                    .onSuccess(v -> headerParams.put(p.value(), v)).orElse(""))
    //                .whenType(FileParam.class).then(p -> String.valueOf(fileParams.put(p.value(), t._2.toString()))
    //            )));

    /**
     * Local inner class for creating a {@link HttpRequestBuilders} or {@link HttpMultipartRequestBuilders}.
     * This class provides a {@code build} method to construct the target {@code builders}.
     */
    abstract class RequestBuilderConstructor {
        HttpRequestBuilders builders;

        /**
         * Build path parameters.
         */
        void pathBuild() {
            pathParams.keySet().stream().forEach(key -> builders.path(key, pathParams.get(key)));
        }

        /**
         * Build query string parameters.
         */
        void queryBuild() {
            queryParams.keySet().stream().forEach(key -> builders.param(key, queryParams.get(key)));
        }

        /**
         * Build ordinary header parameters.
         */
        void headerBuild() {
            headerParams.keySet().stream().forEach(key -> builders.header(key, headerParams.get(key)));
        }

        /**
         * Build a special header parameter, ContentType.
         * The method behaviour varies with different request types..
         */
        abstract void contentTypeBuild();

        /**
         * Build a special header parameter, Accept.
         */
        void acceptBuild() {
            Optional.ofNullable(accept).ifPresent(builders::accept);
        }

        /**
         * Build body form parameters.
         * The method behaviour varies with different request types.
         */
        abstract void bodyBuild();

        /**
         * Attach files with requests.
         * This method is only valid for multipart request type.
         */
        abstract void fileBuild();

        /**
         * Post processors for returning {@code builders}
         */
        abstract void postProcessor();

        /**
         * Return a {@link HttpRequestBuilders}.
         */
        final HttpRequestBuilders build() {
            pathBuild();
            queryBuild();
            headerBuild();
            contentTypeBuild();
            acceptBuild();
            bodyBuild();
            fileBuild();
            postProcessor();
            return builders;
        }
    }

    /**
     * Local inner class for creating a {@link HttpMultipartRequestBuilders}.
     */
    class MultipartConstructor extends RequestBuilderConstructor {
        MultipartBodyFormBuilder multipartBodyFormBuilder = MultipartBodyFormBuilder.create();

        MultipartConstructor(HttpMultipartRequestBuilders builders) {
            this.builders = builders;
        }

        @Override
        void contentTypeBuild() {

        }

        @Override
        void bodyBuild() {
            bodyParams.keySet().stream()
                    .forEach(key -> multipartBodyFormBuilder.param(key, bodyParams.get(key)));
        }

        @Override
        void fileBuild() {
            fileParams.keySet().stream().forEach(key -> fileParams.get(key).stream().forEach(value -> {
                if (value.contains(",")) {
                    for (String file : value.split(",")) {
                        multipartBodyFormBuilder.file(key, file);
                    }
                } else if (!value.isEmpty()) {
                    multipartBodyFormBuilder.file(key, value);
                }
            }));
        }

        @Override
        void postProcessor() {
            HttpMultipartRequestBuilders.class.cast(builders).body(multipartBodyFormBuilder);
        }
    }

    /**
     * Local inner class for creating a {@link HttpRequestBuilders}.
     */
    class RequestConstructor extends RequestBuilderConstructor {

        RequestConstructor(HttpRequestBuilders builders) {
            this.builders = builders;
        }

        @Override
        void contentTypeBuild() {
            Optional.ofNullable(contentType).ifPresent(builders::contentType);
        }

        @Override
        void bodyBuild() {
            bodyParams.keySet().stream().forEach(key -> {
                if (key.equals("")) {
                    // if use a raw string to set up body, then we only add the first value, igonor the further
                    builders.body(bodyParams.get(key).iterator().next());
                } else {
                    builders.body(key, bodyParams.get(key));
                }
            });
        }

        @Override
        void fileBuild() {

        }

        @Override
        void postProcessor() {

        }
    }

    return fileParams.isEmpty()
            ? new RequestConstructor(new HttpRequestBuilders(httpMethod.getHttpRequest(), url, description))
                    .build()
            : new MultipartConstructor(
                    new HttpMultipartRequestBuilders(httpMethod.getHttpRequest(), url, description)).build();
}