I am currently using the jackson gwt library and I was wondering how I can access values that are nested within a json string. My current setup code looks like this:
public static interface PremiumMapper extends ObjectMapper<Premium> {}
public static class Premium {
public float getFaceAmount() {
return faceAmount;
}
public void setFaceAmount(float faceAmount) {
this.faceAmount = faceAmount;
}
public float getStart() {
return start;
}
public void setStart(float start) {
this.start = start;
}
public float getEnd() {
return end;
}
public void setEnd(float end) {
this.end = end;
}
public float start;
public float end;
public float faceAmount;
}
while my access code looks like this:
String json = "{\"errorCode\":\"validation.failed\",\"statusCode\":400,\"details\":[{\"code\":\"targetPremium.monthlyPremiumsCents.outOfBounds\",\"validChoices\":[{\"start\":9450,\"end\":125280}]}]}";
PremiumMapper mapper = GWT.create( PremiumMapper.class );
Premium premium = mapper.read( json );
System.out.println("VALUES OUTPUTTED: " + premium.getStart());
How am I able to get the start value within the json string?
Try This as your Premium class:
-----------------------------------com.example.Premium.java-----------------------------------
package com.example;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Premium {
private String errorCode;
private Integer statusCode;
private List<Detail> details = null;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public Integer getStatusCode() {
return statusCode;
}
public void setStatusCode(Integer statusCode) {
this.statusCode = statusCode;
}
public List<Detail> getDetails() {
return details;
}
public void setDetails(List<Detail> details) {
this.details = details;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
-----------------------------------com.example.Detail.java-----------------------------------
package com.example;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Detail {
private String code;
private List<ValidChoice> validChoices = null;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public List<ValidChoice> getValidChoices() {
return validChoices;
}
public void setValidChoices(List<ValidChoice> validChoices) {
this.validChoices = validChoices;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
-----------------------------------com.example.ValidChoice.java-----------------------------------
package com.example;
import java.util.HashMap;
import java.util.Map;
public class ValidChoice {
private Integer start;
private Integer end;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
public Integer getStart() {
return start;
}
public void setStart(Integer start) {
this.start = start;
}
public Integer getEnd() {
return end;
}
public void setEnd(Integer end) {
this.end = end;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
And get start value like this: premium.getDetails().get(0).getValidChoices(0).getStart()
Related
Kindly help me to get the subnodes list inside bom attributes
JSON file
[
{
"subConfigId":"bac",
"totalPrice":"634.00",
"bom":{
"ucid":"ucid",
"type":"RootNode",
"attributes":{
"visible":true,
"price_status":"SUCCESS"
},
"subnodes":[
{
"description":"Enterprise Shock Rack",
"ucid":"ucid"
},
{
"description":"SVC",
"ucid":"ucid"
}
]
},
"breakdown":{
"SV":550.0,
"HW":6084.0
},
"currency":"USD"
}
]
GsonNodes.java
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
public class GsonNodes {
public static void main(String[] args) throws IOException {
try{
JsonElement je = new JsonParser().parse(new FileReader(
"C:/Desktop/json.txt"));
JsonArray ja = je.getAsJsonArray();
Iterator itr = ja.iterator();
while(itr.hasNext()){
JsonElement je1 = (JsonElement) itr.next();
Gson gson = new Gson();
Details details = gson.fromJson(je1, Details.class);
System.out.println(details.getSubConfigId());
System.out.println(details.getCurrency());
System.out.println(details.getBreakdown());
System.out.println(details.getTotalPrice());
System.out.println(details.getBom().getUcid());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Details.java POJO
import java.io.Serializable;
import java.util.Map;
public class Details implements Serializable{
private String subConfigId;
private String totalPrice;
private Bom bom;
private String currency;
private Map<String, String> breakdown;
public String getSubConfigId() {
return subConfigId;
}
public void setSubConfigId(String subConfigId) {
this.subConfigId = subConfigId;
}
public String getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(String totalPrice) {
this.totalPrice = totalPrice;
}
public Bom getBom() {
return bom;
}
public void setBom(Bom bom) {
this.bom = bom;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public Map<String, String> getBreakdown() {
return breakdown;
}
public void setBreakdown(Map<String, String> breakdown) {
this.breakdown = breakdown;
}
}
Bom.java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class Bom implements Serializable{
private String ucid;
private String type;
private Map<String, String> attributes;
private List<Subnodes> subnodes = new ArrayList<Subnodes>();
public String getUcid() {
return ucid;
}
public void setUcid(String ucid) {
this.ucid = ucid;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Map<String, String> getAttributes() {
return attributes;
}
public void setAttributes(Map<String, String> attributes) {
this.attributes = attributes;
}
#Override
public String toString(){
return getUcid() + ", "+getType()+", "+getAttributes();
}
}
Subnodes.java
import java.io.Serializable;
import java.util.Map;
public class Subnodes implements Serializable{
private String description;
private String ucid;
private Map<String, String> attributes;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUcid() {
return ucid;
}
public void setUcid(String ucid) {
this.ucid = ucid;
}
public Map<String, String> getAttributes() {
return attributes;
}
public void setAttributes(Map<String, String> attributes) {
this.attributes = attributes;
}
}
I am getting an error , when i try to get the "subnodes"
I added the following code in the class
private List<Subnodes> subnodes = new ArrayList<Subnodes>();
then i am getting the error "Expected STRING but was BEGIN_ARRAY"
kindly help me that how can i get the "subnodes" list
In Bom.java
Please add a getter/setter method for :
private List<Subnodes> subnodes = new ArrayList<Subnodes>();
public List<Subnodes> getSubnodes() {
return subnodes;
}
public void setSubnodes(List<Subnodes> subnodes) {
this.subnodes = subnodes;
}
i have tried as below .. this is working fine.
package com.brp.mvc.util;
import java.io.IOException;
import java.util.Iterator;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
public class GsonNodes {
public static void main(String[] args) throws IOException {
try {
JsonElement je = new JsonParser().parse("[{\"subConfigId\":\"bac\",\"totalPrice\":\"634.00\",\"bom\":{\"ucid\":\"ucid\",\"type\":\"RootNode\",\"attributes\":{\"visible\":true,\"price_status\":\"SUCCESS\"},\"subnodes\":[{\"description\":\"Enterprise Shock Rack\",\"ucid\":\"ucid\"},{\"description\":\"SVC\",\"ucid\":\"ucid\"}]},\"breakdown\":{\"SV\":550.0,\"HW\":6084.0},\"currency\":\"USD\"}]");
JsonArray ja = je.getAsJsonArray();
Iterator itr = ja.iterator();
while (itr.hasNext()) {
JsonElement je1 = (JsonElement) itr.next();
Gson gson = new Gson();
Details details = gson.fromJson(je1, Details.class);
System.out.println(details.getSubConfigId());
System.out.println(details.getCurrency());
System.out.println(details.getBreakdown());
System.out.println(details.getTotalPrice());
System.out.println(details.getBom().getUcid());
System.out.println(details.getBom().getSubnodes().get(0).getDescription());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
i have added one method to convert json into string as below :
public static String readFile(String filename) {
String result = "";
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
result = sb.toString();
} catch(Exception e) {
e.printStackTrace();
}
return result;
}
and use this method like below :
JsonElement je = new JsonParser().parse(readFile("C:/Desktop/json.txt"));
just a quick question around Lambda Expressions. I have the following text:
{"hosts":[{"disks":[{"path":"/","space_used":0.608}],"hostname":"host1"},{"disks":[{"path":"/","space_used":0.79},{"path":"/opt","space_used":0.999}],"hostname":"host2"},{"disks":[{"path":"/","space_used":0.107}],"hostname":"host3"}]}
Which I'd like to format the above to each line reading:
{"hostname": "host1", "disks":["Path '/' had utilised 60.8%"]}
{"hostname": "host2", "disks":["Path '/' had utilised 79%", "Path '/opt' had utilised 99.9%"]}
{"hostname": "host3", "disks":["Path '/' had utilised 10.7%"]}
I've tried a few permutations around .stream().map() and then .collect() but somehow I came up short in getting to the output I needed. Any help is much appreciated and apologies if the question is rather n00bish. Thanks.
You could use the Jackson 2 Library to convert your JSON-String to Java objects.
In your concrete case you could e.g. create the following classes:
Disk.java
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({"path", "space_used"})
public class Disk implements Serializable {
private final static long serialVersionUID = -6127352847480270783L;
#JsonProperty("path")
private String path;
#JsonProperty("space_used")
private Double spaceUsed;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("path")
public String getPath() {
return path;
}
#JsonProperty("path")
public void setPath(String path) {
this.path = path;
}
#JsonProperty("space_used")
public Double getSpaceUsed() {
return spaceUsed;
}
#JsonProperty("space_used")
public void setSpaceUsed(Double spaceUsed) {
this.spaceUsed = spaceUsed;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
Host.java
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({"disks", "hostname"})
public class Host implements Serializable {
private final static long serialVersionUID = -1972892789688333505L;
#JsonProperty("disks")
private List<Disk> disks = null;
#JsonProperty("hostname")
private String hostname;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("disks")
public List<Disk> getDisks() {
return disks;
}
#JsonProperty("disks")
public void setDisks(List<Disk> disks) {
this.disks = disks;
}
#JsonProperty("hostname")
public String getHostname() {
return hostname;
}
#JsonProperty("hostname")
public void setHostname(String hostname) {
this.hostname = hostname;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
HostContainer.java
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({"hosts"})
public class HostContainer implements Serializable {
private final static long serialVersionUID = 7917934809738573749L;
#JsonProperty("hosts")
private List<Host> hosts = null;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("hosts")
public List<Host> getHosts() {
return hosts;
}
#JsonProperty("hosts")
public void setHosts(List<Host> hosts) {
this.hosts = hosts;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
Usage:
public void parseMessage() throws IOException {
String msg = "{\"hosts\":[{\"disks\":[{\"path\":\"/\",\"space_used\":0.608}]," +
"\"hostname\":\"host1\"},{\"disks\":[{\"path\":\"/\",\"space_used\":0.79}," +
"{\"path\":\"/opt\",\"space_used\":0.999}],\"hostname\":\"host2\"}," +
"{\"disks\":[{\"path\":\"/\",\"space_used\":0.107}],\"hostname\":\"host3\"}]}";
ObjectMapper mapper = new ObjectMapper();
// This object will contain all the information you need, access it using e.g. getHosts();
HostContainer hostContainer = mapper.readValue(msg, HostContainer.class);
}
I'm using jQuery DataTables in a Java Spring Boot project. When using DataTables's server-side processing, it sends AJAX request with request parameters like:
?columns[0][data]=0
&columns[0][name]=name
&columns[0][searchable]=true
&columns[0][orderable]=true
&columns[0][search][value]=Tom
&columns[0][search][regex]=false
&columns[1][data]=1
&columns[1][name]=address
&columns[1][searchable]=true
&columns[1][orderable]=true
&columns[1][search][value]=
&columns[1][search][regex]=false
to my server.
How can I convert these request parameters to a Java object for processing? The tutorial simply states that
In most modern server-side scripting environments this data will automatically be available to you as an array.
but I cannot find any way to do this in Java, particularly using Spring Boot's #RequestParameter.
Thank you for your help!
Create the following classes, ignore the package names
//DataTableRequest.java
package com.employee.app.model;
import java.util.*;
import com.fasterxml.jackson.annotation.*;
public class DataTableRequest {
private String draw;
private List<Column> columns;
private List<Order> order;
private String start;
private String length;
private Search search;
private String empty;
#JsonProperty("draw")
public String getDraw() { return draw; }
#JsonProperty("draw")
public void setDraw(String value) { this.draw = value; }
#JsonProperty("columns")
public List<Column> getColumns() { return columns; }
#JsonProperty("columns")
public void setColumns(List<Column> value) { this.columns = value; }
#JsonProperty("order")
public List<Order> getOrder() { return order; }
#JsonProperty("order")
public void setOrder(List<Order> value) { this.order = value; }
#JsonProperty("start")
public String getStart() { return start; }
#JsonProperty("start")
public void setStart(String value) { this.start = value; }
#JsonProperty("length")
public String getLength() { return length; }
#JsonProperty("length")
public void setLength(String value) { this.length = value; }
#JsonProperty("search")
public Search getSearch() { return search; }
#JsonProperty("search")
public void setSearch(Search value) { this.search = value; }
#JsonProperty("_")
public String getEmpty() { return empty; }
#JsonProperty("_")
public void setEmpty(String value) { this.empty = value; }
}
// Column.java
package com.employee.app.model;
import java.util.*;
import com.fasterxml.jackson.annotation.*;
public class Column {
private String data;
private String name;
private String searchable;
private String orderable;
private Search search;
#JsonProperty("data")
public String getData() { return data; }
#JsonProperty("data")
public void setData(String value) { this.data = value; }
#JsonProperty("name")
public String getName() { return name; }
#JsonProperty("name")
public void setName(String value) { this.name = value; }
#JsonProperty("searchable")
public String getSearchable() { return searchable; }
#JsonProperty("searchable")
public void setSearchable(String value) { this.searchable = value; }
#JsonProperty("orderable")
public String getOrderable() { return orderable; }
#JsonProperty("orderable")
public void setOrderable(String value) { this.orderable = value; }
#JsonProperty("search")
public Search getSearch() { return search; }
#JsonProperty("search")
public void setSearch(Search value) { this.search = value; }
}
// Search.java
package com.employee.app.model;
import java.util.*;
import com.fasterxml.jackson.annotation.*;
public class Search {
private String value;
private String regex;
#JsonProperty("value")
public String getValue() { return value; }
#JsonProperty("value")
public void setValue(String value) { this.value = value; }
#JsonProperty("regex")
public String getRegex() { return regex; }
#JsonProperty("regex")
public void setRegex(String value) { this.regex = value; }
}
// Order.java
package com.employee.app.model;
import java.util.*;
import com.fasterxml.jackson.annotation.*;
public class Order {
private String column;
private String dir;
#JsonProperty("column")
public String getColumn() { return column; }
#JsonProperty("column")
public void setColumn(String value) { this.column = value; }
#JsonProperty("dir")
public String getDir() { return dir; }
#JsonProperty("dir")
public void setDir(String value) { this.dir = value; }
}
DataTables by default sends requests as FormData, to make it send that request as Json, do the following.
$(document).ready(function() {
$('#datatableId').DataTable( {
"processing": true,
"serverSide": true,
"ajax":{
url: "your_processing_endpoint",
type:"POST",
contentType:"application/json",
data:function(d){
return JSON.stringify(d)
}
},
//include other options
} );
} );
And then in the controller action, assuming your are using Spring boot, do the following
#RequestMapping(value="your_processing_endpoint",method="RequestMethod.POST")
public ResponseEntity<?> processDataTableRequest(#RequestBody DataTableRequest
datatableRequest){
//you can add your logic here
}
I am trying to get java object from dynamic JSON.
One Important point these given classes are from third party API.
#JsonTypeInfo(
use = Id.NAME,
include = As.PROPERTY,
property = "nodeType"
)
#JsonSubTypes({ #Type(
name = "Filter",
value = Filter.class
), #Type(
name = "Criterion",
value = Criterion.class
)})
public abstract class Node {
public Node() {
}
#JsonIgnore
public EvaluationResult evaluate(Map<UUID, List<AnswerValue>> answers) {
Evaluator evaluator = new Evaluator();
return evaluator.evaluateAdvancedLogic(this, answers);
}
}
Filter.java
#JsonInclude(Include.NON_NULL)
#JsonPropertyOrder({"evaluationType", "filters"})
public class Filter extends Node {
#JsonProperty("evaluationType")
private EvaluationType evaluationType;
#NotNull
#JsonProperty("filters")
#Valid
private List<Node> filters = new ArrayList();
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap();
public Filter() {
}
#JsonProperty("evaluationType")
public EvaluationType getEvaluationType() {
return this.evaluationType;
}
#JsonProperty("evaluationType")
public void setEvaluationType(EvaluationType evaluationType) {
this.evaluationType = evaluationType;
}
#JsonProperty("filters")
public List<Node> getFilters() {
return this.filters;
}
#JsonProperty("filters")
public void setFilters(List<Node> filters) {
this.filters = filters;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
}
Criterion.java
#JsonInclude(Include.NON_NULL)
#JsonPropertyOrder({"fieldSourceType", "fieldCategoryName", "sequenceNumber", "fieldName", "values", "operator", "fieldId"})
public class Criterion extends Node {
#JsonProperty("fieldSourceType")
private FieldSourceType fieldSourceType;
#JsonProperty("fieldCategoryName")
private String fieldCategoryName;
#NotNull
#JsonProperty("sequenceNumber")
private Long sequenceNumber;
#JsonProperty("fieldName")
private String fieldName;
#JsonProperty("values")
#Valid
private List<String> values = new ArrayList();
#JsonProperty("operator")
#Valid
private Operator operator;
#NotNull
#JsonProperty("fieldId")
private UUID fieldId;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap();
public Criterion() {
}
#JsonProperty("fieldSourceType")
public FieldSourceType getFieldSourceType() {
return this.fieldSourceType;
}
#JsonProperty("fieldSourceType")
public void setFieldSourceType(FieldSourceType fieldSourceType) {
this.fieldSourceType = fieldSourceType;
}
#JsonProperty("fieldCategoryName")
public String getFieldCategoryName() {
return this.fieldCategoryName;
}
#JsonProperty("fieldCategoryName")
public void setFieldCategoryName(String fieldCategoryName) {
this.fieldCategoryName = fieldCategoryName;
}
#JsonProperty("sequenceNumber")
public Long getSequenceNumber() {
return this.sequenceNumber;
}
#JsonProperty("sequenceNumber")
public void setSequenceNumber(Long sequenceNumber) {
this.sequenceNumber = sequenceNumber;
}
#JsonProperty("fieldName")
public String getFieldName() {
return this.fieldName;
}
#JsonProperty("fieldName")
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
#JsonProperty("values")
public List<String> getValues() {
return this.values;
}
#JsonProperty("values")
public void setValues(List<String> values) {
this.values = values;
}
#JsonProperty("operator")
public Operator getOperator() {
return this.operator;
}
#JsonProperty("operator")
public void setOperator(Operator operator) {
this.operator = operator;
}
#JsonProperty("fieldId")
public UUID getFieldId() {
return this.fieldId;
}
#JsonProperty("fieldId")
public void setFieldId(UUID fieldId) {
this.fieldId = fieldId;
}
}
The json used to conversion is this.
{
"evaluationType":"AND",
"nodeType":"Criterion",
"Criterion":[
{
"fieldName":"sdada",
"values":"sdad",
"operator":{
"operatorType":"Equals"
}
},
{
"nodeType":"Criterion",
"fieldName":"dasa",
"values":"das",
"operator":{
"operatorType":"Equals"
}
},
{
"nodeType":"Criterion",
"fieldName":"dada",
"values":"dads",
"operator":{
"operatorType":"Equals"
}
}
]
}
The problem is that deserialization of this JSON fails with following error:
{
"message": "Class com.cvent.logic.model.Criterion is not assignable to com.cvent.logic.model.Filter"
}
The first part of the JSON is wrong
{
"evaluationType":"AND",
"nodeType":"Criterion",
"Criterion":[
It says that the type is Criterion but it has evaluationType from Filter.
Also, probably "Criterion" : [ should be "filters" : [
Update: After suggestion from one of the experts here, I have cleaned up the following Java code:
There is a class called MyRespModifier and it holds two inner static classes called ResponseMail and Response
I have rewritten this code Scala as an exercise. Scala version: 2.11.2. I am not happy with the results. It resembles Java, and looks like it could do with a large dose of idiomatic Scala from the ground up. I would like to accomplish a reduction in the no of lines and also on inspection of the code it should stand out as elegant Scala code.At least my goal is to understand how some Java constructs can be rewritten in idiomatic Scala.
The Scala equivalent is posted after the Java code:
import java.util.ArrayList;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.io.FileInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.http.entity.ContentType;
public class MyRespModifier {
private static final String VERSION = "1.0.0";
private static final String USER_AGENT = "myuseragent/"+ VERSION + "java";
private static final String ARG_TO = "to[%d]";
private static final String ARG_TONAME = "toname[%d]";
private static final String ARG_CC = "cc[%d]";
private static final String ARG_FROM = "from";
private static final String ARG_FROMNAME = "fromname";
private static final String ARG_REPLYTO = "replyto";
private static final String ARG_SUBJECT = "subject";
private static final String ARG_CONTENTS = "content[%s]";
private static final String ARG_MYSMTPAPI = "x-respModifierSmtpApi";
private String apikey;
private String apivalue;
private String apiUrlBasePath;
private String port;
private String endpoint;
private CloseableHttpClient client;
public MyRespModifier() {
this.apiUrlBasePath = "api/responseshaper/response";
this.endpoint = "/myapi/mymail.dispatch.json";
this.client = HttpClientBuilder.create().setUserAgent(USER_AGENT).build();
}
public MyRespModifier setUrl(String url) {
this.apiUrlBasePath = apiUrlBasePath;
return this;
}
public MyRespModifier setEndpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
public MyRespModifier setClient(CloseableHttpClient client) {
this.client = client;
return this;
}
public HttpEntity constructRespBody(ResponseEmail respEmail) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("api_user", this.apikey);
builder.addTextBody("api_key", this.apivalue);
String[] tos = respEmail.getTos();
String[] tonames = respEmail.getToNames();
String[] ccs = respEmail.getCcs();
if (tos.length == 0) {
builder.addTextBody(String.format(ARG_TO, 0), respEmail.getFrom(), ContentType.create("text/plain", "UTF-8"));
}
for (int i = 0, len = tos.length; i < len; i++)
builder.addTextBody(String.format(ARG_TO, i), tos[i], ContentType.create("text/plain", "UTF-8"));
for (int i = 0, len = tonames.length; i < len; i++)
builder.addTextBody(String.format(ARG_TONAME, i), tonames[i], ContentType.create("text/plain", "UTF-8"));
for (int i = 0, len = ccs.length; i < len; i++)
builder.addTextBody(String.format(ARG_CC, i), ccs[i], ContentType.create("text/plain", "UTF-8"));
if (respEmail.getContentIds().size() > 0) {
Iterator it = respEmail.getContentIds().entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
builder.addTextBody(String.format(ARG_CONTENTS, entry.getKey()), (String) entry.getValue());
}
}
if (respEmail.getFrom() != null && !respEmail.getFrom().isEmpty())
builder.addTextBody(ARG_FROM, respEmail.getFrom(), ContentType.create("text/plain", "UTF-8"));
if (respEmail.getFromName() != null && !respEmail.getFromName().isEmpty())
builder.addTextBody(ARG_FROMNAME, respEmail.getFromName(), ContentType.create("text/plain", "UTF-8"));
if (respEmail.getReplyTo() != null && !respEmail.getReplyTo().isEmpty())
builder.addTextBody(ARG_REPLYTO, respEmail.getReplyTo(), ContentType.create("text/plain", "UTF-8"));
if (respEmail.getSubject() != null && !respEmail.getSubject().isEmpty())
builder.addTextBody(ARG_SUBJECT, respEmail.getSubject(), ContentType.create("text/plain", "UTF-8"));
String tmpString = respEmail.respModifierSmtpApi.jsonString();
if (!tmpString.equals("{}"))
builder.addTextBody(ARG_MYSMTPAPI, tmpString, ContentType.create("text/plain", "UTF-8"));
return builder.build();
} //end of method constructRespBody
public MyRespModifier.Response send(ResponseEmail respMail) throws RespModifierException {
HttpPost httppost = new HttpPost(this.apiUrlBasePath + this.endpoint);
httppost.setEntity(this.constructRespBody(respMail));
try {
HttpResponse res = this.client.execute(httppost);
return new MyRespModifier.Response(res.getStatusLine().getStatusCode(), EntityUtils.toString(res.getEntity()));
} catch (IOException e) {
throw new RespModifierException(e);
}
}
//*********************************************************************
public static class ResponseEmail {
private MyExperimentalApi respModifierSmtpApi;
private ArrayList<String> to;
private ArrayList<String> toname;
private ArrayList<String> cc;
private String from;
private String fromname;
private String replyto;
private String subject;
private String text;
private Map<String, String> contents;
private Map<String, String> headers;
public ResponseEmail () {
this.respModifierSmtpApi = new MyExperimentalApi();
this.to = new ArrayList<String>();
this.toname = new ArrayList<String>();
this.cc = new ArrayList<String>();
this.contents = new HashMap<String, String>();
this.headers = new HashMap<String, String>();
}
public ResponseEmail addTo(String to) {
this.to.add(to);
return this;
}
public ResponseEmail addTo(String[] tos) {
this.to.addAll(Arrays.asList(tos));
return this;
}
public ResponseEmail addTo(String to, String name) {
this.addTo(to);
return this.addToName(name);
}
public ResponseEmail setTo(String[] tos) {
this.to = new ArrayList<String>(Arrays.asList(tos));
return this;
}
public String[] getTos() {
return this.to.toArray(new String[this.to.size()]);
}
public ResponseEmail addSmtpApiTo(String to) {
this.respModifierSmtpApi.addTo(to);
return this;
}
public ResponseEmail addSmtpApiTo(String[] to) {
this.respModifierSmtpApi.addTos(to);
return this;
}
public ResponseEmail addToName(String toname) {
this.toname.add(toname);
return this;
}
public ResponseEmail addToName(String[] tonames) {
this.toname.addAll(Arrays.asList(tonames));
return this;
}
public ResponseEmail setToName(String[] tonames) {
this.toname = new ArrayList<String>(Arrays.asList(tonames));
return this;
}
public String[] getToNames() {
return this.toname.toArray(new String[this.toname.size()]);
}
public ResponseEmail addCc(String cc) {
this.cc.add(cc);
return this;
}
public ResponseEmail addCc(String[] ccs) {
this.cc.addAll(Arrays.asList(ccs));
return this;
}
public ResponseEmail setCc(String[] ccs) {
this.cc = new ArrayList<String>(Arrays.asList(ccs));
return this;
}
public String[] getCcs() {
return this.cc.toArray(new String[this.cc.size()]);
}
public ResponseEmail setFrom(String from) {
this.from = from;
return this;
}
public String getFrom() {
return this.from;
}
public ResponseEmail setFromName(String fromname) {
this.fromname = fromname;
return this;
}
public String getFromName() {
return this.fromname;
}
public ResponseEmail setReplyTo(String replyto) {
this.replyto = replyto;
return this;
}
public String getReplyTo() {
return this.replyto;
}
public ResponseEmail setSubject(String subject) {
this.subject = subject;
return this;
}
public String getSubject() {
return this.subject;
}
public ResponseEmail setText(String text) {
this.text = text;
return this;
}
public String getText() {
return this.text;
}
public JSONObject getFilters() {
return this.respModifierSmtpApi.getFilters();
}
public ResponseEmail addContentId(String attachmentName, String cid) {
this.contents.put(attachmentName, cid);
return this;
}
public Map getContentIds() {
return this.contents;
}
public ResponseEmail addHeader(String key, String val) {
this.headers.put(key, val);
return this;
}
public Map getHeaders() {
return this.headers;
}
public MyExperimentalApi getSMTPAPI() {
return this.respModifierSmtpApi;
}
}
public static class Response {
private int code;
private boolean success;
private String message;
public Response(int code, String msg) {
this.code = code;
this.success = code == 200;
this.message = msg;
}
public int getCode() {
return this.code;
}
public boolean getStatus() {
return this.success;
}
public String getMessage() {
return this.message;
}
}//end of class Response
You can change the imports to save some lines
import java.util.Arrays
import java.util.HashMap
import java.util.Iterator
becomes
import java.util.{Arrays, HashMap, Iterator}
The getters and setters can be generated for you. This is a feature of a Scala class if you declare the constructor parameter with val or var.
A simplified version of your class becomes:
class ResponseEmail(var to: ArrayList[String], var cc: ArrayList[String])
This getters are cc and to and the setters are cc_= and to_=
scala> res6.
asInstanceOf cc cc_= isInstanceOf to toString to_=