MapStruct: how to map list of objects where as source is having only one object - mapstruct

New to MapStruct and I am trying to map list of objects in target class where as source is having individual values including other String variables. No luck with custom implementation also. Any suggestions pleas to implement
public class Source {
String var1;
String var2;
String resourceCd1;
String resourceCd2;
String resourceCd3;
String resourceCd4;
String resourceCd5;
String resourceDesc1;
String resourceDesc2;
String resourceDesc3;
String resourceDesc4;
String resourceDesc5;
String var3;
String var4;
}
public class Target {
List<Resource> resources;
}
public class Resource {
String code;
String description;
}
Expectation is to have list of Resource objects including code and description values like below in Target.
List<Resource> resources = new ArrayList<>();
Resource resource1 = new Resource();
resource1.code = soruce.resourceCd1;
resource1.description = soruce.resourceDesc1;
resources.add(resource1);
Resource resource2 = new Resource();
resource2.code = soruce.resourceCd2;
resource2.description = soruce.resourceDesc2;
resources.add(resource2);
Resource resource3 = new Resource();
resource3.code = soruce.resourceCd3;
resource3.description = soruce.resourceDesc3;
resources.add(resource3);
Resource resource4 = new Resource();
resource4.code = soruce.resourceCd4;
resource4.description = soruce.resourceDesc4;
resources.add(resource4);
Resource resource5 = new Resource();
resource5.code = soruce.resourceCd5;
resource5.description = soruce.resourceDesc5;
resources.add(resource5);
Here resourceCd1,..,resourceCd5 and resourceDesc1,..,resourceDesc5 are from the source class

Not possible with MapStruct out of the box. MapStruct supports bean-to-bean, iterable-to-iterable, map-to-map.
Currently under construction: bean-to-map .. When ready you could convert the map to a list by means of a stream / collector.

#Mapper(componentModel = "spring")
public interface SourceMapper {
#Mapping(target = "resources", qualifiedByName = "mapResources")
Target toTarget(Source source);
#Named("mapResources")
default List<Resource> mapResources(Source source){
List<Resource> resources = new ArrayList<>();
Resource resource1 = new Resource();
resource1.setCode(source.getResourceCd1());
resource1.setDescription(source.getResourceDesc1());
resources.add(resource1);
Resource resource2 = new Resource();
resource2.setCode(source.getResourceCd2());
resource2.setDescription(source.getResourceDesc2());
resources.add(resource2);
Resource resource3 = new Resource();
resource3.setCode(source.getResourceCd3());
resource3.setDescription(source.getResourceDesc3());
resources.add(resource3);
Resource resource4 = new Resource();
resource4.setCode(source.getResourceCd4());
resource4.setDescription(source.getResourceDesc4());
resources.add(resource4);
Resource resource5 = new Resource();
resource5.setCode(source.getResourceCd5());
resource5.setDescription(source.getResourceDesc5());
resources.add(resource5);
return resources;
}
}

Related

mtom does not work, classes are generated by Apache CXF,

It is not possible to optimize the SOAP packet, the data is transmitted. What am I doing wrong?
Generated client classes using JBDS. I looked through a lot of examples it is not possible to implement the ability to transfer files outside the package:
</ SOAP-ENV: Envelope>
---- boundary388.5294117647058824932.470588235294118--
Content-Id: <1.B1150656.EC8A.4B5A.8835.A932E318190B>
Content-Transfer-Encoding: binary
CONTENT-TYPE: application / octet-stream
..........
I change the parameters, but it always turns out like this:
<ns2:AttachmentContentList>
<ns2:AttachmentContent>
<ns2:Id>request.zip</ns2:Id>
<ns2:Content>UEsDBBQACAg......
////
Client:
SMEVMessageExchangeService service1 = null;
SMEVMessageExchangePortType port1 = null;
try {
service1 = new SMEVMessageExchangeService(wsdlLocation, SERVICE);
boolean enabled = true;
int threshold = 10240;
port1 = service1.getSMEVMessageExchangeEndpoint(new MTOMFeature(enabled, threshold));//!!!!
.......
AttachmentContentList acList = new AttachmentContentList();
AttachmentContentType aContentType = new AttachmentContentType();
aContentType.setId("request.zip");
BindingProvider bp = (BindingProvider) port1;
javax.xml.ws.soap.SOAPBinding binding2 = (javax.xml.ws.soap.SOAPBinding) bp.getBinding();
binding2.setMTOMEnabled(true);
System.out.println("_____binding2.isMTOMEnabled() - "+binding2.isMTOMEnabled());
DataSource source = new FileDataSource(reqPthFile);
//DataHandler dh =new DataHandler(source,"application/octet-stream");
DataHandler dh =new DataHandler(source);
aContentType.setContent(dh);
//////
#MTOM(enabled=true)
#BindingType(value = javax.xml.ws.soap.SOAPBinding.SOAP12HTTP_MTOM_BINDING)
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "AttachmentContentType", propOrder = {
"id",
"content"
})
public class AttachmentContentType {
#XmlElement(name = "Id", required = true)
#XmlJavaTypeAdapter(CollapsedStringAdapter.class)
#XmlID
#XmlSchemaType(name = "ID")
protected String id;
#MTOM(enabled=true)
#XmlElement(name = "Content", required = true)
#XmlMimeType("application/octet-stream")
protected DataHandler content;
public DataHandler getContent() {
return content;
}
public void setContent(DataHandler value) {
this.content = value;
}
///////
#MTOM(enabled=true)
#BindingType(value = javax.xml.ws.soap.SOAPBinding.SOAP12HTTP_MTOM_BINDING)
#WebService(targetNamespace = "urn://x-artefacts-smev-gov-ru/services/message-exchange/1.2", name = "SMEVMessageExchangePortType")
#XmlSeeAlso({ru.it.smev.message_exchange.autogenerated.types.v1_2.ObjectFactory.class, ru.it.smev.message_exchange.autogenerated.types.fault.v1_2.ObjectFactory.class, ru.it.smev.message_exchange.autogenerated.types.basic.v1_2.ObjectFactory.class})
#SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
public interface SMEVMessageExchangePortType {
///////
#MTOM(enabled=true)
#BindingType(value = javax.xml.ws.soap.SOAPBinding.SOAP12HTTP_MTOM_BINDING)
#WebServiceClient(name = "SMEVMessageExchangeService",
targetNamespace = "urn://x-artefacts-smev-gov-ru/services/message-exchange/1.2")
public class SMEVMessageExchangeService extends Service {
Problem found.
MTOM stops working if handlerList is added.
Please tell me how you can use both handlerList and MTOM at the same time?
List<Handler> handlerList = binding.getHandlerChain();
// handlerList.add(new Handler1());
// handlerList.add(new Handler2());
handlerList.add(handler1);
handlerList.add(handler2);
binding.setHandlerChain(handlerList);

How do I display REST data from an api in a simple list?

I am trying to pull all the names of teams and place them in a simple list. I have tried so doing this
private void ParseAndDisplay(JsonValue json)
{
dynamic teamData = json["teams"];
//TextView name = FindViewById<TextView>(Resource.Id.txtName);
string[] teams;
foreach (var team in teamData)
{
var name = team["name"];
Console.Out.WriteLine("\r\n {0}", name);
teams = new string[] { name };
//TextView name = FindViewById<TextView>(Resource.Id.txtName);
//name.Text = team["name"];
ListAdapter = new ArrayAdapter<String>(this, Android.Resource.Layout.SimpleListItem1, teams);
}
However on my device it only displays the name of the last team in the data whereas in the output it shows all of them.

Sling Forward with SyntheticResource

I'm trying to build a Sling servlet that returns a modified value of a resource from the JCR. I dont want to change the original resource, so I create a SyntheticResource and make my manipulations. I then return it back using the RequestDispatcher.
The following code doesn't return the Modified content as expected and I don't see any errors in the log either. Can you tell me what I'm doing wrong here
#SlingServlet(methods = "GET", resourceTypes = "sling/components/test", selectors = "test")
public class TestServlet extends SlingSafeMethodsServlet {
/**
*
*/
private static final long serialVersionUID = 4078524820231933974L;
private final Logger log = LoggerFactory.getLogger(getClass());
#Reference
ResourceResolverFactory resolverFactory;
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
Map<String, Object> param = new HashMap<String, Object>();
ResourceResolver resolver = null;
response.setContentType("text/html");
StringWriterResponse writerResponse = new StringWriterResponse(response);
PrintWriter writer = response.getWriter();
try {
param.put(ResourceResolverFactory.SUBSERVICE, "testService");
final String path = request.getRequestPathInfo().getResourcePath();
resolver = resolverFactory.getServiceResourceResolver(param);
final Resource resource = resolver.getResource(path);
String resourceType = resource.getResourceType();
Resource testResource = new SyntheticResource(resolver,
path, resourceType) {
public <T> T adaptTo(Class<T> type) {
if (type == ValueMap.class) {
ModifiableValueMap map = resource
.adaptTo(ModifiableValueMap.class);
map.put("jcr:title", "Modified Title");
return (T)map;
}
return super.adaptTo(type);
}
};
RequestDispatcherOptions requestDispatcherOptions = new RequestDispatcherOptions();
requestDispatcherOptions.setReplaceSelectors("");
final RequestDispatcher requestDispatcher = request.getRequestDispatcher(testResource, requestDispatcherOptions);
requestDispatcher.forward(request, writerResponse);
// log.debug( writerResponse.getString() );
writer.println(writerResponse.getString());
response.setStatus(HttpServletResponse.SC_OK );
} catch (Exception e) {
log.error("Exception: ", e);
} finally {
if( resolver != null) {
resolver.close();
}
if( writer != null ){
writer.close();
}
if (writerResponse != null) {
writerResponse.clearWriter();
}
}
}
}
Using a ResourceDecorator would be simpler, it can return a ResourceWrapper that implements the required changes. Just be careful to keep the decorator's decorate method efficient when it's called for a Resource that it doesn't want to decorate, as it will be called for all Resources.

#Reference Object Query in Morphia using MongoDB

I got two Entities :
public class UserAccount extends BaseEntity {
#Expose
#Property("username")
#Indexed(value = IndexDirection.ASC, name = "userNameIndex", unique = true)
private String userName = new String();
#Expose
#Property("password")
private String password = new String();
}
and
public class UserProfile extends BaseEntity {
#Expose
#Property("first name")
#Indexed(value = IndexDirection.ASC, name = "firstNameIndex")
private String firstName = new String();
#Expose
#Property("middle name")
// #Indexed(value = IndexDirection.ASC, name = "middleNameIndex")
private String middleName = new String();
#Expose
#Property("last name")
#Indexed(value = IndexDirection.ASC, name = "lastNameIndex")
private String lastName = new String();
#Expose
#Reference(/* idOnly = true, */value = "user id" /* , lazy = true */)
private UserAccount userAccount = new UserAccount();
}
I am trying to search all Users based on searched UserName (contains! but unique) and UsedProfileObjectId (#Id). I am trying to constraint check while saving userdetails if the provided username is Unique or not? (I need to check it in both new add and update cases). So I tried to code this:
public List<UserProfile> findAllUsersWithSameUserName(ObjectId id,
String userName) {
Datastore ds = getDatastore();
Query<UserProfile> profileQuery = ds.createQuery(UserProfile.class);
Query<UserAccount> accountQuery = ds.createQuery(UserAccount.class);
accountQuery.criteria("username").containsIgnoreCase(userName);
container.add(profileQuery.criteria("user id").in(
accountQuery.asKeyList()));
return profileQuery.asList();
}
But this code is showing
java.lang.NullPointerException
Am I missing something on code?
Also I try to enforce
#Reference(value = "user id", lazy = true)
private UserAccount userAccount = new UserAccount();
But, I got no clue how to rebind those Object with NO Data?
I tried to do this:
user = userProfileDAO.findUserByProfileID(id);
user.getUserAccount();
user.getUserAccount().getUserName();
user.getUserAccount().getPassword();
// Gson gson = new Gson();
// .setDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").create();
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd")
.excludeFieldsWithoutExposeAnnotation().setPrettyPrinting()
.create();
response = gson.toJson(user, UserProfile.class);
Still the reponse got EMPTY UserAccount Data:
"userAccount": {
"userName": "",
"password": "",
"isDeleted": false,
"isActive": false,
"addedOn": "2015-08-06"
},
Even though on inspection I can get actual data like this: user.getUserAccount().getUserName()
Could not find any good example of using lazy=true in Morphia too? How can I enforce this lazy effect on my code?
This is a way how #Reference Object Query need to be done:
public UserProfile findAllUsersWithSameUserName(ObjectId id, String userName) {
Datastore ds = getDatastore();
Query<UserProfile> profileQuery = ds.createQuery(UserProfile.class);
Query<UserAccount> accountQuery = ds.createQuery(UserAccount.class);
accountQuery.criteria("username").hasThisOne(userName.toString());
profileQuery.and(profileQuery.criteria("_id").notEqual(id),
profileQuery.criteria("user id").in(accountQuery.asKeyList()));
return profileQuery.get();
}

EntityFramework 6.0.0-alpha3 - EdmxWriter.WriteEdmx() fails after update to alpha3 from alpha2

The following extension works for EF6 alpha2 but stopped working with alpha3 with null reference exception. The failing statement is the EdmxWriter.WriteEdmx(..)
The views pre-generation is performed on a code-first context.
How to achieve pre-generate views using EF6 alpha3?
public static PreGeneratedViews PreGenerateViews<T>(this T dbContext) where T : DbContext
{
Trace.TraceInformation("PreGenerating views");
//define ef collections
EdmItemCollection edmItemCollection = null;
StoreItemCollection storeItemCollection = null;
StorageMappingItemCollection mappingItemCollection = null;
//get ef collections
GetItemCollections(
GetEdmx(dbContext),
out edmItemCollection,
out storeItemCollection,
out mappingItemCollection);
IList<EdmSchemaError> errors = null;
//get the generated views
Dictionary<string, string> extentViews = GetExtentViews(mappingItemCollection, out errors);
//return the pregenerated views as string (xml document)
return new PreGeneratedViews
{
EdmEntityContainerName = edmItemCollection.GetItems<EntityContainer>().Single().Name,
StoreEntityContainerName = storeItemCollection.GetItems<EntityContainer>().Single().Name,
HashOverMappingClosure =
ReflectionHelper.GetMappingClosureHash(edmItemCollection.EdmVersion,
mappingItemCollection),
HashOverAllExtentViews =
ReflectionHelper.GenerateHashForAllExtentViewsContent(edmItemCollection.EdmVersion,
extentViews),
ViewCount = extentViews.Count,
Views = CreateViews(extentViews),
ViewsEmbeddedResourceName =
string.Format("DbContextViews{0}.xml", Guid.NewGuid().ToString("N")),
};
}
private static XDocument GetEdmx(DbContext dbContext)
{
var ms = new MemoryStream();
using (XmlWriter writer = XmlWriter.Create(ms))
{
EdmxWriter.WriteEdmx(dbContext, writer);
}
ms.Position = 0;
return XDocument.Load(ms);
}
private static void SplitEdmx(XDocument edmx, out XmlReader csdlReader, out XmlReader ssdlReader,
out XmlReader mslReader)
{
// xml namespace agnostic to make it work with any version of Entity Framework
XNamespace edmxNs = edmx.Root.Name.Namespace;
XElement storageModels = edmx.Descendants(edmxNs + "StorageModels").Single();
XElement conceptualModels = edmx.Descendants(edmxNs + "ConceptualModels").Single();
XElement mappings = edmx.Descendants(edmxNs + "Mappings").Single();
ssdlReader = storageModels.Elements().Single(e => e.Name.LocalName == "Schema").CreateReader();
csdlReader = conceptualModels.Elements().Single(e => e.Name.LocalName == "Schema").CreateReader();
mslReader = mappings.Elements().Single(e => e.Name.LocalName == "Mapping").CreateReader();
}
private static void GetItemCollections(XDocument edmx, out EdmItemCollection edmItemCollection,
out StoreItemCollection storeItemCollection,
out StorageMappingItemCollection mappingItemCollection)
{
// extract csdl, ssdl and msl artifacts from the Edmx
XmlReader csdlReader, ssdlReader, mslReader;
SplitEdmx(edmx, out csdlReader, out ssdlReader, out mslReader);
// Initialize item collections
edmItemCollection = new EdmItemCollection(new[] {csdlReader});
storeItemCollection = new StoreItemCollection(new[] {ssdlReader});
mappingItemCollection = new StorageMappingItemCollection(edmItemCollection, storeItemCollection,
new[] {mslReader});
}
private static Dictionary<string, string> GetExtentViews(StorageMappingItemCollection mappingItemCollection,
out IList<EdmSchemaError> errors)
{
Dictionary<EntitySetBase, string> views = ReflectionHelper.GenerateViews(mappingItemCollection, out errors);
if (errors != null && errors.Any())
{
return null;
}
var extentViews = new Dictionary<string, string>(views.Count);
foreach (var kvp in views)
{
extentViews.Add(
GetExtentFullName(kvp.Key),
kvp.Value.Replace("\r\n", "\n")); // replace accounts for Xml new line normalization
}
return extentViews;
}
private static string GetExtentFullName(EntitySetBase entitySet)
{
return string.Format("{0}.{1}", entitySet.EntityContainer.Name, entitySet.Name);
}
private static string CreateViews(Dictionary<string, string> extentViews)
{
var sb = new StringBuilder();
//var embeddedViewsFileName = Path.ChangeExtension(Host.TemplateFile, "xml");
using (XmlWriter writer = XmlWriter.Create(sb, new XmlWriterSettings
{
Indent = true,
Encoding = Encoding.UTF8
}))
{
writer.WriteStartElement("views");
foreach (var kvp in extentViews)
{
writer.WriteStartElement("view");
writer.WriteAttributeString("extent", kvp.Key);
writer.WriteCData(kvp.Value);
writer.WriteEndElement();
}
writer.WriteEndElement();
}
return sb.ToString();
}
#region Nested type: ReflectionHelper
private static class ReflectionHelper
{
private static readonly Assembly efAssembly = typeof (StorageMappingItemCollection).Assembly;
private static readonly MethodInfo generateViewsMethodInfo =
typeof (StorageMappingItemCollection).GetMethod("GenerateEntitySetViews",
BindingFlags.NonPublic | BindingFlags.Instance);
private static readonly MethodInfo getMappingClosureHashMethodInfo =
efAssembly.GetType("System.Data.Entity.Core.Mapping.MetadataMappingHasherVisitor", true)
.GetMethod("GetMappingClosureHash", BindingFlags.Static | BindingFlags.NonPublic);
private static readonly MethodInfo generateHashForAllExtentViewsContentMethodInfo =
efAssembly.GetType("System.Data.Entity.Core.Common.Utils.MetadataHelper", true)
.GetMethod("GenerateHashForAllExtentViewsContent", BindingFlags.Static | BindingFlags.NonPublic);
public static Dictionary<EntitySetBase, string> GenerateViews(
StorageMappingItemCollection mappingItemCollection, out IList<EdmSchemaError> errors)
{
errors = null;
return
(Dictionary<EntitySetBase, string>)
generateViewsMethodInfo.Invoke(mappingItemCollection, new object[] {errors});
}
public static string GetMappingClosureHash(double schemaVersion,
StorageMappingItemCollection mappingItemCollection)
{
return (string) getMappingClosureHashMethodInfo.Invoke(
null,
new object[]
{
schemaVersion,
// CodeFirst currently creates always one entity container
mappingItemCollection.GetItems<GlobalItem>().Single(
i => i.GetType().Name == "StorageEntityContainerMapping")
});
}
public static string GenerateHashForAllExtentViewsContent(double schemaVersion,
Dictionary<string, string> extentViews)
{
return (string) generateHashForAllExtentViewsContentMethodInfo.Invoke(
null,
new object[] {schemaVersion, extentViews});
}
}
The stacktrace is the following:
NullReferenceException
at: System.Data.Entity.Edm.Serialization.EdmSerializationVisitor.VisitEdmAssociationSet(AssociationSet item)
at: System.Data.Entity.Edm.EdmModelVisitor.VisitCollection[T](IEnumerable1 collection, Action1 visitMethod)
at: System.Data.Entity.Edm.EdmModelVisitor.VisitAssociationSets(EntityContainer container, IEnumerable`1 associationSets)
at: System.Data.Entity.Edm.EdmModelVisitor.VisitEdmEntityContainer(EntityContainer item)
at: System.Data.Entity.Edm.Serialization.EdmSerializationVisitor.VisitEdmEntityContainer(EntityContainer item)
at: System.Data.Entity.Edm.EdmModelVisitor.VisitCollection[T](IEnumerable1 collection, Action1 visitMethod)
at: System.Data.Entity.Edm.EdmModelVisitor.VisitEntityContainers(IEnumerable`1 entityContainers)
at: System.Data.Entity.Edm.EdmModelVisitor.VisitEdmModel(EdmModel item)
at: System.Data.Entity.Edm.Serialization.EdmSerializationVisitor.Visit(EdmModel edmModel, String namespaceName, String provider, String providerManifestToken)
at: System.Data.Entity.Edm.Serialization.EdmSerializationVisitor.Visit(EdmModel edmModel, String provider, String providerManifestToken)
at: System.Data.Entity.Edm.Serialization.SsdlSerializer.Serialize(EdmModel dbDatabase, String provider, String providerManifestToken, XmlWriter xmlWriter, Boolean serializeDefaultNullability)
at: System.Data.Entity.ModelConfiguration.Edm.Serialization.EdmxSerializer.WriteEdmxRuntime()
at: System.Data.Entity.ModelConfiguration.Edm.Serialization.EdmxSerializer.Serialize(DbDatabaseMapping databaseMapping, DbProviderInfo providerInfo, XmlWriter xmlWriter)
at: System.Data.Entity.Infrastructure.EdmxWriter.WriteEdmx(DbModel model, XmlWriter writer)
at: System.Data.Entity.Infrastructure.EdmxWriter.WriteEdmx(DbContext context, XmlWriter writer)
at: **.DbContextPreGenerateViewExtension.GetEdmx(DbContext dbContext)
Thanks!
I just submitted a fix for work item 867 (35852e8392ad). It should fix the NRE. The fix should be included in the today's nightly build. Can you give it a try and let me know if this fixed the problem?
This is a known bug in Alpha 3.