Java Code Examples for org.jboss.forge.furnace.util.Strings#isNullOrEmpty()

The following examples show how to use org.jboss.forge.furnace.util.Strings#isNullOrEmpty() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Versions.java    From furnace with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the Implementation version for the given {@link Class}
 * 
 * @param type the {@link Class} with the corresponding package
 * @return {@link Version} representation from the {@link Package#getImplementationVersion()} returned from
 *         {@link Class#getPackage()}
 */
public static Version getImplementationVersionFor(Class<?> type)
{
   Assert.notNull(type, "Type must not be null.");
   final Version result;
   Package pkg = type.getPackage();
   if (pkg == null)
   {
      result = EmptyVersion.getInstance();
   }
   else
   {
      String version = pkg.getImplementationVersion();
      if (Strings.isNullOrEmpty(version))
      {
         result = EmptyVersion.getInstance();
      }
      else
      {
         result = SingleVersion.valueOf(version);
      }
   }
   return result;
}
 
Example 2
Source File: DiscoverEjbAnnotationsRuleProvider.java    From windup with Eclipse Public License 1.0 6 votes vote down vote up
private void extractEJBMetadata(GraphRewrite event, JavaTypeReferenceModel javaTypeReference)
{
    javaTypeReference.getFile().setGenerateSourceReport(true);
    JavaAnnotationTypeReferenceModel annotationTypeReference = (JavaAnnotationTypeReferenceModel) javaTypeReference;

    JavaClassModel ejbClass = getJavaClass(javaTypeReference);

    String ejbName = getAnnotationLiteralValue(annotationTypeReference, "name");
    if (Strings.isNullOrEmpty(ejbName))
    {
        ejbName = ejbClass.getClassName();
    }

    String sessionType = javaTypeReference.getResolvedSourceSnippit()
                .substring(javaTypeReference.getResolvedSourceSnippit().lastIndexOf(".") + 1);

    Service<EjbSessionBeanModel> sessionBeanService = new GraphService<>(event.getGraphContext(), EjbSessionBeanModel.class);
    EjbSessionBeanModel sessionBean = sessionBeanService.create();

    Set<ProjectModel> applications = ProjectTraversalCache.getApplicationsForProject(event.getGraphContext(), javaTypeReference.getFile().getProjectModel());
    sessionBean.setApplications(applications);
    sessionBean.setBeanName(ejbName);
    sessionBean.setEjbClass(ejbClass);
    sessionBean.setSessionType(sessionType);
}
 
Example 3
Source File: DiscoverDataSourceAnnotationRuleProvider.java    From windup with Eclipse Public License 1.0 6 votes vote down vote up
private void extractDataSourceMetadata(GraphRewrite event, JavaTypeReferenceModel javaTypeReference)
{
    javaTypeReference.getFile().setGenerateSourceReport(true);
    JavaAnnotationTypeReferenceModel annotationTypeReference = (JavaAnnotationTypeReferenceModel) javaTypeReference;

    JavaClassModel datasourceClass = getJavaClass(javaTypeReference);

    String dataSourceName = getAnnotationLiteralValue(annotationTypeReference, "name");
    if (Strings.isNullOrEmpty(dataSourceName))
    {
        dataSourceName = datasourceClass.getClassName();
    }

    String isXaString = getAnnotationLiteralValue(annotationTypeReference, "transactional");

    boolean isXa = isXaString == null || Boolean.getBoolean(isXaString);

    Service<DataSourceModel> dataSourceService = new GraphService<>(event.getGraphContext(), DataSourceModel.class);
    DataSourceModel dataSourceModel = dataSourceService.create();
    Set<ProjectModel> applications = ProjectTraversalCache.getApplicationsForProject(event.getGraphContext(), javaTypeReference.getFile().getProjectModel());

    dataSourceModel.setApplications(applications);
    dataSourceModel.setName(dataSourceName);
    dataSourceModel.setXa(isXa);
    dataSourceModel.setJndiLocation(dataSourceName);
}
 
Example 4
Source File: Versions.java    From furnace with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the Specification version for the given {@link Class}
 * 
 * @param type the {@link Class} with the corresponding package
 * @return {@link Version} representation from the {@link Package#getSpecificationVersion()} returned from
 *         {@link Class#getPackage()}
 */
public static Version getSpecificationVersionFor(Class<?> type)
{
   Assert.notNull(type, "Type must not be null.");
   final Version result;
   Package pkg = type.getPackage();
   if (pkg == null)
   {
      result = EmptyVersion.getInstance();
   }
   else
   {
      String version = pkg.getSpecificationVersion();
      if (Strings.isNullOrEmpty(version))
      {
         result = EmptyVersion.getInstance();
      }
      else
      {
         result = SingleVersion.valueOf(version);
      }
   }
   return result;
}
 
Example 5
Source File: AbstractRulesetMetadata.java    From windup with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean hasTags(String tag, String... tags)
{
    Set<String> expected = new HashSet<>();
    if (!Strings.isNullOrEmpty(tag))
        expected.add(tag);

    if (tags != null)
    {
        for (String t : tags)
        {
            if (!Strings.isNullOrEmpty(tag))
                expected.add(t);
        }
    }

    return getTags().containsAll(expected);
}
 
Example 6
Source File: GitCommandCompletePostProcessor.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
@Override
public UserDetails preprocessRequest(String name, ExecutionRequest executionRequest, HttpServletRequest request) {
    StopWatch watch = new StopWatch();

    UserDetails userDetails = gitUserHelper.createUserDetails(request);
    // TODO this isn't really required if there's a secret associated with the BuildConfig source
    if (Strings.isNullOrEmpty(userDetails.getUser()) || Strings.isNullOrEmpty(userDetails.getUser())) {
        throw new NotAuthorizedException("You must authenticate to be able to perform this command");
    }

    if (Objects.equals(name, Constants.PROJECT_NEW_COMMAND)) {
        List<Map<String, Object>> inputList = executionRequest.getInputList();
        if (inputList != null) {
            Map<String, Object> page1 = inputList.get(0);
            if (page1 != null) {
                if (page1.containsKey(Constants.TARGET_LOCATION_PROPERTY)) {
                    page1.put(Constants.TARGET_LOCATION_PROPERTY, projectFileSystem.getUserProjectFolderLocation(userDetails));
                }
            }
        }
    }

    LOG.info("preprocessRequest took " + watch.taken());

    return userDetails;
}
 
Example 7
Source File: GitUserHelper.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
protected String getGogsURL(boolean external) {
    StopWatch watch = new StopWatch();

    String namespace = kubernetesClient.getNamespace();
    if (Strings.isNullOrEmpty(namespace)) {
        namespace = KubernetesHelper.defaultNamespace();
    }
    String serviceName = GOGS;
    String answer = KubernetesHelper.getServiceURL(kubernetesClient, serviceName, namespace, "http", external);
    if (Strings.isNullOrEmpty(answer)) {
        String kind = external ? "external" : "internal";
        throw new IllegalStateException("Could not find external URL for " + kind + " service: gogs!");
    }
    if (!external) {
        // lets stick with the service name instead as its easier to grok
        return "http://" + serviceName + "/";
    }

    LOG.info("getGogsURL took " + watch.taken());
    return answer;
}
 
Example 8
Source File: ExecutionRequest.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
/**
 * Lets generate a commit message with the command name and all the parameters we specify
 */
public static String createCommitMessage(String name, ExecutionRequest executionRequest) {
    StringBuilder builder = new StringBuilder(name);
    List<Map<String, Object>> inputList = executionRequest.getInputList();
    for (Map<String, Object> map : inputList) {
        Set<Map.Entry<String, Object>> entries = map.entrySet();
        for (Map.Entry<String, Object> entry : entries) {
            String key = entry.getKey();
            String textValue = null;
            Object value = entry.getValue();
            if (value != null) {
                textValue = value.toString();
            }
            if (!Strings.isNullOrEmpty(textValue) && !textValue.equals("0") && !textValue.toLowerCase().equals("false")) {
                builder.append(" --");
                builder.append(key);
                builder.append("=");
                builder.append(textValue);
            }
        }
    }
    return builder.toString();
}
 
Example 9
Source File: GitCommandCompletePostProcessor.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
public static String firstNotBlank(String... texts) {
    for (String text : texts) {
        if (!Strings.isNullOrEmpty(text)) {
            return text;
        }
    }
    return null;
}
 
Example 10
Source File: FunktionArchetypeSelectionWizardStep.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
@Override
public Result execute(UIExecutionContext context) throws Exception {
    UIContext uiContext = context.getUIContext();
    Project project = (Project) uiContext.getAttributeMap().get(Project.class);
    Archetype chosenArchetype = archetype.getValue();
    String coordinate = chosenArchetype.getGroupId() + ":" + chosenArchetype.getArtifactId() + ":"
            + chosenArchetype.getVersion();
    DependencyQueryBuilder depQuery = DependencyQueryBuilder.create(coordinate);
    String repository = chosenArchetype.getRepository();
    if (!Strings.isNullOrEmpty(repository)) {
        if (repository.endsWith(".xml")) {
            int lastRepositoryPath = repository.lastIndexOf('/');
            if (lastRepositoryPath > -1)
                repository = repository.substring(0, lastRepositoryPath);
        }
        if (!repository.isEmpty()) {
            depQuery.setRepositories(new DependencyRepository("archetype", repository));
        }
    }
    Dependency resolvedArtifact = dependencyResolver.resolveArtifact(depQuery);
    FileResource<?> artifact = resolvedArtifact.getArtifact();
    MetadataFacet metadataFacet = project.getFacet(MetadataFacet.class);
    File fileRoot = project.getRoot().reify(DirectoryResource.class).getUnderlyingResourceObject();
    ArchetypeHelper archetypeHelper = new ArchetypeHelper(artifact.getResourceInputStream(), fileRoot,
            metadataFacet.getProjectGroupName(), metadataFacet.getProjectName(), metadataFacet.getProjectVersion());
    JavaSourceFacet facet = project.getFacet(JavaSourceFacet.class);
    archetypeHelper.setPackageName(facet.getBasePackage());
    archetypeHelper.execute();
    return Results.success();
}
 
Example 11
Source File: GitCommandCompletePostProcessor.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
@Inject
public GitCommandCompletePostProcessor(KubernetesClient kubernetes,
                                       GitUserHelper gitUserHelper,
                                       ProjectFileSystem projectFileSystem) {
    this.kubernetes = kubernetes;
    this.gitUserHelper = gitUserHelper;
    this.projectFileSystem = projectFileSystem;
    this.useLocalGitHost = true;
    String useExternalGit = System.getenv("USE_EXTERNAL_GIT_ADDRESS");
    if (!Strings.isNullOrEmpty(useExternalGit) && useExternalGit.toLowerCase().equals("true")){
        useLocalGitHost = false;
    }
    LOG.info("Using " + (useLocalGitHost ? "internal" : "external") + " URLs for hosted git repositories");
}
 
Example 12
Source File: MavenAddonDependencyResolver.java    From furnace with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @param scope the scope to be tested upon
 * @return <code>true</code> if the scope indicates an exported dependency
 */
public static boolean isExported(String scope)
{
   String artifactScope = Strings.isNullOrEmpty(scope) ? JavaScopes.COMPILE : scope;
   switch (artifactScope)
   {
   case JavaScopes.COMPILE:
   case JavaScopes.RUNTIME:
      return true;
   case JavaScopes.PROVIDED:
   default:
      return false;
   }
}
 
Example 13
Source File: FurnaceDeploymentScenarioGenerator.java    From furnace with Eclipse Public License 1.0 5 votes vote down vote up
private void validate(Method deploymentMethod)
{
   if (!Modifier.isStatic(deploymentMethod.getModifiers()))
   {
      throw new IllegalArgumentException("Method annotated with " + Deployment.class.getName() + " is not static. "
               + deploymentMethod);
   }
   if (!Archive.class.isAssignableFrom(deploymentMethod.getReturnType())
            && !Descriptor.class.isAssignableFrom(deploymentMethod.getReturnType()))
   {
      throw new IllegalArgumentException(
               "Method annotated with " + Deployment.class.getName() +
                        " must have return type " + Archive.class.getName() + " or " + Descriptor.class.getName()
                        + ". " + deploymentMethod);
   }
   if (deploymentMethod.getParameterTypes().length != 0)
   {
      throw new IllegalArgumentException("Method annotated with " + Deployment.class.getName()
               + " can not accept parameters. " + deploymentMethod);
   }

   String name = deploymentMethod.getAnnotation(Deployment.class).name();
   try
   {
      if (!Strings.isNullOrEmpty(name) && !"_DEFAULT_".equals(name))
         AddonId.fromCoordinates(name);
   }
   catch (IllegalArgumentException e)
   {
      throw new IllegalArgumentException("@" + Deployment.class.getName()
               + " requires name in the format \"name,version\", but was \"" + name + "\". ");
   }

}
 
Example 14
Source File: FurnaceContainerConfiguration.java    From furnace with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void validate() throws ConfigurationException
{
   if (Strings.isNullOrEmpty(classifier))
   {
      throw new ConfigurationException("Classifier should not be null or empty");
   }
}
 
Example 15
Source File: DiscoverEjbAnnotationsRuleProvider.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
private void extractMessageDrivenMetadata(GraphRewrite event, JavaTypeReferenceModel javaTypeReference)
{
    javaTypeReference.getFile().setGenerateSourceReport(true);
    JavaAnnotationTypeReferenceModel annotationTypeReference = (JavaAnnotationTypeReferenceModel) javaTypeReference;

    JavaClassModel ejbClass = getJavaClass(javaTypeReference);

    String ejbName = getAnnotationLiteralValue(annotationTypeReference, "name");
    if (Strings.isNullOrEmpty(ejbName))
    {
        ejbName = ejbClass.getClassName();
    }

    JavaAnnotationTypeValueModel activationConfigAnnotation = annotationTypeReference.getAnnotationValues().get("activationConfig");

    String destination = getAnnotationLiteralValue(annotationTypeReference, "mappedName");
    if (StringUtils.isBlank(destination))
    {
        destination = getDestinationFromActivationConfig(activationConfigAnnotation);
    }

    Service<EjbMessageDrivenModel> messageDrivenService = new GraphService<>(event.getGraphContext(), EjbMessageDrivenModel.class);
    EjbMessageDrivenModel messageDrivenBean = messageDrivenService.create();
    Set<ProjectModel> applications = ProjectTraversalCache.getApplicationsForProject(event.getGraphContext(), javaTypeReference.getFile().getProjectModel());
    messageDrivenBean.setApplications(applications);
    messageDrivenBean.setBeanName(ejbName);
    messageDrivenBean.setEjbClass(ejbClass);

    if (StringUtils.isNotBlank(destination))
    {
        String destinationType = getPropertyFromActivationConfig(activationConfigAnnotation, "destinationType");

        JmsDestinationService jmsDestinationService = new JmsDestinationService(event.getGraphContext());
        messageDrivenBean.setDestination(jmsDestinationService.createUnique(applications, destination, destinationType));
    }
}
 
Example 16
Source File: HasClassificationHandler.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public HasClassification processElement(ParserContext handlerManager, Element element) throws ConfigurationException
{
    String pattern = $(element).attr("title");
    HasClassification classification = new HasClassification();

    if (!Strings.isNullOrEmpty(pattern))
        classification.setTitlePattern(pattern);

    return classification;
}
 
Example 17
Source File: HasHintHandler.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public HasHint processElement(ParserContext handlerManager, Element element) throws ConfigurationException
{
    String pattern = $(element).attr("message");
    HasHint hint = new HasHint();

    if (!Strings.isNullOrEmpty(pattern))
        hint.setMessagePattern(pattern);

    return hint;
}
 
Example 18
Source File: IndexJavaSourceFilesRuleProvider.java    From windup with Eclipse Public License 1.0 4 votes vote down vote up
private void addParsedClassToFile(GraphRewrite event, EvaluationContext context, JavaSourceFileModel sourceFileModel, FileInputStream fis)
{
    JavaSource<?> javaSource;
    try
    {
        javaSource = Roaster.parse(JavaSource.class, fis);
    }
    catch (ParserException e)
    {
        ClassificationService classificationService = new ClassificationService(event.getGraphContext());
        classificationService.attachClassification(event, context, sourceFileModel, UNPARSEABLE_JAVA_CLASSIFICATION, UNPARSEABLE_JAVA_DESCRIPTION);
        sourceFileModel.setParseError(UNPARSEABLE_JAVA_CLASSIFICATION + ": " + e.getMessage());
        return;
    }

    String packageName = javaSource.getPackage();
    // set the package name to the parsed value
    sourceFileModel.setPackageName(packageName);

    // Set the root path of this source file (if possible). As this could be coming from user-provided source, it
    // is possible that the path will not match the package name. In this case, we will likely end up with a null
    // root path.
    Path rootSourcePath = PathUtil.getRootFolderForSource(sourceFileModel.asFile().toPath(), packageName);
    if (rootSourcePath != null)
    {
        FileModel rootSourceFileModel = new FileService(event.getGraphContext()).createByFilePath(rootSourcePath.toString());
        sourceFileModel.setRootSourceFolder(rootSourceFileModel);
    }

    String qualifiedName = javaSource.getQualifiedName();

    String simpleName = qualifiedName;
    if (packageName != null && !packageName.isEmpty() && simpleName != null)
    {
        simpleName = simpleName.substring(packageName.length() + 1);
    }

    JavaClassService javaClassService = new JavaClassService(event.getGraphContext());
    JavaClassModel javaClassModel = javaClassService.create(qualifiedName);
    javaClassModel.setOriginalSource(sourceFileModel);
    javaClassModel.setSimpleName(simpleName);
    javaClassModel.setPackageName(packageName);
    javaClassModel.setQualifiedName(qualifiedName);
    javaClassModel.setClassFile(sourceFileModel);
    javaClassModel.setPublic(javaSource.isPublic());
    javaClassModel.setInterface(javaSource.isInterface());

    if (javaSource instanceof InterfaceCapable)
    {
        InterfaceCapable interfaceCapable = (InterfaceCapable) javaSource;
        List<String> interfaceNames = interfaceCapable.getInterfaces();
        if (interfaceNames != null)
        {
            for (String iface : interfaceNames)
            {
                JavaClassModel interfaceModel = javaClassService.getOrCreatePhantom(iface);
                javaClassService.addInterface(javaClassModel, interfaceModel);
            }
        }
    }

    if (!javaSource.isInterface() && javaSource instanceof Extendable)
    {
        Extendable<?> extendable = (Extendable<?>) javaSource;
        String superclassName = extendable.getSuperType();
        if (!Strings.isNullOrEmpty(superclassName))
            javaClassModel.setExtends(javaClassService.getOrCreatePhantom(superclassName));
    }

    sourceFileModel.addJavaClass(javaClassModel);
}
 
Example 19
Source File: FurnaceImpl.java    From furnace with Eclipse Public License 1.0 4 votes vote down vote up
public FurnaceImpl()
{
   if (!AddonRepositoryImpl.hasRuntimeAPIVersion())
   {
      logger.warning("Could not detect Furnace runtime version - " +
               "loading all addons, but failures may occur if versions are not compatible.");
   }

   String addonCompatibilityValue = System.getProperty(FURNACE_ADDON_COMPATIBILITY_PROPERTY);
   if (!Strings.isNullOrEmpty(addonCompatibilityValue))
   {
      AddonCompatibilityStrategy strategy = null;
      try
      {
         strategy = AddonCompatibilityStrategies.valueOf(addonCompatibilityValue);
      }
      catch (IllegalArgumentException iae)
      {
         try
         {
            strategy = (AddonCompatibilityStrategy) Class.forName(addonCompatibilityValue).newInstance();
         }
         catch (Exception e)
         {
            logger.log(Level.SEVERE, "Error loading [" + addonCompatibilityValue
                     + "] defined by system property `" + FURNACE_ADDON_COMPATIBILITY_PROPERTY + "` ", e);
         }
      }
      if (strategy == null)
      {
         logger.warning("'" + addonCompatibilityValue + "' is not a valid value for the '"
                  + FURNACE_ADDON_COMPATIBILITY_PROPERTY + "' property. Possible values are: "
                  + Arrays.toString(AddonCompatibilityStrategies.values())
                  + " or a fully qualified class name. Assuming default value.");
      }
      else
      {
         setAddonCompatibilityStrategy(strategy);
      }
   }

   if (!Boolean.getBoolean(FURNACE_LOGGING_LEAK_CLASSLOADERS_PROPERTY))
   {
      /*
       * If enabled, allows the JDK java.util.logging.Level to leak ClassLoaders (memory leak).
       */
      LoggingRepair.init();
   }

   if (Boolean.getBoolean(FURNACE_DEBUG_PROPERTY))
   {
      /*
       * If enabled, prints a LOT of debug logging from JBoss Modules.
       */
      enableLogging();
   }
}
 
Example 20
Source File: GitUserHelper.java    From fabric8-forge with Apache License 2.0 4 votes vote down vote up
public UserDetails createUserDetails(HttpServletRequest request) {
    StopWatch watch = new StopWatch();

    String user = gitUser;
    String password = gitPassword;
    String authorization = null;
    String emailHeader = null;

    // lets try custom headers or request parameters
    if (request != null) {
        authorization = request.getHeader("GogsAuthorization");
        if (Strings.isNullOrEmpty(authorization)) {
            authorization = request.getParameter(Constants.RequestParameters.GOGS_AUTH);
        }
        emailHeader = request.getHeader("GogsEmail");
        if (Strings.isNullOrEmpty(emailHeader)) {
            emailHeader = request.getParameter(Constants.RequestParameters.GOGS_EMAIL);
        }
    }
    if (!Strings.isNullOrEmpty(authorization)) {
        String basicPrefix = "basic";
        String lower = authorization.toLowerCase();
        if (lower.startsWith(basicPrefix)) {
            String base64Credentials = authorization.substring(basicPrefix.length()).trim();
            String credentials = new String(Base64.decode(base64Credentials),
                    Charset.forName("UTF-8"));
            // credentials = username:password
            String[] values = credentials.split(":", 2);
            if (values != null && values.length > 1) {
                user = values[0];
                password = values[1];
            }
        }
    }
    String email = "[email protected]";
    if (!Strings.isNullOrEmpty(emailHeader)) {
        email = emailHeader;
    }
    if (Strings.isNullOrEmpty(address)) {
        address = getGogsURL(true);
        internalAddress = getGogsURL(false);
        if (!address.endsWith("/")) {
            address += "/";
        }
        if (!internalAddress.endsWith("/")) {
            internalAddress += "/";
        }
    }

    LOG.info("createUserDetails took " + watch.taken());
    return new UserDetails(address, internalAddress, user, password, email);
}