groovy api in pin payments secret key location - groovy

im doing an api for pin payment in pin.net.au and i encounter some errors like what you see in the bottom
`#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder'`,` version='0.5.0-RC2' )
import groovyx.net.http.*
import groovyx.net.http.HttpResponseDecorator
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.*
import groovyx.net.http.HttpResponseException
import groovy.swing.SwingBuilder
import javax.swing.JFrame
import wslite.http.auth.*
class Customers {
Customers(){
def rst = new RESTClient( 'https://test-api.pin.net.au/1/')
rst.auth.basic 'mySecretKey',''
def res = rst.post( path: 'customers'){
type ContentType.XML
xml {
cards{
email('pk_qTj9Umqmlf3o7lfa6F9nWw')
card[expiry_month]('12')
card[expiry_year]('2015')
card[cvc]('123')
card[name]('patrick pl')
card[address_line1]('23 frfds')
card[address_city]('Angeles')
card[address_postcode]('2009')
card[address_state]('ph')
card[address_country]('Philippines')
}
}
}
}
public static void main(String []args){
new Customers()
}
}
when i run the code the error was
May 12, 2014 1:07:35 PM org.apache.http.impl.client.DefaultRequestDirector handleResponse
WARNING: Authentication error: Unable to respond to any of these challenges: {}
Caught: groovyx.net.http.HttpResponseException: Authorization Required
groovyx.net.http.HttpResponseException: Authorization Required
at groovyx.net.http.RESTClient.defaultFailureHandler(RESTClient.java:240)
at groovyx.net.http.HTTPBuilder.doRequest(HTTPBuilder.java:475)
at groovyx.net.http.HTTPBuilder.post(HTTPBuilder.java:335)
at groovyx.net.http.HTTPBuilder$post.call(Unknown Source)
at PinPayment.Customers.<init>(Customers.groovy:16)
at PinPayment.Customers.main(Customers.groovy:39)
how could i make the authentication work for the code to be runable??
here is the link for the docs pin.net.au

Document indicates it requires basic HTTP authn.
Calls to the Pin Payments API must be authenticated using HTTP basic
authentication, with your API key as the username, and a blank string
as the password.
Therefore:
def rst = new RESTClient( 'https://test-api.pin.net.au/1/' )
rst.auth.basic 'secretAPIKeyHereAsString', ''

i found the right code for that particular api here def http = new RESTClient('https://test-api.pin.net.au/1/') http.headers['Authorization'] = 'Basic '+"tWqZl0MHsg5nUQdB6czrDQ:".getBytes('iso-8859-1').encodeBase64()

Related

How to Send Array String in Zeep

I have this below soap envelope where I have send string array.
<apiKey xsi:type="xsd:string">Ab12-Ab12-Ab12-Ab12</apiKey>§
<baseScheduleRollout xsi:type="flex:baseScheduleRollout" xmlns:flex="http://app.quinyx.com/soap/FlexForce">
<badgeNos xsi:type="flex:ArrayOfString" soapenc:arrayType="xsd:string[]">
<item1>1022</item1>
<item2>1030</item2>
<item2>10112330</item2>
</badgeNos>
<fromDateTime xsi:type="xsd:dateTime">2020-11-05T00:00:00</fromDateTime>
<toDateTime xsi:type="xsd:dateTime">2020-11-24T00:00:00</toDateTime>
I know how to send a soap request and my complextype is okay. But I think my string array passing system is wrong. Though I tried to use anyObject but still not working
from zeep import Client
from zeep import xsd
import datetime
from requests import Session
from requests.auth import HTTPBasicAuth
from zeep.transports import Transport
wsdl = "https://api.quinyx.com/FlexForceWebServices.php?wsdl"
session = Session()
session.auth = HTTPBasicAuth('username', 'password')
client = Client(wsdl, transport=Transport(session=session))
ArrayOfString = client.get_element('ns0:ArrayOfObject')
badgeNo = ArrayOfString(['146223'])
data = { "apiKey" : "apikey" ,
"baseScheduleRollout" :{
"badgeNos":badgeNo,
"fromDateTime":xsd.SkipValue,
"toDateTime":xsd.SkipValue
}
}
result = client.service.wsdlGetBaseScheduleRolledoutHours(**data)
result
Error
LookupError: No element 'ArrayOfObject' in namespace https://api.quinyx.com/soap/FlexForce. Available elements are: -

Scriptrunner/ Copying Project while logged-in as another user

I want to use my script, so that it will be executed by someone who is not me, but another user (ServiceUser) in the Jira Instance.
This is my functioning code, but I do not know how to make someone else execute it.
import com.atlassian.jira.project.Project
import com.atlassian.jira.project.ProjectManager
import com.atlassian.jira.project.AssigneeTypes
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.user.ApplicationUser
import com.atlassian.jira.component.ComponentAccessor
import com.onresolve.scriptrunner.canned.jira.admin.CopyProject
import org.apache.log4j.Logger
import com.atlassian.jira.bc.projectroles.ProjectRoleService
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.security.roles.ProjectRole
import com.atlassian.jira.util.SimpleErrorCollection
import com.atlassian.jira.security.roles.ProjectRoleManager
import com.atlassian.jira.project.ProjectManager
import com.atlassian.jira.project.Project
import com.atlassian.jira.security.roles.ProjectRoleActor
import com.atlassian.jira.bc.project.ProjectCreationData
import com.atlassian.jira.bc.project.ProjectService
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.project.AssigneeTypes
import com.atlassian.jira.project.type.ProjectTypeKey
// the key for the new project
def projectKey = "EXA987"
def projectName = "EXA987"
def log = Logger.getLogger("com.onresolve.jira.groovy.MyScript")
Thread executorThread = new Thread(new Runnable() {
void run() {
def copyProject = new CopyProject()
def inputs = [
(CopyProject.FIELD_SOURCE_PROJECT) : "SWTEMP",
(CopyProject.FIELD_TARGET_PROJECT) : projectKey,
(CopyProject.FIELD_TARGET_PROJECT_NAME) : projectName,
(CopyProject.FIELD_COPY_VERSIONS) : false,
(CopyProject.FIELD_COPY_COMPONENTS) : false,
(CopyProject.FIELD_COPY_ISSUES) : false,
(CopyProject.FIELD_COPY_DASH_AND_FILTERS) : false,
]
def errorCollection = copyProject.doValidate(inputs, false)
if(errorCollection.hasAnyErrors()) {
log.warn("Couldn't create project: $errorCollection")
}
else {
def util = ComponentAccessor.getUserUtil()
def adminsGroup = util.getGroupObject("jira-administrators")
assert adminsGroup // must have jira-administrators group defined
def admins = util.getAllUsersInGroups([adminsGroup])
assert admins // must have at least one admin
ComponentAccessor.getJiraAuthenticationContext().setLoggedInUser(util.getUserByName(admins.first().name))
copyProject.doScript(inputs)
}
}
})
executorThread.start()
I stumbled upon other codes, using things like
def oldLoggedInUser = jiraAuthenticationContext.getLoggedInUser()
jiraAuthenticationContext.setLoggedInUser(serviceUser)
jiraAuthenticationContext.setLoggedInUser(oldLoggedInUser)
but it was not succesful for me.
I have used following solution to change user during script execution:
def authContext = ComponentAccessor.getJiraAuthenticationContext();
def currentUser = authContext.getLoggedInUser();
def superuser=ComponentAccessor.getUserManager().getUserByKey("ANOTHER_USER_ACCOUNT")
authContext.setLoggedInUser(superuser);
// < do the needed work>
authContext.setLoggedInUser(currentUser);
I had first issues as my used another account had not needed Jira access rights (and I got funny "user must be logged in" errors)

SOAPUI: unable to resolve class TokenType while Automating Token Retrieval

I am trying to perform automatic OAuth retrieval given at link https://support.smartbear.com/readyapi/docs/projects/requests/auth/types/oauth2/automate/sample.html using the following Groovy code:
// Import the required classes
import com.eviware.soapui.impl.rest.actions.oauth.OltuOAuth2ClientFacade;
import com.eviware.soapui.support.editor.inspectors.auth.TokenType;
import com.eviware.soapui.model.support.ModelSupport;
// Set up variables
def project = ModelSupport.getModelItemProject(context.getModelItem());
def authProfile = project.getAuthRepository().getEntry("OAuth 2");
def oldToken = authProfile.getAccessToken();
def tokenType = TokenType.ACCESS;
// Create a facade object
def oAuthFacade = new OltuOAuth2ClientFacade(tokenType);
// Request an access token in headless mode
oAuthFacade.requestAccessToken(authProfile, true, true);
// Wait until the access token gets updated
while(oldToken == authProfile.getAccessToken()) {
}
//The sleep method can be used instead of a while loop
//sleep(3000);
// Post the info to the log
log.info("Set new token: " + authProfile.getAccessToken());
But I am getting following error that it is unable to resolve class TokenType:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: Script15.groovy: 5: unable to resolve class com.eviware.soapui.support.editor.inspectors.auth.TokenType # line 5, column 1. import com.eviware.soapui.support.editor.inspectors.auth.TokenType; ^ org.codehaus.groovy.syntax.SyntaxException: unable to resolve class com.eviware.soapui.support.editor.inspectors.auth.TokenType # line 5, column 1. at org.codehaus.groovy.ast.ClassCodeVisitorSupport.addError(ClassCodeVisitorSupport.java:149) at org.codehaus.groovy.control.ResolveVisitor.visitClass(ResolveVisitor.java:1225) at org.codehaus.groovy.control.ResolveVisitor.startResolving(ResolveVisitor.java:178) at org.codehaus.groovy.control.CompilationUnit$11.call(CompilationUnit.java:651) at org.codehaus.groovy.control.CompilationUnit.applyToSourceUnits(CompilationUnit.java:931) at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:593) at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:542) at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:298) at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:268) at groovy.lang.GroovyShell.parseClass(GroovyShell.java:694) at groovy.lang.GroovyShell.parse(GroovyShell.java:706) at groovy.lang.GroovyShell.parse(GroovyShell.java:742) at groovy.lang.GroovyShell.parse(GroovyShell.java:733) at com.eviware.soapui.support.scripting.groovy.SoapUIGroovyScriptEngine.compile(SoapUIGroovyScriptEngine.java:136) at com.eviware.soapui.support.scripting.groovy.SoapUIGroovyScriptEngine.run(SoapUIGroovyScriptEngine.java:87) at com.eviware.soapui.impl.wsdl.teststeps.WsdlGroovyScriptTestStep.run(WsdlGroovyScriptTestStep.java:141) at com.eviware.soapui.impl.wsdl.panels.teststeps.GroovyScriptStepDesktopPanel$RunAction$1.run(GroovyScriptStepDesktopPanel.java:250) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) 1 error
If I do not import TokenType, then I am getting the error that No Such Property TokenType. How can I import TokenType class OR is there any other way I can request a new Access Token without using TokenType?
I was able to automate the OAuth token retrieval by removing TokenType from the code. OltuOAuth2ClientFacade can be instantiated without specifying TokenType. Following is the updated code:
// Import the required classes
import com.eviware.soapui.impl.rest.actions.oauth.*;
import com.eviware.soapui.model.support.ModelSupport;
//// Set up variables
def authContainer = testRunner.testCase.testSuite.project.OAuth2ProfileContainer
def authProfile = authContainer.getProfileByName("Profile 1")
def oldToken = authProfile.getAccessToken();
// Create a facade object
def oAuthFacade = new OltuOAuth2ClientFacade();
// Request an access token in headless mode
oAuthFacade.requestAccessToken(authProfile);
// Wait until the access token gets updated
while(oldToken == authProfile.getAccessToken()) {
}
// Post the info to the log
log.info("Set new token: " + authProfile.getAccessToken());

How to get a user by email in JIRA Script Runner

When writing a Groovy script for JIRA Script Runner, how do you get a user, or just their username, given their email address?
It seems that you're supposed to use the findUsersByEmail method in the UserSearchService interface.
https://docs.atlassian.com/jira/7.0.2/com/atlassian/jira/bc/user/search/UserSearchService.html
But how do you get an instance of this class?
Related question: How to get a user by email in a JIRA plugin.
The difference is that question is about a plugin, and my question is about JIRA Script Runner.
This code does not work:
setUserProperties(httpMethod: "POST", groups: ["jira-administrators"])
{ MultivaluedMap queryParams, String body, HttpServletRequest request ->
def userPropertyManager = ComponentAccessor.getUserPropertyManager()
def userManager = ComponentAccessor.getUserManager()
def userSearchService = DefaultUserPickerSearchService;
def users = userSearchService.findUsersByEmail("felicity.smoak#queenconsolidated.com")
users.each {
aUser ->
userPropertyManager.getPropertySet(aUser).setString("jira.meta.Company", "Smoak Technologies")
}
return Response.ok(users).build();
}
This is the error I got:
2016-04-18 15:23:06,168 ERROR [common.UserCustomScriptEndpoint]: *************************************************************************************
2016-04-18 15:23:06,168 ERROR [common.UserCustomScriptEndpoint]: Script endpoint failed on method: POST setUserProperties
groovy.lang.MissingMethodException: No signature of method: static com.atlassian.jira.bc.user.search.DefaultUserPickerSearchService.findUsersByEmail() is applicable for argument types: (java.lang.String) values: [felicity.smoak#queenconsolidated.com]
Possible solutions: findUsersByEmail(java.lang.String), findUserKeysByEmail(java.lang.String)
at Script462$_run_closure3.doCall(Script462.groovy:40)
at com.onresolve.scriptrunner.runner.rest.common.UserCustomScriptEndpoint.doEndpoint(UserCustomScriptEndpoint.groovy:308)
at com.onresolve.scriptrunner.runner.rest.common.UserCustomScriptEndpoint.postUserEndpoint(UserCustomScriptEndpoint.groovy:208)
EDIT
Based on #Oldskultxo's and #BjörnKautler suggestions, this is now my working code:
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.ComponentManager
import com.atlassian.jira.user.*
import com.atlassian.jira.bc.user.search.UserSearchService
import com.atlassian.sal.api.user.UserManager
import com.onresolve.scriptrunner.runner.rest.common.CustomEndpointDelegate
import groovy.json.*
import groovy.transform.BaseScript
import javax.servlet.http.HttpServletRequest
import javax.ws.rs.core.MultivaluedMap
import javax.ws.rs.core.Response
#BaseScript CustomEndpointDelegate delegate
setUserProperties(httpMethod: "POST", groups: ["jira-administrators"])
{ MultivaluedMap queryParams, String body, HttpServletRequest request ->
def userPropertyManager = ComponentAccessor.getUserPropertyManager()
def userManager = ComponentAccessor.getUserManager()
def userSearchService = ComponentAccessor.getComponent(UserSearchService.class)
def users = userSearchService.findUsersByEmail("felicity.smoak#queenconsolidated.com")
users.each {
aUser ->
userPropertyManager.getPropertySet(aUser).setString("jira.meta.Company", "Smoak Technologies")
}
return Response.ok("200").build();
}
Use ComponentAccessor.getComponent(UserSearchService) to get the right service if there is no concrete getUserSearchService() method.
I usually get components this way:
ComponentManager.getComponentInstanceOfType(UserSearchService.class);
And then just look for its methods.
Regards

Connection request failed while connecting to sharepoint online

I am trying to connect sharepoint online i used the following code but the response it is showing is request failed . I tried the following code
#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.0-RC2' )
import groovyx.net.http.*;
import static groovyx.net.http.ContentType.*;
import static groovyx.net.http.Method.*;
import groovyx.net.http.HTTPBuilder;
import static groovyx.net.http.Method.GET;
import static groovyx.net.http.ContentType.TEXT;
import groovyx.net.http.RESTClient
import groovy.util.slurpersupport.GPathResult
import static groovyx.net.http.ContentType.URLENC
import groovyx.net.http.URIBuilder
def authSite = new HTTPBuilder( 'https://xyzsharepoint.com' );
authSite.auth.basic 'username', 'password';
authSite.request(GET) { req->
response.success = { resp->
println'request was successful'
assert resp.status<400
}
response.failure = { resp ->
println'request failed'
assert resp.status>=400
}
}
Suggest me where I went wrong.

Resources