How do you customize the java JSON serialization done by Google Cloud Endpoints? - google-cloud-endpoints

Below is the relevant method. One of the properties is of LocalDate (Joda).
#ApiMethod(
name = "taxforms.get",
path = "tax-forms",
httpMethod = ApiMethod.HttpMethod.GET
)
public TaxDataList retrieveTaxDataList(
HttpServletRequest httpServletRequest
) {
TaxDataList taxDataList = new TaxDataList( );
TaxData taxData = SampleTax.sampleTaxData( "Tax1098" );
taxDataList.addFormsItem( taxData );
return taxDataList;
}
If I do my own serialization, my code includes this:
ObjectMapper objectMapper = new ObjectMapper( );
// Special handling for dates
objectMapper.registerModule( new JodaModule( ) );
objectMapper.disable( SerializationFeature.WRITE_DATES_AS_TIMESTAMPS );
objectMapper.writeValue( sw, data );
json = sw.toString( );
How can I customize the way the framework does the serialization?

This is a close sample code to what you want and which uses transforms java LocalDate and Instant classes into strings and numbers:
package com.company.example;
import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.Transformer;
import java.time.Instant;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
#Api(
name="myApi",
version="v1",
transformers={
MyApi.MyInstantTransformer.class,
MyApi.MyLocalDateTransformer.class,
}
)
public class MyApi {
#ApiMethod(name="getStuff")
public MyStuff getStuff() {
return new MyStuff();
}
public static class MyStuff {
private final LocalDate date;
private final Instant instant;
MyStuff() {
date = LocalDate.now();
instant = Instant.now();
}
public LocalDate getDate() { return date; }
public Instant getInstant() { return instant; }
}
public static class MyInstantTransformer implements Transformer<Instant, Long> {
public Instant transformFrom(Long input) {
return Instant.ofEpochMilli(input);
}
public Long transformTo(Instant input) {
return input.toEpochMilli();
}
}
public static class MyLocalDateTransformer implements Transformer<LocalDate, String> {
public LocalDate transformFrom(String input) {
return LocalDate.parse(input, DateTimeFormatter.ISO_LOCAL_DATE);
}
public String transformTo(LocalDate input) {
return input.format(DateTimeFormatter.ISO_LOCAL_DATE);
}
}
}

Related

How to apply Command Design pattern with Dependency Injection using Generic Class?

i want to apply command Design pattern with dependency Injection in the following situation: i have three types of reports in my system (SubscriptionReport, SalesReport, SpechialistReport) so i created one interface IReportService
public interface IReportService<T> where T: class
{
public Task<GenericResponse<List<T>>> GetReport(string searchKey, DateTime from, DateTime to);
}
and to apply OCP i have implemented the GetReport function tree times for (SubscriptionReport, SalesReport, SpechialistReport)
public class SpechialistReportService : IReportService<SpechialistReportDTO>
{
public Task<GenericResponse<List<SpechialistReportDTO>>> Report(string searchKey, DateTime from, DateTime to)
{
throw new NotImplementedException(); // to be implemented later
}
}
public class SubscriptionReportService : IReportService<SubscriptionReportDTO>
{
public Task<GenericResponse<List<SubscriptionReportDTO>>> Report(string searchKey, DateTime from, DateTime to)
{
throw new NotImplementedException(); // to be implemented later
}
}
public class SalesReportService : IReportService<SalesReportDTO>
{
public Task<GenericResponse<List<SalesReportDTO>>> Report(string searchKey, DateTime from, DateTime to)
{
throw new NotImplementedException(); // to be implemented later
}
}
after that i have added the dependency
services.AddScoped(typeof(IReportService<SpechialistReportDTO>), typeof(SpechialistReportService));
services.AddScoped(typeof(IReportService<SubscriptionReportDTO>), typeof(SubscriptionReportService));
services.AddScoped(typeof(IReportService<SalesReportDTO>), typeof(SalesReportService));
the problem is in calling the dependency in the controller constructor
private readonly IEnumerable<IReportService> _reportService; // Should be IReportService<dont know what class should i specify here>
public ReportController(IReportService<T> reportService)
{
this._reportService = reportService;
}
Any help would be appreciated thanks in advance,
Okay i solved this problem by removing the Generic and adding marker interface to the DTOs classes
public interface ReportRoot
{
}
public class SubscriptionReportDTO : ReportRoot
{
// Some data here
}
public class SalesReportDTO: ReportRoot
{
// Some data here
}
In ReportService Interface
public interface IReportService
{
public Task<GenericResponse<List<ReportRoot>>> Report();
}
public class SubscriptionReportService : IReportService {
public async Task<GenericResponse<List<ReportRoot>>> Report()
{
List<ReportRoot> subscriptionReportDTO = new List<ReportRoot>();
SubscriptionReportDTO test = new SubscriptionReportDTO();
test.SalesTax = "1000";
subscriptionReportDTO.Add(test);
return new GenericResponse<List<ReportRoot>>("1", subscriptionReportDTO.Count, "Success", subscriptionReportDTO);
}
}
public class SalesReportService : IReportService {
public async Task<GenericResponse<List<ReportRoot>>> Report()
{
List<ReportRoot> salesReportDTO = new List<ReportRoot>();
SalesReportDTO test = new SalesReportDTO ();
test.SalesTax = "1000";
salesReportDTO .Add(test);
return new GenericResponse<List<ReportRoot>>("1", salesReportDTO.Count, "Success", salesReportDTO );
}
}
In controller
private readonly IEnumerable<IReportService> _reportService;
public ReportController(IEnumerable<IReportService> reportService)
{
this._reportService = reportService;
}

Error While Fetching Data from Corda Custom Tables

How to fetch data from corda Custom tables?
my sample code is as follows :-
Api layer -- getIous() method
{
Field attributeValue=IOUSchemaV1.PersistentIOU.class.getDeclaredField("value");
CriteriaExpression currencyIndex = Builder.equal(attributeValue, "12");
QueryCriteria.VaultCustomQueryCriteria criteria = new
QueryCriteria.VaultCustomQueryCriteria(currencyIndex);
vaultStates = services.vaultQueryByCriteria(criteria,IOUState.class);
}
In ExamplePlugin I added below code for schema registration
public class ExamplePlugin extends CordaPluginRegistry implements
WebServerPluginRegistry
{
#NotNull
#Override
public Set<MappedSchema> getRequiredSchemas()
{
Set<MappedSchema> requiredSchemas = new HashSet<>();
requiredSchemas.add(new IOUSchemaV1());
return requiredSchemas;
}
}
My Schema classes are ---
public final class IOUSchema {
}
#CordaSerializable
public class IOUSchemaV1 extends MappedSchema
{
public IOUSchemaV1() {
super(IOUSchema.class, 1, ImmutableList.of(PersistentIOU.class));
}
#Entity
#Table(name = "iou_states")
public static class PersistentIOU extends PersistentState {
#Column(name = "sender_name") private final String senderName;
#Column(name = "recipient_name") private final String recipientName;
#Column(name = "value") private final int value;
public PersistentIOU(String senderName, String recipientName, int value) {
this.senderName = senderName;
this.recipientName = recipientName;
this.value = value;
}
public String getSenderName() {
return senderName;
}
public String getRecipientName() {
return recipientName;
}
public int getValue() {
return value;
}
}
}
my state has :-
public class IOUState implements LinearState, QueryableState
{
--- some code goes here and below methods as well.---
#Override
public PersistentState generateMappedObject(MappedSchema schema) {
if (schema instanceof IOUSchemaV1) {
return new IOUSchemaV1.PersistentIOU(
this.sender.getName().toString(),
this.recipient.getName().toString(),
this.iou.getValue());
} else {
throw new IllegalArgumentException("Unrecognised schema $schema");
}
}
#Override
public Iterable<MappedSchema> supportedSchemas() {
return ImmutableList.of(new IOUSchemaV1());
}
}
But all the time i am getting below exception.
Caused by: net.corda.core.node.services.VaultQueryException:
Please register the entity 'com.example.schema.IOUSchemaV1' class in your CorDapp's CordaPluginRegistry configuration (requiredSchemas attribute)
and ensure you have declared (in supportedSchemas()) and mapped (in generateMappedObject())
the schema in the associated contract state's QueryableState interface implementation.
Can anyone please help to resolve this.
Try deleting implements WebServerPluginRegistry from your plugin declaration.

spring MVC use #JsonView on spring-data Page

I'm using Spring-MVC, Spring-data-jpa, jackson on a Jhipster project.
I managed to use the #JsonView annotation on an object and it works well when the method in the rest controller return a type ResponseEntity<List<MyObject>> but I can't make it work when the method return type is ResponseEntity<Page<MyObject>>.
I've tried to set MapperFeature.DEFAULT_VIEW_INCLUSION to true (which default is false). When I do it, all attributes are serialized. But filtering through #JsonView does not work anymore.
I can't modify the Page object because it's a Spring-data object.
I'm looking for a way to tell jackson to include all attributes of the Page object.
Here is my code:
My entity:
#Entity
#Table(name = "T_REGION")
public class Region implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "code", nullable = false)
private Integer code;
#Column(name = "name", length = 60, nullable = false)
#JsonView(View.Summary.class)
private String name;
// Getters and setters
}
My rest controller:
#RestController
#RequestMapping("/api")
public class RegionResource {
#RequestMapping(value = "/regionsearch1",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
#JsonView(View.Summary.class)
public ResponseEntity<Page<Region>> findAll1(
#RequestParam(value = "page" , required = false) Integer offset,
#RequestParam(value = "per_page", required = false) Integer limit,
Sort sort)
throws URISyntaxException {
Pageable pageRequest = PaginationUtil.generatePageRequest(offset, limit, sort);
Page<Region> page = regionRepository.findAll(pageRequest);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/regionsearch1", pageRequest);
return new ResponseEntity<>(page, headers, HttpStatus.OK);
}
#RequestMapping(value = "/regionsearch2",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
#JsonView(View.Summary.class)
public ResponseEntity<List<Region>> findAll2(
#RequestParam(value = "page" , required = false) Integer offset,
#RequestParam(value = "per_page", required = false) Integer limit,
Sort sort)
throws URISyntaxException {
Pageable pageRequest = PaginationUtil.generatePageRequest(offset, limit, sort);
Page<Region> page = regionRepository.findAll(pageRequest);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/regionsearch2", pageRequest);
return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
}
findAll1 returns:
[
{
"name": "Ile-de-France"
},
{
"name": "Champagne-Ardenne"
},
....
]
findAll2 returns:
{}
The object Page has no #JsonView on its attributes therefore no attributes are serialized.
I can't find a way to tell Jackson to include all Page attributes even when #JsonView is used.
Any ideas ?
Another way to return all page elements is to create your own implementation for the Page interface (including the JsonView you want):
JsonPage
public class JsonPage<T> extends org.springframework.data.domain.PageImpl<T> {
public JsonPage(final List<T> content, final Pageable pageable, final long total) {
super(content, pageable, total);
}
public JsonPage(final List<T> content) {
super(content);
}
public JsonPage(final Page<T> page, final Pageable pageable) {
super(page.getContent(), pageable, page.getTotalElements());
}
#JsonView(JsonViews.UiView.class)
public int getTotalPages() {
return super.getTotalPages();
}
#JsonView(JsonViews.UiView.class)
public long getTotalElements() {
return super.getTotalElements();
}
#JsonView(JsonViews.UiView.class)
public boolean hasNext() {
return super.hasNext();
}
#JsonView(JsonViews.UiView.class)
public boolean isLast() {
return super.isLast();
}
#JsonView(JsonViews.UiView.class)
public boolean hasContent() {
return super.hasContent();
}
#JsonView(JsonViews.UiView.class)
public List<T> getContent() {
return super.getContent();
}
}
Next return this class to the controller layer:
Service
#Override
public Page<User> findAll(final int page) {
PageRequest pr = new PageRequest(page, pageSize, new Sort(Sort.Direction.DESC, "dateCreated"));
return new JsonPage<User>(userRepository.findAll(pr), pr);
}
Controller
#JsonView(JsonViews.UiView.class)
#RequestMapping(method = RequestMethod.GET, value = "{page}")
public Page<User> getUsers(#PathVariable final int page) {
return userService.findAll(page);
}
I have done like this , it's working well
package com.natixis.spring.ws.configuration;
import java.io.IOException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.Page;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
#Configuration
public class JacksonAdapter extends WebMvcConfigurerAdapter {
#Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
return new Jackson2ObjectMapperBuilder()
.failOnUnknownProperties(false)
.serializationInclusion(Include.NON_EMPTY)
.serializerByType(Page.class, new JsonPageSerializer());
}
public class JsonPageSerializer extends JsonSerializer<Page<?>>{
#Override
public void serialize(Page<?> page, JsonGenerator jsonGen, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
ObjectMapper om = new ObjectMapper()
.disable(MapperFeature.DEFAULT_VIEW_INCLUSION)
.setSerializationInclusion(Include.NON_EMPTY);
jsonGen.writeStartObject();
jsonGen.writeFieldName("size");
jsonGen.writeNumber(page.getSize());
jsonGen.writeFieldName("number");
jsonGen.writeNumber(page.getNumber());
jsonGen.writeFieldName("totalElements");
jsonGen.writeNumber(page.getTotalElements());
jsonGen.writeFieldName("last");
jsonGen.writeBoolean(page.isLast());
jsonGen.writeFieldName("totalPages");
jsonGen.writeNumber(page.getTotalPages());
jsonGen.writeObjectField("sort", page.getSort());
jsonGen.writeFieldName("first");
jsonGen.writeBoolean(page.isFirst());
jsonGen.writeFieldName("numberOfElements");
jsonGen.writeNumber(page.getNumberOfElements());
jsonGen.writeFieldName("content");
jsonGen.writeRawValue(om.writerWithView(serializerProvider.getActiveView())
.writeValueAsString(page.getContent()));
jsonGen.writeEndObject();
}
}
}
Regards,
Régis LIMARE
I know this is an old question, but you can use something like this for a Page of objects
#Configuration
public class JacksonAdapter implements WebMvcConfigurer {
#Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
return new Jackson2ObjectMapperBuilder().failOnUnknownProperties(false).serializerByType(Page.class,
new JsonPageSerializer());
}
public class JsonPageSerializer extends JsonSerializer<Page> {
#Override
public void serialize(Page page, JsonGenerator jsonGen, SerializerProvider serializerProvider)
throws IOException {
ObjectMapper om = new ObjectMapper().disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
jsonGen.writeStartObject();
jsonGen.writeFieldName("size");
jsonGen.writeNumber(page.getSize());
jsonGen.writeFieldName("number");
jsonGen.writeNumber(page.getNumber());
jsonGen.writeFieldName("totalElements");
jsonGen.writeNumber(page.getTotalElements());
jsonGen.writeFieldName("last");
jsonGen.writeBoolean(page.isLast());
jsonGen.writeFieldName("totalPages");
jsonGen.writeNumber(page.getTotalPages());
jsonGen.writeObjectField("sort", page.getSort());
jsonGen.writeFieldName("first");
jsonGen.writeBoolean(page.isFirst());
jsonGen.writeFieldName("numberOfElements");
jsonGen.writeNumber(page.getNumberOfElements());
jsonGen.writeFieldName("content");
jsonGen.writeRawValue(
om.writerWithView(serializerProvider.getActiveView()).writeValueAsString(page.getContent()));
jsonGen.writeEndObject();
}
}
}
I've encountered the same problem and I solved it by setting MapperFeature.DEFAULT_VIEW_INCLUSION to true, but you should annotate all fields in classes where you want to apply your view with JsonView or JsonIgnore annotation so they wouldn't be included by default in json.

How do you specify the date format used when JAXB marshals xsd:dateTime?

When JAXB marshals a date object (XMLGregorianCalendar) into an xsd:dateTime element. How can you specify the format of the resulting XML?
For example:
The default data format uses milliseconds <StartDate>2012-08-21T13:21:58.000Z</StartDate>
I need to omit the milliseconds. <StartDate>2012-08-21T13:21:58Z</StartDate>
How can I specify the output form/date format that I want it to use?
I'm using javax.xml.datatype.DatatypeFactory to create the XMLGregorianCalendar object.
XMLGregorianCalendar xmlCal = datatypeFactory.newXMLGregorianCalendar(cal);
You can use an XmlAdapter to customize how a date type is written to XML.
package com.example;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class DateAdapter extends XmlAdapter<String, Date> {
private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
#Override
public String marshal(Date v) throws Exception {
synchronized (dateFormat) {
return dateFormat.format(v);
}
}
#Override
public Date unmarshal(String v) throws Exception {
synchronized (dateFormat) {
return dateFormat.parse(v);
}
}
}
Then you use the #XmlJavaTypeAdapter annotation to specify that the XmlAdapter should be used for a specific field/property.
#XmlElement(name = "timestamp", required = true)
#XmlJavaTypeAdapter(DateAdapter.class)
protected Date timestamp;
Using a xjb binding file:
<xjc:javaType name="java.util.Date" xmlType="xs:dateTime"
adapter="com.example.DateAdapter"/>
will produce the above mentioned annotation.
(By eventually adding the xjc namespace: xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc")
I use a SimpleDateFormat to create the XMLGregorianCalendar, such as in this example:
public static XMLGregorianCalendar getXmlDate(Date date) throws DatatypeConfigurationException {
return DatatypeFactory.newInstance().newXMLGregorianCalendar(new SimpleDateFormat("yyyy-MM-dd").format(date));
}
public static XMLGregorianCalendar getXmlDateTime(Date date) throws DatatypeConfigurationException {
return DatatypeFactory.newInstance().newXMLGregorianCalendar(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(date));
}
The first method creates an instance of XMLGregorianCalendar that is formatted by the XML marshaller as a valid xsd:date, the second method results in a valid xsd:dateTime.
Very easy way to me. Formatting XMLGregorianCalendar for marshalling in java.
I just create my data in the good format. The toString will be called producing the good result.
public static final XMLGregorianCalendar getDate(Date d) {
try {
return DatatypeFactory.newInstance().newXMLGregorianCalendar(new SimpleDateFormat("yyyy-MM-dd").format(d));
} catch (DatatypeConfigurationException e) {
return null;
}
}
https://www.baeldung.com/jaxb
public class DateAdapter extends XmlAdapter<String, Date> {
private static final ThreadLocal<DateFormat> dateFormat
= new ThreadLocal<DateFormat>() {
#Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
}
#Override
public Date unmarshal(String v) throws Exception {
return dateFormat.get().parse(v);
}
#Override
public String marshal(Date v) throws Exception {
return dateFormat.get().format(v);
}
}
Usage:
import com.company.LocalDateAdapter.yyyyMMdd;
//...
#XmlElement(name = "PROC-DATE")
#XmlJavaTypeAdapter(yyyyMMdd.class)
private LocalDate processingDate;
LocalDateAdapter
import javax.xml.bind.annotation.adapters.XmlAdapter;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class LocalDateAdapter extends XmlAdapter<String, LocalDate> {
public static final class yyyyMMdd extends LocalDateAdapter {
public yyyyMMdd() {
super("yyyyMMdd");
}
}
public static final class yyyy_MM_dd extends LocalDateAdapter {
public yyyy_MM_dd() {
super("yyyy-MM-dd");
}
}
private final DateTimeFormatter formatter;
public LocalDateAdapter(String pattern) {
formatter = DateTimeFormat.forPattern(pattern);
}
#Override
public String marshal(LocalDate date) throws Exception {
return formatter.print(date);
}
#Override
public LocalDate unmarshal(String date) throws Exception {
return formatter.parseLocalDate(date);
}
}

Spring MVC and java script(addRows function) binding

I have question/issue with javascript function binding in Spring MVC . As per our requirement I need to insert a NEW ROW in a table when the user clicks on “ADD” button .
Step1 : So when the user clicks on “Add MORE” button I inserting a new row within a table , I am handling this using javascript
Step 2: When user clicks on the submit button , I Need to send the values entered by user to my Controller (Spring MVC Controller) .
So how can binding the values to controller dynamically ?
Please help me to resolve this issue ASAP .
I do the following when I need to bind a dynamic list of objects coming from the front end :
Post the data as a json array, i.e. in the following format
{ data : [{a:1, b:2}, {a:3, b:4}] }
In the Controller
#RequestMapping(value="save", method=RequestMethod.POST)
public void save(JSONObject object)
{
List<YourType> list = new ArrayList<YourType>();
JSONArray array = object.getJSONArray("data")
for(int i=0; i<array.length(); i++)
{
//getObjectFromJson is your method for converting json to an object of your type.
list.add(JsonUtils.fromJson(array.getJSONObject(i).toString(), YourType.class);
}
}
Spring can bind maps and lists of objects if you give create an appropriate class to hold your form data then use the #ModelAttribute annotation on your controller method.
For example, if your JavaScript creates table rows like this:
<tr>
<td><input name="bells[0]" /></td>
<td><input name="whistles[0]" /></td>
</tr>
<tr>
<td><input name="bells[1]" /></td>
<td><input name="whistles[1]" /></td>
</tr>
Then you can create a model class that contains a list for each repeating field in your HTML form, like this:
public class AsapForm {
private List<String> bells;
private List<String> whistles;
// add getters and setters here
}
And then you can create a controller method that uses that class as a parameter with the #ModelAttribute annotation:
public void postAsapForm(#ModelAttribute("contactForm") AsapForm asapForm, BindingResult result) {
...
}
You can then access the values for each row using asapForm.getBells() and asapForm.getWhistles() etc.
I have achieved this using LazyList.
You need to do this in following way.
Operation.java
package com.xxx.xxx.model;
// Generated Feb 9, 2012 11:30:06 AM by Hibernate Tools 3.2.1.GA
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.apache.commons.collections.FactoryUtils;
import org.apache.commons.collections.list.LazyList;
#Entity
#Table(name="Operations"
,schema="dbo"
)
public class Operations implements java.io.Serializable {
private int operationId;
#Embedded
private Services services;
private String operationName;
private String isHqlsql;
private String isMultipleTables;
private String listOfTablesAffected;
private String hqlQuery;
private String typeOfOperation;
private String operationDetail;
private String inputVariables;
private String outputparamdatatype;
private String isCountQuery;
private String isDynamicWhereQry;
private String isPaginationRequired;
private String biInputParameters;
private List<OperationParameters> operationParameterses = LazyList
.decorate(new ArrayList<OperationParameters>(),
FactoryUtils.instantiateFactory(OperationParameters.class));
public Operations() {
}
public Operations(int operationId, Services services, String operationName) {
this.operationId = operationId;
this.services = services;
this.operationName = operationName;
}
public Operations(int operationId, Services services, String operationName, String isHqlsql, String isMultipleTables, String listOfTablesAffected, String hqlQuery, String typeOfOperation, String operationDetail, String inputVariables, String outputparamdatatype, String isCountQuery, List operationParameterses) {
this.operationId = operationId;
this.services = services;
this.operationName = operationName;
this.isHqlsql = isHqlsql;
this.isMultipleTables = isMultipleTables;
this.listOfTablesAffected = listOfTablesAffected;
this.hqlQuery = hqlQuery;
this.typeOfOperation = typeOfOperation;
this.operationDetail = operationDetail;
this.inputVariables = inputVariables;
this.outputparamdatatype = outputparamdatatype;
this.isCountQuery = isCountQuery;
this.operationParameterses = operationParameterses;
}
#Id
#GeneratedValue
#Column(name="operationId", unique=true, nullable=false)
public int getOperationId() {
return this.operationId;
}
public void setOperationId(int operationId) {
this.operationId = operationId;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="serviceId", nullable=false)
public Services getServices() {
return this.services;
}
public void setServices(Services services) {
this.services = services;
}
#Column(name="operationName", nullable=false, length=250)
public String getOperationName() {
return this.operationName;
}
public void setOperationName(String operationName) {
this.operationName = operationName;
}
#Column(name="isHQLSQL", length=50)
public String getIsHqlsql() {
return this.isHqlsql;
}
public void setIsHqlsql(String isHqlsql) {
this.isHqlsql = isHqlsql;
}
#Column(name="isMultipleTables", length=50)
public String getIsMultipleTables() {
return this.isMultipleTables;
}
public void setIsMultipleTables(String isMultipleTables) {
this.isMultipleTables = isMultipleTables;
}
#Column(name="listOfTablesAffected", length=500)
public String getListOfTablesAffected() {
return this.listOfTablesAffected;
}
public void setListOfTablesAffected(String listOfTablesAffected) {
this.listOfTablesAffected = listOfTablesAffected;
}
#Column(name="hqlQuery")
public String getHqlQuery() {
return this.hqlQuery;
}
public void setHqlQuery(String hqlQuery) {
this.hqlQuery = hqlQuery;
}
#Column(name="typeOfOperation", length=50)
public String getTypeOfOperation() {
return this.typeOfOperation;
}
public void setTypeOfOperation(String typeOfOperation) {
this.typeOfOperation = typeOfOperation;
}
#Column(name="operationDetail")
public String getOperationDetail() {
return this.operationDetail;
}
public void setOperationDetail(String operationDetail) {
this.operationDetail = operationDetail;
}
#Column(name="inputVariables", length=5000)
public String getInputVariables() {
return this.inputVariables;
}
public void setInputVariables(String inputVariables) {
this.inputVariables = inputVariables;
}
#Column(name="outputparamdatatype", length=50)
public String getOutputparamdatatype() {
return this.outputparamdatatype;
}
public void setOutputparamdatatype(String outputparamdatatype) {
this.outputparamdatatype = outputparamdatatype;
}
#Column(name="isCountQuery", length=10)
public String getIsCountQuery() {
return this.isCountQuery;
}
public void setIsCountQuery(String isCountQuery) {
this.isCountQuery = isCountQuery;
}
public String getIsDynamicWhereQry() {
return isDynamicWhereQry;
}
public void setIsDynamicWhereQry(String isDynamicWhereQry) {
this.isDynamicWhereQry = isDynamicWhereQry;
}
public String getIsPaginationRequired() {
return isPaginationRequired;
}
public void setIsPaginationRequired(String isPaginationRequired) {
this.isPaginationRequired = isPaginationRequired;
}
public String getBiInputParameters() {
return biInputParameters;
}
public void setBiInputParameters(String biInputParameters) {
this.biInputParameters = biInputParameters;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="operations")
public List<OperationParameters> getOperationParameterses() {
return this.operationParameterses;
}
public void setOperationParameterses(List<OperationParameters> operationParameterses) {
this.operationParameterses = operationParameterses;
}
}
OperationParameters.java
package com.xxx.xxx.model;
// Generated Feb 9, 2012 11:30:06 AM by Hibernate Tools 3.2.1.GA
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name="OperationParameters"
,schema="dbo"
)
public class OperationParameters implements java.io.Serializable {
private int parameterId;
private Operations operations;
private String inputOutputParamName;
private String inputOutputParamType;
private String inputOutputParamDataType;
public OperationParameters() {
}
public OperationParameters(int parameterId, Operations operations, String inputOutputParamName, String inputOutputParamType, String inputOutputParamDataType) {
this.parameterId = parameterId;
this.operations = operations;
this.inputOutputParamName = inputOutputParamName;
this.inputOutputParamType = inputOutputParamType;
this.inputOutputParamDataType = inputOutputParamDataType;
}
#Id
#GeneratedValue
#Column(name="parameterId", unique=true, nullable=false)
public int getParameterId() {
return this.parameterId;
}
public void setParameterId(int parameterId) {
this.parameterId = parameterId;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="operationId", nullable=false)
public Operations getOperations() {
return this.operations;
}
public void setOperations(Operations operations) {
this.operations = operations;
}
#Column(name="inputOutputParamName", nullable=false, length=250)
public String getInputOutputParamName() {
return this.inputOutputParamName;
}
public void setInputOutputParamName(String inputOutputParamName) {
this.inputOutputParamName = inputOutputParamName;
}
#Column(name="inputOutputParamType", nullable=false, length=250)
public String getInputOutputParamType() {
return this.inputOutputParamType;
}
public void setInputOutputParamType(String inputOutputParamType) {
this.inputOutputParamType = inputOutputParamType;
}
#Column(name="inputOutputParamDataType", nullable=false, length=250)
public String getInputOutputParamDataType() {
return this.inputOutputParamDataType;
}
public void setInputOutputParamDataType(String inputOutputParamDataType) {
this.inputOutputParamDataType = inputOutputParamDataType;
}
}
Conroller method to serve the post request to add new Operation.
/**
* Method that will serve the post request to add the operation and operation parameters submitted by the user.
* #param operations
* #param map
* #return {#link String} The view name that will redirect to the get request to display the previous page with newly entered operation in the list.
*/
#RequestMapping(value="/add", method=RequestMethod.POST)
public String addOperations(#ModelAttribute Operations operations, ModelMap map) {
operations.getOperationParameterses().removeAll(Collections.singleton(null));
for(int i=0; i<operations.getOperationParameterses().size(); i++) {
System.out.println("parameterName :: " + ((OperationParameters)operations.getOperationParameterses().get(i)).getInputOutputParamName());
if(((OperationParameters)operations.getOperationParameterses().get(i)).getInputOutputParamName() == null || "".equalsIgnoreCase((((OperationParameters)operations.getOperationParameterses().get(i))).getInputOutputParamName())) {
operations.getOperationParameterses().remove(i);
System.out.println("empty parameter removed....");
}
}
return "redirect:/operations/" + operations.getServices().getServiceId();
}
Hope this helps you.

Resources