ModelMapper - NPE when trying to skip destination mapping? - modelmapper

A very simple problem which smoked holes in my case. I'm trying to skip userDTO's setPassword every time when I convert User --> UserDTO.
I get NullPointerException, at this line in ModelMapper -
I understand the 'source' mapping is not present but my question is why does it even care about it since I asked it to not set the password at all.
Sorry, I think I'm lacking some basics here with ModelMapper. Thank you for your time and help.
Got help from ModelMapper skip a field and few other links but no luck.
Below is the code
#Bean
public ModelMapper modelMapper() {
ModelMapper mm = new ModelMapper();
mm.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
TypeMap<User, UserDTO> userEntityToDTOMap = mm.createTypeMap(User.class, UserDTO.class);
userEntityToDTOMap.addMappings(a -> a.skip(UserDTO::setPassword));
return mm;
}
public static void main(String[] args) {
BootstrapConfigurationManager mgr = new BootstrapConfigurationManager();
ModelMapper mm = mgr.modelMapper();
mm.getConfiguration().setPropertyCondition(Conditions.isNotNull());
User user = new User();
user.setId(44L);
user.setPassword("password");
UserDTO userDTO = new UserDTO();
userDTO.setEmailAddress("abc#abc.com");
mm.map(user, userDTO);
System.out.println(userDTO.getId());
System.out.println(userDTO.getEmailAddress());
System.out.println(userDTO.getPassword());
}

Ah !!! It was a bug in v 1.1.0. I just upgraded it to 2.3.2 and I no longer get NPE. I should have thought of upgrading the version before posting this question.

Related

How to Mock GetBlobsByHierarchy() from Azure.Storage.Blobs?

Could anyone please help me to mock GetBlobsByHierarchy() from Azure.Storage.Blobs? I need to create mock for the following code in xUnit:
BlobContainerClient container;
var resultSegment = container.GetBlobsByHierarchy(prefix:prefix, delimiter:"/")
.AsPages(continuationToken, segmentSize);
The details of the code is in this Link from Microsoft site. I tried to mock this GetBlobsByHierarchy() function but failed. Please give me some idea/sample.
I resolved my problems. I have created stub class for BlobContainerClient class and overwrite the required functions..
Below are the code sample,
public sealed class StubBlobContainerClient : BlobContainerClient
{
public override Pageable<BlobHierarchyItem> GetBlobsByHierarchy(BlobTraits traits = BlobTraits.None, BlobStates states = BlobStates.None, string delimiter = null, string prefix = null, CancellationToken cancellationToken = default)
{
//implementation
}
}
You are always welcome to share any other way to resolve the issue.

'this' is not available in variables android studio

I have a class to take data from a database and every time I create a variable in the debug mode the name of the variable appears with the message 'this' is not available and I cannot save any type of data in it.
public class DatosPerfilUsuario {
RequestQueue requestQueue;
SharedPreferencias sharedPreferencias = new SharedPreferencias();
String[] StringSplit;
public void RetirarPerfilUsuario(final Context context, final ImageView imageView, final EditText nombre, final EditText nombreusuario, final EditText sexo, final EditText edad, final EditText email, final EditText bio){
StringRequest getRequest = new StringRequest(Request.Method.POST, DatosBase.CONEXION_DB_RETIRAR_PERFILUSUARIO, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.equals("0")){
}else {
StringSplit = response.split("/");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
protected Map<String,String> getParams(){
Map<String, String> params = new HashMap<String, String>();
params.put("NombreUsuario",sharedPreferencias.obtenerValorString(context,"Usuario").toLowerCase());
return params;
}
};
requestQueue = Volley.newRequestQueue(context);
requestQueue.add(getRequest);
}
Code
This situation happens to me with each type of variable that I create int, string, bool ...
I have different classes that do the same, but the problem only arises in this.
I have looked for a solution to the problem in google but there is very little information about this problem, if someone has the solution or understands why this problem is due I would appreciate your help.
UPDATED
It looks like this is not preventing you from compiling and running the code, only that you can't view the variable's contents in the debug window. Sorry. This is not uncommon. The debugger can't determine the this in the current context.
It looks like you may be using Android Studio? If so, check this: https://stackoverflow.com/a/37273436/12431728
OLD / WRONG
Your Response.Listener<String> is an anonymous class, so this refers to the anonymous class. Since StringSplit is a field of the outer class, you should be able to access it as:
OuterClassName.this.StringSplit = ...
Where OuterClassName is the name of the class that contains this code (and StringSplit).

Liferay Hook - Manipulation request parameters

I ran into a little problem with a hook. Szenario:
The Hook should override struts action /document_library/edit_file_entry which is called, whenever a user uploads a document into the document library.
The goal is to check the title of the document and rename it following a given naming-scheme.
My solution:
#Override
public void processAction(
StrutsPortletAction originalStrutsPortletAction,
PortletConfig portletConfig, ActionRequest actionRequest,
ActionResponse actionResponse)
throws Exception {
//Get old title - set new title
String oldTitle = ParamUtil.getString(actionRequest, "title");
String newTitle = "Test";
//wrap request to set param
DynamicActionRequest actionRequestNew = new DynamicActionRequest(actionRequest);
actionRequestNew.setParameter("title", newTitle );
//call original struts action with modified title
originalStrutsPortletAction.processAction(originalStrutsPortletAction, portletConfig, actionRequestNew, actionResponse);
}
The Problem is that the original Struts action in portal-impl/src/com/liferay/portlet/documentlibrary/action/EditFileEntryAction.java uses PortalUtil.getUploadPortletRequest(actionRequest); which expects a PortletRequestImpl.
But DynamicActionRequest cannot be cast to PortletRequestImpl.
See:
12:07:04,466 ERROR [http-bio-8082-exec-44][render_portlet_jsp:154] java.lang.ClassCastException: com.liferay.portal.kernel.portlet.DynamicActionRequest cannot be cast to com.liferay.portlet.PortletRequestImpl
at com.liferay.portal.util.PortalImpl.getUploadPortletRequest(PortalImpl.java:4067)
at com.liferay.portal.util.PortalUtil.getUploadPortletRequest(PortalUtil.java:1253)
at com.liferay.portlet.documentlibrary.action.EditFileEntryAction.updateFileEntry(EditFileEntryAction.java:653)
at com.liferay.portlet.documentlibrary.action.EditFileEntryAction.processAction(EditFileEntryAction.java:129)
at com.liferay.portal.struts.StrutsPortletActionAdapter.processAction(StrutsPortletActionAdapter.java:51)
at com.liferay.portal.kernel.struts.BaseStrutsPortletAction.processAction(BaseStrutsPortletAction.java:42)
at com.foo.hook.portlet.sites.action.MyEditFileEntryAction.processAction(MyEditFileEntryAction.java:83)
at com.liferay.portal.kernel.bean.ClassLoaderBeanHandler.invoke(ClassLoaderBeanHandler.java:67)
at com.liferay.portal.struts.PortletActionAdapter.processAction(PortletActionAdapter.java:55)
at com.liferay.portal.struts.PortletRequestProcessor.process(PortletRequestProcessor.java:169)
at com.liferay.portlet.StrutsPortlet.processAction(StrutsPortlet.java:212)
at com.liferay.portlet.FilterChainImpl.doFilter(FilterChainImpl.java:70)
at com.liferay.portal.kernel.portlet.PortletFilterUtil.doFilter(PortletFilterUtil.java:48)
at com.liferay.portlet.InvokerPortletImpl.invoke(InvokerPortletImpl.java:548)
at com.liferay.portlet.InvokerPortletImpl.invokeAction(InvokerPortletImpl.java:579)
at com.liferay.portlet.InvokerPortletImpl.processAction(InvokerPortletImpl.java:294)
at com.liferay.portal.action.LayoutAction.processPortletRequest(LayoutAction.java:944)
at com.liferay.portal.action.LayoutAction.processLayout(LayoutAction.java:688)
at com.liferay.portal.action.LayoutAction.execute(LayoutAction.java:249)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431)
How can I change the parameter without using DynmicActionRequest? Any suggestions?
I'm running Liferay-Portal 6.1.20 EE.
Thanks in advance.
There are two approaches I can think of.
1) Create ActionRequestWrapper object and add a parameter. This would probably solve your issue.
2) Create a subclass of LR's action class. In that make the needed code changes. Create a hook and make the new action class available to LR.
I hope this helps.
You can set the parameter in existing actionRequest:
actionRequest.setParameter("title", newTitle);
It will updated with new value.

Gmail Api Java Client - Use mockito/powermock example to mock Gmail API calls

We are using the Gmail API Java Client version 1.19.0. Is there anyone that has implemented successfully a working mock object that could be used for stubing requests such as:
gmailClient.users().history().list("me").setStartHistoryId(startHistoryId).setPageToken(pageToken).execute();
Essentially, we would like to stub the above call and create a specific response, to test different business scenarios.
Please check below a working example of the above question. No need to use powermock. Mockito is only needed.
#Before
public void init() throws Exception{
ListHistoryResponse historyResponse = new ListHistoryResponse();
historyResponse.setHistoryId(BigInteger.valueOf(1234L));
List<History> historyList = new ArrayList<>();
History historyEntry = new History();
Message message = new Message();
message.setId("123456");
message.setThreadId("123456");
List<Message> messages = new ArrayList<>();
messages.add(message);
historyEntry.setMessages(messages);
historyList.add(historyEntry);
mock = mock(Gmail.class);
Gmail.Users users = mock(Gmail.Users.class);
Gmail.Users.History history = mock(Gmail.Users.History.class);
Gmail.Users.History.List list = mock(Gmail.Users.History.List.class);
when(mock.users()).thenReturn(users);
when(users.history()).thenReturn(history);
when(history.list("me")).thenReturn(list);
when(list.setStartHistoryId(BigInteger.valueOf(123L))).thenReturn(list);
when(list.setPageToken(null)).thenReturn(list);
when(list.execute()).thenReturn(historyResponse);
}
you can mock the classes are long as they're not final, etc. what's the limitation here? (haven't looked at the source code for the Google java client libraries but shouldn't be gmail-specific--if you've found someone doing it for another Google java client API you should be able to re-use it).
There is also MockHttpTransport helper class for such a scenario. Please consult with documentation chapter HTTP Unit Testing
HttpTransport transport = new MockHttpTransport() {
#Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
return new MockLowLevelHttpRequest() {
#Override
public LowLevelHttpResponse execute() throws IOException {
MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
response.addHeader("custom_header", "value");
response.setStatusCode(404);
response.setContentType(Json.MEDIA_TYPE);
response.setContent("{\"error\":\"not found\"}");
return response;
}
};
}
};

"error": "invalid_client" from custom OWIN implementation

I am implementing OWIN authentication on a mysql backend, I dont thnk thats a problem as my registration work pretty well. I have basically worked off this post (i.e. nicked most of the code).
I am also using DI via autofac so I have changed a few things around to inject dependencies into the SimpleAuthorizationServerProvider
THE PROBLEM
I post grant_type=password, username and password to http://localhost/myappurl/token and I get back "error":"invalid_client". I get no hits when I try to debug so its probably failing in the library and not getting to my own code. Does anyone know why this would be?
Please pardon the lengthy code, I have no idea where the issue could be so I have posted everything I think is relevant, if anyone needs to see more code, please ask.
SimpleAuthorizationServerProvider
public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
private readonly IUserService _userService;
public SimpleAuthorizationServerProvider(IUserService userService)
{
_userService = userService;
}
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
var authenticate = await _userService.FindUser(context.UserName, context.Password);
if (!authenticate)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("role", "user"));
context.Validated(identity);
}
}
Startup
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
ConfigureOAuth(app, (IOAuthAuthorizationServerProvider)config.DependencyResolver.GetService(typeof(IOAuthAuthorizationServerProvider)));
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}
public void ConfigureOAuth(IAppBuilder app, IOAuthAuthorizationServerProvider provider)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(90),
Provider = provider,
ApplicationCanDisplayErrors=true,
};
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
IocConfig
public static class IocConfig
{
public static void Register(HttpConfiguration config)
{
var builder = new ContainerBuilder();
// Configure the container
// Register individual components
builder.Register(c => new MySQLContext()).As<IMySqlContext>().InstancePerRequest();
builder.RegisterType<SimpleAuthorizationServerProvider>().As<IOAuthAuthorizationServerProvider>();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
var container = builder.Build();
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
}
}
You have a lot of code there, so it's not easy to isolate the problem. As a first step, consider removing the code for Autofac DI and see if that makes any difference. It's hard to tell what the problem might be otherwise.
If the issue is indeed related to the DI code, then perhaps this should be a raised as a separate question. In that case, try to create a small code example that demonstrates the issue succinctly. People are more likely to help if the problem code is short and to the point.
Make sure that you've set up SSL for your site. I had a similar issue and the problem was that I was not using SSL.

Resources