With Microsoft CRM 2011 online and using webservices, I am using below method in my Main.java using the OrganizationServiceStub class created by webservices call. The output retrieved no of records is -1 can someone help where I am going wrong. I want to retrieve the accounts where name begins with "Tel" without giving the accountid. I can see the data exists in CRM.
Thanks
public static void getAccountDetails(OrganizationServiceStub service, ArrayOfstring fields)
{
try{
ArrayOfanyType aa = new ArrayOfanyType();
aa.setAnyType(new String[] {"Tel"});
ConditionExpression condition1 = new ConditionExpression();
condition1.setAttributeName("name");
condition1.setOperator(ConditionOperator.BeginsWith);
condition1.setValues(aa);
ArrayOfConditionExpression ss = new ArrayOfConditionExpression();
ss.setConditionExpression(new ConditionExpression[] {condition1});
FilterExpression filter1 = new FilterExpression();
filter1.setConditions(ss);
QueryExpression query = new QueryExpression();
query.setEntityName("account");
ColumnSet cols = new ColumnSet();
cols.setColumns(fields);
query.setColumnSet(cols);
query.setCriteria(filter1);
RetrieveMultiple ll = new RetrieveMultiple();
ll.setQuery(query);
RetrieveMultipleResponse result1 = service.retrieveMultiple(ll);
EntityCollection accounts = result1.getRetrieveMultipleResult();
System.out.println(accounts.getTotalRecordCount());
}
catch (IOrganizationService_RetrieveMultiple_OrganizationServiceFaultFault_FaultMessage e) {
logger.error(e.getMessage());
e.printStackTrace();
}
catch (RemoteException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
}
For Java, include this code snippet works for the above issue
ArrayOfanyType aa = new ArrayOfanyType();
aa.setAnyType(new String[] {"555"});
ConditionExpression condition1 = new ConditionExpression();
condition1.setAttributeName("telephone1");
condition1.setOperator(ConditionOperator.BeginsWith);
condition1.setValues(aa);
ArrayOfConditionExpression ss = new ArrayOfConditionExpression();
ss.setConditionExpression(new ConditionExpression[] {condition1});
FilterExpression filter1 = new FilterExpression();
filter1.setConditions(ss);
QueryExpression query = new QueryExpression();
query.setEntityName("account");
PagingInfo pagingInfo = new PagingInfo();
pagingInfo.setReturnTotalRecordCount(true);
query.setPageInfo(pagingInfo);
OrganizationServiceStub.ColumnSet colSet = new OrganizationServiceStub.ColumnSet();
OrganizationServiceStub.ArrayOfstring cols = new OrganizationServiceStub.ArrayOfstring();
cols.setString(new String[]{"name", "telephone1", "address1_city"});
colSet.setColumns(cols);
query.setColumnSet(colSet);
query.setCriteria(filter1);
RetrieveMultiple ll = new RetrieveMultiple();
ll.setQuery(query);
OrganizationServiceStub.RetrieveMultipleResponse response = serviceStub.retrieveMultiple(ll);
EntityCollection result = response.getRetrieveMultipleResult();
ArrayOfEntity attributes = result.getEntities();
Entity[] keyValuePairs = attributes.getEntity();
for (int i = 0; i < keyValuePairs.length; i++) {
OrganizationServiceStub.KeyValuePairOfstringanyType[] keyValuePairss = keyValuePairs[i].getAttributes().getKeyValuePairOfstringanyType();
for (int j = 0; j < keyValuePairss.length; j++) {
System.out.print(keyValuePairss[j].getKey() + ": ");
System.out.println(keyValuePairss[j].getValue());
}
}
Not sure how similar your EntityCollection object is to the .Net version in the SDK, however you need to specify ReturnTotalRecordCount in the query's PagingInfo in .Net for the TotalRecordCount property to have a value. Could you not instead check accounts.Entities.Count?
Note: I'm not a Java guy either...
Related
public BarChartModel getBcmMarineSH() {
BarChartSeries F1 = new BarChartSeries();
BarChartSeries F2 = new BarChartSeries();
BarChartSeries F3 = new BarChartSeries();
String txtFy = "";
bcmMarine = new BarChartModel();
stacked = new BarChartModel();
try {
ArrayList vec = new ArrayList();
vec.add(getTrade_Type());
ArrayList parm = new ArrayList();
parm.add(vec);
DaoReq[] req = new DaoReq[1];
req[0] = new DaoReq();
req[0].setMethodSignature("225"); // getChaPdb() //getMarinePdbBarChartSM
req[0].setParamCount(1);
req[0].setParamList(parm);
DaoRes res[] = (DaoRes[]) aPosCdbReg.PerformTask(req);
if (res[0].isStatus()) {
ArrayList aRes = (ArrayList) res[0].getResult();
//FY.setLabel((String) aRes.get(0)); /// problem starts here
F1.setLabel("Coastal Bill");
F2.setLabel("Foreign Bill");
F3.setLabel("Total");
//Map
//ArrayList aReq =(ArrayList) res[1].getResult();
F1.setData((Map<Object, Number>) aRes.get(0));
F2.setData((Map<Object, Number>) aRes.get(1));
F3.setData((Map<Object,Number>) aRes.get(2));
} else {
System.out.println(res[0].getMessage());
System.out.println(res[1].getMessage());
System.out.println(res[2].getMessage());
}
bcmMarine.addSeries(F1);
bcmMarine.addSeries(F2);
bcmMarine.addSeries(F3);
bcmMarine.setSeriesColors("FF0066,42EFF5,03FC3D");
bcmMarine.setTitle("Marine Bills for Foreign and Coastal(In Lakhs)");
bcmMarine.setStacked(true);
bcmMarine.setAnimate(true);
bcmMarine.setShowPointLabels(true);
bcmMarine.setShowDatatip(false);
bcmMarine.setLegendPosition("e");
bcmMarine.setLegendCols(1);
bcmMarine.getAxis(AxisType.X).setLabel("Financial Year");
/*stacked.addSeries(F2);
stacked.setSeriesColors("42EFF5");
stacked.setTitle("Marine Bills for Foreign and Coastal(In Lakhs)");
stacked.setStacked(true);
stacked.setAnimate(true);
stacked.setShowPointLabels(true);
stacked.setShowDatatip(false);
stacked.setLegendPosition("e");
stacked.setLegendCols(1);
stacked.getAxis(AxisType.X).setLabel("Financial Year");*/
/*Axis yAxis = bcmMarine.getAxis(AxisType.Y);
yAxis.setMin(0);
yAxis.setMax(1000);*/
} catch (Exception ex) {
System.out.println(ex.getMessage());
} catch (Throwable th) {
System.out.println(th.getMessage());
}
return bcmMarine;
//return stacked;
}
These graph should be stacked but when one ends other one is not showing completely(including previous one It is showing). Should I change my program in backend or what changes should I do In given code.
I have built a Rally dependency, which auto creates test case, folder in Test Plan. While creating test case it checks first if there any any existing test case with same name, else it creates new test case.
This was working while total test case size was small, while the test case size increased, i am seeing duplicate test cases are created. So I made thread to wait for few seconds (Thread.sleep(8000)) after checking existing scenarios and then creating new scenario. It works by this way.
Is there better way to handle & implement this to handle any size of test case. Please advice.
String tcName = rallyMethods.getTestScenarios(parentFolder, scenarioName);
Thread.sleep(8000);
if (tcName == null) {
rallyMethods.createTestCase(parentFolder, scenarioName);
Thread.sleep(8000);
} else {
rallyMethods.updateTestCase(parentFolder, scenarioName);
Thread.sleep(8000);
}
public String getTestScenarios(String parentFolderName, String ScenarioName) throws Throwable {
String sName = null;
String pFolder;
QueryRequest testCaseRequest = new QueryRequest("TestCase");
testCaseRequest.setLimit(Integer.MAX_VALUE);
testCaseRequest.setPageSize(Integer.MAX_VALUE);
testCaseRequest.setFetch(new Fetch("FormattedID", "Name", "Workspace", "Project", "TestFolder"));
testCaseRequest.setQueryFilter(new QueryFilter("Name", "=", ScenarioName));
testCaseRequest.setWorkspace(WORKSPACE_ID);
testCaseRequest.setProject(PROJECT_ID);
QueryResponse testCaseQueryResponse = query(testCaseRequest);
int testCaseCount = testCaseQueryResponse.getTotalResultCount();
// System.out.println("TestCaseCount:" + testCaseCount);
for (int i = 0; i < testCaseCount; i++) {
JsonObject scenarioObj = testCaseQueryResponse.getResults().get(i).getAsJsonObject();
String scenarioName = String.valueOf(scenarioObj.get("Name").getAsString());
JsonElement pFolderObj = scenarioObj.get("TestFolder");
if (!(pFolderObj.isJsonNull())) {
JsonObject tFolderObj = scenarioObj.get("TestFolder").getAsJsonObject();
pFolder = String.valueOf(tFolderObj.get("Name").getAsString());
if (parentFolderName.equalsIgnoreCase(pFolder)) {
sName = scenarioName;
logger.info("Test Scenarios identified in Rally: " + sName);
} else {
logger.info("Scenario, " + ScenarioName + " not found, New Scenario will be created in Rally");
}
}
}
return sName;
}
public void createTestCase(String parentFolderName, String testCaseName) throws Throwable {
String tcName = null;
String userID = readUser();
// Query Child Folders:
QueryRequest testFolderRequest = new QueryRequest("TestFolder");
testFolderRequest.setFetch(new Fetch("Name", "Workspace", "Project"));
testFolderRequest.setQueryFilter(new QueryFilter("Name", "=", parentFolderName));
testFolderRequest.setWorkspace(WORKSPACE_ID);
testFolderRequest.setProject(PROJECT_ID);
QueryResponse testFolderQueryResponse = query(testFolderRequest);
int folderCount = testFolderQueryResponse.getTotalResultCount();
for (int i = 0; i < folderCount; i++) {
String testFolderRef = testFolderQueryResponse.getResults().get(i).getAsJsonObject().get("_ref").getAsString();
JsonObject testFolderObj = testFolderQueryResponse.getResults().get(i).getAsJsonObject();
String pFolder = String.valueOf(testFolderObj.get("Name").getAsString());
if (pFolder.equalsIgnoreCase(parentFolderName)) {
//System.out.println("Creating a test case...");
JsonObject newTC = new JsonObject();
newTC.addProperty("Name", testCaseName);
newTC.addProperty("Workspace", WORKSPACE_ID);
newTC.addProperty("Project", PROJECT_ID);
newTC.addProperty("Description", "Selenium Automated TestCase");
newTC.addProperty("TestFolder", testFolderRef);
newTC.addProperty("Method", "Automated");
newTC.addProperty("Type", "Functional");
if (!(userID == null)) {
newTC.addProperty("Owner", userID);
}
CreateRequest createRequest = new CreateRequest("testcase", newTC);
CreateResponse createResponse = create(createRequest);
if (createResponse.wasSuccessful()) {
JsonObject tcObj = createResponse.getObject();
tcName = String.valueOf(tcObj.get("Name").getAsString());
logger.info("Created test scenario name is: " + tcName);
} else {
String[] createErrors;
createErrors = createResponse.getErrors();
logger.info("Error while creating test scenario below parent folder!");
for (int j = 0; j < createErrors.length; j++) {
System.out.println(createErrors[j]);
logger.info(createErrors[j]);
}
}
}
}
}
Hmmm... I'm not too familiar with the Java REST toolkit, but I can't think of a reason why a larger set of test cases in the workspace would cause the query to fail like that.
Did you try checking testCaseQueryResponse.wasSuccessful()? If it returns false, can you see what the error is? testCaseQueryResponse.getErrors()
My first thoughts are that you should provide a reasonable value for the limit and pageSize parameters, rather than passing Integer.MAX_VALUE. And second, rather than checking if the returned test cases are in the specified parent folder, you should include a query filter to filter the test cases results on TestFolder.Name = parentFolderName. Then you should only be expecting either 1 or 0 results returned (assuming that you're expecting all test cases within a test folder to have unique names).
I am trying to query using the google public dns server (8.8.8.8) to get the IP address of some known URL. However, it seems like I am not able to get that using the following code? I am using the dnsjava java library. This is my current code
The results
Lookup lookup = new Lookup("stackoverflow.com", Type.NS);
SimpleResolver resolver=new SimpleResolver("8.8.8.8");
lookup.setDefaultResolver(resolver);
lookup.setResolver(resolver);
Record [] records = lookup.run();
for (int i = 0; i < records.length; i++) {
Record r = (Record ) records[i];
System.out.println(r.getName()+","+r.getAdditionalName());
}
}
catch ( Exception ex) {
ex.printStackTrace();
logger.error(ex.getMessage(),ex);
}
Results:
stackoverflow.com.,ns-1033.awsdns-01.org.
stackoverflow.com.,ns-cloud-e1.googledomains.com.
stackoverflow.com.,ns-cloud-e2.googledomains.com.
stackoverflow.com.,ns-358.awsdns-44.com.
You don’t need a DNS library just to look up an IP address. You can simply use JNDI:
Properties env = new Properties();
env.setProperty(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.dns.DnsContextFactory");
env.setProperty(Context.PROVIDER_URL, "dns://8.8.8.8");
DirContext context = new InitialDirContext(env);
Attributes list = context.getAttributes("stackoverflow.com",
new String[] { "A" });
NamingEnumeration<? extends Attribute> records = list.getAll();
while (records.hasMore()) {
Attribute record = records.next();
String name = record.get().toString();
System.out.println(name);
}
If you insist on using the dnsjava library, you need to use Type.A (as your code was originally doing, before your edit).
Looking at the documentation for the Record class, notice the long list under Direct Known Subclasses. You need to cast each Record to the appropriate subclass, which in this case is ARecord.
Once you’ve done that cast, you have an additional method available, getAddress:
for (int i = 0; i < records.length; i++) {
ARecord r = (ARecord) records[i];
System.out.println(r.getName() + "," + r.getAdditionalName()
+ " => " + r.getAddress());
}
I am trying to create a web scraper program that takes tables from a website and converts them into ".csv" files.
I'm using Jsoup to pull the data down into a document and have it read from document.html() doc.html() below. The reader as it stands picks up 18 tables at my test site but no table data tags.
Do you have any idea what could be going wrong?
ArrayList<Data_Log> container = new ArrayList<Data_Log>();
ArrayList<ListData_Log> containerList = new ArrayList<ListData_Log>();
ArrayList<String> tableNames = new ArrayList<String>();// Stores native names of tables
ArrayList<Double> meanStorage = new ArrayList<Double>();// Stores data mean per table
ArrayList<String> processlog = new ArrayList<String>();// Keeps a record of all actions taken per iteration
ArrayList<Double> modeStorage = new ArrayList<Double>();
Calendar cal;
private static final long serialVersionUID = -8174362940798098542L;
public void takeData() throws IOException {
if (testModeActive == true) {
System.out.println("Initializing Data Cruncher with developer logs");
System.out.println("Taking data from: " + dataSource); }
int irow = 0;
int icolumn = 0;
int iTable = 0;
// int iListno = 0;
// int iListLevel;
String u = null;
boolean recording = false;
boolean duplicate = false;
Document doc = Jsoup.connect(dataSource).get();
Webtitle = doc.title();
Pattern tb = Pattern.compile("<table");
Matcher tB = tb.matcher(doc.html());
Pattern ttl = Pattern.compile("<title>(//s+)</title>");
Matcher ttl2= ttl.matcher(doc.html());
Pattern tr = Pattern.compile("<tr");
Matcher tR = tr.matcher(doc.html());
Pattern td = Pattern.compile("<td(//s+)</td>");
Matcher tD = td.matcher(doc.html());
Pattern tdc = Pattern.compile("<td class=(//s+)>(//s+)</td>");
Matcher tDC = tdc.matcher(doc.html());
Pattern tb2 = Pattern.compile("</table>");
Matcher tB2 = tb2.matcher(doc.html());
Pattern th = Pattern.compile("<th");
Matcher tH = th.matcher(doc.html());
while (tB.find()) {
iTable++;
while(ttl2.find()) {
tableNames.add(ttl2.group(1));
}
while (tR.find()) {
while (tD.find()||tH.find()) {
u = tD.group(1);
Data_Log v = new Data_Log();
v.setTable(iTable);
v.dataSort(u);
v.setRow(irow);
v.setColumn(icolumn);
container.add(v);
icolumn++;
}
while(tDC.find()) {
u = tDC.group(2);
Data_Log v = new Data_Log();
v.setTable(iTable);
v.dataSort(u);
v.setRow(irow);
v.setColumn(icolumn);
container.add(v);
icolumn++;
}
irow++;
}
if (tB2.find()) {
irow=0;
icolumn=0;
}
}
Expected results:
table# logged + "td"s logged
Actual result:
table# logged "td"s omitted
Since you're using jsoup, use it
var url = "<your url>";
var doc = Jsoup.connect(url).get();
var tables = doc.body().getElementsByTag("table");
tables.forEach(table -> {
System.out.println(table.id());
System.out.println(table.className());
System.out.println(table.getElementsByTag("td"));
});
For your tries to parse html with regex, here's some suggested reading
Using regular expressions to parse HTML: why not?
Why is it such a bad idea to parse XML with regex?
RegEx match open tags except XHTML self-contained tags
I have a custom metric in AWS cloudwatch and i am putting data into it through AWS java API.
for(int i =0;i<collection.size();i++){
String[] cell = collection.get(i).split("\\|\\|");
List<Dimension> dimensions = new ArrayList<>();
dimensions.add(new Dimension().withName(dimension[0]).withValue(cell[0]));
dimensions.add(new Dimension().withName(dimension[1]).withValue(cell[1]));
MetricDatum datum = new MetricDatum().withMetricName(metricName)
.withUnit(StandardUnit.None)
.withValue(Double.valueOf(cell[2]))
.withDimensions(dimensions);
PutMetricDataRequest request = new PutMetricDataRequest().withNamespace(namespace+"_"+cell[3]).withMetricData(datum);
String response = String.valueOf(cw.putMetricData(request));
GetMetricDataRequest res = new GetMetricDataRequest().withMetricDataQueries();
//cw.getMetricData();
com.amazonaws.services.cloudwatch.model.Metric m = new com.amazonaws.services.cloudwatch.model.Metric();
m.setMetricName(metricName);
m.setDimensions(dimensions);
m.setNamespace(namespace);
MetricStat ms = new MetricStat().withMetric(m);
MetricDataQuery metricDataQuery = new MetricDataQuery();
metricDataQuery.withMetricStat(ms);
metricDataQuery.withId("m1");
List<MetricDataQuery> mqList = new ArrayList<MetricDataQuery>();
mqList.add(metricDataQuery);
res.withMetricDataQueries(mqList);
GetMetricDataResult result1= cw.getMetricData(res);
}
Now i want to be able to fetch the latest data entered for a particular namespace, metric name and dimention combination through Java API. I am not able to find appropriate documenation from AWS regarding the same. Can anyone please help me?
I got the results from cloudwatch by the below code.\
GetMetricDataRequest getMetricDataRequest = new GetMetricDataRequest().withMetricDataQueries();
Integer integer = new Integer(300);
Iterator<Map.Entry<String, String>> entries = dimensions.entrySet().iterator();
List<Dimension> dList = new ArrayList<Dimension>();
while (entries.hasNext()) {
Map.Entry<String, String> entry = entries.next();
dList.add(new Dimension().withName(entry.getKey()).withValue(entry.getValue()));
}
com.amazonaws.services.cloudwatch.model.Metric metric = new com.amazonaws.services.cloudwatch.model.Metric();
metric.setNamespace(namespace);
metric.setMetricName(metricName);
metric.setDimensions(dList);
MetricStat ms = new MetricStat().withMetric(metric)
.withPeriod(integer)
.withUnit(StandardUnit.None)
.withStat("Average");
MetricDataQuery metricDataQuery = new MetricDataQuery().withMetricStat(ms)
.withId("m1");
List<MetricDataQuery> mqList = new ArrayList<>();
mqList.add(metricDataQuery);
getMetricDataRequest.withMetricDataQueries(mqList);
long timestamp = 1536962700000L;
long timestampEnd = 1536963000000L;
Date d = new Date(timestamp );
Date dEnd = new Date(timestampEnd );
getMetricDataRequest.withStartTime(d);
getMetricDataRequest.withEndTime(dEnd);
GetMetricDataResult result1= cw.getMetricData(getMetricDataRequest);