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

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

Introduction

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

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this list contains no elements.

Usage

From source file:org.lanternpowered.server.text.gson.JsonTextTranslatableSerializer.java

@SuppressWarnings("deprecation")
@Override/*from www .ja  v  a 2  s  .co  m*/
public JsonElement serialize(TranslatableText src, Type typeOfSrc, JsonSerializationContext context) {
    final Translation translation = src.getTranslation();
    if (this.networkingFormat && !(translation instanceof MinecraftTranslation)) {
        final ImmutableList<Object> arguments = src.getArguments();
        final Object[] rawArguments = arguments.toArray(new Object[arguments.size()]);
        final Locale locale = currentLocale.get();
        for (int i = 0; i < rawArguments.length; i++) {
            Object object = rawArguments[i];
            if (object instanceof TextRepresentable) {
                if (!(object instanceof Text)) {
                    object = ((TextRepresentable) object).toText();
                }
                rawArguments[i] = ((LanternTextSerializer) TextSerializers.LEGACY_FORMATTING_CODE)
                        .serialize((Text) object, locale);
            } else {
                rawArguments[i] = object.toString();
            }
        }
        final String content = src.getTranslation().get(locale, rawArguments);
        return JsonTextLiteralSerializer.serializeLiteralText(src, content, context, this.removeComplexity);
    }
    final JsonObject obj = new JsonObject();
    obj.addProperty(TRANSLATABLE, src.getTranslation().getId());
    final ImmutableList<Object> arguments = src.getArguments();
    if (!arguments.isEmpty()) {
        final JsonArray argumentsArray = new JsonArray();
        for (Object object : arguments) {
            // Only primitive strings and text json is allowed,
            // so we need to convert the objects if possible
            if (object instanceof TextRepresentable) {
                if (!(object instanceof Text)) {
                    object = ((TextRepresentable) object).toText();
                }
                argumentsArray.add(context.serialize(object, Text.class));
            } else {
                argumentsArray.add(new JsonPrimitive(object.toString()));
            }
        }
        obj.add(TRANSLATABLE_ARGS, argumentsArray);
    }
    serialize(obj, src, context);
    return obj;
}

From source file:com.google.template.soy.soytree.TemplateDelegateNodeBuilder.java

/**
 * Alternative to {@code setCmdText()} that sets command text info directly as opposed to having
 * it parsed from the command text string. The cmdText field will be set to a canonical string
 * generated from the given info.//from w ww  . j  av  a 2 s .c om
 *
 * @param delTemplateName The delegate template name.
 * @param delTemplateVariant The delegate template variant.
 * @param delPriority The delegate priority.
 * @param autoescapeMode The mode of autoescaping for this template.
 * @param contentKind Strict mode context. Nonnull iff autoescapeMode is strict.
 * @param requiredCssNamespaces CSS namespaces required to render the template.
 * @return This builder.
 */
public TemplateDelegateNodeBuilder setCmdTextInfo(String delTemplateName, String delTemplateVariant,
        Priority delPriority, AutoescapeMode autoescapeMode, ContentKind contentKind,
        ImmutableList<String> requiredCssNamespaces) {

    Preconditions.checkState(this.cmdText == null);
    Preconditions.checkArgument(BaseUtils.isDottedIdentifier(delTemplateName));
    Preconditions.checkArgument(delTemplateVariant.length() == 0 || BaseUtils.isIdentifier(delTemplateVariant));
    Preconditions.checkArgument((contentKind != null) == (autoescapeMode == AutoescapeMode.STRICT));

    this.delTemplateName = delTemplateName;
    this.delTemplateVariant = delTemplateVariant;
    this.delTemplateKey = DelTemplateKey.create(delTemplateName, delTemplateVariant);
    this.templateNameForUserMsgs = delTemplateKey.toString();
    this.delPriority = delPriority;
    setAutoescapeInfo(autoescapeMode, contentKind);
    setRequiredCssNamespaces(requiredCssNamespaces);

    String cmdText = delTemplateName
            + ((delTemplateVariant.length() == 0) ? "" : " variant=\"" + delTemplateVariant + "\"")
            + " autoescape=\"" + autoescapeMode.getAttributeValue() + "\"";
    if (contentKind != null) {
        cmdText += " kind=\"" + NodeContentKinds.toAttributeValue(contentKind) + '"';
    }
    if (!requiredCssNamespaces.isEmpty()) {
        cmdText += " requirecss=\"" + Joiner.on(", ").join(requiredCssNamespaces) + "\"";
    }
    this.cmdText = cmdText;

    genInternalTemplateNameHelper();

    return this;
}

From source file:com.google.devtools.build.lib.rules.java.JavaCompileAction.java

/** Creates an ArgvFragment containing the common initial command line arguments */
private static CustomMultiArgv spawnCommandLineBase(final PathFragment javaExecutable,
        final Artifact javaBuilderJar, final Artifact langtoolsJar,
        final ImmutableList<Artifact> instrumentationJars, final ImmutableList<String> javaBuilderJvmFlags,
        final String javaBuilderMainClass, final String pathDelimiter) {
    return new CustomMultiArgv() {
        @Override/*w  w  w . j av  a2s. c om*/
        public Iterable<String> argv() {
            checkNotNull(langtoolsJar);
            checkNotNull(javaBuilderJar);

            CustomCommandLine.Builder builder = CustomCommandLine.builder().addPath(javaExecutable)
                    // Langtools jar is placed on the boot classpath so that it can override classes
                    // in the JRE. Typically this has no effect since langtools.jar does not have
                    // classes in common with rt.jar. However, it is necessary when using a version
                    // of javac.jar generated via ant from the langtools build.xml that is of a
                    // different version than AND has an overlap in contents with the default
                    // run-time (eg while upgrading the Java version).
                    .addPaths("-Xbootclasspath/p:%s", langtoolsJar.getExecPath()).add(javaBuilderJvmFlags);
            if (!instrumentationJars.isEmpty()) {
                builder.addJoinExecPaths("-cp", pathDelimiter,
                        Iterables.concat(instrumentationJars, ImmutableList.of(javaBuilderJar)))
                        .add(javaBuilderMainClass);
            } else {
                // If there are no instrumentation jars, use simpler '-jar' option to launch JavaBuilder.
                builder.addExecPath("-jar", javaBuilderJar);
            }
            return builder.build().arguments();
        }
    };
}

From source file:com.google.enterprise.connector.sharepoint.client.SharepointClient.java

/**
 * For a single ListState, handle its crawl queue (if any). This means add it
 * to the ResultSet which we give back to the Connector Manager.
 *
 * @param globalState The recent snapshot of the whole in-memory state file.
 * @param web Represets the current web state
 * @param list Represents the current list state
 * @return {@link SPDocumentList} conatining the crawled documents.
 */// w w w  .jav  a  2s  . c  om
@VisibleForTesting
SPDocumentList handleCrawlQueueForList(final GlobalState globalState, final WebState web,
        final ListState list) {
    if (null == web) {
        LOGGER.log(Level.WARNING, "web is not found");
        return null;
    }
    if (null == list) {
        LOGGER.log(Level.WARNING, "list is not found");
        return null;
    }

    final List<SPDocument> crawlQueue = list.getCrawlQueue();
    if (null == crawlQueue || crawlQueue.size() <= 0) {
        LOGGER.log(Level.FINE, "No CrawlQueue..");
        return null;
    }
    ImmutableList.Builder<SPDocument> newListBuilder = new ImmutableList.Builder<SPDocument>();
    for (SPDocument doc : list.getCrawlQueue()) {
        ListState parentList = doc.getParentList();
        if (parentList == null) {
            LOGGER.log(Level.WARNING,
                    "Document [{0}] is missing parent list. " + "Assigning [{1}] as parent list for document.",
                    new Object[] { doc.getUrl(), list.getListURL() });
            doc.setParentList(list);
        } else {
            if (!list.getPrimaryKey().equals(parentList.getPrimaryKey())) {
                LOGGER.log(Level.WARNING,
                        "Skipping document . Parent List - crawl queue mismatch"
                                + " for document [{0}]. Parent List is [{1}]. "
                                + "Crawl Queue is associated with list is [{2}].",
                        new Object[] { doc, parentList, list });
                continue;
            }
        }
        doc.setParentWeb(web);
        doc.setSharepointClientContext(sharepointClientContext);
        // Update necessary information required for downloading contents.
        if (FeedType.CONTENT_FEED == doc.getFeedType()) {
            doc.setContentDwnldURL(doc.getUrl());
        }

        newListBuilder.add(doc);
        LOGGER.log(Level.FINEST, "[ DocId = " + doc.getDocId() + ", URL = " + doc.getUrl() + " ]");
    }

    ImmutableList<SPDocument> newlist = newListBuilder.build();
    if (newlist.isEmpty()) {
        // If all documents are skipped because of possible 
        // crawl queue mismatch, then clear crawl queue for list.
        list.setCrawlQueue(null);
        return null;
    }

    // Update crawl queue for list with filtered documents.
    list.setCrawlQueue(newlist);

    final SPDocumentList docList = new SPDocumentList(newlist, globalState);
    // FIXME These could be set in traversal manager just before returning
    // start/resumeTraversal
    if (null != sharepointClientContext) {
        // FIXME These could be set in traversal manager just before
        // returning
        // start/resumeTraversal
        docList.setAliasMap(sharepointClientContext.getAliasMap());
        docList.setFQDNConversion(sharepointClientContext.isFQDNConversion());
        docList.setReWriteDisplayUrlUsingAliasMappingRules(
                sharepointClientContext.isReWriteDisplayUrlUsingAliasMappingRules());
        docList.setReWriteRecordUrlUsingAliasMappingRules(
                sharepointClientContext.isReWriteRecordUrlUsingAliasMappingRules());
    } else {
        LOGGER.log(Level.SEVERE, "sharepointClientContext not found!");
    }
    return docList;
}

From source file:com.google.security.zynamics.binnavi.disassembly.types.TypeManager.java

public synchronized TypeMember createStructureMember(final BaseType containingType, final BaseType memberType,
        final String memberName, int memberOffset) throws CouldntSaveDataException {
    Preconditions.checkNotNull(containingType, "Error: containing type argument can not be null");
    Preconditions.checkNotNull(memberType, "Error: member type can not be null");
    Preconditions.checkNotNull(memberName, "Error: name argument can not be null");
    Preconditions.checkArgument(!memberName.isEmpty(), "Error: name argument can not be empty");
    Preconditions.checkArgument(memberOffset >= 0,
            "Error: argument index argument can not be smaller than zero");
    if (typesContainer.willTypeCreateCyclicReference(containingType, memberType)) {
        return null;
    }//from   w  w w.j ava2 s.c  o m
    // We need to determine the original type sizes before doing any changes to the type system!
    final ImmutableMap<BaseType, Integer> originalTypeSizes = captureTypeSizesState(
            typesContainer.getAffectedTypes(containingType));

    // We need to check if there is space in the struct for our new member.
    final ImmutableList<TypeMember> subsequentMembers = containingType
            .getSubsequentMembersInclusive(memberOffset);
    if (!subsequentMembers.isEmpty()) {
        final int moveDelta = (memberOffset + memberType.getBitSize())
                - subsequentMembers.get(0).getBitOffset().get();
        if (moveDelta > 0) {
            for (final TypeMember member : subsequentMembers) {
                final int newOffset = member.getBitOffset().get() + moveDelta;
                backend.updateStructureMember(member, member.getBaseType(), member.getName(), newOffset);
                member.setOffset(Optional.of(newOffset));
                notifyMemberUpdated(member);
            }
        }
    }

    final TypeMember member = backend.createStructureMember(containingType, memberType, memberName,
            memberOffset);
    final ImmutableSet<BaseType> affectedTypes = typesContainer.addMember(member);
    notifyMemberCreation(member, affectedTypes);
    final Set<BaseType> inconsistentTypes = Sets.newHashSet(affectedTypes);
    inconsistentTypes.remove(containingType);
    ensureConsistencyAfterTypeUpdate(affectedTypes, inconsistentTypes, originalTypeSizes);
    return member;
}

From source file:com.google.template.soy.soytree.TemplateBasicNodeBuilder.java

/**
 * Alternative to {@code setCmdText()} that sets command text info directly as opposed to having
 * it parsed from the command text string. The cmdText field will be set to a canonical string
 * generated from the given info./* w  w w  .  j a v  a2 s.c o m*/
 *
 * @param templateName This template's name.
 * @param partialTemplateName This template's partial name. Only applicable for V2; null for V1.
 * @param visibility Visibility of this template.
 * @param autoescapeMode The mode of autoescaping for this template.
 * @param contentKind Strict mode context. Nonnull iff autoescapeMode is strict.
 * @param requiredCssNamespaces CSS namespaces required to render the template.
 * @return This builder.
 */
public TemplateBasicNodeBuilder setCmdTextInfo(String templateName, @Nullable String partialTemplateName,
        Visibility visibility, AutoescapeMode autoescapeMode, ContentKind contentKind,
        ImmutableList<String> requiredCssNamespaces) {

    Preconditions.checkState(this.cmdText == null);
    Preconditions.checkArgument(BaseUtils.isDottedIdentifier(templateName));
    Preconditions.checkArgument(
            partialTemplateName == null || BaseUtils.isIdentifierWithLeadingDot(partialTemplateName));
    Preconditions.checkArgument((contentKind != null) == (autoescapeMode == AutoescapeMode.STRICT));

    setTemplateNames(templateName, partialTemplateName);
    this.templateNameForUserMsgs = templateName;
    this.visibility = visibility;
    setAutoescapeInfo(autoescapeMode, contentKind);
    setRequiredCssNamespaces(requiredCssNamespaces);

    StringBuilder cmdTextBuilder = new StringBuilder();
    cmdTextBuilder.append((partialTemplateName != null) ? partialTemplateName : templateName);
    cmdTextBuilder.append(" autoescape=\"").append(autoescapeMode.getAttributeValue()).append('"');
    if (contentKind != null) {
        cmdTextBuilder.append(" kind=\"" + NodeContentKinds.toAttributeValue(contentKind) + '"');
    }
    if (visibility == Visibility.LEGACY_PRIVATE) {
        // TODO(brndn): generate code for other visibility levels. b/15190131
        cmdTextBuilder.append(" private=\"true\"");
    }
    if (!requiredCssNamespaces.isEmpty()) {
        cmdTextBuilder.append(" requirecss=\"" + Joiner.on(", ").join(requiredCssNamespaces) + "\"");
    }
    this.cmdText = cmdTextBuilder.toString();

    return this;
}

From source file:dagger2.internal.codegen.ProducerFactoryGenerator.java

@Override
ImmutableSet<JavaWriter> write(ClassName generatedTypeName, ProductionBinding binding) {
    TypeMirror keyType = binding.productionType().equals(Type.MAP)
            ? Util.getProvidedValueTypeOfMap(MoreTypes.asDeclared(binding.key().type()))
            : binding.key().type();/*  ww w .ja  v a 2 s .com*/
    TypeName providedTypeName = TypeNames.forTypeMirror(keyType);
    TypeName futureTypeName = ParameterizedTypeName.create(ClassName.fromClass(ListenableFuture.class),
            providedTypeName);
    JavaWriter writer = JavaWriter.inPackage(generatedTypeName.packageName());

    ClassWriter factoryWriter = writer.addClass(generatedTypeName.simpleName());
    ConstructorWriter constructorWriter = factoryWriter.addConstructor();
    constructorWriter.addModifiers(PUBLIC);

    factoryWriter.addField(binding.bindingTypeElement(), "module").addModifiers(PRIVATE, FINAL);
    constructorWriter.addParameter(binding.bindingTypeElement(), "module");
    constructorWriter.body().addSnippet("assert module != null;").addSnippet("this.module = module;");

    factoryWriter.addField(Executor.class, "executor").addModifiers(PRIVATE, FINAL);
    constructorWriter.addParameter(Executor.class, "executor");
    constructorWriter.body().addSnippet("assert executor != null;").addSnippet("this.executor = executor;");

    factoryWriter.annotate(Generated.class).setValue(ComponentProcessor.class.getName());
    factoryWriter.addModifiers(PUBLIC);
    factoryWriter.addModifiers(FINAL);
    factoryWriter.setSuperType(ParameterizedTypeName.create(AbstractProducer.class, providedTypeName));

    MethodWriter getMethodWriter = factoryWriter.addMethod(futureTypeName, "compute");
    getMethodWriter.annotate(Override.class);
    getMethodWriter.addModifiers(PROTECTED);

    final ImmutableMap<BindingKey, FrameworkField> fields = SourceFiles
            .generateBindingFieldsForDependencies(dependencyRequestMapper, binding.dependencies());

    for (FrameworkField bindingField : fields.values()) {
        TypeName fieldType = bindingField.frameworkType();
        FieldWriter field = factoryWriter.addField(fieldType, bindingField.name());
        field.addModifiers(PRIVATE, FINAL);
        constructorWriter.addParameter(field.type(), field.name());
        constructorWriter.body().addSnippet("assert %s != null;", field.name()).addSnippet("this.%1$s = %1$s;",
                field.name());
    }

    boolean returnsFuture = binding.bindingKind().equals(ProductionBinding.Kind.FUTURE_PRODUCTION);
    ImmutableList<DependencyRequest> asyncDependencies = FluentIterable.from(binding.dependencies())
            .filter(new Predicate<DependencyRequest>() {
                @Override
                public boolean apply(DependencyRequest dependency) {
                    return isAsyncDependency(dependency);
                }
            }).toList();

    for (DependencyRequest dependency : asyncDependencies) {
        ParameterizedTypeName futureType = ParameterizedTypeName
                .create(ClassName.fromClass(ListenableFuture.class), asyncDependencyType(dependency));
        String name = fields.get(dependency.bindingKey()).name();
        Snippet futureAccess = Snippet.format("%s.get()", name);
        getMethodWriter.body().addSnippet("%s %sFuture = %s;", futureType, name,
                dependency.kind().equals(DependencyRequest.Kind.PRODUCED)
                        ? Snippet.format("%s.createFutureProduced(%s)", ClassName.fromClass(Producers.class),
                                futureAccess)
                        : futureAccess);
    }

    if (asyncDependencies.isEmpty()) {
        ImmutableList.Builder<Snippet> parameterSnippets = ImmutableList.builder();
        for (DependencyRequest dependency : binding.dependencies()) {
            parameterSnippets.add(frameworkTypeUsageStatement(
                    Snippet.format(fields.get(dependency.bindingKey()).name()), dependency.kind()));
        }
        final boolean wrapWithFuture = false; // since submitToExecutor will create the future
        Snippet invocationSnippet = getInvocationSnippet(wrapWithFuture, binding, parameterSnippets.build());
        TypeName callableReturnType = returnsFuture ? futureTypeName : providedTypeName;
        Snippet throwsClause = getThrowsClause(binding.thrownTypes());
        Snippet callableSnippet = Snippet.format(
                Joiner.on('\n').join("new %1$s<%2$s>() {", "  @Override public %2$s call() %3$s{",
                        "    return %4$s;", "  }", "}"),
                ClassName.fromClass(Callable.class), callableReturnType, throwsClause, invocationSnippet);
        getMethodWriter.body().addSnippet("%s future = %s.submitToExecutor(%s, executor);",
                ParameterizedTypeName.create(ClassName.fromClass(ListenableFuture.class), callableReturnType),
                ClassName.fromClass(Producers.class), callableSnippet);
        getMethodWriter.body().addSnippet("return %s;",
                returnsFuture ? Snippet.format("%s.dereference(future)", ClassName.fromClass(Futures.class))
                        : "future");
    } else {
        final Snippet futureSnippet;
        final Snippet transformSnippet;
        if (asyncDependencies.size() == 1) {
            DependencyRequest asyncDependency = Iterables.getOnlyElement(asyncDependencies);
            futureSnippet = Snippet.format("%s", fields.get(asyncDependency.bindingKey()).name() + "Future");
            String argName = asyncDependency.requestElement().getSimpleName().toString();
            ImmutableList.Builder<Snippet> parameterSnippets = ImmutableList.builder();
            for (DependencyRequest dependency : binding.dependencies()) {
                // We really want to compare instances here, because asyncDependency is an element in the
                // set binding.dependencies().
                if (dependency == asyncDependency) {
                    parameterSnippets.add(Snippet.format("%s", argName));
                } else {
                    parameterSnippets.add(frameworkTypeUsageStatement(
                            Snippet.format(fields.get(dependency.bindingKey()).name()), dependency.kind()));
                }
            }
            boolean wrapWithFuture = !returnsFuture; // only wrap if we don't already have a future
            Snippet invocationSnippet = getInvocationSnippet(wrapWithFuture, binding,
                    parameterSnippets.build());
            Snippet throwsClause = getThrowsClause(binding.thrownTypes());
            transformSnippet = Snippet.format(
                    Joiner.on('\n').join("new %1$s<%2$s, %3$s>() {",
                            "  @Override public %4$s apply(%2$s %5$s) %6$s{", "    return %7$s;", "  }", "}"),
                    ClassName.fromClass(AsyncFunction.class), asyncDependencyType(asyncDependency),
                    providedTypeName, futureTypeName, argName, throwsClause, invocationSnippet);
        } else {
            futureSnippet = Snippet.format("%s.<%s>allAsList(%s)", ClassName.fromClass(Futures.class),
                    ClassName.fromClass(Object.class), Joiner.on(",").join(FluentIterable
                            .from(asyncDependencies).transform(new Function<DependencyRequest, String>() {
                                @Override
                                public String apply(DependencyRequest dependency) {
                                    return fields.get(dependency.bindingKey()).name() + "Future";
                                }
                            })));
            ImmutableList<Snippet> parameterSnippets = getParameterSnippets(binding, fields, "args");
            boolean wrapWithFuture = !returnsFuture; // only wrap if we don't already have a future
            Snippet invocationSnippet = getInvocationSnippet(wrapWithFuture, binding, parameterSnippets);
            ParameterizedTypeName listOfObject = ParameterizedTypeName.create(ClassName.fromClass(List.class),
                    ClassName.fromClass(Object.class));
            Snippet throwsClause = getThrowsClause(binding.thrownTypes());
            transformSnippet = Snippet.format(
                    Joiner.on('\n').join("new %1$s<%2$s, %3$s>() {",
                            "  @SuppressWarnings(\"unchecked\")  // safe by specification",
                            "  @Override public %4$s apply(%2$s args) %5$s{", "    return %6$s;", "  }", "}"),
                    ClassName.fromClass(AsyncFunction.class), listOfObject, providedTypeName, futureTypeName,
                    throwsClause, invocationSnippet);
        }
        getMethodWriter.body().addSnippet("return %s.%s(%s, %s, executor);", ClassName.fromClass(Futures.class),
                "transform", futureSnippet, transformSnippet);
    }

    // TODO(gak): write a sensible toString
    return ImmutableSet.of(writer);
}

From source file:org.eclipse.elk.core.util.nodespacing.LabelAndNodeSizeProcessor.java

/**
 * Places the labels of the given port on the inside of the port's node.
 *
 * @param port//from  w  ww  . j  a  va2  s.c  o  m
 *            the port whose labels to place.
 * @param compoundNodeMode
 *            {@code true} if the node contains further nodes in the original graph. In this
 *            case, port labels are not placed next to ports, but a little down as well to avoid
 *            edge-label-crossings if the port has edges connected to the node's insides.
 * @param labelSpacing
 *            spacing between labels and other objects.
 */
private void placePortLabelsInside(final PortAdapter<?> port, final boolean compoundNodeMode,
        final double labelSpacing) {

    ImmutableList<LabelAdapter<?>> labels = ImmutableList.copyOf(port.getLabels());
    if (labels.isEmpty()) {
        return;
    }

    // The initial y position we'll be starting from depends on the port side
    double y = 0;
    switch (port.getSide()) {
    case WEST:
    case EAST:
        // We need the first label's size here and we know that there is at least one label
        y = compoundNodeMode && port.hasCompoundConnections() ? port.getSize().y
                : (port.getSize().y - labels.get(0).getSize().y) / 2.0 - labelSpacing;
        break;
    case NORTH:
        y = port.getSize().y;
        break;
    case SOUTH:
        y = 0.0;
        break;
    }

    // In the usual case, we simply start at a given y position and place the labels downwards.
    // For southern ports, however, we actually need to start with the last label and place them
    // upwards. We thus first add all labels to a list that we may need to reverse
    if (port.getSide() == PortSide.SOUTH) {
        labels = labels.reverse();
    }

    // Place da labels!
    for (final LabelAdapter<?> label : port.getLabels()) {
        final KVector position = new KVector(port.getPosition());
        switch (port.getSide()) {
        case WEST:
            position.x = port.getSize().x + labelSpacing;
            position.y = y + labelSpacing;

            y += labelSpacing + label.getSize().y;
            break;
        case EAST:
            position.x = -label.getSize().x - labelSpacing;
            position.y = y + labelSpacing;

            y += labelSpacing + label.getSize().y;
            break;
        case NORTH:
            position.x = (port.getSize().x - label.getSize().x) / 2;
            position.y = y + labelSpacing;

            y += labelSpacing + label.getSize().y;
            break;
        case SOUTH:
            position.x = (port.getSize().x - label.getSize().x) / 2;
            position.y = y - labelSpacing - label.getSize().y;

            y -= labelSpacing + label.getSize().y;
            break;
        }
        label.setPosition(position);
    }
}

From source file:org.eclipse.elk.core.util.nodespacing.LabelAndNodeSizeProcessor.java

/**
 * Places the labels of the given port on the outside of the port's node. We suppose that the
 * first label has label side information. Those are then used for all labels. We don't support
 * having some labels above and others below incident edges.
 *
 * @param port//from w w w. j  a  va  2 s .  c o m
 *            the port whose label to place.
 * @param labelSpacing
 *            spacing between labels and other objects.
 */
private void placePortLabelsOutside(final PortAdapter<?> port, final double labelSpacing) {
    ImmutableList<LabelAdapter<?>> labels = ImmutableList.copyOf(port.getLabels());
    if (labels.isEmpty()) {
        return;
    }

    // Retrieve the first label's side
    LabelSide labelSide = labels.get(0).getSide();
    // Default is BELOW.
    labelSide = labelSide == LabelSide.UNKNOWN ? LabelSide.BELOW : labelSide;

    // The initial y position we'll be starting from depends on port and label sides
    double y = 0;
    switch (port.getSide()) {
    case WEST:
    case EAST:
        if (labelSide == LabelSide.BELOW) {
            y = port.getSize().y;
        }
        break;

    case SOUTH:
        y = port.getSize().y;
        break;
    }

    // If labels are below incident edges, we simply start at a given y position and place the
    // labels downwards. Of they are placed above or if we have a northern port, however, we
    // actually need to start with the last label and place them upwards. We thus first add all
    // labels to a list that we may need to reverse
    if (port.getSide() == PortSide.NORTH || labelSide == LabelSide.ABOVE) {
        labels = labels.reverse();
    }

    for (final LabelAdapter<?> label : labels) {
        final KVector position = new KVector(label.getPosition());
        if (labelSide == LabelSide.ABOVE) {
            // Place label "above" edges
            switch (port.getSide()) {
            case WEST:
                position.x = -label.getSize().x - labelSpacing;
                position.y = y - labelSpacing - label.getSize().y;

                y -= labelSpacing + label.getSize().y;
                break;
            case EAST:
                position.x = port.getSize().x + labelSpacing;
                position.y = y - labelSpacing - label.getSize().y;

                y -= labelSpacing + label.getSize().y;
                break;
            case NORTH:
                position.x = -label.getSize().x - labelSpacing;
                position.y = y - labelSpacing - label.getSize().y;

                y -= labelSpacing + label.getSize().y;
                break;
            case SOUTH:
                position.x = -label.getSize().x - labelSpacing;
                position.y = y + labelSpacing;

                y += labelSpacing + label.getSize().y;
                break;
            }
        } else {
            // Place label "below" edges
            switch (port.getSide()) {
            case WEST:
                position.x = -label.getSize().x - labelSpacing;
                position.y = y + labelSpacing;

                y += labelSpacing + label.getSize().y;
                break;
            case EAST:
                position.x = port.getSize().x + labelSpacing;
                position.y = y + labelSpacing;

                y += labelSpacing + label.getSize().y;
                break;
            case NORTH:
                position.x = port.getSize().x + labelSpacing;
                position.y = y - labelSpacing - label.getSize().y;

                y -= labelSpacing + label.getSize().y;
                break;
            case SOUTH:
                position.x = port.getSize().x + labelSpacing;
                position.y = y + labelSpacing;

                y += labelSpacing + label.getSize().y;
                break;
            }
        }
        label.setPosition(position);
    }
}

From source file:de.cau.cs.kieler.kiml.util.nodespacing.LabelAndNodeSizeProcessor.java

/**
 * Places the labels of the given port on the inside of the port's node.
 *
 * @param port//from  w ww .j a v  a  2  s.c o  m
 *            the port whose labels to place.
 * @param compoundNodeMode
 *            {@code true} if the node contains further nodes in the
 *            original graph. In this case, port labels are not placed next
 *            to ports, but a little down as well to avoid
 *            edge-label-crossings if the port has edges connected to the
 *            node's insides.
 * @param labelSpacing
 *            spacing between labels and other objects.
 */
private void placePortLabelsInside(final PortAdapter<?> port, final boolean compoundNodeMode,
        final double labelSpacing) {

    ImmutableList<LabelAdapter<?>> labels = ImmutableList.copyOf(port.getLabels());
    if (labels.isEmpty()) {
        return;
    }

    // The initial y position we'll be starting from depends on the port
    // side
    double y = 0;
    switch (port.getSide()) {
    case WEST:
    case EAST:
        // We need the first label's size here and we know that there is
        // at least one label
        y = compoundNodeMode && port.hasCompoundConnections() ? port.getSize().y
                : ((port.getSize().y - labels.get(0).getSize().y) / 2.0) - labelSpacing;
        break;
    case NORTH:
        y = port.getSize().y;
        break;
    case SOUTH:
        y = 0.0;
        break;
    }

    // In the usual case, we simply start at a given y position and place
    // the labels downwards.
    // For southern ports, however, we actually need to start with the last
    // label and place them
    // upwards. We thus first add all labels to a list that we may need to
    // reverse
    if (port.getSide() == PortSide.SOUTH) {
        labels = labels.reverse();
    }

    // Place da labels!
    for (final LabelAdapter<?> label : port.getLabels()) {
        final KVector position = new KVector(port.getPosition());
        switch (port.getSide()) {
        case WEST:
            position.x = port.getSize().x + labelSpacing;
            position.y = y + labelSpacing;

            y += labelSpacing + label.getSize().y;
            break;
        case EAST:
            position.x = -label.getSize().x - labelSpacing;
            position.y = y + labelSpacing;

            y += labelSpacing + label.getSize().y;
            break;
        case NORTH:
            position.x = (port.getSize().x - label.getSize().x) / 2;
            position.y = y + labelSpacing;

            y += labelSpacing + label.getSize().y;
            break;
        case SOUTH:
            position.x = (port.getSize().x - label.getSize().x) / 2;
            position.y = y - labelSpacing - label.getSize().y;

            y -= labelSpacing + label.getSize().y;
            break;
        }
        label.setPosition(position);
    }
}