retrofit response address insread of data - retrofit

i try to get data from server
server response here
{
"userid": "jin",
"sex": true,
"height": 180,
"authorityDtoSet": [
{
"authorityName": "ROLE_USER"
}
]
}
i want to get data as user class,
my user class here
public class User {
#SerializedName("userid")
public String userid;
#SerializedName("sex")
public boolean sex;
#SerializedName("height")
public int height;
#SerializedName("authorityDtoSet")
public ArrayList<AuthorityDto> authorityDtoSet;
public class AuthorityDto {
#SerializedName("authorityName")
public String authorityName;
public String getAuthorityName() {
return authorityName;
}
}
#Override
public String toString() {
return "PostResult{" +
"userid=" + userid +
", sex=" + sex +
", height='" + height + '\'' +
", authorityDtoSet='" + authorityDtoSet.toString() + '\'' +
'}';
}
}
but when i get response,
result show address of authorityDtoSet
PostResult{userid=jin, sex=true, height='180', authorityDtoSet='[com.example.spring_boot_test.User$AuthorityDto#a7c1edb]'}
i tried to use to.string() but i doesn't work
if(response.isSuccessful()){
User user = response.body(); //
List<User.AuthorityDto> authorityName = user.authorityDtoSet;
Log.i("Tag", "Success##!!# authorityName : " + authorityName.toString());
how can i get "authorityName": "ROLE_USER" data(not address)?
plz help thanks in advance

Related

spring data redis use #RedisHash to generate hash then retrieve its fields

friends! I want to retrieve only a field of a hash from redis database using spring RedisTemplate, but it does not work. Because I think it is reasonable to do it since #RedisHash makes the object a hash table in Redis, I have tried to retrieve or update part of the hash, but don't know why it does not work:
This is the entity I use:
#Data
#RedisHash("arithmetic_gamestats")
public class GameStats {
/**
* Used for redis serialization
*/
public GameStats() {}
public GameStats(long userId, int score) {
this.userId = userId;
this.score = score;
}
public GameStats(long userId, int score, List<Badge> badges) {
this.userId = userId;
this.score = score;
this.badges = badges;
}
#Id
private Long userId;
private int score;
private List<Badge> badg/es;
}
// this is my test, first I create a new object, and save it to redis, this works totally fine:
//#Test #Order(5)
public void testRedisHashtable() {
long userId = userIds.get(random.nextInt(0, userIds.size()));
GameStats gameStats = new GameStats(userId, 1000);
GameStats dbGameStats = gamestatsRepository.save(gameStats);
assertThat(dbGameStats).isNotNull();
}
After insert one instance of the GameStats class in the test method, I get the following result in Redis server which is what I expected:
127.0.0.1:6379> keys *
1) "arithmetic_gamestats"
2) "arithmetic_gamestats:-5461129489864155017"
127.0.0.1:6379> type "arithmetic_gamestats"
set
127.0.0.1:6379> type "arithmetic_gamestats:-5461129489864155017"
hash
127.0.0.1:6379> smembers "arithmetic_gamestats"
1) "-5461129489864155017"
127.0.0.1:6379> hgetall "arithmetic_gamestats:-5461129489864155017"
1) "_class"
2) "com.worldexplorer.arithmeticgamification.entity.GameStats"
3) "score"
4) "1000"
5) "userId"
6) "-5461129489864155017"
127.0.0.1:6379> hget "arithmetic_gamestats:-5461129489864155017" "score"
"1000"
I copy the key from redis to retrieve the data, but the result is null, or empty:
#Test #Order(6)
public void testRedisHash() {
String key = "arithmetic_gamestats:-5461129489864155017";
Object scoreObject = redisTemplate.opsForHash().get(key, "score");
System.out.println("score = " + scoreObject);
Set<Object> keySet = redisTemplate.opsForHash().keys(key);
for (Object object : keySet) {
System.out.println("key = " + object);
}
Map<Object, Object> keyvalueMap = redisTemplate.opsForHash().entries(key);
for (Map.Entry<Object, Object> entry : keyvalueMap.entrySet()) {
System.out.println("key-value = " + entry.getKey() + "-" + entry.getValue());
}
System.out.println("keySet = " + keySet);
System.out.println("keyvalueMap = " + keyvalueMap);
}
This is the result printed in the console:
score = null
keySet = []
keyvalueMap = {}
And here is the repository:
public interface GamestatsRepository extends CrudRepository<GameStats, Long>{
}

How to use Generic Repository for SOAP in Xamarin Form

I used Generic Repository in my sample project in Xamrin form to get data from api.
so my question is how can I make the following code Repository for soap webervice to become generic. so that the If you know of an example or a blog post please point me to the right direction
it is my Sample code:
public interface IGenericRepository
{
Task<T> GetAsync<T>(string uri, string authToken = "");
}
and impeliment interface:
public class GenericRepository: IGenericRepository
{
public async Task<T> GetAsync<T>(string uri, string authToken = "")
{
try
{
HttpClient httpClient = CreateHttpClient(uri);
string jsonResult = string.Empty;
var responseMessage = await Policy
.Handle<WebException>(ex =>
{
Debug.WriteLine($"{ex.GetType().Name + " : " + ex.Message}");
return true;
})
.WaitAndRetryAsync
(
5,
retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))
)
.ExecuteAsync(async () => await httpClient.GetAsync(uri));
if (responseMessage.IsSuccessStatusCode)
{
jsonResult =
await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
var json = JsonConvert.DeserializeObject<T>(jsonResult);
return json;
}
if (responseMessage.StatusCode == HttpStatusCode.Forbidden ||
responseMessage.StatusCode == HttpStatusCode.Unauthorized)
{
throw new ServiceAuthenticationException(jsonResult);
}
throw new HttpRequestExceptionEx(responseMessage.StatusCode, jsonResult);
}
catch (Exception e)
{
Debug.WriteLine($"{ e.GetType().Name + " : " + e.Message}");
throw;
}
}
}

Ballerina : How to send attachment with email

I am using wso2/gmail package to send an email notification. According to the documentation (https://central.ballerina.io/wso2/gmail) we can send an attachment with the mail through the package. However, when I try to define attachment paths as a parameter, I get an error as follows.
incompatible types: expected 'wso2/gmail:0.9.7:AttachmentPath', found 'string'
What is AttachmentPath type? Can we parse string array of attachment paths to AttachmentPath? Here is my function to send mail.
import wso2/gmail;
import ballerina/io;
import ballerina/log;
import ballerina/config;
import ballerina/http;
function sendErrorLogMail(string senderEmail, string recipientEmail, string subject, string messageBody) returns boolean {
endpoint gmail:Client gmailErrorClient {
clientConfig:{
auth:{
accessToken:config:getAsString("gmailApiConfiguration.accessToken"),
refreshToken:config:getAsString("gmailApiConfiguration.refreshToken"),
clientId:config:getAsString("gmailApiConfiguration.clientId"),
clientSecret:config:getAsString("gmailApiConfiguration.clientSecret")
}
}
};
gmail:MessageRequest messageRequest;
messageRequest.recipient = recipientEmail;
messageRequest.sender = senderEmail;
messageRequest.subject = subject;
messageRequest.messageBody = messageBody;
messageRequest.contentType = gmail:TEXT_HTML;
//What is the attachment path?
AttachmentPath attachmentPath = "./org/wso2/logs/loginfo.txt";
messageRequest.attachmentPaths = attachmentPath;
var sendMessageResponse = gmailErrorClient->sendMessage(senderEmail, untaint messageRequest);
string messageId;
string threadId;
match sendMessageResponse {
(string, string) sendStatus => {
(messageId, threadId) = sendStatus;
log:printInfo("Sent email to " + recipientEmail + " with message Id: " + messageId + " and thread Id:"
+ threadId);
return true;
}
gmail:GmailError e => {
log:printInfo(e.message);
return false;
}
}
}
Yes. As #pasan has mentioned, AttachmentPath is a record. Following is the updated code if someone wants to refer.
function sendErrorLogMail(string senderEmail, string recipientEmail, string subject, string messageBody) returns boolean {
endpoint gmail:Client gmailErrorClient {
clientConfig:{
auth:{
accessToken:config:getAsString("gmailApiConfiguration.accessToken"),
refreshToken:config:getAsString("gmailApiConfiguration.refreshToken"),
clientId:config:getAsString("gmailApiConfiguration.clientId"),
clientSecret:config:getAsString("gmailApiConfiguration.clientSecret")
}
}
};
gmail:AttachmentPath attachmentPath= {
attachmentPath:"./org/wso2/logs/loginfo.txt",
mimeType:"Text/plain"
};
gmail:MessageRequest messageRequest;
messageRequest.recipient = recipientEmail;
messageRequest.sender = senderEmail;
messageRequest.subject = subject;
messageRequest.messageBody = messageBody;
messageRequest.contentType = gmail:TEXT_HTML;
messageRequest.attachmentPaths = [attachmentPath];
var sendMessageResponse = gmailErrorClient->sendMessage(senderEmail, untaint messageRequest);
string messageId;
string threadId;
match sendMessageResponse {
(string, string) sendStatus => {
(messageId, threadId) = sendStatus;
log:printInfo("Sent email to " + recipientEmail + " with message Id: " + messageId + " and thread Id:"
+ threadId);
return true;
}
gmail:GmailError e => {
log:printInfo(e.message);
return false;
}
}
}
AttachmentPath is defined in [wso2/gmail][1] as a record. The attachmentPaths field needs an array of such AttachmentPath objects. So following should work.
gmail:AttachmentPath attachmentPath= {
attachmentPath:"./org/wso2/logs/loginfo.txt",
mimeType:"text/plain"
};
messageRequest.attachmentPaths = [attachmentPaths];

Asp.net web api json interraction

Hi there i am developing an azure web api and my put method is below
public string[] Put(SampleRequest request)
{
//Getting Request initials
string[] filmNames = request.Inputs.FilmIds;
int userAge = request.Inputs.UserAge;
char userGender = request.Inputs.UserGender;
int userId = request.Inputs.UserId;
.
.
. Doesnt matter rest of them...
When i tried to communicate with json the request(which is a SampleRequest object) in my put method is getting null so that i cannot parse it to get the data in it, what would be the problem ? My data model,help page json format and my json request(which is in another app) is below
public class SampleRequest
{
public InputsRequest Inputs { get; set; }
}
public class InputsRequest
{
public int UserId { get; set; }
public int UserAge { get; set; }
public char UserGender { get; set; }
public string[] FilmIds { get; set; }
}
application/json, text/json [ API HELP PAGE ]
Sample:
{
"Inputs": {
"UserId": 1,
"UserAge": 2,
"UserGender": "A",
"FilmIds": [
"sample string 1",
"sample string 2"
]
}
}
my request from other app:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:5291/api/values");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "PUT";
var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream());
string json = "{"+"\"Inputs\""+":"+"{"+ "\"UserId\"" + ":" + "12345" + ","
+ "\"UserAge\"" + ":" + "23" + ","
+ "\"UserGender\"" + ":" + "\"M\"" + ","
+ "\"FilmIds\"" + ":" +
"[\"Kung Fu Panda\",\"I Am Legend\",\"I Am Number Four\"]"+
"}"+"}";
streamWriter.Write(json);
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
}
Quick Note: Yes i know the name is FilmIds but i am getting Film names :D dont worry about it
This problem is coming from async methods , the reason behind getting null from put function is that the test application is not sending all of its messages so that the put method gets nothing , solution is using Putasync method below
using (var htc = new HttpClient())
{
var res = await htc.PutAsync("http://localhost:5291/api/values", new StringContent(serializedObject, Encoding.UTF8, "application/json"));
}

Java Code - ArrayIndexOutofBoundsException

I have written the following code and keep running into this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at yournamep3.Yournamep3test.main(Yournamep3test.java:23)
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
public class Yournamep3test {
public static void main(String[] args) {
// Check if target file exists
File targetFile = new File(args[0]);
try {
PrintWriter out = new PrintWriter(targetFile);
out.write("\r\nStringed musical Instrument program");
for (int arrayIndex = 0; arrayIndex < 10; arrayIndex++) {
out.write("\r\n\r\n");
out.write("\r\nCreating new Stringed Musical Instrument object now..............");
Yournamep3 violinInstrument = new Yournamep3();
violinInstrument.setNameOfInstrument("Violin # " + (arrayIndex+1));
out.write("\r\nCreated instrument with name - "
+ violinInstrument.getNameOfInstrument());
int num = violinInstrument.getNumberOfStrings();
out.write("\r\nNumber of strings in instrument is " + num);
out.write("\r\nNames of String are ");
String strings[] = violinInstrument.getStringNames();
for (int counter = 0; counter < num; counter++) {
out.write("\r\n" + strings[counter]);
}
out.write("\r\nIs the Instrument playing - "
+ violinInstrument.isPlaying());
out.write("\r\nIs the Instrument tuned - "
+ violinInstrument.isTuned());
out.write("\r\nTuning now.........");
violinInstrument.setTuned(true);
out.write("\r\nIs the Instrument tuned - "
+ violinInstrument.isTuned());
out.write("\r\nCalling the Instrument play method now..");
violinInstrument.startPlayInstrument();
out.write("\r\nIs the Instrument playing - "
+ violinInstrument.isPlaying());
out.write("\r\nStopping playing of instrument..............");
violinInstrument.stopPlayInstrument();
out.write("\r\nIs the Instrument playing - "
+ violinInstrument.isPlaying());
}
out.close();
} catch (IOException e) {
}
}
}
I think the issue is with line 23. Any advice would be appreciated, thanks.
This is the other part of the code yournamep3
public class Yournamep3 {
//fields to determine if the instrument is isTuned,
private boolean isTuned;
//and if the instrument is currently isPlaying.
private boolean isPlaying;
private String name;
private int numberOfStrings = 4; // number of strings
private String nameofStringsInInstrument[] = {"E", "C", "D", "A"}; //an array of string names
//A constructor method that set the isTuned and currently isPlaying fields to false.
public Yournamep3() {
this.isTuned = false;
this.isPlaying = false;
}
/**
* #return the name
*/
public String getNameOfInstrument() {
return name;
}
/**
* #param name the name to set
*/
public void setNameOfInstrument(String nameOfInstrument) {
this.name = nameOfInstrument;
}
// Other methods
public boolean isPlaying() {
return isPlaying;
}
public void setPlaying(boolean playing) {
this.isPlaying = playing;
}
public boolean isTuned() {
return isTuned;
}
public void setTuned(boolean isTuned) {
this.isTuned = isTuned;
}
public void startPlayInstrument() {
System.out.println("The Instrument is now Playing.");
isPlaying = true;
}
public void stopPlayInstrument() {
System.out.println("The Instrument is not Playing anymore.");
isPlaying = false;
}
public void startTuneInstrument() {
System.out.println("The Instrument is Tuned.");
isTuned = true;
}
public void stopTuneInstrument() {
System.out.println("The Instrument is not Tuned.");
isTuned = false;
}
public int getNumberOfStrings() {
return this.numberOfStrings ;
}
public String[] getStringNames() {
return nameofStringsInInstrument;
}
}
I would look at your getStringNames() method for your violinInstrument. It seems to me that it isn't populating your String array properly, or the getNumberOfStrings() method does not give the right number of strings. If you put the code for that up, I can help a bit more.
Line 23 appears to be
Yournamep3 violinInstrument = new Yournamep3();
If that's the case you should check the constructor for Yournamemp3
Since Line 23 is
File targetFile = new File(args [0]);
It indicates that your args object is empty. ArrayIndexOutOfBoundException is thrown to indicate that an array has been accessed with an illegal index. 0 is an illegal index.

Resources