ClassCastException in customComponentcontroller model - sap-commerce-cloud

I have created my custom ABC component extending the SimpleCMSComponentModel.
It is giving class cast exception in ABCComponentController - > fillModel
java.lang.ClassCastException: de.hybris.platform.cms2.model.contents.components.SimpleCMSComponentModel cannot be cast to ABCComponentController
Any suggestion will be helpfull

You must be forgot to change your custom model from SimpleCMSComponentModel to ABCComponentModel.
This should be like this
#Controller("ABCComponentController")
#Scope("tenant")
#RequestMapping(value = ControllerConstants.Actions.Cms.ABCComponentController)
public class ABCComponentController extends AbstractCMSComponentController<ABCComponentModel>
{
/**
* Fill Model
*/
#Override
protected void fillModel(final HttpServletRequest request, final Model model, final ABCComponentModel component)
{
//
}
}
where
ControllerConstants.Actions.Cms.ABCComponentController = "/view/ABCComponentController"; or your custom path..

Related

Mockito, channel output of void function to System.out?

I have this logging class in my legacy application,
I am trying to Mock it for testing and output all messages from "WriteLog" method to System.out
This is the class
public abstract class LoggingServicesWorker {
public abstract void WriteLog(ELogLevel arg0, int arg1,String arg2,String arg3);
}
This is what I did so far,
I am not sure how to write to System.out
Also How to tell the first argument to have any enum type (ELogLevel)?
LoggingServicesWorker logger = mock(LoggingServicesWorker.class);
Mockito.doNothing().when(logger).WriteLog(ELogLevel.DEBUG,anyInt(),anyString(),Mockito.eq(anyString()));
You can use Mockito#doAnswer for executing side-effects:
doAnswer((invocation -> {
System.out.println(Arrays.toString(invocation.getArguments()));
return null;
}))
.when(worker)
.WriteLog(any(ELogLevel.class), anyInt(), anyString(), anyString());
Standalone class with the default behavior for return values (and usable with Java 7):
class PrintArgsToStdoutAnswer implements Answer<Object> {
private final ReturnsEmptyValues defaultReturn = new ReturnsEmptyValues();
#Override
public Object answer(InvocationOnMock invocation) throws Throwable {
System.out.println(Arrays.toString(invocation.getArguments()));
return defaultReturn.answer(invocation);
}
}
...and used in the test method:
doAnswer(new PrintArgsToStdoutAnswer())...

JukitoRunner, bind mock of final class

How to bind mock of final class in Jukito ?
For example :
public final class SomeFinalClass(){
public SomeFinalClass(String someString){
}
}
//Testing class
#Runwith(JukitoRunner.class)
public class TestingClass(){
#Inject
private SomeFinalClass someFinalClassMock;
public static class TestModule extends JukitoModule {
#Override
protected void configureTest() {
// bind(SomeClient.class).in(TestSingleton.class);
}
#Provides
public SomeFinalClass getSomkeFinalClass() {
return Mokito.mock(SomeFinalClass.class); //throws error
}
}
}
Is there a way i can use PowerMockito with JukitoRunner ?
You can mock a final class if you're using Mockito 2. From Mockito 2 Wiki:
Mocking of final classes and methods is an incubating, opt-in feature. It uses a combination of Java agent instrumentation and subclassing in order to enable mockability of these types. As this works differently to our current mechanism and this one has different limitations and as we want to gather experience and user feedback, this feature had to be explicitly activated to be available ; it can be done via the mockito extension mechanism by creating the file src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker containing a single line: mock-maker-inline.
After you created this file, Mockito will automatically use this new engine and one can do :
final class FinalClass {
final String finalMethod() { return "something"; }
}
FinalClass concrete = new FinalClass();
FinalClass mock = mock(FinalClass.class);
given(mock.finalMethod()).willReturn("not anymore");
assertThat(mock.finalMethod()).isNotEqualTo(concrete.finalMethod());

Cannot override tranlations (journal-lang)

I would like to override some Liferay's modules tranlations. I am fallowing: https://dev.liferay.com/develop/tutorials/-/knowledge_base/7-0/overriding-a-modules-language-keys
It works but not for all strings. First of all I would like to override some strings in journal-lang module (com.liferay.journal.lang), but this module doesn't have servlet context name. I have tried to skip that but it doesn't work. How can I override these strings?
I'm also trying to override some core strings (from portal-impl) but some of them remains untranslated. For example "Add Field" (add-field) from defining new form view. Any possible solutions?
journal-lang is a language components. In order to override some string from them you have to create a component for bundle com.liferay.journal.web or com.liferay.journal.service.
You've to create a CustomResourceBundle with extends ResourceBundle
#Component(immediate = true, property = { "language.id=en_US" }, service = ResourceBundle.class)
public class DefaultCustomResourceBundle extends ResourceBundle {
#Override
public Enumeration<String> getKeys() {
return _resourceBundle.getKeys();
}
#Override
protected Object handleGetObject(String key) {
return _resourceBundle.getObject(key);
}
private final ResourceBundle _resourceBundle = ResourceBundle.getBundle("content.Language", UTF8Control.INSTANCE);
}
And this should override translations accross the portal.

How to override class DefaultScreenNameValidator in liferay 7?

I am trying to override a class DefaultScreenNameValidator that implements ScreenNameValidator interface. For this , I copied the class and put it into another module. One change that I made is in annotation that is as follows:-
#Component(
property = {
"service.ranking:Integer=500"
}
)
I got a successful build using this. But when I tried to deploy the project, I got error as java.lang.NoClassDefFoundError: com/liferay/portal/kernel/security/auth/ScreenNameValidator.Can you suggest me how to eradicate this error. Thanx in advance..
I'm wondering, wouldn't it be better to instead create a module that also implements the ScreenNameValidator interface, and define your custom logic in there? Then you can just simply tell Liferay to use that validator instead of the DefaultScreenNameValidator.
For example, a minimalistic implementation:
import com.liferay.portal.kernel.security.auth.ScreenNameValidator;
import org.osgi.service.component.annotations.Component;
#Component(
immediate = true,
service = ScreenNameValidator.class
)
public class CustomScreenNameValidator implements ScreenNameValidator {
#Override
public boolean validate(long companyId, String screenName) {
// Your custom logic
}
}
make sure you have the dependency to portal-kernel in the build.gradle
dependencies {
compile 'com.liferay.portal:com.liferay.portal.kernel:2.0.0'
I made a screenNameValidator using blade-cli you can see the projet at https://github.com/bruinen/liferay-blade-samples/tree/master/liferay-workspace/modules/blade.screenname.validator
import com.liferay.portal.kernel.security.auth.ScreenNameValidator;
import org.osgi.service.component.annotations.Component;
import java.util.Locale;
#Component(
immediate = true,
property = {"service.ranking:Integer=100"},
service = ScreenNameValidator.class
)
public class CustomScreenNameValidator implements ScreenNameValidator {
#Override
public String getAUIValidatorJS() {
return "function(val) {return !(val.indexOf(\"admin\") !==-1)}";
}
#Override
public String getDescription(Locale locale) {
return "The screenName contains reserved words";
}
#Override
public boolean validate(long companyId, String screenName) {
return !screenName.contains("admin");
}
}

How can I specify which instances of a class are unmarshalled using an XMLAdapter?

I have the following java class and have placed an XmlJavaAdapter annotation on the payerPartyReference variable. I want the adapter PartyReferenceAdapter to be used for unmarshalling ONLY this variable, not any other variables which have the same type of PartyReference, whether in this class or some other class. How can I do this? Thanks for your help!
public class InitialPayment extends PaymentBase
{
// Want PartyReferenceAdapter to be used here
#XmlJavaTypeAdapter(PartyReferenceAdapter.class)
protected PartyReference payerPartyReference;
//
// Dont want PartyReferenceAdapter to be used here
protected PartyReference receiverPartyReference;
//
protected AccountReference receiverAccountReference;
#XmlSchemaType(name = "date")
protected XMLGregorianCalendar adjustablePaymentDate;
#XmlSchemaType(name = "date")
protected XMLGregorianCalendar adjustedPaymentDate;
protected Money paymentAmount;
}
My Adapter is defined as follows:
public class PartyReferenceAdapter
extends XmlAdapter < Object, PartyReference > {
public PartyReference unmarshal(Object obj) throws Exception {
Element element = null;
if (obj instanceof Element) {
element = (Element)obj;
String reference_id = element.getAttribute("href");
PartyReference pr = new PartyReference();
pr.setHref(reference_id);
return pr;
}
public Object marshal(PartyReference arg0) throws Exception {
return null;
}
}
Field/Property Level
If you set #XmlJavaTypeAdapter on a field/property it will only be used for that property.
http://bdoughan.blogspot.com/2010/07/xmladapter-jaxbs-secret-weapon.html
Type Level
If you set #XmlJavaTypeAdapter on a type, then it will used for all references to that type.
http://bdoughan.blogspot.com/2010/12/jaxb-and-immutable-objects.html
Package Level
If you set #XmlJavaTypeAdapter on a package, then it will be used for all references to that type within that package:
http://bdoughan.blogspot.com/2011/05/jaxb-and-joda-time-dates-and-times.html

Resources