I extend ComboBox and in constructor have such code:
ModelType type = new ModelType();
type.setRoot("data");
type.addField("id", "id");
type.addField("name", "name");
JsonLoadResultReader<ListLoadResult<ModelData>> reader = new JsonLoadResultReader<ListLoadResult<ModelData>>(type);
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, "/category/getall");
HttpProxy<String> proxy = new HttpProxy<String>(builder);
BaseListLoader<ListLoadResult<ModelData>> loader = new BaseListLoader<ListLoadResult<ModelData>>(proxy, reader);
ListStore<ModelData> store = new ListStore<ModelData>(loader);
setStore(store);
loader.load();
setValueField("id");
setDisplayField("name");
setName("categoty");
Result: ajax query send to server but no results see in combobox but when click on it it loads data again and then display it, and how to set value to combobox?
I've created a simple store factory method that should solve your issue.
Copy in your class and create the store:
setStore(_createListStore("/category/getall", "data", "id", "name"));
loader.load();
setValueField("id");
setDisplayField("name");
setName("categoty");
the error in your code is that you add two fields to the ModelType, instead you should add just one field with "id" as value and "name" as display
protected ListStore<ModelData> _createListStore(String url, String root, String fieldValue, String displayValue){
ModelType mt = new ModelType();
mt.setRoot(root);
mt.addField(displayValue, fieldValue);
RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, url);
HttpProxy<String> proxy = new HttpProxy<String>(rb);
JsonLoadResultReader<ListLoadResult<ModelData>> reader = new JsonLoadResultReader<ListLoadResult<ModelData>>(mt);
final BaseListLoader<ListLoadResult<ModelData>> loader = new BaseListLoader<ListLoadResult<ModelData>>(proxy, reader);
ListStore<ModelData> store = new ListStore<ModelData>(loader);
return store;
}
Related
I am trying to pass a collection to Freemarker:
My Recipient inner class:
#Data
private class Recipient {
private String phone;
private String languageValue;
}
My template:
<#list recipients as recipient>
{
"address": "${recipient.phone}",
"language": "en"
}
</#list>
My Java code:
List <Recipient> recipientList = new ArrayList <> ();
Recipient r = new Recipient();
r.setPhone("123");
recipientList.add(r);
Template template = new Template("name", new StringReader(myTemplate), new Configuration());
Writer out = new StringWriter();
Map<String, Object> dataModel = new HashMap<>();
dataModel.put("recipients", recipientList);
template.process(dataModel, out);
But I am getting this error:
[pool-1-thread-7] freemarker.runtime: Error executing FreeMarker template freemarker.core.InvalidReferenceException: The following has evaluated to null or missing:==> recipient.phone [in template "name" at line 1, column 220]
What's wrong? Please help. Thanks.
I am a receiving a JSON object and I need to save the values to my DB. But I'm having an issue figuring out how to retrieve the particular values in the JSON object.
In this case, I want to retrieve the values of 'originationNumber' and 'messageBody'
The response object -
{"originationNumber":"***","destinationNumber":"***","messageKeyword":"KEYWORD_***","messageBody":"Answer ","previousPublishedMessageId":"1slamq6mdpucd8q4i7iabf1sikc629ga253tr6o0","inboundMessageId":"88bc02fc-aff3-4277-ac1d-f27b6d3b6abb"}
Method to receive message -
public String getReceivedMessages(Messaging receivedMessage) {
BasicAWSCredentials awsCredentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey);
AmazonSQS sqsClient = AmazonSQSClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(awsCredentials))
.withRegion(String.valueOf(awsRegion)).build();
StringBuilder sb = new StringBuilder();
String queueUrl = "https://sqs.us-east-1.amazonaws.com/1234567/GetReceivedMessages";
List<Message> messages = sqsClient.receiveMessage(new ReceiveMessageRequest(queueUrl)
.withMaxNumberOfMessages(1).withWaitTimeSeconds(20)).getMessages();
for (Message message : messages) {
sb.append(message.getBody());
sqsClient.deleteMessage(queueUrl, message.getReceiptHandle());
}
// Save messages to DB
String userId = connectionRequestRepository.getUserId();
Date date = new Date();
Timestamp now = new Timestamp(date.getTime());
receivedMessage.setUserId(userId);
receivedMessage.setOriginationNumber("");
receivedMessage.setDestinationNumber("***");
receivedMessage.setMessageBody("");
receivedMessage.setMessageType("RECEIVED");
receivedMessage.setCreatedAt(now);
messagingRepository.save(receivedMessage);
System.out.println(sb); <--- Prints response object to console
return sb.toString();
}
You can use jackson library for that.
Solution 1: You can use ObjectMapper as below:
Message Class to map JSON to Java Object:
public class Message {
private String originationNumber;
private String messageBody;
// public getter and setters methods
}
Create Object From JSON String:
Message message = null;
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try {
message = objectMapper.readValue(payload, Message.class);
} catch (JsonProcessingException e) {
// Log Or do some action as per need
}
Here message will have those values. DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES is used here to skip exception as there are other fields also in JSON and not present in Java Class (as we don't need them).
Solution 2: Alternatively you can use JsonNode from same Jackson library and read nodes one by one as below:
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree("{\"originationNumber\":\"***\",\"destinationNumber\":\"***\",\"messageKeyword\":\"KEYWORD_***\",\"messageBody\":\"Answer \",\"previousPublishedMessageId\":\"1slamq6mdpucd8q4i7iabf1sikc629ga253tr6o0\",\"inboundMessageId\":\"88bc02fc-aff3-4277-ac1d-f27b6d3b6abb\"}");
String originationNumber = actualObj.get("originationNumber");
String messageBody = actualObj.get("messageBody");
In this approach you won't need to create Message class.
You can convert the json string into a json object
https://www.javatpoint.com/how-to-convert-string-to-json-object-in-java
String string = "{\"originationNumber\":\"***\",\"destinationNumber\":\"***\",\"messageKeyword\":\"KEYWORD_***\",\"messageBody\":\"Answer \",\"previousPublishedMessageId\":\"1slamq6mdpucd8q4i7iabf1sikc629ga253tr6o0\",\"inboundMessageId\":\"88bc02fc-aff3-4277-ac1d-f27b6d3b6abb\"}";
JSONObject json = new JSONObject(string);
System.out.println(json.toString());
String destinationNumber = json.getString("destinationNumber");
System.out.println(destinationNumber);
where ur json like
{"originationNumber":"***",
"destinationNumber":"***",
"messageKeyword":"KEYWORD_***",
"messageBody":"Answer","previousPublishedMessageId":"1slamq6mdpucd8q4i7iabf1sikc629ga253tr6o0",
"inboundMessageId":"88bc02fc-aff3-4277-ac1d-f27b6d3b6abb"
}
it like
"key":Value
i think ur code will be like
receivedMessage.setUserId(userId);
receivedMessage.setOriginationNumber("originationNumber");
receivedMessage.setDestinationNumber("destinationNumber");
receivedMessage.setMessageBody("messageBody");
receivedMessage.setMessageType("RECEIVED");
receivedMessage.setCreatedAt(now);
messagingRepository.save(receivedMessage);
So I have a json file that has some request and response data, and what I want to accomplish is iterate through this data and create a pact file that uses each request and response.
So at the moment I am using a parameterized test in junit to kinda iterate through our json data, and this basically works except for because the producer name is the same for all pacts, it creates the same file and is overwriting the previous.
private JsonObject requestObject;
private static Gson gson = new Gson();
private static File jsonFile = readJsonFile();
private static int randValue = new Random().nextInt(500);
private static String consmerName = "phx-ev-consumer" + randValue;
#Rule
public PactProviderRuleMk2 provider = new PactProviderRuleMk2("phx-ev-svc-provider", "localhost", 8080, this);
final RestTemplate restTemplate = new RestTemplate();
public EligibilityApiConsumerPactTest(JsonObject requestObject) {
this.requestObject = requestObject;
}
#Parameterized.Parameters
public static Collection primeNumbers() throws JsonSyntaxException, JsonIOException, FileNotFoundException {
return getJson();
}
#Pact(state = "provider accets submit contact form", provider = "phx-ev-svc-provider" , consumer = "phx-ev-consumer")
public RequestResponsePact createFragment(PactDslWithProvider builder) {
Map<String, String> requestHeaders = new HashMap<>();
requestHeaders.put("Content-Type", "application/json");
requestHeaders.put("SM_USER", "wtadmin");
requestHeaders.put("Cookie", "SMCHALLENGE=YES");
// Auth headers
String authString = "wtadmin:labcorp1";
String authEncoded = Base64.getEncoder().encodeToString(authString.getBytes());
requestHeaders.put("Authorization", "Basic " + authEncoded);
Map<String, String> responseHeaders = new HashMap<>();
responseHeaders.put("Content-Type", "application/json");
String jsonRequest = requestObject.get("request").toString();
String jsonResponse = requestObject.get("response").toString();
RequestResponsePact pact = builder.given("phx-eligibility").uponReceiving("Phoenix Eligibility Request")
.method("POST").headers(requestHeaders).body(jsonRequest).path("/phx-rest/eligibility")
.willRespondWith().status(200).headers(responseHeaders).body(jsonResponse).toPact();
return pact;
}
#Test
#PactVerification("phx-ev-svc-provider")
public void runTest() throws IOException {
MultiValueMap<String, String> requestHeaders = new LinkedMultiValueMap<>();
requestHeaders.add("Content-Type", "application/json");
requestHeaders.add("SM_USER", "wtadmin");
requestHeaders.add("Cookie", "SMCHALLENGE=YES");
// Auth headers
String authString = "wtadmin:labcorp1";
String authEncoded = Base64.getEncoder().encodeToString(authString.getBytes());
requestHeaders.add("Authorization", "Basic " + authEncoded);
String jsonRequest = requestObject.get("request").toString();
restTemplate.exchange(provider.getConfig().url() + "/phx-rest/eligibility", HttpMethod.POST,
new HttpEntity<>(jsonRequest, requestHeaders), String.class);
}
public static List<JsonObject> getJson() throws JsonSyntaxException, JsonIOException, FileNotFoundException {
List<JsonObject> results = new ArrayList<JsonObject>();
JsonObject jsonObject = gson.fromJson(new FileReader(jsonFile), JsonObject.class);
JsonArray input = jsonObject.getAsJsonArray("input");
Iterator<JsonElement> iter = input.iterator();
while (iter.hasNext()) {
JsonObject obj = (JsonObject) iter.next();
results.add(obj);
}
return results;
}
public static File readJsonFile() {
File base = new File("");
File inputFile = new File(base.getAbsolutePath() + "/pact/input/eligibility.json");
return inputFile;
}
Not sure if there is a better way to accomplish this, I have looked at the Github for Pact Jvm and looked through stack overflow but have not been able to find someone creating pact files, without statically specifying all of the data.
A Pact file is essentially a JSON document that contains details about a consumer, a provider and a list of interactions. In your case, you seems to have the same consumer and provider, but a JSON file with the requests and responses that make up the interactions.
So you need to create a single pact file, but with an interaction added for each item in your JSON file.
There are a number of ways you can do that, but if you modify your example test, you can chain the calls using the DSL builder by calling .uponReceiving again after the last .body. You can do this in a loop, each additional call to .uponReceiving will start adding a new interaction to the pact. You will have to give each interaction a unique description.
Then call .toPact() at the end to create the final pact.
I created a csv file with three columns in a row..in google bigquery in created a dataset with one table with csv file ....for this i completed my java code...but now i have to add a new column to existed row dynamically in java code..?
// Main method for data print.
#SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) throws IOException, InterruptedException {
// Create a new BigQuery client authorized via OAuth 2.0 protocol
Bigquery bigquery = createAuthorizedClient();
TableRow row = new TableRow();
row.set("Column1", "Sample23");
row.set("Column2", 7);
row.set("Column3", "Sample25");
TableDataInsertAllRequest.Rows rows = new TableDataInsertAllRequest.Rows();
rows.setJson(row);
List rowList = new ArrayList();
rowList.add(rows);
TableDataInsertAllRequest content =
new TableDataInsertAllRequest().setRows(rowList);
TableDataInsertAllResponse response = bigquery.tabledata().insertAll(PROJECT_ID, DATASET_ID, TABLE_ID, content).execute();
System.out.println("Final response = " + response);
}
There are two table operations Update and Patch.
You need to use the Update command, to add new columns to your schema.
Important side notes:
order is important. If you change the ordering, it will look like an incompatible schema.
you can only add new fields at the end of the table. On the old columns, you have the option to change required to nullable.
you cannot add a required field to an existing schema.
you cannot remove old fields, once a table's schema has been specified you cannot change it without first deleting all the of the data associated with it. If you want to change a table's schema, you must specify a writeDisposition of WRITE_TRUNCATE. For more information, see the Jobs resource.
Here is an example of a curl session that adds fields to a schema. It should be relatively easy to adapt to Java. It uses auth.py from here
When using Table.Update(), you must include the full table schema again. If you don't provide an exact matching schema you can get: Provided Schema does not match Table. For example I didn't paid attention to details and in one of my update calls I didn't include an old field like created and it failed.
Actually I didn't use any jobs in my java code. I simply created a dataset with one table with a row in three columns. Now I have to add new column at java code not in csv file. I am posting my complete source code:
public class BigQueryJavaGettingStarted {
// Define required variables.
private static final String PROJECT_ID = "nvjsnsb";
private static final String DATASET_ID = "nvjjvv";
private static final String TABLE_ID = "sampledata";
private static final String CLIENTSECRETS_LOCATION = "client_secrets.json";
static GoogleClientSecrets clientSecrets = loadClientSecrets(CLIENTSECRETS_LOCATION);
// Static variables for API scope, callback URI, and HTTP/JSON functions
private static final List<String> SCOPES = Arrays.asList(BigqueryScopes.BIGQUERY);
private static final String REDIRECT_URI = "https://www.example.com/oauth2callback";
// Global instances of HTTP transport and JSON factory objects.
private static final HttpTransport TRANSPORT = new NetHttpTransport();
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
private static GoogleAuthorizationCodeFlow flow = null;
// Main method for data print.
#SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) throws IOException, InterruptedException {
// Create a new BigQuery client authorized via OAuth 2.0 protocol
Bigquery bigquery = createAuthorizedClient();
TableRow row = new TableRow();
row.set("Column1", "OneMoreCol1");
row.set("Column2", 79);
row.set("Column3", "OneMoreCol2");
TableDataInsertAllRequest.Rows rows = new TableDataInsertAllRequest.Rows();
rows.setJson(row);
List rowList = new ArrayList();
rowList.add(rows);
TableDataInsertAllRequest content = new TableDataInsertAllRequest().setRows(rowList);
TableDataInsertAllResponse response = bigquery.tabledata().insertAll(PROJECT_ID, DATASET_ID, TABLE_ID, content).execute();
System.out.println("Final response = " + response);
}
// Create Authorized client.
public static Bigquery createAuthorizedClient() throws IOException {
String authorizeUrl = new GoogleAuthorizationCodeRequestUrl(
clientSecrets,
REDIRECT_URI,
SCOPES).setState("").build();
System.out.println("Paste this URL into a web browser to authorize BigQuery Access:\n" + authorizeUrl);
System.out.println("... and type the code you received here: ");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String authorizationCode = in.readLine();
// Exchange the auth code for an access token and refresh token
Credential credential = exchangeCode(authorizationCode);
return new Bigquery(TRANSPORT, JSON_FACTORY, credential);
}
// Exchange code method.
static Credential exchangeCode(String authorizationCode) throws IOException {
GoogleAuthorizationCodeFlow flow = getFlow();
GoogleTokenResponse response =
flow.newTokenRequest(authorizationCode).setRedirectUri(REDIRECT_URI).execute();
return flow.createAndStoreCredential(response, null);
}
// Get flow.
static GoogleAuthorizationCodeFlow getFlow() {
if (flow == null) {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport,
jsonFactory,
clientSecrets,
SCOPES)
.setAccessType("offline").setApprovalPrompt("force").build();
}
return flow;
}
// Load client secrets.
private static GoogleClientSecrets loadClientSecrets(String clientSecretsLocation) {
try {
clientSecrets = GoogleClientSecrets.load(new JacksonFactory(),
new InputStreamReader(BigQueryJavaGettingStarted.class.getResourceAsStream(clientSecretsLocation)));
} catch (Exception e) {
System.out.println("Could not load client_secrets.json");
e.printStackTrace();
}
return clientSecrets;
}
}
I'm trying to serialize a hierarchy of objects using jackson, but I must use different fields in each controller method. Currently, I do this:
#RequestMapping(value = "/chat/message/create",
headers = "Accept=application/json",
produces = MediaType.APPLICATION_JSON_VALUE,
method = RequestMethod.GET
)
#Transactional
public #ResponseBody
ChatMessage createChatMessage(#RequestParam("chat_id") Integer chatId,
#RequestParam("chat_from_id") Integer chatFromId,
#RequestParam("chat_content") String content) {
User fromUser = userDAO.find(User.class, chatFromId);
ChatMessage message = new ChatMessage();
message.setContent(content);
message.setLastUpdateDate(new Date());
message.setFromUser(fromUser);
Chat chat = chatDAO.find(Chat.class, chatId);
message.setChat(chat);
chatMessageDAO.save(message);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
FilterProvider filters = new SimpleFilterProvider()
.addFilter("chatMessageFilter", SimpleBeanPropertyFilter.serializeAllExcept(Collections.EMPTY_SET));
ObjectWriter writer = mapper.writer(filters);
try {
return writer.writeValueAsString(message);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
The problem is I want to use MappingJackson2HttpMessageConverter, but I cannot find a way to set the filter provider of list of beanpropertyfilters on it. I WANT to do something like this:
#RequestMapping(value = "/chat/message/create",
headers = "Accept=application/json",
produces = MediaType.APPLICATION_JSON_VALUE,
method = RequestMethod.GET
)
#Transactional
public #ResponseBody
ChatMessage createChatMessage(#RequestParam("chat_id") Integer chatId,
#RequestParam("chat_from_id") Integer chatFromId,
#RequestParam("chat_content") String content) {
User fromUser = userDAO.find(User.class, chatFromId);
ChatMessage message = new ChatMessage();
message.setContent(content);
message.setLastUpdateDate(new Date());
message.setFromUser(fromUser);
Chat chat = chatDAO.find(Chat.class, chatId);
message.setChat(chat);
chatMessageDAO.save(message);
getFilterProvider().addFilter("chatMessageFilter", SimpleBeanPropertyFilter.serializeAllExcept(Collections.EMPTY_SET));
return message;
}
The getFilterProvider() would get the FilterProvider that is used by MappingJackson2HttpMessageConverter. That way, I would set 5 or 6 filters in one method, and a completely different set of filters in another method.
Note: Json views will not help me here. They are way too static, and I can't combine to specify which views to use for nested objects.