I am getting null while reading the values from .properties file when i am executing the test case. here while debugging the test case i am able to see the values which are loaded from properties file when the curser is there in the test class but when the curser enters into the actual class in that class i am getting the same values as null. And my code is as follows
Thanks in advance
#RestController
#PropertySource("classpath:/com/example/prop.properties")
public class ReadProp {
#Value("${name}")
private String name;
#Value("${rollNo}")
private String rollNo;
#RequestMapping(value="/")
public void getDetails(){
System.out.println(name);
System.out.println(rollNo);
}
}
and the test case is as follows
#RunWith(SpringRunner.class)
#SpringBootTest
#PropertySource("classpath:/com/example/prop.properties")
public class ReadPropTest {
private ReadProp readProp = new ReadProp();
#Value("${name}")
private String name;
#Value("${rollNo}")
private String rollNo;
#Test
public void readValues() {
System.out.println(name);
System.out.println(rollNo);
readProp.getDetails();
}
}
Instead of creating a new object using new ReadProp(). You should Autowire it.
#Autowired
ReadProp readProp;
in your test class. If you create an object using new, you don't get the bean which spring created with all the value assigned using #Value.
Try something like this :
#PropertySource("classpath:prop.properties")// your error
public class ReadPropTest {
#Value("${name}")
private String name;
#Value("${rollNo}")
private String rollNo;
}
Related
Spring MVC converts the id from path to corresponding object by making call to JpaRepository's findById method. For example see getVersionTree() method.
public class Controller {
#NonNull
private final MyService service;
#NonNull
private final MyAssembler assembler;
#GetMapping(path = VERSION_TREE_MAPPING, produces = MediaTypes.HAL_JSON_UTF8_VALUE)
public HttpEntity<?> getVersionTree(#PathVariable("id") MappingDocument mappingDocument, Pageable pageable, PagedResourcesAssembler<VersionNode> pagedResourcesAssembler) {
Page<VersionNode> versionNodes = service.getVersionTreeFor(mappingDocument, pageable);
return new ResponseEntity<>(pagedResources, HttpStatus.OK);
}
While testing, SpringMVC throws " Failed to convert value of type 'java.lang.String' to required type 'com.rbc.dna.dtl.mappingdocument.MappingDocument'". I am mocking jpaRepository.findById() method. Test Code is as follows:
#Autowired
private WebApplicationContext webApplicationContext;
#MockBean
private MyRepository repository;
#Mock
MyController controller;
#MockBean
private MyServiceImpl serviceImpl;
#Test
public void testMethod() throws Exception {
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(SecurityMockMvcConfigurers.springSecurity()).build();
MappingDocument mappingDocumentl=MappingDocument.builder().id(17L).build();
Mockito.when(repository.findById(17L)).thenReturn(Optional.of(mappingDocumentl));
Mockito.when(serviceImpl.getVersionTreeFor(mappingDocument,pageable)).thenReturn(pagedResponse);
mockMvc.perform(MockMvcRequestBuilders.get("/abc/17/def").param("page","0").param("size","20").contentType(MediaTypes.HAL_JSON_UTF8_VALUE)
.with(authentication(getOauthTestAuthentication()))
.sessionAttr("scopedTarget.oauth2ClientContext", getOauth2ClientContext()))
.andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
}
Your rest Controller take #PathVariable("id") MappingDocument mappingDocument as variable in your path, but in mockMvc.perform you are passing a simple String/Number or something that doesn't bind with MappingDocument.
Try to replace
public HttpEntity<?> getVersionTree(#PathVariable("id") MappingDocument mappingDocument...
with
public HttpEntity<?> getVersionTree(#PathVariable("id") Long idMappingDocument, ...
If you want to keep your object in #PathVariable you need to change
#GetMapping(path = VERSION_TREE_MAPPING)
To parse an object as PathVariable you need to have path that represent property of your object.
For example if you have
class Person {
String name;
String address;
//getters and setters
}
and you need to define a controller as follow:
#GetMapping(path = "/person/{name}/{address}", produces = MediaTypes.HAL_JSON_UTF8_VALUE)
public HttpEntity<?> getVersionTree(Person person) {
Where {name} and {address} must bind Person properties
I am using spring-data-solr to query indexed Solr data running on a Hadoop cluser. The name of my collection is party_name. Below is the code I used to configure the Cloud client:
#Configuration
#EnableSolrRepositories(basePackages = { "org.nccourts.repository" }, multicoreSupport = true)
public class SpringSolrConfig {
#Value("${spring.data.solr.zk-host}")
private String zkHost;
#Bean
public SolrClient solrClient() {
return new CloudSolrClient(zkHost);
}
#Bean
public SolrTemplate solrTemplate(CloudSolrClient solrClient) throws Exception {
solrClient.setDefaultCollection("party_name");
return new SolrTemplate(solrClient);
}
}
When I run my JUnit test, I am getting the following exception:
org.springframework.data.solr.UncategorizedSolrException: Collection not found: partyname; nested exception is org.apache.solr.common.SolrException: Collection not found: partyname
at org.springframework.data.solr.core.SolrTemplate.execute(SolrTemplate.java:215)
at org.springframework.data.solr.core.SolrTemplate.executeSolrQuery(SolrTemplate.java:1030)
Note the collection not found: partyname, but the collection name I entered is
party_name.
I am using Spring Boot version 1.5.2 with the following dependency:
compile('org.springframework.boot:spring-boot-starter-data-solr')
Any help or pointers are appreciated.
Your suggestion gave me the idea. My model looked like this:
public class PartyName {
#Field("case_status")
private String caseStatus;
private String county;
#Field("court_type")
private String courtType;
private String id;
#Field("in_regards_to")
private String inRegardsTo;
#Field("biz_name")
private String bizName; // business name after parsing name
#Field("first_name")
private String firstName; // person 1st name after parsing name
#Field("last_name")
private String lastName; // person last name after parsing name
#Field("middle_name")
private String middleName; // person middle name after parsing name
private String name; // original name before parsing
private String prefix; // person prefix after parsing name
private String suffix; // person name suffix after parsing name
#Field("party_num")
private Integer partyNumber;
#Field("party_role")
private String partyRole;
#Field("party_status")
private String partyStatus;
#Field("row_of_origin")
private String rowOrigin;
#Field("seq_num")
private Integer seqNumber;
private Integer year;
... getter/setter omitted.
}
When you suggested for me to post my entity code, I realized I needed to add the following annotation:
#SolrDocument(solrCoreName = "party_name")
public class PartyName {
..
After I did that, the JUnit worked fine. Thanks.
I am working with Realm ORM for my application. My Application has three Model classes that extends RealmObject. In one of the class I have defined a List of object which is creating problem.
my first class;
public class Party extends RealmObject implements Parcelable{
public String name;
public String name_en;
public String name_ne;
public String address;
public String phoneNumber;
//get and setters
//parceable
}
My second class;
public class CreatePurchaseOrderRow extends RealmObject implements Parcelable {
public String name;
public float amount;
public String specification;
public String remarks;
public Party party;
// getter setter
//parceable
}
And finally My third class implements List of objects of Second class. that is,
public class CreatePurchasOrder extends RealmObject implements Parcelable {
public int num;
public Date date;
public List<CreatePurchaseOrderRow> createPurchaseOrderRows;
//getter setter
//parceable
}
the List feeds is creating problem.
i have the screenshot for error message here
Realm is not schemaless database. I tried finding the solutions but i cannot. Can anyone help me with this?
Thanks in Advance
RealmObjects can not have fields of type List<>(java.util.List), you have to use RealmList<> instead:
public class CreatePurchasOrder extends RealmObject implements Parcelable {
public int num;
public Date date;
public RealmList<CreatePurchaseOrderRow> createPurchaseOrderRows;
//getter setter
//parceable
}
See also: https://realm.io/docs/java/latest/#many-to-many
I define an object like
public class DrivelogBean implements Serializable{
private String backInfoIdentify;
private DriVehNum driVehNum;
public static class TotalMileageIntd implements Serializable{
private static final long serialVersionUID = -3268743972404969523L;
private String totalMileage;
private String mileageTime;
public String getTotalMileage () {
return totalMileage;
}
public void setTotalMileage (String totalMileage) {
this.totalMileage = totalMileage;
}
public String getMileageTime () {
return mileageTime;
}
public void setMileageTime (String mileageTime) {
this.mileageTime = mileageTime;
}
}
}
and my controller is like:
#RequestMapping(value="saveDriveLog",method = RequestMethod.GET)
public #ResponseBody ResultBean saveDriveLog(DrivelogBean drivelogBean){
driveLogService.addDriveLog (drivelogBean);
ResultBean resultBean = new ResultBean();
resultBean.setRet (1);
resultBean.setDescripion (UsConstants.DRIVELOG_SAVE);
return resultBean;
}
I want request parameters convert to drivelogBean
and my url is like that:
http://127.0.0.1:8080//manage/drivelog/saveDriveLog/?backInfoIdentify=2&totalMileageIntd["driverNum%22]=1&totalMileageIntd["driveCode"]=2
but the page prompt
HTTP ERROR: 404 Problem accessing //manage/drivelog/saveDriveLog/error. Reason:Not Found
and i change the url like :
http://127.0.0.1:8080//manage/drivelog/saveDriveLog/?commendWord=2&totalMileageIntd.driverNum=1&totalMileageIntd.driveCode=2
but the drivelogBean parameter, the property driverNum of totalMileageIntd and the property driveCode of totalMileageIntd is null.
So how can I set the correct url pass parameter to the drivelogBean?
I don't know if binding inner static class works in spring.
Your parametter must match a setter
commendWord=2 => you must have setCommendWord on the class DrivelogBean
totalMileageIntd.driverNum=1 => you must have a setDriverNum() on and a getTotalMileageIntd
The class should look like this (I skipped getter and setter to save space but they must exists)
public class DrivelogBean implements Serializable{
private String backInfoIdentify;
private DriVehNum driVehNum;
private TotalMileageIntd totalMileageIntd ;
public static class TotalMileageIntd implements Serializable{
private static final long serialVersionUID = -3268743972404969523L;
private String totalMileage;
private String mileageTime;
}
}
In this case all the parametter you can use are :
backInfoIdentify=XXX
driVehNum=XXX
totalMileageIntd.totalMileage=XXX
totalMileageIntd.mileageTime=XXX
nothing else
I have these classes
public class Application {
public String name;
public String ico;
public List<MenuStruct> menu =new ArrayList<MenuStruct>();
//Constructor
public Application() { }
}
public class MenuStruct {
public String id;
public String type;
public String parent;
public String name;
public String secId;
//Constructor
public MenuStruct() {}
}
If I try to deserialize a collection directly in this way:
ApplicationManager apm= new ApplicationManager();
s="[ {\"name\":\"reg_salida\" , \"ico\":\"document-open-2-32x32.ico\" }]";
apm.apps=(new Gson()).fromJson(s,apm.apps.getClass() );
for (Application ap:apm.apps){
System.out.println(ap.name); //gets error here
}
I get a java.lang.ClassCastException.
But if I try to deserialize its containig class ApplicationManager it does not fail.
s="{ \"apps\": [ {\"name\":\"reg_salida\" , \"ico\":\"document-open-2-32x32.ico\" }]}";
ApplicationManager apm=(new Gson()).fromJson(s,ApplicationManager.class);
for (Application ap:apm.apps){
System.out.println(ap.name); // now no errors here! and shows reg_salida
}
Is this a bug of gson 2.2.4? or maybe I am doing something not correct?
Eduard.
You have to provide full definition of property class. Your example should looks like that:
manager.apps = gson.fromJson(json, new TypeToken<List<Application>>() {}.getType());