Rally Pull Defect Suite from workspace - rally

i got the code snippet of adding a defect to defect suite from forums.
However, my requirement is to pull defect from defect suite and i am not aware of defect suite information.
Is there a way to pull collection of defect suites and defects from it.
Here is the sample code snippet to add defect to defect suite.
> import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.rallydev.rest.RallyRestApi;
import com.rallydev.rest.request.CreateRequest;
import com.rallydev.rest.request.QueryRequest;
import com.rallydev.rest.request.UpdateRequest;
import com.rallydev.rest.response.CreateResponse;
import com.rallydev.rest.response.QueryResponse;
import com.rallydev.rest.response.UpdateResponse;
import com.rallydev.rest.util.Fetch;
import com.rallydev.rest.util.QueryFilter;
import com.rallydev.rest.util.Ref;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class addDefectToSuite {
public static void main(String[] args) throws URISyntaxException, IOException {
String host = "https://rally1.rallydev.com";
String username = "user#company.com";
String password = "secret";
String wsapiVersion = "v2.0";
String projectRef = "/project/12352608219";
String workspaceRef = "/workspace/12352608129";
String applicationName = "Create defect, add to a defectsuite";
RallyRestApi restApi = new RallyRestApi(
new URI(host),
username,
password);
restApi.setWsapiVersion(wsapiVersion);
restApi.setApplicationName(applicationName);
QueryRequest defectSuiteRequest = new QueryRequest("DefectSuite");
defectSuiteRequest.setFetch(new Fetch("FormattedID","Name", "Defects"));
defectSuiteRequest.setWorkspace(workspaceRef);
defectSuiteRequest.setQueryFilter(new QueryFilter("FormattedID", "=", "DS1"));
QueryResponse defectSuiteQueryResponse = restApi.query(defectSuiteRequest);
JsonObject defectSuiteJsonObject = defectSuiteQueryResponse.getResults().get(0).getAsJsonObject();
System.out.println("defectSuiteJsonObject" + defectSuiteJsonObject);
String defectSuiteRef = defectSuiteJsonObject.get("_ref").getAsString();
int numberOfDefects = defectSuiteJsonObject.getAsJsonObject("Defects").get("Count").getAsInt();
System.out.println(defectSuiteJsonObject.get("Name") + " ref: " + defectSuiteRef + "number of defects: " + numberOfDefects + " " + defectSuiteJsonObject.get("Defects"));
try {
JsonObject defect = new JsonObject();
defect.addProperty("Name", "bad defect 668");
CreateRequest createRequest = new CreateRequest("defect", defect);
CreateResponse createResponse = restApi.create(createRequest);
if (createResponse.wasSuccessful()) {
JsonObject defectJsonObject = createResponse.getObject();
String defectRef = Ref.getRelativeRef(createResponse.getObject().get("_ref").getAsString());
System.out.println(String.format("Created %s", defectRef));
JsonObject defectSuitesOfThisDefect = (JsonObject) defectJsonObject.get("DefectSuites");
int numberOfSuites = defectSuitesOfThisDefect.get("Count").getAsInt();
System.out.println("number of defect suites this defect is part of: " + numberOfSuites);
QueryRequest defectSuitesOfThisDefectRequest = new QueryRequest(defectSuitesOfThisDefect);
JsonArray suites = restApi.query(defectSuitesOfThisDefectRequest).getResults();
System.out.println("suites: " + suites);
suites.add(defectSuiteJsonObject);
System.out.println("suites after add: " + suites);
//Update defect: add to defectsutites collection
JsonObject defectUpdate = new JsonObject();
defectUpdate.add("DefectSuites", suites);
UpdateRequest updateDefectRequest = new UpdateRequest(defectRef,defectUpdate);
UpdateResponse updateResponse = restApi.update(updateDefectRequest);
if (updateResponse.wasSuccessful()) {
System.out.println("Successfully updated defect: " + defectJsonObject.get("FormattedID"));
}
else {
String[] updateErrors;
updateErrors = createResponse.getErrors();
System.out.println("Error");
for (int i=0; i<updateErrors.length;i++) {
System.out.println(updateErrors[i]);
}
}
} else {
System.out.println("error");
}
} finally {
restApi.close();
}
}
}

The Defect object has a DefectSuites collection, so you could just query for all defects where DefectSuites contains your specified DefectSuite:
QueryRequest defectsRequest = new QueryRequest("Defect");
defectsRequest.setFetch(new Fetch("FormattedID","Name"));
defectsRequest.setQueryFilter(new QueryFilter("DefectSuites", "contains", defectSuiteRef));
QueryResponse defectsResponse = restApi.query(defectsRequest);
Or, you can come at it from the other way by querying the Defects collection directly on your DefectSuite in your original code above:
JsonObject defectsCollection = defectSuiteJsonObject.getAsJsonObject("Defects");
QueryRequest defectsRequest = new QueryRequest(defectsCollection);
defectSuiteRequest.setFetch(new Fetch("FormattedID","Name"));
QueryResponse defectsResponse = restApi.query(defectsRequest);

Related

How to fetch a userstory's Actuals,Todo,Estimate fields from detail page of rally using RallyrestApi

I am able to take userstory actual, estimate and Values from its Task.But when tasks are not there for an user story i have to take values from the userstories detail page from rally.
Ex:(i need to fetch as like below from rallyrestapi c# toolkit)
https://rally1.rallydev.com/#/262768386856d/detail/defect/161729744764
Currently i tried as below , but its not working out
// Query for UserStories
[![Request storyRequest = new Rally.RestApi.Request("hierarchicalrequirement");
storyRequest.Workspace = workspaceRef;
// storyRequest.Project = projectRef;
storyRequest.ProjectScopeUp = projectScopingUp;
storyRequest.ProjectScopeDown = projectScopingDown;
storyRequest.Fetch = new List<string>()
{
"Name",
"ObjectID",
"ScheduleState",
"State",
"FormattedID",
"CreationDate",
"ReleaseDate",
"PlanEstimate",
"Iteration",
"StartDate",
"EndDate",
"Release",
"ScheduleState",
"Tasks",
};
string userstoryId = "";
long userstoryObjId ;
storyRequest.Query = new Query("Iteration.Name", Query.Operator.Equals, myIterationName);
QueryResult queryStoryResults = rallyRestApi.Query(storyRequest);
ConvertToJSon(queryStoryResults);
// Fetch Actual and Estimated Time request for task
foreach (var userstory in queryStoryResults.Results)
{
Rally.RestApi.Request tasksRequest = new Rally.RestApi.Request(userstory\["Tasks"\]);
QueryResult queryTaskResult = rallyRestApi.Query(tasksRequest);
}
Request details = new Rally.RestApi.Request("details");
details.Workspace = workspaceRef;
// storyRequest.Project = projectRef;
details.ProjectScopeUp = projectScopingUp;
details.ProjectScopeDown = projectScopingDown;
details.Fetch = new List<string>()
{
"Estimate",
"Actuals",
"ToDo"
};
storyRequest.Query = new Query("Defect.ObjectID", Query.Operator.Equals, "298510499032");
QueryResult detailsdata = rallyRestApi.Query(details);][1]][1]
Unauthorized 401 error it gives. Please guide me how to fetch the above fields from rally details page.
I have the same example in Java but it may help you:
import com.google.gson.JsonObject;
import com.rallydev.rest.RallyRestApi;
import com.rallydev.rest.request.QueryRequest;
import com.rallydev.rest.response.QueryResponse;
import com.rallydev.rest.util.Fetch;
import com.rallydev.rest.util.QueryFilter;
import java.io.IOException;
import java.net.URI;
public class FindUserStoryByID {
public static void main(String[] args) throws IOException {
String host = "https://rally1.rallydev.com";
String apiKey = "YOUR_API_KEY"; #or you may use login/password
RallyRestApi rallyRestApi = null;
try {
rallyRestApi = new RallyRestApi(URI.create(host), apiKey);
QueryRequest query = new QueryRequest("HierarchicalRequirement");
query.setFetch(new Fetch("FormattedID", "Name", "TaskEstimateTotal", "TaskRemainingTotal",
"TaskActualTotal"));
query.setLimit(1000);
query.setScopedDown(true);
query.setQueryFilter(new QueryFilter("FormattedID", "=", "US11111"));
QueryResponse response = rallyRestApi.query(query);
if (response.wasSuccessful()) {
for (int i = 0; i < response.getTotalResultCount(); i++) {
JsonObject jsonObject = response.getResults().get(i).getAsJsonObject();
System.out.println("FormattedID: " + jsonObject.get("FormattedID"));
System.out.println("Name: " + jsonObject.get("Name"));
System.out.println("TaskEstimateTotal: " + jsonObject.get("TaskEstimateTotal"));
System.out.println("TaskRemainingTotal: " + jsonObject.get("TaskRemainingTotal"));
System.out.println("TaskActualTotal: " + jsonObject.get("TaskActualTotal"));
}
}
} finally {
if (rallyRestApi != null) {
rallyRestApi.close();
}
}
}
}
Output will be like this:
FormattedID: "US11111"
Name: "My cool user story"
TaskEstimateTotal: 29.0
TaskRemainingTotal: 29.0
TaskActualTotal: 0.0
check in https://rally1.rallydev.com/account and check api key whehter key access is full grant or not that is the issue

Lucene Document and Java ArrayList

I have a set of data: ID, Name and a ArrayList associated with the ID. I wanted this data to be stored in the Lucene document. The search will be based on the Id and name. The List should not be indexed.
I do not know how a List/ArrayList can be stored in the Lucene Document. What is best way of doing this?
Apache Lucene verison I am using is 7.1.0.
Thanks.
Document doc = new Document();
String id = "something";
String name = "someName";
List someList = new ArrayList();
doc.add(new StringField("Id", id, Field.Store.YES));
doc.add(new TextField("name", name, Field.Store.YES));
How do I do something similar for the 'someList'?
You can use StoredField.
A simple aproach might be serializing the list. Here is a sample code:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Random;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
public class LuceneTest {
public static byte[] serialize(Object obj) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream(200000);
ObjectOutputStream os = new ObjectOutputStream(bos);
os.writeObject(obj);
os.close();
return bos.toByteArray();
}
public static Object unserialize(byte[] bytes) throws ClassNotFoundException, IOException {
ObjectInputStream is = new ObjectInputStream(new ByteArrayInputStream(bytes));
Object result = is.readObject();
is.close();
return result;
}
public static void index() {
String indexPath = "index";
try {
System.out.println("Indexing to directory '" + indexPath + "'...");
Directory dir = FSDirectory.open(Paths.get(indexPath));
Analyzer analyzer = new StandardAnalyzer();
IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
iwc.setOpenMode(OpenMode.CREATE);
IndexWriter writer = new IndexWriter(dir, iwc);
for (int i = 0; i < 100; i++) {
Document doc = new Document();
String id = "id" + i;
String name = "jack " + i;
ArrayList<Object> someList = new ArrayList<>();
someList.add(id + " => " + name);
someList.add("index" + i);
doc.add(new StringField("Id", id, Field.Store.YES));
doc.add(new TextField("name", name, Field.Store.YES));
doc.add(new StoredField("list", serialize(someList)));
writer.addDocument(doc);
}
writer.close();
} catch (IOException e) {
System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage());
}
}
public static void search() {
String index = "index";
String field = "name";
int hitsPerPage = 10;
try {
IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(index)));
IndexSearcher searcher = new IndexSearcher(reader);
Analyzer analyzer = new StandardAnalyzer();
QueryParser parser = new QueryParser(field, analyzer);
Random rnd = new Random();
for (int i = 0; i < 10; i++) {
int randIndex = rnd.nextInt(100);
String nameQuery = "" + randIndex;
Query query = parser.parse(nameQuery);
System.out.println("Searching for: " + query.toString(field));
TopDocs results = searcher.search(query, hitsPerPage);
ScoreDoc[] hits = results.scoreDocs;
for (ScoreDoc scoreDoc : hits) {
Document doc = searcher.doc(scoreDoc.doc);
String id = doc.get("Id");
String name = doc.get("name");
ArrayList<Object> list = (ArrayList<Object>) unserialize(doc.getBinaryValue("list").bytes);
System.out.println("id: " + id + " name: " + name + " list: " + list);
}
System.out.println();
}
reader.close();
} catch (Exception e) {
System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage());
}
}
public static void main(String[] args) {
index();
search();
}
}

Scope validation fails when running the (new) published API of WSO2 AM 1.10.0

I provide a working code in the answer below, as this set of API's is relatively new, and I could not see other end-to-end examples in the web, so may be useful as a reference for anyone wishing to use the new set of API's.
I'm trying to use the new set of published APIs of WSO2 AM 1.10.0. I wrote a sample client, based on an article of Sanjeewa Malalgoda: http://wso2.com/library/articles/2015/11/article-introducing-wso2-api-manager-new-rest-api-for-store-and-publisher-operations
Here is the code, based on that article and fixes some minor errors/typos:
package test;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
import org.wso2.carbon.automation.engine.exceptions.AutomationFrameworkException;
import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil;
import org.wso2.carbon.automation.test.utils.http.client.HttpResponse;
public class test
{
public static void main(String[] args) throws
UnsupportedEncodingException,
AutomationFrameworkException,
InterruptedException,
MalformedURLException,
IOException
{
// PHASE 1: REGISTER CLIENT
// ------------------------
String dcrEndpointURL = getKeyManagerURLHttp() +
"client-registration/v0.9/register";
String applicationRequestBody = " {\n" +
" \"callbackUrl\": \"google.sk\",\n" +
" \"clientName\": \"test_11\",\n" +
" \"tokenScope\": \"Production\",\n" +
" \"owner\": \"admin\",\n" +
" \"grantType\": \"password refresh_token\",\n" +
" \"saasApp\": true\n" +
" }";
Map<String, String> dcrRequestHeaders = new HashMap<String, String>();
// This is base 64 encoded basic Auth value for user name admin and password admin.
String basicAuthAdmin = "admin" + ":" + "admin";
byte [] encodedBytesAdmin = Base64.getEncoder().encode(basicAuthAdmin.getBytes("UTF-8"));
dcrRequestHeaders.put("Authorization", "Basic " + new String(encodedBytesAdmin, "UTF-8"));
System.out.println(dcrRequestHeaders.get("Authorization"));
dcrRequestHeaders.put("Content-Type", "application/json");
JSONObject clientRegistrationResponse = new JSONObject(HttpRequestUtil.doPost(
new URL(dcrEndpointURL),
applicationRequestBody,dcrRequestHeaders));
System.out.println(clientRegistrationResponse);
consumerKey = new JSONObject(clientRegistrationResponse.getString("data")).get("clientId").toString();
consumerSecret =new JSONObject(clientRegistrationResponse.getString("data")).get("clientSecret").toString();
System.out.println(consumerKey);
System.out.println(consumerSecret);
Thread.sleep(2000);
// PHASE 2: REQUEST TOKEN
// ----------------------
String requestBody = "grant_type=password&username=admin&password=admin&scope=API_CREATOR_SCOPE";
URL tokenEndpointURL = new URL(getGatewayURLNhttp() + "token");
Map<String, String> authenticationRequestHeaders = new HashMap<String, String>();
String basicAuthConsumer = consumerKey + ":" + consumerSecret;
byte [] encodedBytesConsumer = Base64.getEncoder().encode(basicAuthConsumer.getBytes("UTF-8"));
authenticationRequestHeaders.put("Authorization", "Basic " + new String(encodedBytesConsumer, "UTF-8"));
JSONObject accessTokenGenerationResponse = new JSONObject(HttpRequestUtil.doPost(tokenEndpointURL, requestBody, authenticationRequestHeaders));
System.out.println(accessTokenGenerationResponse);
//Get access token and refresh token from token API call.
//Now we have access token and refresh token that we can use to invoke API.
JSONObject tokenData = new JSONObject(accessTokenGenerationResponse.getString("data"));
String userAccessToken = tokenData.getString("access_token");
String refreshToken = tokenData.getString("refresh_token");
System.out.println("Access token: " + userAccessToken);
System.out.println("Refresh token: " + refreshToken);
// PHASE 3: CALL THE API
// ---------------------
Map<String, String> requestHeaders = new HashMap<String, String>();
requestHeaders.put("Authorization", "Bearer " + userAccessToken);
System.out.println(requestHeaders);
HttpResponse response = HttpRequestUtil.doGet(getKeyManagerURLHttp()+"api/am/publisher/v0.9/apis?query=admin&type=provide",requestHeaders);
System.out.println(response.getResponseCode());
System.out.println(response.getResponseMessage());
}
static String getKeyManagerURLHttp()
{
return "http://127.0.0.1:9763/";
}
static String getGatewayURLNhttp()
{
return "http://127.0.0.1:8280/";
}
}
The code registers the client and returns access and refresh token successfully.
Here is the response of the token request:
"data":
{
"access_token": "bb5176def22ffbc4a7b12d2fd1ee9733",
"refresh_token": "357926275971df21f9529ebb30ba36d1",
"scope":"default",
"token_type":"Bearer",
"expires_in":2502
}
However, when I send this token in the header of the API query:
{Authorization=Bearer bb5176def22ffbc4a7b12d2fd1ee9733}
I get error code 401/Unauthorized.
Looking at the server log, I get the following:
[2016-02-07 17:38:20,371] ERROR - WebAppAuthenticatorImpl You cannot access API as scope validation failed
[2016-02-07 17:38:20,372] WARN - PhaseInterceptorChain Interceptor for {http://publisher.api.rest.apimgt.carbon.wso2.org/}SubscriptionsApi has thrown exception, unwinding now
org.apache.cxf.interceptor.security.AuthenticationException: Unauthenticated request
at org.wso2.carbon.apimgt.rest.api.util.interceptors.auth.OAuthAuthenticationInterceptor.handleMessage(OAuthAuthenticationInterceptor.java:62)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:251)
at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:234)
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:208)
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:160)
at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:180)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:293)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doGet(AbstractHTTPServlet.java:217)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:268)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:99)
at org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve$1.invoke(CarbonTomcatValve.java:47)
at org.wso2.carbon.webapp.mgt.TenantLazyLoaderValve.invoke(TenantLazyLoaderValve.java:57)
at org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:47)
at org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:62)
at org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:159)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:57)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1739)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1698)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
Some notes
I'm running version 1.10.0, from http://wso2.com/api-management/try-it
WSO2 Published API's that I have on this deployment are all v0.9 (and not v1, as appear in some of the examples)
I tried the token request with both API_CREATOR_SCOPE, API_PUBLISHER_SCOPE. Both fail.
In the response of the token request, it says "scope: default". Not sure if this is ok or not.
The exception says "You cannot access API as scope validation failed", so I guess there is an issue with the scope. But I'm not sure why and how to fix.
Please check roles and scope available in /_system/config/apimgt/applicationdata/tenant-conf.json file. Then request token with scopes mentioned there. Then you will get access token with correct scope. Please note that tokens with default scope cannot use for REST API functionalities.
For basic authentication, change beans.xml of repository\deployment\server\webapps\api#am#publisher#v0.9\WEB-INF to:
<bean id="AuthenticationInterceptor" class="org.wso2.carbon.apimgt.rest.api.util.interceptors.auth.BasicAuthenticationInterceptor" />
And then code is much simplified:
public class test {
public static void main(String[] args) throws
UnsupportedEncodingException,
AutomationFrameworkException,
InterruptedException,
MalformedURLException,
IOException
{
String dcrEndpointURL = getKeyManagerURLHttp()+"client-registration/v0.9/register";
String basicAuthAdmin = "admin" + ":" + "admin";
byte [] encodedBytesAdmin = Base64.getEncoder().encode(basicAuthAdmin.getBytes("UTF-8"));
Map<String, String> requestHeaders = new HashMap<String, String>();
requestHeaders.put("Authorization", "Basic " + new String(encodedBytesAdmin, "UTF-8"));
System.out.println(requestHeaders);
HttpResponse response = HttpRequestUtil.doGet(getKeyManagerURLHttp()+"api/am/publisher/v0.9/apis",requestHeaders);
System.out.println(response.getResponseCode());
System.out.println(response.getResponseMessage());
System.out.println(response.getData());
HttpResponse response1 = HttpRequestUtil.doGet(getKeyManagerURLHttp()+"api/am/publisher/v0.9/subscriptions",requestHeaders);
System.out.println(response1.getResponseCode());
System.out.println(response1.getResponseMessage());
System.out.println(response1.getData());
}
static String getKeyManagerURLHttp()
{
return "http://127.0.0.1:9763/";
}
static String getGatewayURLNhttp()
{
return "http://127.0.0.1:8280/";
}
}
Here is a working example, following Sanjeewa's fix.
package test;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
import org.wso2.carbon.automation.engine.exceptions.AutomationFrameworkException;
import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil;
import org.wso2.carbon.automation.test.utils.http.client.HttpResponse;
public class test
{
public static void main(String[] args) throws
UnsupportedEncodingException,
AutomationFrameworkException,
InterruptedException,
MalformedURLException,
IOException
{
// PHASE 1: REGISTER CLIENT
// ------------------------
String dcrEndpointURL = getKeyManagerURLHttp() +
"client-registration/v0.9/register";
String applicationRequestBody = " {\n" +
" \"callbackUrl\": \"google.sk\",\n" +
" \"clientName\": \"test_11\",\n" +
" \"tokenScope\": \"Production\",\n" +
" \"owner\": \"admin\",\n" +
" \"grantType\": \"password refresh_token\",\n" +
" \"saasApp\": true\n" +
" }";
Map<String, String> dcrRequestHeaders = new HashMap<String, String>();
// This is base 64 encoded basic Auth value for user name admin and password admin.
String basicAuthAdmin = "admin" + ":" + "admin";
byte [] encodedBytesAdmin = Base64.getEncoder().encode(basicAuthAdmin.getBytes("UTF-8"));
dcrRequestHeaders.put("Authorization", "Basic " + new String(encodedBytesAdmin, "UTF-8"));
System.out.println(dcrRequestHeaders.get("Authorization"));
dcrRequestHeaders.put("Content-Type", "application/json");
JSONObject clientRegistrationResponse = new JSONObject(HttpRequestUtil.doPost(
new URL(dcrEndpointURL),
applicationRequestBody,dcrRequestHeaders));
System.out.println(clientRegistrationResponse);
consumerKey = new JSONObject(clientRegistrationResponse.getString("data")).get("clientId").toString();
consumerSecret =new JSONObject(clientRegistrationResponse.getString("data")).get("clientSecret").toString();
System.out.println(consumerKey);
System.out.println(consumerSecret);
Thread.sleep(2000);
// PHASE 2: REQUEST TOKEN
// ----------------------
String requestBody = "grant_type=password&username=admin&password=admin&scope=apim:view_api";
URL tokenEndpointURL = new URL(getGatewayURLNhttp() + "token");
Map<String, String> authenticationRequestHeaders = new HashMap<String, String>();
String basicAuthConsumer = consumerKey + ":" + consumerSecret;
byte [] encodedBytesConsumer = Base64.getEncoder().encode(basicAuthConsumer.getBytes("UTF-8"));
authenticationRequestHeaders.put("Authorization", "Basic " + new String(encodedBytesConsumer, "UTF-8"));
JSONObject accessTokenGenerationResponse = new JSONObject(HttpRequestUtil.doPost(tokenEndpointURL, requestBody, authenticationRequestHeaders));
System.out.println(accessTokenGenerationResponse);
//Get access token and refresh token from token API call.
//Now we have access token and refresh token that we can use to invoke API.
JSONObject tokenData = new JSONObject(accessTokenGenerationResponse.getString("data"));
String userAccessToken = tokenData.getString("access_token");
String refreshToken = tokenData.getString("refresh_token");
System.out.println("Access token: " + userAccessToken);
System.out.println("Refresh token: " + refreshToken);
// PHASE 3: CALL THE API
// ---------------------
Map<String, String> requestHeaders = new HashMap<String, String>();
requestHeaders.put("Authorization", "Bearer " + userAccessToken);
System.out.println(requestHeaders);
HttpResponse response = HttpRequestUtil.doGet(getKeyManagerURLHttp()+"api/am/publisher/v0.9/apis?query=admin&type=provide",requestHeaders);
System.out.println(response.getResponseCode());
System.out.println(response.getResponseMessage());
System.out.println(response.getData());
}
static String getKeyManagerURLHttp()
{
return "http://127.0.0.1:9763/";
}
static String getGatewayURLNhttp()
{
return "http://127.0.0.1:8280/";
}
}
Result:
200
OK
{"count":1,"next":"","list":[{"name":"employees","context":"/employees","id":"09cef2c8-89f0-405e-97af-225942a52d83","description":null,"version":"1.0.0","provider":"admin","status":"PUBLISHED"}],"previous":""}

Rally: How to Map test cases with user stories using REST API?

I am writing code to create new test cases using rally restAPI.
Able to create the test cases under Test Plan & Test folder.
Now, want to map those test cases to Rally user stories.
Work product is the field to map it. But how to get the reference of user story using restAPI?
Please let me know if anyone has done in past.
In WS API user story is HierarchicalRequirement object. Query on the story, which you want to be a workproduct, and get its _ref. Then update the test case, e.g.
testCaseUpdate.addProperty("WorkProduct", storyRef);
Here is a Java example using Rally Rest toolkit for Java, but the approach is the same regardless of your choice of language or toolkit:
public class UpdateTestCase {
public static void main(String[] args) throws URISyntaxException, IOException {
String host = "https://rally1.rallydev.com";
String apiKey = "_abc123";
String workspaceRef = "/workspace/123456";
String applicationName = "RestExample_updateWorkProductOnTestCase";
RallyRestApi restApi = new RallyRestApi(new URI(host),apiKey);
restApi.setApplicationName(applicationName);
try {
String testid = "TC12";
String storyid = "US34";
QueryRequest testCaseRequest = new QueryRequest("TestCase");
testCaseRequest.setWorkspace(workspaceRef);
testCaseRequest.setFetch(new Fetch("FormattedID", "Name", "WorkProduct"));
testCaseRequest.setQueryFilter(new QueryFilter("FormattedID", "=", testid));
QueryResponse testCaseQueryResponse = restApi.query(testCaseRequest);;
if (testCaseQueryResponse.getTotalResultCount() == 0) {
System.out.println("Cannot find test case : " + testid);
return;
}
JsonObject testCaseJsonObject = testCaseQueryResponse.getResults().get(0).getAsJsonObject();
String testCaseRef = testCaseJsonObject.get("_ref").getAsString();
System.out.println(testCaseRef);
QueryRequest storyRequest = new QueryRequest("HierarchicalRequirement");
storyRequest.setWorkspace(workspaceRef);
storyRequest.setFetch(new Fetch("FormattedID", "Name"));
storyRequest.setQueryFilter(new QueryFilter("FormattedID", "=", storyid));
QueryResponse storyQueryResponse = restApi.query(storyRequest);;
if (storyQueryResponse.getTotalResultCount() == 0) {
System.out.println("Cannot find test story : " + storyid);
return;
}
JsonObject storyJsonObject = storyQueryResponse.getResults().get(0).getAsJsonObject();
String storyRef = storyJsonObject.get("_ref").getAsString();
System.out.println(storyRef);
JsonObject testCaseUpdate = new JsonObject();
testCaseUpdate.addProperty("WorkProduct", storyRef);
UpdateRequest updateTestCaseRequest = new UpdateRequest(testCaseRef,testCaseUpdate);
UpdateResponse updateTestCaseResponse = restApi.update(updateTestCaseRequest);
if (updateTestCaseResponse.wasSuccessful()) {
System.out.println("Successfully updated : " + testid + " WorkProduct after update: " + testCaseUpdate.get("WorkProduct"));
}
} finally {
restApi.close();
}
}
}

How do I get all the fields and value from a PDF file using iText?

Using the code below, I'm trying to get all the fields and their values, but it's only returning the field values. What do I need to do to get both?
package PrintFiled;
/*
Usage: java TestDocument <pdf file>
*/
import java.io.File;
import java.io.FileOutputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Iterator;
import java.util.Map;
import org.pdfbox.pdmodel.interactive.form.PDField;
import com.lowagie.text.pdf.AcroFields;
import com.lowagie.text.pdf.MultiColumnText;
import com.lowagie.text.pdf.PdfDictionary;
import com.lowagie.text.pdf.RadioCheckField;
import com.lowagie.text.pdf.PdfSignature;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
import com.lowagie.text.pdf.AcroFields;
import com.lowagie.text.pdf.AcroFields.*;
public class TestDocument
{
public static void main(String[] args) throws Exception
{
// get the destination
String location = "test/";
if (location != null && !location.endsWith(File.separator))
{
location = location + File.separator;
}
PdfReader reader = new PdfReader(location + "acc.pdf");
String name = "Output.pdf";
PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(location + name));
AcroFields form = stamp.getAcroFields();
String last = "subform[0].LastName[0]";
String first = "subform[0].FirstName[0]";
String ProcessDate="subform[0].ProcessDate[0]";
form.setField(last, "HRISTOV");
form.setField(first, "NEDKO");
form.setField(ProcessDate, "Process");
System.out.println("last Name :"+last.toString());
Map val =new HashMap();
//val=form.getFieldCache();
//System.out.println("Value :"+val);
Iterator it = val.entrySet().iterator();
while (it.hasNext())
{
Map.Entry pairs = (Map.Entry)it.next();
System.out.println("Key :"+pairs.getKey() + " = "+"Value :" + pairs.getValue());
}
Collection fieldlist = form.getFields().keySet();
// for (Iterator i = val.iterator(); i.hasNext(); )
for (Iterator i = fieldlist.iterator(); i.hasNext(); )
{
System.out.println(i.next().toString());
System.out.println("Value :"+val);
}
/*List fields = form.getFields();
Iterator fieldsIter = fields.iterator();
System.out.println(new Integer(fields.size()).toString()
+ " top-level fields were found on the form");
while (fieldsIter.hasNext()) {
PDField field = (PDField) fieldsIter.next();
// processField(field, "|--", field.getPartialName());
System.out.println("Field :"+fieldsIter);
}
*/
System.out.println("First Name:"+form.getField(first));
System.out.println("LastName :"+form.getField(last));
System.out.println("ProcessDate :"+form.getField(ProcessDate));
// close pdf stamper
stamp.setFormFlattening(true);
stamp.close();
reader.close();
}
}
To get all the fields and their values with iText:
// you only need a PdfStamper if you're going to change the existing PDF.
PdfReader reader = new PdfReader( pdfPath );
AcroFields fields = reader.getAcroFields();
Set<String> fldNames = fields.getFields().keySet();
for (String fldName : fldNames) {
System.out.println( fldName + ": " + fields.getField( fldName ) );
}
Beyond that, it would help if we could see a PDF that is giving you trouble.
Here's the answer updated for iText version 7.0.2:
PdfReader reader = new PdfReader( pdfPath );
PdfDocument document = new PdfDocument(reader);
PdfAcroForm acroForm = PdfAcroForm.getAcroForm(document, false);
Map<String,PdfFormField> fields = acroForm.getFormFields();
for (String fldName : fields.keySet()) {
System.out.println( fldName + ": " + fields.get( fldName ).getValueAsString() );
}
document.close();
reader.close();