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
AMLSim
AMLSim-master/src/main/java/amlsim/Alert.java
package amlsim; import amlsim.model.aml.AMLTypology; import java.util.*; /* * Group of suspicious transactions and involving accounts as an AML typology * Accounts in this class perform suspicious transactions based on the given typology (model) */ public class Alert { private long alertID; // Alert identifier private List<Account> members; // Accounts involved in this alert private Account mainAccount; // Main account of this alert private AMLTypology model; // Transaction model private AMLSim amlsim; // AMLSim main object Alert(long alertID, AMLTypology model, AMLSim sim){ this.alertID = alertID; this.members = new ArrayList<>(); this.mainAccount = null; this.model = model; this.model.setAlert(this); this.amlsim = sim; } /** * Add transactions * @param step Current simulation step */ void registerTransactions(long step, Account acct){ if(model.isValidStep(step)){ model.sendTransactions(step, acct); } } /** * Involve an account in this alert * @param acct Account object */ void addMember(Account acct){ this.members.add(acct); acct.addAlert(this); } /** * Get main AMLSim object * @return AMLSim object */ public AMLSim getSimulator(){ return amlsim; } /** * Get alert identifier as long type * @return Alert identifier */ public long getAlertID(){ return alertID; } /** * Get member list of the alert * @return Alert account list */ public List<Account> getMembers(){ return members; } /** * Get the main account * @return The main account if exists. */ public Account getMainAccount(){ return mainAccount; } /** * Set the main account * @param account Main account object */ void setMainAccount(Account account){ this.mainAccount = account; } public AMLTypology getModel(){ return model; } public boolean isSAR(){ return this.mainAccount != null && this.mainAccount.isSAR(); } }
2,204
21.96875
93
java
AMLSim
AMLSim-master/src/main/java/amlsim/Branch.java
package amlsim; /** * A branch of a bank * In cash transactions, this class perform like an account */ public class Branch extends Account { private int id; // Branch identifier private float limitAmount = 100.0F; // Limit of deposit/withdrawal amount public Branch(int id){ this.id = id; } /** * Get the limit of deposit/withdrawal amount * @return Limit of deposit/withdrawal amount */ public float getLimitAmount(){ return limitAmount; } /** * Get the branch identifier as String * @return Branch identifier */ public String toString(){ return "B" + this.id; } /** * Get the branch identifier as String * @return Branch identifier */ public String getName() { return toString(); } }
827
19.195122
78
java
AMLSim
AMLSim-master/src/main/java/amlsim/SARAccount.java
package amlsim; import java.util.Random; import amlsim.model.aml.*; import sim.engine.SimState; /** * Suspicious account class */ public class SARAccount extends Account { private int count = 0; SARAccount(String id, int interval, float init_balance, String bankID, Random random) { super(id, interval, init_balance, bankID, random); this.isSAR = true; } public void handleAction(SimState state){ AMLSim amlsim = (AMLSim) state; super.handleAction(amlsim); boolean success = handleAlert(amlsim); if(success){ count++; } } private boolean handleAlert(AMLSim amlsim){ if(alerts.isEmpty()){ return false; } Alert fg = alerts.get(count % alerts.size()); AMLTypology model = fg.getModel(); // this is no-op // figure out why this was here. model.makeTransaction(amlsim.schedule.getSteps()); return true; } public String toString() { return "F" + this.id; } }
918
17.755102
88
java
AMLSim
AMLSim-master/src/main/java/amlsim/SimProperties.java
package amlsim; import java.io.*; import java.nio.file.*; import org.json.*; /** * Simulation properties and global parameters loaded from the configuration JSON file */ public class SimProperties { private static final String separator = File.separator; private JSONObject generalProp; private JSONObject simProp; private JSONObject inputProp; private JSONObject outputProp; private JSONObject cashInProp; private JSONObject cashOutProp; private String workDir; private double marginRatio; // Ratio of margin for AML typology transactions private int seed; // Seed of randomness private String simName; // Simulation name private int normalTxInterval; private double minTxAmount; // Minimum base (normal) transaction amount private double maxTxAmount; // Maximum base (suspicious) transaction amount SimProperties(String jsonName) throws IOException{ String jsonStr = loadTextFile(jsonName); JSONObject jsonObject = new JSONObject(jsonStr); JSONObject defaultProp = jsonObject.getJSONObject("default"); generalProp = jsonObject.getJSONObject("general"); simProp = jsonObject.getJSONObject("simulator"); inputProp = jsonObject.getJSONObject("temporal"); // Input directory of this simulator is temporal directory outputProp = jsonObject.getJSONObject("output"); normalTxInterval = simProp.getInt("transaction_interval"); minTxAmount = defaultProp.getDouble("min_amount"); maxTxAmount = defaultProp.getDouble("max_amount"); System.out.printf("General transaction interval: %d\n", normalTxInterval); System.out.printf("Base transaction amount: Normal = %f, Suspicious= %f\n", minTxAmount, maxTxAmount); cashInProp = defaultProp.getJSONObject("cash_in"); cashOutProp = defaultProp.getJSONObject("cash_out"); marginRatio = defaultProp.getDouble("margin_ratio"); String envSeed = System.getenv("RANDOM_SEED"); seed = envSeed != null ? Integer.parseInt(envSeed) : generalProp.getInt("random_seed"); System.out.println("Random seed: " + seed); simName = System.getProperty("simulation_name"); if(simName == null){ simName = generalProp.getString("simulation_name"); } System.out.println("Simulation name: " + simName); String simName = getSimName(); workDir = inputProp.getString("directory") + separator + simName + separator; System.out.println("Working directory: " + workDir); } private static String loadTextFile(String jsonName) throws IOException{ Path file = Paths.get(jsonName); byte[] bytes = Files.readAllBytes(file); return new String(bytes); } String getSimName(){ return simName; } public int getSeed(){ return seed; } public int getSteps(){ return generalProp.getInt("total_steps"); } boolean isComputeDiameter(){ return simProp.getBoolean("compute_diameter"); } int getTransactionLimit(){ return simProp.getInt("transaction_limit"); } int getNormalTransactionInterval(){ return normalTxInterval; } public double getMinTransactionAmount() { return minTxAmount; } public double getMaxTransactionAmount() { return maxTxAmount; } public double getMarginRatio(){ return marginRatio; } int getNumBranches(){ return simProp.getInt("numBranches"); } String getInputAcctFile(){ return workDir + inputProp.getString("accounts"); } String getInputTxFile(){ return workDir + inputProp.getString("transactions"); } String getInputAlertMemberFile() { return workDir + inputProp.getString("alert_members"); } String getNormalModelsFile() { return workDir + inputProp.getString("normal_models"); } String getOutputTxLogFile(){ return getOutputDir() + outputProp.getString("transaction_log"); } String getOutputDir(){ return outputProp.getString("directory") + separator + simName + separator; } String getCounterLogFile(){ return getOutputDir() + outputProp.getString("counter_log"); } String getDiameterLogFile(){ return workDir + outputProp.getString("diameter_log"); } int getCashTxInterval(boolean isCashIn, boolean isSAR){ String key = isSAR ? "fraud_interval" : "normal_interval"; return isCashIn ? cashInProp.getInt(key) : cashOutProp.getInt(key); } float getCashTxMinAmount(boolean isCashIn, boolean isSAR){ String key = isSAR ? "fraud_min_amount" : "normal_min_amount"; return isCashIn ? cashInProp.getFloat(key) : cashOutProp.getFloat(key); } float getCashTxMaxAmount(boolean isCashIn, boolean isSAR){ String key = isSAR ? "fraud_max_amount" : "normal_max_amount"; return isCashIn ? cashInProp.getFloat(key) : cashOutProp.getFloat(key); } }
5,065
30.6625
117
java
AMLSim
AMLSim-master/src/main/java/amlsim/TargetedTransactionAmount.java
package amlsim; import java.util.Random; public class TargetedTransactionAmount { private SimProperties simProperties; private Random random; private double target; public TargetedTransactionAmount(Number target, Random random) { this.simProperties = AMLSim.getSimProp(); this.random = random; this.target = target.doubleValue(); } public double doubleValue() { double minTransactionAmount = simProperties.getMinTransactionAmount(); double maxTransactionAmount = simProperties.getMaxTransactionAmount(); double min, max, result; if (this.target < maxTransactionAmount) { max = this.target; } else { max = maxTransactionAmount; } if (this.target < minTransactionAmount) { min = this.target; } else { min = minTransactionAmount; } if (max - min <= 0) { result = this.target; } if (this.target - min <= 100) { result = this.target; } else { result = min + random.nextDouble() * (max - min); } return result; } }
1,199
23
77
java
AMLSim
AMLSim-master/src/main/java/amlsim/TransactionRepository.java
package amlsim; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.*; /** * AML Transaction repository (set of transactions) for performance optimizations */ public class TransactionRepository { public final int size; private int index = 0; // private DecimalFormat amt_fmt; private int count = 0; private int limit = Integer.MAX_VALUE; // Number of transactions as buffer private long[] steps; private String[] descriptions; private double[] amounts; private String[] origIDs; private String[] destIDs; private float[] origBefore; private float[] origAfter; private float[] destBefore; private float[] destAfter; private boolean[] isSAR; private long[] alertIDs; private Map<Long, Integer> txCounter; private Map<Long, Integer> sarTxCounter; TransactionRepository(int size) { this.txCounter = new HashMap<>(); this.sarTxCounter = new HashMap<>(); this.size = size; this.steps = new long[size]; this.descriptions = new String[size]; this.amounts = new double[size]; this.origIDs = new String[size]; this.destIDs = new String[size]; this.origBefore = new float[size]; this.origAfter = new float[size]; this.destBefore = new float[size]; this.destAfter = new float[size]; this.isSAR = new boolean[size]; this.alertIDs = new long[size]; } void setLimit(int limit){ this.limit = limit; } void addTransaction(long step, String desc, double amt, String origID, String destID, float origBefore, float origAfter, float destBefore, float destAfter, boolean isSAR, long aid){ if(count >= limit){ if(count == limit){ System.err.println("Warning: the number of output transactions has reached the limit: " + limit); flushLog(); count++; } return; } this.steps[index] = step; this.descriptions[index] = desc; this.amounts[index] = amt; this.origIDs[index] = origID; this.destIDs[index] = destID; this.origBefore[index] = origBefore; this.origAfter[index] = origAfter; this.destBefore[index] = destBefore; this.destAfter[index] = destAfter; this.isSAR[index] = isSAR; this.alertIDs[index] = aid; if(isSAR){ sarTxCounter.put(step, sarTxCounter.getOrDefault(step, 0) + 1); }else if(!desc.contains("CASH-")) { txCounter.put(step, txCounter.getOrDefault(step, 0) + 1); // Exclude cash transactions for counter count--; } count++; index++; if(index >= size){ flushLog(); } } private double getDoublePrecision(double d) { // Round down amount to two digits (e.g. 12.3456 --> 12.34) // DecimalFormat will not be used because of its computation cost return (int)(d * 100) / 100.0; } void writeCounterLog(long steps, String logFile){ try { BufferedWriter writer = new BufferedWriter(new FileWriter(logFile)); writer.write("step,normal,SAR\n"); for(long i=0; i<steps; i++){ int numTx = txCounter.getOrDefault(i, 0); int numSARTx = sarTxCounter.getOrDefault(i, 0); writer.write(i + "," + numTx + "," + numSARTx + "\n"); } writer.flush(); }catch(IOException e){ e.printStackTrace(); } } void flushLog(){ // Flush transaction logs to the CSV file try { FileWriter writer1 = new FileWriter(new File(AMLSim.getTxLogFileName()), true); BufferedWriter writer = new BufferedWriter(writer1); for(int i = 0; i < this.index; i++){ writer.write(steps[i] + "," + descriptions[i] + "," + getDoublePrecision(amounts[i]) + "," + origIDs[i] + "," + getDoublePrecision(origBefore[i]) + "," + getDoublePrecision(origAfter[i]) + "," + destIDs[i] + "," + getDoublePrecision(destBefore[i]) + "," + getDoublePrecision(destAfter[i]) + "," + (isSAR[i] ? "1" : "0") + "," + alertIDs[i] + "\n"); } writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } index = 0; } }
4,575
31.920863
125
java
AMLSim
AMLSim-master/src/main/java/amlsim/model/AbstractTransactionModel.java
package amlsim.model; import amlsim.Account; import amlsim.AccountGroup; import amlsim.AMLSim; /** * Base class of transaction models */ public abstract class AbstractTransactionModel { // Transaction model ID public static final String SINGLE = "single"; // Make a single transaction to each neighbor account public static final String FAN_OUT = "fan_out"; // Send money to all neighbor accounts public static final String FAN_IN = "fan_in"; // Receive money from neighbor accounts public static final String MUTUAL = "mutual"; public static final String FORWARD = "forward"; public static final String PERIODICAL = "periodical"; // protected static Random rand = new Random(AMLSim.getSeed()); protected AccountGroup accountGroup; // Account group object protected int interval = 1; // Default transaction interval protected long startStep = -1; // The first step of transactions protected long endStep = -1; // The end step of transactions protected boolean isSAR = false; /** * Get the assumed number of transactions in this simulation * @return Number of total transactions */ public int getNumberOfTransactions(){ return (int)AMLSim.getNumOfSteps() / interval; } /** * Set an account object group which has this model * * @param accountGroup account group object */ public void setAccountGroup(AccountGroup accountGroup) { this.accountGroup = accountGroup; } /** * Get the simulation step range as the period when this model is valid * If "startStep" and/or "endStep" is undefined (negative), it returns the largest range * @return The total number of simulation steps */ public int getStepRange(){ long st = startStep >= 0 ? startStep : 0; long ed = endStep > 0 ? endStep : AMLSim.getNumOfSteps(); return (int)(ed - st + 1); } /** * Get transaction model name * @return Transaction model name */ public abstract String getModelName(); /** * Generate the start transaction step (to decentralize transaction distribution) * @param range Simulation step range * @return random int value [0, range-1] */ protected static int generateStartStep(int range){ // return rand.nextInt(range); return AMLSim.getRandom().nextInt(range); } /** * Set initial parameters * This method will be called when the account is initialized * @param interval Transaction interval * @param start Start simulation step (It never makes any transactions before this step) * @param end End simulation step (It never makes any transactions after this step) */ public void setParameters(int interval, long start, long end){ this.interval = interval; setParameters(start, end); } /** * Set initial parameters of the transaction model (for AML typology models) * @param start Start simulation step * @param end End simulation step */ public void setParameters(long start, long end){ this.startStep = start; this.endStep = end; } /** * The new workhorse method. * @param step * @param account */ public abstract void sendTransactions(long step, Account account); /** * Generate and register a transaction (for alert transactions) * @param step Current simulation step * @param amount Transaction amount * @param orig Origin account * @param dest Destination account * @param isSAR Whether this transaction is SAR * @param alertID Alert ID */ protected void makeTransaction(long step, double amount, Account orig, Account dest, boolean isSAR, long alertID){ if(amount <= 0){ // Invalid transaction amount // AMLSim.getLogger().warning("Warning: invalid transaction amount: " + amount); return; } String ttype = orig.getTxType(dest); if(isSAR) { AMLSim.getLogger().fine("Handle transaction: " + orig.getID() + " -> " + dest.getID()); } AMLSim.handleTransaction(step, ttype, amount, orig, dest, isSAR, alertID); } /** * Generate and register a transaction (for cash transactions) * @param step Current simulation step * @param amount Transaction amount * @param orig Origin account * @param dest Destination account * @param ttype Transaction type */ protected void makeTransaction(long step, float amount, Account orig, Account dest, String ttype){ AMLSim.handleTransaction(step, ttype, amount, orig, dest, false, -1); } /** * Generate and register a transaction (for normal transactions) * @param step Current simulation step * @param amount Transaction amount * @param orig Origin account * @param dest Destination account */ protected void makeTransaction(long step, double amount, Account orig, Account dest){ makeTransaction(step, amount, orig, dest, false, -1); } }
5,106
33.979452
118
java
AMLSim
AMLSim-master/src/main/java/amlsim/model/ModelParameters.java
package amlsim.model; import java.io.*; import java.util.Random; import java.util.Properties; import amlsim.AMLSim; import amlsim.Account; /** * Adjust transaction parameters for fine-tuning of the transaction network */ public class ModelParameters { // private static Random rand = new Random(AMLSim.getSeed()); private static Random rand = AMLSim.getRandom(); private static Properties prop = null; private static float SAR2SAR_EDGE_THRESHOLD = 0.0F; private static float SAR2NORMAL_EDGE_THRESHOLD = 0.0F; private static float NORMAL2SAR_EDGE_THRESHOLD = 0.0F; private static float NORMAL2NORMAL_EDGE_THRESHOLD = 0.0F; private static float SAR2SAR_TX_PROB = 1.0F; private static float SAR2NORMAL_TX_PROB = 1.0F; private static float NORMAL2SAR_TX_PROB = 1.0F; private static float NORMAL2NORMAL_TX_PROB = 1.0F; private static float SAR2SAR_AMOUNT_RATIO = 1.0F; private static float SAR2NORMAL_AMOUNT_RATIO = 1.0F; private static float NORMAL2SAR_AMOUNT_RATIO = 1.0F; private static float NORMAL2NORMAL_AMOUNT_RATIO = 1.0F; private static float NORMAL_HIGH_RATIO = 1.0F; // High transaction amount ratio from normal accounts private static float NORMAL_LOW_RATIO = 1.0F; // Low transaction amount ratio from normal accounts private static float NORMAL_HIGH_PROB = 0.0F; // Probability of transactions with high amount private static float NORMAL_LOW_PROB = 0.0F; // Probability of transactions with low amount private static float NORMAL_SKIP_PROB = 0.0F; // Probability of skipping transactions /** * Whether it adjusts parameters of normal transactions * @return If true, it affects to normal transaction models * If false, it does not any effects to all normal transactions */ public static boolean isValid(){ return prop != null; } private static float getRatio(String key, float defaultValue){ String value = System.getProperty(key); if(value == null){ value = prop.getProperty(key, String.valueOf(defaultValue)); } return Float.parseFloat(value); } private static float getRatio(String key){ return getRatio(key, 1.0F); } public static void loadProperties(String propFile){ if(propFile == null){ return; } System.out.println("Model parameter file: " + propFile); try{ prop = new Properties(); prop.load(new FileInputStream(propFile)); }catch (IOException e){ System.err.println("Cannot load model parameter file: " + propFile); e.printStackTrace(); prop = null; return; } SAR2SAR_EDGE_THRESHOLD = getRatio("sar2sar.edge.threshold"); SAR2NORMAL_EDGE_THRESHOLD = getRatio("sar2normal.edge.threshold"); NORMAL2SAR_EDGE_THRESHOLD = getRatio("normal2sar.edge.threshold"); NORMAL2NORMAL_EDGE_THRESHOLD = getRatio("normal2normal.edge.threshold"); SAR2SAR_TX_PROB = getRatio("sar2sar.tx.prob"); SAR2NORMAL_TX_PROB = getRatio("sar2normal.tx.prob"); NORMAL2SAR_TX_PROB = getRatio("normal2sar.tx.prob"); NORMAL2NORMAL_TX_PROB = getRatio("normal2normal.tx.prob"); SAR2SAR_AMOUNT_RATIO = getRatio("sar2sar.amount.ratio"); SAR2NORMAL_AMOUNT_RATIO = getRatio("sar2normal.amount.ratio"); NORMAL2SAR_AMOUNT_RATIO = getRatio("normal2sar.amount.ratio"); NORMAL2NORMAL_AMOUNT_RATIO = getRatio("normal2normal.amount.ratio"); NORMAL_HIGH_RATIO = getRatio("normal.high.ratio", 1.0F); NORMAL_LOW_RATIO = getRatio("normal.low.ratio", 1.0F); NORMAL_HIGH_PROB = getRatio("normal.high.prob", 1.0F); NORMAL_LOW_PROB = getRatio("normal.low.prob", 1.0F); NORMAL_SKIP_PROB = getRatio("normal.skip.prob", 1.0F); if(NORMAL_HIGH_RATIO < 1.0){ throw new IllegalArgumentException("The high transaction amount ratio must be 1.0 or more"); } if(NORMAL_LOW_RATIO <= 0.0 || 1.0 < NORMAL_LOW_RATIO){ throw new IllegalArgumentException("The low transaction amount ratio must be positive and 1.0 or less"); } if(1.0 < NORMAL_HIGH_PROB + NORMAL_LOW_PROB + NORMAL_SKIP_PROB){ throw new IllegalArgumentException("The sum of high, low and skip transaction probabilities" + " must be 1.0 or less"); } System.out.println("Transaction Probability:"); System.out.println("\tSAR -> SAR: " + SAR2SAR_TX_PROB); System.out.println("\tSAR -> Normal: " + SAR2NORMAL_TX_PROB); System.out.println("\tNormal -> SAR: " + NORMAL2SAR_TX_PROB); System.out.println("\tNormal -> Normal: " + NORMAL2NORMAL_TX_PROB); System.out.println("Transaction edge addition threshold (proportion of SAR accounts):"); System.out.println("\tSAR -> SAR: " + SAR2SAR_EDGE_THRESHOLD); System.out.println("\tSAR -> Normal: " + SAR2NORMAL_EDGE_THRESHOLD); System.out.println("\tNormal -> SAR: " + NORMAL2SAR_EDGE_THRESHOLD); System.out.println("\tNormal -> Normal: " + NORMAL2NORMAL_EDGE_THRESHOLD); System.out.println("Transaction amount ratio:"); System.out.println("\tSAR -> SAR: " + SAR2SAR_AMOUNT_RATIO); System.out.println("\tSAR -> Normal: " + SAR2NORMAL_AMOUNT_RATIO); System.out.println("\tNormal -> SAR: " + NORMAL2SAR_AMOUNT_RATIO); System.out.println("\tNormal -> Normal: " + NORMAL2NORMAL_AMOUNT_RATIO); } /** * Generate an up to 10% ratio noise for the base transaction amount * @return Amount ratio [0.9, 1.1] */ public static float generateAmountRatio(){ // [0.9, 1.1] return rand.nextFloat() * 0.2F + 0.9F; } /** * Adjust transaction amount from the given accounts and the base amount * @param orig Originator account * @param bene Beneficiary account * @param baseAmount Base amount * @return Adjusted amount (If it should not make this transaction, return non-positive value) */ public static float adjustAmount(Account orig, Account bene, float baseAmount){ // Generate decentralized amount with up to 10% noise float amount = baseAmount * generateAmountRatio(); if(!isValid()){ return amount; } float ratio; float prob = rand.nextFloat(); if(orig.isSAR()){ // SAR originator if(bene.isSAR()){ // SAR -> SAR if(SAR2SAR_TX_PROB <= prob){ return 0.0F; } ratio = SAR2SAR_AMOUNT_RATIO; }else{ // SAR -> Normal if(SAR2NORMAL_TX_PROB <= prob){ return 0.0F; } ratio = SAR2NORMAL_AMOUNT_RATIO; } }else{ // Normal originator if(bene.isSAR()){ // Normal -> SAR if(NORMAL2SAR_TX_PROB <= prob){ return 0.0F; } ratio = NORMAL2SAR_AMOUNT_RATIO; }else{ // Normal -> Normal if(NORMAL2NORMAL_TX_PROB <= prob){ return 0.0F; } ratio = NORMAL2NORMAL_AMOUNT_RATIO; } prob = rand.nextFloat(); if(prob < NORMAL_HIGH_PROB){ // High-amount payment transaction (near to the upper limit) ratio *= NORMAL_HIGH_RATIO; }else if(prob < NORMAL_HIGH_PROB + NORMAL_LOW_PROB){ // Low-amount transaction ratio *= NORMAL_LOW_RATIO; }else if(prob < NORMAL_HIGH_PROB + NORMAL_LOW_PROB + NORMAL_SKIP_PROB){ return 0.0F; // Skip this transaction } } return amount * ratio; } /** * Determine whether the transaction edge should be actually added between the given accounts * @param orig Originator account * @param bene Beneficiary account * @return If the transaction should be actually added, return true. */ public static boolean shouldAddEdge(Account orig, Account bene){ if(!isValid()){ // It always adds this edge return true; } // Proportion of SAR beneficiary accounts of the originator account // float benePropThreshold = SAR2NORMAL_EDGE_THRESHOLD; // int beneNumThreshold = (int) Math.floor(1 / NORMAL2SAR_EDGE_THRESHOLD); int numNeighbors = orig.getBeneList().size(); float propSARBene = orig.getPropSARBene(); if(orig.isSAR()){ // SAR originator if(bene.isSAR()){ // SAR -> SAR return propSARBene >= SAR2SAR_EDGE_THRESHOLD; }else{ // SAR -> Normal // Allow edge creations if the ratio of SAR beneficiary accounts is enough large return propSARBene >= SAR2NORMAL_EDGE_THRESHOLD; } }else{ // Normal originator if(bene.isSAR()){ // Normal -> SAR // Create a transaction edge if the ratio of SAR beneficiary accounts is still large if(NORMAL2SAR_EDGE_THRESHOLD <= 0.0F){ return true; } return numNeighbors > (int) Math.floor(1 / NORMAL2SAR_EDGE_THRESHOLD) && propSARBene >= NORMAL2SAR_EDGE_THRESHOLD; }else{ // Normal -> Normal return propSARBene >= NORMAL2NORMAL_EDGE_THRESHOLD; } } } }
9,599
41.105263
116
java
AMLSim
AMLSim-master/src/main/java/amlsim/model/aml/AMLTypology.java
// Source: http://files.acams.org/pdfs/English_Study_Guide/Chapter_5.pdf // Suspicious transactions which may lead to money laundering // - Unusually high monthly balances in comparison to known sources of income. // - Unusually large deposits, deposits in round numbers or deposits in repeated amounts that are not attributable to legitimate sources of income. // - Multiple deposits made under reportable thresholds. // - The timing of deposits. This is particularly important when dates of illegal payments are known. // - Checks written for unusually large amounts (in relation to the suspect's known practices). // - A lack of account activity. This might indicate transactions in currency or the existence of other unknown bank accounts. // // Note: No specific bank models are used for this AML typology model class. package amlsim.model.aml; import amlsim.AMLSim; import amlsim.Account; import amlsim.Alert; import amlsim.model.AbstractTransactionModel; /** * Suspicious transaction models */ public abstract class AMLTypology extends AbstractTransactionModel { // Transaction model ID of AML typologies private static final int AML_FAN_OUT = 1; private static final int AML_FAN_IN = 2; private static final int CYCLE = 3; private static final int BIPARTITE = 4; private static final int STACK = 5; private static final int RANDOM = 6; private static final int SCATTER_GATHER = 7; // fan-out -> fan-in private static final int GATHER_SCATTER = 8; // fan-in -> fan-out // Transaction scheduling ID static final int FIXED_INTERVAL = 0; // All accounts send money in order with the same interval static final int RANDOM_INTERVAL = 1; // All accounts send money in order with random intervals static final int UNORDERED = 2; // All accounts send money randomly static final int SIMULTANEOUS = 3; // All transactions are performed at single step simultaneously final double marginRatio = AMLSim.getSimProp().getMarginRatio(); // Each member holds this ratio of the received amount /** * Create an AML typology object (alert transaction model) * @param modelID Alert transaction model ID as int * @param minAmount Minimum transaction amount * @param maxAmount Maximum transaction amount * @param startStep Start simulation step (all transactions will start after this step) * @param endStep End simulation step (all transactions will finish before this step) * @return AML typology model object */ public static AMLTypology createTypology(int modelID, double minAmount, double maxAmount, int startStep, int endStep) { AMLTypology model; switch(modelID){ case AML_FAN_OUT: model = new FanOutTypology(minAmount, maxAmount, startStep, endStep); break; case AML_FAN_IN: model = new FanInTypology(minAmount, maxAmount, startStep, endStep); break; case CYCLE: model = new CycleTypology(minAmount, maxAmount, startStep, endStep); break; case BIPARTITE: model = new BipartiteTypology(minAmount, maxAmount, startStep, endStep); break; case STACK: model = new StackTypology(minAmount, maxAmount, startStep, endStep); break; case RANDOM: model = new RandomTypology(minAmount, maxAmount, startStep, endStep); break; case SCATTER_GATHER: model = new ScatterGatherTypology(minAmount, maxAmount, startStep, endStep); break; case GATHER_SCATTER: model = new GatherScatterTypology(minAmount, maxAmount, startStep, endStep); break; default: throw new IllegalArgumentException("Unknown typology model ID: " + modelID); } model.setParameters(startStep, endStep); return model; } Alert alert; protected double minAmount; protected double maxAmount; protected long startStep; protected long endStep; /** * Set parameters (timestamps and amounts) of transactions * @param modelID Scheduling model ID */ public abstract void setParameters(int modelID); // /** // * Get the number of total transactions in this alert // * @return Number of transactions // */ // public abstract int getNumTransactions(); /** * Bind this alert transaction model to the alert * @param ag Alert object */ public void setAlert(Alert ag){ this.alert = ag; } /** * Whether the current simulation step is within the valid simulation step range * @param step Current simulation step * @return If the current step is within the valid simulation step range, return true */ public boolean isValidStep(long step){ return startStep <= step && step <= endStep; } public int getStepRange(){ return (int)(endStep - startStep + 1); } /** * Construct an AML typology with the given basic parameters * @param minAmount Minimum transaction amount (each transaction amount must not be lower than this value) * @param maxAmount Maximum transaction amount (each transaction amount must not be higher than this value) * @param startStep Start simulation step of alert transactions (any transactions cannot be carried out before this step) * @param endStep End simulation step of alert transactions (any transactions cannot be carried out after this step) */ public AMLTypology(double minAmount, double maxAmount, int startStep, int endStep){ this.minAmount = minAmount; this.maxAmount = maxAmount; this.startStep = startStep; this.endStep = endStep; } /** * Update the minimum transaction amount if the given amount is smaller than the current one * @param minAmount New minimum amount */ public void updateMinAmount(double minAmount) { this.minAmount = Math.min(this.minAmount, minAmount); } /** * Update the maximum transaction amount if the given amount is larger than the current one * @param maxAmount New maximum amount */ public void updateMaxAmount(double maxAmount) { this.maxAmount = Math.max(this.maxAmount, maxAmount); } public void updateStartStep(long startStep){ this.startStep = Math.min(this.startStep, startStep); } public void updateEndStep(long endStep){ this.endStep = Math.max(this.endStep, endStep); } /** * Generate a random amount * @return A random amount within "minAmount" and "maxAmount" */ double getRandomAmount(){ return alert.getSimulator().random.nextDouble() * (maxAmount - minAmount) + minAmount; } /** * Generate a random simulation step * @return Random simulation step within startStep and endStep */ long getRandomStep(){ return alert.getSimulator().random.nextLong(getStepRange()) + startStep; } /** * Generate a random simulation step from the given start and end steps * @param start Minimum simulation step * @param end Maximum simulation * @return Random simulation step within the given step range */ long getRandomStepRange(long start, long end){ if(start < startStep || endStep < end){ throw new IllegalArgumentException("The start and end steps must be within " + startStep + " and " + endStep); }else if(end < start){ throw new IllegalArgumentException("The start and end steps are unordered"); } long range = end - start; return alert.getSimulator().random.nextLong(range) + start; } @Override public String getModelName() { return "AMLTypology"; } // ??? // this is a no-op coming from SAR Account // this eventually should go away. // To Do Jordan D. Nelson public final void makeTransaction(long step) { } }
7,889
39.880829
147
java
AMLSim
AMLSim-master/src/main/java/amlsim/model/aml/BipartiteTypology.java
// // Note: No specific bank models are used for this AML typology model class. // package amlsim.model.aml; import amlsim.AMLSim; import amlsim.Account; import amlsim.TargetedTransactionAmount; import java.util.*; /** * Bipartite transaction model * Some accounts send money to a different account set */ public class BipartiteTypology extends AMLTypology { private Random random = AMLSim.getRandom(); @Override public void setParameters(int modelID) { } public BipartiteTypology(double minAmount, double maxAmount, int minStep, int maxStep) { super(minAmount, maxAmount, minStep, maxStep); } @Override public String getModelName() { return "BipartiteTypology"; } @Override public void sendTransactions(long step, Account acct) { List<Account> members = alert.getMembers(); // All members int last_orig_index = members.size() / 2; // The first half accounts are originators for (int i = 0; i < last_orig_index; i++) { Account orig = members.get(i); if (!orig.getID().equals(acct.getID())) { continue; } TargetedTransactionAmount transactionAmount = getTransactionAmount(members.size() - last_orig_index, orig.getBalance()); for (int j = last_orig_index; j < members.size(); j++) { Account bene = members.get(j); // The latter half accounts are beneficiaries makeTransaction(step, transactionAmount.doubleValue(), orig, bene); } } } private TargetedTransactionAmount getTransactionAmount(int numBene, double origBalance) { if (numBene == 0) { return new TargetedTransactionAmount(0, random); } return new TargetedTransactionAmount(origBalance / numBene, random); } }
1,871
28.25
112
java
AMLSim
AMLSim-master/src/main/java/amlsim/model/aml/CycleTypology.java
// // Note: No specific bank models are used for this AML typology model class. // package amlsim.model.aml; import amlsim.AMLSim; import amlsim.Account; import amlsim.TargetedTransactionAmount; import java.util.*; /** * Cycle transaction model */ public class CycleTypology extends AMLTypology { // Transaction schedule private long[] steps; // Array of simulation steps when each transaction is scheduled to be made private Random random = AMLSim.getRandom(); CycleTypology(double minAmount, double maxAmount, int startStep, int endStep){ super(minAmount, maxAmount, startStep, endStep); } /** * Define schedule of transaction * @param modelID Schedule model ID as integer */ public void setParameters(int modelID) { List<Account> members = alert.getMembers(); // All members int length = members.size(); // Number of members (total transactions) steps = new long[length]; int allStep = (int)AMLSim.getNumOfSteps(); int period = (int)(endStep - startStep); this.startStep = generateStartStep(allStep - period); // decentralize the first transaction step this.endStep = Math.min(this.startStep + period, allStep); if(modelID == FIXED_INTERVAL){ // Ordered, same interval period = (int)(endStep - startStep); if(length < period){ this.interval = period / length; // If there is enough number of available steps, make transaction with interval for(int i=0; i<length-1; i++){ steps[i] = startStep + interval * i; } steps[length-1] = endStep; }else{ this.interval = 1; long batch = length / period; // Because of too many transactions, make one or more transactions per step for(int i=0; i<length-1; i++){ steps[i] = startStep + i / batch; } steps[length-1] = endStep; } }else if(modelID == RANDOM_INTERVAL || modelID == UNORDERED){ // Random interval this.interval = 1; // Ensure the specified period steps[0] = startStep; steps[1] = endStep; for(int i=2; i<length; i++){ steps[i] = getRandomStep(); } if(modelID == RANDOM_INTERVAL){ Arrays.sort(steps); // Ordered } } // System.out.println(Arrays.toString(steps)); } // @Override // public int getNumTransactions() { // return alert.getMembers().size(); // The number of transactions is the same as the number of members // } @Override public String getModelName() { return "CycleTypology"; } /** * Create and add transactions * @param step Current simulation step */ @Override public void sendTransactions(long step, Account acct) { int length = alert.getMembers().size(); long alertID = alert.getAlertID(); boolean isSAR = alert.isSAR(); double amount = Double.MAX_VALUE; TargetedTransactionAmount transactionAmount; // Create cycle transactions for (int i = 0; i < length; i++) { if (steps[i] == step) { int j = (i + 1) % length; // i, j: index of the previous, next account Account src = alert.getMembers().get(i); // The previous account Account dst = alert.getMembers().get(j); // The next account if (src.getBalance() < amount) { amount = src.getBalance(); } transactionAmount = new TargetedTransactionAmount(amount, random); makeTransaction(step, transactionAmount.doubleValue(), src, dst, isSAR, alertID); // Update the next transaction amount double margin = amount * marginRatio; amount = amount - margin; } } } }
4,065
33.752137
128
java
AMLSim
AMLSim-master/src/main/java/amlsim/model/aml/FanInTypology.java
// // Note: No specific bank models are used for this AML typology model class. // package amlsim.model.aml; import amlsim.AMLSim; import amlsim.Account; import amlsim.TargetedTransactionAmount; import java.util.*; /** * Multiple accounts send money to the main account */ public class FanInTypology extends AMLTypology { // Originators and the main beneficiary private Account bene; // The destination (beneficiary) account private List<Account> origList = new ArrayList<>(); // The origin (originator) accounts private long[] steps; private static final int SIMULTANEOUS = 1; private static final int FIXED_INTERVAL = 2; private static final int RANDOM_RANGE = 3; private TargetedTransactionAmount transactionAmount; private Random random = AMLSim.getRandom(); FanInTypology(double minAmount, double maxAmount, int start, int end){ super(minAmount, maxAmount, start, end); } public void setParameters(int schedulingID){ // Set members List<Account> members = alert.getMembers(); Account mainAccount = alert.getMainAccount(); bene = mainAccount != null ? mainAccount : members.get(0); // The main account is the beneficiary for(Account orig : members){ // The rest of accounts are originators if(orig != bene) origList.add(orig); } // Set transaction schedule int numOrigs = origList.size(); int totalStep = (int)(endStep - startStep + 1); int defaultInterval = Math.max(totalStep / numOrigs, 1); this.startStep = generateStartStep(defaultInterval); // decentralize the first transaction step steps = new long[numOrigs]; if(schedulingID == SIMULTANEOUS){ long step = getRandomStep(); Arrays.fill(steps, step); }else if(schedulingID == FIXED_INTERVAL){ int range = (int)(endStep - startStep + 1); if(numOrigs < range){ interval = range / numOrigs; for(int i=0; i<numOrigs; i++){ steps[i] = startStep + interval*i; } }else{ long batch = numOrigs / range; for(int i=0; i<numOrigs; i++){ steps[i] = startStep + i/batch; } } }else if(schedulingID == RANDOM_RANGE){ for(int i=0; i<numOrigs; i++){ steps[i] = getRandomStep(); } } } // @Override // public int getNumTransactions() { // return alert.getMembers().size() - 1; // } @Override public String getModelName() { return "FanInTypology"; } public void sendTransactions(long step, Account acct){ long alertID = alert.getAlertID(); boolean isSAR = alert.isSAR(); for (int i = 0; i < origList.size(); i++) { if (steps[i] == step) { Account orig = origList.get(i); this.transactionAmount = new TargetedTransactionAmount(orig.getBalance(), this.random); makeTransaction(step, this.transactionAmount.doubleValue(), orig, bene, isSAR, alertID); } } } }
3,217
31.505051
106
java
AMLSim
AMLSim-master/src/main/java/amlsim/model/aml/FanOutTypology.java
// // Note: No specific bank models are used for this AML typology model class. // package amlsim.model.aml; import amlsim.AMLSim; import amlsim.Account; import amlsim.TargetedTransactionAmount; import java.util.*; /** * The main account distributes money to multiple members */ public class FanOutTypology extends AMLTypology { // Originator and beneficiary accounts private Account orig; private List<Account> beneList = new ArrayList<>(); private Random random = AMLSim.getRandom(); private long[] steps; FanOutTypology(double minAmount, double maxAmount, int minStep, int maxStep){ super(minAmount, maxAmount, minStep, maxStep); } public int getNumTransactions(){ return alert.getMembers().size() - 1; } public void setParameters(int scheduleID){ // Set members List<Account> members = alert.getMembers(); Account mainAccount = alert.getMainAccount(); orig = mainAccount != null ? mainAccount : members.get(0); for(Account bene : members){ if(orig != bene) beneList.add(bene); } // Set schedule int numBenes = beneList.size(); int totalStep = (int)(endStep - startStep + 1); int defaultInterval = Math.max(totalStep / numBenes, 1); this.startStep = generateStartStep(defaultInterval); // decentralize the first transaction step steps = new long[numBenes]; if(scheduleID == SIMULTANEOUS){ long step = getRandomStep(); Arrays.fill(steps, step); }else if(scheduleID == FIXED_INTERVAL){ int range = (int)(endStep - startStep + 1); if(numBenes < range){ interval = range / numBenes; for(int i=0; i<numBenes; i++){ steps[i] = startStep + interval*i; } }else{ long batch = numBenes / range; for(int i=0; i<numBenes; i++){ steps[i] = startStep + i/batch; } } }else if(scheduleID == RANDOM_INTERVAL || scheduleID == UNORDERED){ for(int i=0; i<numBenes; i++){ steps[i] = getRandomStep(); } } } @Override public String getModelName() { return "FanOutTypology"; } @Override public void sendTransactions(long step, Account acct) { if(!orig.getID().equals(acct.getID())){ return; } long alertID = alert.getAlertID(); boolean isSAR = alert.isSAR(); double amount = this.getTransactionAmount().doubleValue(); for (int i = 0; i < beneList.size(); i++) { if (steps[i] == step) { Account bene = beneList.get(i); makeTransaction(step, amount, orig, bene, isSAR, alertID); } } } private TargetedTransactionAmount getTransactionAmount() { if (this.beneList.size() == 0) { return new TargetedTransactionAmount(0, this.random); } return new TargetedTransactionAmount(orig.getBalance() / this.beneList.size(), random); } }
3,179
29.576923
105
java
AMLSim
AMLSim-master/src/main/java/amlsim/model/aml/GatherScatterTypology.java
package amlsim.model.aml; import amlsim.AMLSim; import amlsim.Account; import amlsim.TargetedTransactionAmount; import java.util.*; /** * Gather-Scatter transaction model (Multiple accounts -> fan-in -> main account -> fan-out -> multiple accounts) */ public class GatherScatterTypology extends AMLTypology { private List<Account> origAccts = new ArrayList<>(); private List<Account> beneAccts = new ArrayList<>(); private long[] gatherSteps; private long[] scatterSteps; private long middleStep; private double totalReceivedAmount = 0.0; private double scatterAmount = 0.0; // Scatter transaction amount will be defined after gather transactions private Random random = AMLSim.getRandom(); GatherScatterTypology(double minAmount, double maxAmount, int startStep, int endStep) { super(minAmount, maxAmount, startStep, endStep); } @Override public void setParameters(int modelID) { middleStep = (startStep + endStep) / 2; // System.out.println(startStep + " " + middleStep + " " + endStep); int numSubMembers = alert.getMembers().size() - 1; int numOrigMembers = numSubMembers / 2; int numBeneMembers = numSubMembers - numOrigMembers; gatherSteps = new long[numOrigMembers]; scatterSteps = new long[numBeneMembers]; Account mainAcct = alert.getMainAccount(); List<Account> subMembers = new ArrayList<>(); for (Account acct : alert.getMembers()){ if(acct != mainAcct){ subMembers.add(acct); } } assert(numSubMembers == subMembers.size()); for(int i=0; i<numSubMembers; i++){ Account acct = subMembers.get(i); if(i < numOrigMembers){ origAccts.add(acct); }else{ beneAccts.add(acct); } } // Ensure the specified period gatherSteps[0] = startStep; for(int i=1; i<numOrigMembers; i++){ gatherSteps[i] = getRandomStepRange(startStep, middleStep); } scatterSteps[0] = endStep; for(int i=1; i<numBeneMembers; i++){ scatterSteps[i] = getRandomStepRange(middleStep + 1, endStep); } } // @Override // public int getNumTransactions() { // return origAccts.size() + beneAccts.size(); // } @Override public void sendTransactions(long step, Account acct) { long alertID = alert.getAlertID(); boolean isSAR = alert.isSAR(); int numGathers = gatherSteps.length; int numScatters = scatterSteps.length; if(step <= middleStep){ for(int i=0; i<numGathers; i++){ if(gatherSteps[i] == step){ Account orig = origAccts.get(i); Account bene = alert.getMainAccount(); double amount = new TargetedTransactionAmount(orig.getBalance(), random).doubleValue(); makeTransaction(step, amount, orig, bene, isSAR, alertID); totalReceivedAmount += amount; } } }else{ for(int i=0; i<numScatters; i++){ if(scatterSteps[i] == step){ Account orig = alert.getMainAccount(); Account bene = beneAccts.get(i); double target = Math.min(orig.getBalance(), scatterAmount); TargetedTransactionAmount transactionAmount = new TargetedTransactionAmount(target, random); makeTransaction(step, transactionAmount.doubleValue(), orig, bene, isSAR, alertID); } } } if(step == middleStep){ // Define the amount of scatter transactions double margin = totalReceivedAmount * marginRatio; scatterAmount = (totalReceivedAmount - margin) / numScatters; } } @Override public String getModelName() { return "GatherScatterTypology"; } }
4,016
34.866071
113
java
AMLSim
AMLSim-master/src/main/java/amlsim/model/aml/RandomTypology.java
// // Note: No specific bank models are used for this AML typology model class. // package amlsim.model.aml; import amlsim.AMLSim; import amlsim.Account; import amlsim.TargetedTransactionAmount; import java.util.*; /** * The main account makes a transaction with one of the neighbor accounts * and the neighbor also makes transactions with its neighbors. * The beneficiary account and amount of each transaction are determined randomly. */ public class RandomTypology extends AMLTypology { private static Random random = AMLSim.getRandom(); private Set<Long> steps = new HashSet<>(); // Set of simulation steps when the transaction is performed private Account nextOrig; // Originator account for the next transaction @Override public void setParameters(int modelID) { int numMembers = alert.getMembers().size(); for(int i=0; i<numMembers; i++) { steps.add(getRandomStep()); } nextOrig = alert.getMainAccount(); } // @Override // public int getNumTransactions() { // return alert.getMembers().size(); // } RandomTypology(double minAmount, double maxAmount, int minStep, int maxStep) { super(minAmount, maxAmount, minStep, maxStep); } @Override public String getModelName() { return "RandomTypology"; } public boolean isValidStep(long step){ return super.isValidStep(step) && steps.contains(step); } public void sendTransactions(long step, Account acct){ boolean isSAR = alert.isSAR(); long alertID = alert.getAlertID(); if(!isValidStep(step))return; List<Account> beneList = nextOrig.getBeneList(); int numBenes = beneList.size(); if(numBenes == 0)return; int idx = random.nextInt(numBenes); Account bene = beneList.get(idx); TargetedTransactionAmount transactionAmount = new TargetedTransactionAmount(nextOrig.getBalance(), random); makeTransaction(step, transactionAmount.doubleValue(), nextOrig, bene, isSAR, (int)alertID); // Main account makes transactions to one of the neighbors nextOrig = bene; // The next originator account is the previous beneficiary account } }
2,228
31.779412
160
java
AMLSim
AMLSim-master/src/main/java/amlsim/model/aml/ScatterGatherTypology.java
package amlsim.model.aml; import amlsim.AMLSim; import amlsim.Account; import amlsim.TargetedTransactionAmount; import java.util.*; /** * Scatter-Gather transaction model (Main originator account -> fan-out -> multiple accounts -> fan-in -> single account) */ public class ScatterGatherTypology extends AMLTypology { private Account orig = null; // The first sender (main) account private Account bene = null; // The last beneficiary account private List<Account> intermediate = new ArrayList<>(); private long[] scatterSteps; private long[] gatherSteps; private double scatterAmount; private double gatherAmount; private Random random = AMLSim.getRandom(); ScatterGatherTypology(double minAmount, double maxAmount, int startStep, int endStep) { super(minAmount, maxAmount, startStep, endStep); } @Override public void setParameters(int modelID) { scatterAmount = maxAmount; double margin = scatterAmount * marginRatio; gatherAmount = Math.max(scatterAmount - margin, minAmount); orig = alert.getMainAccount(); for (Account acct : alert.getMembers()) { if (acct == orig) { continue; } if (bene == null) { bene = acct; } else { intermediate.add(acct); } } int size = alert.getMembers().size() - 2; scatterSteps = new long[size]; gatherSteps = new long[size]; long middleStep = (endStep + startStep) / 2; // Ensure the specified period scatterSteps[0] = startStep; gatherSteps[0] = endStep; for (int i = 1; i < size; i++) { scatterSteps[i] = getRandomStepRange(startStep, middleStep); gatherSteps[i] = getRandomStepRange(middleStep + 1, endStep); } } // @Override // public int getNumTransactions() { // int totalMembers = alert.getMembers().size(); // int midMembers = totalMembers - 2; // return midMembers * 2; // } @Override public void sendTransactions(long step, Account acct) { long alertID = alert.getAlertID(); boolean isSAR = alert.isSAR(); int numTotalMembers = alert.getMembers().size(); int numMidMembers = numTotalMembers - 2; for(int i=0; i<numMidMembers; i++){ if(scatterSteps[i] == step){ Account _bene = intermediate.get(i); double target = Math.min(orig.getBalance(), scatterAmount); TargetedTransactionAmount transactionAmount = new TargetedTransactionAmount(target, random); makeTransaction(step, transactionAmount.doubleValue(), orig, _bene, isSAR, alertID); }else if(gatherSteps[i] == step) { Account _orig = intermediate.get(i); double target = Math.min(_orig.getBalance(), scatterAmount); TargetedTransactionAmount transactionAmount = new TargetedTransactionAmount(target, random); makeTransaction(step, transactionAmount.doubleValue(), _orig, bene, isSAR, alertID); } } } @Override public String getModelName() { return "ScatterGatherTypology"; } }
3,278
33.515789
121
java
AMLSim
AMLSim-master/src/main/java/amlsim/model/aml/StackTypology.java
// // Note: No specific bank models are used for this AML typology model class. // package amlsim.model.aml; import java.util.Random; import amlsim.AMLSim; import amlsim.Account; import amlsim.TargetedTransactionAmount; /** * Stacked bipartite transactions */ public class StackTypology extends AMLTypology { private Random random = AMLSim.getRandom(); @Override public void setParameters(int modelID) { } // @Override // public int getNumTransactions() { // int total_members = alert.getMembers().size(); // int orig_members = total_members / 3; // First 1/3 accounts are originator accounts // int mid_members = orig_members; // Second 1/3 accounts are intermediate accounts // int bene_members = total_members - orig_members * 2; // Rest of accounts are beneficiary accounts // return orig_members * mid_members + mid_members + bene_members; // } StackTypology(double minAmount, double maxAmount, int minStep, int maxStep) { super(minAmount, maxAmount, minStep, maxStep); } @Override public String getModelName() { return "StackTypology"; } @Override public void sendTransactions(long step, Account acct) { int total_members = alert.getMembers().size(); int orig_members = total_members / 3; // First 1/3 accounts are originator accounts int mid_members = orig_members; // Second 1/3 accounts are intermediate accounts int bene_members = total_members - orig_members * 2; // Rest of accounts are beneficiary accounts for(int i=0; i<orig_members; i++){ // originator accounts --> Intermediate accounts Account orig = alert.getMembers().get(i); if(!orig.getID().equals(acct.getID())){ continue; } int numBene = (orig_members + mid_members) - orig_members; TargetedTransactionAmount transactionAmount = getTransactionAmount(numBene, orig.getBalance()); for (int j = orig_members; j < (orig_members + mid_members); j++) { Account bene = alert.getMembers().get(j); makeTransaction(step, transactionAmount.doubleValue(), orig, bene); } } for(int i=orig_members; i<(orig_members+mid_members); i++){ // Intermediate accounts --> Beneficiary accounts Account orig = alert.getMembers().get(i); if(!orig.getID().equals(acct.getID())){ continue; } int numBene = total_members - (orig_members + mid_members); TargetedTransactionAmount transactionAmount = getTransactionAmount(numBene, orig.getBalance()); for (int j = (orig_members + mid_members); j < total_members; j++) { Account bene = alert.getMembers().get(j); makeTransaction(step, transactionAmount.doubleValue(), orig, bene); } } } private TargetedTransactionAmount getTransactionAmount(int numBene, double origBalance) { if (numBene == 0) { return new TargetedTransactionAmount(0, random); } return new TargetedTransactionAmount(origBalance / numBene, random); } }
3,230
34.505495
119
java
AMLSim
AMLSim-master/src/main/java/amlsim/model/cash/CashInModel.java
package amlsim.model.cash; import amlsim.Branch; /** * Cash-in (deposit) model */ public class CashInModel extends CashModel { private static int NORMAL_INTERVAL = 1; private static int SUSPICIOUS_INTERVAL = 1; private static float NORMAL_MIN = 10; private static float NORMAL_MAX = 100; private static float SUSPICIOUS_MIN = 10; private static float SUSPICIOUS_MAX = 100; public static void setParam(int norm_int, int case_int, float norm_min, float norm_max, float case_min, float case_max){ NORMAL_INTERVAL = norm_int; SUSPICIOUS_INTERVAL = case_int; NORMAL_MIN = norm_min; NORMAL_MAX = norm_max; SUSPICIOUS_MIN = case_min; SUSPICIOUS_MAX = case_max; System.out.println("Norm: " + NORMAL_INTERVAL + " Case: " + SUSPICIOUS_INTERVAL); } private boolean isNextStep(long step){ return false; } private float computeAmount(){ if(this.account.isSAR()){ return SUSPICIOUS_MIN + rand.nextFloat() * (SUSPICIOUS_MAX - SUSPICIOUS_MIN); }else{ return NORMAL_MIN + rand.nextFloat() * (NORMAL_MAX - NORMAL_MIN); } } @Override public String getModelName() { return "CASH-IN"; } @Override public void makeTransaction(long step) { if(isNextStep(step)){ Branch branch = account.getBranch(); float amount = computeAmount(); makeTransaction(step, amount, account, branch, "CASH-IN"); } } }
1,527
27.830189
124
java
AMLSim
AMLSim-master/src/main/java/amlsim/model/cash/CashModel.java
package amlsim.model.cash; import amlsim.AMLSim; import amlsim.Account; import amlsim.model.AbstractTransactionModel; import java.util.Random; /** * Cash transaction model (between an account and a deposit account) * There are two subclasses: CashInModel (deposit) and CashOutModel (withdrawal) */ public abstract class CashModel extends AbstractTransactionModel { protected static Random rand = AMLSim.getRandom(); // needed for cash accounts temporarily protected Account account; protected double[] randValues; // Random values to generate transaction amounts protected static final int randSize = 10; // Number of random values to be stored public void setAccount(Account account) { this.account = account; } public CashModel(){ randValues = new double[randSize]; for(int i = 0; i< randSize; i++){ randValues[i] = rand.nextGaussian(); // from -1.0 to 1.0 } } // to satisfy interface public void sendTransactions(long step, Account acct) { } // Abstract methods from TransactionModel public abstract String getModelName(); // Get transaction type description public abstract void makeTransaction(long step); // Create and add transactions }
1,267
28.488372
86
java
AMLSim
AMLSim-master/src/main/java/amlsim/model/cash/CashOutModel.java
package amlsim.model.cash; import amlsim.Branch; /** * Cash-out (withdrawal) model */ public class CashOutModel extends CashModel { private static int NORMAL_INTERVAL = 1; private static int SUSPICIOUS_INTERVAL = 1; private static float NORMAL_MIN = 10; private static float NORMAL_MAX = 100; private static float SUSPICIOUS_MIN = 10; private static float SUSPICIOUS_MAX = 100; public static void setParam(int norm_int, int case_int, float norm_min, float norm_max, float case_min, float case_max){ NORMAL_INTERVAL = norm_int; SUSPICIOUS_INTERVAL = case_int; NORMAL_MIN = norm_min; NORMAL_MAX = norm_max; SUSPICIOUS_MIN = case_min; SUSPICIOUS_MAX = case_max; } private boolean isNextStep(long step){ return false; } private float computeAmount(){ if(this.account.isSAR()){ return SUSPICIOUS_MIN + rand.nextFloat() * (SUSPICIOUS_MAX - SUSPICIOUS_MIN); }else{ return NORMAL_MIN + rand.nextFloat() * (NORMAL_MAX - NORMAL_MIN); } } @Override public String getModelName() { return "CASH-OUT"; } @Override public void makeTransaction(long step) { // List<AMLTransaction> txs = new ArrayList<>(); if(isNextStep(step)){ Branch branch = account.getBranch(); float amount = computeAmount(); makeTransaction(step, amount, branch, account, "CASH-OUT"); } } }
1,500
27.320755
124
java
AMLSim
AMLSim-master/src/main/java/amlsim/model/normal/EmptyModel.java
package amlsim.model.normal; import java.util.Random; import amlsim.Account; import amlsim.AccountGroup; import amlsim.model.AbstractTransactionModel; /** * Empty transaction model (It does not make any transactions) * Used when invalid model IDs are specified */ public class EmptyModel extends AbstractTransactionModel { public EmptyModel( AccountGroup accountGroup, Random random ) { } @Override public String getModelName() { return "Default"; } @Override public void sendTransactions(long step, Account origAccount) { // Do nothing in default } }
629
19.322581
66
java
AMLSim
AMLSim-master/src/main/java/amlsim/model/normal/FanInTransactionModel.java
package amlsim.model.normal; import amlsim.Account; import amlsim.AccountGroup; import amlsim.TargetedTransactionAmount; import amlsim.model.AbstractTransactionModel; import java.util.*; /** * Receive money from one of the senders (fan-in) */ public class FanInTransactionModel extends AbstractTransactionModel { private int index = 0; private Random random; private TargetedTransactionAmount transactionAmount; public FanInTransactionModel( AccountGroup accountGroup, Random random ) { this.accountGroup = accountGroup; this.random = random; } public void setParameters(int interval, long start, long end){ super.setParameters(interval, start, end); if(this.startStep < 0){ // decentralize the first transaction step this.startStep = generateStartStep(interval); } } @Override public String getModelName() { return "FanIn"; } private boolean isValidStep(long step){ return (step - startStep) % interval == 0; } @Override public void sendTransactions(long step, Account account) { List<Account> beneList = account.getBeneList(); // Destination accounts int numOrigs = beneList.size(); if (!isValidStep(step) || numOrigs == 0) { return; } if (index >= numOrigs) { index = 0; } this.transactionAmount = new TargetedTransactionAmount(account.getBalance(), this.random); double amount = this.transactionAmount.doubleValue(); Account bene = beneList.get(index); makeTransaction(step, amount, account, bene); index++; } }
1,702
25.2
98
java
AMLSim
AMLSim-master/src/main/java/amlsim/model/normal/FanOutTransactionModel.java
package amlsim.model.normal; import amlsim.*; import amlsim.model.AbstractTransactionModel; import java.util.*; /** * Distribute money to multiple neighboring accounts (fan-out) */ public class FanOutTransactionModel extends AbstractTransactionModel { private int index = 0; private Random random; private TargetedTransactionAmount transactionAmount; public FanOutTransactionModel( AccountGroup accountGroup, Random random ) { this.accountGroup = accountGroup; this.random = random; } public void setParameters(int interval, long start, long end){ super.setParameters(interval, start, end); if(this.startStep < 0){ // decentralize the first transaction step this.startStep = generateStartStep(interval); } } @Override public String getModelName() { return "FanOut"; } private boolean isValidStep(long step){ return (step - startStep) % interval == 0; } @Override public void sendTransactions(long step, Account account) { List<Account> beneList = account.getBeneList(); // Destination accounts int numBene = beneList.size(); if (!isValidStep(step) || numBene == 0) { // No more destination accounts return; } if (index >= numBene) { index = 0; } this.transactionAmount = new TargetedTransactionAmount(account.getBalance(), random); double amount = this.transactionAmount.doubleValue(); Account bene = beneList.get(index); if (amount > 0) { this.makeTransaction(step, amount, account, bene); } index++; } }
1,707
25.6875
93
java
AMLSim
AMLSim-master/src/main/java/amlsim/model/normal/ForwardTransactionModel.java
package amlsim.model.normal; import amlsim.Account; import amlsim.AccountGroup; import amlsim.TargetedTransactionAmount; import amlsim.model.AbstractTransactionModel; import java.util.*; /** * Send money received from an account to another account in a similar way */ public class ForwardTransactionModel extends AbstractTransactionModel { private int index = 0; private Random random; public ForwardTransactionModel( AccountGroup accountGroup, Random random ) { this.accountGroup = accountGroup; this.random = random; } public void setParameters(int interval, long start, long end){ super.setParameters(interval, start, end); if(this.startStep < 0){ // decentralize the first transaction step this.startStep = generateStartStep(interval); } } @Override public String getModelName() { return "Forward"; } @Override public void sendTransactions(long step, Account account) { TargetedTransactionAmount transactionAmount = new TargetedTransactionAmount(account.getBalance(), random); List<Account> dests = account.getBeneList(); int numDests = dests.size(); if(numDests == 0){ return; } if((step - startStep) % interval != 0){ return; } if(index >= numDests){ index = 0; } Account dest = dests.get(index); this.makeTransaction(step, transactionAmount.doubleValue(), account, dest); index++; } }
1,574
25.25
114
java
AMLSim
AMLSim-master/src/main/java/amlsim/model/normal/MutualTransactionModel.java
package amlsim.model.normal; import amlsim.*; import amlsim.model.AbstractTransactionModel; import java.util.List; import java.util.Random; /** * Return money to one of the previous senders */ public class MutualTransactionModel extends AbstractTransactionModel { private Random random; public MutualTransactionModel( AccountGroup accountGroup, Random random ) { this.accountGroup = accountGroup; this.random = random; } public void setParameters(int interval, long start, long end){ super.setParameters(interval, start, end); if(this.startStep < 0){ // decentralize the first transaction step this.startStep = generateStartStep(interval); } } @Override public String getModelName() { return "Mutual"; } @Override public void sendTransactions(long step, Account account) { if((step - this.startStep) % interval != 0)return; Account counterpart = account.getPrevOrig(); if(counterpart == null){ List<Account> origs = account.getOrigList(); if(origs.isEmpty()) { return; }else{ counterpart = origs.get(0); } } TargetedTransactionAmount transactionAmount = new TargetedTransactionAmount(account.getBalance(), random); if(!account.getBeneList().contains(counterpart)) { account.addBeneAcct(counterpart); // Add a new destination } makeTransaction(step, transactionAmount.doubleValue(), account, counterpart); } }
1,607
26.254237
114
java
AMLSim
AMLSim-master/src/main/java/amlsim/model/normal/PeriodicalTransactionModel.java
package amlsim.model.normal; import java.util.Random; import amlsim.Account; import amlsim.AccountGroup; import amlsim.TargetedTransactionAmount; import amlsim.model.AbstractTransactionModel; /** * Send money to neighbors periodically */ public class PeriodicalTransactionModel extends AbstractTransactionModel { private int index = 0; private Random random; public PeriodicalTransactionModel( AccountGroup accountGroup, Random random ) { this.accountGroup = accountGroup; this.random = random; } public void setParameters(int interval, long start, long end){ super.setParameters(interval, start, end); if(this.startStep < 0){ // decentralize the first transaction step this.startStep = generateStartStep(interval); } } @Override public String getModelName() { return "Periodical"; } private boolean isValidStep(long step){ return (step - startStep) % interval == 0; } @Override public void sendTransactions(long step, Account account) { if(!isValidStep(step) || account.getBeneList().isEmpty()){ return; } int numDests = account.getBeneList().size(); if(index >= numDests){ index = 0; } int totalCount = getNumberOfTransactions(); // Total number of transactions int eachCount = (numDests < totalCount) ? 1 : numDests / totalCount; TargetedTransactionAmount transactionAmount = new TargetedTransactionAmount(account.getBalance() / eachCount, random); for (int i = 0; i < eachCount; i++) { Account dest = account.getBeneList().get(index); this.makeTransaction(step, transactionAmount.doubleValue(), account, dest); index++; if (index >= numDests) break; } index = 0; } }
1,909
26.681159
126
java
AMLSim
AMLSim-master/src/main/java/amlsim/model/normal/SingleTransactionModel.java
package amlsim.model.normal; import amlsim.AMLSim; import amlsim.Account; import amlsim.AccountGroup; import amlsim.TargetedTransactionAmount; import amlsim.model.AbstractTransactionModel; import java.util.List; import java.util.Random; /** * Send money only for once to one of the neighboring accounts regardless the transaction interval parameter */ public class SingleTransactionModel extends AbstractTransactionModel { /** * Simulation step when this transaction is done */ private long txStep = -1; private Random random; public SingleTransactionModel( AccountGroup accountGroup, Random random ) { this.random = random; this.accountGroup = accountGroup; } public String getModelName(){ return "Single"; } public void setParameters(int interval, long start, long end){ super.setParameters(interval, start, end); if(this.startStep < 0){ // Unlimited start step this.startStep = 0; } if(this.endStep < 0){ // Unlimited end step this.endStep = AMLSim.getNumOfSteps(); } // The transaction step is determined randomly within the given range of steps this.txStep = this.startStep + this.random.nextInt((int)(endStep - startStep + 1)); } public void sendTransactions(long step, Account account){ List<Account> beneList = account.getBeneList(); int numBene = beneList.size(); if(step != this.txStep || numBene == 0){ return; } TargetedTransactionAmount transactionAmount = new TargetedTransactionAmount(account.getBalance(), random); int index = this.random.nextInt(numBene); Account dest = beneList.get(index); this.makeTransaction(step, transactionAmount.doubleValue(), account, dest); } }
1,865
29.590164
114
java
AMLSim
AMLSim-master/src/main/java/amlsim/stat/Diameter.java
package amlsim.stat; import java.io.*; import java.util.*; import it.unimi.dsi.webgraph.*; import it.unimi.dsi.webgraph.algo.HyperBall; /** * Compute diameter and average distance of the transaction graph */ public class Diameter { private ArrayListMutableGraph graph; // Transaction graph (WebGraph) private Map<String, Integer> id2idx; // Account ID --> Index of Graph private Map<Integer, Set<Integer>> adj; // Adjacency set (account index --> neighbor account index) public Diameter(int numAccounts){ this.graph = new ArrayListMutableGraph(numAccounts); this.id2idx = new HashMap<>(numAccounts); this.adj = new HashMap<>(numAccounts); } /** * Add an edge to the internal transaction graph * @param srcID source account ID * @param dstID destination account ID */ // public void addEdge(long srcID, long dstID){ public void addEdge(String srcID, String dstID){ if(!id2idx.containsKey(srcID)){ int idx = id2idx.size(); id2idx.put(srcID, idx); adj.put(idx, new HashSet<>()); } if(!id2idx.containsKey(dstID)){ int idx = id2idx.size(); id2idx.put(dstID, idx); adj.put(idx, new HashSet<>()); } int srcIdx = id2idx.get(srcID); int dstIdx = id2idx.get(dstID); if(!adj.get(srcIdx).contains(dstIdx)) { // If this edge is not yet added, add it graph.addArc(srcIdx, dstIdx); adj.get(srcIdx).add(dstIdx); } } /** * Compute diameter and average length with HyperANF * @return Diameter and average length as an array of double values */ public double[] computeDiameter(){ int log2m = 10; // Register length exponent: it affects elapsed time, memory consumption and precision) int th = 4; // Number of threads int maxDistance = 50; // Limit of distance double aver = 0.0; double[] result = new double[2]; try { ImmutableGraph g = graph.immutableView(); HyperBall hyperanf = new HyperBall(g, null, log2m, null, th, 0, 0, false); hyperanf.init(); int connectedNodes = g.numNodes(); long start = System.currentTimeMillis(); int prev = connectedNodes; for(int i=0; i<maxDistance; i++){ hyperanf.iterate(); int mod = hyperanf.modified(); int num = prev - mod; if(i == 0){ connectedNodes -= num; }else{ aver += i * (double)num / connectedNodes; } // System.out.println("Step:" + i + " Average Distance:" + aver); prev = mod; if(mod == 0){ // reached all vertices System.out.println("Diameter: " + i); result[0] = i; break; } } System.out.println("Average Distance: " + aver); result[1] = aver; hyperanf.close(); long end = System.currentTimeMillis(); System.out.println("Elapsed Time: " + (end - start)/1000 + "s"); return result; } catch (IOException e) { System.err.println("Cannot load and compute graph data"); e.printStackTrace(); return null; } } public static void main(String[] args) throws IOException{ int num_accts = Integer.parseInt(args[0]); String tx_csv = args[1]; List<List<Integer>> srcs = new ArrayList<>(); List<List<Integer>> dsts = new ArrayList<>(); int num_bins = 16; for(int i=0; i<num_bins; i++){ srcs.add(new ArrayList<>()); dsts.add(new ArrayList<>()); } System.out.println("Load Transaction List"); String line; String[] data; BufferedReader br = new BufferedReader(new FileReader(tx_csv)); br.readLine(); while((line = br.readLine()) != null){ data = line.split(","); int src = Integer.parseInt(data[1]); int dst = Integer.parseInt(data[2]); int tm = Integer.parseInt(data[6]); int bin = tm / 10; srcs.get(bin).add(src); dsts.get(bin).add(dst); } System.out.println("Compute Diameter"); Diameter diameter = new Diameter(num_accts); for(int i=0; i<num_bins; i++){ int tm = i * 10; List<Integer> src_list = srcs.get(i); List<Integer> dst_list = dsts.get(i); int num_edges = src_list.size(); for(int j=0; j<num_edges; j++){ String src = String.valueOf(src_list.get(j)); String dst = String.valueOf(dst_list.get(j)); diameter.addEdge(src, dst); } double[] ret = diameter.computeDiameter(); System.out.println(tm + "," + ret[0] + "," + ret[1]); } } }
5,087
32.695364
112
java
AMLSim
AMLSim-master/src/test/java/amlsim/AccountTests.java
package amlsim; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.BeforeEach; import amlsim.model.ModelParameters; import amlsim.model.normal.SingleTransactionModel; import sim.engine.Schedule; import java.util.Random; import java.util.logging.Logger; import org.mockito.MockedStatic; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.never; import static org.mockito.Mockito.when; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; // How to mock static // try (MockedStatic<AMLSim> mocked = mockStatic(AMLSim.class)) { // mocked.when(AMLSim::getRandom).thenReturn(new Random(1)); class AccountTests { public Schedule schedule; public AMLSim amlSim; public SimProperties simProperties; public Random random; @BeforeEach void beforeEach() { this.schedule = mock(Schedule.class); this.amlSim = mock(AMLSim.class); this.amlSim.schedule = this.schedule; this.simProperties = mock(SimProperties.class); this.random = new Random(1); } @Test void zeroSteps() { long step = 0; when(this.schedule.getSteps()).thenReturn(step); try (MockedStatic<AMLSim> mocked = mockStatic(AMLSim.class)) { mocked.when(AMLSim::getRandom).thenReturn(new Random(1)); Account anAccount = new Account("1", 5, 1000.0f, "bankid", this.random); anAccount.handleAction(amlSim); mocked.verify(() -> AMLSim.handleTransaction(1, "TRANSFER", 1000.0f, anAccount, anAccount, false, 1), never()); } } @Test void SingleTransactionModelBenefitListZero() { long step = 1; when(this.schedule.getSteps()).thenReturn(step); Account anAccount = new Account("1", 5, 1000.0f, "bankid", this.random); Account beneAccount = new Account("2", 5, 1000.0f, "bankid", this.random); try (MockedStatic<AMLSim> mocked = mockStatic(AMLSim.class)) { mocked.when(AMLSim::getRandom).thenReturn(new Random(1)); anAccount.handleAction(amlSim); mocked.verify(() -> AMLSim.handleTransaction(1L, "TRANSFER", 3.0, anAccount, beneAccount, false, -1L), never()); } } @Test public void SingleTransactionModelBenefitListExists() { long step = 1; when(this.schedule.getSteps()).thenReturn(step); try (MockedStatic<AMLSim> mocked = mockStatic(AMLSim.class); MockedStatic<ModelParameters> mockey = mockStatic(ModelParameters.class) ) { SimProperties mockedProperties = mock(SimProperties.class); when(mockedProperties.getMaxTransactionAmount()).thenReturn(100.0); mocked.when(AMLSim::getRandom).thenReturn(new Random(1)); mocked.when(AMLSim::getSimProp).thenReturn( mockedProperties ); mocked.when(AMLSim::getLogger).thenReturn( Logger.getLogger("AMLSim") ); mockey.when(() -> ModelParameters.shouldAddEdge(any(), any())).thenReturn(true); Account anAccount = new Account("1", 5, 1000.0f, "bankid", this.random); Account beneAccount = new Account("2", 5, 1000.0f, "bankid", this.random); anAccount.addBeneAcct(beneAccount); anAccount.addTxType(beneAccount, "TRANSFER"); AccountGroup accountGroup = new AccountGroup(1, this.amlSim); accountGroup.addMember(anAccount); accountGroup.addMember(beneAccount); accountGroup.setMainAccount(anAccount); SingleTransactionModel model = new SingleTransactionModel(accountGroup, this.random); model.setParameters(30, 1, 1); accountGroup.setModel( model ); anAccount.accountGroups.add(accountGroup); anAccount.handleAction(amlSim); mocked.verify(() -> AMLSim.handleTransaction(1L, "TRANSFER", 41.00808114922017d, anAccount, beneAccount, false, -1L), times(1)); } } @Test public void SingleTransactionModelHasBenesNotMain() { long step = 1; when(this.schedule.getSteps()).thenReturn(step); try (MockedStatic<AMLSim> mocked = mockStatic(AMLSim.class); MockedStatic<ModelParameters> mockey = mockStatic(ModelParameters.class) ) { SimProperties mockedProperties = mock(SimProperties.class); when(mockedProperties.getMaxTransactionAmount()).thenReturn(100.0); mocked.when(AMLSim::getRandom).thenReturn(new Random(1)); mocked.when(AMLSim::getSimProp).thenReturn( mockedProperties ); mocked.when(AMLSim::getLogger).thenReturn( Logger.getLogger("AMLSim") ); mockey.when(() -> ModelParameters.shouldAddEdge(any(), any())).thenReturn(true); Account anAccount = new Account("1", 5, 1000.0f, "bankid", this.random); Account beneAccount = new Account("2", 5, 1000.0f, "bankid", this.random); anAccount.addBeneAcct(beneAccount); anAccount.addTxType(beneAccount, "TRANSFER"); AccountGroup accountGroup = new AccountGroup(1, this.amlSim); accountGroup.addMember(anAccount); accountGroup.addMember(beneAccount); accountGroup.setMainAccount(beneAccount); SingleTransactionModel model = new SingleTransactionModel(accountGroup, this.random); model.setParameters(30, 1, 1); accountGroup.setModel( model ); anAccount.accountGroups.add(accountGroup); anAccount.handleAction(amlSim); mocked.verify(() -> AMLSim.handleTransaction(1L, "TRANSFER", 41.00808114922017d, anAccount, beneAccount, false, -1L), never()); } } }
6,072
33.902299
140
java
AMLSim
AMLSim-master/src/test/java/amlsim/TargetedTransactionAmountTests.java
package amlsim; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import java.util.Random; import org.junit.jupiter.api.BeforeEach; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.when; public class TargetedTransactionAmountTests { public Random random; @BeforeEach void beforeEach() { this.random = new Random(1); } @Test void testTargetIsMin() { SimProperties mockedSimProperties = mock(SimProperties.class); when(mockedSimProperties.getMinTransactionAmount()).thenReturn(100.0); when(mockedSimProperties.getMaxTransactionAmount()).thenReturn(200.0); try (MockedStatic<AMLSim> mocked = mockStatic(AMLSim.class)) { mocked.when(AMLSim::getSimProp).thenReturn(mockedSimProperties); TargetedTransactionAmount transactionAmount = new TargetedTransactionAmount(100.0, this.random); assertEquals(100.0, transactionAmount.doubleValue()); } } @Test void testTargetIsMid() { SimProperties mockedSimProperties = mock(SimProperties.class); when(mockedSimProperties.getMinTransactionAmount()).thenReturn(100.0); when(mockedSimProperties.getMaxTransactionAmount()).thenReturn(200.0); try (MockedStatic<AMLSim> mocked = mockStatic(AMLSim.class)) { mocked.when(AMLSim::getSimProp).thenReturn(mockedSimProperties); TargetedTransactionAmount transactionAmount = new TargetedTransactionAmount(150.0, this.random); assertEquals(150.0, transactionAmount.doubleValue()); } } @Test void testTargetIsMidWideRange() { SimProperties mockedSimProperties = mock(SimProperties.class); when(mockedSimProperties.getMinTransactionAmount()).thenReturn(100.0); when(mockedSimProperties.getMaxTransactionAmount()).thenReturn(4000.0); try (MockedStatic<AMLSim> mocked = mockStatic(AMLSim.class)) { mocked.when(AMLSim::getSimProp).thenReturn(mockedSimProperties); TargetedTransactionAmount transactionAmount = new TargetedTransactionAmount(300.0, this.random); assertTrue(transactionAmount.doubleValue() <= 300.0); assertTrue(transactionAmount.doubleValue() >= 100.0); } } @Test void testTargetIsBelowMin() { SimProperties mockedSimProperties = mock(SimProperties.class); when(mockedSimProperties.getMinTransactionAmount()).thenReturn(100.0); when(mockedSimProperties.getMaxTransactionAmount()).thenReturn(4000.0); try (MockedStatic<AMLSim> mocked = mockStatic(AMLSim.class)) { mocked.when(AMLSim::getSimProp).thenReturn(mockedSimProperties); TargetedTransactionAmount transactionAmount = new TargetedTransactionAmount(40.0, this.random); assertEquals(40.0, transactionAmount.doubleValue()); } } }
3,097
35.880952
108
java
empathic-jason
empathic-jason-master/argumentationServer/src/main/java/argumentation/ArgumentationServer.java
package main.java.argumentation; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Collection; import java.util.Collections; import com.google.gson.*; import fi.iki.elonen.NanoHTTPD; import net.sf.tweety.arg.dung.reasoner.AbstractExtensionReasoner; import net.sf.tweety.arg.dung.reasoner.SimpleCompleteReasoner; import net.sf.tweety.arg.dung.reasoner.SimpleGroundedReasoner; import net.sf.tweety.arg.dung.reasoner.SimpleIdealReasoner; import net.sf.tweety.arg.dung.reasoner.SimplePreferredReasoner; import net.sf.tweety.arg.dung.reasoner.SimpleStableReasoner; import net.sf.tweety.arg.dung.reasoner.SimpleSemiStableReasoner; import net.sf.tweety.arg.dung.semantics.Extension; import net.sf.tweety.arg.dung.syntax.Argument; import net.sf.tweety.arg.dung.syntax.Attack; import net.sf.tweety.arg.dung.syntax.DungTheory; import net.sf.tweety.logics.pl.sat.Sat4jSolver; import net.sf.tweety.logics.pl.sat.SatSolver; public class ArgumentationServer extends NanoHTTPD { JsonParser parser = new JsonParser(); public ArgumentationServer() throws IOException { super(8080); start(NanoHTTPD.SOCKET_READ_TIMEOUT, false); System.out.println("\nRunning! Point your browsers to http://localhost:8080/ \n"); } public static void main(String[] args) { try { new ArgumentationServer(); } catch (IOException ioe) { System.err.println("Couldn't start server:\n" + ioe); } } private enum ExtensionType { complete, ground, ideal, stable, semiStable, preferred; } private static Collection<Extension> getExtensions (String sExtensionType, DungTheory theory) { if(sExtensionType == null) { sExtensionType = "ideal"; } System.out.println("Extension type: " + sExtensionType); ExtensionType extensionType = ExtensionType.valueOf(sExtensionType); switch (extensionType) { case complete: return new SimpleCompleteReasoner().getModels(theory); case ground: return new SimpleGroundedReasoner().getModels(theory); case preferred: return new SimplePreferredReasoner().getModels(theory); case stable: return new SimpleStableReasoner().getModels(theory); case semiStable: return new SimpleSemiStableReasoner().getModels(theory); case ideal: default: Collection<Extension> preferredExtensions = new SimplePreferredReasoner().getModels(theory); Extension idealExtension = new Extension(); Extension preferredExtension = preferredExtensions.iterator().next(); for (Argument arg : preferredExtension) { Boolean isIdeal = true; for (Extension ext : preferredExtensions) { if(!ext.contains(arg)) { isIdeal = false; break; } } if(isIdeal) { idealExtension.add(arg); } } Collection<Extension> idealExtensions = Collections.singletonList(idealExtension); return idealExtensions; } } @Override public Response serve(IHTTPSession session) { DungTheory theory = new DungTheory(); Map<String, String> params = session.getParms(); String extensionType = params.remove("extensionType"); Map<String, Argument> arguments = new HashMap<>(); for (Map.Entry<String, String> param : params.entrySet()) { String argumentId = param.getKey(); System.out.println("Creating argument: " + argumentId); arguments.put(argumentId, new Argument(argumentId)); theory.add(arguments.get(argumentId)); } for (Map.Entry<String, String> param : params.entrySet()) { String argumentId = param.getKey(); System.out.println("Launching attacks for argument: " + argumentId); JsonArray jAttacks = parser.parse(param.getValue()).getAsJsonArray(); for (JsonElement jAttackedArg : jAttacks) { String attackedArg = jAttackedArg.getAsString(); System.out.println("Attacking: " + attackedArg); theory.add(new Attack(arguments.get(argumentId), arguments.get(attackedArg))); } } System.out.println(theory); System.out.println(); SatSolver.setDefaultSolver(new Sat4jSolver()); System.out.println("Extension type: " + extensionType); Collection<Extension> extensions = getExtensions(extensionType, theory); System.out.println("Extensions, type " + extensionType + ": " + extensions); JsonArray jExtensions = new JsonArray(); for (Extension extension : extensions) { JsonArray jExtension = new JsonArray(); for (Argument argument : extension) { jExtension.add(argument.toString()); } jExtensions.add(jExtension); } System.out.println("Extensions, type " + extensionType + ": " + extensions); return newFixedLengthResponse(jExtensions.toString()); } }
5,386
40.122137
108
java
empathic-jason
empathic-jason-master/argumentationServer/src/test/java/argumentation/AppTest.java
package argumentation; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( AppTest.class ); } /** * Rigourous Test :-) */ public void testApp() { assertTrue( true ); } }
641
15.461538
46
java
empathic-jason
empathic-jason-master/src/empathy/solve_argument.java
// Internal action code for project empathic_example.mas2j package empathy; import jason.*; import jason.asSemantics.*; import jason.asSyntax.*; import org.apache.http.*; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.client.utils.URIBuilder; import org.apache.http.client.methods.*; import com.google.gson.*; import java.util.List; public class solve_argument extends DefaultInternalAction { @Override public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception { // execute the internal action HttpClient client = new DefaultHttpClient(); URIBuilder builder = new URIBuilder("http://localhost:8080"); JsonParser parser = new JsonParser(); ListTerm tArguments = (ListTerm) args[0]; Term handoverArg = args[1]; // construct request ListTerm tValidArgumentNames = ListTermImpl.parseList("[]"); for (Term tArgument : tArguments) { ListTerm tExtension = (ListTerm) tArgument; List<Term> lExtension = tExtension.getAsList(); String argName = lExtension.get(0).toString() .replaceAll("^\"|\"$", "") .replaceAll("\"", "\\\""); System.out.println(argName); tValidArgumentNames.append(lExtension.get(0)); lExtension.remove(0); String arguments = tExtension.get(1).toString(); builder.setParameter(argName, arguments); } ts.getAg().getLogger().info("executing internal action 'empathy.solve_argument'"); if (false) { // just to show how to throw another kind of exception throw new JasonException("not implemented!"); } HttpGet request = new HttpGet(builder.build()); ResponseHandler<String> handler = new BasicResponseHandler(); // send request and handle response HttpResponse response = client.execute(request); System.out.println("Response code: " + response.getStatusLine().getStatusCode()); String body = handler.handleResponse(response); System.out.println("Response body: " + body); JsonArray jBody = parser.parse(body).getAsJsonArray(); ListTerm tCompleteExtensions = ListTermImpl.parseList("[]"); for (JsonElement jArgs : jBody) { ListTerm tExtension = ListTermImpl.parseList("[]"); for (JsonElement jArg : jArgs.getAsJsonArray()) { StringTerm tArg = StringTermImpl.parseString(jArg.toString()); tExtension.append(tArg); } tCompleteExtensions.append(tExtension); } for (Term tExtension : tCompleteExtensions) { for (Term arg : (ListTerm) tExtension) { tValidArgumentNames.remove(arg); } } return un.unifies(tValidArgumentNames, handoverArg); } }
3,086
38.075949
90
java
graphql-server-benchmark
graphql-server-benchmark-master/Java/springboot-graphql-java/src/main/java/com/github/graphql/server/benchmark/springboot/Application.java
/* * Copyright 2019 Red Hat, Inc. * * Red Hat licenses this file to you 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 com.github.graphql.server.benchmark.springboot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
952
31.862069
76
java
graphql-server-benchmark
graphql-server-benchmark-master/Java/springboot-graphql-java/src/main/java/com/github/graphql/server/benchmark/springboot/Author.java
/* * Copyright 2019 Red Hat, Inc. * * Red Hat licenses this file to you 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 com.github.graphql.server.benchmark.springboot; public class Author { private Integer id; private String firstName; private String lastName; private String bio; public Author(Integer id, String firstName, String lastName, String bio) { this.id = id; this.firstName = firstName; this.lastName = lastName; this.bio = bio; } public Integer getId() { return id; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getBio() { return bio; } }
1,198
23.469388
76
java
graphql-server-benchmark
graphql-server-benchmark-master/Java/springboot-graphql-java/src/main/java/com/github/graphql/server/benchmark/springboot/AuthorDao.java
/* * Copyright 2019 Red Hat, Inc. * * Red Hat licenses this file to you 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 com.github.graphql.server.benchmark.springboot; import com.github.benmanes.caffeine.cache.Caffeine; import com.github.benmanes.caffeine.cache.LoadingCache; import graphql.schema.DataFetchingEnvironment; import graphql.servlet.GraphQLContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import org.springframework.web.reactive.function.client.WebClient; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; @Component public class AuthorDao { @Autowired WebClient.Builder webClientBuilder; @Autowired Environment env; WebClient webClient; @PostConstruct void init() { this.webClient = webClientBuilder.baseUrl(env.getProperty("backend.baseUrl")).build(); } public Author findById(int authorId, DataFetchingEnvironment env) { LoadingCache<Integer, Author> authorCache = getAuthorCache(env); return authorCache.get(authorId); } private LoadingCache<Integer, Author> getAuthorCache(DataFetchingEnvironment env) { GraphQLContext context = env.getContext(); HttpServletRequest httpServletRequest = context.getHttpServletRequest().get(); LoadingCache<Integer, Author> authorCache = (LoadingCache<Integer, Author>) httpServletRequest.getAttribute("authorCache"); if (authorCache == null) { authorCache = Caffeine.newBuilder() .build(key -> webClient.get().uri("/author/{id}", key).retrieve().bodyToMono(Author.class).block()); httpServletRequest.setAttribute("authorCache", authorCache); } return authorCache; } }
2,274
34.546875
127
java
graphql-server-benchmark
graphql-server-benchmark-master/Java/springboot-graphql-java/src/main/java/com/github/graphql/server/benchmark/springboot/AuthorResolver.java
/* * Copyright 2019 Red Hat, Inc. * * Red Hat licenses this file to you 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 com.github.graphql.server.benchmark.springboot; import com.coxautodev.graphql.tools.GraphQLResolver; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; @Component public class AuthorResolver implements GraphQLResolver<Author> { @Autowired PostDao postDao; @Autowired CommentDao commentDao; public List<Post> getPosts(Author author) { return postDao.findByAuthorId(author.getId()); } public List<Comment> getComments(Author author) { return commentDao.findByAuthorId(author.getId()); } }
1,232
28.357143
76
java
graphql-server-benchmark
graphql-server-benchmark-master/Java/springboot-graphql-java/src/main/java/com/github/graphql/server/benchmark/springboot/Comment.java
/* * Copyright 2019 Red Hat, Inc. * * Red Hat licenses this file to you 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 com.github.graphql.server.benchmark.springboot; public class Comment { private int postId; private int authorId; private String content; public Comment(int postId, int authorId, String content) { this.postId = postId; this.authorId = authorId; this.content = content; } public int getPostId() { return postId; } public int getAuthorId() { return authorId; } public String getContent() { return content; } }
1,089
24.348837
76
java
graphql-server-benchmark
graphql-server-benchmark-master/Java/springboot-graphql-java/src/main/java/com/github/graphql/server/benchmark/springboot/CommentDao.java
/* * Copyright 2019 Red Hat, Inc. * * Red Hat licenses this file to you 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 com.github.graphql.server.benchmark.springboot; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; import java.sql.JDBCType; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.Map; import java.util.Set; import static java.util.stream.Collectors.groupingBy; @Component public class CommentDao { @Autowired JdbcTemplate jdbcTemplate; public List<Comment> findByAuthorId(Integer authorId) { return jdbcTemplate.query( "select * from comments where author_id = ?", ps -> ps.setInt(1, authorId), this::toComment ); } public Map<Integer, List<Comment>> findComments(Set<Integer> keys) { Integer[] array = keys.toArray(new Integer[0]); return jdbcTemplate.query( "select * from comments where post_id = any(?)", ps -> ps.setArray(1, ps.getConnection().createArrayOf(JDBCType.INTEGER.getName(), array)), this::toComment ).stream().collect(groupingBy(Comment::getPostId)); } private Comment toComment(ResultSet rs, int idx) throws SQLException { return new Comment(rs.getInt("post_id"), rs.getInt("author_id"), rs.getString("content")); } }
1,904
31.288136
96
java
graphql-server-benchmark
graphql-server-benchmark-master/Java/springboot-graphql-java/src/main/java/com/github/graphql/server/benchmark/springboot/CommentResolver.java
/* * Copyright 2019 Red Hat, Inc. * * Red Hat licenses this file to you 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 com.github.graphql.server.benchmark.springboot; import com.coxautodev.graphql.tools.GraphQLResolver; import graphql.schema.DataFetchingEnvironment; import org.dataloader.DataLoader; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.concurrent.CompletableFuture; @Component public class CommentResolver implements GraphQLResolver<Comment> { @Autowired AuthorDao authorDao; public CompletableFuture<Post> getPost(Comment comment, DataFetchingEnvironment env) { DataLoader<Integer, Post> post = env.getDataLoader("post"); return post.load(comment.getPostId()); } public Author getAuthor(Comment comment, DataFetchingEnvironment env) { return authorDao.findById(comment.getAuthorId(), env); } }
1,430
33.071429
88
java
graphql-server-benchmark
graphql-server-benchmark-master/Java/springboot-graphql-java/src/main/java/com/github/graphql/server/benchmark/springboot/CustomGraphQLContextBuilder.java
/* * Copyright 2019 Red Hat, Inc. * * Red Hat licenses this file to you 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 com.github.graphql.server.benchmark.springboot; import graphql.servlet.DefaultGraphQLContextBuilder; import graphql.servlet.GraphQLContext; import graphql.servlet.GraphQLContextBuilder; import org.dataloader.DataLoader; import org.dataloader.DataLoaderRegistry; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.websocket.Session; import javax.websocket.server.HandshakeRequest; import java.util.List; import java.util.concurrent.CompletableFuture; @Component public class CustomGraphQLContextBuilder implements GraphQLContextBuilder { @Autowired CommentDao commentDao; @Autowired PostDao postDao; @Override public GraphQLContext build(HttpServletRequest req, HttpServletResponse response) { GraphQLContext context = new DefaultGraphQLContextBuilder().build(req, response); context.setDataLoaderRegistry(buildDataLoaderRegistry()); return context; } @Override public GraphQLContext build() { GraphQLContext context = new DefaultGraphQLContextBuilder().build(); context.setDataLoaderRegistry(buildDataLoaderRegistry()); return context; } @Override public GraphQLContext build(Session session, HandshakeRequest request) { GraphQLContext context = new DefaultGraphQLContextBuilder().build(session, request); context.setDataLoaderRegistry(buildDataLoaderRegistry()); return context; } private DataLoaderRegistry buildDataLoaderRegistry() { DataLoader<Integer, List<Comment>> commentDataLoader = DataLoader.newMappedDataLoader((keys, env) -> { return CompletableFuture.completedFuture(commentDao.findComments(keys)); }); DataLoader<Integer, Post> postDataLoader = DataLoader.newMappedDataLoader((keys, env) -> { return CompletableFuture.completedFuture(postDao.findPosts(keys)); }); return new DataLoaderRegistry() .register("comment", commentDataLoader) .register("post", postDataLoader); } }
2,706
34.618421
106
java
graphql-server-benchmark
graphql-server-benchmark-master/Java/springboot-graphql-java/src/main/java/com/github/graphql/server/benchmark/springboot/Post.java
/* * Copyright 2019 Red Hat, Inc. * * Red Hat licenses this file to you 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 com.github.graphql.server.benchmark.springboot; public class Post { private int id; private int authorId; private String title; private String content; public Post(int id, int authorId, String title, String content) { this.id = id; this.authorId = authorId; this.title = title; this.content = content; } public int getId() { return id; } public int getAuthorId() { return authorId; } public String getTitle() { return title; } public String getContent() { return content; } }
1,173
22.959184
76
java
graphql-server-benchmark
graphql-server-benchmark-master/Java/springboot-graphql-java/src/main/java/com/github/graphql/server/benchmark/springboot/PostDao.java
/* * Copyright 2019 Red Hat, Inc. * * Red Hat licenses this file to you 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 com.github.graphql.server.benchmark.springboot; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; import java.sql.JDBCType; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; @Component public class PostDao { @Autowired JdbcTemplate jdbcTemplate; public List<Post> findPosts() { return jdbcTemplate.query("select * from posts", this::toPost); } public List<Post> findByAuthorId(Integer authorId) { return jdbcTemplate.query( "select * from posts where author_id = ?", ps -> ps.setInt(1, authorId), this::toPost ); } public Map<Integer, Post> findPosts(Set<Integer> keys) { Integer[] array = keys.toArray(new Integer[0]); return jdbcTemplate.query( "select * from posts where id = any(?)", ps -> ps.setArray(1, ps.getConnection().createArrayOf(JDBCType.INTEGER.getName(), array)), this::toPost ).stream().collect(HashMap::new, (map, post) -> map.put(post.getId(), post), HashMap::putAll); } private Post toPost(ResultSet rs, int idx) throws SQLException { return new Post(rs.getInt("id"), rs.getInt("author_id"), rs.getString("title"), rs.getString("content")); } }
1,999
31.258065
109
java
graphql-server-benchmark
graphql-server-benchmark-master/Java/springboot-graphql-java/src/main/java/com/github/graphql/server/benchmark/springboot/PostResolver.java
/* * Copyright 2019 Red Hat, Inc. * * Red Hat licenses this file to you 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 com.github.graphql.server.benchmark.springboot; import com.coxautodev.graphql.tools.GraphQLResolver; import graphql.schema.DataFetchingEnvironment; import org.dataloader.DataLoader; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; import java.util.concurrent.CompletableFuture; @Component public class PostResolver implements GraphQLResolver<Post> { @Autowired AuthorDao authorDao; public Author getAuthor(Post post, DataFetchingEnvironment env) { return authorDao.findById(post.getAuthorId(), env); } public CompletableFuture<List<Comment>> getComments(Post post, DataFetchingEnvironment env) { DataLoader<Integer, List<Comment>> comment = env.getDataLoader("comment"); return comment.load(post.getId()); } }
1,456
32.883721
95
java
graphql-server-benchmark
graphql-server-benchmark-master/Java/springboot-graphql-java/src/main/java/com/github/graphql/server/benchmark/springboot/QueryResolver.java
/* * Copyright 2019 Red Hat, Inc. * * Red Hat licenses this file to you 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 com.github.graphql.server.benchmark.springboot; import com.coxautodev.graphql.tools.GraphQLQueryResolver; import graphql.schema.DataFetchingEnvironment; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; @Component public class QueryResolver implements GraphQLQueryResolver { @Autowired PostDao postDao; @Autowired AuthorDao authorDao; public List<Post> getPosts() { return postDao.findPosts(); } public Author getAuthor(int authorId, DataFetchingEnvironment env) { return authorDao.findById(authorId, env); } }
1,257
28.255814
76
java
graphql-server-benchmark
graphql-server-benchmark-master/Java/vertx-graphql-java/src/main/java/com/github/graphql/server/benchmark/vertx/ServerVerticle.java
/* * Copyright 2019 Red Hat, Inc. * * Red Hat licenses this file to you 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 com.github.graphql.server.benchmark.vertx; import com.github.benmanes.caffeine.cache.AsyncLoadingCache; import com.github.benmanes.caffeine.cache.Caffeine; import graphql.GraphQL; import graphql.schema.DataFetcher; import graphql.schema.DataFetchingEnvironment; import graphql.schema.GraphQLSchema; import graphql.schema.idl.*; import io.vertx.core.AbstractVerticle; import io.vertx.core.Context; import io.vertx.core.Future; import io.vertx.core.Promise; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.client.HttpResponse; import io.vertx.ext.web.client.WebClient; import io.vertx.ext.web.client.WebClientOptions; import io.vertx.ext.web.client.predicate.ResponsePredicate; import io.vertx.ext.web.codec.BodyCodec; import io.vertx.ext.web.handler.graphql.GraphQLHandler; import io.vertx.ext.web.handler.graphql.GraphiQLHandler; import io.vertx.ext.web.handler.graphql.VertxPropertyDataFetcher; import io.vertx.pgclient.PgConnectOptions; import io.vertx.pgclient.PgPool; import io.vertx.sqlclient.PoolOptions; import io.vertx.sqlclient.Row; import io.vertx.sqlclient.SqlResult; import io.vertx.sqlclient.Tuple; import org.dataloader.BatchLoaderEnvironment; import org.dataloader.DataLoader; import org.dataloader.DataLoaderRegistry; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.stream.Collector; import static graphql.schema.idl.RuntimeWiring.newRuntimeWiring; import static java.util.stream.Collectors.*; public class ServerVerticle extends AbstractVerticle { private Executor contextExecutor; private WebClient webClient; private PgPool pgClient; @Override public void start() { Context context = vertx.getOrCreateContext(); contextExecutor = cmd -> context.runOnContext(v -> cmd.run()); JsonObject config = config(); int port = config.getInteger("port", 8080); setupWebClient(config); setupPgClient(config); GraphQL graphQL = setupGraphQL(); GraphQLHandler graphQLHandler = GraphQLHandler.create(graphQL) .dataLoaderRegistry(rc -> { DataLoader<Integer, JsonArray> commentDataLoader = DataLoader.newMappedDataLoader((keys, env) -> { return toCompletableFuture(findComments(keys, env)); }); DataLoader<Integer, JsonObject> postDataLoader = DataLoader.newMappedDataLoader((keys, env) -> { return toCompletableFuture(findPosts(keys, env)); }); return new DataLoaderRegistry() .register("comment", commentDataLoader) .register("post", postDataLoader); }); Router router = Router.router(vertx); router.route("/graphql").handler(graphQLHandler); router.get("/graphiql/*").handler(GraphiQLHandler.create()); vertx.createHttpServer() .requestHandler(router) .listen(port); } private void setupWebClient(JsonObject config) { JsonObject backend = config.getJsonObject("backend", new JsonObject()); String backendHost = System.getenv().getOrDefault("BACKEND_HOST", backend.getString("host", "localhost")); int backendPort = backend.getInteger("port", 8181); int maxSize = backend.getInteger("poolSize", 32); WebClientOptions webClientOptions = new WebClientOptions() .setDefaultHost(backendHost) .setDefaultPort(backendPort) .setMaxPoolSize(maxSize) .setPipelining(true); webClient = WebClient.create(vertx, webClientOptions); } private void setupPgClient(JsonObject config) { JsonObject postgres = config.getJsonObject("postgres", new JsonObject()); String postgresHost = System.getenv().getOrDefault("POSTGRES_HOST", postgres.getString("host", "localhost")); int postgresPort = postgres.getInteger("port", 5432); int maxSize = postgres.getInteger("poolSize", 4); PgConnectOptions pgConnectOptions = new PgConnectOptions() .setHost(postgresHost) .setPort(postgresPort) .setUser("graphql") .setPassword("graphql") .setDatabase("blogdb") .setCachePreparedStatements(true); PoolOptions pgPoolOptions = new PoolOptions() .setMaxSize(maxSize); pgClient = PgPool.pool(vertx, pgConnectOptions, pgPoolOptions); } private GraphQL setupGraphQL() { String schema = vertx.fileSystem().readFileBlocking("blog.graphqls").toString(); SchemaParser schemaParser = new SchemaParser(); TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema); RuntimeWiring runtimeWiring = newRuntimeWiring() .wiringFactory(new WiringFactory() { @Override public DataFetcher getDefaultDataFetcher(FieldWiringEnvironment environment) { return new VertxPropertyDataFetcher(environment.getFieldDefinition().getName()); } }) .type("Query", builder -> { return builder .dataFetcher("posts", env -> toCompletableFuture(findPosts(null, env))) .dataFetcher("author", env -> toCompletableFuture(findAuthor(env.getArgument("id"), env))); }).type("Post", builder -> { return builder .dataFetcher("author", env -> { JsonObject post = env.getSource(); return toCompletableFuture(findAuthor(post.getInteger("author_id"), env)); }).dataFetcher("comments", env -> { JsonObject post = env.getSource(); DataLoader<Integer, JsonArray> comment = env.getDataLoader("comment"); return comment.load(post.getInteger("id"), env); }); }).type("Author", builder -> { return builder .dataFetcher("posts", env -> { JsonObject author = env.getSource(); return toCompletableFuture(findPosts(author.getInteger("id"), env)); }).dataFetcher("comments", env -> { JsonObject author = env.getSource(); return toCompletableFuture(findComments(author.getInteger("id"), env)); }); }).type("Comment", builder -> { return builder .dataFetcher("author", env -> { JsonObject comment = env.getSource(); return toCompletableFuture(findAuthor(comment.getInteger("author_id"), env)); }).dataFetcher("post", env -> { JsonObject comment = env.getSource(); DataLoader<Integer, JsonObject> post = env.getDataLoader("post"); return post.load(comment.getInteger("post_id"), env); }); }) .build(); SchemaGenerator schemaGenerator = new SchemaGenerator(); GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring); return GraphQL.newGraphQL(graphQLSchema).build(); } private Future<JsonObject> findAuthor(Integer authorId, DataFetchingEnvironment env) { Promise<JsonObject> promise = Promise.promise(); AsyncLoadingCache<Integer, JsonObject> authorCache = getAuthorCache(env); authorCache.get(authorId).whenComplete((jsonObject, throwable) -> { if (throwable == null) { promise.complete(jsonObject); } else { promise.fail(throwable); } }); return promise.future(); } private AsyncLoadingCache<Integer, JsonObject> getAuthorCache(DataFetchingEnvironment env) { RoutingContext rc = env.getContext(); AsyncLoadingCache<Integer, JsonObject> authorCache = rc.get("authorCache"); if (authorCache == null) { authorCache = Caffeine.newBuilder() .executor(contextExecutor) .buildAsync((key, executor) -> toCompletableFuture(loadAuthor(key))); rc.put("authorCache", authorCache); } return authorCache; } private Future<JsonObject> loadAuthor(Integer authorId) { Promise<HttpResponse<JsonObject>> promise = Promise.promise(); webClient.get("/author/" + authorId) .as(BodyCodec.jsonObject()) .expect(ResponsePredicate.SC_OK) .send(promise); return promise.future().map(HttpResponse::body); } private Future<JsonArray> findPosts(Integer authorId, DataFetchingEnvironment env) { Promise<SqlResult<JsonArray>> promise = Promise.promise(); Collector<Row, ?, JsonArray> collector = mapping(this::toPost, collectingAndThen(toList(), JsonArray::new)); if (authorId == null) { pgClient.preparedQuery("select * from posts", collector, promise); } else { pgClient.preparedQuery("select * from posts where author_id = $1", Tuple.of(authorId), collector, promise); } return promise.future().map(SqlResult::value); } private Future<Map<Integer, JsonObject>> findPosts(Set<Integer> ids, BatchLoaderEnvironment env) { Promise<SqlResult<Map<Integer, JsonObject>>> promise = Promise.promise(); Collector<Row, ?, Map<Integer, JsonObject>> collector = toMap(row -> row.getInteger("id"), this::toPost); pgClient.preparedQuery("select * from posts where id = any($1)", Tuple.of(ids.toArray(new Integer[0])), collector, promise); return promise.future().map(SqlResult::value); } private JsonObject toPost(Row row) { return new JsonObject() .put("id", row.getInteger("id")) .put("author_id", row.getInteger("author_id")) .put("title", row.getString("title")) .put("content", row.getString("content")); } private Future<Map<Integer, JsonArray>> findComments(Set<Integer> postIds, BatchLoaderEnvironment env) { Promise<SqlResult<Map<Integer, JsonArray>>> promise = Promise.promise(); Collector<Row, ?, Map<Integer, JsonArray>> collector = groupingBy( row -> row.getInteger("post_id"), mapping(this::toComment, collectingAndThen(toList(), JsonArray::new)) ); pgClient.preparedQuery("select * from comments where post_id = any($1)", Tuple.of(postIds.toArray(new Integer[0])), collector, promise); return promise.future().map(SqlResult::value); } private Future<JsonArray> findComments(Integer authorId, DataFetchingEnvironment env) { Promise<SqlResult<JsonArray>> promise = Promise.promise(); Collector<Row, ?, JsonArray> collector = mapping(this::toComment, collectingAndThen(toList(), JsonArray::new)); pgClient.preparedQuery("select * from comments where author_id = $1", Tuple.of(authorId), collector, promise); return promise.future().map(SqlResult::value); } private JsonObject toComment(Row row) { return new JsonObject() .put("post_id", row.getInteger("post_id")) .put("author_id", row.getInteger("author_id")) .put("content", row.getString("content")); } private <T> CompletableFuture<T> toCompletableFuture(Future<T> future) { CompletableFuture<T> cf = new CompletableFuture<>(); future.setHandler(ar -> { if (ar.succeeded()) { cf.complete(ar.result()); } else { cf.completeExceptionally(ar.cause()); } }); return cf; } }
11,535
39.055556
140
java
graphql-server-benchmark
graphql-server-benchmark-master/backend/src/main/java/com/github/graphql/server/benchmark/backend/BackendVerticle.java
/* * Copyright 2019 Red Hat, Inc. * * Red Hat licenses this file to you 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 com.github.graphql.server.benchmark.backend; import io.vertx.core.AbstractVerticle; import io.vertx.core.buffer.Buffer; import io.vertx.core.json.JsonObject; import io.vertx.core.parsetools.RecordParser; import io.vertx.core.shareddata.LocalMap; import io.vertx.ext.web.Route; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.handler.ResponseContentTypeHandler; public class BackendVerticle extends AbstractVerticle { private LocalMap<Integer, Buffer> authors; private long delay; private int burnCpuMicros; private long iterationsForOneMilli; @Override public void start() throws Exception { authors = vertx.sharedData().getLocalMap("authors"); JsonObject config = config(); int port = config.getInteger("port", 8181); delay = config.getLong("delay", 2L); burnCpuMicros = config.getInteger("burnCpuMicros", 500); if (burnCpuMicros > 0) { iterationsForOneMilli = Utils.calibrateBlackhole(); } loadData(); Router router = Router.router(vertx); Route route = router.get("/author/:id").produces("application/json"); route.handler(ResponseContentTypeHandler.create()); route.handler(this::delayResponse); route.handler(this::getAuthor); vertx.createHttpServer() .requestHandler(router) .listen(port); } private void loadData() { Buffer csv = vertx.fileSystem().readFileBlocking("authors.data"); RecordParser parser = RecordParser.newDelimited("\n"); parser.handler(line -> { String[] split = line.toString().split("\\|"); JsonObject author = new JsonObject() .put("id", Integer.valueOf(split[0].trim())) .put("firstName", split[1].trim()) .put("lastName", split[2].trim()) .put("bio", split[3].trim()); authors.put(author.getInteger("id"), author.toBuffer()); }); parser.handle(csv); } private void delayResponse(RoutingContext rc) { vertx.setTimer(delay, l -> rc.next()); if (burnCpuMicros > 0) { final long targetDelay = Utils.ONE_MICRO_IN_NANO * burnCpuMicros; long numIters = Math.round(targetDelay * 1.0 * iterationsForOneMilli / Utils.ONE_MILLI_IN_NANO); Utils.blackholeCpu(numIters); } } private void getAuthor(RoutingContext rc) { Integer authorId = Integer.valueOf(rc.pathParam("id")); Buffer author = authors.get(authorId); if (author == null) { rc.response().setStatusCode(404).end(); } else { rc.response().end(author); } } }
3,155
31.875
102
java
graphql-server-benchmark
graphql-server-benchmark-master/backend/src/main/java/com/github/graphql/server/benchmark/backend/Utils.java
/* * Copyright 2019 Red Hat, Inc. * * Red Hat licenses this file to you 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 com.github.graphql.server.benchmark.backend; import java.lang.management.ManagementFactory; import java.lang.management.ThreadMXBean; import java.util.concurrent.ThreadLocalRandom; /** * Copied from https://github.com/vietj/http2-bench * * @author <a href="mailto:julien@julienviet.com">Julien Viet</a> */ public class Utils { public static long res = 0; // value sink public static long ONE_MILLI_IN_NANO = 1000000; public static long ONE_MICRO_IN_NANO = 1000; /* the purpose of this method is to consume pure CPU without * additional resources (memory, io). * We may need to simulate milliseconds of cpu usage so * base calculation is somewhat complex to avoid too many iterations */ public static void blackholeCpu(long iterations) { long result = 0; for (int i = 0; i < iterations; i++) { int next = (ThreadLocalRandom.current().nextInt() % 1019) / 17; result = result ^ (Math.round(Math.pow(next, 3)) % 251); } res += result; } /* Estimates the number of iterations of blackholeCpu needed to * spend one milliseconds of CPU time */ public static long calibrateBlackhole() { ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); // Make the blackholeCpu method hot, to force C2 optimization for (int i = 0; i < 50000; i++) { Utils.blackholeCpu(100); } // find the number of iterations needed to spend more than 1 milli // of cpu time final long[] iters = {1000, 5000, 10000, 20000, 50000, 100000}; long timing = 0; int i = -1; while (timing < ONE_MILLI_IN_NANO && ++i < iters.length) { long start_cpu = threadBean.getCurrentThreadCpuTime(); Utils.blackholeCpu(iters[i]); timing = threadBean.getCurrentThreadCpuTime() - start_cpu; } // estimate the number of iterations for 1 milli return Math.round(Math.ceil((ONE_MILLI_IN_NANO * 1.0 / timing) * iters[i])); } }
2,554
34.985915
80
java
Tables_Provider
Tables_Provider-master/src/com/fluidops/iwb/provider/HTMLProvider.java
package com.fluidops.iwb.provider; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.Serializable; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.log4j.Logger; import org.eclipse.jetty.http.HttpStatus; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import org.openrdf.model.Literal; import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.model.vocabulary.OWL; import org.openrdf.model.vocabulary.RDF; import org.openrdf.model.vocabulary.RDFS; import org.openrdf.query.GraphQuery; import org.openrdf.query.GraphQueryResult; import org.openrdf.query.QueryLanguage; import org.openrdf.query.Update; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.sail.SailRepository; import org.openrdf.rio.RDFFormat; import org.openrdf.sail.memory.MemoryStore; import com.fluidops.iwb.model.ParameterConfigDoc; import com.fluidops.iwb.model.TypeConfigDoc; import com.fluidops.iwb.model.Vocabulary; import com.fluidops.iwb.model.Vocabulary.DCTERMS; import com.fluidops.iwb.provider.AbstractFlexProvider; import com.fluidops.util.GenUtil; import com.fluidops.util.StringUtil; import org.jsoup.Jsoup; import org.jsoup.helper.Validate; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import weka.classifiers.Classifier; import weka.classifiers.bayes.NaiveBayes; import weka.classifiers.functions.SMO; import weka.classifiers.trees.J48; import weka.core.DenseInstance; import weka.core.Instances; import weka.core.converters.ConverterUtils.DataSource; import weka.filters.Filter; import weka.filters.unsupervised.attribute.Remove; /** * Gathers data from a particular table from website and parses it into RDF * format * * Current Provider URL (to be used as location): * http://gov.spb.ru/gov/otrasl/tr_infr_kom/tekobjekt/tek_rem/ * * @author mgalkin */ @TypeConfigDoc("Gathers data from a table on a website") public class HTMLProvider extends AbstractFlexProvider<HTMLProvider.Config> { private static final Logger logger = Logger.getLogger(HTMLProvider.class .getName()); private static final long serialVersionUID = 1000L; public static class Config implements Serializable { private static final long serialVersionUID = 1001L; @ParameterConfigDoc(desc = "URL of the source table", required = true) public String url; } @Override public void setLocation(String location) { config.url = location; } @Override public String getLocation() { return config.url; } @Override public void gather(List<Statement> res) throws Exception { String url = config.url; Document doc = Jsoup.connect(url).get(); Elements tables = doc.select("table:not(:has(table))"); Elements tableElem; URI nameURI = null; URI roadsURI = null; URI sideURI = null; URI totalURI = null; // Classifier genuine = (Classifier) // weka.core.SerializationHelper.read("/Users/mikhailgalkin/Documents/workspace/HTMLProvider/genuine.model"); // Classifier orientation = (Classifier) // weka.core.SerializationHelper.read("/Users/mikhailgalkin/Documents/workspace/HTMLProvider/orientation.model"); StringService service = new StringService(); DataSource source = new DataSource( "/Users/mikhailgalkin/Documents/workspace/HTMLProvider/tables.arff"); Instances data = source.getDataSet(); Instances structure = source.getStructure(); HTMLVocabulary vocab = new HTMLVocabulary(config.url.toString()); for (Element table : tables) { Instances test = new Instances(structure); Elements rows = table.select("tr"); double[] instanceValue = new double[structure.numAttributes()]; // Count euristics instanceValue[0] = service.diffMaxSimHoriz(rows); if (Double.isNaN(instanceValue[0])) instanceValue[0] = 0.0; instanceValue[1] = service.diffMaxSimVertical(rows); if (Double.isNaN(instanceValue[1])) instanceValue[1] = 0.0; instanceValue[2] = service.diffAvgSimHoriz(rows); if (Double.isNaN(instanceValue[2])) instanceValue[2] = 0.0; instanceValue[3] = service.diffAvgSimVertical(rows); if (Double.isNaN(instanceValue[3])) instanceValue[3] = 0.0; instanceValue[4] = instanceValue[0] - instanceValue[1]; instanceValue[5] = instanceValue[2] - instanceValue[3]; test.add(new DenseInstance(1.0, instanceValue)); System.out.println(rows.get(0).text()); System.out.println(instanceValue[0]); System.out.println(instanceValue[1]); System.out.println(instanceValue[2]); System.out.println(instanceValue[3]); System.out.println(instanceValue[4]); System.out.println(instanceValue[5]); // predict values NaiveBayes bayes = new NaiveBayes(); data.setClassIndex(data.numAttributes() - 2); test.setClassIndex(test.numAttributes() - 2); bayes.buildClassifier(data); // genuinity double gen_predict = bayes.classifyInstance(test.instance(0)); String genuine_prediction = data.classAttribute().value( (int) gen_predict); System.out.println("Predicted value of instance with param " + data.classAttribute().name() + " is " + genuine_prediction); // orientaton data.setClassIndex(data.numAttributes() - 1); test.setClassIndex(test.numAttributes() - 1); bayes.buildClassifier(data); double or_predict = bayes.classifyInstance(test.instance(0)); String orientation_predict = data.classAttribute().value( (int) or_predict); System.out.println("Predicted value of instance with param " + data.classAttribute().name() + " is " + orientation_predict); // write to the train.arff file // write to a database if valid if (genuine_prediction.equals("true")) { if (orientation_predict.equals("horizontal")) { nameURI = ProviderUtils.objectToURIInNamespace( vocab.HTML_CATALOG_NAMESPACE, "Name"); roadsURI = ProviderUtils.objectToURIInNamespace( vocab.HTML_CATALOG_NAMESPACE, "roads_len"); sideURI = ProviderUtils.objectToURIInNamespace( vocab.HTML_CATALOG_NAMESPACE, "side_len"); totalURI = ProviderUtils.objectToURIInNamespace( vocab.HTML_CATALOG_NAMESPACE, "total"); for (int i = 1; i < rows.size(); i++) { Elements column = rows.get(i).select("td"); res.add(ProviderUtils.createStatement(ProviderUtils .objectToURIInNamespace( vocab.HTML_CATALOG_NAMESPACE, column.get(0).text()), RDF.TYPE, nameURI)); res.add(ProviderUtils.createLiteralStatement( ProviderUtils.objectToURIInNamespace( vocab.HTML_CATALOG_NAMESPACE, column.get(0).text()), RDFS.LABEL, "Saint Petersburg " + column.get(0).text())); res.add(ProviderUtils.createLiteralStatement( ProviderUtils.objectToURIInNamespace( vocab.HTML_CATALOG_NAMESPACE, column.get(0).text()), roadsURI, column .get(1).text())); res.add(ProviderUtils.createLiteralStatement( ProviderUtils.objectToURIInNamespace( vocab.HTML_CATALOG_NAMESPACE, column.get(0).text()), sideURI, column .get(2).text())); res.add(ProviderUtils.createLiteralStatement( ProviderUtils.objectToURIInNamespace( vocab.HTML_CATALOG_NAMESPACE, column.get(0).text()), totalURI, column .get(3).text())); } } } } } @Override public Class<? extends Config> getConfigClass() { return HTMLProvider.Config.class; } private static void print(String msg, Object... args) { System.out.println(String.format(msg, args)); } private static String trim(String s, int width) { if (s.length() > width) return s.substring(0, width - 1) + "."; else return s; } private class HTMLVocabulary { private String HTML_CATALOG_NAMESPACE; public final URI HTML_CATALOG; public final Literal HTML_CATALOG_LABEL; public HTMLVocabulary(String url) { HTML_CATALOG_NAMESPACE = url; // URI identifying the CKAN catalog itself HTML_CATALOG = ProviderUtils.objectToURIInNamespace( HTML_CATALOG_NAMESPACE, "datatable"); // Label for the CKAN catalog HTML_CATALOG_LABEL = ProviderUtils.toLiteral(HTML_CATALOG_NAMESPACE + "datatable"); } } }
8,926
32.185874
115
java
Tables_Provider
Tables_Provider-master/src/com/fluidops/iwb/provider/PrepareDatabase.java
package com.fluidops.iwb.provider; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.List; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import weka.classifiers.Classifier; import weka.classifiers.Evaluation; import weka.classifiers.bayes.NaiveBayes; import weka.classifiers.functions.SMO; import weka.classifiers.trees.J48; import weka.core.DenseInstance; import weka.core.Instances; import weka.core.converters.ConverterUtils.DataSource; import weka.filters.Filter; import weka.filters.unsupervised.attribute.Remove; import au.com.bytecode.opencsv.CSVReader; import au.com.bytecode.opencsv.CSVWriter; public class PrepareDatabase { public static void main(String[] args) throws Exception{ File input = new File("./tables.html"); Document doc = null; Elements tables = null; try { prepareDB(); DataSource source = new DataSource("/Users/mikhailgalkin/Documents/workspace/HTMLProvider/train.arff"); Instances data = source.getDataSet(); data.setClassIndex(data.numAttributes()-2); String[] options = new String[2]; options[0]= "-R"; options[1]="8"; Remove remove = new Remove(); remove.setOptions(options); remove.setInputFormat(data); Instances newData = Filter.useFilter(data, remove); //build model1 for the geniune/nongenuine prediction NaiveBayes bayes = new NaiveBayes(); bayes.buildClassifier(newData); weka.core.SerializationHelper.write("/Users/mikhailgalkin/Documents/workspace/HTMLProvider/genuine.model", bayes); //build model for the orientation prediction NaiveBayes bayes2 = new NaiveBayes(); data.setClassIndex(data.numAttributes()-1); bayes2.buildClassifier(data); weka.core.SerializationHelper.write("/Users/mikhailgalkin/Documents/workspace/HTMLProvider/orientation.model", bayes2); } catch (Exception e) { System.out.println("Error " + e.getLocalizedMessage()); } //Deserialization //Classifier cls = (Classifier) weka.core.SerializationHelper.read("./tables.model"); //System.out.println(cls); } public static Instances loadTrainData() throws Exception { DataSource source = new DataSource("./tables.arff"); Instances data = source.getDataSet(); System.out.println(source.getStructure()); return data; } public static Classifier execute(Classifier cls, Instances data) throws Exception{ cls.buildClassifier(data); return cls; } public static String evaluate(Classifier cls, Instances data, int folds, long seed) throws Exception{ Evaluation eval = new Evaluation(data); eval.crossValidateModel(cls, data, folds, data.getRandomNumberGenerator(seed)); return eval.toSummaryString(); } public static void listFiles (final File folder){ for (final File fileEntry:folder.listFiles()){ if (fileEntry.isDirectory()){ listFiles(fileEntry); } else { System.out.println(fileEntry.getName()); } } } public static void prepareDB() throws Exception{ DataSource source = new DataSource("/Users/mikhailgalkin/Documents/workspace/HTMLProvider/tables.arff"); Instances structure = source.getStructure(); Instances trainSet = new Instances(structure); StringService service = new StringService(); final File folder = new File("/Users/mikhailgalkin/Downloads/tables"); for (final File entry : folder.listFiles()) { System.out.println("Accessing file " + entry.getAbsolutePath()); // create the reader for a particular csv file CSVReader csvReader = new CSVReader(new FileReader( entry.getAbsolutePath())); List<String[]> data = csvReader.readAll(); double[] instanceValue = new double[structure.numAttributes()]; // count diffMaxSimHorizontal try { instanceValue[0] = service.csv_diffMaxSimHorizontal(data); } catch (Exception e) { instanceValue[0] = 0.0; } // count diffMaxSimVertical try { instanceValue[1] = service.csv_diffMaxSimVertical(data); } catch (Exception e) { instanceValue[1] = 0.0; } // count diffAvgSimHorizontal try { instanceValue[2] = service.csv_diffAvgSimHorizontal(data); } catch (Exception e) { instanceValue[2] = 0.0; } // count diffAvgSimVertical try { instanceValue[3] = service.csv_diffAvgSimVertical(data); } catch (Exception e) { instanceValue[3] = 0.0; } instanceValue[4] = instanceValue[0] - instanceValue[1]; instanceValue[5] = instanceValue[2] - instanceValue[3]; if ((instanceValue[4] <0 && instanceValue[5]<0) ||(Math.abs(instanceValue[4])> Math.abs(instanceValue[5]))){ instanceValue[7]=0; } else instanceValue[7]=1; if (instanceValue[0]==1.0 || instanceValue[1]==1.0){ instanceValue[6]=1; instanceValue[7]=2; } trainSet.add(new DenseInstance(1.0, instanceValue)); System.out.println(instanceValue[0]); System.out.println(instanceValue[1]); System.out.println(instanceValue[2]); System.out.println(instanceValue[3]); System.out.println(instanceValue[4]); System.out.println(instanceValue[5]); } // write the set to the file BufferedWriter writer = new BufferedWriter(new FileWriter( "/Users/mikhailgalkin/Documents/workspace/HTMLProvider/train.arff")); writer.write(trainSet.toString()); writer.newLine(); writer.flush(); writer.close(); //CSVWriter csv_writer = new CSVWriter(new FileWriter("/Users/mikhailgalkin/Documents/workspace/HTMLProvider/train.csv")); //csv_writer.writeNext(trainSet.toString().split(",")); //csv_writer.close(); } }
5,654
30.769663
124
java
Tables_Provider
Tables_Provider-master/src/com/fluidops/iwb/provider/StringService.java
package com.fluidops.iwb.provider; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import uk.ac.shef.wit.simmetrics.similaritymetrics.AbstractStringMetric; import uk.ac.shef.wit.simmetrics.similaritymetrics.JaroWinkler; import uk.ac.shef.wit.simmetrics.similaritymetrics.Levenshtein; import uk.ac.shef.wit.simmetrics.similaritymetrics.QGramsDistance; public class StringService { private String str1; private String str2; private Elements rows; private List<String[]> data; private static AbstractStringMetric metric = new Levenshtein(); /*public String getStr1() { return str1; } public void setStr1(String str1) { this.str1 = str1; } public String getStr2() { return str2; } public void setStr2(String str2) { this.str2 = str2; }*/ public Elements getRows() { return rows; } public void setRows(Elements rows) { this.rows = rows; } public List<String[]> getData() { return data; } public void setData(List<String[]> data) { this.data = data; } public static AbstractStringMetric getMetric() { return metric; } public static void setMetric(AbstractStringMetric metric) { StringService.metric = metric; } private static double modifiedLevenstein(String str1, String str2) { // Consider digits as the same objects try { String mod_str1 = str1.replace(",", "."); String mod_str2 = str2.replace(",", "."); double val1 = Double.parseDouble(mod_str1); double val2 = Double.parseDouble(mod_str2); mod_str1 = str1.replaceAll("[0-9]", "1"); mod_str2 = str2.replaceAll("[0-9]", "1"); return metric.getSimilarity(mod_str1, mod_str2); } catch (NumberFormatException e) { // Consider strings of more than 3 words as similar int threshold = 3; if (str1.split(" ").length >= threshold && str2.split(" ").length >= threshold && !str1.equals(str2)) { return 0.25; } else return metric.getSimilarity(str1, str2); } } public double diffMaxSimHoriz(Elements rows) { double max = 0; for (int k = 1; k < rows.size(); k++) { Elements cols = rows.get(k).select("td"); double total = 0; for (int i = 0; i <= cols.size() - 1; i++) { for (int j = 0; j < cols.size(); j++) { String str1 = cols.get(i).text(); String str2 = cols.get(j).text(); // writer.println("Score between " + str1 + " and " + str2 // + " is " + modifiedLevenstein(str1, str2)); //total += modifiedLevenstein(str1, str2); total+=metric.getSimilarity(str1, str2); } } total = total / Math.pow(cols.size(), 2); if (total >= max) max = total; //System.out.println("total score is " + total); } return max; } public double diffMaxSimVertical(Elements rows) { int numCols = rows.get(0).select("td").size(); // initializing ArrayList<Elements> cols = new ArrayList<Elements>(); for (int i = 0; i < numCols - 1; i++) { Elements col = new Elements(); cols.add(col); } // creating the columns for (Element row : rows) { Elements columns = row.select("td"); for (int i = 1; i < numCols; i++) { Elements column = cols.get(i - 1); column.add(columns.get(i)); cols.set(i - 1, column); } } // count double max = 0; for (int i = 0; i < cols.size(); i++) { Elements column = cols.get(i); double total = 0; for (int j = 0; j < column.size(); j++) { for (int k = 0; k < column.size(); k++) { String str1 = column.get(j).text(); String str2 = column.get(k).text(); //total += modifiedLevenstein(str1, str2); total+=metric.getSimilarity(str1, str2); } } total = total / Math.pow(column.size(), 2); if (total >= max) max = total; } return max; } public double diffAvgSimHoriz(Elements rows) { int numCols = rows.get(0).select("td").size(); double very_total = 0; for (int k = 1; k < rows.size(); k++) { Elements cols = rows.get(k).select("td"); double total = 0; for (int i = 0; i <= cols.size() - 1; i++) { for (int j = 0; j < cols.size(); j++) { String str1 = cols.get(i).text(); String str2 = cols.get(j).text(); //total += modifiedLevenstein(str1, str2); total+=metric.getSimilarity(str1, str2); } } total = total / Math.pow(cols.size(), 2); very_total += total; } very_total = very_total / (rows.size() - 1); // numCols return very_total; } public double diffAvgSimVertical(Elements rows) { int numCols = rows.get(0).select("td").size(); // initializing ArrayList<Elements> cols = new ArrayList<Elements>(); for (int i = 0; i < numCols - 1; i++) { Elements col = new Elements(); cols.add(col); } // creating the columns for (Element row : rows) { Elements columns = row.select("td"); for (int i = 1; i < numCols; i++) { Elements column = cols.get(i - 1); column.add(columns.get(i)); cols.set(i - 1, column); } } // count double very_total = 0; for (int i = 0; i < cols.size(); i++) { Elements column = cols.get(i); double total = 0; for (int j = 0; j < column.size(); j++) { for (int k = 0; k < column.size(); k++) { String str1 = column.get(j).text(); String str2 = column.get(k).text(); //total += modifiedLevenstein(str1, str2); total+=metric.getSimilarity(str1, str2); } } total = total / Math.pow(column.size(), 2); very_total += total; } very_total = very_total / (numCols - 1); // *rows.size() return very_total; } public double csv_diffAvgSimVertical(List<String[]> data) { // TODO Auto-generated method stub int numCols = data.get(0).length; // initializing ArrayList<String[]> cols = new ArrayList<String[]>(); for (int i = 0; i < numCols - 1; i++) { String[] col = new String[data.size()]; cols.add(col); } // creating the columns for (int k = 0; k < data.size(); k++) { String[] columns = data.get(k); for (int i = 1; i < numCols; i++) { String[] column = cols.get(i - 1); column[k] = columns[i]; cols.set(i - 1, column); } } // count double very_total = 0; for (int i = 0; i < cols.size(); i++) { String[] column = cols.get(i); double total = 0; for (int j = 0; j < column.length; j++) { for (int k = 0; k < column.length; k++) { String str1 = column[j]; String str2 = column[k]; //total += modifiedLevenstein(str1, str2); total+=metric.getSimilarity(str1, str2); } } total = total / Math.pow(column.length, 2); very_total += total; } very_total = very_total / (numCols - 1); // *rows.size() return very_total; } public double csv_diffAvgSimHorizontal(List<String[]> data) { // TODO Auto-generated method stub int numCols = data.get(0).length; double very_total = 0; for (int k = 1; k < data.size(); k++) { String[] cols = data.get(k); double total = 0; for (int i = 0; i <= cols.length - 1; i++) { for (int j = 0; j < cols.length; j++) { String str1 = cols[i]; String str2 = cols[j]; // System.out.println("Score between " + str1 + " and " // + str2 + " is " // + metric.getSimilarity(str1, str2)); //total += modifiedLevenstein(str1, str2); total+=metric.getSimilarity(str1, str2); } } total = total / Math.pow(cols.length, 2); very_total += total; System.out.println("used metric "+metric.getShortDescriptionString() ); } very_total = very_total / (data.size() - 1); // numCols return very_total; } public double csv_diffMaxSimVertical(List<String[]> data) { // TODO Auto-generated method stub int numCols = data.get(0).length; // initializing ArrayList<String[]> cols = new ArrayList<String[]>(); for (int i = 0; i < numCols - 1; i++) { String[] col = new String[data.size()]; cols.add(col); } // creating the columns for (int k = 0; k < data.size(); k++) { String[] columns = data.get(k); for (int i = 1; i < numCols; i++) { String[] column = cols.get(i - 1); column[k] = columns[i]; cols.set(i - 1, column); } } // count double max = 0; for (int i = 0; i < cols.size(); i++) { String[] column = cols.get(i); double total = 0; for (int j = 0; j < column.length; j++) { for (int k = 0; k < column.length; k++) { String str1 = column[j]; String str2 = column[k]; //total += modifiedLevenstein(str1, str2); total+=metric.getSimilarity(str1, str2); } } total = total / Math.pow(column.length, 2); if (total >= max) max = total; } return max; } public double csv_diffMaxSimHorizontal(List<String[]> data) { // TODO Auto-generated method stub double max = 0; for (int k = 1; k < data.size(); k++) { // Elements cols = rows.get(k).select("td"); String[] cols = data.get(k); double total = 0; for (int i = 0; i <= cols.length - 1; i++) { for (int j = 0; j < cols.length; j++) { String str1 = cols[i]; String str2 = cols[j]; // writer.println("Score between " + str1 + " and " + str2 // + " is " + modifiedLevenstein(str1, str2)); //total += modifiedLevenstein(str1, str2); total+=metric.getSimilarity(str1, str2); } } total = total / Math.pow(cols.length, 2); if (total >= max) max = total; //System.out.println("total score is " + total); } return max; } }
9,356
26.848214
74
java
sonarqube
sonarqube-master/plugins/sonar-education-plugin/src/main/java/org/sonar/education/EducationBuiltInQualityProfileDefinition.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.education; import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition; import static org.sonar.education.EducationRulesDefinition.EDUCATION_KEY; import static org.sonar.education.EducationRulesDefinition.EDUCATION_RULE_REPOSITORY_KEY; import static org.sonar.education.sensors.EducationPrinciplesSensor.EDUCATION_WITH_GENERIC_CONCEPTS_RULE_KEY; import static org.sonar.education.sensors.EducationWithContextsSensor.EDUCATION_WITH_CONTEXTS_RULE_KEY; import static org.sonar.education.sensors.EducationWithDetectedContextSensor.EDUCATION_WITH_DETECTED_CONTEXT_RULE_KEY; import static org.sonar.education.sensors.EducationWithSingleContextSensor.EDUCATION_WITH_SINGLE_CONTEXT_RULE_KEY; public class EducationBuiltInQualityProfileDefinition implements BuiltInQualityProfilesDefinition { @Override public void define(Context context) { NewBuiltInQualityProfile profile = context.createBuiltInQualityProfile("Built in QP for Education", EDUCATION_KEY); profile.setDefault(true); profile.activateRule(EDUCATION_RULE_REPOSITORY_KEY, EDUCATION_WITH_GENERIC_CONCEPTS_RULE_KEY); profile.activateRule(EDUCATION_RULE_REPOSITORY_KEY, EDUCATION_WITH_SINGLE_CONTEXT_RULE_KEY); profile.activateRule(EDUCATION_RULE_REPOSITORY_KEY, EDUCATION_WITH_CONTEXTS_RULE_KEY); profile.activateRule(EDUCATION_RULE_REPOSITORY_KEY, EDUCATION_WITH_DETECTED_CONTEXT_RULE_KEY); profile.done(); } }
2,271
51.837209
119
java
sonarqube
sonarqube-master/plugins/sonar-education-plugin/src/main/java/org/sonar/education/EducationLanguage.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.education; import org.sonar.api.resources.Language; public class EducationLanguage implements Language { @Override public String getKey() { return EducationRulesDefinition.EDUCATION_KEY; } @Override public String getName() { return "Education"; } @Override public String[] getFileSuffixes() { return new String[]{".edu"}; } }
1,222
28.829268
75
java
sonarqube
sonarqube-master/plugins/sonar-education-plugin/src/main/java/org/sonar/education/EducationPlugin.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.education; import org.sonar.education.sensors.EducationWithContextsSensor; import org.sonar.education.sensors.EducationWithDetectedContextSensor; import org.sonar.education.sensors.EducationPrinciplesSensor; import org.sonar.education.sensors.EducationWithSingleContextSensor; import org.sonar.api.Plugin; public class EducationPlugin implements Plugin { @Override public void define(Context context) { context.addExtensions( EducationRulesDefinition.class, EducationLanguage.class, EducationWithContextsSensor.class, EducationWithDetectedContextSensor.class, EducationPrinciplesSensor.class, EducationWithSingleContextSensor.class, EducationBuiltInQualityProfileDefinition.class); } }
1,602
37.166667
75
java
sonarqube
sonarqube-master/plugins/sonar-education-plugin/src/main/java/org/sonar/education/EducationRulesDefinition.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.education; import java.nio.charset.StandardCharsets; import org.apache.commons.io.IOUtils; import org.sonar.api.server.rule.RuleDescriptionSection; import org.sonar.api.server.rule.RulesDefinition; import org.sonar.education.sensors.EducationPrinciplesSensor; import org.sonar.education.sensors.EducationWithContextsSensor; import org.sonar.education.sensors.EducationWithDetectedContextSensor; import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.ASSESS_THE_PROBLEM_SECTION_KEY; import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.HOW_TO_FIX_SECTION_KEY; import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.INTRODUCTION_SECTION_KEY; import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.RESOURCES_SECTION_KEY; import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.ROOT_CAUSE_SECTION_KEY; import static org.sonar.education.sensors.EducationWith2LinkedCodeSnippetsSensor.EDUCATION_WITH_2_LINKED_CODE_SNIPPETS_RULE_KEY; import static org.sonar.education.sensors.EducationWith4LinkedCodeSnippetsSensor.EDUCATION_WITH_4_LINKED_CODE_SNIPPETS_RULE_KEY; import static org.sonar.education.sensors.EducationWithSingleContextSensor.EDUCATION_WITH_SINGLE_CONTEXT_RULE_KEY; public class EducationRulesDefinition implements RulesDefinition { public static final String EDUCATION_RULE_REPOSITORY_KEY = "edu"; public static final String EDUCATION_KEY = "education"; private static final String[] ALL_SECTIONS = {INTRODUCTION_SECTION_KEY, ROOT_CAUSE_SECTION_KEY, ASSESS_THE_PROBLEM_SECTION_KEY, RESOURCES_SECTION_KEY, HOW_TO_FIX_SECTION_KEY}; private static final String IGNORED_FAKE_SECTION = "fake_section_to_be_ignored"; public static final String[] CONTEXTS = {"spring", "hibernate", "apache_commons", "vaadin", "mybatis"}; private static final String HTML_LOREM_IPSUM = "<a href=\"https://google.com\">Lorem</a> ipsum dolor sit amet, consectetur adipiscing " + "elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco " + "laboris nisi ut aliquip ex ea commodo consequat.<br />Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu " + "fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."; @Override public void define(Context context) { NewRepository repo = context.createRepository(EDUCATION_RULE_REPOSITORY_KEY, EDUCATION_KEY); createRuleWithDescriptionSectionsAndEducationPrinciples(repo); createRuleWithDescriptionSectionsAndSingleContext(repo); createRuleWithDescriptionSectionsAndMultipleContexts(repo); createRuleWithDescriptionSectionsAndMultipleContextsIncludingOneDetected(repo); createRuleWith2LinkedCodeSnippetsInTwoSections(repo); createRuleWith4LinkedCodeSnippetsInOneSection(repo); repo.done(); } private void createRuleWithDescriptionSectionsAndEducationPrinciples(NewRepository repo) { String[] educationPrinciples = {"defense_in_depth", "never_trust_user_input"}; String ruleKey = EducationPrinciplesSensor.EDUCATION_WITH_GENERIC_CONCEPTS_RULE_KEY; NewRule ruleWithSingleContext = repo.createRule(ruleKey).setName("Rule with description sections and education principles") .addTags(EDUCATION_KEY); ruleWithSingleContext .setHtmlDescription(String.format("This rule contains description sections. To trigger an issue using this rule you need to " + "scan any text file with a line containing %s key word. This rule also contains 2 education principles - %s and %s", ruleKey, educationPrinciples[0], educationPrinciples[1])) .addEducationPrincipleKeys(educationPrinciples); addNonContextualizedDescriptionSections(ruleWithSingleContext); descriptionSection(HOW_TO_FIX_SECTION_KEY); } private void createRuleWithDescriptionSectionsAndSingleContext(NewRepository repo) { String ruleKey = EDUCATION_WITH_SINGLE_CONTEXT_RULE_KEY; NewRule ruleWithSingleContext = repo.createRule(ruleKey).setName("Rule with description sections and single " + "contexts for 'how to fix'") .addTags(EDUCATION_KEY); ruleWithSingleContext .setHtmlDescription(String.format("This rule contains description sections and single context for 'how to fix' section. To " + "trigger an issue using this rule you need to scan any text file with a line containing %s key word.", ruleKey)); addNonContextualizedDescriptionSections(ruleWithSingleContext); ruleWithSingleContext.addDescriptionSection(descriptionHowToFixSectionWithContext(CONTEXTS[0])); } private void createRuleWithDescriptionSectionsAndMultipleContexts(NewRepository repo) { NewRule ruleWithMultipleContexts = repo.createRule(EducationWithContextsSensor.EDUCATION_WITH_CONTEXTS_RULE_KEY) .setName("Rule with description sections and multiple contexts for 'how to fix'") .addTags(EDUCATION_KEY); ruleWithMultipleContexts .setHtmlDescription(String.format("This rule contains description sections and multiple contexts for 'how to fix' section. To trigger " + "an issue using this rule you need to scan any text file with a line containing %s keyword.", EducationWithContextsSensor.EDUCATION_WITH_CONTEXTS_RULE_KEY)); addNonContextualizedDescriptionSections(ruleWithMultipleContexts); for (String context : CONTEXTS) { ruleWithMultipleContexts.addDescriptionSection(descriptionHowToFixSectionWithContext(context)); } } private void createRuleWithDescriptionSectionsAndMultipleContextsIncludingOneDetected(NewRepository repo) { NewRule ruleWithMultipleContexts = repo.createRule(EducationWithDetectedContextSensor.EDUCATION_WITH_DETECTED_CONTEXT_RULE_KEY) .setName("Rule with description sections and multiple contexts (including one detected) for 'how to fix'") .addTags(EDUCATION_KEY); ruleWithMultipleContexts .setHtmlDescription(String.format("This rule contains description sections and multiple contexts (including one detected) for " + "'how to fix' section. To trigger an issue using this rule you need to scan any text file with a line containing %s keyword.", EducationWithDetectedContextSensor.EDUCATION_WITH_DETECTED_CONTEXT_RULE_KEY)); addNonContextualizedDescriptionSections(ruleWithMultipleContexts); for (String context : CONTEXTS) { ruleWithMultipleContexts.addDescriptionSection(descriptionHowToFixSectionWithContext(context)); } } private void createRuleWith2LinkedCodeSnippetsInTwoSections(NewRepository repo) { String ruleKey = EDUCATION_WITH_2_LINKED_CODE_SNIPPETS_RULE_KEY; NewRule rule2CodeSnippetsIn2Sections = repo.createRule(ruleKey).setName("Rule with description sections and code snippets " + "linked to each other in 2 different sections in order to display diff between them.") .addTags(EDUCATION_KEY); rule2CodeSnippetsIn2Sections .setHtmlDescription(String.format("This rule contains description sections and 2 linked code snippets in 2 sections. To " + "trigger an issue using this rule you need to scan any text file with a line containing %s key word.", ruleKey)); String completelyDifferentSnippetsHtml = readResource("2completelyDifferentSnippets.html"); String codeSnippetsHtml = readResource("2codeSnippets.html"); rule2CodeSnippetsIn2Sections.addDescriptionSection(descriptionSection(INTRODUCTION_SECTION_KEY)) .addDescriptionSection(descriptionSection(ROOT_CAUSE_SECTION_KEY, completelyDifferentSnippetsHtml)) .addDescriptionSection(descriptionSection(ASSESS_THE_PROBLEM_SECTION_KEY)) .addDescriptionSection(descriptionSection(HOW_TO_FIX_SECTION_KEY, codeSnippetsHtml)) .addDescriptionSection(descriptionSection(RESOURCES_SECTION_KEY)); } private void createRuleWith4LinkedCodeSnippetsInOneSection(NewRepository repo) { String ruleKey = EDUCATION_WITH_4_LINKED_CODE_SNIPPETS_RULE_KEY; NewRule rule2CodeSnippetsInTheSameSection = repo.createRule(ruleKey).setName("Rule with description sections and code snippets " + "linked to each other in the same section in order to display diff between them.") .addTags(EDUCATION_KEY); rule2CodeSnippetsInTheSameSection .setHtmlDescription(String.format("This rule contains description sections and 4 linked code snippets in the same section. To " + "trigger an issue using this rule you need to scan any text file with a line containing %s key word.", ruleKey)); String codeSnippetsHtml = readResource("4codeSnippets.html"); rule2CodeSnippetsInTheSameSection.addDescriptionSection(descriptionSection(INTRODUCTION_SECTION_KEY)) .addDescriptionSection(descriptionSection(ROOT_CAUSE_SECTION_KEY, codeSnippetsHtml)) .addDescriptionSection(descriptionSection(ASSESS_THE_PROBLEM_SECTION_KEY)) .addDescriptionSection(descriptionSection(HOW_TO_FIX_SECTION_KEY)) .addDescriptionSection(descriptionSection(RESOURCES_SECTION_KEY)); } private static void addNonContextualizedDescriptionSections(NewRule newRule) { newRule.addDescriptionSection(descriptionSection(INTRODUCTION_SECTION_KEY)) .addDescriptionSection(descriptionSection(ROOT_CAUSE_SECTION_KEY)) .addDescriptionSection(descriptionSection(ASSESS_THE_PROBLEM_SECTION_KEY)) .addDescriptionSection(descriptionSection(RESOURCES_SECTION_KEY)) .addDescriptionSection(descriptionSection(IGNORED_FAKE_SECTION)); } private static RuleDescriptionSection descriptionHowToFixSectionWithContext(String context) { var ruleContext = new org.sonar.api.server.rule.Context(context, context); return RuleDescriptionSection.builder() .sectionKey(HOW_TO_FIX_SECTION_KEY) .context(ruleContext) .htmlContent(String.format("%s: %s", HOW_TO_FIX_SECTION_KEY, HTML_LOREM_IPSUM)) .build(); } private static RuleDescriptionSection descriptionSection(String sectionKey) { return descriptionSection(sectionKey, HTML_LOREM_IPSUM); } private static RuleDescriptionSection descriptionSection(String sectionKey, String htmlContent) { return RuleDescriptionSection.builder() .sectionKey(sectionKey) .htmlContent(htmlContent) .build(); } private String readResource(String file) { try { return IOUtils.toString(getClass().getResource(file), StandardCharsets.UTF_8); } catch (Exception e) { throw new RuntimeException(e); } } }
11,520
53.34434
143
java
sonarqube
sonarqube-master/plugins/sonar-education-plugin/src/main/java/org/sonar/education/sensors/EducationPrinciplesSensor.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.education.sensors; import org.sonar.api.batch.fs.FileSystem; import org.sonar.api.batch.rule.ActiveRules; public class EducationPrinciplesSensor extends EducationRuleSensor { public static final String EDUCATION_WITH_GENERIC_CONCEPTS_RULE_KEY = "EDUCATION"; public EducationPrinciplesSensor(FileSystem fs, ActiveRules activeRules) { super(fs, activeRules, EDUCATION_WITH_GENERIC_CONCEPTS_RULE_KEY); } }
1,278
37.757576
84
java
sonarqube
sonarqube-master/plugins/sonar-education-plugin/src/main/java/org/sonar/education/sensors/EducationRuleSensor.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.education.sensors; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.sonar.api.batch.fs.FileSystem; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.rule.ActiveRules; import org.sonar.api.batch.sensor.Sensor; import org.sonar.api.batch.sensor.SensorContext; import org.sonar.api.batch.sensor.SensorDescriptor; import org.sonar.api.batch.sensor.issue.NewIssue; import org.sonar.api.rule.RuleKey; import static org.sonar.education.EducationRulesDefinition.EDUCATION_KEY; import static org.sonar.education.EducationRulesDefinition.EDUCATION_RULE_REPOSITORY_KEY; public abstract class EducationRuleSensor implements Sensor { private final FileSystem fs; private final ActiveRules activeRules; private final String ruleKeyName; private final String tag; EducationRuleSensor(FileSystem fs, ActiveRules activeRules, String ruleKey) { this.fs = fs; this.activeRules = activeRules; this.ruleKeyName = ruleKey; this.tag = ruleKey; } @Override public void describe(SensorDescriptor descriptor) { descriptor .name("Education sensor for " + tag) .createIssuesForRuleRepository(EDUCATION_RULE_REPOSITORY_KEY); } @Override public void execute(SensorContext context) { RuleKey ruleKey = RuleKey.of(EDUCATION_RULE_REPOSITORY_KEY, ruleKeyName); if (activeRules.find(ruleKey) == null) { return; } for (InputFile inputFile : fs.inputFiles(fs.predicates().hasLanguage(EDUCATION_KEY))) { processFile(inputFile, context, ruleKey); } } protected String getDetectedContext() { return null; } protected void processFile(InputFile inputFile, SensorContext context, RuleKey ruleKey) { try { int[] lineCounter = {1}; try (InputStreamReader isr = new InputStreamReader(inputFile.inputStream(), inputFile.charset()); BufferedReader reader = new BufferedReader(isr)) { reader.lines().forEachOrdered(lineStr -> { int startIndex = -1; while ((startIndex = lineStr.indexOf(tag, startIndex + 1)) != -1) { NewIssue newIssue = context.newIssue(); newIssue .forRule(ruleKey) .at(newIssue.newLocation() .on(inputFile) .at(inputFile.newRange(lineCounter[0], startIndex, lineCounter[0], startIndex + tag.length()))) .setRuleDescriptionContextKey(getDetectedContext()) .save(); } lineCounter[0]++; }); } } catch (IOException e) { throw new IllegalStateException("Fail to process " + inputFile, e); } } }
3,519
34.918367
111
java
sonarqube
sonarqube-master/plugins/sonar-education-plugin/src/main/java/org/sonar/education/sensors/EducationWith2LinkedCodeSnippetsSensor.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.education.sensors; import org.sonar.api.batch.fs.FileSystem; import org.sonar.api.batch.rule.ActiveRules; public class EducationWith2LinkedCodeSnippetsSensor extends EducationRuleSensor { public static final String EDUCATION_WITH_2_LINKED_CODE_SNIPPETS_RULE_KEY = "2_LINKED_CODE_SNIPPETS"; public EducationWith2LinkedCodeSnippetsSensor(FileSystem fs, ActiveRules activeRules) { super(fs, activeRules, EDUCATION_WITH_2_LINKED_CODE_SNIPPETS_RULE_KEY); } }
1,329
39.30303
103
java
sonarqube
sonarqube-master/plugins/sonar-education-plugin/src/main/java/org/sonar/education/sensors/EducationWith4LinkedCodeSnippetsSensor.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.education.sensors; import org.sonar.api.batch.fs.FileSystem; import org.sonar.api.batch.rule.ActiveRules; public class EducationWith4LinkedCodeSnippetsSensor extends EducationRuleSensor { public static final String EDUCATION_WITH_4_LINKED_CODE_SNIPPETS_RULE_KEY = "4_LINKED_CODE_SNIPPETS"; public EducationWith4LinkedCodeSnippetsSensor(FileSystem fs, ActiveRules activeRules) { super(fs, activeRules, EDUCATION_WITH_4_LINKED_CODE_SNIPPETS_RULE_KEY); } }
1,329
39.30303
103
java
sonarqube
sonarqube-master/plugins/sonar-education-plugin/src/main/java/org/sonar/education/sensors/EducationWithContextsSensor.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.education.sensors; import org.sonar.api.batch.fs.FileSystem; import org.sonar.api.batch.rule.ActiveRules; public class EducationWithContextsSensor extends EducationRuleSensor { public static final String EDUCATION_WITH_CONTEXTS_RULE_KEY = "CONTEXTS"; public EducationWithContextsSensor(FileSystem fs, ActiveRules activeRules) { super(fs, activeRules, EDUCATION_WITH_CONTEXTS_RULE_KEY); } }
1,265
37.363636
78
java
sonarqube
sonarqube-master/plugins/sonar-education-plugin/src/main/java/org/sonar/education/sensors/EducationWithDetectedContextSensor.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.education.sensors; import org.sonar.api.batch.fs.FileSystem; import org.sonar.api.batch.rule.ActiveRules; import static org.sonar.education.EducationRulesDefinition.CONTEXTS; public class EducationWithDetectedContextSensor extends EducationRuleSensor { public static final String EDUCATION_WITH_DETECTED_CONTEXT_RULE_KEY = "DETECTED_CONTEXT"; public EducationWithDetectedContextSensor(FileSystem fs, ActiveRules activeRules) { super(fs, activeRules, EDUCATION_WITH_DETECTED_CONTEXT_RULE_KEY); } @Override protected String getDetectedContext() { return CONTEXTS[0]; } }
1,456
35.425
91
java
sonarqube
sonarqube-master/plugins/sonar-education-plugin/src/main/java/org/sonar/education/sensors/EducationWithSingleContextSensor.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.education.sensors; import org.sonar.api.batch.fs.FileSystem; import org.sonar.api.batch.rule.ActiveRules; public class EducationWithSingleContextSensor extends EducationRuleSensor { public static final String EDUCATION_WITH_SINGLE_CONTEXT_RULE_KEY = "SINGLE_CONTEXT"; public EducationWithSingleContextSensor(FileSystem fs, ActiveRules activeRules) { super(fs, activeRules, EDUCATION_WITH_SINGLE_CONTEXT_RULE_KEY); } }
1,293
38.212121
87
java
sonarqube
sonarqube-master/plugins/sonar-education-plugin/src/test/java/org/sonar/education/EducationBuiltInQualityProfileDefinitionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.education; import org.junit.Test; import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition; import static org.assertj.core.api.Assertions.assertThat; public class EducationBuiltInQualityProfileDefinitionTest { private final EducationBuiltInQualityProfileDefinition underTest = new EducationBuiltInQualityProfileDefinition(); @Test public void define_definesAtLeast4rules() { BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context(); underTest.define(context); BuiltInQualityProfilesDefinition.BuiltInQualityProfile profile = context.profile("education", "Built in QP for Education"); assertThat(profile.isDefault()).isTrue(); assertThat(profile.rules()).hasSizeGreaterThanOrEqualTo(4); } }
1,639
38.047619
127
java
sonarqube
sonarqube-master/plugins/sonar-education-plugin/src/test/java/org/sonar/education/EducationLanguageTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.education; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class EducationLanguageTest { private final EducationLanguage underTest = new EducationLanguage(); @Test public void getFileSuffixes_notEmpty() { String[] fileSuffixes = underTest.getFileSuffixes(); assertThat(fileSuffixes).isNotEmpty(); } @Test public void getName_notEmpty() { String name = underTest.getName(); assertThat(name).isNotEmpty(); } @Test public void getKey_notEmpty() { String key = underTest.getKey(); assertThat(key).isNotEmpty(); } }
1,466
27.764706
75
java
sonarqube
sonarqube-master/plugins/sonar-education-plugin/src/test/java/org/sonar/education/EducationPluginTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.education; import org.junit.Test; import org.sonar.api.Plugin; import org.sonar.api.SonarEdition; import org.sonar.api.SonarQubeSide; import org.sonar.api.SonarRuntime; import org.sonar.api.internal.PluginContextImpl; import org.sonar.api.internal.SonarRuntimeImpl; import org.sonar.api.utils.Version; import static org.assertj.core.api.Assertions.assertThat; public class EducationPluginTest { @Test public void define_addSomeExtensionsForSonarQube() { SonarRuntime runtime = SonarRuntimeImpl.forSonarQube(Version.parse("9.5"), SonarQubeSide.SCANNER, SonarEdition.COMMUNITY); Plugin.Context context = new PluginContextImpl.Builder().setSonarRuntime(runtime).build(); EducationPlugin plugin = new EducationPlugin(); plugin.define(context); assertThat(context.getExtensions()).isNotEmpty(); } }
1,687
35.695652
126
java
sonarqube
sonarqube-master/plugins/sonar-education-plugin/src/test/java/org/sonar/education/EducationRulesDefinitionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.education; import java.util.List; import org.junit.Test; import org.sonar.api.server.rule.RulesDefinition; import static org.assertj.core.api.Assertions.assertThat; public class EducationRulesDefinitionTest { @Test public void define_addsRuleDefinitions() { EducationRulesDefinition educationRulesDefinition = new EducationRulesDefinition(); RulesDefinition.Context context = new RulesDefinition.Context(); educationRulesDefinition.define(context); List<RulesDefinition.Repository> repositories = context.repositories(); assertThat(repositories).hasSize(1); RulesDefinition.Repository repository = context.repositories().get(0); List<RulesDefinition.Rule> rules = repository.rules(); assertThat(rules).hasSizeGreaterThanOrEqualTo(4); } }
1,645
34.782609
87
java
sonarqube
sonarqube-master/plugins/sonar-education-plugin/src/test/java/org/sonar/education/sensors/EducationPrinciplesSensorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.education.sensors; import java.io.IOException; import org.junit.Test; import org.sonar.api.batch.fs.internal.DefaultFileSystem; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.sensor.internal.SensorContextTester; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.education.sensors.EducationPrinciplesSensor.EDUCATION_WITH_GENERIC_CONCEPTS_RULE_KEY; public class EducationPrinciplesSensorTest extends EducationSensorTest { @Test public void processFile_givenCorrectTagPassed_oneSecurityHotspotWithContextsIsRaised() throws IOException { DefaultInputFile inputFile = newTestFile(EDUCATION_WITH_GENERIC_CONCEPTS_RULE_KEY); DefaultFileSystem fs = new DefaultFileSystem(temp.newFolder()); fs.add(inputFile); SensorContextTester sensorContextTester = SensorContextTester.create(temp.newFolder().toPath()); var sensor = new EducationPrinciplesSensor(fs, activeRules); sensor.execute(sensorContextTester); assertThat(sensorContextTester.allIssues()).hasSize(1); } }
1,929
39.208333
109
java
sonarqube
sonarqube-master/plugins/sonar-education-plugin/src/test/java/org/sonar/education/sensors/EducationSensorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.education.sensors; import java.nio.charset.Charset; import org.junit.Before; import org.junit.Rule; import org.junit.rules.TemporaryFolder; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.fs.internal.TestInputFileBuilder; import org.sonar.api.batch.rule.ActiveRule; import org.sonar.api.batch.rule.ActiveRules; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.education.EducationRulesDefinition.EDUCATION_KEY; public class EducationSensorTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); protected final ActiveRules activeRules = mock(ActiveRules.class); @Before public void before() { when(activeRules.find(any())).thenReturn(mock(ActiveRule.class)); } protected DefaultInputFile newTestFile(String content) { return new TestInputFileBuilder("foo", "hello.edu") .setLanguage(EDUCATION_KEY) .setContents(content) .setCharset(Charset.defaultCharset()) .build(); } }
1,936
33.589286
75
java
sonarqube
sonarqube-master/plugins/sonar-education-plugin/src/test/java/org/sonar/education/sensors/EducationWith2LinkedCodeSnippetsSensorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.education.sensors; import java.io.IOException; import org.junit.Test; import org.sonar.api.batch.fs.internal.DefaultFileSystem; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.sensor.internal.SensorContextTester; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.education.sensors.EducationWith2LinkedCodeSnippetsSensor.EDUCATION_WITH_2_LINKED_CODE_SNIPPETS_RULE_KEY; public class EducationWith2LinkedCodeSnippetsSensorTest extends EducationSensorTest { @Test public void processFile_givenCorrectTagPassed_oneSecurityHotspotWithContextsIsRaised() throws IOException { DefaultInputFile inputFile = newTestFile(EDUCATION_WITH_2_LINKED_CODE_SNIPPETS_RULE_KEY); DefaultFileSystem fs = new DefaultFileSystem(temp.newFolder()); fs.add(inputFile); SensorContextTester sensorContextTester = SensorContextTester.create(temp.newFolder().toPath()); var sensor = new EducationWith2LinkedCodeSnippetsSensor(fs, activeRules); sensor.execute(sensorContextTester); assertThat(sensorContextTester.allIssues()).hasSize(1); } }
1,979
41.12766
128
java
sonarqube
sonarqube-master/plugins/sonar-education-plugin/src/test/java/org/sonar/education/sensors/EducationWith4LinkedCodeSnippetsSensorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.education.sensors; import java.io.IOException; import org.junit.Test; import org.sonar.api.batch.fs.internal.DefaultFileSystem; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.sensor.internal.SensorContextTester; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.education.sensors.EducationWith4LinkedCodeSnippetsSensor.EDUCATION_WITH_4_LINKED_CODE_SNIPPETS_RULE_KEY; public class EducationWith4LinkedCodeSnippetsSensorTest extends EducationSensorTest { @Test public void processFile_givenCorrectTagPassed_oneSecurityHotspotWithContextsIsRaised() throws IOException { DefaultInputFile inputFile = newTestFile(EDUCATION_WITH_4_LINKED_CODE_SNIPPETS_RULE_KEY); DefaultFileSystem fs = new DefaultFileSystem(temp.newFolder()); fs.add(inputFile); SensorContextTester sensorContextTester = SensorContextTester.create(temp.newFolder().toPath()); var sensor = new EducationWith4LinkedCodeSnippetsSensor(fs, activeRules); sensor.execute(sensorContextTester); assertThat(sensorContextTester.allIssues()).hasSize(1); } }
1,980
40.270833
128
java
sonarqube
sonarqube-master/plugins/sonar-education-plugin/src/test/java/org/sonar/education/sensors/EducationWithContextsSensorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.education.sensors; import java.io.IOException; import org.junit.Test; import org.sonar.api.batch.fs.internal.DefaultFileSystem; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.sensor.internal.SensorContextTester; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.education.sensors.EducationWithContextsSensor.EDUCATION_WITH_CONTEXTS_RULE_KEY; public class EducationWithContextsSensorTest extends EducationSensorTest { @Test public void processFile_givenCorrectTagPassed_oneSecurityHotspotWithContextsIsRaised() throws IOException { DefaultInputFile inputFile = newTestFile(EDUCATION_WITH_CONTEXTS_RULE_KEY); DefaultFileSystem fs = new DefaultFileSystem(temp.newFolder()); fs.add(inputFile); SensorContextTester sensorContextTester = SensorContextTester.create(temp.newFolder().toPath()); var sensor = new EducationWithContextsSensor(fs, activeRules); sensor.execute(sensorContextTester); assertThat(sensorContextTester.allIssues()).hasSize(1); } }
1,919
39
109
java
sonarqube
sonarqube-master/plugins/sonar-education-plugin/src/test/java/org/sonar/education/sensors/EducationWithDetectedContextSensorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.education.sensors; import java.io.IOException; import org.junit.Test; import org.sonar.api.batch.fs.internal.DefaultFileSystem; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.sensor.internal.SensorContextTester; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.education.sensors.EducationWithDetectedContextSensor.EDUCATION_WITH_DETECTED_CONTEXT_RULE_KEY; public class EducationWithDetectedContextSensorTest extends EducationSensorTest { @Test public void processFile_givenCorrectTagPassed_oneSecurityHotspotWithContextsIsRaised() throws IOException { DefaultInputFile inputFile = newTestFile(EDUCATION_WITH_DETECTED_CONTEXT_RULE_KEY); DefaultFileSystem fs = new DefaultFileSystem(temp.newFolder()); fs.add(inputFile); SensorContextTester sensorContextTester = SensorContextTester.create(temp.newFolder().toPath()); var sensor = new EducationWithDetectedContextSensor(fs, activeRules); sensor.execute(sensorContextTester); assertThat(sensorContextTester.allIssues()).hasSize(1); } }
1,956
39.770833
118
java
sonarqube
sonarqube-master/plugins/sonar-education-plugin/src/test/java/org/sonar/education/sensors/EducationWithSingleContextSensorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.education.sensors; import java.io.IOException; import org.junit.Test; import org.sonar.api.batch.fs.internal.DefaultFileSystem; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.sensor.internal.SensorContextTester; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.education.sensors.EducationWithSingleContextSensor.EDUCATION_WITH_SINGLE_CONTEXT_RULE_KEY; public class EducationWithSingleContextSensorTest extends EducationSensorTest { @Test public void processFile_givenCorrectTagPassed_oneSecurityHotspotWithContextsIsRaised() throws IOException { DefaultInputFile inputFile = newTestFile(EDUCATION_WITH_SINGLE_CONTEXT_RULE_KEY); DefaultFileSystem fs = new DefaultFileSystem(temp.newFolder()); fs.add(inputFile); SensorContextTester sensorContextTester = SensorContextTester.create(temp.newFolder().toPath()); var sensor = new EducationWithSingleContextSensor(fs, activeRules); sensor.execute(sensorContextTester); assertThat(sensorContextTester.allIssues()).hasSize(1); } }
1,946
39.5625
114
java
sonarqube
sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/Xoo.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.xoo; import org.sonar.api.config.Configuration; import org.sonar.api.resources.Language; public class Xoo implements Language { public static final String KEY = "xoo"; public static final String NAME = "Xoo"; public static final String FILE_SUFFIXES_KEY = "sonar.xoo.file.suffixes"; public static final String DEFAULT_FILE_SUFFIXES = ".xoo"; private final Configuration config; public Xoo(Configuration config) { this.config = config; } @Override public String getKey() { return KEY; } @Override public String getName() { return NAME; } @Override public String[] getFileSuffixes() { return config.getStringArray(FILE_SUFFIXES_KEY); } @Override public boolean publishAllFiles() { return true; } }
1,624
27.017241
75
java
sonarqube
sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/Xoo2.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.xoo; import org.sonar.api.resources.Language; public class Xoo2 implements Language { public static final String KEY = "xoo2"; public static final String NAME = "Xoo2"; public static final String FILE_SUFFIX = ".xoo2"; private static final String[] XOO_SUFFIXES = { FILE_SUFFIX }; @Override public String getKey() { return KEY; } @Override public String getName() { return NAME; } @Override public String[] getFileSuffixes() { return XOO_SUFFIXES; } @Override public boolean publishAllFiles() { return true; } }
1,435
25.592593
75
java
sonarqube
sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/Xoo3NoAutoPublish.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.xoo; import org.sonar.api.resources.Language; public class Xoo3NoAutoPublish implements Language { public static final String KEY = "xoo3"; public static final String NAME = "Xoo3"; public static final String FILE_SUFFIX = ".xoo3"; private static final String[] XOO_SUFFIXES = { FILE_SUFFIX }; @Override public String getKey() { return KEY; } @Override public String getName() { return NAME; } @Override public String[] getFileSuffixes() { return XOO_SUFFIXES; } @Override public boolean publishAllFiles() { return false; } }
1,448
26.339623
75
java
sonarqube
sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/Xoo3QualityProfileDefinition.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.xoo; import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition; public class Xoo3QualityProfileDefinition implements BuiltInQualityProfilesDefinition { private static final String PROFILE_NAME = "Sonar way"; @Override public void define(Context context) { NewBuiltInQualityProfile profile = context.createBuiltInQualityProfile(PROFILE_NAME, Xoo3NoAutoPublish.KEY); profile.setDefault(true); profile.done(); } }
1,308
35.361111
112
java
sonarqube
sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/XooPlugin.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.xoo; import org.sonar.api.Plugin; import org.sonar.api.PropertyType; import org.sonar.api.SonarProduct; import org.sonar.api.config.PropertyDefinition; import org.sonar.api.resources.Qualifiers; import org.sonar.xoo.coverage.ItCoverageSensor; import org.sonar.xoo.coverage.OverallCoverageSensor; import org.sonar.xoo.coverage.UtCoverageSensor; import org.sonar.xoo.extensions.XooIssueFilter; import org.sonar.xoo.extensions.XooPostJob; import org.sonar.xoo.extensions.XooProjectBuilder; import org.sonar.xoo.global.DeprecatedGlobalSensor; import org.sonar.xoo.global.GlobalProjectSensor; import org.sonar.xoo.lang.CpdTokenizerSensor; import org.sonar.xoo.lang.LineMeasureSensor; import org.sonar.xoo.lang.MeasureSensor; import org.sonar.xoo.lang.SignificantCodeSensor; import org.sonar.xoo.lang.SymbolReferencesSensor; import org.sonar.xoo.lang.SyntaxHighlightingSensor; import org.sonar.xoo.rule.AnalysisErrorSensor; import org.sonar.xoo.rule.ChecksSensor; import org.sonar.xoo.rule.CreateIssueByInternalKeySensor; import org.sonar.xoo.rule.CustomMessageSensor; import org.sonar.xoo.rule.HasTagSensor; import org.sonar.xoo.rule.MarkAsUnchangedSensor; import org.sonar.xoo.rule.MultilineHotspotSensor; import org.sonar.xoo.rule.MultilineIssuesSensor; import org.sonar.xoo.rule.NoSonarSensor; import org.sonar.xoo.rule.OneBlockerIssuePerFileSensor; import org.sonar.xoo.rule.OneBugIssuePerLineSensor; import org.sonar.xoo.rule.OneBugIssuePerTestLineSensor; import org.sonar.xoo.rule.OneCodeSmellIssuePerLineSensor; import org.sonar.xoo.rule.OneCodeSmellIssuePerTestLineSensor; import org.sonar.xoo.rule.OneDayDebtPerFileSensor; import org.sonar.xoo.rule.OneExternalIssueOnProjectSensor; import org.sonar.xoo.rule.OneExternalIssuePerLineSensor; import org.sonar.xoo.rule.OneExternalIssuePerLineWithoutMessageSensor; import org.sonar.xoo.rule.OneIssueOnDirPerFileSensor; import org.sonar.xoo.rule.OneIssuePerDirectorySensor; import org.sonar.xoo.rule.OneIssuePerFileSensor; import org.sonar.xoo.rule.OneIssuePerLineSensor; import org.sonar.xoo.rule.OneIssuePerModuleSensor; import org.sonar.xoo.rule.OneIssuePerTestFileSensor; import org.sonar.xoo.rule.OneIssuePerUnknownFileSensor; import org.sonar.xoo.rule.OnePredefinedAndAdHocRuleExternalIssuePerLineSensor; import org.sonar.xoo.rule.OnePredefinedRuleExternalIssuePerLineSensor; import org.sonar.xoo.rule.OneQuickFixPerLineSensor; import org.sonar.xoo.rule.OneVulnerabilityIssuePerModuleSensor; import org.sonar.xoo.rule.RandomAccessSensor; import org.sonar.xoo.rule.SaveDataTwiceSensor; import org.sonar.xoo.rule.Xoo2BasicProfile; import org.sonar.xoo.rule.Xoo2SonarWayProfile; import org.sonar.xoo.rule.XooBasicProfile; import org.sonar.xoo.rule.XooBuiltInQualityProfilesDefinition; import org.sonar.xoo.rule.XooEmptyProfile; import org.sonar.xoo.rule.XooFakeExporter; import org.sonar.xoo.rule.XooFakeImporter; import org.sonar.xoo.rule.XooFakeImporterWithMessages; import org.sonar.xoo.rule.XooRulesDefinition; import org.sonar.xoo.rule.XooSonarWayProfile; import org.sonar.xoo.rule.hotspot.HotspotWithContextsSensor; import org.sonar.xoo.rule.hotspot.HotspotWithSingleContextSensor; import org.sonar.xoo.rule.hotspot.HotspotWithoutContextSensor; import org.sonar.xoo.rule.variant.HotspotWithCodeVariantsSensor; import org.sonar.xoo.rule.variant.IssueWithCodeVariantsSensor; import org.sonar.xoo.scm.XooBlameCommand; import org.sonar.xoo.scm.XooIgnoreCommand; import org.sonar.xoo.scm.XooScmProvider; /** * Plugin entry-point, as declared in pom.xml. */ public class XooPlugin implements Plugin { @Override public void define(Context context) { context.addExtensions( PropertyDefinition.builder(Xoo.FILE_SUFFIXES_KEY) .defaultValue(Xoo.DEFAULT_FILE_SUFFIXES) .name("File suffixes") .description("Comma-separated list of suffixes for files to analyze. To not filter, leave the list empty.") .subCategory("General") .onQualifiers(Qualifiers.PROJECT) .multiValues(true) .build(), // Used by DuplicationsTest and IssueFilterOnCommonRulesTest. If not declared it is not returned by api/settings PropertyDefinition.builder("sonar.cpd.xoo.minimumTokens") .onQualifiers(Qualifiers.PROJECT) .type(PropertyType.INTEGER) .build(), PropertyDefinition.builder("sonar.cpd.xoo.minimumLines") .onQualifiers(Qualifiers.PROJECT) .type(PropertyType.INTEGER) .build(), Xoo.class, Xoo2.class, Xoo3NoAutoPublish.class, Xoo3QualityProfileDefinition.class, XooRulesDefinition.class, XooBuiltInQualityProfilesDefinition.class, XooSonarWayProfile.class, XooBasicProfile.class, Xoo2SonarWayProfile.class, Xoo2BasicProfile.class, XooEmptyProfile.class, XooFakeExporter.class, XooFakeImporter.class, XooFakeImporterWithMessages.class, // SCM XooScmProvider.class, XooBlameCommand.class, // sensors HasTagSensor.class, LineMeasureSensor.class, SyntaxHighlightingSensor.class, SymbolReferencesSensor.class, ChecksSensor.class, RandomAccessSensor.class, SaveDataTwiceSensor.class, NoSonarSensor.class, CpdTokenizerSensor.class, OneBlockerIssuePerFileSensor.class, OneIssuePerLineSensor.class, OneDayDebtPerFileSensor.class, OneIssuePerFileSensor.class, OneIssuePerTestFileSensor.class, OneBugIssuePerTestLineSensor.class, OneCodeSmellIssuePerTestLineSensor.class, OneIssuePerDirectorySensor.class, OneIssuePerModuleSensor.class, OneIssueOnDirPerFileSensor.class, OneIssuePerUnknownFileSensor.class, OneQuickFixPerLineSensor.class, OneExternalIssuePerLineSensor.class, OneExternalIssuePerLineWithoutMessageSensor.class, OneExternalIssueOnProjectSensor.class, OnePredefinedRuleExternalIssuePerLineSensor.class, OnePredefinedAndAdHocRuleExternalIssuePerLineSensor.class, CreateIssueByInternalKeySensor.class, MultilineIssuesSensor.class, MultilineHotspotSensor.class, CustomMessageSensor.class, OneBugIssuePerLineSensor.class, OneCodeSmellIssuePerLineSensor.class, OneVulnerabilityIssuePerModuleSensor.class, DeprecatedGlobalSensor.class, GlobalProjectSensor.class, HotspotWithoutContextSensor.class, HotspotWithContextsSensor.class, HotspotWithSingleContextSensor.class, HotspotWithCodeVariantsSensor.class, // Coverage UtCoverageSensor.class, ItCoverageSensor.class, OverallCoverageSensor.class, // Analysis errors AnalysisErrorSensor.class, // Other MarkAsUnchangedSensor.class, XooProjectBuilder.class, XooPostJob.class, XooIssueFilter.class, XooIgnoreCommand.class, SignificantCodeSensor.class, IssueWithCodeVariantsSensor.class); if (context.getRuntime().getProduct() != SonarProduct.SONARLINT) { context.addExtension(MeasureSensor.class); } } }
7,930
37.5
118
java
sonarqube
sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.xoo; import javax.annotation.ParametersAreNonnullByDefault;
953
38.75
75
java
sonarqube
sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/checks/Check.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.xoo.checks; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.sensor.SensorContext; import org.sonar.api.rule.RuleKey; public interface Check { Class[] ALL = new Class[] {TemplateRuleCheck.class}; void execute(SensorContext context, InputFile file, RuleKey ruleKey); }
1,157
34.090909
75
java
sonarqube
sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/checks/TemplateRuleCheck.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.xoo.checks; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.sensor.SensorContext; import org.sonar.api.batch.sensor.issue.NewIssue; import org.sonar.api.rule.RuleKey; import org.sonar.check.Cardinality; import org.sonar.check.Rule; import org.sonar.check.RuleProperty; @Rule(key = TemplateRuleCheck.RULE_KEY, cardinality = Cardinality.MULTIPLE, name = "Template rule", description = "Sample template rule") public class TemplateRuleCheck implements Check { public static final String RULE_KEY = "TemplateRule"; @RuleProperty(key = "line") private int line; @Override public void execute(SensorContext sensorContext, InputFile file, RuleKey ruleKey) { NewIssue newIssue = sensorContext.newIssue(); newIssue .forRule(ruleKey) .at(newIssue.newLocation() .on(file) .at(file.selectLine(line))) .save(); } }
1,743
33.88
137
java
sonarqube
sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/coverage/AbstractCoverageSensor.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.xoo.coverage; import com.google.common.base.Splitter; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.sensor.Sensor; import org.sonar.api.batch.sensor.SensorContext; import org.sonar.api.batch.sensor.SensorDescriptor; import org.sonar.api.batch.sensor.coverage.NewCoverage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.xoo.Xoo; public abstract class AbstractCoverageSensor implements Sensor { private static final Logger LOG = LoggerFactory.getLogger(AbstractCoverageSensor.class); private void processCoverage(InputFile inputFile, SensorContext context) { File coverageFile = new File(inputFile.file().getParentFile(), inputFile.file().getName() + getCoverageExtension()); if (coverageFile.exists()) { LOG.debug("Processing " + coverageFile.getAbsolutePath()); try { List<String> lines = FileUtils.readLines(coverageFile, context.fileSystem().encoding().name()); NewCoverage coverageBuilder = context.newCoverage() .onFile(inputFile); int lineNumber = 0; for (String line : lines) { lineNumber++; if (StringUtils.isBlank(line)) { continue; } if (line.startsWith("#")) { continue; } try { Iterator<String> split = Splitter.on(":").split(line).iterator(); int lineId = Integer.parseInt(split.next()); int lineHits = Integer.parseInt(split.next()); coverageBuilder.lineHits(lineId, lineHits); if (split.hasNext()) { int conditions = Integer.parseInt(split.next()); int coveredConditions = Integer.parseInt(split.next()); coverageBuilder.conditions(lineId, conditions, coveredConditions); } } catch (Exception e) { throw new IllegalStateException("Error processing line " + lineNumber + " of file " + coverageFile.getAbsolutePath(), e); } } coverageBuilder.save(); } catch (IOException e) { throw new RuntimeException(e); } } } protected abstract String getCoverageExtension(); @Override public void describe(SensorDescriptor descriptor) { descriptor .name(getSensorName()) .onlyOnLanguages(Xoo.KEY); } protected abstract String getSensorName(); @Override public void execute(SensorContext context) { for (InputFile file : context.fileSystem().inputFiles(context.fileSystem().predicates().hasLanguages(Xoo.KEY))) { processCoverage(file, context); } } }
3,635
36.102041
133
java
sonarqube
sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/coverage/ItCoverageSensor.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.xoo.coverage; /** * Parse files *.xoo.itcoverage */ public class ItCoverageSensor extends AbstractCoverageSensor { @Override protected String getCoverageExtension() { return ".itcoverage"; } @Override protected String getSensorName() { return "Xoo IT Coverage Sensor"; } }
1,160
29.552632
75
java
sonarqube
sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/coverage/OverallCoverageSensor.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.xoo.coverage; /** * Parse files *.xoo.overallcoverage */ public class OverallCoverageSensor extends AbstractCoverageSensor { @Override protected String getCoverageExtension() { return ".overallcoverage"; } @Override protected String getSensorName() { return "Xoo Overall Coverage Sensor"; } }
1,180
30.078947
75
java
sonarqube
sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/coverage/UtCoverageSensor.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.xoo.coverage; /** * Parse files *.xoo.coverage */ public class UtCoverageSensor extends AbstractCoverageSensor { @Override protected String getCoverageExtension() { return ".coverage"; } @Override protected String getSensorName() { return "Xoo UT Coverage Sensor"; } }
1,156
29.447368
75
java
sonarqube
sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/coverage/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.xoo.coverage; import javax.annotation.ParametersAreNonnullByDefault;
962
39.125
75
java
sonarqube
sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/extensions/XooIssueFilter.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.xoo.extensions; import org.sonar.api.batch.fs.TextRange; import org.sonar.api.config.Configuration; import org.sonar.api.scan.issue.filter.FilterableIssue; import org.sonar.api.scan.issue.filter.IssueFilter; import org.sonar.api.scan.issue.filter.IssueFilterChain; public class XooIssueFilter implements IssueFilter { private final Configuration config; public XooIssueFilter(Configuration config) { this.config = config; } @Override public boolean accept(FilterableIssue issue, IssueFilterChain chain) { if (config.getBoolean("sonar.xoo.excludeAllIssuesOnOddLines").orElse(false) && isOdd(issue)) { return false; } return chain.accept(issue); } private static boolean isOdd(FilterableIssue issue) { TextRange textRange = issue.textRange(); return textRange != null && textRange.start().line() % 2 == 1; } }
1,722
33.46
98
java
sonarqube
sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/extensions/XooPostJob.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.xoo.extensions; import org.sonar.api.batch.postjob.PostJob; import org.sonar.api.batch.postjob.PostJobContext; import org.sonar.api.batch.postjob.PostJobDescriptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class XooPostJob implements PostJob { private static final Logger LOG = LoggerFactory.getLogger(XooPostJob.class); @Override public void describe(PostJobDescriptor descriptor) { descriptor.name("Xoo Post Job") .requireProperty("sonar.xoo.enablePostJob"); } @Override public void execute(PostJobContext context) { LOG.info("Running Xoo PostJob"); } }
1,474
32.522727
78
java
sonarqube
sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/extensions/XooProjectBuilder.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.xoo.extensions; import java.io.File; import org.sonar.api.batch.bootstrap.ProjectBuilder; import org.sonar.api.batch.bootstrap.ProjectDefinition; public class XooProjectBuilder extends ProjectBuilder { @Override public void build(Context context) { if (!context.config().getBoolean("sonar.xoo.enableProjectBuilder").orElse(false)) { return; } ProjectDefinition root = context.projectReactor().getRoot(); root.resetSources(); ProjectDefinition module = ProjectDefinition.create() .setKey(root.getKey() + ":module1") .setName("Module 1"); module.setBaseDir(new File(root.getBaseDir(), "module1")); module.setWorkDir(new File(root.getWorkDir(), "module1")); module.setSources("src"); root.addSubProject(module); } }
1,642
32.530612
87
java
sonarqube
sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/global/DeprecatedGlobalSensor.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.xoo.global; import org.sonar.api.batch.sensor.Sensor; import org.sonar.api.batch.sensor.SensorContext; import org.sonar.api.batch.sensor.SensorDescriptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DeprecatedGlobalSensor implements Sensor { private static final Logger LOG = LoggerFactory.getLogger(DeprecatedGlobalSensor.class); public static final String ENABLE_PROP = "sonar.scanner.mediumtest.deprecatedGlobalSensor"; @Override public void describe(SensorDescriptor descriptor) { descriptor .name("Deprecated Global Sensor") .global() .onlyWhenConfiguration(c -> c.hasKey(ENABLE_PROP)); } @Override public void execute(SensorContext context) { context.fileSystem().inputFiles(context.fileSystem().predicates().all()).forEach(inputFile -> LOG.info("Deprecated Global Sensor: {}", inputFile.relativePath())); } }
1,750
37.065217
166
java
sonarqube
sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/global/GlobalProjectSensor.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.xoo.global; import org.sonar.api.scanner.sensor.ProjectSensor; import org.sonar.api.batch.sensor.SensorContext; import org.sonar.api.batch.sensor.SensorDescriptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class GlobalProjectSensor implements ProjectSensor { private static final Logger LOG = LoggerFactory.getLogger(GlobalProjectSensor.class); public static final String ENABLE_PROP = "sonar.scanner.mediumtest.globalSensor"; @Override public void describe(SensorDescriptor descriptor) { descriptor .name("Global Sensor") .onlyWhenConfiguration(c -> c.hasKey(ENABLE_PROP)); } @Override public void execute(SensorContext context) { context.fileSystem().inputFiles(context.fileSystem().predicates().all()).forEach(inputFile -> LOG.info("Global Sensor: {}", inputFile.relativePath())); } }
1,712
37.066667
155
java
sonarqube
sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/lang/CpdTokenizerSensor.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.xoo.lang; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.sonar.api.batch.fs.FilePredicates; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.fs.InputFile.Type; import org.sonar.api.batch.sensor.Sensor; import org.sonar.api.batch.sensor.SensorContext; import org.sonar.api.batch.sensor.SensorDescriptor; import org.sonar.api.batch.sensor.cpd.NewCpdTokens; import org.sonar.xoo.Xoo; /** * Tokenize files for CPD */ public class CpdTokenizerSensor implements Sensor { private void tokenize(InputFile inputFile, SensorContext context) { int lineIdx = 1; NewCpdTokens newCpdTokens = context.newCpdTokens().onFile(inputFile); try { StringBuilder sb = new StringBuilder(); for (String line : FileUtils.readLines(inputFile.file(), inputFile.charset())) { int startOffset = 0; int endOffset = 0; for (int i = 0; i < line.length(); i++) { char c = line.charAt(i); if (Character.isWhitespace(c)) { if (sb.length() > 0) { newCpdTokens.addToken(inputFile.newRange(lineIdx, startOffset, lineIdx, endOffset), sb.toString()); sb.setLength(0); } startOffset = endOffset; } else { sb.append(c); } endOffset++; } if (sb.length() > 0) { newCpdTokens.addToken(inputFile.newRange(lineIdx, startOffset, lineIdx, endOffset), sb.toString()); sb.setLength(0); } lineIdx++; } } catch (IOException e) { throw new IllegalStateException("Unable to tokenize", e); } newCpdTokens.save(); } @Override public void describe(SensorDescriptor descriptor) { descriptor .name("Xoo Cpd Tokenizer Sensor") .onlyOnLanguages(Xoo.KEY); } @Override public void execute(SensorContext context) { FilePredicates p = context.fileSystem().predicates(); for (InputFile file : context.fileSystem().inputFiles(p.and(p.hasLanguages(Xoo.KEY), p.hasType(Type.MAIN)))) { tokenize(file, context); } } }
2,964
33.476744
114
java
sonarqube
sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/lang/LineMeasureSensor.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.xoo.lang; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.sensor.Sensor; import org.sonar.api.batch.sensor.SensorContext; import org.sonar.api.batch.sensor.SensorDescriptor; import org.sonar.api.measures.FileLinesContext; import org.sonar.api.measures.FileLinesContextFactory; import org.sonar.api.utils.KeyValueFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.xoo.Xoo; /** * Parse files *.xoo.measures */ public class LineMeasureSensor implements Sensor { private static final Logger LOG = LoggerFactory.getLogger(LineMeasureSensor.class); private static final String MEASURES_EXTENSION = ".linemeasures"; private FileLinesContextFactory contextFactory; public LineMeasureSensor(FileLinesContextFactory contextFactory) { this.contextFactory = contextFactory; } private void processFileMeasures(InputFile inputFile, SensorContext context) { File ioFile = inputFile.file(); File measureFile = new File(ioFile.getParentFile(), ioFile.getName() + MEASURES_EXTENSION); if (measureFile.exists()) { LOG.debug("Processing " + measureFile.getAbsolutePath()); try { FileLinesContext linesContext = contextFactory.createFor(inputFile); List<String> lines = FileUtils.readLines(measureFile, context.fileSystem().encoding().name()); int lineNumber = 0; for (String line : lines) { lineNumber++; if (StringUtils.isBlank(line) || line.startsWith("#")) { continue; } processMeasure(linesContext, measureFile, lineNumber, line); } linesContext.save(); } catch (IOException e) { throw new IllegalStateException(e); } } } private void processMeasure(FileLinesContext context, File measureFile, int lineNumber, String line) { try { String metricKey = StringUtils.substringBefore(line, ":"); String value = line.substring(metricKey.length() + 1); saveMeasure(context, metricKey, KeyValueFormat.parseIntInt(value)); } catch (Exception e) { LOG.error("Error processing line " + lineNumber + " of file " + measureFile.getAbsolutePath(), e); throw new IllegalStateException("Error processing line " + lineNumber + " of file " + measureFile.getAbsolutePath(), e); } } private void saveMeasure(FileLinesContext context, String metricKey, Map<Integer, Integer> values) { for (Map.Entry<Integer, Integer> entry : values.entrySet()) { context.setIntValue(metricKey, entry.getKey(), entry.getValue()); } } @Override public void describe(SensorDescriptor descriptor) { descriptor .name("Xoo Line Measure Sensor") .onlyOnLanguages(Xoo.KEY); } @Override public void execute(SensorContext context) { for (InputFile file : context.fileSystem().inputFiles(context.fileSystem().predicates().hasLanguages(Xoo.KEY))) { processFileMeasures(file, context); } } }
3,999
36.037037
126
java
sonarqube
sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/lang/MeasureSensor.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.xoo.lang; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.util.List; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.sonar.api.batch.fs.InputComponent; import org.sonar.api.batch.fs.InputDir; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.measure.MetricFinder; import org.sonar.api.batch.sensor.Sensor; import org.sonar.api.batch.sensor.SensorContext; import org.sonar.api.batch.sensor.SensorDescriptor; import org.sonar.api.batch.sensor.measure.NewMeasure; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.xoo.Xoo; import org.sonar.xoo.Xoo2; /** * Parse files *.xoo.measures */ public class MeasureSensor implements Sensor { private static final Logger LOG = LoggerFactory.getLogger(MeasureSensor.class); private static final String MEASURES_EXTENSION = ".measures"; private MetricFinder metricFinder; public MeasureSensor(MetricFinder metricFinder) { this.metricFinder = metricFinder; } private void processFileMeasures(InputComponent component, File measureFile, SensorContext context) { if (measureFile.exists()) { LOG.debug("Processing " + measureFile.getAbsolutePath()); try { List<String> lines = FileUtils.readLines(measureFile, context.fileSystem().encoding().name()); int lineNumber = 0; for (String line : lines) { lineNumber++; if (StringUtils.isBlank(line) || line.startsWith("#")) { continue; } processMeasure(component, context, measureFile, lineNumber, line); } } catch (IOException e) { throw new IllegalStateException(e); } } } private void processMeasure(InputComponent component, SensorContext context, File measureFile, int lineNumber, String line) { try { String metricKey = StringUtils.substringBefore(line, ":"); String value = line.substring(metricKey.length() + 1); saveMeasure(context, component, metricKey, value); } catch (Exception e) { LOG.error("Error processing line " + lineNumber + " of file " + measureFile.getAbsolutePath(), e); throw new IllegalStateException("Error processing line " + lineNumber + " of file " + measureFile.getAbsolutePath(), e); } } private void saveMeasure(SensorContext context, InputComponent component, String metricKey, String value) { org.sonar.api.batch.measure.Metric<Serializable> metric = metricFinder.findByKey(metricKey); if (metric == null) { throw new IllegalStateException("Unknown metric with key: " + metricKey); } NewMeasure<Serializable> newMeasure = context.newMeasure() .forMetric(metric) .on(component); if (Boolean.class.equals(metric.valueType())) { newMeasure.withValue(Boolean.parseBoolean(value)); } else if (Integer.class.equals(metric.valueType())) { newMeasure.withValue(Integer.valueOf(value)); } else if (Double.class.equals(metric.valueType())) { newMeasure.withValue(Double.valueOf(value)); } else if (String.class.equals(metric.valueType())) { newMeasure.withValue(value); } else if (Long.class.equals(metric.valueType())) { newMeasure.withValue(Long.valueOf(value)); } else { throw new UnsupportedOperationException("Unsupported type :" + metric.valueType()); } newMeasure.save(); } @Override public void describe(SensorDescriptor descriptor) { descriptor .name("Xoo Measure Sensor") .onlyOnLanguages(Xoo.KEY, Xoo2.KEY); } @Override public void execute(SensorContext context) { for (InputFile file : context.fileSystem().inputFiles(context.fileSystem().predicates().hasLanguages(Xoo.KEY, Xoo2.KEY))) { File ioFile = file.file(); File measureFile = new File(ioFile.getParentFile(), ioFile.getName() + MEASURES_EXTENSION); processFileMeasures(file, measureFile, context); InputDir inputDir = context.fileSystem().inputDir(ioFile.getParentFile()); if (inputDir != null) { processFileMeasures(inputDir, new File(ioFile.getParentFile(), "folder" + MEASURES_EXTENSION), context); } } processFileMeasures(context.module(), new File(context.fileSystem().baseDir(), "module" + MEASURES_EXTENSION), context); } }
5,185
38.287879
127
java
sonarqube
sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/lang/SignificantCodeSensor.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.xoo.lang; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import org.apache.commons.lang.StringUtils; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.sensor.Sensor; import org.sonar.api.batch.sensor.SensorContext; import org.sonar.api.batch.sensor.SensorDescriptor; import org.sonar.api.batch.sensor.code.NewSignificantCode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.xoo.Xoo; public class SignificantCodeSensor implements Sensor { private static final Logger LOG = LoggerFactory.getLogger(SignificantCodeSensor.class); private static final String FILE_EXTENSION = ".significantCode"; @Override public void describe(SensorDescriptor descriptor) { descriptor .name("Xoo Significant Code Ranges Sensor") .onlyOnLanguages(Xoo.KEY); } @Override public void execute(SensorContext context) { for (InputFile file : context.fileSystem().inputFiles(context.fileSystem().predicates().hasLanguages(Xoo.KEY))) { processSignificantCodeFile(file, context); } } private void processSignificantCodeFile(InputFile inputFile, SensorContext context) { Path ioFile = inputFile.path(); Path significantCodeFile = ioFile.resolveSibling(ioFile.getFileName() + FILE_EXTENSION).toAbsolutePath(); if (Files.exists(significantCodeFile) && Files.isRegularFile(significantCodeFile)) { LOG.debug("Processing " + significantCodeFile.toString()); try { List<String> lines = Files.readAllLines(significantCodeFile, context.fileSystem().encoding()); NewSignificantCode significantCode = context.newSignificantCode() .onFile(inputFile); for (String line : lines) { if (StringUtils.isBlank(line) || line.startsWith("#")) { continue; } processLine(line, inputFile, significantCode); } significantCode.save(); } catch (IOException e) { throw new IllegalStateException(e); } } } private void processLine(String fileLine, InputFile inputFile, NewSignificantCode significantCode) { String[] textPointer = fileLine.split(","); if (textPointer.length != 3) { throw new IllegalStateException("Invalid format in error file"); } try { int line = Integer.parseInt(textPointer[0]); int startLineOffset = Integer.parseInt(textPointer[1]); int endLineOffset = Integer.parseInt(textPointer[2]); significantCode.addRange(inputFile.newRange(line, startLineOffset, line, endLineOffset)); } catch (NumberFormatException e) { throw new IllegalStateException("Invalid format in error file", e); } } }
3,578
36.673684
117
java
sonarqube
sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/lang/SymbolReferencesSensor.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.xoo.lang; import com.google.common.base.Splitter; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.sensor.Sensor; import org.sonar.api.batch.sensor.SensorContext; import org.sonar.api.batch.sensor.SensorDescriptor; import org.sonar.api.batch.sensor.symbol.NewSymbol; import org.sonar.api.batch.sensor.symbol.NewSymbolTable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.xoo.Xoo; import static java.lang.Integer.parseInt; /** * Parse files *.xoo.symbol */ public class SymbolReferencesSensor implements Sensor { private static final Logger LOG = LoggerFactory.getLogger(SymbolReferencesSensor.class); private static final String SYMBOL_EXTENSION = ".symbol"; private void processFileSymbol(InputFile inputFile, SensorContext context) { File ioFile = inputFile.file(); File symbolFile = new File(ioFile.getParentFile(), ioFile.getName() + SYMBOL_EXTENSION); if (symbolFile.exists()) { LOG.debug("Processing " + symbolFile.getAbsolutePath()); try { List<String> lines = FileUtils.readLines(symbolFile, context.fileSystem().encoding().name()); int lineNumber = 0; NewSymbolTable symbolTable = context.newSymbolTable() .onFile(inputFile); for (String line : lines) { lineNumber++; if (StringUtils.isBlank(line) || line.startsWith("#")) { continue; } processLine(symbolFile, lineNumber, symbolTable, line); } symbolTable.save(); } catch (IOException e) { throw new IllegalStateException(e); } } } private static void processLine(File symbolFile, int lineNumber, NewSymbolTable symbolTable, String line) { try { Iterator<String> split = Splitter.on(",").split(line).iterator(); String[] symbolOffsets = split.next().split(":"); if (symbolOffsets.length == 4) { int startLine = parseInt(symbolOffsets[0]); int startLineOffset = parseInt(symbolOffsets[1]); int endLine = parseInt(symbolOffsets[2]); int endLineOffset = parseInt(symbolOffsets[3]); NewSymbol s = symbolTable.newSymbol(startLine, startLineOffset, endLine, endLineOffset); parseReferences(s, split); } else { throw new IllegalStateException("Illegal number of elements separated by ':'. " + "Must be startLine:startLineOffset:endLine:endLineOffset"); } } catch (Exception e) { throw new IllegalStateException("Error processing line " + lineNumber + " of file " + symbolFile.getAbsolutePath(), e); } } private static void parseReferences(NewSymbol s, Iterator<String> split) { while (split.hasNext()) { addReference(s, split.next()); } } private static void addReference(NewSymbol s, String str) { String[] split = str.split(":"); if (split.length == 4) { int startLine = parseInt(split[0]); int startLineOffset = parseInt(split[1]); int endLine = parseInt(split[2]); int endLineOffset = parseInt(split[3]); s.newReference(startLine, startLineOffset, endLine, endLineOffset); } else { throw new IllegalStateException("Illegal number of elements separated by ':'"); } } @Override public void describe(SensorDescriptor descriptor) { descriptor .name("Xoo Symbol Reference Sensor") .onlyOnLanguages(Xoo.KEY); } @Override public void execute(SensorContext context) { for (InputFile file : context.fileSystem().inputFiles(context.fileSystem().predicates().hasLanguages(Xoo.KEY))) { processFileSymbol(file, context); } } }
4,675
35.53125
125
java
sonarqube
sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/lang/SyntaxHighlightingSensor.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.xoo.lang; import java.io.File; import java.io.IOException; import java.util.List; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.sensor.Sensor; import org.sonar.api.batch.sensor.SensorContext; import org.sonar.api.batch.sensor.SensorDescriptor; import org.sonar.api.batch.sensor.highlighting.NewHighlighting; import org.sonar.api.batch.sensor.highlighting.TypeOfText; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.xoo.Xoo; import static java.lang.Integer.parseInt; /** * Parse files *.xoo.highlighting */ public class SyntaxHighlightingSensor implements Sensor { private static final Logger LOG = LoggerFactory.getLogger(SyntaxHighlightingSensor.class); private static final String HIGHLIGHTING_EXTENSION = ".highlighting"; private void processFileHighlighting(InputFile inputFile, SensorContext context) { File ioFile = inputFile.file(); File highlightingFile = new File(ioFile.getParentFile(), ioFile.getName() + HIGHLIGHTING_EXTENSION); if (highlightingFile.exists()) { LOG.debug("Processing " + highlightingFile.getAbsolutePath()); try { List<String> lines = FileUtils.readLines(highlightingFile, context.fileSystem().encoding().name()); int lineNumber = 0; NewHighlighting highlighting = context.newHighlighting() .onFile(inputFile); for (String line : lines) { lineNumber++; if (StringUtils.isBlank(line) || line.startsWith("#")) { continue; } processLine(highlightingFile, lineNumber, highlighting, line); } highlighting.save(); } catch (IOException e) { throw new IllegalStateException(e); } } } private static void processLine(File highlightingFile, int lineNumber, NewHighlighting highlighting, String line) { try { String[] split = line.split(":"); if (split.length == 5) { int startLine = parseInt(split[0]); int startLineOffset = parseInt(split[1]); int endLine = parseInt(split[2]); int endLineOffset = parseInt(split[3]); highlighting.highlight(startLine, startLineOffset, endLine, endLineOffset, TypeOfText.forCssClass(split[4])); } else { throw new IllegalStateException("Illegal number of elements separated by ':'. " + "Must be startLine:startLineOffset:endLine:endLineOffset:class"); } } catch (Exception e) { throw new IllegalStateException("Error processing line " + lineNumber + " of file " + highlightingFile.getAbsolutePath(), e); } } @Override public void describe(SensorDescriptor descriptor) { descriptor .name("Xoo Highlighting Sensor") .onlyOnLanguages(Xoo.KEY); } @Override public void execute(SensorContext context) { for (InputFile file : context.fileSystem().inputFiles(context.fileSystem().predicates().hasLanguages(Xoo.KEY))) { processFileHighlighting(file, context); } } }
3,926
37.126214
131
java
sonarqube
sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/lang/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.xoo.lang; import javax.annotation.ParametersAreNonnullByDefault;
958
38.958333
75
java
sonarqube
sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/AbstractXooRuleSensor.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.xoo.rule; import org.sonar.api.batch.fs.FileSystem; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.rule.ActiveRules; import org.sonar.api.batch.sensor.Sensor; import org.sonar.api.batch.sensor.SensorContext; import org.sonar.api.batch.sensor.SensorDescriptor; import org.sonar.api.rule.RuleKey; import org.sonar.xoo.Xoo; public abstract class AbstractXooRuleSensor implements Sensor { private final FileSystem fs; private final ActiveRules activeRules; public AbstractXooRuleSensor(FileSystem fs, ActiveRules activeRules) { this.fs = fs; this.activeRules = activeRules; } protected abstract String getRuleKey(); @Override public void describe(SensorDescriptor descriptor) { descriptor .onlyOnLanguage(Xoo.KEY) .createIssuesForRuleRepository(XooRulesDefinition.XOO_REPOSITORY); } @Override public void execute(SensorContext context) { doAnalyse(context, Xoo.KEY); } private void doAnalyse(SensorContext context, String languageKey) { RuleKey ruleKey = RuleKey.of(XooRulesDefinition.XOO_REPOSITORY, getRuleKey()); if (activeRules.find(ruleKey) == null) { return; } for (InputFile inputFile : fs.inputFiles(fs.predicates().hasLanguage(languageKey))) { processFile(inputFile, context, ruleKey, languageKey); } } protected abstract void processFile(InputFile inputFile, SensorContext context, RuleKey ruleKey, String languageKey); }
2,307
33.447761
119
java
sonarqube
sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/AnalysisErrorSensor.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.xoo.rule; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import org.apache.commons.lang.StringUtils; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.sensor.Sensor; import org.sonar.api.batch.sensor.SensorContext; import org.sonar.api.batch.sensor.SensorDescriptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.xoo.Xoo; public class AnalysisErrorSensor implements Sensor { private static final Logger LOG = LoggerFactory.getLogger(AnalysisErrorSensor.class); private static final String ERROR_EXTENSION = ".error"; @Override public void describe(SensorDescriptor descriptor) { descriptor .name("Xoo Analysis Error Sensor") .onlyOnLanguages(Xoo.KEY); } @Override public void execute(SensorContext context) { for (InputFile file : context.fileSystem().inputFiles(context.fileSystem().predicates().hasLanguages(Xoo.KEY))) { processFileError(file, context); } } private void processFileError(InputFile inputFile, SensorContext context) { Path ioFile = inputFile.file().toPath(); Path errorFile = ioFile.resolveSibling(ioFile.getFileName() + ERROR_EXTENSION).toAbsolutePath(); if (Files.exists(errorFile) && Files.isRegularFile(errorFile)) { LOG.debug("Processing " + errorFile.toString()); try { List<String> lines = Files.readAllLines(errorFile, context.fileSystem().encoding()); for (String line : lines) { if (StringUtils.isBlank(line) || line.startsWith("#")) { continue; } processLine(line, inputFile, context); } } catch (IOException e) { throw new IllegalStateException(e); } } } private void processLine(String fileLine, InputFile inputFile, SensorContext context) { String[] textPointer = fileLine.split(","); if (textPointer.length != 3) { throw new IllegalStateException("Invalid format in error file"); } try { int line = Integer.parseInt(textPointer[0]); int lineOffset = Integer.parseInt(textPointer[1]); String msg = textPointer[2]; context.newAnalysisError() .onFile(inputFile) .at(inputFile.newPointer(line, lineOffset)) .message(msg) .save(); } catch (NumberFormatException e) { throw new IllegalStateException("Invalid format in error file", e); } } }
3,306
33.447917
117
java