How to map enum to String using Mapstruct - mapstruct

I can find answers where we have String to Enum mapping but I can't find how can I map an Enum to a String.
public class Result {
Value enumValue;
}
public enum Value {
TEST,
NO TEST
}
public class Person {
String value;
}
How can I map this ?
I tried :
#Mapping(target = "value", source = "enumValue", qualifiedByName = "mapValue")
#Named("mapValue")
default Person mapValue(final Value en) {
return Person.builder().value(en.name()).build();
}

mapstruct should support this out of the box.
So #Mapping(target = "value", source = "enumValue") should suffice.
Complete example including target/source classes:
#Mapper
public interface EnumMapper {
#Mapping( target = "value", source = "enumValue" )
Person map(Result source);
}
class Result {
private Value enumValue;
public Value getEnumValue() {
return enumValue;
}
public void setEnumValue(Value enumValue) {
this.enumValue = enumValue;
}
}
enum Value {
TEST, NO_TEST
}
class Person {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
This results in the following generated code:
#Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2022-02-20T12:33:00+0100",
comments = "version: 1.5.0.Beta2, compiler: Eclipse JDT (IDE) 1.4.50.v20210914-1429, environment: Java 17.0.1 (Azul Systems, Inc.)"
)
public class EnumMapperImpl implements EnumMapper {
#Override
public Person map(Result source) {
if ( source == null ) {
return null;
}
Person person = new Person();
if ( source.getEnumValue() != null ) {
person.setValue( source.getEnumValue().name() );
}
return person;
}
}

Related

Deepclone of same class with SubclassMapping

I'd like to use mapstruct to deepclone same objects. However situation is little bit trickier as I'm using abstraction.
public abstract class Fruit {
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
public class Banana extends Fruit {
private String origin;
public String getOrigin() {
return origin;
}
public void setOrigin(String origin) {
this.origin = origin;
}
}
public class Apple extends Fruit {
private String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
#Mapper(mappingControl = DeepClone.class, subclassExhaustiveStrategy = SubclassExhaustiveStrategy.RUNTIME_EXCEPTION)
public interface FruitMapper {
#SubclassMapping(source = Apple.class, target = Apple.class)
#SubclassMapping(source = Banana.class, target = Banana.class)
Fruit clone(Fruit fruit);
}
and finally this is what is generated:
public class FruitMapperImpl implements FruitMapper {
#Override
public Fruit clone(Fruit fruit) {
if ( fruit == null ) {
return null;
}
if (fruit instanceof Apple) {
return (Apple) fruit;
}
else if (fruit instanceof Banana) {
return (Banana) fruit;
}
else {
throw new IllegalArgumentException("Not all subclasses are supported for this mapping. Missing for " + fruit.getClass());
}
}
}
The thing I'm missing is the actual implementation of given subclasses. Is that a bug or is it designed like this?
Because if I add method like Apple clone(Apple apple); then it should be good (for Apple only) however I don't see any benefit of adding SubclassMapping
public class FruitMapperImpl implements FruitMapper {
#Override
public Fruit clone(Fruit fruit) {
if ( fruit == null ) {
return null;
}
if (fruit instanceof Apple) {
return clone( (Apple) fruit );
}
else if (fruit instanceof Banana) {
return (Banana) fruit;
}
else {
throw new IllegalArgumentException("Not all subclasses are supported for this mapping. Missing for " + fruit.getClass());
}
}
#Override
public Apple clone(Apple apple) {
if ( apple == null ) {
return null;
}
Apple apple1 = new Apple();
apple1.setId( apple.getId() );
apple1.setType( apple.getType() );
return apple1;
}
}
EDIT:
issue created

Invoke some method of result object after mapping in MyBatis

Let's say I have the next java class:
class User {
private String loginName;
private boolean active = true;
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public void deactivate() {
this.active = false;
}
}
If I manually map ResultSet on this object I would do something like:
if (resultSet.getBoolean("col_active") == false) {
user.deactivate();
}
How can I implement this using MyBatis?

Trying to read values returned on jsp form submission in springboot project by setters and use the combination to call another java class

So, I have values in getter setter variables when I click on form submit but now want to have those values in variables and check combination of them to run code from another java class
I have tried using parametrized constructor or may be having a common setter but that did not help.
package com.grt.dto;
import java.util.Set;
public class WDPayrollRecon {
public Set<String> dataType;
public String planCountry;
public String payPeriod;
public String currentPeriod;
public String lastPayPeriod;
Set<String> test;
public Set<String> getdataType() {
return dataType;
}
public void setdataType(Set<String> dataType) {
this.dataType = dataType;
System.out.println("this is dataType" +dataType);
test = dataType;
}
public String getPlanCountry() {
return planCountry;
}
public void setPlanCountry(String planCountry) {
this.planCountry = planCountry;
}
public String getPayPeriod() {
return payPeriod;
}
public void setPayPeriod(String payPeriod) {
this.payPeriod = payPeriod;
}
public String getCurrentPeriod() {
return currentPeriod;
}
public void setCurrentPeriod(String currentPeriod) {
this.currentPeriod = currentPeriod;
}
public String getlastPayPeriod() {
return lastPayPeriod;
}
public void setlastPayPeriod(String lastPayPeriod) {
this.lastPayPeriod = lastPayPeriod;
}
public WDPayrollRecon()
{
}
public WDPayrollRecon(Set<String> dataType,String planCountry,String payPeriod,String currentPeriod,String lastPayPeriod)
{
this.dataType = dataType;
this.planCountry = planCountry;
this.payPeriod = payPeriod;
this.currentPeriod = currentPeriod;
this.lastPayPeriod = lastPayPeriod;
if(dataType.contains("GTLI")& planCountry.equals("USA")){
System.out.println("This is test");
}
else{
System.out.println("This is not test");
}
}
}

InvalidDataAccessApiUsageException:Parameter value did not match expected type

please can you help me with the following exception: org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [myCalendar] did not match expected type [pl.sda.jira.calendar.domain.model.Name (n/a)].
I'm having difficulty fixing this error. Grateful if you could let me know what options I have.
The test where I get the error:
#Test
public void shouldGetCalendarEqualToName() throws Exception {
MockHttpServletResponse response = restClient.perform(
MockMvcRequestBuilders.post("/calendars")
.param("columnName", "name")
.param("type", "equals")
.param("value", "myCalendar"))
.andReturn().getResponse();
assertEquals(HttpStatus.OK.value(), response.getStatus());
assertEquals("[{\"name\":\"calendar0\",\"owner\":\"Jon\"}]", response.getContentAsString());
}
My QueryService (pasting only the applicable case from the switch-case):
private Specification<Calendar> createSpecificationsFrom(QueryCriteriaDto queryCriteriaDto) {
switch (queryCriteriaDto.getType()) {
case "equals":
return ((root, criteriaQuery, criteriaBuilder) ->
criteriaBuilder.equal(root.get(queryCriteriaDto.getColumnName()), (queryCriteriaDto.getValue())));
}
throw new IllegalArgumentException();
}
My class Name:
public class Name {
private String value;
public Name(String value) {
this.value = value;
}
public String value() {
return value;
}}
I'm also using a Converter:
#Converter
public class NameConverter implements AttributeConverter<Name, String> {
#Override
public String convertToDatabaseColumn(Name name) {
return name.value();
}
#Override
public Name convertToEntityAttribute(String value) {
return new Name(value);
}}

ASP.NET MVC 2 Authorization with Gateway Page

I've got an MVC 2 application which won't be doing its own authentication, but will retrieve a user ID from the HTTP request header, since users must pass through a gateway before reaching the application.
Once in the app, we need to match up the user ID to information in a "users" table, which contains some security details the application makes use of.
I'm familiar with setting up custom membership and roles providers in ASP.NET, but this feels so different, since the user never should see a login page once past the gateway application.
Questions:
How do I persist the user ID, if at all? It starts out in the request header, but do I have to put it in a cookie? How about SessionState?
Where/when do I get this information? The master page shows the user's name, so it should be available everywhere.
I'd like to still use the [Authorize(Roles="...")] tag in my controller if possible.
We have a very similar setup where I work. As #Mystere Man mentioned, there are risks with this setup, but if the whole infrastructure is setup and running correctly, we have found it to be a secure setup (we do care about security). One thing to ensure, is that the SiteMinder agent is running on the IIS node you're trying to secure, as it will validate an encrypted SMSESSION key also passed in the headers, which will make the requests secure (it would be extremely difficult to spoof the value of the SMSESSION header).
We are using ASP.NET MVC3, which has global action filters, which is what we're using. But with MVC2, you could create a normal, controller level action filter that could be applied to a base controller class so that all of your controllers/actions will be secured.
We have created a custom configuration section that allows us to turn this security filter on and off via web.config. If it's turned off, our configuration section has properties that will allow you to "impersonate" a given user with given roles for testing and debugging purposes. This configuration section also allows us to store the values of the header keys we're looking for in config as well, in case the vendor ever changes the header key names on us.
public class SiteMinderConfiguration : ConfigurationSection
{
[ConfigurationProperty("enabled", IsRequired = true)]
public bool Enabled
{
get { return (bool)this["enabled"]; }
set { this["enabled"] = value; }
}
[ConfigurationProperty("redirectTo", IsRequired = true)]
public RedirectToElement RedirectTo
{
get { return (RedirectToElement)this["redirectTo"]; }
set { this["redirectTo"] = value; }
}
[ConfigurationProperty("sessionCookieName", IsRequired = true)]
public SiteMinderSessionCookieNameElement SessionCookieName
{
get { return (SiteMinderSessionCookieNameElement)this["sessionCookieName"]; }
set { this["sessionCookieName"] = value; }
}
[ConfigurationProperty("userKey", IsRequired = true)]
public UserKeyElement UserKey
{
get { return (UserKeyElement)this["userKey"]; }
set { this["userKey"] = value; }
}
[ConfigurationProperty("rolesKey", IsRequired = true)]
public RolesKeyElement RolesKey
{
get { return (RolesKeyElement)this["rolesKey"]; }
set { this["rolesKey"] = value; }
}
[ConfigurationProperty("firstNameKey", IsRequired = true)]
public FirstNameKeyElement FirstNameKey
{
get { return (FirstNameKeyElement)this["firstNameKey"]; }
set { this["firstNameKey"] = value; }
}
[ConfigurationProperty("lastNameKey", IsRequired = true)]
public LastNameKeyElement LastNameKey
{
get { return (LastNameKeyElement)this["lastNameKey"]; }
set { this["lastNameKey"] = value; }
}
[ConfigurationProperty("impersonate", IsRequired = false)]
public ImpersonateElement Impersonate
{
get { return (ImpersonateElement)this["impersonate"]; }
set { this["impersonate"] = value; }
}
}
public class SiteMinderSessionCookieNameElement : ConfigurationElement
{
[ConfigurationProperty("value", IsRequired = true)]
public string Value
{
get { return (string)this["value"]; }
set { this["value"] = value; }
}
}
public class RedirectToElement : ConfigurationElement
{
[ConfigurationProperty("loginUrl", IsRequired = false)]
public string LoginUrl
{
get { return (string)this["loginUrl"]; }
set { this["loginUrl"] = value; }
}
}
public class UserKeyElement : ConfigurationElement
{
[ConfigurationProperty("value", IsRequired = true)]
public string Value
{
get { return (string)this["value"]; }
set { this["value"] = value; }
}
}
public class RolesKeyElement : ConfigurationElement
{
[ConfigurationProperty("value", IsRequired = true)]
public string Value
{
get { return (string)this["value"]; }
set { this["value"] = value; }
}
}
public class FirstNameKeyElement : ConfigurationElement
{
[ConfigurationProperty("value", IsRequired = true)]
public string Value
{
get { return (string)this["value"]; }
set { this["value"] = value; }
}
}
public class LastNameKeyElement : ConfigurationElement
{
[ConfigurationProperty("value", IsRequired = true)]
public string Value
{
get { return (string)this["value"]; }
set { this["value"] = value; }
}
}
public class ImpersonateElement : ConfigurationElement
{
[ConfigurationProperty("username", IsRequired = false)]
public UsernameElement Username
{
get { return (UsernameElement)this["username"]; }
set { this["username"] = value; }
}
[ConfigurationProperty("roles", IsRequired = false)]
public RolesElement Roles
{
get { return (RolesElement)this["roles"]; }
set { this["roles"] = value; }
}
}
public class UsernameElement : ConfigurationElement
{
[ConfigurationProperty("value", IsRequired = true)]
public string Value
{
get { return (string)this["value"]; }
set { this["value"] = value; }
}
}
public class RolesElement : ConfigurationElement
{
[ConfigurationProperty("value", IsRequired = true)]
public string Value
{
get { return (string)this["value"]; }
set { this["value"] = value; }
}
}
So our web.config looks something like this
<configuration>
<configSections>
<section name="siteMinderSecurity" type="MyApp.Web.Security.SiteMinderConfiguration, MyApp.Web" />
...
</configSections>
...
<siteMinderSecurity enabled="false">
<redirectTo loginUrl="https://example.com/login/?ReturnURL={0}"/>
<sessionCookieName value="SMSESSION"/>
<userKey value="SM_USER"/>
<rolesKey value="SN-AD-GROUPS"/>
<firstNameKey value="SN-AD-FIRST-NAME"/>
<lastNameKey value="SN-AD-LAST-NAME"/>
<impersonate>
<username value="ImpersonateMe" />
<roles value="Role1, Role2, Role3" />
</impersonate>
</siteMinderSecurity>
...
</configuration>
We have a custom SiteMinderIdentity...
public class SiteMinderIdentity : GenericIdentity, IIdentity
{
public SiteMinderIdentity(string name, string type) : base(name, type) { }
public IList<string> Roles { get; set; }
}
And a custom SiteMinderPrincipal...
public class SiteMinderPrincipal : GenericPrincipal, IPrincipal
{
public SiteMinderPrincipal(IIdentity identity) : base(identity, null) { }
public SiteMinderPrincipal(IIdentity identity, string[] roles) : base(identity, roles) { }
}
And we populate HttpContext.Current.User and Thread.CurrentPrincipal with an instance of SiteMinderPrincipal that we build up based on information that we pull from the request headers in our action filter...
public class SiteMinderSecurity : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
var request = filterContext.HttpContext.Request;
var response = filterContext.HttpContext.Response;
if (MyApp.SiteMinderConfig.Enabled)
{
string[] userRoles = null; // default to null
userRoles = Array.ConvertAll(request.Headers[MyApp.SiteMinderConfig.RolesKey.Value].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries), r => r.Trim());
var identity = new SiteMinderIdentity(request.Headers[MyApp.SiteMinderConfig.UserKey.Value];, "SiteMinder");
if (userRoles != null)
identity.Roles = userRoles.ToList();
var principal = new SiteMinderPrincipal(identity, userRoles);
HttpContext.Current.User = principal;
Thread.CurrentPrincipal = principal;
}
else
{
var roles = Array.ConvertAll(MyApp.SiteMinderConfig.Impersonate.Roles.Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries), r => r.Trim());
var identity = new SiteMinderIdentity(MyApp.SiteMinderConfig.Impersonate.Username.Value, "SiteMinder") { Roles = roles.ToList() };
var principal = new SiteMinderPrincipal(identity, roles);
HttpContext.Current.User = principal;
Thread.CurrentPrincipal = principal;
}
}
}
MyApp is a static class that gets initialized at application startup that caches the configuration information so we're not reading it from web.config on every request...
public static class MyApp
{
private static bool _isInitialized;
private static object _lock;
static MyApp()
{
_lock = new object();
}
private static void Initialize()
{
if (!_isInitialized)
{
lock (_lock)
{
if (!_isInitialized)
{
// Initialize application version number
_version = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion;
_siteMinderConfig = (SiteMinderConfiguration)ConfigurationManager.GetSection("siteMinderSecurity");
_isInitialized = true;
}
}
}
}
private static string _version;
public static string Version
{
get
{
Initialize();
return _version;
}
}
private static SiteMinderConfiguration _siteMinderConfig;
public static SiteMinderConfiguration SiteMinderConfig
{
get
{
Initialize();
return _siteMinderConfig;
}
}
}
From what I gather of your situation, you have information in a database that you'll need to lookup based on the information in the headers to get everything you need, so this won't be exactly what you need, but it seems like it should at least get you started.
Hope this helps.