proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
oshi_oshi
|
oshi/oshi-demo/src/main/java/oshi/demo/ComputerID.java
|
ComputerID
|
getComputerIdentifier
|
class ComputerID {
public static final List<String> NON_UNIQUE_UUIDS = Arrays.asList("03000200-0400-0500-0006-000700080009",
"FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF", "00000000-0000-0000-0000-000000000000");
/**
* <p>
* main.
* </p>
*
* @param args an array of {@link java.lang.String} objects.
*/
@SuppressForbidden(reason = "Using System.out in a demo class")
public static void main(String[] args) {
String unknownHash = String.format(Locale.ROOT, "%08x", Constants.UNKNOWN.hashCode());
System.out.println("Here's a unique (?) id for your computer.");
System.out.println(getComputerIdentifier());
System.out.println("If any field is " + unknownHash
+ " then I couldn't find a serial number or unique uuid, and running as sudo might change this.");
}
/**
* Generates a Computer Identifier, which may be part of a strategy to construct a licence key. (The identifier may
* not be unique as in one case hashcode could be same for multiple values, and the result may differ based on
* whether the program is running with sudo/root permission.) The identifier string is based upon the processor
* serial number, vendor, system UUID, processor identifier, and total processor count.
*
* @return A string containing four hyphen-delimited fields representing the processor; the first 3 are 32-bit
* hexadecimal values and the last one is an integer value.
*/
public static String getComputerIdentifier() {<FILL_FUNCTION_BODY>}
}
|
SystemInfo systemInfo = new SystemInfo();
OperatingSystem operatingSystem = systemInfo.getOperatingSystem();
HardwareAbstractionLayer hardwareAbstractionLayer = systemInfo.getHardware();
CentralProcessor centralProcessor = hardwareAbstractionLayer.getProcessor();
ComputerSystem computerSystem = hardwareAbstractionLayer.getComputerSystem();
String vendor = operatingSystem.getManufacturer();
String processorSerialNumber = computerSystem.getSerialNumber();
String uuid = computerSystem.getHardwareUUID();
if (NON_UNIQUE_UUIDS.contains(uuid.toUpperCase(Locale.ROOT))) {
uuid = Constants.UNKNOWN;
}
String processorIdentifier = centralProcessor.getProcessorIdentifier().getIdentifier();
int processors = centralProcessor.getLogicalProcessorCount();
String delimiter = "-";
return String.format(Locale.ROOT, "%08x", vendor.hashCode()) + delimiter
+ String.format(Locale.ROOT, "%08x", processorSerialNumber.hashCode()) + delimiter
+ String.format(Locale.ROOT, "%08x", uuid.hashCode()) + delimiter
+ String.format(Locale.ROOT, "%08x", processorIdentifier.hashCode()) + delimiter + processors;
| 491
| 331
| 822
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-demo/src/main/java/oshi/demo/DetectVM.java
|
DetectVM
|
identifyVM
|
class DetectVM {
private static final String OSHI_VM_MAC_ADDR_PROPERTIES = "oshi.vmmacaddr.properties";
private static final Properties vmMacAddressProps = FileUtil
.readPropertiesFromFilename(OSHI_VM_MAC_ADDR_PROPERTIES);
// Constant for CPU vendor string
private static final Map<String, String> vmVendor = new HashMap<>();
static {
vmVendor.put("bhyve bhyve", "bhyve");
vmVendor.put("KVMKVMKVM", "KVM");
vmVendor.put("TCGTCGTCGTCG", "QEMU");
vmVendor.put("Microsoft Hv", "Microsoft Hyper-V or Windows Virtual PC");
vmVendor.put("lrpepyh vr", "Parallels");// (endianness mismatch of "prl hyperv ")
vmVendor.put("VMwareVMware", "VMware");
vmVendor.put("XenVMMXenVMM", "Xen HVM");
vmVendor.put("ACRNACRNACRN", "Project ACRN");
vmVendor.put("QNXQVMBSQG", "QNX Hypervisor");
}
private static final String[] vmModelArray = new String[] { "Linux KVM", "Linux lguest", "OpenVZ", "Qemu",
"Microsoft Virtual PC", "VMWare", "linux-vserver", "Xen", "FreeBSD Jail", "VirtualBox", "Parallels",
"Linux Containers", "LXC" };
/**
* The main method, executing the {@link #identifyVM} method.
*
* @param args Arguments, ignored.
*/
@SuppressForbidden(reason = "Using System.out in a demo class")
public static void main(String[] args) {
String vmString = identifyVM();
if (vmString.isEmpty()) {
System.out.println("You do not appear to be on a Virtual Machine.");
} else {
System.out.println("You appear to be on a VM: " + vmString);
}
}
/**
* The function attempts to identify which Virtual Machine (VM) based on common VM signatures in MAC address and
* computer model.
*
* @return A string indicating the machine's virtualization info if it can be determined, or an emptry string
* otherwise.
*/
public static String identifyVM() {<FILL_FUNCTION_BODY>}
}
|
SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hw = si.getHardware();
// Check CPU Vendor
String vendor = hw.getProcessor().getProcessorIdentifier().getVendor().trim();
if (vmVendor.containsKey(vendor)) {
return vmVendor.get(vendor);
}
// Try well known MAC addresses
List<NetworkIF> nifs = hw.getNetworkIFs();
for (NetworkIF nif : nifs) {
String mac = nif.getMacaddr().toUpperCase(Locale.ROOT);
String oui = mac.length() > 7 ? mac.substring(0, 8) : mac;
if (vmMacAddressProps.containsKey(oui)) {
return vmMacAddressProps.getProperty(oui);
}
}
// Try well known models
String model = hw.getComputerSystem().getModel();
for (String vm : vmModelArray) {
if (model.contains(vm)) {
return vm;
}
}
String manufacturer = hw.getComputerSystem().getManufacturer();
if ("Microsoft Corporation".equals(manufacturer) && "Virtual Machine".equals(model)) {
return "Microsoft Hyper-V";
}
// Couldn't find VM, return empty string
return "";
| 646
| 343
| 989
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-demo/src/main/java/oshi/demo/DiskStoreForPath.java
|
DiskStoreForPath
|
main
|
class DiskStoreForPath {
/**
* Main method
*
* @param args Optional file path
* @throws URISyntaxException on invalid path
*/
@SuppressForbidden(reason = "Using System.out in a demo class")
public static void main(String[] args) throws URISyntaxException {<FILL_FUNCTION_BODY>}
private static Pair<Integer, Integer> getDiskStoreAndPartitionForPath(String path, List<HWDiskStore> diskStores) {
for (int ds = 0; ds < diskStores.size(); ds++) {
HWDiskStore store = diskStores.get(ds);
List<HWPartition> parts = store.getPartitions();
for (int part = 0; part < parts.size(); part++) {
String mount = parts.get(part).getMountPoint();
if (!mount.isEmpty() && path.substring(0, mount.length()).equalsIgnoreCase(mount)) {
return new Pair<>(ds, part);
}
}
}
return new Pair<>(-1, -1);
}
private static int getFileStoreForPath(String path, List<OSFileStore> fileStores) {
for (int fs = 0; fs < fileStores.size(); fs++) {
String mount = fileStores.get(fs).getMount();
if (!mount.isEmpty() && path.substring(0, mount.length()).equalsIgnoreCase(mount)) {
return fs;
}
}
return -1;
}
}
|
// Use the arg as a file path or get this class's path
String filePath = args.length > 0 ? args[0]
: new File(DiskStoreForPath.class.getProtectionDomain().getCodeSource().getLocation().toURI())
.getPath();
System.out.println("Searching stores for path: " + filePath);
SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hal = si.getHardware();
List<HWDiskStore> diskStores = hal.getDiskStores();
Pair<Integer, Integer> dsPartIdx = getDiskStoreAndPartitionForPath(filePath, diskStores);
int dsIndex = dsPartIdx.getA();
int partIndex = dsPartIdx.getB();
System.out.println();
System.out.println("DiskStore index " + dsIndex + " and Partition index " + partIndex);
if (dsIndex >= 0 && partIndex >= 0) {
System.out.println(diskStores.get(dsIndex));
System.out.println(" |-- " + diskStores.get(dsIndex).getPartitions().get(partIndex));
} else {
System.out.println("Couldn't find that path on a partition.");
}
OperatingSystem os = si.getOperatingSystem();
List<OSFileStore> fileStores = os.getFileSystem().getFileStores();
int fsIndex = getFileStoreForPath(filePath, fileStores);
System.out.println();
System.out.println("FileStore index " + fsIndex);
if (fsIndex >= 0) {
System.out.println(fileStores.get(fsIndex));
} else {
System.out.println("Couldn't find that path on a filestore.");
}
| 398
| 465
| 863
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-demo/src/main/java/oshi/demo/Json.java
|
Json
|
main
|
class Json {
/**
* <p>
* main.
* </p>
*
* @param args an array of {@link java.lang.String} objects.
*/
@SuppressForbidden(reason = "Using System.out in a demo class")
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
// Jackson ObjectMapper
ObjectMapper mapper = new ObjectMapper();
// Fetch some OSHI objects
SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hal = si.getHardware();
try {
// Pretty print computer system
System.out.println("JSON for CPU:");
CentralProcessor cpu = hal.getProcessor();
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(cpu));
// Print memory
System.out.println("JSON for Memory:");
GlobalMemory mem = hal.getMemory();
System.out.println(mapper.writeValueAsString(mem));
} catch (JsonProcessingException e) {
System.out.println("Exception encountered: " + e.getMessage());
}
| 97
| 201
| 298
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-demo/src/main/java/oshi/demo/OshiGui.java
|
OshiGui
|
getJMenu
|
class OshiGui {
private JFrame mainFrame;
private JButton jMenu;
private SystemInfo si = new SystemInfo();
public static void main(String[] args) {
OshiGui gui = new OshiGui();
gui.init();
SwingUtilities.invokeLater(gui::setVisible);
}
private void setVisible() {
mainFrame.setVisible(true);
mainFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
jMenu.doClick();
}
private void init() {
// Create the external frame
mainFrame = new JFrame(Config.GUI_TITLE);
mainFrame.setSize(Config.GUI_WIDTH, Config.GUI_HEIGHT);
mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
mainFrame.setResizable(true);
mainFrame.setLocationByPlatform(true);
mainFrame.setLayout(new BorderLayout());
// Add a menu bar
JMenuBar menuBar = new JMenuBar();
mainFrame.setJMenuBar(menuBar);
// Assign the first menu option to be clicked on visibility
jMenu = getJMenu("OS & HW Info", 'O', "Hardware & OS Summary", new OsHwTextPanel(si));
menuBar.add(jMenu);
// Add later menu items
menuBar.add(getJMenu("Memory", 'M', "Memory Summary", new MemoryPanel(si)));
menuBar.add(getJMenu("CPU", 'C', "CPU Usage", new ProcessorPanel(si)));
menuBar.add(getJMenu("FileStores", 'F', "FileStore Usage", new FileStorePanel(si)));
menuBar.add(getJMenu("Processes", 'P', "Processes", new ProcessPanel(si)));
menuBar.add(getJMenu("USB Devices", 'U', "USB Device list", new UsbPanel(si)));
menuBar.add(getJMenu("Network", 'N', "Network Params and Interfaces", new InterfacePanel(si)));
}
private JButton getJMenu(String title, char mnemonic, String toolTip, OshiJPanel panel) {<FILL_FUNCTION_BODY>}
private void resetMainGui() {
this.mainFrame.getContentPane().removeAll();
}
private void refreshMainGui() {
this.mainFrame.revalidate();
this.mainFrame.repaint();
}
}
|
JButton button = new JButton(title);
button.setMnemonic(mnemonic);
button.setToolTipText(toolTip);
button.addActionListener(e -> {
Container contentPane = this.mainFrame.getContentPane();
if (contentPane.getComponents().length <= 0 || contentPane.getComponent(0) != panel) {
resetMainGui();
this.mainFrame.getContentPane().add(panel);
refreshMainGui();
}
});
return button;
| 632
| 136
| 768
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-demo/src/main/java/oshi/demo/OshiHTTPServer.java
|
OshiHTTPServer
|
run
|
class OshiHTTPServer implements Runnable {
// port to listen connection
private static final int PORT = 8080;
private static final Logger logger = LoggerFactory.getLogger(OshiHTTPServer.class);
// Client Connection via Socket Class
private Socket connect;
public OshiHTTPServer(Socket c) {
connect = c;
logger.debug("Connecton opened.");
}
public static void main(String[] args) {
try (ServerSocket serverConnect = new ServerSocket(PORT)) {
logger.info("Server started. Listening for connections on port {}", PORT);
// we listen until user halts server execution
while (true) { // NOSONAR squid:S2189
OshiHTTPServer myServer = new OshiHTTPServer(serverConnect.accept());
// create dedicated thread to manage the client connection
Thread thread = new Thread(myServer);
thread.start();
}
} catch (IOException e) {
logger.error("Server Connection error: {}", e.getMessage());
}
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
}
|
try ( // read characters from the client via input stream on the socket
BufferedReader in = new BufferedReader(
new InputStreamReader(connect.getInputStream(), StandardCharsets.UTF_8));
// get character output stream to client (for headers)
PrintWriter out = new PrintWriter(
new OutputStreamWriter(connect.getOutputStream(), StandardCharsets.UTF_8));
// get binary output stream to client (for requested data)
BufferedOutputStream dataOut = new BufferedOutputStream(connect.getOutputStream())) {
// get first line of the request from the client
String input = in.readLine();
if (input == null) {
throw new IOException("No characters read from input stream.");
}
// we parse the request with a string tokenizer
StringTokenizer parse = new StringTokenizer(input);
String method = parse.nextToken().toUpperCase(Locale.ROOT); // we get the HTTP method of the client
// we get fields requested
String fileRequested = parse.nextToken().toLowerCase(Locale.ROOT);
// we support only GET and HEAD methods, we check
if (!method.equals("GET") && !method.equals("HEAD")) {
logger.debug("501 Not Implemented: {}", method);
String contentMimeType = "text/html";
// we send HTTP Headers with data to client
out.println("HTTP/1.1 501 Not Implemented");
out.println("Server: OSHI HTTP Server");
out.println("Date: " + Instant.now());
out.println("Content-type: " + contentMimeType);
out.println("Content-length: " + 0);
out.println(); // blank line between headers and content, very important !
out.flush(); // flush character output stream buffer
// Could return other information here...
} else {
// Possibly could use the fileRequested value from user input to work down
// OSHI's JSON tree and only return the relevant info instead of the entire
// SystemInfo object.
SystemInfo si = new SystemInfo();
ObjectMapper mapper = new ObjectMapper();
byte[] content = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(si)
.getBytes(StandardCharsets.UTF_8);
if (method.equals("GET")) { // GET method so we return content
// send HTTP Headers
out.println("HTTP/1.1 200 OK");
out.println("Server: OSHI HTTP Server");
out.println("Date: " + Instant.now());
out.println("Content-type: application/json");
out.println("Content-length: " + content.length);
out.println(); // blank line between headers and content, very important !
out.flush(); // flush character output stream buffer
dataOut.write(content, 0, content.length);
dataOut.flush();
}
logger.debug("Data {} returned", fileRequested);
}
} catch (IOException ioe) {
logger.error("Server error: {}", ioe.getMessage());
} finally {
try {
// close socket connection, defined for this thread
connect.close();
} catch (Exception e) {
logger.error("Error closing connection: {}", e.getMessage());
}
logger.debug("Connection closed.");
}
| 310
| 832
| 1,142
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-demo/src/main/java/oshi/demo/UserComInit.java
|
UserComInit
|
loopWmiQueriesWithUserCom
|
class UserComInit {
private static final int REPETITIONS = 300;
@SuppressForbidden(reason = "Using System.out in a demo class")
public static void main(String[] args) {
wakeUpCom();
System.out.println("Collecting statistics with default COM setup");
loopWmiQueries();
System.out.println("Collecting statistics with user-init COM setup");
loopWmiQueriesWithUserCom();
}
private static void wakeUpCom() {
// The first COM query can take extra long so just do one separately
Win32OperatingSystem.queryOsVersion();
}
@SuppressForbidden(reason = "Using System.out in a demo class")
private static void loopWmiQueries() {
long t = System.nanoTime();
for (int i = 0; i < REPETITIONS; i++) {
Win32OperatingSystem.queryOsVersion();
}
t = System.nanoTime() - t;
System.out.println("Average ms per rep: " + t / (1_000_000d * REPETITIONS));
}
private static void loopWmiQueriesWithUserCom() {<FILL_FUNCTION_BODY>}
}
|
// Create instance using existing WmiQueryHandler class for convenience, only to
// be used for COM init/uninit. Not needed if user initializes COM.
WmiQueryHandler handlerForSingleCOMinit = Objects.requireNonNull(WmiQueryHandler.createInstance());
boolean singleComInit = false;
try {
// Initialize using the default query handler. This is unnecessary in a user
// application if the application controls COM initialization elsewhere.
singleComInit = handlerForSingleCOMinit.initCOM();
// Change query handler class to not initialize COM
WmiQueryHandler.setInstanceClass(WmiNoComInitQueryHandler.class);
loopWmiQueries();
} catch (COMException e) {
// Ignore for demo. Production code should handle this!
} finally {
// User should ununitialize COM in their own application
if (singleComInit) {
handlerForSingleCOMinit.unInitCOM();
}
}
| 326
| 237
| 563
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-demo/src/main/java/oshi/demo/gui/FileStorePanel.java
|
FileStorePanel
|
init
|
class FileStorePanel extends OshiJPanel { // NOSONAR squid:S110
private static final long serialVersionUID = 1L;
private static final String USED = "Used";
private static final String AVAILABLE = "Available";
private static final DecimalFormatSymbols ROOT_SYMBOLS = DecimalFormatSymbols.getInstance(Locale.ROOT);
public FileStorePanel(SystemInfo si) {
super();
init(si.getOperatingSystem().getFileSystem());
}
private void init(FileSystem fs) {<FILL_FUNCTION_BODY>}
private static boolean updateDatasets(FileSystem fs, DefaultPieDataset<String>[] fsData, JFreeChart[] fsCharts) {
List<OSFileStore> fileStores = fs.getFileStores();
if (fileStores.size() != fsData.length) {
return false;
}
int i = 0;
for (OSFileStore store : fileStores) {
fsCharts[i].setTitle(store.getName());
List<TextTitle> subtitles = new ArrayList<>();
if (SystemInfo.getCurrentPlatform().equals(PlatformEnum.WINDOWS)) {
subtitles.add(new TextTitle(store.getLabel()));
}
long usable = store.getUsableSpace();
long total = store.getTotalSpace();
subtitles.add(new TextTitle(
"Available: " + FormatUtil.formatBytes(usable) + "/" + FormatUtil.formatBytes(total)));
fsCharts[i].setSubtitles(subtitles);
fsData[i].setValue(USED, (double) total - usable);
fsData[i].setValue(AVAILABLE, usable);
i++;
}
return true;
}
private static void configurePlot(JFreeChart chart) {
@SuppressWarnings("unchecked")
PiePlot<String> plot = (PiePlot<String>) chart.getPlot();
plot.setSectionPaint(USED, Color.red);
plot.setSectionPaint(AVAILABLE, Color.green);
plot.setExplodePercent(USED, 0.10);
plot.setSimpleLabels(true);
PieSectionLabelGenerator labelGenerator = new StandardPieSectionLabelGenerator("{0}: {1} ({2})",
new DecimalFormat("0", ROOT_SYMBOLS), new DecimalFormat("0%", ROOT_SYMBOLS));
plot.setLabelGenerator(labelGenerator);
}
}
|
List<OSFileStore> fileStores = fs.getFileStores();
@SuppressWarnings("unchecked")
DefaultPieDataset<String>[] fsData = new DefaultPieDataset[fileStores.size()];
JFreeChart[] fsCharts = new JFreeChart[fsData.length];
JPanel fsPanel = new JPanel();
fsPanel.setLayout(new GridBagLayout());
GridBagConstraints fsConstraints = new GridBagConstraints();
fsConstraints.weightx = 1d;
fsConstraints.weighty = 1d;
fsConstraints.fill = GridBagConstraints.BOTH;
int modBase = (int) (fileStores.size() * (Config.GUI_HEIGHT + Config.GUI_WIDTH)
/ (Config.GUI_WIDTH * Math.sqrt(fileStores.size())));
for (int i = 0; i < fileStores.size(); i++) {
fsData[i] = new DefaultPieDataset<>();
fsCharts[i] = ChartFactory.createPieChart(null, fsData[i], true, true, false);
configurePlot(fsCharts[i]);
fsConstraints.gridx = i % modBase;
fsConstraints.gridy = i / modBase;
fsPanel.add(new ChartPanel(fsCharts[i]), fsConstraints);
}
updateDatasets(fs, fsData, fsCharts);
add(fsPanel, BorderLayout.CENTER);
Timer timer = new Timer(Config.REFRESH_SLOWER, e -> {
if (!updateDatasets(fs, fsData, fsCharts)) {
((Timer) e.getSource()).stop();
fsPanel.removeAll();
init(fs);
fsPanel.revalidate();
fsPanel.repaint();
}
});
timer.start();
| 669
| 494
| 1,163
|
<methods>public void <init>() <variables>protected javax.swing.JLabel msgLabel,protected javax.swing.JPanel msgPanel,private static final long serialVersionUID
|
oshi_oshi
|
oshi/oshi-demo/src/main/java/oshi/demo/gui/InterfacePanel.java
|
InterfacePanel
|
buildParamsText
|
class InterfacePanel extends OshiJPanel { // NOSONAR squid:S110
private static final long serialVersionUID = 1L;
private static final int INIT_HASH_SIZE = 100;
private static final String IP_ADDRESS_SEPARATOR = "; ";
private static final String PARAMS = "Network Parameters";
private static final String INTERFACES = "Network Interfaces";
private static final String[] COLUMNS = { "Name", "Index", "Speed", "IPv4 Address", "IPv6 address", "MAC address" };
private static final double[] COLUMN_WIDTH_PERCENT = { 0.02, 0.02, 0.1, 0.25, 0.45, 0.15 };
public InterfacePanel(SystemInfo si) {
super();
init(si);
}
private void init(SystemInfo si) {
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
JLabel paramsLabel = new JLabel(PARAMS);
paramsLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
add(paramsLabel);
JTextArea paramsArea = new JTextArea(0, 0);
paramsArea.setText(buildParamsText(si.getOperatingSystem()));
add(paramsArea);
JLabel interfaceLabel = new JLabel(INTERFACES);
interfaceLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
add(interfaceLabel);
List<NetworkIF> networkIfList = si.getHardware().getNetworkIFs(true);
TableModel model = new DefaultTableModel(parseInterfaces(networkIfList), COLUMNS);
JTable intfTable = new JTable(model);
JScrollPane scrollV = new JScrollPane(intfTable);
scrollV.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
resizeColumns(intfTable.getColumnModel());
add(scrollV);
}
private static String buildParamsText(OperatingSystem os) {<FILL_FUNCTION_BODY>}
private static Object[][] parseInterfaces(List<NetworkIF> list) {
Map<NetworkIF, Integer> intfSortValueMap = new HashMap<>(INIT_HASH_SIZE);
for (NetworkIF intf : list) {
intfSortValueMap.put(intf, intf.getIndex());
}
List<Entry<NetworkIF, Integer>> intfList = new ArrayList<>(intfSortValueMap.entrySet());
intfList.sort(Entry.comparingByValue());
int i = 0;
Object[][] intfArr = new Object[intfList.size()][COLUMNS.length];
for (Entry<NetworkIF, Integer> e : intfList) {
NetworkIF intf = e.getKey();
intfArr[i][0] = intf.getName();
intfArr[i][1] = intf.getIndex();
intfArr[i][2] = intf.getSpeed();
intfArr[i][3] = getIPAddressesString(intf.getIPv4addr());
intfArr[i][4] = getIPAddressesString(intf.getIPv6addr());
intfArr[i][5] = Constants.UNKNOWN.equals(intf.getMacaddr()) ? "" : intf.getMacaddr();
i++;
}
return intfArr;
}
private static void resizeColumns(TableColumnModel tableColumnModel) {
TableColumn column;
int tW = tableColumnModel.getTotalColumnWidth();
int cantCols = tableColumnModel.getColumnCount();
for (int i = 0; i < cantCols; i++) {
column = tableColumnModel.getColumn(i);
int pWidth = (int) Math.round(COLUMN_WIDTH_PERCENT[i] * tW);
column.setPreferredWidth(pWidth);
}
}
private static String getIPAddressesString(String[] ipAddressArr) {
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String ipAddress : ipAddressArr) {
if (first) {
first = false;
} else {
sb.append(IP_ADDRESS_SEPARATOR);
}
sb.append(ipAddress);
}
return sb.toString();
}
}
|
NetworkParams params = os.getNetworkParams();
StringBuilder sb = new StringBuilder("Host Name: ").append(params.getHostName());
if (!params.getDomainName().isEmpty()) {
sb.append("\nDomain Name: ").append(params.getDomainName());
}
sb.append("\nIPv4 Default Gateway: ").append(params.getIpv4DefaultGateway());
if (!params.getIpv6DefaultGateway().isEmpty()) {
sb.append("\nIPv6 Default Gateway: ").append(params.getIpv6DefaultGateway());
}
sb.append("\nDNS Servers: ").append(getIPAddressesString(params.getDnsServers()));
return sb.toString();
| 1,173
| 193
| 1,366
|
<methods>public void <init>() <variables>protected javax.swing.JLabel msgLabel,protected javax.swing.JPanel msgPanel,private static final long serialVersionUID
|
oshi_oshi
|
oshi/oshi-demo/src/main/java/oshi/demo/gui/MemoryPanel.java
|
MemoryPanel
|
init
|
class MemoryPanel extends OshiJPanel { // NOSONAR squid:S110
private static final long serialVersionUID = 1L;
private static final String PHYSICAL_MEMORY = "Physical Memory";
private static final String VIRTUAL_MEMORY = "Virtual Memory (Swap)";
private static final String USED = "Used";
private static final String AVAILABLE = "Available";
private static final DecimalFormatSymbols ROOT_SYMBOLS = DecimalFormatSymbols.getInstance(Locale.ROOT);
public MemoryPanel(SystemInfo si) {
super();
init(si.getHardware().getMemory());
}
private void init(GlobalMemory memory) {<FILL_FUNCTION_BODY>}
private static String updatePhysTitle(GlobalMemory memory) {
return memory.toString();
}
private static String updateVirtTitle(GlobalMemory memory) {
return memory.getVirtualMemory().toString();
}
private static String updateMemoryText(GlobalMemory memory) {
StringBuilder sb = new StringBuilder();
List<PhysicalMemory> pmList = memory.getPhysicalMemory();
for (PhysicalMemory pm : pmList) {
sb.append('\n').append(pm.toString());
}
return sb.toString();
}
private static void updateDatasets(GlobalMemory memory, DefaultPieDataset<String> physMemData,
DefaultPieDataset<String> virtMemData) {
physMemData.setValue(USED, (double) memory.getTotal() - memory.getAvailable());
physMemData.setValue(AVAILABLE, memory.getAvailable());
VirtualMemory virtualMemory = memory.getVirtualMemory();
virtMemData.setValue(USED, virtualMemory.getSwapUsed());
virtMemData.setValue(AVAILABLE, (double) virtualMemory.getSwapTotal() - virtualMemory.getSwapUsed());
}
private static void configurePlot(JFreeChart chart) {
@SuppressWarnings("unchecked")
PiePlot<String> plot = (PiePlot<String>) chart.getPlot();
plot.setSectionPaint(USED, Color.red);
plot.setSectionPaint(AVAILABLE, Color.green);
plot.setExplodePercent(USED, 0.10);
plot.setSimpleLabels(true);
PieSectionLabelGenerator labelGenerator = new StandardPieSectionLabelGenerator("{0}: {1} ({2})",
new DecimalFormat("0", ROOT_SYMBOLS), new DecimalFormat("0%", ROOT_SYMBOLS));
plot.setLabelGenerator(labelGenerator);
}
}
|
DefaultPieDataset<String> physMemData = new DefaultPieDataset<>();
DefaultPieDataset<String> virtMemData = new DefaultPieDataset<>();
updateDatasets(memory, physMemData, virtMemData);
JFreeChart physMem = ChartFactory.createPieChart(PHYSICAL_MEMORY, physMemData, true, true, false);
JFreeChart virtMem = ChartFactory.createPieChart(VIRTUAL_MEMORY, virtMemData, true, true, false);
configurePlot(physMem);
configurePlot(virtMem);
physMem.setSubtitles(Collections.singletonList(new TextTitle(updatePhysTitle(memory))));
virtMem.setSubtitles(Collections.singletonList(new TextTitle(updateVirtTitle(memory))));
GridBagConstraints pmConstraints = new GridBagConstraints();
pmConstraints.weightx = 1d;
pmConstraints.weighty = 1d;
pmConstraints.fill = GridBagConstraints.BOTH;
GridBagConstraints vmConstraints = (GridBagConstraints) pmConstraints.clone();
vmConstraints.gridx = 1;
GridBagConstraints textConstraints = new GridBagConstraints();
textConstraints.gridy = 1;
textConstraints.gridwidth = 2;
textConstraints.fill = GridBagConstraints.BOTH;
JPanel memoryPanel = new JPanel();
memoryPanel.setLayout(new GridBagLayout());
memoryPanel.add(new ChartPanel(physMem), pmConstraints);
memoryPanel.add(new ChartPanel(virtMem), vmConstraints);
JTextArea textArea = new JTextArea(60, 20);
textArea.setText(updateMemoryText(memory));
memoryPanel.add(textArea, textConstraints);
add(memoryPanel, BorderLayout.CENTER);
Timer timer = new Timer(Config.REFRESH_SLOW, e -> {
updateDatasets(memory, physMemData, virtMemData);
physMem.setSubtitles(Collections.singletonList(new TextTitle(updatePhysTitle(memory))));
virtMem.setSubtitles(Collections.singletonList(new TextTitle(updateVirtTitle(memory))));
textArea.setText(updateMemoryText(memory));
});
timer.start();
| 689
| 606
| 1,295
|
<methods>public void <init>() <variables>protected javax.swing.JLabel msgLabel,protected javax.swing.JPanel msgPanel,private static final long serialVersionUID
|
oshi_oshi
|
oshi/oshi-demo/src/main/java/oshi/demo/gui/OsHwTextPanel.java
|
OsHwTextPanel
|
init
|
class OsHwTextPanel extends OshiJPanel { // NOSONAR squid:S110
private static final long serialVersionUID = 1L;
private static final String OPERATING_SYSTEM = "Operating System";
private static final String HARDWARE_INFORMATION = "Hardware Information";
private static final String PROCESSOR = "Processor";
private static final String DISPLAYS = "Displays";
private String osPrefix;
public OsHwTextPanel(SystemInfo si) {
super();
init(si);
}
private void init(SystemInfo si) {<FILL_FUNCTION_BODY>}
private static String getOsPrefix(SystemInfo si) {
StringBuilder sb = new StringBuilder(OPERATING_SYSTEM);
OperatingSystem os = si.getOperatingSystem();
sb.append(String.valueOf(os));
sb.append("\n\n").append("Booted: ").append(Instant.ofEpochSecond(os.getSystemBootTime())).append('\n')
.append("Uptime: ");
return sb.toString();
}
private static String getHw(SystemInfo si) {
StringBuilder sb = new StringBuilder();
ObjectMapper mapper = new ObjectMapper();
ComputerSystem computerSystem = si.getHardware().getComputerSystem();
try {
sb.append(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(computerSystem));
} catch (JsonProcessingException e) {
sb.append(e.getMessage());
}
return sb.toString();
}
private static String getProc(SystemInfo si) {
StringBuilder sb = new StringBuilder();
CentralProcessor proc = si.getHardware().getProcessor();
sb.append(proc.toString());
return sb.toString();
}
private static String getDisplay(SystemInfo si) {
StringBuilder sb = new StringBuilder();
List<Display> displays = si.getHardware().getDisplays();
if (displays.isEmpty()) {
sb.append("None detected.");
} else {
int i = 0;
for (Display display : displays) {
byte[] edid = display.getEdid();
byte[][] desc = EdidUtil.getDescriptors(edid);
String name = "Display " + i;
for (byte[] b : desc) {
if (EdidUtil.getDescriptorType(b) == 0xfc) {
name = EdidUtil.getDescriptorText(b);
}
}
if (i++ > 0) {
sb.append('\n');
}
sb.append(name).append(": ");
int hSize = EdidUtil.getHcm(edid);
int vSize = EdidUtil.getVcm(edid);
sb.append(String.format(Locale.ROOT, "%d x %d cm (%.1f x %.1f in)", hSize, vSize, hSize / 2.54,
vSize / 2.54));
}
}
return sb.toString();
}
private String updateOsData(SystemInfo si) {
return osPrefix + FormatUtil.formatElapsedSecs(si.getOperatingSystem().getSystemUptime());
}
}
|
osPrefix = getOsPrefix(si);
GridBagConstraints osLabel = new GridBagConstraints();
GridBagConstraints osConstraints = new GridBagConstraints();
osConstraints.gridy = 1;
osConstraints.fill = GridBagConstraints.BOTH;
osConstraints.insets = new Insets(0, 0, 15, 15); // T,L,B,R
GridBagConstraints procLabel = (GridBagConstraints) osLabel.clone();
procLabel.gridy = 2;
GridBagConstraints procConstraints = (GridBagConstraints) osConstraints.clone();
procConstraints.gridy = 3;
GridBagConstraints displayLabel = (GridBagConstraints) procLabel.clone();
displayLabel.gridy = 4;
GridBagConstraints displayConstraints = (GridBagConstraints) osConstraints.clone();
displayConstraints.gridy = 5;
displayConstraints.insets = new Insets(0, 0, 0, 15); // T,L,B,R
GridBagConstraints csLabel = (GridBagConstraints) osLabel.clone();
csLabel.gridx = 1;
GridBagConstraints csConstraints = new GridBagConstraints();
csConstraints.gridx = 1;
csConstraints.gridheight = 6;
csConstraints.fill = GridBagConstraints.BOTH;
JPanel oshwPanel = new JPanel();
oshwPanel.setLayout(new GridBagLayout());
JTextArea osArea = new JTextArea(0, 0);
osArea.setText(updateOsData(si));
oshwPanel.add(new JLabel(OPERATING_SYSTEM), osLabel);
oshwPanel.add(osArea, osConstraints);
JTextArea procArea = new JTextArea(0, 0);
procArea.setText(getProc(si));
oshwPanel.add(new JLabel(PROCESSOR), procLabel);
oshwPanel.add(procArea, procConstraints);
JTextArea displayArea = new JTextArea(0, 0);
displayArea.setText(getDisplay(si));
oshwPanel.add(new JLabel(DISPLAYS), displayLabel);
oshwPanel.add(displayArea, displayConstraints);
JTextArea csArea = new JTextArea(0, 0);
csArea.setText(getHw(si));
oshwPanel.add(new JLabel(HARDWARE_INFORMATION), csLabel);
oshwPanel.add(csArea, csConstraints);
add(oshwPanel, BorderLayout.CENTER);
// Update up time every second
Timer timer = new Timer(Config.REFRESH_FAST, e -> osArea.setText(updateOsData(si)));
timer.start();
| 838
| 759
| 1,597
|
<methods>public void <init>() <variables>protected javax.swing.JLabel msgLabel,protected javax.swing.JPanel msgPanel,private static final long serialVersionUID
|
oshi_oshi
|
oshi/oshi-demo/src/main/java/oshi/demo/gui/ProcessorPanel.java
|
ProcessorPanel
|
init
|
class ProcessorPanel extends OshiJPanel { // NOSONAR squid:S110
private static final long serialVersionUID = 1L;
private long[] oldTicks;
private long[][] oldProcTicks;
public ProcessorPanel(SystemInfo si) {
super();
CentralProcessor cpu = si.getHardware().getProcessor();
oldTicks = new long[TickType.values().length];
oldProcTicks = new long[cpu.getLogicalProcessorCount()][TickType.values().length];
init(cpu);
}
private void init(CentralProcessor processor) {<FILL_FUNCTION_BODY>}
private static float[] floatArrayPercent(double d) {
float[] f = new float[1];
f[0] = (float) (100d * d);
return f;
}
private double cpuData(CentralProcessor proc) {
double d = proc.getSystemCpuLoadBetweenTicks(oldTicks);
oldTicks = proc.getSystemCpuLoadTicks();
return d;
}
private double[] procData(CentralProcessor proc) {
double[] p = proc.getProcessorCpuLoadBetweenTicks(oldProcTicks);
oldProcTicks = proc.getProcessorCpuLoadTicks();
return p;
}
}
|
GridBagConstraints sysConstraints = new GridBagConstraints();
sysConstraints.weightx = 1d;
sysConstraints.weighty = 1d;
sysConstraints.fill = GridBagConstraints.BOTH;
GridBagConstraints procConstraints = (GridBagConstraints) sysConstraints.clone();
procConstraints.gridx = 1;
Date date = Date.from(LocalDateTime.now(ZoneId.systemDefault()).atZone(ZoneId.systemDefault()).toInstant());
DynamicTimeSeriesCollection sysData = new DynamicTimeSeriesCollection(1, 60, new Second());
sysData.setTimeBase(new Second(date));
sysData.addSeries(floatArrayPercent(cpuData(processor)), 0, "All cpus");
JFreeChart systemCpu = ChartFactory.createTimeSeriesChart("System CPU Usage", "Time", "% CPU", sysData, true,
true, false);
double[] procUsage = procData(processor);
DynamicTimeSeriesCollection procData = new DynamicTimeSeriesCollection(procUsage.length, 60, new Second());
procData.setTimeBase(new Second(date));
for (int i = 0; i < procUsage.length; i++) {
procData.addSeries(floatArrayPercent(procUsage[i]), i, "cpu" + i);
}
JFreeChart procCpu = ChartFactory.createTimeSeriesChart("Processor CPU Usage", "Time", "% CPU", procData, true,
true, false);
JPanel cpuPanel = new JPanel();
cpuPanel.setLayout(new GridBagLayout());
cpuPanel.add(new ChartPanel(systemCpu), sysConstraints);
cpuPanel.add(new ChartPanel(procCpu), procConstraints);
add(cpuPanel, BorderLayout.CENTER);
Timer timer = new Timer(Config.REFRESH_FAST, e -> {
sysData.advanceTime();
sysData.appendData(floatArrayPercent(cpuData(processor)));
procData.advanceTime();
int newest = procData.getNewestIndex();
double[] procUsageData = procData(processor);
for (int i = 0; i < procUsageData.length; i++) {
procData.addValue(i, newest, (float) (100 * procUsageData[i]));
}
});
timer.start();
| 352
| 614
| 966
|
<methods>public void <init>() <variables>protected javax.swing.JLabel msgLabel,protected javax.swing.JPanel msgPanel,private static final long serialVersionUID
|
oshi_oshi
|
oshi/oshi-demo/src/main/java/oshi/demo/gui/UsbPanel.java
|
UsbPanel
|
init
|
class UsbPanel extends OshiJPanel { // NOSONAR squid:S110
private static final long serialVersionUID = 1L;
private static final String USB_DEVICES = "USB Devices";
public UsbPanel(SystemInfo si) {
super();
init(si.getHardware());
}
private void init(HardwareAbstractionLayer hal) {<FILL_FUNCTION_BODY>}
private static String getUsbString(HardwareAbstractionLayer hal) {
StringBuilder sb = new StringBuilder();
boolean first = true;
for (UsbDevice usbDevice : hal.getUsbDevices(true)) {
if (first) {
first = false;
} else {
sb.append('\n');
}
sb.append(String.valueOf(usbDevice));
}
return sb.toString();
}
}
|
JLabel usb = new JLabel(USB_DEVICES);
add(usb, BorderLayout.NORTH);
JTextArea usbArea = new JTextArea(60, 20);
JScrollPane scrollV = new JScrollPane(usbArea);
scrollV.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
DefaultCaret caret = (DefaultCaret) usbArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
usbArea.setText(getUsbString(hal));
add(scrollV, BorderLayout.CENTER);
Timer timer = new Timer(Config.REFRESH_SLOW, e -> usbArea.setText(getUsbString(hal)));
timer.start();
| 232
| 211
| 443
|
<methods>public void <init>() <variables>protected javax.swing.JLabel msgLabel,protected javax.swing.JPanel msgPanel,private static final long serialVersionUID
|
oshi_oshi
|
oshi/oshi-demo/src/main/java/oshi/demo/jmx/demo/Client.java
|
Client
|
main
|
class Client {
@SuppressForbidden(reason = "Using System.out in a demo class")
public static void main(String[] args) throws IOException, MalformedObjectNameException, ReflectionException,
InstanceNotFoundException, MBeanException, AttributeNotFoundException {<FILL_FUNCTION_BODY>}
}
|
// The address of the connector server
JMXServiceURL address = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:8888/server");
// Map for custom properties key values
Map<String, ?> environment = null;
// Create the JMXCconnectorServer
JMXConnector cntor = JMXConnectorFactory.connect(address, environment);
// Obtain a "stub" for the remote MBeanServer
MBeanServerConnection mbsc = cntor.getMBeanServerConnection();
// Here we can obtain all the domains and there would be one called oshi, meaning
// that is the one that we registered into our MbeanServer related with the
// baseboard
ObjectName objectQuery = new ObjectName("oshi:component=BaseBoard");
PropertiesAvailable mBean = MBeanServerInvocationHandler.newProxyInstance(mbsc, objectQuery,
PropertiesAvailable.class, false);
List<String> mBeanInfo = mBean.getProperties();
System.out.println(mbsc.getAttribute(objectQuery, mBeanInfo.get(1)));
System.out.println(mbsc.getAttribute(objectQuery, mBeanInfo.get(2)));
System.out.println(mbsc.getAttribute(objectQuery, mBeanInfo.get(3)));
System.out.println(mbsc.getAttribute(objectQuery, mBeanInfo.get(4)));
| 79
| 364
| 443
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-demo/src/main/java/oshi/demo/jmx/mbeans/Baseboard.java
|
Baseboard
|
setUpMBean
|
class Baseboard implements DynamicMBean, PropertiesAvailable {
private oshi.hardware.Baseboard baseboard;
private MBeanInfo dMBeanInfo = null;
private List<String> propertiesAvailable = new ArrayList<>();
private final String PROPERTIES = "Properties";
private void setUpMBean() throws IntrospectionException, javax.management.IntrospectionException {<FILL_FUNCTION_BODY>}
public Baseboard(oshi.hardware.Baseboard baseboard)
throws IntrospectionException, javax.management.IntrospectionException {
this.baseboard = baseboard;
this.setUpMBean();
}
@Override
public Object getAttribute(String attribute) {
switch (attribute) {
case PROPERTIES:
return this.getProperties();
case "Manufacturer":
return baseboard.getManufacturer();
case "Model":
return baseboard.getModel();
case "Version":
return baseboard.getVersion();
case "SerialNumber":
return baseboard.getSerialNumber();
default:
throw new IllegalArgumentException("No attribute " + attribute);
}
}
@Override
public MBeanInfo getMBeanInfo() {
return dMBeanInfo;
}
@Override
public List<String> getProperties() {
return propertiesAvailable;
}
@Override
public void setAttribute(Attribute attribute)
throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException {
}
@Override
public AttributeList getAttributes(String[] attributes) {
return null;
}
@Override
public AttributeList setAttributes(AttributeList attributes) {
return null;
}
@Override
public Object invoke(String actionName, Object[] params, String[] signature)
throws MBeanException, ReflectionException {
return null;
}
}
|
PropertyDescriptor[] methods = Introspector.getBeanInfo(baseboard.getClass()).getPropertyDescriptors();
MBeanAttributeInfo[] attributeInfos = new MBeanAttributeInfo[methods.length];
for (int i = 0; i < methods.length; i++) {
attributeInfos[i] = new MBeanAttributeInfo(methods[i].getName(), methods[i].getShortDescription(),
methods[i].getReadMethod(), null);
propertiesAvailable.add(
methods[i].getName().substring(0, 1).toUpperCase(Locale.ROOT) + methods[i].getName().substring(1));
}
dMBeanInfo = new MBeanInfo(baseboard.getClass().getName(), null, attributeInfos, null, null,
new MBeanNotificationInfo[0]);
| 483
| 203
| 686
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-demo/src/main/java/oshi/demo/jmx/strategiesplatform/WindowsStrategyRegistrattionPlatform.java
|
WindowsStrategyRegistrattionPlatform
|
registerMBeans
|
class WindowsStrategyRegistrattionPlatform implements StrategyRegistrationPlatformMBeans {
@Override
public void registerMBeans(SystemInfo systemInfo, MBeanServer mBeanServer)
throws NotCompliantMBeanException, InstanceAlreadyExistsException, MBeanRegistrationException,
MalformedObjectNameException, IntrospectionException, javax.management.IntrospectionException {<FILL_FUNCTION_BODY>}
}
|
// here we can register all the MBeans reletad to windows. for this sample we
// are only gonna register one MBean with two Attribute
ObjectName objectName = new ObjectName("oshi:component=BaseBoard");
oshi.demo.jmx.mbeans.Baseboard baseBoardMBean = new oshi.demo.jmx.mbeans.Baseboard(
systemInfo.getHardware().getComputerSystem().getBaseboard());
mBeanServer.registerMBean(baseBoardMBean, objectName);
| 104
| 138
| 242
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-cas/src/main/java/org/pac4j/cas/authorization/DefaultCasAuthorizationGenerator.java
|
DefaultCasAuthorizationGenerator
|
generate
|
class DefaultCasAuthorizationGenerator implements AuthorizationGenerator {
/** Constant <code>DEFAULT_REMEMBER_ME_ATTRIBUTE_NAME="longTermAuthenticationRequestTokenUsed"</code> */
public static final String DEFAULT_REMEMBER_ME_ATTRIBUTE_NAME = "longTermAuthenticationRequestTokenUsed";
// default name of the CAS attribute for remember me authentication (CAS 3.4.10+)
protected String rememberMeAttributeName = DEFAULT_REMEMBER_ME_ATTRIBUTE_NAME;
/**
* <p>Constructor for DefaultCasAuthorizationGenerator.</p>
*/
public DefaultCasAuthorizationGenerator() {
}
/**
* <p>Constructor for DefaultCasAuthorizationGenerator.</p>
*
* @param rememberMeAttributeName a {@link String} object
*/
public DefaultCasAuthorizationGenerator(final String rememberMeAttributeName) {
this.rememberMeAttributeName = rememberMeAttributeName;
}
/** {@inheritDoc} */
@Override
public Optional<UserProfile> generate(final CallContext ctx, final UserProfile profile) {<FILL_FUNCTION_BODY>}
}
|
val rememberMeValue = (String) profile.getAttribute(rememberMeAttributeName);
val isRemembered = rememberMeValue != null && Boolean.parseBoolean(rememberMeValue);
profile.setRemembered(isRemembered);
return Optional.of(profile);
| 294
| 72
| 366
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-cas/src/main/java/org/pac4j/cas/client/CasClient.java
|
CasClient
|
internalInit
|
class CasClient extends IndirectClient {
@Getter
@Setter
private CasConfiguration configuration = new CasConfiguration();
/**
* <p>Constructor for CasClient.</p>
*/
public CasClient() { }
/**
* <p>Constructor for CasClient.</p>
*
* @param configuration a {@link CasConfiguration} object
*/
public CasClient(final CasConfiguration configuration) {
setConfiguration(configuration);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
protected CallbackUrlResolver newDefaultCallbackUrlResolver() {
return new QueryParameterCallbackUrlResolver(configuration.getCustomParams());
}
/** {@inheritDoc} */
@Override
public void notifySessionRenewal(final CallContext ctx, final String oldSessionId) {
val sessionLogoutHandler = findSessionLogoutHandler();
if (sessionLogoutHandler != null) {
findSessionLogoutHandler().renewSession(ctx, oldSessionId);
}
}
}
|
assertNotNull("configuration", configuration);
configuration.setUrlResolver(this.getUrlResolver());
setRedirectionActionBuilderIfUndefined(new CasRedirectionActionBuilder(configuration, this));
setCredentialsExtractorIfUndefined(new CasCredentialsExtractor(configuration));
setAuthenticatorIfUndefined(new CasAuthenticator(configuration, getName(),getUrlResolver(), getCallbackUrlResolver(),
callbackUrl, findSessionLogoutHandler()));
setLogoutProcessorIfUndefined(new CasLogoutProcessor(configuration, findSessionLogoutHandler()));
setLogoutActionBuilderIfUndefined(new CasLogoutActionBuilder(configuration.computeFinalPrefixUrl(null) + "logout",
configuration.getPostLogoutUrlParameter()));
addAuthorizationGenerator(new DefaultCasAuthorizationGenerator());
| 295
| 197
| 492
|
<methods>public non-sealed void <init>() ,public java.lang.String computeFinalCallbackUrl(org.pac4j.core.context.WebContext) ,public java.lang.String getCodeVerifierSessionAttributeName() ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getLogoutAction(CallContext, org.pac4j.core.profile.UserProfile, java.lang.String) ,public java.lang.String getNonceSessionAttributeName() ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getRedirectionAction(CallContext) ,public java.lang.String getStateSessionAttributeName() ,public org.pac4j.core.exception.http.HttpAction processLogout(CallContext, org.pac4j.core.credentials.Credentials) <variables>public static final java.lang.String ATTEMPTED_AUTHENTICATION_SUFFIX,private static final java.lang.String CODE_VERIFIER_SESSION_PARAMETER,private static final java.lang.String NONCE_SESSION_PARAMETER,private static final java.lang.String STATE_SESSION_PARAMETER,private org.pac4j.core.http.ajax.AjaxRequestResolver ajaxRequestResolver,protected java.lang.String callbackUrl,protected org.pac4j.core.http.callback.CallbackUrlResolver callbackUrlResolver,private boolean checkAuthenticationAttempt,private org.pac4j.core.logout.LogoutActionBuilder logoutActionBuilder,private org.pac4j.core.logout.processor.LogoutProcessor logoutProcessor,private org.pac4j.core.redirect.RedirectionActionBuilder redirectionActionBuilder,protected org.pac4j.core.http.url.UrlResolver urlResolver
|
pac4j_pac4j
|
pac4j/pac4j-cas/src/main/java/org/pac4j/cas/client/CasProxyReceptor.java
|
CasProxyReceptor
|
internalInit
|
class CasProxyReceptor extends IndirectClient {
/** Constant <code>PARAM_PROXY_GRANTING_TICKET_IOU="pgtIou"</code> */
public static final String PARAM_PROXY_GRANTING_TICKET_IOU = "pgtIou";
/** Constant <code>PARAM_PROXY_GRANTING_TICKET="pgtId"</code> */
public static final String PARAM_PROXY_GRANTING_TICKET = "pgtId";
private Store<String, String> store = new GuavaStore<>(1000, 1, TimeUnit.MINUTES);
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
}
|
assertNotNull("store", this.store);
setRedirectionActionBuilderIfUndefined(ctx
-> { throw new TechnicalException("Not supported by the CAS proxy receptor"); });
setCredentialsExtractorIfUndefined(ctx -> {
val webContext = ctx.webContext();
// like CommonUtils.readAndRespondToProxyReceptorRequest in CAS client
val proxyGrantingTicketIou = webContext.getRequestParameter(PARAM_PROXY_GRANTING_TICKET_IOU);
logger.debug("proxyGrantingTicketIou: {}", proxyGrantingTicketIou);
val proxyGrantingTicket = webContext.getRequestParameter(PARAM_PROXY_GRANTING_TICKET);
logger.debug("proxyGrantingTicket: {}", proxyGrantingTicket);
if (proxyGrantingTicket.isEmpty() || proxyGrantingTicketIou.isEmpty()) {
logger.warn("Missing proxyGrantingTicket or proxyGrantingTicketIou -> returns ok");
throw new OkAction(Pac4jConstants.EMPTY_STRING);
}
this.store.set(proxyGrantingTicketIou.get(), proxyGrantingTicket.get());
logger.debug("Found pgtIou and pgtId for CAS proxy receptor -> returns ok");
throw new OkAction("<?xml version=\"1.0\"?>\n<casClient:proxySuccess xmlns:casClient=\"http://www.yale.edu/tp/casClient\" />");
});
setAuthenticatorIfUndefined((ctx, credentials)
-> { throw new TechnicalException("Not supported by the CAS proxy receptor"); });
| 206
| 431
| 637
|
<methods>public non-sealed void <init>() ,public java.lang.String computeFinalCallbackUrl(org.pac4j.core.context.WebContext) ,public java.lang.String getCodeVerifierSessionAttributeName() ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getLogoutAction(CallContext, org.pac4j.core.profile.UserProfile, java.lang.String) ,public java.lang.String getNonceSessionAttributeName() ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getRedirectionAction(CallContext) ,public java.lang.String getStateSessionAttributeName() ,public org.pac4j.core.exception.http.HttpAction processLogout(CallContext, org.pac4j.core.credentials.Credentials) <variables>public static final java.lang.String ATTEMPTED_AUTHENTICATION_SUFFIX,private static final java.lang.String CODE_VERIFIER_SESSION_PARAMETER,private static final java.lang.String NONCE_SESSION_PARAMETER,private static final java.lang.String STATE_SESSION_PARAMETER,private org.pac4j.core.http.ajax.AjaxRequestResolver ajaxRequestResolver,protected java.lang.String callbackUrl,protected org.pac4j.core.http.callback.CallbackUrlResolver callbackUrlResolver,private boolean checkAuthenticationAttempt,private org.pac4j.core.logout.LogoutActionBuilder logoutActionBuilder,private org.pac4j.core.logout.processor.LogoutProcessor logoutProcessor,private org.pac4j.core.redirect.RedirectionActionBuilder redirectionActionBuilder,protected org.pac4j.core.http.url.UrlResolver urlResolver
|
pac4j_pac4j
|
pac4j/pac4j-cas/src/main/java/org/pac4j/cas/client/direct/DirectCasProxyClient.java
|
DirectCasProxyClient
|
internalInit
|
class DirectCasProxyClient extends DirectClient {
private CasConfiguration configuration;
private UrlResolver urlResolver = new DefaultUrlResolver();
private CallbackUrlResolver callbackUrlResolver = new NoParameterCallbackUrlResolver();
private String serviceUrl;
/**
* <p>Constructor for DirectCasProxyClient.</p>
*/
public DirectCasProxyClient() { }
/**
* <p>Constructor for DirectCasProxyClient.</p>
*
* @param casConfiguration a {@link CasConfiguration} object
* @param serviceUrl a {@link String} object
*/
public DirectCasProxyClient(final CasConfiguration casConfiguration, final String serviceUrl) {
this.configuration = casConfiguration;
this.serviceUrl = serviceUrl;
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
}
|
assertNotBlank("serviceUrl", this.serviceUrl);
assertNotNull("configuration", this.configuration);
// must be a CAS proxy protocol
val protocol = configuration.getProtocol();
assertTrue(protocol == CasProtocol.CAS20_PROXY || protocol == CasProtocol.CAS30_PROXY,
"The DirectCasProxyClient must be configured with a CAS proxy protocol (CAS20_PROXY or CAS30_PROXY)");
setCredentialsExtractorIfUndefined(new ParameterExtractor(CasConfiguration.TICKET_PARAMETER, true, false));
setAuthenticatorIfUndefined(new CasAuthenticator(configuration, getName(), urlResolver, callbackUrlResolver, this.serviceUrl,
findSessionLogoutHandler()));
addAuthorizationGenerator(new DefaultCasAuthorizationGenerator());
| 236
| 208
| 444
|
<methods>public non-sealed void <init>() ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getLogoutAction(CallContext, org.pac4j.core.profile.UserProfile, java.lang.String) ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getRedirectionAction(CallContext) ,public final org.pac4j.core.exception.http.HttpAction processLogout(CallContext, org.pac4j.core.credentials.Credentials) <variables>
|
pac4j_pac4j
|
pac4j/pac4j-cas/src/main/java/org/pac4j/cas/client/rest/AbstractCasRestClient.java
|
AbstractCasRestClient
|
requestServiceTicket
|
class AbstractCasRestClient extends DirectClient {
@Getter
@Setter
protected CasConfiguration configuration;
/**
* <p>destroyTicketGrantingTicket.</p>
*
* @param profile a {@link CasRestProfile} object
* @param context a {@link WebContext} object
*/
public void destroyTicketGrantingTicket(final CasRestProfile profile, final WebContext context) {
HttpURLConnection connection = null;
try {
val endpointURL = new URL(configuration.computeFinalRestUrl(context));
val deleteURL = new URL(endpointURL, endpointURL.getPath() + "/" + profile.getTicketGrantingTicketId());
connection = HttpUtils.openDeleteConnection(deleteURL);
val responseCode = connection.getResponseCode();
if (responseCode != HttpConstants.OK) {
throw new TechnicalException("TGT delete request for `" + profile + "` failed: " +
HttpUtils.buildHttpErrorMessage(connection));
}
} catch (final IOException e) {
throw new TechnicalException(e);
} finally {
HttpUtils.closeConnection(connection);
}
}
/**
* <p>requestServiceTicket.</p>
*
* @param serviceURL a {@link String} object
* @param profile a {@link CasRestProfile} object
* @param context a {@link WebContext} object
* @return a {@link TokenCredentials} object
*/
public TokenCredentials requestServiceTicket(final String serviceURL, final CasRestProfile profile, final WebContext context) {<FILL_FUNCTION_BODY>}
/**
* <p>validateServiceTicket.</p>
*
* @param serviceURL a {@link String} object
* @param ticket a {@link TokenCredentials} object
* @param context a {@link WebContext} object
* @return a {@link CasProfile} object
*/
public CasProfile validateServiceTicket(final String serviceURL, final TokenCredentials ticket, final WebContext context) {
try {
val assertion = configuration.retrieveTicketValidator(context).validate(ticket.getToken(), serviceURL);
val principal = assertion.getPrincipal();
val casProfile = new CasProfile();
casProfile.setId(ProfileHelper.sanitizeIdentifier(principal.getName()));
casProfile.addAttributes(principal.getAttributes());
return casProfile;
} catch (final TicketValidationException e) {
throw new TechnicalException(e);
}
}
}
|
HttpURLConnection connection = null;
try {
val endpointURL = new URL(configuration.computeFinalRestUrl(context));
val ticketURL = new URL(endpointURL, endpointURL.getPath() + "/" + profile.getTicketGrantingTicketId());
connection = HttpUtils.openPostConnection(ticketURL);
val payload = HttpUtils.encodeQueryParam("service", serviceURL);
val out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8));
out.write(payload);
out.close();
val responseCode = connection.getResponseCode();
if (responseCode == HttpConstants.OK) {
try (var in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
return new TokenCredentials(in.readLine());
}
}
throw new TechnicalException("Service ticket request for `" + profile + "` failed: " +
HttpUtils.buildHttpErrorMessage(connection));
} catch (final IOException e) {
throw new TechnicalException(e);
} finally {
HttpUtils.closeConnection(connection);
}
| 643
| 294
| 937
|
<methods>public non-sealed void <init>() ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getLogoutAction(CallContext, org.pac4j.core.profile.UserProfile, java.lang.String) ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getRedirectionAction(CallContext) ,public final org.pac4j.core.exception.http.HttpAction processLogout(CallContext, org.pac4j.core.credentials.Credentials) <variables>
|
pac4j_pac4j
|
pac4j/pac4j-cas/src/main/java/org/pac4j/cas/client/rest/CasRestBasicAuthClient.java
|
CasRestBasicAuthClient
|
internalInit
|
class CasRestBasicAuthClient extends AbstractCasRestClient {
private String headerName = HttpConstants.AUTHORIZATION_HEADER;
private String prefixHeader = HttpConstants.BASIC_HEADER_PREFIX;
/**
* <p>Constructor for CasRestBasicAuthClient.</p>
*/
public CasRestBasicAuthClient() {}
/**
* <p>Constructor for CasRestBasicAuthClient.</p>
*
* @param configuration a {@link CasConfiguration} object
* @param headerName a {@link String} object
* @param prefixHeader a {@link String} object
*/
public CasRestBasicAuthClient(final CasConfiguration configuration,
final String headerName, final String prefixHeader) {
this.configuration = configuration;
this.headerName = headerName;
this.prefixHeader = prefixHeader;
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
}
|
assertNotBlank("headerName", this.headerName);
assertNotNull("prefixHeader", this.prefixHeader);
assertNotNull("configuration", this.configuration);
setCredentialsExtractorIfUndefined(new BasicAuthExtractor(this.headerName, this.prefixHeader));
setAuthenticatorIfUndefined(new CasRestAuthenticator(this.configuration));
| 256
| 93
| 349
|
<methods>public non-sealed void <init>() ,public void destroyTicketGrantingTicket(org.pac4j.cas.profile.CasRestProfile, org.pac4j.core.context.WebContext) ,public org.pac4j.core.credentials.TokenCredentials requestServiceTicket(java.lang.String, org.pac4j.cas.profile.CasRestProfile, org.pac4j.core.context.WebContext) ,public org.pac4j.cas.profile.CasProfile validateServiceTicket(java.lang.String, org.pac4j.core.credentials.TokenCredentials, org.pac4j.core.context.WebContext) <variables>protected org.pac4j.cas.config.CasConfiguration configuration
|
pac4j_pac4j
|
pac4j/pac4j-cas/src/main/java/org/pac4j/cas/client/rest/CasRestFormClient.java
|
CasRestFormClient
|
internalInit
|
class CasRestFormClient extends AbstractCasRestClient {
private String usernameParameter = Pac4jConstants.USERNAME;
private String passwordParameter = Pac4jConstants.PASSWORD;
/**
* <p>Constructor for CasRestFormClient.</p>
*/
public CasRestFormClient() {}
/**
* <p>Constructor for CasRestFormClient.</p>
*
* @param configuration a {@link CasConfiguration} object
* @param usernameParameter a {@link String} object
* @param passwordParameter a {@link String} object
*/
public CasRestFormClient(final CasConfiguration configuration, final String usernameParameter, final String passwordParameter) {
this.configuration = configuration;
this.usernameParameter = usernameParameter;
this.passwordParameter = passwordParameter;
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
}
|
assertNotBlank("usernameParameter", this.usernameParameter);
assertNotBlank("passwordParameter", this.passwordParameter);
assertNotNull("configuration", this.configuration);
setCredentialsExtractorIfUndefined(new FormExtractor(this.usernameParameter, this.passwordParameter));
setAuthenticatorIfUndefined(new CasRestAuthenticator(this.configuration));
| 240
| 94
| 334
|
<methods>public non-sealed void <init>() ,public void destroyTicketGrantingTicket(org.pac4j.cas.profile.CasRestProfile, org.pac4j.core.context.WebContext) ,public org.pac4j.core.credentials.TokenCredentials requestServiceTicket(java.lang.String, org.pac4j.cas.profile.CasRestProfile, org.pac4j.core.context.WebContext) ,public org.pac4j.cas.profile.CasProfile validateServiceTicket(java.lang.String, org.pac4j.core.credentials.TokenCredentials, org.pac4j.core.context.WebContext) <variables>protected org.pac4j.cas.config.CasConfiguration configuration
|
pac4j_pac4j
|
pac4j/pac4j-cas/src/main/java/org/pac4j/cas/credentials/authenticator/CasAuthenticator.java
|
CasAuthenticator
|
validateTicket
|
class CasAuthenticator extends ProfileDefinitionAware implements Authenticator {
protected CasConfiguration configuration;
protected String clientName;
protected UrlResolver urlResolver;
protected CallbackUrlResolver callbackUrlResolver;
protected String callbackUrl;
protected SessionLogoutHandler sessionLogoutHandler;
/**
* <p>Constructor for CasAuthenticator.</p>
*
* @param configuration a {@link CasConfiguration} object
* @param clientName a {@link String} object
* @param urlResolver a {@link UrlResolver} object
* @param callbackUrlResolver a {@link CallbackUrlResolver} object
* @param callbackUrl a {@link String} object
* @param sessionLogoutHandler the sessionLogoutHandler
*/
public CasAuthenticator(final CasConfiguration configuration, final String clientName, final UrlResolver urlResolver,
final CallbackUrlResolver callbackUrlResolver, final String callbackUrl,
final SessionLogoutHandler sessionLogoutHandler) {
this.configuration = configuration;
this.clientName = clientName;
this.urlResolver = urlResolver;
this.callbackUrlResolver = callbackUrlResolver;
this.callbackUrl = callbackUrl;
this.sessionLogoutHandler = sessionLogoutHandler;
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {
CommonHelper.assertNotNull("urlResolver", urlResolver);
CommonHelper.assertNotNull("callbackUrlResolver", callbackUrlResolver);
CommonHelper.assertNotBlank("clientName", clientName);
CommonHelper.assertNotBlank("callbackUrl", callbackUrl);
CommonHelper.assertNotNull("configuration", configuration);
setProfileDefinitionIfUndefined(new CasProfileDefinition());
}
@Override
public Optional<Credentials> validate(final CallContext ctx, final Credentials cred) {
if (cred instanceof TokenCredentials credentials) {
init();
val webContext = ctx.webContext();
val ticket = credentials.getToken();
try {
val assertion = validateTicket(webContext, ticket);
recordSession(ctx, ticket);
val principal = assertion.getPrincipal();
LOGGER.debug("principal: {}", principal);
val profile = createUserProfile(principal);
createUserProfileAttributes(assertion, principal, profile);
LOGGER.debug("profile returned by CAS: {}", profile);
credentials.setUserProfile(profile);
} catch (final TicketValidationException e) {
var message = "cannot validate CAS ticket: " + ticket;
throw new TechnicalException(message, e);
}
}
return Optional.ofNullable(cred);
}
protected void recordSession(final CallContext ctx, final String ticket) {
if (sessionLogoutHandler != null) {
sessionLogoutHandler.recordSession(ctx, ticket);
}
}
protected void createUserProfileAttributes(final Assertion assertion, final AttributePrincipal principal,
final UserProfile profile) {
Map<String, Object> newPrincipalAttributes = new HashMap<>();
Map<String, Object> newAuthenticationAttributes = new HashMap<>();
// restore both sets of attributes
val oldPrincipalAttributes = principal.getAttributes();
val oldAuthenticationAttributes = assertion.getAttributes();
if (oldPrincipalAttributes != null) {
newPrincipalAttributes.putAll(oldPrincipalAttributes);
}
if (oldAuthenticationAttributes != null) {
newAuthenticationAttributes.putAll(oldAuthenticationAttributes);
}
getProfileDefinition().convertAndAdd(profile, newPrincipalAttributes, newAuthenticationAttributes);
}
protected UserProfile createUserProfile(final AttributePrincipal principal) {
val id = principal.getName();
val profile = getProfileDefinition().newProfile(id, configuration.getProxyReceptor(), principal);
profile.setId(ProfileHelper.sanitizeIdentifier(id));
return profile;
}
protected Assertion validateTicket(final WebContext webContext, final String ticket) throws TicketValidationException {<FILL_FUNCTION_BODY>}
}
|
val finalCallbackUrl = callbackUrlResolver.compute(urlResolver, callbackUrl, clientName, webContext);
return configuration.retrieveTicketValidator(webContext).validate(ticket, finalCallbackUrl);
| 1,015
| 51
| 1,066
|
<methods>public non-sealed void <init>() ,public org.pac4j.core.profile.definition.ProfileDefinition getProfileDefinition() ,public void setProfileDefinition(org.pac4j.core.profile.definition.ProfileDefinition) <variables>private org.pac4j.core.profile.definition.ProfileDefinition profileDefinition
|
pac4j_pac4j
|
pac4j/pac4j-cas/src/main/java/org/pac4j/cas/credentials/authenticator/CasRestAuthenticator.java
|
CasRestAuthenticator
|
validate
|
class CasRestAuthenticator implements Authenticator {
protected CasConfiguration configuration;
/**
* <p>Constructor for CasRestAuthenticator.</p>
*
* @param configuration a {@link CasConfiguration} object
*/
public CasRestAuthenticator(final CasConfiguration configuration) {
CommonHelper.assertNotNull("configuration", configuration);
this.configuration = configuration;
}
/** {@inheritDoc} */
@Override
public Optional<Credentials> validate(final CallContext ctx, final Credentials cred) {<FILL_FUNCTION_BODY>}
private String requestTicketGrantingTicket(final String username, final String password, final WebContext context) {
HttpURLConnection connection = null;
try {
connection = HttpUtils.openPostConnection(new URL(this.configuration.computeFinalRestUrl(context)));
val payload = HttpUtils.encodeQueryParam(Pac4jConstants.USERNAME, username)
+ "&" + HttpUtils.encodeQueryParam(Pac4jConstants.PASSWORD, password);
val out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8));
out.write(payload);
out.close();
val locationHeader = connection.getHeaderField("location");
val responseCode = connection.getResponseCode();
if (locationHeader != null && responseCode == HttpConstants.CREATED) {
return locationHeader.substring(locationHeader.lastIndexOf("/") + 1);
}
LOGGER.debug("Ticket granting ticket request failed: " + locationHeader + " " + responseCode +
HttpUtils.buildHttpErrorMessage(connection));
return null;
} catch (final IOException e) {
throw new TechnicalException(e);
} finally {
HttpUtils.closeConnection(connection);
}
}
}
|
val credentials = (UsernamePasswordCredentials) cred;
if (credentials == null || credentials.getPassword() == null || credentials.getUsername() == null) {
throw new TechnicalException("Credentials are required");
}
val ticketGrantingTicketId = requestTicketGrantingTicket(credentials.getUsername(), credentials.getPassword(), ctx.webContext());
if (CommonHelper.isNotBlank(ticketGrantingTicketId)) {
credentials.setUserProfile(new CasRestProfile(ticketGrantingTicketId, credentials.getUsername()));
}
return Optional.of(credentials);
| 461
| 159
| 620
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-cas/src/main/java/org/pac4j/cas/credentials/extractor/CasCredentialsExtractor.java
|
CasCredentialsExtractor
|
extract
|
class CasCredentialsExtractor implements CredentialsExtractor {
private final static int DECOMPRESSION_FACTOR = 10;
protected CasConfiguration configuration;
/**
* <p>Constructor for CasCredentialsExtractor.</p>
*
* @param configuration a {@link CasConfiguration} object
*/
public CasCredentialsExtractor(final CasConfiguration configuration) {
CommonHelper.assertNotNull("configuration", configuration);
this.configuration = configuration;
}
/** {@inheritDoc} */
@Override
public Optional<Credentials> extract(final CallContext ctx) {<FILL_FUNCTION_BODY>}
/**
* <p>isTokenRequest.</p>
*
* @param context a {@link WebContext} object
* @return a boolean
*/
protected boolean isTokenRequest(final WebContext context) {
return getArtifactParameter(context).isPresent();
}
/**
* <p>getArtifactParameter.</p>
*
* @param context a {@link WebContext} object
* @return a {@link Optional} object
*/
protected Optional<String> getArtifactParameter(final WebContext context) {
if (configuration.getProtocol() == CasProtocol.SAML) {
val optValue = context.getRequestParameter(Protocol.SAML11.getArtifactParameterName());
if (optValue.isPresent()) {
return optValue;
}
}
return context.getRequestParameter(CasConfiguration.TICKET_PARAMETER);
}
/**
* <p>isBackLogoutRequest.</p>
*
* @param context a {@link WebContext} object
* @return a boolean
*/
protected boolean isBackLogoutRequest(final WebContext context) {
return WebContextHelper.isPost(context)
&& !isMultipartRequest(context)
&& context.getRequestParameter(CasConfiguration.LOGOUT_REQUEST_PARAMETER).isPresent();
}
/**
* <p>isMultipartRequest.</p>
*
* @param context a {@link WebContext} object
* @return a boolean
*/
protected boolean isMultipartRequest(final WebContext context) {
val contentType = context.getRequestHeader(HttpConstants.CONTENT_TYPE_HEADER);
return contentType.isPresent() && contentType.get().toLowerCase().startsWith("multipart");
}
/**
* <p>isFrontLogoutRequest.</p>
*
* @param context a {@link WebContext} object
* @return a boolean
*/
protected boolean isFrontLogoutRequest(final WebContext context) {
return WebContextHelper.isGet(context)
&& context.getRequestParameter(CasConfiguration.LOGOUT_REQUEST_PARAMETER).isPresent();
}
/**
* <p>uncompressLogoutMessage.</p>
*
* @param originalMessage a {@link String} object
* @return a {@link String} object
*/
protected String uncompressLogoutMessage(final String originalMessage) {
val binaryMessage = Base64.getMimeDecoder().decode(originalMessage);
Inflater decompresser = null;
try {
// decompress the bytes
decompresser = new Inflater();
decompresser.setInput(binaryMessage);
val result = new byte[binaryMessage.length * DECOMPRESSION_FACTOR];
val resultLength = decompresser.inflate(result);
// decode the bytes into a String
return new String(result, 0, resultLength, "UTF-8");
} catch (final Exception e) {
LOGGER.error("Unable to decompress logout message", e);
throw new TechnicalException(e);
} finally {
if (decompresser != null) {
decompresser.end();
}
}
}
}
|
Credentials credentials = null;
val webContext = ctx.webContext();
// like the SingleSignOutFilter from the Apereo CAS client:
if (isTokenRequest(webContext)) {
val ticket = getArtifactParameter(webContext).get();
credentials = new TokenCredentials(ticket);
} else if (isBackLogoutRequest(webContext)) {
val logoutMessage = webContext.getRequestParameter(CasConfiguration.LOGOUT_REQUEST_PARAMETER).get();
LOGGER.trace("Logout request:\n{}", logoutMessage);
val ticket = XmlUtils.getTextForElement(logoutMessage, CasConfiguration.SESSION_INDEX_TAG);
credentials = new SessionKeyCredentials(LogoutType.BACK, ticket);
} else if (isFrontLogoutRequest(webContext)) {
val logoutMessage = uncompressLogoutMessage(
webContext.getRequestParameter(CasConfiguration.LOGOUT_REQUEST_PARAMETER).get());
LOGGER.trace("Logout request:\n{}", logoutMessage);
val ticket = XmlUtils.getTextForElement(logoutMessage, CasConfiguration.SESSION_INDEX_TAG);
credentials = new SessionKeyCredentials(LogoutType.FRONT, ticket);
}
LOGGER.debug("extracted credentials: {}", credentials);
return Optional.ofNullable(credentials);
| 1,002
| 344
| 1,346
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-cas/src/main/java/org/pac4j/cas/logout/processor/CasLogoutProcessor.java
|
CasLogoutProcessor
|
processLogout
|
class CasLogoutProcessor implements LogoutProcessor {
protected CasConfiguration configuration;
protected SessionLogoutHandler sessionLogoutHandler;
/**
* <p>Constructor for CasLogoutProcessor.</p>
*
* @param configuration a {@link CasConfiguration} object
* @param sessionLogoutHandler a {@link SessionLogoutHandler} object
*/
public CasLogoutProcessor(final CasConfiguration configuration, final SessionLogoutHandler sessionLogoutHandler) {
CommonHelper.assertNotNull("configuration", configuration);
this.configuration = configuration;
this.sessionLogoutHandler = sessionLogoutHandler;
}
/** {@inheritDoc} */
@Override
public HttpAction processLogout(final CallContext ctx, final Credentials logoutCredentials) {<FILL_FUNCTION_BODY>}
/**
* <p>getFinalActionForFrontChannelLogout.</p>
*
* @param context a {@link WebContext} object
* @return a {@link HttpAction} object
*/
protected HttpAction getFinalActionForFrontChannelLogout(final WebContext context) {
val relayStateValue = context.getRequestParameter(CasConfiguration.RELAY_STATE_PARAMETER);
// if we have a state value -> redirect to the CAS server to continue the logout process
if (relayStateValue.isPresent()) {
val buffer = new StringBuilder();
buffer.append(configuration.getPrefixUrl());
if (!configuration.getPrefixUrl().endsWith("/")) {
buffer.append("/");
}
buffer.append("logout?_eventId=next&");
buffer.append(CasConfiguration.RELAY_STATE_PARAMETER);
buffer.append("=");
buffer.append(CommonHelper.urlEncode(relayStateValue.get()));
val redirectUrl = buffer.toString();
LOGGER.debug("Redirection url to the CAS server: {}", redirectUrl);
return HttpActionHelper.buildRedirectUrlAction(context, redirectUrl);
} else {
return new OkAction(Pac4jConstants.EMPTY_STRING);
}
}
}
|
assertTrue(logoutCredentials instanceof SessionKeyCredentials, "credentials must be of type SessionKeyCredentials");
val credentials = (SessionKeyCredentials) logoutCredentials;
val sessionKey = credentials.getSessionKey();
if (credentials.getLogoutType() == LogoutType.BACK) {
if (isNotBlank(sessionKey) && sessionLogoutHandler != null) {
sessionLogoutHandler.destroySession(ctx, sessionKey);
}
LOGGER.debug("back logout: no content returned");
return NoContentAction.INSTANCE;
} else {
if (isNotBlank(sessionKey) && sessionLogoutHandler != null) {
sessionLogoutHandler.destroySession(ctx, sessionKey);
}
val action = getFinalActionForFrontChannelLogout(ctx.webContext());
LOGGER.debug("front logout, returning: {}", action);
return action;
}
| 528
| 234
| 762
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-cas/src/main/java/org/pac4j/cas/profile/CasProfileDefinition.java
|
CasProfileDefinition
|
newProfile
|
class CasProfileDefinition extends CommonProfileDefinition {
/**
* <p>Constructor for CasProfileDefinition.</p>
*/
public CasProfileDefinition() {
super(parameters -> new CasProfile());
}
/** {@inheritDoc} */
@Override
public UserProfile newProfile(final Object... parameters) {<FILL_FUNCTION_BODY>}
}
|
val proxyReceptor = (CasProxyReceptor) getParameter(parameters, 1);
if (proxyReceptor != null) {
val profile = new CasProxyProfile();
profile.setPrincipal((AttributePrincipal) getParameter(parameters, 2));
return profile;
} else {
return super.newProfile(parameters);
}
| 96
| 93
| 189
|
<methods>public void <init>() ,public void <init>(org.pac4j.core.profile.factory.ProfileFactory) <variables>public static final java.lang.String DISPLAY_NAME,public static final java.lang.String EMAIL,public static final java.lang.String FAMILY_NAME,public static final java.lang.String FIRST_NAME,public static final java.lang.String GENDER,public static final java.lang.String LOCALE,public static final java.lang.String LOCATION,public static final java.lang.String PICTURE_URL,public static final java.lang.String PROFILE_URL
|
pac4j_pac4j
|
pac4j/pac4j-cas/src/main/java/org/pac4j/cas/profile/CasProxyProfile.java
|
CasProxyProfile
|
getProxyTicketFor
|
class CasProxyProfile extends CasProfile {
@Serial
private static final long serialVersionUID = 4956675835922254493L;
protected AttributePrincipal attributePrincipal = null;
/**
* Store the CAS principal.
*
* @param attributePrincipal the principal with attributes
*/
public void setPrincipal(final AttributePrincipal attributePrincipal) {
this.attributePrincipal = attributePrincipal;
}
/**
* Get a proxy ticket for a given service.
*
* @param service the CAS service
* @return the proxy ticket for the given service
*/
public String getProxyTicketFor(final String service) {<FILL_FUNCTION_BODY>}
}
|
if (this.attributePrincipal != null) {
logger.debug("Requesting PT from principal: {} and for service: {}", attributePrincipal, service);
val pt = this.attributePrincipal.getProxyTicketFor(service);
logger.debug("Get PT: {}", pt);
return pt;
}
return null;
| 196
| 92
| 288
|
<methods>public non-sealed void <init>() <variables>private static final long serialVersionUID
|
pac4j_pac4j
|
pac4j/pac4j-cas/src/main/java/org/pac4j/cas/profile/CasRestProfile.java
|
CasRestProfile
|
equals
|
class CasRestProfile extends CommonProfile {
@Serial
private static final long serialVersionUID = -1688563185891330018L;
private static final String TGT_KEY = "$tgt_key";
/**
* <p>Constructor for CasRestProfile.</p>
*/
public CasRestProfile() {
}
/**
* <p>Constructor for CasRestProfile.</p>
*
* @param ticketGrantingTicketId a {@link String} object
* @param userName a {@link String} object
*/
public CasRestProfile(final String ticketGrantingTicketId, final String userName) {
super();
addAttribute(TGT_KEY, ticketGrantingTicketId);
setId(userName);
}
/**
* <p>getTicketGrantingTicketId.</p>
*
* @return a {@link String} object
*/
public String getTicketGrantingTicketId() {
return (String) getAttribute(TGT_KEY);
}
/** {@inheritDoc} */
@Override
public void removeLoginData() {
removeAttribute(TGT_KEY);
}
/** {@inheritDoc} */
@Override
public int hashCode() {
return getTicketGrantingTicketId().hashCode();
}
/** {@inheritDoc} */
@Override
public boolean equals(final Object obj) {<FILL_FUNCTION_BODY>}
}
|
if (obj == null) {
return false;
}
return obj instanceof CasRestProfile casRestProfile
&& (obj == this || getTicketGrantingTicketId().equals(casRestProfile.getTicketGrantingTicketId()));
| 397
| 66
| 463
|
<methods>public void <init>() ,public void <init>(boolean) ,public java.lang.String getDisplayName() ,public java.lang.String getEmail() ,public java.lang.String getFamilyName() ,public java.lang.String getFirstName() ,public org.pac4j.core.profile.Gender getGender() ,public java.util.Locale getLocale() ,public java.lang.String getLocation() ,public java.net.URI getPictureUrl() ,public java.net.URI getProfileUrl() ,public java.lang.String getUsername() ,public boolean isExpired() <variables>private static final long serialVersionUID
|
pac4j_pac4j
|
pac4j/pac4j-cas/src/main/java/org/pac4j/cas/redirect/CasRedirectionActionBuilder.java
|
CasRedirectionActionBuilder
|
constructRedirectUrl
|
class CasRedirectionActionBuilder implements RedirectionActionBuilder {
protected CasConfiguration configuration;
protected CasClient client;
/**
* <p>Constructor for CasRedirectionActionBuilder.</p>
*
* @param configuration a {@link CasConfiguration} object
* @param client a {@link CasClient} object
*/
public CasRedirectionActionBuilder(final CasConfiguration configuration, final CasClient client) {
CommonHelper.assertNotNull("configuration", configuration);
CommonHelper.assertNotNull("client", client);
this.configuration = configuration;
this.client = client;
}
/** {@inheritDoc} */
@Override
public Optional<RedirectionAction> getRedirectionAction(final CallContext ctx) {
val webContext = ctx.webContext();
var computeLoginUrl = configuration.computeFinalLoginUrl(webContext);
val computedCallbackUrl = client.computeFinalCallbackUrl(webContext);
val renew = configuration.isRenew()
|| webContext.getRequestAttribute(RedirectionActionBuilder.ATTRIBUTE_FORCE_AUTHN).isPresent();
val gateway = configuration.isGateway()
|| webContext.getRequestAttribute(RedirectionActionBuilder.ATTRIBUTE_PASSIVE).isPresent();
val redirectionUrl = constructRedirectUrl(computeLoginUrl, getServiceParameter(),
computedCallbackUrl, renew, gateway, configuration.getMethod());
LOGGER.debug("redirectionUrl: {}", redirectionUrl);
return Optional.of(HttpActionHelper.buildRedirectUrlAction(webContext, redirectionUrl));
}
/**
* <p>getServiceParameter.</p>
*
* @return a {@link String} object
*/
protected String getServiceParameter() {
if (configuration.getProtocol() == CasProtocol.SAML) {
return Protocol.SAML11.getServiceParameterName();
} else {
return CasConfiguration.SERVICE_PARAMETER;
}
}
// like CommonUtils.constructRedirectUrl in CAS client
/**
* <p>constructRedirectUrl.</p>
*
* @param casServerLoginUrl a {@link String} object
* @param serviceParameterName a {@link String} object
* @param serviceUrl a {@link String} object
* @param renew a boolean
* @param gateway a boolean
* @param method a {@link String} object
* @return a {@link String} object
*/
public static String constructRedirectUrl(final String casServerLoginUrl, final String serviceParameterName,
final String serviceUrl, final boolean renew, final boolean gateway, final String method) {<FILL_FUNCTION_BODY>}
}
|
return casServerLoginUrl + (casServerLoginUrl.contains("?") ? "&" : "?") + serviceParameterName + "="
+ CommonHelper.urlEncode(serviceUrl) + (renew ? "&renew=true" : "") + (gateway ? "&gateway=true" : "")
+ (method != null ? "&method=" + method : "");
| 665
| 99
| 764
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-config/src/main/java/org/pac4j/config/builder/AbstractBuilder.java
|
AbstractBuilder
|
getAuthenticator
|
class AbstractBuilder implements PropertiesConstants {
/** Constant <code>MAX_NUM_CLIENTS=100</code> */
protected static final int MAX_NUM_CLIENTS = 100;
/** Constant <code>MAX_NUM_AUTHENTICATORS=10</code> */
protected static final int MAX_NUM_AUTHENTICATORS = 10;
/** Constant <code>MAX_NUM_CUSTOM_PROPERTIES=5</code> */
protected static final int MAX_NUM_CUSTOM_PROPERTIES = 5;
/** Constant <code>MAX_NUM_ENCODERS=10</code> */
protected static final int MAX_NUM_ENCODERS = 10;
protected final Map<String, String> properties;
protected final Map<String, Authenticator> authenticators;
/**
* <p>Constructor for AbstractBuilder.</p>
*
* @param properties a {@link Map} object
*/
protected AbstractBuilder(final Map<String, String> properties) {
this.properties = properties;
this.authenticators = new HashMap<>();
}
/**
* <p>Constructor for AbstractBuilder.</p>
*
* @param properties a {@link Map} object
* @param authenticators a {@link Map} object
*/
protected AbstractBuilder(final Map<String, String> properties, final Map<String, Authenticator> authenticators) {
this.properties = properties;
this.authenticators = authenticators;
}
/**
* <p>concat.</p>
*
* @param value a {@link String} object
* @param num a int
* @return a {@link String} object
*/
protected String concat(final String value, int num) {
return value.concat(num == 0 ? Pac4jConstants.EMPTY_STRING : "." + num);
}
/**
* <p>getProperty.</p>
*
* @param name a {@link String} object
* @return a {@link String} object
*/
protected String getProperty(final String name) {
return properties.get(name);
}
/**
* <p>getProperty.</p>
*
* @param name a {@link String} object
* @param num a int
* @return a {@link String} object
*/
protected String getProperty(final String name, final int num) {
return getProperty(concat(name, num));
}
/**
* <p>containsProperty.</p>
*
* @param name a {@link String} object
* @param num a int
* @return a boolean
*/
protected boolean containsProperty(final String name, final int num) {
return properties.containsKey(concat(name, num));
}
/**
* <p>getPropertyAsBoolean.</p>
*
* @param name a {@link String} object
* @param num a int
* @return a boolean
*/
protected boolean getPropertyAsBoolean(final String name, final int num) {
return Boolean.valueOf(getProperty(name, num));
}
/**
* <p>getPropertyAsInteger.</p>
*
* @param name a {@link String} object
* @param num a int
* @return a int
*/
protected int getPropertyAsInteger(final String name, final int num) {
return Integer.parseInt(getProperty(name, num));
}
/**
* <p>getPropertyAsLong.</p>
*
* @param name a {@link String} object
* @param num a int
* @return a long
*/
protected long getPropertyAsLong(final String name, final int num) {
return Long.parseLong(getProperty(name, num));
}
/**
* <p>getAuthenticator.</p>
*
* @param name a {@link String} object
* @return a {@link Authenticator} object
*/
protected Authenticator getAuthenticator(final String name) {<FILL_FUNCTION_BODY>}
}
|
if (AUTHENTICATOR_TEST_TOKEN.equals(name)) {
return new SimpleTestTokenAuthenticator();
} else if (AUTHENTICATOR_TEST_USERNAME_PASSWORD.equals(name)) {
return new SimpleTestUsernamePasswordAuthenticator();
} else {
return authenticators.get(name);
}
| 1,067
| 91
| 1,158
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-config/src/main/java/org/pac4j/config/builder/CasClientBuilder.java
|
CasClientBuilder
|
tryCreateCasClient
|
class CasClientBuilder extends AbstractBuilder {
/**
* <p>Constructor for CasClientBuilder.</p>
*
* @param properties a {@link Map} object
*/
public CasClientBuilder(final Map<String, String> properties) {
super(properties);
}
/**
* <p>tryCreateCasClient.</p>
*
* @param clients a {@link java.util.List} object
*/
public void tryCreateCasClient(final Collection<Client> clients) {<FILL_FUNCTION_BODY>}
}
|
for (var i = 0; i <= MAX_NUM_CLIENTS; i++) {
val loginUrl = getProperty(CAS_LOGIN_URL, i);
val protocol = getProperty(CAS_PROTOCOL, i);
if (isNotBlank(loginUrl)) {
var configuration = new CasConfiguration();
val casClient = new CasClient(configuration);
configuration.setLoginUrl(loginUrl);
if (isNotBlank(protocol)) {
configuration.setProtocol(CasProtocol.valueOf(protocol));
}
casClient.setName(concat(casClient.getName(), i));
clients.add(casClient);
}
}
| 147
| 170
| 317
|
<methods><variables>protected static final int MAX_NUM_AUTHENTICATORS,protected static final int MAX_NUM_CLIENTS,protected static final int MAX_NUM_CUSTOM_PROPERTIES,protected static final int MAX_NUM_ENCODERS,protected final non-sealed Map<java.lang.String,org.pac4j.core.credentials.authenticator.Authenticator> authenticators,protected final non-sealed Map<java.lang.String,java.lang.String> properties
|
pac4j_pac4j
|
pac4j/pac4j-config/src/main/java/org/pac4j/config/builder/DbAuthenticatorBuilder.java
|
DbAuthenticatorBuilder
|
buildDataSource
|
class DbAuthenticatorBuilder extends AbstractBuilder {
/**
* <p>Constructor for DbAuthenticatorBuilder.</p>
*
* @param properties a {@link Map} object
*/
public DbAuthenticatorBuilder(final Map<String, String> properties) {
super(properties);
}
/**
* <p>tryBuildDbAuthenticator.</p>
*
* @param authenticators a {@link Map} object
* @param encoders a {@link Map} object
*/
public void tryBuildDbAuthenticator(final Map<String, Authenticator> authenticators, final Map<String, PasswordEncoder> encoders) {
for (var i = 0; i <= MAX_NUM_AUTHENTICATORS; i++) {
if (containsProperty(DB_DATASOURCE_CLASS_NAME, i) || containsProperty(DB_JDBC_URL, i)) {
try {
val ds = buildDataSource(i);
val authenticator = new DbProfileService(ds);
if (containsProperty(DB_ATTRIBUTES, i)) {
authenticator.setAttributes(getProperty(DB_ATTRIBUTES, i));
}
if (containsProperty(DB_USER_ID_ATTRIBUTE, i)) {
authenticator.setIdAttribute(getProperty(DB_USER_ID_ATTRIBUTE, i));
}
if (containsProperty(DB_USERNAME_ATTRIBUTE, i)) {
authenticator.setUsernameAttribute(getProperty(DB_USERNAME_ATTRIBUTE, i));
}
if (containsProperty(DB_USER_PASSWORD_ATTRIBUTE, i)) {
authenticator.setPasswordAttribute(getProperty(DB_USER_PASSWORD_ATTRIBUTE, i));
}
if (containsProperty(DB_USERS_TABLE, i)) {
authenticator.setUsersTable(getProperty(DB_USERS_TABLE, i));
}
if (containsProperty(DB_PASSWORD_ENCODER, i)) {
authenticator.setPasswordEncoder(encoders.get(getProperty(DB_PASSWORD_ENCODER, i)));
}
authenticators.put(concat("db", i), authenticator);
} catch (final SQLException e) {
throw new TechnicalException(e);
}
}
}
}
private DataSource buildDataSource(final int i) throws SQLException {<FILL_FUNCTION_BODY>}
}
|
val ds = new HikariDataSource();
if (containsProperty(DB_DATASOURCE_CLASS_NAME, i)) {
ds.setDataSourceClassName(getProperty(DB_DATASOURCE_CLASS_NAME, i));
} else if (containsProperty(DB_JDBC_URL, i)) {
ds.setJdbcUrl(getProperty(DB_JDBC_URL, i));
}
if (containsProperty(DB_USERNAME, i)) {
ds.setUsername(getProperty(DB_USERNAME, i));
}
if (containsProperty(DB_PASSWORD, i)) {
ds.setPassword(getProperty(DB_PASSWORD, i));
}
if (containsProperty(DB_AUTO_COMMIT, i)) {
ds.setAutoCommit(getPropertyAsBoolean(DB_AUTO_COMMIT, i));
}
if (containsProperty(DB_CONNECTION_TIMEOUT, i)) {
ds.setConnectionTimeout(getPropertyAsLong(DB_CONNECTION_TIMEOUT, i));
}
if (containsProperty(DB_IDLE_TIMEOUT, i)) {
ds.setIdleTimeout(getPropertyAsLong(DB_IDLE_TIMEOUT, i));
}
if (containsProperty(DB_MAX_LIFETIME, i)) {
ds.setMaxLifetime(getPropertyAsLong(DB_MAX_LIFETIME, i));
}
if (containsProperty(DB_CONNECTION_TEST_QUERY, i)) {
ds.setConnectionTestQuery(getProperty(DB_CONNECTION_TEST_QUERY, i));
}
if (containsProperty(DB_MINIMUM_IDLE, i)) {
ds.setMinimumIdle(getPropertyAsInteger(DB_MINIMUM_IDLE, i));
}
if (containsProperty(DB_MAXIMUM_POOL_SIZE, i)) {
ds.setMaximumPoolSize(getPropertyAsInteger(DB_MAXIMUM_POOL_SIZE, i));
}
if (containsProperty(DB_POOL_NAME, i)) {
ds.setPoolName(getProperty(DB_POOL_NAME, i));
}
if (containsProperty(DB_INITIALIZATION_FAIL_TIMEOUT, i)) {
ds.setInitializationFailTimeout(getPropertyAsLong(DB_INITIALIZATION_FAIL_TIMEOUT, i));
}
if (containsProperty(DB_ISOLATE_INTERNAL_QUERIES, i)) {
ds.setIsolateInternalQueries(getPropertyAsBoolean(DB_ISOLATE_INTERNAL_QUERIES, i));
}
if (containsProperty(DB_ALLOW_POOL_SUSPENSION, i)) {
ds.setAllowPoolSuspension(getPropertyAsBoolean(DB_ALLOW_POOL_SUSPENSION, i));
}
if (containsProperty(DB_READ_ONLY, i)) {
ds.setReadOnly(getPropertyAsBoolean(DB_READ_ONLY, i));
}
if (containsProperty(DB_REGISTER_MBEANS, i)) {
ds.setRegisterMbeans(getPropertyAsBoolean(DB_REGISTER_MBEANS, i));
}
if (containsProperty(DB_CATALOG, i)) {
ds.setCatalog(getProperty(DB_CATALOG, i));
}
if (containsProperty(DB_CONNECTION_INIT_SQL, i)) {
ds.setConnectionInitSql(getProperty(DB_CONNECTION_INIT_SQL, i));
}
if (containsProperty(DB_DRIVER_CLASS_NAME, i)) {
ds.setDriverClassName(getProperty(DB_DRIVER_CLASS_NAME, i));
}
if (containsProperty(DB_TRANSACTION_ISOLATION, i)) {
ds.setTransactionIsolation(getProperty(DB_TRANSACTION_ISOLATION, i));
}
if (containsProperty(DB_VALIDATION_TIMEOUT, i)) {
ds.setValidationTimeout(getPropertyAsLong(DB_VALIDATION_TIMEOUT, i));
}
if (containsProperty(DB_LEAK_DETECTION_THRESHOLD, i)) {
ds.setLeakDetectionThreshold(getPropertyAsLong(DB_LEAK_DETECTION_THRESHOLD, i));
}
for (var j = 1; j <= MAX_NUM_CUSTOM_PROPERTIES; j++) {
if (containsProperty(DB_CUSTOM_PARAM_KEY + j, i)) {
ds.addDataSourceProperty(getProperty(DB_CUSTOM_PARAM_KEY + j, i), getProperty(DB_CUSTOM_PARAM_VALUE + j, i));
}
}
if (containsProperty(DB_LOGIN_TIMEOUT, i)) {
ds.setLoginTimeout(getPropertyAsInteger(DB_LOGIN_TIMEOUT, i));
}
if (containsProperty(DB_DATASOURCE_JNDI, i)) {
ds.setDataSourceJNDI(getProperty(DB_DATASOURCE_JNDI, i));
}
return ds;
| 620
| 1,315
| 1,935
|
<methods><variables>protected static final int MAX_NUM_AUTHENTICATORS,protected static final int MAX_NUM_CLIENTS,protected static final int MAX_NUM_CUSTOM_PROPERTIES,protected static final int MAX_NUM_ENCODERS,protected final non-sealed Map<java.lang.String,org.pac4j.core.credentials.authenticator.Authenticator> authenticators,protected final non-sealed Map<java.lang.String,java.lang.String> properties
|
pac4j_pac4j
|
pac4j/pac4j-config/src/main/java/org/pac4j/config/builder/DirectClientBuilder.java
|
DirectClientBuilder
|
tryCreateAnonymousClient
|
class DirectClientBuilder extends AbstractBuilder {
/**
* <p>Constructor for DirectClientBuilder.</p>
*
* @param properties a {@link Map} object
* @param authenticators a {@link Map} object
*/
public DirectClientBuilder(final Map<String, String> properties, final Map<String, Authenticator> authenticators) {
super(properties, authenticators);
}
/**
* <p>tryCreateAnonymousClient.</p>
*
* @param clients a {@link java.util.List} object
*/
public void tryCreateAnonymousClient(final Collection<Client> clients) {<FILL_FUNCTION_BODY>}
/**
* <p>tryCreateDirectBasciAuthClient.</p>
*
* @param clients a {@link java.util.List} object
*/
public void tryCreateDirectBasciAuthClient(final Collection<Client> clients) {
for (var i = 0; i <= MAX_NUM_CLIENTS; i++) {
val authenticator = getProperty(DIRECTBASICAUTH_AUTHENTICATOR, i);
if (isNotBlank(authenticator)) {
val directBasicAuthClient = new DirectBasicAuthClient();
directBasicAuthClient.setAuthenticator(getAuthenticator(authenticator));
directBasicAuthClient.setName(concat(directBasicAuthClient.getName(), i));
clients.add(directBasicAuthClient);
}
}
}
}
|
val anonymous = getProperty(ANONYMOUS);
if (isNotBlank(anonymous)) {
clients.add(new AnonymousClient());
}
| 377
| 44
| 421
|
<methods><variables>protected static final int MAX_NUM_AUTHENTICATORS,protected static final int MAX_NUM_CLIENTS,protected static final int MAX_NUM_CUSTOM_PROPERTIES,protected static final int MAX_NUM_ENCODERS,protected final non-sealed Map<java.lang.String,org.pac4j.core.credentials.authenticator.Authenticator> authenticators,protected final non-sealed Map<java.lang.String,java.lang.String> properties
|
pac4j_pac4j
|
pac4j/pac4j-config/src/main/java/org/pac4j/config/builder/IndirectHttpClientBuilder.java
|
IndirectHttpClientBuilder
|
tryCreateIndirectBasicAuthClient
|
class IndirectHttpClientBuilder extends AbstractBuilder {
/**
* <p>Constructor for IndirectHttpClientBuilder.</p>
*
* @param properties a {@link Map} object
* @param authenticators a {@link Map} object
*/
public IndirectHttpClientBuilder(final Map<String, String> properties, final Map<String, Authenticator> authenticators) {
super(properties, authenticators);
}
/**
* <p>tryCreateLoginFormClient.</p>
*
* @param clients a {@link java.util.List} object
*/
public void tryCreateLoginFormClient(final Collection<Client> clients) {
for (var i = 0; i <= MAX_NUM_CLIENTS; i++) {
val loginUrl = getProperty(FORMCLIENT_LOGIN_URL, i);
val authenticator = getProperty(FORMCLIENT_AUTHENTICATOR, i);
if (isNotBlank(loginUrl) && isNotBlank(authenticator)) {
val formClient = new FormClient();
formClient.setLoginUrl(loginUrl);
formClient.setAuthenticator(getAuthenticator(authenticator));
if (containsProperty(FORMCLIENT_USERNAME_PARAMETER, i)) {
formClient.setUsernameParameter(getProperty(FORMCLIENT_USERNAME_PARAMETER, i));
}
if (containsProperty(FORMCLIENT_PASSWORD_PARAMETER, i)) {
formClient.setPasswordParameter(getProperty(FORMCLIENT_PASSWORD_PARAMETER, i));
}
formClient.setName(concat(formClient.getName(), i));
clients.add(formClient);
}
}
}
/**
* <p>tryCreateIndirectBasicAuthClient.</p>
*
* @param clients a {@link java.util.List} object
*/
public void tryCreateIndirectBasicAuthClient(final Collection<Client> clients) {<FILL_FUNCTION_BODY>}
}
|
for (var i = 0; i <= MAX_NUM_CLIENTS; i++) {
val authenticator = getProperty(INDIRECTBASICAUTH_AUTHENTICATOR, i);
if (isNotBlank(authenticator)) {
val indirectBasicAuthClient = new IndirectBasicAuthClient();
indirectBasicAuthClient.setAuthenticator(getAuthenticator(authenticator));
if (containsProperty(INDIRECTBASICAUTH_REALM_NAME, i)) {
indirectBasicAuthClient.setRealmName(getProperty(INDIRECTBASICAUTH_REALM_NAME, i));
}
indirectBasicAuthClient.setName(concat(indirectBasicAuthClient.getName(), i));
clients.add(indirectBasicAuthClient);
}
}
| 507
| 202
| 709
|
<methods><variables>protected static final int MAX_NUM_AUTHENTICATORS,protected static final int MAX_NUM_CLIENTS,protected static final int MAX_NUM_CUSTOM_PROPERTIES,protected static final int MAX_NUM_ENCODERS,protected final non-sealed Map<java.lang.String,org.pac4j.core.credentials.authenticator.Authenticator> authenticators,protected final non-sealed Map<java.lang.String,java.lang.String> properties
|
pac4j_pac4j
|
pac4j/pac4j-config/src/main/java/org/pac4j/config/builder/OAuthBuilder.java
|
OAuthBuilder
|
tryCreateLinkedInClient
|
class OAuthBuilder extends AbstractBuilder {
/**
* <p>Constructor for OAuthBuilder.</p>
*
* @param properties a {@link Map} object
*/
public OAuthBuilder(final Map<String, String> properties) {
super(properties);
}
/**
* <p>tryCreateLinkedInClient.</p>
*
* @param clients a {@link java.util.List} object
*/
public void tryCreateLinkedInClient(final Collection<Client> clients) {<FILL_FUNCTION_BODY>}
/**
* <p>tryCreateFacebookClient.</p>
*
* @param clients a {@link java.util.List} object
*/
public void tryCreateFacebookClient(final Collection<Client> clients) {
val id = getProperty(FACEBOOK_ID);
val secret = getProperty(FACEBOOK_SECRET);
val scope = getProperty(FACEBOOK_SCOPE);
val fields = getProperty(FACEBOOK_FIELDS);
if (isNotBlank(id) && isNotBlank(secret)) {
val facebookClient = new FacebookClient(id, secret);
if (isNotBlank(scope)) {
facebookClient.setScope(scope);
}
if (isNotBlank(fields)) {
facebookClient.setFields(fields);
}
clients.add(facebookClient);
}
}
/**
* <p>tryCreateWindowsLiveClient.</p>
*
* @param clients a {@link java.util.List} object
*/
public void tryCreateWindowsLiveClient(final Collection<Client> clients) {
val id = getProperty(WINDOWSLIVE_ID);
val secret = getProperty(WINDOWSLIVE_SECRET);
if (isNotBlank(id) && isNotBlank(secret)) {
Client client = new WindowsLiveClient(id, secret);
clients.add(client);
}
}
/**
* <p>tryCreateFoursquareClient.</p>
*
* @param clients a {@link java.util.List} object
*/
public void tryCreateFoursquareClient(final Collection<Client> clients) {
val id = getProperty(FOURSQUARE_ID);
val secret = getProperty(FOURSQUARE_SECRET);
if (isNotBlank(id) && isNotBlank(secret)) {
Client client = new FoursquareClient(id, secret);
clients.add(client);
}
}
/**
* <p>tryCreateGoogleClient.</p>
*
* @param clients a {@link java.util.List} object
*/
public void tryCreateGoogleClient(final Collection<Client> clients) {
val id = getProperty(GOOGLE_ID);
val secret = getProperty(GOOGLE_SECRET);
if (isNotBlank(id) && isNotBlank(secret)) {
val client = new Google2Client(id, secret);
val scope = getProperty(GOOGLE_SCOPE);
if (isNotBlank(scope)) {
client.setScope(Google2Client.Google2Scope.valueOf(scope.toUpperCase()));
}
clients.add(client);
}
}
/**
* <p>tryCreateYahooClient.</p>
*
* @param clients a {@link java.util.List} object
*/
public void tryCreateYahooClient(final Collection<Client> clients) {
val id = getProperty(YAHOO_ID);
val secret = getProperty(YAHOO_SECRET);
if (isNotBlank(id) && isNotBlank(secret)) {
Client client = new YahooClient(id, secret);
clients.add(client);
}
}
/**
* <p>tryCreateDropboxClient.</p>
*
* @param clients a {@link java.util.List} object
*/
public void tryCreateDropboxClient(final Collection<Client> clients) {
val id = getProperty(DROPBOX_ID);
val secret = getProperty(DROPBOX_SECRET);
if (isNotBlank(id) && isNotBlank(secret)) {
Client client = new DropBoxClient(id, secret);
clients.add(client);
}
}
/**
* <p>tryCreateGithubClient.</p>
*
* @param clients a {@link java.util.List} object
*/
public void tryCreateGithubClient(final Collection<Client> clients) {
val id = getProperty(GITHUB_ID);
val secret = getProperty(GITHUB_SECRET);
if (isNotBlank(id) && isNotBlank(secret)) {
Client client = new GitHubClient(id, secret);
clients.add(client);
}
}
/**
* <p>tryCreateTwitterClient.</p>
*
* @param clients a {@link java.util.List} object
*/
public void tryCreateTwitterClient(final Collection<Client> clients) {
val id = getProperty(TWITTER_ID);
val secret = getProperty(TWITTER_SECRET);
if (isNotBlank(id) && isNotBlank(secret)) {
Client twitterClient = new TwitterClient(id, secret);
clients.add(twitterClient);
}
}
/**
* <p>tryCreateGenericOAuth2Clients.</p>
*
* @param clients a {@link java.util.List} object
*/
public void tryCreateGenericOAuth2Clients(final Collection<Client> clients) {
for (var i = 0; i <= MAX_NUM_CLIENTS; i++) {
val id = getProperty(OAUTH2_ID, i);
val secret = getProperty(OAUTH2_SECRET, i);
if (isNotBlank(id) && isNotBlank(secret)) {
val client = new GenericOAuth20Client();
client.setName(concat(client.getName(), i));
client.setKey(id);
client.setSecret(secret);
client.setAuthUrl(getProperty(OAUTH2_AUTH_URL, i));
client.setTokenUrl(getProperty(OAUTH2_TOKEN_URL, i));
client.setProfileUrl(getProperty(OAUTH2_PROFILE_URL, i));
client.setProfilePath(getProperty(OAUTH2_PROFILE_PATH, i));
client.setProfileId(getProperty(OAUTH2_PROFILE_ID, i));
client.setScope(getProperty(OAUTH2_SCOPE, i));
if (containsProperty(OAUTH2_WITH_STATE, i)) {
client.setWithState(getPropertyAsBoolean(OAUTH2_WITH_STATE, i));
}
if (containsProperty(OAUTH2_CLIENT_AUTHENTICATION_METHOD, i)) {
client.setClientAuthenticationMethod(getProperty(OAUTH2_CLIENT_AUTHENTICATION_METHOD, i));
}
clients.add(client);
}
}
}
}
|
val id = getProperty(LINKEDIN_ID);
val secret = getProperty(LINKEDIN_SECRET);
val scope = getProperty(LINKEDIN_SCOPE);
if (isNotBlank(id) && isNotBlank(secret)) {
val linkedInClient = new LinkedIn2Client(id, secret);
if (isNotBlank(scope)) {
linkedInClient.setScope(scope);
}
clients.add(linkedInClient);
}
| 1,877
| 129
| 2,006
|
<methods><variables>protected static final int MAX_NUM_AUTHENTICATORS,protected static final int MAX_NUM_CLIENTS,protected static final int MAX_NUM_CUSTOM_PROPERTIES,protected static final int MAX_NUM_ENCODERS,protected final non-sealed Map<java.lang.String,org.pac4j.core.credentials.authenticator.Authenticator> authenticators,protected final non-sealed Map<java.lang.String,java.lang.String> properties
|
pac4j_pac4j
|
pac4j/pac4j-config/src/main/java/org/pac4j/config/builder/OidcClientBuilder.java
|
OidcClientBuilder
|
tryCreateOidcClient
|
class OidcClientBuilder extends AbstractBuilder {
/**
* <p>Constructor for OidcClientBuilder.</p>
*
* @param properties a {@link Map} object
*/
public OidcClientBuilder(final Map<String, String> properties) {
super(properties);
}
/**
* <p>tryCreateOidcClient.</p>
*
* @param clients a {@link java.util.List} object
*/
public void tryCreateOidcClient(final Collection<Client> clients) {<FILL_FUNCTION_BODY>}
}
|
for (var i = 0; i <= MAX_NUM_CLIENTS; i++) {
val id = getProperty(OIDC_ID, i);
if (isNotBlank(id)) {
val configuration = new OidcConfiguration();
configuration.setClientId(id);
val secret = getProperty(OIDC_SECRET, i);
if (isNotBlank(secret)) {
configuration.setSecret(secret);
}
val scope = getProperty(OIDC_SCOPE, i);
if (isNotBlank(scope)) {
configuration.setScope(scope);
}
val discoveryUri = getProperty(OIDC_DISCOVERY_URI, i);
if (isNotBlank(discoveryUri)) {
configuration.setDiscoveryURI(discoveryUri);
}
val responseType = getProperty(OIDC_RESPONSE_TYPE, i);
if (isNotBlank(responseType)) {
configuration.setResponseType(responseType);
}
val responseMode = getProperty(OIDC_RESPONSE_MODE, i);
if (isNotBlank(responseMode)) {
configuration.setResponseMode(responseMode);
}
val useNonce = getProperty(OIDC_USE_NONCE, i);
if (isNotBlank(useNonce)) {
configuration.setUseNonce(Boolean.parseBoolean(useNonce));
}
val jwsAlgo = getProperty(OIDC_PREFERRED_JWS_ALGORITHM, i);
if (isNotBlank(jwsAlgo)) {
configuration.setPreferredJwsAlgorithm(JWSAlgorithm.parse(jwsAlgo));
}
val maxClockSkew = getProperty(OIDC_MAX_CLOCK_SKEW, i);
if (isNotBlank(maxClockSkew)) {
configuration.setMaxClockSkew(Integer.parseInt(maxClockSkew));
}
val clientAuthenticationMethod = getProperty(OIDC_CLIENT_AUTHENTICATION_METHOD, i);
if (isNotBlank(clientAuthenticationMethod)) {
configuration.setClientAuthenticationMethod(ClientAuthenticationMethod.parse(clientAuthenticationMethod));
}
for (var j = 1; j <= MAX_NUM_CUSTOM_PROPERTIES; j++) {
if (containsProperty(OIDC_CUSTOM_PARAM_KEY + j, i)) {
configuration.addCustomParam(getProperty(OIDC_CUSTOM_PARAM_KEY + j, i),
getProperty(OIDC_CUSTOM_PARAM_VALUE + j, i));
}
}
val type = getProperty(OIDC_TYPE, i);
final OidcClient oidcClient;
if (OIDC_AZURE_TYPE.equalsIgnoreCase(type)) {
val azureAdConfiguration = new AzureAd2OidcConfiguration(configuration);
val tenant = getProperty(OIDC_AZURE_TENANT, i);
if (isNotBlank(tenant)) {
azureAdConfiguration.setTenant(tenant);
}
oidcClient = new AzureAd2Client(azureAdConfiguration);
} else if (OIDC_GOOGLE_TYPE.equalsIgnoreCase(type)) {
oidcClient = new GoogleOidcClient(configuration);
} else {
oidcClient = new OidcClient(configuration);
}
oidcClient.setName(concat(oidcClient.getName(), i));
clients.add(oidcClient);
}
}
| 155
| 917
| 1,072
|
<methods><variables>protected static final int MAX_NUM_AUTHENTICATORS,protected static final int MAX_NUM_CLIENTS,protected static final int MAX_NUM_CUSTOM_PROPERTIES,protected static final int MAX_NUM_ENCODERS,protected final non-sealed Map<java.lang.String,org.pac4j.core.credentials.authenticator.Authenticator> authenticators,protected final non-sealed Map<java.lang.String,java.lang.String> properties
|
pac4j_pac4j
|
pac4j/pac4j-config/src/main/java/org/pac4j/config/builder/RestAuthenticatorBuilder.java
|
RestAuthenticatorBuilder
|
tryBuildRestAuthenticator
|
class RestAuthenticatorBuilder extends AbstractBuilder {
/**
* <p>Constructor for RestAuthenticatorBuilder.</p>
*
* @param properties a {@link Map} object
*/
public RestAuthenticatorBuilder(final Map<String, String> properties) {
super(properties);
}
/**
* <p>tryBuildRestAuthenticator.</p>
*
* @param authenticators a {@link Map} object
*/
public void tryBuildRestAuthenticator(final Map<String, Authenticator> authenticators) {<FILL_FUNCTION_BODY>}
}
|
for (var i = 0; i <= MAX_NUM_AUTHENTICATORS; i++) {
val url = getProperty(REST_URL, i);
if (isNotBlank(url)) {
authenticators.put(concat("rest", i), new RestAuthenticator(url));
}
}
| 157
| 83
| 240
|
<methods><variables>protected static final int MAX_NUM_AUTHENTICATORS,protected static final int MAX_NUM_CLIENTS,protected static final int MAX_NUM_CUSTOM_PROPERTIES,protected static final int MAX_NUM_ENCODERS,protected final non-sealed Map<java.lang.String,org.pac4j.core.credentials.authenticator.Authenticator> authenticators,protected final non-sealed Map<java.lang.String,java.lang.String> properties
|
pac4j_pac4j
|
pac4j/pac4j-config/src/main/java/org/pac4j/config/builder/Saml2ClientBuilder.java
|
Saml2ClientBuilder
|
tryCreateSaml2Client
|
class Saml2ClientBuilder extends AbstractBuilder {
/**
* <p>Constructor for Saml2ClientBuilder.</p>
*
* @param properties a {@link Map} object
*/
public Saml2ClientBuilder(final Map<String, String> properties) {
super(properties);
}
/**
* <p>tryCreateSaml2Client.</p>
*
* @param clients a {@link java.util.List} object
*/
public void tryCreateSaml2Client(final Collection<Client> clients) {<FILL_FUNCTION_BODY>}
}
|
for (var i = 0; i <= MAX_NUM_CLIENTS; i++) {
val keystorePassword = getProperty(SAML_KEYSTORE_PASSWORD, i);
val privateKeyPassword = getProperty(SAML_PRIVATE_KEY_PASSWORD, i);
val keystorePath = getProperty(SAML_KEYSTORE_PATH, i);
val identityProviderMetadataPath = getProperty(SAML_IDENTITY_PROVIDER_METADATA_PATH, i);
if (isNotBlank(keystorePassword) && isNotBlank(privateKeyPassword)
&& isNotBlank(keystorePath) && isNotBlank(identityProviderMetadataPath)) {
val maximumAuthenticationLifetime = getProperty(SAML_MAXIMUM_AUTHENTICATION_LIFETIME, i);
val serviceProviderEntityId = getProperty(SAML_SERVICE_PROVIDER_ENTITY_ID, i);
val serviceProviderMetadataPath = getProperty(SAML_SERVICE_PROVIDER_METADATA_PATH, i);
val destinationBindingType = getProperty(SAML_AUTHN_REQUEST_BINDING_TYPE, i);
val keystoreAlias = getProperty(SAML_KEYSTORE_ALIAS, i);
val cfg = new SAML2Configuration(keystorePath, keystorePassword,
privateKeyPassword, identityProviderMetadataPath);
if (isNotBlank(maximumAuthenticationLifetime)) {
cfg.setMaximumAuthenticationLifetime(Integer.parseInt(maximumAuthenticationLifetime));
}
if (isNotBlank(serviceProviderEntityId)) {
cfg.setServiceProviderEntityId(serviceProviderEntityId);
}
if (isNotBlank(serviceProviderMetadataPath)) {
cfg.setServiceProviderMetadataPath(serviceProviderMetadataPath);
}
if (isNotBlank(destinationBindingType)) {
cfg.setAuthnRequestBindingType(destinationBindingType);
}
if (isNotBlank(keystoreAlias)) {
cfg.setKeyStoreAlias(keystoreAlias);
}
val acceptedSkew = getProperty(SAML_ACCEPTED_SKEW, i);
if (isNotBlank(acceptedSkew)) {
cfg.setAcceptedSkew(Long.parseLong(acceptedSkew));
}
val assertionConsumerServiceIndex = getProperty(SAML_ASSERTION_CONSUMER_SERVICE_INDEX, i);
if (isNotBlank(assertionConsumerServiceIndex)) {
cfg.setAssertionConsumerServiceIndex(Integer.parseInt(assertionConsumerServiceIndex));
}
val forceAuth = getProperty(SAML_FORCE_AUTH, i);
if (isNotBlank(forceAuth)) {
cfg.setForceAuth(Boolean.parseBoolean(forceAuth));
}
val attributeAsId = getProperty(SAML_ATTRIBUTE_AS_ID, i);
if (isNotBlank(attributeAsId)) {
cfg.setAttributeAsId(attributeAsId);
}
val authnContextClassRefs = getProperty(SAML_AUTHN_CONTEXT_CLASS_REFS, i);
if (isNotBlank(authnContextClassRefs)) {
cfg.setAuthnContextClassRefs(Arrays.stream(authnContextClassRefs.split(",")).collect(Collectors.toList()));
}
val comparisonType = getProperty(SAML_COMPARISON_TYPE, i);
if (isNotBlank(comparisonType)) {
cfg.setComparisonType(comparisonType);
}
val issuerFormat = getProperty(SAML_ISSUER_FORMAT, i);
if (isNotBlank(issuerFormat)) {
cfg.setIssuerFormat(issuerFormat);
}
val authnRequestSigned = getProperty(SAML_AUTHN_REQUEST_SIGNED, i);
if (isNotBlank(authnRequestSigned)) {
cfg.setAuthnRequestSigned(Boolean.parseBoolean(authnRequestSigned));
}
val mappedAttributes = getProperty(SAML_MAPPED_ATTRIBUTES, i);
if (isNotBlank(mappedAttributes)) {
var mapped = Arrays.stream(mappedAttributes.split(","))
.collect(Collectors.toMap(key -> key.split(":")[0],
value -> value.split(":")[1]));
cfg.setMappedAttributes(mapped);
}
val nameIdAttribute = getProperty(SAML_NAMEID_ATTRIBUTE, i);
if (isNotBlank(nameIdAttribute)) {
cfg.setNameIdAttribute(nameIdAttribute);
}
val passive = getProperty(SAML_PASSIVE, i);
if (isNotBlank(passive)) {
cfg.setPassive(Boolean.parseBoolean(passive));
}
val responseBindingType = getProperty(SAML_RESPONSE_BINDING_TYPE, i);
if (isNotBlank(responseBindingType)) {
cfg.setResponseBindingType(responseBindingType);
}
val wantsAssertionsSigned = getProperty(SAML_WANTS_ASSERTIONS_SIGNED, i);
if (isNotBlank(wantsAssertionsSigned)) {
cfg.setWantsAssertionsSigned(Boolean.parseBoolean(wantsAssertionsSigned));
}
val wantsResponsesSigned = getProperty(SAML_WANTS_RESPONSES_SIGNED, i);
if (isNotBlank(wantsResponsesSigned)) {
cfg.setWantsResponsesSigned(Boolean.parseBoolean(wantsResponsesSigned));
}
val saml2Client = new SAML2Client(cfg);
val clientName = StringUtils.defaultString(getProperty(CLIENT_NAME, i),
concat(saml2Client.getName(), i));
saml2Client.setName(clientName);
clients.add(saml2Client);
}
}
| 155
| 1,590
| 1,745
|
<methods><variables>protected static final int MAX_NUM_AUTHENTICATORS,protected static final int MAX_NUM_CLIENTS,protected static final int MAX_NUM_CUSTOM_PROPERTIES,protected static final int MAX_NUM_ENCODERS,protected final non-sealed Map<java.lang.String,org.pac4j.core.credentials.authenticator.Authenticator> authenticators,protected final non-sealed Map<java.lang.String,java.lang.String> properties
|
pac4j_pac4j
|
pac4j/pac4j-config/src/main/java/org/pac4j/config/builder/ShiroEncoderBuilder.java
|
ShiroEncoderBuilder
|
tryCreatePasswordEncoder
|
class ShiroEncoderBuilder extends AbstractBuilder {
/**
* <p>Constructor for ShiroEncoderBuilder.</p>
*
* @param properties a {@link Map} object
*/
public ShiroEncoderBuilder(final Map<String, String> properties) {
super(properties);
}
/**
* <p>tryCreatePasswordEncoder.</p>
*
* @param encoders a {@link Map} object
*/
public void tryCreatePasswordEncoder(final Map<String, PasswordEncoder> encoders) {<FILL_FUNCTION_BODY>}
}
|
for (var i = 0; i <= MAX_NUM_ENCODERS; i++) {
val exists = getProperty(SHIRO_ENCODER, i);
val hasProperty = containsProperty(SHIRO_ENCODER_GENERATE_PUBLIC_SALT, i)
|| containsProperty(SHIRO_ENCODER_HASH_ALGORITHM_NAME, i)
|| containsProperty(SHIRO_ENCODER_HASH_ITERATIONS, i) || containsProperty(SHIRO_ENCODER_PRIVATE_SALT, i);
if (isNotBlank(exists) || hasProperty) {
val passwordService = new DefaultPasswordService();
if (hasProperty) {
val hashService = new DefaultHashService();
if (containsProperty(SHIRO_ENCODER_GENERATE_PUBLIC_SALT, i)) {
hashService.setGeneratePublicSalt(getPropertyAsBoolean(SHIRO_ENCODER_GENERATE_PUBLIC_SALT, i));
}
if (containsProperty(SHIRO_ENCODER_HASH_ALGORITHM_NAME, i)) {
hashService.setHashAlgorithmName(getProperty(SHIRO_ENCODER_HASH_ALGORITHM_NAME, i));
}
if (containsProperty(SHIRO_ENCODER_HASH_ITERATIONS, i)) {
hashService.setHashIterations(getPropertyAsInteger(SHIRO_ENCODER_HASH_ITERATIONS, i));
}
if (containsProperty(SHIRO_ENCODER_PRIVATE_SALT, i)) {
hashService.setPrivateSalt(ByteSource.Util.bytes(getProperty(SHIRO_ENCODER_PRIVATE_SALT, i)));
}
passwordService.setHashService(hashService);
}
encoders.put(concat(SHIRO_ENCODER, i), new ShiroPasswordEncoder(passwordService));
}
}
| 158
| 519
| 677
|
<methods><variables>protected static final int MAX_NUM_AUTHENTICATORS,protected static final int MAX_NUM_CLIENTS,protected static final int MAX_NUM_CUSTOM_PROPERTIES,protected static final int MAX_NUM_ENCODERS,protected final non-sealed Map<java.lang.String,org.pac4j.core.credentials.authenticator.Authenticator> authenticators,protected final non-sealed Map<java.lang.String,java.lang.String> properties
|
pac4j_pac4j
|
pac4j/pac4j-config/src/main/java/org/pac4j/config/builder/SpringEncoderBuilder.java
|
SpringEncoderBuilder
|
tryCreatePasswordEncoder
|
class SpringEncoderBuilder extends AbstractBuilder {
/**
* <p>Constructor for SpringEncoderBuilder.</p>
*
* @param properties a {@link Map} object
*/
public SpringEncoderBuilder(final Map<String, String> properties) {
super(properties);
}
/**
* <p>tryCreatePasswordEncoder.</p>
*
* @param encoders a {@link Map} object
*/
public void tryCreatePasswordEncoder(final Map<String, org.pac4j.core.credentials.password.PasswordEncoder> encoders) {<FILL_FUNCTION_BODY>}
}
|
for (var i = 0; i <= MAX_NUM_ENCODERS; i++) {
val type = getProperty(SPRING_ENCODER_TYPE, i);
if (isNotBlank(type)) {
final PasswordEncoder encoder;
if (SpringEncoderType.NOOP.toString().equalsIgnoreCase(type)) {
LOGGER.debug("Please notice that the NOOP Spring encoder type is insecure and for tests only");
encoder = NoOpPasswordEncoder.getInstance();
} else if (SpringEncoderType.BCRYPT.toString().equalsIgnoreCase(type)) {
if (containsProperty(SPRING_ENCODER_BCRYPT_LENGTH, i)) {
encoder = new BCryptPasswordEncoder(getPropertyAsInteger(SPRING_ENCODER_BCRYPT_LENGTH, i));
} else {
encoder = new BCryptPasswordEncoder();
}
} else if (SpringEncoderType.PBKDF2.toString().equalsIgnoreCase(type)) {
if (containsProperty(SPRING_ENCODER_PBKDF2_SECRET, i)) {
val secret = getProperty(SPRING_ENCODER_PBKDF2_SECRET, i);
if (containsProperty(SPRING_ENCODER_PBKDF2_ITERATIONS, i)
&& containsProperty(SPRING_ENCODER_PBKDF2_HASH_WIDTH, i)) {
encoder = new Pbkdf2PasswordEncoder(secret, 16, getPropertyAsInteger(SPRING_ENCODER_PBKDF2_ITERATIONS, i),
getPropertyAsInteger(SPRING_ENCODER_PBKDF2_HASH_WIDTH, i));
} else {
encoder = new Pbkdf2PasswordEncoder(secret, 16, 310000,
Pbkdf2PasswordEncoder.SecretKeyFactoryAlgorithm.PBKDF2WithHmacSHA256);
}
} else {
encoder = Pbkdf2PasswordEncoder.defaultsForSpringSecurity_v5_8();
}
} else if (SpringEncoderType.SCRYPT.toString().equalsIgnoreCase(type)) {
if (containsProperty(SPRING_ENCODER_SCRYPT_CPU_COST, i) && containsProperty(SPRING_ENCODER_SCRYPT_MEMORY_COST, i)
&& containsProperty(SPRING_ENCODER_SCRYPT_PARALLELIZATION, i)
&& containsProperty(SPRING_ENCODER_SCRYPT_KEY_LENGTH, i)
&& containsProperty(SPRING_ENCODER_SCRYPT_SALT_LENGTH, i)) {
encoder = new SCryptPasswordEncoder(getPropertyAsInteger(SPRING_ENCODER_SCRYPT_CPU_COST, i),
getPropertyAsInteger(SPRING_ENCODER_SCRYPT_MEMORY_COST, i),
getPropertyAsInteger(SPRING_ENCODER_SCRYPT_PARALLELIZATION, i),
getPropertyAsInteger(SPRING_ENCODER_SCRYPT_KEY_LENGTH, i),
getPropertyAsInteger(SPRING_ENCODER_SCRYPT_SALT_LENGTH, i));
} else {
encoder = SCryptPasswordEncoder.defaultsForSpringSecurity_v5_8();
}
} else if (SpringEncoderType.STANDARD.toString().equalsIgnoreCase(type)) {
LOGGER.debug("Please notice that the STANDARD Spring encoder type is insecure and for tests only");
if (containsProperty(SPRING_ENCODER_STANDARD_SECRET, i)) {
encoder = new StandardPasswordEncoder(getProperty(SPRING_ENCODER_STANDARD_SECRET, i));
} else {
encoder = new StandardPasswordEncoder();
}
} else {
throw new TechnicalException("Unsupported spring encoder type: " + type);
}
encoders.put(concat(SPRING_ENCODER, i), new SpringSecurityPasswordEncoder(encoder));
}
}
| 168
| 1,059
| 1,227
|
<methods><variables>protected static final int MAX_NUM_AUTHENTICATORS,protected static final int MAX_NUM_CLIENTS,protected static final int MAX_NUM_CUSTOM_PROPERTIES,protected static final int MAX_NUM_ENCODERS,protected final non-sealed Map<java.lang.String,org.pac4j.core.credentials.authenticator.Authenticator> authenticators,protected final non-sealed Map<java.lang.String,java.lang.String> properties
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/adapter/DefaultFrameworkAdapter.java
|
DefaultFrameworkAdapter
|
compareManagers
|
class DefaultFrameworkAdapter extends FrameworkAdapter {
/** {@inheritDoc} */
@Override
public int compareManagers(final Object obj1, final Object obj2) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public void applyDefaultSettingsIfUndefined(final Config config) {
CommonHelper.assertNotNull("config", config);
config.setSecurityLogicIfUndefined(DefaultSecurityLogic.INSTANCE);
config.setCallbackLogicIfUndefined(DefaultCallbackLogic.INSTANCE);
config.setLogoutLogicIfUndefined(DefaultLogoutLogic.INSTANCE);
config.setProfileManagerFactoryIfUndefined(ProfileManagerFactory.DEFAULT);
}
/** {@inheritDoc} */
@Override
public String toString() {
return "default";
}
}
|
if (obj1 != null && obj2 != null) {
return obj2.getClass().getSimpleName().compareTo(obj1.getClass().getSimpleName());
} else {
return 0;
}
| 216
| 60
| 276
|
<methods>public non-sealed void <init>() ,public abstract void applyDefaultSettingsIfUndefined(org.pac4j.core.config.Config) ,public abstract int compareManagers(java.lang.Object, java.lang.Object) <variables>public static final non-sealed org.pac4j.core.adapter.FrameworkAdapter INSTANCE
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/authorization/authorizer/AbstractCheckAuthenticationAuthorizer.java
|
AbstractCheckAuthenticationAuthorizer
|
handleError
|
class AbstractCheckAuthenticationAuthorizer extends ProfileAuthorizer {
private String redirectionUrl;
/**
* <p>Constructor for AbstractCheckAuthenticationAuthorizer.</p>
*/
public AbstractCheckAuthenticationAuthorizer() {}
/**
* <p>Constructor for AbstractCheckAuthenticationAuthorizer.</p>
*
* @param redirectionUrl a {@link String} object
*/
public AbstractCheckAuthenticationAuthorizer(final String redirectionUrl) {
this.redirectionUrl = redirectionUrl;
}
/** {@inheritDoc} */
@Override
protected boolean handleError(final WebContext context, final SessionStore sessionStore) {<FILL_FUNCTION_BODY>}
}
|
if (this.redirectionUrl != null) {
throw HttpActionHelper.buildRedirectUrlAction(context, this.redirectionUrl);
} else {
return false;
}
| 175
| 51
| 226
|
<methods>public non-sealed void <init>() ,public boolean isAllAuthorized(org.pac4j.core.context.WebContext, org.pac4j.core.context.session.SessionStore, Iterable<org.pac4j.core.profile.UserProfile>) ,public boolean isAnyAuthorized(org.pac4j.core.context.WebContext, org.pac4j.core.context.session.SessionStore, Iterable<org.pac4j.core.profile.UserProfile>) <variables>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/authorization/authorizer/AbstractRequireAllAuthorizer.java
|
AbstractRequireAllAuthorizer
|
isProfileAuthorized
|
class AbstractRequireAllAuthorizer<E extends Object> extends AbstractRequireElementAuthorizer<E> {
/** {@inheritDoc} */
@Override
protected boolean isProfileAuthorized(final WebContext context, final SessionStore sessionStore, final UserProfile profile) {<FILL_FUNCTION_BODY>}
}
|
if (elements == null || elements.isEmpty()) {
return true;
}
for (val element : elements) {
if (!check(context, sessionStore, profile, element)) {
return false;
}
}
return true;
| 75
| 66
| 141
|
<methods>public non-sealed void <init>() ,public Set<E> getElements() ,public boolean isAuthorized(org.pac4j.core.context.WebContext, org.pac4j.core.context.session.SessionStore, List<org.pac4j.core.profile.UserProfile>) ,public void setElements(Set<E>) ,public void setElements(List<E>) ,public transient void setElements(E[]) <variables>protected Set<E> elements
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/authorization/authorizer/AbstractRequireAnyAuthorizer.java
|
AbstractRequireAnyAuthorizer
|
isProfileAuthorized
|
class AbstractRequireAnyAuthorizer<E extends Object> extends AbstractRequireElementAuthorizer<E> {
/** {@inheritDoc} */
@Override
protected boolean isProfileAuthorized(final WebContext context, final SessionStore sessionStore, final UserProfile profile) {<FILL_FUNCTION_BODY>}
}
|
if (elements == null || elements.isEmpty()) {
return check(context, sessionStore, profile, null);
}
for (val element : elements) {
if (check(context, sessionStore, profile, element)) {
return true;
}
}
return false;
| 75
| 75
| 150
|
<methods>public non-sealed void <init>() ,public Set<E> getElements() ,public boolean isAuthorized(org.pac4j.core.context.WebContext, org.pac4j.core.context.session.SessionStore, List<org.pac4j.core.profile.UserProfile>) ,public void setElements(Set<E>) ,public void setElements(List<E>) ,public transient void setElements(E[]) <variables>protected Set<E> elements
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/authorization/authorizer/AbstractRequireElementAuthorizer.java
|
AbstractRequireElementAuthorizer
|
setElements
|
class AbstractRequireElementAuthorizer<E extends Object> extends ProfileAuthorizer {
protected Set<E> elements;
/** {@inheritDoc} */
@Override
public boolean isAuthorized(final WebContext context, final SessionStore sessionStore, final List<UserProfile> profiles) {
return isAnyAuthorized(context, sessionStore, profiles);
}
/**
* Check a specific element.
*
* @param context the web context
* @param sessionStore the session store
* @param profile the profile
* @param element the element to check
* @return whether it is authorized for this element
*/
protected abstract boolean check(final WebContext context, final SessionStore sessionStore,
final UserProfile profile, final E element);
/**
* <p>Getter for the field <code>elements</code>.</p>
*
* @return a {@link Set} object
*/
public Set<E> getElements() {
return elements;
}
/**
* <p>Setter for the field <code>elements</code>.</p>
*
* @param elements a {@link Set} object
*/
public void setElements(final Set<E> elements) {
this.elements = elements;
}
/**
* <p>Setter for the field <code>elements</code>.</p>
*
* @param elements a {@link List} object
*/
public void setElements(final List<E> elements) {<FILL_FUNCTION_BODY>}
/**
* <p>Setter for the field <code>elements</code>.</p>
*
* @param elements a E object
*/
public void setElements(final E... elements) {
if (elements != null) {
setElements(Arrays.asList(elements));
}
}
}
|
if (elements != null) {
this.elements = new HashSet<>(elements);
}
| 478
| 29
| 507
|
<methods>public non-sealed void <init>() ,public boolean isAllAuthorized(org.pac4j.core.context.WebContext, org.pac4j.core.context.session.SessionStore, Iterable<org.pac4j.core.profile.UserProfile>) ,public boolean isAnyAuthorized(org.pac4j.core.context.WebContext, org.pac4j.core.context.session.SessionStore, Iterable<org.pac4j.core.profile.UserProfile>) <variables>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/authorization/authorizer/AndAuthorizer.java
|
AndAuthorizer
|
isAuthorized
|
class AndAuthorizer implements Authorizer {
private final List<Authorizer> authorizers;
/**
* <p>Constructor for AndAuthorizer.</p>
*
* @param authorizers a {@link List} object
*/
public AndAuthorizer(List<Authorizer> authorizers) {
this.authorizers = authorizers;
}
/** {@inheritDoc} */
@Override
public boolean isAuthorized(final WebContext context, final SessionStore sessionStore, final List<UserProfile> profiles) {<FILL_FUNCTION_BODY>}
/**
* <p>and.</p>
*
* @param authorizers a {@link Authorizer} object
* @return a {@link Authorizer} object
*/
public static Authorizer and(Authorizer... authorizers) {
return new AndAuthorizer(asList(authorizers));
}
}
|
for (var authorizer : authorizers) {
if (!authorizer.isAuthorized(context, sessionStore, profiles)) return false;
}
return true;
| 225
| 44
| 269
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/authorization/authorizer/CsrfAuthorizer.java
|
CsrfAuthorizer
|
isAuthorized
|
class CsrfAuthorizer implements Authorizer {
private String parameterName = Pac4jConstants.CSRF_TOKEN;
private String headerName = Pac4jConstants.CSRF_TOKEN;
private boolean checkAllRequests = false;
/**
* <p>Constructor for CsrfAuthorizer.</p>
*/
public CsrfAuthorizer() {
}
/**
* <p>Constructor for CsrfAuthorizer.</p>
*
* @param parameterName a {@link String} object
* @param headerName a {@link String} object
*/
public CsrfAuthorizer(final String parameterName, final String headerName) {
this.parameterName = parameterName;
this.headerName = headerName;
}
/**
* <p>Constructor for CsrfAuthorizer.</p>
*
* @param parameterName a {@link String} object
* @param headerName a {@link String} object
* @param checkAllRequests a boolean
*/
public CsrfAuthorizer(final String parameterName, final String headerName, final boolean checkAllRequests) {
this(parameterName, headerName);
this.checkAllRequests = checkAllRequests;
}
/** {@inheritDoc} */
@Override
public boolean isAuthorized(final WebContext context, final SessionStore sessionStore, final List<UserProfile> profiles) {<FILL_FUNCTION_BODY>}
/**
* <p>hashEquals.</p>
*
* @param a a {@link String} object
* @param b a {@link String} object
* @return a boolean
*/
protected boolean hashEquals(final String a, final String b) {
if (a == null || b == null) {
return false;
}
return a.hashCode() == b.hashCode();
}
}
|
val checkRequest = checkAllRequests || isPost(context) || isPut(context) || isPatch(context) || isDelete(context);
if (checkRequest) {
val parameterToken = context.getRequestParameter(parameterName).orElse(null);
val headerToken = context.getRequestHeader(headerName).orElse(null);
LOGGER.debug("parameterToken: {}", parameterToken);
LOGGER.debug("headerToken: {}", headerToken);
val sessionPreviousToken = sessionStore.get(context, Pac4jConstants.PREVIOUS_CSRF_TOKEN);
val sessionToken = sessionStore.get(context, Pac4jConstants.CSRF_TOKEN);
val sessionDate = sessionStore.get(context, Pac4jConstants.CSRF_TOKEN_EXPIRATION_DATE);
if (sessionStore.getSessionId(context, false).isPresent()) {
sessionStore.set(context, Pac4jConstants.PREVIOUS_CSRF_TOKEN, null);
}
// all checks are always performed, conditional operations are turned into logical ones,
// string comparisons are replaced by hash equalities to be protected against time-based attacks
val hasSessionData = sessionToken.isPresent() & sessionDate.isPresent();
val previousToken = (String) sessionPreviousToken.orElse(Pac4jConstants.EMPTY_STRING);
LOGGER.debug("previous token: {}", previousToken);
val token = (String) sessionToken.orElse(Pac4jConstants.EMPTY_STRING);
LOGGER.debug("token: {}", token);
val isGoodCurrentToken = hashEquals(token, parameterToken) | hashEquals(token, headerToken);
val isGoodPreviousToken = hashEquals(previousToken, parameterToken) | hashEquals(previousToken, headerToken);
val isGoodToken = isGoodCurrentToken | isGoodPreviousToken;
val expirationDate = (Long) sessionDate.orElse(0L);
val now = new Date().getTime();
val isDateExpired = expirationDate < now;
if (!hasSessionData | !isGoodToken | isDateExpired) {
return false;
}
}
return true;
| 480
| 547
| 1,027
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/authorization/authorizer/IsFullyAuthenticatedAuthorizer.java
|
IsFullyAuthenticatedAuthorizer
|
isProfileAuthorized
|
class IsFullyAuthenticatedAuthorizer extends AbstractCheckAuthenticationAuthorizer {
/**
* <p>Constructor for IsFullyAuthenticatedAuthorizer.</p>
*/
public IsFullyAuthenticatedAuthorizer() {}
/**
* <p>Constructor for IsFullyAuthenticatedAuthorizer.</p>
*
* @param redirectionUrl a {@link String} object
*/
public IsFullyAuthenticatedAuthorizer(final String redirectionUrl) {
super(redirectionUrl);
}
/** {@inheritDoc} */
@Override
public boolean isAuthorized(final WebContext context, final SessionStore sessionStore, final List<UserProfile> profiles) {
return isAnyAuthorized(context, sessionStore, profiles);
}
/** {@inheritDoc} */
@Override
public boolean isProfileAuthorized(final WebContext context, final SessionStore sessionStore, final UserProfile profile) {<FILL_FUNCTION_BODY>}
/**
* <p>isFullyAuthenticated.</p>
*
* @return a {@link IsFullyAuthenticatedAuthorizer} object
*/
public static IsFullyAuthenticatedAuthorizer isFullyAuthenticated() {
return new IsFullyAuthenticatedAuthorizer();
}
}
|
return profile != null && !(profile instanceof AnonymousProfile) && !profile.isRemembered();
| 326
| 28
| 354
|
<methods>public void <init>() ,public void <init>(java.lang.String) <variables>private java.lang.String redirectionUrl
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/authorization/authorizer/IsRememberedAuthorizer.java
|
IsRememberedAuthorizer
|
isProfileAuthorized
|
class IsRememberedAuthorizer extends AbstractCheckAuthenticationAuthorizer {
/**
* <p>Constructor for IsRememberedAuthorizer.</p>
*/
public IsRememberedAuthorizer() {}
/**
* <p>Constructor for IsRememberedAuthorizer.</p>
*
* @param redirectionUrl a {@link String} object
*/
public IsRememberedAuthorizer(final String redirectionUrl) {
super(redirectionUrl);
}
/** {@inheritDoc} */
@Override
public boolean isAuthorized(final WebContext context, final SessionStore sessionStore, final List<UserProfile> profiles) {
return isAnyAuthorized(context, sessionStore, profiles);
}
/** {@inheritDoc} */
@Override
public boolean isProfileAuthorized(final WebContext context, final SessionStore sessionStore, final UserProfile profile) {<FILL_FUNCTION_BODY>}
/**
* <p>isRemembered.</p>
*
* @return a {@link IsRememberedAuthorizer} object
*/
public static IsRememberedAuthorizer isRemembered() {
return new IsRememberedAuthorizer();
}
}
|
return profile != null && !(profile instanceof AnonymousProfile) && profile.isRemembered();
| 306
| 27
| 333
|
<methods>public void <init>() ,public void <init>(java.lang.String) <variables>private java.lang.String redirectionUrl
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/authorization/authorizer/OrAuthorizer.java
|
OrAuthorizer
|
isAuthorized
|
class OrAuthorizer implements Authorizer {
private final List<Authorizer> authorizers;
/**
* <p>Constructor for OrAuthorizer.</p>
*
* @param authorizers a {@link List} object
*/
public OrAuthorizer(List<Authorizer> authorizers) {
this.authorizers = authorizers;
}
/** {@inheritDoc} */
@Override
public boolean isAuthorized(final WebContext context, final SessionStore sessionStore, final List<UserProfile> profiles) {<FILL_FUNCTION_BODY>}
/**
* <p>or.</p>
*
* @param authorizers a {@link Authorizer} object
* @return a {@link OrAuthorizer} object
*/
public static OrAuthorizer or(Authorizer... authorizers) {
return new OrAuthorizer(asList(authorizers));
}
}
|
for (val authorizer : authorizers) {
if (authorizer.isAuthorized(context, sessionStore, profiles)) return true;
}
return false;
| 227
| 44
| 271
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/authorization/authorizer/ProfileAuthorizer.java
|
ProfileAuthorizer
|
isAnyAuthorized
|
class ProfileAuthorizer implements Authorizer {
/**
* If all profiles are authorized.
*
* @param context the web context
* @param sessionStore the session store
* @param profiles the user profiles
* @return whether all profiles are authorized
*/
public boolean isAllAuthorized(final WebContext context, final SessionStore sessionStore, final Iterable<UserProfile> profiles) {
for (val profile : profiles) {
if (!isProfileAuthorized(context, sessionStore, profile)) {
return handleError(context, sessionStore);
}
}
return true;
}
/**
* If any of the profiles is authorized.
*
* @param context the web context
* @param sessionStore the session store
* @param profiles the user profiles
* @return whether any of the profiles is authorized
*/
public boolean isAnyAuthorized(final WebContext context, final SessionStore sessionStore, final Iterable<UserProfile> profiles) {<FILL_FUNCTION_BODY>}
/**
* Whether a specific profile is authorized.
*
* @param context the web context
* @param sessionStore the session store
* @param profile the user profile
* @return whether a specific profile is authorized
*/
protected abstract boolean isProfileAuthorized(WebContext context, SessionStore sessionStore, UserProfile profile);
/**
* Handle the error.
*
* @param context the web context
* @param sessionStore the session store
* @return <code>false</code>
*/
protected boolean handleError(final WebContext context, final SessionStore sessionStore) {
return false;
}
}
|
for (val profile : profiles) {
if (isProfileAuthorized(context, sessionStore, profile)) {
return true;
}
}
return handleError(context, sessionStore);
| 411
| 52
| 463
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/authorization/authorizer/RequireAnyAttributeAuthorizer.java
|
RequireAnyAttributeAuthorizer
|
check
|
class RequireAnyAttributeAuthorizer extends AbstractRequireAnyAuthorizer<String> {
private final String valueToMatch;
/**
* <p>Constructor for RequireAnyAttributeAuthorizer.</p>
*/
public RequireAnyAttributeAuthorizer() {
this(".+");
}
/**
* <p>Constructor for RequireAnyAttributeAuthorizer.</p>
*
* @param valueToMatch a {@link String} object
*/
public RequireAnyAttributeAuthorizer(final String valueToMatch) {
this.valueToMatch = valueToMatch;
}
/** {@inheritDoc} */
@Override
protected boolean check(final WebContext context, final SessionStore sessionStore, final UserProfile profile, final String element) {<FILL_FUNCTION_BODY>}
/**
* <p>requireAnyAttribute.</p>
*
* @param valueToMatch a {@link String} object
* @return a {@link RequireAnyAttributeAuthorizer} object
*/
public static RequireAnyAttributeAuthorizer requireAnyAttribute(String valueToMatch) {
return new RequireAnyAttributeAuthorizer(valueToMatch);
}
}
|
if (!profile.containsAttribute(element)) {
return false;
}
if (CommonHelper.isBlank(this.valueToMatch)) {
return true;
}
val attributeValues = profile.getAttribute(element);
if (attributeValues instanceof Collection) {
return Collection.class.cast(attributeValues)
.stream()
.anyMatch(v -> v.toString().matches(this.valueToMatch));
}
return attributeValues.toString().matches(this.valueToMatch);
| 294
| 133
| 427
|
<methods>public non-sealed void <init>() <variables>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/authorization/authorizer/RequireAnyRoleAuthorizer.java
|
RequireAnyRoleAuthorizer
|
check
|
class RequireAnyRoleAuthorizer extends AbstractRequireAnyAuthorizer<String> {
/**
* <p>Constructor for RequireAnyRoleAuthorizer.</p>
*/
public RequireAnyRoleAuthorizer() { }
/**
* <p>Constructor for RequireAnyRoleAuthorizer.</p>
*
* @param roles a {@link String} object
*/
public RequireAnyRoleAuthorizer(final String... roles) {
setElements(roles);
}
/**
* <p>Constructor for RequireAnyRoleAuthorizer.</p>
*
* @param roles a {@link List} object
*/
public RequireAnyRoleAuthorizer(final List<String> roles) {
setElements(roles);
}
/**
* <p>Constructor for RequireAnyRoleAuthorizer.</p>
*
* @param roles a {@link Set} object
*/
public RequireAnyRoleAuthorizer(final Set<String> roles) { setElements(roles); }
/** {@inheritDoc} */
@Override
protected boolean check(final WebContext context, final SessionStore sessionStore, final UserProfile profile, final String element) {<FILL_FUNCTION_BODY>}
/**
* <p>requireAnyRole.</p>
*
* @param roles a {@link String} object
* @return a {@link RequireAnyRoleAuthorizer} object
*/
public static RequireAnyRoleAuthorizer requireAnyRole(String ... roles) {
return new RequireAnyRoleAuthorizer(roles);
}
/**
* <p>requireAnyRole.</p>
*
* @param roles a {@link List} object
* @return a {@link RequireAnyRoleAuthorizer} object
*/
public static RequireAnyRoleAuthorizer requireAnyRole(List<String> roles) {
return new RequireAnyRoleAuthorizer(roles);
}
/**
* <p>requireAnyRole.</p>
*
* @param roles a {@link Set} object
* @return a {@link RequireAnyRoleAuthorizer} object
*/
public static RequireAnyRoleAuthorizer requireAnyRole(Set<String> roles) {
return new RequireAnyRoleAuthorizer(roles);
}
}
|
val profileRoles = profile.getRoles();
if( profileRoles.isEmpty() ) {
return false;
}
if( element == null ) {
return true;
}
return profileRoles.contains(element);
| 582
| 64
| 646
|
<methods>public non-sealed void <init>() <variables>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/authorization/generator/DefaultRolesAuthorizationGenerator.java
|
DefaultRolesAuthorizationGenerator
|
generate
|
class DefaultRolesAuthorizationGenerator implements AuthorizationGenerator {
private Collection<String> defaultRoles;
/**
* <p>Constructor for DefaultRolesAuthorizationGenerator.</p>
*/
public DefaultRolesAuthorizationGenerator() {}
/**
* <p>Constructor for DefaultRolesAuthorizationGenerator.</p>
*
* @param defaultRoles a {@link Collection} object
*/
public DefaultRolesAuthorizationGenerator(final Collection<String> defaultRoles) {
this.defaultRoles = defaultRoles;
}
/**
* <p>Constructor for DefaultRolesAuthorizationGenerator.</p>
*
* @param defaultRoles an array of {@link String} objects
*/
public DefaultRolesAuthorizationGenerator(final String[] defaultRoles) {
if (defaultRoles != null) {
this.defaultRoles = Arrays.asList(defaultRoles);
} else {
this.defaultRoles = null;
}
}
/** {@inheritDoc} */
@Override
public Optional<UserProfile> generate(final CallContext ctx, final UserProfile profile) {<FILL_FUNCTION_BODY>}
/**
* Setter for defaultRoles
*
* @param defaultRolesStr a coma-separated string of role names
*/
public void setDefaultRoles(final String defaultRolesStr) {
this.defaultRoles = Arrays.asList(defaultRolesStr.split(","));
}
}
|
if (defaultRoles != null) {
profile.addRoles(defaultRoles);
}
return Optional.of(profile);
| 383
| 39
| 422
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/authorization/generator/FromAttributesAuthorizationGenerator.java
|
FromAttributesAuthorizationGenerator
|
generateAuth
|
class FromAttributesAuthorizationGenerator implements AuthorizationGenerator {
private Collection<String> roleAttributes;
private String splitChar = ",";
/**
* <p>Constructor for FromAttributesAuthorizationGenerator.</p>
*/
public FromAttributesAuthorizationGenerator() {
this.roleAttributes = new ArrayList<>();
}
/**
* <p>Constructor for FromAttributesAuthorizationGenerator.</p>
*
* @param roleAttributes a {@link Collection} object
*/
public FromAttributesAuthorizationGenerator(final Collection<String> roleAttributes) {
this.roleAttributes = roleAttributes;
}
/**
* <p>Constructor for FromAttributesAuthorizationGenerator.</p>
*
* @param roleAttributes an array of {@link String} objects
*/
public FromAttributesAuthorizationGenerator(final String[] roleAttributes) {
if (roleAttributes != null) {
this.roleAttributes = Arrays.asList(roleAttributes);
} else {
this.roleAttributes = null;
}
}
/** {@inheritDoc} */
@Override
public Optional<UserProfile> generate(final CallContext ctx, final UserProfile profile) {
generateAuth(profile, this.roleAttributes);
return Optional.of(profile);
}
private void generateAuth(final UserProfile profile, final Iterable<String> attributes) {<FILL_FUNCTION_BODY>}
private void addRoleToProfile(final UserProfile profile, final String value) {
profile.addRole(value);
}
}
|
if (attributes == null) {
return;
}
for (val attribute : attributes) {
val value = profile.getAttribute(attribute);
if (value != null) {
if (value instanceof String) {
val st = new StringTokenizer((String) value, this.splitChar);
while (st.hasMoreTokens()) {
addRoleToProfile(profile, st.nextToken());
}
} else if (value.getClass().isArray() && value.getClass().getComponentType().isAssignableFrom(String.class)) {
for (var item : (Object[]) value) {
addRoleToProfile(profile, item.toString());
}
} else if (Collection.class.isAssignableFrom(value.getClass())) {
for (Object item : (Collection<?>) value) {
if (item.getClass().isAssignableFrom(String.class)) {
addRoleToProfile(profile, item.toString());
}
}
}
}
}
| 387
| 261
| 648
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/authorization/generator/LoadLinkedUserAuthorizationGenerator.java
|
LoadLinkedUserAuthorizationGenerator
|
generate
|
class LoadLinkedUserAuthorizationGenerator implements AuthorizationGenerator {
private ProfileService profileService;
private boolean failIfLinkedUserNotFound = true;
/**
* <p>Constructor for LoadLinkedUserAuthorizationGenerator.</p>
*/
public LoadLinkedUserAuthorizationGenerator() {}
/**
* <p>Constructor for LoadLinkedUserAuthorizationGenerator.</p>
*
* @param profileService a {@link ProfileService} object
*/
public LoadLinkedUserAuthorizationGenerator(final ProfileService profileService) {
this.profileService = profileService;
}
/** {@inheritDoc} */
@Override
public Optional<UserProfile> generate(final CallContext ctx, final UserProfile profile) {<FILL_FUNCTION_BODY>}
}
|
CommonHelper.assertNotNull("profileService", profileService);
val linkedProfile = profileService.findByLinkedId(profile.getId());
if (linkedProfile != null) {
return Optional.ofNullable(linkedProfile);
} else {
if (failIfLinkedUserNotFound) {
throw new TechnicalException("No linked account found for: " + profile);
} else {
// fallback to the original account
return Optional.ofNullable(profile);
}
}
| 199
| 124
| 323
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/authorization/generator/SpringSecurityPropertiesAuthorizationGenerator.java
|
SpringSecurityPropertiesAuthorizationGenerator
|
generate
|
class SpringSecurityPropertiesAuthorizationGenerator implements AuthorizationGenerator {
/** Constant <code>DISABLED="disabled"</code> */
public final static String DISABLED = "disabled";
/** Constant <code>ENABLED="enabled"</code> */
public final static String ENABLED = "enabled";
private Map<String, List<String>> rolesByUsers = new HashMap<>();
/**
* <p>Constructor for SpringSecurityPropertiesAuthorizationGenerator.</p>
*
* @param properties a {@link Properties} object
*/
public SpringSecurityPropertiesAuthorizationGenerator(final Properties properties) {
val keys = properties.stringPropertyNames();
for (val key : keys) {
val value = properties.getProperty(key);
if (CommonHelper.isNotBlank(value)) {
val parts = value.split(",");
val nb = parts.length;
if (nb > 1) {
val latest = parts[nb - 1];
if (!DISABLED.equals(latest)) {
final List<String> roles = new ArrayList<>(Arrays.asList(parts));
if (ENABLED.equals(latest)) {
roles.remove(nb - 1);
}
roles.remove(0);
rolesByUsers.put(key, roles);
}
}
}
}
}
/** {@inheritDoc} */
@Override
public Optional<UserProfile> generate(final CallContext ctx, final UserProfile profile) {<FILL_FUNCTION_BODY>}
}
|
val id = profile.getId();
val roles = rolesByUsers.get(id);
if (roles != null && !roles.isEmpty()) {
profile.addRoles(roles);
}
return Optional.of(profile);
| 387
| 65
| 452
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/client/Clients.java
|
Clients
|
internalInit
|
class Clients extends InitializableObject {
private volatile List<Client> clients = new ArrayList<>();
private Map<String, Client> clientsMap;
private volatile Integer oldClientsHash;
private String callbackUrl;
private AjaxRequestResolver ajaxRequestResolver;
private UrlResolver urlResolver;
private CallbackUrlResolver callbackUrlResolver;
private List<AuthorizationGenerator> authorizationGenerators = new ArrayList<>();
private String defaultSecurityClients;
/**
* <p>Constructor for Clients.</p>
*/
public Clients() {
}
/**
* <p>Constructor for Clients.</p>
*
* @param callbackUrl a {@link String} object
* @param clients a {@link List} object
*/
public Clients(final String callbackUrl, final List<Client> clients) {
setCallbackUrl(callbackUrl);
setClients(clients);
}
/**
* <p>Constructor for Clients.</p>
*
* @param callbackUrl a {@link String} object
* @param clients a {@link Client} object
*/
public Clients(final String callbackUrl, final Client... clients) {
setCallbackUrl(callbackUrl);
setClients(clients);
}
/**
* <p>Constructor for Clients.</p>
*
* @param clients a {@link List} object
*/
public Clients(final List<Client> clients) {
setClients(clients);
}
/**
* <p>Constructor for Clients.</p>
*
* @param clients a {@link Client} object
*/
public Clients(final Client... clients) {
setClients(clients);
}
/** {@inheritDoc} */
@Override
protected boolean shouldInitialize(final boolean forceReinit) {
if (forceReinit) {
return true;
}
return oldClientsHash == null || oldClientsHash.intValue() != clients.hashCode();
}
/**
* {@inheritDoc}
*
* Populate the resolvers, callback URL and authz generators in the Client
* if defined in Clients and not already in the Client itself. And check the client name.
*/
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
/**
* Return the right client according to the specific name.
*
* @param name name of the client
* @return the right client
*/
public Optional<Client> findClient(final String name) {
CommonHelper.assertNotBlank("name", name);
init();
val foundClient = clientsMap.get(name.toLowerCase().trim());
LOGGER.debug("Found client: {} for name: {}", foundClient, name);
return Optional.ofNullable(foundClient);
}
/**
* Find all the clients (initialized).
*
* @return all the clients (initialized)
*/
public List<Client> findAllClients() {
init();
return getClients();
}
/**
* <p>addClient.</p>
*
* @param client a {@link Client} object
*/
public void addClient(final Client client) {
this.clients.add(client);
}
/**
* <p>Setter for the field <code>clients</code>.</p>
*
* @param clients a {@link List} object
*/
public void setClients(final List<Client> clients) {
CommonHelper.assertNotNull("clients", clients);
this.clients = clients;
}
/**
* <p>Setter for the field <code>clients</code>.</p>
*
* @param clients a {@link Client} object
*/
public void setClients(final Client... clients) {
CommonHelper.assertNotNull("clients", clients);
setClients(new ArrayList<>(Arrays.asList(clients)));
}
/**
* <p>Setter for the field <code>authorizationGenerators</code>.</p>
*
* @param authorizationGenerators a {@link List} object
*/
public void setAuthorizationGenerators(final List<AuthorizationGenerator> authorizationGenerators) {
CommonHelper.assertNotNull("authorizationGenerators", authorizationGenerators);
this.authorizationGenerators = authorizationGenerators;
}
/**
* <p>Setter for the field <code>authorizationGenerators</code>.</p>
*
* @param authorizationGenerators a {@link AuthorizationGenerator} object
*/
public void setAuthorizationGenerators(final AuthorizationGenerator... authorizationGenerators) {
CommonHelper.assertNotNull("authorizationGenerators", authorizationGenerators);
this.authorizationGenerators = Arrays.asList(authorizationGenerators);
}
/**
* <p>setAuthorizationGenerator.</p>
*
* @param authorizationGenerator a {@link AuthorizationGenerator} object
*/
public void setAuthorizationGenerator(final AuthorizationGenerator authorizationGenerator) {
addAuthorizationGenerator(authorizationGenerator);
}
/**
* <p>addAuthorizationGenerator.</p>
*
* @param authorizationGenerator a {@link AuthorizationGenerator} object
*/
public void addAuthorizationGenerator(final AuthorizationGenerator authorizationGenerator) {
CommonHelper.assertNotNull("authorizationGenerator", authorizationGenerator);
this.authorizationGenerators.add(authorizationGenerator);
}
}
|
clientsMap = new HashMap<>();
for (val client : this.clients) {
val name = client.getName();
CommonHelper.assertNotBlank("name", name);
val lowerTrimmedName = name.toLowerCase().trim();
if (clientsMap.containsKey(lowerTrimmedName)) {
throw new TechnicalException("Duplicate name in clients: " + name);
}
clientsMap.put(lowerTrimmedName, client);
if (client instanceof IndirectClient indirectClient) {
if (this.callbackUrl != null && indirectClient.getCallbackUrl() == null) {
indirectClient.setCallbackUrl(this.callbackUrl);
}
if (this.urlResolver != null && indirectClient.getUrlResolver() == null) {
indirectClient.setUrlResolver(this.urlResolver);
}
if (this.callbackUrlResolver != null && indirectClient.getCallbackUrlResolver() == null) {
indirectClient.setCallbackUrlResolver(this.callbackUrlResolver);
}
if (this.ajaxRequestResolver != null && indirectClient.getAjaxRequestResolver() == null) {
indirectClient.setAjaxRequestResolver(this.ajaxRequestResolver);
}
}
val baseClient = (BaseClient) client;
if (!authorizationGenerators.isEmpty()) {
baseClient.addAuthorizationGenerators(this.authorizationGenerators);
}
}
this.oldClientsHash = this.clients.hashCode();
| 1,469
| 371
| 1,840
|
<methods>public non-sealed void <init>() ,public int getNbAttempts() ,public void init() ,public void init(boolean) ,public final boolean isInitialized() ,public void reinit() <variables>private java.util.concurrent.atomic.AtomicBoolean initialized,private volatile java.lang.Long lastAttempt,private int maxAttempts,private long minTimeIntervalBetweenAttemptsInMilliseconds,private java.util.concurrent.atomic.AtomicInteger nbAttempts
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/client/DirectClient.java
|
DirectClient
|
afterInternalInit
|
class DirectClient extends BaseClient {
/** {@inheritDoc} */
@Override
protected void beforeInternalInit(final boolean forceReinit) {
if (saveProfileInSession == null) {
saveProfileInSession = false;
}
}
/** {@inheritDoc} */
@Override
protected final void afterInternalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public final Optional<RedirectionAction> getRedirectionAction(final CallContext ctx) {
throw new UnsupportedOperationException("Direct clients cannot redirect for login");
}
/** {@inheritDoc} */
@Override
public final HttpAction processLogout(final CallContext ctx, final Credentials credentials) {
throw new UnsupportedOperationException("Direct clients cannot process logout");
}
/** {@inheritDoc} */
@Override
public final Optional<RedirectionAction> getLogoutAction(final CallContext ctx, final UserProfile currentProfile,
final String targetUrl) {
throw new UnsupportedOperationException("Direct clients cannot redirect for logout");
}
}
|
// ensures components have been properly initialized
assertNotNull("credentialsExtractor", getCredentialsExtractor());
assertNotNull("authenticator", getAuthenticator());
assertNotNull("profileCreator", getProfileCreator());
| 281
| 56
| 337
|
<methods>public non-sealed void <init>() ,public void addAuthorizationGenerator(org.pac4j.core.authorization.generator.AuthorizationGenerator) ,public void addAuthorizationGenerators(Collection<org.pac4j.core.authorization.generator.AuthorizationGenerator>) ,public org.pac4j.core.logout.handler.SessionLogoutHandler findSessionLogoutHandler() ,public Optional<org.pac4j.core.credentials.Credentials> getCredentials(CallContext) ,public java.lang.String getName() ,public java.lang.Boolean getSaveProfileInSession(org.pac4j.core.context.WebContext, org.pac4j.core.profile.UserProfile) ,public final Optional<org.pac4j.core.profile.UserProfile> getUserProfile(CallContext, org.pac4j.core.credentials.Credentials) ,public boolean isMultiProfile(org.pac4j.core.context.WebContext, org.pac4j.core.profile.UserProfile) ,public void notifySessionRenewal(CallContext, java.lang.String) ,public Optional<org.pac4j.core.profile.UserProfile> renewUserProfile(CallContext, org.pac4j.core.profile.UserProfile) ,public void setAuthorizationGenerator(org.pac4j.core.authorization.generator.AuthorizationGenerator) ,public void setAuthorizationGenerators(List<org.pac4j.core.authorization.generator.AuthorizationGenerator>) ,public transient void setAuthorizationGenerators(org.pac4j.core.authorization.generator.AuthorizationGenerator[]) ,public void setCustomProperties(Map<java.lang.String,java.lang.Object>) ,public void setProfileFactoryWhenNotAuthenticated(org.pac4j.core.profile.factory.ProfileFactory) ,public final Optional<org.pac4j.core.credentials.Credentials> validateCredentials(CallContext, org.pac4j.core.credentials.Credentials) <variables>private org.pac4j.core.credentials.authenticator.Authenticator authenticator,private List<org.pac4j.core.authorization.generator.AuthorizationGenerator> authorizationGenerators,private org.pac4j.core.config.Config config,private org.pac4j.core.credentials.extractor.CredentialsExtractor credentialsExtractor,private Map<java.lang.String,java.lang.Object> customProperties,protected final org.slf4j.Logger logger,private boolean multiProfile,private java.lang.String name,private org.pac4j.core.profile.creator.ProfileCreator profileCreator,private org.pac4j.core.profile.factory.ProfileFactory profileFactoryWhenNotAuthenticated,protected java.lang.Boolean saveProfileInSession,private static boolean warned
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/client/direct/AnonymousClient.java
|
AnonymousClient
|
internalInit
|
class AnonymousClient extends DirectClient {
/** Constant <code>INSTANCE</code> */
public static final AnonymousClient INSTANCE = new AnonymousClient();
private static boolean warned;
/**
* <p>Constructor for AnonymousClient.</p>
*/
public AnonymousClient() {
if (!warned) {
logger.warn("Be careful when using the 'AnonymousClient': an 'AnonymousProfile' is returned "
+ "and the access is granted for the request.");
warned = true;
}
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>}
}
|
setCredentialsExtractorIfUndefined(ctx -> Optional.of(AnonymousCredentials.INSTANCE));
setAuthenticatorIfUndefined((ctx, cred) -> {
cred.setUserProfile(AnonymousProfile.INSTANCE);
return Optional.of(AnonymousCredentials.INSTANCE);
});
| 179
| 81
| 260
|
<methods>public non-sealed void <init>() ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getLogoutAction(CallContext, org.pac4j.core.profile.UserProfile, java.lang.String) ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getRedirectionAction(CallContext) ,public final org.pac4j.core.exception.http.HttpAction processLogout(CallContext, org.pac4j.core.credentials.Credentials) <variables>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/client/finder/DefaultCallbackClientFinder.java
|
DefaultCallbackClientFinder
|
find
|
class DefaultCallbackClientFinder implements ClientFinder {
/**
* <p>Constructor for DefaultCallbackClientFinder.</p>
*/
public DefaultCallbackClientFinder() {}
/** {@inheritDoc} */
@Override
public List<Client> find(final Clients clients, final WebContext context, final String clientNames) {<FILL_FUNCTION_BODY>}
}
|
List<Client> result = new ArrayList<>();
List<Client> indirectClients = new ArrayList<>();
for (val client : clients.findAllClients()) {
if (client instanceof IndirectClient indirectClient) {
indirectClients.add(client);
indirectClient.init();
if (indirectClient.getCallbackUrlResolver().matches(indirectClient.getName(), context)) {
result.add(indirectClient);
}
}
}
LOGGER.debug("result: {}", result.stream().map(Client::getName).collect(Collectors.toList()));
// fallback: no client found and we have a default client, use it
if (result.isEmpty() && CommonHelper.isNotBlank(clientNames)) {
val defaultClient = clients.findClient(clientNames);
if (defaultClient.isPresent()) {
LOGGER.debug("Defaulting to the configured client: {}", defaultClient);
result.add(defaultClient.get());
}
}
// fallback: no client found and we only have one indirect client, use it
if (result.isEmpty() && indirectClients.size() == 1) {
LOGGER.debug("Defaulting to the only client: {}", indirectClients.get(0));
result.addAll(indirectClients);
}
return result;
| 100
| 339
| 439
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/client/finder/DefaultSecurityClientFinder.java
|
DefaultSecurityClientFinder
|
find
|
class DefaultSecurityClientFinder implements ClientFinder {
private String clientNameParameter = Pac4jConstants.DEFAULT_FORCE_CLIENT_PARAMETER;
/** {@inheritDoc} */
@Override
public List<Client> find(final Clients clients, final WebContext context, final String clientNames) {<FILL_FUNCTION_BODY>}
}
|
final List<Client> result = new ArrayList<>();
var securityClientNames = clientNames;
// we don't have defined clients to secure the URL, use the general default security ones from the Clients if they exist
// we check the nullity and not the blankness to allow the blank string to mean no client
// so no clients parameter -> use the default security ones; clients=blank string -> no clients defined
LOGGER.debug("Provided clientNames: {}", securityClientNames);
if (securityClientNames == null) {
securityClientNames = clients.getDefaultSecurityClients();
LOGGER.debug("Default security clients: {}", securityClientNames);
// still no clients defined and we only have one client, use it
if (securityClientNames == null && clients.findAllClients().size() == 1) {
securityClientNames = clients.getClients().get(0).getName();
LOGGER.debug("Only client: {}", securityClientNames);
}
}
if (CommonHelper.isNotBlank(securityClientNames)) {
val names = Arrays.asList(securityClientNames.split(Pac4jConstants.ELEMENT_SEPARATOR));
val clientOnRequest = context.getRequestParameter(clientNameParameter);
// if a client is provided on the request, get the client
// and check if it is allowed (defined in the list of the clients)
LOGGER.debug("clientNameOnRequest: {}", clientOnRequest);
if (clientOnRequest.isPresent()) {
// from the request
val client = clients.findClient(clientOnRequest.get());
if (client.isPresent()) {
val nameFound = client.get().getName();
// if allowed -> return it
for (val name : names) {
if (CommonHelper.areEqualsIgnoreCaseAndTrim(name, nameFound)) {
result.add(client.get());
break;
}
}
}
} else {
// no client provided, return all
for (val name : names) {
// from its name
val client = clients.findClient(name);
if (client.isPresent()) {
result.add(client.get());
}
}
}
}
LOGGER.debug("result: {}", result.stream().map(Client::getName).collect(Collectors.toList()));
return result;
| 91
| 588
| 679
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/config/ConfigBuilder.java
|
ConfigBuilder
|
build
|
class ConfigBuilder {
/**
* <p>build.</p>
*
* @param factoryName a {@link String} object
* @param parameters a {@link Object} object
* @return a {@link Config} object
*/
@SuppressWarnings("unchecked")
public synchronized static Config build(final String factoryName, final Object... parameters) {<FILL_FUNCTION_BODY>}
}
|
try {
LOGGER.info("Build the configuration from factory: {}", factoryName);
val factory = (ConfigFactory) CommonHelper.getConstructor(factoryName).newInstance();
return factory.build(parameters);
} catch (final Exception e) {
throw new TechnicalException("Cannot build configuration", e);
}
| 109
| 82
| 191
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/context/WebContextHelper.java
|
WebContextHelper
|
isQueryStringParameter
|
class WebContextHelper implements HttpConstants {
private static final ZoneId GMT = ZoneId.of("GMT");
/**
* Date formats with time zone as specified in the HTTP RFC to use for formatting.
* @see <a href="https://tools.ietf.org/html/rfc7231#section-7.1.1.1">Section 7.1.1.1 of RFC 7231</a>
*/
private static final DateTimeFormatter DATE_FORMATTER =
DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US).withZone(GMT);
/**
* Get a specific cookie by its name.
*
* @param cookies provided cookies
* @param name the name of the cookie
* @return the cookie
*/
public static Cookie getCookie(final Iterable<Cookie> cookies, final String name) {
if (cookies != null) {
for (val cookie : cookies) {
if (cookie != null && CommonHelper.areEquals(name, cookie.getName())) {
return cookie;
}
}
}
return null;
}
/**
* Get a specific cookie by its name.
*
* @param context the current web context
* @param name the name of the cookie
* @return the cookie
*/
public static Cookie getCookie(final WebContext context, final String name) {
return getCookie(context.getRequestCookies(), name);
}
/**
* Whether it is a GET request.
*
* @param context the web context
* @return whether it is a GET request
*/
public static boolean isGet(final WebContext context) {
return HttpConstants.HTTP_METHOD.GET.name().equalsIgnoreCase(context.getRequestMethod());
}
/**
* Whether it is a POST request.
*
* @param context the web context
* @return whether it is a POST request
*/
public static boolean isPost(final WebContext context) {
return HttpConstants.HTTP_METHOD.POST.name().equalsIgnoreCase(context.getRequestMethod());
}
/**
* Whether it is a PUT request.
*
* @param context the web context
* @return whether it is a PUT request
*/
public static boolean isPut(final WebContext context) {
return HttpConstants.HTTP_METHOD.PUT.name().equalsIgnoreCase(context.getRequestMethod());
}
/**
* Whether it is a PATCH request.
*
* @param context the web context
* @return whether it is a PATCH request
*/
public static boolean isPatch(final WebContext context) {
return HttpConstants.HTTP_METHOD.PATCH.name().equalsIgnoreCase(context.getRequestMethod());
}
/**
* Whether it is a DELETE request.
*
* @param context the web context
* @return whether it is a DELETE request
*/
public static boolean isDelete(final WebContext context) {
return HttpConstants.HTTP_METHOD.DELETE.name().equalsIgnoreCase(context.getRequestMethod());
}
/**
* Whether the request is HTTPS or secure.
*
* @param context the current web context
* @return whether the request is HTTPS or secure
*/
public static boolean isHttpsOrSecure(final WebContext context) {
return SCHEME_HTTPS.equalsIgnoreCase(context.getScheme()) || context.isSecure();
}
/**
* Whether the request is HTTP.
*
* @param context the current web context
* @return whether the request is HTTP
*/
public static boolean isHttp(final WebContext context) {
return SCHEME_HTTP.equalsIgnoreCase(context.getScheme());
}
/**
* Whether the request is HTTPS.
*
* @param context the current web context
* @return whether the request is HTTPS
*/
public static boolean isHttps(final WebContext context) {
return SCHEME_HTTPS.equalsIgnoreCase(context.getScheme());
}
/**
* Custom method for adding cookie because the servlet-api version doesn't support SameSite attributes.
* Sets the default SameSite policy to lax which is what most browsers do if the cookie doesn't specify
* a SameSite policy.
*
* @param cookie pac4j Cookie object
* @return a {@link String} object
*/
public static String createCookieHeader(Cookie cookie) {
var builder = new StringBuilder();
builder.append(String.format("%s=%s;", cookie.getName(), cookie.getValue()));
if (cookie.getMaxAge() > -1) {
builder.append(String.format(" Max-Age=%s;", cookie.getMaxAge()));
long millis = cookie.getMaxAge() > 0 ? System.currentTimeMillis() + (cookie.getMaxAge() * 1000) : 0;
Instant instant = Instant.ofEpochMilli(millis);
ZonedDateTime time = ZonedDateTime.ofInstant(instant, GMT);
builder.append(String.format(" Expires=%s;", DATE_FORMATTER.format(time)));
}
if (CommonHelper.isNotBlank(cookie.getDomain())) {
builder.append(String.format(" Domain=%s;", cookie.getDomain()));
}
builder.append(String.format(" Path=%s;", CommonHelper.isNotBlank(cookie.getPath()) ? cookie.getPath() : "/"));
var sameSitePolicy = cookie.getSameSitePolicy() == null ? "lax" : cookie.getSameSitePolicy().toLowerCase();
switch (sameSitePolicy) {
case "strict" -> builder.append(" SameSite=Strict;");
case "none" -> builder.append(" SameSite=None;");
default -> builder.append(" SameSite=Lax;");
}
if (cookie.isSecure() || "none".equals(sameSitePolicy)) {
builder.append(" Secure;");
}
if (cookie.isHttpOnly()) {
builder.append(" HttpOnly;");
}
var value = builder.toString();
if (value.endsWith(";")) {
value = value.substring(0, value.length() - 1);
}
return value;
}
/**
* Checks whether this parameter is part of the query string.
*
* @param context the web context
* @param name the parameter name
* @return whether this parameter is part of the query string
*/
public static boolean isQueryStringParameter(final WebContext context, final String name) {<FILL_FUNCTION_BODY>}
}
|
val queryString = context.getQueryString();
return queryString.filter(s -> context.getRequestParameter(name).isPresent() && s.contains(name + '=')).isPresent();
| 1,739
| 51
| 1,790
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/credentials/AnonymousCredentials.java
|
AnonymousCredentials
|
equals
|
class AnonymousCredentials extends Credentials {
@Serial
private static final long serialVersionUID = 7526472295622776147L;
/** Constant <code>INSTANCE</code> */
public final static AnonymousCredentials INSTANCE = new AnonymousCredentials();
/** {@inheritDoc} */
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public int hashCode() {
return 0;
}
}
|
if (o instanceof AnonymousCredentials) {
return true;
}
return false;
| 148
| 28
| 176
|
<methods>public non-sealed void <init>() ,public boolean isForAuthentication() <variables>protected org.pac4j.core.logout.LogoutType logoutType,private static final long serialVersionUID,protected java.lang.String source,private org.pac4j.core.profile.UserProfile userProfile
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/credentials/authenticator/LocalCachingAuthenticator.java
|
LocalCachingAuthenticator
|
validate
|
class LocalCachingAuthenticator extends InitializableObject implements Authenticator {
private Authenticator delegate;
private int cacheSize;
private int timeout;
private TimeUnit timeUnit;
private Store<Credentials, UserProfile> store;
/**
* <p>Constructor for LocalCachingAuthenticator.</p>
*/
public LocalCachingAuthenticator() {}
/**
* <p>Constructor for LocalCachingAuthenticator.</p>
*
* @param delegate a {@link Authenticator} object
* @param store a {@link Store} object
*/
public LocalCachingAuthenticator(final Authenticator delegate, final Store<Credentials, UserProfile> store) {
this.delegate = delegate;
this.store = store;
}
/**
* <p>Constructor for LocalCachingAuthenticator.</p>
*
* @param delegate a {@link Authenticator} object
* @param cacheSize a int
* @param timeout a int
* @param timeUnit a {@link TimeUnit} object
*/
public LocalCachingAuthenticator(final Authenticator delegate, final int cacheSize,
final int timeout, final TimeUnit timeUnit) {
this.delegate = delegate;
this.cacheSize = cacheSize;
this.timeout = timeout;
this.timeUnit = timeUnit;
}
/** {@inheritDoc} */
@Override
public Optional<Credentials> validate(final CallContext ctx, final Credentials credentials) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {
if (this.store == null) {
this.store = new GuavaStore<>(cacheSize, timeout, timeUnit);
}
if (delegate instanceof InitializableObject initializableObject) {
initializableObject.init(forceReinit);
}
}
/**
* <p>removeFromCache.</p>
*
* @param credentials a {@link Credentials} object
*/
public void removeFromCache(final Credentials credentials) {
this.store.remove(credentials);
}
/**
* <p>isCached.</p>
*
* @param credentials a {@link Credentials} object
* @return a boolean
*/
public boolean isCached(final Credentials credentials) {
return this.store.get(credentials).isPresent();
}
}
|
init();
var optProfile = this.store.get(credentials);
if (optProfile.isEmpty()) {
LOGGER.debug("No cached credentials found. Delegating authentication to {}...", delegate);
delegate.validate(ctx, credentials);
val profile = credentials.getUserProfile();
LOGGER.debug("Caching credential. Using profile {}...", profile);
store.set(credentials, profile);
} else {
credentials.setUserProfile(optProfile.get());
LOGGER.debug("Found cached credential. Using cached profile {}...", optProfile.get());
}
return Optional.of(credentials);
| 641
| 161
| 802
|
<methods>public non-sealed void <init>() ,public int getNbAttempts() ,public void init() ,public void init(boolean) ,public final boolean isInitialized() ,public void reinit() <variables>private java.util.concurrent.atomic.AtomicBoolean initialized,private volatile java.lang.Long lastAttempt,private int maxAttempts,private long minTimeIntervalBetweenAttemptsInMilliseconds,private java.util.concurrent.atomic.AtomicInteger nbAttempts
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/credentials/extractor/BasicAuthExtractor.java
|
BasicAuthExtractor
|
extract
|
class BasicAuthExtractor implements CredentialsExtractor {
private final HeaderExtractor extractor;
public BasicAuthExtractor() {
this(HttpConstants.AUTHORIZATION_HEADER, HttpConstants.BASIC_HEADER_PREFIX);
}
public BasicAuthExtractor(final String headerName, final String prefixHeader) {
this.extractor = new HeaderExtractor(headerName, prefixHeader);
}
@Override
public Optional<Credentials> extract(final CallContext ctx) {<FILL_FUNCTION_BODY>}
}
|
val optCredentials = this.extractor.extract(ctx);
return optCredentials.map(cred -> {
val credentials = (TokenCredentials) cred;
final byte[] decoded;
try {
decoded = Base64.getDecoder().decode(credentials.getToken());
} catch (IllegalArgumentException e) {
throw new CredentialsException("Bad format of the basic auth header");
}
val token = new String(decoded, StandardCharsets.UTF_8);
val delim = token.indexOf(':');
if (delim < 0) {
throw new CredentialsException("Bad format of the basic auth header");
}
val upc = new UsernamePasswordCredentials(token.substring(0, delim), token.substring(delim + 1));
upc.setSource(CredentialSource.HEADER.name());
return upc;
});
| 144
| 231
| 375
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/credentials/extractor/FormExtractor.java
|
FormExtractor
|
extract
|
class FormExtractor implements CredentialsExtractor {
private final String usernameParameter;
private final String passwordParameter;
@Setter
private ExtractionMode extractionMode = ExtractionMode.ALL;
@Override
public Optional<Credentials> extract(final CallContext ctx) {<FILL_FUNCTION_BODY>}
public enum ExtractionMode {
QUERY_PARAM,
REQUEST_BODY,
ALL
}
}
|
val webContext = ctx.webContext();
var username = Optional.<String>empty();
var password = Optional.<String>empty();
switch (extractionMode) {
case ALL:
username = webContext.getRequestParameter(this.usernameParameter);
password = webContext.getRequestParameter(this.passwordParameter);
break;
case QUERY_PARAM:
try {
if (WebContextHelper.isQueryStringParameter(webContext, this.usernameParameter)) {
username = webContext.getRequestParameter(this.usernameParameter);
}
if (WebContextHelper.isQueryStringParameter(webContext, this.passwordParameter)) {
password = webContext.getRequestParameter(this.passwordParameter);
}
} catch (final Exception e) {
LOGGER.warn(e.getMessage(), e);
}
break;
case REQUEST_BODY:
if ("POST".equalsIgnoreCase(webContext.getRequestMethod())) {
if (!WebContextHelper.isQueryStringParameter(webContext, this.usernameParameter)) {
username = webContext.getRequestParameter(this.usernameParameter);
}
if (!WebContextHelper.isQueryStringParameter(webContext, this.passwordParameter)) {
password = webContext.getRequestParameter(this.passwordParameter);
}
}
break;
}
if (username.isEmpty() || password.isEmpty()) {
return Optional.empty();
}
val upc = new UsernamePasswordCredentials(username.get(), password.get());
upc.setSource(CredentialSource.FORM.name());
return Optional.of(upc);
| 117
| 405
| 522
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/credentials/extractor/HeaderExtractor.java
|
HeaderExtractor
|
extract
|
class HeaderExtractor implements CredentialsExtractor {
private String headerName;
private String prefixHeader;
private boolean trimValue;
/**
* <p>Getter for the field <code>headerName</code>.</p>
*
* @return a {@link String} object
*/
public String getHeaderName() {
return headerName;
}
/**
* <p>Setter for the field <code>headerName</code>.</p>
*
* @param headerName a {@link String} object
*/
public void setHeaderName(String headerName) {
this.headerName = headerName;
}
/**
* <p>Getter for the field <code>prefixHeader</code>.</p>
*
* @return a {@link String} object
*/
public String getPrefixHeader() {
return prefixHeader;
}
/**
* <p>Setter for the field <code>prefixHeader</code>.</p>
*
* @param prefixHeader a {@link String} object
*/
public void setPrefixHeader(String prefixHeader) {
this.prefixHeader = prefixHeader;
}
/**
* <p>isTrimValue.</p>
*
* @return a boolean
*/
public boolean isTrimValue() {
return trimValue;
}
/**
* <p>Setter for the field <code>trimValue</code>.</p>
*
* @param trimValue a boolean
*/
public void setTrimValue(boolean trimValue) {
this.trimValue = trimValue;
}
/**
* <p>Constructor for HeaderExtractor.</p>
*/
public HeaderExtractor() {
// empty constructor as needed to be instanciated by beanutils
}
/**
* <p>Constructor for HeaderExtractor.</p>
*
* @param headerName a {@link String} object
* @param prefixHeader a {@link String} object
*/
public HeaderExtractor(final String headerName, final String prefixHeader) {
this.headerName = headerName;
this.prefixHeader = prefixHeader;
}
/** {@inheritDoc} */
@Override
public Optional<Credentials> extract(final CallContext ctx) {<FILL_FUNCTION_BODY>}
}
|
CommonHelper.assertNotBlank("headerName", this.headerName);
CommonHelper.assertNotNull("prefixHeader", this.prefixHeader);
var header = ctx.webContext().getRequestHeader(this.headerName);
if (header.isEmpty()) {
header = ctx.webContext().getRequestHeader(this.headerName.toLowerCase());
if (header.isEmpty()) {
return Optional.empty();
}
}
if (!header.get().startsWith(this.prefixHeader)) {
throw new CredentialsException("Wrong prefix for header: " + this.headerName);
}
var headerWithoutPrefix = header.get().substring(this.prefixHeader.length());
if (trimValue) {
headerWithoutPrefix = headerWithoutPrefix.trim();
}
return Optional.of(new TokenCredentials(headerWithoutPrefix));
| 624
| 217
| 841
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/credentials/extractor/ParameterExtractor.java
|
ParameterExtractor
|
extract
|
class ParameterExtractor implements CredentialsExtractor {
private final String parameterName;
private boolean supportGetRequest;
private boolean supportPostRequest;
/**
* <p>Constructor for ParameterExtractor.</p>
*
* @param parameterName a {@link String} object
*/
public ParameterExtractor(final String parameterName) {
this(parameterName, false, true);
}
/**
* <p>Constructor for ParameterExtractor.</p>
*
* @param parameterName a {@link String} object
* @param supportGetRequest a boolean
* @param supportPostRequest a boolean
*/
public ParameterExtractor(final String parameterName, final boolean supportGetRequest,
final boolean supportPostRequest) {
this.parameterName = parameterName;
this.supportGetRequest = supportGetRequest;
this.supportPostRequest = supportPostRequest;
}
/** {@inheritDoc} */
@Override
public Optional<Credentials> extract(final CallContext ctx) {<FILL_FUNCTION_BODY>}
}
|
val webContext = ctx.webContext();
if (WebContextHelper.isGet(webContext) && !supportGetRequest) {
throw new CredentialsException("GET requests not supported");
} else if (WebContextHelper.isPost(webContext) && !supportPostRequest) {
throw new CredentialsException("POST requests not supported");
}
val value = webContext.getRequestParameter(this.parameterName);
if (value.isEmpty()) {
return Optional.empty();
}
return Optional.of(new TokenCredentials(value.get()));
| 276
| 144
| 420
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/engine/AbstractExceptionAwareLogic.java
|
AbstractExceptionAwareLogic
|
handleException
|
class AbstractExceptionAwareLogic {
private String errorUrl;
/**
* Handle exceptions.
*
* @param e the thrown exception
* @param httpActionAdapter the HTTP action adapter
* @param context the web context
* @return the final HTTP result
*/
protected Object handleException(final Exception e, final HttpActionAdapter httpActionAdapter, final WebContext context) {<FILL_FUNCTION_BODY>}
/**
* Wrap an Exception into a RuntimeException.
*
* @param exception the original exception
* @return the RuntimeException
*/
protected RuntimeException runtimeException(final Exception exception) {
if (exception instanceof RuntimeException runtimeException) {
throw runtimeException;
} else {
throw new RuntimeException(exception);
}
}
/**
* <p>buildContext.</p>
*
* @param config a {@link Config} object
* @param parameters a {@link FrameworkParameters} object
* @return a {@link CallContext} object
*/
protected CallContext buildContext(final Config config, final FrameworkParameters parameters) {
assertNotNull("config", config);
assertNotNull("config.getWebContextFactory()", config.getWebContextFactory());
val webContext = config.getWebContextFactory().newContext(parameters);
assertNotNull("context", webContext);
assertNotNull("config.getSessionStoreFactory()", config.getSessionStoreFactory());
val sessionStore = config.getSessionStoreFactory().newSessionStore(parameters);
assertNotNull("sessionStore", sessionStore);
val profileManagerFactory = config.getProfileManagerFactory();
assertNotNull("profileManagerFactory", profileManagerFactory);
return new CallContext(webContext, sessionStore, profileManagerFactory);
}
}
|
if (httpActionAdapter == null || context == null) {
throw runtimeException(e);
} else if (e instanceof HttpAction httpAction) {
LOGGER.debug("extra HTTP action required in security: {}", httpAction.getCode());
return httpActionAdapter.adapt(httpAction, context);
} else {
if (CommonHelper.isNotBlank(errorUrl)) {
val action = HttpActionHelper.buildRedirectUrlAction(context, errorUrl);
return httpActionAdapter.adapt(action, context);
} else {
throw runtimeException(e);
}
}
| 439
| 149
| 588
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/engine/DefaultCallbackLogic.java
|
DefaultCallbackLogic
|
perform
|
class DefaultCallbackLogic extends AbstractExceptionAwareLogic implements CallbackLogic {
/** Constant <code>INSTANCE</code> */
public static final DefaultCallbackLogic INSTANCE = new DefaultCallbackLogic();
private ClientFinder clientFinder = new DefaultCallbackClientFinder();
private SavedRequestHandler savedRequestHandler = new DefaultSavedRequestHandler();
/** {@inheritDoc} */
@Override
public Object perform(final Config config, final String inputDefaultUrl, final Boolean inputRenewSession,
final String defaultClient, final FrameworkParameters parameters) {<FILL_FUNCTION_BODY>}
/**
* <p>saveUserProfile.</p>
*
* @param ctx a {@link CallContext} object
* @param config a {@link Config} object
* @param profile a {@link UserProfile} object
* @param saveProfileInSession a boolean
* @param multiProfile a boolean
* @param renewSession a boolean
*/
protected void saveUserProfile(final CallContext ctx, final Config config, final UserProfile profile,
final boolean saveProfileInSession, final boolean multiProfile, final boolean renewSession) {
val manager = ctx.profileManagerFactory().apply(ctx.webContext(), ctx.sessionStore());
if (profile != null) {
manager.save(saveProfileInSession, profile, multiProfile);
if (renewSession) {
renewSession(ctx, config);
}
}
}
/**
* <p>renewSession.</p>
*
* @param ctx a {@link CallContext} object
* @param config a {@link Config} object
*/
protected void renewSession(final CallContext ctx, final Config config) {
val context = ctx.webContext();
val sessionStore = ctx.sessionStore();
val optOldSessionId = sessionStore.getSessionId(context, true);
if (optOldSessionId.isEmpty()) {
LOGGER.error("No old session identifier retrieved although the session creation has been requested");
} else {
val oldSessionId = optOldSessionId.get();
val renewed = sessionStore.renewSession(context);
if (renewed) {
val optNewSessionId = sessionStore.getSessionId(context, true);
if (optNewSessionId.isEmpty()) {
LOGGER.error("No new session identifier retrieved although the session creation has been requested");
} else {
val newSessionId = optNewSessionId.get();
LOGGER.debug("Renewing session: {} -> {}", oldSessionId, newSessionId);
val clients = config.getClients();
if (clients != null) {
val clientList = clients.getClients();
for (val client : clientList) {
val baseClient = (BaseClient) client;
baseClient.notifySessionRenewal(ctx, oldSessionId);
}
}
}
} else {
LOGGER.error("Unable to renew the session. The session store may not support this feature");
}
}
}
/**
* <p>redirectToOriginallyRequestedUrl.</p>
*
* @param ctx a {@link CallContext} object
* @param defaultUrl a {@link String} object
* @return a {@link HttpAction} object
*/
protected HttpAction redirectToOriginallyRequestedUrl(final CallContext ctx, final String defaultUrl) {
return savedRequestHandler.restore(ctx, defaultUrl);
}
}
|
LOGGER.debug("=== CALLBACK ===");
// checks
val ctx = buildContext(config, parameters);
val webContext = ctx.webContext();
val httpActionAdapter = config.getHttpActionAdapter();
assertNotNull("httpActionAdapter", httpActionAdapter);
HttpAction action;
try {
assertNotNull("clientFinder", clientFinder);
// default values
final String defaultUrl;
defaultUrl = Objects.requireNonNullElse(inputDefaultUrl, Pac4jConstants.DEFAULT_URL_VALUE);
val renewSession = inputRenewSession == null || inputRenewSession;
assertNotBlank(Pac4jConstants.DEFAULT_URL, defaultUrl);
val clients = config.getClients();
assertNotNull("clients", clients);
val foundClients = clientFinder.find(clients, webContext, defaultClient);
assertTrue(foundClients != null && foundClients.size() == 1,
"unable to find one indirect client for the callback: check the callback URL for a client name parameter or suffix path"
+ " or ensure that your configuration defaults to one indirect client");
val foundClient = foundClients.get(0);
LOGGER.debug("foundClient: {}", foundClient);
assertNotNull("foundClient", foundClient);
var credentials = foundClient.getCredentials(ctx).orElse(null);
LOGGER.debug("extracted credentials: {}", credentials);
credentials = foundClient.validateCredentials(ctx, credentials).orElse(null);
LOGGER.debug("validated credentials: {}", credentials);
if (credentials != null && !credentials.isForAuthentication()) {
action = foundClient.processLogout(ctx, credentials);
} else {
if (credentials != null) {
val optProfile = foundClient.getUserProfile(ctx, credentials);
LOGGER.debug("optProfile: {}", optProfile);
if (optProfile.isPresent()) {
val profile = optProfile.get();
val saveProfileInSession = ((BaseClient) foundClient).getSaveProfileInSession(webContext, profile);
val multiProfile = ((BaseClient) foundClient).isMultiProfile(webContext, profile);
LOGGER.debug("saveProfileInSession: {} / multiProfile: {}", saveProfileInSession, multiProfile);
saveUserProfile(ctx, config, profile, saveProfileInSession, multiProfile, renewSession);
}
}
action = redirectToOriginallyRequestedUrl(ctx, defaultUrl);
}
} catch (final RuntimeException e) {
return handleException(e, httpActionAdapter, webContext);
}
return httpActionAdapter.adapt(action, webContext);
| 875
| 680
| 1,555
|
<methods>public non-sealed void <init>() <variables>private java.lang.String errorUrl
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/engine/DefaultLogoutLogic.java
|
DefaultLogoutLogic
|
perform
|
class DefaultLogoutLogic extends AbstractExceptionAwareLogic implements LogoutLogic {
/** Constant <code>INSTANCE</code> */
public static final LogoutLogic INSTANCE = new DefaultLogoutLogic();
/** {@inheritDoc} */
@Override
public Object perform(final Config config, final String defaultUrl, final String inputLogoutUrlPattern, final Boolean inputLocalLogout,
final Boolean inputDestroySession, final Boolean inputCentralLogout, final FrameworkParameters parameters) {<FILL_FUNCTION_BODY>}
/**
* <p>enhanceRedirectUrl.</p>
*
* @param ctx a {@link CallContext} object
* @param config a {@link Config} object
* @param client a {@link Client} object
* @param redirectUrl a {@link String} object
* @return a {@link String} object
*/
protected String enhanceRedirectUrl(final CallContext ctx, final Config config, final Client client, final String redirectUrl) {
return redirectUrl;
}
}
|
LOGGER.debug("=== LOGOUT ===");
// checks
val ctx = buildContext(config, parameters);
val webContext = ctx.webContext();
val httpActionAdapter = config.getHttpActionAdapter();
assertNotNull("httpActionAdapter", httpActionAdapter);
HttpAction action;
try {
val sessionStore = ctx.sessionStore();
// default values
final String logoutUrlPattern;
logoutUrlPattern = Objects.requireNonNullElse(inputLogoutUrlPattern, Pac4jConstants.DEFAULT_LOGOUT_URL_PATTERN_VALUE);
val localLogout = inputLocalLogout == null || inputLocalLogout;
val destroySession = inputDestroySession != null && inputDestroySession;
val centralLogout = inputCentralLogout != null && inputCentralLogout;
assertNotBlank(Pac4jConstants.LOGOUT_URL_PATTERN, logoutUrlPattern);
val configClients = config.getClients();
assertNotNull("configClients", configClients);
// logic
val manager = ctx.profileManagerFactory().apply(webContext, sessionStore);
manager.setConfig(config);
val profiles = manager.getProfiles();
// compute redirection URL
val url = webContext.getRequestParameter(Pac4jConstants.URL);
var redirectUrl = defaultUrl;
if (url.isPresent() && Pattern.matches(logoutUrlPattern, url.get())) {
redirectUrl = url.get();
}
LOGGER.debug("redirectUrl: {}", redirectUrl);
if (redirectUrl != null) {
action = HttpActionHelper.buildRedirectUrlAction(webContext, redirectUrl);
} else {
action = NoContentAction.INSTANCE;
}
// local logout if requested or multiple profiles
if (localLogout || profiles.size() > 1) {
LOGGER.debug("Performing application logout");
manager.removeProfiles();
String sessionId = null;
if (sessionStore != null) {
sessionId = sessionStore.getSessionId(webContext, false).orElse(null);
if (destroySession) {
val removed = sessionStore.destroySession(webContext);
if (!removed) {
LOGGER.error("Unable to destroy the web session. The session store may not support this feature");
}
}
} else {
LOGGER.error("No session store available for this web context");
}
val sessionLogoutHandler = config.getSessionLogoutHandler();
if (sessionLogoutHandler != null && sessionId != null) {
sessionLogoutHandler.cleanRecord(sessionId);
}
}
// central logout
if (centralLogout) {
LOGGER.debug("Performing central logout");
for (val profile : profiles) {
LOGGER.debug("Profile: {}", profile);
val clientName = profile.getClientName();
if (clientName != null) {
val client = configClients.findClient(clientName);
if (client.isPresent()) {
String targetUrl = null;
if (redirectUrl != null) {
redirectUrl = enhanceRedirectUrl(ctx, config, client.get(), redirectUrl);
if (redirectUrl.startsWith(HttpConstants.SCHEME_HTTP) ||
redirectUrl.startsWith(HttpConstants.SCHEME_HTTPS)) {
targetUrl = redirectUrl;
}
}
val logoutAction =
client.get().getLogoutAction(ctx, profile, targetUrl);
LOGGER.debug("Logout action: {}", logoutAction);
if (logoutAction.isPresent()) {
action = logoutAction.get();
break;
}
}
}
}
}
} catch (final RuntimeException e) {
return handleException(e, httpActionAdapter, webContext);
}
return httpActionAdapter.adapt(action, webContext);
| 261
| 1,012
| 1,273
|
<methods>public non-sealed void <init>() <variables>private java.lang.String errorUrl
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/engine/DefaultSecurityLogic.java
|
DefaultSecurityLogic
|
perform
|
class DefaultSecurityLogic extends AbstractExceptionAwareLogic implements SecurityLogic {
/** Constant <code>INSTANCE</code> */
public static final DefaultSecurityLogic INSTANCE = new DefaultSecurityLogic();
private ClientFinder clientFinder = new DefaultSecurityClientFinder();
private AuthorizationChecker authorizationChecker = new DefaultAuthorizationChecker();
private MatchingChecker matchingChecker = new DefaultMatchingChecker();
private SavedRequestHandler savedRequestHandler = new DefaultSavedRequestHandler();
private boolean loadProfilesFromSession = true;
/** {@inheritDoc} */
@Override
public Object perform(final Config config, final SecurityGrantedAccessAdapter securityGrantedAccessAdapter,
final String clients, final String authorizers, final String matchers, final FrameworkParameters parameters) {<FILL_FUNCTION_BODY>}
/**
* Load the profiles.
*
* @param ctx the context
* @param manager the profile manager
* @param clients the current clients
* @return a {@link List} object
*/
protected List<UserProfile> loadProfiles(final CallContext ctx, final ProfileManager manager, final List<Client> clients) {
return manager.getProfiles();
}
/**
* Return a forbidden error.
*
* @param ctx the context
* @param currentClients the current clients
* @param profiles the current profiles
* @param authorizers the authorizers
* @return a forbidden error
*/
protected HttpAction forbidden(final CallContext ctx, final List<Client> currentClients,
final List<UserProfile> profiles, final String authorizers) {
return new ForbiddenAction();
}
/**
* Return whether we must start a login process if the first client is an indirect one.
*
* @param ctx the context
* @param currentClients the current clients
* @return whether we must start a login process
*/
protected boolean startAuthentication(final CallContext ctx, final List<Client> currentClients) {
return isNotEmpty(currentClients) && currentClients.get(0) instanceof IndirectClient;
}
/**
* Save the requested url.
*
* @param ctx the context
* @param currentClients the current clients
* @param ajaxRequestResolver the AJAX request resolver
*/
protected void saveRequestedUrl(final CallContext ctx, final List<Client> currentClients,
final AjaxRequestResolver ajaxRequestResolver) {
if (ajaxRequestResolver == null || !ajaxRequestResolver.isAjax(ctx)) {
savedRequestHandler.save(ctx);
}
}
/**
* Perform a redirection to start the login process of the first indirect client.
*
* @param ctx the context
* @param currentClients the current clients
* @return the performed redirection
*/
protected HttpAction redirectToIdentityProvider(final CallContext ctx, final List<Client> currentClients) {
Client currentClient = (IndirectClient) currentClients.get(0);
return currentClient.getRedirectionAction(ctx).get();
}
/**
* Return an unauthorized error.
*
* @param ctx the context
* @param currentClients the current clients
* @return an unauthorized error
*/
protected HttpAction unauthorized(final CallContext ctx, final List<Client> currentClients) {
return HttpActionHelper.buildUnauthenticatedAction(ctx.webContext());
}
}
|
LOGGER.debug("=== SECURITY ===");
// checks
val ctx = buildContext(config, parameters);
val webContext = ctx.webContext();
val sessionStore = ctx.sessionStore();
val httpActionAdapter = config.getHttpActionAdapter();
assertNotNull("httpActionAdapter", httpActionAdapter);
HttpAction action;
try {
assertNotNull("clientFinder", clientFinder);
assertNotNull("authorizationChecker", authorizationChecker);
assertNotNull("matchingChecker", matchingChecker);
val configClients = config.getClients();
assertNotNull("configClients", configClients);
// logic
LOGGER.debug("url: {}", webContext.getFullRequestURL());
LOGGER.debug("clients: {} | matchers: {}", clients, matchers);
val currentClients = clientFinder.find(configClients, webContext, clients);
LOGGER.debug("currentClients: {}", currentClients);
if (matchingChecker.matches(ctx, matchers, config.getMatchers(), currentClients)) {
val manager = ctx.profileManagerFactory().apply(webContext, sessionStore);
manager.setConfig(config);
var profiles = this.loadProfilesFromSession
? loadProfiles(ctx, manager, currentClients)
: List.<UserProfile>of();
LOGGER.debug("Loaded profiles (from session: {}): {} ", this.loadProfilesFromSession, profiles);
// no profile and some current clients
if (isEmpty(profiles) && isNotEmpty(currentClients)) {
var updated = false;
// loop on all clients searching direct ones to perform authentication
for (val currentClient : currentClients) {
if (currentClient instanceof DirectClient directClient) {
LOGGER.debug("Performing authentication for direct client: {}", currentClient);
var credentials = currentClient.getCredentials(ctx).orElse(null);
credentials = currentClient.validateCredentials(ctx, credentials).orElse(null);
LOGGER.debug("credentials: {}", credentials);
if (credentials != null && credentials.isForAuthentication()) {
val optProfile = currentClient.getUserProfile(ctx, credentials);
LOGGER.debug("profile: {}", optProfile);
if (optProfile.isPresent()) {
val profile = optProfile.get();
val saveProfileInSession = directClient.getSaveProfileInSession(webContext, profile);
val multiProfile = directClient.isMultiProfile(webContext, profile);
LOGGER.debug("saveProfileInSession: {} / multiProfile: {}", saveProfileInSession, multiProfile);
manager.save(saveProfileInSession, profile, multiProfile);
updated = true;
if (!multiProfile) {
break;
}
}
}
}
}
if (updated) {
profiles = loadProfiles(ctx, manager, currentClients);
LOGGER.debug("Reloaded profiles: {}", profiles);
}
}
// we have profile(s) -> check authorizations; otherwise, redirect to identity provider or 401
if (isNotEmpty(profiles)) {
LOGGER.debug("authorizers: {}", authorizers);
if (authorizationChecker.isAuthorized(webContext, sessionStore, profiles,
authorizers, config.getAuthorizers(), currentClients)) {
LOGGER.debug("authenticated and authorized -> grant access");
return securityGrantedAccessAdapter.adapt(webContext, sessionStore, profiles);
} else {
LOGGER.debug("forbidden");
action = forbidden(ctx, currentClients, profiles, authorizers);
}
} else {
if (startAuthentication(ctx, currentClients)) {
LOGGER.debug("Starting authentication");
saveRequestedUrl(ctx, currentClients, config.getClients().getAjaxRequestResolver());
action = redirectToIdentityProvider(ctx, currentClients);
} else {
LOGGER.debug("unauthorized");
action = unauthorized(ctx, currentClients);
}
}
} else {
LOGGER.debug("no matching for this request -> grant access");
return securityGrantedAccessAdapter.adapt(webContext, sessionStore, Collections.emptyList());
}
} catch (final Exception e) {
return handleException(e, httpActionAdapter, webContext);
}
return httpActionAdapter.adapt(action, webContext);
| 893
| 1,139
| 2,032
|
<methods>public non-sealed void <init>() <variables>private java.lang.String errorUrl
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/engine/savedrequest/DefaultSavedRequestHandler.java
|
DefaultSavedRequestHandler
|
restore
|
class DefaultSavedRequestHandler implements SavedRequestHandler {
/** {@inheritDoc} */
@Override
public void save(final CallContext ctx) {
val webContext = ctx.webContext();
val sessionStore = ctx.sessionStore();
val requestedUrl = getRequestedUrl(webContext, sessionStore);
if (WebContextHelper.isPost(webContext)) {
LOGGER.debug("requestedUrl with data: {}", requestedUrl);
val formPost = HttpActionHelper.buildFormPostContent(webContext);
sessionStore.set(webContext, Pac4jConstants.REQUESTED_URL, new OkAction(formPost));
} else {
LOGGER.debug("requestedUrl: {}", requestedUrl);
sessionStore.set(webContext, Pac4jConstants.REQUESTED_URL, requestedUrl);
}
}
/**
* <p>getRequestedUrl.</p>
*
* @param context a {@link WebContext} object
* @param sessionStore a {@link SessionStore} object
* @return a {@link String} object
*/
protected String getRequestedUrl(final WebContext context, final SessionStore sessionStore) {
return context.getFullRequestURL();
}
/** {@inheritDoc} */
@Override
public HttpAction restore(final CallContext ctx, final String defaultUrl) {<FILL_FUNCTION_BODY>}
}
|
val webContext = ctx.webContext();
val sessionStore = ctx.sessionStore();
val optRequestedUrl = sessionStore.get(webContext, Pac4jConstants.REQUESTED_URL);
HttpAction requestedAction = null;
if (optRequestedUrl.isPresent()) {
sessionStore.set(webContext, Pac4jConstants.REQUESTED_URL, null);
val requestedUrl = optRequestedUrl.get();
if (requestedUrl instanceof String) {
requestedAction = new FoundAction((String) requestedUrl);
} else if (requestedUrl instanceof RedirectionAction) {
requestedAction = (RedirectionAction) requestedUrl;
}
}
if (requestedAction == null) {
requestedAction = new FoundAction(defaultUrl);
}
LOGGER.debug("requestedAction: {}", requestedAction.getMessage());
if (requestedAction instanceof FoundAction) {
return HttpActionHelper.buildRedirectUrlAction(webContext, ((FoundAction) requestedAction).getLocation());
} else {
return HttpActionHelper.buildFormPostContentAction(webContext, ((OkAction) requestedAction).getContent());
}
| 348
| 285
| 633
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/http/ajax/DefaultAjaxRequestResolver.java
|
DefaultAjaxRequestResolver
|
buildAjaxResponse
|
class DefaultAjaxRequestResolver implements AjaxRequestResolver, HttpConstants, Pac4jConstants {
private boolean addRedirectionUrlAsHeader = false;
/** {@inheritDoc} */
@Override
public boolean isAjax(final CallContext ctx) {
val webContext = ctx.webContext();
val xmlHttpRequest = AJAX_HEADER_VALUE
.equalsIgnoreCase(webContext.getRequestHeader(AJAX_HEADER_NAME).orElse(null));
val hasDynamicAjaxParameter = Boolean.TRUE.toString()
.equalsIgnoreCase(webContext.getRequestHeader(IS_AJAX_REQUEST).orElse(null));
val hasDynamicAjaxHeader = Boolean.TRUE.toString()
.equalsIgnoreCase(webContext.getRequestParameter(IS_AJAX_REQUEST).orElse(null));
return xmlHttpRequest || hasDynamicAjaxParameter || hasDynamicAjaxHeader;
}
/** {@inheritDoc} */
@Override
public HttpAction buildAjaxResponse(final CallContext ctx, final RedirectionActionBuilder redirectionActionBuilder) {<FILL_FUNCTION_BODY>}
}
|
String url = null;
if (addRedirectionUrlAsHeader) {
val action = redirectionActionBuilder.getRedirectionAction(ctx).orElse(null);
if (action instanceof WithLocationAction) {
url = ((WithLocationAction) action).getLocation();
}
}
val webContext = ctx.webContext();
if (webContext.getRequestParameter(FACES_PARTIAL_AJAX_PARAMETER).isEmpty()) {
if (CommonHelper.isNotBlank(url)) {
webContext.setResponseHeader(HttpConstants.LOCATION_HEADER, url);
}
LOGGER.debug("Faces is not used: returning unauthenticated error for url: {}", url);
return HttpActionHelper.buildUnauthenticatedAction(webContext);
}
val buffer = new StringBuilder();
buffer.append("<?xml version='1.0' encoding='UTF-8'?>");
buffer.append("<partial-response>");
if (CommonHelper.isNotBlank(url)) {
buffer.append("<redirect url=\"" + url.replaceAll("&", "&") + "\"></redirect>");
}
buffer.append("</partial-response>");
LOGGER.debug("Faces is used: returning partial response content for url: {}", url);
return HttpActionHelper.buildFormPostContentAction(webContext, buffer.toString());
| 278
| 359
| 637
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/http/callback/PathParameterCallbackUrlResolver.java
|
PathParameterCallbackUrlResolver
|
matches
|
class PathParameterCallbackUrlResolver implements CallbackUrlResolver {
/** {@inheritDoc} */
@Override
public String compute(final UrlResolver urlResolver, final String url, final String clientName, final WebContext context) {
var newUrl = urlResolver.compute(url, context);
if (newUrl != null) {
if (!newUrl.endsWith("/")) {
newUrl += "/";
}
newUrl += clientName;
}
return newUrl;
}
/** {@inheritDoc} */
@Override
public boolean matches(final String clientName, final WebContext context) {<FILL_FUNCTION_BODY>}
}
|
val path = context.getPath();
if (path != null) {
val pos = path.lastIndexOf("/");
final String name;
if (pos >= 0) {
name = path.substring(pos + 1);
} else {
name = path;
}
return CommonHelper.areEqualsIgnoreCaseAndTrim(name, clientName);
}
return false;
| 166
| 104
| 270
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/http/callback/QueryParameterCallbackUrlResolver.java
|
QueryParameterCallbackUrlResolver
|
compute
|
class QueryParameterCallbackUrlResolver implements CallbackUrlResolver {
@Getter
@Setter
private String clientNameParameter = Pac4jConstants.DEFAULT_CLIENT_NAME_PARAMETER;
private Map<String, String> customParams = new HashMap<>();
/**
* <p>Constructor for QueryParameterCallbackUrlResolver.</p>
*/
public QueryParameterCallbackUrlResolver() {
}
/**
* <p>Constructor for QueryParameterCallbackUrlResolver.</p>
*
* @param customParams a {@link Map} object
*/
public QueryParameterCallbackUrlResolver(final Map<String, String> customParams) {
this.customParams = customParams;
}
/** {@inheritDoc} */
@Override
public String compute(final UrlResolver urlResolver, final String url, final String clientName, final WebContext context) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public boolean matches(final String clientName, final WebContext context) {
val name = context.getRequestParameter(this.clientNameParameter).orElse(null);
return CommonHelper.areEqualsIgnoreCaseAndTrim(name, clientName);
}
}
|
var newUrl = urlResolver.compute(url, context);
if (newUrl != null && !newUrl.contains(this.clientNameParameter + '=')) {
newUrl = CommonHelper.addParameter(newUrl, this.clientNameParameter, clientName);
}
for (val entry : this.customParams.entrySet()) {
newUrl = CommonHelper.addParameter(newUrl, entry.getKey(), entry.getValue());
}
return newUrl;
| 307
| 118
| 425
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/http/url/DefaultUrlResolver.java
|
DefaultUrlResolver
|
compute
|
class DefaultUrlResolver implements UrlResolver {
private boolean completeRelativeUrl;
/**
* <p>Constructor for DefaultUrlResolver.</p>
*/
public DefaultUrlResolver() {}
/**
* <p>Constructor for DefaultUrlResolver.</p>
*
* @param completeRelativeUrl a boolean
*/
public DefaultUrlResolver(final boolean completeRelativeUrl) {
this.completeRelativeUrl = completeRelativeUrl;
}
/** {@inheritDoc} */
@Override
public String compute(final String url, WebContext context) {<FILL_FUNCTION_BODY>}
}
|
if (this.completeRelativeUrl) {
val relativeUrl = url != null
&& !url.startsWith(HttpConstants.SCHEME_HTTP) && !url.startsWith(HttpConstants.SCHEME_HTTPS);
if (context != null && relativeUrl) {
val sb = new StringBuilder();
sb.append(context.getScheme()).append("://").append(context.getServerName());
val notDefaultHttpPort = WebContextHelper.isHttp(context) &&
context.getServerPort() != HttpConstants.DEFAULT_HTTP_PORT;
val notDefaultHttpsPort = WebContextHelper.isHttps(context) &&
context.getServerPort() != HttpConstants.DEFAULT_HTTPS_PORT;
if (notDefaultHttpPort || notDefaultHttpsPort) {
sb.append(":").append(context.getServerPort());
}
sb.append(url.startsWith("/") ? url : "/" + url);
return sb.toString();
}
}
return url;
| 162
| 271
| 433
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/logout/CasLogoutActionBuilder.java
|
CasLogoutActionBuilder
|
getLogoutAction
|
class CasLogoutActionBuilder implements LogoutActionBuilder {
private final String serverLogoutUrl;
private final String postLogoutUrlParameter;
/**
* <p>Constructor for CasLogoutActionBuilder.</p>
*
* @param serverLogoutUrl a {@link String} object
* @param postLogoutUrlParameter a {@link String} object
*/
public CasLogoutActionBuilder(final String serverLogoutUrl, final String postLogoutUrlParameter) {
if (isNotBlank(serverLogoutUrl)) {
assertNotBlank("postLogoutUrlParameter", postLogoutUrlParameter);
}
this.serverLogoutUrl = serverLogoutUrl;
this.postLogoutUrlParameter = postLogoutUrlParameter;
}
/** {@inheritDoc} */
@Override
public Optional<RedirectionAction> getLogoutAction(final CallContext ctx, final UserProfile currentProfile, final String targetUrl) {<FILL_FUNCTION_BODY>}
}
|
if (isBlank(serverLogoutUrl)) {
return Optional.empty();
}
var redirectUrl = serverLogoutUrl;
if (isNotBlank(targetUrl)) {
redirectUrl = addParameter(redirectUrl, postLogoutUrlParameter, targetUrl);
}
LOGGER.debug("redirectUrl: {}", redirectUrl);
return Optional.of(HttpActionHelper.buildRedirectUrlAction(ctx.webContext(), redirectUrl));
| 248
| 117
| 365
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/logout/GoogleLogoutActionBuilder.java
|
GoogleLogoutActionBuilder
|
getLogoutAction
|
class GoogleLogoutActionBuilder implements LogoutActionBuilder {
/** {@inheritDoc} */
@Override
public Optional<RedirectionAction> getLogoutAction(final CallContext ctx, final UserProfile currentProfile, final String targetUrl) {<FILL_FUNCTION_BODY>}
}
|
val redirectUrl = "https://accounts.google.com/Logout";
LOGGER.debug("redirectUrl: {}", redirectUrl);
return Optional.of(HttpActionHelper.buildRedirectUrlAction(ctx.webContext(), redirectUrl));
| 71
| 64
| 135
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/logout/handler/DefaultSessionLogoutHandler.java
|
DefaultSessionLogoutHandler
|
destroySession
|
class DefaultSessionLogoutHandler implements SessionLogoutHandler {
private Store<String, Object> store = new GuavaStore<>(10000, 30, TimeUnit.MINUTES);
private boolean destroySession;
/**
* <p>Constructor for DefaultSessionLogoutHandler.</p>
*/
public DefaultSessionLogoutHandler() {}
/**
* <p>Constructor for DefaultSessionLogoutHandler.</p>
*
* @param store a {@link Store} object
*/
public DefaultSessionLogoutHandler(final Store<String, Object> store) {
this.store = store;
}
/** {@inheritDoc} */
@Override
public void recordSession(final CallContext ctx, final String key) {
val webContext = ctx.webContext();
val sessionStore = ctx.sessionStore();
if (sessionStore == null) {
LOGGER.error("No session store available for this web context");
} else {
val optSessionId = sessionStore.getSessionId(webContext, true);
if (optSessionId.isEmpty()) {
LOGGER.error("No session identifier retrieved although the session creation has been requested");
} else {
val sessionId = optSessionId.get();
val optTrackableSession = sessionStore.getTrackableSession(webContext);
if (optTrackableSession.isPresent()) {
val trackableSession = optTrackableSession.get();
LOGGER.debug("key: {} -> trackableSession: {}", key, trackableSession);
LOGGER.debug("sessionId: {}", sessionId);
store.set(key, trackableSession);
store.set(sessionId, key);
} else {
LOGGER.debug("No trackable session for the current session store: {}", sessionStore);
}
}
}
}
/** {@inheritDoc} */
@Override
public void destroySession(final CallContext ctx, final String key) {<FILL_FUNCTION_BODY>}
/**
* <p>destroy.</p>
*
* @param webContext a {@link WebContext} object
* @param sessionStore a {@link SessionStore} object
* @param profileManagerFactory a {@link ProfileManagerFactory} object
* @param channel a {@link String} object
*/
protected void destroy(final WebContext webContext, final SessionStore sessionStore,
final ProfileManagerFactory profileManagerFactory, final String channel) {
// remove profiles
val manager = profileManagerFactory.apply(webContext, sessionStore);
manager.removeProfiles();
LOGGER.debug("{} channel logout call: destroy the user profiles", channel);
// and optionally the web session
if (destroySession) {
LOGGER.debug("destroy the whole session");
val invalidated = sessionStore.destroySession(webContext);
if (!invalidated) {
LOGGER.error("The session has not been invalidated");
}
}
}
/** {@inheritDoc} */
@Override
public void renewSession(final CallContext ctx, final String oldSessionId) {
val optKey = cleanRecord(oldSessionId);
if (optKey.isPresent()) {
recordSession(ctx, optKey.get());
}
}
/** {@inheritDoc} */
@Override
public Optional<String> cleanRecord(final String sessionId) {
val key = (String) store.get(sessionId).orElse(null);
store.remove(sessionId);
LOGGER.debug("cleaning sessionId: {} -> key: {}", sessionId, key);
if (key != null) {
store.remove(key);
}
return Optional.ofNullable(key);
}
}
|
val webContext = ctx.webContext();
val sessionStore = ctx.sessionStore();
val optTrackableSession = store.get(key);
if (optTrackableSession.isPresent()) {
store.remove(key);
}
if (sessionStore == null) {
LOGGER.warn("No session store. Cannot destroy session");
return;
}
val optCurrentSessionId = sessionStore.getSessionId(ctx.webContext(), false);
if (optCurrentSessionId.isPresent()) {
val currentSessionId = optCurrentSessionId.get();
LOGGER.debug("current sessionId: {}", currentSessionId);
val keyForCurrentSession = (String) store.get(currentSessionId).orElse(null);
LOGGER.debug("key associated to the current session: {}", key);
store.remove(currentSessionId);
if (CommonHelper.areEquals(key, keyForCurrentSession)) {
destroy(webContext, sessionStore, ctx.profileManagerFactory(), "front");
return;
} else {
LOGGER.debug("Unknown/new web session: cannot perform front channel logout");
}
} else {
LOGGER.debug("No web session: cannot perform front channel logout");
}
LOGGER.debug("TrackableSession: {} for key: {}", optTrackableSession, key);
if (optTrackableSession.isEmpty()) {
LOGGER.debug("No trackable session: cannot perform back channel logout");
} else {
val optNewSessionStore = sessionStore
.buildFromTrackableSession(webContext, optTrackableSession.get());
if (optNewSessionStore.isPresent()) {
val newSessionStore = optNewSessionStore.get();
LOGGER.debug("newSesionStore: {}", newSessionStore);
val sessionId = newSessionStore.getSessionId(webContext, true).get();
LOGGER.debug("new sessionId: {}", sessionId);
store.remove(sessionId);
destroy(webContext, newSessionStore, ctx.profileManagerFactory(), "back");
return;
} else {
LOGGER.warn("Cannot build new session store from tracked session: cannot perform back channel logout");
}
}
| 932
| 557
| 1,489
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/matching/matcher/CacheControlMatcher.java
|
CacheControlMatcher
|
matches
|
class CacheControlMatcher implements Matcher {
/** {@inheritDoc} */
@Override
public boolean matches(final CallContext ctx) {<FILL_FUNCTION_BODY>}
}
|
val webContext = ctx.webContext();
val url = webContext.getFullRequestURL().toLowerCase();
if (!url.endsWith(".css")
&& !url.endsWith(".js")
&& !url.endsWith(".png")
&& !url.endsWith(".jpg")
&& !url.endsWith(".ico")
&& !url.endsWith(".jpeg")
&& !url.endsWith(".bmp")
&& !url.endsWith(".gif")) {
webContext.setResponseHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
webContext.setResponseHeader("Pragma", "no-cache");
webContext.setResponseHeader("Expires", "0");
}
return true;
| 49
| 195
| 244
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/matching/matcher/CorsMatcher.java
|
CorsMatcher
|
matches
|
class CorsMatcher implements Matcher {
private String allowOrigin;
private String exposeHeaders;
private int maxAge = -1;
private Boolean allowCredentials;
private Set<HttpConstants.HTTP_METHOD> allowMethods;
private String allowHeaders;
/** {@inheritDoc} */
@Override
public boolean matches(final CallContext ctx) {<FILL_FUNCTION_BODY>}
}
|
val webContext = ctx.webContext();
CommonHelper.assertNotBlank("allowOrigin", allowOrigin);
webContext.setResponseHeader(HttpConstants.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, allowOrigin);
if (CommonHelper.isNotBlank(exposeHeaders)) {
webContext.setResponseHeader(HttpConstants.ACCESS_CONTROL_EXPOSE_HEADERS_HEADER, exposeHeaders);
}
if (maxAge != -1) {
webContext.setResponseHeader(HttpConstants.ACCESS_CONTROL_MAX_AGE_HEADER, Pac4jConstants.EMPTY_STRING + maxAge);
}
if (allowCredentials != null && allowCredentials) {
webContext.setResponseHeader(HttpConstants.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER, allowCredentials.toString());
}
if (allowMethods != null) {
val methods = allowMethods.stream().map(Enum::toString).collect(Collectors.joining(", "));
webContext.setResponseHeader(HttpConstants.ACCESS_CONTROL_ALLOW_METHODS_HEADER, methods);
}
if (CommonHelper.isNotBlank(allowHeaders)) {
webContext.setResponseHeader(HttpConstants.ACCESS_CONTROL_ALLOW_HEADERS_HEADER, allowHeaders);
}
return true;
| 110
| 361
| 471
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/matching/matcher/HeaderMatcher.java
|
HeaderMatcher
|
matches
|
class HeaderMatcher implements Matcher {
private String headerName;
private String expectedValue;
protected Pattern pattern;
/**
* <p>Constructor for HeaderMatcher.</p>
*/
public HeaderMatcher() {}
/**
* <p>Constructor for HeaderMatcher.</p>
*
* @param headerName a {@link String} object
* @param expectedValue a {@link String} object
*/
public HeaderMatcher(final String headerName, final String expectedValue) {
setHeaderName(headerName);
setExpectedValue(expectedValue);
}
/** {@inheritDoc} */
@Override
public boolean matches(final CallContext ctx) {<FILL_FUNCTION_BODY>}
/**
* <p>Setter for the field <code>expectedValue</code>.</p>
*
* @param expectedValue a {@link String} object
*/
public void setExpectedValue(final String expectedValue) {
this.expectedValue = expectedValue;
if (expectedValue != null) {
pattern = Pattern.compile(expectedValue);
}
}
}
|
CommonHelper.assertNotBlank("headerName", headerName);
val headerValue = ctx.webContext().getRequestHeader(this.headerName);
val headerNull = expectedValue == null && headerValue.isEmpty();
val headerMatches = headerValue.isPresent() && pattern != null && pattern.matcher(headerValue.get()).matches();
return headerNull || headerMatches;
| 300
| 98
| 398
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/matching/matcher/HttpMethodMatcher.java
|
HttpMethodMatcher
|
matches
|
class HttpMethodMatcher implements Matcher {
private Set<HttpConstants.HTTP_METHOD> methods;
/**
* <p>Constructor for HttpMethodMatcher.</p>
*/
public HttpMethodMatcher() {}
/**
* <p>Constructor for HttpMethodMatcher.</p>
*
* @param methods a {@link HttpConstants.HTTP_METHOD} object
*/
public HttpMethodMatcher(final HttpConstants.HTTP_METHOD... methods) {
if (methods != null) {
this.methods = new HashSet<>(Arrays.asList(methods));
}
}
/** {@inheritDoc} */
@Override
public boolean matches(final CallContext ctx) {<FILL_FUNCTION_BODY>}
}
|
CommonHelper.assertNotNull("methods", methods);
val requestMethod = ctx.webContext().getRequestMethod();
for (val method : methods) {
if (method.name().equalsIgnoreCase(requestMethod)) {
return true;
}
}
return false;
| 195
| 73
| 268
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/matching/matcher/PathMatcher.java
|
PathMatcher
|
warnRegexp
|
class PathMatcher implements Matcher {
private final Set<String> includedPaths = new HashSet<>();
@Getter
private final Set<String> excludedPaths = new HashSet<>();
@Getter
private final Set<Pattern> excludedPatterns = new HashSet<>();
private static boolean warnedRegexp;
private static boolean warnedInclude;
/**
* <p>Constructor for PathMatcher.</p>
*/
public PathMatcher() {}
/**
* Any path exactly matching this string will be excluded. Use this method if you are excluding a specific path.
*
* @param path the path to be excluded
* @return this path matcher
*/
public PathMatcher excludePath(final String path) {
validatePath(path);
excludedPaths.add(path);
return this;
}
/**
* <p>excludePaths.</p>
*
* @param paths a {@link String} object
* @return a {@link PathMatcher} object
*/
public PathMatcher excludePaths(final String... paths) {
if (paths != null && paths.length > 0) {
for (val path : paths) {
excludePath(path);
}
}
return this;
}
/**
* <p>includePath.</p>
*
* @param path a {@link String} object
* @return a {@link PathMatcher} object
*/
public PathMatcher includePath(final String path) {
warnInclude();
validatePath(path);
includedPaths.add(path);
return this;
}
/**
* <p>includePaths.</p>
*
* @param paths a {@link String} object
* @return a {@link PathMatcher} object
*/
public PathMatcher includePaths(final String... paths) {
if (paths != null && paths.length > 0) {
for (val path : paths) {
includePath(path);
}
}
return this;
}
/**
* Convenience method for excluding all paths starting with a prefix e.g. "/foo" would exclude "/foo", "/foo/bar", etc.
*
* @param path the prefix for the paths to be excluded
* @return this path matcher
*/
public PathMatcher excludeBranch(final String path) {
warnRegexp();
validatePath(path);
excludedPatterns.add(Pattern.compile("^" + path + "(/.*)?$"));
return this;
}
/**
* Any path matching this regex will be excluded.
*
* @param regex the regular expression matching the paths to be excluded
* @return this path matcher
*/
public PathMatcher excludeRegex(final String regex) {
warnRegexp();
CommonHelper.assertNotBlank("regex", regex);
if (!regex.startsWith("^") || !regex.endsWith("$")) {
throw new TechnicalException("Your regular expression: '" + regex + "' must start with a ^ and end with a $ " +
"to define a full path matching");
}
excludedPatterns.add(Pattern.compile(regex));
return this;
}
/**
* <p>warnRegexp.</p>
*/
protected void warnRegexp() {<FILL_FUNCTION_BODY>}
/**
* <p>warnInclude.</p>
*/
protected void warnInclude() {
if (!warnedInclude) {
LOGGER.warn("Be careful when using the 'includePath' or 'includePaths' methods. "
+ "The security will only apply on these paths. It could not be secure enough.");
warnedInclude = true;
}
}
/** {@inheritDoc} */
@Override
public boolean matches(final CallContext ctx) {
return matches(ctx.webContext().getPath());
}
// Returns true if a path should be authenticated, false to skip authentication.
boolean matches(final String requestPath) {
LOGGER.debug("request path to match: {}", requestPath);
if (!includedPaths.isEmpty()) {
for (val path : includedPaths) {
// accepts any request path starting with the included path
if (requestPath != null && requestPath.startsWith(path)) {
return true;
}
}
return false;
}
// just exclude the exact matching request path
if (excludedPaths.contains(requestPath)) {
return false;
}
for (val pattern : excludedPatterns) {
if (pattern.matcher(requestPath).matches()) {
return false;
}
}
return true;
}
/**
* <p>Setter for the field <code>excludedPaths</code>.</p>
*
* @param paths a {@link java.util.Collection} object
*/
public void setExcludedPaths(Iterable<String> paths) {
excludedPaths.clear();
paths.forEach(this::excludePath);
}
/**
* <p>Setter for the field <code>excludedPatterns</code>.</p>
*
* @param regularExpressions a {@link java.util.Collection} object
*/
public void setExcludedPatterns(Iterable<String> regularExpressions) {
excludedPatterns.clear();
regularExpressions.forEach(this::excludeRegex);
}
/**
* <p>setExcludedPath.</p>
*
* @param path a {@link String} object
*/
public void setExcludedPath(final String path) {
excludedPaths.clear();
excludePath(path);
}
/**
* <p>setExcludedPattern.</p>
*
* @param regularExpression a {@link String} object
*/
public void setExcludedPattern(final String regularExpression) {
excludedPatterns.clear();
excludeRegex(regularExpression);
}
private static void validatePath(String path) {
CommonHelper.assertNotBlank("path", path);
if (!path.startsWith("/")) {
throw new TechnicalException("Excluded path must begin with a /");
}
}
}
|
if (!warnedRegexp) {
LOGGER.warn("Be careful when using the 'excludeBranch' or 'excludeRegex' methods. "
+ "They use regular expressions and their definitions may be error prone. You could exclude more URLs than expected.");
warnedRegexp = true;
}
| 1,626
| 80
| 1,706
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/matching/matcher/StrictTransportSecurityMatcher.java
|
StrictTransportSecurityMatcher
|
matches
|
class StrictTransportSecurityMatcher implements Matcher {
/**
* 6 months in seconds.
*/
private final static int DEFAULT_MAX_AGE = 15768000;
private int maxAge = DEFAULT_MAX_AGE;
/**
* <p>Constructor for StrictTransportSecurityMatcher.</p>
*/
public StrictTransportSecurityMatcher() {}
/**
* <p>Constructor for StrictTransportSecurityMatcher.</p>
*
* @param maxAge a int
*/
public StrictTransportSecurityMatcher(final int maxAge) {
this.maxAge = maxAge;
}
/** {@inheritDoc} */
@Override
public boolean matches(final CallContext ctx) {<FILL_FUNCTION_BODY>}
}
|
val webContext = ctx.webContext();
if (WebContextHelper.isHttpsOrSecure(webContext)) {
webContext.setResponseHeader("Strict-Transport-Security", "max-age=" + maxAge + " ; includeSubDomains");
}
return true;
| 211
| 76
| 287
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/matching/matcher/csrf/CsrfTokenGeneratorMatcher.java
|
CsrfTokenGeneratorMatcher
|
matches
|
class CsrfTokenGeneratorMatcher implements Matcher {
private CsrfTokenGenerator csrfTokenGenerator;
private String domain;
private String path = "/";
private Boolean httpOnly = true;
private Boolean secure = true;
private Integer maxAge;
private String sameSitePolicy;
private boolean addTokenAsAttribute = true;
private boolean addTokenAsHeader = false;
private boolean addTokenAsCookie = true;
/**
* <p>Constructor for CsrfTokenGeneratorMatcher.</p>
*
* @param csrfTokenGenerator a {@link CsrfTokenGenerator} object
*/
public CsrfTokenGeneratorMatcher(final CsrfTokenGenerator csrfTokenGenerator) {
this.csrfTokenGenerator = csrfTokenGenerator;
}
/** {@inheritDoc} */
@Override
public boolean matches(final CallContext ctx) {<FILL_FUNCTION_BODY>}
}
|
val webContext = ctx.webContext();
CommonHelper.assertNotNull("csrfTokenGenerator", csrfTokenGenerator);
if (addTokenAsAttribute || addTokenAsHeader || addTokenAsCookie) {
val token = csrfTokenGenerator.get(webContext, ctx.sessionStore());
if (addTokenAsAttribute) {
webContext.setRequestAttribute(Pac4jConstants.CSRF_TOKEN, token);
}
if (addTokenAsHeader) {
webContext.setResponseHeader(Pac4jConstants.CSRF_TOKEN, token);
}
if (addTokenAsCookie) {
val cookie = new Cookie(Pac4jConstants.CSRF_TOKEN, token);
if (CommonHelper.isNotBlank(domain)) {
cookie.setDomain(domain);
} else {
cookie.setDomain(webContext.getServerName());
}
if (CommonHelper.isNotBlank(path)) {
cookie.setPath(path);
}
if (httpOnly != null) {
cookie.setHttpOnly(httpOnly.booleanValue());
}
if (secure != null) {
cookie.setSecure(secure.booleanValue());
}
if (maxAge != null) {
cookie.setMaxAge(maxAge.intValue());
}
if (CommonHelper.isNotBlank(sameSitePolicy)) {
cookie.setSameSitePolicy(sameSitePolicy);
}
webContext.addResponseCookie(cookie);
}
}
return true;
| 247
| 403
| 650
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/matching/matcher/csrf/DefaultCsrfTokenGenerator.java
|
DefaultCsrfTokenGenerator
|
get
|
class DefaultCsrfTokenGenerator implements CsrfTokenGenerator {
// 4 hours
private int ttlInSeconds = 4*60*60;
private boolean rotateTokens = true;
/** {@inheritDoc} */
@Override
public String get(final WebContext context, final SessionStore sessionStore) {<FILL_FUNCTION_BODY>}
}
|
String token = null;
val optCurrentToken = sessionStore.get(context, Pac4jConstants.CSRF_TOKEN);
if (optCurrentToken.isPresent()) {
token = (String) optCurrentToken.get();
LOGGER.debug("previous CSRF token: {}", token);
sessionStore.set(context, Pac4jConstants.PREVIOUS_CSRF_TOKEN, token);
} else {
sessionStore.set(context, Pac4jConstants.PREVIOUS_CSRF_TOKEN, null);
}
if (optCurrentToken.isEmpty() || rotateTokens) {
token = CommonHelper.randomString(32);
LOGGER.debug("generated CSRF token: {} for current URL: {}", token, context.getFullRequestURL());
val expirationDate = new Date().getTime() + ttlInSeconds * 1000;
sessionStore.set(context, Pac4jConstants.CSRF_TOKEN, token);
sessionStore.set(context, Pac4jConstants.CSRF_TOKEN_EXPIRATION_DATE, expirationDate);
}
return token;
| 96
| 292
| 388
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/profile/Color.java
|
Color
|
toPaddedHexString
|
class Color implements Serializable {
@Serial
private static final long serialVersionUID = -28080878626869621L;
private int red;
private int green;
private int blue;
/**
* <p>Constructor for Color.</p>
*
* @param red a int
* @param green a int
* @param blue a int
*/
public Color(final int red, final int green, final int blue) {
if (red < 0 || red > 255 || green < 0 || green > 255 || blue < 0 || blue > 255)
throw new TechnicalException("Color's red, green or blue values must be between 0 and 255.");
this.red = red;
this.green = green;
this.blue = blue;
}
/**
* <p>Getter for the field <code>red</code>.</p>
*
* @return a int
*/
public int getRed() {
return this.red;
}
/**
* <p>Getter for the field <code>green</code>.</p>
*
* @return a int
*/
public int getGreen() {
return this.green;
}
/**
* <p>Getter for the field <code>blue</code>.</p>
*
* @return a int
*/
public int getBlue() {
return this.blue;
}
/**
* <p>Setter for the field <code>red</code>.</p>
*
* @param red a int
*/
public void setRed(final int red) {
this.red = red;
}
/**
* <p>Setter for the field <code>green</code>.</p>
*
* @param green a int
*/
public void setGreen(final int green) {
this.green = green;
}
/**
* <p>Setter for the field <code>blue</code>.</p>
*
* @param blue a int
*/
public void setBlue(final int blue) {
this.blue = blue;
}
/** {@inheritDoc} */
@Override
public String toString() {
return toPaddedHexString(this.red) + toPaddedHexString(this.green) + toPaddedHexString(this.blue);
}
private String toPaddedHexString(final int i) {<FILL_FUNCTION_BODY>}
}
|
// add "0" padding to single-digit hex values
return i < 16 ? "0" + Integer.toHexString(i).toUpperCase() : Integer.toHexString(i).toUpperCase();
| 680
| 59
| 739
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/profile/CommonProfile.java
|
CommonProfile
|
getAttributeAsDate
|
class CommonProfile extends BasicUserProfile {
@Serial
private static final long serialVersionUID = -1856159870249261877L;
/**
* <p>Constructor for CommonProfile.</p>
*/
public CommonProfile() {
this(true);
}
/**
* Create a profile with possibility to merge attributes with the same name and collection-type values
*
* @param canMergeAttributes if true - merge attributes with the same name and collection-type values, if false -
* overwrite them
* @since 3.1.0
*/
public CommonProfile(final boolean canMergeAttributes) {
super(canMergeAttributes);
}
/**
* Return the email of the user.
*
* @return the email of the user
*/
@JsonIgnore
public String getEmail() {
return getAttributeAsString(CommonProfileDefinition.EMAIL);
}
/**
* Return the first name of the user.
*
* @return the first name of the user
*/
@JsonIgnore
public String getFirstName() {
return getAttributeAsString(CommonProfileDefinition.FIRST_NAME);
}
/**
* Return the family name of the user.
*
* @return the family name of the user
*/
@JsonIgnore
public String getFamilyName() {
return getAttributeAsString(CommonProfileDefinition.FAMILY_NAME);
}
/**
* Return the displayed name of the user. It can be the username or the first and last names (separated by a space).
*
* @return the displayed name of the user
*/
@JsonIgnore
public String getDisplayName() {
return getAttributeAsString(CommonProfileDefinition.DISPLAY_NAME);
}
/**
* {@inheritDoc}
*
* Return the username of the user. It can be a login or a specific username.
*/
@JsonIgnore
@Override
public String getUsername() {
return getAttributeAsString(Pac4jConstants.USERNAME);
}
/**
* Return the gender of the user.
*
* @return the gender of the user
*/
@JsonIgnore
public Gender getGender() {
return getAttributeAsType(CommonProfileDefinition.GENDER, Gender.class, Gender.UNSPECIFIED);
}
/**
* Return the locale of the user.
*
* @return the locale of the user
*/
@JsonIgnore
public Locale getLocale() {
return getAttributeAsType(CommonProfileDefinition.LOCALE, Locale.class, null);
}
/**
* Return the url of the picture of the user.
*
* @return the url of the picture of the user.
*/
@JsonIgnore
public URI getPictureUrl() {
return getAttributeAsType(CommonProfileDefinition.PICTURE_URL, URI.class, null);
}
/**
* Return the url of the profile of the user.
*
* @return the url of the profile of the user.
*/
@JsonIgnore
public URI getProfileUrl() {
return getAttributeAsType(CommonProfileDefinition.PROFILE_URL, URI.class, null);
}
/**
* Return the location of the user.
*
* @return the location of the user
*/
@JsonIgnore
public String getLocation() {
return getAttributeAsString(CommonProfileDefinition.LOCATION);
}
@JsonIgnore
@Override
public boolean isExpired() {
return false;
}
/**
* <p>getAttributeAsString.</p>
*
* @param name a {@link String} object
* @return a {@link String} object
*/
protected String getAttributeAsString(final String name) {
val value = getAttribute(name);
if (value != null) {
return value.toString();
}
else {
return null;
}
}
/**
* <p>getAttributeAsType.</p>
*
* @param name a {@link String} object
* @param clazz a {@link Class} object
* @param defaultValue a T object
* @param <T> a T class
* @return a T object
*/
protected <T> T getAttributeAsType(final String name, Class<T> clazz, T defaultValue) {
val value = getAttribute(name);
if (value != null && clazz.isAssignableFrom(value.getClass())) {
return clazz.cast(value);
}
else {
return defaultValue;
}
}
/**
* <p>getAttributeAsDate.</p>
*
* @param name a {@link String} object
* @return a {@link Date} object
*/
protected Date getAttributeAsDate(final String name) {<FILL_FUNCTION_BODY>}
}
|
val value = getAttribute(name);
// it should be a Date, but in case it's a Long (Vertx issue with profiles serialized to JSON and restored)
if (value instanceof Long l) {
return new Date(l);
}
else if (value instanceof Double d) {
return new Date(d.longValue());
}
else {
return (Date) getAttribute(name);
}
| 1,287
| 107
| 1,394
|
<methods>public void <init>() ,public void <init>(boolean) ,public void addAttribute(java.lang.String, java.lang.Object) ,public void addAttributes(Map<java.lang.String,java.lang.Object>) ,public void addAuthenticationAttribute(java.lang.String, java.lang.Object) ,public void addAuthenticationAttributes(Map<java.lang.String,java.lang.Object>) ,public void addRole(java.lang.String) ,public void addRoles(Collection<java.lang.String>) ,public java.security.Principal asPrincipal() ,public void build(java.lang.Object, Map<java.lang.String,java.lang.Object>) ,public void build(java.lang.Object, Map<java.lang.String,java.lang.Object>, Map<java.lang.String,java.lang.Object>) ,public boolean containsAttribute(java.lang.String) ,public boolean containsAuthenticationAttribute(java.lang.String) ,public List<java.lang.String> extractAttributeValues(java.lang.String) ,public java.lang.Object getAttribute(java.lang.String) ,public T getAttribute(java.lang.String, Class<T>) ,public Map<java.lang.String,java.lang.Object> getAttributes() ,public java.lang.Object getAuthenticationAttribute(java.lang.String) ,public T getAuthenticationAttribute(java.lang.String, Class<T>) ,public Map<java.lang.String,java.lang.Object> getAuthenticationAttributes() ,public Set<java.lang.String> getRoles() ,public java.lang.String getTypedId() ,public java.lang.String getUsername() ,public boolean isExpired() ,public void readExternal(java.io.ObjectInput) throws java.io.IOException, java.lang.ClassNotFoundException,public void removeAttribute(java.lang.String) ,public void removeAuthenticationAttribute(java.lang.String) ,public void removeLoginData() ,public void setId(java.lang.String) ,public void setRoles(Set<java.lang.String>) ,public void writeExternal(java.io.ObjectOutput) throws java.io.IOException<variables>private Map<java.lang.String,java.lang.Object> attributes,private Map<java.lang.String,java.lang.Object> authenticationAttributes,private final non-sealed boolean canAttributesBeMerged,private java.lang.String clientName,private java.lang.String id,private boolean isRemembered,private java.lang.String linkedId,protected final transient org.slf4j.Logger logger,private Set<java.lang.String> roles,private static final long serialVersionUID
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/profile/ProfileHelper.java
|
ProfileHelper
|
buildUserProfileByClassCompleteName
|
class ProfileHelper {
private static List<String> profileClassPrefixes = List.of("org.pac4j.");
private ProfileHelper() {}
/**
* Indicate if the user identifier matches this kind of profile.
*
* @param id user identifier
* @param clazz profile class
* @return if the user identifier matches this kind of profile
*/
public static boolean isTypedIdOf(final String id, final Class<? extends UserProfile> clazz) {
return id != null && clazz != null && id.startsWith(clazz.getName() + Pac4jConstants.TYPED_ID_SEPARATOR);
}
/**
* Build a profile by its class name.
*
* @param completeName the class name
* @return the built user profile
*/
public static UserProfile buildUserProfileByClassCompleteName(final String completeName) {<FILL_FUNCTION_BODY>}
/**
* Flat the list of profiles into a single optional profile (skip any anonymous profile unless it's the only one).
*
* @param profiles the list of profiles
* @param <U> the kind of profile
* @return the (optional) profile
*/
public static <U extends UserProfile> Optional<U> flatIntoOneProfile(final Collection<U> profiles) {
val profile = profiles.stream().filter(p -> p != null && !(p instanceof AnonymousProfile)).findFirst();
if (profile.isPresent()) {
return profile;
} else {
return profiles.stream().filter(Objects::nonNull).findFirst();
}
}
/**
* Flat the map of profiles into a list of profiles.
*
* @param profiles the map of profiles
* @param <U> the kind of profile
* @return the list of profiles
*/
public static <U extends UserProfile> List<U> flatIntoAProfileList(final Map<String, U> profiles) {
return new ArrayList<>(profiles.values());
}
/**
* Sanitize into a string identifier.
*
* @param id the identifier object
* @return the sanitized identifier
*/
public static String sanitizeIdentifier(final Object id) {
if (id != null) {
var sId = id.toString();
if (sId.contains(Pac4jConstants.TYPED_ID_SEPARATOR)) {
val profileClass = substringBefore(sId, Pac4jConstants.TYPED_ID_SEPARATOR);
for (val profileClassPrefix : getProfileClassPrefixes()) {
if (profileClass.startsWith(profileClassPrefix)) {
return sId.substring(profileClass.length() + 1);
}
}
}
return sId;
}
return null;
}
/**
* <p>Getter for the field <code>profileClassPrefixes</code>.</p>
*
* @return a {@link List} object
*/
public static List<String> getProfileClassPrefixes() {
return profileClassPrefixes;
}
/**
* <p>Setter for the field <code>profileClassPrefixes</code>.</p>
*
* @param profileClassPrefixes a {@link List} object
*/
public static void setProfileClassPrefixes(final List<String> profileClassPrefixes) {
CommonHelper.assertNotNull("profileClassPrefixes", profileClassPrefixes);
ProfileHelper.profileClassPrefixes = profileClassPrefixes;
}
}
|
try {
val constructor = CommonHelper.getConstructor(completeName);
return (UserProfile) constructor.newInstance();
} catch (final ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException
| InstantiationException e) {
throw new TechnicalException(e);
}
| 897
| 78
| 975
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/profile/ProfileManager.java
|
ProfileManager
|
saveAll
|
class ProfileManager {
private final Authorizer IS_AUTHENTICATED_AUTHORIZER = new IsAuthenticatedAuthorizer();
protected final Logger logger = LoggerFactory.getLogger(getClass());
protected final WebContext context;
protected SessionStore sessionStore;
@Getter
@Setter
protected Config config;
/**
* <p>Constructor for ProfileManager.</p>
*
* @param context a {@link WebContext} object
* @param sessionStore a {@link SessionStore} object
*/
public ProfileManager(final WebContext context, final SessionStore sessionStore) {
CommonHelper.assertNotNull("context", context);
CommonHelper.assertNotNull("sessionStore", sessionStore);
this.context = context;
this.sessionStore = sessionStore;
}
/**
* Retrieve the first user profile if it exists, ignoring any {@link AnonymousProfile} if possible.
*
* @return the user profile
*/
public Optional<UserProfile> getProfile() {
val allProfiles = retrieveAll(true);
return ProfileHelper.flatIntoOneProfile(allProfiles.values());
}
/**
* <p>getProfile.</p>
*
* @param clazz a {@link Class} object
* @param <U> a U class
* @return a {@link Optional} object
*/
public <U extends UserProfile> Optional<U> getProfile(final Class<U> clazz) {
return (Optional<U>) getProfile();
}
/**
* Retrieve all user profiles.
*
* @return the user profiles
*/
public List<UserProfile> getProfiles() {
val profiles = retrieveAll(true);
return ProfileHelper.flatIntoAProfileList(profiles);
}
/**
* Retrieve the map of profiles from the session or the request.
*
* @param readFromSession if the user profiles must be read from session
* @return the map of profiles
*/
protected LinkedHashMap<String, UserProfile> retrieveAll(final boolean readFromSession) {
val profiles = new LinkedHashMap<String, UserProfile>();
this.context.getRequestAttribute(Pac4jConstants.USER_PROFILES)
.ifPresent(requestAttribute -> {
LOGGER.debug("Retrieved profiles (request): {}", requestAttribute);
profiles.putAll((Map<String, UserProfile>) requestAttribute);
});
if (readFromSession) {
this.sessionStore.get(this.context, Pac4jConstants.USER_PROFILES)
.ifPresent(sessionAttribute -> {
LOGGER.debug("Retrieved profiles (session): {}", sessionAttribute);
profiles.putAll((Map<String, UserProfile>) sessionAttribute);
});
}
removeOrRenewExpiredProfiles(profiles, readFromSession);
return profiles;
}
/**
* <p>removeOrRenewExpiredProfiles.</p>
*
* @param profiles a {@link LinkedHashMap} object
* @param readFromSession a boolean
*/
protected void removeOrRenewExpiredProfiles(final LinkedHashMap<String, UserProfile> profiles, final boolean readFromSession) {
var profilesUpdated = false;
for (val entry : profiles.entrySet()) {
val key = entry.getKey();
val profile = entry.getValue();
if (profile.isExpired()) {
LOGGER.debug("Expired profile: {}", profile);
profilesUpdated = true;
profiles.remove(key);
if (config != null && profile.getClientName() != null) {
val client = config.getClients().findClient(profile.getClientName());
if (client.isPresent()) {
try {
val newProfile = client.get().renewUserProfile(new CallContext(context, sessionStore), profile);
if (newProfile.isPresent()) {
LOGGER.debug("Renewed by profile: {}", newProfile);
profiles.put(key, newProfile.get());
}
} catch (final RuntimeException e) {
logger.error("Unable to renew the user profile for key: {}", key, e);
}
}
}
}
}
if (profilesUpdated) {
saveAll(profiles, readFromSession);
}
}
/**
* Remove the current user profile(s).
*/
public void removeProfiles() {
val sessionExists = sessionStore.getSessionId(context, false).isPresent();
if (sessionExists) {
LOGGER.debug("Removing profiles from session");
this.sessionStore.set(this.context, Pac4jConstants.USER_PROFILES, new LinkedHashMap<String, UserProfile>());
}
LOGGER.debug("Removing profiles from request");
this.context.setRequestAttribute(Pac4jConstants.USER_PROFILES, new LinkedHashMap<String, UserProfile>());
}
/**
* Save the given user profile (replace the current one if multi profiles are not supported, add it otherwise).
*
* @param saveInSession if the user profile must be saved in session
* @param profile a given user profile
* @param multiProfile whether multiple profiles are supported
*/
public void save(final boolean saveInSession, final UserProfile profile, final boolean multiProfile) {
final LinkedHashMap<String, UserProfile> profiles;
val clientName = retrieveClientName(profile);
if (multiProfile) {
profiles = retrieveAll(saveInSession);
profiles.remove(clientName);
} else {
profiles = new LinkedHashMap<>();
}
profiles.put(clientName, profile);
saveAll(profiles, saveInSession);
}
/**
* <p>retrieveClientName.</p>
*
* @param profile a {@link UserProfile} object
* @return a {@link String} object
*/
protected String retrieveClientName(final UserProfile profile) {
var clientName = profile.getClientName();
if (clientName == null) {
clientName = "DEFAULT";
}
return clientName;
}
/**
* <p>saveAll.</p>
*
* @param profiles a {@link LinkedHashMap} object
* @param saveInSession a boolean
*/
protected void saveAll(LinkedHashMap<String, UserProfile> profiles, final boolean saveInSession) {<FILL_FUNCTION_BODY>}
/**
* Tests if the current user is authenticated (meaning a user profile exists
* which is not an {@link AnonymousProfile}).
*
* @return whether the current user is authenticated
*/
public boolean isAuthenticated() {
try {
return IS_AUTHENTICATED_AUTHORIZER.isAuthorized(context, sessionStore, getProfiles());
} catch (final HttpAction e) {
throw new TechnicalException(e);
}
}
}
|
if (saveInSession) {
LOGGER.debug("Saving profiles (session): {}", profiles);
this.sessionStore.set(this.context, Pac4jConstants.USER_PROFILES, profiles);
}
LOGGER.debug("Saving profiles (request): {}", profiles);
this.context.setRequestAttribute(Pac4jConstants.USER_PROFILES, profiles);
| 1,773
| 99
| 1,872
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/profile/converter/AbstractAttributeConverter.java
|
AbstractAttributeConverter
|
convert
|
class AbstractAttributeConverter implements AttributeConverter {
private final Class<? extends Object> clazz;
/**
* <p>Constructor for AbstractAttributeConverter.</p>
*
* @param clazz a {@link Class} object
*/
protected AbstractAttributeConverter(final Class<? extends Object> clazz) {
this.clazz = clazz;
}
/** {@inheritDoc} */
@Override
public Object convert(final Object attribute) {<FILL_FUNCTION_BODY>}
/**
* <p>internalConvert.</p>
*
* @param attribute a {@link Object} object
* @return a {@link Object} object
*/
protected Object internalConvert(final Object attribute) {
return null;
}
/**
* <p>defaultValue.</p>
*
* @return a {@link Object} object
*/
protected Object defaultValue() {
return null;
}
/**
* <p>accept.</p>
*
* @param typeName a {@link String} object
* @return a {@link Boolean} object
*/
public Boolean accept(final String typeName){
return clazz.getSimpleName().equals(typeName);
}
}
|
Object t = null;
if (attribute != null) {
if (clazz.isAssignableFrom(attribute.getClass())) {
t = attribute;
} else if (attribute instanceof List l) {
if (l.size() > 0) {
val element = l.get(0);
if (clazz.isAssignableFrom(element.getClass())) {
t = element;
}else {
t = internalConvert(element);
}
}
} else {
t = internalConvert(attribute);
}
}
if (t != null) {
return t;
} else {
return defaultValue();
}
| 323
| 174
| 497
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/profile/converter/BooleanConverter.java
|
BooleanConverter
|
internalConvert
|
class BooleanConverter extends AbstractAttributeConverter {
/**
* <p>Constructor for BooleanConverter.</p>
*/
public BooleanConverter() {
super(Boolean.class);
}
/** {@inheritDoc} */
@Override
protected Boolean internalConvert(final Object attribute) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
protected Boolean defaultValue() {
return Boolean.FALSE;
}
}
|
if (attribute instanceof String) {
return "1".equals(attribute) || "true".equals(attribute);
} else if (attribute instanceof Number) {
return Integer.valueOf(1).equals(attribute);
}
return null;
| 119
| 63
| 182
|
<methods>public java.lang.Boolean accept(java.lang.String) ,public java.lang.Object convert(java.lang.Object) <variables>private final non-sealed Class<? extends java.lang.Object> clazz
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/profile/converter/ColorConverter.java
|
ColorConverter
|
internalConvert
|
class ColorConverter extends AbstractAttributeConverter {
/**
* <p>Constructor for ColorConverter.</p>
*/
public ColorConverter() {
super(Color.class);
}
/** {@inheritDoc} */
@Override
protected Color internalConvert(final Object attribute) {<FILL_FUNCTION_BODY>}
}
|
if (attribute instanceof String s && s.length() == 6) {
try {
var hex = s.substring(0, 2);
val r = Integer.parseInt(hex, 16);
hex = s.substring(2, 4);
val g = Integer.parseInt(hex, 16);
hex = s.substring(4, 6);
val b = Integer.parseInt(hex, 16);
return new Color(r, g, b);
} catch (final NumberFormatException e) {
LOGGER.error("Cannot convert " + s + " into color", e);
}
}
return null;
| 88
| 169
| 257
|
<methods>public java.lang.Boolean accept(java.lang.String) ,public java.lang.Object convert(java.lang.Object) <variables>private final non-sealed Class<? extends java.lang.Object> clazz
|
pac4j_pac4j
|
pac4j/pac4j-core/src/main/java/org/pac4j/core/profile/converter/DateConverter.java
|
DateConverter
|
internalConvert
|
class DateConverter extends AbstractAttributeConverter {
protected String format;
protected Locale locale;
/**
* <p>Constructor for DateConverter.</p>
*/
public DateConverter() {
this(DateTimeFormatter.ISO_LOCAL_DATE_TIME.toString());
}
/**
* <p>Constructor for DateConverter.</p>
*
* @param format a {@link String} object
*/
public DateConverter(final String format) {
super(Date.class);
this.format = format;
}
/**
* <p>Constructor for DateConverter.</p>
*
* @param format a {@link String} object
* @param locale a {@link Locale} object
*/
public DateConverter(final String format, final Locale locale) {
this(format);
this.locale = locale;
}
/** {@inheritDoc} */
@Override
protected Date internalConvert(final Object attribute) {<FILL_FUNCTION_BODY>}
}
|
if (attribute instanceof String s) {
SimpleDateFormat simpleDateFormat;
if (this.locale == null) {
simpleDateFormat = new SimpleDateFormat(this.format);
} else {
simpleDateFormat = new SimpleDateFormat(this.format, this.locale);
}
try {
return simpleDateFormat.parse(s);
} catch (final ParseException e) {
LOGGER.error("parse exception on {} with format: {} and locale: {}", s, this.format, this.locale, e);
}
}
return null;
| 264
| 145
| 409
|
<methods>public java.lang.Boolean accept(java.lang.String) ,public java.lang.Object convert(java.lang.Object) <variables>private final non-sealed Class<? extends java.lang.Object> clazz
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.