Flexible Search Query with JOIN Hybris Example - Hybris Interview question

Flexible Search is an API provided by Hybris to fetch results from Database . You can either use it on hac console or directly in java .

There are some Flexible Query examples which are widely used in Hybris Project .

1. Flexible Query in Hybris to fetch Products :


SELECT * FROM {Product}


We have to put the Model from which the results are required in {}


2. Flexible Query to fetch Products of a particular Catalog

For this type of query we have to use JOIN to as Catalog and Product are different Models in hybris so the data is stored in 2 different tables.


SELECT * FROM {Product AS p
    JOIN Catalog AS  catalog on {p:catalog} = {catalog:pk}}
WHERE 
    {catalog.id} ='electronicProductCatalog'


This above flexible search query will fetch all products of electronicProductCatalog for both Staged and Online Version.


3. Flexible Query in Hybris to fetch Products of a Catalog with Online version

For this type of query we have to use 2 JOIN to as Catalog, Product and CatalogVersion are different Models and  3 different tables.

SELECT * FROM {Product AS p
    JOIN Catalog AS  catalog on {p:catalog} = {catalog:pk}
    JOIN CatalogVersion As ver on {p:catalogVersion} = {ver:pk}
}
WHERE 
    {catalog.id} ='electronicProductCatalog' AND
    {ver.version} = 'Online'


4. Flexible Query in Hybris to fetch Products of a Catalog with Staged version


SELECT * FROM {Product AS p
    JOIN Catalog AS  catalog on {p:catalog} = {catalog:pk}
    JOIN CatalogVersion As ver on {p:catalogVersion} = {ver:pk}
}
WHERE 
    {catalog.id} ='electronicProductCatalog' AND
    {ver.version} = 'Staged'

ModelService.Refresh() method and Its uses - Hybris Interview question


The OOB Hybris Model Service provides a method, to refresh the model. Usually we use this method to refresh the data, before saving the data in database, using save method.
There might be conditions, where some other thread or operation would be updating the same model instance. By doing a refresh, we can be sure of not loosing those changes. This is of more importance, if we are going through a time consuming transaction like payment.
Also transaction like, stock update, may happen simultaneously from multiple users, so we should always refresh the model, before saving it.






Flexible Search Query with JOIN Hybris Example


Hybris Composite Cron Job

Composite Cron Job in Hybris - Hybris Interview question



Composite Cron Job : 

1. A composite cronJob is a composition of multiple cronjobs .

2. It means that a cronjob will call another job and also multiple cronjobs successively.

3. This phenomena is driven by CompositeCronJob and CompositeEntry.





How to make Extension as Template in Hybris - Hybris Interview question

1.Change in extensioninfo.xml file 

First add the property below in the extensioninfo.xml after core tag of  the extension which you want to use as a template.

Eg. We want to make electronicstore as template. Add he below property in extensioninfo.xml of  electronicstore.

<meta key=”extgen-template-extension” value=”true”/>


2. Create an extgen.properties file .

Create  a blank file named as extgen.properties parallel to project.properties file in your extension.

We will create an extgen.properties file in electronic store 

3. Modify extgen.properties file .

Modify extgen.properties file with below properties :

YEXTNAME_TOKEN=electronicsstore
YMODULE_TOKEN=electronic
YMODULE_PACKAGE_ROOT=store
YMODULE_CLASS_PREFIX=store
YPACKAGE_TOKEN=de.hybris.platform.electronicsstore
YMANAGER_TOKEN=ElectronicsstoreManager
YCLASSPREFIX_TOKEN=Electronicsstore
YGENERATED_TOKEN=Generated

4. Do Ant extgen .

Go to your platform directory .
Type setantenv.bat 
Type ant extgen .
You will see your extension in templates.

Create a new extension in Hybris - Hybris Interview question

To create an extension we will use ant extgen command and yempty template .

1. Go to platform directory .

2. Run setantenv.bat commad.

3. Run ant extgen

4. Extgen prompts you to enter extension name . Enter extension name and press Enter.

5. Enter package name as desired .

6. New Extension will be created in custom folder in your hybris /bin directory.

7. Add Extension name to localExtensions.xml.

8. Run ant clean all.

Difference between ant all and ant clean all in hybris - Hybris Interview question

ant clean all
ant all
 Delete all model classes create again.
Does not delete model classes but create new ones if required.
It checks whether config,log,data,temp etc folders are available inside hybris folder.
If this folder structure is not available then it creates the folder structure
It assumes folder structure is already exist
 If there is no build, It will create a build from scratch, if there is any build exist, It will delete and recreate it
If there is no build, it will create a build from scratch, if there is any build exist, it will modify it rather than recreating it.
Slower than ant all as it delete classes and folders and regenerate them.
Faster than ant clean all
Is advised to use only when there are changes in items.xml file
Is advised to use for every build.

How can you add values to a collection type attribute and Map from Impex in Hybris ?

1. For Collection type attribute you can use comma separated values which are to be inserted.

eg. INSERT_UPDATE UserGroup;uid[unique=true];groups(uid)[mode=append];readableLanguages(isocode);writeableLanguages(isocode);
;base-electronics-cmsmanagergroup;basecmsmanagergroup;ja,en,de,zh;ja,en,de,zh



Here , both readableLanguages and writeableLanguages are of type LanguageCollection .

2. Also you can use mode=append in header for Collection Type attribute .



3. For Map type attribute by default you have to use -> delimiter within key and value pair .

INSERT_UPDATE myProduct;myAttribute
;myKey->myValue

How to make cronjob run on some servers(in case of load balancer or cluster ) and but not on others?

This scenario can be achieved using Nodes concept in hybris.

1. First you need to define applicable nodes in local.properties using cluster.node.groups property such as


cluster.node.groups = backoffice,storefront .


2. Assign the cronjob to group of nodes by 2 ways :

 a) When you define the cronjob then use method .setNodeGroup("nameofnodegroup") like .setNodeGroup("storefront ").

b) Using Impex :


INSERT_UPDATE CronJob; code[unique=true];job(code);nodeGroup
;myCronJob;myJob;storefront


Whenever next time the cronjob is going to it will trigger on the nodeGroup defined .

Model service create method vs new operator - Hybris Interview question



ModelService is a Service provided by Hybris Out of the Box . It has many predefined methods such as create() , save () ,saveAll() .




When we try to create a new instances of an item type programmatically, there are two ways




1 . Using the Traditional new operator

2. or the hybris way, using the ModelService.create()




For Example

ProductModel product1 = new ProductModel();

ProductModel product2 = modelService.create(ProductModel.class);

The advantages of using model service method are below:
The model service create method will generate and assign the pk for product object.
The create method will initialize the default values, defined in items.xml for mandatory attributes.
While calling save all method, the object is already attached to context, and will be saved. While product1 needs to attach explicitly.



Flexible Search Query with JOIN Hybris Example


Hybris Composite Cron Job

Hybris Interview Questions -items.xml

Q.1 What is the location of items.xml in Hybris?

Ans : Items.xml is extension specific . Every Extension has resources folder in which you can find items.xml file which perfix the extension name . The syntax is extensioname-items.xml.  For Example : core-items.xml or cockpit-items.xml.

Q .2 What is the basic structure of an Items.xml ?
Ans : The basic sturcture of an items.xml is

    xsi:noNamespaceSchemaLocation="items.xsd">
    <atomictypes>
    ...
    </atomictypes>
    <collectiontypes>
    ...
    </collectiontypes>
    <enumtypes>
    ...
    </enumtypes>
    <maptypes>
    ...
    </maptypes>
    <relations>
    ...
    </relations>
    <itemtypes>
    ...
    </itemtypes>
</items>

Q3. Can the order of the defined itemtypes vary in item.xml?
Ans : No , all the itemtypes defined should be in the order defined above otherwise it ll lead to a build error.

Q4 . How can you define a new item type in items.xml?
Ans : A new item type can be defined using the <itemtypes> tag which should include the code and description attributes of the defined item type.eg:
<itemtype code="NewType"
    extends="Product"
    autocreate="true"
    generate="true" >
</itemtype>

Q5. What is the meaning of various attributes used in defining a new itemtype?
Ans :

1. code: code is the name of the itemtype you defined . For eg. in above mentioned example NewType is the name of the itemtype I have created.

2. extends : extends attribute represents the parent of the new itemtype defined as in the above example Product item the parent of the NewType item defined.

3.autocreate : autocreate attrbiute can take only boolean value such as true and false. Setting autocreate element to true, which lets the hybris Commerce Suite create a new database entry for this type at initialization/update process. Setting the autocreate modifier to false causes a build failure if we are defining a new subtype if you are just adding an attribute the already defined item then autocreate can be set to false as it already has a database entry.

4. generate : This attribute allows the creation of a new Model (Java class) for the new itemtype defined .Setting it to false will lead to non creation of the model class due to which there wont be any build error but you wont be able to use the getter /setters of the attributes defined.

Q6. How an items.xml is verified or validated?
Ans : In your extension's directory /resources folder an item.xsd file exists  using which Hybris commerce Suite validated the items.xml against items.xsd. Any discrepancy caused between two files lead to build failure.

Q7. After creating a new itemtype which layers are effected and how many new classes are created?
Ans :
1. JaloLayer: under gensrc directory of that Extension ->Generated*.java  and gensrc directory is refreshed.
2. Service Layer: Generate model classes as *Model.java under bootstrap/gensrc directory in service layer .
3. *DTO .java and *resources.java :Webservice-related classes which are created to support CRUD logic via RESTful URIs. These classes are only generated when the optional extension platformwebservices is included in your configuration.
4. *java : In JaloLayer which extends the *Generated.java class.

SO in Total 5 new Java classes are created .


                                             Model service create method vs new operator - Hybris Interview question


Q.8 How to make cronjob run on some servers(in case of load balancer or cluster ) and  but not on others?

Ans : Read Here 

Q.9 How can you add values to a collection type attribute and Map from Impex in Hybris ?

Ans : Read Here

Q.10 Difference between ant all and ant clean all in hybris .

Ans .  Read Here .


Q.11 When to use modelService.refresh() method?

Ans . Read Here


How to run 2 hybris servers on same machine ?

How to run multiple hybris instances on same machine?

Flexible Search Query with JOIN Hybris Example

Hybris Composite Cron Job

Spring MVC / Hybris JUnit For Validators

Hi Guys ,today I am going to write a post on Test Validators in Spring MVC with Junit or How to write Junit for Validators.
I faced quite a lot problem in finding a proper solution for that while working in a project . These Validators are used
in Spring MVC and Hybris projects . So Basically while writting a Validator I had to check 2 main things 1st was that expiry date should not be null and
other was the file uploaded in form should have valid format and lesser than 5MB in size. so My Validator method looks as below:




@Override
public void validate(final Object object, final Errors errors)
{
final myForm myForm = (myForm) object;

 if (!checkFileContentType(myForm.getFileScan().getContentType())
{
errors.rejectValue("file", "File is Invalid");
}


if (myForm.getExpiryDate() == null || myForm.getExpiryDate().equals(""))
{
errors.rejectValue("date", "Invalid date");
}

}





so for JUnit of this validator i need to varify errors.rejectValue as feel upload a dummy file with java code in my validtor class.
So my Test class looks as below :






MyValidator = new MyValidator();
}

@Before
public void setUp() throws Exception
{
MockitoAnnotations.initMocks(this);// this line is optional if not using mockito

MyForm myForm= new MyForm();
String path = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
File file = new File(path + "abc.jpeg");
FileItem fi = this.createFileItem("file", file);
CommonsMultipartFile FileScan = new CommonsMultipartFile(fi);
myForm.setFileScan(FileScan);
}



@Test
public void testdatenull()
{

myForm.setFileName("testFileName");
myForm.setExpiryDate(null);
final BindException errors = new BindException(myForm, myForm.class.getName());
MyValidator.validate(myForm, errors);

assertEquals("Invalid date", errors.getFieldError("date").getCode());


}

@Test
public void testEmptyFileScan()
{
MyForm myNewForm= new MyForm();
String path = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
File file = new File(path + "abc.xml");
FileItem fi = this.createFileItem("file", file);
CommonsMultipartFile newFileScan = new CommonsMultipartFile(fi);
myNewForm.setFileScan(newFileScan);
myNewForm.setFileName(StringUtils.EMPTY);
myNewForm.setExpiryDate("15/08/2013");
final BindException errors = new BindException(myNewForm, MyForm.class.getName());
MyValidator.validate(myNewForm, errors);
assertEquals("File is invalid", errors.getFieldError("file").getCode());


}

private FileItem createFileItem(final String fieldName, final File file) throws Exception
{

final boolean isFormField = false;
final String fileName = file.getName();
final String contentType = new MimetypesFileTypeMap().getContentType(file);

final DiskFileItemFactory factory = new DiskFileItemFactory();
final FileItem fileItem = factory.createItem(fieldName, contentType, isFormField, fileName);

final InputStream input = new FileInputStream(file);
final OutputStream output = fileItem.getOutputStream();

IOUtils.copy(input, output);

IOUtils.closeQuietly(input);
IOUtils.closeQuietly(output);

return fileItem;
}





1. In method createFileItem I created a dummy file to send as parameter to my validate method . In test methods I am using
two differen files test.txt and test.jpg as my validtor allows only media file so test.txt is to check the failing criteria.

2. to check error.rejectValue in junit I have used assertEquals . It conatins 2 parameters first is the String and other one is the
value set in Errors object by validator .errors.getFieldError("date") in this the fieldName date is same as given in validator for errors.setrejectValue.


I hope this post helps .If someone has a better code or enhancements that can b done please comment below or also write a mail to admin@javainhouse.com