repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
gluon
gluon-master/test/validation/Knight/SolverCorrect.java
package test.validation.Knight; import java.awt.Point; public class SolverCorrect { private KnightMoves km; private Point me; private int moves; public SolverCorrect(KnightMoves km, Point me, int moves) { this.km=km; this.me=me; this.moves=moves; } public void go() { Point []next=new Point[8]; int c=0; int m[]={1,-1}; /* Check if other thread has a better solution */ if (km.get_solution(me) <= moves) return; km.set_solution(me,moves); if (me.equals(km.get_prey())) return; for (int i=1; i <= 2; i++) for (int j=1; j <= 2; j++) if (i != j) for (int k=0; k < 2; k++) for (int l=0; l < 2; l++) next[c++]=new Point(i*m[k]+me.x,j*m[l]+me.y); for (Point n: next) if (n.x >= 0 && n.y >= 0 && n.x < KnightMoves.WIDTH && n.y < KnightMoves.WIDTH) { //System.out.println(n.toString()); new SolverCorrect(km,n,moves+1).go(); } } }
926
17.918367
58
java
gluon
gluon-master/test/validation/AllocateVector/Main.java
package test.validation.AllocateVector; import java.io.*; /** * class Test: Used to test class AllocationVector. */ public class Main { /** * Indicates number of threads runs to perform. */ private static final int runsNum = 1; /** * MAIN METHOD. * Gets from command-line: 1. Name of output file. * 2. Concurrency Parameter (little,average,lot). * @param args command-line arguments as written above. */ public static void main(String[] args) { for (int i=0; i < runsNum; i++) { runTest(args); } } /** * Gets from 'args': 1. Name of output file. * 2. Concurrency Parameter (little,average,lot). * @param args command-line arguments as written above. */ public static void runTest(String[] args) { AllocationVector vector = null; TestThread1 Thread1 = null; TestThread1 Thread2 = null; int[] Thread1Result = null; int[] Thread2Result = null; FileOutputStream out = null; /** * Reading command-line arguments. */ try { if (args.length != 2) { throw new Exception(); } // Opening output file with name 'args[0]' for append write. out = new FileOutputStream(args[0], false); // Checking concurrency parameter correctness. if ( (args[1].compareTo("little") != 0) && (args[1].compareTo("average") != 0) && (args[1].compareTo("lot") != 0)) { throw new Exception(); } } catch (Exception e) { System.err.println("Invalid command-line arguments..."); System.exit(1); } /** * If here, then command-line arguments are correct. * Therefore, proceeding according to the concurrency parameter value. */ // Setting threads run configuration according to concurrency parameter. if (args[1].compareTo("little") == 0) { vector = new AllocationVector(20000); Thread1Result = new int[1000]; Thread2Result = new int[1000]; } else if (args[1].compareTo("average") == 0) { vector = new AllocationVector(10000); Thread1Result = new int[2000]; Thread2Result = new int[2000]; } else if (args[1].compareTo("lot") == 0) { vector = new AllocationVector(5000); Thread1Result = new int[5000]; Thread2Result = new int[5000]; } // Creating threads, starting their run and waiting till they finish. Thread1 = new TestThread1(vector,Thread1Result); Thread2 = new TestThread1(vector,Thread2Result); Thread1.start(); //for (int i = 0; i < 100000; i++); // "Pause" between threads run to try "hide" // the BUG. Thread2.start(); try { Thread1.join(); Thread2.join(); } catch (InterruptedException e) { System.err.println("Error joining threads..."); System.exit(1); } // Checking correctness of threads run results and printing the according // tuple to output file. try { if (Thread1Result[0] == -2) { out.write("<Test, Thread1 tried to allocate block which is allocated, weak-reality (Two stage access)>\n".getBytes()); System.out.println("ups"); } else if (Thread1Result[0] == -3){ out.write("<Test, Thread1 tried to free block which is free, weak-reality (Two stage access)>\n".getBytes()); System.out.println("ups"); } else if (Thread2Result[0] == -2) { out.write("<Test, Thread2 tried to allocate block which is allocated, weak-reality (Two stage access)>\n".getBytes()); System.out.println("ups"); } else if (Thread2Result[0] == -3){ out.write("<Test, Thread2 tried to free block which is free, weak-reality (Two stage access)>\n".getBytes()); System.out.println("ups"); } else { out.write("<Test, correct-run, none>\n".getBytes()); } } catch (IOException ex) { System.err.println("Error writing to output file..."); System.exit(1); } } }
3,724
30.302521
122
java
gluon
gluon-master/test/validation/AllocateVector/AllocationVector.java
package test.validation.AllocateVector; import test.common.Atomic; import test.common.Contract; /** * class AllocationVector: Used to manage allocation and freeing of blocks. * BUG DOCUMENTATION: There is a synchronization GAP between the methods * "getFreeBlockIndex" and "markAsAllocatedBlock", in which anything can be done. */ @Contract(clauses ="getFreeBlockIndex markAsAllocatedBlock;") public class AllocationVector { /** * Character vector which holds information about allocated and free blocks, * in the following way: * if vector[i] == 'F' -> i-th block is free. * if vector[i] == 'A' -> i-th block is allocated. */ private char[] vector = null; /** * Constructor: Constructs AllocationVector for 'size' blocks, when all blocks * are free. * @param size Size of AllocationVector. */ public AllocationVector(int size) { // Allocating vector of size 'size', // when all blocks are assigned to free. vector = new char[size]; for (int i=0; i < size; i++) { vector[i] = 'F'; } } /** * Returns index of free block, if such exists. * If no free block, then -1 is returned. * @return Index of free block if such exists, else -1. */ @Atomic public int getFreeBlockIndex() { int i; int count; int startIndex; int interval; int searchDirection; double randomValue; int[] primeValues = { 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53 }; randomValue = Math.random(); // Choosing randomly start entry for search. startIndex = (int)Math.floor((vector.length - 1) * randomValue); // Choosing randomly increment/decrement prime value. interval = primeValues[(int)Math.floor((primeValues.length - 1) * randomValue)]; // Choosing randomly search direction and starting the search from randomly // choosen start entry in that direction with the randomly choosen interval. if (randomValue > 0.5) { // Searching forward. for (i = startIndex,count = 0; (count < vector.length) && (vector[i] != 'F') ; i = i + interval, i %= vector.length, count++); } else { // Searching backward. for (i = startIndex,count = 0; (count < vector.length) && (vector[i] != 'F') ; count++) { i = i - interval; if (i < 0) { i = i + vector.length; } } } if (count == vector.length) { return -1; // Indicates "no free block". } else { return i; // Returns the index of the found free block. } } /** * Marks i-th block as allocated. * @param i Index of block to allocate. * NOTE: If allocating already allocated block, then Exception is thrown. */ @Atomic public void markAsAllocatedBlock(int i) /*throws Exception */{ if (vector[i] != 'A') { vector[i] = 'A'; // Allocates i-th block. } else { // throw new Exception("Allocation"); } } /** * Marks i-th block as free. * @param i Index of block to free. * NOTE: If freeing already free block, then Exception is thrown. */ @Atomic public void markAsFreeBlock(int i)/* throws Exception*/ { if (vector[i] != 'F') { vector[i] = 'F'; // Frees i-th block. } else { // throw new Exception("Freeing"); } } }
3,153
27.160714
88
java
gluon
gluon-master/test/validation/AllocateVector/TestThread1.java
package test.validation.AllocateVector; // import org.deuce.Atomic; /** * class TestThread1: Used to run thread which allocates and frees blocks by * given AllocationVector object. */ public class TestThread1 extends Thread { /** * Reference to class AllocationVector object with which the thread will work. */ private AllocationVector vector = null; /** * An array to which the resulting allocated blocks indexes will be stored. * It's lenght indicates the number of accesses, which to perform to 'vector'. */ private int[] resultBuf = null; /** * Constructor: Constructs thread which will work on class AllocationVector * object 'vec', to which the thread will perform 'resBuf.length' accesses of * allocation and 'resBuf.length' accesses of frees. * The resulting allocated blocks indexes will be stored to 'resBuf'. * @param vec class AllocationVector object on which the thread will work. * resBuf Buffer for resulting allocated blocks indexes, which also * indicates the number of access which to perform to 'vec'. * NOTE: */ public TestThread1(AllocationVector vec,int[] resBuf) { if ((vec == null) || (resBuf == null)) { System.err.println("Thread start error..."); System.exit(1); } vector = vec; resultBuf = resBuf; } // @Atomic private void alloc_block(int i)/* throws Exception*/{ resultBuf[i] = vector.getFreeBlockIndex(); if (resultBuf[i] != -1) vector.markAsAllocatedBlock(resultBuf[i]); } /** * Perform 2 * 'resultBuf.length' accesses to 'vector', in the following way: * 'resultBuf.length' blocks allocations. * 'resultBuf.length' blocks frees. * NOTE: If allocation/free block error occurs, function sets resultBuf[0] to -2/-3. */ public void run() { // try { // Allocating 'resultBuf.length' blocks. for (int i = 0; i < resultBuf.length; i++) alloc_block(i); // Freeing 'resultBuf.length' blocks. for (int i = 0; i < resultBuf.length; i++) { if (resultBuf[i] != -1) { vector.markAsFreeBlock(resultBuf[i]); } } /*} catch (Exception e) { if (e.getMessage().compareTo("Allocation") == 0) { // resultBuf[0] = -2; } else { // resultBuf[0] = -3; } }*/ } }
2,217
28.184211
85
java
gluon
gluon-master/test/validation/Local/Cell.java
package test.validation.Local; import test.common.Atomic; import test.common.Contract; @Contract(clauses = "getValue setValue;" +"setValue getValue;") class Cell { private int n = 0; @Atomic int getValue() { return n; } @Atomic void setValue(int x) { n = x; } }
319
15
40
java
gluon
gluon-master/test/validation/Local/Local.java
package test.validation.Local; public class Local extends Thread { static Cell x = new Cell(); public static void main(String[] args) { new Local().start(); new Local().start(); } public void run() { int tmp; tmp = x.getValue(); tmp++; x.setValue(tmp); } }
278
13.684211
41
java
gluon
gluon-master/test/validation/Elevator/Floor.java
package test.validation.Elevator; /* * Copyright (C) 2000 by ETHZ/INF/CS * All rights reserved * * @version $Id$ * @author Roger Karrer */ import java.util.*; // class to represent a floor in the control object class Floor { // Lists of people waiting to go up, and down // The Vectors will have instances of Integer objects. The Integer will // store the floor that the person wants to go to public Vector upPeople, downPeople; // True if an elevator has claimed the the up or down call public boolean upFlag, downFlag; public Floor() { upPeople = new Vector(); downPeople = new Vector(); upFlag = false; downFlag = false; } }
655
20.866667
72
java
gluon
gluon-master/test/validation/Elevator/Lift.java
package test.validation.Elevator; /* * Copyright (C) 2000 by ETHZ/INF/CS * All rights reserved * * @version $Id$ * @author Roger Karrer */ import java.util.*; // class that implements the elevator threads class Lift extends Thread { // used for assigning unique ids to the elevators private static int count = 0; public static final int IDLE = 0; public static final int UP = 1; public static final int DOWN = 2; private int travelDir; // one of IDLE, UP, or DOWN private int currentFloor; // holds the number of people who want to get off on each floor private int[] peopleFor; // Values in pickupOn can be IDLE, UP, DOWN, and UP|DOWN, which indicate // which calls the elevator should respond to on each floor. IDLE means // don't pick up on that floor private int[] pickupOn; private int firstFloor, lastFloor; // reference to the shared control object private Controls controls; // Create a new elevator that can travel from floor 1 to floor numFloors. // The elevator starts on floor 1, and is initially idle with no passengers. // c is a reference to the shared control object // The thread starts itself public Lift(int numFloors, Controls c) { super("Lift " + count++); controls = c; firstFloor = 1; lastFloor = numFloors; travelDir = IDLE; currentFloor = firstFloor; pickupOn = new int[numFloors + 1]; peopleFor = new int[numFloors + 1]; for (int i = 0; i <= numFloors; i++) { pickupOn[i] = IDLE; peopleFor[i] = 0; } start(); } // Body of the thread. If the elevator is idle, it checks for calls // every tenth of a second. If it is moving, it takes 1 second to // move between floors. public void run() { while (true) { if (travelDir == IDLE) { try { sleep(100); } catch (InterruptedException e) { } doIdle(); } else { try { sleep(1000); } catch (InterruptedException e) { } doMoving(); } } } // IDLE // First check to see if there is an up or down call on what ever floor // the elevator is idle on. If there isn't one, then check the other floors. private void doIdle() { boolean foundFloor = false; int targetFloor = -1; if (claimUp(controls, getName(), currentFloor)) { // System.out.println("Lift::doIdle - could claim upcall on current floor"); // // CARE foundFloor = true; targetFloor = currentFloor; travelDir = UP; addPeople(controls.getUpPeople(currentFloor)); } else if (claimDown(controls, getName(), currentFloor)) { // System.out.println("Lift::doIdle - could claim downcall on current floor"); // // CARE foundFloor = true; targetFloor = currentFloor; travelDir = DOWN; addPeople(controls.getDownPeople(currentFloor)); } // System.out.println("Lift::doIdle - lookuing for calls on other floors"); // // CARE for (int floor = firstFloor; !foundFloor && floor <= lastFloor; floor++) { // System.out.println("Lift::doIdle - checking floor " + floor); // // CARE if (claimUp(controls, getName(), floor)) { // System.out.println("Lift::doIdle - success with claimUp " + // floor); // CARE foundFloor = true; targetFloor = floor; pickupOn[floor] |= UP; travelDir = (targetFloor > currentFloor) ? UP : DOWN; } else if (claimDown(controls, getName(), floor)) { // System.out.println("Lift::doIdle - success with claimDown " + // floor); // CARE foundFloor = true; targetFloor = floor; pickupOn[floor] |= DOWN; travelDir = (targetFloor > currentFloor) ? UP : DOWN; } } if (foundFloor) { // System.out.println(getName() + " is now moving " // + ((travelDir == UP) ? "UP" : "DOWN")); } } // MOVING // First change floor (up or down as appropriate) // Drop off passengers if we have to // Then pick up passengers if we have to private void doMoving() { currentFloor += (travelDir == UP) ? 1 : -1; int oldDir = travelDir; if (travelDir == UP && currentFloor == lastFloor) travelDir = DOWN; if (travelDir == DOWN && currentFloor == firstFloor) travelDir = UP; // System.out.println(getName() + " now on " + currentFloor); if (peopleFor[currentFloor] > 0) { // System.out.println(getName() + " delivering " // + peopleFor[currentFloor] + " passengers on " // + currentFloor); peopleFor[currentFloor] = 0; } // Pickup people who want to go up if: // 1) we previous claimed an up call on this floor, or // 2) we are travelling up and there is an unclaimed up call on this // floor if (((pickupOn[currentFloor] & UP) != 0) || (travelDir == UP && claimUp(controls, getName(), currentFloor))) { addPeople(controls.getUpPeople(currentFloor)); pickupOn[currentFloor] &= ~UP; } // Pickup people who want to go down if: // 1) we previous claimed an down call on this floor, or // 2) we are travelling down and there is an unclaimed down call on this // floor if (((pickupOn[currentFloor] & DOWN) != 0) || (travelDir == DOWN && claimDown(controls, getName(), currentFloor))) { addPeople(controls.getDownPeople(currentFloor)); pickupOn[currentFloor] &= ~DOWN; } if (travelDir == UP) { // If we are travelling up, and there are people who want to get off // on a floor above this one, continue to go up. if (stopsAbove()) ; else { // If we are travelling up, but no one wants to get off above // this // floor, but they do want to get off below this one, start // moving down if (stopsBelow()) travelDir = DOWN; // Otherwise, no one is the elevator, so become idle else travelDir = IDLE; } } else { // If we are travelling down, and there are people who want to get // off // on a floor below this one, continue to go down. if (stopsBelow()) ; else { // If we are travelling down, but no one wants to get off below // this // floor, but they do want to get off above this one, start // moving up if (stopsAbove()) travelDir = UP; // Otherwise, no one is the elevator, so become idle else travelDir = IDLE; } } // Print out are new direction if (oldDir != travelDir) { // System.out.print(getName()); if (travelDir == IDLE){ // System.out.println(" becoming IDLE"); } else if (travelDir == UP){ // System.out.println(" changing to UP"); } else if (travelDir == DOWN){ // System.out.println(" changing to DOWN"); } } } // Returns true if there are passengers in the elevator who want to stop // on a floor above currentFloor, or we claimed a call on a floor below // currentFloor private boolean stopsAbove() { boolean above = false; for (int i = currentFloor + 1; !above && i <= lastFloor; i++) above = (pickupOn[i] != IDLE) || (peopleFor[i] != 0); return above; } // Returns true if there are passengers in the elevator who want to stop // on a floor below currentFloor, or we claiemda call on a floor above // currentFloor private boolean stopsBelow() { boolean below = false; for (int i = currentFloor - 1; !below && (i >= firstFloor); i--) below = (pickupOn[i] != IDLE) || (peopleFor[i] != 0); return below; } // Updates peopleFor based on the Vector of destination floors received // from the control object private void addPeople(Vector people) { // System.out.println(getName() + " picking up " + people.size() // + " passengers on " + currentFloor); for (Enumeration e = people.elements(); e.hasMoreElements();) { int toFloor = ((Integer) e.nextElement()).intValue(); peopleFor[toFloor] += 1; } } // An elevator calls this if it wants to claim an up call // Sets the floor's upFlag to true if he has not already been set to true // Returns true if the elevator has successfully claimed the call, and // False if the call was already claimed (upFlag was already true) public boolean claimUp(Controls c, String lift, int floor) { if (c.checkUp(floor)) { c.claimUp(floor); return true; } return false; } // An elevator calls this if it wants to claim an down call // Sets the floor's downFlag to true if he has not already been set to true // Returns true if the elevator has successfully claimed the call, and // False if the call was already claimed (downFlag was already true) public boolean claimDown(Controls c, String lift, int floor) { if (c.checkDown(floor)) { c.claimDown(floor); return true; } return false; } }
8,532
29.916667
81
java
gluon
gluon-master/test/validation/Elevator/Controls.java
package test.validation.Elevator; /* * Copyright (C) 2000 by ETHZ/INF/CS * All rights reserved * * @version $Id$ * @author Roger Karrer */ import java.util.*; import test.common.Atomic; import test.common.Contract; // class of the shared control object @Contract(clauses = "checkUp(X) claimUp(X);" +"checkDown(X) claimDown(X);") class Controls { private Floor[] floors; public Controls(int numFloors) { floors = new Floor[numFloors + 1]; for (int i = 0; i <= numFloors; i++) floors[i] = new Floor(); } // this is called to inform the control object of a down call on floor // onFloor // @Atomic public void pushDown(int onFloor, int toFloor) { // synchronized(floors[onFloor]) { // System.out.println("*** Someone on floor " + onFloor // + " wants to go to " + toFloor); floors[onFloor].downPeople.addElement(new Integer(toFloor)); if (floors[onFloor].downPeople.size() == 1) floors[onFloor].downFlag = false; // } } // this is called to inform the control object of an up call on floor // onFloor // @Atomic public void pushUp(int onFloor, int toFloor) { // synchronized(floors[onFloor]) { // System.out.println("*** Someone on floor " + onFloor // + " wants to go to " + toFloor); floors[onFloor].upPeople.addElement(new Integer(toFloor)); if (floors[onFloor].upPeople.size() == 1) floors[onFloor].upFlag = false; // } } // Added by Vasco Pessanha @Atomic public boolean claimUp(int floor) { floors[floor].upFlag = true; return true; } // Added by Vasco Pessanha @Atomic public boolean claimDown(int floor) { floors[floor].downFlag = true; return true; } // An elevator calls this to see if an up call has occured on the given // floor. If another elevator has already claimed the up call on the // floor, checkUp() will return false. This prevents an elevator from // wasting its time trying to claim a call that has already been claimed @Atomic public boolean checkUp(int floor) { // synchronized(floors[floor]) { boolean ret = floors[floor].upPeople.size() != 0; ret = ret && !floors[floor].upFlag; return ret; // } } // An elevator calls this to see if a down call has occured on the given // floor. If another elevator has already claimed the down call on the // floor, checkUp() will return false. This prevents an elevator from // wasting its time trying to claim a call that has already been claimed @Atomic public boolean checkDown(int floor) { // synchronized(floors[floor]) { boolean ret = floors[floor].downPeople.size() != 0; ret = ret && !floors[floor].downFlag; return ret; // } } // An elevator calls this to get the people waiting to go up. The // returned Vector contains Integer objects that represent the floors // to which the people wish to travel. The floors vector and upFlag // are reset. @Atomic public Vector getUpPeople(int floor) { // synchronized(floors[floor]) { Vector temp = floors[floor].upPeople; floors[floor].upPeople = new Vector(); floors[floor].upFlag = false; return temp; // } } // An elevator calls this to get the people waiting to go down. The // returned Vector contains Integer objects that represent the floors // to which the people wish to travel. The floors vector and downFlag // are reset. @Atomic public Vector getDownPeople(int floor) { // synchronized(floors[floor]) { Vector temp = floors[floor].downPeople; floors[floor].downPeople = new Vector(); floors[floor].downFlag = false; return temp; // } } }
3,563
28.213115
73
java
gluon
gluon-master/test/validation/Elevator/Elevator.java
package test.validation.Elevator; /* * Copyright (C) 2000 by ETHZ/INF/CS * All rights reserved * * @version $Id$ * @author Roger Karrer */ import java.util.*; import java.io.*; public class Elevator { // shared control object private Controls controls; private Vector events; // Initializer for main class, reads the input and initlizes // the events Vector with ButtonPress objects private Elevator() { InputStreamReader reader = new InputStreamReader(System.in); StreamTokenizer st = new StreamTokenizer(reader); st.lowerCaseMode(true); st.parseNumbers(); events = new Vector(); int numFloors = 0, numLifts = 0; try { numFloors = readNum(st); numLifts = readNum(st); int time = 0, to = 0, from = 0; do { time = readNum(st); if (time != 0) { from = readNum(st); to = readNum(st); events.addElement(new ButtonPress(time, from, to)); } } while (time != 0); } catch (IOException e) { System.err.println("error reading input: " + e.getMessage()); e.printStackTrace(System.err); System.exit(1); } // Create the shared control object controls = new Controls(numFloors); // Create the elevators for (int i = 0; i < numLifts; i++) new Lift(numFloors, controls); } // Press the buttons at the correct time private void begin() { // Get the thread that this method is executing in Thread me = Thread.currentThread(); // First tick is 1 int time = 1; for (int i = 0; i < events.size();) { ButtonPress bp = (ButtonPress) events.elementAt(i); // if the current tick matches the time of th next event // push the correct buttton if (time == bp.time) { System.out .println("Elevator::begin - its time to press a button"); if (bp.onFloor > bp.toFloor) controls.pushDown(bp.onFloor, bp.toFloor); else controls.pushUp(bp.onFloor, bp.toFloor); i += 1; } // wait 1/2 second to next tick try { me.sleep(500); } catch (InterruptedException e) { } time += 1; } } private int readNum(StreamTokenizer st) throws IOException { int tokenType = st.nextToken(); if (tokenType != StreamTokenizer.TT_NUMBER) throw new IOException("Number expected!"); return (int) st.nval; } public static void main(String args[]) { Elevator building = new Elevator(); building.begin(); } }
2,349
22.737374
64
java
gluon
gluon-master/test/validation/Elevator/ButtonPress.java
package test.validation.Elevator; /* * Copyright (C) 2000 by ETHZ/INF/CS * All rights reserved * * @version $Id$ * @author Roger Karrer */ // class to represent a press of a call button class ButtonPress { // floor on which the button is pressed public int onFloor; // floor to which the person wishes to travel public int toFloor; // tick at which the button is pressed public int time; public ButtonPress(int t, int from, int to) { onFloor = from; toFloor = to; time = t; } }
503
17
46
java
gluon
gluon-master/test/validation/VectorFail/Main.java
package test.validation.VectorFail; public class Main{ public int x; public int y; public Main (int x , int y){ this.x = x; this.y = y; } public static void main(String[] args) { Vector pair = new Vector(1,2); for(int i = 0; i < 10; i++){ new MyThread(pair).start(); } } }
294
15.388889
41
java
gluon
gluon-master/test/validation/VectorFail/Vector.java
package test.validation.VectorFail; import test.common.Atomic; import test.common.Contract; @Contract(clauses = "getMax getMin;" +"getMin getMax;") public class Vector{ public int first; public int second; public boolean firstIsGreater; public Vector(int x1, int x2) { this.first = x1; this.second = x2; this.firstIsGreater = x1 > x2; } public int getFirst() { return first; } public int getSecond() { return second; } @Atomic public int getMax() { if(firstIsGreater) return first; return second; } @Atomic public int getMin() { if(!firstIsGreater) return first; return second; } @Atomic public void setElements(int x1, int x2){ this.first = x1; this.second = x2; } public String toString(){ return "("+first+","+second+")"; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + new Integer(first).hashCode(); result = prime * result + new Integer(second).hashCode(); return result; } @Override public boolean equals(Object obj) { if (!(obj instanceof Vector)) return false; Vector other = (Vector) obj; return first == other.first && second == other.second; } }
1,202
17.227273
59
java
gluon
gluon-master/test/validation/VectorFail/MyThread.java
package test.validation.VectorFail; import java.util.Random; public class MyThread extends Thread{ Vector vector; public MyThread(Vector v){ this.vector = v; } public void run() { while(true){ Random r = new Random(); int val = r.nextInt(10); vector.setElements(val, val*2); int max = vector.getMax(); int min = vector.getMin(); assert(max == 2*min); // if(max != 2*min) // System.err.println("ERROR: MAX ("+max+") != 2.MIN (2."+min+")"); } } }
485
17
70
java
gluon
gluon-master/test/validation/Jigsaw/Main.java
package test.validation.Jigsaw; class Runner extends Thread { private ResourceStoreManager rsm; public Runner(ResourceStoreManager rsm) { this.rsm = rsm; } // not synched!!! HLDR, but we get a false negative! ResourceStore loadResourceStore(ResourceStoreManager r) { if (r.checkClosed()) return null; // R(closed) Entry e = r.lookupEntry(new Object()); // R(entries), W(entries) return e.getStore(); } public void run() { loadResourceStore(rsm); rsm.shutdown(); } } public class Main { public static void main(String args[]) { ResourceStoreManager rsm = new ResourceStoreManager(); new Runner(rsm).start(); new Runner(rsm).start(); new Runner(rsm).start(); } }
729
21.8125
66
java
gluon
gluon-master/test/validation/Jigsaw/ResourceStoreManager.java
package test.validation.Jigsaw; import java.util.HashMap; import java.util.Map; import test.common.Atomic; import test.common.Contract; @Contract(clauses = "checkClosed lookupEntry;") public class ResourceStoreManager { boolean closed = false; Map entries = new HashMap(); // @Atomic // void checkClosed() { // if (closed) // throw new RuntimeException(); // } //We rewrite the method without exceptions @Atomic boolean checkClosed() { return closed; } @Atomic Entry lookupEntry(Object key) { Entry e = (Entry) entries.get(key); if (e == null) { e = new Entry(key.toString()); entries.put(key, e); entries=null; } return e; } @Atomic void shutdown() { entries.clear(); closed = true; } }
753
16.534884
47
java
gluon
gluon-master/test/validation/Jigsaw/Entry.java
package test.validation.Jigsaw; public class Entry { protected ResourceStore store; public Entry(String name){ store = new ResourceStore(name); } public ResourceStore getStore() { return store; } public String getName(){ return store.getName(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((store == null) ? 0 : store.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Entry other = (Entry) obj; if (store == null) { if (other.store != null) return false; } else if (!store.equals(other.store)) return false; return true; } }
782
17.209302
69
java
gluon
gluon-master/test/validation/Jigsaw/ResourceStore.java
package test.validation.Jigsaw; public class ResourceStore { protected String name; public ResourceStore(String name){ this.name = name; } public String getName(){ return name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ResourceStore other = (ResourceStore) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
718
17.921053
67
java
gluon
gluon-master/test/validation/MyStringBuffer/Main.java
package test.validation.MyStringBuffer; public class Main { public static void main(String args[]) { MyStringBuffer ham = new MyStringBuffer("ham"); MyStringBuffer burger = new MyStringBuffer("burger"); append(ham, burger); System.out.println(ham); } public static MyStringBuffer append(MyStringBuffer t, MyStringBuffer other) { int len = other.length(); //read other.length // ...other threads may change sb.length(), // ...so len does not reflect the length of 'other' char[] value = new char[len]; other.getChars(0, len, value, 0); return t; } }
580
21.346154
78
java
gluon
gluon-master/test/validation/MyStringBuffer/MyStringBuffer.java
package test.validation.MyStringBuffer; import test.common.Atomic; import test.common.Contract; /* * Simulates java.lang.StringBuffer */ @Contract(clauses = "X=length getChars(_,X,_,_);") class MyStringBuffer { private java.lang.StringBuffer buffer; public MyStringBuffer(String string) { this.buffer = new StringBuffer(string); } @Atomic public int length() { return this.buffer.length(); //Read buffer } @Atomic public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) { this.buffer.getChars(srcBegin, srcEnd, dst, dstBegin); //Read buffer } }
584
20.666667
75
java
gluon
gluon-master/test/validation/Coord03/T3.java
package test.validation.Coord03; public class T3 extends Thread{ /* * x3 = c.getX(); * y3 = c.getY(); * use(x3,y3); */ Vars v; public T3(Vars v){ this.v = v; } public void run() { System.out.println("Estou no run do t3"); int x3 = v.getX(); int y3 = v.getY(); use(x3,y3); } private void use(int x3, int y3) { // Do something... } }
363
13.56
43
java
gluon
gluon-master/test/validation/Coord03/Main.java
package test.validation.Coord03; public class Main{ public int x; public int y; public Main (int x , int y){ this.x = x; this.y = y; } public static void main(String[] args) { Vars v = new Vars(); for(int i = 0;i<10;i++){ new T1(v).start(); new T2(v).start(); new T3(v).start(); new T4(v).start(); } } }
333
15.7
41
java
gluon
gluon-master/test/validation/Coord03/Pair.java
package test.validation.Coord03; public class Pair<T1, T2> { private T1 first; private T2 second; public Pair(T1 first, T2 second) { super(); this.first = first; this.second = second; } public Pair(Pair<T1, T2> p) { if(p != null){ this.first = p.first; this.second = p.second; } } public T1 getFirst() { return first; } public void setFirst(T1 first) { this.first = first; } public T2 getSecond() { return second; } public void setSecond(T2 second) { this.second = second; } public String toString(){ if(first == null || second == null) return ""; return "("+first.toString()+","+second.toString()+")"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((first == null) ? 0 : first.hashCode()); result = prime * result + ((second == null) ? 0 : second.hashCode()); return result; } @Override public boolean equals(Object obj) { if (!(obj instanceof Pair<?,?>)) return false; Pair<?, ?> other = (Pair<?,?>) obj; if (first == null) { if (other.first != null) return false; } else if (!first.equals(other.first)) return false; if (second == null) { if (other.second != null) return false; } else if (!second.equals(other.second)) return false; return true; } }
1,317
18.382353
71
java
gluon
gluon-master/test/validation/Coord03/Vars.java
package test.validation.Coord03; import test.common.Atomic; import test.common.Contract; @Contract(clauses = "getX getY;" +"getY getX;" +"setX setY;" +"setY setX;") public class Vars { int x = 0; int y = 0; public Vars (int x, int y){ this.x = x; this.y = y; } public Vars(){ this(0,0); } @Atomic public int getX() { return x; } @Atomic public void setX(int x) { this.x = x; } @Atomic public int getY() { return y; } @Atomic public void setY(int y) { this.y = y; } @Atomic public Pair<Integer,Integer> getXY() { return new Pair<Integer,Integer>(x,y); } @Atomic public void setXY(int x1, int x2) { x = x1; y = x2; } }
727
12.735849
40
java
gluon
gluon-master/test/validation/Coord03/T4.java
package test.validation.Coord03; public class T4 extends Thread{ /* * x4 = c.getX(); * use(x4); * d4 = c.getXY(); * x4 = d4.getX(); * y4 = d4.getY(); * use(x4,y4); */ Vars v; public T4(Vars v){ this.v = v; } @Override public void run() { System.out.println("Estou no run do t4"); int x4 = v.getX(); use(x4); Pair<Integer,Integer> v2 = v.getXY(); x4 = v2.getFirst(); int y4 = v2.getSecond(); use(x4,y4); } private void use(int x4, int y4) { // Do something... } private void use(int x4) { // Do something... } }
562
13.815789
43
java
gluon
gluon-master/test/validation/Coord03/T2.java
package test.validation.Coord03; public class T2 extends Thread{ Vars v; public T2(Vars v){ this.v = v; } private void use(int a){ // Do something... } public void run() { System.out.println("Estou no run do t2"); int z = v.getX(); use(z); } }
264
12.947368
43
java
gluon
gluon-master/test/validation/Coord03/T1.java
package test.validation.Coord03; public class T1 extends Thread{ /* * d1 = new Coord(1,2); * c.setXY(d1); */ Vars v; public T1(Vars v){ this.v = v; } public void run() { System.out.println("Estou no run do t1"); v.setXY(1,2); } }
251
11.6
43
java
gluon
gluon-master/test/validation/ConnectionTest/Counter.java
package test.validation.ConnectionTest; import test.common.Atomic; public class Counter { int n = 0; @Atomic public void reset() { n = 0; } public void increment() { n++; } }
189
10.176471
39
java
gluon
gluon-master/test/validation/ConnectionTest/GUI.java
package test.validation.ConnectionTest; import java.io.IOException; import java.util.Random; class GUI extends Thread { Connection connection; public GUI(Connection connection) { this.connection = connection; } public static void main(String args[]) { Connection connection = new Connection(); connection.connect(); for (int i = 0; i < 10; i++) new GUI(connection).start(); } boolean trySendMsg(String msg) throws IOException { if (this.connection.isConnected()) { this.connection.send(msg); return true; } else { return false; } } private void disconnect() { try { this.connection.resetSocket(); this.connection.resetCounter(); } catch (Exception e) { } } public void run() { Random rand = new Random(); int command; try { do { command = rand.nextInt(10); if (command == 0) disconnect(); else { byte[] bytes = new byte[rand.nextInt(10)]; rand.nextBytes(bytes); String msg = new String(bytes); this.trySendMsg(msg); } } while (command != 0); } catch (IOException e) { e.printStackTrace(); } } }
1,190
18.209677
52
java
gluon
gluon-master/test/validation/ConnectionTest/Connection.java
package test.validation.ConnectionTest; import java.io.IOException; import java.net.Socket; import test.common.Atomic; import test.common.Contract; @Contract(clauses = "isConnected send;" +"resetSocket resetCounter;") class Connection { private final Counter counter; private Socket socket; public Connection() { this.socket = null; this.counter = new Counter(); } // BCT public void connect() { this.socket = new Socket(); } public void resetCounter() { this.counter.reset(); } //Method created to englobe the transaction @Atomic public void resetSocket() throws IOException{ this.socket.close(); } @Atomic public boolean isConnected() { return !this.socket.isClosed(); // (this.socket != null); } @Atomic public void send(String msg) throws IOException { this.socket.getOutputStream().write(msg.getBytes()); // socket = null; this.counter.increment(); } }
924
17.877551
54
java
gluon
gluon-master/test/validation/ArithmeticDatabase/Main.java
package test.validation.ArithmeticDatabase; public class Main { public static final int CLIENTS=5; private static Table<RPN_Expression,Integer> exp_table; private static Table<Integer,Integer> res_table; private static void debug_print_tables() { System.out.println("exp table:"); System.out.println(exp_table); System.out.println(); System.out.println("res table:"); System.out.println(res_table); } /* The database is consistent if, and only if, * * 1. For each entry in exp table there is a entry in res * with the correct expression value. * 2. There is no duplicate res in res table. * 3. Every key in res table is unique. * 4. Every entry in res table is referenced at least by one * entry in exp table. */ private static boolean is_db_consistent() { /* check condition 1 */ for (Pair<RPN_Expression,Integer> exp_tuple: exp_table) for (Pair<Integer,Integer> res_tuple: res_table) if (exp_tuple.v == res_tuple.k && exp_tuple.k.evaluate() != res_tuple.v) return false; /* Check condition 2 and 3 */ for (Pair<Integer,Integer> res1_tuple: res_table) for (Pair<Integer,Integer> res2_tuple: res_table) if (res1_tuple != res2_tuple && (res1_tuple.k == res2_tuple.k || res1_tuple.v == res2_tuple.v)) return false; /* check condition 4 * * This condition will not be violated with our * current program. */ for (Pair<Integer,Integer> res_tuple: res_table) { boolean ok=false; for (Pair<RPN_Expression,Integer> exp_tuple: exp_table) if (res_tuple.k == exp_tuple.v) { ok=true; break; } if (!ok) return false; } return true; } public static void main(String[] args) { Client[] clients=new Client[CLIENTS]; exp_table=new Table<RPN_Expression,Integer>(); res_table=new Table<Integer,Integer>(); for (int i=0; i < CLIENTS; i++) { clients[i]=new Client(exp_table,res_table); clients[i].start(); } for (Client c: clients) try { c.join(); } catch (Exception e) {} //debug_print_tables(); if (!is_db_consistent()) System.out.println("err"); } }
2,138
23.586207
61
java
gluon
gluon-master/test/validation/ArithmeticDatabase/Pair.java
package test.validation.ArithmeticDatabase; public class Pair<K extends Comparable<K>, V> { public K k; public V v; public Pair(K k, V v) { super(); this.k = k; this.v = v; } public Pair(Pair<K, V> p) { if(p != null){ this.k = p.k; this.v = p.v; } } public K getk() { return k; } public void setk(K k) { this.k = k; } public V getv() { return v; } public void setv(V v) { this.v = v; } public String toString(){ if(k == null || v == null) return ""; return "("+k.toString()+","+v.toString()+")"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((k == null) ? 0 : k.hashCode()); result = prime * result + ((v == null) ? 0 : v.hashCode()); return result; } @Override public boolean equals(Object obj) { if (!(obj instanceof Pair<?,?>)) return false; Pair<?, ?> other = (Pair<?,?>) obj; if (k == null) { if (other.k != null) return false; } else if (!k.equals(other.k)) return false; if (v == null) { if (other.v != null) return false; } else if (!v.equals(other.v)) return false; return true; } }
1,153
16.753846
61
java
gluon
gluon-master/test/validation/ArithmeticDatabase/Table.java
package test.validation.ArithmeticDatabase; import java.util.List; import java.util.LinkedList; import java.util.Iterator; import test.common.Atomic; import test.common.Contract; @Contract(clauses="get_max_key insert;" +"iterator get_max_key;") public class Table<K extends Comparable<K>,V> implements Iterable<Pair<K,V>> { private List<Pair<K,V>> table; public Table() { table=new LinkedList<Pair<K,V>>(); } @Atomic public /*synchronized*/ void insert(K k, V v) { table.add(new Pair<K,V>(k,v)); } @Atomic public /*synchronized*/ int count() { return table.size(); } @Atomic public /*synchronized*/ K get_max_key() { K max=null; for (Pair<K,V> row: table) if (max == null || max.compareTo(row.k) < 0) max=row.k; return max; } // @Atomic public /*synchronized*/ Iterator<Pair<K,V>> iterator() { return table.iterator(); } @Atomic public /*synchronized*/ String toString() { String r="{"; int i=0; for (Pair<K,V> p: table) { r+=(i == 0 ? "" : ",")+"\n ("+p.k+","+p.v+")"; i++; } return r+"}"; } }
1,103
15.477612
76
java
gluon
gluon-master/test/validation/ArithmeticDatabase/Client.java
package test.validation.ArithmeticDatabase; import java.util.Random; import test.common.Atomic; public class Client extends Thread { public static final int EXPS=5; public static final int EXP_OPS=10; Table<RPN_Expression,Integer> exp_table; Table<Integer,Integer> res_table; public Client(Table<RPN_Expression,Integer> exp_table, Table<Integer,Integer> res_table) { this.exp_table=exp_table; this.res_table=res_table; } private RPN_Expression create_expression() { Random rnd=new Random(); RPN_Expression exp=new RPN_Expression(); /* We will not care if the expression overflows, * since the results, although arithmetically wrong, * are consistent. */ for (int i=0; i <= EXP_OPS; i++) exp.push(rnd.nextInt()%100); for (int i=0; i < EXP_OPS; i++) exp.push("+-*/%".charAt(Math.abs(rnd.nextInt())%5)); return exp; } /* Returns -1 if no key have the pretended result */ @Atomic private int get_key_by_result(int result) { for (Pair<Integer,Integer> t: res_table) if (t.v == result) return t.k; return -1; } private void insert_new_expression(RPN_Expression exp) { Integer foreign_key=null; /* If there is a entry with exp.evaluate() in * exp_table use that entry instead of inserting * a new one */ if ((foreign_key = get_key_by_result(exp.evaluate())) < 0) { foreign_key = res_table.get_max_key(); foreign_key = (foreign_key == null) ? 0 : foreign_key+1; res_table.insert(foreign_key,exp.evaluate()); } exp_table.insert(exp,foreign_key); } public void run() { for (int i=0; i < EXPS; i++) { RPN_Expression exp; do exp=create_expression(); while (!exp.isFinite()); /* System.out.println(exp.evaluate()); */ insert_new_expression(exp); } } }
1,791
19.597701
60
java
gluon
gluon-master/test/validation/ArithmeticDatabase/RPN_Expression.java
package test.validation.ArithmeticDatabase; import java.util.List; import java.util.Stack; import java.util.LinkedList; public class RPN_Expression implements Comparable<RPN_Expression> { private class RPN_Node { public boolean operator; public char op; public int integer; public RPN_Node(char op) { operator=true; this.op=op; } public RPN_Node(int integer) { operator=false; this.integer=integer; } }; private List<RPN_Node> exp; public RPN_Expression() { exp=new LinkedList<RPN_Node>(); } public void push(char op) { exp.add(new RPN_Node(op)); } public void push(int integer) { exp.add(new RPN_Node(integer)); } // pre: !stack.empty() public int evaluate() { Stack<Integer> stack=new Stack<Integer>(); for (RPN_Node node: exp) if (node.operator) { int o2=stack.pop(); int o1=stack.pop(); switch (node.op) { case '+': stack.push(o1+o2); break; case '-': stack.push(o1-o2); break; case '*': stack.push(o1*o2); break; case '/': stack.push(o1/o2); break; case '%': stack.push(o1%o2); break; } } else stack.push(node.integer); return stack.pop(); } public boolean isFinite() { try { evaluate(); } catch (ArithmeticException e) { return false; } return true; } public int compareTo(RPN_Expression other) { return -1; // dummy } public String toString() { String r=""; int i=0; for (RPN_Node node: exp) { r+=(i == 0 ? "" : ", "); if (node.operator) r+=node.op; else r+=node.integer; i++; } return r; } }
1,598
13.536364
44
java
gluon
gluon-master/test/validation/Coord04/CoordMain.java
package test.validation.Coord04; public class CoordMain extends Thread { Coord coord; public static void main(String[] args) { Coord c = new Coord(); new CoordMain(c).start(); new CoordMain(c).start(); } public CoordMain(Coord coord) { this.coord = coord; } public void run() { coord.swap(); reset(); } public void reset() { coord.resetX(); // inconsistent state (0, y) coord.resetY(); } }
447
15
41
java
gluon
gluon-master/test/validation/Coord04/Coord.java
package test.validation.Coord04; import test.common.Atomic; import test.common.Contract; @Contract(clauses = "resetX resetY;" +"resetY resetX;") class Coord { private int x, y; public Coord() { x=y=0; } @Atomic public void swap() { int oldX = x; x = y; // swap X y = oldX; // swap Y } @Atomic public void resetX(){ x = 0; } @Atomic public void resetY(){ y = 0; } }
490
13.878788
37
java
gluon
gluon-master/test/validation/AccountTest/Main.java
package test.validation.AccountTest; public class Main { static Account a; public static void main(String[] args) { //this will be accessed by both threadsd a = new Account(0, "Account name"); new Update().start(); new Update().start(); } }
254
18.615385
42
java
gluon
gluon-master/test/validation/AccountTest/Account.java
package test.validation.AccountTest; import test.common.Atomic; import test.common.Contract; @Contract(clauses = "getBalance setBalance;" +"setBalance getBalance;") public class Account { protected int balance; protected String name; public Account(){ this.balance = 0; this.name = ""; } public Account(int balance, String name){ this.balance = balance; this.name = name; } public String getName(){ return name; } @Atomic public int getBalance() { return balance; } @Atomic public void setBalance(int newValue) { balance = newValue; } }
593
14.631579
42
java
gluon
gluon-master/test/validation/AccountTest/Update.java
package test.validation.AccountTest; import java.util.Random; public class Update extends Thread { void update (Account account, int a) { int tmp = account.getBalance(); tmp = tmp + a; account.setBalance(tmp); } public void run() { while(true){ Random r = new Random(); int n = r.nextInt(); update(Main.a,n); } } }
342
15.333333
39
java
gluon
gluon-master/test/validation/NASA/Cell.java
package test.validation.NASA; public class Cell { public Object value; public boolean achieved; public Cell(){ value = null; achieved = false; } public Cell(Object value, boolean achieved){ this.value = value; this.achieved = achieved; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (achieved ? 1231 : 1237); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Cell other = (Cell) obj; if (achieved != other.achieved) return false; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; } }
873
19.809524
69
java
gluon
gluon-master/test/validation/NASA/Main.java
package test.validation.NASA; public class Main { public static void main(String[] args) { Cell[] table = new Cell[100]; Object[] system_state = new Object[100]; new Daemon(table, system_state).start(); new Task(table).start(); new Task(table).start(); new Task(table).start(); } }
300
17.8125
42
java
gluon
gluon-master/test/validation/NASA/Task.java
package test.validation.NASA; public class Task extends Thread { public TaskManager tm; public Task(Cell[] table) { super(); tm=new TaskManager(table); } public void run() { int N = 42; Object v = new Object(); tm.setValue(v,N); /* achieve property */ tm.setAchieved(v,N); } }
309
12.478261
34
java
gluon
gluon-master/test/validation/NASA/TaskManager.java
package test.validation.NASA; import test.common.Atomic; import test.common.Contract; @Contract(clauses = "setValue(_,X) setAchieved(_,X);") class TaskManager extends Thread { public Cell[] table; public TaskManager(Cell[] table) { super(); this.table = table; } @Atomic public void setValue(Object v,int N){ table[N].value = v; } @Atomic public void setAchieved(Object v, int N){ table[N].achieved = true; } }
434
15.730769
54
java
gluon
gluon-master/test/validation/NASA/Daemon.java
package test.validation.NASA; import test.common.Atomic; public class Daemon extends Thread { public Cell[] table; public Object[] system_state; public Daemon(Cell[] table, Object[] system_state) { super(); this.table = table; this.system_state = system_state; } public void run() { int N = 42; while (true) { tryIssueWarning(N); } } @Atomic private void tryIssueWarning(int N){ if (table[N].achieved && system_state[N] != table[N].value) issueWarning(); } private void issueWarning() { throw new RuntimeException("PANIC!!!"); } }
569
17.387097
61
java
gluon
gluon-master/test/validation/Store/Main.java
package test.validation.Store; public class Main { public static void main(String[] args) { ProductWorld.init(); Store.init(); Client c1 = new Client("Vasco", "Estrada bla bla bla", 23, 1, 200); Client c2 = new Client("Joao", "Rua bla bla bla", 22, 2, 400); Client c3 = new Client("Pedro", "Avenida bla bla bla", 41, 3, 450); Worker w1 = new Worker("worker1", "blabla1",19,1,1000,5); Worker w2 = new Worker("worker2", "blabla2",22,2,1500,7); Worker w3 = new Worker("worker3", "blabla3",31,3,1200,6); Supplier s1 = new Supplier("Supplier1"); Supplier s2 = new Supplier("Supplier2"); Supplier s3 = new Supplier("Supplier3"); //Start Clients c1.start(); c2.start(); c3.start(); //Start Workers w1.start(); w2.start(); w3.start(); //Start Supliers s1.start(); s2.start(); s3.start(); } }
840
21.72973
69
java
gluon
gluon-master/test/validation/Store/Pair.java
package test.validation.Store; public class Pair<T1, T2> { private T1 first; private T2 second; public Pair(T1 first, T2 second) { super(); this.first = first; this.second = second; } public Pair(Pair<T1, T2> p) { if(p != null){ this.first = p.first; this.second = p.second; } } public T1 getFirst() { return first; } public void setFirst(T1 first) { this.first = first; } public T2 getSecond() { return second; } public void setSecond(T2 second) { this.second = second; } public String toString(){ if(first == null || second == null) return ""; return "("+first.toString()+","+second.toString()+")"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((first == null) ? 0 : first.hashCode()); result = prime * result + ((second == null) ? 0 : second.hashCode()); return result; } @Override public boolean equals(Object obj) { if (!(obj instanceof Pair<?,?>)) return false; Pair<?, ?> other = (Pair<?,?>) obj; if (first == null) { if (other.first != null) return false; } else if (!first.equals(other.first)) return false; if (second == null) { if (other.second != null) return false; } else if (!second.equals(other.second)) return false; return true; } }
1,314
18.626866
71
java
gluon
gluon-master/test/validation/Store/ProductWorld.java
package test.validation.Store; import java.util.ArrayList; import java.util.List; import java.util.Random; public class ProductWorld { //fruit protected static Product apple; protected static Product banana; protected static Product strawberry; protected static Product pineapple; protected static Product fig; //pasta protected static Product spaguetti; protected static Product noodles; //cereals protected static Product chocapic; protected static Product chococrispies; protected static Product snacks; //candies protected static Product smarties; protected static Product kitkat; protected static Product mms; protected static Product snickers; //drinks protected static Product martini; protected static Product vodka; protected static Product cocacola; protected static Product icetea; public static void init() { apple = new Product("Apple", 30 , "23/01/2011", 1, 1 /*fruit*/); banana = new Product("banana", 25 , "25/01/2011", 3, 1 /*fruit*/); strawberry = new Product("StrawBerry", 21 , "13/01/2011", 1, 1 /*fruit*/); pineapple = new Product("Pineapple", 22 , "23/05/2011", 2, 1 /*fruit*/); fig = new Product("Fig", 15 , "3/02/2011", 3, 1 /*fruit*/); martini = new Product("martini", 30 , "23/01/2011", 1, 2 /*drinks*/); vodka = new Product("vodka", 30 , "23/01/2011", 1, 2 /*drinks*/); cocacola = new Product("cocacola", 30 , "23/01/2011", 1, 2 /*drinks*/); icetea = new Product("icetea", 30 , "23/01/2011", 1, 2 /*drinks*/); chocapic = new Product("chocapic", 30 , "23/01/2011", 1, 3 /*cereals*/); chococrispies = new Product("chococrispies", 30 , "23/01/2011", 1,3 /*cereals*/); snacks = new Product("snacks", 30 , "23/01/2011", 1, 3 /*cereals*/); smarties = new Product("smarties", 30 , "23/01/2011", 1, 4 /*candies*/); kitkat = new Product("kitkat", 30 , "23/01/2011", 1, 4 /*candies*/); mms = new Product("mms", 30 , "23/01/2011", 1, 4 /*candies*/); snickers = new Product("snickers", 30 , "23/01/2011", 1, 4 /*candies*/); spaguetti = new Product("Spaguetti", 30 , "23/01/2011", 1, 5 /*pasta*/); noodles = new Product("Noodles", 25 , "25/01/2011", 3, 5 /*pasta*/); } public static Product getRandomProduct(){ Random r = new Random(); int num = r.nextInt(17); switch(num){ case 0: return apple; case 1: return banana; case 2: return strawberry; case 3: return pineapple; case 4: return fig; case 5: return spaguetti; case 6: return noodles ; case 7: return chocapic; case 8: return chococrispies; case 9: return snacks; case 10: return smarties; case 11: return kitkat; case 12: return mms; case 13: return snickers; case 14: return martini; case 15: return vodka; case 16: return cocacola; default: return icetea; } } public static List<Product> getProducts() { List<Product> result = new ArrayList<Product>(); result.add(apple);result.add(banana); result.add(strawberry);result.add(pineapple); result.add(fig);result.add(spaguetti); result.add(noodles);result.add(chocapic); result.add(chococrispies);result.add(snacks); result.add(smarties);result.add(kitkat); result.add(mms);result.add(snickers); result.add(martini);result.add(vodka); result.add(cocacola);result.add(icetea); return result; } }
3,353
26.719008
83
java
gluon
gluon-master/test/validation/Store/Store.java
package test.validation.Store; import java.util.ArrayList; import java.util.List; import java.util.Random; import test.common.Atomic; public class Store { // init is done? protected static boolean inited = false; // All store's products protected static List<StoreProduct> products; // Log with all sells protected static String log; // List with all orders protected static List<Order> orders; public static void init(){ inited = true; products = new ArrayList<StoreProduct>(); orders = new ArrayList<Order>(); log = ""; Random r = new Random(); for(Product p : ProductWorld.getProducts()){ int quantity = r.nextInt(5); StoreProduct sp = new StoreProduct(p, r.nextInt(30)+5, quantity, quantity == 0); products.add(sp); } } public static void addLog(int num_employer, Client client, List<Pair<Product, Integer>> iterator, int total) { if(!inited){ return; } log += "Sell{"+num_employer+" Client = "+client+" | Products = "+iterator+"\n\n"; } public static void addLog(String string) { if(!inited){ return; } log += string; } // public static void checkInited(String where){ // if(!inited){ // System.err.println("STORE: ERROR - NOT INITED ("+where+")"); // } // } public static int getPrice(Product p) { if(!inited){ return -1; } StoreProduct sp = getStoreProduct(p); return sp.getPrice(); } private static StoreProduct getStoreProduct(Product p) { if(!inited){ return null; } for(StoreProduct sp : products){ if(p.equals(sp.getProduct())){ return sp; } } return null; } // public static boolean hasProduct(Product p, int n) { // checkInited("hasProduct"); // for(StoreProduct sp : products){ // if(sp.getProduct().equals(p)){ // return sp.canBeSeld(n); // } // } // return false; // } @Atomic public synchronized static boolean hasOrders() { if(!inited){ return false; } return orders.size()>0; } public synchronized static Order getOrder() { if(!inited){ return null; } if(orders.size() > 0){ // Sort "orders" so we can remove the oldest orders = sortOrders(); } // Return the oldest order return orders.size() == 0? null :orders.remove(0); } private static List<Order> sortOrders() { int size = orders.size(); List<Order> result = new ArrayList<Order>(); if(size == 0){ return result; } boolean[] visited = new boolean[size]; Order[] aOrders = toArray(); // We get always the oldest order and put it first for(int i = 0; i < size; i++){ Order newest = aOrders[0]; for(int j = 1; j < size ; j++){ if(!visited[j] && aOrders[j].getDate().compareTo(newest.getDate())<0){ newest = aOrders[j]; visited[j] = true; } } aOrders[i] = newest; } return result; } private static Order[] toArray() { Order[] result = new Order[orders.size()]; int count = 0; for(Order o : orders){ result[count] = o; count++; } return result; } public static void sell(Product p, int n) { if(!inited){ return; } StoreProduct sp = getStoreProduct(p); if(sp.isSoldOut() || sp.getNumberUnits() < n){ // System.err.println("ERROR: Store - This product is not for sale or has no enough units"); } sp.decProduct(n); } public static void buyProducts(Order order) { if(!inited){ return; } orders.add(order); } public static void supply(Product p, int aux) { if(!inited){ return; } StoreProduct sp = getStoreProduct(p); if(sp == null){ // System.err.println("Store : shouldn't happen (Product doesn't exist)"); } if(!sp.isConsistent()){ // System.err.println("Store : ERROR! Inconsistency between 'soldOut' and number"); } sp.incProduct(aux); } }
3,709
20.2
94
java
gluon
gluon-master/test/validation/Store/Client.java
package test.validation.Store; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; public class Client extends Thread implements Person { // Persons attributes protected String name; protected String address; protected int age; // Client attributes protected int num_client; protected int money; public Client(String name, String address, int age, int num_client,int money){ this.name = name; this.age = age; this.address = address; this.num_client = num_client; this.money = money; } public String toString(){ return "Client "+name+ ", "+age+"years old, from "+address+"(nº = "+num_client+")"; } public void run(){ int tres = 3; boolean b = tres == 3; while(b){ //while true // System.out.println("Client "+name+" lets buy?"); Random r = new Random(); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Order order = new Order(this, dateFormat.format(new Date()), 5); int num_products = r.nextInt(3)+1; for(int i = 0; i < num_products; i++){ boolean found = false; Product p = null; while(!found){ // get a random product p = ProductWorld.getRandomProduct(); int n = r.nextInt(5);//max 5 of each // if(Store.hasProduct(p,n) && !order.contains(p)){ order.add(p,n); found = true; // } } } // Buy product Store.buyProducts(order); waitAbit(); } } private void waitAbit() { try { Thread.sleep(7*(new Random().nextInt(10))); } catch (InterruptedException e) {} } @Override public int getAge() { return age; } @Override public String getAddress() { return address; } @Override public String getPersonName() { return name; } }
1,750
20.096386
85
java
gluon
gluon-master/test/validation/Store/Supplier.java
package test.validation.Store; import java.util.Random; public class Supplier extends Thread{ protected String name; public final Random r = new Random(); public Supplier(String name){ this.name = name; } public void run() { boolean b = 1.0 == 0.5 + 3/2-1.0; while(b){ //while true Product p = ProductWorld.getRandomProduct(); // System.out.println("Supplier "+name+" more product "+p); Store.supply(p, r.nextInt(4)+1); waitNextOpportunity(); } } private void waitNextOpportunity() { try { Thread.sleep(8*(new Random().nextInt(10))); } catch (InterruptedException e) {} } }
615
19.533333
61
java
gluon
gluon-master/test/validation/Store/Person.java
package test.validation.Store; /** * This interface represents an abstract person * @author Vasco Pessanha */ public interface Person { public String getPersonName(); public int getAge(); public String getAddress(); }
228
14.266667
47
java
gluon
gluon-master/test/validation/Store/Product.java
package test.validation.Store; /** * This class represents a given product (that can be selled by our store) * @author Vasco Pessanha * */ public class Product { protected String name; protected int weight; protected String date; protected int validity; //in months protected ProductType type; public Product(String name, int weight, String date, int validity, int type){ this.name = name; this.weight = weight; this.date = date; this.validity = validity; this.type = new ProductType(type); } public String toString(){ return "Product "+name+"("+type+"), "+weight+" kg, valid for "+validity+" months after "+date; } public boolean isFruit(){ return type.isFruit(); } public boolean isDrink(){ return type.isDrink(); } public boolean isCereal(){ return type.isCereal(); } public boolean isCandy(){ return type.isCandy(); } public boolean isPasta(){ return type.isPasta(); } public String getName(){ return name; } }
967
20.511111
96
java
gluon
gluon-master/test/validation/Store/Order.java
package test.validation.Store; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Order { // Client who ordered protected Client client; // Date of the order protected String date; // Maximum number of products protected int max_number; // Products protected List<Product> products; // Number of products of each type protected List<Integer> quantities; public Order(Client c, String d,int max){ this(c,d,max,new ArrayList<Product>(),new ArrayList<Integer>()); } public Order(Client c, String d, int max, List<Product> products, List<Integer> numbers){ if(products.size() != numbers.size()){ System.err.println("ERROR! Order has to have the same products/quantities"); System.exit(-1); } this.client = c; this.date = d; this.max_number = max; this.products = products; this.quantities = numbers; } public void add(Product p, int n) { if(!products.contains(p)){ products.add(p); quantities.add(n); } } public List<Pair<Product, Integer>> getList(){ List<Pair<Product,Integer>> result = new ArrayList<Pair<Product,Integer>>(); Iterator<Integer> i = quantities.iterator(); for(Product p : products){ result.add(new Pair<Product,Integer>(p, i.next())); } return result; } public String getDate(){ return date; } public int size(){ return products.size(); } public Client getClient() { return client; } public boolean contains(Product p) { return products.contains(p); } @Override public Order clone(){ return new Order(client, date, max_number, products, quantities); } }
1,600
22.202899
90
java
gluon
gluon-master/test/validation/Store/WorkerAux.java
package test.validation.Store; import java.util.List; import test.common.Atomic; import test.common.Contract; @Contract(clauses = "hasOrders treatOrder;") class WorkerAux { public static boolean hasOrders() { return Store.hasOrders(); } @Atomic public static String treatOrder() { Order order = Store.getOrder(); int total = 0; List<Pair<Product,Integer>> list = order.getList(); while(list.size() > 0){ Pair<Product, Integer> pair = list.remove(0); Product p = pair.getFirst(); int n = pair.getSecond(); total += Store.getPrice(p); Store.sell(p,n); } return "Sell{"+42+" Client = "+order.getClient()+" | Nº prod = "+order.size()+"\n\n"; } }
706
21.09375
87
java
gluon
gluon-master/test/validation/Store/ProductType.java
package test.validation.Store; /** * This Class represents the possible types of products * * @author Vasco Pessanha * */ public class ProductType { public static final int fruitType = 1; public static final int drinksType = 2; public static final int cerealsType = 3; public static final int candyType = 4; public static final int pastaType = 5; private final String fruitString = "Fruits"; private final String drinksString = "Drinks"; private final String cerealsString = "Cereals"; private final String candyString = "Candies"; private final String pastaString = "Pastas"; public static final ProductType fruits = new ProductType(fruitType); public static final ProductType drinks = new ProductType(drinksType); public static final ProductType cereals = new ProductType(cerealsType); public static final ProductType candies = new ProductType(candyType); public static final ProductType pastas = new ProductType(pastaType); protected int type; public ProductType(int type){ isValid(type); this.type = type; } private void isValid(int inType) { if(inType != fruitType && inType != drinksType && inType != cerealsType && inType != candyType && inType != pastaType){ System.err.println("ERROR (ProductType) - tried to introduced an invalid type ("+inType+")"); System.exit(-1); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + type; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ProductType other = (ProductType) obj; if (type != other.type) return false; return true; } public String toString(){ if(this.equals(fruits)) return fruitString; else if(this.equals(drinks)) return drinksString; else if(this.equals(cereals)) return cerealsString; else if(this.equals(candies)) return candyString; else if(this.equals(pastas)) return pastaString; else return "WRONG TYPE"; } public boolean isFruit(){ return type == fruitType; } public boolean isDrink(){ return type == drinksType; } public boolean isCereal(){ return type == cerealsType; } public boolean isCandy(){ return type == candyType; } public boolean isPasta(){ return type == pastaType; } }
2,365
24.170213
96
java
gluon
gluon-master/test/validation/Store/Worker.java
package test.validation.Store; import java.util.Random; public class Worker extends Thread implements Person{ //Person attributes protected String name; protected String address; protected int age; //Worker attributes protected int num_employer; protected int salary; protected int yearsOfWork; public Worker(String name, String address, int age, int num_employer, int salary, int yearsOfWork){ this.name = name; this.address = address; this.age = age; this.num_employer = num_employer; this.salary = salary; this.yearsOfWork = yearsOfWork; } public void run() { int tres = 3; boolean b = tres == 3; while(b){ //while true // System.out.println("Worker "+name+" has orders?"); if(WorkerAux.hasOrders()){ String log = WorkerAux.treatOrder(); Store.addLog(log); } waitClients(); } } /** * Wait for the entrance of more clients.. */ private void waitClients() { try { Thread.sleep((new Random()).nextInt(10)*5); } catch (InterruptedException e) { // Wake up... more clients? } } public String getPersonName() { return name; } @Override public int getAge() { return age; } @Override public String getAddress() { return address; } }
1,224
17.560606
100
java
gluon
gluon-master/test/validation/Store/StoreProduct.java
package test.validation.Store; import test.common.Atomic; /** * This class represents a Store's product. * * @author Vasco Pessanha */ public class StoreProduct { // store's product represented by this class protected Product product; // number of units of that product protected int n; // (is this product for sale?) protected boolean soldOut; // Product's price protected int price; public StoreProduct(Product p, int price){ this(p,price,1,true); } public StoreProduct(Product p, int price, int numberUnits, boolean soldOut){ this.product = p; this.n = numberUnits; this.soldOut = soldOut; this.price = price; } public int hashCodeIgnoreCase() { final int prime = 31; int result = 1; result = prime * result + ((product == null) ? 0 : product.hashCode()); return result; } public boolean equalsIgnoreCase(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; StoreProduct other = (StoreProduct) obj; if (product == null) { if (other.product != null) return false; } else if (!product.equals(other.product)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (soldOut ? 1231 : 1237); result = prime * result + n; result = prime * result + ((product == null) ? 0 : product.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; StoreProduct other = (StoreProduct) obj; if (soldOut != other.soldOut) return false; if (n != other.n) return false; if (product == null) { if (other.product != null) return false; } else if (!product.equals(other.product)) return false; return true; } @Atomic public synchronized boolean isConsistent(){ return (soldOut && n == 0) || (n > 0 && !soldOut); } public void incProduct(int aux){ incNumber(aux); // Someone can read this inconsistent state // ( We have product but it is sold out) setSoldOutA(false); } public void decProduct(int aux){ decNumber(aux); // Someone can read this inconsistent state // ( We have product but it is sold out) setSoldOut(n == 0); } @Atomic public synchronized void incNumber(int aux) { n += aux; } public synchronized void decNumber(int n2) { n = n > n2? n - n2 : 0; } private synchronized void setSoldOut(boolean soldOut) { this.soldOut = soldOut; } @Atomic private synchronized void setSoldOutA(boolean soldOut) { this.soldOut = soldOut; } @Override public String toString(){ String result = "StoreProduct "+product.getName()+" - " + n; if(soldOut) return result + "(Sold out)"; return result; } public int getPrice(){ return price; } public Product getProduct() { return product; } public boolean isSoldOut(){ return soldOut; } public int getNumberUnits(){ return n; } }
3,039
19.821918
77
java
null
wildfly-main/ee-security/src/test/java/org/wildfly/extension/eesecurity/EESecuritySubsystemTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.eesecurity; import java.io.IOException; import java.util.EnumSet; import java.util.Locale; import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** * @author <a href="kabir.khan@jboss.com">Kabir Khan</a> */ @RunWith(Parameterized.class) public class EESecuritySubsystemTestCase extends AbstractSubsystemBaseTest { @Parameters public static Iterable<EESecuritySubsystemSchema> parameters() { return EnumSet.allOf(EESecuritySubsystemSchema.class); } private final EESecuritySubsystemSchema schema; public EESecuritySubsystemTestCase(EESecuritySubsystemSchema schema) { super(EESecurityExtension.SUBSYSTEM_NAME, new EESecurityExtension()); this.schema = schema; } @Override protected String getSubsystemXml() throws IOException { return String.format(Locale.ROOT, "<subsystem xmlns=\"%s\"/>", this.schema.getNamespace()); } @Override protected String getSubsystemXsdPath() throws Exception { return String.format(Locale.ROOT, "schema/wildfly-ee-security_%d_%d.xsd", this.schema.getVersion().major(), this.schema.getVersion().minor()); } //no point in testing 1.0.0 (current) --> 1.0.0 (all previous) for transformers }
2,393
37.612903
150
java
null
wildfly-main/ee-security/src/main/java/org/wildfly/extension/eesecurity/EESecuritySubsystemAdd.java
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.eesecurity; import org.jboss.as.controller.AbstractBoottimeAddStepHandler; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.registry.Resource; import org.jboss.as.server.AbstractDeploymentChainStep; import org.jboss.as.server.DeploymentProcessorTarget; import org.jboss.as.server.deployment.Phase; import org.jboss.dmr.ModelNode; import org.jboss.msc.service.ServiceTarget; /** * The EE subsystem add update handler. * * @author Stuart Douglas */ class EESecuritySubsystemAdd extends AbstractBoottimeAddStepHandler { static final EESecuritySubsystemAdd INSTANCE = new EESecuritySubsystemAdd(); protected void populateModel(ModelNode operation, ModelNode model) { model.setEmptyObject(); } protected void performBoottime(final OperationContext context, ModelNode operation, Resource resource) { final ServiceTarget serviceTarget = context.getServiceTarget(); context.addStep(new AbstractDeploymentChainStep() { public void execute(DeploymentProcessorTarget processorTarget) { processorTarget.addDeploymentProcessor(EESecurityExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_EE_SECURITY_ANNOTATIONS, new EESecurityAnnotationProcessor()); processorTarget.addDeploymentProcessor(EESecurityExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_EE_SECURITY, new EESecurityDependencyProcessor()); } }, OperationContext.Stage.RUNTIME); } }
2,549
42.220339
180
java
null
wildfly-main/ee-security/src/main/java/org/wildfly/extension/eesecurity/EESecurityDependencyProcessor.java
/* * Copyright (C) 2018 Red Hat, inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ package org.wildfly.extension.eesecurity; import static org.wildfly.extension.eesecurity.EESecuritySubsystemDefinition.ELYTRON_JAKARTA_SECURITY; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.module.ModuleDependency; import org.jboss.as.server.deployment.module.ModuleSpecification; import org.jboss.modules.Module; import org.jboss.modules.ModuleLoader; class EESecurityDependencyProcessor implements DeploymentUnitProcessor { @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit unit = phaseContext.getDeploymentUnit(); final DeploymentUnit top = unit.getParent() == null ? unit : unit.getParent(); final ModuleLoader moduleLoader = Module.getBootModuleLoader(); final ModuleSpecification moduleSpec = unit.getAttachment(Attachments.MODULE_SPECIFICATION); moduleSpec.addSystemDependency(new ModuleDependency(moduleLoader, "jakarta.security.enterprise.api", false, false, true, false)); Boolean securityPresent = top.getAttachment(EESecurityAnnotationProcessor.SECURITY_PRESENT); if(securityPresent != null && securityPresent) { moduleSpec.addSystemDependency(new ModuleDependency(moduleLoader, ELYTRON_JAKARTA_SECURITY, false, false, true, false)); } } }
2,575
47.603774
137
java
null
wildfly-main/ee-security/src/main/java/org/wildfly/extension/eesecurity/EESecurityAnnotationProcessor.java
/* * Copyright (C) 2018 Red Hat, inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ package org.wildfly.extension.eesecurity; import java.util.List; import org.jboss.as.server.deployment.AttachmentKey; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.annotation.CompositeIndex; import org.jboss.jandex.AnnotationInstance; import org.jboss.jandex.AnnotationTarget; import org.jboss.jandex.DotName; import org.jboss.jandex.FieldInfo; class EESecurityAnnotationProcessor implements DeploymentUnitProcessor { static final AttachmentKey<Boolean> SECURITY_PRESENT = AttachmentKey.create(Boolean.class); static final DotName[] ANNOTATIONS = { DotName.createSimple("jakarta.security.enterprise.authentication.mechanism.http.BasicAuthenticationMechanismDefinition"), DotName.createSimple("jakarta.security.enterprise.authentication.mechanism.http.CustomFormAuthenticationMechanismDefinition"), DotName.createSimple("jakarta.security.enterprise.authentication.mechanism.http.FormAuthenticationMechanismDefinition"), DotName.createSimple("jakarta.security.enterprise.authentication.mechanism.http.OpenIdAuthenticationMechanismDefinition"), DotName.createSimple("jakarta.security.enterprise.authentication.mechanism.http.LoginToContinue"), DotName.createSimple("jakarta.security.enterprise.authentication.mechanism.http.RememberMe"), DotName.createSimple("jakarta.security.enterprise.authentication.mechanism.http.AutoApplySession"), DotName.createSimple("jakarta.security.enterprise.authentication.mechanism.http.openid.ClaimsDefinition"), DotName.createSimple("jakarta.security.enterprise.authentication.mechanism.http.openid.LogoutDefinition"), DotName.createSimple("jakarta.security.enterprise.authentication.mechanism.http.openid.OpenIdProviderMetadata"), DotName.createSimple("jakarta.security.enterprise.identitystore.DatabaseIdentityStoreDefinition"), DotName.createSimple("jakarta.security.enterprise.identitystore.LdapIdentityStoreDefinition") }; static final DotName[] INTERFACES = { DotName.createSimple("jakarta.security.enterprise.authentication.mechanism.http.HttpAuthenticationMechanism"), DotName.createSimple("jakarta.security.enterprise.identitystore.IdentityStoreHandler"), DotName.createSimple("jakarta.security.enterprise.identitystore.IdentityStore"), DotName.createSimple("jakarta.security.enterprise.identitystore.RememberMeIdentityStore") }; static final DotName INJECTION_TYPE = DotName.createSimple("jakarta.inject.Inject"); static final DotName SECURITY_CONTEXT = DotName.createSimple("jakarta.security.enterprise.SecurityContext"); @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); CompositeIndex index = deploymentUnit.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX); for (DotName annotation : ANNOTATIONS) { if (!index.getAnnotations(annotation).isEmpty()) { markAsEESecurity(deploymentUnit); return; } } for (DotName annotation : INTERFACES) { if (!index.getAllKnownImplementors(annotation).isEmpty()) { markAsEESecurity(deploymentUnit); return; } } // Get list of injected objects List<AnnotationInstance> injectionAnnotations = index.getAnnotations(INJECTION_TYPE); for (AnnotationInstance annotation : injectionAnnotations) { final AnnotationTarget annotationTarget = annotation.target(); if (annotationTarget instanceof FieldInfo) { // Enable if injected object is a SecurityContext field, WFLY-17541 final FieldInfo fieldInfo = (FieldInfo) annotationTarget; DotName injectedFieldName = fieldInfo.type().name(); if (injectedFieldName.equals(SECURITY_CONTEXT)) { markAsEESecurity(deploymentUnit); return; } } } } private void markAsEESecurity(DeploymentUnit deploymentUnit) { DeploymentUnit top = deploymentUnit.getParent() == null ? deploymentUnit : deploymentUnit.getParent(); top.putAttachment(SECURITY_PRESENT, true); } }
5,656
52.87619
138
java
null
wildfly-main/ee-security/src/main/java/org/wildfly/extension/eesecurity/EESecuritySubsystemSchema.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.eesecurity; import static org.jboss.as.controller.PersistentResourceXMLDescription.builder; import org.jboss.as.controller.PersistentResourceXMLDescription; import org.jboss.as.controller.PersistentSubsystemSchema; import org.jboss.as.controller.SubsystemSchema; import org.jboss.as.controller.xml.VersionedNamespace; import org.jboss.staxmapper.IntVersion; /** * Enumerates the supported subsystem schema namespaces of the EE security subsystem. * @author Paul Ferraro */ public enum EESecuritySubsystemSchema implements PersistentSubsystemSchema<EESecuritySubsystemSchema> { VERSION_1_0(1), ; static final EESecuritySubsystemSchema CURRENT = VERSION_1_0; private final VersionedNamespace<IntVersion, EESecuritySubsystemSchema> namespace; EESecuritySubsystemSchema(int major) { this.namespace = SubsystemSchema.createLegacySubsystemURN(EESecurityExtension.SUBSYSTEM_NAME, new IntVersion(major)); } @Override public VersionedNamespace<IntVersion, EESecuritySubsystemSchema> getNamespace() { return this.namespace; } @Override public PersistentResourceXMLDescription getXMLDescription() { return builder(EESecurityExtension.SUBSYSTEM_PATH, this.namespace).build(); } }
2,305
38.084746
125
java
null
wildfly-main/ee-security/src/main/java/org/wildfly/extension/eesecurity/EESecuritySubsystemDefinition.java
/* * Copyright (C) 2014 Red Hat, inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ package org.wildfly.extension.eesecurity; import java.util.Collection; import java.util.Collections; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.PersistentResourceDefinition; import org.jboss.as.controller.ReloadRequiredRemoveStepHandler; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.capability.RuntimeCapability; import org.jboss.as.controller.registry.RuntimePackageDependency; /** * @author Stuart Douglas */ public class EESecuritySubsystemDefinition extends PersistentResourceDefinition { static final String EE_SECURITY_CAPABILITY_NAME = "org.wildfly.ee.security"; static final String WELD_CAPABILITY_NAME = "org.wildfly.weld"; static final String ELYTRON_JAKARTA_SECURITY = "org.wildfly.security.jakarta.security"; static final RuntimeCapability<Void> EE_SECURITY_CAPABILITY = RuntimeCapability.Builder.of(EE_SECURITY_CAPABILITY_NAME) .setServiceType(Void.class) .addRequirements(WELD_CAPABILITY_NAME) .build(); EESecuritySubsystemDefinition() { super(new SimpleResourceDefinition.Parameters(EESecurityExtension.SUBSYSTEM_PATH, EESecurityExtension.SUBSYSTEM_RESOLVER) .setAddHandler(EESecuritySubsystemAdd.INSTANCE) .addCapabilities(EE_SECURITY_CAPABILITY) .setRemoveHandler(ReloadRequiredRemoveStepHandler.INSTANCE) .setAdditionalPackages(RuntimePackageDependency.required(ELYTRON_JAKARTA_SECURITY)) ); } @Override public Collection<AttributeDefinition> getAttributes() { return Collections.emptyList(); } }
2,655
41.83871
129
java
null
wildfly-main/ee-security/src/main/java/org/wildfly/extension/eesecurity/EESecurityExtension.java
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.eesecurity; import java.util.EnumSet; import java.util.List; import org.jboss.as.controller.Extension; import org.jboss.as.controller.ExtensionContext; import org.jboss.as.controller.ModelVersion; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.PersistentResourceXMLDescription; import org.jboss.as.controller.PersistentResourceXMLDescriptionReader; import org.jboss.as.controller.PersistentResourceXMLDescriptionWriter; import org.jboss.as.controller.SubsystemRegistration; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.controller.descriptions.ParentResourceDescriptionResolver; import org.jboss.as.controller.descriptions.SubsystemResourceDescriptionResolver; import org.jboss.as.controller.operations.common.GenericSubsystemDescribeHandler; import org.jboss.as.controller.parsing.ExtensionParsingContext; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.dmr.ModelNode; import org.jboss.staxmapper.XMLElementReader; /** * Domain extension used to initialize the EE Security subsystem. * * @author Stuart Douglas */ public class EESecurityExtension implements Extension { public static final String SUBSYSTEM_NAME = "ee-security"; public static final ModelVersion MODEL_VERSION_1_0_0 = ModelVersion.create(1, 0, 0); private static final ModelVersion CURRENT_MODEL_VERSION = MODEL_VERSION_1_0_0; static final PathElement SUBSYSTEM_PATH = PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, SUBSYSTEM_NAME); static final ParentResourceDescriptionResolver SUBSYSTEM_RESOLVER = new SubsystemResourceDescriptionResolver(SUBSYSTEM_NAME, EESecurityExtension.class); private final PersistentResourceXMLDescription currentDescription = EESecuritySubsystemSchema.CURRENT.getXMLDescription(); @Override public void initialize(final ExtensionContext context) { final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION); final ManagementResourceRegistration registration = subsystem.registerSubsystemModel(new EESecuritySubsystemDefinition()); registration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE); subsystem.registerXMLElementWriter(new PersistentResourceXMLDescriptionWriter(this.currentDescription)); } @Override public void initializeParsers(final ExtensionParsingContext context) { for (EESecuritySubsystemSchema schema : EnumSet.allOf(EESecuritySubsystemSchema.class)) { XMLElementReader<List<ModelNode>> reader = (schema == EESecuritySubsystemSchema.CURRENT) ? new PersistentResourceXMLDescriptionReader(this.currentDescription) : schema; context.setSubsystemXmlMapping(SUBSYSTEM_NAME, schema.getNamespace().getUri(), reader); } } }
3,955
48.45
180
java
null
wildfly-main/observability/micrometer-api/src/main/java/org/wildfly/extension/micrometer/api/MicrometerCdiExtension.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2021 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.micrometer.api; import io.micrometer.core.instrument.MeterRegistry; import jakarta.enterprise.event.Observes; import jakarta.enterprise.inject.spi.AfterBeanDiscovery; import jakarta.enterprise.inject.spi.Extension; import jakarta.inject.Singleton; public class MicrometerCdiExtension implements Extension { private final MeterRegistry registry; public MicrometerCdiExtension(MeterRegistry registry) { this.registry = registry; } public void registerMicrometerBeans(@Observes AfterBeanDiscovery abd) { abd.addBean() .scope(Singleton.class) .addTransitiveTypeClosure(MeterRegistry.class) .produceWith(i -> registry); } }
1,449
32.72093
75
java
null
wildfly-main/observability/opentelemetry-api/src/main/java/org/wildfly/extension/opentelemetry/api/WildFlyOpenTelemetryConfig.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.opentelemetry.api; import java.util.Collections; import java.util.HashMap; import java.util.Map; import io.smallrye.opentelemetry.api.OpenTelemetryConfig; public final class WildFlyOpenTelemetryConfig implements OpenTelemetryConfig { public static final String OTEL_BSP_MAX_EXPORT_BATCH_SIZE = "otel.bsp.max.export.batch.size"; public static final String OTEL_BSP_MAX_QUEUE_SIZE = "otel.bsp.max.queue.size"; public static final String OTEL_BSP_SCHEDULE_DELAY = "otel.bsp.schedule.delay"; public static final String OTEL_EXPERIMENTAL_SDK_ENABLED = "otel.experimental.sdk.enabled"; public static final String OTEL_EXPORTER_JAEGER_ENDPOINT = "otel.exporter.jaeger.endpoint"; public static final String OTEL_EXPORTER_JAEGER_TIMEOUT = "otel.exporter.jaeger.timeout"; public static final String OTEL_EXPORTER_OTLP_ENDPOINT = "otel.exporter.otlp.endpoint"; public static final String OTEL_EXPORTER_OTLP_TIMEOUT = "otel.exporter.otlp.timeout"; public static final String OTEL_METRICS_EXPORTER = "otel.metrics.exporter"; public static final String OTEL_SDK_DISABLED = "otel.sdk.disabled"; public static final String OTEL_SERVICE_NAME = "otel.service.name"; public static final String OTEL_TRACES_EXPORTER = "otel.traces.exporter"; public static final String OTEL_TRACES_SAMPLER = "otel.traces.sampler"; public static final String OTEL_TRACES_SAMPLER_ARG = "otel.traces.sampler.arg"; private final Map<String, String> properties; public WildFlyOpenTelemetryConfig(String serviceName, String exporter, String endpoint, Long batchDelay, Long maxQueueSize, Long maxExportBatchSize, Long exportTimeout, String sampler, Double ratio) { Map<String, String> config = new HashMap<>(); // Default to on addValue(config, OTEL_SDK_DISABLED, "false"); addValue(config, OTEL_EXPERIMENTAL_SDK_ENABLED, "true"); addValue(config, OTEL_SERVICE_NAME, serviceName); addValue(config, OTEL_METRICS_EXPORTER, "none"); addValue(config, OTEL_TRACES_EXPORTER, exporter); switch (exporter) { case "jaeger": addValue(config, OTEL_EXPORTER_JAEGER_ENDPOINT, endpoint); addValue(config, OTEL_EXPORTER_JAEGER_TIMEOUT, exportTimeout); break; case "otlp": addValue(config, OTEL_EXPORTER_OTLP_ENDPOINT, endpoint); addValue(config, OTEL_EXPORTER_OTLP_TIMEOUT, exportTimeout); break; } addValue(config, OTEL_BSP_SCHEDULE_DELAY, batchDelay); addValue(config, OTEL_BSP_MAX_QUEUE_SIZE, maxQueueSize); addValue(config, OTEL_BSP_MAX_EXPORT_BATCH_SIZE, maxExportBatchSize); if (sampler != null) { switch (sampler) { case "on": addValue(config, OTEL_TRACES_SAMPLER, "always_on"); break; case "off": addValue(config, OTEL_TRACES_SAMPLER, "always_off"); break; case "ratio": addValue(config, OTEL_TRACES_SAMPLER, "traceidratio"); break; } } addValue(config, OTEL_TRACES_SAMPLER_ARG, ratio); properties = Collections.unmodifiableMap(config); } @Override public Map<String, String> properties() { return properties; } /* Only add the value to the config if it is non-null, and convert the type to String to satisfy library requirements. */ private void addValue(Map<String, String> config, String key, Object value) { if (value != null) { config.put(key, value.toString()); } } }
4,537
44.38
98
java
null
wildfly-main/observability/opentelemetry-api/src/main/java/org/wildfly/extension/opentelemetry/api/OpenTelemetryCdiExtension.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.opentelemetry.api; import java.util.Map; import io.smallrye.opentelemetry.api.OpenTelemetryConfig; import io.smallrye.opentelemetry.implementation.rest.OpenTelemetryClientFilter; import io.smallrye.opentelemetry.implementation.rest.OpenTelemetryServerFilter; import jakarta.enterprise.event.Observes; import jakarta.enterprise.inject.Default; import jakarta.enterprise.inject.spi.AfterBeanDiscovery; import jakarta.enterprise.inject.spi.BeanManager; import jakarta.enterprise.inject.spi.BeforeBeanDiscovery; import jakarta.enterprise.inject.spi.Extension; import jakarta.inject.Singleton; public final class OpenTelemetryCdiExtension implements Extension { private final boolean useServerConfig; private final Map<String, String> config; public OpenTelemetryCdiExtension(boolean useServerConfig, Map<String, String> config) { this.useServerConfig = useServerConfig; this.config = config; } public void beforeBeanDiscovery(@Observes BeforeBeanDiscovery beforeBeanDiscovery, final BeanManager beanManager) { beforeBeanDiscovery.addAnnotatedType(beanManager.createAnnotatedType(OpenTelemetryServerFilter.class), OpenTelemetryServerFilter.class.getName()); beforeBeanDiscovery.addAnnotatedType(beanManager.createAnnotatedType(OpenTelemetryClientFilter.class), OpenTelemetryClientFilter.class.getName()); } public void registerOpenTelemetryConfigBean(@Observes AfterBeanDiscovery abd) { if (useServerConfig) { abd.addBean() .scope(Singleton.class) .addQualifier(Default.Literal.INSTANCE) .types(OpenTelemetryConfig.class) .createWith(e -> (OpenTelemetryConfig) () -> config); } } }
2,528
40.459016
119
java
null
wildfly-main/observability/micrometer/src/test/java/org/wildfly/extension/micrometer/SubsystemParsingTestCase.java
package org.wildfly.extension.micrometer; import java.util.EnumSet; import org.jboss.as.subsystem.test.AbstractSubsystemSchemaTest; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** * @author <a href="jasondlee@redhat.com">Jason Lee</a> */ @RunWith(Parameterized.class) public class SubsystemParsingTestCase extends AbstractSubsystemSchemaTest<MicrometerSubsystemSchema> { @Parameters public static Iterable<MicrometerSubsystemSchema> parameters() { return EnumSet.allOf(MicrometerSubsystemSchema.class); } public SubsystemParsingTestCase(MicrometerSubsystemSchema schema) { super(MicrometerExtension.SUBSYSTEM_NAME, new MicrometerExtension(), schema, MicrometerSubsystemSchema.CURRENT); } @Override protected String getSubsystemXmlPathPattern() { return "%s_%d_%d.xml"; } }
917
29.6
120
java
null
wildfly-main/observability/micrometer/src/main/java/org/wildfly/extension/micrometer/MicrometerDeploymentProcessor.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022-2023 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.micrometer; import static org.wildfly.extension.micrometer.MicrometerExtension.WELD_CAPABILITY_NAME; import static org.wildfly.extension.micrometer.MicrometerExtensionLogger.MICROMETER_LOGGER; import java.util.List; import java.util.function.Supplier; import org.jboss.as.controller.capability.CapabilityServiceSupport; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentModelUtils; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.weld.WeldCapability; import org.wildfly.extension.micrometer.api.MicrometerCdiExtension; import org.wildfly.extension.micrometer.registry.WildFlyRegistry; import io.micrometer.core.instrument.MeterRegistry; class MicrometerDeploymentProcessor implements DeploymentUnitProcessor { private final boolean exposeAnySubsystem; private final List<String> exposedSubsystems; private final Supplier<WildFlyRegistry> registrySupplier; MicrometerDeploymentProcessor(boolean exposeAnySubsystem, List<String> exposedSubsystems, Supplier<WildFlyRegistry> registrySupplier) { this.exposeAnySubsystem = exposeAnySubsystem; this.exposedSubsystems = exposedSubsystems; this.registrySupplier = registrySupplier; } @Override public void deploy(DeploymentPhaseContext deploymentPhaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = deploymentPhaseContext.getDeploymentUnit(); MicrometerDeploymentService.install(deploymentPhaseContext.getServiceTarget(), deploymentPhaseContext, deploymentUnit.getAttachment(DeploymentModelUtils.DEPLOYMENT_RESOURCE), deploymentUnit.getAttachment(DeploymentModelUtils.MUTABLE_REGISTRATION_ATTACHMENT), registrySupplier, exposeAnySubsystem, exposedSubsystems); registerCdiExtension(deploymentPhaseContext); } @Override public void undeploy(DeploymentUnit context) { } private void registerCdiExtension(DeploymentPhaseContext deploymentPhaseContext) throws DeploymentUnitProcessingException { DeploymentUnit deploymentUnit = deploymentPhaseContext.getDeploymentUnit(); try { CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT); final WeldCapability weldCapability = support.getCapabilityRuntimeAPI(WELD_CAPABILITY_NAME, WeldCapability.class); if (!weldCapability.isPartOfWeldDeployment(deploymentUnit)) { MICROMETER_LOGGER.noCdiDeployment(); } else { WildFlyRegistry registry = registrySupplier.get(); if (registry == null) { throw new DeploymentUnitProcessingException(new IllegalStateException()); } weldCapability.registerExtensionInstance(new MicrometerCdiExtension((MeterRegistry) registry), deploymentUnit); } } catch (CapabilityServiceSupport.NoSuchCapabilityException e) { //We should not be here since the subsystem depends on weld capability. Just in case ... MICROMETER_LOGGER.deploymentRequiresCapability(deploymentUnit.getName(), WELD_CAPABILITY_NAME); } } }
4,318
44.463158
127
java
null
wildfly-main/observability/micrometer/src/main/java/org/wildfly/extension/micrometer/MicrometerRegistryService.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.micrometer; import static org.wildfly.extension.micrometer.MicrometerExtensionLogger.MICROMETER_LOGGER; import static org.wildfly.extension.micrometer.MicrometerSubsystemDefinition.MICROMETER_REGISTRY_RUNTIME_CAPABILITY; import java.io.IOException; import java.util.function.Consumer; import java.util.function.Supplier; import org.jboss.as.controller.CapabilityServiceBuilder; import org.jboss.as.controller.OperationContext; import org.jboss.msc.Service; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StopContext; import org.wildfly.extension.micrometer.jmx.JmxMicrometerCollector; import org.wildfly.extension.micrometer.registry.NoOpRegistry; import org.wildfly.extension.micrometer.registry.WildFlyOtlpRegistry; import org.wildfly.extension.micrometer.registry.WildFlyRegistry; class MicrometerRegistryService implements Service { private final Consumer<WildFlyRegistry> registriesConsumer; private final WildFlyMicrometerConfig config; private WildFlyRegistry registry; /** * Installs a service that provides {@link WildFlyRegistry}, and provides a {@link Supplier} the * subsystem can use to obtain that registry. * * @param context the management operation context to use to install the service. Cannot be {@code null} * @param config the configuration object for the registry * @return the {@link Supplier}. Will not return {@code null}. */ static Supplier<WildFlyRegistry> install(OperationContext context, WildFlyMicrometerConfig config) { CapabilityServiceBuilder<?> serviceBuilder = context.getCapabilityServiceTarget() .addCapability(MICROMETER_REGISTRY_RUNTIME_CAPABILITY); RegistrySupplier registrySupplier = new RegistrySupplier(serviceBuilder.provides(MICROMETER_REGISTRY_RUNTIME_CAPABILITY.getCapabilityServiceName())); serviceBuilder.setInstance(new MicrometerRegistryService(registrySupplier, config)) .install(); return registrySupplier; } private MicrometerRegistryService(Consumer<WildFlyRegistry> registriesConsumer, WildFlyMicrometerConfig config) { this.registriesConsumer = registriesConsumer; this.config = config; } @Override public void start(StartContext context) { if (config.url() != null) { registry = new WildFlyOtlpRegistry(config); } else { MICROMETER_LOGGER.noOpRegistryChosen(); registry = new NoOpRegistry(); } try { // register metrics from JMX MBeans for base metrics new JmxMicrometerCollector(registry).init(); } catch (IOException e) { throw MICROMETER_LOGGER.failedInitializeJMXRegistrar(e); } registriesConsumer.accept(registry); } @Override public void stop(StopContext context) { if (registry != null) { registry.close(); registry = null; } registriesConsumer.accept(null); } /* Caches the WildFlyRegistry created in Service.start for use by the subsystem. */ private static final class RegistrySupplier implements Consumer<WildFlyRegistry>, Supplier<WildFlyRegistry> { private final Consumer<WildFlyRegistry> wrapped; private volatile WildFlyRegistry registry; private RegistrySupplier(Consumer<WildFlyRegistry> wrapped) { this.wrapped = wrapped; } @Override public void accept(WildFlyRegistry registry) { this.registry = registry; // Pass the registry on to MSC's consumer wrapped.accept(registry); } @Override public WildFlyRegistry get() { return registry; } } }
4,516
36.957983
129
java
null
wildfly-main/observability/micrometer/src/main/java/org/wildfly/extension/micrometer/WildFlyMicrometerConfig.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2023 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.micrometer; import java.time.Duration; import java.util.Map; import io.micrometer.registry.otlp.OtlpConfig; public final class WildFlyMicrometerConfig implements OtlpConfig { /** * The OTLP endpoint to which to push metrics */ private final String endpoint; /** * How frequently, in seconds, to push metrics */ private final Long step; public WildFlyMicrometerConfig(String endpoint, Long step) { this.endpoint = endpoint; this.step = step; } @Override public String get(String key) { return null; // Accept defaults not explicitly overridden below } @Override public Map<String, String> resourceAttributes() { Map<String, String> attributes = OtlpConfig.super.resourceAttributes(); if (!attributes.containsKey("service.name")) { attributes.put("service.name", "wildfly"); } return attributes; } @Override public String url() { return endpoint; } @Override public Duration step() { Duration duration = Duration.ofSeconds(step); return duration; } }
1,881
27.515152
79
java
null
wildfly-main/observability/micrometer/src/main/java/org/wildfly/extension/micrometer/MicrometerDeploymentService.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.micrometer; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DEPLOYMENT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBDEPLOYMENT; import static org.wildfly.extension.micrometer.MicrometerExtensionLogger.MICROMETER_LOGGER; import static org.wildfly.extension.micrometer.MicrometerSubsystemDefinition.MICROMETER_COLLECTOR; import java.util.List; import java.util.function.Supplier; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.controller.registry.Resource; import org.jboss.as.ee.structure.DeploymentType; import org.jboss.as.ee.structure.DeploymentTypeMarker; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentCompleteServiceProcessor; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceTarget; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StopContext; import org.wildfly.extension.micrometer.metrics.MetricRegistration; import org.wildfly.extension.micrometer.metrics.MicrometerCollector; import org.wildfly.extension.micrometer.registry.WildFlyRegistry; class MicrometerDeploymentService implements Service { private final Resource rootResource; private final ManagementResourceRegistration managementResourceRegistration; private final PathAddress deploymentAddress; private final Supplier<MicrometerCollector> metricCollector; private final Supplier<WildFlyRegistry> registrySupplier; private final boolean exposeAnySubsystem; private final List<String> exposedSubsystems; private volatile MetricRegistration registration; static void install(ServiceTarget serviceTarget, DeploymentPhaseContext deploymentPhaseContext, Resource rootResource, ManagementResourceRegistration managementResourceRegistration, Supplier<WildFlyRegistry> registrySupplier, boolean exposeAnySubsystem, List<String> exposedSubsystems) { MICROMETER_LOGGER.processingDeployment(); final DeploymentUnit deploymentUnit = deploymentPhaseContext.getDeploymentUnit(); if (!DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) { return; } PathAddress deploymentAddress = createDeploymentAddressPrefix(deploymentUnit); ServiceBuilder<?> sb = serviceTarget.addService(deploymentUnit.getServiceName().append(".micrometer-metrics")); Supplier<MicrometerCollector> metricCollectorSupplier = sb.requires(MICROMETER_COLLECTOR); /* * The deployment metric service depends on the deployment complete service name to ensure that the metrics from * the deployment are collected and registered once the deployment services have all be properly installed. */ sb.requires(DeploymentCompleteServiceProcessor.serviceName(deploymentUnit.getServiceName())); sb.setInstance(new MicrometerDeploymentService(rootResource, managementResourceRegistration, deploymentAddress, metricCollectorSupplier, registrySupplier, exposeAnySubsystem, exposedSubsystems)) .install(); } private MicrometerDeploymentService(Resource rootResource, ManagementResourceRegistration managementResourceRegistration, PathAddress deploymentAddress, Supplier<MicrometerCollector> metricCollectorSupplier, Supplier<WildFlyRegistry> registrySupplier, boolean exposeAnySubsystem, List<String> exposedSubsystems) { this.rootResource = rootResource; this.managementResourceRegistration = managementResourceRegistration; this.deploymentAddress = deploymentAddress; this.metricCollector = metricCollectorSupplier; this.registrySupplier = registrySupplier; this.exposeAnySubsystem = exposeAnySubsystem; this.exposedSubsystems = exposedSubsystems; } private static PathAddress createDeploymentAddressPrefix(DeploymentUnit deploymentUnit) { if (deploymentUnit.getParent() == null) { return PathAddress.pathAddress(DEPLOYMENT, deploymentUnit.getAttachment(Attachments.MANAGEMENT_NAME)); } else { return createDeploymentAddressPrefix(deploymentUnit.getParent()).append(SUBDEPLOYMENT, deploymentUnit.getName()); } } @Override public void start(StartContext context) { registration = metricCollector.get() .collectResourceMetrics(rootResource, managementResourceRegistration, // prepend the deployment address to the subsystem resource address deploymentAddress::append, exposeAnySubsystem, exposedSubsystems); } @Override public void stop(StopContext context) { registration.unregister(); } }
6,153
47.078125
125
java
null
wildfly-main/observability/micrometer/src/main/java/org/wildfly/extension/micrometer/MicrometerConfigurationConstants.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.micrometer; public final class MicrometerConfigurationConstants { private MicrometerConfigurationConstants() { } static final String OTLP_REGISTRY = "otlp-registry"; public static final String ENDPOINT = "endpoint"; public static final String STEP = "step"; }
1,022
34.275862
75
java
null
wildfly-main/observability/micrometer/src/main/java/org/wildfly/extension/micrometer/MicrometerSubsystemDefinition.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022-2023 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.micrometer; import java.util.Arrays; import java.util.Collection; import java.util.concurrent.TimeUnit; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.PersistentResourceDefinition; import org.jboss.as.controller.ReloadRequiredRemoveStepHandler; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.StringListAttributeDefinition; import org.jboss.as.controller.capability.RuntimeCapability; import org.jboss.as.controller.client.helpers.MeasurementUnit; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.controller.registry.RuntimePackageDependency; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.msc.service.ServiceName; import org.wildfly.extension.micrometer.metrics.MicrometerCollector; import org.wildfly.extension.micrometer.registry.WildFlyRegistry; class MicrometerSubsystemDefinition extends PersistentResourceDefinition { private static final String MICROMETER_MODULE = "org.wildfly.extension.micrometer"; private static final String MICROMETER_API_MODULE = "org.wildfly.micrometer.deployment"; static final String CLIENT_FACTORY_CAPABILITY = "org.wildfly.management.model-controller-client-factory"; static final String MANAGEMENT_EXECUTOR = "org.wildfly.management.executor"; static final String PROCESS_STATE_NOTIFIER = "org.wildfly.management.process-state-notifier"; static final RuntimeCapability<Void> MICROMETER_COLLECTOR_RUNTIME_CAPABILITY = RuntimeCapability.Builder.of(MICROMETER_MODULE + ".wildfly-collector", MicrometerCollector.class) .addRequirements(CLIENT_FACTORY_CAPABILITY, MANAGEMENT_EXECUTOR, PROCESS_STATE_NOTIFIER) .build(); static final RuntimeCapability<Void> MICROMETER_REGISTRY_RUNTIME_CAPABILITY = RuntimeCapability.Builder.of(MICROMETER_MODULE + ".registry", WildFlyRegistry.class) .build(); static final ServiceName MICROMETER_COLLECTOR = MICROMETER_COLLECTOR_RUNTIME_CAPABILITY.getCapabilityServiceName(); static final String[] MODULES = { }; static final String[] EXPORTED_MODULES = { MICROMETER_API_MODULE, "io.opentelemetry.otlp", "io.micrometer" }; public static final SimpleAttributeDefinition ENDPOINT = SimpleAttributeDefinitionBuilder .create(MicrometerConfigurationConstants.ENDPOINT, ModelType.STRING) .setAttributeGroup(MicrometerConfigurationConstants.OTLP_REGISTRY) .setRequired(false) .setAllowExpression(true) .setRestartAllServices() .build(); public static final SimpleAttributeDefinition STEP = SimpleAttributeDefinitionBuilder .create(MicrometerConfigurationConstants.STEP, ModelType.LONG, true) .setAttributeGroup(MicrometerConfigurationConstants.OTLP_REGISTRY) .setDefaultValue(new ModelNode(TimeUnit.MINUTES.toSeconds(1))) .setMeasurementUnit(MeasurementUnit.SECONDS) .setAllowExpression(true) .setRestartAllServices() .build(); static final StringListAttributeDefinition EXPOSED_SUBSYSTEMS = new StringListAttributeDefinition.Builder("exposed-subsystems" ) .setDefaultValue(ModelNode.fromJSONString("[\"*\"]")) .setRequired(false) .setRestartAllServices() .build(); static final AttributeDefinition[] ATTRIBUTES = { EXPOSED_SUBSYSTEMS, ENDPOINT, STEP }; protected MicrometerSubsystemDefinition() { super(new SimpleResourceDefinition.Parameters(MicrometerExtension.SUBSYSTEM_PATH, MicrometerExtension.SUBSYSTEM_RESOLVER) .setAddHandler(MicrometerSubsystemAdd.INSTANCE) .setRemoveHandler(ReloadRequiredRemoveStepHandler.INSTANCE)); } @Override public Collection<AttributeDefinition> getAttributes() { return Arrays.asList(ATTRIBUTES); } @Override public void registerAdditionalRuntimePackages(ManagementResourceRegistration resourceRegistration) { resourceRegistration.registerAdditionalRuntimePackages( RuntimePackageDependency.required("io.micrometer" ) ); } }
5,253
43.905983
119
java
null
wildfly-main/observability/micrometer/src/main/java/org/wildfly/extension/micrometer/MicrometerExtensionLogger.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.micrometer; import static org.jboss.logging.Logger.Level.DEBUG; import static org.jboss.logging.Logger.Level.ERROR; import static org.jboss.logging.Logger.Level.INFO; import static org.jboss.logging.Logger.Level.WARN; import java.io.IOException; import org.jboss.as.controller.PathAddress; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; @MessageLogger(projectCode = "WFLYMMTREXT", length = 4) public interface MicrometerExtensionLogger extends BasicLogger { MicrometerExtensionLogger MICROMETER_LOGGER = Logger.getMessageLogger(MicrometerExtensionLogger.class, MicrometerExtensionLogger.class.getPackage().getName()); @LogMessage(level = INFO) @Message(id = 1, value = "Activating Micrometer Subsystem") void activatingSubsystem(); @LogMessage(level = INFO) // DEBUG @Message(id = 2, value = "Micrometer Subsystem is processing deployment") void processingDeployment(); @LogMessage(level = DEBUG) @Message(id = 3, value = "The deployment does not have Jakarta Contexts and Dependency Injection enabled. Skipping Micrometer integration.") void noCdiDeployment(); @LogMessage(level = DEBUG) @Message(id = 4, value = "Deployment %s requires use of the '%s' capability but it is not currently registered") void deploymentRequiresCapability(String deploymentName, String capabilityName); @LogMessage(level = WARN) @Message(id = 5, value = "Unable to read attribute %s on %s: %s.") void unableToReadAttribute(String attributeName, PathAddress address, String error); @LogMessage(level = WARN) @Message(id = 6, value = "Unable to convert attribute %s on %s to Double value.") void unableToConvertAttribute(String attributeName, PathAddress address, @Cause Exception exception); @LogMessage(level = ERROR) @Message(id = 7, value = "Malformed name.") void malformedName(@Cause Exception exception); @Message(id = 8, value = "Failed to initialize metrics from JMX MBeans") IllegalArgumentException failedInitializeJMXRegistrar(@Cause IOException e); @Message(id = 9, value = "An unsupported metric type was found: %s") IllegalArgumentException unsupportedMetricType(String type); @LogMessage(level = INFO) @Message(id = 10, value = "Not activating Micrometer Subsystem") void notActivatingSubsystem(); @LogMessage(level = WARN) @Message(id = 11, value = "Micrometer has been enabled, but no endpoint has been configured. A No-op metrics registry has been configured.") void noOpRegistryChosen(); }
3,498
41.156627
144
java
null
wildfly-main/observability/micrometer/src/main/java/org/wildfly/extension/micrometer/MicrometerExtension.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.micrometer; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import java.util.EnumSet; import java.util.List; import org.jboss.as.controller.Extension; import org.jboss.as.controller.ExtensionContext; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.PersistentResourceXMLDescription; import org.jboss.as.controller.PersistentResourceXMLDescriptionReader; import org.jboss.as.controller.PersistentResourceXMLDescriptionWriter; import org.jboss.as.controller.SubsystemRegistration; import org.jboss.as.controller.descriptions.ParentResourceDescriptionResolver; import org.jboss.as.controller.descriptions.SubsystemResourceDescriptionResolver; import org.jboss.as.controller.operations.common.GenericSubsystemDescribeHandler; import org.jboss.as.controller.parsing.ExtensionParsingContext; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.dmr.ModelNode; import org.jboss.staxmapper.XMLElementReader; public class MicrometerExtension implements Extension { public static final String WELD_CAPABILITY_NAME = "org.wildfly.weld"; public static final String SUBSYSTEM_NAME = "micrometer"; public static final PathElement SUBSYSTEM_PATH = PathElement.pathElement(SUBSYSTEM, SUBSYSTEM_NAME); static final ParentResourceDescriptionResolver SUBSYSTEM_RESOLVER = new SubsystemResourceDescriptionResolver(SUBSYSTEM_NAME, MicrometerExtension.class); private final PersistentResourceXMLDescription currentDescription = MicrometerSubsystemSchema.CURRENT.getXMLDescription(); @Override public void initialize(ExtensionContext context) { final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, MicrometerSubsystemModel.CURRENT.getVersion()); subsystem.registerXMLElementWriter(new PersistentResourceXMLDescriptionWriter(this.currentDescription)); final ManagementResourceRegistration registration = subsystem.registerSubsystemModel(new MicrometerSubsystemDefinition()); registration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE); } @Override public void initializeParsers(ExtensionParsingContext context) { for (MicrometerSubsystemSchema schema : EnumSet.allOf(MicrometerSubsystemSchema.class)) { XMLElementReader<List<ModelNode>> reader = (schema == MicrometerSubsystemSchema.CURRENT) ? new PersistentResourceXMLDescriptionReader(this.currentDescription) : schema; context.setSubsystemXmlMapping(SUBSYSTEM_NAME, schema.getNamespace().getUri(), reader); } } }
3,434
48.782609
137
java
null
wildfly-main/observability/micrometer/src/main/java/org/wildfly/extension/micrometer/MicrometerSubsystemAdd.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022-2023 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.micrometer; import static org.jboss.as.controller.OperationContext.Stage.RUNTIME; import static org.jboss.as.controller.OperationContext.Stage.VERIFY; import static org.jboss.as.controller.PathAddress.EMPTY_ADDRESS; import static org.jboss.as.server.deployment.Phase.DEPENDENCIES; import static org.jboss.as.server.deployment.Phase.DEPENDENCIES_MICROMETER; import static org.jboss.as.server.deployment.Phase.POST_MODULE; import static org.jboss.as.server.deployment.Phase.POST_MODULE_MICROMETER; import static org.wildfly.extension.micrometer.MicrometerExtension.SUBSYSTEM_NAME; import java.util.List; import java.util.function.Function; import java.util.function.Supplier; import org.jboss.as.controller.AbstractBoottimeAddStepHandler; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.registry.ImmutableManagementResourceRegistration; import org.jboss.as.controller.registry.Resource; import org.jboss.as.server.AbstractDeploymentChainStep; import org.jboss.as.server.DeploymentProcessorTarget; import org.jboss.dmr.ModelNode; import org.wildfly.extension.micrometer.metrics.MicrometerCollector; import org.wildfly.extension.micrometer.registry.WildFlyRegistry; class MicrometerSubsystemAdd extends AbstractBoottimeAddStepHandler { MicrometerSubsystemAdd() { super(MicrometerSubsystemDefinition.ATTRIBUTES); } public static final MicrometerSubsystemAdd INSTANCE = new MicrometerSubsystemAdd(); /** * {@inheritDoc} */ @Override protected void performBoottime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { List<String> exposedSubsystems = MicrometerSubsystemDefinition.EXPOSED_SUBSYSTEMS.unwrap(context, model); boolean exposeAnySubsystem = exposedSubsystems.remove("*"); String endpoint = MicrometerSubsystemDefinition.ENDPOINT.resolveModelAttribute(context, model) .asStringOrNull(); Long step = MicrometerSubsystemDefinition.STEP.resolveModelAttribute(context, model) .asLong(); WildFlyMicrometerConfig config = new WildFlyMicrometerConfig(endpoint, step); Supplier<WildFlyRegistry> registrySupplier = MicrometerRegistryService.install(context, config); Supplier<MicrometerCollector> collectorSupplier = MicrometerCollectorService.install(context); context.addStep(new AbstractDeploymentChainStep() { @Override public void execute(DeploymentProcessorTarget processorTarget) { processorTarget.addDeploymentProcessor(SUBSYSTEM_NAME, DEPENDENCIES, DEPENDENCIES_MICROMETER, new MicrometerDependencyProcessor()); processorTarget.addDeploymentProcessor(SUBSYSTEM_NAME, POST_MODULE, POST_MODULE_MICROMETER, new MicrometerDeploymentProcessor(exposeAnySubsystem, exposedSubsystems, registrySupplier)); } }, RUNTIME); context.addStep((operationContext, modelNode) -> { MicrometerCollector micrometerCollector = collectorSupplier.get(); if (micrometerCollector == null) { throw new IllegalStateException(); } ImmutableManagementResourceRegistration rootResourceRegistration = context.getRootResourceRegistration(); Resource rootResource = context.readResourceFromRoot(EMPTY_ADDRESS); micrometerCollector.collectResourceMetrics(rootResource, rootResourceRegistration, Function.identity(), exposeAnySubsystem, exposedSubsystems); }, VERIFY); MicrometerExtensionLogger.MICROMETER_LOGGER.activatingSubsystem(); } }
4,513
44.59596
117
java
null
wildfly-main/observability/micrometer/src/main/java/org/wildfly/extension/micrometer/MicrometerSubsystemSchema.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.micrometer; import static org.jboss.as.controller.PersistentResourceXMLDescription.builder; import org.jboss.as.controller.PersistentResourceXMLDescription; import org.jboss.as.controller.PersistentSubsystemSchema; import org.jboss.as.controller.SubsystemSchema; import org.jboss.as.controller.xml.VersionedNamespace; import org.jboss.staxmapper.IntVersion; public enum MicrometerSubsystemSchema implements PersistentSubsystemSchema<MicrometerSubsystemSchema> { VERSION_1_0(1, 0), // WildFly 28 VERSION_1_1(1, 1), // WildFly 29.0.0.Alpha1 ; public static final MicrometerSubsystemSchema CURRENT = VERSION_1_1; private final VersionedNamespace<IntVersion, MicrometerSubsystemSchema> namespace; MicrometerSubsystemSchema(int major, int minor) { this.namespace = SubsystemSchema.createSubsystemURN(MicrometerExtension.SUBSYSTEM_NAME, new IntVersion(major, minor)); } @Override public VersionedNamespace<IntVersion, MicrometerSubsystemSchema> getNamespace() { return this.namespace; } @Override public PersistentResourceXMLDescription getXMLDescription() { return builder(org.wildfly.extension.micrometer.MicrometerExtension.SUBSYSTEM_PATH, this.namespace) .addAttributes(MicrometerSubsystemDefinition.ATTRIBUTES) .build(); } }
2,080
37.537037
126
java
null
wildfly-main/observability/micrometer/src/main/java/org/wildfly/extension/micrometer/MicrometerCollectorService.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.micrometer; import static org.wildfly.extension.micrometer.MicrometerSubsystemDefinition.CLIENT_FACTORY_CAPABILITY; import static org.wildfly.extension.micrometer.MicrometerSubsystemDefinition.MANAGEMENT_EXECUTOR; import static org.wildfly.extension.micrometer.MicrometerSubsystemDefinition.MICROMETER_COLLECTOR; import static org.wildfly.extension.micrometer.MicrometerSubsystemDefinition.MICROMETER_COLLECTOR_RUNTIME_CAPABILITY; import static org.wildfly.extension.micrometer.MicrometerSubsystemDefinition.MICROMETER_REGISTRY_RUNTIME_CAPABILITY; import static org.wildfly.extension.micrometer.MicrometerSubsystemDefinition.PROCESS_STATE_NOTIFIER; import java.util.concurrent.Executor; import java.util.function.Consumer; import java.util.function.Supplier; import org.jboss.as.controller.CapabilityServiceBuilder; import org.jboss.as.controller.LocalModelControllerClient; import org.jboss.as.controller.ModelControllerClientFactory; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.ProcessStateNotifier; import org.jboss.msc.Service; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StopContext; import org.wildfly.extension.micrometer.metrics.MicrometerCollector; import org.wildfly.extension.micrometer.registry.WildFlyRegistry; /** * Service to create a metric collector */ class MicrometerCollectorService implements Service { private final Supplier<ModelControllerClientFactory> modelControllerClientFactory; private final Supplier<Executor> managementExecutor; private final Supplier<ProcessStateNotifier> processStateNotifier; private final Supplier<WildFlyRegistry> registrySupplier; private final Consumer<MicrometerCollector> metricCollectorConsumer; private LocalModelControllerClient modelControllerClient; /** * Installs a service that provides {@link MicrometerCollector}, and provides a {@link Supplier} the * subsystem can use to obtain that collector. * @param context the management operation context to use to install the service. Cannot be {@code null} * @return the {@link Supplier}. Will not return {@code null}. */ static Supplier<MicrometerCollector> install(OperationContext context) { CapabilityServiceBuilder<?> serviceBuilder = context.getCapabilityServiceTarget().addCapability(MICROMETER_COLLECTOR_RUNTIME_CAPABILITY); Supplier<ModelControllerClientFactory> modelControllerClientFactory = serviceBuilder.requiresCapability(CLIENT_FACTORY_CAPABILITY, ModelControllerClientFactory.class); Supplier<Executor> managementExecutor = serviceBuilder.requiresCapability(MANAGEMENT_EXECUTOR, Executor.class); Supplier<ProcessStateNotifier> processStateNotifier = serviceBuilder.requiresCapability(PROCESS_STATE_NOTIFIER, ProcessStateNotifier.class); Supplier<WildFlyRegistry> registrySupplier = serviceBuilder.requiresCapability(MICROMETER_REGISTRY_RUNTIME_CAPABILITY.getName(), WildFlyRegistry.class); MicrometerCollectorSupplier collectorSupplier = new MicrometerCollectorSupplier(serviceBuilder.provides(MICROMETER_COLLECTOR)); MicrometerCollectorService service = new MicrometerCollectorService(modelControllerClientFactory, managementExecutor, processStateNotifier, registrySupplier, collectorSupplier); serviceBuilder.setInstance(service) .install(); return collectorSupplier; } MicrometerCollectorService(Supplier<ModelControllerClientFactory> modelControllerClientFactory, Supplier<Executor> managementExecutor, Supplier<ProcessStateNotifier> processStateNotifier, Supplier<WildFlyRegistry> registrySupplier, Consumer<MicrometerCollector> metricCollectorConsumer) { this.modelControllerClientFactory = modelControllerClientFactory; this.managementExecutor = managementExecutor; this.processStateNotifier = processStateNotifier; this.registrySupplier = registrySupplier; this.metricCollectorConsumer = metricCollectorConsumer; } @Override public void start(StartContext context) { // [WFLY-11933] if RBAC is enabled, the local client does not have enough privileges to read metrics modelControllerClient = modelControllerClientFactory.get().createClient(managementExecutor.get()); MicrometerCollector micrometerCollector = new MicrometerCollector(modelControllerClient, processStateNotifier.get(), registrySupplier.get()); metricCollectorConsumer.accept(micrometerCollector); } @Override public void stop(StopContext context) { metricCollectorConsumer.accept(null); modelControllerClient.close(); } /* Caches the MicrometerCollector created in Service.start for use by the subsystem. */ private static final class MicrometerCollectorSupplier implements Consumer<MicrometerCollector>, Supplier<MicrometerCollector> { private final Consumer<MicrometerCollector> wrapped; private volatile MicrometerCollector collector; private MicrometerCollectorSupplier(Consumer<MicrometerCollector> wrapped) { this.wrapped = wrapped; } @Override public void accept(MicrometerCollector micrometerCollector) { this.collector = micrometerCollector; // Pass the collector on to MSC's consumer wrapped.accept(micrometerCollector); } @Override public MicrometerCollector get() { return collector; } } }
6,449
48.236641
145
java
null
wildfly-main/observability/micrometer/src/main/java/org/wildfly/extension/micrometer/MicrometerSubsystemModel.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.micrometer; import org.jboss.as.controller.ModelVersion; import org.jboss.as.controller.SubsystemModel; public enum MicrometerSubsystemModel implements SubsystemModel { VERSION_1_0_0(1, 0, 0), VERSION_1_1_0(1, 1, 0); public static final MicrometerSubsystemModel CURRENT = VERSION_1_1_0; private final ModelVersion version; MicrometerSubsystemModel(int major, int minor, int micro) { this.version = ModelVersion.create(major, minor, micro); } @Override public ModelVersion getVersion() { return version; } }
1,305
30.853659
75
java
null
wildfly-main/observability/micrometer/src/main/java/org/wildfly/extension/micrometer/MicrometerDependencyProcessor.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.micrometer; import static org.wildfly.extension.micrometer.MicrometerSubsystemDefinition.EXPORTED_MODULES; import static org.wildfly.extension.micrometer.MicrometerSubsystemDefinition.MODULES; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.module.ModuleDependency; import org.jboss.as.server.deployment.module.ModuleSpecification; import org.jboss.modules.Module; import org.jboss.modules.ModuleLoader; class MicrometerDependencyProcessor implements DeploymentUnitProcessor { @Override public void deploy(DeploymentPhaseContext phaseContext) { addDependencies(phaseContext.getDeploymentUnit()); } @Override public void undeploy(DeploymentUnit deploymentUnit) { } private void addDependencies(DeploymentUnit deploymentUnit) { ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION); ModuleLoader moduleLoader = Module.getBootModuleLoader(); for (String module : MODULES) { moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, module, false, false, true, false)); } for (String module : EXPORTED_MODULES) { moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, module, false, true, true, false)); } } }
2,272
40.327273
123
java
null
wildfly-main/observability/micrometer/src/main/java/org/wildfly/extension/micrometer/jmx/JmxMicrometerCollector.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.micrometer.jmx; import static org.jboss.as.controller.client.helpers.MeasurementUnit.NONE; import static org.wildfly.common.Assert.checkNotNullParam; import java.io.IOException; import java.io.InputStream; import java.lang.management.ManagementFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.OptionalDouble; import java.util.Properties; import java.util.Set; import java.util.stream.Collectors; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import javax.management.openmbean.CompositeData; import org.jboss.as.controller.client.helpers.MeasurementUnit; import org.wildfly.extension.micrometer.MicrometerExtensionLogger; import org.wildfly.extension.micrometer.metrics.MetricMetadata; import org.wildfly.extension.micrometer.metrics.WildFlyMetric; import org.wildfly.extension.micrometer.registry.WildFlyRegistry; public class JmxMicrometerCollector { public static final String JMX_METRICS_PROPERTIES = "jmx-metrics.properties"; private final MBeanServer mbs; private final WildFlyRegistry registry; public JmxMicrometerCollector(WildFlyRegistry registry) { this.registry = registry; this.mbs = ManagementFactory.getPlatformMBeanServer(); } public void init() throws IOException { List<JmxMetricMetadata> configs = findMetadata(); // expand multi mbeans List<JmxMetricMetadata> expandedConfigs = new ArrayList<>(); Iterator<JmxMetricMetadata> iterator = configs.iterator(); while (iterator.hasNext()) { JmxMetricMetadata metadata = iterator.next(); try { String[] split = metadata.getMBean().split("/"); String query = split[0]; String attribute = split[1]; Set<ObjectName> objectNames = mbs.queryNames(ObjectName.getInstance(query), null); for (ObjectName objectName : objectNames) { // fill the tags from the object names fields List<MetricMetadata.MetricTag> tags = new ArrayList<>(metadata.getTagsToFill().size()); for (String key : metadata.getTagsToFill()) { String value = objectName.getKeyProperty(key); tags.add(new MetricMetadata.MetricTag(key, value)); } expandedConfigs.add(new JmxMetricMetadata(metadata.getMetricName(), metadata.getDescription(), metadata.getMeasurementUnit(), metadata.getType(), objectName.getCanonicalName() + "/" + attribute, Collections.emptyList(), tags)); } // now, it has been expanded, remove the "multi" mbean iterator.remove(); } catch (MalformedObjectNameException e) { MicrometerExtensionLogger.MICROMETER_LOGGER.malformedName(e); } } configs.addAll(expandedConfigs); for (JmxMetricMetadata config : configs) { register(config); } } void register(JmxMetricMetadata metadata) { WildFlyMetric metric = new WildFlyMetric() { @Override public OptionalDouble getValue() { try { return getValueFromMBean(mbs, metadata.getMBean()); } catch (Exception e) { return OptionalDouble.empty(); } } }; registry.addMeter(metric, metadata); } private List<JmxMetricMetadata> findMetadata() throws IOException { try ( InputStream propertiesResource = getResource()) { if (propertiesResource == null) { return Collections.emptyList(); } return loadMetadataFromProperties(propertiesResource); } } List<JmxMetricMetadata> loadMetadataFromProperties(InputStream propertiesResource) throws IOException { Properties props = new Properties(); props.load(propertiesResource); Map<String, List<MetricProperty>> parsedMetrics = props.entrySet() .stream() .map(MetricProperty::new) .collect(Collectors.groupingBy(MetricProperty::getMetricName)); return parsedMetrics.entrySet() .stream() .map(this::metadataOf) .sorted(Comparator.comparing(JmxMetricMetadata::getMetricName)) .collect(Collectors.toList()); } private InputStream getResource() { InputStream is = getClass().getResourceAsStream(JMX_METRICS_PROPERTIES); if (is == null) { is = Thread.currentThread().getContextClassLoader().getResourceAsStream(JMX_METRICS_PROPERTIES); } return is; } private JmxMetricMetadata metadataOf(Map.Entry<String, List<MetricProperty>> metadataEntry) { String name = metadataEntry.getKey(); Map<String, String> entryProperties = new HashMap<>(); metadataEntry.getValue() .forEach( prop -> entryProperties.put(prop.propertyKey, prop.propertyValue)); List<String> tagsToFill = new ArrayList<>(); if (entryProperties.containsKey("tagsToFill")) { tagsToFill = Arrays.asList(entryProperties.get("tagsToFill").split(",")); } final MeasurementUnit unit = (entryProperties.get("unit") == null) ? NONE : MeasurementUnit.valueOf(entryProperties.get("unit").toUpperCase()); return new JmxMetricMetadata(name, entryProperties.get("description"), unit, MetricMetadata.Type.valueOf(entryProperties.get("type").toUpperCase()), entryProperties.get("mbean"), tagsToFill, Collections.emptyList()); } private static class MetricProperty { MetricProperty(Map.Entry<Object, Object> keyValue) { String key = (String) keyValue.getKey(); int propertyIdEnd = key.lastIndexOf('.'); metricName = key.substring(0, propertyIdEnd); propertyKey = key.substring(propertyIdEnd + 1); propertyValue = (String) keyValue.getValue(); } String metricName; String propertyKey; String propertyValue; String getMetricName() { return metricName; } } private static OptionalDouble getValueFromMBean(MBeanServer mbs, String mbeanExpression) { checkNotNullParam("mbs", mbs); checkNotNullParam("mbeanExpression", mbeanExpression); if (!mbeanExpression.contains("/")) { throw new IllegalArgumentException(mbeanExpression); } int slashIndex = mbeanExpression.indexOf('/'); String mbean = mbeanExpression.substring(0, slashIndex); String attName = mbeanExpression.substring(slashIndex + 1); String subItem = null; if (attName.contains("#")) { int hashIndex = attName.indexOf('#'); subItem = attName.substring(hashIndex + 1); attName = attName.substring(0, hashIndex); } try { ObjectName objectName = new ObjectName(mbean); Object attribute = mbs.getAttribute(objectName, attName); if (attribute instanceof Number) { Number num = (Number) attribute; return OptionalDouble.of(num.doubleValue()); } else if (attribute instanceof CompositeData) { CompositeData compositeData = (CompositeData) attribute; Number num = (Number) compositeData.get(subItem); return OptionalDouble.of(num.doubleValue()); } else { return OptionalDouble.empty(); } } catch (Exception e) { throw new RuntimeException(e); } } }
8,972
38.355263
151
java
null
wildfly-main/observability/micrometer/src/main/java/org/wildfly/extension/micrometer/jmx/JmxMetricMetadata.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.micrometer.jmx; import java.util.List; import org.jboss.as.controller.client.helpers.MeasurementUnit; import org.wildfly.extension.micrometer.metrics.MetricID; import org.wildfly.extension.micrometer.metrics.MetricMetadata; class JmxMetricMetadata implements MetricMetadata { private final String name; private final String description; private final MeasurementUnit unit; private final Type type; private final String mbean; private final MetricID metricID; private final List<String> tagsToFill; private final List<MetricTag> tags; JmxMetricMetadata(String name, String description, MeasurementUnit unit, Type type, String mbean, List<String> tagsToFill, List<MetricTag> tags) { this.name = name; this.description = description; this.unit = unit; this.type = type; this.mbean = mbean; this.tagsToFill = tagsToFill; this.tags = tags; this.metricID = new MetricID(name, tags.toArray(new MetricTag[0])); } String getMBean() { return mbean; } List<String> getTagsToFill() { return tagsToFill; } @Override public MetricID getMetricID() { return metricID; } @Override public String getMetricName() { return name; } @Override public MetricTag[] getTags() { return tags.toArray(new MetricTag[0]); } @Override public String getDescription() { return description; } @Override public Type getType() { return type; } @Override public MeasurementUnit getMeasurementUnit() { return unit; } }
2,389
26.471264
150
java
null
wildfly-main/observability/micrometer/src/main/java/org/wildfly/extension/micrometer/metrics/MetricID.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.micrometer.metrics; import java.util.Iterator; import java.util.Map; import java.util.Objects; import java.util.TreeMap; public class MetricID implements Comparable<MetricID> { private final String metricName; // keep a map of tags to ensure that the identity of the metrics does not differ if the // tags are not in the same order in the array private final Map<String, String> tags = new TreeMap<>(); public MetricID(String metricName, WildFlyMetricMetadata.MetricTag[] tags) { this.metricName = metricName; for (WildFlyMetricMetadata.MetricTag tag : tags) { this.tags.put(tag.getKey(), tag.getValue()); } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MetricID metricID = (MetricID) o; return metricName.equals(metricID.metricName) && tags.equals(metricID.tags); } @Override public int hashCode() { return Objects.hash(metricName, tags); } @Override public int compareTo(MetricID other) { int compareVal = this.metricName.compareTo(other.metricName); if (compareVal == 0) { compareVal = this.tags.size() - other.tags.size(); if (compareVal == 0) { Iterator<Map.Entry<String, String>> thisIterator = tags.entrySet().iterator(); Iterator<Map.Entry<String, String>> otherIterator = other.tags.entrySet().iterator(); while (thisIterator.hasNext() && otherIterator.hasNext()) { Map.Entry<String, String> thisEntry = thisIterator.next(); Map.Entry<String, String> otherEntry = otherIterator.next(); compareVal = thisEntry.getKey().compareTo(otherEntry.getKey()); if (compareVal != 0) { return compareVal; } else { compareVal = thisEntry.getValue().compareTo(otherEntry.getValue()); if (compareVal != 0) { return compareVal; } } } } } return compareVal; } }
3,063
35.47619
101
java
null
wildfly-main/observability/micrometer/src/main/java/org/wildfly/extension/micrometer/metrics/MetricRegistration.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.micrometer.metrics; import java.util.ArrayList; import java.util.List; import org.wildfly.extension.micrometer.registry.WildFlyRegistry; import io.micrometer.core.instrument.Meter; public class MetricRegistration { private final List<Runnable> registrationTasks = new ArrayList<>(); private final List<Meter.Id> unregistrationTasks = new ArrayList<>(); private final WildFlyRegistry registry; public MetricRegistration(WildFlyRegistry registry) { this.registry = registry; } public void register() { // synchronized to avoid registering same thing twice. Shouldn't really be possible; just being cautious synchronized (registry) { registrationTasks.forEach(Runnable::run); registrationTasks.clear(); } } public void unregister() { synchronized (registry) { unregistrationTasks.forEach(registry::remove); unregistrationTasks.clear(); } } public void registerMetric(WildFlyMetric metric, WildFlyMetricMetadata metadata) { unregistrationTasks.add(registry.addMeter(metric, metadata)); } public synchronized void addRegistrationTask(Runnable task) { registrationTasks.add(task); } }
1,993
31.688525
112
java
null
wildfly-main/observability/micrometer/src/main/java/org/wildfly/extension/micrometer/metrics/MetricMetadata.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.micrometer.metrics; import org.jboss.as.controller.client.helpers.MeasurementUnit; public interface MetricMetadata { String getMetricName(); MetricTag[] getTags(); String getDescription(); MeasurementUnit getMeasurementUnit(); Type getType(); MetricID getMetricID(); default String getBaseMetricUnit() { return baseMetricUnit(getMeasurementUnit()); } static String baseMetricUnit(MeasurementUnit unit) { if (unit == null) { return "none"; } switch (unit.getBaseUnits()) { case PERCENTAGE: return "percent"; case BYTES: case KILOBYTES: case MEGABYTES: case GIGABYTES: case TERABYTES: case PETABYTES: return "bytes"; case BITS: case KILOBITS: case MEGABITS: case GIGABITS: case TERABITS: case PETABITS: return "bits"; case EPOCH_MILLISECONDS: case EPOCH_SECONDS: case NANOSECONDS: case MILLISECONDS: case MICROSECONDS: case SECONDS: case MINUTES: case HOURS: case DAYS: return "seconds"; case JIFFYS: return "jiffys"; case PER_JIFFY: return "per-jiffy"; case PER_NANOSECOND: case PER_MICROSECOND: case PER_MILLISECOND: case PER_SECOND: case PER_MINUTE: case PER_HOUR: case PER_DAY: return "per_second"; case CELSIUS: return "degree_celsius"; case KELVIN: return "kelvin"; case FAHRENHEIGHT: return "degree_fahrenheit"; case NONE: default: return "none"; } } enum Type { COUNTER, GAUGE; @Override public String toString() { return this.name().toLowerCase(); } } class MetricTag { private String key; private String value; public MetricTag() { } public MetricTag(String key, String value) { this.key = key; this.value = value; } public String getKey() { return key; } public String getValue() { return value; } public void setKey(String key) { this.key = key; } public void setValue(String value) { this.value = value; } @Override public String toString() { return "MetricTag{" + "key='" + key + '\'' + ", value='" + value + '\'' + '}'; } } }
3,647
24.51049
75
java
null
wildfly-main/observability/micrometer/src/main/java/org/wildfly/extension/micrometer/metrics/Metric.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.micrometer.metrics; import java.util.OptionalDouble; /** * A representation of a metric. * It is possibe that the value can not be computed (e.g. if it is backed by a WildFly * management attribute value which is undefined). */ public interface Metric { OptionalDouble getValue(); }
1,034
31.34375
86
java
null
wildfly-main/observability/micrometer/src/main/java/org/wildfly/extension/micrometer/metrics/WildFlyMetricMetadata.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.micrometer.metrics; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DEPLOYMENT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBDEPLOYMENT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.wildfly.common.Assert.checkNotNullParamWithNullPointerException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.client.helpers.MeasurementUnit; public class WildFlyMetricMetadata implements MetricMetadata { private static final Pattern SNAKE_CASE_PATTERN = Pattern.compile("(?<=[a-z])[A-Z]"); private static final String STATISTICS = "statistics"; private final String description; private final MeasurementUnit unit; private final Type type; private final String attributeName; private final PathAddress address; private String metricName; private MetricTag[] tags; private MetricID metricID; public WildFlyMetricMetadata(String attributeName, PathAddress address, String description, MeasurementUnit unit, Type type) { this.attributeName = checkNotNullParamWithNullPointerException("attributeName", attributeName); this.address = checkNotNullParamWithNullPointerException("address", address); this.description = checkNotNullParamWithNullPointerException("description", description); this.type = checkNotNullParamWithNullPointerException("type", type); this.unit = unit != null ? unit : MeasurementUnit.NONE; init(); } private void init() { StringBuilder metricPrefix = new StringBuilder(); List<String> labelNames = new ArrayList<>(); List<String> labelValues = new ArrayList<>(); for (PathElement element : address) { String key = element.getKey(); String value = element.getValue(); // prepend the subsystem or statistics name to the attribute if (key.equals(SUBSYSTEM) || key.equals(STATISTICS)) { metricPrefix.append(value) .append("-"); continue; } if (!key.equals(DEPLOYMENT) && !key.equals(SUBDEPLOYMENT)) { labelNames.add("type"); labelValues.add(key); labelNames.add("name"); labelValues.add(value); } else { labelNames.add(getDottedName(key)); labelValues.add(value); } } // if the resource address defines a deployment (without subdeployment), int deploymentIndex = labelNames.indexOf(DEPLOYMENT); int subdeploymentIndex = labelNames.indexOf(SUBDEPLOYMENT); if (deploymentIndex > -1 && subdeploymentIndex == -1) { labelNames.add(SUBDEPLOYMENT); subdeploymentIndex = labelNames.size()-1; labelValues.add(labelValues.get(deploymentIndex)); } if (deploymentIndex == -1) { labelNames.add(DEPLOYMENT); labelValues.add(""); } if (subdeploymentIndex == -1) { labelNames.add(SUBDEPLOYMENT); labelValues.add(""); } if (!labelNames.contains("app")) { labelNames.add("app"); labelValues.add(deploymentIndex >= 0 ? labelValues.get(deploymentIndex) : "wildfly"); } metricName = getDottedName(metricPrefix + attributeName); tags = new MetricTag[labelNames.size()]; for (int i = 0; i < labelNames.size(); i++) { tags[i] = new MetricTag(labelNames.get(i), labelValues.get(i)); } metricID = new MetricID(metricName, tags); } @Override public String getMetricName() { return metricName; } @Override public MetricTag[] getTags() { return tags; } @Override public String getDescription() { return description; } @Override public MeasurementUnit getMeasurementUnit() { return unit; } @Override public Type getType() { return type; } @Override public MetricID getMetricID() { return metricID; } private static String getDottedName(String name) { return decamelize(name.replaceAll("[^\\w]+", ".")); } private static String decamelize(String in) { Matcher m = SNAKE_CASE_PATTERN.matcher(in); StringBuffer sb = new StringBuffer(); while (m.find()) { m.appendReplacement(sb, "." + m.group().toLowerCase()); } m.appendTail(sb); return sb.toString().toLowerCase(); } @Override public String toString() { return ("WildFlyMetricMetadata{" + "description='" + description + '\'' + ", unit=" + unit + ", type=" + type + ", attributeName='" + attributeName + '\'' + ", address=" + address + ", metricName='" + metricName + '\'' + ", tags=" + Arrays.toString(tags) + ", metricID=" + metricID + '}').replaceAll("\\n", ""); } }
6,227
33.988764
103
java
null
wildfly-main/observability/micrometer/src/main/java/org/wildfly/extension/micrometer/metrics/MicrometerCollector.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.micrometer.metrics; import static org.jboss.as.controller.PathAddress.EMPTY_ADDRESS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ATTRIBUTES; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DESCRIPTION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.wildfly.extension.micrometer.metrics.MetricMetadata.Type.COUNTER; import static org.wildfly.extension.micrometer.metrics.MetricMetadata.Type.GAUGE; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.function.Function; import org.jboss.as.controller.ControlledProcessState; import org.jboss.as.controller.LocalModelControllerClient; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.ProcessStateNotifier; import org.jboss.as.controller.client.helpers.MeasurementUnit; import org.jboss.as.controller.descriptions.DescriptionProvider; import org.jboss.as.controller.registry.AttributeAccess; import org.jboss.as.controller.registry.ImmutableManagementResourceRegistration; import org.jboss.as.controller.registry.Resource; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.wildfly.extension.micrometer.registry.WildFlyRegistry; public class MicrometerCollector { private final LocalModelControllerClient modelControllerClient; private final ProcessStateNotifier processStateNotifier; private final WildFlyRegistry micrometerRegistry; public MicrometerCollector(LocalModelControllerClient modelControllerClient, ProcessStateNotifier processStateNotifier, WildFlyRegistry micrometerRegistry) { this.modelControllerClient = modelControllerClient; this.processStateNotifier = processStateNotifier; this.micrometerRegistry = micrometerRegistry; } // collect metrics from the resources public synchronized MetricRegistration collectResourceMetrics(final Resource resource, ImmutableManagementResourceRegistration managementResourceRegistration, Function<PathAddress, PathAddress> resourceAddressResolver, boolean exposeAnySubsystem, List<String> exposedSubsystems) { MetricRegistration registration = new MetricRegistration(micrometerRegistry); queueMetricRegistration(resource, managementResourceRegistration, EMPTY_ADDRESS, resourceAddressResolver, registration, exposeAnySubsystem, exposedSubsystems); // Defer the actual registration until the server is running and they can be collected w/o errors this.processStateNotifier.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (ControlledProcessState.State.RUNNING == evt.getNewValue()) { registration.register(); } else if (ControlledProcessState.State.STOPPING == evt.getNewValue()) { // Unregister so if this is a reload they won't still be around in a static cache in MetricsRegistry // and cause problems when the server is starting registration.unregister(); processStateNotifier.removePropertyChangeListener(this); } } }); // If server is already running, we won't get a change event so register now if (ControlledProcessState.State.RUNNING == this.processStateNotifier.getCurrentState()) { registration.register(); } return registration; } private void queueMetricRegistration(final Resource current, ImmutableManagementResourceRegistration managementResourceRegistration, PathAddress address, Function<PathAddress, PathAddress> resourceAddressResolver, MetricRegistration registration, boolean exposeAnySubsystem, List<String> exposedSubsystems) { if (!isExposingMetrics(address, exposeAnySubsystem, exposedSubsystems)) { return; } Map<String, AttributeAccess> attributes = managementResourceRegistration.getAttributes(address); if (attributes == null) { return; } ModelNode resourceDescription = null; for (Map.Entry<String, AttributeAccess> entry : attributes.entrySet()) { AttributeAccess attributeAccess = entry.getValue(); if (!isCollectibleMetric(attributeAccess)) { continue; } if (resourceDescription == null) { DescriptionProvider modelDescription = managementResourceRegistration.getModelDescription(address); resourceDescription = modelDescription.getModelDescription(Locale.getDefault()); } PathAddress resourceAddress = resourceAddressResolver.apply(address); String attributeName = entry.getKey(); MeasurementUnit unit = attributeAccess.getAttributeDefinition().getMeasurementUnit(); boolean isCounter = attributeAccess.getFlags().contains(AttributeAccess.Flag.COUNTER_METRIC); String attributeDescription = resourceDescription.get(ATTRIBUTES, attributeName, DESCRIPTION).asStringOrNull(); WildFlyMetric metric = new WildFlyMetric(modelControllerClient, resourceAddress, attributeName); WildFlyMetricMetadata metadata = new WildFlyMetricMetadata(attributeName, resourceAddress, attributeDescription, unit, isCounter ? COUNTER : GAUGE); registration.addRegistrationTask(() -> registration.registerMetric(metric, metadata)); } for (String type : current.getChildTypes()) { for (Resource.ResourceEntry entry : current.getChildren(type)) { final PathElement pathElement = entry.getPathElement(); final PathAddress childAddress = address.append(pathElement); queueMetricRegistration(entry, managementResourceRegistration, childAddress, resourceAddressResolver, registration, exposeAnySubsystem, exposedSubsystems); } } } private boolean isExposingMetrics(PathAddress address, boolean exposeAnySubsystem, List<String> exposedSubsystems) { // root resource if (address.size() == 0) { return true; } String subsystemName = getSubsystemName(address); if (subsystemName != null) { return exposeAnySubsystem || exposedSubsystems.contains(subsystemName); } // do not expose metrics for resources outside the subsystems and deployments. return false; } private String getSubsystemName(PathAddress address) { if (address.size() == 0) { return null; } if (address.getElement(0).getKey().equals(SUBSYSTEM)) { return address.getElement(0).getValue(); } else { return getSubsystemName(address.subAddress(1)); } } private boolean isCollectibleMetric(AttributeAccess attributeAccess) { if (attributeAccess.getAccessType() == AttributeAccess.AccessType.METRIC && attributeAccess.getStorageType() == AttributeAccess.Storage.RUNTIME) { // handle only metrics with simple numerical types ModelType type = attributeAccess.getAttributeDefinition().getType(); return type == ModelType.INT || type == ModelType.LONG || type == ModelType.DOUBLE; } return false; } }
8,912
47.440217
123
java
null
wildfly-main/observability/micrometer/src/main/java/org/wildfly/extension/micrometer/metrics/WildFlyMetric.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.micrometer.metrics; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILURE_DESCRIPTION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATION_HEADERS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ROLES; import static org.wildfly.extension.micrometer.MicrometerExtensionLogger.MICROMETER_LOGGER; import java.util.OptionalDouble; import org.jboss.as.controller.LocalModelControllerClient; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.dmr.ModelNode; public class WildFlyMetric implements Metric { private static final ModelNode UNDEFINED = new ModelNode(); private LocalModelControllerClient modelControllerClient; private PathAddress address; private String attributeName; static { UNDEFINED.protect(); } public WildFlyMetric() { } public WildFlyMetric(LocalModelControllerClient modelControllerClient, PathAddress address, String attributeName) { this.modelControllerClient = modelControllerClient; this.address = address; this.attributeName = attributeName; } @Override public OptionalDouble getValue() { ModelNode result = readAttributeValue(address, attributeName); if (result.isDefined()) { try { return OptionalDouble.of(result.asDouble()); } catch (Exception e) { MICROMETER_LOGGER.unableToConvertAttribute(attributeName, address, e); } } return OptionalDouble.empty(); } private ModelNode readAttributeValue(PathAddress address, String attributeName) { final ModelNode readAttributeOp = new ModelNode(); readAttributeOp.get(OP).set(READ_ATTRIBUTE_OPERATION); readAttributeOp.get(OP_ADDR).set(address.toModelNode()); readAttributeOp.get(ModelDescriptionConstants.INCLUDE_UNDEFINED_METRIC_VALUES).set(false); readAttributeOp.get(NAME).set(attributeName); readAttributeOp.get(OPERATION_HEADERS).get(ROLES).add("Monitor"); ModelNode response = modelControllerClient.execute(readAttributeOp); String error = getFailureDescription(response); if (error != null) { // [WFLY-11933] if the value can not be read if the management resource is not accessible due to RBAC, // it is logged it at a lower level. if (error.contains("WFLYCTL0216")) { MICROMETER_LOGGER.debugf("Unable to read attribute %s: %s.", attributeName, error); } else{ MICROMETER_LOGGER.unableToReadAttribute(attributeName, address, error); } return UNDEFINED; } return response.get(RESULT); } private String getFailureDescription(ModelNode result) { if (result.hasDefined(FAILURE_DESCRIPTION)) { return result.get(FAILURE_DESCRIPTION).toString(); } return null; } }
4,233
40.106796
119
java
null
wildfly-main/observability/micrometer/src/main/java/org/wildfly/extension/micrometer/registry/WildFlyOtlpRegistry.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2022 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.micrometer.registry; import org.wildfly.extension.micrometer.WildFlyMicrometerConfig; import io.micrometer.core.instrument.Clock; import io.micrometer.registry.otlp.OtlpMeterRegistry; public class WildFlyOtlpRegistry extends OtlpMeterRegistry implements WildFlyRegistry { public WildFlyOtlpRegistry(WildFlyMicrometerConfig config) { super(config, Clock.SYSTEM); } }
1,125
35.322581
87
java
null
wildfly-main/observability/micrometer/src/main/java/org/wildfly/extension/micrometer/registry/NoOpRegistry.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2023 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.micrometer.registry; import java.time.Duration; import java.util.concurrent.TimeUnit; import java.util.function.ToDoubleFunction; import java.util.function.ToLongFunction; import io.micrometer.core.instrument.Clock; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.DistributionSummary; import io.micrometer.core.instrument.FunctionCounter; import io.micrometer.core.instrument.FunctionTimer; import io.micrometer.core.instrument.Gauge; import io.micrometer.core.instrument.Measurement; import io.micrometer.core.instrument.Meter; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.Timer; import io.micrometer.core.instrument.distribution.DistributionStatisticConfig; import io.micrometer.core.instrument.distribution.pause.PauseDetector; import io.micrometer.core.instrument.noop.NoopCounter; import io.micrometer.core.instrument.noop.NoopDistributionSummary; import io.micrometer.core.instrument.noop.NoopFunctionCounter; import io.micrometer.core.instrument.noop.NoopFunctionTimer; import io.micrometer.core.instrument.noop.NoopGauge; import io.micrometer.core.instrument.noop.NoopMeter; import io.micrometer.core.instrument.noop.NoopTimer; public class NoOpRegistry extends MeterRegistry implements WildFlyRegistry { public NoOpRegistry() { super(Clock.SYSTEM); } @Override protected <T> Gauge newGauge(Meter.Id id, T t, ToDoubleFunction<T> toDoubleFunction) { return new NoopGauge(id); } @Override protected Counter newCounter(Meter.Id id) { return new NoopCounter(id); } @Override protected Timer newTimer(Meter.Id id, DistributionStatisticConfig distributionStatisticConfig, PauseDetector pauseDetector) { return new NoopTimer(id); } @Override protected DistributionSummary newDistributionSummary(Meter.Id id, DistributionStatisticConfig distributionStatisticConfig, double v) { return new NoopDistributionSummary(id); } @Override protected Meter newMeter(Meter.Id id, Meter.Type type, Iterable<Measurement> iterable) { return new NoopMeter(id); } @Override protected <T> FunctionTimer newFunctionTimer(Meter.Id id, T t, ToLongFunction<T> toLongFunction, ToDoubleFunction<T> toDoubleFunction, TimeUnit timeUnit) { return new NoopFunctionTimer(id); } @Override protected <T> FunctionCounter newFunctionCounter(Meter.Id id, T t, ToDoubleFunction<T> toDoubleFunction) { return new NoopFunctionCounter(id); } @Override protected TimeUnit getBaseTimeUnit() { return TimeUnit.SECONDS; } @Override protected DistributionStatisticConfig defaultHistogramConfig() { return DistributionStatisticConfig.builder().expiry(Duration.ZERO).build().merge(DistributionStatisticConfig.DEFAULT); } }
3,608
35.454545
159
java
null
wildfly-main/observability/micrometer/src/main/java/org/wildfly/extension/micrometer/registry/WildFlyRegistry.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2023 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.micrometer.registry; import java.util.Arrays; import java.util.OptionalDouble; import java.util.stream.Collectors; import org.jboss.as.controller.client.helpers.MeasurementUnit; import org.wildfly.extension.micrometer.MicrometerExtensionLogger; import org.wildfly.extension.micrometer.metrics.MetricMetadata; import org.wildfly.extension.micrometer.metrics.WildFlyMetric; import io.micrometer.core.instrument.FunctionCounter; import io.micrometer.core.instrument.Gauge; import io.micrometer.core.instrument.Meter; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.Tag; import io.micrometer.core.instrument.Tags; public interface WildFlyRegistry { Meter remove(Meter.Id mappedId); default Meter.Id addMeter(WildFlyMetric metric, MetricMetadata metadata) { switch (metadata.getType()) { case GAUGE: return addGauge(metric, metadata); case COUNTER: return addCounter(metric, metadata); default: throw MicrometerExtensionLogger.MICROMETER_LOGGER.unsupportedMetricType(metadata.getType().name()); } } default void close() { } private Meter.Id addCounter(WildFlyMetric metric, MetricMetadata metadata) { return FunctionCounter.builder(metadata.getMetricName(), metric, value -> getMetricValue(metric, metadata.getMeasurementUnit())) .tags(getTags(metadata)) .baseUnit(getBaseUnit(metadata)) .description(metadata.getDescription()) .register((MeterRegistry) this) .getId(); } private Meter.Id addGauge(WildFlyMetric metric, MetricMetadata metadata) { return Gauge.builder(metadata.getMetricName(), metric, value -> getMetricValue(metric, metadata.getMeasurementUnit())) .tags(getTags(metadata)) .baseUnit(getBaseUnit(metadata)) .description(metadata.getDescription()) .register((MeterRegistry) this) .getId(); } private Tags getTags(MetricMetadata metadata) { return Tags.of(Arrays.stream(metadata.getTags()) .map(t -> Tag.of(t.getKey(), t.getValue())) .collect(Collectors.toList())); } private String getBaseUnit(MetricMetadata metadata) { String measurementUnit = metadata.getBaseMetricUnit(); return "none".equalsIgnoreCase(measurementUnit) ? null : measurementUnit.toLowerCase(); } private double getMetricValue(WildFlyMetric metric, MeasurementUnit unit) { OptionalDouble metricValue = metric.getValue(); return metricValue.isPresent() ? scaleToBaseUnit(metricValue.getAsDouble(), unit) : 0.0; } private double scaleToBaseUnit(double value, MeasurementUnit unit) { return value * MeasurementUnit.calculateOffset(unit, unit.getBaseUnits()); } }
3,737
37.9375
115
java
null
wildfly-main/observability/opentelemetry/src/test/java/org/wildfly/extension/opentelemetry/SubsystemParsingTestCase.java
package org.wildfly.extension.opentelemetry; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import java.io.IOException; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.stream.XMLStreamException; import org.jboss.as.subsystem.test.AbstractSubsystemSchemaTest; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** * @author <a href="jasondlee@redhat.com">Jason Lee</a> */ @RunWith(Parameterized.class) public class SubsystemParsingTestCase extends AbstractSubsystemSchemaTest<OpenTelemetrySubsystemSchema> { @Parameters public static Iterable<OpenTelemetrySubsystemSchema> parameters() { return EnumSet.allOf(OpenTelemetrySubsystemSchema.class); } public SubsystemParsingTestCase(OpenTelemetrySubsystemSchema schema) { super(OpenTelemetrySubsystemExtension.SUBSYSTEM_NAME, new OpenTelemetrySubsystemExtension(), schema, OpenTelemetrySubsystemSchema.CURRENT); } @Test public void testInvalidExporter() throws Exception { Assert.assertThrows(XMLStreamException.class, () -> this.parse(readResource("invalid-exporter.xml"))); } @Test public void testInvalidSampler() throws Exception { Assert.assertThrows(XMLStreamException.class, () -> this.parse(readResource("invalid-sampler.xml"))); } @Test public void testInvalidSpanProcessor() throws Exception { Assert.assertThrows(XMLStreamException.class, () -> this.parse(readResource("invalid-span-processor.xml"))); } @Test public void testExpressions() throws IOException, XMLStreamException { String xml = readResource("expressions.xml"); List<ModelNode> operations = this.parse(xml); Assert.assertEquals(1, operations.size()); //Check that each operation has the correct content ModelNode addSubsystem = operations.get(0); Assert.assertEquals(ADD, addSubsystem.get(OP).asString()); Map<String, String> values = new HashMap<>(); values.put("service-name", "test-service"); values.put("exporter-type", "jaeger"); values.put("endpoint", "http://localhost:14250"); values.put("span-processor-type", "batch"); values.put("batch-delay", "5000"); values.put("max-queue-size", "2048"); values.put("max-export-batch-size", "512"); values.put("export-timeout", "30000"); values.put("sampler-type", "on"); values.put("ratio", "0.75"); for (Map.Entry<String, String> entry : values.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); ModelNode node = addSubsystem.get(key); Assert.assertTrue(node.getType().equals(ModelType.EXPRESSION)); Assert.assertEquals("${test." + key + ":" + value + "}", node.asString()); Assert.assertEquals(value, node.asExpression().resolveString()); } } }
3,259
36.906977
147
java
null
wildfly-main/observability/opentelemetry/src/main/java/org/wildfly/extension/opentelemetry/OpenTelemetrySubsystemExtension.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2021 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.opentelemetry; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import java.util.EnumSet; import java.util.List; import org.jboss.as.controller.Extension; import org.jboss.as.controller.ExtensionContext; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.PersistentResourceXMLDescription; import org.jboss.as.controller.PersistentResourceXMLDescriptionReader; import org.jboss.as.controller.PersistentResourceXMLDescriptionWriter; import org.jboss.as.controller.SubsystemRegistration; import org.jboss.as.controller.descriptions.ParentResourceDescriptionResolver; import org.jboss.as.controller.descriptions.SubsystemResourceDescriptionResolver; import org.jboss.as.controller.operations.common.GenericSubsystemDescribeHandler; import org.jboss.as.controller.parsing.ExtensionParsingContext; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.dmr.ModelNode; import org.jboss.staxmapper.XMLElementReader; /** * @author <a href="jasondlee@redhat.com">Jason Lee</a> */ public class OpenTelemetrySubsystemExtension implements Extension { public static final String SUBSYSTEM_NAME = "opentelemetry"; public static final PathElement SUBSYSTEM_PATH = PathElement.pathElement(SUBSYSTEM, SUBSYSTEM_NAME); static final ParentResourceDescriptionResolver SUBSYSTEM_RESOLVER = new SubsystemResourceDescriptionResolver(SUBSYSTEM_NAME, OpenTelemetrySubsystemExtension.class); private final PersistentResourceXMLDescription currentDescription = OpenTelemetrySubsystemSchema.CURRENT.getXMLDescription(); @Override public void initialize(ExtensionContext context) { final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, OpenTelemetrySubsystemModel.CURRENT.getVersion()); subsystem.registerXMLElementWriter(new PersistentResourceXMLDescriptionWriter(this.currentDescription)); final ManagementResourceRegistration registration = subsystem.registerSubsystemModel(new OpenTelemetrySubsystemDefinition()); registration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE); } @Override public void initializeParsers(ExtensionParsingContext context) { for (OpenTelemetrySubsystemSchema schema : EnumSet.allOf(OpenTelemetrySubsystemSchema.class)) { XMLElementReader<List<ModelNode>> reader = (schema == OpenTelemetrySubsystemSchema.CURRENT) ? new PersistentResourceXMLDescriptionReader(this.currentDescription) : schema; context.setSubsystemXmlMapping(SUBSYSTEM_NAME, schema.getNamespace().getUri(), reader); } } }
3,441
48.171429
183
java
null
wildfly-main/observability/opentelemetry/src/main/java/org/wildfly/extension/opentelemetry/OpenTelemetryExtensionLogger.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2021 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.opentelemetry; import static org.jboss.logging.Logger.Level.ERROR; import static org.jboss.logging.Logger.Level.INFO; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; @MessageLogger(projectCode = "WFLYOTELEXT", length = 4) interface OpenTelemetryExtensionLogger extends BasicLogger { OpenTelemetryExtensionLogger OTEL_LOGGER = Logger.getMessageLogger(OpenTelemetryExtensionLogger.class, OpenTelemetryExtensionLogger.class.getPackage().getName()); @LogMessage(level = INFO) @Message(id = 1, value = "Activating OpenTelemetry Subsystem") void activatingSubsystem(); /* @LogMessage(level = DEBUG) @Message(id = 2, value = "OpenTelemetry Subsystem is processing deployment") void processingDeployment(); @LogMessage(level = DEBUG) @Message(id = 3, value = "The deployment does not have Jakarta Contexts and Dependency Injection enabled. Skipping OpenTelemetry integration.") void noCdiDeployment(); */ @Message(id = 4, value = "Deployment %s requires use of the '%s' capability but it is not currently registered") DeploymentUnitProcessingException deploymentRequiresCapability(String deploymentName, String capabilityName); @LogMessage(level = ERROR) @Message(id = 5, value = "Error resolving the OpenTelemetry instance.") void errorResolvingTelemetry(@Cause Exception ex); /* @LogMessage(level = DEBUG) @Message(id = 6, value = "Deriving service name based on the deployment unit's name: %s") void serviceNameDerivedFromDeploymentUnit(String serviceName); @LogMessage(level = DEBUG) @Message(id = 7, value = "Registering %s as the OpenTelemetry Tracer") void registeringTracer(String message); */ @Message(id = 8, value = "An unsupported exporter was specified: '%s'.") IllegalArgumentException unsupportedExporter(String exporterType); @LogMessage(level = ERROR) @Message(id = 9, value = "Error resolving the tracer.") void errorResolvingTracer(@Cause Exception ex); @Message(id = 10, value = "An unsupported span processor was specified: '%s'.") IllegalArgumentException unsupportedSpanProcessor(String spanProcessor); @Message(id = 11, value = "Unrecognized value for sampler: '%s'.") IllegalArgumentException unsupportedSampler(String sampler); @Message(id = 12, value = "Invalid ratio. Must be between 0.0 and 1.0 inclusive") IllegalArgumentException invalidRatio(); }
3,454
39.647059
147
java
null
wildfly-main/observability/opentelemetry/src/main/java/org/wildfly/extension/opentelemetry/OpenTelemetryDependencyProcessor.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2021 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.opentelemetry; import static org.wildfly.extension.opentelemetry.OpenTelemetrySubsystemDefinition.API_MODULE; import static org.wildfly.extension.opentelemetry.OpenTelemetrySubsystemDefinition.EXPORTED_MODULES; import org.jboss.as.controller.capability.CapabilityServiceSupport; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.module.ModuleDependency; import org.jboss.as.server.deployment.module.ModuleSpecification; import org.jboss.as.weld.Capabilities; import org.jboss.as.weld.WeldCapability; import org.jboss.modules.Module; import org.jboss.modules.ModuleLoader; class OpenTelemetryDependencyProcessor implements DeploymentUnitProcessor { public OpenTelemetryDependencyProcessor() { } @Override public void deploy(DeploymentPhaseContext phaseContext) { addDependencies(phaseContext.getDeploymentUnit()); } private void addDependencies(DeploymentUnit deploymentUnit) { final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION); final ModuleLoader moduleLoader = Module.getBootModuleLoader(); try { CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT); WeldCapability weldCapability = support.getCapabilityRuntimeAPI(Capabilities.WELD_CAPABILITY_NAME, WeldCapability.class); if (weldCapability.isPartOfWeldDeployment(deploymentUnit)) { // Export the -api module only if CDI is available moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, API_MODULE, false, true, true, false)); } // Export all other modules regardless of CDI availability for (String module : EXPORTED_MODULES) { moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, module, false, true, true, false)); } } catch (CapabilityServiceSupport.NoSuchCapabilityException e) { throw new IllegalStateException(); } } }
3,089
42.521127
119
java
null
wildfly-main/observability/opentelemetry/src/main/java/org/wildfly/extension/opentelemetry/OpenTelemetrySubsystemSchema.java
package org.wildfly.extension.opentelemetry; import static org.jboss.as.controller.PersistentResourceXMLDescription.builder; import org.jboss.as.controller.PersistentResourceXMLDescription; import org.jboss.as.controller.PersistentSubsystemSchema; import org.jboss.as.controller.SubsystemSchema; import org.jboss.as.controller.xml.VersionedNamespace; import org.jboss.staxmapper.IntVersion; public enum OpenTelemetrySubsystemSchema implements PersistentSubsystemSchema<OpenTelemetrySubsystemSchema> { VERSION_1_0(1, 0), // WildFly 25 ; public static final OpenTelemetrySubsystemSchema CURRENT = VERSION_1_0; private final VersionedNamespace<IntVersion, OpenTelemetrySubsystemSchema> namespace; OpenTelemetrySubsystemSchema(int major, int minor) { this.namespace = SubsystemSchema.createSubsystemURN(OpenTelemetrySubsystemExtension.SUBSYSTEM_NAME, new IntVersion(major, minor)); } @Override public VersionedNamespace<IntVersion, OpenTelemetrySubsystemSchema> getNamespace() { return this.namespace; } @Override public PersistentResourceXMLDescription getXMLDescription() { return builder(OpenTelemetrySubsystemExtension.SUBSYSTEM_PATH, this.namespace) .addAttributes(OpenTelemetrySubsystemDefinition.ATTRIBUTES) .build(); } }
1,336
38.323529
138
java
null
wildfly-main/observability/opentelemetry/src/main/java/org/wildfly/extension/opentelemetry/OpenTelemetrySubsystemModel.java
package org.wildfly.extension.opentelemetry; import org.jboss.as.controller.ModelVersion; import org.jboss.as.controller.SubsystemModel; public enum OpenTelemetrySubsystemModel implements SubsystemModel { VERSION_1_0_0(1, 0, 0); public static final OpenTelemetrySubsystemModel CURRENT = VERSION_1_0_0; private final ModelVersion version; OpenTelemetrySubsystemModel(int major, int minor, int micro) { this.version = ModelVersion.create(major, minor, micro); } @Override public ModelVersion getVersion() { return version; } }
579
25.363636
76
java