Java 类org.eclipse.xtext.util.Strings 实例源码

项目:xtext-core    文件:CodeConfig.java   
public String getAnnotationImportsAsString() {
  boolean _isEmpty = this.classAnnotations.isEmpty();
  if (_isEmpty) {
    return null;
  }
  final StringBuilder stringBuilder = new StringBuilder();
  for (final IClassAnnotation annotation : this.classAnnotations) {
    {
      final TypeReference importString = annotation.getAnnotationImport();
      if ((importString != null)) {
        stringBuilder.append("import ").append(importString).append(";").append(Strings.newLine());
      }
    }
  }
  return stringBuilder.toString();
}
项目:n4js    文件:ContentAssistContextFactory.java   
@Override
protected void createContextsForLastCompleteNode(EObject previousModel, boolean strict) {
    String currentNodePrefix = getPrefix(currentNode);
    if (!Strings.isEmpty(currentNodePrefix) && !currentNode.getText().equals(currentNodePrefix)) {
        lexer.setCharStream(new ANTLRStringStream(currentNodePrefix));
        Token token = lexer.nextToken();
        if (token == Token.EOF_TOKEN) { // error case - nothing could be parsed
            return;
        }
        while (token != Token.EOF_TOKEN) {
            if (isErrorToken(token))
                return;
            token = lexer.nextToken();
        }
    }
    String prefix = "";
    Collection<FollowElement> followElements = getParser().getFollowElements(rootNode, 0, completionOffset, strict);
    doCreateContexts(lastCompleteNode, currentNode, prefix, previousModel, followElements);
}
项目:n4js    文件:ImportRewriter.java   
private ImportRewriter(IDocument document, Resource resource) {
    if (document instanceof IDocumentExtension4) {
        lineDelimiter = ((IDocumentExtension4) document).getDefaultLineDelimiter();
    } else {
        lineDelimiter = Strings.newLine();
    }
    this.script = (Script) resource.getContents().get(0);
    this.existingImports = Lists.newArrayList();
    for (ScriptElement element : script.getScriptElements()) {
        if (element instanceof ImportDeclaration)
            existingImports.add((ImportDeclaration) element);
    }
    this.requestedImports = Sets.newLinkedHashSet();
    this.lazySpacer = new Lazy<>(() -> spacerPreference.getSpacingPreference(resource));

}
项目:n4js    文件:N4JSNameValidator.java   
private boolean holdsDoesNotStartWithUpperCaseLetter(N4MemberDeclaration n4Member) {
    if (n4Member.isStatic()) {
        return true;
    }

    if (isConstFieldDeclaration(n4Member)) {
        return true;
    }

    if (Character.isUpperCase(n4Member.getName().charAt(0))) {
        final String msg = getMessageForCLF_NAME_DOES_NOT_START_LOWERCASE(keywordProvider.keyword(n4Member));
        addIssue(
                Strings.toFirstUpper(msg),
                n4Member,
                N4JSFeatureUtils.attributeOfNameFeature(n4Member),
                CLF_NAME_DOES_NOT_START_LOWERCASE);
        return false;
    }
    return true;
}
项目:n4js    文件:N4JSNameValidator.java   
private boolean holdsStartWithLowercaseLetter(Variable variable) {

        if (variable.isConst()) {
            return true;
        }

        final char first = variable.getName().charAt(0);
        if (Character.isLetter(first) && !Character.isLowerCase(first)) {
            final String msg = getMessageForCLF_NAME_DOES_NOT_START_LOWERCASE(keywordProvider.keyword(variable));
            addIssue(
                    Strings.toFirstUpper(msg),
                    variable,
                    IDENTIFIABLE_ELEMENT__NAME,
                    CLF_NAME_DOES_NOT_START_LOWERCASE);
            return false;
        }
        return true;
    }
项目:n4js    文件:N4JSNameValidator.java   
private boolean holdsNoTypeNameOrNameEqualsType(NamedElement namedElement) {
    if (namedElement instanceof TypableElement) {
        String name = namedElement.getName();
        if (BASE_TYPES.contains(name)) {
            TypeRef typeRef = ts.tau((TypableElement) namedElement);
            if (typeRef != null && typeRef.getDeclaredType() != null) {
                String typeName = typeRef.getDeclaredType().getName();
                if (!Strings.isEmpty(typeName) && !name.equals(typeName)) {
                    final String message = getMessageForCLF_NAME_DIFFERS_TYPE(
                            validatorMessageHelper.description(namedElement), name, typeName);
                    addIssue(Strings.toFirstUpper(message), namedElement,
                            N4JSFeatureUtils.attributeOfNameFeature(namedElement),
                            CLF_NAME_DIFFERS_TYPE);
                    return false;
                }
            }
        }
    }
    return true;
}
项目:n4js    文件:LegacyOctalIntValueConverter.java   
@Override
public BigDecimal toValue(String string, INode node) {
    if (Strings.isEmpty(string))
        throw new N4JSValueConverterException(IssueCodes.getMessageForVCO_OCTALINT_CONVERT_EMPTY_STR(),
                IssueCodes.VCO_OCTALINT_CONVERT_EMPTY_STR, node, null);
    if (string.length() <= 1) {
        throw new N4JSValueConverterWithValueException(
                IssueCodes.getMessageForVCO_OCTALINT_CONVERT_TOO_SHORT(string),
                IssueCodes.VCO_OCTALINT_CONVERT_TOO_SHORT, node,
                BigDecimal.ZERO, null);
    }
    try {
        return new BigDecimal(new BigInteger(string, 8));
    } catch (NumberFormatException e) {
        try {
            BigDecimal result = new BigDecimal(new BigInteger(string, 10));
            throw new LeadingZerosException(IssueCodes.getMessageForVCO_OCTALINT_LEADING_ZEROS(string),
                    IssueCodes.VCO_OCTALINT_LEADING_ZEROS, node, result);
        } catch (NumberFormatException again) {
            throw new N4JSValueConverterException(IssueCodes.getMessageForVCO_OCTALINT_CONVERT_STR(string),
                    IssueCodes.VCO_OCTALINT_CONVERT_STR, node, null);
        }
    }
}
项目:n4js    文件:OctalIntValueConverter.java   
@Override
public BigDecimal toValue(String string, INode node) {
    if (Strings.isEmpty(string))
        throw new N4JSValueConverterException(IssueCodes.getMessageForVCO_OCTALINT_CONVERT_EMPTY_STR(),
                IssueCodes.VCO_OCTALINT_CONVERT_EMPTY_STR, node, null);
    if (string.length() <= 2) {
        throw new N4JSValueConverterWithValueException(
                IssueCodes.getMessageForVCO_OCTALINT_CONVERT_TOO_SHORT(string),
                IssueCodes.VCO_OCTALINT_CONVERT_TOO_SHORT, node,
                BigDecimal.ZERO, null);
    }
    try {
        return new BigDecimal(new BigInteger(string.substring(2), 8));
    } catch (NumberFormatException e) {
        throw new N4JSValueConverterException(IssueCodes.getMessageForVCO_OCTALINT_CONVERT_STR(string),
                IssueCodes.VCO_OCTALINT_CONVERT_STR, node, null);
    }
}
项目:n4js    文件:HexIntValueConverter.java   
@Override
public BigDecimal toValue(String string, INode node) {
    if (Strings.isEmpty(string))
        throw new N4JSValueConverterException(IssueCodes.getMessageForVCO_HEXINT_CONVERT_EMPTY_STR(),
                IssueCodes.VCO_HEXINT_CONVERT_EMPTY_STR, node, null);
    if (string.length() <= 2) {
        throw new N4JSValueConverterWithValueException(
                IssueCodes.getMessageForVCO_HEXINT_CONVERT_TOO_SHORT(string),
                IssueCodes.VCO_HEXINT_CONVERT_TOO_SHORT, node,
                BigDecimal.ZERO, null);
    }
    try {
        return new BigDecimal(new BigInteger(string.substring(2), 16));
    } catch (NumberFormatException e) {
        throw new N4JSValueConverterException(IssueCodes.getMessageForVCO_HEXINT_CONVERT_STR(string),
                IssueCodes.VCO_HEXINT_CONVERT_STR, node, null);
    }
}
项目:n4js    文件:BinaryIntValueConverter.java   
@Override
public BigDecimal toValue(String string, INode node) {
    if (Strings.isEmpty(string))
        throw new N4JSValueConverterException(IssueCodes.getMessageForVCO_BINARYINT_CONVERT_EMPTY_STR(),
                IssueCodes.VCO_BINARYINT_CONVERT_EMPTY_STR, node, null);
    if (string.length() <= 2) {
        throw new N4JSValueConverterWithValueException(
                IssueCodes.getMessageForVCO_BINARYINT_CONVERT_TOO_SHORT(string),
                IssueCodes.VCO_BINARYINT_CONVERT_TOO_SHORT, node,
                BigDecimal.ZERO, null);
    }
    try {
        return new BigDecimal(new BigInteger(string.substring(2), 2));
    } catch (NumberFormatException e) {
        throw new N4JSValueConverterException(IssueCodes.getMessageForVCO_HEXINT_CONVERT_STR(string),
                IssueCodes.VCO_HEXINT_CONVERT_STR, node, null);
    }
}
项目:n4js    文件:AbstractTypeVisibilityChecker.java   
private boolean isProjectVisible(Resource contextResource, final T element) {
    if (contextResource != null) {
        final TModule contextModule = N4JSResource.getModule(contextResource);
        if (contextModule != null) {
            final TModule elementModule = N4JSResource.getModule(element.eResource());
            return elementModule == null
                    || elementModule == contextModule
                    || ( //
                    Strings.equal(contextModule.getProjectId(), elementModule.getProjectId())
                            && Strings.equal(contextModule.getVendorID(), elementModule.getVendorID()) //
                    )
                    || isTestedProjectOf(contextModule, elementModule);
        }
    }
    return false;
}
项目:gemoc-studio-modeldebugging    文件:SequentialSingleLanguageNewWizard.java   
@Override
public void init(BaseProjectWizardFields data) {
    super.init(data);
    setWindowTitle(WizardTemplateMessages.SequentialSingleLanguageTemplate_wtitle);

    try {
        String project = getData().projectName;
        String SUFFIX = ".xdsml";
        if(project.endsWith(SUFFIX)){

            int startSuffix = project.length() - SUFFIX.length();
            int startName = project.lastIndexOf(".", startSuffix-1) + 1;

            String packageName = project.substring(0, startName - 1).toLowerCase();
            String languageName = project.substring(startName, startSuffix);
            languageName = Strings.toFirstUpper(languageName);

            ITemplateSection[] selections = getTemplateSections();
            SequentialSingleLanguageTemplate selection = (SequentialSingleLanguageTemplate) selections[0];
            selection.updateOptions(packageName, languageName, languageName);
        }
    } catch (Exception e) {}
}
项目:gemoc-studio-modeldebugging    文件:SequentialExtendedLanguageNewWizard.java   
@Override
public void init(BaseProjectWizardFields data) {
    super.init(data);
    setWindowTitle(WizardTemplateMessages.SequentialExtendedLanguageTemplate_wtitle);

    try {
        String project = getData().projectName;
        String SUFFIX = ".xdsml";
        if(project.endsWith(SUFFIX)){

            int startSuffix = project.length() - SUFFIX.length();
            int startName = project.lastIndexOf(".", startSuffix-1) + 1;

            String packageName = project.substring(0, startName - 1).toLowerCase();
            String languageName = project.substring(startName, startSuffix);
            languageName = Strings.toFirstUpper(languageName);

            ITemplateSection[] selections = getTemplateSections();
            SequentialExtendedLanguageTemplate selection = (SequentialExtendedLanguageTemplate) selections[0];
            selection.updateOptions(packageName, languageName, languageName);
        }
    } catch (Exception e) {}
}
项目:solidity-ide    文件:SolidityContentProposalPriorities.java   
@Override
protected void adjustPriority(ICompletionProposal proposal, String prefix, int priority) {
    if (proposal == null || !(proposal instanceof ConfigurableCompletionProposal))
        return;
    ConfigurableCompletionProposal castedProposal = (ConfigurableCompletionProposal) proposal;
    if (castedProposal.getPriority() != getDefaultPriority())
        return;
    int adjustedPriority = priority;
    if (!Strings.isEmpty(prefix)) {
        if (castedProposal.getReplacementString().equals(prefix))
            adjustedPriority = (int) (adjustedPriority * sameTextMultiplier);
        else if (castedProposal.getReplacementString().startsWith(prefix))
            adjustedPriority = adjustedPriority * proposalWithPrefixMultiplier;
    }
    castedProposal.setPriority(adjustedPriority);
}
项目:solidity-ide    文件:SolidityFoldingRegionProvider.java   
@Override
protected void computeCommentFolding(IXtextDocument xtextDocument,
        IFoldingRegionAcceptor<ITextRegion> foldingRegionAcceptor, ITypedRegion typedRegion,
        boolean initiallyFolded) {

    String text;
    try {
        text = xtextDocument.get(typedRegion.getOffset(), typedRegion.getLength());
        int lines = Strings.countLines(text);
        if (shouldCreateCommentFolding(lines)) {
            boolean collapse = shouldCollapse(typedRegion, lines);
            super.computeCommentFolding(xtextDocument, foldingRegionAcceptor, typedRegion, collapse);
        }
    } catch (BadLocationException e) {
        log.error(e, e);
    }

}
项目:xtext-core    文件:LazyURIEncoder.java   
/**
 * ONLY public to be testable
 */
public INode getNode(final INode node, String path) {
    final List<String> split = Strings.split(path, '/');
    INode result = node;
    for (String string : split) {
        String trimmed = string.trim();
        if (trimmed.length() > 0) {
            if ("..".equals(trimmed)) {
                if (result.getParent() == null)
                    throw new IllegalStateException("node has no parent");
                result = result.getParent();
            } else {
                int index = Integer.parseInt(string);
                if (index >= 0) {
                    INode child = ((ICompositeNode) result).getFirstChild();
                    while(index > 0) {
                        child = child.getNextSibling();
                        index--;
                    }
                    result = child;
                }
            }
        }
    }
    return result;
}
项目:dsl-devkit    文件:CheckJavaValidator.java   
/**
 * Checks that an issue expression provides all required bindings.
 *
 * @param expression
 *          the expression
 */
@Check
public void checkIssuedBindings(final XIssueExpression expression) {
  if (generatorExtensions.issuedCheck(expression) == null) {
    return;
  }
  String message = generatorExtensions.issuedCheck(expression).getMessage();
  if (Strings.isEmpty(message)) {
    return;
  }
  try {
    int boundParameters = expression.getMessageParameters().size();
    int requiredBindings = new MessageFormat(message).getFormatsByArgumentIndex().length;

    if (boundParameters != requiredBindings) {
      error(NLS.bind(Messages.CheckJavaValidator_ISSUED_BINDINGS, requiredBindings, boundParameters), CheckPackage.Literals.XISSUE_EXPRESSION__MESSAGE_PARAMETERS, IssueCodes.ISSUED_BINDINGS);
    }
    // CHECKSTYLE:OFF
  } catch (IllegalArgumentException e) {
    // CHECKSTYLE:ON
    // do nothing here, because we can have potentially wrong messages given to MessageFormat, e.g. "{}"
  }

}
项目:xtext-extras    文件:TypeLiteralLinkingCandidate.java   
@Override
protected void preApply() {
    XAbstractFeatureCall expression = getExpression();
    JvmType type = getType();
    if (expression instanceof XMemberFeatureCall) {
        if (type instanceof JvmDeclaredType) {
            JvmDeclaredType declaredType = (JvmDeclaredType) type;
            if (declaredType.getDeclaringType() == null) {
                helper.applyPackageFragment((XMemberFeatureCall) expression, declaredType);
            } else {
                String queriedName = description.getName().toString(); // may be Map$Entry
                String qualifiedName = declaredType.getIdentifier();
                String packageName = Strings.emptyIfNull(declaredType.getPackageName());
                if (packageName.length() + 1 + queriedName.length() == qualifiedName.length()) {
                    helper.applyPackageFragment((XMemberFeatureCall) expression, declaredType);
                }
            }
        }
    }
}
项目:xtext-core    文件:ContentAssistContextFactory.java   
protected void createContextsForLastCompleteNode(EObject previousModel, boolean strict) {
    String currentNodePrefix = getPrefix(currentNode);
    if (!Strings.isEmpty(currentNodePrefix) && !currentNode.getText().equals(currentNodePrefix)) {
        lexer.setCharStream(new ANTLRStringStream(currentNodePrefix));
        Token token = lexer.nextToken();
        if (token == Token.EOF_TOKEN) { // error case - nothing could be parsed
            return;
        }
        while(token != Token.EOF_TOKEN) {
            if (isErrorToken(token))
                return;
            token = lexer.nextToken();
        }
    }
    String prefix = "";
    String completeInput = getInputToParse(document, completionOffset);
    Collection<FollowElement> followElements = parser.getFollowElements(completeInput, strict);
    doCreateContexts(lastCompleteNode, currentNode, prefix, previousModel, followElements);
}
项目:xtext-core    文件:SlotEntry.java   
protected boolean matches(Set<EClass> eclasses, IEObjectDescription desc) {
    boolean valid = eclasses.isEmpty();
    for (Iterator<EClass> iterator = eclasses.iterator(); !valid && iterator.hasNext();) {
        EClass eClass = iterator.next();
        valid = valid || EcorePackage.Literals.EOBJECT == eClass || eClass.isSuperTypeOf(desc.getEClass());
    }
    if (name != null) {
        if (Strings.isEmpty(namespaceDelimiter)) {
            return valid && name.equals(desc.getName().toString());
        } else {
            QualifiedName qualifiedName = QualifiedName.create(name.split(Pattern.quote(getNamespaceDelimiter())));
            return valid && (qualifiedName == null || qualifiedName.equals(desc.getName()));
        }
    } 
    return valid;
}
项目:xtext-extras    文件:JvmTypesBuilder.java   
/**
 * Creates a getter method for the given property name and the field name.
 * 
 * Example: <code>
 * public String getPropertyName() {
 *   return this.fieldName;
 * }
 * </code>
 * 
 * @return a getter method for a JavaBeans property, <code>null</code> if sourceElement or name are <code>null</code>.
 */
/* @Nullable */
public JvmOperation toGetter(/* @Nullable */ final EObject sourceElement, /* @Nullable */ final String propertyName, /* @Nullable */ final String fieldName, /* @Nullable */ JvmTypeReference typeRef) {
    if(sourceElement == null || propertyName == null || fieldName == null) 
        return null;
    JvmOperation result = typesFactory.createJvmOperation();
    result.setVisibility(JvmVisibility.PUBLIC);
    String prefix = (isPrimitiveBoolean(typeRef) ? "is" : "get");
    result.setSimpleName(prefix + Strings.toFirstUpper(propertyName));
    result.setReturnType(cloneWithProxies(typeRef));
    setBody(result, new Procedures.Procedure1<ITreeAppendable>() {
        @Override
        public void apply(/* @Nullable */ ITreeAppendable p) {
            if(p != null) {
                p = p.trace(sourceElement);
                p.append("return this.");
                p.append(javaKeywords.isJavaKeyword(fieldName) ? fieldName+"_" : fieldName);
                p.append(";");
            }
        }
    });
    return associate(sourceElement, result);
}
项目:dsl-devkit    文件:FormatQualifiedNameConverter.java   
@Override
public QualifiedName toQualifiedName(final String qualifiedNameAsString) {
  if (qualifiedNameAsString == null || qualifiedNameAsString.equals("") || Strings.isEmpty(getDelimiter())) {
    return super.toQualifiedName(qualifiedNameAsString);
  }
  Matcher m = STRING_PATTERN.matcher(qualifiedNameAsString);
  if (m.find()) {
    String string = m.group();
    String before = qualifiedNameAsString.substring(0, qualifiedNameAsString.indexOf(string));
    String after = qualifiedNameAsString.substring(qualifiedNameAsString.indexOf(string) + string.length());
    String[] segments = segments(before);
    segments[segments.length - 1] = segments[segments.length - 1] + string; // NOPMD using StringBuffer here is silly IMHO
    segments = join(segments, segments(after));
    return QualifiedName.create(segments);
  }
  return super.toQualifiedName(qualifiedNameAsString);
}
项目:xtext-extras    文件:SerializerScopeProvider.java   
protected IScope doGetTypeScope(XMemberFeatureCall call, JvmType type) {
    if (call.isPackageFragment()) {
        if (type instanceof JvmDeclaredType) {
            int segmentIndex = countSegments(call);
            String packageName = ((JvmDeclaredType) type).getPackageName();
            List<String> splitted = Strings.split(packageName, '.');
            String segment = splitted.get(segmentIndex);
            return new SingletonScope(EObjectDescription.create(segment, type), IScope.NULLSCOPE);
        }
        return IScope.NULLSCOPE;
    } else {
        if (type instanceof JvmDeclaredType && ((JvmDeclaredType) type).getDeclaringType() == null) {
            return new SingletonScope(EObjectDescription.create(type.getSimpleName(), type), IScope.NULLSCOPE);
        } else {
            XAbstractFeatureCall target = (XAbstractFeatureCall) call.getMemberCallTarget();
            if (target.isPackageFragment()) {
                String qualifiedName = type.getQualifiedName();
                int dot = qualifiedName.lastIndexOf('.');
                String simpleName = qualifiedName.substring(dot + 1);
                return new SingletonScope(EObjectDescription.create(simpleName, type), IScope.NULLSCOPE);
            } else {
                return new SingletonScope(EObjectDescription.create(type.getSimpleName(), type), IScope.NULLSCOPE); 
            }
        }
    }
}
项目:xtext-extras    文件:XbaseImportedNamespaceScopeProvider.java   
/**
 * Create a new {@link ImportNormalizer} for the given namespace.
 * @param namespace the namespace.
 * @param ignoreCase <code>true</code> if the resolver should be case insensitive.
 * @return a new {@link ImportNormalizer} or <code>null</code> if the namespace cannot be converted to a valid
 * qualified name.
 */
protected ImportNormalizer createImportedNamespaceResolver(final String namespace, boolean ignoreCase) {
    if (Strings.isEmpty(namespace))
        return null;
    QualifiedName importedNamespace = qualifiedNameConverter.toQualifiedName(namespace);
    if (importedNamespace == null || importedNamespace.isEmpty()) {
        return null;
    }
    boolean hasWildCard = ignoreCase ? 
            importedNamespace.getLastSegment().equalsIgnoreCase(getWildCard()) :
            importedNamespace.getLastSegment().equals(getWildCard());
    if (hasWildCard) {
        if (importedNamespace.getSegmentCount() <= 1)
            return null;
        return doCreateImportNormalizer(importedNamespace.skipLast(1), true, ignoreCase);
    } else {
        return doCreateImportNormalizer(importedNamespace, false, ignoreCase);
    }
}
项目:xtext-extras    文件:XImportSectionNamespaceScopeProvider.java   
/**
 * Create a new {@link ImportNormalizer} for the given namespace.
 * @param namespace the namespace.
 * @param ignoreCase <code>true</code> if the resolver should be case insensitive.
 * @return a new {@link ImportNormalizer} or <code>null</code> if the namespace cannot be converted to a valid
 * qualified name.
 */
protected ImportNormalizer createImportedNamespaceResolver(final String namespace, boolean ignoreCase) {
    if (Strings.isEmpty(namespace))
        return null;
    QualifiedName importedNamespace = qualifiedNameConverter.toQualifiedName(namespace);
    if (importedNamespace == null || importedNamespace.isEmpty()) {
        return null;
    }
    boolean hasWildcard = ignoreCase ? 
            importedNamespace.getLastSegment().equalsIgnoreCase(getWildcard()) :
            importedNamespace.getLastSegment().equals(getWildcard());
    if (hasWildcard) {
        if (importedNamespace.getSegmentCount() <= 1)
            return null;
        return doCreateImportNormalizer(importedNamespace.skipLast(1), true, ignoreCase);
    } else {
        return doCreateImportNormalizer(importedNamespace, false, ignoreCase);
    }
}
项目:dsl-devkit    文件:CheckExtensionHelperManager.java   
/**
 * Finds extensions of given {@link ExtensionType extension type} in given {@link IPluginModelBase plugin model}.
 * If {@code type} is {@link ExtensionType#ALL}, all extensions which may be mapped to {@link ExtensionType} are
 * returned. (They must have an ID pattern as defined in {@link #getExtensionId(CheckCatalog, ExtensionType)}).
 *
 * @param pluginModel
 *          the plugin in which to find the extensions
 * @param catalogName
 *          qualified catalog name
 * @param type
 *          the extension type to be looked up
 * @return a collection of extensions in the plugin.xml that match given extension type
 */
private Collection<IPluginExtension> findExtensions(final IPluginModelBase pluginModel, final QualifiedName catalogName, final ExtensionType type) {
  IPluginExtension[] pluginExtensions = pluginModel.getPluginBase().getExtensions();
  final String extensionId = getExtensionId(catalogName, type);
  final String point = getExtensionHelper(type) == null ? null : getExtensionHelper(type).getExtensionPointId();

  return Collections2.filter(Arrays.asList(pluginExtensions), new Predicate<IPluginExtension>() {
    @Override
    public boolean apply(final IPluginExtension extension) {
      final String currentExtensionId = extension.getId();
      if (type == ExtensionType.ALL) {
        if (currentExtensionId == null) {
          return getAllExtensionPointIds().contains(extension.getPoint());
        } else {
          final int pos = currentExtensionId.lastIndexOf('.');
          return pos != -1 && getAllExtensionPointIds().contains(extension.getPoint()) && Strings.equal(currentExtensionId.substring(0, pos), extensionId);
        }
      } else {
        return Strings.equal(currentExtensionId, extensionId) && Strings.equal(extension.getPoint(), point);
      }
    }
  });
}
项目:xtext-core    文件:LazyURIEncoder.java   
public EObject resolveShortFragment(Resource res, String shortFragment) {
    List<String> split = Strings.split(shortFragment, '.');
    int contentsIdx = Integer.parseInt(split.get(0));
    EObject result = res.getContents().get(contentsIdx);
    int splitIdx = 1;
    while(splitIdx < split.size()) {
        int featureId = Integer.parseInt(split.get(splitIdx++));
        EReference reference = (EReference) result.eClass().getEStructuralFeature(featureId);
        if (reference.isMany()) {
            List<?> list = (List<?>) result.eGet(reference);
            int listIdx = Integer.parseInt(split.get(splitIdx++));
            result = (EObject) list.get(listIdx);
        } else {
            result = (EObject) result.eGet(reference);
        }
    }
    return result;
}
项目:xtext-core    文件:DefaultDeclarativeQualifiedNameProvider.java   
@Override
public QualifiedName getFullyQualifiedName(final EObject obj) {
    return cache.get(Tuples.pair(obj, "fqn"), obj.eResource(), new Provider<QualifiedName>(){

        @Override
        public QualifiedName get() {
            EObject temp = obj;
            QualifiedName qualifiedNameFromDispatcher = qualifiedName.invoke(temp);
            if (qualifiedNameFromDispatcher!=null)
                return qualifiedNameFromDispatcher;
            String name = getResolver().apply(temp);
            if (Strings.isEmpty(name))
                return null;
            QualifiedName qualifiedNameFromConverter = converter.toQualifiedName(name);
            while (temp.eContainer() != null) {
                temp = temp.eContainer();
                QualifiedName parentsQualifiedName = getFullyQualifiedName(temp);
                if (parentsQualifiedName != null)
                    return parentsQualifiedName.append(qualifiedNameFromConverter);
            }
            return qualifiedNameFromConverter;
        }
    });
}
项目:xtext-extras    文件:AppendableBasedTraceRegion.java   
protected void leftCompressTrace(String completeContent) {
    List<AbstractTraceRegion> allNested = getWritableNestedRegions();
    int i = 0;
    while (i < allNested.size()) {
        AppendableBasedTraceRegion nested = (AppendableBasedTraceRegion) allNested.get(i);
        int offset = nested.getMyOffset();
        int diff = 0;
        while(completeContent.charAt(offset + diff) <= ' ' && diff < nested.length) {
            diff++;
        }
        if (diff == nested.length) {
            allNested.remove(i);
        } else {
            nested.lineNumber += Strings.countLineBreaks(completeContent, offset, offset + diff);
            nested.offset += diff;
            nested.length -= diff;
            nested.leftCompressTrace(completeContent);
            i++;
        }
    }
}
项目:xtext-extras    文件:EclipseJavaCompiler.java   
public Writer getErrorWriter() {
    if (errorWriter == null) {
        errorWriter = new Writer() {
            @Override
            public void write(char[] data, int offset, int count) throws IOException {
                String message = String.copyValueOf(data, offset, count);
                if (!Strings.isEmpty(message.trim())) {
                    if (configuration.isVerbose())
                        LOG.warn(message);
                }
            }

            @Override
            public void flush() throws IOException {
            }

            @Override
            public void close() throws IOException {
            }
        };
    }
    return errorWriter;
}
项目:xtext-core    文件:KeywordInspector.java   
public void inspectKeywordHidesTerminalRule(Keyword keyword) {
    AbstractRule container = GrammarUtil.containingRule(keyword);
    if (container instanceof TerminalRule)
        return;
    Grammar grammar = GrammarUtil.getGrammar(container);
    List<TerminalRule> rules = GrammarUtil.allTerminalRules(grammar);
    for(TerminalRule rule: rules) {
        if (!rule.isFragment()) {
            AbstractElement element = rule.getAlternatives();
            if (element instanceof Keyword && Strings.isEmpty(element.getCardinality())) {
                String value = ((Keyword) element).getValue();
                if (value.equals(keyword.getValue()))
                acceptor.acceptError(
                        "The keyword '" + value + "' hides the terminal rule " + rule.getName()+ ".", 
                        keyword,
                        XtextPackage.Literals.KEYWORD__VALUE,
                        ValidationMessageAcceptor.INSIGNIFICANT_INDEX, null);
            }
        }
    }
}
项目:xtext-core    文件:QualifiedNameValueConverter.java   
@Override
public String toString(String value) {
    if (value == null) {
        throw new ValueConverterException("'null' is not a valid qualified name value", null, null);
    }
    String valueDelimiter = getValueNamespaceDelimiter();
    List<String> segments = valueDelimiter.length() == 1 ? Strings.split(value, valueDelimiter.charAt(0)) : Strings.split(value, valueDelimiter);
    int size = segments.size();
    if (size == 1) {
        return delegateToString(segments.get(0));
    }
    StringBuilder result = new StringBuilder(value.length());
    String delimiterToUse = getStringNamespaceDelimiter();
    for (int i = 0; i < size; i++) {
        if (i != 0) {
            result.append(delimiterToUse);
        }
        if (i == size - 1 && getWildcardLiteral().equals(segments.get(i))) {
            result.append(getWildcardLiteral());
        } else {
            result.append(delegateToString(segments.get(i)));
        }
    }
    return result.toString();
}
项目:xtext-core    文件:Validator.java   
@Override
public int compare(MWEDiagnostic o1, MWEDiagnostic o2) {
    Issue issue1 = (Issue) o1.getElement();
    Issue issue2 = (Issue) o2.getElement();
    int lineNumberCompare = nullSafeCompare(issue1.getLineNumber(), issue2.getLineNumber());
    if (lineNumberCompare != 0) {
        return lineNumberCompare;
    }
    int columnCompare = nullSafeCompare(issue1.getColumn(), issue2.getColumn());
    if (columnCompare != 0) {
        return columnCompare;
    }
    int offsetCompare = nullSafeCompare(issue1.getOffset(), issue2.getOffset());
    if (offsetCompare != 0) {
        return offsetCompare;
    }
    return Strings.notNull(o1.getMessage()).compareTo(Strings.notNull(o2.getMessage()));
}
项目:xtext-extras    文件:EMFGeneratorFragment.java   
@Override
public String[] getExportedPackagesRt(Grammar grammar) {
    List<GeneratedMetamodel> typeSelect = org.eclipse.xtext.EcoreUtil2.typeSelect(
            grammar.getMetamodelDeclarations(), GeneratedMetamodel.class);
    Set<String> exportedPackages = new LinkedHashSet<String>();
    if (modelPluginID == null) {
        for (GeneratedMetamodel generatedMetamodel : typeSelect) {
            final String modelPackage = Strings.skipLastToken(
                    getGeneratedEPackageName(grammar, generatedMetamodel.getEPackage()), ".");
            exportedPackages.add(modelPackage);
            exportedPackages.add(modelPackage + ".impl");
            exportedPackages.add(modelPackage + ".util");
        }
    }
    return exportedPackages.toArray(new String[exportedPackages.size()]);
}
项目:xtext-core    文件:EcoreQualifiedNameProvider.java   
@Override
public QualifiedName getFullyQualifiedName(final EObject obj) {
    return cache.get(Tuples.pair(obj, getCacheKey()), obj.eResource(), new Provider<QualifiedName>() {

        @Override
        public QualifiedName get() {
            EObject temp = obj;
            String name = nameDispatcher.invoke(temp);
            if (Strings.isEmpty(name))
                return null;
            QualifiedName qualifiedName = QualifiedName.create(name);
            if(!isRecurseParent(obj))
                return qualifiedName;
            QualifiedName parentsQualifiedName = getFullyQualifiedName(obj.eContainer());
            if (parentsQualifiedName == null)
                return null;
            else 
                return parentsQualifiedName.append(qualifiedName);
        }

    });
}
项目:dsl-devkit    文件:ParameterListMatcher.java   
/**
 * Adds a formal parameter to the set of parameters consumed so far during the matching process and updates status.
 * <p>
 * Checks if {@code formal} is a duplicate named formal and, if so, adds it to the list of duplicate formals.<br>
 * The result status is updated if {@code formal} is an invalid formal parameter.
 * </p>
 *
 * @param formal
 *          the formal parameter to add, may be {@code null}
 */
protected void addConsumedFormal(final IFormalParameter formal) {
  if (formal != null) {
    getConsumedFormals().add(formal);
    if (formal instanceof INamedFormalParameter) {
      INamedFormalParameter namedFormal = (INamedFormalParameter) formal;
      String name = namedFormal.getName();
      if (!Strings.isEmpty(name)) {
        if (getConsumedNamedFormals().containsKey(name) && !formal.isMulti()) {
          addDuplicateNamedFormal(namedFormal);
        } else {
          getConsumedNamedFormals().put(name, namedFormal);
          return;
        }
      }
    } else {
      return; // is an unnamed formal
    }
  }
  setStatus(ParameterListMatchStatus.INVALID_FORMAL);
}
项目:xtext-extras    文件:GeneratedClassAnnotation.java   
@Override
public String toString() {
    StringBuilder stringBuilder = new StringBuilder("@Generated(");
    if (includeDate || !Strings.isEmpty(comment)) {
        stringBuilder.append("value = ");
    }
    stringBuilder.append('\"').append(getGeneratorName()).append('\"');
    if (includeDate) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ");
        String date = dateFormat.format(new Date());
        stringBuilder.append(", date = \"").append(date).append('\"');
    }
    if (!Strings.isEmpty(comment)) {
        String convertedComment = Strings.convertToJavaString(comment);
        stringBuilder.append(", comments = \"").append(convertedComment).append('\"');
    }
    return stringBuilder.append(')').toString();
}
项目:xtext-core    文件:ManifestMergerTest.java   
@Test public void testNoLongLine() throws Exception {
    String packageName = getClass().getPackage().getName().replace('.', '/');
    InputStream resourceAsStream = getClass().getResourceAsStream("/" + packageName + "/Test_Manifest.MF");
    MergeableManifest manifest = new MergeableManifest(resourceAsStream);
    manifest.addExportedPackages(Collections.singleton("foobar"));
    assertTrue(manifest.isModified());
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    manifest.write(out);
    String result = out.toString();
    String lookup = "Require-Bundle: org.eclipse.xtext,";
    int idx = result.indexOf(lookup);
    assertTrue(idx != -1);
    idx += lookup.length();
    String lineDelimiter = Strings.newLine();
    for (int i=0; i< lineDelimiter.length(); i++) {
        assertEquals(result, lineDelimiter.charAt(i), result.charAt(idx+i));
    }
    assertEquals(result, ' ', result.charAt(idx + lineDelimiter.length()));
}
项目:xtext-core    文件:ImportedNamespaceAwareLocalScopeProvider.java   
/**
 * Create a new {@link ImportNormalizer} for the given namespace.
 * @param namespace the namespace.
 * @param ignoreCase <code>true</code> if the resolver should be case insensitive.
 * @return a new {@link ImportNormalizer} or <code>null</code> if the namespace cannot be converted to a valid
 * qualified name.
 */
protected ImportNormalizer createImportedNamespaceResolver(final String namespace, boolean ignoreCase) {
    if (Strings.isEmpty(namespace))
        return null;
    QualifiedName importedNamespace = qualifiedNameConverter.toQualifiedName(namespace);
    if (importedNamespace == null || importedNamespace.isEmpty()) {
        return null;
    }
    boolean hasWildCard = ignoreCase ? 
            importedNamespace.getLastSegment().equalsIgnoreCase(getWildCard()) :
            importedNamespace.getLastSegment().equals(getWildCard());
    if (hasWildCard) {
        if (importedNamespace.getSegmentCount() <= 1)
            return null;
        return doCreateImportNormalizer(importedNamespace.skipLast(1), true, ignoreCase);
    } else {
        return doCreateImportNormalizer(importedNamespace, false, ignoreCase);
    }
}