Creating custom JUnit launch configuration in eclipse [duplicate] - java

I am trying to write a custom launch configuration while running a plugin project as an eclipse application. I have to run the plugin with limited dependencies. Is it possible to override methods in org.eclipse.pde.launching.EclipseApplicationLaunchConfiguration ? If yes then how do I do it ?

You can't easily override the methods in EclipseApplicationLaunchConfiguration. That would require writing a new launch configuration - probably by using the org.eclipse.debug.core.launchConfigurationTypes extension point to define a new launch type.
EclipseApplicationLaunchConfiguration always uses the settings from the current entry in the 'Eclipse Application' section of the 'Run Configurations'. You can always edit the run configuration to change the dependencies or create another run configuration with different dependencies.

To write a custom configuration file
Extend the class org.eclipse.jdt.junit.launcher.JUnitLaunchShortcut
Override the method createLaunchConfiguration
Invoking super.createLaunchConfiguration(element) will return a ILaunchConfigurationWorkingCopy
Use the copy and set your own attributes that have to be modified
Attributes can be found in IPDELauncherConstants
Eclipse by default runs all the projects found in the workspace. This behavior can be modified by using the configuration created and overriding it with custom configuration.
public class LaunchShortcut extends JUnitLaunchShortcut {
class PluginModelNameBuffer {
private List<String> nameList;
PluginModelNameBuffer() {
super();
this.nameList = new ArrayList<>();
}
void add(final IPluginModelBase model) {
this.nameList.add(getPluginName(model));
}
private String getPluginName(final IPluginModelBase model) {
IPluginBase base = model.getPluginBase();
String id = base.getId();
StringBuilder buffer = new StringBuilder(id);
ModelEntry entry = PluginRegistry.findEntry(id);
if ((entry != null) && (entry.getActiveModels().length > 1)) {
buffer.append('*');
buffer.append(model.getPluginBase().getVersion());
}
return buffer.toString();
}
#Override
public String toString() {
Collections.sort(this.nameList);
StringBuilder result = new StringBuilder();
for (String name : this.nameList) {
if (result.length() > 0) {
result.append(',');
}
result.append(name);
}
if (result.length() == 0) {
return null;
}
return result.toString();
}
}
#Override
protected ILaunchConfigurationWorkingCopy createLaunchConfiguration(final IJavaElement element)
throws CoreException {
ILaunchConfigurationWorkingCopy configuration = super.createLaunchConfiguration(element);
configuration.setAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS, "memory");
configuration.setAttribute(IPDELauncherConstants.USE_PRODUCT, false);
configuration.setAttribute(IPDELauncherConstants.USE_DEFAULT, false);
configuration.setAttribute(IPDELauncherConstants.AUTOMATIC_ADD, false);
addDependencies(configuration);
return configuration;
}
#SuppressWarnings("restriction")
private void addDependencies(final ILaunchConfigurationWorkingCopy configuration) throws CoreException {
PluginModelNameBuffer wBuffer = new PluginModelNameBuffer();
PluginModelNameBuffer tBuffer = new PluginModelNameBuffer();
Set<IPluginModelBase> addedModels = new HashSet<>();
String projectName = configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, "");
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
IPluginModelBase model = PluginRegistry.findModel(project);
wBuffer.add(model);
addedModels.add(model);
IPluginModelBase[] externalModels = PluginRegistry.getExternalModels();
for (IPluginModelBase externalModel : externalModels) {
String id = externalModel.getPluginBase().getId();
if (id != null) {
switch (id) {
case "org.eclipse.ui.ide.application":
case "org.eclipse.equinox.ds":
case "org.eclipse.equinox.event":
tBuffer.add(externalModel);
addedModels.add(externalModel);
break;
default:
break;
}
}
}
TreeSet<String> checkedWorkspace = new TreeSet<>();
IPluginModelBase[] workspaceModels = PluginRegistry.getWorkspaceModels();
for (IPluginModelBase workspaceModel : workspaceModels) {
checkedWorkspace.add(workspaceModel.getPluginBase().getId());
}
EclipsePluginValidationOperation eclipsePluginValidationOperation = new EclipsePluginValidationOperation(
configuration);
eclipsePluginValidationOperation.run(null);
while (eclipsePluginValidationOperation.hasErrors()) {
Set<String> additionalIds = DependencyManager.getDependencies(addedModels.toArray(), true, null);
if (additionalIds.isEmpty()) {
break;
}
additionalIds.stream().map(PluginRegistry::findEntry).filter(Objects::nonNull).map(ModelEntry::getModel)
.forEach(addedModels::add);
for (String id : additionalIds) {
IPluginModelBase plugin = findPlugin(id);
if (checkedWorkspace.contains(plugin.getPluginBase().getId())
&& (!plugin.getPluginBase().getId().endsWith("tests"))) {
wBuffer.add(plugin);
} else {
tBuffer.add(plugin);
}
}
eclipsePluginValidationOperation.run(null);
}
configuration.setAttribute(IPDELauncherConstants.SELECTED_WORKSPACE_PLUGINS, wBuffer.toString());
configuration.setAttribute(IPDELauncherConstants.SELECTED_TARGET_PLUGINS, tBuffer.toString());
}
protected IPluginModelBase findPlugin(final String id) {
ModelEntry entry = PluginRegistry.findEntry(id);
if (entry != null) {
return entry.getModel();
}
return null;
}
}

Related

Synchronization of two workspaces in same RTC repository

I am working currently on a project using RTC (Rational Team Concert) through Plain Java API.
I have a online-repository on which I have a main stream named Sample_ROOT. From this stream I want to create another one named Sample_Client_Application. The Sample_Client_Application should have all components of Sample_ROOT and whenever changes are committed in Sample_ROOT, they have to be pushed into Sample_Client_Application.
I tried to implement all the process described above in eclipse with RTC Plain Java API with the code below.
/*
parentStream : represents Sample_ROOT
appStream : represents DTO of Sample_Client_Application
projectStreams is a map of projects with their workspaces : HashMap<String, List<IWorkspaceHandle>>
*/
public IWorkspaceConnection createAppInTeamAreas(String parentStream, StreamDTO appStream)
throws TeamRepositoryException {
monitor.println("Getting Workspace");
IWorkspaceManager workspaceManager = SCMPlatform.getWorkspaceManager(repository);
IWorkspaceConnection workspaceConnection = null;
Optional<IWorkspaceHandle> handle = projectStreams.get(appStream.getProjectName()).stream().filter(xHandle -> {
IWorkspace workspace = null;
try {
workspace = (IWorkspace) repository.itemManager().fetchCompleteItem(xHandle, IItemManager.DEFAULT,
null);
} catch (TeamRepositoryException e) {
e.printStackTrace();
}
return workspace != null && workspace.getName() == parentStream;
}).findFirst();
if (handle.isPresent()) {
IWorkspace parentWorkSpace = null;
try {
parentWorkSpace = (IWorkspace) repository.itemManager().fetchCompleteItem(handle.get(),
IItemManager.DEFAULT, null);
} catch (TeamRepositoryException e) {
e.printStackTrace();
return null;
}
IWorkspaceConnection parentConn = workspaceManager.getWorkspaceConnection(handle.get(), monitor);
List<IComponentHandle> parentComps = (List<IComponentHandle>) parentConn.getComponents();
IWorkspaceConnection childConn = null;
IItemManager itemManager = repository.itemManager();
for (IComponentHandle parentCompHandle : parentComps) {
IItemHandle itemHandle = (IItemHandle) parentCompHandle;
IComponent parentComp = (IComponent) itemManager.fetchCompleteItem(itemHandle, IItemManager.DEFAULT,
monitor);
monitor.println(String.format("Component name : %s", parentComp.getName()));
childConn = createAndAddSycrhronizedComponents(parentWorkSpace, parentComp, parentConn, appStream,
childConn);
}
workspaceConnection = childConn;
}
return workspaceConnection;
}
private IWorkspaceConnection createAndAddSycrhronizedComponents(IWorkspace parentStream, IComponent parentComp,
IWorkspaceConnection parentConnection, StreamDTO childStream, IWorkspaceConnection childConnection) {
IWorkspaceManager workspaceManager = SCMPlatform.getWorkspaceManager(repository);
IWorkspaceConnection workspaceConnection = null;
try {
if (childConnection == null) {
workspaceConnection = workspaceManager.createWorkspace(repository.loggedInContributor(),
childStream.getName(), childStream.getDescription(), monitor);
} else {
workspaceConnection = childConnection;
//Set flow for the newly created repository
IFlowTable flowTarget=workspaceConnection.getFlowTable().getWorkingCopy();
flowTarget.addDeliverFlow(parentStream, repository.getId(), repository.getRepositoryURI(), parentConnection.getComponents(), "Scoped");
flowTarget.addAcceptFlow(parentStream, repository.getId(), repository.getRepositoryURI(), parentConnection.getComponents(), "Scoped");
flowTarget.setCurrent(flowTarget.getDeliverFlow(parentStream));
flowTarget.setCurrent(flowTarget.getAcceptFlow(parentStream));
flowTarget.setDefault(flowTarget.getDeliverFlow(parentStream));
flowTarget.setDefault(flowTarget.getAcceptFlow(parentStream));
workspaceConnection.setFlowTable(flowTarget, monitor);
//Add the components to the workspace
List<Object> componentsToBeAdded=new ArrayList<>();
componentsToBeAdded.add(workspaceConnection.componentOpFactory().addComponent(parentComp, true));
workspaceConnection.applyComponentOperations(componentsToBeAdded, monitor);
//Accept stream changes to local repository
IChangeHistorySyncReport streamChangeHistorySyncReport=workspaceConnection.compareTo(parentConnection, WorkspaceComparisonFlags.INCLUDE_BASELINE_INFO, Collections.EMPTY_LIST, null);
workspaceConnection.accept(AcceptFlags.DEFAULT, parentConnection, streamChangeHistorySyncReport, streamChangeHistorySyncReport.incomingBaselines(parentComp), streamChangeHistorySyncReport.incomingChangeSets(parentComp), monitor);
}
} catch (TeamRepositoryException e) {
e.printStackTrace();
}
return workspaceConnection;
}
Sample_Client_Application is created successfully but it has no components. Can anyone help me Please ?

Eclipse Californium CoAP wildcard as url path

I'm working on a CoAP app using Eclipse Californium that will declare explicitly only the root resource path, and the rest of the resources should be served and resolved through a wildcard /root/* just like on REST APIs or servlets.
Is there any way to achieve that ?
Ok I managed to do it.
So after a few hours of digging on their Source code here is what ended up doing.
Note that it works but it's only to show how it could be done, it's still a work on progress (I did this in 3h) as I removed some code like observer etc..
As soon as I have some time, I'll digg onto the Californium Api more and make this generic and optimized I'll create a Github project and link it here.
1 : Create a model class
public class ProxyRes {
public CoapResource coapRes;
public String path;
public ProxyRes () {
}
public CoapResource getCoapRes () {
return coapRes;
}
public void setCoapRes (CoapResource coapRes) {
this.coapRes = coapRes;
}
public String getPath () {
return path;
}
public void setPath (String path) {
this.path = path;
}
}
2 : Create an abstract CoapResource that should inject the Wildcards list
public abstract class AbstractResource extends CoapResource {
private LinkedList<String> wildcards;
protected AbstractResource (String name) {
super (name);
}
protected AbstractResource (String name, boolean visible) {
super (name, visible);
}
public LinkedList<String> getWildcards () {
return wildcards;
}
public void setWildcards (LinkedList<String> wildcards) {
this.wildcards = wildcards;
}
}
3 : Create a Temperature Resource extending AbstractResource
public class TemperatureResource extends AbstractResource {
public TemperatureResource () {
super (ResourceSpecs.House.Sensors.Temperature);
getAttributes ().setTitle ("Temperature resource !");
}
#Override
public void handleGET (CoapExchange exchange) {
String response = "The temperature";
if (getWildcard () != null) {
response += " of the " + getWildcard ().get (0) + " on the " + getWildcard ().get (1);
}
response += " is : 25 degree C";
exchange.respond (response);
}
}
4 : Create a resources directory on the root of my eclipse project, with json conf files of my resources
{
"verb": "get",
"endpoint": "/houses/*/rooms/*/sensors/temperature",
"class": "com.wild.coap.resources.TemperatureResource"
}
5 : Create a Resources Loader (class that will load the specs definition of the resources and instantiate them independently instead of creating a Tree on the server)
public class ResourcesLoader {
private final static String Path = new File (".").getAbsolutePath () + File.separator + "resources";
private List<ProxyRes> resourcesList;
public ResourcesLoader () throws Exception {
resourcesList = new ArrayList<ProxyRes> ();
File resources = new File (Path);
for (String resName : resources.list ()) {
File resFile = new File (resources, resName);
InputStream is = new FileInputStream (resFile);
JsonObject o = new JsonObject (is);
resourcesArr.add (o);
resourcesList.add (buildObject (o));
}
}
private ProxyRes buildObject (JsonObject o) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
ProxyRes r = new ProxyRes ();
r.setPath (o.getString ("endpoint"));
Class<?> clazz = Class.forName (o.getString ("class"));
CoapResource coapRes = (CoapResource)clazz.newInstance ();
r.setCoapRes (coapRes);
return r;
}
public List<ProxyRes> getResourcesList () {
return resourcesList;
}
}
6 : Create a Custom MessageDelieverer
public class DynamicMessageDeliverer implements MessageDeliverer {
private final List<ProxyRes> resources;
public DynamicMessageDeliverer (List<ProxyRes> resources) {
this.resources = resources;
}
public void deliverRequest (final Exchange exchange) {
Request request = exchange.getRequest ();
List<String> path = request.getOptions ().getUriPath ();
final Resource resource = registerResources (path);
if (resource != null) {
executeResource (exchange, resource);
} else {
exchange.sendResponse (new Response (ResponseCode.NOT_FOUND));
throw new RuntimeException ("Did not find resource " + path.toString() + " requested by " + request.getSource()+":"+request.getSourcePort());
}
}
private void executeResource (final Exchange exchange, final Resource resource) {
// Get the executor and let it process the request
Executor executor = resource.getExecutor ();
if (executor != null) {
exchange.setCustomExecutor ();
executor.execute (new Runnable () {
public void run () {
resource.handleRequest (exchange);
}
});
} else {
resource.handleRequest (exchange);
}
}
private Resource registerResources (List<String> list) {
LinkedList<String> path = new LinkedList<String> (list);
String flatRequestedEndpoint = Arrays.toString (path.toArray ());
LinkedList<String> wildcards = new LinkedList <String> ();
ProxyRes retainedResource = null;
for (ProxyRes proxyRes : resources) {
String[] res = proxyRes.getPath ().replaceFirst ("/", "").split ("/");
int length = res.length;
if (length != path.size ()) {
continue;
}
String flatResEndpoint = Arrays.toString (res);
if (flatResEndpoint.equals (flatRequestedEndpoint)) {
retainedResource = proxyRes;
break;
}
boolean match = true;
for (int i = 0; i < length; i ++) {
String str = res[i];
if (str.equals ("*")) {
wildcards.add (path.get (i));
continue;
}
if (!str.equals (path.get (i))) {
match = false;
break;
}
}
if (!match) {
wildcards.clear ();
continue;
}
retainedResource = proxyRes;
break;
}
if (retainedResource == null) {
return null;
}
((AbstractResource)retainedResource.getCoapRes ()).setWildcard (wildcards);
return retainedResource.getCoapRes ();
}
public void deliverResponse (Exchange exchange, Response response) {
if (response == null) throw new NullPointerException();
if (exchange == null) throw new NullPointerException();
if (exchange.getRequest() == null) throw new NullPointerException();
exchange.getRequest().setResponse(response);
Request request = exchange.getRequest ();
List<String> path = request.getOptions ().getUriPath ();
System.out.println ("Path retrieved : " + Arrays.toString (path.toArray ()));
}
}
7 : Create the Server
public class WildCoapServer extends CoapServer {
private static final int COAP_PORT = NetworkConfig.getStandard ().getInt (NetworkConfig.Keys.COAP_PORT);
public WildCoapServer () throws Exception {
// add endpoints on all IP addresses
addEndpoints ();
ResourcesLoader resLoader = new ResourcesLoader ();
List<ProxyRes> resources = resLoader.getResourcesList ();
setMessageDeliverer (new DynamicMessageDeliverer (resources));
}
#Override
protected Resource createRoot () {
return new WildRootResource ();
}
// Add individual endpoints listening on default CoAP port on all IPv4 addresses of all network interfaces.
private void addEndpoints () {
for (InetAddress addr : EndpointManager.getEndpointManager ().getNetworkInterfaces ()) {
// only binds to IPv4 addresses and localhost
if (addr instanceof Inet4Address || addr.isLoopbackAddress ()) {
InetSocketAddress bindToAddress = new InetSocketAddress (addr, COAP_PORT);
addEndpoint (new CoapEndpoint (bindToAddress));
}
}
}
}
8 : Start the server
public class Main {
public static void main (String[] args) {
try {
WildCoapServer server = new WildCoapServer ();
server.start ();
} catch (Exception e) {
throw new RuntimeException (e.getMessage (), e);
}
}
}
9 : Consume the Temperature resource from a client
public class Client {
public static void main (String[] args) {
URI uri = null;
try {
uri = new URI ("coap://192.168.200.1:5683/houses/house1/rooms/kitchen/sensors/temperature");
} catch (URISyntaxException e) {
throw new RuntimeException (e.getMessage (), e);
}
CoapClient client = new CoapClient (uri);
CoapResponse response = client.get ();
if (response != null) {
System.out.println (response.getCode ());
System.out.println (response.getOptions ());
System.out.println (response.getResponseText ());
System.out.println ("\nADVANCED\n");
// access advanced API with access to more details through .advanced ()
System.out.println (Utils.prettyPrint (response));
} else {
System.out.println ("No response received.");
}
}
}
Hope that helps someone.
This is my solution for this problem.
CoapResource wildcard = new CoapResource("*") {
#Override
public void handleGET(CoapExchange exchange) {
...
}
};
CoapResource root = new CoapResource("root") {
#Override
public Resource getChild(String name) {
return wildcard;
}
};

Testing controllers using Spring, JUNIT, MockMvc and Hamcrest

I am trying to test a controller of mine which returns me a List of Objects on the get method to populate a dropdown on my page.
I am trying to write a JUnit test using MockMvc and Hamcrest to test the same.
I want to compare the List of objects and test if it fails or not.
I have created a static List of objects in my Test.java and I am getting a List of objects from the model.attribute method.
To Test: if both the List of Objects are equal and don't contain any other objects.
My object is called Option which has 3 properties. Key, Value and Selected. I have to check if the all the keys exists in the List or not.
I am unable to create a matcher to do the same. I am trying to create a matcher to compare my List.
So far I have done the following:
#Before
public void setup() throws Exception {
// This would build a MockMvc with only the following controller
this.mockMvc = MockMvcBuilders.standaloneSetup(openAccountController)
.build();
}
#Test
public void testOpenAccount() {
try {
setAllLegislations();
this.mockMvc
.perform(get("/open_account.htm"))
// This method is used to print out the actual httprequest
// and httpresponse on the console.
.andDo(print())
// Checking if status is 200
.andExpect(status().isOk())
.andExpect(
model().attributeExists("appFormAccountPlans",
"appFormLiraLegislations",
"appFormLrspLegislations",
"appFormRlspLegislations"))
.andExpect(
model().attribute("appFormAccountPlans", hasSize(5)))
.andExpect(
model().attribute("appFormLiraLegislations",
hasSize(8)))
.andExpect(
model().attribute("appFormLrspLegislations",
hasSize(2)))
.andExpect(
model().attribute("appFormRlspLegislations",
hasSize(1)))
.andExpect(
model().attribute(
"appFormLiraLegislations",
hasKeyFeatureMatcher(getLiraLegislations(allLegislations))));
private Matcher<List<Option>> hasKeyFeatureMatcher(
final List<Option> expectedOptions) {
return new FeatureMatcher<List<Option>, List<Option>>(
equalTo(expectedOptions), "Options are", "was") {
#Override
protected List<Option> featureValueOf(List<Option> actualOptions) {
boolean flag = false;
if (actualOptions.size() == expectedOptions.size()) {
for (Option expectedOption : expectedOptions) {
for (Option actualOption : actualOptions) {
if (expectedOption.getKey().equals(
actualOption.getKey())) {
flag = true;
} else {
flag = false;
break;
}
}
}
}
if (flag)
return actualOptions;
else
return null;
}
};
}
private List<Option> getLiraLegislations(List<Option> legislation) {
List<Option> liraLegislations = new ArrayList<Option>();
Iterator<Option> iterator = legislation.iterator();
while (iterator.hasNext()) {
Option option = iterator.next();
if (LIRA_LEGISLATIONS.contains(option.getKey())) {
liraLegislations.add(option);
}
}
return liraLegislations;
}
private List<Option> allLegislations;
public List<Option> getAllLegislations() {
return allLegislations;
}
public void setAllLegislations() {
allLegislations = new ArrayList<Option>();
for (String key : ALL_LEGISLATIONS) {
Option option = new Option();
option.setKey(key);
allLegislations.add(option);
}
}
private static final Set<String> ALL_LEGISLATIONS = new HashSet<String>(
Arrays.asList(AccountLegislationEnum.AB.toString(),
AccountLegislationEnum.MB.toString(),
AccountLegislationEnum.NB.toString(),
AccountLegislationEnum.NL.toString(),
AccountLegislationEnum.NS.toString(),
AccountLegislationEnum.ON.toString(),
AccountLegislationEnum.QC.toString(),
AccountLegislationEnum.SK.toString(),
AccountLegislationEnum.BC.toString(),
AccountLegislationEnum.FE.toString(),
AccountLegislationEnum.NT.toString(),
AccountLegislationEnum.PE.toString(),
AccountLegislationEnum.YT.toString(),
AccountLegislationEnum.NU.toString(),
AccountLegislationEnum.UNKNOWN.toString()));
This is how I am getting my model attribute as:
Attribute = appFormLiraLegislations
value = [com.abc.arch.core.gui.eform.gui.Option#199d1739, com.abc.arch.core.gui.eform.gui.Option#185fac52, com.abc.arch.core.gui.eform.gui.Option#312a47fe, com.abc.arch.core.gui.eform.gui.Option#4edc8de9, com.abc.arch.core.gui.eform.gui.Option#71e8e471, com.abc.arch.core.gui.eform.gui.Option#70edf123, com.abc.arch.core.gui.eform.gui.Option#15726ac1, com.abc.arch.core.gui.eform.gui.Option#abeafe7]
Thanks in advance.
You can make your life definitely easier when you correctly implement Option object hashCode() and equals() methods using key attribute; then you can simply write:
model().attribute("appFormLiraLegislations",getLiraLegislations(allLegislations)))
and rely on list1.equals(list2) method to do the work for you.
Option hashCode and equals implementation:
public class Option {
private String key;
private String label;
...
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((key == null) ? 0 : key.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Option other = (Option) obj;
if (key == null) {
if (other.key != null)
return false;
} else if (!key.equals(other.key))
return false;
return true;
}
}
Methods above are generated by my IDE. I also don't know exactly what is structure of your Option class, so I add label property for example in addition to key property.
I created a custom Hamcrest matcher to compare the List of Option by checking the size and the keys.
private Matcher<List<Option>> hasOptionsFeatureMatcher(
final List<Option> expectedOptions) {
return new FeatureMatcher<List<Option>, List<Option>>(
equalTo(expectedOptions), "Options are", "Options were") {
#Override
protected List<Option> featureValueOf(List<Option> actualOptions) {
boolean flag = false;
if (expectedOptions.size() == actualOptions.size()) {
for (Option expected : expectedOptions) {
for (Option actual : actualOptions) {
if (expected.getKey().equals(actual.getKey())) {
flag = true;
break;
} else {
flag = false;
}
}
}
} else
flag = false;
if (flag)
return expectedOptions;
else
return null;
}
};
Implementation would be as follows:
private static final ImmutableBiMap<String, String> LIRA = new ImmutableBiMap.Builder<String, String>()
.put(AccountLegislationEnum.AB.toString(), "ALBERTA")
.put(AccountLegislationEnum.MB.toString(), "MANITTOBA")
.put(AccountLegislationEnum.NB.toString(), "NEW BRUNSWICK")
.put(AccountLegislationEnum.NL.toString(), "NEWFOUNDLAND")
.put(AccountLegislationEnum.NS.toString(), "NOVA SCOTIA")
.put(AccountLegislationEnum.ON.toString(), "ONTARIO")
.put(AccountLegislationEnum.QC.toString(), "QUEBEC")
.put(AccountLegislationEnum.SK.toString(), "SASKATCHEWAN")
.put(AccountLegislationEnum.UNKNOWN.toString(), "UNKNOWN").build();
private List<Option> prepareOptions(ImmutableBiMap<String, String> map) {
List<Option> legislations = new ArrayList<Option>();
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
Option option = new Option();
option.setKey(key);
option.setValue(value);
legislations.add(option);
}
return legislations;
}
.andExpect(model().attribute("appFormLiraLegislations",hasOptionsFeatureMatcher(prepareOptions(LIRA))))

How do I "register" a new Module Type in an IntelliJ Plugin?

I am a beginner when it comes to IntelliJ plugin development but i want my plugin to register a new Module Type in the "New Project" / "New Module" windows.
I already searched through the Documentation for plugin developers but wasn't able to find anything useful. I also looked at existing plugins like Kotlin and Scala which also add new Module types but I can't figure out how to get a finished ModuleType to show up in the dialogs mentioned above.
What do I have to change in the plugin.xml file? I already added extensions and created java classes for ModuleType, ModuleBuilder and the ModuleConfigurationExtensionProvider but that doesn't change anything.
I hope you can help me and thanks in advance.
This can be achieved through New Project Wizard feature of IntelliJ IDEA, by providing your Module / Project type implementation class of ModuleBuilder i.e by extending the intelliJ IDEA provided extension point for the same (com.intellij).
You need the below changes to make in your plugin.xml for making appear your new Module / Project type in New Project Wizard project /modules types list.
<extensions defaultExtensionNs="com.intellij">
<moduleBuilder builderClass="com.yourcompany.wizards.YourModuleBuilder"/>
</extensions>
Provide your ModuleBuilder class with package to buildlerClass attribute, thats enough.
Here is sample ModuleBuilder implementation:
public class AsposeJavaModuleBuilder extends ModuleBuilder implements SourcePathsBuilder {
private Project myProject;
ResourceBundle bundle = ResourceBundle.getBundle("Bundle");
#Override
public String getBuilderId() {
return getClass().getName();
}
#Override
public String getPresentableName() {
return "Aspose Application";
}
#Override
public String getDescription() {
return bundle.getString("AsposeWizardPanel.myMainPanel.description");
}
#Override
public Icon getBigIcon() {
return AsposeIcons.AsposeMedium;
}
#Override
public Icon getNodeIcon() {
return AsposeIcons.AsposeLogo;
}
#Override
public ModuleWizardStep[] createWizardSteps(#NotNull WizardContext wizardContext, #NotNull ModulesProvider modulesProvider) {
return new ModuleWizardStep[]{
new AsposeAPIsWizardStep(this, wizardContext),
};
}
#Override
public void setupRootModel(ModifiableRootModel rootModel) throws com.intellij.openapi.options.ConfigurationException {
setMyProject(rootModel.getProject());
final CompilerModuleExtension compilerModuleExtension = rootModel.getModuleExtension(CompilerModuleExtension.class);
compilerModuleExtension.setExcludeOutput(true);
if (myJdk != null) {
rootModel.setSdk(myJdk);
} else {
rootModel.inheritSdk();
}
ContentEntry contentEntry = doAddContentEntry(rootModel);
if (contentEntry != null) {
final List<Pair<String, String>> sourcePaths = getSourcePaths();
if (sourcePaths != null) {
for (final Pair<String, String> sourcePath : sourcePaths) {
String first = sourcePath.first;
new File(first).mkdirs();
final VirtualFile sourceRoot = LocalFileSystem.getInstance()
.refreshAndFindFileByPath(FileUtil.toSystemIndependentName(first));
if (sourceRoot != null) {
contentEntry.addSourceFolder(sourceRoot, false, sourcePath.second);
}
}
}
}
if (myCompilerOutputPath != null) {
// should set only absolute paths
String canonicalPath;
try {
canonicalPath = FileUtil.resolveShortWindowsName(myCompilerOutputPath);
} catch (IOException e) {
canonicalPath = myCompilerOutputPath;
}
compilerModuleExtension
.setCompilerOutputPath(VfsUtil.pathToUrl(FileUtil.toSystemIndependentName(canonicalPath)));
} else {
compilerModuleExtension.inheritCompilerOutputPath(true);
}
LibraryTable libraryTable = rootModel.getModuleLibraryTable();
for (Pair<String, String> libInfo : myModuleLibraries) {
final String moduleLibraryPath = libInfo.first;
final String sourceLibraryPath = libInfo.second;
Library library = libraryTable.createLibrary();
Library.ModifiableModel modifiableModel = library.getModifiableModel();
modifiableModel.addRoot(getUrlByPath(moduleLibraryPath), OrderRootType.CLASSES);
if (sourceLibraryPath != null) {
modifiableModel.addRoot(getUrlByPath(sourceLibraryPath), OrderRootType.SOURCES);
}
modifiableModel.commit();
}
RunnableHelper.runWhenInitialized(getMyProject(), new Runnable() {
public void run() {
System.out.println("Hello I came here");
final LibraryTablesRegistrar libTablesRegistrar = LibraryTablesRegistrar.getInstance();
final LibraryTable libraryTable = libTablesRegistrar.getLibraryTable(getMyProject());
final LibraryTable.ModifiableModel libTableModel = libraryTable.getModifiableModel();
Library library = libTableModel.createLibrary(AsposeConstants.LIBRARY_NAME);
libTableModel.commit();
#NonNls final String path = getContentEntryPath() + File.separator + AsposeConstants.LIB_FOLDER;
new File(path).mkdirs();
for (AsposeJavaAPI api : AsposeProject.getApiList().values()) {
System.out.println("Hello I came here2");
if (api.is_selected()) {
try {
System.out.println("Hello I came here3");
AsposeAPIsManager.copyDirectory(AsposeAPIsManager.getLibaryDownloadPath() + api.get_name().toLowerCase(), path + File.separator + api.get_name());
} catch (IOException ex) {
ex.printStackTrace();
}
String[] children = new File(path + File.separator + api.get_name().toLowerCase() + File.separator).list();
for (String _child : children) {
String jarPath = "jar://" + path + File.separator + api.get_name() + File.separator + _child + "!/";
Library.ModifiableModel model = library.getModifiableModel();
model.addRoot(jarPath, OrderRootType.CLASSES);
model.commit();
}
}
}
Collection<Module> modules = ModuleUtil.getModulesOfType(getMyProject(), StdModuleTypes.JAVA);
Iterator itr = modules.iterator();
Module module = null;
while (itr.hasNext()) {
module = (Module) itr.next();
break;
}
final ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
final ModifiableRootModel moduleRootModel = moduleRootManager.getModifiableModel();
final Library lib = libraryTable.getLibraryByName(AsposeConstants.LIBRARY_NAME);
if (moduleRootModel.findLibraryOrderEntry(lib) == null) {
moduleRootModel.addLibraryEntry(lib);
}
moduleRootModel.commit();
}
});
}
#Override
public String getGroupName() {
return JavaModuleType.JAVA_GROUP;
}
public Project getMyProject() {
return myProject;
}
public void setMyProject(Project myProject) {
this.myProject = myProject;
}
#Nullable
public ModuleWizardStep getCustomOptionsStep(WizardContext context, Disposable parentDisposable) {
AsposeIntroWizardStep step = new AsposeIntroWizardStep();
Disposer.register(parentDisposable, step);
return step;
}
private String myCompilerOutputPath;
// Pair<Source Path, Package Prefix>
private List<Pair<String, String>> mySourcePaths;
// Pair<Library path, Source path>
private final List<Pair<String, String>> myModuleLibraries = new ArrayList<Pair<String, String>>();
public final void setCompilerOutputPath(String compilerOutputPath) {
myCompilerOutputPath = acceptParameter(compilerOutputPath);
}
public List<Pair<String, String>> getSourcePaths() {
if (mySourcePaths == null) {
final List<Pair<String, String>> paths = new ArrayList<Pair<String, String>>();
#NonNls final String path = getContentEntryPath() + File.separator + "src";
new File(path).mkdirs();
paths.add(Pair.create(path, ""));
return paths;
}
return mySourcePaths;
}
public void setSourcePaths(List<Pair<String, String>> sourcePaths) {
mySourcePaths = sourcePaths != null ? new ArrayList<Pair<String, String>>(sourcePaths) : null;
}
public void addSourcePath(Pair<String, String> sourcePathInfo) {
if (mySourcePaths == null) {
mySourcePaths = new ArrayList<Pair<String, String>>();
}
mySourcePaths.add(sourcePathInfo);
}
public ModuleType getModuleType() {
return StdModuleTypes.JAVA;
}
#Override
public boolean isSuitableSdkType(SdkTypeId sdkType) {
return sdkType instanceof JavaSdkType;
}
#Nullable
#Override
public ModuleWizardStep modifySettingsStep(#NotNull SettingsStep settingsStep) {
return StdModuleTypes.JAVA.modifySettingsStep(settingsStep, this);
}
private static String getUrlByPath(final String path) {
return VfsUtil.getUrlForLibraryRoot(new File(path));
}
public void addModuleLibrary(String moduleLibraryPath, String sourcePath) {
myModuleLibraries.add(Pair.create(moduleLibraryPath, sourcePath));
}
#Nullable
protected static String getPathForOutputPathStep() {
return null;
}
}
For complete source code reference for creating new Module / Project Types in IntelliJ IDEA, please see the source code of Aspose Project Wizard (an IntelliJ IDEA Plugin By Aspose pty Ltd)
Source codes can be downloaded from the following URL:
https://asposejetbrains.codeplex.com/

How to Mock repository Items in ATG

I am trying to create a Mock class for droplet. I am able to mock the repository calls and req.getParameter but need help on how to mock the repository item list from the repository. Below is the sample code.
for (final RepositoryItem item : skuList) {
final String skuId = (String) item.getPropertyValue("id");
final String skuType = (String) item.getPropertyValue("skuType");
if (this.isLoggingDebug()) {
this.logDebug("skuType [ " + skuType + " ]");
}
final String skuActive = (String) item.getPropertyValue("isActive");
if EJSD.equalsIgnoreCase(skuType) && (skuActive.equals("1"))) {
eSkuList.add(item);
skuCode = (String) item.getPropertyValue(ESTConstants.SKU_MISC1);
} else (PJPROMIS.equalsIgnoreCase(skuType) && skuId.contains("PP") && (skuActive.equals("1"))) {
personalSkuList.add(item);
String tmp = "";
if (skuId.lastIndexOf("-") > -1) {
tmp = skuId.substring(skuId.lastIndexOf("-") + 1);
tmp = tmp.toUpperCase();
if (this.getDefaultDisplayNameMap() != null) {
String val = this.getDefaultDisplayNameMap().get(tmp);
if (StringUtils.isNotEmpty(val)) {
displayNameMap.put(skuId, val);
} else {
val = (String) item.getPropertyValue("displayName");
displayNameMap.put(skuId, val);
}
} else {
final String val = (String) item.getPropertyValue("displayName");
displayNameMap.put(skuId, val);
}
}
}
}
There are a multitude of ways to 'mock' the list. I've been doing it this was as I feel it is more readable.
#Mock private RepositoryItem skuMockA;
#Mock private RepositoryItem skuMockB;
List<RepositoryItem> skuList = new ArrayList<RepositoryItem>();
#BeforeMethod(groups = { "unit" })
public void setup() throws Exception {
testObj = new YourDropletName();
MockitoAnnotations.initMocks(this);
skuList = new ArrayList<RepositoryItem>();
skuList.add(skuMockA);
skuList.add(skuMockB);
Mockito.when(skuMockA.getPropertyValue("id")).thenReturn("skuA");
Mockito.when(skuMockA.getPropertyValue("skuType")).thenReturn(ActiveSkuDroplet.EJSD);
Mockito.when(skuMockA.getPropertyValue(ESTConstants.SKU_MISC1)).thenReturn("skuCodeA");
Mockito.when(skuMockA.getPropertyValue("displayName")).thenReturn("skuADisplayName");
Mockito.when(skuMockB.getPropertyValue("id")).thenReturn("skuB-PP");
Mockito.when(skuMockB.getPropertyValue("skuType")).thenReturn(ActiveSkuDroplet.PJPROMIS);
Mockito.when(skuMockB.getPropertyValue(ESTConstants.SKU_MISC1)).thenReturn("skuCodeB");
Mockito.when(skuMockB.getPropertyValue("displayName")).thenReturn("skuBDisplayName");
}
So when you then call this within a test it will be something like this:
Mockito.when(someMethodThatReturnsAList).thenReturn(skuList);
So the key really is that you are not mocking the List but instead the contents of the List.
Creating a mock using mockito is a good option.
But I am here explaining a different way of mocking the repository item.
Create a common implementation for RepositoryItem, say MockRepositoryItemImpl like this in your test package.
Public MockRepositoryItemImpl implements RepositoryItem {
private Map<String, Object> properties;
MockRepositoryItemImpl(){
properties = new HashMap<>();
}
#override
public Object getPropertyValue(String propertyName){
return properties.get(propertyName);
}
#override
public void setPropertyValue(String propertyName, Object propertyValue){
properties.put(propertyName, propertyValue);
}
}
Use this implementation to create the mock object in your test case.
RepositoryItem mockSKU = new MockRepositoryItemImpl();
mockSKU.setPropertyValue("id", "sku0001");
mockSKU.setPropertyValue("displayName", "Mock SKU");
mockSKU.setPropertyValue("skuType", "Type1");
mockSKU.setPropertyValue("isActive", "1");

Categories