Get right dependencies name in custom plugin - plugins

buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.google.guava:guava:18.0'
}
}
apply plugin: LolPlugin
class LolPlugin implements Plugin<Project> {
public void apply(Project p) {
p.buildscript.dependencies.each {
println it
}
}
}
In this example, you can try to get dependencies name inside custom plugin class.
But it's different between contents of output and the expected .
I expect that,
'com.google.guava:guava:18.0'
But output is
org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependenciesHandler_Decorate#174b0a8

Almost duplicate of this question: How to iterate gradle dependencies in custom gradle plugin?
Short answer:
class LolPlugin implements Plugin<Project> {
public void apply(Project p) {
p.buildscript.configurations.each {
it.allDependencies.each {
println "${it.group}:${it.name}:${it.version}"
}
}
}
}

Related

Spring Boot Gradle setup

I tried to setup gradle in eclipse Luna for a simple spring boot application, but none of the jars are downloaded. Can anyone give me an idea of what I'm missing ?
I ran gradle clean build in the command line and it compiles successfully:
This is the content of my build.gradle file :
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.1.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'spring-boot'
jar {
baseName = 'sample'
version = '0.1.0'
}
repositories {
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
}
This is the content of the class with the controller:
package sample;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class SampleController {
#RequestMapping("/sample")
public String sampleIt(){
return "Hello! Welcome to Spring Boot Sample. ";
}
}
This is the class with the main function :
package sample;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
#SpringBootApplication
public class SampleApplication {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(SampleApplication.class, args);
System.out.println(ctx.getDisplayName());
System.out.println("This is my first Spring Boot Example");
}
}
Answer from the comment:
It is necessary to install the gradle plugin and import the gradle project afterwards. (Don't forget to click the 'Build Model' button)

Eclipse CDT extend AdapterFactory

I try to override the functionality of CDT ResumeAtLine, MoveToLine, RunToLine. For this reason I created a custom SuspendResumeAdapterFactory but it isn't loaded but compiles and runs without error. Do I maybe need a custom adaptableType too?
Here is the content of my plugin.xml.
<extension point="org.eclipse.core.runtime.adapters">
<factory
class="my.package.CustomSuspendResumeAdapterFactory"
adaptableType="org.eclipse.cdt.dsf.ui.viewmodel.IVMContext">
<adapter type="org.eclipse.debug.core.model.ISuspendResume"/>
</factory>
</extension>
And here my CustomSuspendResumeAdapterFactory this class is reconstructed from memory not 100% sure if the syntax is correct, but I think it should be clear to see what I want to do.
package my.package;
import org.eclipse.cdt.dsf.datamodel.DMContexts;
import org.eclipse.cdt.dsf.debug.internal.ui.actions.MoveToLine;
import org.eclipse.cdt.dsf.debug.internal.ui.actions.ResumeAtLine;
import org.eclipse.cdt.dsf.debug.internal.ui.actions.RunToLine;
import org.eclipse.cdt.dsf.debug.service.IRunControl.IContainerDMContext;
import org.eclipse.cdt.dsf.debug.service.IRunControl.IExecutionDMContext;
import org.eclipse.cdt.dsf.ui.viewmodel.datamodel.IDMVMContext;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IAdapterFactory;
import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.core.model.ISuspendResume;
public class CustomSuspendResumeAdapterFactory implements IAdapterFactory {
static class SuspendResume implements ISuspendResume, IAdaptable {
private final CustomRunToLine fRunToLine;
private final CustomMoveToLine fMoveToLine;
private final CustomResumeAtLine fResumeAtLine;
SuspendResume(IExecutionDMContext execCtx) {
fRunToLine = new CustomRunToLine(execCtx);
fMoveToLine = new CustomMoveToLine(execCtx);
fResumeAtLine = new CustomResumeAtLine(execCtx);
}
#SuppressWarnings("unchecked")
#Override
public <T> T getAdapter(Class<T> adapter) {
if (adapter.isInstance(RunToLine.class)) {
System.out.println("CUSTOM RUNTOLINE");
return (T)fRunToLine;
}
if (adapter.isInstance(MoveToLine.class)) {
System.out.println("CUSTOM MOVETOLINE");
return (T)fMoveToLine;
}
if (adapter.isInstance(ResumeToLine.class)) {
System.out.println("CUSTOM RESUMEATLINE");
return (T)fResumeAtLine;
}
return null;
}
#Override
public boolean canResume() { return false; }
#Override
public boolean canSuspend() { return false; }
// This must return true because the platform
// RunToLineActionDelegate will only enable the
// action if we are suspended
#Override
public boolean isSuspended() { return true; }
#Override
public void resume() throws DebugException {}
#Override
public void suspend() throws DebugException {}
}
#SuppressWarnings("unchecked")
#Override
public <T> T getAdapter(Object adaptableObject, Class<T> adapterType) {
if (ISuspendResume.class.equals(adapterType)) {
if (adaptableObject instanceof IDMVMContext) {
IExecutionDMContext execDmc = DMContexts.getAncestorOfType(
((IDMVMContext)adaptableObject).getDMContext(),
IExecutionDMContext.class);
// It only makes sense to RunToLine, MoveToLine or
// ResumeAtLine if we are dealing with a thread, not a container
if (execDmc != null && !(execDmc instanceof IContainerDMContext)) {
return (T)new SuspendResume(execDmc);
}
}
}
return null;
}
#Override
public Class<?>[] getAdapterList() {
return new Class[] { ISuspendResume.class };
}
}
Why your code is not run
You have provided a new adapter factory that converts object types that are already handled. i.e. your plugin.xml says you can convert IVMContext to ISuspendResume. But the DSF plug-in already provides such an adapter factory. If you have a new target type (like IMySpecialRunToLine) you could install a factory for that, it would take IVMContext and convert it to a IMySpecialRunToLine).
Although dated, the Eclipse Corner Article on Adapter Pattern may be useful if this is a new concept.
How to do custom Run To Line implementation
If you want to provide different implementation of Run To Line, you need to provide your own version of org.eclipse.cdt.dsf.debug.service.IRunControl2.runToLine(IExecutionDMContext, String, int, boolean, RequestMonitor). The org.eclipse.cdt.dsf.debug.internal.ui.actions.RunToLine class is simply glue to connect UI features (such as buttons/etc some provided directly, some by the core eclipse debug) to the DSF backend. i.e. if you look at what RunToLine does, all it actually does is get the IRunControl2 service and call runToLine on it.
The way to provider your own implementation of IRunControl2 is override org.eclipse.cdt.dsf.gdb.service.GdbDebugServicesFactory.createRunControlService(DsfSession) and provide your own GdbDebugServicesFactory in your custom launch delegate by overriding org.eclipse.cdt.dsf.gdb.launching.GdbLaunchDelegate.newServiceFactory(ILaunchConfiguration, String)
RunToLine will be triggered when the user select Run To Line from the popup menu in the editor, as per this screenshot:

E4 Preference Initializer won´t get called

I´m trying to migrate my e3-rcp-app to a e4-rcp-app.
Therefore I need to define my default Preferences. (Not the Pref.Pages)
And by doing and trying so, I just can´t get my Initializer called. Here Is my initializer-class:
public class MyPreferenceInitializer extends AbstractPreferenceInitializer {
public MyPreferenceInitializer (){}
#Override
public void initializeDefaultPreferences() {
Preferences defaults = DefaultScope.INSTANCE.getNode(InspectIT.ID);
// Set defaults using things like:
defaults.put("DUMMY", "DUMMYCONTENT");
try {
defaults.flush();
} catch (BackingStoreException e) {
e.printStackTrace();
}
//And this other approach to make sure that one of them works
IPreferenceStore store = InspectIT.getDefault().getPreferenceStore();
store.setDefault("DUMMY", "DUMMYCONTENT");
try {
((Preferences) store).flush();
} catch (BackingStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Dummy impl
default Preferences....,
}
}
I also got an Activator class with the following structure: (Just posting the relevant methods(?))
public class Activator implements BundleActivator {
private static BundleContext context;
static BundleContext getContext() {
return context;
}
private static Activator plugin;
private volatile ScopedPreferenceStore preferenceStore;
public void start(BundleContext context) throws Exception {
plugin = this;
Activator.context = context;
locateRuntimeDir();
logListener = new LogListener();
Platform.addLogListener(logListener);
//access to my initializor
String text = getPreferenceStore().getDefaultString("DUMMY");
String text2 = getPreferenceStore().getString("DUMMY");
}
public void stop(BundleContext context) throws Exception {
Activator.context = null;
plugin = null;
}
public static <E> E getService(Class<E> clazz) {
ServiceReference<E> reference = context.getServiceReference(clazz);
if (null != reference) {
return context.getService(reference);
}
throw new RuntimeException("Requested service of the class " + clazz.getName() + " is not registered in the bundle.");
}
public ScopedPreferenceStore getPreferenceStore() {
if (null == preferenceStore) {
synchronized (this) {
if (null == preferenceStore) {
preferenceStore = new ScopedPreferenceStore(ConfigurationScope.INSTANCE, ID);
}
}
}
return preferenceStore;
}
}
The ScopedPreferenceStore I´m using is the one available at: https://github.com/opcoach/e4Preferences/tree/master/com.opcoach.e4.preferences
As well, I declared the plugin.xml Extension like this (I do need this, right?)
...
<extension
point="org.eclipse.core.runtime.preferences">
<initializer class="MyApplication.rcp.preferences.MyPreferenceInitializer ">
</initializer>
</extension>
...
I´m using Eclipse 4.5.1 on a win7 x64
I googled a lot and found a lot of Threads concerning this, but I just can´t find my mistake =/.
Anyone got a suggestion for why my default preferences initializer won´t get called?
Thanks in advance
You must still use the org.eclipse.core.runtime.preferences extension point to define the preferences initializer.
<extension
point="org.eclipse.core.runtime.preferences">
<initializer
class="package.MyPreferenceInitializer">
</initializer>
</extension>
In the initializer use:
#Override
public void initializeDefaultPreferences()
{
Preferences defaults = DefaultScope.INSTANCE.getNode(Activator.ID);
// Set defaults using things like:
defaults.putInt("pref id", 0);
}
Finally I found a solution for this issue.
Accidentally got over this problem again and the mistake was in the Activator. I wrongly set the ID onto a wrong name. I reset it to my projects name and now it is working!
public ScopedPreferenceStore getPreferenceStore() {
if (null == preferenceStore) {
synchronized (this) {
if (null == preferenceStore)
preferenceStore = new ScopedPreferenceStore(ConfigurationScope.INSTANCE, ID);
}
}
return preferenceStore;
}
ID = Project-Name

refering to buildscript from Inner class in build.gradle

I have an inner class inside a buid.gradle:
class MyClass {
MyClass(String path) {
project.project(path);
}
}
That is failing, because it cannot find project. Is there any workaround for this?

How to iterate gradle dependencies in custom gradle plugin?

I have followed this guide:
http://www.gradle.org/docs/current/userguide/custom_plugins.html
to create a standalone gradle plugin with the following structure/files:
my-gradle-plugin
> src
> main
> java
> com
> mygroup
> MyGradlePlugin.groovy
> build.gradle
> settings.gradle
build.gradle :
apply plugin: 'groovy'
dependencies {
compile gradleApi()
groovy localGroovy()
}
apply plugin: 'maven'
repositories {
mavenCentral()
}
group = 'com.mygroup'
version = '1.0.0-SNAPSHOT'
MyGradlePlugin.groovy :
package com.mygroup
import org.gradle.api.*
class MyGradlePlugin implements Plugin<Project> {
void apply(Project project) {
print " project.name " + project.name + "\n"
print " project.dependencies " + project.dependencies + "\n"
// How do we iterate each dependency and print artifactId, group, version??
// project.dependencies.each {
// compile(it) {
// print it.next()
// print it.name
// }
// }
project.configurations.each {
print it.dump()
}
}
}
In another project I use/apply this plugin:
apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'eclipse'
repositories {
mavenLocal()
}
buildscript {
repositories {
mavenLocal()
}
dependencies {
classpath group: 'com.mygroup', name: 'my-gradle-plugin', version: '1.0.0-SNAPSHOT'
}
}
dependencies {
compile group: 'commons-codec', name: 'commons-codec', version: '1.4'
compile group: 'commons-beanutils', name: 'commons-beanutils', version: '1.7.0'
}
install.doLast {
apply plugin: 'my-gradle-plugin'
}
But how do I iterate the commons dependencies from the apply method in MyGradlePlugin.groovy and print their coordinates (artifactId, groupId, version)?
I know this is an old question but since there is not a selected answer I'll throw in an example that I have used. This is based on the example in section 49.8.2.2 of the gradle docs.
I'm using it to do custom dependency resolution, but you can do whatever you'd like inside the dependency iteration. Note that this works because its passing a closure that is executed after the configuration phase.
Plugin code:
package com.overtherainbow
import org.gradle.api.Project
import org.gradle.api.Plugin
import org.gradle.api.artifacts.DependencyResolveDetails
class DefaultVersionPlugin implements Plugin<Project> {
// This is where dependency versions are defined
def defaultVersionsMap = [
'javax.servlet:servlet-api' : '2.5',
'log4j:log4j' : '1.2.16']
void apply(Project project) {
project.configurations.all {
resolutionStrategy.eachDependency {
DependencyResolveDetails details -> resolveDependencyVersion(project, details)
}
}
}
def resolveDependencyVersion(Project project, DependencyResolveDetails details) {
if (details.requested.version == 'default') {
def version = resolveDefaultVersion(project, details.requested.group, details.requested.name)
details.useVersion version
}
}
def resolveDefaultVersion(Project project, String group, String name) {
project.logger.debug("Resolving default dependency for $group:$name")
println "Resolving default dependency for $group:$name"
defaultVersionsMap["$group:$name"]
}
}
The problem is that dependency graph is only available after project is fully evaluated. That's why you can't rely on that directly in the apply method. You have to postpone the execution using the afterEvaluate method. The following code will do the trick:
class MyGradlePlugin implements Plugin<Project> {
void apply(Project project) {
project.afterEvaluate {
println " Project:" + project.name
project.configurations.each { conf ->
println " Configuration: ${conf.name}"
conf.allDependencies.each { dep ->
println " ${dep.group}:${dep.name}:${dep.version}"
}
}
}
}
}
UPDATE: Following question updates and discussions in the comments and chat you can also do the following:
class MyGradlePlugin implements Plugin<Project> {
void apply(Project project) {
project.tasks.findByName('install')?.doLast {
...
}
}
}