Jenkins Uploading file from local machine to confluence REST API - Groovy - groovy

So I am trying to work on a groovy script within Jenkins that takes a file from local machine and pushes to a confluence page.
I can't seem to find any documentation for this.
I found this code, and I'm new to groovy so just wanted to make sure I'm on the correct track. I added some comments to my understanding if someone could clarify what they mean that would be awesome, and let me know if I am on the right track?
def server = new XMLRPCServerProxy("http://confluence:8090/rpc/xmlrpc")//Here we would have the link to our confluence server
def spaceKey = "Area" // not sure what spaceKey means
def pageTitel = "FileUpload"//The title of the page we are uploading to
def fileName = "D:\\datamodel.pdf"//the file path
def contentType = "application/pdf"//file extensions
def token = server.confluence2.login("UserName" , "Password")//confluence login credientials
def page = server.confluence2.getPage(token, spaceKey, pageTitel)//not sure
def file = new File (fileName)
server.confluence2.addAttachment( token, page.id, [ fileName: file.name, contentType:contentType ], file.bytes )

i'm work with the same task, but find only case with curl. It's work, but this is not groovy.

Related

Why is my embeded Image not always displayed?

So i did a simple rewrite of this bot in python.
It fetches a link and uses an API to return an Imageurl.
Here's the relevant Code:
#bot.command(name='ss')
async def screenshot(context, *args):
if len(args) != 1:
await context.channel.send("Error Missing Inspection Link!")
return
await context.message.add_reaction("✅")
#Getting the Imageurl in a Class (sgg) in another Python File
sgg.getscreenshot(args[0])
while sgg.imglnk == "":
sleep(0.2)
e = discord.Embed(description=sgg.imglnk)
e.set_image(url=sgg.imglnk)
print(ppretty(e._image))
await context.channel.send(embed=e)
This does work sometimes, other times it doesn't. (See Image below)
I checked the Library and found out that the Imageurl is placed in the class member Embed._image.
So to see if i'm maybe getting a malformed URL or something i ppretty printed the class member.
It returned the correct URL for both tests.
https://s.swap.gg/rca4ofNZx.jpg
{'url': 'https://s.swap.gg/rca4ofNZx.jpg'}
https://s.swap.gg/DG-7kjyu6.jpg
{'url': 'https://s.swap.gg/DG-7kjyu6.jpg'}
So on to my question, does anyone have a clue why it sometimes correctly displays the Image and other times just doesn't?

How to get AccessToken and also close browser window in ReadyAPI

I wrote some code that gets an access token. When the code runs, a browser displays on the screen which contains the access token.
But when I try to get the access token and log it, a null string is being displayed. Also, I do not know if there is a way to force the browser to close using my code. Right now when I run this code, the browser window opens but I have to click on it to close it.
Could you please let me know what I am doing wrong ?
import com.eviware.soapui.impl.rest.actions.oauth.OltuOAuth2ClientFacade
import com.eviware.soapui.support.editor.inspectors.auth.TokenType
def project = context.getTestCase().getTestSuite().getProject();
def oAuthProfile = project.getAuthRepository().getEntry("IMAGEN_Profile");
def clientSecret = testRunner.testCase.testSuite.getPropertyValue("Client_Secret")
def clientID = testRunner.testCase.testSuite.getPropertyValue("Client_ID")
oAuthProfile.setClientSecret(clientSecret);
oAuthProfile.setClientID(clientID);
log.info("Client Secret:"+clientSecret)
log.info("Client ID:"+clientID)
// the following code for getting new access token
def oAuthClientFacade = new OltuOAuth2ClientFacade(TokenType.ACCESS);
oAuthClientFacade.requestAccessToken(oAuthProfile, true);
def accessToken = oAuthProfile.getAccessToken()
testRunner.testCase.testSuite.setPropertyValue("Auth_Code",accessToken)
log.info("Access Token:"+accessToken)
Unfortunately, the SoapUI documentation is rather terse.
Change your
oAuthClientFacade.requestAccessToken(oAuthProfile, true);
to
oAuthClientFacade.requestAccessToken(oAuthProfile, true, true);
source

How to pass params to a HTTP request (teststep) in a SOAP UI Test case using groovy and run it

I am writing a groovy script to execute/automate my test suite. In one test case i have a HTTPRequest where i have a request URL, parameters( username and password) and method( GET) to get a token-id and then i would pass that token id to my next step( a SOAP request)to get the data.
I am stuck at a point where i need to pass the params(username and password), request URL and method(GET) using groovy.
I have a test step created manaully under a test case, i just need to pass the params
as i search online i got to know how to pass headers,url to a SOAP request which is like below
def headers = new StringToStringMap()
testRunner = new com.eviware............WsdlTestCaseRunner(myTestCase,null);
testStepContext = new com.eviware.soapui........WsdlTestRunContext(testsetp);
headers.put("apikey", "abcd")
teststep.getTestRequest().setRequestHeaders(headers)
teststep.getHttpRequest().setEndpoint(encpointurl);
testsetp.run(testRunner ,testStepContext )
but i looking to know how to pass params to a http request(test step) and run it.
Add a Properties teststep to your testcase. Just let it keep the default "Properties" name.
Add the properties to the Properties teststep, that you need to transfer
Inside your groovy teststep, you may set the properties using something like:
def properties = testRunner.testCase.getTestStepByName("Properties");
properties.setPropertyValue("name", "value");
Add the parameters directly in your request using variables in the format ${Properties#name} and replace "name" with the actual parameter name. This can be done both in the request body and in the URL if you should wish to do so.
It can be done completely in groovy by using groovy.json.JsonBuilder Class.
def body = new StringToStringMap()
def jsonbildr = new JsonBuilder()
body.put("username","Hackme")
body.put("password","LockUout")
def root = jsonbildr body
jsonbildr = jsonbildr.toPrettyString()
log.info(jsonbildr)
testStep.setPropertyValue("Request", jsonbildr)
Output :
{
"password": "LockUout",
"username": "Hackme"
}

Get requests body using selenium and proxies

I want to be able to get a body of the specific subrequest using a selenium behind the proxy.
Now I'm using python + selenium + chromedriver. With logging I'm able to get each subrequest's headers but not body. My logging settings:
caps['loggingPrefs'] =
{'performance': 'ALL',
'browser': 'ALL'}
caps['perfLoggingPrefs'] = {"enableNetwork": True,
"enablePage": True,
"enableTimeline": True}
I know there are several options to form a HAR with selenium:
Use geckodriver and har-export-trigger. I tried to make it work with the following code:
window.foo = HAR.triggerExport().then(harLog => { return(harLog); });
return window.foo;
Unfortunately, I don't see the body of the response in the returning data.
Use browsermob proxy. The solution seems totally fine but I didn't find the way to make browsermob proxy work behind the proxy.
So the question is: how can I get the body of the specific network response on the request made during the downloading of the webpage with selenium AND use proxies.
UPD: Actually, with har-export-trigger I get the response bodies, but not all of them: the response body I need is in json, it's MIME type is 'text/html; charset=utf-8' and it is missing from the HAR file I generate, so the solution is still missing.
UPD2: After further investigation, I realized that a response body is missing even on my desktop firefox when the har-export-trigger add-on is turned on, so this solution may be a dead-end (issue on Github)
UPD3: This bug can be seen only with the latest version of har-export-trigger. With version 0.6.0. everything works just fine.
So, for future googlers: you may use har-export-trigger v. 0.6.0. or the approach from the accepted answer.
I have actually just finished to implemented a selenium HAR script with tools you are mentioned in the question. Both HAR getting from har-export-trigger and BrowserMob are verified with Google HAR Analyser.
A class using selenium, gecko driver and har-export-trigger:
class MyWebDriver(object):
# a inner class to implement custom wait
class PageIsLoaded(object):
def __call__(self, driver):
state = driver.execute_script('return document.readyState;')
MyWebDriver._LOGGER.debug("checking document state: " + state)
return state == "complete"
_FIREFOX_DRIVER = "geckodriver"
# load HAR_EXPORT_TRIGGER extension
_HAR_TRIGGER_EXT_PATH = os.path.abspath(
"har_export_trigger-0.6.1-an+fx_orig.xpi")
_PROFILE = webdriver.FirefoxProfile()
_PROFILE.set_preference("devtools.toolbox.selectedTool", "netmonitor")
_CAP = DesiredCapabilities().FIREFOX
_OPTIONS = FirefoxOptions()
# add runtime argument to run with devtools opened
_OPTIONS.add_argument("-devtools")
_LOGGER = my_logger.get_custom_logger(os.path.basename(__file__))
def __init__(self, log_body=False):
self.browser = None
self.log_body = log_body
# return the webdriver instance
def get_instance(self):
if self.browser is None:
self.browser = webdriver.Firefox(capabilities=
MyWebDriver._CAP,
executable_path=
MyWebDriver._FIREFOX_DRIVER,
firefox_options=
MyWebDriver._OPTIONS,
firefox_profile=
MyWebDriver._PROFILE)
self.browser.install_addon(MyWebDriver._HAR_TRIGGER_EXT_PATH,
temporary=True)
MyWebDriver._LOGGER.info("Web Driver initialized.")
return self.browser
def get_har(self):
# JSON.stringify has to be called to return as a string
har_harvest = "myString = HAR.triggerExport().then(" \
"harLog => {return JSON.stringify(harLog);});" \
"return myString;"
har_dict = dict()
har_dict['log'] = json.loads(self.browser.execute_script(har_harvest))
# remove content body
if self.log_body is False:
for entry in har_dict['log']['entries']:
temp_dict = entry['response']['content']
try:
temp_dict.pop("text")
except KeyError:
pass
return har_dict
def quit(self):
self.browser.quit()
MyWebDriver._LOGGER.warning("Web Driver closed.")
A subclass adding BrowserMob proxy for your reference as well:
class MyWebDriverWithProxy(MyWebDriver):
_PROXY_EXECUTABLE = os.path.join(os.getcwd(), "venv", "lib",
"browsermob-proxy-2.1.4", "bin",
"browsermob-proxy")
def __init__(self, url, log_body=False):
super().__init__(log_body=log_body)
self.server = Server(MyWebDriverWithProxy._PROXY_EXECUTABLE)
self.server.start()
self.proxy = self.server.create_proxy()
self.proxy.new_har(url,
options={'captureHeaders': True,
'captureContent': self.log_body})
super()._LOGGER.info("BrowserMob server started")
super()._PROFILE.set_proxy(self.proxy.selenium_proxy())
def get_har(self):
return self.proxy.har
def quit(self):
self.browser.quit()
self.proxy.close()
MyWebDriver._LOGGER.info("BroswerMob server and Web Driver closed.")

Trying to use Yelp API for something other than business_id

I'm a student and only a few weeks into Python, so bear with me. I found a good answer in this link for initially working with Yelp's v3 API to at least get it to successfully make a request by business_id: How to use Yelp's new API
However, I can't seem to figure out how to search by anything other than reviews using the code that someone provided above (copy-pasted here as the below does work, just not what I need it for:
import requests
import yelp
from config import api_key
API_KEY = api_key
API_HOST = 'https://api.yelp.com'
BUSINESS_PATH = '/v3/businesses/'
def get_business(business_id):
business_path = BUSINESS_PATH + business_id
url = API_HOST + business_path + '/reviews'
headers = {'Authorization': f"Bearer {API_KEY}"}
response = requests.get(url, headers=headers)
return response.json()
results = get_business('the-white-horse-pub-kansas-city')
pprint(results)
Again, the code does work if you're only looking up one place by name. But when I try something other than "/reviews" in the url function, such as "search" or "term" or something else going off of the Yelp Fusion API documentation (https://yelp.com/developers/documentation/v3/business_search), I can't get anything to pull. My intent is to pull a bunch of breweries in the local area and then eventually put them in a dataframe, but I can't figure out what parameters or code to use, other than 'review'.
I believe I found an answer where you can at least look for type if you add the first item to the dependencies and the lower items as a separate function:
BUSINESS_PATH_CAT = '/v3/categories/'
def get_all_categories(alias):
url = API_HOST + BUSINESS_PATH_CAT + alias
headers = {'Authorization': f"Bearer {API_KEY}"}
response = requests.get(url, headers=headers)
return response.json()
results = get_all_categories('brewpubs')
pprint(results)
Aside from this though, on the authentication guide for Yelp Fusion, it discusses using Postman. If you're a fellow noob, setting this up can be a lifesaver as this allowed me to actually see the HTTP wording and how it's split up for search terms and how to add them compared to the API documentation.

Resources