Make input parameter mandatory JAX-WS - java

Input paramter to my webservice method is an Object of Class AddSingleDocRequest. This class contains all the input fields as class instance variable with their getter and setter. I want to make some of the input fields mandatory. What is the best way to achieve this ?
Following is the code snippet:
**//webservice method
public String uploadDoc(AddSingleDocRequest request)
{
}
**//Request Class**
public class AddSingleDocRequest
{
private String sFilepath;
private String sDataClass;
public void setDataClassName(String dataClassName)
{
this.sDataClass= dataClassName;
}
public String getDataClassName() {
return sDataClass;
}
public void setFilePath(String filePath)
{
this.sFilepath=filePath;
}
public String getFilePath()
{
return sFilepath;
}
}
I want to make sFilePath parameter as mandatory.

Add the next JAX-B annotations:
#XmlType(name = "AddSingleDocRequestType", propOrder = {
"sFilepath", "sDataClass"
})
public class AddSingleDocRequest {
#XmlElement(name = "sFilepath", required = true)
private String sFilepath;
#XmlElement(name = "sDataClass", required = false)
private String sDataClass;
public void setDataClassName(String dataClassName) {
this.sDataClass = dataClassName;
}
public String getDataClassName() {
return sDataClass;
}
public void setFilePath(String filePath) {
this.sFilepath = filePath;
}
public String getFilePath() {
return sFilepath;
}
}
See more in Using JAXB to customize mapping for JAX-WS web services.

Related

How to store a List of a class object into MySql using Spring boot

I want to store a List of class : RestApiResponse into MySql. But getting below error:
org.hibernate.HibernateException: Could not determine a type for class: com.try.sreapi.beans.RestApiResponse
Below are my classes:
Entity class : SREAPITestingHistory.java
#NamedQueries(#NamedQuery(name="getSREAPITestHistory.findAll", query="SELECT a FROM SREAPITestingHistory a"))
#SqlResultSetMapping(name="sreapitestinghistoryres",
entities=#EntityResult(entityClass=SREAPITestingHistory.class))
#Entity
#Table(name="sreapi_testing_history_details")
#Transactional
public class SREAPITestingHistory implements Serializable{
private static final long serialVersionUID = -7221709766109001257L;
#Id
#Column(name="request_time")
private String request_time;
#Column(name="req_id")
private String req_id;
#Column(name="app_name")
private String app_name;
#Column(name="request_name")
private String request_name;
#Lob
#Column(name="response_body")
private List<RestApiResponse> response;
public String getRequest_time() {
return request_time;
}
public void setRequest_time(String request_time) {
this.request_time = request_time;
}
public String getReq_id() {
return req_id;
}
public void setReq_id(String req_id) {
this.req_id = req_id;
}
public String getApp_name() {
return app_name;
}
public void setApp_name(String app_name) {
this.app_name = app_name;
}
public String getRequest_name() {
return request_name;
}
public void setRequest_name(String request_name) {
this.request_name = request_name;
}
public List<RestApiResponse> getResponse() {
return response;
}
public void setResponse(List<RestApiResponse> response) {
this.response = response;
}
}
Repository Class: SREAPITestingRepository.java
#Repository
public interface SREAPITestingRepository extends CrudRepository< SREAPITestingHistory, String> {
#Modifying
#Transactional
#Query(value="INSERT into sreapi_testing_history_details (request_time,req_id,app_name,request_name,response_body)"+ "VALUES (:request_time,:req_id,:app_name,:request_name,:response_body)", nativeQuery = true)
public void setApiTestHistoryDetails(#Param("request_time") String request_time,#Param("req_id") String req_id,#Param("app_name") String app_name,#Param("request_name") String request_name,#Param("response_body") List<RestApiResponse> response_body);
}
When I am trying to add values for response_body which is actually a List of RestApiResponse class and I am getting Could not determine a type for class: com.try.sreapi.beans.RestApiResponse exception
From Official doc
A Lob may be either a binary or character type.
The Lob type is inferred from the type of the persistent field or
property, and except for string and character-based types defaults to
Blob.
Example 1:
#Lob #Basic(fetch=LAZY) #Column(name="REPORT")
String report;
Example 2:
#Lob #Basic(fetch=LAZY) #Column(name="EMP_PIC",
columnDefinition="BLOB NOT NULL") protected byte[] pic;
So you can convert your list of data into json string or bytes to store.

Spring JPA + Mongo - Unable to delete by query

I have simple Java Class that is getting stored to MongoDB through Spring JPA -
public class PlanRecoveryStrategy {
String planId;
String processId;
String strategyId;
public String getPlanId() {
return planId;
}
public void setPlanId(String planId) {
this.planId = planId;
}
public String getProcessId() {
return processId;
}
public void setProcessId(String processId) {
this.processId = processId;
}
public String getStrategyId() {
return strategyId;
}
public void setStrategyId(String strategyId) {
this.strategyId = strategyId;
}
}
This is my DataAccessObject Class -
#Repository("PlanRecoveryStrategy")
public interface PlanRecoveryStrategyDao extends MongoRepository<PlanRecoveryStrategy, String> {
#Query(value = "{ 'planId' : ?0, 'processId' : ?1, 'strategyId' : ?2}", delete = true)
List<PlanRecoveryStrategy> deletePlanRecoveryStrategy(String planId, String processId, String strategyId);
}
However, on trying to delete, I get the error saying - No id property found for object of type class com.apeiron.dataModel.plan.PlanRecoveryStrategy
What is the reason for the error?
Just create a field with #Id annotation and create getters and setters for it

Searching for a string from a comma separated field in solr

I have installed solr-6.5.1 in my Spring MVC Java Web Application refering the following documentations:
http://www.baeldung.com/apache-solrj
https://github.com/eugenp/tutorials/tree/master/apache-solrj/src/main/java/com/baeldung/solrjava
I have a POJO declared as shown below:
public class WebContentSearchHB
{
private int webContentDefinitionId;
private String pageTitle;
private String pageKwd;
private String pageDesc;
private int siteId;
private int applicationId;
private Date pageCreatedTime;
private Date pageUpdatedDate ;
private String webContentData;
private String webContentType;
private String category;
public int getWebContentDefinitionId()
{
return webContentDefinitionId;
}
#Field("webContentDefinitionId")
public void setWebContentDefinitionId(int webContentDefinitionId)
{
this.webContentDefinitionId = webContentDefinitionId;
}
public String getPageTitle()
{
return pageTitle;
}
#Field("pageTitle")
public void setPageTitle(String pageTitle)
{
this.pageTitle = pageTitle;
}
public String getPageKwd()
{
return pageKwd;
}
#Field("pageKwd")
public void setPageKwd(String pageKwd)
{
this.pageKwd = pageKwd;
}
public String getPageDesc()
{
return pageDesc;
}
#Field("pageDesc")
public void setPageDesc(String pageDesc)
{
this.pageDesc = pageDesc;
}
public int getSiteId()
{
return siteId;
}
#Field("siteId")
public void setSiteId(int siteId)
{
this.siteId = siteId;
}
public int getApplicationId()
{
return applicationId;
}
#Field("applicationId")
public void setApplicationId(int applicationId)
{
this.applicationId = applicationId;
}
public Date getPageCreatedTime()
{
return pageCreatedTime;
}
#Field("pageCreatedTime")
public void setPageCreatedTime(Date pageCreatedTime)
{
this.pageCreatedTime = pageCreatedTime;
}
public Date getPageUpdatedDate()
{
return pageUpdatedDate;
}
#Field("pageUpdatedDate")
public void setPageUpdatedDate(Date pageUpdatedDate)
{
this.pageUpdatedDate = pageUpdatedDate;
}
public String getWebContentData()
{
return webContentData;
}
#Field("webContentData")
public void setWebContentData(String webContentData)
{
this.webContentData = webContentData;
}
public String getWebContentType()
{
return webContentType;
}
#Field("webContentType")
public void setWebContentType(String webContentType)
{
this.webContentType = webContentType;
}
public String getCategory() {
return category;
}
#Field("category")
public void setCategory(String category) {
this.category = category;
}
}
I haven't created any schema.xml file or edited the existing schema.xml file. I am manually setting the values for each field in the POJO and adding it to the Solr index using my application as follows:
solrClient = new HttpSolrClient.Builder(solrUrl).build();
solrClient.setParser(new XMLResponseParser());
WebContentSearchHB searcHB = new WebContentSearchHB();
//codes to set data
solrClient.addBean(searcHB);
solrClient.commit();
I have also added the following maven dependency to my pom.xml file
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-solrj</artifactId>
<version>6.5.1</version>
</dependency>
One of my fields in the WebContentSearchHB class, named category will contain a comma separated string of ids of various categories for that content.
A sample data would look like the one shown below:
[
{"pageTitle":["Test page"],
"pageKwd":["Test page"],
"pageDesc":["Test page"],
"applicationId":[1],
"siteId":[5],
"category":["2,6,7,8"],
"pageCreatedTime":["2017-02-17T05:58:19.648Z"],
"pageUpdatedDate":["2017-06-12T03:46:45.489Z"],
"webContentDefinitionId":[4947],
"webContentType":["simplewebcontent.html"],
"id":"717821d9-989e-4c4f-b66a-8b5185ed88ca",
"webContentData":"test"],
"_version_":1570012287149801472}
]
here there are multiple categories added as comma seperated values. Now when I try search for the data in the catagory field as follows:
http://localhost::8983/solr/swcm_qa/select?indent=on&q=category:7*&wt=json
no data is returned. But if I search as follows,
http://localhost::8983/solr/swcm_qa/select?indent=on&q=category:2*&wt=json
All rows where 2appears as the first value in the comma separated string is returned. How can I search for a string from among the comma separated values in the category field? Also, how can I specify if the field is storing multiple values as comma separated string in the #Field annotation?
In category field "2,6,7,8" is indexed as single string
category:["2,6,7,8"]
It should be like
category:["2","6","7","8"]
Either you should apply filter to that category field before indexing so that it stores individual numeric value into the field with ,as delimiter
OR
modify query like q=category:*7*

RestTemplate mapping to object

I am trying to use RestTemplate to call a webservice, currently I am using the Object type rather than a concrete user defined one which is what I want to do.
Currently the response from the web service is:
{Locales=[{Code=ar-AE, Name=العربية (الإمارات العربية المتحدة)}, {Code=az-AZ, Name=Azərbaycan­ılı (Azərbaycan)}, {Code=bg-BG, Name=български (България)}]}
I am currently doing this:
Object locales = restTemplate.getForObject(localeUrl, Object.class, apiKey);
which is I want to be able to map it to a class that I have defined, but not sure how my class should be laid out, my class currently looks like this:
#Data
#JsonIgnoreProperties(ignoreUnknown = true)
#XmlRootElement(name = "Locales")
#XmlAccessorType(XmlAccessType.FIELD)
public class Locales {
private List<Locale> Locales = new ArrayList<>();
private Locales(){};
public List<Locale> getLocales() {
return Locales;
}
public void setLocales(ArrayList<Locale> newLocales) {
this.Locales = newLocales;
}
}
#Data
#JsonIgnoreProperties(ignoreUnknown = true)
public class Locale {
private String Code;
private String Name;
private Locale(){}
public String getCode() {
return this.Code;
}
public void setCode(String Code) {
this.Code = Code;
}
public String getName() {
return this.Name;
}
public void setName(String Name) {
this.Name = Name;
}
}
Use below code for calling API -
Locales locales = restTemplate.getForObject(localeUrl, Locales.class, apiKey);
Create one class Locales -
#XmlRootElement(name = "Locales")
#XmlAccessorType(XmlAccessType.FIELD)
public class Locales{
private List<Locale> locales = new ArrayList<>();
// getter and setter
}

Get data from a repository using Spring

Ok so I am new to spring and don't really know how this works. I have been trying a few things and think its close to doing it but not getting any data from the server and giving me this error
Unsatisfied dependency expressed through constructor argument with index 4 of type [jp.co.fusionsystems.dimare.crm.service.impl.MyDataDefaultService]: : Error creating bean with name 'MyDataDefaultService' defined in file
My end point
//mobile data endpoint
#RequestMapping(
value = API_PREFIX + ENDPOINT_MyData + "/getMyData",
method = RequestMethod.GET)
public MyData getMyData() {
return MyDataDefaultService.getData();
}
My Object
public class MyData {
public MyData(final Builder builder) {
videoLink = builder.videoLink;
}
private String videoLink;
public String getVideoLink()
{
return videoLink;
}
public static class Builder
{
private String videoLink = "";
public Builder setVideo(String videoLink)
{
this.videoLink = videoLink;
return this;
}
public MyData build()
{
return new MyData(this);
}
}
#Override
public boolean equals(final Object other) {
return ObjectUtils.equals(this, other);
}
#Override
public int hashCode() {
return ObjectUtils.hashCode(this);
}
#Override
public String toString() {
return ObjectUtils.toString(this);
}
}
The Repository
public classMyServerMyDataRepository implements MyDataRepository{
private finalMyServerMyDataJpaRepository jpaRepository;
private final MyDataConverter MyDataConverter = new MyDataConverter();
#Autowired
publicMyServerMyDataRepository(finalMyServerMyDataJpaRepository jpaRepository) {
this.jpaRepository = Validate.notNull(jpaRepository);
}
#Override
public MyData getData() {
MyDataEntity entity = jpaRepository.findOne((long) 0);
MyData.Builder builder = new MyData.Builder()
.setVideo(entity.getVideoLink());
return builder.build();
}
The DefaultService that gets called by the endpoint
public class MyDataDefaultService {
private static final Logger logger = LoggerFactory.getLogger(NotificationDefaultService.class);
private finalMyServerMyDataRepository repository;
#Autowired
public MyDataDefaultService(MyServerMyDataRepository repository) {
this.repository = Validate.notNull(repository);
}
//Get the data from the server
public MobileData getData()
{
logger.info("Get Mobile Data from the server");
//Get the data from the repository
MobileData mobileData = repository.getData();
return mobileData;
}
}
The Converter
public class MyDataConverter extends AbstractConverter<MyDataEntity, MyData>
{
#Override
public MyData convert(MyDataEntity entity) {
MyData.Builder builder = new MyData.Builder()
.setVideo(entity.getVideoLink());
return builder.build();
}
}
My Entity
#Entity
#Table(name = “myServer”)
public class MyDataEntity extends AbstractEntity{
#Column(name = "video_link", nullable = true)
private String videoLink;
public String getVideoLink() {
return videoLink;
}
public void setVideoLink(final String videoLink) {
this.videoLink = videoLink;
}
}
Thank you for any help with this
Hibernate entity should have default constructor defined and implement Serializable interface as well, assume AbstractEntity matches the requirement. Hibernate won't accept an entity without a primary key so you have to define the one too:
#Entity
#Table(name = “myServer”)
public class MyDataEntity implements Serializable {
#Id
#GeneratedValue
private Long id;
#Column(name = "video_link", nullable = true)
private String videoLink;
public MyDataEntity() {
}
...setters&getters
}
MyData object represents the JSON server response, you can use Jackson annotations to control the result JSON properties:
public class MyDataResponse {
#JsonProperty("video_link")
private String videoLink;
public MyDataResponse() {
}
public MyDataResponse(String videoLink) {
this.videoLink = videoLink;
}
...setters&getters
}
Spring has an awesome project so called Spring Data that provides the JPA repositories, so there's no even the #Repository annotation ever needed:
public class MyDataRepository extends CrudRepository<MyDataEntity, Long> {
}
The Builder class represents the Service layer:
#Service
public class MyDataService {
#Autowired
private MyDataRepository myDataRepository;
public MyDataResponse getMyData(Long id) {
MyDataEntity entity = myDataRepository.findOne(id);
...rest logic, copy necessary data to MyDataResponse
}
}
Then a controller is:
#RestController // #ResponseBody not needed when using like this
public MyDataController {
#Autowired
private MyDataService myDataService;
#RequestMapping("/getMyData") // no need to specify method for GET
public MyDataResponse getMyData(#RequestParam("ID") Long myDataId) {
... validation logic
return myDataService.getMyData(myDataId); // return response
}
}
Now it should work, don't forget to add required dependencies to your classpath.

Categories

Resources