How to get all keys from properties file? - spring-mvc

I am working on spring boot application ,I have one property file ,I am reading property file like below
#Configuration
#ConfigurationProperties(locations = "classpath:mail.properties", prefix = "mail")
public class MailConfiguration {
public static class Smtp {
private boolean auth;
private boolean starttlsEnable;
// ... getters and setters
}
#NotBlank
private String host;
private int port;
private String from;
private String username;
..............
}
Mail .properites
mail.host=localhost
mail.port=25
mail.smtp.auth=false
mail.smtp.starttls-enable=false
mail.from=me#localhost
This working fine ,But Instead of reading one by one property , I want to get all property keys from properties file ,How can I get this .

Use Map for that. Something like: (its "pseudo-code" - may contain spelling mistakes or something, just to show You the idea)
#Configuration
#ConfigurationProperties(locations = "classpath:mail.properties", prefix = "mail")
public static class MailConfiguration {
private Map<String, Object> mail = new HashMap<String, Object>();
public Map<String, Object> getMail() {
return this.mail;
}
}
Should do the work.
Regards,

Related

With Spring Data Redis, can CrudRepository operations use string keys and values instead of HASH?

I have the below data object and CrudRepository implementation. When I use the CrudRepository operations both the key and value get stored as HASH data types when I would like to have them stored as String datatypes. How can I configure this behavior? I tried adding the RedisTemplate bean as below and when debugging I do see that redis template is being used, but for data conversions it uses some other KeyValueAdapter classes instead it seems, and I'm having a hard time configuring that.
#Data
#RedisHash("DATA")
#Accessors(chain = true)
public class Data implements Serializable {
#Id
private String id;
private List<AnotherObject> objects;
private Long last_updated;
}
#Repository
public interface DataCache extends CrudRepository<Data, String> {
}
#Bean
public RedisTemplate<?, ?> redisTemplate(
#Autowired RedisConnectionFactory redisConnectionFactory,
#Autowired ObjectMapper mapper) {
RedisTemplate<byte[], byte[]> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
Jackson2JsonRedisSerializer valueSerializer = new Jackson2JsonRedisSerializer(Object.class);
valueSerializer.setObjectMapper(mapper);
template.setValueSerializer(valueSerializer);
template.setHashKeySerializer(valueSerializer);
template.setDefaultSerializer(new StringRedisSerializer());
template.setEnableDefaultSerializer(false);
template.afterPropertiesSet();
return template;
}

how to get the values from properties file in the test cases

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;
}

How to pass parameter to controller to get the correct object in spring mvc

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

Curiosities in deserializing collections with gson 2

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());

ASMX Web Service (ASP.net 2.0) - Serializable Dictionary not serialized

All,
I have an instance of ProjectBudget class returned from a web method.
Ex:
[WebMethod()]
public ProjectBudget LoadBudget(int id)
{
ProjectBudget budget = BudgetManager.LoadBudget(id);
return budget;
}
The ProjectBudget class contains the following defintion:
public class ProjectBudget
{
public int Id = -1;
public long VersionNumber = -1;
public string QuoteNumber = "";
public string CurrencyCode = "";
public ProjectInfo Project;
public ClientInfo Client;
public readonly List<InventoryItem> Inventory = new List<InventoryItem>();
public readonly List<Staff> Staff = new List<Staff>();
public readonly List<CodeType> Departments = new List<CodeType>();
public readonly SerializableDictionary<string, string> Tasks = new SerializableDictionary<string, string>();
public ProjectBudget()
{
}
}
All public fields you see are serialized just fine with the exception of Tasks field, which is completely ignored by XML serializer. Since we all know by now that Dictionaries cannot be handled by XML serializer, I use a serializable dictionary (which is just a dictionary that implements IXmlSerializable) here but XML serializer decides to ignore it completely, i.e. the XML output does not contain any tasks and the generated proxy class doesn't have this field.
I need to figure out how to tell the XML serializer not to omit this field.
Btw, what is interesting is that a web method that returns SerializableDictionary works fine!
A very similar question as yours appears to have been asked already: Link.
Use DataContractSerializer or try explicitly implementing your getter (and setter), as per this link.

Resources