Is it possible to operate a VM using Azure Functions managed ID?
I used a service principal to write code to operate a VM from my PC.
/**
* Main function which runs the actual sample.
*
* #param azure instance of the azure client
* #return true if sample runs successfully
*/
public static boolean runSample(Azure azure) {
final String rgName1 = "rgName";
final String linuxVMName = "vmName";
try {
VirtualMachine virtualMachine = azure.virtualMachines().getByResourceGroup(rgName1, linuxVMName);
System.out.println("Running Command");
List<String> commands = new ArrayList<>();
commands.add("whoami");
commands.add("touch /tmp/tmp.txt");
RunCommandInput runParams = new RunCommandInput()
.withCommandId("RunShellScript")
.withScript(commands);
RunCommandResult runResult = azure.virtualMachines().runCommand(virtualMachine.resourceGroupName(), virtualMachine.name(), runParams);
for (InstanceViewStatus resopnse : runResult.value()) {
System.out.println("code : " + resopnse.code());
System.out.println("status : " + resopnse.displayStatus());
System.out.println("message : " + resopnse.message());
}
return true;
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
System.out.println("final");
}
return false;
}
/**
* Main entry point.
*
* #param args the parameters
*/
public static void main(String[] args) {
try {
// Authenticate
String clientId = "XXXXXXXXX";
String domain = "XXXXXXXXXX";
String secret = "XXXXXXXXXX";
//MSICredentials credentials = new MSICredentials();
AzureTokenCredentials credentials = new ApplicationTokenCredentials(clientId, domain, secret, AzureEnvironment.AZURE);
Azure azure = Azure
.configure()
.withLogLevel(LogLevel.NONE)
.authenticate(credentials)
.withDefaultSubscription();
// Print selected subscription
System.out.println("Selected subscription: " + azure.subscriptionId());
runSample(azure);
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
I would like to modify some of this code to run on Azure Functions.
Is it possible to operate a VM using an Azure Functions managed ID without using a service principal?
According to my understanding, you want to use MSI to use Azure VM run command feature in Azure Function. If so, please refer to the following steps
Enable Azure MSI in Azure Function
Assing Azure RABC role to the MSI.
Running a command requires the Microsoft.Compute/virtualMachines/runCommand/action permission. The Virtual Machine Contributor role and higher levels have this permission.
Code. I use the package com.microsoft.azure:azure:1.38.0
String subscriptionId="";
AppServiceMSICredentials appServiceMsiCredentials = new AppServiceMSICredentials(AzureEnvironment.AZURE);
Azure azure = Azure
.configure()
.withLogLevel(LogLevel.NONE)
.authenticate(appServiceMsiCredentials)
.withSubscription(subscriptionId);
final String rgName1 = "testlinux_group";
final String linuxVMName = "testlinux";
try {
VirtualMachine virtualMachine = azure.virtualMachines().getByResourceGroup(rgName1, linuxVMName);
System.out.println("Running Command");
List<String> commands = new ArrayList<>();
commands.add("echo 1");
RunCommandInput runParams = new RunCommandInput()
.withCommandId("RunShellScript")
.withScript(commands);
RunCommandResult runResult = azure.virtualMachines().runCommand(virtualMachine.resourceGroupName(), virtualMachine.name(), runParams);
for (InstanceViewStatus res : runResult.value()) {
context.getLogger().info("code : " + res.code());
context.getLogger().info("status : " + res.displayStatus());
context.getLogger().info("message : " + res.message());
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
System.out.println("final");
}
Related
We use Minio as our backend service but we communicate with it through
software.amazon.awssdk.services.s3.S3Client
I see that this class contains method putBucketPolicy
but I don't see any method which allow to assign policy to user. Is there any way to assigh user policy using S3Client ?
Edited Answer:
Your updated question helped me determine what you were looking for.
You need to create a policy and assign it to a role. You can then assign that role to your user. The AWS SDK for Java 2.x provides support for all of these actions with IAM.
Here's what we can do:
1- Creating a policy
To create a new policy, provide the policy’s name and a JSON-formatted policy document in a CreatePolicyRequest to the IamClient’s createPolicy method.
Imports
import software.amazon.awssdk.core.waiters.WaiterResponse;
import software.amazon.awssdk.services.iam.model.CreatePolicyRequest;
import software.amazon.awssdk.services.iam.model.CreatePolicyResponse;
import software.amazon.awssdk.services.iam.model.GetPolicyRequest;
import software.amazon.awssdk.services.iam.model.GetPolicyResponse;
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.waiters.IamWaiter;
Code
public static String createIAMPolicy(IamClient iam, String policyName ) {
try {
// Create an IamWaiter object
IamWaiter iamWaiter = iam.waiter();
CreatePolicyRequest request = CreatePolicyRequest.builder()
.policyName(policyName)
.policyDocument(PolicyDocument).build();
CreatePolicyResponse response = iam.createPolicy(request);
// Wait until the policy is created
GetPolicyRequest polRequest = GetPolicyRequest.builder()
.policyArn(response.policy().arn())
.build();
WaiterResponse<GetPolicyResponse> waitUntilPolicyExists = iamWaiter.waitUntilPolicyExists(polRequest);
waitUntilPolicyExists.matched().response().ifPresent(System.out::println);
return response.policy().arn();
} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
return "" ;
}
You can check out CreatePolicy.java for complete example.
2- Attach a role policy
You can attach a policy to an IAM role by calling the IamClient’s attachRolePolicy method.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.services.iam.model.AttachRolePolicyRequest;
import software.amazon.awssdk.services.iam.model.AttachedPolicy;
import software.amazon.awssdk.services.iam.model.ListAttachedRolePoliciesRequest;
import software.amazon.awssdk.services.iam.model.ListAttachedRolePoliciesResponse;
import java.util.List;
Code
public static void attachIAMRolePolicy(IamClient iam, String roleName, String policyArn ) {
try {
ListAttachedRolePoliciesRequest request = ListAttachedRolePoliciesRequest.builder()
.roleName(roleName)
.build();
ListAttachedRolePoliciesResponse response = iam.listAttachedRolePolicies(request);
List<AttachedPolicy> attachedPolicies = response.attachedPolicies();
// Ensure that the policy is not attached to this role
String polArn = "";
for (AttachedPolicy policy: attachedPolicies) {
polArn = policy.policyArn();
if (polArn.compareTo(policyArn)==0) {
System.out.println(roleName +
" policy is already attached to this role.");
return;
}
}
AttachRolePolicyRequest attachRequest =
AttachRolePolicyRequest.builder()
.roleName(roleName)
.policyArn(policyArn)
.build();
iam.attachRolePolicy(attachRequest);
System.out.println("Successfully attached policy " + policyArn +
" to role " + roleName);
} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
System.out.println("Done");
}
You can check out AttachRolePolicy.java for complete example.
Bonus Content
Scenario for create a user and assume a role
The following code example shows how to:
Create a user who has no permissions.
Create a role that grants permission to list Amazon S3 buckets for the account.
Add a policy to let the user assume the role.
Assume the role and list Amazon S3 buckets using temporary credentials.
Delete the policy, role, and user.
/*
To run this Java V2 code example, set up your development environment, including your credentials.
For information, see this documentation topic:
https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
This example performs these operations:
1. Creates a user that has no permissions.
2. Creates a role and policy that grants Amazon S3 permissions.
3. Creates a role.
4. Grants the user permissions.
5. Gets temporary credentials by assuming the role. Creates an Amazon S3 Service client object with the temporary credentials.
6. Deletes the resources.
*/
public class IAMScenario {
public static final String DASHES = new String(new char[80]).replace("\0", "-");
public static final String PolicyDocument =
"{" +
" \"Version\": \"2012-10-17\"," +
" \"Statement\": [" +
" {" +
" \"Effect\": \"Allow\"," +
" \"Action\": [" +
" \"s3:*\"" +
" ]," +
" \"Resource\": \"*\"" +
" }" +
" ]" +
"}";
public static void main(String[] args) throws Exception {
final String usage = "\n" +
"Usage:\n" +
" <username> <policyName> <roleName> <roleSessionName> <fileLocation> <bucketName> \n\n" +
"Where:\n" +
" username - The name of the IAM user to create. \n\n" +
" policyName - The name of the policy to create. \n\n" +
" roleName - The name of the role to create. \n\n" +
" roleSessionName - The name of the session required for the assumeRole operation. \n\n" +
" fileLocation - The file location to the JSON required to create the role (see Readme). \n\n" +
" bucketName - The name of the Amazon S3 bucket from which objects are read. \n\n" ;
if (args.length != 6) {
System.out.println(usage);
System.exit(1);
}
String userName = args[0];
String policyName = args[1];
String roleName = args[2];
String roleSessionName = args[3];
String fileLocation = args[4];
String bucketName = args[5];
Region region = Region.AWS_GLOBAL;
IamClient iam = IamClient.builder()
.region(region)
.credentialsProvider(ProfileCredentialsProvider.create())
.build();
System.out.println(DASHES);
System.out.println("Welcome to the AWS IAM example scenario.");
System.out.println(DASHES);
System.out.println(DASHES);
System.out.println(" 1. Create the IAM user.");
Boolean createUser = createIAMUser(iam, userName);
System.out.println(DASHES);
if (createUser) {
System.out.println(userName + " was successfully created.");
System.out.println(DASHES);
System.out.println("2. Creates a policy.");
String polArn = createIAMPolicy(iam, policyName);
System.out.println("The policy " + polArn + " was successfully created.");
System.out.println(DASHES);
System.out.println(DASHES);
System.out.println("3. Creates a role.");
String roleArn = createIAMRole(iam, roleName, fileLocation);
System.out.println(roleArn + " was successfully created.");
System.out.println(DASHES);
System.out.println(DASHES);
System.out.println("4. Grants the user permissions.");
attachIAMRolePolicy(iam, roleName, polArn);
System.out.println(DASHES);
System.out.println(DASHES);
System.out.println("*** Wait for 1 MIN so the resource is available");
TimeUnit.MINUTES.sleep(1);
System.out.println("5. Gets temporary credentials by assuming the role.");
System.out.println("Perform an Amazon S3 Service operation using the temporary credentials.");
assumeGivenRole(roleArn, roleSessionName, bucketName);
System.out.println(DASHES);
System.out.println(DASHES);
System.out.println("6 Getting ready to delete the AWS resources");
deleteRole(iam, roleName, polArn);
deleteIAMUser(iam, userName);
System.out.println(DASHES);
System.out.println(DASHES);
System.out.println("This IAM Scenario has successfully completed");
System.out.println(DASHES);
} else {
System.out.println(userName +" was not successfully created.");
}
}
public static Boolean createIAMUser(IamClient iam, String username ) {
try {
// Create an IamWaiter object
IamWaiter iamWaiter = iam.waiter();
CreateUserRequest request = CreateUserRequest.builder()
.userName(username)
.build();
// Wait until the user is created.
CreateUserResponse response = iam.createUser(request);
GetUserRequest userRequest = GetUserRequest.builder()
.userName(response.user().userName())
.build();
WaiterResponse<GetUserResponse> waitUntilUserExists = iamWaiter.waitUntilUserExists(userRequest);
waitUntilUserExists.matched().response().ifPresent(System.out::println);
return true;
} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
return false;
}
public static String createIAMRole(IamClient iam, String rolename, String fileLocation ) throws Exception {
try {
JSONObject jsonObject = (JSONObject) readJsonSimpleDemo(fileLocation);
CreateRoleRequest request = CreateRoleRequest.builder()
.roleName(rolename)
.assumeRolePolicyDocument(jsonObject.toJSONString())
.description("Created using the AWS SDK for Java")
.build();
CreateRoleResponse response = iam.createRole(request);
System.out.println("The ARN of the role is "+response.role().arn());
return response.role().arn();
} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
return "";
}
public static String createIAMPolicy(IamClient iam, String policyName ) {
try {
// Create an IamWaiter object.
IamWaiter iamWaiter = iam.waiter();
CreatePolicyRequest request = CreatePolicyRequest.builder()
.policyName(policyName)
.policyDocument(PolicyDocument).build();
CreatePolicyResponse response = iam.createPolicy(request);
// Wait until the policy is created.
GetPolicyRequest polRequest = GetPolicyRequest.builder()
.policyArn(response.policy().arn())
.build();
WaiterResponse<GetPolicyResponse> waitUntilPolicyExists = iamWaiter.waitUntilPolicyExists(polRequest);
waitUntilPolicyExists.matched().response().ifPresent(System.out::println);
return response.policy().arn();
} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
return "" ;
}
public static void attachIAMRolePolicy(IamClient iam, String roleName, String policyArn ) {
try {
ListAttachedRolePoliciesRequest request = ListAttachedRolePoliciesRequest.builder()
.roleName(roleName)
.build();
ListAttachedRolePoliciesResponse response = iam.listAttachedRolePolicies(request);
List<AttachedPolicy> attachedPolicies = response.attachedPolicies();
String polArn;
for (AttachedPolicy policy: attachedPolicies) {
polArn = policy.policyArn();
if (polArn.compareTo(policyArn)==0) {
System.out.println(roleName + " policy is already attached to this role.");
return;
}
}
AttachRolePolicyRequest attachRequest = AttachRolePolicyRequest.builder()
.roleName(roleName)
.policyArn(policyArn)
.build();
iam.attachRolePolicy(attachRequest);
System.out.println("Successfully attached policy " + policyArn + " to role " + roleName);
} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
}
// Invoke an Amazon S3 operation using the Assumed Role.
public static void assumeGivenRole(String roleArn, String roleSessionName, String bucketName) {
StsClient stsClient = StsClient.builder()
.region(Region.US_EAST_1)
.build();
try {
AssumeRoleRequest roleRequest = AssumeRoleRequest.builder()
.roleArn(roleArn)
.roleSessionName(roleSessionName)
.build();
AssumeRoleResponse roleResponse = stsClient.assumeRole(roleRequest);
Credentials myCreds = roleResponse.credentials();
String key = myCreds.accessKeyId();
String secKey = myCreds.secretAccessKey();
String secToken = myCreds.sessionToken();
// List all objects in an Amazon S3 bucket using the temp creds.
Region region = Region.US_EAST_1;
S3Client s3 = S3Client.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsSessionCredentials.create(key, secKey, secToken)))
.region(region)
.build();
System.out.println("Created a S3Client using temp credentials.");
System.out.println("Listing objects in "+bucketName);
ListObjectsRequest listObjects = ListObjectsRequest.builder()
.bucket(bucketName)
.build();
ListObjectsResponse res = s3.listObjects(listObjects);
List<S3Object> objects = res.contents();
for (S3Object myValue : objects) {
System.out.println("The name of the key is " + myValue.key());
System.out.println("The owner is " + myValue.owner());
}
} catch (StsException e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
public static void deleteRole(IamClient iam, String roleName, String polArn) {
try {
// First the policy needs to be detached.
DetachRolePolicyRequest rolePolicyRequest = DetachRolePolicyRequest.builder()
.policyArn(polArn)
.roleName(roleName)
.build();
iam.detachRolePolicy(rolePolicyRequest);
// Delete the policy.
DeletePolicyRequest request = DeletePolicyRequest.builder()
.policyArn(polArn)
.build();
iam.deletePolicy(request);
System.out.println("*** Successfully deleted "+polArn);
// Delete the role.
DeleteRoleRequest roleRequest = DeleteRoleRequest.builder()
.roleName(roleName)
.build();
iam.deleteRole(roleRequest);
System.out.println("*** Successfully deleted " +roleName);
} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
}
public static void deleteIAMUser(IamClient iam, String userName) {
try {
DeleteUserRequest request = DeleteUserRequest.builder()
.userName(userName)
.build();
iam.deleteUser(request);
System.out.println("*** Successfully deleted " + userName);
} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
}
public static Object readJsonSimpleDemo(String filename) throws Exception {
FileReader reader = new FileReader(filename);
JSONParser jsonParser = new JSONParser();
return jsonParser.parse(reader);
}
}
Original Answer:
PutBucketPolicy
If you don't have PutBucketPolicy permissions, Amazon S3 returns a 403 Access Denied error. If you have the correct permissions, but you're not using an identity that belongs to the bucket owner's account, Amazon S3 returns a 405 Method Not Allowed error.
You can check out for more from AWS API Reference: PutBucketPolicy
I am trying to call an RPG Logon program on an AS400 system from JAVA. The issue is whenever I give incorrect parameters, I get a response, such as user ID is incorrect, password is incorrect. When I give an incorrect path to the program, I do get the response saying "Object does not exist." However, when all the parameters are right, I don't get any response and the java program keep running without ending. What could be wrong? Code below:
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400Message;
import com.ibm.as400.access.AS400SecurityException;
import com.ibm.as400.access.ErrorCompletingRequestException;
import com.ibm.as400.access.ObjectDoesNotExistException;
import com.ibm.as400.access.ProgramCall;
import com.ibm.as400.access.ProgramParameter;
import java.beans.PropertyVetoException;
import java.io.IOException;
/**
* Test program to test the RPG call from Java.
*/
public class CallingAS400PGM {
private static final String HOST = "xxxxxx";
private static final String UID = "yyyyyyy";
private static final String PWD = "zzzzzzz";
public static void main(String[] args) {
String input = "testuser";
String fullProgramName = "/QSYS.lib/SEOBJP10.lib/LOGON.pgm";
AS400 as400 = null;
byte[] inputData;
byte[] outputData;
ProgramParameter[] parmList;
ProgramCall programCall;
try {
// Create an AS400 object
as400 = new AS400(HOST, UID, PWD);
// Create a parameter list
// The list must have both input and output parameters
parmList = new ProgramParameter[2];
// Convert the Strings to IBM format
inputData = input.getBytes("IBM285");
// Create the input parameter
parmList[0] = new ProgramParameter(inputData);
// Create the output parameter
//Prarameterised Constructor is for the OUTPUT LENGTH. here it is 10
parmList[1] = new ProgramParameter(10);
/**
* Create a program object specifying the name of the program and
* the parameter list.
*/
programCall = new ProgramCall(as400);
programCall.setProgram(fullProgramName, parmList);
// Run the program.
if (!programCall.run()) {
/**
* If the AS/400 is not run then look at the message list to
* find out why it didn't run.
*/
AS400Message[] messageList = programCall.getMessageList();
for (AS400Message message : messageList) {
System.out.println(message.getID() + " - " + message.getText());
}
} else {
/**
* Else the program is successfull. Process the output, which
* contains the returned data.
*/
System.out.println("CONNECTION IS SUCCESSFUL");
outputData = parmList[1].getOutputData();
String output = new String(outputData, "IBM285").trim();
System.out.println("Output is " + output);
}
} catch (PropertyVetoException | AS400SecurityException | ErrorCompletingRequestException | IOException | InterruptedException | ObjectDoesNotExistException e) {
System.err.println(":: Exception ::" + e.toString());
} finally {
try {
// Make sure to disconnect
if (as400 != null) {
as400.disconnectAllServices();
}
} catch (Exception e) {
System.err.println(":: Exception ::" + e.toString());
}
}
}
}
Carefully think about what parameter type,number of parameters are accepting from AS400 RPG program, and use communication only USERID.
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400Message;
import com.ibm.as400.access.AS400Text;
import com.ibm.as400.access.ProgramCall;
import com.ibm.as400.access.ProgramParameter;
public class CallingAS400PGM {
private static final String HOST = "192.168.1.1";//AS400 IP
private static final String UID = "UNAME"; //userid
private static final String PWD = "PWORD"; //password
public static void main(String[] args) {
//AS400 RPG progam path
String fullProgramName = "/QSYS.LIB/PBFORM12.LIB/PBFORM12CL.PGM";
AS400 as400 = null;
ProgramParameter[] parmList;//parameter list witch is accepting AS400 RPG program
ProgramCall programCall;
try {
// Create an AS400 object
as400 = new AS400(HOST, UID, PWD);
// Create a parameter list
// The list must have both input and output parameters
parmList = new ProgramParameter[2];
// Convert the Strings to IBM format
AS400Text nametext1 = new AS400Text(2);
AS400Text nametext2 = new AS400Text(200);
// Create the input parameter // get the exact patameter type and
length, if not this not be working
parmList[0] = new ProgramParameter(nametext1.toBytes("1"),2);
parmList[1] = new ProgramParameter(nametext2.toBytes("Ravinath
Fernando"),200);
// Create the output parameter
programCall = new ProgramCall(as400);
programCall.setProgram(fullProgramName, parmList);
if (!programCall.run()) {
/**
* If the AS/400 is not run then look at the message list to
* find out why it didn't run.
*/
AS400Message[] messageList = programCall.getMessageList();
for (AS400Message message : messageList) {
System.out.println(message.getID() + " - " + message.getText());
}
} else {
System.out.println("success");
/**
* Else the program is successfull. Process the output, which
* contains the returned data.
*/
//use same parameter type which will be return from AS400 program
AS400Text text1 = new AS400Text(2);
System.out.println(text1.toObject(parmList[0].getOutputData()));
AS400Text text2 = new AS400Text(200);
System.out.println(text2.toObject(parmList[1].getOutputData()));
}
as400.disconnectService(AS400.COMMAND);
//-----------------------
} catch (Exception e) {
e.printStackTrace();
System.err.println(":: Exception ::" + e.toString());
} finally {
try {
// Make sure to disconnect
if (as400 != null) {
as400.disconnectAllServices();
}
} catch (Exception e) {
System.err.println(":: Exception ::" + e.toString());
}
}
}
}
I'm not able to create SIB JMS topic or queue. I tried the below code. The code ran without any exception or error
public void createSIBJMSTopic(String topicName, String jndiName, String busName, String topicSpace) {
try {
String server = "server1";
String description = "abc";
Session session = new Session();
CommandMgr commandMgr = CommandMgr.getCommandMgr(client);
configService = new ConfigServiceProxy(client);
System.out.println("Commands list" + commandMgr.listAllCommands().toString());
AdminCommand cmd = commandMgr.createCommand("createSIBJMSTopic");
System.out.println(session);
ObjectName targetObject = configService.resolve(session, null, "Node=mbaastest40Node02,Server=server1")[0];
cmd.setTargetObject(targetObject);
cmd.setParameter("name", topicName);
cmd.setParameter("jndiName", jndiName);
cmd.setParameter("busName", busName);
cmd.setParameter("topicSpace", topicSpace);
System.out.println("Before Execute");
cmd.execute();
CommandResult result = cmd.getCommandResult();
System.out.println("after execute");
if (result.isSuccessful())
System.out.println(result.toString());
if (!result.isSuccessful())
throw new AdminException(result.getException());
System.out.println("done");
configService.save(session, true);
System.out.println("After save");
}
catch (Exception e) {
e.printStackTrace();
}
}
You need to link the AdminCommand with the config Session via:
AdminCommand cmd = commandMgr.createCommand("createSIBJMSTopic");
cmd.setConfigSession(session);
You should also note the recommendation to call configService.discard(session) when done:
Here's a good getting started article that may help too.
I am trying to create contact from my application of java in infusion soft, but failed to get response. sometime i got connection timeout error, sometime got error 596.
My example code is under fellow:
public static void addContact() {
try {
//Sets up the java client, including the api url
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setEnabledForExtensions(true);
config.setConnectionTimeout(60 * 1000);
config.setReplyTimeout(60 * 1000);
config.setServerURL(new URL(\"https://api.infusionsoft.com/\"));
XmlRpcClient client = new XmlRpcClient();
client.setConfig(config);
//The secure encryption key
String key = \"sdfsdfsdfsdfs34534534534534\";
/**
* ***********************************************
* *
* ADD CONTACT TO DATABASE *
* ***********************************************
*/
List parameters = new ArrayList();
Map contactData = new HashMap();
contactData.put(\"FirstName\", \"Java John\");
contactData.put(\"LastName\", \"Doe\");
contactData.put(\"Email\", \"john#doe.com\");
parameters.add(key); //The secure key
//parameters.add(\"Contact\"); //The table we will be adding to
parameters.add(contactData); //The data to be added
//Make the call
Integer contactId = (Integer) client.execute(\"ContactService.add\", parameters);
System.out.println(\"Contact added was \" + contactId);
} catch (MalformedURLException ex) {
System.out.println(ex);
} catch (XmlRpcException ex) {
System.out.println(ex);
}
}
how do i create a contact in infusion soft using XMLRPC service in java? can i have example code?
This is complete code to create a contact in infusion soft.
Key: The key parametter is the secret key provided by the infusion soft while creating account
URL: "https://myApp.infusionsoft.com:443/api/xmlrpc", need to write name of your app on the place of 'myApp'.
public static void addContact() {
try {
//Sets up the java client, including the api url
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setServerURL(new URL("https://myApp.infusionsoft.com:443/api/xmlrpc"));
XmlRpcClient client = new XmlRpcClient();
client.setConfig(config);
//The secure encryption key
String key = "34534k34h5k34hj34k5hhk";
/**
* ***********************************************
* *
* ADD CONTACT TO DATABASE *
* ***********************************************
*/
List parameters = new ArrayList();
Map contactData = new HashMap();
contactData.put("FirstName", "Java John");
contactData.put("LastName", "Doe");
contactData.put("Email", "john#doe.com");
parameters.add(key); //The secure key
//parameters.add("Contact"); //The table we will be adding to
parameters.add(contactData); //The data to be added
//Make the call
Integer contactId = (Integer) client.execute("ContactService.add", parameters);
System.out.println("Contact added was " + contactId);
} catch (MalformedURLException ex) {
System.out.println(ex);
} catch (XmlRpcException ex) {
System.out.println(ex);
}
}
It is complete working code after spending 3 days i am able to get solution.
i am running a workflow which has java code which in turn launches another oozie workflow. the main workflow is working fine but the workflow launched from the java code is always in suspended status. i am unable to resume it because the user for that is mapred and not me. any idea what might be the problem?
here's my main workflow
<java>
<job-tracker>${jobTracker}</job-tracker>
<name-node>${nameNode}</name-node>
<main-class>com.last.play.LaunchJob</main-class>
<arg>currentUser=${currentUser}</arg>
</java>
and here's the java code:
Map<String, String> commandArgs = getActionArgs(args);
Path appPropertyPath = new Path("/user/cmahajan/app.properties");
Path jobPropertyPath = new Path("/user/cmahajan/job.properties");
OozieClient wc = new OozieClient("http://host07.com:11000/oozie");
String userName = commandArgs.get("currentUser");
System.out.println("User Name recieved ::" + userName);
Configuration trial = new Configuration();
FileSystem fs = FileSystem.get(trial);
Properties conf = wc.createConfiguration();
Properties jobProperties = new Properties();
Properties appProperties = new Properties();
appProperties.load(fs.open(appPropertyPath));
String version = appProperties.getProperty("version");
jobProperties.load(fs.open(jobPropertyPath));
for (Object key : jobProperties.keySet()) {
String propValue = jobProperties.getProperty((String) key);
propValue = propValue.replaceAll("\\$\\{user.name\\}", userName);
conf.setProperty((String) key, propValue);
System.out.println("Key ::" + key);
System.out.println("Value ::" + propValue);
System.out.println(" ===================");
}
String appsRoot = "${wfsBasePath}/" + version + "/apps";
conf.setProperty("appsRoot", appsRoot);
try {
String jobId = wc.run(conf);
System.out.println("Workflow job submitted");
while (wc.getJobInfo(jobId).getStatus() == WorkflowJob.Status.RUNNING) {
System.out.println("Workflow job running ...");
Thread.sleep(10 * 1000);
}
System.out.println("Workflow job completed ...");
System.out.println(wc.getJobInfo(jobId));
} catch (OozieClientException oozieClientException) {
oozieClientException.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
You can use the UserGroupInformation to set the user.
UserGroupInformation ugi = UserGroupInformation.createRemoteUser(username);
ugi.doAs(new PrivilegedExceptionAction<MyMapReduceWrapperClass>() {
public Object run() throws Exception {
MyMapReduceWrapperClass mr = new MyMapReduceWrapperClass();
ToolRunner.run(mr, null);
return mr;
}
});