Soap Request using axis2 java in Eclipse - java

I want to make an insert operation in an import set table through the web service from ServiceNow with axis2 version 1.6.4
I used wsdl2java with the wsdl file to create classes in my java project.
After it, i created a new class Request on which i would build my soap request to the webservice.
I believe I have 2 (might be more) major problems:
Unserstanding the difference between a stub and a proxy, respectively, the classes ServiceNowSoapStub and ServiceNowSoapProxy and what is the purpose of each of them.
The existing insert method needs a lot of arguments and i wish to make inserts with a selected number of arguments. do i need to add that specific insert method to the architecture?
Here is what I have:
public class Request {
public static void main(String[] args) throws RemoteException {
try{
HttpTransportProperties.Authenticator basicAuthentication = new HttpTransportProperties.Authenticator();
basicAuthentication.setUsername("xxxx");
basicAuthentication.setPassword("xxxx");
ServiceNowSoapStub proxy = new ServiceNowSoapStub();
proxy._setProperty(org.apache.axis2.transport.http.HTTPConstants.CHUNKED, Boolean.FALSE);
proxy._setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, basicAuthentication);
BigDecimal actuals = new BigDecimal("0.04");
BigInteger appId = new BigInteger("3495766");
String appNonApp = "ApNon";
BigInteger productId = new BigInteger("704217");
BigInteger serviceId = new BigInteger("1537");
String serviceName = "IT";
String bpName = "BNK-RSK";
String method = "N";
String bsCode = "ITDV";
String customerCostCode = "30973250";
String customerCountry = "US";
String customerGroup = "Wealth";
String customerLegalEntity = "HB";
String dsId = "EU56";
BigInteger supplierCostCode = new BigInteger("675136");
String supplierCountry = "UK";
String supplierLegalEntity = "BR";
BigInteger total = new BigInteger ("411");
ServiceNowSoapProxy request = new ServiceNowSoapProxy("https://dev34363.service-now.com/u_it_actuals_import_set");
request.insertTest(actuals, appId, appNonApp, productId, serviceId, serviceName, bpName, method, bsCode, customerCostCode,
customerCountry, customerGroup, customerLegalEntity, dsId, supplierCostCode, supplierCountry, supplierLegalEntity, total);
} catch (org.apache.axis.AxisFault e) {
e.printStackTrace();
}
}
}
What am I doing wrong? or can please anyone refer me to some helpful link?
The wiki page of servicenow addressing this subject is a bit out of date so i can't solve my problem through it.
Thanks!

Related

How to add SAS for file services of azure in java?

I got code in c# or code for blob storage. I need some reference code in java to have SAS token for file storage in azure. The SAS may be applicable for account or services.
Code 1 :
static string GetAccountSASToken()
{
// To create the account SAS, you need to use your shared key credentials. Modify for your account.
const string ConnectionString = "DefaultEndpointsProtocol=https;AccountName=account-name;AccountKey=account-key";
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionString);
// Create a new access policy for the account.
SharedAccessAccountPolicy policy = new SharedAccessAccountPolicy()
{
Permissions = SharedAccessAccountPermissions.Read | SharedAccessAccountPermissions.Write | SharedAccessAccountPermissions.List,
Services = SharedAccessAccountServices.Blob | SharedAccessAccountServices.File,
ResourceTypes = SharedAccessAccountResourceTypes.Service,
SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),
Protocols = SharedAccessProtocol.HttpsOnly
};
// Return the SAS token.
return storageAccount.GetSharedAccessSignature(policy);
}
This code is about creating SAS token for account verification and expiry time.I need the same in java. I am not getting few things like, in first code how I can write the 'Permission' in java? I mean multiple in one line. Please provide equivalent java code for this.
Code 2 :
#Test
public String testFileSAS(CloudFileShare share, CloudFile file) throws InvalidKeyException,
IllegalArgumentException, StorageException, URISyntaxException, InterruptedException {
SharedAccessFilePolicy policy = createSharedAccessPolicy(EnumSet.of(SharedAccessFilePermissions.READ,
SharedAccessFilePermissions.LIST, SharedAccessFilePermissions.WRITE), 24);
FileSharePermissions perms = new FileSharePermissions();
// SharedAccessProtocols protocol = SharedAccessProtocols.HTTPS_ONLY;
perms.getSharedAccessPolicies().put("readperm", policy);
share.uploadPermissions(perms);
// Thread.sleep(30000);
CloudFile sasFile = new CloudFile(
new URI(file.getUri().toString() + "?" + file.generateSharedAccessSignature(null, "readperm")));
sasFile.download(new ByteArrayOutputStream());
// do not give the client and check that the new file's client has the
// correct permissions
CloudFile fileFromUri = new CloudFile(
PathUtility.addToQuery(file.getStorageUri(), file.generateSharedAccessSignature(null, "readperm")));
assertEquals(StorageCredentialsSharedAccessSignature.class.toString(),
fileFromUri.getServiceClient().getCredentials().getClass().toString());
// create credentials from sas
StorageCredentials creds = new StorageCredentialsSharedAccessSignature(
file.generateSharedAccessSignature(policy, null, null));
System.out.println("Generated SAS token is : " + file.generateSharedAccessSignature(policy, null, null));
String token = file.generateSharedAccessSignature(policy, null, null);
CloudFileClient client = new CloudFileClient(sasFile.getServiceClient().getStorageUri(), creds);
CloudFile fileFromClient = client.getShareReference(file.getShare().getName()).getRootDirectoryReference()
.getFileReference(file.getName());
assertEquals(StorageCredentialsSharedAccessSignature.class.toString(),
fileFromClient.getServiceClient().getCredentials().getClass().toString());
assertEquals(client, fileFromClient.getServiceClient());
// self written
// String sharedUri =
// file.generateSharedAccessSignature(policy,null,null);
// System.out.println("token created is : "+sharedUri);
return token;
}
private final static SharedAccessFilePolicy createSharedAccessPolicy(EnumSet<SharedAccessFilePermissions> sap,
int expireTimeInSeconds) {
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
calendar.setTime(new Date());
calendar.add(Calendar.HOUR, expireTimeInSeconds);
SharedAccessFilePolicy policy = new SharedAccessFilePolicy();
policy.setPermissions(sap);
policy.setSharedAccessExpiryTime(calendar.getTime());
return policy;
}
This code is a jUnit test. I don' want to import jUnit library. Want to do it in pure java.How I can convert the code? What I can use instead of assertEqauls?
Please consider the following code snippet in Java.
public static final String storageConnectionString = "DefaultEndpointsProtocol=https;AccountName=account-name;AccountKey=account-key";
public String getAccountSASToken() throws InvalidKeyException, URISyntaxException, StorageException {
CloudStorageAccount account = CloudStorageAccount.parse(storageConnectionString);
SharedAccessAccountPolicy policy = new SharedAccessAccountPolicy();
policy.setPermissions(EnumSet.of(SharedAccessAccountPermissions.READ, SharedAccessAccountPermissions.WRITE, SharedAccessAccountPermissions.LIST));
policy.setServices(EnumSet.of(SharedAccessAccountService.BLOB, SharedAccessAccountService.FILE) );
policy.setResourceTypes(EnumSet.of(SharedAccessAccountResourceType.SERVICE));
policy.setSharedAccessExpiryTime(Date.from(ZonedDateTime.now(ZoneOffset.UTC).plusHours(24L).toInstant()));
policy.setProtocols(SharedAccessProtocols.HTTPS_ONLY);
return account.generateSharedAccessSignature(policy);
}

How to use Bitpay with Java

I found this post about BitPay but it's not very clear how I can use it.
https://help.bitpay.com/development/how-do-i-use-the-bitpay-java-client-library
I implemented this code:
public void createInvoice() throws BitPayException
{
ECKey key = KeyUtils.createEcKey();
BitPay bitpay = new BitPay(key);
InvoiceBuyer buyer = new InvoiceBuyer();
buyer.setName("Satoshi");
buyer.setEmail("satoshi#bitpay.com");
Invoice invoice = new Invoice(100.0, "USD");
invoice.setBuyer(buyer);
invoice.setFullNotifications(true);
invoice.setNotificationEmail("satoshi#bitpay.com");
invoice.setPosData("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890");
Invoice createInvoice = bitpay.createInvoice(invoice);
}
How should I implement the private key?
That answer, I believe, is found in the following file: https://github.com/bitpay/java-bitpay-client/blob/master/src/main/java/controller/BitPay.java - that is to say, you would set your private key on the BitPay client instance. There you can find the appropriate constructor for your needs. You will want to use one or more of the following fields depending on your specific needs:
private ECKey _ecKey = null;
private String _identity = "";
private String _clientName = "";
private Hashtable<String, String> _tokenCache;
Edit: encryption and decryption of your private key exists here: https://github.com/bitpay/java-bitpay-client/blob/master/src/main/java/controller/KeyUtils.java
If, for instance, you used the following constructor:
public BitPay(URI privateKey) throws BitPayException, URISyntaxException, IOException {
this(KeyUtils.loadEcKey(privateKey), BITPAY_PLUGIN_INFO, BITPAY_URL);
}
You would pass in the URI for your private key.
Specific instructions on this available here: https://github.com/bitpay/java-bitpay-client/blob/master/GUIDE.md
Two very simple examples:
BitPay bitpay = new BitPay();
ECKey key = KeyUtils.createEcKey();
this.bitpay = new BitPay(key);
Number two:
// Create the private key external to the SDK, store it in a file, and inject the private key into the SDK.
String privateKey = KeyUtils.getKeyStringFromFile(privateKeyFile);
ECKey key = KeyUtils.createEcKeyFromHexString(privateKey);
this.bitpay = new BitPay(key);
After implementing the private key, you'd till need to initialize the client and connect to the server.

Using AWS Java's SDKs, how can I terminate the CloudFormation stack of the current instance?

Uses on-line decomentation I come up with the following code to terminate the current EC2 Instance:
public class Ec2Utility {
static private final String LOCAL_META_DATA_ENDPOINT = "http://169.254.169.254/latest/meta-data/";
static private final String LOCAL_INSTANCE_ID_SERVICE = "instance-id";
static public void terminateMe() throws Exception {
TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest().withInstanceIds(getInstanceId());
AmazonEC2 ec2 = new AmazonEC2Client();
ec2.terminateInstances(terminateRequest);
}
static public String getInstanceId() throws Exception {
//SimpleRestClient, is an internal wrapper on http client.
SimpleRestClient client = new SimpleRestClient(LOCAL_META_DATA_ENDPOINT);
HttpResponse response = client.makeRequest(METHOD.GET, LOCAL_INSTANCE_ID_SERVICE);
return IOUtils.toString(response.getEntity().getContent(), "UTF-8");
}
}
My issue is that my EC2 instance is under an AutoScalingGroup which is under a CloudFormationStack, that is because of my organisation deployment standards though this single EC2 is all there is there for this feature.
So, I want to terminate the entire CloudFormationStack from the JavaSDK, keep in mind, I don't have the CloudFormation Stack Name in advance as I didn't have the EC2 Instance Id so I will have to get it from the code using the API calls.
How can I do that, if I can do it?
you should be able to use the deleteStack method from cloud formation sdk
DeleteStackRequest request = new DeleteStackRequest();
request.setStackName(<stack_name_to_be_deleted>);
AmazonCloudFormationClient client = new AmazonCloudFormationClient (<credentials>);
client.deleteStack(request);
If you don't have the stack name, you should be able to retrieve from the Tag of your instance
DescribeInstancesRequest request =new DescribeInstancesRequest();
request.setInstanceIds(instancesList);
DescribeInstancesResult disresult = ec2.describeInstances(request);
List <Reservation> list = disresult.getReservations();
for (Reservation res:list){
List <Instance> instancelist = res.getInstances();
for (Instance instance:instancelist){
List <Tag> tags = instance.getTags();
for (Tag tag:tags){
if (tag.getKey().equals("aws:cloudformation:stack-name")) {
tag.getValue(); // name of the stack
}
}
At the end I've achieved the desired behaviour using the set of the following util functions I wrote:
/**
* Delete the CloudFormationStack with the given name.
*
* #param stackName
* #throws Exception
*/
static public void deleteCloudFormationStack(String stackName) throws Exception {
AmazonCloudFormationClient client = new AmazonCloudFormationClient();
DeleteStackRequest deleteStackRequest = new DeleteStackRequest().withStackName("");
client.deleteStack(deleteStackRequest);
}
static public String getCloudFormationStackName() throws Exception {
AmazonEC2 ec2 = new AmazonEC2Client();
String instanceId = getInstanceId();
List<Tag> tags = getEc2Tags(ec2, instanceId);
for (Tag t : tags) {
if (t.getKey().equalsIgnoreCase(TAG_KEY_STACK_NAME)) {
return t.getValue();
}
}
throw new Exception("Couldn't find stack name for instanceId:" + instanceId);
}
static private List<Tag> getEc2Tags(AmazonEC2 ec2, String instanceId) throws Exception {
DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest().withInstanceIds(instanceId);
DescribeInstancesResult describeInstances = ec2.describeInstances(describeInstancesRequest);
List<Reservation> reservations = describeInstances.getReservations();
if (reservations.isEmpty()) {
throw new Exception("DescribeInstances didn't returned reservation for instanceId:" + instanceId);
}
List<Instance> instances = reservations.get(0).getInstances();
if (instances.isEmpty()) {
throw new Exception("DescribeInstances didn't returned instance for instanceId:" + instanceId);
}
return instances.get(0).getTags();
}
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// Example of usage from the code:
deleteCloudFormationStack(getCloudFormationStackName());
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Atlassian Confluence : how do I update page using REST API

I am trying to update a Confluence page using this code:
https://bitbucket.org/jaysee00/confluence-rest-api-example/src/master/src/main/java/com/atlassian/api/examples/Main.java
Code is:
public class Confluence {
/**
* Demonstrates how to update a page using the Conflunence 5.5 REST API.
*/
private static final Logger LOGGER = Logger.getLogger(Confluence.class);;
private static final String BASE_URL = "http://confluence:8080";
private static final String USERNAME = "admin";
private static final String PASSWORD = "admin";
private static final String ENCODING = "utf-8";
private String getContentRestUrl(Long contentId, String[] expansions)
throws UnsupportedEncodingException {
String expand = URLEncoder.encode(StringUtils.join(expansions, ","),
ENCODING);
return String
.format("%s/rest/api/content/%s?expand=%s&os_authType=basic&os_username=%s&os_password=%s",
BASE_URL, contentId, expand,
URLEncoder.encode(USERNAME, ENCODING),
URLEncoder.encode(PASSWORD, ENCODING));
}
public void publish() throws ClientProtocolException, IOException, Exception {
final long pageId = 36307446;
HttpClient client = new DefaultHttpClient();
// Get current page version
String pageObj = null;
HttpEntity pageEntity = null;
try {
String restUrl = getContentRestUrl(pageId,
new String[] { "body.storage", "version", "ancestors" });
HttpGet getPageRequest = new HttpGet(restUrl);
HttpResponse getPageResponse = client.execute(getPageRequest);
pageEntity = getPageResponse.getEntity();
pageObj = IOUtils.toString(pageEntity.getContent());
LOGGER.info("Get Page Request returned "
+ getPageResponse.getStatusLine().toString());
LOGGER.info(pageObj);
LOGGER.info((int)pageObj.trim().charAt(0));
} finally {
if (pageEntity != null) {
EntityUtils.consume(pageEntity);
}
}
// Parse response into JSON
JSONObject page = new JSONObject(pageObj.trim());
// Update page
// The updated value must be Confluence Storage Format
// NOT HTML.
page.getJSONObject("body").getJSONObject("storage")
.put("value", "hello, world");
int currentVersion = page.getJSONObject("version").getInt("number");
page.getJSONObject("version").put("number", currentVersion + 1);
// Send update request
HttpEntity putPageEntity = null;
try {
HttpPut putPageRequest = new HttpPut(getContentRestUrl(pageId,
new String[] {}));
StringEntity entity = new StringEntity(page.toString());
entity.setContentType("application/json");
putPageRequest.setEntity(entity);
HttpResponse putPageResponse = client.execute(putPageRequest);
putPageEntity = putPageResponse.getEntity();
System.out.println("Put Page Request returned "
+ putPageResponse.getStatusLine().toString());
System.out.println("");
System.out.println(IOUtils.toString(putPageEntity.getContent()));
} finally {
EntityUtils.consume(putPageEntity);
}
}
}
The response is alway 'HTTP 404 - Page not found'. I have changed the page id to one I know exists in Confluence.
An exception follows when it tries to parse the response into a JSON object:
avvvaorg.json.JSONException: A JSONObject text must begin with '{' at character 1
at org.json.JSONTokener.syntaxError(JSONTokener.java:496)
at org.json.JSONObject.<init>(JSONObject.java:180)
at org.json.JSONObject.<init>(JSONObject.java:403)
at com.openet.report.publish.Confluence.publish(Confluence.java:74)
at com.openet.report.miner.ReportMiner.generateSummary(ReportMiner.java:268)
at com.openet.report.miner.ReportMiner.runReport(ReportMiner.java:251)
at com.openet.report.miner.ReportMiner.main(ReportMiner.java:138)
Updating confluence pages using REST is not supported by Confluence 4.3.1. The API is much more limited:
https://docs.atlassian.com/atlassian-confluence/REST/4.3.1/
You can however update confluence using XML RPC:
public void publish() throws IOException {
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date today = Calendar.getInstance().getTime();
XWikiXmlRpcClient rpc = new XWikiXmlRpcClient(CONFLUENCE_URI);
try {
rpc.login(USER_NAME, PASSWORD);
//The info macro would get rendered an info box in the Page
Page page = new Page();
page.setSpace("Some space");
page.setTitle("Testing XML RPC calls in confluence_" + df.format(today));
//page.setContent(
String s = String.format("||Heading 1||Heading 2||Heading 3||%s|col A1|col A2|col A3|", "\r\n");
page.setContent(s);
page.setParentId(PAGEID);
rpc.storePage(page);
} catch (XmlRpcException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated catch block
}
This requires the following libraries:
import org.apache.xmlrpc.XmlRpcException;
import org.codehaus.swizzle.confluence.Page;
import org.w3c.dom.Document;
import org.xwiki.xmlrpc.XWikiXmlRpcClient;
Note that these libraries are not in the standard maven repository. You will have to update your repository manager (artifactory in my case) to sync with the XWiki maven repo. You will also need the service rocket plugin (https://community.servicerocket.com/servicerocket/topics/the-license-could-not-be-verified-there-is-no-license-certificate-installed-for-customware-scaffolding-plugin-for-confluence) configured correctly on Confluence.

Testing Forms in Play 2 with Java and JUnit

So, testing in Play is causing me a headache and I'm hoping someone out there will have an answer to my problem.
I need to test my registration system (among many other things), which of course involves the submission of a form on behalf of the user.
My Stripped Down Version of Controller Action - add()
public static Result add() {
String email = form().bindFromRequest().get("email");
String name = form().bindFromRequest().get("name");
String password = form().bindFromRequest().get("password");
String password_confirm = form().bindFromRequest().get("password-confirm");
[stripped out code]
if(!check){
flash("error", "Not a valid email, please use the email address provided by your employer");
return redirect(
routes.UserController.registration()
);
}
else {
String passwordHash = BCrypt.hashpw(form().bindFromRequest().get("password"), BCrypt.gensalt());
// Create unverified User
User newUser = User.create(
form().bindFromRequest().get("email"),
form().bindFromRequest().get("name"),
passwordHash
);
// Generate verification key
String key = newUser.verification_key;
// Send verification email
sendVerificationLink(key);
flash("success", "Thanks for registering! We have sent you an email with a verification link.");
return redirect(
routes.Application.login()
);
}
Here's the JUnit Test I've written.
#Test
public void registerTest() {
running(fakeApplication(), new Runnable() {
public void run() {
String registeredUserName = "bob";
String registeredUserEmail = "bob#gmail.ac.uk";
String registeredUserPass = "secret";
String registeredUserPassConfirm = "secret";
Map<String, String> userData = new HashMap<String, String>();
userData.put("name", registeredUserName);
userData.put("email", registeredUserEmail);
userData.put("password", registeredUserPass);
userData.put("passwordconfirm", registeredUserPassConfirm);
Result r = callAction(routes.ref.UserController.add(), fakeRequest()
.withFormUrlEncodedBody(Form.form(User.class).bind(userData).data()));
assertEquals(r, 200);
}
});
}
Given suitably correct details within the HashMap, r, in my mind, should return OK or 200?
However, I am getting the following... "expected: play.test.Helpers$1#29cd761a but was:<200>"
What is this "play.test.Helpers$1#29cd761a"? It looks like it referencing an object or memory address but I don't know why??
If this is vague in anyway, please just say so and I'll try to elaborate.
Thanks in advance
Yo!
Sussed it!
For anyone else having a momentary brain fart... use the status() method to read the returned result!
Result r = callAction(routes.ref.UserController.add(), fakeRequest()
.withFormUrlEncodedBody(Form.form(User.class).bind(userData).data()));
assertEquals(200, status(r));

Categories