I'm having this error :
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
ContentModel cannot be resolved to a variable
at test2CMIS.Test.main(Test.java:39)"
And I dont understand from where it comes, here is my code :
public class Test {
public static void main(String[] args){
Test atest = new Test();
Session session = atest.iniSession();
AuthenticationService authenticationService=null;
PersonService personService = null;
if (authenticationService.authenticationExists("test") == false)
{
authenticationService.createAuthentication("test", "changeMe".toCharArray());
PropertyMap ppOne = new PropertyMap(4);
ppOne.put(ContentModel.PROP_USERNAME, "test");
ppOne.put(ContentModel.PROP_FIRSTNAME, "firstName");
ppOne.put(ContentModel.PROP_LASTNAME, "lastName");
ppOne.put(ContentModel.PROP_EMAIL, "test"+"#example.com");
personService.createPerson(ppOne);
}
}
I did import the : import org.alfresco.model.ContentModel; and a lot of others librarys for my code.
Thx for help.
The code I'm using and I left some things that I tried too in comments so you can see what things I have done:
import java.io.File;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import org.alfresco.service.cmr.security.*;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.model.ContentModel;
import java.util.Iterator;
import org.alfresco.repo.jscript.People;
import org.alfresco.repo.security.authentication.AuthenticationException;
import org.alfresco.service.cmr.security.AuthenticationService;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.namespace.QName;
import org.alfresco.util.PropertyMap;
import org.apache.chemistry.opencmis.client.api.CmisObject;
import org.apache.chemistry.opencmis.client.api.Document;
import org.apache.chemistry.opencmis.client.api.Folder;
import org.apache.chemistry.opencmis.client.api.Session;
import org.apache.chemistry.opencmis.commons.PropertyIds;
import org.apache.chemistry.opencmis.commons.SessionParameter;
import org.apache.chemistry.opencmis.commons.enums.BindingType;
import org.apache.chemistry.opencmis.commons.enums.VersioningState;
import org.apache.chemistry.opencmis.commons.exceptions.CmisContentAlreadyExistsException;
import org.apache.chemistry.opencmis.commons.exceptions.CmisUnauthorizedException;
import org.apache.chemistry.opencmis.client.util.FileUtils;
import org.apache.chemistry.opencmis.client.runtime.SessionFactoryImpl;
public class Test {
public static void main(String[] args){
Test atest = new Test();
Session session = atest.iniSession();
AuthenticationService authenticationService=new AuthenticationServiceImpl();
PersonService personService = new PersonServiceImpl();
HashMap<QName, Serializable> properties = new HashMap<QName, Serializable>();
properties.put(ContentModel.PROP_USERNAME, "test");
properties.put(ContentModel.PROP_FIRSTNAME, "test");
properties.put(ContentModel.PROP_LASTNAME, "qsdqsd");
properties.put(ContentModel.PROP_EMAIL, "wshAlors#gmail.com");
properties.put(ContentModel.PROP_ENABLED, Boolean.valueOf(true));
properties.put(ContentModel.PROP_ACCOUNT_LOCKED, Boolean.valueOf(false));
personService.createPerson(properties);
authenticationService.createAuthentication("test", "changeme".toCharArray());
authenticationService.setAuthenticationEnabled("test", true);
authenticationService.getAuthenticationEnabled("Admin");
//String testAuthen = authenticationService.getCurrentTicket();
//System.out.println(testAuthen);
//QName username = QName.createQName("test");
//Map<QName,Serializable> propertiesUser = new HashMap<QName,Serializable>();
//propertiesUser.put(ContentModel.PROP_USERNAME,username);
//propertiesUser.put(ContentModel.PROP_FIRSTNAME,"test");
//propertiesUser.put(ContentModel.PROP_LASTNAME,"test");
//propertiesUser.put(ContentModel.PROP_EMAIL, "test#example.com");
//propertiesUser.put(ContentModel.PROP_PASSWORD,"0000");
//personService.createPerson(propertiesUser);
//if (authenticationService.authenticationExists("test") == false)
//{
// authenticationService.createAuthentication("test", "changeMe".toCharArray());
// PropertyMap ppOne = new PropertyMap(4);
// ppOne.put(ContentModel.PROP_USERNAME, "test");
// ppOne.put(ContentModel.PROP_FIRSTNAME, "test");
// ppOne.put(ContentModel.PROP_LASTNAME, "test");
// ppOne.put(ContentModel.PROP_EMAIL, "test#example.com");
//ppOne.put(ContentModel.PROP_JOBTITLE, "jobTitle");
// personService.createPerson(ppOne);
//}
}
public Session iniSession() {
Session session;
SessionFactoryImpl sf = SessionFactoryImpl.newInstance();
Map<String, String> parameters = new HashMap<String, String>();
Scanner reader = new Scanner(System.in);
System.out.println("Enter your logging : ");
String log = reader.nextLine();
System.out.println("Enter your password : ");
String pass = reader.nextLine();
parameters.put(SessionParameter.USER, log);
parameters.put(SessionParameter.PASSWORD, pass);
parameters.put(SessionParameter.BROWSER_URL, "http://127.0.0.1:8080/alfresco/api/-default-/public/cmis/versions/1.1/browser");
parameters.put(SessionParameter.BINDING_TYPE, BindingType.BROWSER.value());
parameters.put(SessionParameter.REPOSITORY_ID, "-default-");
try{
session = sf.createSession(parameters);
}catch(CmisUnauthorizedException cue){
session = null;
System.out.println("Wrong logging OR password !");
}
return session;
}
You are writing a runnable class which is not running the same process as Alfresco. In that sense, your class is running "remotely".
Because your class is running remotely to Alfresco, you are correct in using CMIS. But CMIS will only allow you to perform Create, Read, Update, and Delete (CRUD) functions against documents and folders in Alfresco. CMIS does not know how to create users or groups.
Your class will not be able to instantiate the AuthenticationService or PersonService. Those are part of the Alfresco Foundation API which only works when you are running in the same process as Alfresco, such as in an Action, a Behavior, or a Java-backed web script. In those cases, you will use Spring Dependency Injection to inject those services into your Java class. You would then put your class in a JAR that gets deployed into the Alfresco web application and loaded by the same classloader as Alfresco's.
If you want to create users remotely you should consider using the Alfresco REST API. Your runnable class can then use an HTTP client to invoke REST calls to create people and groups.
Thanks you for everything ! Thanks to you and researches I found out how to do it ! For the others who wonder how to do I'll post how I did and what site I used to understand it !
So you just need to manipulate JSON with Java because your alfresco people page (127.0.0.1:8080/alfresco/service/api/people) returns a JSON object, and you'll be able to create, delete, search... users! Thx again !
Sites :
https://api-explorer.alfresco.com/api-explorer/#/people
http://crunchify.com/json-manipulation-in-java-examples/
The code :
This is for creating an user :
public User createUser(String firstN, String lastN, String email, String pass, String authTicket) throws Exception{
try{
String url = "http://127.0.0.1:8080/alfresco/service/api/people?alf_ticket="+authTicket;
HttpClient httpclient = new HttpClient();
PostMethod mPost = new PostMethod(url);
//JSONObject obj = new JSONObject();
//JSONArray people = obj.getJSONArray("people");
JSONObject newUser = new JSONObject();
newUser.put("userName", firstN.toLowerCase().charAt(0)+lastN.toLowerCase());
newUser.put("enabled",true);
newUser.put("firstName",firstN);
newUser.put("lastName", lastN);
newUser.put("email", email);
newUser.put("quota",-1);
newUser.put("emailFreedDisable",false);
newUser.put("isDeleted",false);
newUser.put("isAdminAuthority",false);
newUser.put("password", pass);
//people.put(newUser);
//Response response = PostRequest(newUser.toString()));
StringRequestEntity requestEntity = new StringRequestEntity(
newUser.toString(),
"application/json",
"UTF-8");
mPost.setRequestEntity(requestEntity);
int statusCode2 = httpclient.executeMethod(mPost);
mPost.releaseConnection();
}catch(Exception e){
System.err.println("[ERROR] "+e);
}
return new User(firstN, lastN);
}
And if you want to get all the users you have on alfresco :
public ArrayList<User> getAllUsers(String authTicket)
{
ArrayList<User> allUsers = new ArrayList<>();
String lastName, firstName;
try{
String url = "http://127.0.0.1:8080/alfresco/service/api/people?alf_ticket="+authTicket;
HttpClient httpclient = new HttpClient();
GetMethod mPost = new GetMethod(url);
int statusCode1 = httpclient.executeMethod(mPost);
System.out.println("statusLine >>> "+statusCode1+"....."
+"\n status line \n"
+mPost.getStatusLine()+"\nbody \n"+mPost.getResponseBodyAsString());
JSONObject obj = new JSONObject(mPost.getResponseBodyAsString());
JSONArray people = obj.getJSONArray("people");
int n = people.length();
for(int i =0 ; i < n ; i++)
{
JSONObject peoples = people.getJSONObject(i);
User u = new User(peoples.getString("firstName"), peoples.getString("lastName"));
if (!allUsers.contains(u)){
allUsers.add(u);
}
}
}catch(Exception e){
System.err.println("[ERROR] "+e);
}
return(allUsers);
}
Related
I am using Google Bigquery V2 Java API. I am not able to find a way to get query results in JSON format.
In Bigquery Web UI we can see this JSON and Table form of results. see scrrenshot.
Is there any way to get the GetQueryResultsResponse as JSON, using Java API.
One option is to apply the TO_JSON_STRING function to the results of your query. For example,
#standardSQL
SELECT TO_JSON_STRING(t)
FROM (
SELECT x, y
FROM YourTable
WHERE z = 10
) AS t;
If you want all of the table's columns as JSON, you can use a simpler form:
#standardSQL
SELECT TO_JSON_STRING(t)
FROM YourTable AS t
WHERE z = 10;
I'm using a service account to access the BigQuery REST API to get the response in JSON format.
In order to use a service account, you will have to go to credentials (https://console.cloud.google.com/apis/credentials) and choose a project.
You will get a drop down like this:
Create a Service account for your project and download the secret file in the JSON format. Keep the JSON file in your file system and set the path to it. Check below image to set the file path:
So, now all you have to do in is use JAVA client api to consume the Big Query REST API.
Here's is a simple solution that I've been using for my project.
package com.example.bigquery;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import org.apache.log4j.Logger;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.common.io.CharStreams;
public class BigQueryDemo {
private static final String QUERY_URL_FORMAT = "https://www.googleapis.com/bigquery/v2/projects/%s/queries" + "?access_token=%s";
private static final String QUERY = "query";
private static final String QUERY_HACKER_NEWS_COMMENTS = "SELECT * FROM [bigquery-public-data:hacker_news.comments] LIMIT 1000";
private static final Logger logger = Logger.getLogger(BigQueryDemo.class);
static GoogleCredential credential = null;
static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
static final JsonFactory JSON_FACTORY = new JacksonFactory();
static {
// Authenticate requests using Google Application Default credentials.
try {
credential = GoogleCredential.getApplicationDefault();
credential = credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/bigquery"));
credential.refreshToken();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void implicit() {
String projectId = credential.getServiceAccountProjectId();
String accessToken = generateAccessToken();
// Set the content of the request.
Dataset dataset = new Dataset().addLabel(QUERY, QUERY_HACKER_NEWS_COMMENTS);
HttpContent content = new JsonHttpContent(JSON_FACTORY, dataset.getLabels());
// Send the request to the BigQuery API.
GenericUrl url = new GenericUrl(String.format(QUERY_URL_FORMAT, projectId, accessToken));
logger.debug("URL: " + url.toString());
String responseJson = getQueryResult(content, url);
logger.debug(responseJson);
}
private static String getQueryResult(HttpContent content, GenericUrl url) {
String responseContent = null;
HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
HttpRequest request = null;
try {
request = requestFactory.buildPostRequest(url, content);
request.setParser(JSON_FACTORY.createJsonObjectParser());
request.setHeaders(
new HttpHeaders().set("X-HTTP-Method-Override", "POST").setContentType("application/json"));
HttpResponse response = request.execute();
InputStream is = response.getContent();
responseContent = CharStreams.toString(new InputStreamReader(is));
} catch (IOException e) {
logger.error(e);
}
return responseContent;
}
private static String generateAccessToken() {
String accessToken = null;
if ((System.currentTimeMillis() > credential.getExpirationTimeMilliseconds())) {
accessToken = credential.getRefreshToken();
} else {
accessToken = credential.getAccessToken();
}
System.out.println(accessToken);
return accessToken;
}
}
Following is the Github link to the code: https://github.com/vslala/BigQueryRestSample
It is just a demo project to fetch JSON data from the BQ REST API. Do not use it in your project directly.
Let me know if you have any questions.
I'm trying to use the Google Custom Search API to, obviously, search in google. I've made this Java Agent in Lotus Notes.
The Main Class:
import java.util.List;
import lotus.domino.AgentBase;
import com.google.api.services.customsearch.model.Result;
public class JavaAgent extends AgentBase {
public void NotesMain() {
GoogleSearchClient gsc = new GoogleSearchClient();
String searchKeyWord = "test";
List<Result> resultList = gsc.getSearchResult(searchKeyWord);
if(resultList != null && resultList.size() > 0){
for(Result result: resultList){
System.out.println(result.getHtmlTitle());
System.out.println(result.getFormattedUrl());
System.out.println("----------------------------------------");
}
}
}
}
And that's the GoogleSearchClient class:
import java.util.Collections;
import java.util.List;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.services.customsearch.Customsearch;
import com.google.api.services.customsearch.model.Result;
import com.google.api.services.customsearch.model.Search;
public class GoogleSearchClient {
public List<Result> getSearchResult(String keyword){
String GOOGLE_SEARCH_URL = https://www.googleapis.com/customsearch/v1?";
//api key
String API_KEY = "xxxxxxxxxxxxxxxxxxxxx";
//custom search engine ID
String SEARCH_ENGINE_ID = "xxxxxxxxxx:xxxxxxxxxxxx";
String FINAL_URL= GOOGLE_SEARCH_URL + "key=" + API_KEY + "&cx=" + SEARCH_ENGINE_ID;
// Set up the HTTP transport and JSON factory
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new com.google.api.client.json.jackson2.JacksonFactory();
//HttpRequestInitializer initializer = (HttpRequestInitializer)new CommonGoogleClientRequestInitializer(API_KEY);
Customsearch customsearch = new Customsearch(httpTransport, jsonFactory,null);
List<Result> resultList = Collections.emptyList();
try {
Customsearch.Cse.List list = customsearch.cse().list(keyword);
list.setKey(API_KEY);
list.setCx(SEARCH_ENGINE_ID);
//num results per page
//list.setNum(2L);
//for pagination
list.setStart(10L);
Search results = list.execute();
resultList = results.getItems();
}catch (Exception e) {
e.printStackTrace();
}
return resultList;
}
}
I've got the code here.
This returns me this Exception:
java.security.AccessControlException: Access denied (java.lang.reflect.ReflectPermission suppressAccessChecks)
at java.security.AccessController.throwACE(AccessController.java:100)
at java.security.AccessController.checkPermission(AccessController.java:174)
at java.lang.SecurityManager.checkPermission(SecurityManager.java:544)
at COM.ibm.JEmpower.applet.AppletSecurity.superDotCheckPermission(AppletSecurity.java:1449)
at COM.ibm.JEmpower.applet.AppletSecurity.checkPermission(AppletSecurity.java:1617)
at COM.ibm.JEmpower.applet.AppletSecurity.checkPermission(AppletSecurity.java:1464)
at java.lang.reflect.AccessibleObject.setAccessible(AccessibleObject.java:118)
at com.google.api.client.util.FieldInfo.of(FieldInfo.java:97)
at com.google.api.client.util.ClassInfo.<init>(ClassInfo.java:172)
at com.google.api.client.util.ClassInfo.of(ClassInfo.java:90)
at com.google.api.client.util.GenericData.<init>(GenericData.java:79)
at com.google.api.client.util.GenericData.<init>(GenericData.java:61)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.<init>(AbstractGoogleClientRequest.java:109)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.<init>(AbstractGoogleJsonClientRequest.java:57)
at com.google.api.services.customsearch.CustomsearchRequest.<init>(CustomsearchRequest.java:43)
at com.google.api.services.customsearch.Customsearch$Cse$List.<init>(Customsearch.java:178)
at com.google.api.services.customsearch.Customsearch$Cse.list(Customsearch.java:154)
at GoogleSearchClient.getSearchResult(Unknown Source)
at JavaAgent.NotesMain(Unknown Source)
at lotus.domino.AgentBase.runNotes(Unknown Source)
at lotus.domino.NotesThread.run(Unknown Source)
I've digged this Exception in the internet and I've understood that the JVM doesn't think that I have the privileges and tried some things.
I added this permissions below in the "Java.policy" archive in my local machine and in the server, but it doesn't work.
grant { permission java.util.PropertyPermission "http.keepAlive", "read, write"; };
grant { permission java.security.AllPermission; }
I would try this but my Software Version is 9.
I tryed this same code in Eclipse and it worked just fine, so I think that's a Notes Security configuration that is wrong. I have to do in Lotus Notes because I have to save the informations in forms etc.
I changed the Runtime security Level to 3 (Allow restricted operations with full administration rights)
Any ideas that how can I go through this?
When I was working on WS-Security for my Web Service Consumer in Lotus, I got the same error. I found out that I can avoid this by using AccessController.doPrivileged method in my .jar file. So, you need to create separate .jar in your IDE and use it in your Lotus Agent.
Here is example of using AccessController.doPrivileged with your code:
import java.util.Collections;
import java.util.List;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.services.customsearch.Customsearch;
import com.google.api.services.customsearch.model.Result;
import com.google.api.services.customsearch.model.Search;
public class GoogleSearchClient {
public List<Result> getSearchResult(final String keyword){
String GOOGLE_SEARCH_URL = https://www.googleapis.com/customsearch/v1?";
//api key
final String API_KEY = "xxxxxxxxxxxxxxxxxxxxx";
//custom search engine ID
final String SEARCH_ENGINE_ID = "xxxxxxxxxx:xxxxxxxxxxxx";
String FINAL_URL= GOOGLE_SEARCH_URL + "key=" + API_KEY + "&cx=" + SEARCH_ENGINE_ID;
// Set up the HTTP transport and JSON factory
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new com.google.api.client.json.jackson2.JacksonFactory();
//HttpRequestInitializer initializer = (HttpRequestInitializer)new CommonGoogleClientRequestInitializer(API_KEY);
final Customsearch customsearch = new Customsearch(httpTransport, jsonFactory,null);
return AccessController.doPrivileged(
new PrivilegedAction<List<Result>>() {
#Override
public List<Result> run() {
List<Result> resultList = Collections.emptyList();
try {
Customsearch.Cse.List list = customsearch.cse().list(keyword);
list.setKey(API_KEY);
list.setCx(SEARCH_ENGINE_ID);
//num results per page
//list.setNum(2L);
//for pagination
list.setStart(10L);
Search results = list.execute();
resultList = results.getItems();
}catch (Exception e) {
e.printStackTrace();
}
return resultList;
}
});
}
}
Am trying to update testcase results in Rally Tool by using the below code:
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.testng.annotations.Test;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.rallydev.rest.RallyRestApi;
import com.rallydev.rest.request.CreateRequest;
import com.rallydev.rest.request.GetRequest;
import com.rallydev.rest.request.QueryRequest;
import com.rallydev.rest.response.CreateResponse;
import com.rallydev.rest.response.GetResponse;
import com.rallydev.rest.response.QueryResponse;
import com.rallydev.rest.util.Fetch;
import com.rallydev.rest.util.QueryFilter;
import com.rallydev.rest.util.Ref;
public class RallyStatusUpdate {
#Test
public void f() throws IOException, URISyntaxException {
// Create and configure a new instance of RallyRestApi
RallyRestApi restApi = new RallyRestApi(new URI("https://rally1.rallydev.com"),"user#company.com", "123");
restApi.setWsapiVersion("2.0.1");
restApi.setApplicationName("Add Test Case Result");
//Query User
QueryRequest userRequest = new QueryRequest("user");
userRequest.setFetch(new Fetch("user", "Subscription", "DisplayName"));
userRequest.setQueryFilter(new QueryFilter("user", "=", "user#company.com"));
QueryResponse userQueryResponse = restApi.query(userRequest);
JsonArray userQueryResults = userQueryResponse.getResults();
JsonElement userQueryElement = userQueryResults.get(0);
JsonObject userQueryObject = userQueryElement.getAsJsonObject();
String userRef = userQueryObject.get("_ref").getAsString();
// Query for Test Case to which we want to add results
QueryRequest testCaseRequest = new QueryRequest("TC_001_Automation_Sample_Test");
testCaseRequest.setFetch(new Fetch("FormattedID","TC_001_Automation_Sample_Test"));
testCaseRequest.setQueryFilter(new QueryFilter("FormattedID", "=", "TC5238"));
QueryResponse testCaseQueryResponse = restApi.query(testCaseRequest);
JsonObject testCaseJsonObject = testCaseQueryResponse.getResults().get(0).getAsJsonObject();
String testCaseRef = testCaseQueryResponse.getResults().get(0).getAsJsonObject().get("_ref").getAsString();
try{
//Add a Test Case Result
System.out.println("Creating Test Case Result...");
JsonObject newTestCaseResult = new JsonObject();
newTestCaseResult.addProperty("Verdict", "Pass");
newTestCaseResult.addProperty("Date", "2015-07-16T18:00:00.000Z");
newTestCaseResult.addProperty("Notes", "Automated Selenium Test Runs");
newTestCaseResult.addProperty("Build", "2015.07.16.0020101");
newTestCaseResult.addProperty("Tester", userRef);
newTestCaseResult.addProperty("TestCase", testCaseRef);
CreateRequest createRequest = new CreateRequest("testcaseresult", newTestCaseResult);
CreateResponse createResponse = restApi.create(createRequest);
if(createResponse.wasSuccessful()){
// println(String.format("Created %s", createResponse.getObject().get("_ref").getAsString()));
//Read Test Case
String ref = Ref.getRelativeRef(createResponse.getObject().get("_ref").getAsString());
System.out.println(String.format("\nReading Test Case Result %s...", ref));
GetRequest getRequest = new GetRequest(ref);
getRequest.setFetch(new Fetch("Date", "Verdict"));
GetResponse getResponse = restApi.get(getRequest);
JsonObject obj = getResponse.getObject();
//println(String.format("Read Test Case Result. Date = %s, Verdict = %s", obj.get("Date").getAsString(), obj.get("Verdict").getAsString()));
} else {
String[] createErrors;
createErrors = createResponse.getErrors();
System.out.println("Error occurred creating Test Case: ");
for (int i=0; i<createErrors.length;i++) {
System.out.println(createErrors[i]);
}
}
}
finally{
restApi.close();
}
}
}
however I am getting "HTTP/1.1 401 SSO Redirection !" error.
As SO answers pointed 401 error maybe due to authentication issue, I changed with different logins/environment it did not work.
If your organization uses SSO to access Rally, using an API Key is a good way to connect to CA Agile Central via the Java SDK, without the need to do the SAML handshaking. API Key details are included in this article:
http://www.ca.com/us/services-support/ca-support/ca-support-online/knowledge-base-articles.TEC01000001898.html?intcmp=searchresultclick&resultnum=2
Also, you should set your WSAPI version string to "v2.0" as there's no "2.0.1"
We are using the Java Rest API to export data.
For the HierarchicalRequirement object, how do we access the email address for the Owner?
Owner is a reference to a User object, and this object's fields need to be included in the fetch, for exaple:
storyRequest.setFetch(new Fetch("Name","Owner","UserName", "EmailAddress"));
Here is the full code:
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;
import java.net.URISyntaxException;
public class aRESTstories {
public static void main(String[] args) throws URISyntaxException, IOException {
String host = "https://rally1.rallydev.com";
String username = "user#co.com";
String password = "secret";
String projectRef = "/project/2222";
String workspaceRef = "/workspace/1111";
String applicationName = "RESTExampleStoriesChildren";
RallyRestApi restApi = new RallyRestApi(
new URI(host),
username,
password);
restApi.setApplicationName(applicationName);
System.out.println(restApi.getWsapiVersion()); //v.2.0 by default when using 2.0.2 jar
QueryRequest storyRequest = new QueryRequest("HierarchicalRequirement");
storyRequest.setFetch(new Fetch("Name","Owner","UserName", "EmailAddress"));
storyRequest.setLimit(1000);
storyRequest.setScopedDown(false);
storyRequest.setScopedUp(false);
storyRequest.setWorkspace(workspaceRef);
storyRequest.setProject(projectRef);
storyRequest.setQueryFilter(new QueryFilter("FormattedID", "=", "US16"));
QueryResponse storyQueryResponse = restApi.query(storyRequest);
JsonObject storyJsonObject = storyQueryResponse.getResults().get(0).getAsJsonObject();
System.out.println("Name: " + storyJsonObject.get("Name"));
JsonObject userObject = storyJsonObject.get("Owner").getAsJsonObject().getAsJsonObject();
System.out.println(userObject.get("UserName"));
System.out.println(userObject.get("EmailAddress"));
}
}
i'm having trouble with java programming. This java is calling Google API which provide me with GData access
I'm having trouble when it's querying some query, resulting #5fa01e33. This is my code:
package com.thegroovie;
import java.net.URL;
import javax.swing.JOptionPane;
import com.google.gdata.client.DocumentQuery;
import com.google.gdata.client.docs.DocsService;
import com.google.gdata.data.docs.DocumentListEntry;
import com.google.gdata.data.docs.DocumentListFeed;
public class GDataExample {
public static void main(String[] args) {
String username = JOptionPane.showInputDialog(null,"Input Username");
String password = JOptionPane.showInputDialog(null,"Input Password");
try{
DocsService service = new DocsService("Document List demo");
service.setProtocolVersion(DocsService.Versions.V3);
service.setUserCredentials(username, password);
URL documentListFeedUrl = new
URL("https://docs.google.com/feeds/default/private/full");
DocumentListFeed feed = service.getFeed(documentListFeedUrl, DocumentListFeed.class);
for(DocumentListEntry entry : feed.getEntries()){
System.out.println(entry.getTitle().getPlainText());
}
System.out.println("*******************************");
String input_query = JOptionPane.showInputDialog(null,"Search : ");
DocumentQuery query = new DocumentQuery(documentListFeedUrl);
query.setFullTextQuery(input_query);
DocumentListFeed feeds = service.getFeed(query, DocumentListFeed.class);
System.out.print(feeds);
}
catch (Exception ex){
System.err.println("Exception "+ ex.getMessage());
}
}
}
How to resolve this?
Thank you
This does not look like as an error code. Rather you print the DocumentListFeed object which type doesn't have an overridden toString method. You can access the feed's contents with the appropriate accessor methods described in the docs.