To write the data into the Google spreadsheet I am using following code.
private static void writeValuesInSpreedSheet(Sheets service, String spreadsheetId, int sheetSize) throws IOException {
String range = "A"+(sheetSize+1)+":K"+(sheetSize+1);
List<List<Object>> newData = new ArrayList<>();
List<Object> rowValues = new ArrayList();
rowValues.add(getCurentDateInESTFormat());
rowValues.add("2");
rowValues.add("3");
rowValues.add("4");
rowValues.add("5");
rowValues.add("6");
rowValues.add("7");
rowValues.add("8");
rowValues.add("9");
rowValues.add("10");
rowValues.add("11");
/* List<Object> rowValues1 = new ArrayList();
rowValues1.add("1");
rowValues1.add("2");*/
newData.add(rowValues);
//newData.add(rowValues1);
// response.setValues(newData);
ValueRange oRange = new ValueRange();
oRange.setRange(range); // I NEED THE NUMBER OF THE LAST ROW
oRange.setValues(newData);
List<ValueRange> oList = new ArrayList<>();
oList.add(oRange);
BatchUpdateValuesRequest oRequest = new BatchUpdateValuesRequest();
oRequest.setValueInputOption("RAW");
oRequest.setData(oList);
BatchUpdateValuesResponse oResp1 = service.spreadsheets().values().batchUpdate(spreadsheetId, oRequest).execute();
System.out.println("Response Values " +oResp1.values());
}
private static Object getCurentDateInESTFormat() {
SimpleDateFormat sdfAmerica = new SimpleDateFormat("MM/dd/YYYY");
sdfAmerica.setTimeZone(TimeZone.getTimeZone("America/New_York"));
String sDateInAmerica = sdfAmerica.format(new Date());
return sDateInAmerica;
}
In sheet we have defined the date and currency type of respective column.
I am able to write the data but eventually its prepending ' in the data for example - '09/04/2016
Because of this we are not able to open it into date format. I have attached one screen shot as well.
We are using Google Sheets API V4.
I am asking this question because i did not find any link/solution related to it.
When using the ValueInputOption RAW you need to pass dates in the serial number format. The Apache POI library provides a getExcelDate method that will handle most of this for you, but you'll need to add a day to account for the difference in the epoch used.
Related
I have one data in excel which holds numeric value and when I am sending the same value from Excel to Soap UI properties, it's value getting converted into string like below:
In Excel:
Value of Data column is 200
In Soap UI properties:
Value of Data field is getting changed to 200.0
Can anyone help me to get the same numeric value in Soap UI properties?
FileInputStream fis = new FileInputSTream("Excel File Location");
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet Sheet = new XSSFSheet("SheetName");
int totalRows = sheet.getPhysicalNumberOfRows();
testRunner.testCase.SetPropertyvalue("totalRows",totalRows.toString())
def int totalcolumn = sheet.getrow(0).getLastCellNum();
def columns = []
def data = []
def rowIndex = testrunner.testCase.getPropertyValue("RowIndex").toInteger();
if(rowIndex<totalRows)
{
for(int i = 0;i<totalcolumn;i++)
{
colData = sheet.getRow(0).getCell(i).toString();
propdataarray.add(colData)
testData = sheet.getRow(rowIndex).getCell(i).toString();
dataArray.add(testData);
testRunner.testCase.getTestStepByName("Properties").setPropertyValue(columns.get[i],data.get[i])
}
}
As Axel Richter said, use DataFormatter.formatCellValue to correct the value from the source. Or you can use an abstraction script that works very well with Groovy that handles that for you.
As you said, SoapUI only uses string for property values. If you want to correct it on the receiving/use side, you can use this:
def propVal = '200.0'
assert propVal instanceof java.lang.String
println propVal.toFloat().toInteger()
assert propVal.toFloat().toInteger() instanceof java.lang.Integer
It is generally better to correct the format at source (before storing it in a property).
I'm sorry this question header is not 100% correct. Because of that, I'll explain my scenario here.
I created a function to merge 4 data sets into one return format. Because that's the format front-end side needed. So this is working fine now.
public ReturnFormat makeThribleLineChart(List<NameCountModel> totalCount, List<NameCountModel>,p1Count, List<NameCountModel> p2Count, List<NameCountModel> average) {
ReturnFormat returnFormat = new ReturnFormat(null,null);
try {
String[] totalData = new String[totalCount.size()];
String[] p1Data = new String[p1Count.size()];
String[] p2Data = new String[p2Count.size()];
String[] averageData = new String[p2Count.size()];
String[] lableList = new String[totalCount.size()];
for (int x = 0; x < totalCount.size(); x++) {
totalData[x] = totalCount.get(x).getCount();
p1Data[x] = p1Count.get(x).getCount();
p2Data[x] = p2Count.get(x).getCount();
averageData[x] = average.get(x).getCount();
lableList[x] = totalCount.get(x).getName();
}
FormatHelper<String[]> totalFormatHelper= new FormatHelper<String[]>();
totalFormatHelper.setData(totalData);
totalFormatHelper.setType("line");
totalFormatHelper.setLabel("Uudet");
totalFormatHelper.setyAxisID("y-axis-1");
FormatHelper<String[]> p1FormatHelper= new FormatHelper<String[]>();
p1FormatHelper.setData(p1Data);
p1FormatHelper.setType("line");
p1FormatHelper.setLabel("P1 päivystykseen heti");
FormatHelper<String[]> p2FormatHelper= new FormatHelper<String[]>();
p2FormatHelper.setData(p2Data);
p2FormatHelper.setType("line");
p2FormatHelper.setLabel("P2 päivystykseen muttei yöllä");
FormatHelper<String[]> averageFormatHelper= new FormatHelper<String[]>();
averageFormatHelper.setData(averageData);
averageFormatHelper.setType("line");
averageFormatHelper.setLabel("Jonotusaika keskiarvo");
averageFormatHelper.setyAxisID("y-axis-2");
List<FormatHelper<String[]>> formatHelpObj = new ArrayList<FormatHelper<String[]>>();
formatHelpObj.add(totalFormatHelper);
formatHelpObj.add(p1FormatHelper);
formatHelpObj.add(p2FormatHelper);
formatHelpObj.add(averageFormatHelper);
returnFormat.setData(formatHelpObj);
returnFormat.setLabels(lableList);
returnFormat.setMessage(Messages.Success);
returnFormat.setStatus(ReturnFormat.Status.SUCCESS);
} catch (Exception e) {
returnFormat.setData(null);
returnFormat.setMessage(Messages.InternalServerError);
returnFormat.setStatus(ReturnFormat.Status.ERROR);
}
return returnFormat;
}
so, as you can see here, all the formatting is hardcoded. So my question is how to automate this code for list count. Let's assume next time I have to create chart formatting for five datasets. So I have to create another function to it. That's the thing I want to reduce. So I hope you can understand my question.
Thank you.
You're trying to solve the more general problem of composing a result object (in this case ReturnFormat) based on dynamic information. In addition, there's some metadata being setup along with each dataset - the type, label, etc. In the example that you've posted, you've hardcoded the relationship between a dataset and this metadata, but you'd need some way to establish this relationship for data dynamically if you have a variable number of parameters here.
Therefore, you have a couple of options:
Make makeThribleLineChart a varargs method to accept a variable number of parameters representing your data. Now you have the problem of associating metadata with your parameters - best option is probably to wrap the data and metadata together in some new object that is provided as each param of makeThribleLineChart.
So you'll end up with a signature that looks a bit like ReturnFormat makeThribleLineChart(DataMetadataWrapper... allDatasets), where DataMetadataWrapper contains everything required to build one FormatHelper instance.
Use a builder pattern, similar to the collection builders in guava, for example something like so:
class ThribbleLineChartBuilder {
List<FormatHelper<String[]>> formatHelpObj = new ArrayList<>();
ThribbleLineChartBuilder addDataSet(String describeType, String label, String yAxisId, List<NameCountModel> data) {
String[] dataArray = ... ; // build your array of data
FormatHelper<String[]> formatHelper = new FormatHelper<String[]>();
formatHelper.setData(dataArray);
formatHelper.setType(describeType);
... // set any other parameters that the FormatHelper requires here
formatHelpObj.add(formatHelper);
return this;
}
ReturnFormat build() {
ReturnFormat returnFormat = new ReturnFormat(null, null);
returnFormat.setData(this.formatHelpObj);
... // setup any other fields you need in ReturnFormat
return returnFormat;
}
}
// usage:
new ThribbleLineChartBuilder()
.addDataSet("line", "Uudet", "y-axis-1", totalCount)
.addDataSet("line", "P1 päivystykseen heti", null, p1Count)
... // setup your other data sources
.build()
I'm having trouble appending values to the first non-null cell in column c using Java in Google Sheets API V4.
public void appendValues() throws IOException {
ValueRange oRange = new ValueRange();
oRange.setRange("B1");
oRange.setValues(getDataToAppend());
BatchUpdateValuesRequest oRequest = new BatchUpdateValuesRequest();
oRequest.setValueInputOption("RAW");
List<ValueRange> oList = new ArrayList<>();
oList.add(oRange);
oRequest.setData(oList);
System.out.println("a");
// TODO : BORKED!
service.spreadsheets().values().append(spreadsheetId, "a", oRange).execute();
}
public List<List<Object>> getDataToAppend() {
List<Object> data1 = new ArrayList<Object>();
// TODO
data1.add("a");
List<List<Object>> data = new ArrayList<List<Object>>();
data.add(data1);
return data;
}
Try using spreadsheets.batchUpdate.
The following spreadsheets.batchUpdate request appends rows and
columns. The first request appends three empty rows to the end of the
sheet, while the second appends a single empty column.
The request protocol is shown below. The Updating Spreadsheets guide
shows how to implement a batch update in different languages using the
Google API client libraries.
POST
https://sheets.googleapis.com/v4/spreadsheets/spreadsheetId:batchUpdate
I'm trying to use ElasticSearch spring data for some aggregations
Here Is my query
final FilteredQueryBuilder filteredQuery = QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(),
FilterBuilders.andFilter(FilterBuilders.termFilter("gender", "F"),
FilterBuilders.termFilter("place", "Arizona"),
FilterBuilders.rangeFilter("dob").from(from).to(to)));
final MetricsAggregationBuilder<?> aggregateArtifactcount = AggregationBuilders.sum("delivery")
.field("birth");
final AggregationBuilder<?> dailyDateHistogarm =
AggregationBuilders.dateHistogram(AggregationConstants.DAILY).field("dob")
.interval(DateHistogram.Interval.DAY).subAggregation(aggregateArtifactcount);
final SearchQuery query = new NativeSearchQueryBuilder().withIndices(index).withTypes(type)
.withQuery(filteredQuery).addAggregation(dailyDateHistogarm).build();
return elasticsearchTemplate.query(query, new DailyDeliveryAggregation());
Also this is my Aggregation
public class DailyDeliveryAggregation implements ResultsExtractor<List<DailyDeliverySum>> {
#SuppressWarnings("unchecked")
#Override
public List<DailyDeliverySum> extract(final SearchResponse response) {
final List<DailyDeliverySum> dailyDeliverySum = new ArrayList<DailyDeliverySum>();
final Aggregations aggregations = response.getAggregations();
final DateHistogram daily = aggregations.get(AggregationConstants.DAILY);
final List<DateHistogram.Bucket> buckets = (List<DateHistogram.Bucket>) daily.getBuckets();
for (final DateHistogram.Bucket bucket : buckets) {
final Sum sum = (Sum) bucket.getAggregations().getAsMap().get("delivery");
final int deliverySum = (int) sum.getValue();
final int delivery = (int) bucket.getDocCount();
final String dateString = bucket.getKeyAsText().string();
dailyDeliverySum.add(new DailyDeliverySum(deliverySum, delivery, dateString));
}
return dailyDeliverySum;
}
}
It gives me the correct data , But It doesn't satisfy all my needs
Suppose if I query for time range of 10 days , If there is no data for a date in the given time range It miss that date in Date histogram buckets ,But I want to set 0 as default value for aggregation and doc count if there is no data available
Is there any way to do it ??
Yes, you can use the "minimum document count" feature of the date_histogram aggregation and set it to 0. That way, you'll also get buckets that don't contain any data:
final AggregationBuilder<?> dailyDateHistogarm =
AggregationBuilders.dateHistogram(AggregationConstants.DAILY)
.field("dob")
.minDocCount(0) <--- add this line
.interval(DateHistogram.Interval.DAY)
.subAggregation(aggregateArtifactcount);
Example from #Val by itself did not work for me (I'm using the high-level API with ElasticSearch 6.2.x). What did work though, was telling that the aggregation should handle missing values as 0:
final AggregationBuilder<?> dailyDateHistogarm =
AggregationBuilders.dateHistogram(AggregationConstants.DAILY)
.field("dob")
.minDocCount(0)
.missing(0)
.interval(DateHistogram.Interval.DAY)
.subAggregation(aggregateArtifactcount);
In a java class, am using an arraylist say reports containing list of all the reports which have reportid, reportname, reporttype etc which i want to add into NameValuePair and send a Http postmethod call to a particular url.
I want to add the arraylists - reportname into name value pair(org.apache.commons.httpclient.NameValuePair) and then use the http client post method to submit the name value pair data to a particular url.
Here is my name value pair
if (validateRequest()) {
NameValuePair[] data = {
new NameValuePair("first_name", firstName),
new NameValuePair("last_name", lastName),
new NameValuePair("email", mvrUser.getEmail()),
new NameValuePair("organization", mvrUser.getOrganization()),
new NameValuePair("phone", mvrUser.getPhone()),
new NameValuePair("website", mvrUser.getWebsite()),
new NameValuePair("city", mvrUser.getCity()),
new NameValuePair("state", mvrUser.getState()),
new NameValuePair("country", mvrUser.getCountry()),
new NameValuePair(**"report(s)", reports**.)
};
please suggest me how to add the reports arraylist reportname into reports field of NameValuePair.
--
thanks
# adarsh
can I use with generics something like this?
reportname = "";
for (GSReport report : reports) {
reportname = reportname + report.getReportName();
reportname += ",";
}
and then add in namevalue pair as
new NameValuePair("report(s)", reportname)
for name value pair use map like things... eg. Hastable(it is synchronized) , u can use other
implementation of Map which are not synchronized.
I suggest to serialize your reports ArrayList into a JSON formatted String.
new NameValuePair("reports", reportsAsJson)
You can build your reportsAsJson variable using any of the JSON serialization libraries (like the one at http://json.org/java/). It will have approximatively this format :
reportsAsJson = "[{reportid:'1',reportname:'First Report',reporttype:'Type 1'}, {reportid:'2',reportname:'Seond Report',reporttype:'Type 2'}]";
Well, you cannot do that. NameValuePair takes in String arguments in the constructor. It makes sense as it is used for HTTP POST.
What you can do is come up with a way to serialize the Report object into String and send this string as a string parameter. One way of doing this maybe is to delimit the parameters of the Report class.
reports=reportName1|reportName2|reportName3
Assuming reports is your ArrayList,
String reportsStr = "";
for(int i = 0; i < reports.size(); i++) {
reportStr += reportName;
if(i != reports.size() - 1) {
reportsStr += "|";
}
}
NameValuePair nvPair = new NameValuePair("reports", reportsStr);