am trying to understand the below line why do we need to call a stage with .call()
buildStage(slurper).call() can someone explain me what this line means why cant we just call with
buildStage(slurper)
def call(String jsonString) {
node("unix") {
try {
def slurper = new JsonSlurperClassic().parseText(jsonString)
buildStage(slurper).call()
deployStage()
}catch(error) {
println ex.toString()
}finally{
sendEmail()
}
}
}
def buildStage(slurper){
stage ('Build') {
}
}
def deployStage(slurper){
stage ('Deploy') {
}
}
From your above example buildStage(slurper).call() is not needed as it can be called like buildStage(slurper),
methondName.call() is needed if the method has a closure block that needs to be executed upon calling, see my below example
myPipeline.groovy
import groovy.json.JsonSlurperClassic
def call(String jsonString) {
node() {
try {
def slurper = new JsonSlurperClassic().parseText(jsonString)
buildStage(slurper)
println deployStage(slurper).call()
}catch(Exception ex ) {
throw ex;
}finally{
// do nothing
}
}
}
def buildStage(slurper){
stage ('Build') {
return {
println slurper
def r = 5 + 5
println r
}.call()
}
}
def deployStage(slurper){
stage ('Deploy') {
return {
return "The name is "+ slurper.name
}
}
}
Jenkinsfile
def myJSON = '''
{ "name" : "XYZ"}
'''
myPipeline(myJSON)
Related
I would like to make simple widget for my weather app, to show local temperature. My question is: how to get the LocationTracker in my widget class?
class Widget: GlanceAppWidget() {...}
I found the solution, I use fusedLocationProviderClient
//client
val locationProviderClient =
LocationServices.getFusedLocationProviderClient(context)
So, my method get location:
> //get location
private suspend fun getCurrentLocation(
context: Context,
locationClient: FusedLocationProviderClient
): Location? {
val hasAccessFineLocationPermission = ContextCompat.checkSelfPermission(
context,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
val hasAccessCoarseLocationPermission = ContextCompat.checkSelfPermission(
context,
Manifest.permission.ACCESS_COARSE_LOCATION
) == PackageManager.PERMISSION_GRANTED
val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
val isGpsEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
if (!hasAccessCoarseLocationPermission || !hasAccessFineLocationPermission || !isGpsEnabled) {
return null
}
return suspendCancellableCoroutine { cont ->
locationClient.lastLocation.apply {
if (isComplete) {
if (isSuccessful) {
cont.resume(result)
} else {
cont.resume(null)
}
return#suspendCancellableCoroutine
}
addOnSuccessListener {
cont.resume(it)
}
addOnFailureListener {
cont.resume(null)
}
addOnCanceledListener {
cont.cancel()
}
}
}
}
I want to initialize socket IO in my kotlin app.
my problem is here :
private var mSocket: Socket? = null
{
try {
mSocket = IO.socket("http://chat.socket.io")
} catch (URISyntaxException e) {
}
}
import com.github.nkzawa.socketio.client.IO
cant recognize
I searched for this some more and found this solution:
You connect your ws like this:
val opts = IO.Options()
opts.path = "/path/to/ws"
opts.transports = arrayOf(WebSocket.NAME) // Set the transfer to 'websocket' instead of 'polling'
val webSocket = IO.socket("http(s)://your.ip.here", opts)
webSocket.connect()
.on(Socket.EVENT_CONNECT) {
// Do your stuff here
}
.on("foo") { parameters -> // do something on recieving a 'foo' event
// 'parameters' is an Array of all parameters you sent
// Do your stuff here
}
If you want to emit an event, you'll call:
webSocket.emit("foo", "bar") // Emits a 'foo' event with 'bar' as a parameter
You will need to use
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;
so be sure to add the corresponding libraries to your build.gradle
dependencies {
...
implementation 'com.github.nkzawa:socket.io-client:0.6.0'
}
first import this
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;
and then initialize this one
val socket = IO.socket("http://localhost:4000/")
socket.on(Socket.EVENT_CONNECT, Emitter.Listener {
socket.emit("messages", "hi")
});
socket.connect()
It's a static block in java But we can't wirte same as in Kotlin.
We can use its like a companion object.
companion object{
private var mSocket: Socket?=null
init {
try {
mSocket = IO.socket(Constants.Chat_URl)
}
catch (e: Exception){
throw RuntimeException(e)
}
}
}
In Kotlin you can make a Socket Client like the following. All the Exceptions are handled here too.
fun pingYourTCPServerWith(message: String): String{
try {
val socket = Socket("<YOUR IP ADDRESS>", <YOUR PORT HERE>)
socket.use {
var responseString : String? = null
it.getOutputStream().write(message.toByteArray())
val bufferReader = BufferedReader(InputStreamReader(it.inputStream))
while (true) {
val line = bufferReader.readLine() ?: break
responseString += line
if (line == "exit") break
}
println("Received: $responseString")
bufferReader.close()
it.close()
return responseString!!
}
}catch (he: UnknownHostException){
val exceptionString = "An exception occurred:\n ${he.printStackTrace()}"
return exceptionString
}catch (ioe: IOException){
val exceptionString = "An exception occurred:\n ${ioe.printStackTrace()}"
return exceptionString
} catch (ce: ConnectException){
val exceptionString = "An exception occurred:\n ${ce.printStackTrace()}"
return exceptionString
}catch (se: SocketException){
val exceptionString = "An exception occurred:\n ${se.printStackTrace()}"
return exceptionString
}
}
The right syntax is below for anyone who is interested in the future
private lateinit var mSocket:Socket
fun socket(){
try {
mSocket=IO.socket("http://host:port")
}
catch(e: URISyntaxException){
println("Exception"+e)
}
}
I understand the difference between print and println methods.
But why Gradle with default logging level prints output with println but doesn't with print or printf?
TaskProgress.groovy
public class TaskProgress {
private static final String PROGRESS_SYMBOLS = '_/\\_';
private static final int MAX_POINTS = PROGRESS_SYMBOLS.length() - 2
AtomicBoolean inProgress = new AtomicBoolean(true)
int currentChar = 0
int delta = 1
private TaskProgress() {}
static TaskProgress doProgress() {
Log.error("START PROGRESS")
def taskProgress = new TaskProgress();
taskProgress.startProgress()
return taskProgress
}
private void startProgress() {
Thread.start {
Log.error('STARTING:')
while (inProgress.get()) {
if (currentChar > MAX_POINTS) {
delta = -1
} else if (currentChar == 0) {
delta = 1
}
println PROGRESS_SYMBOLS[currentChar] // it works
print PROGRESS_SYMBOLS[currentChar] // it doesn't work
currentChar += delta
if (!inProgress.get()) break;
}
Log.error('STOPPING:')
}
}
public void stopProgress() {
Log.error("STOP PROGRESS")
inProgress.set(false)
}
}
buid.gradle
task progress {
doLast {
def progress = TaskProgress.doProgress()
Thread.sleep(1000)
progress.stopProgress()
}
}
When I use print in the main thread it works okay. Is it a defect?
I raised a topic on official gradle forum: Gradle print vs println
PHP offers useful magic constants like:
__CLASS__
__FILE__
__METHOD__
and so on. Also the
get_class()
function provides a similar functionality.
Is there anything similar in Dart?
Compiler constants similar to PHP not available. But you can do this manually (not constant value).
This slower but it works.
import 'package:stack_trace/stack_trace.dart';
void main() {
print(__LINE__);
print(__METHOD__);
print(__FILE__);
new Foo();
}
class Foo {
Foo() {
print(__CLASS__);
}
}
String get __CLASS__ {
var frames = new Trace.current().frames;
if(frames.length > 1) {
var member = frames[1].member;
var parts = member.split(".");
if(parts.length > 1) {
return parts[1];
}
}
return null;
}
String get __METHOD__ {
var frames = new Trace.current().frames;
if(frames.length > 1) {
return frames[1].member;
}
return null;
}
String get __FILE__ {
var frames = new Trace.current().frames;
if(frames.length > 1) {
return frames[1].uri.path;
}
return null;
}
int get __LINE__ {
var frames = new Trace.current().frames;
if(frames.length > 1) {
return frames[1].line;
}
return null;
}
4
main
/home/andrew/dart/for_web/test/bin/test.dart
Foo
I'm leaking jRuby processes, and I don't know how to stop this. I need the groovy script to keep going after launching jRuby, and I need jRuby to die when the main script dies.
test.groovy, loop.rb
loop.rb
while( true )
puts 'Hello from jRuby'
sleep 1
end
test.groovy
def command = "jruby ./loop.rb"
Thread.start {
Process process
try {
process = command.execute()
}
catch (IOException e) {
e.printStackTrace()
return
}
Runtime.runtime.addShutdownHook {
println "Attempting to stop process"
process.destroy()
}
process.consumeProcessOutput(System.out, System.err)
process.waitFor()
}
while( true ){ println 'Hello from groovy'; Thread.sleep(1000) }
Execute
groovy test.groovy
How do I make sure that the external javaw process I create with jRuby is killed? Even though sending Cntrl+C to the running application kills the running groovy process, the jRuby process sticks around. Help?
This should do the trick, but it's ugly:
The basic solution is to look at the output of jps -lm and kill the appropriate process from the PIDs listed there.
new JavaProcessKiller().killAll('loop.rb')
class JavaProcessKiller {
public void killAll(String processPattern) {
getRunningJavaProcesses().each { String processLine ->
if (processLine.contains(processPattern)) {
String pidToKill = getPidFromProcessLine(processLine)
killPid(pidToKill)
}
}
}
protected String[] getRunningJavaProcesses() {
def output = new ByteArrayOutputStream()
def p = ['jps', '-lm'].execute()
p.consumeProcessOutput(new PrintStream(output), System.err)
p.waitFor()
return output.toString().split("\\n")
}
protected String getPidFromProcessLine(String line) {
def pidPattern = /^(\d+).*$/
def matcher = (line =~ pidPattern)
return matcher[0][1]
}
protected void killPid(String pid) {
def killCommands = [
['taskkill', '/F', '/PID', pid],
['kill', pid]
]
boolean processKilledSuccessfully = false
killCommands.each { command ->
if (!processKilledSuccessfully) {
try {
def output = new ByteArrayOutputStream()
def error = new ByteArrayOutputStream()
def process = command.execute()
process.consumeProcessOutput(new PrintStream(output), new PrintStream(error))
process.waitFor()
processKilledSuccessfully = true
}
catch (Exception e) {
}
}
}
}
}