Resource Filtering with own plugin - maven

Currently i develop my own plugin which will do resource filtering with loading of a an other file which influence the resource filtering.
I have the following code in my plugin (execute) method:
public void execute() throws MojoExecutionException {
if (StringUtils.isEmpty(encoding) && isFilteringEnabled(getResources())) {
getLog().warn(
"File encoding has not been set, using platform encoding "
+ ReaderFactory.FILE_ENCODING
+ ", i.e. build is platform dependent!");
}
Scope scope = convertToScope(getScope());
getLog().info("Hallo welt. (" + scope + ")");
if (getResources() != null) {
for (Resource item : getResources()) {
getLog().info(" --| Resource: " + item.getFiltering() + "|" + item.getDirectory());
}
}
try {
MavenResourcesExecution mavenResourcesExecution = new MavenResourcesExecution(
resources, outputDirectory, project, encoding, null,
nonFilteredFileExtensions, mavenSession);
ValueSource valueSource = new ValueSource() {
#Override
public Object getValue(String expression) {
getLog().info("Expression: " + expression);
return "XXX";
}
#Override
public List getFeedback() {
getLog().info("getFeedback()");
return Collections.EMPTY_LIST;
}
#Override
public void clearFeedback() {
// TODO Auto-generated method stub
getLog().info("clearFeedback()");
}
};
mavenResourcesExecution.addFilerWrapperWithEscaping(valueSource,
"\\#", "\\#", "#", false);
mavenResourcesExecution.setUseDefaultFilterWrappers(false);
mavenResourcesFiltering.filterResources(mavenResourcesExecution);
} catch (MavenFilteringException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
}
But during my integration tests the filtering will not be done. In my output i can't find the output of getValue(), getFeedback() etc.
Currently the output during my integration test looks like:
[INFO] Hallo welt. ()
[INFO] --| Resource: true|src/main/resource-files
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[DEBUG] resource with targetPath null
directory src/main/resource-files
excludes []
includes []
[DEBUG] ignoreDelta true
[INFO] Copying 1 resource
[DEBUG] file thisIsTheFirst.properties has a filtered file extension
[DEBUG] filtering ..it\configurationTest\src\main\resource-files\thisIsTheFirst.properties to ...\it\configurationTest\target\classes\thisIsTheFirst.properties
But unfortunately the getValue() method is not called in this case.
So the question is: Does someone has an idea what i'm doing wrong ? (Full source is available here.

The solution is NOT to use regular expressions:
mavenResourcesExecution.addFilerWrapperWithEscaping(valueSource, "#", "#", "#", false);

Related

How to define a Map<String,CustomObject> in build.gradle

I have a plugin as below
class AbstractConfigExtension {
public static final String NAME = "abstract_extension"
Project project
// Configuration extension properties
String service
String substrate
String region
String group
String pod
Map<String,InstanceGridDetails> instanceGridDetails = new HashMap<String,InstanceGridDetails>()
// new HashMap<String,String>()
List<String> tags = new ArrayList<>()
List<String> instances = ["i01"]
int numInstances = 1
boolean generateServiceFiles = true
}
I have a different class called InstanceGridDetails.groovy
class InstanceGridDetails {
// Grid Properties
String grid
String dsName
String ddName
public AcdsInstanceGridDetails () {
}
String getGrid() {
return this.grid
}
void grid(String grid) {
this.grid = grid
}
String dsName() {
return this.dsName
}
void dsName(String dsName) {
this.dsName = dsName
}
String ddName() {
return this.ddName
}
void ddName(String ddName) {
this.ddName = ddName
}
}
This is called as a plugin using the build.gradle as below
apply plugin: 'java'
apply plugin: HoconConfigPlugin
apply plugin: GriddableCaacRpmPlugin
abstract_extension {
service "relay"
substrate "1p"
region "xrd"
instanceGridDetails = ["i01": InstanceGridDetails { gridName "grid1"
dsName "ds1"
ddName "dd1"} ]
numInstances 1
tags = ["medium_mem"]
}
when I am doing as above I am getting the issue as below
FAILURE: Build failed with an exception.
Where: Build file 'config-packages/service-cfg-1p-xrd/build.gradle'
line: 13
What went wrong: A problem occurred evaluating project ':config-packages:service-cfg-1p-xrd'.
Could not find method InstanceGridDetails() for arguments [build_b1plunv4uhm1dpn66jee47jiz$_run_closure1$_closure2#25cf3fbf] on
object of type AbstractConfigExtension.
Your constructor is still called AcdsInstanceGridDetails while your class is called InstanceGridDetails. They should have the same name.
Try replacing all occurrences of AcdsInstanceGridDetails with InstanceGridDetails

How to generate testng report without overwritng the previous test result

I am automating Web Application using Selenium with Java.
I am executing multiple testng xml files in parallel, so the result gets overridden every time.
Eg: I have two xml files (testng1.xml and testng 2.xml). When I run these two files in parallel, result from testng2.xml is override with testng1.xml in the emailable report.
How to generate a separate report for each xml file?
I have achieved this scenario by using the below code.
public String xmlString;
public int xmlIndex;
public String folderName;
public String locationName;
public static String reportName = "emailable-report.html";
xmlString = <list of xml files>;
xmlIndex = xmlString.lastIndexOf("/");
locationName = xmlString.substring(xmlIndex+1);
folderName = locationName.replace(".xml", "").toUpperCase();
File dir = new File("Result"); // Here I am creating a common folder and the sub folders will be created as per the xml file executions.
if(dir.exists())
{
try {
FileUtils.deleteDirectory(dir);
} catch (IOException e) {
e.printStackTrace();
}
dir.mkdir();
}
else
{
dir.mkdir();
}
String xmlFolderPath = System.getProperty("user.dir") +"/"+ dir + "/"+ folderName;
testng.setOutputDirectory(xmlFolderPath);
File resultFile = new File(System.getProperty("user.dir") +"/"+ dir + "/" +"ResultFiles"); // In this folder only testng result (.html)files are moved here.
resultFile.mkdir();
File folder = new File(xmlFolderPath); // In this folder, separate sub folders were created according to the xml files and the sub folder will be the xml file names.
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
if(reportName.equalsIgnoreCase("emailable-report.html"))
{
Path src = Paths.get(xmlFolderPath + "/" + reportName);
Path desc = Paths.get(resultFile + "/" + folderName + ".html"); // Here emailable-report.html is renamed according to the XML file name and moved to this folder
try
{
Files.move(src, desc, StandardCopyOption.REPLACE_EXISTING);
System.out.println(src.resolveSibling(folderName + ".html"));
break;
}
catch (IOException e)
{
System.out.println(e);
}
}
else
{
System.out.println("Expected file not present in the specified folder..!!!");
}
}
}

How to get entity relationship with annotations using testing class?

I have created a simple Spring-boot application with two entities as Company.java and User.java. These two has #OneToMany relationship. And I have a created a test file for generating typescript file with printing those two entity's attributes. Here is the my test case.
#Inject
RepositoryRestMvcConfiguration configuration;
#Test
public void getEndPoints() {
configuration.resourceMappings().forEach(c -> {
String className = c.getDomainType().getName();
try {
Class<?> entityClass = Class.forName(className);
Field[] fields = entityClass.getDeclaredFields();
File tsClassDir = new File("data/tsClass");
File tsClass = new File(tsClassDir, entityClass.getSimpleName() + ".ts");
if (!tsClass.getParentFile().exists()) {
tsClass.getParentFile().mkdirs();
}
tsClass.createNewFile();
String code = "export interface " + entityClass.getSimpleName() + "{\n";
for (Field field : fields) {
try {
NotNull notNullAnnotation = field.getDeclaredAnnotation(NotNull.class);
Class<?> filedClass = Class.forName(field.getType().getName());
if (notNullAnnotation == null){
code += "\t" + field.getName() + "?: " + filedClass.getSimpleName().trim() + ";" + "\n";
}else{
code += "\t" + field.getName() + ": " + filedClass.getSimpleName().trim() + ";" + "\n";
}
} catch (Exception e) {
// TODO: handle exception
}
// System.err.println(field.getName());
}
code += "}";
Files.write(tsClass.toPath(), code.getBytes());
System.err.println(code);
} catch (Exception e) {
// TODO: handle exception
}
});
}
After test run I got the result given below.
export interface User{
userName: String;
password: String;
email: String;
company?: Company;
}
export interface Company{
name: String;
email: String;
users?: Set;
}
But I need to print that Company and User has #OneToMany relationship in the typescript file. How do I do that?

MEF - Two way import and export

I'm using MEF in order to execute plugins code in my project.
1. I'm loading my dll sources :
public void AssembleComponents()
{
try
{
//Creating an instance of aggregate catalog. It aggregates other catalogs
var aggregateCatalog = new AggregateCatalog();
//Build the directory path where the parts will be available
var directoryPath =
string.Concat(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase)
.Split('\\').Reverse().Skip(4).Reverse().Aggregate((a, b) => a + "\\" + b)
, "\\", "ExportComponents\\Components");
string localPath = new Uri(directoryPath).LocalPath;
//Load parts from the available dlls in the specified path using the directory catalog
var directoryCatalog = new DirectoryCatalog(localPath, "*.dll");
//Load parts from the current assembly if available
var asmCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
//Add to the aggregate catalog
aggregateCatalog.Catalogs.Add(directoryCatalog);
aggregateCatalog.Catalogs.Add(asmCatalog);
//Crete the composition container
var container = new CompositionContainer(aggregateCatalog);
// Composable parts are created here i.e. the Import and Export components assembles here
container.ComposeParts(this);
}
catch (Exception ex)
{
throw ex;
}
}
I'm going through my plugins and executing a "Validate" method :
public List<string> Validate(string operationType)
{
List<string> res = null;
foreach (System.Lazy<IValidationRules, IPluginMetadata> plugin in ChekcsPlugins)
{
if (plugin.Metadata.DisplayName == operationType)
{
res = plugin.Value.Validate();
break;
}
}
return res;
}
I'm know how to export back a returned value once the "Validate" is done but what i need is to return values at run time back during the method execution.
Is it possible?

spring security's searchForSingleEntryInternal method throws exception if record not found

I'm working on an application that uses Spring Security's searchForSingleEntryInternal method. Is there a way to do the same thing without throwing an exception if a record is not found? I want to be able to create a condition that handles missing records.
What I want to change
if (results.size() == 0) {
throw new IncorrectResultSizeDataAccessException(1, 0);
}
From this method
/**
* Internal method extracted to avoid code duplication in AD search.
*/
public static DirContextOperations searchForSingleEntryInternal(DirContext ctx, SearchControls searchControls,
String base, String filter, Object[] params) throws NamingException {
final DistinguishedName ctxBaseDn = new DistinguishedName(ctx.getNameInNamespace());
final DistinguishedName searchBaseDn = new DistinguishedName(base);
final NamingEnumeration<SearchResult> resultsEnum = ctx.search(searchBaseDn, filter, params, searchControls);
if (logger.isDebugEnabled()) {
logger.debug("Searching for entry under DN '" + ctxBaseDn + "', base = '" + searchBaseDn + "', filter = '" + filter + "'");
}
Set<DirContextOperations> results = new HashSet<DirContextOperations>();
try {
while (resultsEnum.hasMore()) {
SearchResult searchResult = resultsEnum.next();
// Work out the DN of the matched entry
DistinguishedName dn = new DistinguishedName(new CompositeName(searchResult.getName()));
if (base.length() > 0) {
dn.prepend(searchBaseDn);
}
if (logger.isDebugEnabled()) {
logger.debug("Found DN: " + dn);
}
results.add(new DirContextAdapter(searchResult.getAttributes(), dn, ctxBaseDn));
}
} catch (PartialResultException e) {
LdapUtils.closeEnumeration(resultsEnum);
logger.info("Ignoring PartialResultException");
}
if (results.size() == 0) {
throw new IncorrectResultSizeDataAccessException(1, 0);
}
if (results.size() > 1) {
throw new IncorrectResultSizeDataAccessException(1, results.size());
}
return results.iterator().next();
}
}
I'm somewhat new to spring and maybe I'm missing something obvious. Any advice would be much appreciated
easy fix, just had to copy over the searchForSingleEntryInternal method from Spring Security and place it in my own project. From there I was able to tweak the exception handling so the application didn't come to a grinding halt if a record wasn't found.

Resources