Java Code Examples for org.jboss.forge.furnace.util.Strings

The following examples show how to use org.jboss.forge.furnace.util.Strings. These examples are extracted from open source projects. 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 Project: fabric8-forge   Source File: ExecutionRequest.java    License: 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 2
Source Project: fabric8-forge   Source File: GitUserHelper.java    License: 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 3
@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 4
Source Project: furnace   Source File: Versions.java    License: 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 Project: furnace   Source File: Versions.java    License: 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 6
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 7
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 8
Source Project: windup   Source File: AbstractRulesetMetadata.java    License: 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 9
@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 10
public static String firstNotBlank(String... texts) {
    for (String text : texts) {
        if (!Strings.isNullOrEmpty(text)) {
            return text;
        }
    }
    return null;
}
 
Example 11
@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 12
/**
 * @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
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
@Override
public void validate() throws ConfigurationException
{
   if (Strings.isNullOrEmpty(classifier))
   {
      throw new ConfigurationException("Classifier should not be null or empty");
   }
}
 
Example 15
Source Project: windup   Source File: HasClassificationHandler.java    License: 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 16
Source Project: windup   Source File: HasHintHandler.java    License: 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 17
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 18
Source Project: fabric8-forge   Source File: GitUserHelper.java    License: 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);
}
 
Example 19
@Override
public void firePostCompleteActions(String name, ExecutionRequest executionRequest, RestUIContext context, CommandController controller, ExecutionResult results, HttpServletRequest request) {
    StopWatch watch = new StopWatch();

    UserDetails userDetails = gitUserHelper.createUserDetails(request);
    String origin = projectFileSystem.getRemote();

    try {
        if (name.equals(Constants.PROJECT_NEW_COMMAND)) {

            String targetLocation = projectFileSystem.getUserProjectFolderLocation(userDetails);
            String named = null;
            List<Map<String, Object>> inputList = executionRequest.getInputList();

            for (Map<String, Object> map : inputList) {
                if (Strings.isNullOrEmpty(named)) {
                    Object value = map.get("named");
                    if (value != null) {
                        named = value.toString();
                    }
                }
            }
            if (Strings.isNullOrEmpty(targetLocation)) {
                LOG.warn("No targetLocation could be found!");
            } else if (Strings.isNullOrEmpty(named)) {
                LOG.warn("No named could be found!");
            } else {
                File basedir = new File(targetLocation, named);
                if (!basedir.isDirectory() || !basedir.exists()) {
                    LOG.warn("Generated project folder does not exist: " + basedir.getAbsolutePath());
                } else {
                    String namespace = firstNotBlank(context.getProjectName(), executionRequest.getNamespace());
                    String projectName = firstNotBlank(named, context.getProjectName(), executionRequest.getProjectName());
                    String message = ExecutionRequest.createCommitMessage(name, executionRequest);

                    BuildConfigHelper.CreateGitProjectResults createProjectResults = BuildConfigHelper.importNewGitProject(this.kubernetes, userDetails, basedir, namespace, projectName, origin, message, true, useLocalGitHost);

                    results.setOutputProperty("fullName", createProjectResults.getFullName());
                    results.setOutputProperty("cloneUrl", createProjectResults.getCloneUrl());
                    results.setOutputProperty("htmlUrl", createProjectResults.getHtmlUrl());

                    results.setProjectName(projectName);

                    LOG.info("Creating any pending webhooks");
                    registerWebHooks(context);

                    LOG.info("Done creating webhooks!");
                }
            }
        } else {
            registerWebHooks(context);
        }
    } catch (Exception e) {
        handleException(e);
    }

    LOG.info("firePostCompleteActions took " + watch.taken());
}
 
Example 20
Source Project: fabric8-forge   Source File: SpringBootNewProjectCommand.java    License: Apache License 2.0 4 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);
    if (project == null) {
        project = getSelectedProject(context.getUIContext());
    }
    MetadataFacet metadataFacet = project.getFacet(MetadataFacet.class);

    String projectName = metadataFacet.getProjectName();
    String groupId = metadataFacet.getProjectGroupName();
    String version = metadataFacet.getProjectVersion();
    File folder = project.getRoot().reify(DirectoryResource.class).getUnderlyingResourceObject();

    Map<String, SpringBootDependencyDTO> selectedDTOs = new HashMap<>();
    int[] selected = dependencies.getSelectedIndexes();
    CollectionStringBuffer csbSpringBoot = new CollectionStringBuffer(",");
    CollectionStringBuffer csbFabric8 = new CollectionStringBuffer(",");
    for (int val : selected) {
        SpringBootDependencyDTO dto = choices.get(val);
        if (isFabric8Dependency(dto.getId())) {
            csbFabric8.append(dto.getId());
        } else {
            csbSpringBoot.append(dto.getId());
        }
        selectedDTOs.put(dto.getId(), dto);
    }
    String springBootDeps = csbSpringBoot.toString();
    String fabric8Deps = csbFabric8.toString();
    // boot version need the RELEASE suffix
    String bootVersion = springBootVersion.getValue() + ".RELEASE";

    String url = String.format("%s?bootVersion=%s&groupId=%s&artifactId=%s&version=%s&packageName=%s&dependencies=%s",
            STARTER_URL, bootVersion, groupId, projectName, version, groupId, springBootDeps);

    LOG.info("About to query url: " + url);

    // use http client to call start.spring.io that creates the project
    OkHttpClient client = createOkHttpClient();

    Request request = new Request.Builder().url(url).build();

    Response response = client.newCall(request).execute();
    InputStream is = response.body().byteStream();

    // some archetypes might not use maven or use the maven source layout so lets remove
    // the pom.xml and src folder if its already been pre-created
    // as these will be created if necessary via the archetype jar's contents
    File pom = new File(folder, "pom.xml");
    if (pom.isFile() && pom.exists()) {
        pom.delete();
    }
    File src = new File(folder, "src");
    if (src.isDirectory() && src.exists()) {
        recursiveDelete(src);
    }

    File name = new File(folder, projectName + ".zip");
    if (name.exists()) {
        name.delete();
    }

    FileOutputStream fos = new FileOutputStream(name, false);
    copyAndCloseInput(is, fos);
    close(fos);

    // unzip the download from spring starter
    unzip(name, folder);

    LOG.info("Unzipped file to folder: {}", folder.getAbsolutePath());

    // and delete the zip file
    name.delete();

    if (!Strings.isEmpty(fabric8Deps)) {
        addFabric8DependenciesToPom(project, fabric8Deps, selectedDTOs);
    }

    // are there any fabric8 dependencies to add afterwards?
    return Results.success("Created new Spring Boot project in directory: " + folder.getName());
}
 
Example 21
Source Project: furnace   Source File: FurnaceImpl.java    License: 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 22
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);
}