Arraylist can't add element - arraylist

Why isn't this working for me?
public class Band {
public void addMember(Musician musician) {
musicians.add(musician);
System.out.println("Muscian: " + musician + "was successfully added");
}
}
public static void main(String[] args) {
Band Beatles = new Band("Beatles");
Beatles.addMember("John Lennon");
}
public class Musician {
private String name;
public Musician(String name, Instrument instrument) {
this.name = name;
Instrument Guitar = instrument;
}
public void play() {
}
}

Beatles.addMember("John Lennon");
should be
Beatles.addMember(new Musician("John Lennon", new Instrument(new Guitar()));
I suspect, without seeing your actual Instrument class, based on your comment that this line should work.
The problem is that you are treating some objects as Strings. You need to create the object out of the class that defines it first.

Related

Jackson Serialization Problems

I am having some trouble serializing/deserializing my classes below.
My Data class holds a list of other classes.
When I call the serialize/deserialize methods in the Data class, I get the following error:
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.amazon.rancor.storage.types.ChildData: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?)
The error comes from the deserialize method. But I also believe the serialization is not working properly. This is what the serialized Data object looks like:
{childData:[{zipCode:{present:true},countryCode:"US"}]
The Optional field is not being serialized properly even though I have set the objectMapper.registerModule(new Jdk8Module()); field
I can't seem to figure out what I am doing wrong. Maybe I need to change something in ChildData and ChildDataV2 class. But I am not sure what.
Any pointers would be appreciated!
public class Data {
private List<ChildData> childData;
private List<ChildDataV2> childDataV2;
private static ObjectMapper objectMapper;
static {
objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.registerModule(new Jdk8Module());
}
public Data() { }
#JsonCreator
public Data(#JsonProperty("childData") final List<ChildData> childData,
#JsonProperty("childDataV2") final List<ChildDataV2> childDataV2) {
this.childData = childData;
this.childDataV2 = childDataV2;
}
public List<ChildData> getChildData() {
return childData;
}
public void setChildData(final List<ChildData> childData) {
this.childData = childData;
}
public List<ChildDataV2> getChildDataV2() {
return childDataV2;
}
public void setChildDataV2(final List<ChildDataV2> childDataV2) {
this.childDataV2 = childDataV2;
}
public String serialize() {
try {
return objectMapper.writeValueAsString(this);
} catch (JsonProcessingException e) {
throw new RuntimeException("Failed to serialize. Data: " + this, e);
}
}
public Data deSerialize(final String data) {
try {
return objectMapper.readValue(data, Data.class);
} catch (IOException e) {
throw new RuntimeException("Failed to deserialize. Data" + data, e);
}
}
}
public class ChildData {
private final String countryCode;
private final Optional<String> zipCode;
public ChildData(final String countryCode, final Optional<String> zipCode) {
this.countryCode = countryCode;
this.zipCode = zipCode;
}
public Optional<String> getZipCode() {
return zipCode;
}
public String getCountryCode() {
return countryCode;
}
}
public class ChildDataV2 extends ChildData {
private final Object struct;
public ChildDataV2(final String cc, final Optional<String> postalCode,
final Object struct) {
super(cc, postalcode);
this.struct = struct;
}
}
The exception is quite clear right? You need to add a default constructor for ChildData or annotate the existing constructor like this:
#JsonCreator
public ChildData(#JsonProperty("countryCode") String countryCode, #JsonProperty("zipCode") Optional<String> zipCode) {
this.countryCode = countryCode;
this.zipCode = zipCode;
}

No converter found capable of converting from type [java.lang.String] to type [org.springframework.data.solr.core.geo.Point]

I am trying to use spring-data-solr in order to access to my Solr instance through my Spring boot application. I have the following bean class:
#SolrDocument(solrCoreName = "associations")
public class Association implements PlusimpleEntityI {
#Id
#Indexed
private String id;
#Indexed
private String name;
#Indexed
private Point location;
#Indexed
private String description;
#Indexed
private Set<String> tags;
#Indexed
private Set<String> topics;
#Indexed
private Set<String> professionals;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Point getLocation() {
return location;
}
public void setLocation(Point location) {
this.location = location;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Set<String> getTags() {
return tags;
}
public void setTags(Set<String> tags) {
this.tags = tags;
}
public Set<String> getTopics() {
return topics;
}
public void setTopics(Set<String> topics) {
this.topics = topics;
}
public Set<String> getProfessionals() {
return professionals;
}
public void setProfessionals(Set<String> professionals) {
this.professionals = professionals;
}
}
I have implemented the following repository in order to access to the related information:
public interface AssociationsRepository extends SolrCrudRepository<Association, String> {
}
I have created a configuration class which looks like the following one:
#Configuration
#EnableSolrRepositories(basePackages = {"com.package.repositories"}, multicoreSupport = true)
public class SolrRepositoryConfig {
#Value("${solr.url}")
private String solrHost;
#Bean
public SolrConverter solrConverter() {
MappingSolrConverter solrConverter = new MappingSolrConverter(new SimpleSolrMappingContext());
solrConverter.setCustomConversions(new CustomConversions(null));
return solrConverter;
}
#Bean
public SolrClientFactory solrClientFactory () throws Exception {
return new MulticoreSolrClientFactory(solrClient());
}
#Bean
public SolrClient solrClient() throws Exception {
return new HttpSolrClient.Builder(solrHost).build();
}
#Bean
public SolrOperations associationsTemplate() throws Exception {
SolrTemplate solrTemplate = new SolrTemplate(solrClient());
solrTemplate.setSolrConverter(solrConverter());
return solrTemplate;
}
}
Unfortunately, when I try to read an association from my Solr instance I got the following error:
org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [org.springframework.data.solr.core.geo.Point]
I don't understand why it is not able to find a converter if I have explicitly defined it in the solrTemplate() method.
This is my POM definition:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-solr</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
Thank you for your help.
EDIT:
I've also tried with different BUILD-RELEASEs but they are highly unstable and I've found a lot of errors using them.
Alessandro, as you can see directly in the GeoConverters class on GitHub, the implemented converters are only for:
org.springframework.data.geo.Point
and not for:
org.springframework.data.solr.core.geo.Point
Simply use this class and you don't even need a custom converter for this. Spring Data for Solr will perform the conversion for you.
I'm using a slightly patched version of the 3.0.0 M4, but I'm pretty sure this solution should apply seamlessly also to your case.

Spring-data-solr config

i met a problem in Studying with Spring data solr,this is my Configuration Class:
#Configuration
#EnableSolrRepositories(basePackages={"cn.likefund.solr.repository"}, multicoreSupport=true)
public class SolrContext {
static final String SOLR_HOST = "http://192.168.11.157:8080/solr";
#Bean
public SolrClient solrClient() {
return new HttpSolrClient(SOLR_HOST);
}
}
and this is my Repository:
package cn.likefund.solr.repository;
import java.util.List;
import org.springframework.data.solr.repository.SolrCrudRepository;
import cn.likefund.solr.model.Activity;
public interface ActivityRepository extends SolrCrudRepository<Activity, String>{
List<Activity> findByName(String name);
}
when I start the application,the message in console is this
error
When I delete the method findByName in the repository,the application start with no problem, i just want to the method findByName worked,anybody know what should i do with this problem?
here is the Activity Class:
#Entity
#SolrDocument(solrCoreName ="core_activity")
public class Activity implements Serializable{
private static final long serialVersionUID = 1566434582540525979L;
#Id
#Field(value = "id")
private String id;
#Field(value = "CREATEDT")
private String createdt;
#Indexed
#Field(value = "NAME")
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCreatedt() {
return createdt;
}
public void setCreatedt(String createdt) {
this.createdt = createdt;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
So, obviously the CrudRepository is not created .
when you delete the findByName, can you manually query your repo ? (just to be sure the problem comes from the method, and not the SOLR schema)
have you tried to annotate annotate the method to explicitly set the query ? Something like
#Query("NAME:?0")
List findByName(String name);

Does a set() field pointcut get invoked if field is set via reflection?

I have a field set pointcut, which seems to do as I expect. Its defined as follows
before(Object newval): set(#Serviced private * *.*) && args(newval)
The above is meant to capture: whenever a private field attribute, annotated with #Serviced, is set call my before advice.
Everything seems to work fine, except for the one case in my code that sets a variable matching the above via java reflection ( ie via java.lang.reflect.Field.set(....).
Any idea's how I can catch that "set" also?
Thanks
As you have noticed, the set() pointcut cannot intercept reflective field changes. But if you control (i.e. can weave aspects into) the code calling the Field.set*(..) methods, you can work around that issue by also using reflection. Here is a complete, compileable code sample illustrating the solution:
Sample annotation:
package de.scrum_master.app;
import java.lang.annotation.*;
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.FIELD)
public #interface Serviced {}
Sample entity class with main method:
package de.scrum_master.app;
public class Person {
#Serviced private int id;
#Serviced private String name;
private String country;
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getCountry() { return country; }
public void setCountry(String country) { this.country = country; }
public void setIdReflective(int id) throws Exception {
Person.class.getDeclaredField("id").setInt(this, id);
}
public void setNameReflective(String name) throws Exception {
Person.class.getDeclaredField("name").set(this, name);
}
public void setCountryReflective(String country) throws Exception {
Person.class.getDeclaredField("country").set(this, country);
}
#Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", country=" + country + "]";
}
public static void main(String[] args) throws Exception {
Person person = new Person();
person.setId(11);
person.setName("Tin Man");
person.setCountry("Oz");
System.out.println("Before reflective setters: " + person);
person.setIdReflective(22);
person.setNameReflective("Cowardly Lion");
person.setCountryReflective("The Land of Oz");
System.out.println("After reflective setters: " + person);
}
}
As you can see, only two out of three private fields have the #Serviced annotation. Setters are called for all three fields twice: once normally and once via reflection.
Aspect intercepting both normal and reflective field changes:
package de.scrum_master.aspect;
import de.scrum_master.app.Serviced;
import java.lang.reflect.Field;
public aspect ServicedFieldChangeInterceptor {
before(Object newValue):
set(#Serviced private * *) && args(newValue)
{
System.out.println(thisJoinPointStaticPart + " -> " + newValue);
}
before(Object newValue, Field field):
call(public void Field.set*(Object, *)) && args(*, newValue) && target(field)
{
if (field.getAnnotation(Serviced.class) == null)
return;
System.out.println(thisJoinPointStaticPart + " -> " + field + ", " + newValue);
}
}
Sample output when running Person.main:
set(int de.scrum_master.app.Person.id) -> 11
set(String de.scrum_master.app.Person.name) -> Tin Man
Before reflective setters: Person [id=11, name=Tin Man, country=Oz]
call(void java.lang.reflect.Field.setInt(Object, int)) -> private int de.scrum_master.app.Person.id, 22
call(void java.lang.reflect.Field.set(Object, Object)) -> private java.lang.String de.scrum_master.app.Person.name, Cowardly Lion
After reflective setters: Person [id=22, name=Cowardly Lion, country=The Land of Oz]
The output clearly shows that both advice only "do something" (in this case print information to standard output) for fields annotated with #Serviced, whereas other fields are skipped. While the set() pointcut applies statically, the reflective one needs to determine if the target field has a matching annotation dynamically.

Problem getting same class instance passed from one activity to another

I am trying to pass SampleParcelable class object say sampleObj from my ClassA (current) activity to ClassB (a new one), but when i log the objects value, the object's value which i am creating in ClassA is totally different from what i get in ClassB.
ClassA :-
public class ClassA extends Activity
{
private SampleParcelable sampleObj;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
sampleObj = new SampleParcelable();
Log.d("Actual Reference Value", "\t" + sampleObj);
Intent terminateActivity = new Intent( ClassA.this, ClassB.class );
terminateActivity.putExtra("SampleValue", sampleObj);
SampleParcelable readbackCi = terminateActivity.getParcelableExtra("SampleValue");
Log.d("Retrieved Value", "\n\n\t" + readbackCi);
}
}
ClassB :-
public class ClassB extends Activity
{
private SampleParcelable newSampleObj;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
try {
Intent intentObj = getIntent();
Log.d("Intent Value", "intent: " + intentObj.toString());
Log.d("Extra Values", "extras: " + intentObj.getExtras());
newSampleObj = (SampleParcelable) intentObj.getParcelableExtra("SampleValue");
Log.d("New Value", " " + newSampleObj.toString());
} catch (Exception e) {
Log.d("Exception in main", e.toString());
}
}
}
SampleParcelable :-
public class SampleParcelable implements Parcelable
{
public SampleParcelable(Parcel in) {
in.readParcelable(SampleParcelable.class.getClassLoader());
}
public SampleParcelable() {
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
}
public static final Parcelable.Creator<SampleParcelable> CREATOR = new Parcelable.Creator<SampleParcelable>() {
public SampleParcelable createFromParcel(Parcel in) {
return new SampleParcelable(in);
}
public SampleParcelable[] newArray(int size) {
return new SampleParcelable[size];
}
};
}
After debugging I guess, I know 1 reason why my object values are different, because when retrieving object in ClassB using getParcelableExtra() at that time my SampleParcelable class createFromParcel method is called which internally creates a new object. May be i m wrong.
I am not getting any solution for this, i just want same object in my new class so that i can access some values using that object which were set in my ClassA activity.
Thanks in advance
Here how you can achieve what you intend for::
package com.unundoinc.FaceBook.Activity;
import android.os.Parcel;
import android.os.Parcelable;
public class CheckParcelable implements Parcelable
{
private Facebook facebook;
public CheckParcelable() { ; }
/**
*
* Constructor to use when re-constructing object
* from a parcel
*
* #param in a parcel from which to read this object
*/
public CheckParcelable(Parcel in) {
readFromParcel(in);
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags)
{
// TODO Auto-generated method stub
dest.writeValue(getFacebook());
}
private void readFromParcel(Parcel in) {
// readParcelable needs the ClassLoader
// but that can be picked up from the class
// This will solve the BadParcelableException
// because of ClassNotFoundException
facebook = (Facebook) in.readValue(Facebook.class.getClassLoader());
}
public void setFacebook(Facebook facebook) {
this.facebook = facebook;
}
public Facebook getFacebook() {
return facebook;
}
public static final Parcelable.Creator<CheckParcelable> CREATOR =
new Parcelable.Creator<CheckParcelable>()
{
public CheckParcelable createFromParcel(Parcel in)
{
return new CheckParcelable(in);
}
public CheckParcelable[] newArray(int size) {
return new CheckParcelable[size];
}
};
}
For Using the Parceable You Need to do something like this in the class from where you require pass the object to the other Activity::
Facebook facebook = new Facebook();
facebook.setAccessToken("TIMEPASS");
CheckParcelable parcelable = new CheckParcelable();
parcelable.setFacebook(facebook);
Intent newIntent = new Intent(ActivityA.this, ActivityB.class);
newIntent.putExtra("CheckParcelable", parcelable);
And for getting the Object from Other Activity you require to perform this thing ::
CheckParcelable parcelable = getIntent().getExtras().getParcelable("CheckParcelable");
Facebook facebook = parcelable.getFacebook();
Log.v(TAG, "PARCELABLE IS ::" +facebook.getAccessToken());
I hope this would solve you problem ;D