How to access to web page using Groovy? - groovy

i try to connect to webpage using Groovy,
i tried this, it works when the URL is www.google.fr
String.metaClass.browse {
def handler = [(~/^Mac OS.*/) : { "open $it".execute() }, (~/^Windows.*/) : { "cmd /C start $it".execute() },
(~/.*/) : {
//--- assume Unix or Linux
def browsers = [ 'firefox'.'chrome' ]
//--- find a browser we know the location of
def browser = browsers.find {
"which $it".execute().waitFor() == 0
}
//--- and run it if one found
if( browser )
"$browser $it".execute()
}
]
def k = handler.find { k, v -> k.matcher( System.properties.'os.name' ).matches() }
k?.value( delegate )
}
www.google.fr".browse.()
if i put URL which download a file it throw Compilation error. Thank you for your help.

If you want to add it as a method to the String class, you can do:
String.metaClass.browse = { ->
java.awt.Desktop.desktop.browse(new URI(delegate))
}
Then calling
"http://www.google.com".browse()
Will open your default browser

Related

Starting Microsoft Edge from MFC with web file paramater

If I open up a console prompt I can type this command:
start msedge "d:\HTML\Verticle Alignment.HTM"
It starts Microsoft Edge and opens the web page.
So I tried to do this programmatically in a test program using MFC:
void CMFCApplication8Dlg::OnBnClickedButton1()
{
ExecuteProgram(_T("start"), _T("msedge d:\\HTML\\Verticle Alignment.HTM"));
}
BOOL CMFCApplication8Dlg::ExecuteProgram(CString strProgram, CString strArguments)
{
SHELLEXECUTEINFO se = { 0 };
MSG sMessage;
DWORD dwResult;
se.cbSize = sizeof(se);
se.lpFile = strProgram;
se.lpParameters = strArguments;
se.nShow = SW_SHOWDEFAULT;
se.fMask = SEE_MASK_NOCLOSEPROCESS;
ShellExecuteEx(&se);
if (se.hProcess != nullptr)
{
do
{
dwResult = ::MsgWaitForMultipleObjects(1, &(se.hProcess), FALSE,
INFINITE, QS_ALLINPUT);
if (dwResult != WAIT_OBJECT_0)
{
while (PeekMessage(&sMessage, nullptr, NULL, NULL, PM_REMOVE))
{
TranslateMessage(&sMessage);
DispatchMessage(&sMessage);
}
}
} while ((dwResult != WAIT_OBJECT_0) && (dwResult != WAIT_FAILED));
CloseHandle(se.hProcess);
}
if ((DWORD_PTR)(se.hInstApp) < 33)
{
// Throw error
AfxThrowUserException();
return FALSE;
}
return TRUE;
}
But when I run it I get this error message:
So how can I launch my file in Microsoft Edge? I am using the latest Windows 10 so it is Microsoft Edge Chromium.
I have seen other questions which refer to making Edge the default browser and then just "opening" the data file and it working it all out but this is not OK in this case. In my editor I have a menu flyout which lists all the installed browsers (excluding Edge for now). But i want to add Edge so need to be able to programatically start it with my file to view.
Based on the comments provided to me, and to factor in for spaces in the file name, this works:
ExecuteProgram(_T("msedge"), _T("\"d:/HTML/Verticle Alignment.HTM\""));
The program to execute needs to be msedge and not start.
The parameter needs to be wrapped in " quotes.

Can I automatically link Jira issue with confluence page

I am trying to create a process with Jira and confluence, using Scriptrunner Cloud.
I am trying to do the following :
I want to create a confluence page automatically with posfunction scriptrunner on Jira issue creation, and want to link this page and issue automatically too.
I already automatized creation with some code, but this code does not link page and issues automatically.
I am using following code :
def spaceKey = 'LTSE'
def result = get("/rest/api/3/issue/${issueKey}")
.header('Content-Type', 'application/json')
.asObject(Map)
if (result.status != 200) {
return "Error retrieving issue ${result}"
}
def title = "${result.body.key} - ${result.body.fields.summary}"
def rootContent = "<h2>Description</h2><p>${result.body.fields.description}</p>"
def parent = createConfluencePage(title, spaceKey, rootContent, null)
result.body.fields.subtasks.forEach { subtask ->
def subtaskResult = get("/rest/api/3/issue/${subtask.id}")
.header('Content-Type', 'application/json')
.asObject(Map)
if (subtaskResult.status != 200) {
logger.error("Error retrieving issue ${subtaskResult}")
}
def subtitle = "${subtask.key} - ${subtask.fields.summary}"
def pageContent = "<h2>Description</h2><p>${subtaskResult.body.fields.description}</p>"
createConfluencePage(subtitle, spaceKey, pageContent, parent)
}
String createConfluencePage(String pageTitle, String spaceKey, String pageContent, String parentPage) {
def params = [
type : "page",
title: pageTitle,
space: [
key: spaceKey
],
body : [
storage: [
value : pageContent.toString(),
representation: "storage"
]
]
]
if (parentPage != null) {
params["ancestors"] = [parentPage].collect { [id: parentPage.toString()] }
}
def pageResult = post('/wiki/rest/api/content')
.header('Content-Type', 'application/json')
.body(params)
.asObject(Map).body
if (pageResult.statusCode) {
logger.error("Failed to create a new page. Confluence responded with error code: {}", pageResult.statusCode)
} else {
logger.info("Successfully created a new space with id: {}", pageResult)
}
pageResult.id
}
parent
Is there anything I can do, to automatize linking?
please have in mind that I use Cloud Jira and confluence
Is it possible to add content to the Confluence page using Scriptrunner? If so, just add the link of the JIRA issue to the Confluence page. This will automatically be converted to a JIRA issue macro on the page and will create a link with the JIRA issue itself. See:
https://www.atlassian.com/blog/confluence/link-jira-issues-to-confluence-pages-automatically
This only works if you have created application links between JIRA and Confluence:
https://confluence.atlassian.com/adminjiracloud/using-applinks-to-link-to-other-applications-779295829.html

How can I retrieve the build parameters from a queued job?

I would like to write a system groovy script which inspects the queued jobs in Jenkins, and extracts the build parameters (and build cause as a bonus) supplied as the job was scheduled. Ideas?
Specifically:
def q = Jenkins.instance.queue
q.items.each { println it.task.name }
retrieves the queued items. I can't for the life of me figure out where the build parameters live.
The closest I am getting is this:
def q = Jenkins.instance.queue
q.items.each {
println("${it.task.name}:")
it.task.properties.each { key, val ->
println(" ${key}=${val}")
}
}
This gets me this:
4.1.next-build-launcher:
com.sonyericsson.jenkins.plugins.bfa.model.ScannerJobProperty$ScannerJobPropertyDescriptor#b299407=com.sonyericsson.jenkins.plugins.bfa.model.ScannerJobProperty#5e04bfd7
com.chikli.hudson.plugin.naginator.NaginatorOptOutProperty$DescriptorImpl#40d04eaa=com.chikli.hudson.plugin.naginator.NaginatorOptOutProperty#16b308db
hudson.model.ParametersDefinitionProperty$DescriptorImpl#b744c43=hudson.mod el.ParametersDefinitionProperty#440a6d81
...
The params property of the queue element itself contains a string with the parameters in a property file format -- key=value with multiple parameters separated by newlines.
def q = Jenkins.instance.queue
q.items.each {
println("${it.task.name}:")
println("Parameters: ${it.params}")
}
yields:
dbacher params:
Parameters:
MyParameter=Hello world
BoolParameter=true
I'm no Groovy expert, but when exploring the Jenkins scripting interface, I've found the following functions to be very helpful:
def showProps(inst, prefix="Properties:") {
println prefix
for (prop in inst.properties) {
def pc = ""
if (prop.value != null) {
pc = prop.value.class
}
println(" $prop.key : $prop.value ($pc)")
}
}
def showMethods(inst, prefix="Methods:") {
println prefix
inst.metaClass.methods.name.unique().each {
println " $it"
}
}
The showProps function reveals that the queue element has another property named causes that you'll need to do some more decoding on:
causes : [hudson.model.Cause$UserIdCause#56af8f1c] (class java.util.Collections$UnmodifiableRandomAccessList)

How to add dynamically node to XML in Groovy with the StreamingMarkupBuilder

I am trying to dynamically create an XML file with Groovy. I'm pleased with the simplicity everything works, but i am having a hard time understanding the whole mechanism behind closures and delegates. While it appears to be easy to add properties and child nodes with a fixed name, adding a node with a dynamic name appears to be a special case.
My use case is creating a _rep_policy file, which can be used in CQ5.
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:jcr="http://www.jcp.org/jcr/1.0" xmlns:rep="internal"
jcr:primaryType="rep:ACL">
<allow
jcr:primaryType="rep:GrantACE"
rep:principalName="administrators"
rep:privileges="{Name}[jcr:all]"/>
<allow0
jcr:primaryType="rep:GrantACE"
rep:principalName="contributor"
rep:privileges="{Name}[jcr:read]"/>
</jcr:root>
Processing the collections works fine, but generating the name ...
import groovy.xml.StreamingMarkupBuilder
import groovy.xml.XmlUtil
def _rep_policy_files = [
'/content': [ // the path
'deny': [ // permission
'jcr:read': [ // action
'a1', 'b2']], // groups
'allow': [
'jcr:read, jcr:write': [
'c2']
]
]
]
def getNodeName(n, i) {
(i == 0) ? n : n + (i - 1)
}
_rep_policy_files.each {
path, permissions ->
def builder = new StreamingMarkupBuilder();
builder.encoding = "UTF-8";
def p = builder.bind {
mkp.xmlDeclaration()
namespaces << [
jcr: 'http://www.jcp.org/jcr/1.0',
rep: 'internal'
]
'jcr:root'('jcr:primaryType': 'rep:ACL') {
permissions.each {
permission, actions ->
actions.each {
action, groups ->
groups.eachWithIndex {
group, index ->
def nodeName = getNodeName(permission, index)
"$nodeName"(
'jcr:primaryType': 'rep:GrantACE',
'rep:principalName': "$group",
'rep:privileges': "{Name}[$action]")
}
}
}
}
}
print(XmlUtil.serialize(p))
}
Is this something (or similar) that you are looking for?
'jcr:root'('jcr:primaryType': 'rep:ACL') {
_rep_policy_files['/content'].each {k, v ->
if(k == 'allow')
"$k"('jcr:primaryType': 'rep:GrantACE',
'rep:principalName': 'administrators',
'rep:privileges': "$v" ){}
if(k == 'deny')
"$k"('jcr:primaryType': 'rep:GrantACE',
'rep:principalName': 'contributor',
'rep:privileges': "$v" ){}
}
}
The resultant xml shown in question cannot be apprehended properly with what you have in _rep_policy_files.

Testing URLs in groovy

How can we check whether urls are working or not in groovy?
when we click a button, i will get all the urls from existing db from 'urls' table and need to check which url is working
Ex:
http://baldwinfilter.com/products/start.html - not working
http://www.subaru.com/ - working
and so many urls from db.
My aim is to get all urls and check which one is working and which is not .
do we need to check on the status it returns ??
Can any one help me giving idea ...
thanks in advance
sri...
You could use HttpBuilder like so:
#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.0-RC2' )
import groovyx.net.http.HTTPBuilder
def urls = [
"http://baldwinfilter.com/products/start.html",
"http://www.subaru.com/"
]
def up = urls.collect { url ->
try {
new HTTPBuilder( url ).get( path:'' ) { response ->
response.statusLine.statusCode == 200
}
}
catch( e ) { false }
}
println up

Resources