I need to set some private fields in an object using another object's fields. Those two objects may not be instances of same class.
What I see from a short reading, I can use Apache's BeanUtils and Spring's ReflectionUtils for that. I couldn't find a satisfying explanation for them regarding security, performance, support etc.
The solution will be used in production environment too, so I need a concrete solution.
Which approach do you suggest for such a task.
I think you need use just the BeanUtils library. See my sample, i do a copy properties from CustomerBean to SellerBean.
package testes.beanutils;
import org.apache.commons.beanutils.BeanUtils;
public class Main {
public static void main(String[] args) throws Exception {
Customer customer = new Customer();
customer.setId((long)1);
customer.setName("Bruno");
customer.setLastname("Tafarelo");
Seller seller = new Seller();
BeanUtils.copyProperties(seller, customer);
System.out.println(customer);
System.out.println(seller);
}
}
class Customer {
private Long id;
private String name;
private String lastname;
//getters and setters
//toString
}
class Seller {
private Long id;
private String name;
private int sales;
//getters and setters
//toString
}
Related
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;
}
I have a Mongo - Java MVC Spring 4 connectivity. My insert operations work only once, they don't do a second insert in the collection. What could be the problem?
Here's my code.
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection="subject")
public class Employee {
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE)
private int id;
private String name;
private String email;
private String address;
private String telephone;
strong text
...
public class EmployeeDAOImpl implements EmployeeDAO {
MongoTemplate mongoTemplate;
public MongoTemplate getMongoTemplate() {
return mongoTemplate;
}
public void setMongoTemplate(MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}
#Override
public void addEmployee(Employee employee) {
mongoTemplate.save(employee);;
}
#Override
public List<Employee> getAllEmployees() {
// TODO Auto-generated method stub
return mongoTemplate.findAll(Employee.class);
}
#GeneratedValue(strategy=GenerationType.SEQUENCE) annotation is for JPA and not for Mongo.
Make sure that you import the #Id from the mongo package and ID should be auto generated by Mongo.
The first insert works because int has default value of 0 and the second time it tries to insert with the same key.
if you want to have custom ids generated, here is a great tutorial for that: https://www.baeldung.com/spring-boot-mongodb-auto-generated-field
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 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,
recently posted about questioning how unsafe static variables are, I've since discovered I need to get rid of them. But I cannot figure out how to? Was thinking a static Get() method for each class, that returns a single instance, but then that instance would have to be declared static.
So the only way to do it, is to have the instance references (for each helper, I.E user helper.cs, imagehelper.cs etc.) is to declare them as instance properties on some sort of globally accessible class? But which class? Is there something I'm missing here?
Code below of a sample class I need to change:
sing System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Mvc.Mailer;
namespace MVCWebsite.Helpers
{
public class AppSettings
{
public static void OnAppInit()
{
//General
AppName = "MyApp";
DesktopBaseURLs = new Dictionary<string, string>();
DesktopBaseURLs.Add("dev", "localhost:50560");
DesktopBaseURLs.Add("test", "www.test.whatever.com");
DesktopBaseURLs.Add("live", "www.whatever.com");
MobileBaseURLs = new Dictionary<string, string>();
MobileBaseURLs.Add("dev", "m.local.whatever.com");
MobileBaseURLs.Add("test", "m.test.whatever.com");
MobileBaseURLs.Add("live", "m.whatever.com");
//Emails
EmailHostName = AppName + ".com"; //For the moment atleast
NoReplyEmailAddress = "no-reply#" + EmailHostName.ToLower();
SupportEmailAddress = "support#" + EmailHostName.ToLower();
ErrorEmailAddress = "errors#" + EmailHostName.ToLower();
//Resources
TempFileURL = "/content/temp/";
UserDataURL = "/content/user-content/";
ProfilePicturesURL = UserDataURL + "profile-pictures/";
var a = GlobalHelper.GetURLAsServerPath(ProfilePicturesURL);
var b = a;
}
//General
public static string AppName { get; set; }
public static Dictionary<string, string> DesktopBaseURLs;
public static Dictionary<string, string> MobileBaseURLs;
//Emails
public static string EmailHostName { get; set; }
public static string NoReplyEmailAddress { get; set; }
public static string SupportEmailAddress { get; set; }
public static string ErrorEmailAddress { get; set; }
//Resources
public static string UserDataURL { get; set; }
public static string TempFileURL { get; set; }
public static string ProfilePicturesURL { get; set; }
//Methods
public static void SetAppURL()
{
}
}
}
I recommend creating an interface for your AppSettings class, so that you can use it in your controllers now, and implement it in different ways as you see fit:
public interface IAppSettings
{
string AppName { get; set; }
...
}
You can then implement it immediately with your static class via a wrapper class:
public class AppSettingsWrapper : IAppSettings
{
public AppName
{
get
{
return AppSettings.AppName;
}
set
{
AppSettings.AppName = value;
}
}
...
}
Later on, you can create an implementation of IAppSettings that uses session, or cookies, or database values, or whatever. The important thing is to abstract the way you store things so that you can implement in a way that meets your needs.
The answer to you previous question clearly stated that the IDictionary was the only unsafe variable in your static method because it's not thread safe. You just need to store these variables differently. You don't need to get rid of all of your static variables. You just need to change IDictionary to something thread safe.
By the way, someone there makes a good coment about web.config
Right I think I've figured it out, they should be stored as instance variables within Global.asax.cs. This file contains your Application class which inherits from System.Web.HttpApplication. This master class is limited to one instance (of itself) per request. So if you store any references to your helpers here, you can reference them by going, MvcApplication.MyHelper.DoSomething(); Someone please correct me if this is wrong, but seems right to me. "At any single point of time, an HTTPApplication instance handles only one request, so we don't need to think about locking and unlocking of any non static members, but for static members we do require. " -from : http://www.codeproject.com/Articles/87316/A-walkthrough-to-Application-State#c