Quickbooks Online Rest API Reporting Java ERROR - java

I have used a tutorial and the Java SDK to pull reports from the new REST reporting API.
https://developer.intuit.com/docs/0025_quickbooksapi/0055_devkits/0201_ipp_java_devkit_3.0/reports
I have used the following code as specified by the tutorial:
String consumerKey = "XXXXXXXXXXXTDF2GEP0tlzdGxxpQRfSb4";
String consumerSecret = "XXXXXXXXXXYuy9CLaWiyAVHTowK0NuGMKN1X";
String accessToken = "XXXXXXXXXXXGPU4SUGAaeyhRJFp05NUg4s8QnbY4eI4U";
String accessTokenSecret = "XXXXXXXXXXXgkz50A8Ho3Z3pgMO8QFh2ZBv3XjI";
OAuthAuthorizer oauth = new OAuthAuthorizer(consumerKey, consumerSecret, accessToken, accessTokenSecret);
String appToken = "011e510ebf68ab4683b8a06b21f6228dfa03";
String companyID = "1067363490";
try {
Context context = new Context(oauth, appToken, ServiceType.QBO, companyID);
ReportService service = new ReportService(context);
service.setStart_date("2014-02-01");
service.setEnd_date("2014-04-20");
service.setAccounting_method("Accrual");
Object report = service.executeReport(ReportName.PROFITANDLOSS.toString());
String name = "ryan";
//System.out.println(report.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Inside service.executeReport it keeps throwing a java.lang.ClassCastException: com.intuit.ipp.data.Report cannot be cast to com.intuit.ipp.core.Response
Has anyone got these reports to work with the Java SDK? Am I doing something wrong?

At present reports support only Json.
Please verify that you are specifying:
Config.setProperty(Config.SERIALIZATION_RESPONSE_FORMAT, "json");

Update Line:
Object report = service.executeReport(ReportName.PROFITANDLOSS.toString());
To:
Report report = service.executeReport(ReportName.PROFITANDLOSS.toString());
As shown here: https://developer.intuit.com/docs/0100_accounting/0500_developer_kits/0201_ipp_java_devkit_3.0/reports

Related

How to obtain refresh token in Microsoft Authorization Code flow - java sdk

I am implementing "Login with Microsoft button" and I need to store the refresh token in my database so that I can use that to obtain new access tokens in future. I am trying to do this with Java sdk for microsoft graph.
Edit 1: I actually want to create calendar events using my web application. So, the goal is for the web app to access Graph API without having a signed in user present.
This is what the code looks like:
AuthorizationCode authorizationCode = new AuthorizationCode(httpServletRequest.getParameter("code"));
String currentUri = httpServletRequest.getRequestURL().toString();
IAuthenticationResult result;
ConfidentialClientApplication app;
try {
app = createClientApplication();
String authCode = authorizationCode.getValue();
Set<String> scopes = new HashSet<String>();
scopes.add("Calendars.ReadWrite");
AuthorizationCodeParameters parameters = AuthorizationCodeParameters.builder(authCode, new URI(currentUri)).scopes(scopes)
.build();
Future<IAuthenticationResult> future = app.acquireToken(parameters);
result = future.get();
} catch (ExecutionException e) {
throw e.getCause();
}
String accessToken = result.accessToken();
/*
IAuthenticationResult does not contain any method to get the refresh token - how do I get the refresh token??
I want to do something like: result.refreshToken();
*/
IAuthenticationResult is implemented by AuthenticationResult -- but, AuthenticationResult is declared in another class and is not public. AuthenticationResult exposes a method to obtain refreshToken but, I am not able to access it.
Can someone help me access the refresh token?
Thanks!
I got the answer from this link: https://github.com/AzureAD/microsoft-authentication-library-for-java/issues/228
Short Answer: Use reflection
try {
//see com.microsoft.aad.msal4j.AuthenticationResult#refreshToken
final Field refreshTokenField = result.getClass()
.getDeclaredField("refreshToken");
refreshTokenField.setAccessible(true);
return refreshTokenField.get(result).toString();
} catch (IllegalAccessException | NoSuchFieldException e) {
throw new RuntimeException(e);
}

Create an issue to JIRA by Java Code

I am able to connect to JIRA by JIRARestClient API and also able to get the information about issue but whenever I am trying to create issue by below code, getting this error "RestClientException{statusCode=Optional.of(400), errorCollections=[ErrorCollection{status=400, errors={issuetype=valid issue type is required}, errorMessages=[]}]}"
IssueRestClient issueClient = new AsynchronousJiraRestClientFactory()
.createWithBasicHttpAuthentication(baseUri, username, password).getIssueClient();
IssueType issueType = new IssueType(null, 0L, "bug", false, "my issue", null);
BasicProject basicProject = new BasicProject(null, "CPQ", 1L, null);
IssueInput newIssue = new IssueInputBuilder(basicProject,issueType,"Mopendra").build();
String issueCreated = issueClient.createIssue(newIssue).claim().getKey();
can anyone please help me on this?
the cause is that you should use valid issue type that exists in your Jira and fill parameters correctly. You can fetch existing issue types and choose one you need. See
Jira issue type values for Rest api
Please refer the below-working code. This should solve your problem.
//call method createIssue
final String issueKey = myJiraClient.createIssue("YOUR_PRAJECT_NAME", 1L, "Issue created from Standalone App");
// method declaration
private String createIssue(String projectKey, Long iType, String issueSummary) {
IssueRestClient issueClient = restClient.getIssueClient();
BasicProject cpqProject = null;
IssueType issueType = null;
try {
final Iterable<BasicProject> projects = restClient.getProjectClient().getAllProjects().claim();
System.out.println("======================getting all projoects======================");
for (BasicProject project : projects) {
if(project.getKey().equalsIgnoreCase("cpq")) {
cpqProject = project;
}
}
Promise<Project> project = restClient.getProjectClient().getProject(projectKey);
for(IssueType type : (project.get()).getIssueTypes()) {
if(type.getName().equalsIgnoreCase("Bug")){
issueType = type;
}
}
} catch (Exception e) {
e.printStackTrace();
}
IssueInput newIssue = new IssueInputBuilder(cpqProject, issueType, issueSummary).build();
return issueClient.createIssue(newIssue).claim().getKey();
}

Mailjet API v3 update

I have a serious issue regarding the REST API of Mailjet as used with the recommended v3 library.
When I try to UPDATE I am able to do so for the first time without errors, but when I try to do so again, I got NullPointerException. In spite of that, it does update the stat in the Mailjet Server part.
Also the HTTP Response I get is HTTP/1.1 500 Internal Server Error
Code used:
thisUser=cl.createCall(User.Update).identifiedBy(UserProperty.ID, **myUniqueID**).property(UserProperty.USERNAME, propertyValue).execute();
Any thoughts would be more than welcome.
Ok after the comment, here is the function:
#Path("/userUpdate/{propertyName}/{propertyValue}")
#GET
public Response userUpdate(#PathParam("propertyName") String propertyName, #PathParam("propertyValue") String propertyValue) throws ClientProtocolException, IOException{
MailJetApiClient cl=null;
User thisUser=null;
Response resp=null;
StringEntity stringEntity = null;
try {
cl = MailjetUsersRest.createClient();
} catch (MailJetClientConfigurationException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
thisUser=cl.createCall(User.Get).identifiedBy(UserProperty.ID, ___MY_UNIQUE_ID___).execute();
} catch (MailJetApiCallException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
String email = thisUser.getEmail();
String lastip = thisUser.getLastIp();
Date lastlogin = thisUser.getLastLoginAt();
String local = thisUser.getLocale();
String timezone = thisUser.getTimezone();
Date warned = thisUser.getWarnedRatelimitAt();
try {
cl = MailjetUsersRest.createClient();
switch(propertyName){
case "Username":
thisUser=cl.createCall(User.Update).identifiedBy(UserProperty.ID, ___MY_UNIQUE_ID___).property(UserProperty.USERNAME, propertyValue).execute();
resp = Response.status(200).entity(thisUser).build();
break;
default:
System.out.println("Invalid propertyName.");
break;
}
} catch (MailJetClientConfigurationException | MailJetApiCallException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return resp;
}
First of all, thank you for using Mailjet!
After some testing, I was unable to reproduce your issue. You will find below the code I used.
However I strongly suggest that you open a ticket with our support here.
A working code
Please note that it is unnecessary and considered bad practice to rebuild the client before each call.
// Build a Mailjet client config
MailJetClientConfiguration config;
config = new MailJetClientConfiguration()
.setBaseUrl("https://api.mailjet.com/v3/REST/")
.setDefaultApiKey(System.getenv("MJ_PROD_PUBLIC"))
.setDefaultSecretKey(System.getenv("MJ_PROD_PRIVATE"));
// Build a Mailjet client
MailJetApiClient client = config.buildClient();
// Your code (adapted to my environment, ie no 'Response' object
// and no client factory.)
User thisUser = null;
try
{
// Note that the 'L' in the 'identifiedBy' value fi is necessary
thisUser = client
.createCall(User.Get)
.identifiedBy(UserProperty.ID, /*Our user's ID*/L)
.execute();
}
catch (MailJetApiCallException e2)
{
e2.printStackTrace();
}
String email = thisUser.getEmail();
String lastip = thisUser.getLastIp();
Date lastlogin = thisUser.getLastLoginAt();
String local = thisUser.getLocale();
String timezone = thisUser.getTimezone();
Date warned = thisUser.getWarnedRatelimitAt();
try
{
thisUser = client
.createCall(User.Update)
.identifiedBy(UserProperty.ID, /*Our user's ID*/L)
.property(UserProperty.USERNAME, "DevRel Team Mailjet")
.execute();
}
catch (MailJetApiCallException e)
{
e.printStackTrace();
}
Copy pasting the last bit (the update process) so that the update call is executed twice (without the same new username, of course) doesn't throw any error and certainly not a NullPointerException or a 500 HTTP error code.
And the username is changed accordingly.
So yeah, as written above, please contact our support here. This will allow us to better help you.
If this answer satisfies you, don't forget to accept & upvote it so that others going through similar issues can know this helped :-)

How to add a graphical image signature using CoSign Signature Soap API

If possible add some code snippet. I have used Java for coding.
DSS: I would like to add multiple graphical image signature using CoSign Signature Soap API, how can I achieve it? If possible add some code snippet.
Here is a code sample in Java that demonstrates how to add a graphical signature using CoSign Signature SOAP API:
public static void AddGraphicalImage(String username, String domain, String password, byte[] imageBuffer, String imageName) throws Exception {
try {
SignRequest request = new SignRequest();
RequestBaseType.OptionalInputs optInputs = new RequestBaseType.OptionalInputs();
// Set signature type
optInputs.setSignatureType("http://arx.com/SAPIWS/DSS/1.0/set-graphic-image");
// Set user credentials
ClaimedIdentity claimedIdentity = new ClaimedIdentity();
NameIdentifierType nameIdentifier = new NameIdentifierType();
nameIdentifier.setValue(username);
nameIdentifier.setNameQualifier(domain);
CoSignAuthDataType coSignAuthData = new CoSignAuthDataType();
coSignAuthData.setLogonPassword(password);
claimedIdentity.setName(nameIdentifier);
claimedIdentity.setSupportingInfo(coSignAuthData);
optInputs.setClaimedIdentity(claimedIdentity);
// Set graphical image data
GraphicImageType graphicImage = new GraphicImageType();
graphicImage.setGraphicImage(imageBuffer);
graphicImage.setDataFormat(Long.valueOf(6)); //JPG
graphicImage.setGraphicImageName(imageName);
optInputs.setGraphicImageToSet(graphicImage);
request.setOptionalInputs(optInputs);
// Initiate service client
DSS client = new DSS(new URL("https://prime.cosigntrial.com:8080/sapiws/dss.asmx"));
// Send the request
DssSignResult response = client.getDSSSoap().dssSign(request);
// Check result
String errmsg = "" + response.getResult().getResultMajor();
if (errmsg.compareTo("urn:oasis:names:tc:dss:1.0:resultmajor:Success") == 0) {
System.out.println("Graphical image was added successfully!");
return;
}
else {
throw new Exception(response.getResult().getResultMessage().toString());
}
}
catch (Exception e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
}
}

Jira issue type values for Rest api

Where can I find Jira issue type values that we pass to IssueBuilder class constructor?
For ex: If i want to create a issue type of bug using jira rest api , We pass value '1L' to Issue Builder class constructor.
IssueInputBuilder issueBuilder = new IssueInputBuilder("Key", 1l);
Similarly what are the values of other jira issue types ?.. Anybody know the values we need to pass ?
If you are using later Jira REST Java Client API (e.g. 4.0), the interface has been changed. You must use following code to browsing all issue types:
private static final String JIRA_SERVER = "http://jiralab";
public static void main(String[] args) {
try {
JiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
URI uri = new URI(JIRA_SERVER);
JiraRestClient client = factory.createWithBasicHttpAuthentication(uri, "admin", "admin");
listAllIssueTypes(client);
}
catch (Exception ex) {
}
}
private static void listAllIssueTypes(JiraRestClient client) throws Exception {
Promise<Iterable<IssueType>> promise = client.getMetadataClient().getIssueTypes();
Iterable<IssueType> issueTypes = promise.claim();
for (IssueType it : issueTypes) {
System.out.println("Type ID = " + it.getId() + ", Name = " + it.getName());
}
}
If you want to get a list of all available issuetypes, you can use the REST API (/rest/api/2/issuetype). To try that on your JIRA instance, I like to recommend the Atlassian REST API Browser.
Or just look here: Finding the Id for Issue Types
In Java you can get a list of all issuetype object using getAllIssueTypeObjects().

Categories

Resources