Team foundation server getting users of a project using Java SDK - java

i'm trying to get all the users that belong to a project through the SDK for Java version 11.0.0 but i'm stuck.
With that code i retrieve the collections and the projects:
TeamFoundationServerEntity teamFoundationServer=configurationServer.getTeamFoundationServerEntity(true);
if (teamFoundationServer != null)
{
ProjectCollectionEntity[] projectCollections = teamFoundationServer.getProjectCollections();
for (ProjectCollectionEntity pce : projectCollections) {
System.out.println("Collection: "+pce.getDisplayName()+" "+pce.getDescription());
TeamProjectEntity[] tpe=pce.getTeamProjects();
for (TeamProjectEntity teamProjectEntity : tpe) {
System.out.println(" teamProjectEntity: "+teamProjectEntity.getDisplayName()+" * "+teamProjectEntity.getProjectURI());
}
}
}
Also with the following code taken from the example in the downloaded zip and has the groups information:
GUID[] resourceTypes = new GUID[]{
CatalogResourceTypes.PROJECT_COLLECTION
};
CatalogResource[] resources =
configurationServer.getCatalogService().queryResourcesByType(resourceTypes, CatalogQueryOptions.NONE);
if (resources != null)
{
for (CatalogResource resource : resources)
{
String instanceId = resource.getProperties().get("InstanceId");
TFSTeamProjectCollection tpc = configurationServer.getTeamProjectCollection(new GUID(instanceId));
System.out.println("TFSTeamProjectCollection");
System.out.println("\tName: " + tpc.getName().toString());
System.out.println("\tURI: " + tpc.getBaseURI());
ProjectCollection pc=tpc.getWorkItemClient().getProjects();
for (Project project : pc) {
System.out.println("---"+project.getName()+" * "+project.getID());
String[] grps=tpc.getWorkItemClient().getGroupDataProvider(project.getName()).getGroups();
}
}
}
I have found the class IdentityManagementService
IdentityManagementService ims=new IdentityManagementService(configurationServer);
but i don't know how to use the listApplicationGroups and readIdentities methods that maybe are useful to find a solution.
Has anyone some idea to get the users in every project group?
A few more trial after #Cece - MSFT answer and looking at the blog and the book Microsoft Team Foundation Server 2015 Cookbook. Using this code
TeamFoundationIdentity[] appGroups=ims.listApplicationGroups(project.getURI(), ReadIdentityOptions.EXTENDED_PROPERTIES);
for (TeamFoundationIdentity group : appGroups)
{
System.out.println(group.getDisplayName());
TeamFoundationIdentity[] groupMembers= ims.readIdentities(new IdentityDescriptor[]{group.getDescriptor()}, MembershipQuery.EXPANDED, ReadIdentityOptions.EXTENDED_PROPERTIES);
for (TeamFoundationIdentity member : groupMembers)
{
for(IdentityDescriptor memberID : member.getMembers())
{
TeamFoundationIdentity memberInfo=ims.readIdentity(IdentitySearchFactor.IDENTIFIER, memberID.getIdentifier(), MembershipQuery.EXPANDED, ReadIdentityOptions.EXTENDED_PROPERTIES);
System.out.println(memberInfo.getDisplayName());
}
}
}
the variable appGroups is always empty. Maybe the method project.getURI() is not suitable? If I put null
TeamFoundationIdentity[] tfi=ims.listApplicationGroups(null, ReadIdentityOptions.INCLUDE_READ_FROM_SOURCE);
for (TeamFoundationIdentity teamFoundationIdentity : tfi) {
System.out.println(teamFoundationIdentity.getDisplayName());
System.out.println(teamFoundationIdentity.getDescriptor().getIdentityType());
IdentityDescriptor[] mbs=teamFoundationIdentity.getMembers();
for (IdentityDescriptor mb : mbs) {
TeamFoundationIdentity mbi=ims.readIdentity(mb, MembershipQuery.EXPANDED, ReadIdentityOptions.EXTENDED_PROPERTIES);
System.out.println(mbi.getProperties());
}
}
the output is
[DefaultCollection]\Project Collection Administrators
Microsoft.TeamFoundation.Identity
[DefaultCollection]\Project Collection Build Administrators
Microsoft.TeamFoundation.Identity
[DefaultCollection]\Project Collection Build Service Accounts
Microsoft.TeamFoundation.Identity
[DefaultCollection]\Project Collection Proxy Service Accounts
Microsoft.TeamFoundation.Identity
[DefaultCollection]\Project Collection Service Accounts
Microsoft.TeamFoundation.Identity
[DefaultCollection]\Project Collection Test Service Accounts
Microsoft.TeamFoundation.Identity
[DefaultCollection]\Project Collection Valid Users
Microsoft.TeamFoundation.Identity
Why I can't get the Contributors, Readers and the other groups with project.getURI() in listApplicationGroups method? I can only get them with
String[] grps=tpc.getWorkItemClient().getGroupDataProvider(project.getName()).getGroups();

Check this blog. In this blog, author used IGroupSecurityService service to get the list of application groups and get the details of which group the user is a member.
But now, IGroupSecurityService is obsolete. You need to use the IIdentityManagementService or ISecurityService instead.
The code snippet should look like:
var sec = tfs.GetService<IIdentityManagementService>();
Identity[] appGroups = sec.ListApplicationGroups(Scope Uri);
foreach (Identity group in appGroups)
{
Identity[] groupMembers = sec.ReadIdentities(SearchFactor.Sid, new string[] { group.Sid }, QueryMembership.Expanded);
foreach (Identity member in groupMembers)
{
var groupM = new GroupMembership {GroupName = member.DisplayName, GroupSid = member.Sid};
if (member.Members != null)
{
foreach (string memberSid in member.Members)
{
Identity memberInfo = sec.ReadIdentity(SearchFactor.Sid, memberSid, QueryMembership.Expanded);
var userName = memberInfo.Domain + "\\" + memberInfo.AccountName;
Detailed steps, you can check the blog.

For anyone who is interested in this two link there is the answer:
get groups of project and get members of a group

Related

AmazonEC2Client describeInstances() returns zero Reservations in Java

While running "aws ec2 describe-instances" in command line, It gives list of all ec2 Instances but with Java AWS-SDK it's gives zero Reservations. Please see below code snippet,
AmazonEC2 ec2;
if (ec2 == null) {
AWSCredentialsProviderChain credentialsProvider = new
AWSCredentialsProviderChain(
new InstanceProfileCredentialsProvider(),
new ProfileCredentialsProvider("default"));
ec2 = new AmazonEC2Client(credentialsProvider);
}
for (Reservation reservation : ec2.describeInstances().getReservations()) {
for (Instance instance : reservation.getInstances()) {
System.out.println("TAG" + instance.getInstanceId());
}
}
`
The most likely cause is that it's not looking in the correct region.
Another possibility is that it throws an exception that you don't see. To verify that this is not the case, you need to insert some logging statements. At the very least, one before and after the for loop.
This is the code in Java 8 which I use to describe all instances from all the regions:
amazonEC2.describeRegions().getRegions().forEach(region -> {
System.out.println("Region : " + region.getRegionName());
amazonEC2 = AmazonEC2ClientBuilder.standard().withCredentials(awsprovider).withRegion(region.getRegionName()).build();
amazonEC2.describeInstances().getReservations().forEach(reservation -> {
reservation.getInstances().forEach(instance -> {
System.out.println(instance.getInstanceId());
});
});
});
Thanks,
Akshay

Why httpbuilder is not giving the exact JSON output?

I am trying to get the projectid of my project from JIRA using gradle script.I wrote few methods which basically try to get the JSON output and fetch the project id of that particular project but now i am not able to get the projectId from that. Below is the methods which i am using to get the JSON result. it's working fine but not giving me the exact JSON output.My project Name is TESTPROJECT and id is 12345.I am looking when you have fresh project and need to get the projectid of that project using JIRA request method.I pasted the below JSON output which doesn't have {} "" so not exactly JSON output.Can someone tell me how could I get the project id with below way or am I doing something wrong?
buildscript {
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
classpath 'org.codehaus.groovy.modules.http-builder:http-builder:0.7.1'
classpath 'org.apache.httpcomponents:httpmime:4.2.1'
classpath 'commons-io:commons-io:2.4'
}
}
ext {
jiraURL = "https://test.test.com/"
jiraProject = 'TESTPROJECT'
jiraUser = "test"
jiraPassword = "*****"
}
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.ContentType
def String authHeader() {
String userAndPassword = "${jiraUser}:${jiraPassword}"
String authHeader = 'Basic ' + userAndPassword.getBytes().encodeBase64().toString()
return authHeader
}
/*
* Get the Jira project details
*/
def Map getJiraprojectDetails(String projectName) {
Map json = jiraProjectRequest(
"project/${projectName}",
groovyx.net.http.Method.GET,
null,
'Get JIRA version failure - getJiraprojectDetails()'
)
existingProjectId = json.key.id[0]
if (existingProjectId == null || existingProjectId == 0)
throw new GradleException("Project was not found in JIRA")
return existingProjectId
}
def Map jiraProjectRequest(String path, groovyx.net.http.Method method, Map jsonBody, String failMessage) {
Map jsonResult = null
def jira = new HTTPBuilder("${jiraURL}/rest/api/2/${path}", ContentType.JSON)
jira.request(method) { req ->
headers.'Authorization' = authHeader()
requestContentType = ContentType.JSON
if (body != null)
body = jsonBody
response.success = { resp, json ->
println "$json"
jsonResult = json
println "$jsonResult"
}
response.failure = { resp ->
String message = "${failMessage}: ${resp.status} - ${resp.statusLine.reasonPhrase}"
throw new GradleException(message)
}
}
return jsonResult
}
def void makeNewversion() {
def projectName = "${jiraProject}"
println "$projectName"
projectid = getJiraprojectDetails(projectName)
}
task createJiraVersion() {
doLast {
if (project.hasProperty('createVersion')) {
makeNewversion()
}
}
}
JSON Output
[jira] Response data: -----
[jira] [expand:description,lead,url,projectKeys, self:https://test.test1.com/rest/api/2/project/48352, id:48352, key:TESTPROJECT, description:, lead:[self:https://test.test1.com/rest/api/2/user?username=C56765, key:C56765, name:C56765, avatarUrls:[48x48:https://test.test1.com/secure/useravatar?ownerId=C56765&avatarId=42213, 24x24:https://test.test1.com/secure/useravatar?size=small&ownerId=C56765&avatarId=42213, 16x16:https://test.test1.com/secure/useravatar?size=xsmall&ownerId=h156765&avatarId=42213, 32x32:https://test.test1.com/secure/useravatar?size=medium&ownerId=C56765&avatarId=42213], displayName:karry test, active:true], components:[], issueTypes:[[self:https://test.test1.com/rest/api/2/issuetype/1, id:1, description:A problem which impairs or prevents the functions or performance of the product or its related artifacts. It can be related to software, hardware or both., iconUrl:https://test.test1.com/secure/viewavatar?size=xsmall&avatarId=31313&avatarType=issuetype, name:Defect, subtask:false, avatarId:31313], [self:https://test.test1.com/rest/api/2/issuetype/66, id:66, description:Created by JIRA Software - do not edit or delete. Issue type for a big user story that needs to be broken down., iconUrl:https://test.test1.com/secure/viewavatar?size=xsmall&avatarId=31317&avatarType=issuetype, name:Epic, subtask:false, avatarId:31317], [self:https://test.test1.com/rest/api/2/issuetype/67, id:67, description:Created by JIRA Software - do not edit or delete. Issue type for a user story., iconUrl:https://test.test1.com/secure/viewavatar?size=xsmall&avatarId=31325&avatarType=issuetype, name:Story, subtask:false, avatarId:31325], [self:https://test.test1.com/rest/api/2/issuetype/10600, id:10600, description:, iconUrl:https://test.test1.com/secure/viewavatar?size=xsmall&avatarId=31324&avatarType=issuetype, name:Initiative, subtask:false, avatarId:31324], [self:https://test.test1.com/rest/api/2/issuetype/2, id:2, description:A new feature of the product., iconUrl:https://test.test1.com/secure/viewavatar?size=xsmall&avatarId=31321&avatarType=issuetype, name:New Feature, subtask:false, avatarId:31321], [self:https://test.test1.com/rest/api/2/issuetype/4, id:4, description:An enhancement to an existing feature., iconUrl:https://test.test1.com/secure/viewavatar?size=xsmall&avatarId=31320&avatarType=issuetype, name:Improvement, subtask:false, avatarId:31320], [self:https://test.test1.com/rest/api/2/issuetype/25, id:25, description:A formal request to change an existing, baselined project artifact. , iconUrl:https://test.test1.com/secure/viewavatar?size=xsmall&avatarId=31330&avatarType=issuetype, name:Change Request, subtask:false, avatarId:31330], [self:https://test.test1.com/rest/api/2/issuetype/3, id:3, description:A task that needs to be done., iconUrl:https://test.test1.com/secure/viewavatar?size=xsmall&avatarId=31328&avatarType=issuetype, name:Task, subtask:false, avatarId:31328], [self:https://test.test1.com/rest/api/2/issuetype/26, id:26, description:A risk is an uncertain future event or condition, with a probability of occurrence, and a potential for loss., iconUrl:https://test.test1.com/secure/viewavatar?size=xsmall&avatarId=31318&avatarType=issuetype, name:Risk, subtask:false, avatarId:31318], [self:https://test.test1.com/rest/api/2/issuetype/87, id:87, description:An impediment is something that makes it difficult to do or complete something in a project and thus requires action. It may be a project risks that has occurred and typically represents something upon which a decision and actions are needed. The decision may not necessarily change the scope, schedule or cost of the project but the lack of a decision would affect the schedule., iconUrl:https://test.test1.com/secure/viewavatar?size=xsmall&avatarId=31318&avatarType=issuetype, name:Impediment, subtask:false, avatarId:31318], [self:https://test.test1.com/rest/api/2/issuetype/8, id:8, description:An item discussed in a meeting that requires further action or work., iconUrl:https://test.test1.com/secure/viewavatar?size=xsmall&avatarId=31328&avatarType=issuetype, name:Action Item, subtask:false, avatarId:31328], [self:https://test.test1.com/rest/api/2/issuetype/83, id:83, description:, iconUrl:https://test.test1.com/secure/viewavatar?size=xsmall&avatarId=31314&avatarType=issuetype, name:Root Cause Analysis, subtask:false, avatarId:31314], [self:https://test.test1.com/rest/api/2/issuetype/58, id:58, description:Any issue, solution or improvement learned in a project that should be shared with other people and/or projects., iconUrl:https://test.test1.com/secure/viewavatar?size=xsmall&avatarId=31324&avatarType=issuetype, name:Lesson Learned, subtask:false, avatarId:31324], [self:https://test.test1.com/rest/api/2/issuetype/39, id:39, description:A summary of a meeting including participants, decisions, and resulting actions., iconUrl:https://test.test1.com/secure/viewavatar?size=xsmall&avatarId=39910&avatarType=issuetype, name:Meeting Minutes, subtask:false, avatarId:39910], [self:https://test.test1.com/rest/api/2/issuetype/55, id:55, description:An item for managing a review consisting of one or more review findings., iconUrl:https://test.test1.com/secure/viewavatar?size=xsmall&avatarId=31323&avatarType=issuetype, name:Review, subtask:false, avatarId:31323], [self:https://test.test1.com/rest/api/2/issuetype/43, id:43, description:Used to track and manage Process Compliance and Configuration Audits on a project., iconUrl:https://test.test1.com/secure/viewavatar?size=xsmall&avatarId=42820&avatarType=issuetype, name:Audit, subtask:false, avatarId:42820], [self:https://test.test1.com/rest/api/2/issuetype/63, id:63, description:Used for requesting the approval of a particular work product and collecting approval from multiple individuals., iconUrl:https://test.test1.com/secure/viewavatar?size=xsmall&avatarId=31316&avatarType=issuetype, name:Approval Request, subtask:false, avatarId:31316], [self:https://test.test1.com/rest/api/2/issuetype/5, id:5, description:A task that needs to be done., iconUrl:https://test.test1.com/secure/viewavatar?size=xsmall&avatarId=31328&avatarType=issuetype, name:Sub-Task, subtask:true, avatarId:31328], [self:https://test.test1.com/rest/api/2/issuetype/35, id:35, description:An item discussed in a meeting that requires further action or work., iconUrl:https://test.test1.com/secure/viewavatar?size=xsmall&avatarId=31328&avatarType=issuetype, name:Action Item (Sub-Issue), subtask:true, avatarId:31328], [self:https://test.test1.com/rest/api/2/issuetype/56, id:56, description:A defect, question, suggestion or other issue resulting from the review of a document or other artifact. , iconUrl:https://test.test1.com/secure/viewavatar?size=xsmall&avatarId=31323&avatarType=issuetype, name:Review Finding, subtask:true, avatarId:31323], [self:https://test.test1.com/rest/api/2/issuetype/62, id:62, description:, iconUrl:https://test.test1.com/images/icons/issuetypes/documentation.png, name:Mitigation Plan, subtask:true], [self:https://test.test1.com/rest/api/2/issuetype/61, id:61, description:An issue (non-compliance, recommendation) found during an audit., iconUrl:https://test.test1.com/secure/viewavatar?size=xsmall&avatarId=31323&avatarType=issuetype, name:Audit Finding, subtask:true, avatarId:31323], [self:https://test.test1.com/rest/api/2/issuetype/64, id:64, description:A sub-issue type used for capturing the approval (or disapproval) of an individual for a particular work product., iconUrl:https://test.test1.com/secure/viewavatar?size=xsmall&avatarId=31316&avatarType=issuetype, name:Approval, subtask:true, avatarId:31316]], assigneeType:PROJECT_LEAD, versions:[[self:https://test.test1.com/rest/api/2/version/98423, id:98423, name:TCD 1.2.3, archived:false, released:false, projectId:48352]], name:Test PAAS, roles:[CCB:https://test.test1.com/rest/api/2/project/48352/role/10020, L1 Support:https://test.test1.com/rest/api/2/project/48352/role/10050, Developers:https://test.test1.com/rest/api/2/project/48352/role/10001, Approvers:https://test.test1.com/rest/api/2/project/48352/role/10052, Administrators:https://test.test1.com/rest/api/2/project/48352/role/10002, Watcher:https://test.test1.com/rest/api/2/project/48352/role/10030, Bulkcloners:https://test.test1.com/rest/api/2/project/48352/role/10070, Testers:https://test.test1.com/rest/api/2/project/48352/role/10010, Users:https://test.test1.com/rest/api/2/project/48352/role/10000, L2 Support:https://test.test1.com/rest/api/2/project/48352/role/10051], avatarUrls:[48x48:https://test.test1.com/secure/projectavatar?avatarId=39413, 24x24:https://test.test1.com/secure/projectavatar?size=small&avatarId=39413, 16x16:https://test.test1.com/secure/projectavatar?size=xsmall&avatarId=39413, 32x32:https://test.test1.com/secure/projectavatar?size=medium&avatarId=39413], projectCategory:[self:https://test.test1.com/rest/api/2/projectCategory/18032, id:18032, name:Solutions, description:TO-12179], projectTypeKey:software]
Below is the code to get the project id
/*
* Get the Jira project ID for a project like 'ABC'
*/
def int getJiraProjectid(String jiraProject) {
int existingProjectId = 0
def json = [jiraprojectRequest()]
json.each {
existingProjectId = it."id".toInteger()
//println "$existingVersionId"
}
if (existingProjectId == 0)
throw new GradleException("Existing project ${jiraProject} was not found in JIRA")
return existingProjectId
}
def Map jiraprojectRequest() {
Map jsonResultList = null
def jira = new HTTPBuilder("${jiraURL}/rest/api/2/project/${jiraProject}", ContentType.JSON)
jira.request(groovyx.net.http.Method.GET) { req ->
headers.'Authorization' = authHeader()
response.success = { resp, json ->
project.getLogger().info('[jira] Response data: -----')
project.getLogger().info("[jira] $json")
project.getLogger().info('\n--------------------')
jsonResultList = json
}
response.failure = { resp ->
throw new GradleException("Get JIRA versions failure - jiraGetVersions(): ${resp.status} - ${resp.statusLine.reasonPhrase}")
}
}
return jsonResultList
}

On Camunda-Spring Integration TaskDefinition is null for active task

I have integrated Camunda Engine with Spring in our application. I want to find properties assigned to each active task for the running process instance. I am able to get the task instances with following code
List<Task> tasks = this.taskService.createTaskQuery().processInstanceId("12").list()
but if i cast task object into TaskEntity and then use getTaskDefinition() , I get null.
Other way to get task details is through ProcessDefinitionEntity.getTaskDefinitions() but it also returns null.
How should I get the task detail?
For read properties and documentation attributes use the BPMN Model API.
This example use a elementId for read both.
String processDefinitionId = repositoryService.createProcessDefinitionQuery()
.processDefinitionKey(DEFINITON_KEY).singleResult().getId();
BpmnModelInstance bpmnModelInstance = repositoryService.getBpmnModelInstance(processDefinitionId);
ServiceTask serviceTask = (ServiceTask) bpmnModelInstance.getModelElementById(ELEMENT_ID);
// Documentation, is a collection, but the modeler supports only one attribute
Collection<Documentation> documentations = serviceTask.getDocumentations();
// Properties
Collection<Property> properties = serviceTask.getProperties();
Above answer gave me a hint but didn't solve the problem completely so here is my code which is serving the purpose.
My usertask in .bpmn file looks like:
<bpmn:userTask id="Task_063x95d" name="Tech Task">
<bpmn:documentation>SUCCESS,FAIL</bpmn:documentation>
<bpmn:extensionElements>
<camunda:inputOutput>
<camunda:inputParameter name="language">Java</camunda:inputParameter>
<camunda:outputParameter name="Platform">Linux</camunda:outputParameter>
</camunda:inputOutput>
<camunda:properties>
<camunda:property name="user" value="Test_User" />
</camunda:properties>
</bpmn:extensionElements>
<bpmn:incoming>SequenceFlow_1xjoyjq</bpmn:incoming>
<bpmn:outgoing>SequenceFlow_028pkxo</bpmn:outgoing>
</bpmn:userTask>
I have analysed the .bpmn file and then just rendered its elements with help of below code
// Active tasks for currently running instanceId(input to below code)
List<Task> tasks = this.taskService.createTaskQuery().processInstanceId(instanceId).list();
String documentation= null;
for (Task task : tasks)
{
//This gives [documentation][1] field.
documentation = task.getDescription();
UserTaskImpl modelElementById = (UserTaskImpl) bpmnModelInstance.getModelElementById(tasks.get(0)
.getTaskDefinitionKey());
ExtensionElements childElementsByType2 = modelElementById.getExtensionElements();
Collection<ModelElementInstance> elements = childElementsByType2.getElements();
for (ModelElementInstance elem : elements)
{
//To access all properties.
if (elem instanceof CamundaPropertiesImpl)
{
CamundaPropertiesImpl camundaPropertiesImpl = (CamundaPropertiesImpl) elem;
Collection<CamundaProperty> camundaProperties = camundaPropertiesImpl.getCamundaProperties();
for (CamundaProperty test : camundaProperties)
{
System.out.println("camunda property name :" + test.getCamundaName() + " $ " + test.getCamundaValue());
}
}
else if (elem instanceof CamundaInputOutputImpl)
{
// To access input/output param
CamundaInputOutputImpl camundaInputOutputImpl = (CamundaInputOutputImpl) elem;
for (CamundaInputParameter test : camundaInputOutputImpl.getCamundaInputParameters())
{
log.info("camunda input params name :" + test.getCamundaName() + " $ " + test.getTextContent());
}
for (CamundaOutputParameter test : camundaInputOutputImpl.getCamundaOutputParameters())
{
log.info("camunda output params name :" + test.getCamundaName() + " $ " + test.getTextContent());
}
}
}
}

How to get client list using SOAP Web Services in Netsuite ERP?

I am really new to SOAP web services and to Netsuite ERP and I am trying to generate a report in my company where I need to obtain all the Clients and their Invoices using the data available in Netsuite ERP. I followed the Java and Axis tutorial they offer with their sample app for the ERP and I successfully created a Java project in Eclipse that consumes the WSDL for netsuite 2015-2 and compiles the needed classes to run the sample app. So, I followed an example found in their CRM exapmle app to obtain a Client's information but the only problem is that their example method needs you to introduce the Client's ID. Here is the sample code:
public int getCustomerList() throws RemoteException,
ExceededUsageLimitFault, UnexpectedErrorFault, InvalidSessionFault,
ExceededRecordCountFault, UnsupportedEncodingException {
// This operation requires a valid session
this.login(true);
// Prompt for list of internalIds and put in an array
_console
.write("\ninternalIds for records to retrieved (separated by commas): ");
String reqKeys = _console.readLn();
String[] internalIds = reqKeys.split(",");
return getCustomerList(internalIds, false);
}
private int getCustomerList(String[] internalIds, boolean isExternal)
throws RemoteException, ExceededUsageLimitFault,
UnexpectedErrorFault, InvalidSessionFault, ExceededRecordCountFault {
// Build an array of RecordRef objects and invoke the getList()
// operation to retrieve these records
RecordRef[] recordRefs = new RecordRef[internalIds.length];
for (int i = 0; i < internalIds.length; i++) {
RecordRef recordRef = new RecordRef();
recordRef.setInternalId(internalIds[i]);
recordRefs[i] = recordRef;
recordRefs[i].setType(RecordType.customer);
}
// Invoke getList() operation
ReadResponseList getResponseList = _port.getList(recordRefs);
// Process response from get() operation
if (!isExternal)
_console.info("\nRecords returned from getList() operation: \n");
int numRecords = 0;
ReadResponse[] getResponses = getResponseList.getReadResponse();
for (int i = 0; i < getResponses.length; i++) {
_console.info("\n Record[" + i + "]: ");
if (!getResponses[i].getStatus().isIsSuccess()) {
_console.errorForRecord(getStatusDetails(getResponses[i]
.getStatus()));
} else {
numRecords++;
Customer customer = (Customer) getResponses[i].getRecord();
_console.info(" internalId="
+ customer.getInternalId()
+ "\n entityId="
+ customer.getEntityId()
+ (customer.getCompanyName() == null ? ""
: ("\n companyName=" + customer
.getCompanyName()))
+ (customer.getEntityStatus() == null ? ""
: ("\n status=" + customer.getEntityStatus().getName()))
+ (customer.getEmail() == null ? ""
: ("\n email=" + customer.getEmail()))
+ (customer.getPhone() == null ? ""
: ("\n phone=" + customer.getPhone()))
+ "\n isInactive="
+ customer.getIsInactive()
+ (customer.getDateCreated() != null ? ""
: ("\n dateCreated=" + customer
.getDateCreated().toString())));
}
}
return numRecords;
}
So as you can see, this method needs the internal ID of each Customer which I find not useful as I have a many Customers and I don't want to pass each Customer's ID. I read their API docs (which I find hard to navigate and kind of useless) and I found a web service called getAll() that gives all the records given a getAllRecord object which requires a getAllRecordType object. However, the getAllRecordType object does not support Customer entities, so I can't obtain all the customers on the ERP this way.
Is there an easy way to obtain all the Customers in my Netsuite ERP (maybe using other thing rather than the SOAP Web Services they offer? I am desperate about this situation as understanding how Netsuite's Web Services API has been really troublesome.
Thanks!
You would normally use a search to select a list of customers. On a large account you would not normally get all customers on any regular basis. If you are trying to get the invoices you might just find it more practical to get those with a search.
You wrote "in your company". Are you trying to write an application of some sort? If this is an internal project (and even if it's not) you'll probably find using SuiteScripts much more efficient in terms of your time and frustration level.
I made it using the following code on my getCustomerList method:
CustomerSearch customerSrch = new CustomerSearch();
SearchResult searchResult = _port.search(customerSrch);
System.out.println(searchResult.getTotalRecords());
RecordList rl = searchResult.getRecordList();
for (int i = 0; i <searchResult.getTotalRecords()-1; i++) {
Record r = rl.getRecord(i);
System.out.println("Customer # " + i);
Customer testcust = (Customer)r;
System.out.println("First Name: " + testcust.getFirstName());
}

What is the proper way to check if a file/folder in a Box account is read-only using the Box Android library (apiV2)?

I am working on an android app used to access a Box account. The problem I am facing is how to determine a folder/file in the user's account is read only (shared with him/her as a Viewer) so that the upload/delete operations can be disabled.
What I currently do is:
1) Get the items in a folder:
BoxCollection itemsCollection = _boxClient.getFoldersManager()
.getFolderItems(folderId, folderContentRequest);
String userMail = ...
ArrayList<BoxTypedObject> result = null;
2) Determine which one is folder, get it's collaborations, check if it's accessible by the logged-in user, and check whether he is an editor:
if (itemsCollection != null) {
result = itemsCollection.getEntries();
for(BoxTypedObject boxObject : result) {
if(boxObject instanceof BoxAndroidFolder) {
BoxAndroidFolder folder = (BoxAndroidFolder)boxObject;
List<BoxCollaboration> folderCollaborations = _boxClient.getFoldersManager().getFolderCollaborations(folder.getId(), null);
for(BoxCollaboration collaboration : folderCollaborations) {
if( userMail.equalsIgnoreCase(collaboration.getAccessibleBy().getLogin()) &&
!BoxCollaborationRole.EDITOR.equalsIgnoreCase(collaboration.getRole()))
System.out.println("" + folder.getName() + " is readonly");
}
}
}
}
So, is there a simpler and faster (fewer requests) way to get that property of a folder with the android SDK?
You can first check the owner of the folder (folder.getOwnedBy()), if it's the current user then you don't need to check collaborations. However if it's not the current user you'll have to check collaborations.

Categories