How to Handle Json when Some time getting Object or Some Time getting Array using Retrofit - retrofit

I have facing Issues when we getting Some time JSON object and SOME Time JSON Array using Retrofit Libarary.
So Please suggest me How can Handle it.

if your response is like some times
{
"accounts": {
"AccountType":
{
"accountId": 620430,
"active": true,
}
},
"code": "OK"
}
and some time
{
"accounts": {
"AccountType": [
{
"accountId": 620430,
"active": true,
},
{
"accountId": 620330,
"active": true,
}
]
},
"code": "OK"
}
then use these code , hope it will solve your problem
static Gson gson = new GsonBuilder().registerTypeAdapter(Accounts.class, new LocationsDeserializer()).create();
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
;
public static class LocationsDeserializer implements JsonDeserializer<Accounts> {
#Override
public Accounts deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonElement monumentElement = json.getAsJsonObject().get("AccountType");
if (monumentElement.isJsonArray()) {
return new Accounts((AccountType[]) context.deserialize(monumentElement.getAsJsonArray(), AccountType[].class));
} else if (monumentElement.isJsonObject()) {
return new Accounts((AccountType) context.deserialize(monumentElement.getAsJsonObject(), AccountType.class));
} else {
throw new JsonParseException("Unsupported type of monument element");
}
}
}
and your model class will be
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class AccountResponse {
#SerializedName("accounts")
#Expose
private Accounts accounts;
#SerializedName("code")
#Expose
private String code;
public Accounts getAccounts() {
return accounts;
}
public void setAccounts(Accounts accounts) {
this.accounts = accounts;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
-----------------------------------com.example.AccountType.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class AccountType {
#SerializedName("accountId")
#Expose
private Integer accountId;
#SerializedName("active")
#Expose
private Boolean active;
public Integer getAccountId() {
return accountId;
}
public void setAccountId(Integer accountId) {
this.accountId = accountId;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
}
-----------------------------------com.example.Accounts.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Accounts {
#SerializedName("AccountType")
#Expose
private List<AccountType> accountType = null;
public Accounts(AccountType ... ms) {
accountType = Arrays.asList(ms);
}
public List<AccountType> getAccountType() {
return accountType;
}
public void setAccountType(List<AccountType> accountType) {
this.accountType = accountType;
}
}

Related

Can not read data from firebase as List in android

I read many articles but still my problem is continuing, while fetching data from firebase as list. could you please help me on this.
Error: com.google.firebase.database.DatabaseException: Can't convert
object of type java.lang.String to type SubCategoryLoad Object
Firebase database image
--> Loading data from firebase:
mSubCategoryDatabaseRef = FirebaseDatabase.getInstance().getReference("user_post_add_database_ref").child("yeswanth599").child(mCategoryNameReceive);
mSubCategoryDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
GenericTypeIndicator<Map<String,SubCategoryLoad>> genericTypeIndicator=new GenericTypeIndicator<Map<String,SubCategoryLoad>>(){};
(-->Error Showing in this Line) Map<String,SubCategoryLoad> map=(Map<String, SubCategoryLoad>)postSnapshot.getValue(genericTypeIndicator);
assert map != null;
mSubCategoryLoad=new ArrayList<>(map.values());
}
mSubCategoryAdapter = new SubCategoryDisplayAdapter(getContext(), mSubCategoryLoad);
mSubCategoryRecyclerView.setAdapter(mSubCategoryAdapter);
mSubCategoryProgressCircle.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getContext(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
mSubCategoryProgressCircle.setVisibility(View.INVISIBLE);
}
});
--> SubCategoryLoad.Class
public class SubCategoryLoad {
private String mUserPostAddress;
private String mUserPostBusinessEndTime;
private String mUserPostBusinessSelectedCity;
private String mUserPostBusinessSelectedCountry;
private String mUserPostBusinessStartTime;
private String mUserPostCategory;
private String mUserPostEmail;
private List<UserPostAdsImages> mUserPostImages;
private String mUserPostName;
private String mUserPostPhonenumber;
private List<UserPostAdsLanguages> mUserPostSupportingLanguage;
private String mUserPostWebsite;
public SubCategoryLoad() {
//empty constructor needed
}
public SubCategoryLoad(String userPostAddress, String userPostBusinessEndTime,
String userPostBusinessSelectedCity, String userPostBusinessSelectedCountry,
String userPostBusinessStartTime, String userPostCategory,
String userPostEmail, List<UserPostAdsImages> userPostImages,
String userPostName, String userPostPhonenumber,
List<UserPostAdsLanguages> userPostSupportingLanguage, String userPostWebsite
) {
mUserPostAddress = userPostAddress;
mUserPostBusinessEndTime = userPostBusinessEndTime;
mUserPostBusinessSelectedCity = userPostBusinessSelectedCity;
mUserPostBusinessSelectedCountry = userPostBusinessSelectedCountry;
mUserPostBusinessStartTime = userPostBusinessStartTime;
mUserPostCategory = userPostCategory;
mUserPostEmail = userPostEmail;
mUserPostImages = userPostImages;
mUserPostName = userPostName;
mUserPostPhonenumber = userPostPhonenumber;
mUserPostSupportingLanguage = userPostSupportingLanguage;
mUserPostWebsite = userPostWebsite;
}
public void setUserPostAddress(String userPostAddress) {
this.mUserPostAddress = userPostAddress;
}
public void setUserPostBusinessEndTime(String userPostBusinessEndTime) {
this.mUserPostBusinessEndTime = userPostBusinessEndTime;
}
public void setUserPostBusinessSelectedCity(String userPostBusinessSelectedCity) {
this.mUserPostBusinessSelectedCity = userPostBusinessSelectedCity;
}
public void setUserPostBusinessSelectedCountry(String userPostBusinessSelectedCountry) {
this.mUserPostBusinessSelectedCountry = userPostBusinessSelectedCountry;
}
public void setUserPostBusinessStartTime(String userPostBusinessStartTime) {
this.mUserPostBusinessStartTime = userPostBusinessStartTime;
}
public void setUserPostCategory(String userPostCategory) {
this.mUserPostCategory = userPostCategory;
}
public void setUserPostEmail(String userPostEmail) {
this.mUserPostEmail = userPostEmail;
}
public void setUserPostImages(List<UserPostAdsImages> userPostImages) {
this.mUserPostImages = userPostImages;
}
public void setUserPostName(String userPostName) {
this.mUserPostName = userPostName;
}
public void setUserPostPhonenumber(String userPostPhonenumber) {
this.mUserPostPhonenumber = userPostPhonenumber;
}
public void setUserPostSupportingLanguage(List<UserPostAdsLanguages> userPostSupportingLanguage) {
this.mUserPostSupportingLanguage = userPostSupportingLanguage;
}
public void setUserPostWebsite(String userPostWebsite) {
this.mUserPostWebsite = userPostWebsite;
}
public String getUserPostAddress() {
return mUserPostAddress;
}
public String getUserPostBusinessEndTime() {
return mUserPostBusinessEndTime;
}
public String getUserPostBusinessSelectedCity() {
return mUserPostBusinessSelectedCity;
}
public String getUserPostBusinessSelectedCountry() {
return mUserPostBusinessSelectedCountry;
}
public String getUserPostBusinessStartTime() {
return mUserPostBusinessStartTime;
}
public String getUserPostCategory() {
return mUserPostCategory;
}
public String getUserPostEmail() {
return mUserPostEmail;
}
public List<UserPostAdsImages> getUserPostImages() {
return mUserPostImages;
}
public String getUserPostName() {
return mUserPostName;
}
public String getUserPostPhonenumber() {
return mUserPostPhonenumber;
}
public List<UserPostAdsLanguages> getUserPostSupportingLanguage() {
return mUserPostSupportingLanguage;
}
public String getUserPostWebsite() {
return mUserPostWebsite;
}
}
--> SubCategoryDisplayAdapter.class
SubCategoryLoad subCategoryLoadCurrent = mSubCategoryLoad.get(position);
holder.mSubCategoryAdsTitle.setText(subCategoryLoadCurrent.getUserPostName());
holder.mSubCategoryAdsSupportingLanguagesList.setText("English,Japanese");
//Log.i(TAG, "message:"+subCategoryLoadCurrent.getUserPostImages().get(0).getUserPostImageList());
Glide.with(mContext)
.load(subCategoryLoadCurrent.getUserPostImages().get(0).getUserPostImageList())
.into(holder.mSubCategoryAdsImage);
Thanks & Regards,
Yeswanth.
I used to have the same issue with my parsing and the problem was instead of a list of custom objects i was supposed to be using a Map like this
private Map<String,Boolean>
That field in Firebase contains a key and a state (True or False).
Also you can check the code on the docs to see how they parse these objects.
https://firebase.google.com/docs/database/android/read-and-write?authuser=0#read_data_once

Spring custom Generic converter not working

In my spring mvc web-application i use a generic converter that converts String (id) to Company by fetch using (service and dao) components
first of all in my MVC-config i add the converter like follow :
#Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new GenericIdToCompanyConverter(new CompanyServiceImp()));
}
companyService
#Service
#Transactional
#Qualifier("companyService")
public class CompanyServiceImp implements ICompanyService {
#Resource
#Qualifier("companyDAO")
private ICompanyDao dao;
public void setDao(ICompanyDao dao) {
this.dao = dao;
}
#Override
public Company find(Long id) throws BusinessException {
Company current = dao.find(id);
if(current == null) {
throw new BusinessException("notFound");
}
return current;
}
....
}
Generic converter :
public class GenericIdToCompanyConverter implements GenericConverter {
private ICompanyService companyService;
public GenericIdToCompanyConverter(ICompanyService companyService) {
super();
this.companyService = companyService;
}
#Override
public Set<ConvertiblePair> getConvertibleTypes() {
ConvertiblePair[] pairs = new ConvertiblePair[] { new ConvertiblePair(Number.class, Company.class), new ConvertiblePair(String.class, Company.class) };
return ImmutableSet.copyOf(pairs);
}
#Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
long id = 0;
if( sourceType.getType() == String.class) {
try {
id = Long.valueOf((String) source);
}catch(NumberFormatException e) {
return null;
}
}else if( sourceType.getType() == Number.class) {
id = (Long) source;
}else {
return null;
}
try {
return companyService.find(Long.valueOf(id));
} catch (BusinessException e) {
return null;
}
}
}
and here the controller that receives data form (via ajax request)
public #ResponseBody JsonResponseBean applay(#Valid VoucherForm form, BindingResult result, Locale locale) throws BusinessException {
....
}
where VoucherForm has these attributes
public class VoucherForm{
protected Long id;
protected Company company;
...
}
when i run the application and call controller method it returns type mismatch error for company attribute
and when i execute this on debug mode i see that it fails on serviceCompany - dao.find(id) statment where my dao is == null
Please help
finally i have to autowire the converter
Mvc-config
....
#Autowired
private GenericIdToCompanyConverter genericIdToCompanyConverter;
#Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(genericIdToCompanyConverter);
}
and update the converter like follow :
public class GenericIdToCompanyConverter implements GenericConverter {
#Resource
#Qualifier("companyService")
private ICompanyService companyService;
#Override
public Set<ConvertiblePair> getConvertibleTypes() {
....
}
#Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
....
}
}

Error While Fetching Data from Corda Custom Tables

How to fetch data from corda Custom tables?
my sample code is as follows :-
Api layer -- getIous() method
{
Field attributeValue=IOUSchemaV1.PersistentIOU.class.getDeclaredField("value");
CriteriaExpression currencyIndex = Builder.equal(attributeValue, "12");
QueryCriteria.VaultCustomQueryCriteria criteria = new
QueryCriteria.VaultCustomQueryCriteria(currencyIndex);
vaultStates = services.vaultQueryByCriteria(criteria,IOUState.class);
}
In ExamplePlugin I added below code for schema registration
public class ExamplePlugin extends CordaPluginRegistry implements
WebServerPluginRegistry
{
#NotNull
#Override
public Set<MappedSchema> getRequiredSchemas()
{
Set<MappedSchema> requiredSchemas = new HashSet<>();
requiredSchemas.add(new IOUSchemaV1());
return requiredSchemas;
}
}
My Schema classes are ---
public final class IOUSchema {
}
#CordaSerializable
public class IOUSchemaV1 extends MappedSchema
{
public IOUSchemaV1() {
super(IOUSchema.class, 1, ImmutableList.of(PersistentIOU.class));
}
#Entity
#Table(name = "iou_states")
public static class PersistentIOU extends PersistentState {
#Column(name = "sender_name") private final String senderName;
#Column(name = "recipient_name") private final String recipientName;
#Column(name = "value") private final int value;
public PersistentIOU(String senderName, String recipientName, int value) {
this.senderName = senderName;
this.recipientName = recipientName;
this.value = value;
}
public String getSenderName() {
return senderName;
}
public String getRecipientName() {
return recipientName;
}
public int getValue() {
return value;
}
}
}
my state has :-
public class IOUState implements LinearState, QueryableState
{
--- some code goes here and below methods as well.---
#Override
public PersistentState generateMappedObject(MappedSchema schema) {
if (schema instanceof IOUSchemaV1) {
return new IOUSchemaV1.PersistentIOU(
this.sender.getName().toString(),
this.recipient.getName().toString(),
this.iou.getValue());
} else {
throw new IllegalArgumentException("Unrecognised schema $schema");
}
}
#Override
public Iterable<MappedSchema> supportedSchemas() {
return ImmutableList.of(new IOUSchemaV1());
}
}
But all the time i am getting below exception.
Caused by: net.corda.core.node.services.VaultQueryException:
Please register the entity 'com.example.schema.IOUSchemaV1' class in your CorDapp's CordaPluginRegistry configuration (requiredSchemas attribute)
and ensure you have declared (in supportedSchemas()) and mapped (in generateMappedObject())
the schema in the associated contract state's QueryableState interface implementation.
Can anyone please help to resolve this.
Try deleting implements WebServerPluginRegistry from your plugin declaration.

Th:each iterate specific variables from a hashSet Thymeleaf Spring MVC

So I"m using Thymeleaf and spring MVC and I have a Course object which has a TreeSet of Posts and the set of posts are similar to a reddit post. I'm trying to represent a set of Posts, on a user homepage that I created. I want the posts to come in chronological order, in a newsfeed sort of way, and I already have the user's courses that they are subscribed to on the model.
My problem is that when I try to iterate through each of the posts I can only pull up the post's id, which looks something like this [com.quizbanks.domain.Post#26], and when I try to show the title, which is the variable for the title of the post I always get a spring processor error.
So here's what my thymeleaf code looks like
<table class="table table-bordered">
<tr th:each="course : ${courses}" th:object="${course}">
<td><span th:text="${course.posts}"></span></td>
</tr>
</table>
and then I tried this, but this gives me the spring processor error
<table class="table table-bordered">
<tr th:each="course : ${courses}" th:object="${course}">
<td><span th:text="${course.posts.title}"></span></td>
</tr>
</table>
So I'm not really sure what to do, if anyone can see my issue and help me out that would be great, thanks in advance.
Also if you want to see my controller code or anything else, let me know and I'll post it.
UPDATE
User Class
package com.quizbanks.domain;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.quizbanks.security.Authorities;
import com.quizbanks.validators.ValidEmail;
#Entity
#Table(name="users")
#JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "#id")
public class User
{
private Long id;
#ValidEmail
#NotNull
#NotEmpty
private String email;
private String username;
private String password;
private University university;
private Set<Authorities> authorities = new HashSet<>();
private Set<Course> courses = new HashSet<>();
private Set<Post> posts = new HashSet<>();
private Set<Comment> comments = new HashSet<>();
private Set<StudySet> studySet = new HashSet<>();
private Set<Course> myCourses = new HashSet<Course>();
public User ()
{
}
public User(User user)
{
this.id = user.getId();
this.email = user.getEmail();
this.username = user.getUsername();
this.password = user.getPassword();
this.university = user.getUniversity();
this.authorities = user.getAuthorities();
this.courses = user.getCourses();
this.posts = user.getPosts();
this.comments = user.getComments();
this.studySet = user.getStudySet();
this.myCourses = user.getMyCourses();
}
#Id
#GeneratedValue
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="user", orphanRemoval=true)
public Set<Course> getCourses()
{
return courses;
}
public void setCourses(Set<Course> courses)
{
this.courses = courses;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="user", orphanRemoval=true)
public Set<Post> getPosts() {
return posts;
}
public void setPosts(Set<Post> posts) {
this.posts = posts;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
#ManyToOne
public University getUniversity() {
return university;
}
public void setUniversity(University university) {
this.university = university;
}
#OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL, mappedBy="user")
#JsonManagedReference
#JsonIgnoreProperties(allowGetters=true, value = "user" )
public Set<Comment> getComments() {
return comments;
}
public void setComments(Set<Comment> comments) {
this.comments = comments;
}
#OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL, mappedBy="user")
public Set<Authorities> getAuthorities()
{
return authorities;
}
public void setAuthorities(Set<Authorities> authorities)
{
this.authorities = authorities;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="user", orphanRemoval=true)
public Set<StudySet> getStudySet() {
return studySet;
}
public void setStudySet(Set<StudySet> studySet) {
this.studySet = studySet;
}
#ManyToMany(cascade={CascadeType.ALL}, fetch=FetchType.EAGER)
#JoinTable(name="user_myCourses")
public Set<Course> getMyCourses()
{
return myCourses;
}
public void setMyCourses(Set<Course> myCourses)
{
this.myCourses = myCourses;
}
}
Post Class
package com.quizbanks.domain;
import java.util.Set;
import java.util.TreeSet;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
#Entity
#JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "#id")
public class Course
{
private Long id;
#Size(min=1, max=50)
private String name;
#Size(min=1, max=50)
private String professor;
#Size(min=1, max=50)
private University university;
private Set<Post> posts = new TreeSet<>();
private User user;
#Id
#GeneratedValue
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
#ManyToOne
public User getUser()
{
return user;
}
public void setUser(User user)
{
this.user = user;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getProfessor()
{
return professor;
}
public void setProfessor(String professor)
{
this.professor = professor;
}
#ManyToOne
public University getUniversity() {
return university;
}
public void setUniversity(University university) {
this.university = university;
}
#OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL, mappedBy="course")
public Set<Post> getPosts()
{
return posts;
}
public void setPosts(Set<Post> posts)
{
this.posts = posts;
}
#Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Course other = (Course) obj;
if (id == null)
{
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
Post
package com.quizbanks.domain;
import java.util.Set;
import java.util.TreeSet;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
#Entity
#JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "#id")
public class Post
{
private Long id;
#Size(min=1, max=140)
#NotNull
private String title;
#Size(min=1, max=1000)
private String content;
private Course course;
private Set<Comment> comments = new TreeSet<>();
private User user;
#Id
#GeneratedValue
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
#ManyToOne
public Course getCourse()
{
return course;
}
public void setCourse(Course course)
{
this.course = course;
}
#ManyToOne
public User getUser()
{
return user;
}
public void setUser(User user)
{
this.user = user;
}
#OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL, mappedBy="post")
public Set<Comment> getComments() {
return comments;
}
public void setComments(Set<Comment> comments) {
this.comments = comments;
}
#Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Post other = (Post) obj;
if (id == null)
{
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
Controller
#RequestMapping(value="{user}", method=RequestMethod.GET)
public String userPageGet (ModelMap model, #AuthenticationPrincipal User user)
{
List<User> usersList = userRepo.findAll();
model.addAttribute("usersList", usersList);
List<StudySet> studySets = studySetRepo.findByUser(user);
model.addAttribute("studySets", studySets);
List<Course> courses = courseRepo.findByUser(user);
model.addAttribute("courses", courses);
return "user";
}
${courses} is a list of Courses with posts set inside.
It seems that the problem is that posts is a TreeSet, so you should iterate for each element inside that set to get actual Posts and then get titles.
UPDATE:
List<Course> courses = courseRepo.findByUser(user); here you get all courses for your user. So, next step is to iterate over that list to get all posts:
Set<Post> posts = new TreeSet<>();
for (Course course : courses) {
posts.addAll(course.getPosts);
}
model.addAttribute("posts", posts);

Nunit tests on Response.Cache.VaryByHeader

I am doing some Unit testing with NUnit and NSubstitute on a function that uses HttpResponse, I know you can't mock these objects so I have created interfaces to represent them and some of there properties.
I'm having trouble understanding how to create an interface for Response.Cache.VaryByHeader
// This is my HttpResponse interface
public interface IHttpResponse
{
Stream Filter { get ; set; }
IHttpCachePolicy Cache { get; set; }
void AppendHeader(string name, string value);
}
// concrete httresponse
public class HttpResponseProxy : IHttpResponse
{
private HttpResponse _httpResponse;
public Stream Filter {
get {
return _httpResponse.Filter ?? new MemoryStream();
}
set { _httpResponse.Filter = value; }
}
public IHttpCachePolicy Cache
{
get { return new HttpCachePolicyProxy(_httpResponse.Cache); }
set { }
}
public HttpResponseProxy(HttpResponse httpResponse)
{
if (httpResponse == null)
{
throw new ArgumentNullException("httpResponse");
}
_httpResponse = httpResponse;
_httpResponse.Filter = httpResponse.Filter;
}
public void AppendHeader(string name, string value)
{
_httpResponse.AppendHeader(name, value);
}
}
// HttpCachePolicy interface
public interface IHttpCachePolicy
{
IHttpCacheVaryByHeaders VaryByHeaders { get; set; }
}
// concrete HttpCachePolicy
public class HttpCachePolicyProxy : IHttpCachePolicy
{
private HttpCachePolicy _httpCachePolicy;
public HttpCachePolicyProxy(HttpCachePolicy httpCachePolicy)
{
_httpCachePolicy = httpCachePolicy;
}
public IHttpCacheVaryByHeaders VaryByHeaders
{
get { return new HttpCacheVaryByHeadersProxy(_httpCachePolicy.VaryByHeaders as HttpCacheVaryByHeaders); }
set { }
}
}
public interface IHttpCacheVaryByHeaders
{
IHttpCacheVaryByHeaders HttpCacheVaryByHeaders { get; set; }
}
public class HttpCacheVaryByHeadersProxy : IHttpCacheVaryByHeaders
{
private HttpCacheVaryByHeaders _httpCacheVaryByHeaders;
public HttpCacheVaryByHeadersProxy(HttpCacheVaryByHeaders httpCacheVaryByHeaders)
{
_httpCacheVaryByHeaders = httpCacheVaryByHeaders;
}
public IHttpCacheVaryByHeaders HttpCacheVaryByHeaders
{
get { return new HttpCacheVaryByHeadersProxy(_httpCacheVaryByHeaders); }
set { }
}
}
This is the function i am actually testing:
public static void CompressPage(IHttpRequestGetCompressionMode getCompressionMode, IHttpResponse httpResponse)
{
string supportedCompression = getCompressionMode.GetClientSupportedCompressionMode();
if (supportedCompression != HttpHeaderValues.NoCompression)
{
switch (supportedCompression)
{
case HttpHeaderValues.DeflateCompression:
httpResponse.Filter = new DeflateStream(httpResponse.Filter, CompressionMode.Compress);
break;
case HttpHeaderValues.GZipCompression:
httpResponse.Filter = new GZipStream(httpResponse.Filter, CompressionMode.Compress);
break;
}
httpResponse.AppendHeader(HttpHeaderValues.ContentEncodingHeader, supportedCompression);
// this line is where i have the problem
httpResponse.Cache.VaryByHeaders[HttpHeaderValues.AcceptEncodingHeader] = true;
}
}
I'm getting "cannot apply index to an expression of type IHttpCacheVaryByHeaders" errors.
I have the interface for the response and cache but how do I represent VaryByHeaders in an interface and then use it in a concrete class?
The error seems to suggest that IHttpCacheVaryByHeaders does not have an indexer declared (e.g. bool this[string header] { get; set; }), but rather than implementing these wrappers yourself, try the HttpResponseWrapper and other System.Web.Abstractions. This will should make testing this stuff a lot easier. :)

Resources