repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
struppigel/PortexAnalyzerGUI
https://github.com/struppigel/PortexAnalyzerGUI/blob/88091e58891354ddefd35db0d79bc3e0c8e3e57a/src/main/java/io/github/struppigel/gui/pedetails/signatures/YaraRuleMatch.java
src/main/java/io/github/struppigel/gui/pedetails/signatures/YaraRuleMatch.java
/** * ***************************************************************************** * Copyright 2022 Karsten Hahn * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a> * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **************************************************************************** */ package io.github.struppigel.gui.pedetails.signatures; import java.util.List; import java.util.stream.Collectors; public class YaraRuleMatch implements RuleMatch { final String ruleName; final List<PatternMatch> patterns; final List<String> tags; public YaraRuleMatch(String ruleName, List<PatternMatch> patterns, List<String> tags) { this.ruleName = ruleName; this.patterns = patterns; this.tags = tags; } // {"Source", "Match name", "Scan mode"}; public Object[] toSummaryRow() { Object[] row = {"Yara", ruleName, "Full file"}; return row; } public List<Object[]> toPatternRows() { return patterns.stream().map(p -> p.toPatternRow(ruleName)).collect(Collectors.toList()); } }
java
Apache-2.0
88091e58891354ddefd35db0d79bc3e0c8e3e57a
2026-01-05T02:37:12.650809Z
false
struppigel/PortexAnalyzerGUI
https://github.com/struppigel/PortexAnalyzerGUI/blob/88091e58891354ddefd35db0d79bc3e0c8e3e57a/src/main/java/io/github/struppigel/gui/pedetails/signatures/PatternMatch.java
src/main/java/io/github/struppigel/gui/pedetails/signatures/PatternMatch.java
/** * ***************************************************************************** * Copyright 2022 Karsten Hahn * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a> * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **************************************************************************** */ package io.github.struppigel.gui.pedetails.signatures; public class PatternMatch { final long offset; final String patternContent; String patternName; String location = "NaN"; public PatternMatch(long offset, String patternName, String patternContent) { this.offset = offset; this.patternName = patternName; this.patternContent = patternContent; } // {"Rule name" , "Pattern name", "Pattern content", "Offset", "Location"}; // TODO location cannot be implemented here because it needs to parse the whole PE again and this is only a getter public Object[] toPatternRow(String rulename) { Object[] row = {rulename, patternName, patternContent, offset, location}; return row; } }
java
Apache-2.0
88091e58891354ddefd35db0d79bc3e0c8e3e57a
2026-01-05T02:37:12.650809Z
false
struppigel/PortexAnalyzerGUI
https://github.com/struppigel/PortexAnalyzerGUI/blob/88091e58891354ddefd35db0d79bc3e0c8e3e57a/src/main/java/io/github/struppigel/gui/pedetails/signatures/SignaturesPanel.java
src/main/java/io/github/struppigel/gui/pedetails/signatures/SignaturesPanel.java
/** * ***************************************************************************** * Copyright 2022 Karsten Hahn * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a> * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **************************************************************************** */ package io.github.struppigel.gui.pedetails.signatures; import io.github.struppigel.gui.FullPEData; import io.github.struppigel.gui.PEFieldsTable; import io.github.struppigel.gui.pedetails.FileContentPreviewPanel; import io.github.struppigel.gui.utils.PortexSwingUtils; import io.github.struppigel.gui.utils.WorkerKiller; import io.github.struppigel.gui.utils.WriteSettingsWorker; import io.github.struppigel.settings.PortexSettings; import io.github.struppigel.settings.PortexSettingsKey; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.swing.*; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableRowSorter; import java.awt.*; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Vector; public class SignaturesPanel extends JPanel { private static final Logger LOGGER = LogManager.getLogger(); private final JProgressBar scanRunningBar = new JProgressBar(); private final PortexSettings settings; private final FileContentPreviewPanel previewPanel; private FullPEData pedata; private String rulePath; // TODO set a default path private String yaraPath; // e.g. Yara|PEiD, XORedPE, Full file|EP private final String[] summaryHeaders = {"Source", "Match name", "Scan mode"}; //e.g. XORedPE, "This program", "0xcafebabe", "Resource" private final String[] patternHeaders = {"Match name", "Pattern name", "Pattern content", "Offset"}; //, "Location"}; private boolean hexEnabled = true; private boolean ignoreYaraScan = true; private JTextField yaraPathTextField = new JTextField(30); private JTextField rulePathTextField = new JTextField(30); private List<YaraRuleMatch> yaraResults = null; // TODO put this here in result table! private List<PEidRuleMatch> peidResults = null; public SignaturesPanel(PortexSettings settings, FileContentPreviewPanel previewPanel) { this.settings = settings; this.previewPanel = previewPanel; applyLoadedSettings(); } private void applyLoadedSettings() { if(settings.containsKey(PortexSettingsKey.YARA_PATH)) { yaraPath = settings.get(PortexSettingsKey.YARA_PATH); yaraPathTextField.setText(yaraPath); } if(settings.containsKey(PortexSettingsKey.YARA_SIGNATURE_PATH)) { rulePath = settings.get(PortexSettingsKey.YARA_SIGNATURE_PATH); rulePathTextField.setText(rulePath); } } private void initProgressBar() { this.removeAll(); this.add(scanRunningBar); this.setLayout(new FlowLayout()); scanRunningBar.setIndeterminate(true); scanRunningBar.setVisible(true); this.repaint(); } private void buildTables() { this.removeAll(); //remove progress bar PEFieldsTable summaryTable = new PEFieldsTable(hexEnabled); PEFieldsTable patternTable = new PEFieldsTable(hexEnabled); patternTable.setPreviewOffsetColumn(3, previewPanel); DefaultTableModel sumModel = new PEFieldsTable.PETableModel(); sumModel.setColumnIdentifiers(summaryHeaders); DefaultTableModel patModel = new PEFieldsTable.PETableModel(); patModel.setColumnIdentifiers(patternHeaders); summaryTable.setModel(sumModel); patternTable.setModel(patModel); initListener(summaryTable, patternTable); fillTableModelsWithData(sumModel, patModel); JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, new JScrollPane(summaryTable), new JScrollPane(patternTable)); splitPane.setDividerLocation(200); this.setLayout(new BorderLayout()); this.add(splitPane, BorderLayout.CENTER); // set up buttons JPanel buttonPanel = new JPanel(); JButton rescan = new JButton("Rescan"); JButton pathSettings = new JButton("Settings"); buttonPanel.add(rescan); buttonPanel.add(pathSettings); pathSettings.addActionListener(e -> requestPaths()); rescan.addActionListener(e -> scan(false)); this.add(buttonPanel, BorderLayout.SOUTH); revalidate(); repaint(); } private void fillTableModelsWithData(DefaultTableModel sumModel, DefaultTableModel patModel) { List<RuleMatch> allResults = new ArrayList<>(); if(yaraResults != null) allResults.addAll(yaraResults); if(peidResults != null) allResults.addAll(peidResults); if(allResults.isEmpty()) { allResults.add(new EmptyRuleMatch()); } for (RuleMatch match : allResults) { sumModel.addRow(match.toSummaryRow()); for (Object[] row : match.toPatternRows()) { patModel.addRow(row); } } } void requestPaths() { this.removeAll(); JPanel tablePanel = new JPanel(); tablePanel.setLayout(new GridLayout(0, 1)); JButton yaraPathButton = new JButton("..."); JButton rulePathButton = new JButton("..."); JPanel demand = new JPanel(); demand.add(new JLabel("Add your yara and signature paths for signature scanning")); tablePanel.add(demand); JPanel firstRow = new JPanel(); firstRow.setLayout(new FlowLayout()); firstRow.add(new JLabel("Yara path:")); firstRow.add(yaraPathTextField); firstRow.add(yaraPathButton); tablePanel.add(firstRow); JPanel secondRow = new JPanel(); secondRow.setLayout(new FlowLayout()); secondRow.add(new JLabel("Signature path:")); secondRow.add(rulePathTextField); secondRow.add(rulePathButton); tablePanel.add(secondRow); JButton scanButton = new JButton("Scan"); JPanel thirdRow = new JPanel(); thirdRow.add(scanButton); tablePanel.add(thirdRow); setButtonListenersForRequestPath(scanButton, yaraPathButton, rulePathButton); this.setLayout(new BorderLayout()); this.add(tablePanel, BorderLayout.NORTH); this.add(Box.createVerticalGlue(), BorderLayout.CENTER); revalidate(); repaint(); } private void setButtonListenersForRequestPath(JButton scanButton, JButton yaraPathButton, JButton rulePathButton) { scanButton.addActionListener(e -> { // this button is used in settings dialog and acts also as save button yaraPath = yaraPathTextField.getText(); rulePath = rulePathTextField.getText(); writeSettings(); scan(true); }); yaraPathButton.addActionListener(e -> { String result = PortexSwingUtils.getOpenFileNameFromUser(this); if(result != null) { yaraPath = result; yaraPathTextField.setText(yaraPath); } }); rulePathButton.addActionListener(e -> { String result = PortexSwingUtils.getOpenFileNameFromUser(this); if(result != null) { rulePath = result; rulePathTextField.setText(rulePath); } }); } private void writeSettings() { if (yaraPath != null && rulePath != null && new File(yaraPath).exists() && new File(rulePath).exists()) { settings.put(PortexSettingsKey.YARA_PATH, yaraPath); settings.put(PortexSettingsKey.YARA_SIGNATURE_PATH, rulePath); new WriteSettingsWorker(settings).execute(); } } private void initListener(JTable summaryTable, JTable patternTable) { ListSelectionModel model = summaryTable.getSelectionModel(); model.addListSelectionListener(e -> { String rule = getRuleNameForSelectedRow(summaryTable); LOGGER.info(rule + " selected"); // filters exact matches with rule name at column 0 RowFilter<PEFieldsTable.PETableModel, Object> rf = new RowFilter() { @Override public boolean include(Entry entry) { if (rule == null || entry == null) return true; return rule.equals(entry.getStringValue(0)); } }; ((TableRowSorter) patternTable.getRowSorter()).setRowFilter(rf); }); } private String getRuleNameForSelectedRow(JTable table) { final int RULE_NAME_COL = 1; DefaultTableModel model = (DefaultTableModel) table.getModel(); int row = getSelectedRow(table); if (row == -1) return null; Vector vRow = (Vector) model.getDataVector().elementAt(row); Object rule = vRow.elementAt(RULE_NAME_COL); return rule.toString(); } /** * Return a vector of the data in the currently selected row. Returns null if no row selected * * @param table * @return vector of the data in the currently selected row or null if nothing selected */ private int getSelectedRow(JTable table) { int rowIndex = table.getSelectedRow(); if (rowIndex >= 0) { return table.convertRowIndexToModel(rowIndex); } return -1; } private void scan(boolean warnUser) { if (yaraPath != null && rulePath != null && new File(yaraPath).exists() && new File(rulePath).exists()) { initProgressBar(); this.ignoreYaraScan = false; YaraScanner yaraScanner = new YaraScanner(this, pedata, yaraPath, rulePath, settings); PEidScanner peidScanner = new PEidScanner(this, pedata); yaraScanner.execute(); peidScanner.execute(); WorkerKiller.getInstance().addWorker(yaraScanner); WorkerKiller.getInstance().addWorker(peidScanner); } else { if(warnUser) { String message = "Cannot scan"; if(yaraPath == null) { message += ", because no yara path set"; } else if(rulePath == null) { message += ", because no rule path set"; } else if(!new File(yaraPath).exists()) { message += ", because yara path is not an existing file: " + yaraPath; } else if(!new File(rulePath).exists()) { message += ", because rule path is not an existing file: " + rulePath; } else { message += ". The reason is unknown :("; } JOptionPane.showMessageDialog(this, message, "Cannot scan with yara", JOptionPane.WARNING_MESSAGE); } initProgressBar(); this.ignoreYaraScan = true; PEidScanner peidScanner = new PEidScanner(this, pedata); peidScanner.execute(); WorkerKiller.getInstance().addWorker(peidScanner); } } public void setPeData(FullPEData data) { this.pedata = data; scan(false); } public void setHexEnabled(boolean hexEnabled) { this.hexEnabled = hexEnabled; if(pedata == null){return;} buildTables(); // new renderer settings, refresh the panel } public void buildPEiDTables(List<PEidRuleMatch> signatureMatches) { this.peidResults = signatureMatches; if(yaraResults != null || ignoreYaraScan) { buildTables(); } } public void buildYaraTables(List<YaraRuleMatch> scanResults) { this.yaraResults = scanResults; if(peidResults != null) { buildTables(); } } }
java
Apache-2.0
88091e58891354ddefd35db0d79bc3e0c8e3e57a
2026-01-05T02:37:12.650809Z
false
struppigel/PortexAnalyzerGUI
https://github.com/struppigel/PortexAnalyzerGUI/blob/88091e58891354ddefd35db0d79bc3e0c8e3e57a/src/main/java/io/github/struppigel/gui/utils/TableContent.java
src/main/java/io/github/struppigel/gui/utils/TableContent.java
/** * ***************************************************************************** * Copyright 2023 Karsten Hahn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a> * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **************************************************************************** */ package io.github.struppigel.gui.utils; import io.github.struppigel.parser.StandardField; import java.util.ArrayList; import java.util.List; /** * Table entries and description. Currently used to hold the data for one tab in the TabbedPanel */ public class TableContent extends ArrayList<StandardField> { private String title; private String description; public TableContent(List<StandardField> list, String title) { this(list, title, ""); } public TableContent(List<StandardField> list, String title, String description) { super(list); this.title = title; this.description = description; } public String getTitle() { return title; } public String getDescription() { return description; } }
java
Apache-2.0
88091e58891354ddefd35db0d79bc3e0c8e3e57a
2026-01-05T02:37:12.650809Z
false
struppigel/PortexAnalyzerGUI
https://github.com/struppigel/PortexAnalyzerGUI/blob/88091e58891354ddefd35db0d79bc3e0c8e3e57a/src/main/java/io/github/struppigel/gui/utils/WriteSettingsWorker.java
src/main/java/io/github/struppigel/gui/utils/WriteSettingsWorker.java
/** * ***************************************************************************** * Copyright 2022 Karsten Hahn * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a> * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **************************************************************************** */ package io.github.struppigel.gui.utils; import io.github.struppigel.settings.PortexSettings; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.swing.*; import java.io.IOException; public class WriteSettingsWorker extends SwingWorker<Boolean, Void> { private static final Logger LOGGER = LogManager.getLogger(); private final PortexSettings settings; public WriteSettingsWorker(PortexSettings settings) { this.settings = settings; } @Override protected Boolean doInBackground() { try { settings.writeSettings(); return true; } catch (IOException e) { e.printStackTrace(); LOGGER.error(e); } return false; } }
java
Apache-2.0
88091e58891354ddefd35db0d79bc3e0c8e3e57a
2026-01-05T02:37:12.650809Z
false
struppigel/PortexAnalyzerGUI
https://github.com/struppigel/PortexAnalyzerGUI/blob/88091e58891354ddefd35db0d79bc3e0c8e3e57a/src/main/java/io/github/struppigel/gui/utils/PELoadWorker.java
src/main/java/io/github/struppigel/gui/utils/PELoadWorker.java
/** * ***************************************************************************** * Copyright 2022 Karsten Hahn * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a> * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **************************************************************************** */ package io.github.struppigel.gui.utils; import io.github.struppigel.parser.*; import io.github.struppigel.parser.sections.SectionHeader; import io.github.struppigel.parser.sections.SectionLoader; import io.github.struppigel.parser.sections.SectionTable; import io.github.struppigel.parser.sections.clr.*; import io.github.struppigel.parser.sections.debug.*; import io.github.struppigel.parser.sections.edata.ExportEntry; import io.github.struppigel.parser.sections.edata.ExportNameEntry; import io.github.struppigel.parser.sections.idata.*; import io.github.struppigel.parser.sections.rsrc.IDOrName; import io.github.struppigel.parser.sections.rsrc.Level; import io.github.struppigel.parser.sections.rsrc.Resource; import io.github.struppigel.parser.sections.rsrc.version.VersionInfo; import io.github.struppigel.tools.*; import io.github.struppigel.tools.anomalies.Anomaly; import io.github.struppigel.tools.anomalies.PEAnomalyScanner; import io.github.struppigel.tools.sigscanner.FileTypeScanner; import io.github.struppigel.tools.sigscanner.MatchedSignature; import io.github.struppigel.gui.FullPEData; import io.github.struppigel.gui.MainFrame; import com.google.common.base.Optional; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.swing.*; import java.io.File; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Loads and computes all the data related to PE files, so that this code does not run in the event dispatch thread. * Everything that is too complicated here must be improved in the library PortEx. */ public class PELoadWorker extends SwingWorker<FullPEData, String> { private static final Logger LOGGER = LogManager.getLogger(); private final String NL = System.getProperty("line.separator"); private final File file; private final MainFrame frame; private final JLabel progressText; public PELoadWorker(File file, MainFrame frame, JLabel progressText) { this.file = file; this.frame = frame; this.progressText = progressText; } @Override protected FullPEData doInBackground() throws Exception { setProgress(0); publish("Loading Headers..."); PEData data = PELoader.loadPE(file); java.util.Optional<CLRSection> maybeCLR = loadCLRSection(data).transform(java.util.Optional::of).or(java.util.Optional.empty()); List<StandardField> dotnetMetaDataRootEntries = createDotNetMetadataRootEntries(maybeCLR); List<Object[]> dotNetStreamHeaders = createDotNetStreamHeaders(maybeCLR); List<StandardField> optimizedStreamEntries = createOptimizedStreamEntries(maybeCLR); Map<String, List<List<Object>>> clrTables = data.loadCLRTables(); Map<String, List<String>> clrTableHeaders = data.loadCLRTableHeaders(); setProgress(10); publish("Calculating Hashes..."); ReportCreator r = ReportCreator.newInstance(data.getFile()); String hashesReport = createHashesReport(data); List<Object[]> hashesForSections = createHashTableEntries(data); setProgress(20); publish("Calculating Entropies..."); double[] sectionEntropies = calculateSectionEntropies(data); setProgress(30); publish("Extracting Imports..."); List<ImportDLL> importDLLs = data.loadImports(); List<ImportDLL> delayDLLs = data.loadDelayLoadImports(); List<Object[]> impEntries = createImportTableEntries(importDLLs); List<Object[]> delayLoadEntries = createImportTableEntries(delayDLLs); List<Object[]> boundImportEntries = createBoundImportEntries(data); setProgress(40); publish("Scanning for signatures..."); String rehintsReport = r.reversingHintsReport(); setProgress(50); publish("Loading Resources..."); List<Object[]> resourceTableEntries = createResourceTableEntries(data); List<String> manifests = data.loadManifests(); List<Object[]> vsInfoTable = createVersionInfoEntries(data); List<Object[]> stringTableEntries = createStringTableEntries(data); setProgress(60); publish("Loading Exports..."); List<ExportEntry> exports = data.loadExports(); List<Object[]> exportEntries = createExportTableEntries(data); setProgress(70); publish("Loading Debug Info..."); List<TableContent> debugTableEntries = getDebugTableEntries(data); data.loadExtendedDllCharacteristics(); // preload it so it can be accessed next time setProgress(80); publish("Scanning for Anomalies..."); List<Object[]> anomaliesTable = createAnomalyTableEntries(data); setProgress(90); publish("Scanning Overlay..."); Overlay overlay = new Overlay(data); double overlayEntropy = ShannonEntropy.entropy(data.getFile(), overlay.getOffset(), overlay.getSize()); List<String> overlaySignatures = data.getOverlaySignatures().stream().map(MatchedSignature::toString).collect(Collectors.toList()); setProgress(100); publish("Done!"); return new FullPEData(data, overlay, overlayEntropy, overlaySignatures, sectionEntropies, importDLLs, impEntries, delayLoadEntries, boundImportEntries, resourceTableEntries, data.loadResources(), manifests, exportEntries, exports, hashesReport, hashesForSections, anomaliesTable, debugTableEntries, vsInfoTable, rehintsReport, stringTableEntries, dotnetMetaDataRootEntries, maybeCLR, dotNetStreamHeaders, optimizedStreamEntries, clrTables, clrTableHeaders); } private Object[] createBoundImportEntry(BoundImportDescriptor bi) { List<Object> line = new ArrayList<>(); line.add(bi.getName()); line.add(bi.get(BoundImportDescriptorKey.OFFSET_MODULE_NAME)); line.add(bi.get(BoundImportDescriptorKey.TIME_DATE_STAMP)); line.add(bi.get(BoundImportDescriptorKey.NR_OF_MODULE_FORWARDER_REFS)); line.add(bi.rawOffset()); return line.toArray(); } private List<Object[]> createBoundImportEntries(PEData data) throws IOException { Optional<BoundImportSection> section = new SectionLoader(data).maybeLoadBoundImportSection(); if(section.isPresent()) { BoundImportSection bsec = section.get(); return bsec.getEntries().stream() .map(this::createBoundImportEntry) .collect(Collectors.toList()); } return new ArrayList<>(); } private Optional<CLRSection> loadCLRSection(PEData data) { SectionLoader loader = new SectionLoader(data); try { Optional<CLRSection> maybeClr = loader.maybeLoadCLRSection(); return maybeClr; } catch(IOException e){ LOGGER.error(e); e.printStackTrace(); } return Optional.absent(); } private List<StandardField> createOptimizedStreamEntries(java.util.Optional<CLRSection> clr) { if(clr.isPresent() && !clr.get().isEmpty()) { MetadataRoot root = clr.get().metadataRoot(); if(root.maybeGetOptimizedStream().isPresent()){ OptimizedStream optStream = root.maybeGetOptimizedStream().get(); return optStream.getEntriesList(); } } return new ArrayList<>(); } private List<Object[]> createDotNetStreamHeaders(java.util.Optional<CLRSection> clr) { if(clr.isPresent() && !clr.get().isEmpty()) { MetadataRoot root = clr.get().metadataRoot(); List<StreamHeader> headers = root.getStreamHeaders(); return headers.stream() .map(h -> new Object[]{ h.name(), h.size(), h.offset(), root.getBSJBOffset() + h.offset() }) .collect(Collectors.toList()); } return new ArrayList<>(); } private List<StandardField> createDotNetMetadataRootEntries(java.util.Optional<CLRSection> clr) { if(clr.isPresent() && !clr.get().isEmpty()) { MetadataRoot root = clr.get().metadataRoot(); Map<MetadataRootKey, StandardField> entriesMap = root.getMetaDataEntries(); return entriesMap.values().stream().collect(Collectors.toList()); } return new ArrayList<>(); } private List<Object[]> createStringTableEntries(PEData data) { Map<Long, String> strTable = data.loadStringTable(); return strTable.entrySet().stream() .map(e -> new Object[]{e.getKey(), e.getValue()}) .collect(Collectors.toList()); } private List<Object[]> createVersionInfoEntries(PEData data) { return data.loadResources().stream() .filter(r -> r.getType().equals("RT_VERSION")) .flatMap( r -> VersionInfo.apply(r, data.getFile()).getVersionStrings().entrySet() .stream() .map(e -> new Object[]{e.getKey(), e.getValue()}) ) .collect(Collectors.toList()); } private List<Object[]> createAnomalyTableEntries(PEData data) { List<Anomaly> anomalies = PEAnomalyScanner.newInstance(data).getAnomalies(); return anomalies.stream() .map(a -> new Object[]{a.description(), a.getType(), a.subtype(), a.key()}) .collect(Collectors.toList()); } private String createHashesReport(PEData data) { String text = "Full File Hashes" + NL + NL; try { MessageDigest sha256 = MessageDigest.getInstance("SHA-256"); MessageDigest md5 = MessageDigest.getInstance("MD5"); Hasher hasher = new Hasher(data); text += "MD5: " + hash(hasher.fileHash(md5)) + NL; text += "SHA256: " + hash(hasher.fileHash(sha256)) + NL; text += "ImpHash: " + ImpHash.createString(data.getFile()) + NL; java.util.Optional<byte[]> maybeRich = hasher.maybeRichHash(); if (maybeRich.isPresent()) { text += "Rich: " + hash(maybeRich.get()) + NL; java.util.Optional<byte[]> maybeRichPV = hasher.maybeRichPVHash(); if (maybeRichPV.isPresent()) { text += "RichPV: " + hash(maybeRichPV.get()) + NL; } } } catch (NoSuchAlgorithmException | IOException e) { throw new RuntimeException(e); } return text; } private List<Object[]> createHashTableEntries(PEData data) { List<Object[]> entries = new ArrayList<>(); SectionTable sectionTable = data.getSectionTable(); try { MessageDigest sha256 = MessageDigest.getInstance("SHA-256"); MessageDigest md5 = MessageDigest.getInstance("MD5"); Hasher hasher = new Hasher(data); for (SectionHeader s : sectionTable.getSectionHeaders()) { String secName = s.getNumber() + ". " + s.getName(); String md5Str = hash(hasher.sectionHash(s.getNumber(), md5)); String sha256Str = hash(hasher.sectionHash(s.getNumber(), sha256)); md5Str = md5Str.equals("") ? "empty section" : md5Str; sha256Str = sha256Str.equals("") ? "empty section" : sha256Str; String[] md5Entry = {secName, "MD5", md5Str}; String[] sha256Entry = {secName, "SHA256", sha256Str}; entries.add(md5Entry); entries.add(sha256Entry); } } catch (NoSuchAlgorithmException | IOException e) { throw new RuntimeException(e); } return entries; } private String hash(byte[] array) { return ByteArrayUtil.byteToHex(array, ""); } private String getCodeViewInfo(DebugDirectoryEntry d) { String report = ""; CodeviewInfo c = d.getCodeView(); report += "Codeview" + NL + NL; report += "Path: " + c.filePath() + NL; report += "Age: " + c.age() + NL; report += "GUID: " + CodeviewInfo.guidToString(c.guid()) + NL; return report; } private String getDebugInfo(DebugDirectoryEntry d, Boolean isRepro) { String time = isRepro ? "invalid - reproducibility build" : String.valueOf(d.getTimeDateStamp()); String report = "Time date stamp: " + time + NL; report += "Type: " + d.getTypeDescription() + NL + NL; return report; } private List<TableContent> getDebugTableEntries(PEData pedata) { List<TableContent> tables = new ArrayList<TableContent>(); try { Optional<DebugSection> sec = new SectionLoader(pedata).maybeLoadDebugSection(); if (sec.isPresent()) { DebugSection debugSec = sec.get(); List<DebugDirectoryEntry> debugList = debugSec.getEntries(); for(DebugDirectoryEntry d : debugList) { Map<DebugDirectoryKey, StandardField> dirTable = d.getDirectoryTable(); List<StandardField> vals = dirTable.values().stream().collect(Collectors.toList()); String title = d.getDebugType().toString(); String debugInfo = getDebugInfo(d, pedata.isReproBuild()); if(d.getDebugType() == DebugType.CODEVIEW) { try{ debugInfo += getCodeViewInfo(d); } catch (IllegalStateException ise) { debugInfo += "Invalid codeview structure!"; LOGGER.warn(ise.getMessage()); } } if(d.getDebugType() == DebugType.REPRO) { debugInfo += d.getRepro().getInfo(); } if(d.getDebugType() == DebugType.EX_DLLCHARACTERISTICS) { debugInfo += d.getExtendedDLLCharacteristics().getInfo(); } tables.add(new TableContent(vals, title, debugInfo)); } } } catch (IOException e) { LOGGER.error(e); e.printStackTrace(); } return tables; } private List<Object[]> createExportTableEntries(PEData pedata) { List<Object[]> entries = new ArrayList<>(); List<ExportEntry> exports = pedata.loadExports(); for (ExportEntry e : exports) { // TODO this is a hack because of lacking support to check for export names, *facepalm* String name = e instanceof ExportNameEntry ? ((ExportNameEntry) e).name() : ""; String forwarder = e.maybeGetForwarder().isPresent() ? e.maybeGetForwarder().get() : ""; Object[] entry = {name, e.ordinal(), e.symbolRVA(), forwarder}; entries.add(entry); } return entries; } private List<Object[]> createResourceTableEntries(PEData pedata) { List<Resource> resources = pedata.loadResources(); List<Object[]> entries = new ArrayList<>(); for (Resource r : resources) { Map<Level, IDOrName> lvlIds = r.getLevelIDs(); if(lvlIds == null) return entries; IDOrName nameLvl = lvlIds.get(Level.nameLevel()); IDOrName langLvl = lvlIds.get(Level.languageLevel()); if(nameLvl != null && langLvl != null) { String nameId = nameLvl.toString(); String langId = langLvl.toString(); String signatures; long offset = r.rawBytesLocation().from(); long size = r.rawBytesLocation().size(); Stream<String> scanresults = FileTypeScanner.apply(pedata.getFile()) .scanAtReport(offset).stream() // TODO this is a hack because lack of support from PortEx for scanAt function .map(s -> s.contains("bytes matched:") ? s.split("bytes matched:")[0] : s); signatures = scanresults.collect(Collectors.joining(", ")); Object[] entry = {r.getType(), nameId, langId, offset, size, signatures}; entries.add(entry); } } return entries; } private List<Object[]> createImportTableEntries(List<ImportDLL> imports) { List<Object[]> entries = new ArrayList<>(); for (ImportDLL dll : imports) { for (NameImport imp : dll.getNameImports()) { Optional<SymbolDescription> symbol = ImportDLL.getSymbolDescriptionForName(imp.getName()); String description = ""; String category = ""; if (symbol.isPresent()) { description = symbol.get().getDescription().or(""); // TODO replacing special chars is a hack for proper symbol descriptions, fix this in PortEx category = symbol.get().getCategory().replace("]", "").replace("[", ""); String subcategory = symbol.get().getSubCategory().or("").replace(">", "").replace("<", ""); if (!subcategory.equals("")) { category += " -> " + subcategory; } } Object[] entry = {dll.getName(), category, imp.getName(), description, imp.getRVA(), imp.getHint()}; entries.add(entry); } for (OrdinalImport imp : dll.getOrdinalImports()) { Object[] entry = {dll.getName(), "", imp.getOrdinal() + "", "", imp.getRVA(), ""}; entries.add(entry); } } return entries; } private double[] calculateSectionEntropies(PEData data) { int sectionNumber = data.getSectionTable().getNumberOfSections(); double[] sectionEntropies = new double[sectionNumber]; ShannonEntropy entropy = new ShannonEntropy(data); for (int i = 0; i < sectionNumber; i++) { sectionEntropies[i] = entropy.forSection(i + 1); } return sectionEntropies; } @Override protected void process(List<String> statusText) { String lastMsg = statusText.get(statusText.size() - 1); progressText.setText(lastMsg); } @Override protected void done() { if(isCancelled()) {return;} try { FullPEData data = get(); frame.setPeData(data); } catch (InterruptedException | ExecutionException e) { String message = "Could not load PE file! Reason: " + e.getMessage(); if (e.getMessage().contains("given file is no PE file")) { message = "Could not load PE file! The given file is no PE file"; } LOGGER.warn(message); LOGGER.warn(e); e.printStackTrace(); JOptionPane.showMessageDialog(null, message, "Unable to load", JOptionPane.ERROR_MESSAGE); } } }
java
Apache-2.0
88091e58891354ddefd35db0d79bc3e0c8e3e57a
2026-01-05T02:37:12.650809Z
false
struppigel/PortexAnalyzerGUI
https://github.com/struppigel/PortexAnalyzerGUI/blob/88091e58891354ddefd35db0d79bc3e0c8e3e57a/src/main/java/io/github/struppigel/gui/utils/PortexSwingUtils.java
src/main/java/io/github/struppigel/gui/utils/PortexSwingUtils.java
/** * ***************************************************************************** * Copyright 2022 Karsten Hahn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a> * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **************************************************************************** */ package io.github.struppigel.gui.utils; import io.github.struppigel.gui.pedetails.PEDetailsPanel; import javax.swing.*; import java.awt.*; import java.io.File; public class PortexSwingUtils { private static final File userdir = new File(System.getProperty("user.dir")); public static String getOpenFileNameFromUser(Component parent) { JFileChooser fc = new JFileChooser(userdir); int state = fc.showOpenDialog(parent); if (state == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); if (file != null) { return file.getAbsolutePath(); } } return null; } /** * Determines if a file can be safely written by checking if it already exists and asking for consent if it does. * Will return whether file can be written. * @param parent GUI component where messages should be shown * @param file to check * @return true if file can be written to specified location in path */ public static Boolean checkIfFileExistsAndAskIfOverwrite(Component parent, File file) { // file does not exist, so we can immediately return true if(!file.exists()) return true; // file exists, we need to ask int choice = JOptionPane.showConfirmDialog(parent, "File already exists, do you want to overwrite?", "File already exists", JOptionPane.YES_NO_OPTION); int YES_OPTION = 0; // user wants to overwrite if(choice == YES_OPTION) return true; // user does not want to overwrite, we tell them the consequences JOptionPane.showMessageDialog(parent, "Unable to save file", "File not saved", JOptionPane.WARNING_MESSAGE); return false; } public static String getSaveFileNameFromUser(Component parent, String defaultFileName) { JFileChooser fc = new JFileChooser(userdir); fc.setSelectedFile(new File(defaultFileName)); int state = fc.showSaveDialog(parent); if (state == JFileChooser.APPROVE_OPTION) { File dir = fc.getCurrentDirectory(); File file = fc.getSelectedFile(); if (file != null && !file.isDirectory()) { return file.getAbsolutePath(); } } return null; } public static String getSaveFolderNameFromUser(PEDetailsPanel parent) { JFileChooser fc = new JFileChooser(userdir); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fc.setAcceptAllFileFilterUsed(false); int state = fc.showSaveDialog(parent); if (state == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); if (file != null) { return file.getAbsolutePath(); } } return null; } }
java
Apache-2.0
88091e58891354ddefd35db0d79bc3e0c8e3e57a
2026-01-05T02:37:12.650809Z
false
struppigel/PortexAnalyzerGUI
https://github.com/struppigel/PortexAnalyzerGUI/blob/88091e58891354ddefd35db0d79bc3e0c8e3e57a/src/main/java/io/github/struppigel/gui/utils/WorkerKiller.java
src/main/java/io/github/struppigel/gui/utils/WorkerKiller.java
package io.github.struppigel.gui.utils; import javax.swing.*; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * Singleton that holds and cancels SwingWorkers when new PE loaded. Long running workers will otherwise set data for * previously loaded files. */ public class WorkerKiller { private static WorkerKiller singleton; private List<SwingWorker> workers = new ArrayList(); private WorkerKiller(){} public static synchronized WorkerKiller getInstance() { if(singleton == null) { singleton = new WorkerKiller(); } return singleton; } public void addWorker(SwingWorker worker) { cleanDoneWorkers(); // use this occasion to get rid of old ones this.workers.add(worker); } private void cleanDoneWorkers() { List<SwingWorker> toRemove = workers.stream().filter(w -> w.isCancelled() || w.isDone()).collect(Collectors.toList()); for(SwingWorker w : toRemove) { workers.remove(w); } } public void cancelAndDeleteWorkers() { for(SwingWorker worker : workers) { worker.cancel(true); } workers.clear(); } }
java
Apache-2.0
88091e58891354ddefd35db0d79bc3e0c8e3e57a
2026-01-05T02:37:12.650809Z
false
WorksApplications/icefig
https://github.com/WorksApplications/icefig/blob/60bcc893c80c27f61335696819a8ae261ac339c7/src/test/java/com/worksap/icefig/lang/Helpers.java
src/test/java/com/worksap/icefig/lang/Helpers.java
/* * Copyright (C) 2015 The Fig Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.worksap.icefig.lang; /** * Created by liuyang on 7/30/15. */ public class Helpers { public static void assertThrows(Class<? extends Exception> exception, Runnable action) { try { action.run(); throw new AssertionError("Expected exception: " + exception.getTypeName() + ", but no exception thrown"); } catch (Exception e) { if (!e.getClass().equals(exception)) { throw new AssertionError("Expected exception: " + exception.getTypeName() + ", but was " + e.getClass().getTypeName()); } } } }
java
Apache-2.0
60bcc893c80c27f61335696819a8ae261ac339c7
2026-01-05T02:37:21.030242Z
false
WorksApplications/icefig
https://github.com/WorksApplications/icefig/blob/60bcc893c80c27f61335696819a8ae261ac339c7/src/test/java/com/worksap/icefig/lang/SeqTest.java
src/test/java/com/worksap/icefig/lang/SeqTest.java
/* * Copyright (C) 2015 The Fig Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.worksap.icefig.lang; import org.junit.Test; import java.util.*; import java.util.function.*; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; /** * Created by liuyang on 7/23/15. */ public class SeqTest { @Test public void testConstruction() { Integer[] ints = new Integer[]{1, 2, 3}; assertEquals(3, Seqs.newMutableSeq(ints).size()); Collection<Integer> collection = new ArrayList<>(); collection.add(1); collection.add(2); assertEquals(2, Seqs.newSeq(collection).size()); assertArrayEquals(new Integer[]{1, 2, 3}, Seqs.newMutableSeq(1, 2, 3).toArray()); assertArrayEquals(new Integer[]{2}, Seqs.newMutableSeq(2).toArray()); List<Integer> list = new ArrayList<>(); list.add(3); list.add(4); assertArrayEquals(new Integer[]{3, 4}, Seqs.newMutableSeq(list).toArray()); Integer[] values = null; Helpers.assertThrows(NullPointerException.class, () -> Seqs.newMutableSeq(values)); Collection<Integer> cols = null; Helpers.assertThrows(NullPointerException.class, () -> Seqs.newMutableSeq(cols)); // for 100% coverage new Seqs(); } @Test public void testEquals() { Integer[] ints = new Integer[]{1, 2, 3}; assertFalse(Seqs.newMutableSeq(ints).equals(null)); assertFalse(Seqs.newMutableSeq(ints).equals(new ArrayList<>())); assertTrue(Seqs.newMutableSeq(ints).equals(Seqs.newMutableSeq(1, 2, 3))); assertEquals(Arrays.asList(ints).toString(), Seqs.newMutableSeq(ints).toString()); } @Test public void testMap() { assertArrayEquals(new Integer[]{2, 4, 6}, Seqs.newMutableSeq(1, 2, 3).map(i -> i * 2).toArray()); assertArrayEquals(new String[]{"x1", "x2", "x3"}, Seqs.newMutableSeq(1, 2, 3).map(i -> "x" + i).toArray()); Function<Integer, Integer> f = null; Helpers.assertThrows(NullPointerException.class, () -> Seqs.newMutableSeq(1).map(f)); } @Test public void testFlatMap() { assertArrayEquals(new Integer[]{2, 3, 4, 3, 4, 5, 4, 5, 6}, Seqs.newMutableSeq(1, 2, 3).flatMap(i -> Seqs.newMutableSeq(i + 1, i + 2, i + 3)).toArray()); assertArrayEquals(new Integer[]{1, 0, 2, 1, 3, 2}, Seqs.newMutableSeq(1, 2, 3).flatMap((i, idx) -> Seqs.newMutableSeq(i, idx)).toArray()); Function<Integer, Seq<Integer>> f = null; Helpers.assertThrows(NullPointerException.class, () -> Seqs.newMutableSeq(1).flatMap(f)); } @Test public void testMapWithIndex() { assertArrayEquals(new String[]{"a1", "b2", "c3"}, Seqs.newMutableSeq("a", "b", "c").map((s, i) -> s + (i + 1)).toArray()); BiFunction<Integer, Integer, Integer> f = null; Helpers.assertThrows(NullPointerException.class, () -> Seqs.newMutableSeq(1).map(f)); } @Test public void testSample() { assertNull(Seqs.newMutableSeq().sample()); assertEquals((Integer) 1, Seqs.newMutableSeq(1).sample()); assertEquals(0, Seqs.newMutableSeq().sample(1).size()); assertEquals(2, Seqs.newMutableSeq(1, 2, 3).sample(2).size()); assertEquals(3, Seqs.newMutableSeq(1, 2, 3).sample(3).size()); assertEquals(3, Seqs.newMutableSeq(1, 2, 3).sample(4).size()); assertEquals(3, Seqs.newMutableSeq(1, 2, 3).sample(5).size()); } @Test public void testShuffle() { MutableSeq<Integer> seq = Seqs.newMutableSeq(1, 2, 3); for (int i = 0; i < 3; i++) { assertEquals(seq.shuffle().size(), 3); assertArrayEquals(new Integer[]{1, 2, 3}, seq.toArray()); } } @Test public void testShuffle$() { MutableSeq<Integer> seq = Seqs.newMutableSeq(1, 2, 3); for (int i = 0; i < 3; i++) { MutableSeq<Integer> shuffled = seq.shuffleInPlace(); assertEquals(shuffled.size(), 3); assertArrayEquals(shuffled.toArray(), seq.toArray()); } } @Test public void testIndexOf() { assertEquals(1, Seqs.newSeq(1, 2, 2, 3).indexOf(2)); assertEquals(2, Seqs.newSeq(1, 2, 2, 3).lastIndexOf(2)); assertEquals(-1, Seqs.newSeq(1, 2, 2, 3).indexOf(4)); } @Test public void testContainsAny() { Helpers.assertThrows(NullPointerException.class, () -> Seqs.newSeq(1, 2, 3).any((Predicate<Integer>) null)); Helpers.assertThrows(NullPointerException.class, () -> Seqs.newSeq(1, 2, 3).any((BiPredicate<Integer, Integer>) null)); assertTrue(Seqs.newSeq(1, 2, 3).any(i -> i > 2)); assertTrue(Seqs.newSeq(1, 2, 3).any((e, i) -> e + i == 3)); assertFalse(Seqs.newSeq(1, 2, 3).any((e, i) -> e + i == 4)); assertFalse(Seqs.newSeq(1, 2, 3).any(i -> i > 3)); } @Test public void testContainsAll() { Helpers.assertThrows(NullPointerException.class, () -> Seqs.newSeq(1, 2, 3).all((Predicate<Integer>) null)); Helpers.assertThrows(NullPointerException.class, () -> Seqs.newSeq(1, 2, 3).all((BiPredicate<Integer, Integer>) null)); assertTrue(Seqs.newSeq(1, 2, 3).all(i -> i > 0)); assertTrue(Seqs.newSeq(3, 2, 1).all((e, i) -> e + i == 3)); assertFalse(Seqs.newSeq(1, 2, 3).all((e, i) -> e + i == 3)); assertFalse(Seqs.newSeq(1, 2, 3).all(i -> i > 1)); } @Test public void testContainsNone() { Helpers.assertThrows(NullPointerException.class, () -> Seqs.newSeq(1, 2, 3).none((Predicate<Integer>) null)); Helpers.assertThrows(NullPointerException.class, () -> Seqs.newSeq(1, 2, 3).none((BiPredicate<Integer, Integer>) null)); assertTrue(Seqs.newSeq(1, 2, 3).none(i -> i > 3)); assertTrue(Seqs.newSeq(1, 2, 3).none((e, i) -> e + i == 4)); assertFalse(Seqs.newSeq(1, 2, 3).none((e, i) -> e + i == 3)); assertFalse(Seqs.newSeq(1, 2, 3).none(i -> i > 1)); } @Test public void testContainSubSeq() { assertTrue(Seqs.newSeq('B', 'B', 'C', ' ', 'A', 'B', 'C', 'D', 'A', 'B', ' ', 'A', 'B', 'C', 'D', 'A', 'B', 'C', 'D', 'A', 'B', 'D', 'E') .containsSubSeq(Seqs.newSeq('A', 'B', 'C', 'D', 'A', 'B', 'D'))); assertFalse(Seqs.newSeq('B', 'B', 'C', ' ', 'A', 'B', 'C', 'D', 'A', 'B', ' ', 'A', 'B', 'C', 'D', 'A', 'B', 'C', 'D', 'A', 'B', 'D', 'E') .containsSubSeq(Seqs.newSeq('A', 'B', 'C', 'D', 'A', 'B', 'A'))); assertFalse(Seqs.newSeq('A') .containsSubSeq(Seqs.newSeq('B'))); assertFalse(Seqs.newSeq() .containsSubSeq(Seqs.newSeq('B'))); assertTrue(Seqs.newSeq('A') .containsSubSeq(Seqs.newSeq())); assertEquals(-1, Seqs.newSeq().lastIndexOfSubSeq(Seqs.newSeq('A'))); assertEquals(-1, Seqs.newSeq('A', 'B').lastIndexOfSubSeq(Seqs.newSeq('C', 'B'))); assertEquals(-1, Seqs.newSeq('A', 'A', 'B').lastIndexOfSubSeq(Seqs.newSeq('C', 'B'))); assertEquals(0, Seqs.newSeq('A').lastIndexOfSubSeq(Seqs.newSeq())); assertTrue(Seqs.newSeq('A', 'B', 'C') .containsSubSeq(Seqs.newSeq('A', 'B', 'C'))); Helpers.assertThrows(NullPointerException.class, () -> Seqs.newSeq('A', 'B', 'C').containsSubSeq(null)); assertEquals(15, Seqs.newSeq('B', 'B', 'C', ' ', 'A', 'B', 'C', 'D', 'A', 'B', ' ', 'A', 'B', 'C', 'D', 'A', 'B', 'C', 'D', 'A', 'B', 'D', 'E') .indexOfSubSeq(Seqs.newSeq('A', 'B', 'C', 'D', 'A', 'B', 'D'))); assertEquals(15, Seqs.newSeq('B', 'B', 'C', ' ', 'A', 'B', 'C', 'D', 'A', 'B', ' ', 'A', 'B', 'C', 'D', 'A', 'B', 'C', 'D', 'A', 'B', 'D', 'E') .lastIndexOfSubSeq(Seqs.newSeq('A', 'B', 'C', 'D', 'A', 'B', 'D'))); assertEquals(1, Seqs.newSeq(3, 1, 2, 1, 2, 1, 2, 3) .indexOfSubSeq(Seqs.newSeq(1, 2, 1, 2))); assertEquals(3, Seqs.newSeq(3, 1, 2, 1, 2, 1, 2, 3) .lastIndexOfSubSeq(Seqs.newSeq(1, 2, 1, 2))); Helpers.assertThrows(NullPointerException.class, () -> Seqs.newSeq('A', 'B', 'C').indexOfSubSeq(null)); Helpers.assertThrows(NullPointerException.class, () -> Seqs.newSeq('A', 'B', 'C').lastIndexOfSubSeq(null)); } @Test public void testIntersect() { Helpers.assertThrows(NullPointerException.class, () -> Seqs.newSeq(1).intersect(null)); assertEquals(Seqs.newSeq(), Seqs.newSeq(1, 2, 3).intersect(Seqs.newSeq())); assertEquals(Seqs.newSeq(3, 6, 2, 3), Seqs.newSeq(3, 6, 2, 4, 3, 6, 2).intersect(Seqs.newSeq(6, 2, 3, 3, 8, 3))); } @Test public void testDifference() { Helpers.assertThrows(NullPointerException.class, () -> Seqs.newSeq(1).difference(null)); assertEquals(Seqs.newSeq(1, 2, 3), Seqs.newSeq(1, 2, 3).difference(Seqs.newSeq())); assertEquals(Seqs.newSeq(), Seqs.newSeq(3, 6, 2, 4, 3, 6, 2).difference(Seqs.newSeq(3, 6, 2, 4, 3, 6, 2))); assertEquals(Seqs.newSeq(4, 3, 6, 2), Seqs.newSeq(3, 6, 2, 4, 3, 6, 2).difference(Seqs.newSeq(3, 6, 2, 7))); } @Test public void testForEachWithIndex() { final MutableSeq<String> seq = Seqs.newMutableSeq("a", "b", "c"); seq.forEach((item, index) -> { assertEquals(seq.get(index), item); }); seq.forEach(item -> assertTrue(seq.contains(item))); BiConsumer<String, Integer> f = null; Helpers.assertThrows(NullPointerException.class, () -> seq.forEach(f)); } @Test public void testForEachReverse() { MutableSeq<Integer> result = Seqs.newMutableSeq(); Seqs.newMutableSeq(1, 2, 3, 4, 5).forEachReverse(i -> { result.appendInPlace(i); }); assertEquals(Seqs.newSeq(5, 4, 3, 2, 1), result); MutableSeq<Integer> result2 = Seqs.newMutableSeq(); Seqs.newMutableSeq(1, 2, 3, 4, 5).forEachReverse((e, i) -> { result2.appendInPlace(e + i); }); assertEquals(Seqs.newSeq(9, 7, 5, 3, 1), result2); } @Test public void testEachCons() { final MutableSeq<String> seq = Seqs.newMutableSeq("a", "b", "c", "d"); assertArrayEquals(new Object[]{Seqs.newMutableSeq("a", "b"), Seqs.newMutableSeq("b", "c"), Seqs.newMutableSeq("c", "d")}, seq.eachCons(2).toArray()); assertArrayEquals(new Object[]{Seqs.newMutableSeq("a", "b", "c"), Seqs.newMutableSeq("b", "c", "d")}, seq.eachCons(3).toArray()); assertArrayEquals(new Object[]{Seqs.newMutableSeq("a", "b", "c", "d")}, seq.eachCons(4).toArray()); assertArrayEquals(new Object[]{}, seq.eachCons(5).toArray()); Helpers.assertThrows(IllegalArgumentException.class, () -> seq.eachCons(-1)); } @Test public void testForEachCons() { final MutableSeq<String> seq = Seqs.newMutableSeq("a", "b", "c", "d"); MutableSeq<Seq<String>> result = Seqs.newMutableSeq(); seq.forEachCons(2, result::appendInPlace); assertArrayEquals(new Object[]{Seqs.newMutableSeq("a", "b"), Seqs.newMutableSeq("b", "c"), Seqs.newMutableSeq("c", "d")}, result.toArray()); result.clear(); seq.forEachCons(3, result::appendInPlace); assertArrayEquals(new Object[]{Seqs.newMutableSeq("a", "b", "c"), Seqs.newMutableSeq("b", "c", "d")}, result.toArray()); result.clear(); seq.forEachCons(4, result::appendInPlace); assertArrayEquals(new Object[]{Seqs.newMutableSeq("a", "b", "c", "d")}, result.toArray()); result.clear(); seq.forEachCons(5, result::appendInPlace); assertArrayEquals(new Object[]{}, result.toArray()); Helpers.assertThrows(NullPointerException.class, () -> seq.forEachCons(0, null)); Helpers.assertThrows(IllegalArgumentException.class, () -> seq.forEachCons(0, result::appendInPlace)); } @Test public void testDistinct() { MutableSeq<Integer> seq = Seqs.newMutableSeq(1, 2, 3); assertArrayEquals(new Integer[]{1, 2, 3}, seq.distinct().toArray()); assertEquals(Seqs.newMutableSeq(1, 2, 3), seq); assertArrayEquals(new Integer[]{1, 2, 3}, seq.distinctInPlace().toArray()); assertEquals(Seqs.newMutableSeq(1, 2, 3), seq); seq = Seqs.newMutableSeq(1, 2, 3, 2, 3); assertArrayEquals(new Integer[]{1, 2, 3}, seq.distinct().toArray()); assertEquals(Seqs.newMutableSeq(1, 2, 3, 2, 3), seq); assertArrayEquals(new Integer[]{1, 2, 3}, seq.distinctInPlace().toArray()); assertEquals(Seqs.newMutableSeq(1, 2, 3), seq); seq = Seqs.newMutableSeq(3, 2, 1, 2, 3, 4); assertArrayEquals(new Integer[]{3, 2, 1, 4}, seq.distinct().toArray()); assertEquals(Seqs.newMutableSeq(3, 2, 1, 2, 3, 4), seq); assertArrayEquals(new Integer[]{3, 2, 1, 4}, seq.distinctInPlace().toArray()); assertEquals(Seqs.newMutableSeq(3, 2, 1, 4), seq); seq = Seqs.newMutableSeq(1, 1, 1, 1); assertEquals(Seqs.newMutableSeq(1), seq.distinct()); assertEquals(Seqs.newMutableSeq(1, 1, 1, 1), seq); assertEquals(Seqs.newMutableSeq(1), seq.distinctInPlace()); assertEquals(Seqs.newMutableSeq(1), seq); seq = Seqs.newMutableSeq(null, 1, null, 1, 2); assertEquals(Seqs.newMutableSeq(null, 1, 2), seq.distinct()); assertEquals(Seqs.newMutableSeq(null, 1, null, 1, 2), seq); assertEquals(Seqs.newMutableSeq(null, 1, 2), seq.distinctInPlace()); assertEquals(Seqs.newMutableSeq(null, 1, 2), seq); seq.clear(); assertEquals(Seqs.newMutableSeq(), seq.distinct()); assertEquals(Seqs.newMutableSeq(), seq); assertEquals(Seqs.newMutableSeq(), seq.distinctInPlace()); assertEquals(Seqs.newMutableSeq(), seq); } @Test public void testSort() { MutableSeq<Integer> seq = Seqs.newMutableSeq(2, 1, 3); assertArrayEquals(new Integer[]{1, 2, 3}, seq.sort((a, b) -> a - b).toArray()); assertArrayEquals(new Integer[]{3, 2, 1}, seq.sort((a, b) -> b - a).toArray()); // original seq should remain unchanged assertArrayEquals(new Integer[]{2, 1, 3}, seq.toArray()); assertArrayEquals(new Integer[]{1, 2, 3}, seq.sort(null).toArray()); assertEquals(Seqs.newMutableSeq(), Seqs.newMutableSeq().sort(null)); } @Test public void testSortInPlace() { MutableSeq<Integer> seq = Seqs.newMutableSeq(2, 1, 3); assertArrayEquals(new Integer[]{1, 2, 3}, seq.sortInPlace((a, b) -> a - b).toArray()); assertArrayEquals(new Integer[]{3, 2, 1}, seq.sortInPlace((a, b) -> b - a).toArray()); assertArrayEquals(new Integer[]{3, 2, 1}, seq.toArray()); assertArrayEquals(new Integer[]{1, 2, 3}, seq.sortInPlace(null).toArray()); assertEquals(Seqs.newMutableSeq(), Seqs.newMutableSeq().sortInPlace(null)); } @Test public void testJoin() { MutableSeq<Integer> seq = Seqs.newMutableSeq(1, 2, 3); assertEquals("123", seq.join().toString()); assertEquals("1,2,3", seq.join(",").toString()); assertEquals("!1-2-3!", seq.join("-", "!", "!").toString()); } @Test public void testFirstLast() { MutableSeq<Integer> seq = Seqs.newMutableSeq(1, 2, 3); assertEquals((Integer) 1, seq.first()); assertEquals((Integer) 3, seq.last()); seq.clear(); Helpers.assertThrows(IndexOutOfBoundsException.class, () -> seq.first()); Helpers.assertThrows(IndexOutOfBoundsException.class, () -> seq.last()); } static class TestObj { private String name; private int age; public TestObj(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } static TestObj jim = new TestObj("Jim", 15); static TestObj tom = new TestObj("Tom", 16); static TestObj kate = new TestObj("Kate", 15); static TestObj john = new TestObj("John", 20); static MutableSeq<TestObj> people = Seqs.newMutableSeq(Arrays.asList(new TestObj[]{jim, tom, kate, john})); @Test public void testFind() { assertEquals(jim, people.findFirst(p -> p.age == 15)); assertEquals(kate, people.findLast(p -> p.age == 15)); assertEquals(0, people.findFirstIndex(p -> p.age == 15)); assertEquals(2, people.findLastIndex(p -> p.age == 15)); assertEquals(-1, people.findFirstIndex(p -> p.age == 1)); assertEquals(-1, people.findLastIndex(p -> p.age == 1)); assertNull(people.findFirst(p -> p.age == 1)); assertNull(people.findLast(p -> p.age == 1)); Helpers.assertThrows(NullPointerException.class, () -> people.findFirst(null)); Helpers.assertThrows(NullPointerException.class, () -> people.findLast(null)); Helpers.assertThrows(NullPointerException.class, () -> people.findFirstIndex(null)); Helpers.assertThrows(NullPointerException.class, () -> people.findLastIndex(null)); } @Test public void testAppendPrependInPlace() { assertEquals(Seqs.newMutableSeq(1, 2, 3, 4, 5), Seqs.newMutableSeq(1, 2, 3).appendInPlace(4, 5)); assertEquals(Seqs.newMutableSeq(1, 2, 3, 4, 5), Seqs.newMutableSeq(1, 2, 3).appendInPlace(Arrays.asList(new Integer[]{4, 5}))); assertEquals(Seqs.newMutableSeq(1, 2, 3, 4), Seqs.newMutableSeq(1, 2, 3).appendInPlace(4)); assertEquals(Seqs.newMutableSeq(1, 2, 3, 4, 5), Seqs.newMutableSeq(3, 4, 5).prependInPlace(1, 2)); assertEquals(Seqs.newMutableSeq(1, 3, 4, 5), Seqs.newMutableSeq(3, 4, 5).prependInPlace(1)); assertEquals(Seqs.newMutableSeq(2, 3, 4, 5), Seqs.newMutableSeq(3, 4, 5).prependInPlace(Seqs.newMutableSeq(2))); MutableSeq<Integer> seq = Seqs.newMutableSeq(1, 2, 3); seq.appendInPlace(4, 5); assertEquals(Seqs.newMutableSeq(1, 2, 3, 4, 5), seq); seq.prependInPlace(4, 5); assertEquals(Seqs.newMutableSeq(4, 5, 1, 2, 3, 4, 5), seq); Integer[] ints = null; Helpers.assertThrows(NullPointerException.class, () -> Seqs.newMutableSeq(1).appendInPlace(ints)); Collection<Integer> cols = null; Helpers.assertThrows(NullPointerException.class, () -> Seqs.newMutableSeq(1).appendInPlace(cols)); } @Test public void testIsEmpty() { assertTrue(Seqs.newSeq().isEmpty()); assertFalse(Seqs.newSeq(1, 2, 3).isEmpty()); } @Test public void testAppendPrepend() { assertEquals(Seqs.newMutableSeq(1, 2, 3, 4, 5), Seqs.newMutableSeq(1, 2, 3).append(4, 5)); assertEquals(Seqs.newMutableSeq(1, 2, 3, 4, 5), Seqs.newMutableSeq(1, 2, 3).append(Arrays.asList(new Integer[]{4, 5}))); assertEquals(Seqs.newMutableSeq(1, 2, 3, 4), Seqs.newMutableSeq(1, 2, 3).append(4)); assertEquals(Seqs.newMutableSeq(1, 2, 3, 4, 5), Seqs.newMutableSeq(3, 4, 5).prepend(1, 2)); assertEquals(Seqs.newMutableSeq(1, 3, 4, 5), Seqs.newMutableSeq(3, 4, 5).prepend(1)); MutableSeq<Integer> seq = Seqs.newMutableSeq(1, 2, 3); seq.append(4, 5); assertEquals(Seqs.newMutableSeq(1, 2, 3), seq); seq.prepend(4, 5); assertEquals(Seqs.newMutableSeq(1, 2, 3), seq); Integer[] ints = null; Helpers.assertThrows(NullPointerException.class, () -> Seqs.newMutableSeq(1).prepend(ints)); Helpers.assertThrows(NullPointerException.class, () -> Seqs.newMutableSeq(1).append(ints)); Helpers.assertThrows(NullPointerException.class, () -> Seqs.newMutableSeq(1).prepend(ints)); Collection<Integer> cols = null; Helpers.assertThrows(NullPointerException.class, () -> Seqs.newMutableSeq(1).prepend(cols)); Helpers.assertThrows(NullPointerException.class, () -> Seqs.newMutableSeq(1).append(cols)); Helpers.assertThrows(NullPointerException.class, () -> Seqs.newMutableSeq(1).prepend(cols)); seq = Seqs.newMutableSeq(1, 2, 3); assertEquals(Seqs.newMutableSeq(1, 2, 3, 1, 2, 3), seq.append(seq)); assertEquals(Seqs.newMutableSeq(3, 2, 1, 1, 2, 3), seq.prepend(seq.reverse())); } @Test public void testReject() { MutableSeq<Integer> seq = Seqs.newMutableSeq(1, 2, 3); MutableSeq<Integer> seq1 = seq.reject((e, i) -> (e > 1 && i % 2 == 0)); assertEquals(Seqs.newMutableSeq(1, 2, 3), seq); assertEquals(Seqs.newMutableSeq(1, 2), seq1); MutableSeq<Integer> seq$ = Seqs.newMutableSeq(1, 2, 3); MutableSeq<Integer> seq1$ = seq$.rejectInPlace((e, i) -> (e > 1 && i % 2 == 0)); assertEquals(Seqs.newMutableSeq(1, 2), seq$); assertEquals(Seqs.newMutableSeq(1, 2), seq1$); assertEquals(seq$, seq1$); seq = Seqs.newMutableSeq(1, 2, 3); seq1 = seq.reject(e -> e > 1); assertEquals(Seqs.newMutableSeq(1, 2, 3), seq); assertEquals(Seqs.newMutableSeq(1), seq1); seq$ = Seqs.newMutableSeq(1, 2, 3); seq1$ = seq$.rejectInPlace(e -> e > 1); assertEquals(Seqs.newMutableSeq(1), seq$); assertEquals(Seqs.newMutableSeq(1), seq1$); assertEquals(seq$, seq1$); Predicate<Integer> predicate = null; Helpers.assertThrows(NullPointerException.class, () -> Seqs.newMutableSeq(1).reject(predicate)); Helpers.assertThrows(NullPointerException.class, () -> Seqs.newMutableSeq(1).rejectInPlace(predicate)); BiPredicate<Integer, Integer> biPredicate = null; Helpers.assertThrows(NullPointerException.class, () -> Seqs.newMutableSeq(1).reject(biPredicate)); Helpers.assertThrows(NullPointerException.class, () -> Seqs.newMutableSeq(1).rejectInPlace(biPredicate)); } @Test public void testRejectWhile() { MutableSeq<Integer> seq = Seqs.newMutableSeq(1, 2, 1); assertThat(seq.rejectWhile(e -> e < 2), is(equalTo(Seqs.newMutableSeq(2, 1)))); assertThat(seq.rejectWhile(e -> e < 1), is(equalTo(Seqs.newMutableSeq(1, 2, 1)))); assertThat(seq.rejectWhile(e -> e > 0), is(equalTo(Seqs.newMutableSeq()))); assertThat(seq.rejectWhile((e, i) -> e < 2), is(equalTo(Seqs.newMutableSeq(2, 1)))); assertThat(seq.rejectWhile((e, i) -> e < 1), is(equalTo(Seqs.newMutableSeq(1, 2, 1)))); assertThat(seq.rejectWhile((e, i) -> e > 0), is(equalTo(Seqs.newMutableSeq()))); assertThat(Seqs.newMutableSeq(1, 2, 1).rejectWhileInPlace(e -> e < 2), is(equalTo(Seqs.newMutableSeq(2, 1)))); assertThat(Seqs.newMutableSeq(1, 2, 1).rejectWhileInPlace(e -> e < 1), is(equalTo(Seqs.newMutableSeq(1, 2, 1)))); assertThat(Seqs.newMutableSeq(1, 2, 1).rejectWhileInPlace(e -> e > 0), is(equalTo(Seqs.newMutableSeq()))); assertThat(Seqs.newMutableSeq(1, 2, 1).rejectWhileInPlace((e, i) -> e < 2), is(equalTo(Seqs.newMutableSeq(2, 1)))); assertThat(Seqs.newMutableSeq(1, 2, 1).rejectWhileInPlace((e, i) -> e < 1), is(equalTo(Seqs.newMutableSeq(1, 2, 1)))); assertThat(Seqs.newMutableSeq(1, 2, 1).rejectWhileInPlace((e, i) -> e > 0), is(equalTo(Seqs.newMutableSeq()))); Helpers.assertThrows(NullPointerException.class, () -> Seqs.newMutableSeq(1).rejectWhile((Predicate<Integer>) null)); Helpers.assertThrows(NullPointerException.class, () -> Seqs.newMutableSeq(1).rejectWhileInPlace((Predicate<Integer>) null)); Helpers.assertThrows(NullPointerException.class, () -> Seqs.newMutableSeq(1).rejectWhile((BiPredicate<Integer, Integer>) null)); Helpers.assertThrows(NullPointerException.class, () -> Seqs.newMutableSeq(1).rejectWhileInPlace((BiPredicate<Integer, Integer>) null)); } @Test public void testFilter() { MutableSeq<Integer> seq = Seqs.newMutableSeq(1, 2, 3); MutableSeq<Integer> seq1 = seq.filter((e, i) -> (e > 1 && i % 2 == 0)); assertEquals(Seqs.newMutableSeq(1, 2, 3), seq); assertEquals(Seqs.newMutableSeq(3), seq1); MutableSeq<Integer> seq2 = Seqs.newMutableSeq(1, 2, 3); MutableSeq<Integer> seq3 = seq2.filterInPlace((e, i) -> (e > 1 && i % 2 == 0)); assertEquals(Seqs.newMutableSeq(3), seq2); assertEquals(Seqs.newMutableSeq(3), seq3); assertEquals(seq2, seq3); seq2 = Seqs.newMutableSeq(1, 2, 3); seq3 = seq2.filterInPlace(e -> e > 1); assertEquals(Seqs.newMutableSeq(2, 3), seq2); assertEquals(Seqs.newMutableSeq(2, 3), seq3); assertEquals(seq2, seq3); MutableSeq<Integer> seq1$ = seq.filter(e -> e > 1); assertEquals(Seqs.newMutableSeq(1, 2, 3), seq); assertEquals(Seqs.newMutableSeq(2, 3), seq1$); Predicate<Integer> predicate = null; Helpers.assertThrows(NullPointerException.class, () -> seq.filter(predicate)); Helpers.assertThrows(NullPointerException.class, () -> seq.filterInPlace(predicate)); BiPredicate<Integer, Integer> biPredicate = null; Helpers.assertThrows(NullPointerException.class, () -> seq.filter(biPredicate)); Helpers.assertThrows(NullPointerException.class, () -> seq.filterInPlace(biPredicate)); } @Test public void testFilterWhile() { MutableSeq<Integer> seq = Seqs.newMutableSeq(1, 2, 1); assertThat(seq.filterWhile(e -> e < 2), is(equalTo(Seqs.newMutableSeq(1)))); assertThat(seq.filterWhile(e -> e < 1), is(equalTo(Seqs.newMutableSeq()))); assertThat(seq.filterWhile(e -> e > 0), is(equalTo(Seqs.newMutableSeq(1, 2, 1)))); assertThat(seq.filterWhile((e, i) -> e < 2), is(equalTo(Seqs.newMutableSeq(1)))); assertThat(seq.filterWhile((e, i) -> e < 1), is(equalTo(Seqs.newMutableSeq()))); assertThat(seq.filterWhile((e, i) -> e > 0), is(equalTo(Seqs.newMutableSeq(1, 2, 1)))); assertThat(Seqs.newMutableSeq(1, 2, 1).filterWhileInPlace(e -> e < 2), is(equalTo(Seqs.newMutableSeq(1)))); assertThat(Seqs.newMutableSeq(1, 2, 1).filterWhileInPlace(e -> e < 1), is(equalTo(Seqs.newMutableSeq()))); assertThat(Seqs.newMutableSeq(1, 2, 1).filterWhileInPlace(e -> e > 0), is(equalTo(Seqs.newMutableSeq(1, 2, 1)))); assertThat(Seqs.newMutableSeq(1, 2, 1).filterWhileInPlace((e, i) -> e < 2), is(equalTo(Seqs.newMutableSeq(1)))); assertThat(Seqs.newMutableSeq(1, 2, 1).filterWhileInPlace((e, i) -> e < 1), is(equalTo(Seqs.newMutableSeq()))); assertThat(Seqs.newMutableSeq(1, 2, 1).filterWhileInPlace((e, i) -> e > 0), is(equalTo(Seqs.newMutableSeq(1, 2, 1)))); Helpers.assertThrows(NullPointerException.class, () -> Seqs.newMutableSeq(1).filterWhile((Predicate<Integer>) null)); Helpers.assertThrows(NullPointerException.class, () -> Seqs.newMutableSeq(1).filterWhileInPlace((Predicate<Integer>) null)); Helpers.assertThrows(NullPointerException.class, () -> Seqs.newMutableSeq(1).filterWhile((BiPredicate<Integer, Integer>) null)); Helpers.assertThrows(NullPointerException.class, () -> Seqs.newMutableSeq(1).filterWhileInPlace((BiPredicate<Integer, Integer>) null)); } @Test public void testGet() { MutableSeq<Integer> seq = Seqs.newMutableSeq(1, 2, 3, 4, 5, 6); assertEquals(new Integer(1), seq.get(0)); assertEquals(new Integer(6), seq.get(5)); assertEquals(new Integer(6), seq.get(-1)); assertEquals(new Integer(1), seq.get(-6)); assertEquals(new Integer(2), seq.get(1, 100)); assertEquals(new Integer(6), seq.get(-1, 100)); assertEquals(new Integer(100), seq.get(6, 100)); assertEquals(new Integer(100), seq.get(-7, 100)); Helpers.assertThrows(IndexOutOfBoundsException.class, () -> seq.get(6)); Helpers.assertThrows(IndexOutOfBoundsException.class, () -> seq.get(-7)); } @Test public void testRepeat() { MutableSeq<Integer> seq = Seqs.newMutableSeq(1, 2); assertEquals(Seqs.newMutableSeq(1, 2, 1, 2, 1, 2, 1, 2), seq.repeat(4)); assertEquals(Seqs.newMutableSeq(1, 2), seq); assertEquals(Seqs.newMutableSeq(1, 2), seq.repeatInPlace(1)); assertEquals(Seqs.newMutableSeq(1, 2, 1, 2, 1, 2, 1, 2), seq.repeatInPlace(4)); assertEquals(Seqs.newMutableSeq(1, 2, 1, 2, 1, 2, 1, 2), seq); Helpers.assertThrows(IllegalArgumentException.class, () -> seq.repeat(0)); Helpers.assertThrows(IllegalArgumentException.class, () -> seq.repeatInPlace(0)); } @Test public void testCompact() { MutableSeq<Integer> seq = Seqs.newMutableSeq(1, 2, null, 3, 4, 5, null); assertEquals(Seqs.newMutableSeq(1, 2, 3, 4, 5), seq.compact()); assertEquals(Seqs.newMutableSeq(1, 2, null, 3, 4, 5, null), seq); assertEquals(Seqs.newMutableSeq(1, 2, 3, 4, 5), seq.compactInPlace()); assertEquals(Seqs.newMutableSeq(1, 2, 3, 4, 5), seq); } @Test public void testCount() { MutableSeq<Integer> seq = Seqs.newMutableSeq(1, 1, null, 2, null, 3, 1, 4); assertEquals(3, seq.count(1)); assertEquals(1, seq.count(2)); assertEquals(2, seq.count(null)); assertEquals(2, seq.countIf(e -> e == null)); assertEquals(3, seq.countIf(e -> e != null && e > 1)); assertEquals(2, seq.countIf((e, i) -> e != null && e > 1 && i < seq.size() - 1)); Predicate<Integer> predicate = null; Helpers.assertThrows(NullPointerException.class, () -> seq.countIf(predicate)); BiPredicate<Integer, Integer> biPredicate = null; Helpers.assertThrows(NullPointerException.class, () -> seq.countIf(biPredicate)); } @Test public void testEachSlice() { final MutableSeq<String> seq = Seqs.newMutableSeq("a", "b", "c", "d", "e"); assertArrayEquals(new Object[]{Seqs.newMutableSeq("a"), Seqs.newMutableSeq("b"), Seqs.newMutableSeq("c"), Seqs.newMutableSeq("d"), Seqs.newMutableSeq("e")}, seq.eachSlice(1).toArray()); assertArrayEquals(new Object[]{Seqs.newMutableSeq("a", "b"), Seqs.newMutableSeq("c", "d"), Seqs.newMutableSeq("e")}, seq.eachSlice(2).toArray()); assertArrayEquals(new Object[]{Seqs.newMutableSeq("a", "b", "c"), Seqs.newMutableSeq("d", "e")}, seq.eachSlice(3).toArray()); assertArrayEquals(new Object[]{Seqs.newMutableSeq("a", "b", "c", "d"), Seqs.newMutableSeq("e")}, seq.eachSlice(4).toArray()); assertArrayEquals(new Object[]{seq}, seq.eachSlice(5).toArray()); assertArrayEquals(new Object[]{seq}, seq.eachSlice(6).toArray()); Helpers.assertThrows(IllegalArgumentException.class, () -> seq.eachSlice(0)); } @Test public void testForEachSlice() { final MutableSeq<String> seq = Seqs.newMutableSeq("a", "b", "c", "d"); MutableSeq<Seq<String>> result = Seqs.newMutableSeq(); seq.forEachSlice(2, result::appendInPlace); assertArrayEquals(new Object[]{Seqs.newMutableSeq("a", "b"), Seqs.newMutableSeq("c", "d")}, result.toArray()); result.clear(); seq.forEachSlice(3, result::appendInPlace); assertArrayEquals(new Object[]{Seqs.newMutableSeq("a", "b", "c"), Seqs.newMutableSeq("d")}, result.toArray()); result.clear(); seq.forEachSlice(4, result::appendInPlace); assertArrayEquals(new Object[]{Seqs.newMutableSeq("a", "b", "c", "d")}, result.toArray()); result.clear(); seq.forEachSlice(5, result::appendInPlace); assertArrayEquals(new Object[]{Seqs.newMutableSeq("a", "b", "c", "d")}, result.toArray()); Helpers.assertThrows(IllegalArgumentException.class, () -> seq.forEachSlice(0, result::appendInPlace)); Helpers.assertThrows(NullPointerException.class, () -> seq.forEachSlice(0, null)); } @Test public void testReduce() { MutableSeq<Integer> seq = Seqs.newMutableSeq(1, 2, 3, 4, 5); assertEquals(new Integer(15), seq.reduce(0, Integer::sum)); assertEquals(new Integer(15), seq.reduce(Integer::sum)); seq = Seqs.newMutableSeq(); assertEquals(null, seq.reduce(Integer::sum));
java
Apache-2.0
60bcc893c80c27f61335696819a8ae261ac339c7
2026-01-05T02:37:21.030242Z
true
WorksApplications/icefig
https://github.com/WorksApplications/icefig/blob/60bcc893c80c27f61335696819a8ae261ac339c7/src/test/java/com/worksap/icefig/lang/CharSeqTest.java
src/test/java/com/worksap/icefig/lang/CharSeqTest.java
/* * Copyright (C) 2015 The Fig Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.worksap.icefig.lang; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import static org.junit.Assert.*; /** * Created by lijunxiao on 7/27/15. */ public class CharSeqTest { @Test public void testSubSeq() { CharSeq seq = CharSeq.of("Father Charles gets down and ends battle."); assertEquals(CharSeq.of("Father"), seq.subSeq(0, 6)); assertEquals(CharSeq.of("Charles "), seq.subSeq(7, 15)); assertEquals(CharSeq.of("Charles gets down and ends battle."), seq.subSeq(7, 41)); assertEquals(CharSeq.of("."), seq.subSeq(40)); assertEquals(CharSeq.of(""), seq.subSeq(41)); assertEquals(CharSeq.of("Father Charles gets down and ends battle."), seq.subSeq(0)); } @Test public void testLength() { CharSeq seq = CharSeq.of("The quick brown fox jumps over a lazy dog"); assertEquals(41, seq.length()); CharSeq emptySeq = CharSeq.of(""); assertEquals(0, emptySeq.length()); } @Test public void testCapitalize() { CharSeq seq = CharSeq.of("the Quick Brown FoX JumpS Over A lazy dog"); assertEquals(CharSeq.of("The quick brown fox jumps over a lazy dog"), seq.capitalize()); assertEquals(CharSeq.of(""), CharSeq.of("").capitalize()); } @Test public void testToLowerCase() { assertEquals(CharSeq.of("the quick brown fox jumps over a lazy dog"), CharSeq.of("THE QUICK BROWN FOX JUMPS OVER A LAZY DOG").toLowerCase()); assertEquals(CharSeq.of(""), CharSeq.of("").toLowerCase()); } @Test public void testConcatAndPrepend() { CharSeq seq = CharSeq.of("I'm a rich man"); assertEquals(CharSeq.of("I'm a rich man, am I?"), seq.concat(CharSeq.of(", am I?"))); assertEquals(CharSeq.of("I'm a rich man, am I? Of course!"), seq.concat(", am I? Of course!")); assertEquals(CharSeq.of("Do you think I'm a rich man?"), seq.concat("?").prepend(CharSeq.of("Do you think "))); assertEquals(CharSeq.of("Don't you think I'm a rich man?"), seq.concat("?").prepend("Don't you think ")); } @Test public void testReverse() { assertEquals(CharSeq.of(""), CharSeq.of("").reverse()); assertEquals(CharSeq.of("was i tac a ro rac a ti saw"), CharSeq.of("was it a car or a cat i saw").reverse()); } @Test public void testSwapcase() { assertEquals(CharSeq.of(""), CharSeq.of("").swapcase()); assertEquals(CharSeq.of("tHe QuIck bRown fOx jumpS ovEr a laZy DoG"), CharSeq.of("ThE qUiCK BrOWN FoX JUMPs OVeR A LAzY dOg").swapcase()); } @Test public void testSplit() { assertArrayEquals(new CharSeq[]{CharSeq.of("021"), CharSeq.of("50242132")}, CharSeq.of("021 50242132").split("[- ]").toArray()); assertArrayEquals(new CharSeq[]{CharSeq.of("021"), CharSeq.of("50242132")}, CharSeq.of("021-50242132").split("[- ]").toArray()); assertArrayEquals(new CharSeq[]{CharSeq.of("021_50242132")}, CharSeq.of("021_50242132").split("[- ]").toArray()); } @Test public void testStartsWithAndEndsWith() { assertTrue(CharSeq.of("021 50242132").startsWith(CharSeq.of("021"))); assertFalse(CharSeq.of("021 50242132").startsWith(CharSeq.of("021 502421321"))); assertFalse(CharSeq.of("021 50242132").endsWith(CharSeq.of("232"))); } @Test public void testTrim() { assertEquals(CharSeq.of("With prefix blanking"), CharSeq.of(" With prefix blanking").trim()); assertEquals(CharSeq.of("With no blanking"), CharSeq.of("With no blanking").trim()); assertEquals(CharSeq.of("With suffix blanking"), CharSeq.of("With suffix blanking ").trim()); assertEquals(CharSeq.of("With both side blanking"), CharSeq.of(" With both side blanking ").trim()); } @Test public void testScan() { CharSeq seq = CharSeq.of("ATE@ShangHai Works Applications"); assertArrayEquals(new CharSeq[]{CharSeq.of("ATE"), CharSeq.of("ShangHai"), CharSeq.of("Works"), CharSeq.of("Applications")}, seq.scan("\\w+").toArray()); assertArrayEquals(new CharSeq[]{CharSeq.of("ATE@ShangHai"), CharSeq.of("Works"), CharSeq.of("Applications")}, seq.scan("[\\w@]+").toArray()); } @Test public void testPartition() { CharSeq seq = CharSeq.of("var sample = 'Good good study, day day up.'"); assertArrayEquals(new CharSeq[]{CharSeq.of("var sample "), CharSeq.of("="), CharSeq.of(" 'Good good study, day day up.'")}, seq.partition("=").toArray()); CharSeq seq1 = CharSeq.of("_word"); assertArrayEquals(new CharSeq[]{CharSeq.of(""), CharSeq.of("_word"), CharSeq.of("")}, seq1.partition("\\w+").toArray()); assertArrayEquals(new CharSeq[]{CharSeq.of(""), CharSeq.of(""), CharSeq.of("_word")}, seq1.partition("\\W+").toArray()); CharSeq seq2 = CharSeq.of("hello"); assertArrayEquals(new CharSeq[]{CharSeq.of("he"), CharSeq.of("l"), CharSeq.of("lo")}, seq2.partition("l").toArray()); assertArrayEquals(new CharSeq[]{CharSeq.of("hel"), CharSeq.of("l"), CharSeq.of("o")}, seq2.rPartition("l").toArray()); assertArrayEquals(new CharSeq[]{CharSeq.of(""), CharSeq.of(""), CharSeq.of("hello")}, seq2.rPartition("no").toArray()); } @Test public void testGetLines() { CharSeq seq = CharSeq.of("凤凰台上凤凰游,凤去台空江自流。\n" + "吴宫花草埋幽径,晋代衣冠成古丘。\n" + "三山半落青天外,二水中分白鹭洲。\r\n" + "总为浮云能蔽日,长安不见使人愁。"); assertArrayEquals(new CharSeq[]{ CharSeq.of("凤凰台上凤凰游,凤去台空江自流。"), CharSeq.of("吴宫花草埋幽径,晋代衣冠成古丘。"), CharSeq.of("三山半落青天外,二水中分白鹭洲。"), CharSeq.of("总为浮云能蔽日,长安不见使人愁。") }, seq.eachLine().toArray()); } @Test public void testCompare() { assertTrue(CharSeq.of("Good Boy").compareTo(CharSeq.of("good boy")) < 0); assertTrue(CharSeq.of("Good Boy").compareToIgnoreCase(CharSeq.of("good boy")) == 0); } @Test public void testReplace() { CharSeq seq = CharSeq.of("PhoneNumbers: 021-55831183, 010-55131123, 020-11239901"); assertEquals(CharSeq.of("PhoneNumbers: 025-55831183, 010-55131123, 020-11239901"), seq.replaceFirst("\\d{3}-", CharSeq.of("025-"))); assertEquals(CharSeq.of("PhoneNumbers: 025-55831183, 025-55131123, 025-11239901"), seq.replaceAll("\\d{3}-", CharSeq.of("025-"))); } @Test public void testMatches() { String regex = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*" + "@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; assertTrue(CharSeq.of("ljxnegod@hotmail.com").matches(regex)); assertFalse(CharSeq.of("ljxnegod@1").matches(regex)); assertFalse(CharSeq.of("ljxnegod@1 ").matches(regex)); assertFalse(CharSeq.of("ljxnegod@1..com.cn").matches(regex)); } @Test public void testEachLines() { CharSeq seq = CharSeq.of("凤凰台上凤凰游,凤去台空江自流。\r\n" + "吴宫花草埋幽径,晋代衣冠成古丘。\n" + "三山半落青天外,二水中分白鹭洲。\n" + "总为浮云能蔽日,长安不见使人愁。"); CharSeq seq2 = CharSeq.of("凤凰台上凤凰游,凤去台空江自流。\r\n" + "三山半落青天外,二水中分白鹭洲。\n"); MutableSeq<CharSeq> result = Seqs.newMutableSeq(); seq.forEachLine((Consumer<CharSeq>) result::appendInPlace); assertEquals(seq.eachLine(), result); MutableSeq<CharSeq> result2 = Seqs.newMutableSeq(); seq.forEachLine((c, i) -> { if (i % 2 == 0) { result2.appendInPlace(c); } }); assertEquals(seq2.eachLine(), result2); } @Test public void testEachChar() { CharSeq seq = CharSeq.of("Albert"); Character[] increased = new Character[]{'B', 'm', 'c', 'f', 's', 'u'}; List<Character> chars = new ArrayList<>(); seq.forEachChar(ch -> chars.add((char) (ch + 1))); assertArrayEquals(increased, chars.toArray()); seq.forEachChar((ch, index) -> assertEquals(new Character((char) (ch + 1)), increased[index])); } @Test public void testEachByte() { String einstein = "Einstein"; CharSeq seq = CharSeq.of(einstein); MutableSeq<Byte> bytes = Seqs.newMutableSeq(); seq.forEachByte((Consumer<Byte>) bytes::appendInPlace); seq.forEachByte((b, i) -> assertEquals(new Character((char) (b.byteValue())), seq.charAt(i))); } @Test public void testEachCodePoint() { CharSeq cs = CharSeq.of("hello\u0639"); MutableSeq<Integer> codePoints = Seqs.newMutableSeq(); cs.forEachCodePoint(codePoints::appendInPlace); assertEquals(6, cs.length()); assertEquals(6, cs.eachCodePoint().size()); assertEquals(Seqs.newMutableSeq(104, 101, 108, 108, 111, 1593), codePoints); assertEquals(Seqs.newMutableSeq(), CharSeq.of("").eachCodePoint()); Helpers.assertThrows(NullPointerException.class, () -> cs.forEachCodePoint(null)); } @Test public void testEquals() { CharSeq cs = CharSeq.of("Hello World!"); assertFalse(cs.equals(null)); assertFalse(cs.equals("Hello World!")); assertTrue(cs.equals(CharSeq.of("Hello World!"))); assertFalse(cs.equals(CharSeq.of("Hello!"))); } @Test public void testContainSubSeq() { assertTrue(CharSeq.of("BBC ABCDAB ABCDABCDABDE") .containsSubSeq("ABCDABD")); assertTrue(CharSeq.of("BBC ABCDAB ABCDABCDABDE") .containsSubSeq(CharSeq.of("ABCDABD"))); assertFalse(CharSeq.of("BBC ABCDAB ABCDABCDABDE") .containsSubSeq("ABCDABA")); assertFalse(CharSeq.of("BBC ABCDAB ABCDABCDABDE") .containsSubSeq(CharSeq.of("ABCDABA"))); assertFalse(CharSeq.of("A") .containsSubSeq("B")); assertFalse(CharSeq.of("") .containsSubSeq("B")); assertEquals(-1, CharSeq.of("").lastIndexOfSubSeq(CharSeq.of("A"))); assertEquals(-1, CharSeq.of("AB").lastIndexOfSubSeq("CB")); assertEquals(-1, CharSeq.of("AAB").lastIndexOfSubSeq("CB")); assertEquals(0, CharSeq.of("A").lastIndexOfSubSeq(CharSeq.of(""))); assertTrue(CharSeq.of("A") .containsSubSeq(CharSeq.of(""))); assertTrue(CharSeq.of("ABC") .containsSubSeq("ABC")); Helpers.assertThrows(NullPointerException.class, () -> CharSeq.of("ABC").containsSubSeq((String) null)); Helpers.assertThrows(NullPointerException.class, () -> CharSeq.of("ABC").containsSubSeq((CharSeq) null)); assertEquals(15, CharSeq.of("BBC ABCDAB ABCDABCDABDE") .indexOfSubSeq("ABCDABD")); assertEquals(15, CharSeq.of("BBC ABCDAB ABCDABCDABDE") .lastIndexOfSubSeq("ABCDABD")); assertEquals(1, CharSeq.of("31212123") .indexOfSubSeq("1212")); assertEquals(3, CharSeq.of("31212123") .lastIndexOfSubSeq("1212")); Helpers.assertThrows(NullPointerException.class, () -> CharSeq.of("ABC").indexOfSubSeq((String) null)); Helpers.assertThrows(NullPointerException.class, () -> CharSeq.of("ABC").lastIndexOfSubSeq((String) null)); Helpers.assertThrows(NullPointerException.class, () -> CharSeq.of("ABC").indexOfSubSeq((CharSeq) null)); Helpers.assertThrows(NullPointerException.class, () -> CharSeq.of("ABC").lastIndexOfSubSeq((CharSeq) null)); } }
java
Apache-2.0
60bcc893c80c27f61335696819a8ae261ac339c7
2026-01-05T02:37:21.030242Z
false
WorksApplications/icefig
https://github.com/WorksApplications/icefig/blob/60bcc893c80c27f61335696819a8ae261ac339c7/src/test/java/com/worksap/icefig/lang/HashTest.java
src/test/java/com/worksap/icefig/lang/HashTest.java
/* * Copyright (C) 2015 The Fig Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.worksap.icefig.lang; import com.worksap.icefig.lang.*; import org.junit.Test; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Objects; import static org.junit.Assert.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Created by lijunxiao on 8/6/15. */ public class HashTest { @Test public void testConstruction() { MutableHash<String, String> hash = Hashes.newMutableHash(); assertTrue(hash.size() == 0); assertTrue(hash.isEmpty()); hash.putInPlace("23", "Micheal Jordan"); hash.putInPlace("24", "Kobe Bryant"); assertEquals(hash.size(), 2); assertEquals(hash.get("24"), "Kobe Bryant"); assertNull(hash.get("25")); hash.putInPlace("1", "Allen Iverson"); assertEquals(hash.size(), 3); hash.putIfAbsentInPlace("1", "Tracy McGrady"); assertEquals(hash.get("1"), "Allen Iverson"); hash.putInPlace("1", "Tracy McGrady"); assertEquals(hash.get("1"), "Tracy McGrady"); hash.removeInPlace("23"); assertEquals(hash.size(), 2); assertNull(hash.get("23")); assertEquals(0, hash.clear().size()); assertEquals(Hashes.newMutableHash(), hash); Hash<String, String> hash1 = Hashes.<String, String>newHash().put("3", "Chris Paul").put("30", "Stephen Curry"); assertEquals(2, hash1.size()); assertEquals(3, hash1.put("7", "Carmelo Anthony").size()); assertEquals(2, hash1.size()); assertEquals("Chris Paul", hash1.putIfAbsent("3", "Li").get("3")); assertEquals(1, hash1.remove("3").size()); assertEquals(null, hash1.remove("3").get("3")); assertEquals("Chris Paul", hash1.get("3")); HashMap<String, String> map = new HashMap<>(); map.put("key", "value"); Hash<String, String> hash2 = Hashes.<String, String>newHash().put("key", "value"); assertEquals(map, hash2.toHashMap()); } @Test public void testContainsAny() { MutableHash<Integer, Integer> hash = Hashes.newMutableHash(new HashMap<>()); hash.putInPlace(1, 2).putInPlace(2, 4).putInPlace(5, 1); assertTrue(hash.containsAny((k, v) -> k + v == 3)); assertTrue(hash.containsAny((k, v) -> k + v == 6)); assertFalse(hash.containsAny((k, v) -> k + v == 5)); Helpers.assertThrows(NullPointerException.class, () -> hash.containsAny(null)); } @Test public void testInvert() { Hash<String, String> hash = Hashes.<String, String>newHash(new HashMap<>()).put("en", "British English").put("ja", "Japanese"). put("zh", "Chinese").put("zh-CN", "Chinese"); Hash<String, String> invertedHash = hash.invert(); assertEquals(invertedHash.size(), 3); assertEquals(invertedHash.get("British English"), "en"); assertEquals(invertedHash.get("Japanese"), "ja"); assertEquals(invertedHash.get("Chinese"), "zh"); } @Test public void testReject(){ Hash<Integer, Integer> hash = Hashes.<Integer, Integer>newHash().put(1, 2).put(2, 4).put(5, 1); Hash<Integer, Integer> rejected = Hashes.<Integer, Integer>newHash().put(2, 4).put(5, 1); assertTrue(rejected.equals(hash.reject((k, v) -> k + v != 6))); assertEquals(Hashes.newHash(), hash.reject((k, v) -> !Objects.equals(k, v))); assertNotEquals(Hashes.newHash(), hash); Helpers.assertThrows(NullPointerException.class, () -> hash.reject(null)); } @Test public void testFilter(){ Hash<Integer, Integer> hash = Hashes.<Integer, Integer>newHash().put(1, 2).put(2, 4).put(5, 1); Hash<Integer, Integer> origin = Hashes.<Integer, Integer>newHash().put(1, 2).put(2, 4).put(5, 1); assertEquals(origin, hash); Hash<Integer, Integer> filtered = Hashes.<Integer, Integer>newHash().put(1, 2); assertTrue(filtered.equals(hash.filter((k, v) -> k + v != 6))); assertFalse(filtered.equals(hash)); assertEquals(origin, hash); assertEquals(Hashes.newHash(), hash.filter(Objects::equals)); assertNotEquals(Hashes.newHash(), hash); assertEquals(origin, hash); Helpers.assertThrows(NullPointerException.class, () -> hash.filter(null)); } @Test public void testRejectInplace() { MutableHash<Integer, Integer> hash = Hashes.newMutableHash(); hash.putInPlace(1, 2).putInPlace(2, 4).putInPlace(5, 1); assertEquals(2, hash.rejectInPlace((k, v) -> k > 1 && v > 1).size()); assertEquals(2, hash.size()); assertEquals(null, hash.get(2)); assertEquals(2, hash.rejectInPlace(Objects::equals).size()); assertEquals(Hashes.newHash(), hash.rejectInPlace((k, v) -> !Objects.equals(k, v))); Helpers.assertThrows(NullPointerException.class, () -> hash.rejectInPlace(null)); } @Test public void testFilterInplace() { MutableHash<Integer, Integer> hash = Hashes.<Integer, Integer>newMutableHash(); hash.putInPlace(1, 2).putInPlace(2, 4).putInPlace(5, 1); assertEquals(3, hash.size()); assertEquals(2, hash.filterInPlace((k, v) -> !(k > 1 && v > 1)).size()); assertEquals(null, hash.get(2)); assertEquals(2, hash.filterInPlace((k, v) -> !Objects.equals(k, v)).size()); assertEquals(Hashes.newHash(), hash.filterInPlace(Objects::equals)); Helpers.assertThrows(NullPointerException.class, () -> hash.filterInPlace(null)); } @Test public void testKeysOf() { Hash<Integer, Integer> hash = Hashes.<Integer, Integer>newHash().put(1, 2).put(2, 4).put(3, 2).put(4, null).put(5, 1); Seq<Integer> keys = hash.keysOf(2); keys.sort(Integer::compare); assertEquals(Seqs.newSeq(1, 3), keys); assertEquals(Seqs.newSeq(2), hash.keysOf(4)); assertEquals(Seqs.newSeq(), hash.keysOf(3)); assertEquals(Seqs.newSeq(4), hash.keysOf(null)); } @Test public void testMerge() { Hash<Integer, Integer> hash1 = Hashes.<Integer, Integer>newHash().put(1, 2).put(2, 4); Hash<Integer, Integer> origin1 = Hashes.<Integer, Integer>newHash().put(1, 2).put(2, 4); Hash<Integer, Integer> hash2 = Hashes.<Integer, Integer>newHash().put(3, 2).put(2, 3); Hash<Integer, Integer> origin2 = Hashes.<Integer, Integer>newHash().put(3, 2).put(2, 3); Hash<Integer, Integer> merged = Hashes.<Integer, Integer>newHash().put(1, 2).put(2, 3).put(3, 2); assertEquals(merged, hash1.merge(hash2)); assertEquals(origin1, hash1); assertEquals(origin2, hash2); merged = merged.put(2, 4); assertEquals(merged, hash2.merge(hash1)); assertEquals(origin1, hash1); assertEquals(origin2, hash2); assertEquals(origin1, hash1.merge(Hashes.newHash())); assertEquals(origin1, Hashes.newHash().merge(hash1)); assertEquals(origin1, hash1.merge(null)); hash1 = hash1.put(null, 1); merged = merged.put(null, 1); merged = merged.put(2, 3); assertEquals(merged, hash1.merge(hash2)); } @Test public void testMergeInplace() { MutableHash<Integer, Integer> hash1 = Hashes.newMutableHash(); hash1.putInPlace(1, 2).putInPlace(2, 4); MutableHash<Integer, Integer> origin1 = Hashes.newMutableHash(); origin1.putInPlace(1, 2).putInPlace(2, 4); MutableHash<Integer, Integer> hash2 = Hashes.newMutableHash(); hash2.putInPlace(3, 2).putInPlace(2, 3); MutableHash<Integer, Integer> origin2 = Hashes.newMutableHash(); origin2.putInPlace(3, 2).putInPlace(2, 3); MutableHash<Integer, Integer> merged = Hashes.newMutableHash(); merged.putInPlace(1, 2).putInPlace(2, 3).putInPlace(3, 2); assertEquals(merged, hash1.mergeInPlace(hash2)); assertEquals(merged, hash1); assertEquals(origin2, hash2); hash1 = Hashes.newMutableHash(); hash1.putInPlace(1, 2).putInPlace(2, 4); merged.putInPlace(2, 4); assertEquals(merged, hash2.mergeInPlace(hash1)); assertEquals(origin1, hash1); assertEquals(merged, hash2); hash2 = Hashes.newMutableHash(); hash2.putInPlace(3, 2).putInPlace(2, 3); assertEquals(origin1, hash1.merge(Hashes.newHash())); assertEquals(origin1, Hashes.newHash().merge(hash1)); assertEquals(origin1, hash1.mergeInPlace(null)); hash1.putInPlace(null, 1); merged.putInPlace(null, 1); merged.putInPlace(2, 3); assertEquals(merged, hash1.mergeInPlace(hash2)); } @Test public void testKeysValues() { Hash<Integer, Integer> hash = Hashes.newHash(); assertEquals(Seqs.newSeq(), hash.keys()); assertEquals(Seqs.newSeq(), hash.values()); hash = hash.put(1, null).put(null, 1); assertEquals(2, hash.keys().size()); assertTrue(hash.keys().contains(null)); assertTrue(hash.keys().contains(1)); assertEquals(2, hash.values().size()); assertTrue(hash.values().contains(null)); assertTrue(hash.values().contains(1)); assertTrue(hash.containsKey(1)); assertTrue(hash.containsKey(null)); assertTrue(hash.containsValue(1)); assertTrue(hash.containsValue(null)); assertFalse(hash.containsValue(2)); assertFalse(hash.containsKey(2)); } @Test public void testEquals() { Hash<Integer, Integer> hash = Hashes.<Integer, Integer>newHash().put(1, 2).put(3, 4); Hash<Integer, Integer> hash2 = hash; Hash<Integer, Integer> hash3 = Hashes.<Integer, Integer>newHash().put(1, 2).put(3, 4); assertTrue(hash.equals(hash2)); assertFalse(hash.equals(null)); assertTrue(hash.equals(hash3)); } @Test public void testPrivateConstructor() throws Exception { Constructor constructor = Hashes.class.getDeclaredConstructor(); assertTrue("Constructor is not private", Modifier.isPrivate(constructor.getModifiers())); constructor.setAccessible(true); constructor.newInstance(); } @Test public void testRemove() { Hash<Integer, Integer> hash = Hashes.<Integer, Integer>newHash().put(1, 2).put(3, 4); assertEquals(2, hash.size()); Hash<Integer, Integer> another = hash.remove(1); assertEquals(2, hash.size()); assertEquals(1, another.size()); another = hash.remove(1, 3); assertEquals(2, hash.size()); assertEquals(2, another.size()); another = hash.remove(2, 2); assertEquals(2, hash.size()); assertEquals(2, another.size()); another = hash.remove(1, 2); assertEquals(2, hash.size()); assertEquals(1, another.size()); MutableHash<Integer, Integer> mutableHash = Hashes.<Integer, Integer>newMutableHash().putInPlace(1, 2).putInPlace(3, 4); assertEquals(2, mutableHash.size()); MutableHash<Integer, Integer> anotherMutableHash = mutableHash.removeInPlace(1); assertEquals(1, mutableHash.size()); assertEquals(1, anotherMutableHash.size()); mutableHash.putInPlace(1, 2); anotherMutableHash = mutableHash.removeInPlace(1, 3); assertEquals(2, mutableHash.size()); assertEquals(2, anotherMutableHash.size()); anotherMutableHash = mutableHash.removeInPlace(2, 2); assertEquals(2, mutableHash.size()); assertEquals(2, anotherMutableHash.size()); anotherMutableHash = mutableHash.removeInPlace(1, 2); assertEquals(1, mutableHash.size()); assertEquals(1, anotherMutableHash.size()); } @Test public void testReplace() { Hash<Integer, Integer> hash = Hashes.<Integer, Integer>newHash().put(1, 2).put(3, 4); Hash<Integer, Integer> another = hash.replace(1, 3); assertEquals(new Integer(2), hash.get(1)); assertEquals(new Integer(3), another.get(1)); another = hash.replace(4, 3); assertNull(hash.get(4)); assertNull(another.get(4)); another = hash.replace(1, 2, 10); assertEquals(new Integer(2), hash.get(1)); assertEquals(new Integer(10), another.get(1)); another = hash.replace(1, 3, 11); assertEquals(new Integer(2), hash.get(1)); assertEquals(new Integer(2), another.get(1)); another = hash.replaceAll((k, v) -> k + v); assertEquals(new Integer(2), hash.get(1)); assertEquals(new Integer(3), another.get(1)); hash = hash.put(null, null); another = hash.replace(null, 1); assertEquals(null, hash.get(null)); assertEquals(new Integer(1), another.get(null)); another = hash.replace(null, null, 1); assertEquals(null, hash.get(null)); assertEquals(new Integer(1), another.get(null)); MutableHash<Integer, Integer> mutableHash = Hashes.<Integer, Integer>newMutableHash().putInPlace(1, 2).putInPlace(3, 4); MutableHash<Integer, Integer> anotherMutableHash = mutableHash.replaceInPlace(1, 3); assertEquals(new Integer(3), mutableHash.get(1)); assertEquals(new Integer(3), anotherMutableHash.get(1)); anotherMutableHash = mutableHash.replaceInPlace(4, 3); assertNull(mutableHash.get(4)); assertNull(anotherMutableHash.get(4)); anotherMutableHash = mutableHash.replaceInPlace(1, 3, 10); assertEquals(new Integer(10), mutableHash.get(1)); assertEquals(new Integer(10), anotherMutableHash.get(1)); anotherMutableHash = mutableHash.replaceInPlace(1, 3, 11); assertEquals(new Integer(10), mutableHash.get(1)); assertEquals(new Integer(10), anotherMutableHash.get(1)); anotherMutableHash = mutableHash.replaceAllInPlace((k, v) -> k + v); assertEquals(new Integer(11), mutableHash.get(1)); assertEquals(new Integer(11), anotherMutableHash.get(1)); mutableHash.putInPlace(null, null); anotherMutableHash = mutableHash.replaceInPlace(null, 3); assertEquals(new Integer(3), mutableHash.get(null)); assertEquals(new Integer(3), anotherMutableHash.get(null)); anotherMutableHash = mutableHash.replaceInPlace(null, null, 3); assertEquals(new Integer(3), mutableHash.get(null)); assertEquals(new Integer(3), anotherMutableHash.get(null)); } @Test public void testCount() { Hash<Integer, Integer> hash = Hashes.<Integer, Integer>newHash().put(1, 2).put(2, 2).put(3, 4).put(null, null); assertEquals(1, hash.count(4)); assertEquals(2, hash.count(2)); assertEquals(0, hash.count(3)); assertEquals(1, hash.count(null)); assertEquals(2, hash.countIf((k, v) -> k != null && v < 3)); MutableHash<Integer, Integer> mutableHash = Hashes.<Integer, Integer>newMutableHash().putInPlace(1, 2).putInPlace(2, 2).putInPlace(3, 4); assertEquals(1, mutableHash.count(4)); assertEquals(2, mutableHash.count(2)); assertEquals(0, mutableHash.count(3)); assertEquals(2, mutableHash.countIf((k, v) -> v < 3)); } }
java
Apache-2.0
60bcc893c80c27f61335696819a8ae261ac339c7
2026-01-05T02:37:21.030242Z
false
WorksApplications/icefig
https://github.com/WorksApplications/icefig/blob/60bcc893c80c27f61335696819a8ae261ac339c7/src/test/java/com/worksap/icefig/lang/RangeTest.java
src/test/java/com/worksap/icefig/lang/RangeTest.java
/* * Copyright (C) 2015 The Fig Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.worksap.icefig.lang; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.function.BiFunction; import java.util.function.Function; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class RangeTest { @Test public void testConstruct() { Range<Integer> range = new Range<>(1); assertThat(range.getFrom(), is(1)); range = new Range<>(2, 10, i -> i + 2); assertThat(range.getFrom(), is(2)); assertThat(range.getTo(), is(10)); assertThat(range.isToIncluded(), is(true)); } @Test public void testFrom() { assertThat(new Range<>(1).from(2).getFrom(), is(2)); Helpers.assertThrows(NullPointerException.class, () -> new Range<>("").from(null)); } @Test public void testTo() { Range<Character> range = new Range<>('a').to('z'); assertThat(range.getTo(), is('z')); assertThat(range.isToIncluded(), is(true)); Helpers.assertThrows(NullPointerException.class, () -> new Range<>("").to(null)); } @Test public void testUntil() { Range<Character> range = new Range<>('a').until('z'); assertThat(range.getTo(), is('z')); assertThat(range.isToIncluded(), is(false)); Helpers.assertThrows(NullPointerException.class, () -> new Range<>("").until(null)); } @Test public void testNext() { Function<String, String> next = null; Helpers.assertThrows(NullPointerException.class, () -> new Range<>("").next(next)); BiFunction<String, Integer, String> biNext = null; Helpers.assertThrows(NullPointerException.class, () -> new Range<>("").next(biNext)); } @Test public void testForEach() { List<Integer> list = new ArrayList<>(); new Range<>(1).to(64).next(i -> i + i).forEach(e -> list.add(e)); assertThat(list, equalTo(Arrays.asList(1, 2, 4, 8, 16, 32, 64))); list.clear(); new Range<>(1).until(64).next(i -> i + i).forEach(e -> list.add(e)); assertThat(list, equalTo(Arrays.asList(1, 2, 4, 8, 16, 32))); list.clear(); new Range<>(64).to(1).next(i -> i / 2).forEach(e -> list.add(e)); assertThat(list, equalTo(Arrays.asList(64, 32, 16, 8, 4, 2, 1))); list.clear(); new Range<>(1).to(1).next(i -> i + i).forEach(e -> list.add(e)); assertThat(list, equalTo(Arrays.asList(1))); list.clear(); new Range<>(1).until(1).next(i -> i + i).forEach(e -> list.add(e)); assertThat(list, equalTo(Collections.emptyList())); list.clear(); List<Integer> indices = new ArrayList<>(); new Range<>(1).until(64).next(i -> i + i) .forEach((e, i) -> { list.add(e); indices.add(i); }); assertThat(list, equalTo(Arrays.asList(1, 2, 4, 8, 16, 32))); assertThat(indices, equalTo(Arrays.asList(0, 1, 2, 3, 4, 5))); list.clear(); new Range<>(1).to(720).next((c, i) -> c * (i + 2)).forEach(e -> list.add(e)); assertThat(list, equalTo(Arrays.asList(1, 2, 6, 24, 120, 720))); list.clear(); new Range<>(1).to(5).next(i -> i + 1).next((c, i) -> c * (i + 2)).forEach(e -> list.add(e)); assertThat(list, equalTo(Arrays.asList(1, 2, 3, 4, 5))); list.clear(); Helpers.assertThrows(NullPointerException.class, () -> new Range<>(1).to(10).forEach(e -> list.add(e))); } @Test public void testToSeq() { assertThat(new Range<>(1).to(1).next(i -> i + 1).toSeq(), is(equalTo(Seqs.newSeq(1)))); assertThat(new Range<>(1).until(1).next(i -> i + 1).toSeq(), is(equalTo(Seqs.newSeq()))); assertThat(new Range<>('a').to('e').next(c -> (char) (c + 1)).toSeq(), is(equalTo(Seqs.newSeq('a', 'b', 'c', 'd', 'e')))); assertThat(new Range<>(6).until(0).next(i -> i - 2).toSeq(), is(equalTo(Seqs.newSeq(6, 4, 2)))); } @Test public void testToMutableSeq() { assertThat(new Range<>(1).to(5).next(i -> i + 1).toMutableSeq(), is(equalTo(Seqs.newMutableSeq(1, 2, 3, 4, 5)))); } @Test public void testIterator() { Iterator<Integer> itr = new Range<>(1).to(1).next(i -> i + 1).iterator(); assertThat(itr.next(), is(1)); assertThat(itr.hasNext(), is(false)); final Iterator<Integer> it = itr; Helpers.assertThrows(NoSuchElementException.class, () -> it.next()); itr = new Range<>(1).to(2).next(i -> i + 1).iterator(); assertThat(itr.next(), is(1)); assertThat(itr.next(), is(2)); assertThat(itr.hasNext(), is(false)); itr = new Range<>(1).next(i -> i + 1).iterator(); assertThat(itr.hasNext(), is(true)); for (int i = 0; i < 100; i++) { itr.next(); } assertThat(itr.next(), is(101)); assertThat(itr.hasNext(), is(true)); List<Integer> list = new ArrayList<>(); for (int d: new Range<>(1).next(i -> i + 1).until(5)) { list.add(d); } assertThat(list, equalTo(Arrays.asList(1, 2, 3, 4))); } @Test public void testSpliterator() { Helpers.assertThrows(IllegalArgumentException.class, () -> new Range<>(1).next(i -> i + 1).take(-1)); } @Test public void testTake() { assertThat(new Range<>(1).next(i -> i + 1).take(0), equalTo(Seqs.newMutableSeq())); assertThat(new Range<>(1).next(i -> i + 1).take(5), equalTo(Seqs.newMutableSeq(1, 2, 3, 4, 5))); assertThat(new Range<>(1).next(i -> i + 1).to(3).take(5), equalTo(Seqs.newMutableSeq(1, 2, 3))); Helpers.assertThrows(UnsupportedOperationException.class, () -> new Range<>(1).spliterator()); } @Test public void testTakeWhile() { assertThat(new Range<>(1).next(i -> i + 1).takeWhile(e -> e <= 5), equalTo(Seqs.newMutableSeq(1, 2, 3, 4, 5))); assertThat(new Range<>(1).next(i -> i + 1).takeWhile(e -> e < 1), equalTo(Seqs.newMutableSeq())); assertThat(new Range<>(1).next(i -> i + 1).until(1).takeWhile(e -> e <= 5), equalTo(Seqs.newMutableSeq())); assertThat(new Range<>(1).next(i -> i + 1).takeWhile((e, i) -> i < 5), equalTo(Seqs.newMutableSeq(1, 2, 3, 4, 5))); assertThat(new Range<>(1).next(i -> i + 1).takeWhile((e, i) -> i < 0), equalTo(Seqs.newMutableSeq())); assertThat(new Range<>(1).next(i -> i + 1).until(1).takeWhile((e, i) -> i < 5), equalTo(Seqs.newMutableSeq())); List<Integer> indices = new ArrayList<>(); assertThat(new Range<>(1).next(i -> i + i) .takeWhile((e, i) -> { indices.add(i); return e < 64; }), equalTo(Seqs.newMutableSeq(1, 2, 4, 8, 16, 32))); assertThat(indices, equalTo(Arrays.asList(0, 1, 2, 3, 4, 5, 6))); } }
java
Apache-2.0
60bcc893c80c27f61335696819a8ae261ac339c7
2026-01-05T02:37:21.030242Z
false
WorksApplications/icefig
https://github.com/WorksApplications/icefig/blob/60bcc893c80c27f61335696819a8ae261ac339c7/src/main/java/com/worksap/icefig/lang/HashImpl.java
src/main/java/com/worksap/icefig/lang/HashImpl.java
/* * Copyright (C) 2015 The Fig Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.worksap.icefig.lang; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.HashMap; import java.util.Objects; import java.util.function.BiFunction; import java.util.function.BiPredicate; /** * Created by lijunxiao on 8/6/15. */ class HashImpl<K, V> implements MutableHash<K, V> { private HashMap<K, V> hash; protected HashImpl() { this.hash = new HashMap<>(); } protected HashImpl(Map<? extends K, ? extends V> m) { this.hash = new HashMap<>(m); } @Override public boolean containsAny(BiPredicate<K, V> condition) { for (Map.Entry<K, V> entry : hash.entrySet()) { if (condition.test(entry.getKey(), entry.getValue())) { return true; } } return false; } @Override public boolean containsKey(K k) { return hash.containsKey(k); } @Override public boolean containsValue(V v) { return hash.containsValue(v); } @Override public boolean isEmpty() { return hash.isEmpty(); } @Override public boolean equals(Object o) { if (o == this) return true; if (o instanceof HashImpl) { HashImpl<K, V> h = (HashImpl<K, V>)o; return hash.equals(h.hash); } return false; } @Override public int size() { return hash.size(); } @Override public V get(K k) { return hash.get(k); } @Override public Seq<V> values() { return Seqs.newMutableSeq(hash.values()); } @Override public Seq<K> keys() { return Seqs.newMutableSeq(hash.keySet()); } @Override public Seq<Map.Entry<K, V>> entrySeq() { return Seqs.newMutableSeq(hash.entrySet()); } @Override public MutableHash<K, V> put(K k, V v) { Map<K, V> newHash = new HashMap<>(hash); newHash.put(k, v); return new HashImpl<>(newHash); } @Override public MutableHash<K, V> putIfAbsent(K k, V v) { Map<K, V> newHash = new HashMap<>(hash); newHash.putIfAbsent(k, v); return new HashImpl<>(newHash); } @Override public MutableHash<K, V> filter(BiPredicate<K, V> condition) { Objects.requireNonNull(condition); Map<K, V> newHash = new HashMap<>(); this.hash.forEach((k, v) -> { if (condition.test(k, v)) { newHash.put(k, v); } }); return new HashImpl<>(newHash); } @Override public MutableHash<K, V> reject(BiPredicate<K, V> condition) { Objects.requireNonNull(condition); Map<K, V> newHash = new HashMap<>(); hash.forEach((k, v) -> { if (!condition.test(k, v)) { newHash.put(k, v); } }); return new HashImpl<>(newHash); } @Override public MutableHash<V, K> invert() { Map<V, K> newHash = new HashMap<>(); hash.forEach((k, v) -> newHash.put(v, k)); return new HashImpl<>(newHash); } @Override public MutableHash<K, V> merge(Hash<? extends K, ? extends V> another) { Map<K, V> newHash = new HashMap<>(hash); if (another != null) { another.entrySeq().forEach(entry -> { newHash.put(entry.getKey(), entry.getValue()); }); } return new HashImpl<>(newHash); } @Override public MutableHash<K, V> remove(K k) { Map<K, V> newHash = new HashMap<>(hash); newHash.remove(k); return new HashImpl<>(newHash); } @Override public MutableHash<K, V> remove(K k, V v) { Map<K, V> newHash = new HashMap<>(hash); newHash.remove(k, v); return new HashImpl<>(newHash); } @Override public MutableHash<K, V> filterInPlace(BiPredicate<K, V> condition) { Objects.requireNonNull(condition); final Iterator<Map.Entry<K, V>> each = hash.entrySet().iterator(); while (each.hasNext()) { Map.Entry<K, V> nextEntry = each.next(); if (!condition.test(nextEntry.getKey(), nextEntry.getValue())) { each.remove(); } } return this; } @Override public MutableHash<K, V> rejectInPlace(BiPredicate<K, V> condition) { Objects.requireNonNull(condition); final Iterator<Map.Entry<K, V>> each = hash.entrySet().iterator(); while (each.hasNext()) { Map.Entry<K, V> nextEntry = each.next(); if (condition.test(nextEntry.getKey(), nextEntry.getValue())) { each.remove(); } } return this; } @Override public MutableHash<K, V> mergeInPlace(Hash<? extends K, ? extends V> another) { if (another != null) { another.entrySeq().forEach(entry -> { hash.put(entry.getKey(), entry.getValue()); }); } return this; } @Override public MutableHash<K, V> clear() { hash.clear(); return this; } @Override public MutableHash<K, V> replaceInPlace(K k, V v) { hash.replace(k, v); return this; } @Override public MutableHash<K, V> replaceInPlace(K k, V oldValue, V newValue) { hash.replace(k, oldValue, newValue); return this; } @Override public MutableHash<K, V> replaceAllInPlace(BiFunction<? super K, ? super V, ? extends V> function) { Objects.requireNonNull(function); hash.replaceAll(function); return this; } @Override public MutableHash<K, V> putInPlace(K k, V v) { hash.put(k, v); return this; } @Override public MutableHash<K, V> putIfAbsentInPlace(K k, V v) { hash.putIfAbsent(k, v); return this; } @Override public MutableHash<K, V> removeInPlace(K k) { hash.remove(k); return this; } @Override public MutableHash<K, V> removeInPlace(K k, V v) { hash.remove(k, v); return this; } @Override public Seq<K> keysOf(V value) { MutableSeq<K> result = Seqs.newMutableSeq(); hash.forEach((k, v) -> { if (value == null && v == null) result.appendInPlace(k); else if (value != null && v != null && v.equals(value)) result.appendInPlace(k); }); return result; } @Override public MutableHash<K, V> replace(K k, V v) { Map<K, V> newHash = new HashMap<>(hash); newHash.replace(k, v); return new HashImpl<>(newHash); } @Override public MutableHash<K, V> replace(K k, V oldValue, V newValue) { Map<K, V> newHash = new HashMap<>(hash); newHash.replace(k, oldValue, newValue); return new HashImpl<>(newHash); } @Override public MutableHash<K, V> replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { Objects.requireNonNull(function); Map<K, V> newHash = new HashMap<>(hash); newHash.replaceAll(function); return new HashImpl<>(newHash); } @Override public int count(V value) { return this.values().count(value); } @Override public int countIf(BiPredicate<K, V> condition) { Objects.requireNonNull(condition); int count = 0; final Iterator<Map.Entry<K, V>> each = hash.entrySet().iterator(); while (each.hasNext()) { Map.Entry<K, V> nextEntry = each.next(); if (condition.test(nextEntry.getKey(), nextEntry.getValue())) { count++; } } return count; } @Override public HashMap<K,V> toHashMap(){ return this.hash; } }
java
Apache-2.0
60bcc893c80c27f61335696819a8ae261ac339c7
2026-01-05T02:37:21.030242Z
false
WorksApplications/icefig
https://github.com/WorksApplications/icefig/blob/60bcc893c80c27f61335696819a8ae261ac339c7/src/main/java/com/worksap/icefig/lang/Seqs.java
src/main/java/com/worksap/icefig/lang/Seqs.java
/* * Copyright (C) 2015 The Fig Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.worksap.icefig.lang; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; /** * Factory class for construct Seq and MutableSeq */ public class Seqs { /** * Create an empty Seq */ public static <T> Seq<T> newSeq() { return new SeqImpl<>(); } /** * Create an Seq with the single value */ public static <T> Seq<T> newSeq(T value) { Collection<T> collection = new ArrayList<>(); collection.add(value); return new SeqImpl<>(collection); } /** * Create an Seq with the values */ @SuppressWarnings({"varargs", "unchecked"}) public static <T> Seq<T> newSeq(T... values) { return new SeqImpl<>(Arrays.asList(values)); } /** * Create an Seq with the single values inside the collection */ public static <T> Seq<T> newSeq(Collection<T> values) { return new SeqImpl<>(values); } /** * Create an empty MutableSeq */ public static <T> MutableSeq<T> newMutableSeq() { return new SeqImpl<>(); } /** * Create an MutableSeq with the single value */ public static <T> MutableSeq<T> newMutableSeq(T value) { Collection<T> collection = new ArrayList<>(); collection.add(value); return new SeqImpl<>(collection); } /** * Create an MutableSeq with the values */ @SuppressWarnings({"varargs", "unchecked"}) public static <T> MutableSeq<T> newMutableSeq(T... values) { return new SeqImpl<>(Arrays.asList(values)); } /** * Create an MutableSeq with the single values inside the collection */ public static <T> MutableSeq<T> newMutableSeq(Collection<T> values) { return new SeqImpl<>(values); } }
java
Apache-2.0
60bcc893c80c27f61335696819a8ae261ac339c7
2026-01-05T02:37:21.030242Z
false
WorksApplications/icefig
https://github.com/WorksApplications/icefig/blob/60bcc893c80c27f61335696819a8ae261ac339c7/src/main/java/com/worksap/icefig/lang/Hash.java
src/main/java/com/worksap/icefig/lang/Hash.java
/* * Copyright (C) 2015 The Fig Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.worksap.icefig.lang; import java.util.ConcurrentModificationException; import java.util.Map; import java.util.HashMap; import java.util.function.BiFunction; import java.util.function.BiPredicate; /** * Elegant supplement for Map in JDK */ public interface Hash<K, V> { /** * Check whether this hash contains any key-value pair that satisfies the condition. * * @param condition the condition used to filter key-value pairs by passing the key and value of the pair, * returns true if the key-value pair satisfies the condition, otherwise returns false. * @return whether this hash contains any key-value pair that satisfies the condition * @throws NullPointerException if condition is null */ boolean containsAny(BiPredicate<K, V> condition); /** * Returns <tt>true</tt> if this hash contains a mapping for the specified * key. More formally, returns <tt>true</tt> if and only if * this hash contains a mapping for a key <tt>k</tt> such that * <tt>(key==null ? k==null : key.equals(k))</tt>. (There can be * at most one such mapping.) * * @param key key whose presence in this hash is to be tested * @return <tt>true</tt> if this hash contains a mapping for the specified * key * @throws ClassCastException if the key is of an inappropriate type for * this map * @throws NullPointerException if the specified key is null and this map * does not permit null keys */ boolean containsKey(K key); boolean containsValue(V value); boolean isEmpty(); int size(); V get(K k); /** * Returns a {@link Seq} view of the values contained in this hash. * * @return a seq view of the values contained in this hash */ Seq<V> values(); /** * Returns a {@link Seq} view of the keys contained in this hash. * * @return a seq view of the keys contained in this hash */ Seq<K> keys(); /** * Returns a {@link Seq} view of the mappings contained in this hash. * * @return a seq view of the mappings contained in this hash */ Seq<Map.Entry<K, V>> entrySeq(); Hash<K, V> put(K k, V v); Hash<K, V> putIfAbsent(K k, V v); /** * Return a new hash with the key-value pairs of the original Hash which satisfy the condition. * * @param condition the condition used to filter key-value pairs by passing the key and value of the pair, * returns true if the key-value pair satisfies the condition, otherwise returns false. * @return a new with only key-value pairs which satisfy the condition * @throws NullPointerException if condition is null */ Hash<K, V> filter(BiPredicate<K, V> condition); /** * Return a new hash with the key-value pairs of the original Hash which don't satisfy the condition. * * @param condition the condition used to filter key-value pairs by passing the key and value of the pair, * returns true if the key-value pair satisfies the condition, otherwise returns false. * @return a new hash with key-value pairs which don't satisfy the condition * @throws NullPointerException if condition is null */ Hash<K, V> reject(BiPredicate<K, V> condition); /** * Returns a new hash created by using hash’s values as keys, and the keys as values. * If there are duplicated values, the last key is kept. * Since it is hash map, the order of keys is decided by hash table. * * @return an inverted hash */ Hash<V, K> invert(); /** * Returns a new hash containing the mappings of the specified hash and this hash itself. * The value for entries with duplicate keys will be that of the specified hash. * * @param another the specified hash to be merged * @return the new hash containing all the mappings of the specified hash and this hash itself */ Hash<K, V> merge(Hash<? extends K, ? extends V> another); /** * Removes the mapping for a key from this map if it is present * (optional operation). More formally, if this hash contains a mapping * from key <tt>k</tt> to value <tt>v</tt> such that * <code>(key==null ? k==null : key.equals(k))</code>, that mapping * is removed. (The map can contain at most one such mapping.) * * @param key key whose mapping is to be removed from the map * @return a new hash after the key is removed * @throws UnsupportedOperationException if the <tt>remove</tt> operation * is not supported by this hash * @throws ClassCastException if the key is of an inappropriate type for * this hash * @throws NullPointerException if the specified key is null and this * hash does not permit null keys */ Hash<K, V> remove(K key); /** * Removes the entry for the specified key only if it is currently * mapped to the specified value. * * @param key key with which the specified value is associated * @param value value expected to be associated with the specified key * @return a new hash after the entry is removed * @throws UnsupportedOperationException if the {@code remove} operation * is not supported by this hash * @throws ClassCastException if the key or value is of an inappropriate * type for this hash * @throws NullPointerException if the specified key or value is null, * and this map does not permit null keys or values */ Hash<K, V> remove(K key, V value); /** * Returns a Seq of keys of the given value. * * @param value the value * @return the collection of keys whose value is the given value */ Seq<K> keysOf(V value); /** * Replaces the entry for the specified key only if it is * currently mapped to some value. * * @param key key with which the specified value is associated * @param value value to be associated with the specified key * @return a new hash after the entry is replaced * @throws ClassCastException if the class of the specified key or value * prevents it from being stored in this hash * @throws NullPointerException if the specified key or value is null, * and this hash does not permit null keys or values * @throws IllegalArgumentException if some property of the specified key * or value prevents it from being stored in this hash */ Hash<K, V> replace(K key, V value); /** * Replaces the entry for the specified key only if currently * mapped to the specified value. * * @param key key with which the specified value is associated * @param oldValue value expected to be associated with the specified key * @param newValue value to be associated with the specified key * @return a new hash after the entry is replaced * @throws UnsupportedOperationException if the {@code put} operation * is not supported by this hash * @throws ClassCastException if the class of a specified key or value * prevents it from being stored in this hash * @throws NullPointerException if a specified key or newValue is null, * and this hash does not permit null keys or values * @throws NullPointerException if oldValue is null and this hash does not * permit null values * @throws IllegalArgumentException if some property of a specified key * or value prevents it from being stored in this hash */ Hash<K, V> replace(K key, V oldValue, V newValue); /** * Replaces each entry's value with the result of invoking the given * function on that entry until all entries have been processed or the * function throws an exception. Exceptions thrown by the function are * relayed to the caller. * * @param function the function to apply to each entry * @return a new hash after all the entries are replaced * @throws UnsupportedOperationException if the {@code set} operation * is not supported by this hash's entry set iterator. * @throws ClassCastException if the class of a replacement value * prevents it from being stored in this hash * @throws NullPointerException if the specified function is null, or the * specified replacement value is null, and this hash does not permit null * values * @throws ClassCastException if a replacement value is of an inappropriate * type for this hash * @throws NullPointerException if function or a replacement value is null, * and this hash does not permit null keys or values * @throws IllegalArgumentException if some property of a replacement value * prevents it from being stored in this hash * @throws ConcurrentModificationException if an entry is found to be * removed during iteration */ Hash<K, V> replaceAll(BiFunction<? super K, ? super V, ? extends V> function); /** * Returns the number of the specified value in this hash. * @param value the value to count * @return the number of the specified value in this hash */ int count(V value); /** * Returns the number of entries which satisfy the condition. * * @param condition the condition used to filter entries by passing the key and the value, * returns true if the entry satisfies the condition, otherwise returns false. * @return the number of entries which satisfy the condition * @throws NullPointerException if condition is null */ int countIf(BiPredicate<K, V> condition); HashMap<K,V> toHashMap(); }
java
Apache-2.0
60bcc893c80c27f61335696819a8ae261ac339c7
2026-01-05T02:37:21.030242Z
false
WorksApplications/icefig
https://github.com/WorksApplications/icefig/blob/60bcc893c80c27f61335696819a8ae261ac339c7/src/main/java/com/worksap/icefig/lang/Seq.java
src/main/java/com/worksap/icefig/lang/Seq.java
/* * Copyright (C) 2015 The Fig Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.worksap.icefig.lang; import java.util.*; import java.util.function.*; /** * Elegant supplement for List in JDK */ public interface Seq<T> { /** * Transform each element of the seq into another value using the same function, resulting a new seq without changing the original one. * * @return The new seq after transformation. * @throws NullPointerException if func is null */ <R> Seq<R> map(Function<T, R> func); /** * Similar to {@link #map(Function)}, with additional parameter "index" as the second parameter of the lambda expression. * * @throws NullPointerException if func is null */ <R> Seq<R> map(BiFunction<T, Integer, R> func); /** * Transform each element into a seq, and concat all seq together into a new seq. * * @return The new seq after transformation. * @throws NullPointerException if func is null */ <R> Seq<R> flatMap(Function<T, Seq<R>> func); /** * Similar to {@link #flatMap(Function)}, with additional parameter "index" as the second parameter of the lambda expression. * * @throws NullPointerException if func is null */ <R> Seq<R> flatMap(BiFunction<T, Integer, Seq<R>> func); /** * @return The beginning element of the seq. * @throws IndexOutOfBoundsException if the seq is empty */ default T first() { return get(0); } /** * @return The ending element of the seq. * @throws IndexOutOfBoundsException if the seq is empty */ default T last() { return get(size() - 1); } /** * Convert all elements into String, and connect each String together to a single String, following the same order of the seq. */ default CharSeq join() { return join(""); } /** * Convert all elements into String, and connect each String together to a single String, following the same order of the seq. * Insert a delimiter at each connection point. */ default CharSeq join(CharSequence delimiter) { return join(delimiter, "", ""); } /** * Convert all elements into String, and connect each String together to a single String, following the same order of the seq. * Insert a delimiter at each connection point. Add prefix and suffix to the final result. */ default CharSeq join(CharSequence delimiter, CharSequence prefix, CharSequence suffix) { StringBuilder stringBuilder = new StringBuilder(prefix); forEach((t, i) -> { if (i != 0) { stringBuilder.append(delimiter); } stringBuilder.append(t); }); stringBuilder.append(suffix); return CharSeq.of(stringBuilder.toString()); } /** * Randomly find an element in the seq. * * @return The selected element, or null if the seq is empty. */ default T sample() { if (size() == 0) { return null; } Random rand = new Random(); int randomNum = rand.nextInt(size()); return get(randomNum); } /** * Randomly find n elements in the seq. * * @return A new seq of the selected elements. If the size of seq is lower than n, return all elements. * Return empty result if the seq is empty. The order of selected elements may be changed. */ Seq<T> sample(int n); /** * Get the number of elements in this seq. */ int size(); boolean contains(T t); /** * Randomly shuffle the seq, resulting a new seq. */ Seq<T> shuffle(); ArrayList<T> toArrayList(); /** * Iterate each element of the seq. * * @throws NullPointerException if action is null */ default void forEach(Consumer<? super T> action) { Objects.requireNonNull(action); for (int i = 0; i < this.size(); i++) { action.accept(this.get(i)); } } /** * Similar to {@link #forEach(Consumer)}, with additional parameter "index" as the second parameter of the lambda expression. * * @throws NullPointerException if action is null */ default void forEach(BiConsumer<? super T, Integer> action) { Objects.requireNonNull(action); for (int i = 0; i < this.size(); i++) { action.accept(this.get(i), i); } } /** * Iterate each element of the seq from the end to the beginning. * * @throws NullPointerException if action is null */ default void forEachReverse(Consumer<? super T> action) { Objects.requireNonNull(action); for (int i = size() - 1; i >= 0; i--) { action.accept(this.get(i)); } } /** * Similar to {@link #forEachReverse(Consumer)}, with additional parameter "index" as the second parameter of the lambda expression. * * @throws NullPointerException if action is null */ default void forEachReverse(BiConsumer<? super T, Integer> action) { Objects.requireNonNull(action); for (int i = size() - 1; i >= 0; i--) { action.accept(this.get(i), i); } } /** * Transform the seq, to a seq of each continuous n elements starting from each element. * <p> * [1, 2, 3, 4] with n=2 will result to [[1, 2], [2, 3], [3, 4]] * </p> * If the size of seq is lower than n, result will be empty. * * @throws IllegalArgumentException if n <= 0 */ Seq<? extends Seq<T>> eachCons(int n); /** * Similar with {@link #eachCons(int)}, but instead of to return the transformed seq, it iterates the transformed seq and do action. * * @throws NullPointerException if action is null * @throws IllegalArgumentException if n <= 0 */ default void forEachCons(int n, Consumer<Seq<T>> action) { Objects.requireNonNull(action); if (n <= 0) { throw new IllegalArgumentException("n should be a positive number!"); } for (int i = 0; i <= this.size() - n; i++) { action.accept(this.subSeq(i, i + n)); } } boolean isEmpty(); Object[] toArray(); /** * Sort the seq by the comparator, resulting a new seq, without changing the original seq. * * @param comparator the comparator to determine the order of the seq. A * {@code null} value indicates that the elements' <i>natural * ordering</i> should be used. * @return A new seq sorted */ Seq<T> sort(Comparator<? super T> comparator); /** * Reduce duplicated elements, keeping only the first occurrence, resulting a new seq. * * @return A new seq reduced */ Seq<T> distinct(); /** * Find the first element which satisfy the condition. * * @return The element, or null if no element found. * @throws NullPointerException if condition is null */ default T findFirst(Predicate<T> condition) { Objects.requireNonNull(condition); for (int i = 0; i < size(); i++) { T t = get(i); if (condition.test(t)) { return t; } } return null; } /** * Find the last element which satisfy the condition. * * @return The element, or null if no element found. * @throws NullPointerException if condition is null */ default T findLast(Predicate<T> condition) { Objects.requireNonNull(condition); for (int i = size() - 1; i >= 0; i--) { T t = get(i); if (condition.test(t)) { return t; } } return null; } /** * Find the index of the first element which satisfy the condition. * * @return The index, or -1 if no element found. * @throws NullPointerException if condition is null */ default int findFirstIndex(Predicate<T> condition) { Objects.requireNonNull(condition); for (int i = 0; i < size(); i++) { T t = get(i); if (condition.test(t)) { return i; } } return -1; } /** * Find the index of the last element which satisfy the condition. * * @return The index, or -1 if no element found. * @throws NullPointerException if condition is null */ default int findLastIndex(Predicate<T> condition) { Objects.requireNonNull(condition); for (int i = size() - 1; i >= 0; i--) { T t = get(i); if (condition.test(t)) { return i; } } return -1; } /** * Append values to the seq at the end of it, resulting a new seq. * <p> * Note: This method does <strong>NOT</strong> change the seq. * </p> * * @return A new seq after the change * @throws NullPointerException is values is null */ Seq<T> append(T value); /** * Append values to the seq at the end of it, resulting a new seq. * <p> * Note: This method does <strong>NOT</strong> change the seq. * </p> * * @return A new seq after the change * @throws NullPointerException is values is null */ @SuppressWarnings({"unchecked", "varargs"}) Seq<T> append(T... values); /** * Append values to the seq at the end of it, resulting a new seq. * <p> * Note: This method does <strong>NOT</strong> change the seq. * </p> * * @return A new seq after the change * @throws NullPointerException is collection is null */ Seq<T> append(Collection<? extends T> collection); /** * Append values to the seq at the end of it, resulting a new seq. * <p> * Note: This method does <strong>NOT</strong> change the seq. * </p> * * @return A new seq after the change * @throws NullPointerException is collection is null */ Seq<T> append(Seq<? extends T> seq); /** * Prepend values into the seq at the beginning of it. Values keep the parameter order after being prepended. * <p> * Note: This method does <strong>NOT</strong> change the seq. * </p> * * @return A new seq after the change * @throws NullPointerException is values is null */ Seq<T> prepend(T values); /** * Prepend values into the seq at the beginning of it. Values keep the parameter order after being prepended. * <p> * Note: This method does <strong>NOT</strong> change the seq. * </p> * * @return A new seq after the change * @throws NullPointerException is values is null */ @SuppressWarnings({"unchecked", "varargs"}) Seq<T> prepend(T... values); /** * Prepend values into the seq at the beginning of it. Values keep the order after being merged into the seq. * <p> * Note: This method does <strong>NOT</strong> change the seq. * </p> * * @return A new seq after the change * @throws NullPointerException is collection is null */ Seq<T> prepend(Collection<? extends T> collection); /** * Prepend values into the seq at the beginning of it. Values keep the order after being merged into the seq. * <p> * Note: This method does <strong>NOT</strong> change the seq. * </p> * * @return A new seq after the change * @throws NullPointerException is collection is null */ Seq<T> prepend(Seq<? extends T> seq); /** * Create a new seq which is the sub seq of the current one. * * @param fromIndex The start index, inclusive. * @param toIndex The end index, exclusive. * @throws IndexOutOfBoundsException if an endpoint index value is out of range * {@code (fromIndex < 0 || toIndex > size)} * @throws IllegalArgumentException if the endpoint indices are out of order * {@code (fromIndex > toIndex)} */ Seq<T> subSeq(int fromIndex, int toIndex); /** * Removes elements which satisfy the condition, resulting a new seq without changing the original one. * * @param condition the condition used to filter elements by passing the element, * returns true if the element satisfies the condition, otherwise returns false. * @return the new seq without elements which satisfy the condition * @throws NullPointerException if condition is null */ Seq<T> reject(Predicate<T> condition); /** * Removes elements which satisfy the condition, resulting a new seq without changing the original one. * <p> * Similar to {@link #reject(Predicate)}, with additional parameter "index" as the second parameter of the lambda expression * </p> * * @param condition the condition used to filter elements by passing the element and its index, * returns true if the element satisfies the condition, otherwise returns false. * @return the new seq without elements which satisfy the condition * @throws NullPointerException if condition is null */ Seq<T> reject(BiPredicate<T, Integer> condition); /** * Removes elements at the front of this seq which satisfy the condition, resulting a new seq without changing the original one. * * @param condition the condition used to filter elements by passing the element, * returns true if the element satisfies the condition, otherwise returns false. * @return the new seq without elements which satisfy the condition * @throws NullPointerException if condition is null */ Seq<T> rejectWhile(Predicate<T> condition); /** * Removes elements at the front of this seq which satisfy the condition, resulting a new seq without changing the original one. * <p> * Similar to {@link #reject(Predicate)}, with additional parameter "index" as the second parameter of the lambda expression * </p> * * @param condition the condition used to filter elements by passing the element and its index, * returns true if the element satisfies the condition, otherwise returns false. * @return the new seq without elements which satisfy the condition * @throws NullPointerException if condition is null */ Seq<T> rejectWhile(BiPredicate<T, Integer> condition); /** * Gets elements which satisfy the condition, resulting a new seq without changing the original one. * * @param condition the condition used to filter elements by passing the element's index, * returns true if the element satisfies the condition, otherwise returns false * @return the new seq containing only the elements satisfying the condition * @throws NullPointerException if condition is null */ Seq<T> filter(Predicate<T> condition); /** * Gets elements which satisfy the condition, resulting a new seq without changing the original one. * <p> * Similar to {@link #filter(Predicate)}, with additional parameter "index" as the second parameter of the lambda expression. * </p> * * @param condition the condition used to filter elements by passing the element and its index, * returns true if the element satisfies the condition, otherwise returns false * @return the new seq containing only the elements satisfying the condition * @throws NullPointerException if condition is null */ Seq<T> filter(BiPredicate<T, Integer> condition); /** * Gets elements at the front of this seq which satisfy the condition, resulting a new seq without changing the original one. * * @param condition the condition used to filter elements by passing the element's index, * returns true if the element satisfies the condition, otherwise returns false * @return the new seq containing only the elements satisfying the condition * @throws NullPointerException if condition is null */ Seq<T> filterWhile(Predicate<T> condition); /** * Gets elements at the front of this seq which satisfy the condition, resulting a new seq without changing the original one. * <p> * Similar to {@link #filter(Predicate)}, with additional parameter "index" as the second parameter of the lambda expression. * </p> * * @param condition the condition used to filter elements by passing the element and its index, * returns true if the element satisfies the condition, otherwise returns false * @return the new seq containing only the elements satisfying the condition * @throws NullPointerException if condition is null */ Seq<T> filterWhile(BiPredicate<T, Integer> condition); /** * Returns a new seq built by concatenating the <tt>times</tt> copies of this seq. * * @param times times to repeat * @return the new seq * @throws IllegalArgumentException if <tt>times &lt;= 0</tt> */ Seq<T> repeat(int times); /** * Returns a copy of the seq itself with all null elements removed. * * @return the new seq with all null elements removed */ Seq<T> compact(); /** * Returns the number of the specified element. * * @param element the element to countIf * @return the number of the specified element */ default int count(T element) { int count = 0; for (int i = 0; i < size(); i++) { if (element == null) { if (this.get(i) == null) count++; } else { if (this.get(i) != null && this.get(i).equals(element)) count++; } } return count; } /** * Returns the number of elements which satisfy the condition. * * @param condition the condition used to filter elements by passing the element, * returns true if the element satisfies the condition, otherwise returns false. * @return the number of elements which satisfy the condition * @throws NullPointerException if condition is null */ default int countIf(Predicate<T> condition) { Objects.requireNonNull(condition); int count = 0; for (int i = 0; i < size(); i++) { if (condition.test(this.get(i))) count++; } return count; } /** * Returns the number of elements which satisfy the condition. * <p> * Similar to {@link #countIf(Predicate)}, with additional parameter "index" as the second parameter of the lambda expression. * </p> * * @param condition the condition used to filter elements by passing the element and its index, * returns true if the element satisfies the condition, otherwise returns false. * @return the number of elements which satisfy the condition * @throws NullPointerException if condition is null */ default int countIf(BiPredicate<T, Integer> condition) { Objects.requireNonNull(condition); int count = 0; for (int i = 0; i < size(); i++) { if (condition.test(this.get(i), i)) count++; } return count; } /** * Returns the element at index. A negative index counts from the end of self. * * @param index index of the element to return * @return the element at the specified position in this seq * @throws IndexOutOfBoundsException if the index is out of range * (<tt>index &gt;= size() || index &lt; -size()</tt>) */ T get(int index); /** * Returns the element at index. A negative index counts from the end of self. * If the index is out of range(<tt>index &lt; -size() || index &gt;= size()</tt>), a default value is returned. * <p> * Similar to {@link #get(int)}. The difference between these two functions is how to solve the situation of illegal index.<br/> * {@link #get(int, Object)} returns a default value when the index is illegal. <br/> * {@link #get(int)} throws an exception({@link IndexOutOfBoundsException}) when the index is illegal. * </p> * * @param index index of the element to return * @param defaultValue default value to return when the index is out of range * @return The element at the specified position in this seq, or default value if the index is out of range */ default T get(int index, T defaultValue) { if (index < -this.size() || index >= this.size()) { return defaultValue; } return this.get(index); } /** * Slices this seq to construct some slices in the original order, * each of slice contains <tt>n</tt> elements(only the last slice can contain less than <tt>n</tt> elements). * * @param n the number of elements in each slice except the last one * @return the collection of these slices * @throws IllegalArgumentException if <tt>n &lt;= 0</tt> */ Seq<? extends Seq<T>> eachSlice(int n); /** * Slices the seq to construct some slices and take action on each slice. * <p> * Similar to {@link #eachSlice(int)}, but instead of returning the slice collection, * it iterates the slice collection and takes action on each slice. * </p> * * @param n the number of elements in each slice except the last one * @param action the action to take on each slice * @throws IllegalArgumentException if <tt>n &lt;= 0</tt> * @throws NullPointerException if action is null */ default void forEachSlice(int n, Consumer<Seq<T>> action) { Objects.requireNonNull(action); if (n <= 0) throw new IllegalArgumentException("n should be a positive number."); int size = this.size(); for (int i = 0; i < size; i += n) { action.accept(this.subSeq(i, i + n > size ? size : i + n)); } } /** * Performs a reduction on the elements of this seq, using the provided * binary operation, and returns the reduced value. * * @param accumulator the binary operation for combining two values * @return the result of the reduction, or null if the seq is empty * @throws NullPointerException if accumulator is null */ default T reduce(BinaryOperator<T> accumulator) { Objects.requireNonNull(accumulator); boolean foundAny = false; T result = null; for (int i = 0; i < size(); i++) { if (!foundAny) { foundAny = true; result = this.get(i); } else result = accumulator.apply(result, this.get(i)); } return result; } /** * Performs a reduction on the elements of this seq, using the provided initial value * and a binary function, and returns the reduced value. * <p> * Similar to {@link #reduce(BinaryOperator)}, * with an additional parameter "init" as the initial value of the reduction * </p> * * @param init the initial value for the accumulating function * @param accumulator the binary function for combining two values * @return the result of the reduction * @throws NullPointerException if accumulator is null */ default <R> R reduce(R init, BiFunction<R, T, R> accumulator) { Objects.requireNonNull(accumulator); R result = init; for (int i = 0; i < size(); i++) result = accumulator.apply(result, this.get(i)); return result; } /** * Constructs a new seq containing all the elements of this seq in reverse order. * * @return the new seq with elements in reverse order */ Seq<T> reverse(); /** * Similar with {@link #eachCombination(int)}, but instead of to return the seq, it iterates the seq and do action. */ void forEachCombination(int n, Consumer<Seq<T>> action); /** * Return a new Seq of all combinations of length n of elements from this seq. * The implementation makes no guarantees about the order in which the combinations are returned. * This method uses the index as the identity of each element, thus it may return a combination with duplicated elements inside. * If you want to avoid this, use {@link #distinct()} before calling this method. */ Seq<? extends Seq<T>> eachCombination(int n); /** * Check whether any element of the seq satisfies the condition * * @throws NullPointerException if condition is null */ default boolean any(Predicate<T> condition) { Objects.requireNonNull(condition); for (int i = 0; i < size(); i++) { if (condition.test(get(i))) { return true; } } return false; } /** * Check whether any element of the seq satisfies the condition * * @throws NullPointerException if condition is null */ default boolean any(BiPredicate<T, Integer> condition) { Objects.requireNonNull(condition); for (int i = 0; i < size(); i++) { if (condition.test(get(i), i)) { return true; } } return false; } /** * Returns the index of the first occurrence of the specified element * in this list, or -1 if this list does not contain the element. * More formally, returns the lowest index <tt>i</tt> such that * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>, * or -1 if there is no such index. */ int indexOf(T t); /** * Returns the index of the last occurrence of the specified element * in this list, or -1 if this list does not contain the element. * More formally, returns the highest index <tt>i</tt> such that * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>, * or -1 if there is no such index. */ int lastIndexOf(T t); /** * Check whether this seq contains the sub seq, if the given seq is empty, always return true. * * @throws NullPointerException if seq is null */ default boolean containsSubSeq(Seq<T> seq) { return indexOfSubSeq(seq) != -1; } /** * Return the first index of the given sub seq, or -1 if the given seq is not a sub seq. * If the given seq is empty, always return 0. * * @throws NullPointerException if seq is null */ default int indexOfSubSeq(Seq<T> seq) { Objects.requireNonNull(seq); if (seq.isEmpty()) { return 0; } if (size() < seq.size()) { return -1; } //Sunday algorithm Map<T, Integer> lastIndex = new HashMap<>(); seq.forEach(lastIndex::put); int startI = 0, size = size(), len = seq.size(); while (size - startI >= len) { for (int i = 0; ; i++) { if (!get(startI + i).equals(seq.get(i))) { if (startI + len >= size) { return -1; } T next = get(startI + len); Integer last = lastIndex.get(next); if (last == null) { startI += len + 1; } else { startI += len - last; } break; } else if (i == len - 1) { return startI; } } } return -1; } /** * Return the last index of the given sub seq, or -1 if the given seq is not a sub seq. * If the given seq is empty, always return 0. * * @throws NullPointerException if seq is null */ default int lastIndexOfSubSeq(Seq<T> seq) { Objects.requireNonNull(seq); if (seq.isEmpty()) { return 0; } if (size() < seq.size()) { return -1; } //Sunday algorithm Map<T, Integer> lastIndex = new HashMap<>(); seq.forEachReverse(lastIndex::put); int size = size(), endI = size - 1, len = seq.size(); while (endI >= len - 1) { for (int i = 0; ; i++) { if (!get(endI - i).equals(seq.get(len - 1 - i))) { if (endI - len < 0) { return -1; } T next = get(endI - len); Integer last = lastIndex.get(next); if (last == null) { endI -= len + 1; } else { endI -= last + 1; } break; } else if (i == len - 1) { return endI - len + 1; } } } return -1; } /** * Computes the multiset intersection between this seq and another seq. * * @return A new seq which contains all elements of this seq which also appear in that, keeping the order of this seq. * If an element value x appears n times in that, then the first n occurrences of x will be retained in the result, but any following occurrences will be omitted. * @throws NullPointerException if the parameter seq is null */ Seq<T> intersect(Seq<T> seq); /** * Computes the multiset difference between this seq and another seq. * * @return A new seq which contains all elements of this seq except some of occurrences of elements that also appear in that, keeping the order of this seq. * If an element value x appears n times in that, then the first n occurrences of x will not form part of the result, but any following occurrences will. * @throws NullPointerException if the parameter seq is null */ Seq<T> difference(Seq<T> seq); /** * Check whether all elements of the seq satisfy the condition * * @throws NullPointerException if condition is null */ default boolean all(Predicate<T> condition) { Objects.requireNonNull(condition); for (int i = 0; i < size(); i++) { if (!condition.test(get(i))) { return false; } } return true; } /** * Check whether all elements of the seq satisfy the condition * * @throws NullPointerException if condition is null */ default boolean all(BiPredicate<T, Integer> condition) { Objects.requireNonNull(condition); for (int i = 0; i < size(); i++) { if (!condition.test(get(i), i)) { return false; } } return true; } /** * Check whether no element of the seq satisfies the condition * * @throws NullPointerException if condition is null */ default boolean none(Predicate<T> condition) { Objects.requireNonNull(condition); for (int i = 0; i < size(); i++) { if (condition.test(get(i))) { return false; } } return true; } /** * Check whether no element of the seq satisfies the condition * * @throws NullPointerException if condition is null */ default boolean none(BiPredicate<T, Integer> condition) { Objects.requireNonNull(condition); for (int i = 0; i < size(); i++) { if (condition.test(get(i), i)) { return false; } } return true; } /** * Returns the maximum element of the seq * * @throws NullPointerException if comparator is null */ default Optional<T> max(Comparator<? super T> comparator) { Objects.requireNonNull(comparator); if (size() == 0) { return Optional.empty(); }
java
Apache-2.0
60bcc893c80c27f61335696819a8ae261ac339c7
2026-01-05T02:37:21.030242Z
true
WorksApplications/icefig
https://github.com/WorksApplications/icefig/blob/60bcc893c80c27f61335696819a8ae261ac339c7/src/main/java/com/worksap/icefig/lang/MutableSeq.java
src/main/java/com/worksap/icefig/lang/MutableSeq.java
/* * Copyright (C) 2015 The Fig Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.worksap.icefig.lang; import java.util.*; import java.util.function.*; /** * An interface extending {@link Seq} (which is immutable), with additional in-place methods to change the seq itself. * Those methods are generally named xxxInPlace */ public interface MutableSeq<T> extends Seq<T> { @Override <R> MutableSeq<R> map(Function<T, R> func); @Override <R> MutableSeq<R> map(BiFunction<T, Integer, R> func); @Override <R> MutableSeq<R> flatMap(Function<T, Seq<R>> func); @Override <R> MutableSeq<R> flatMap(BiFunction<T, Integer, Seq<R>> func); @Override MutableSeq<T> sample(int n); @Override MutableSeq<T> shuffle(); @Override MutableSeq<MutableSeq<T>> eachCons(int n); @Override MutableSeq<T> sort(Comparator<? super T> comparator); @Override MutableSeq<T> distinct(); @Override MutableSeq<T> append(T value); @Override @SuppressWarnings({"varargs", "unchecked"}) MutableSeq<T> append(T... values); @Override MutableSeq<T> append(Collection<? extends T> collection); @Override MutableSeq<T> append(Seq<? extends T> seq); @Override MutableSeq<T> prepend(T value); @Override @SuppressWarnings({"varargs", "unchecked"}) MutableSeq<T> prepend(T... values); @Override MutableSeq<T> prepend(Collection<? extends T> collection); @Override MutableSeq<T> prepend(Seq<? extends T> seq); @Override MutableSeq<T> subSeq(int fromIndex, int toIndex); @Override MutableSeq<T> reject(Predicate<T> condition); @Override MutableSeq<T> reject(BiPredicate<T, Integer> condition); @Override MutableSeq<T> rejectWhile(Predicate<T> condition); @Override MutableSeq<T> rejectWhile(BiPredicate<T, Integer> condition); @Override MutableSeq<T> filter(Predicate<T> condition); @Override MutableSeq<T> filter(BiPredicate<T, Integer> condition); @Override MutableSeq<T> filterWhile(Predicate<T> condition); @Override MutableSeq<T> filterWhile(BiPredicate<T, Integer> condition); @Override MutableSeq<T> repeat(int times); @Override default MutableSeq<T> compact() { return this.reject(e -> e == null); } @Override MutableSeq<MutableSeq<T>> eachSlice(int n); @Override MutableSeq<T> reverse(); @Override MutableSeq<MutableSeq<T>> eachCombination(int n); /** * In-place method of {@link #append(Object)} */ MutableSeq<T> appendInPlace(T value); /** * In-place method of {@link #append(T...)} */ @SuppressWarnings({"varargs", "unchecked"}) MutableSeq<T> appendInPlace(T... values); /** * In-place method of {@link #append(Collection)} */ MutableSeq<T> appendInPlace(Collection<? extends T> collection); /** * In-place method of {@link #append(Seq)} */ MutableSeq<T> appendInPlace(Seq<? extends T> seq); /** * In-place method of {@link #prepend(Object)} */ MutableSeq<T> prependInPlace(T value); /** * In-place method of {@link #prepend(T...)} */ @SuppressWarnings({"varargs", "unchecked"}) MutableSeq<T> prependInPlace(T... values); /** * In-place method of {@link #prepend(Collection)} */ MutableSeq<T> prependInPlace(Collection<? extends T> collection); /** * In-place method of {@link #prepend(Seq)} */ MutableSeq<T> prependInPlace(Seq<? extends T> seq); /** * Remove all elements in the seq. * * @return The seq itself after changed. */ MutableSeq<T> clear(); /** * Update the element at the index. * * @return The seq itself after changed. */ MutableSeq<T> set(int i, T t); /** * In-place method of {@link #shuffle()} */ MutableSeq<T> shuffleInPlace(); /** * In-place method of {@link #reverse()} */ MutableSeq<T> reverseInPlace(); /** * In-place method of {@link #distinct()} */ MutableSeq<T> distinctInPlace(); /** * In-place method of {@link #repeat(int)} */ MutableSeq<T> repeatInPlace(int times); /** * In-place method of {@link #compact()} */ MutableSeq<T> compactInPlace(); /** * In-place method of {@link #sort(Comparator)} */ MutableSeq<T> sortInPlace(Comparator<? super T> comparator); /** * In-place method of {@link #filter(Predicate)} */ MutableSeq<T> filterInPlace(Predicate<T> condition); /** * In-place method of {@link #filter(BiPredicate)} */ MutableSeq<T> filterInPlace(BiPredicate<T, Integer> condition); /** * In-place method of {@link #filterWhile(Predicate)} */ MutableSeq<T> filterWhileInPlace(Predicate<T> condition); /** * In-place method of {@link #filterWhile(BiPredicate)} */ MutableSeq<T> filterWhileInPlace(BiPredicate<T, Integer> condition); /** * In-place method of {@link #reject(Predicate)} */ MutableSeq<T> rejectInPlace(Predicate<T> condition); /** * In-place method of {@link #reject(BiPredicate)} */ MutableSeq<T> rejectInPlace(BiPredicate<T, Integer> condition); /** * In-place method of {@link #rejectWhile(Predicate)} */ MutableSeq<T> rejectWhileInPlace(Predicate<T> condition); /** * In-place method of {@link #rejectWhile(BiPredicate)} */ MutableSeq<T> rejectWhileInPlace(BiPredicate<T, Integer> condition); /** * In-place method of {@link #swap(int, int)} */ MutableSeq<T> swapInPlace(int i, int j); /** * In-place method of {@link #rotate(int)} */ MutableSeq<T> rotateInPlace(int distance); }
java
Apache-2.0
60bcc893c80c27f61335696819a8ae261ac339c7
2026-01-05T02:37:21.030242Z
false
WorksApplications/icefig
https://github.com/WorksApplications/icefig/blob/60bcc893c80c27f61335696819a8ae261ac339c7/src/main/java/com/worksap/icefig/lang/CharSeq.java
src/main/java/com/worksap/icefig/lang/CharSeq.java
/* * Copyright (C) 2015 The Fig Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.worksap.icefig.lang; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Elegant supplement for String in JDK */ public class CharSeq { private final String str; CharSeq(String str) { this.str = Objects.requireNonNull(str); } /** * Returns a CharSeq that contains a substring of this CharSeq's string. * The substring begins at the specified {@code beginIndex} and * extends to the character at index {@code endIndex - 1}. * Thus the length of the substring is {@code endIndex-beginIndex}. * <p> * <p> * Examples: * <blockquote><pre> * CharSeq.of("hamburger").subSeq(4, 8) returns CharSeq.of("urge") * CharSeq.of("smiles").subSeq(1, 5) returns CharSeq.of("mile") * </pre></blockquote> * </p> * * @param fromIndex the beginning index, inclusive. * @param toIndex the ending index, exclusive. * @return CharSeq with the specified substring. */ public CharSeq subSeq(int fromIndex, int toIndex) { return new CharSeq(str.substring(fromIndex, toIndex)); } /** * Returns a CharSeq that contains a substring of this CharSeq's string. * The substring begins at the specified {@code beginIndex} and * extends to the end of this string. * <p> * <p> * Examples: * <blockquote><pre> * CharSeq.of("unhappy").subSeq(2) returns CharSeq.of("happy") * CharSeq.of("Harbison").subSeq(3) returns CharSeq.of("bison") * </pre></blockquote> * </p> * * @param fromIndex the beginning index, inclusive. * @return CharSeq with the specified substring. */ public CharSeq subSeq(int fromIndex) { return this.subSeq(fromIndex, str.length()); } /** * Append string of the given CharSeq to this CharSeq * * @param another the given CharSeq * @return appended result */ public CharSeq concat(CharSeq another) { return new CharSeq(str + another.str); } /** * Append the given string to this CharSeq * * @param another the given string * @return appended result */ public CharSeq concat(String another) { return new CharSeq(str + another); } /** * Prepend string of the given CharSeq to this CharSeq * * @param another the given string * @return prepended result */ public CharSeq prepend(CharSeq another) { return new CharSeq(another.str + str); } /** * Prepend the given string to this CharSeq * * @param another the given string * @return prepended result */ public CharSeq prepend(String another) { return new CharSeq(another + str); } /** * Returns the length of string of this CharSeq. * The length is equal to the number of Unicode * code units in the string. * * @return the length */ public int length() { return str.length(); } /** * Returns {@code true} if, and only if, {@link #length()} is {@code 0}. * * @return {@code true} if {@link #length()} is {@code 0}, otherwise * {@code false} */ public boolean isEmpty() { return str.isEmpty(); } /** * Returns a copy of CharSeq with the string's first character * converted to uppercase and the remainder to lowercase. * * @return CharSeq with capitalized string */ public CharSeq capitalize() { return isEmpty() ? this : this.subSeq(0, 1).toUpperCase().concat(this.subSeq(1).toLowerCase()); } /** * Returns a copy of CharSeq with the string's characters all * converted to uppercase. * * @return */ public CharSeq toUpperCase() { return new CharSeq(str.toUpperCase()); } /** * Returns a copy of this CharSeq with characters all * converted to lowercase. * * @return */ public CharSeq toLowerCase() { return new CharSeq(str.toLowerCase()); } /** * Splits this CharSeq around matches of the given regular expression. * * @param regex Regular expression * @return */ public Seq<CharSeq> split(String regex) { return Seqs.newSeq(str.split(regex)).map(CharSeq::new); } /** * Construct a new CharSeq with the given string * * @param str the given string * @return */ public static CharSeq of(String str) { return new CharSeq(str); } /** * Construct a new CharSeq with the given char array * * @param charArr the given char array * @return */ public static CharSeq of(char[] charArr) { return new CharSeq(new String(charArr)); } /** * Return a new CharSeq with the characters from * this CharSeq in reverse order. * <p> * <p> * Examples: * <blockquote><pre> * CharSeq.of("stressed").reverse() returns CharSeq.of("desserts") * </pre></blockquote> * </p> * * @return A new Seq */ public CharSeq reverse() { return CharSeq.of(new StringBuilder(str).reverse().toString()); } /** * Return a new CharSeq with all characters' cases toggled. * <p> * <p> * Examples: * <blockquote><pre> * CharSeq.of("sTrEsSed").swapcase() returns CharSeq.of("StReSsED") * </pre></blockquote> * </p> * * @return A new CharSeq */ public CharSeq swapcase() { char[] chars = str.toCharArray(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; if (Character.isUpperCase(c)) { chars[i] = Character.toLowerCase(c); } else if (Character.isLowerCase(c)) { chars[i] = Character.toUpperCase(c); } else { chars[i] = c; } } return CharSeq.of(chars); } /** * Tests whether this CharSeq ends with the specified suffix * * @param suffix suffix * @return A boolean */ public boolean endsWith(CharSeq suffix) { return this.endsWith(suffix.str); } /** * Tests whether this CharSeq ends with the specified suffix * * @param suffix suffix * @return A boolean */ public boolean endsWith(String suffix) { return str.endsWith(suffix); } /** * Tests whether this CharSeq starts with the specified prefix * * @param prefix prefix * @return A boolean */ public boolean startsWith(CharSeq prefix) { return str.startsWith(prefix.str); } /** * Return the Character at the index i of this CharSeq * * @param i the index * @return The specified Character */ public Character charAt(int i) { return str.charAt(i); } /** * Returns a CharSeq whose value is this CharSeq, with any leading and trailing * whitespace removed. * * @return A new CharSeq with leading and trailing whitespace removed */ public CharSeq trim() { return CharSeq.of(str.trim()); } /** * Scan through this CharSeq iteratively, generate a Seq of CharSeq * with all the matching subStrings. * * @param regex The regular expression * @return A Seq of CharSeq */ public Seq<CharSeq> scan(String regex) { Pattern pat = Pattern.compile(regex); Matcher m = pat.matcher(str); MutableSeq<CharSeq> charSeq = Seqs.newMutableSeq(); while (m.find()) { charSeq.appendInPlace(CharSeq.of(m.group())); } return charSeq; } /** * Performs the given action for each character of the CharSeq. * * @param action Consumer with single parameter of Character * @return Self */ public CharSeq forEachChar(Consumer<Character> action) { Objects.requireNonNull(action); eachChar().forEach(action); return this; } /** * Performs the given action for each character of the CharSeq, * with additional parameter "index" as the second parameter. * * @param action BiConsumer with parameters of Character and the index * @return Self */ public CharSeq forEachChar(BiConsumer<Character, Integer> action) { Objects.requireNonNull(action); eachChar().forEach(action); return this; } /** * Performs the given action for each byte of the CharSeq. * * @param action Consumer with single parameter of Byte * @return Self */ public CharSeq forEachByte(Consumer<Byte> action) { Objects.requireNonNull(action); eachByte().forEach(action); return this; } /** * Performs the given action for each byte of the CharSeq, * with additional parameter "index" as the second parameter. * * @param action BiConsumer with parameters of Byte and the index * @return Self */ public CharSeq forEachByte(BiConsumer<Byte, Integer> action) { Objects.requireNonNull(action); eachByte().forEach(action); return this; } /** * Performs the given action for each line of the CharSeq. * * @param action Consumer with single parameter of CharSeq * @return Self */ public CharSeq forEachLine(Consumer<CharSeq> action) { Objects.requireNonNull(action); Seq<CharSeq> lines = this.eachLine(); lines.forEach(action); return this; } /** * Performs the given action for each line of the CharSeq, * with additional parameter "index" as the second parameter. * * @param action BiConsumer with parameters of CharSeq and the index * @return Self */ public CharSeq forEachLine(BiConsumer<CharSeq, Integer> action) { Objects.requireNonNull(action); Seq<CharSeq> lines = this.eachLine(); lines.forEach(action); return this; } /** * Split the CharSeq by the newline character and return the * result as a Seq of CharSeq. * * @return A Seq of CharSeq */ public Seq<CharSeq> eachLine() { return this.split("\n|\r\n"); } /** * Tells whether or not this CharSeq matches the given regular expression. * * @return A boolean */ public boolean matches(String regex) { return this.str.matches(regex); } /** * Return a new CharSeq by replacing the first substring of this CharSeq * that matches the given regular expression with the given CharSeq replacement. * * @param regex The regular expression * @param replacement The replacement CharSeq * @return A new CharSeq */ public CharSeq replaceFirst(String regex, CharSeq replacement) { return this.replaceFirst(regex, replacement.str); } /** * Return a new CharSeq by replacing the first substring of this CharSeq * that matches the given regular expression with the given String replacement. * * @param regex The regular expression * @param replacement The replacement String * @return A new CharSeq */ public CharSeq replaceFirst(String regex, String replacement) { return CharSeq.of(str.replaceFirst(regex, replacement)); } /** * Return a new CharSeq by replacing each substring of this * CharSeq that matches the given regular expression with * the given CharSeq replacement. * * @param regex The regular expression * @param replacement The replacement CharSeq * @return A new CharSeq */ public CharSeq replaceAll(String regex, CharSeq replacement) { return this.replaceAll(regex, replacement.str); } /** * Return a new CharSeq by replacing each substring of this * CharSeq that matches the given regular expression with * the given String replacement. * * @param regex The regular expression * @param replacement The replacement String * @return A new CharSeq */ public CharSeq replaceAll(String regex, String replacement) { return CharSeq.of(str.replaceAll(regex, replacement)); } @Override public boolean equals(Object another) { return another instanceof CharSeq && str.equals(((CharSeq) another).str); } @Override public String toString() { return str; } /** * Compares two CharSeqs lexicographically. * * @return the value {@code 0} if the argument CharSeq is equal to * this CharSeq; a value less than {@code 0} if this CharSeq * is lexicographically less than the CharSeq argument; and a * value greater than {@code 0} if this CharSeq is * lexicographically greater than the CharSeq argument. */ public int compareTo(CharSeq another) { return str.compareTo(another.str); } /** * Compares two CharSeqs lexicographically ignore case differences. * * @return a negative integer, zero, or a positive integer as the * specified String is greater than, equal to, or less * than this String, ignoring case considerations. */ public int compareToIgnoreCase(CharSeq another) { return str.compareToIgnoreCase(another.str); } /** * Searches pattern (regex) in the CharSeq and returns * a Seq of CharSeq consists of the part before it, * the first match, and the part after it. * <p> * If no such match is found in this CharSeq, return a Seq * of CharSeq consists two empty CharSeqs and the CharSeq itself. * * @param regex Regular Expression * @return A Seq of CharSeq */ public Seq<CharSeq> partition(String regex) { Matcher m = Pattern.compile(regex).matcher(str); if (m.find()) { return Seqs.newSeq(CharSeq.of(str.substring(0, m.start())), CharSeq.of(m.group()), CharSeq.of(str.substring(m.end()))); } else { return Seqs.newSeq(CharSeq.of(""), CharSeq.of(""), CharSeq.of(str)); } } /** * Searches pattern (regex) in the CharSeq and returns * a Seq of CharSeq consists of the part before it, * the last match, and the part after it. * <p> * If no such match is found in this CharSeq, return a Seq * of CharSeq consists of two empty CharSeqs and the CharSeq itself. * * @param regex Regular Expression * @return A Seq of CharSeq */ public Seq<CharSeq> rPartition(String regex) { Matcher m = Pattern.compile(regex).matcher(str); String match = null; int start = 0, end = 0; while (m.find()) { match = m.group(); start = m.start(); end = m.end(); } if (match != null) { return Seqs.newSeq(CharSeq.of(str.substring(0, start)), CharSeq.of(match), CharSeq.of(str.substring(end)) ); } return Seqs.newSeq(CharSeq.of(""), CharSeq.of(""), CharSeq.of(str)); } /** * Converts this CharSeq to a new Character Seq. * * @return A Seq of Character */ public Seq<Character> eachChar() { char[] chars = str.toCharArray(); Character[] characters = new Character[str.length()]; for (int i = 0; i < characters.length; i++) { characters[i] = chars[i]; } return Seqs.newSeq(characters); } /** * Encodes this {@code CharSeq} into a sequence of bytes using the * platform's default charset, storing the result into a new Byte Seq. * * @return A Seq of Byte */ public Seq<Byte> eachByte() { byte[] rawBytes = str.getBytes(); Byte[] bytes = new Byte[rawBytes.length]; for (int i = 0; i < bytes.length; i++) { bytes[i] = rawBytes[i]; } return Seqs.newSeq(bytes); } /** * Returns the collection of the Unicode of each character in this {@code CharSeq}. * * @return the collection of ths Unicode of each character */ public Seq<Integer> eachCodePoint() { MutableSeq<Integer> codePoints = Seqs.newMutableSeq(); char[] chars = str.toCharArray(); for (int i = 0; i < chars.length; i++) { codePoints.appendInPlace((int) chars[i]); } return codePoints; } /** * Takes action on the Unicode of each character in this {@code CharSeq}. * <p> * Similar to {@link #eachCodePoint()}, but instead of returning the Unicode collection, it iterates the collection and takes action. * </p> * * @param consumer the action to be taken on the Unicode of each character * @throws NullPointerException if consumer is null */ public CharSeq forEachCodePoint(Consumer<Integer> consumer) { Objects.requireNonNull(consumer); eachCodePoint().forEach(consumer); return this; } /** * Check whether this CharSeq contains the sub seq, if the given seq is empty, always return true. * * @throws NullPointerException if seq is null */ public boolean containsSubSeq(String seq) { return indexOfSubSeq(seq) != -1; } /** * Return the first index of the given sub seq, or -1 if the given seq is not a sub seq. * If the given seq is empty, always return 0. * * @throws NullPointerException if seq is null */ public int indexOfSubSeq(String seq) { return indexOfSubSeq(CharSeq.of(seq)); } /** * Return the last index of the given sub seq, or -1 if the given seq is not a sub seq. * If the given seq is empty, always return 0. * * @throws NullPointerException if seq is null */ public int lastIndexOfSubSeq(String seq) { return lastIndexOfSubSeq(CharSeq.of(seq)); } /** * Check whether this CharSeq contains the sub seq, if the given seq is empty, always return true. * * @throws NullPointerException if seq is null */ public boolean containsSubSeq(CharSeq seq) { return indexOfSubSeq(seq) != -1; } /** * Return the first index of the given sub seq, or -1 if the given seq is not a sub seq. * If the given seq is empty, always return 0. * * @throws NullPointerException if seq is null */ public int indexOfSubSeq(CharSeq seq) { Objects.requireNonNull(seq); if (seq.isEmpty()) { return 0; } if (length() < seq.length()) { return -1; } //Sunday algorithm Map<Character, Integer> lastIndex = new HashMap<>(); seq.forEachChar(lastIndex::put); int startI = 0, size = length(), len = seq.length(); while (size - startI >= len) { for (int i = 0; ; i++) { if (!charAt(startI + i).equals(seq.charAt(i))) { if (startI + len >= size) { return -1; } Character next = charAt(startI + len); Integer last = lastIndex.get(next); if (last == null) { startI += len + 1; } else { startI += len - last; } break; } else if (i == len - 1) { return startI; } } } return -1; } /** * Return the last index of the given sub seq, or -1 if the given seq is not a sub seq. * If the given seq is empty, always return 0. * * @throws NullPointerException if seq is null */ public int lastIndexOfSubSeq(CharSeq seq) { Objects.requireNonNull(seq); if (seq.isEmpty()) { return 0; } if (length() < seq.length()) { return -1; } //Sunday algorithm Map<Character, Integer> lastIndex = new HashMap<>(); for (int i = seq.length() - 1; i >= 0; i--) { lastIndex.put(seq.charAt(i), i); } int size = length(), endI = size - 1, len = seq.length(); while (endI >= len - 1) { for (int i = 0; ; i++) { if (!charAt(endI - i).equals(seq.charAt(len - 1 - i))) { if (endI - len < 0) { return -1; } Character next = charAt(endI - len); Integer last = lastIndex.get(next); if (last == null) { endI -= len + 1; } else { endI -= last + 1; } break; } else if (i == len - 1) { return endI - len + 1; } } } return -1; } }
java
Apache-2.0
60bcc893c80c27f61335696819a8ae261ac339c7
2026-01-05T02:37:21.030242Z
false
WorksApplications/icefig
https://github.com/WorksApplications/icefig/blob/60bcc893c80c27f61335696819a8ae261ac339c7/src/main/java/com/worksap/icefig/lang/SeqImpl.java
src/main/java/com/worksap/icefig/lang/SeqImpl.java
/* * Copyright (C) 2015 The Fig Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.worksap.icefig.lang; import java.util.*; import java.util.function.*; /** * The implementation of Seq and MutableSeq. */ class SeqImpl<T> implements MutableSeq<T> { private final ArrayList<T> list; SeqImpl() { this.list = new ArrayList<>(); } SeqImpl(Collection<T> collection) { this.list = new ArrayList<>(collection); } /** * Returns the element at index. A negative index counts from the end of self. * * @param index index of the element to return * @return the element at the specified position in this seq * @throws IndexOutOfBoundsException if the index is out of range * (<tt>index &gt;= size() || index &lt; -size()</tt>) */ @Override public T get(int index) { int size = size(); if (index >= size || index < -size) throw new IndexOutOfBoundsException("Index " + index + ", size " + size + ", should be within [" + (-size) + ", " + size + ")"); if (index >= 0) return list.get(index); else return list.get(size + index); } @Override public <R> MutableSeq<R> map(Function<T, R> func) { Objects.requireNonNull(func); MutableSeq<R> result = new SeqImpl<>(); this.forEach(i -> result.appendInPlace(func.apply(i))); return result; } @Override public <R> MutableSeq<R> map(BiFunction<T, Integer, R> func) { Objects.requireNonNull(func); MutableSeq<R> result = new SeqImpl<>(); this.forEach((s, i) -> result.appendInPlace(func.apply(s, i))); return result; } @Override public <R> MutableSeq<R> flatMap(Function<T, Seq<R>> func) { Objects.requireNonNull(func); MutableSeq<R> result = new SeqImpl<>(); this.forEach(i -> result.appendInPlace(func.apply(i))); return result; } @Override public <R> MutableSeq<R> flatMap(BiFunction<T, Integer, Seq<R>> func) { Objects.requireNonNull(func); MutableSeq<R> result = new SeqImpl<>(); this.forEach((s, i) -> result.appendInPlace(func.apply(s, i))); return result; } @Override public MutableSeq<T> sample(int n) { MutableSeq<T> shuffled = shuffle(); return shuffled.subSeq(0, Math.min(n, this.size())); } @Override public int size() { return list.size(); } @Override public Object[] toArray() { return list.toArray(); } @Override public MutableSeq<T> shuffle() { List<T> newList = new ArrayList<>(list); Collections.shuffle(newList); return new SeqImpl<>(newList); } @Override public MutableSeq<MutableSeq<T>> eachCons(int n) { if (n <= 0) { throw new IllegalArgumentException("n should be positive number!"); } MutableSeq<MutableSeq<T>> result = new SeqImpl<>(); for (int i = 0; i <= this.size() - n; i++) { result.appendInPlace(this.subSeq(i, i + n)); } return result; } @Override public MutableSeq<T> sort(Comparator<? super T> comparator) { List<T> newList = new ArrayList<>(list); Collections.sort(newList, comparator); return new SeqImpl<>(newList); } @Override public MutableSeq<T> distinct() { return new SeqImpl<>(new LinkedHashSet<>(list)); } @Override public MutableSeq<T> append(T value) { List<T> newList = new ArrayList<>(list); newList.add(value); return new SeqImpl<>(newList); } @Override @SafeVarargs final public MutableSeq<T> append(T... values) { return append(Arrays.asList(values)); } @Override public MutableSeq<T> append(Collection<? extends T> collection) { List<T> newList = new ArrayList<>(list); newList.addAll(collection); return new SeqImpl<>(newList); } @Override public MutableSeq<T> append(Seq<? extends T> seq) { List<T> newList = new ArrayList<>(list); seq.forEach((Consumer<T>) newList::add); return new SeqImpl<>(newList); } @Override public MutableSeq<T> appendInPlace(T value) { list.add(value); return this; } @Override @SafeVarargs final public MutableSeq<T> appendInPlace(T... values) { Collections.addAll(list, values); return this; } @Override public MutableSeq<T> appendInPlace(Collection<? extends T> collection) { list.addAll(collection); return this; } @Override public MutableSeq<T> appendInPlace(Seq<? extends T> seq) { list.addAll(seq.toArrayList()); return this; } @Override public MutableSeq<T> prepend(T value) { List<T> newList = new ArrayList<>(); newList.add(value); newList.addAll(list); return new SeqImpl<>(newList); } @Override @SafeVarargs final public MutableSeq<T> prepend(T... values) { Objects.requireNonNull(values); return prepend(Arrays.asList(values)); } @Override public MutableSeq<T> prepend(Collection<? extends T> collection) { List<T> newList = new ArrayList<>(); newList.addAll(collection); newList.addAll(list); return new SeqImpl<>(newList); } @Override public MutableSeq<T> prepend(Seq<? extends T> seq) { List<T> newList = new ArrayList<>(); seq.forEach((Consumer<T>) newList::add); newList.addAll(list); return new SeqImpl<>(newList); } @Override public MutableSeq<T> prependInPlace(T value) { list.add(0, value); return this; } @Override @SafeVarargs final public MutableSeq<T> prependInPlace(T... values) { return prependInPlace(Arrays.asList(values)); } @Override public MutableSeq<T> prependInPlace(Collection<? extends T> collection) { list.addAll(0, collection); return this; } @Override public MutableSeq<T> prependInPlace(Seq<? extends T> seq) { list.addAll(0, seq.toArrayList()); return this; } @Override public MutableSeq<T> subSeq(int fromIndex, int toIndex) { return new SeqImpl<>(list.subList(fromIndex, toIndex)); } @Override public MutableSeq<T> reject(Predicate<T> condition) { Objects.requireNonNull(condition); List<T> newList = new ArrayList<>(); this.forEach(e -> { if (!condition.test(e)) newList.add(e); }); return new SeqImpl<>(newList); } @Override public MutableSeq<T> reject(BiPredicate<T, Integer> condition) { Objects.requireNonNull(condition); List<T> newList = new ArrayList<>(); this.forEach((e, i) -> { if (!condition.test(e, i)) newList.add(e); }); return new SeqImpl<>(newList); } @Override public MutableSeq<T> rejectWhile(Predicate<T> condition) { Objects.requireNonNull(condition); int idx = 0; for (; idx < size() && condition.test(get(idx)); idx++); MutableSeq<T> seq = new SeqImpl<>(); for (; idx < size(); idx++) { seq.appendInPlace(get(idx)); } return seq; } @Override public MutableSeq<T> rejectWhile(BiPredicate<T, Integer> condition) { Objects.requireNonNull(condition); int idx = 0; for (; idx < size() && condition.test(get(idx), idx); idx++); MutableSeq<T> seq = new SeqImpl<>(); for (; idx < size(); idx++) { seq.appendInPlace(get(idx)); } return seq; } @Override public MutableSeq<T> filter(Predicate<T> condition) { Objects.requireNonNull(condition); List<T> newList = new ArrayList<>(); this.forEach(e -> { if (condition.test(e)) newList.add(e); }); return new SeqImpl<>(newList); } @Override public MutableSeq<T> filter(BiPredicate<T, Integer> condition) { Objects.requireNonNull(condition); List<T> newList = new ArrayList<>(); this.forEach((e, i) -> { if (condition.test(e, i)) newList.add(e); }); return new SeqImpl<>(newList); } @Override public MutableSeq<T> filterWhile(Predicate<T> condition) { Objects.requireNonNull(condition); MutableSeq<T> seq = new SeqImpl<>(); for (int idx = 0; idx < size() && condition.test(get(idx)); idx++) { seq.appendInPlace(get(idx)); } return seq; } @Override public MutableSeq<T> filterWhile(BiPredicate<T, Integer> condition) { Objects.requireNonNull(condition); MutableSeq<T> seq = new SeqImpl<>(); for (int idx = 0; idx < size() && condition.test(get(idx), idx); idx++) { seq.appendInPlace(get(idx)); } return seq; } @Override public MutableSeq<T> repeat(int times) { if (times <= 0) throw new IllegalArgumentException("times must be a positive number."); List<T> newList = new ArrayList<>(); while (times > 0) { newList.addAll(list); times--; } return new SeqImpl<>(newList); } @Override public MutableSeq<MutableSeq<T>> eachSlice(int n) { if (n <= 0) throw new IllegalArgumentException("n should be a positive number."); List<MutableSeq<T>> newList = new ArrayList<>(); int size = this.size(); for (int i = 0; i < size; i += n) { newList.add(subSeq(i, i + n > size ? size : i + n)); } return new SeqImpl<>(newList); } @Override public boolean isEmpty() { return list.isEmpty(); } @Override public MutableSeq<T> reverse() { List<T> newList = new ArrayList<>(); for (int i = size() - 1; i >= 0; i--) newList.add(this.get(i)); return new SeqImpl<>(newList); } private Seq<T> indexToSeq(int[] idxs) { MutableSeq<T> result = new SeqImpl<>(); for (int i : idxs) { result.appendInPlace(get(i)); } return result; } public void forEachCombination(int n, Consumer<Seq<T>> action) { Objects.requireNonNull(action); if (n <= 0) { throw new IllegalArgumentException("n should be a positive number"); } if (n > size()) { return; } //Selected element indices of a valid combination int[] comb = new int[n]; //initialize first combination by the first n elements for (int i = 0; i < n; i++) { comb[i] = i; } action.accept(indexToSeq(comb)); while (comb[0] < size() - n) { for (int i = 0; ; i++) { if (i == n - 1 || comb[i + 1] - comb[i] > 1) { // find the first selected element that the next element of it is not selected comb[i]++; // make the next element selected instead // set all selected elements before i, to the beginning elements for (int j = 0; j < i; j++) { comb[j] = j; } action.accept(indexToSeq(comb)); break; } } } } public MutableSeq<MutableSeq<T>> eachCombination(int n) { MutableSeq<MutableSeq<T>> result = new SeqImpl<>(); forEachCombination(n, s -> result.appendInPlace((MutableSeq<T>) s)); return result; } @Override public MutableSeq<T> clear() { list.clear(); return this; } @Override public boolean contains(T t) { return list.contains(t); } @Override public MutableSeq<T> set(int i, T t) { list.set(i, t); return this; } @Override public ArrayList<T> toArrayList() { return list; } @Override public MutableSeq<T> shuffleInPlace() { Collections.shuffle(list); return this; } @Override public MutableSeq<T> distinctInPlace() { Collection<T> collection = new LinkedHashSet<>(list); list.clear(); list.addAll(collection); return this; } @Override public MutableSeq<T> sortInPlace(Comparator<? super T> comparator) { Collections.sort(list, comparator); return this; } @Override public MutableSeq<T> rejectInPlace(Predicate<T> condition) { Objects.requireNonNull(condition); final Iterator<T> each = list.iterator(); while (each.hasNext()) { if (condition.test(each.next())) { each.remove(); } } return this; } @Override public MutableSeq<T> rejectInPlace(BiPredicate<T, Integer> condition) { Objects.requireNonNull(condition); final Iterator<T> each = list.iterator(); int index = 0; while (each.hasNext()) { if (condition.test(each.next(), index)) { each.remove(); } index++; } return this; } @Override public MutableSeq<T> rejectWhileInPlace(Predicate<T> condition) { Objects.requireNonNull(condition); final Iterator<T> each = list.iterator(); while (each.hasNext() && condition.test(each.next())) { each.remove(); } return this; } @Override public MutableSeq<T> rejectWhileInPlace(BiPredicate<T, Integer> condition) { Objects.requireNonNull(condition); final Iterator<T> each = list.iterator(); for (int idx = 0; each.hasNext() && condition.test(each.next(), idx); idx++) { each.remove(); } return this; } @Override public MutableSeq<T> filterInPlace(Predicate<T> condition) { Objects.requireNonNull(condition); final Iterator<T> each = list.iterator(); while (each.hasNext()) { if (!condition.test(each.next())) { each.remove(); } } return this; } @Override public MutableSeq<T> filterInPlace(BiPredicate<T, Integer> condition) { Objects.requireNonNull(condition); final Iterator<T> each = list.iterator(); int index = 0; while (each.hasNext()) { if (!condition.test(each.next(), index)) { each.remove(); } index++; } return this; } @Override public MutableSeq<T> filterWhileInPlace(Predicate<T> condition) { Objects.requireNonNull(condition); int posToRemove = 0; for (; posToRemove < size() && condition.test(get(posToRemove)); posToRemove++); for (int idx = size() - 1; idx >= posToRemove; idx--) { list.remove(idx); } return this; } @Override public MutableSeq<T> filterWhileInPlace(BiPredicate<T, Integer> condition) { Objects.requireNonNull(condition); int posToRemove = 0; for (; posToRemove < size() && condition.test(get(posToRemove), posToRemove); posToRemove++); for (int idx = size() - 1; idx >= posToRemove; idx--) { list.remove(idx); } return this; } @Override public MutableSeq<T> repeatInPlace(int times) { if (times <= 0) throw new IllegalArgumentException("times must be a positive number."); else if (times >= 2) { times--; Collection<T> copy = new ArrayList<>(list); while (times > 0) { list.addAll(copy); times--; } } return this; } @Override public MutableSeq<T> compactInPlace() { list.removeIf(e -> e == null); return this; } @Override public MutableSeq<T> reverseInPlace() { int size = size(); for (int i = 0; i < size / 2; i++) { T temp = this.get(i); this.set(i, this.get(size - 1 - i)); this.set(size - 1 - i, temp); } return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SeqImpl<?> seq = (SeqImpl<?>) o; return Objects.equals(list, seq.list); } @Override public int hashCode() { return Objects.hash(list); } @Override public String toString() { return list.toString(); } @Override public int indexOf(T t) { return list.indexOf(t); } @Override public int lastIndexOf(T t) { return list.lastIndexOf(t); } @Override public Seq<T> intersect(Seq<T> seq) { Objects.requireNonNull(seq); if (seq.isEmpty()) { return new SeqImpl<>(); } HashMap<T, Integer> map = countIndex(seq); SeqImpl<T> result = new SeqImpl<>(); forEach(t -> { Integer count = map.get(t); if (count != null) { result.appendInPlace(t); if (count == 1) { map.remove(t); } else { map.put(t, count - 1); } } }); return result; } private HashMap<T, Integer> countIndex(Seq<T> seq) { HashMap<T, Integer> map = new HashMap<>(seq.size()); seq.forEach(t -> { Integer count = map.get(t); if (count != null) { map.put(t, count + 1); } else { map.put(t, 1); } }); return map; } @Override public Seq<T> difference(Seq<T> seq) { Objects.requireNonNull(seq); if (seq.isEmpty()) { return new SeqImpl<>(list); } HashMap<T, Integer> map = countIndex(seq); SeqImpl<T> result = new SeqImpl<>(); forEach(t -> { Integer count = map.get(t); if (count != null) { if (count == 1) { map.remove(t); } else { map.put(t, count - 1); } } else { result.appendInPlace(t); } }); return result; } @Override public Seq<T> swap(int i, int j) { MutableSeq<T> newSeq = new SeqImpl<>(list); newSeq.swapInPlace(i, j); return newSeq; } @Override public MutableSeq<T> swapInPlace(int i, int j) { T tmp = get(i); set(i, get(j)); set(j, tmp); return this; } @Override public Seq<T> rotate(int distance) { MutableSeq<T> newSeq = new SeqImpl<>(); int size = size(); if (size == 0) { return newSeq; } distance = distance % size(); if (distance < 0) { distance += size; } for (int i = 0; i < size(); i++) { newSeq.appendInPlace(get((size + i - distance) % size)); } return newSeq; } @Override public MutableSeq<T> rotateInPlace(int distance) { int size = size(); if (size == 0 || distance % size == 0) { return this; } distance = distance % size(); if (distance < 0) { distance += size; } for (int cycleStart = 0, movedSteps = 0; movedSteps != size; cycleStart++) { T displaced = list.get(cycleStart); int i = cycleStart; do { i += distance; if (i >= size) { i -= size; } displaced = list.set(i, displaced); movedSteps++; } while (i != cycleStart); } return null; } }
java
Apache-2.0
60bcc893c80c27f61335696819a8ae261ac339c7
2026-01-05T02:37:21.030242Z
false
WorksApplications/icefig
https://github.com/WorksApplications/icefig/blob/60bcc893c80c27f61335696819a8ae261ac339c7/src/main/java/com/worksap/icefig/lang/Hashes.java
src/main/java/com/worksap/icefig/lang/Hashes.java
/* * Copyright (C) 2015 The Fig Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.worksap.icefig.lang; import java.util.Map; /** * Factory class for construct Hash and MutableHash */ public class Hashes { private Hashes() { } public static <K, V> Hash<K, V> newHash() { return new HashImpl<>(); } public static <K, V> Hash<K, V> newHash(Map<K, V> map) { return new HashImpl<>(map); } public static <K, V> MutableHash<K, V> newMutableHash() { return new HashImpl<>(); } public static <K, V> MutableHash<K, V> newMutableHash(Map<K, V> map) { return new HashImpl<>(map); } }
java
Apache-2.0
60bcc893c80c27f61335696819a8ae261ac339c7
2026-01-05T02:37:21.030242Z
false
WorksApplications/icefig
https://github.com/WorksApplications/icefig/blob/60bcc893c80c27f61335696819a8ae261ac339c7/src/main/java/com/worksap/icefig/lang/Range.java
src/main/java/com/worksap/icefig/lang/Range.java
/* * Copyright (C) 2015 The Fig Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.worksap.icefig.lang; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Optional; import java.util.Spliterator; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; /** * Range is an element generator on the basis of start point, * end point and next element function. */ public class Range<C extends Comparable<C>> implements Iterable<C> { private C from; private C to; private boolean toIncluded; private Function<C, C> next; private BiFunction<C, Integer, C> biNext; /** * @param from The start point. * @throws NullPointerException if from is null. */ public Range(C from) { this.from(from); } /** * @param from The start point. * @param to The end point. It is included in the range. * @param next The next element generator. * @throws NullPointerException if from, to or next is null. */ public Range(C from, C to, Function<C, C> next) { this.from(from); this.to(to); this.next(next); } /** * Set start point * * @param from The start point. * @return Current range object. * @throws NullPointerException if from is null. */ public Range<C> from(C from) { Objects.requireNonNull(from); this.from = from; return this; } /** * Set end point. The end point is included in this range. * * @param to The end point. * @return Current range object. * @throws NullPointerException if to is null. */ public Range<C> to(C to) { Objects.requireNonNull(to); this.to = to; toIncluded = true; return this; } /** * Set end point. The end point is excluded in this range. * * @param to The end point. * @return Current range object. * @throws NullPointerException if to is null. */ public Range<C> until(C to) { Objects.requireNonNull(to); this.to = to; toIncluded = false; return this; } /** * Set next element generator. * * @param next The next element generator * @return Current range object. * @throws NullPointerException if next is null. */ public Range<C> next(Function<C, C> next) { Objects.requireNonNull(next); this.next = next; return this; } /** * Set next element generator. * * @param next The next element generator * @return Current range object. * @throws NullPointerException if next is null. */ public Range<C> next(BiFunction<C, Integer, C> next) { Objects.requireNonNull(next); this.biNext = next; return this; } /** * @return The start point */ public C getFrom() { return from; } /** * @return The end point */ public C getTo() { return to; } /** * @return Whether the end point is included in this range. */ public boolean isToIncluded() { return toIncluded; } /** * Iterate each element of the range. * * @throws NullPointerException if action, this.from, this.to or this.next is null. */ public void forEach(Consumer<? super C> action) { forEach((e, i) -> action.accept(e)); } /** * Similar to {@link #forEach(Consumer)}, with additional parameter "index" as the second parameter of the lambda expression. * * @throws NullPointerException if action, this.from, this.to or this.next is null. */ public void forEach(BiConsumer<? super C, Integer> action) { Objects.requireNonNull(action); Objects.requireNonNull(to); Itr itr = new Itr(); while (itr.hasNext()) { int idx = itr.cursor; C current = itr.next(); action.accept(current, idx); } } public Seq<C> toSeq() { MutableSeq<C> seq = Seqs.newMutableSeq(); forEach((Consumer<C>) seq::appendInPlace); return seq; } public MutableSeq<C> toMutableSeq() { MutableSeq<C> seq = Seqs.newMutableSeq(); forEach((Consumer<C>) seq::appendInPlace); return seq; } /** * * @throws NullPointerException if this.from or this.next is null. */ @Override public Iterator<C> iterator() { return new Itr(); } @Override public Spliterator<C> spliterator() { throw new UnsupportedOperationException("spliterator"); } /** * Get the first n elements of this range. * * @return The Seq containing the first n elements. * @throws IllegalArgumentException if n < 0 */ public Seq<C> take(int n) { if (n < 0) { throw new IllegalArgumentException("n"); } Itr itr = new Itr(); MutableSeq<C> seq = Seqs.newMutableSeq(); while (itr.hasNext() && itr.cursor < n) { seq.appendInPlace(itr.next()); } return seq; } /** * Get elements at the front of this range which satisfy the condition. * * @param condition the condition used to filter elements by passing the element, * returns true if the element satisfies the condition, otherwise returns false. * @return The seq containing all the elements satisfying the condition * @throws NullPointerException if condition is null */ public Seq<C> takeWhile(Predicate<C> condition) { Objects.requireNonNull(condition); Itr itr = new Itr(); MutableSeq<C> seq = Seqs.newMutableSeq(); while (itr.hasNext()) { C candidate = itr.next(); if (!condition.test(candidate)) { break; } seq.appendInPlace(candidate); } return seq; } /** * Get elements at the front of this range which satisfy the condition. * <p> * Similar to {@link #takeWhile(Predicate)}, with additional parameter "index" as the second parameter of the lambda expression. * </p> * * @param condition the condition used to filter elements by passing the element and its index, * returns true if the element satisfies the condition, otherwise returns false. * @return The seq containing all the elements satisfying the condition * @throws NullPointerException if condition is null */ public Seq<C> takeWhile(BiPredicate<C, Integer> condition) { Objects.requireNonNull(condition); Itr itr = new Itr(); MutableSeq<C> seq = Seqs.newMutableSeq(); while (itr.hasNext()) { int idx = itr.cursor; C candidate = itr.next(); if (!condition.test(candidate, idx)) { break; } seq.appendInPlace(candidate); } return seq; } private class Itr implements Iterator<C> { int cursor; C current; C last; C end; boolean endIncluded; /* * orientation = 0 means to is equal to from; * orientation > 0 means to is greater than from; * otherwise to is less than from. */ final Optional<Integer> orientation; private Itr() { Objects.requireNonNull(from); if (Objects.isNull(biNext)) { Objects.requireNonNull(next); } current = from; end = to; endIncluded = toIncluded; if (Objects.isNull(end)) { orientation = Optional.empty(); } else { orientation = Optional.of(current.compareTo(end)); } } @Override public boolean hasNext() { if (!orientation.isPresent()) { return true; } int cmp = current.compareTo(end); return cmp * orientation.get() > 0 || endIncluded && cmp == 0; } @Override public C next() { if (!hasNext()) { throw new NoSuchElementException(); } last = current; if (Objects.nonNull(next)) { current = next.apply(current); } else { current = biNext.apply(current, cursor); } Objects.requireNonNull(current); ++ cursor; return last; } } }
java
Apache-2.0
60bcc893c80c27f61335696819a8ae261ac339c7
2026-01-05T02:37:21.030242Z
false
WorksApplications/icefig
https://github.com/WorksApplications/icefig/blob/60bcc893c80c27f61335696819a8ae261ac339c7/src/main/java/com/worksap/icefig/lang/MutableHash.java
src/main/java/com/worksap/icefig/lang/MutableHash.java
/* * Copyright (C) 2015 The Fig Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.worksap.icefig.lang; import java.util.function.BiFunction; import java.util.function.BiPredicate; /** * An interface extending {@link Hash} (which is immutable), with additional in-place methods to change the hash itself. * Those methods are generally named xxxInPlace */ public interface MutableHash<K, V> extends Hash<K, V> { @Override MutableHash<K, V> put(K k, V v); @Override MutableHash<K, V> putIfAbsent(K k, V v); @Override MutableHash<K, V> filter(BiPredicate<K, V> condition); @Override MutableHash<K, V> reject(BiPredicate<K, V> condition); @Override MutableHash<V, K> invert(); @Override MutableHash<K, V> merge(Hash<? extends K, ? extends V> another); @Override MutableHash<K, V> remove(K k); @Override MutableHash<K, V> remove(K k, V v); @Override Seq<K> keysOf(V v); @Override MutableHash<K, V> replace(K k, V v); @Override MutableHash<K, V> replace(K k, V oldValue, V newValue); @Override MutableHash<K, V> replaceAll(BiFunction<? super K, ? super V, ? extends V> function); /** * In-place method of {@link #put(K, V)} */ MutableHash<K, V> putInPlace(K k, V v); /** * In-place method of {@link #putIfAbsent(K, V)} */ MutableHash<K, V> putIfAbsentInPlace(K k, V v); /** * In-place method of {@link #remove(K)} */ MutableHash<K, V> removeInPlace(K k); /** * In-place method of {@link #remove(K, V)} */ MutableHash<K, V> removeInPlace(K k, V v); /** * In-place method of {@link #filter(BiPredicate)} */ MutableHash<K, V> filterInPlace(BiPredicate<K, V> condition); /** * In-place method of {@link #reject(BiPredicate)} */ MutableHash<K, V> rejectInPlace(BiPredicate<K, V> condition); /** * In-place method of {@link #merge(Hash)} */ MutableHash<K, V> mergeInPlace(Hash<? extends K, ? extends V> another); /** * Remove all the key-value pair at this hash. * * @return the hash itself after clear */ MutableHash<K, V> clear(); /** * In-place method of {@link #replace(K, V)} */ MutableHash<K, V> replaceInPlace(K k, V v); /** * In-place method of {@link #replace(K, V, V)} */ MutableHash<K, V> replaceInPlace(K k, V oldValue, V newValue); /** * In-place method of {@link #replaceAll(BiFunction)} */ MutableHash<K, V> replaceAllInPlace(BiFunction<? super K, ? super V, ? extends V> function); }
java
Apache-2.0
60bcc893c80c27f61335696819a8ae261ac339c7
2026-01-05T02:37:21.030242Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/jmh/BenchmarkRunner.java
src/test/java/jmh/BenchmarkRunner.java
package jmh; import java.util.concurrent.TimeUnit; import jenkins.benchmark.jmh.BenchmarkFinder; import org.junit.jupiter.api.Test; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.results.format.ResultFormatType; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.options.ChainedOptionsBuilder; import org.openjdk.jmh.runner.options.OptionsBuilder; class BenchmarkRunner { @Test void runJmhBenchmarks() throws Exception { ChainedOptionsBuilder options = new OptionsBuilder() .mode(Mode.AverageTime) .warmupIterations(2) .timeUnit(TimeUnit.MICROSECONDS) .threads(2) .forks(2) .measurementIterations(15) .shouldFailOnError(true) .shouldDoGC(true).resultFormat(ResultFormatType.JSON) .result("jmh-report.json"); BenchmarkFinder bf = new BenchmarkFinder(getClass()); bf.findBenchmarks(options); new Runner(options.build()).run(); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/jmh/JmhJenkinsRule.java
src/test/java/jmh/JmhJenkinsRule.java
package jmh; import java.net.MalformedURLException; import java.net.URL; import java.util.Objects; import jenkins.model.Jenkins; import org.htmlunit.Cache; import org.jvnet.hudson.test.JenkinsRule; /** * Extension of {@link JenkinsRule} to allow it to be used from JMH benchmarks. * * <p>This class should be instantiated only * when the Jenkins instance is confirmed to exist. */ public class JmhJenkinsRule extends JenkinsRule { private final Jenkins jenkins; public JmhJenkinsRule() { super(); jenkins = Objects.requireNonNull(Jenkins.getInstanceOrNull()); super.jenkins = null; // the jenkins is not started from JenkinsRule } @Override public URL getURL() throws MalformedURLException { // the rootURL should not be null as it should've been set by JmhBenchmarkState return new URL(Objects.requireNonNull(jenkins.getRootUrl())); } /** * {@inheritDoc} */ @Override public WebClient createWebClient() { WebClient webClient = super.createWebClient(); Cache cache = new Cache(); cache.setMaxSize(0); webClient.setCache(cache); // benchmarks should not rely on cached content webClient.setJavaScriptEnabled(false); // TODO enable JavaScript when we can find jQuery webClient.setThrowExceptionOnFailingStatusCode(false); webClient.getOptions().setPrintContentOnFailingStatusCode(false); // reduce 404 noise return webClient; } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/jmh/benchmarks/WebClientBenchmark.java
src/test/java/jmh/benchmarks/WebClientBenchmark.java
package jmh.benchmarks; import jenkins.benchmark.jmh.JmhBenchmark; import jenkins.benchmark.jmh.JmhBenchmarkState; import jmh.JmhJenkinsRule; import org.jvnet.hudson.test.JenkinsRule; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.infra.Blackhole; @JmhBenchmark public class WebClientBenchmark { public static class JenkinsState extends JmhBenchmarkState { } // WebClient is not thread-safe, so use a different WebClient for each thread @State(Scope.Thread) public static class ThreadState { JenkinsRule.WebClient webClient = null; @Setup(Level.Iteration) public void setup() throws Exception { // JQuery UI is 404 from these tests so disable stopping benchmark when it is used. JmhJenkinsRule j = new JmhJenkinsRule(); webClient = j.createWebClient(); webClient.login("mockUser", "mockUser"); } @TearDown(Level.Iteration) public void tearDown() { webClient.close(); } } @Benchmark public void viewRenderBenchmark(JenkinsState state, ThreadState threadState, Blackhole blackhole) throws Exception { blackhole.consume(threadState.webClient.goTo("")); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/jmh/benchmarks/MaliciousRegexBenchmark.java
src/test/java/jmh/benchmarks/MaliciousRegexBenchmark.java
package jmh.benchmarks; import com.cloudbees.hudson.plugins.folder.Folder; import com.michelin.cio.hudson.plugins.rolestrategy.RoleBasedAuthorizationStrategy; import hudson.model.User; import hudson.security.ACL; import java.util.Random; import jenkins.benchmark.jmh.JmhBenchmark; import jenkins.benchmark.jmh.JmhBenchmarkState; import jenkins.model.Jenkins; import jmh.JmhJenkinsRule; import org.jvnet.hudson.test.JenkinsRule; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.infra.Blackhole; @JmhBenchmark public class MaliciousRegexBenchmark { private static final String testUser = "user33"; public static class JenkinsState extends JmhBenchmarkState { @Override public void setup() throws Exception { Jenkins jenkins = getJenkins(); jenkins.setSecurityRealm(new JenkinsRule().createDummySecurityRealm()); RoleBasedAuthorizationStrategy rbas = new RoleBasedAuthorizationStrategy(); jenkins.setAuthorizationStrategy(rbas); for (int i = 0; i < 200; i++) { jenkins.createProject(Folder.class, "Foooooolder" + i); } Random rand = new Random(33); for (int i = 0; i < 300; i++) { if (rand.nextBoolean()) { rbas.doAddRole(RoleBasedAuthorizationStrategy.PROJECT, "role" + i, "hudson.model.Item.Discover,hudson.model.Item.Read,hudson.model.Item.Build", "true", "F(o+)+lder[" + rand.nextInt(10) + rand.nextInt(10) + "]{1,2}", ""); } rbas.doAssignRole(RoleBasedAuthorizationStrategy.PROJECT, "role" + i, "user" + i); } } } @State(Scope.Thread) public static class ThreadState { @Setup(Level.Iteration) public void setup() { ACL.as(User.getById(testUser, true)); } } @State(Scope.Thread) public static class WebClientState { JenkinsRule.WebClient webClient = null; @Setup(Level.Iteration) public void setup() throws Exception { JmhJenkinsRule jenkinsRule = new JmhJenkinsRule(); webClient = jenkinsRule.createWebClient(); webClient.login(testUser); } @TearDown(Level.Iteration) public void tearDown() { webClient.close(); } } @Benchmark public void benchmarkPermissionCheck(JenkinsState state, ThreadState threadState, Blackhole blackhole) { blackhole.consume(state.getJenkins().getAllItems()); // checks for READ permission } @Benchmark public void benchmarkPageLoad(JenkinsState state, WebClientState webClientState) throws Exception { webClientState.webClient.goTo(""); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/jmh/benchmarks/CascBenchmark.java
src/test/java/jmh/benchmarks/CascBenchmark.java
package jmh.benchmarks; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.jenkinsci.plugins.rolestrategy.PermissionAssert.assertHasNoPermission; import static org.jenkinsci.plugins.rolestrategy.PermissionAssert.assertHasPermission; import com.cloudbees.hudson.plugins.folder.Folder; import com.michelin.cio.hudson.plugins.rolestrategy.PermissionEntry; import com.michelin.cio.hudson.plugins.rolestrategy.Role; import com.michelin.cio.hudson.plugins.rolestrategy.RoleBasedAuthorizationStrategy; import com.synopsys.arc.jenkins.plugins.rolestrategy.RoleType; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.model.Computer; import hudson.model.FreeStyleProject; import hudson.model.Item; import hudson.model.User; import hudson.security.ACL; import hudson.security.AuthorizationStrategy; import io.jenkins.plugins.casc.misc.jmh.CascJmhBenchmarkState; import java.util.Map; import java.util.Objects; import java.util.Set; import jenkins.benchmark.jmh.JmhBenchmark; import jenkins.model.Jenkins; import org.jvnet.hudson.test.JenkinsRule; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; @JmhBenchmark public class CascBenchmark { @State(Scope.Benchmark) public static class CascJenkinsState extends CascJmhBenchmarkState { RoleBasedAuthorizationStrategy rbas = null; Folder folder = null; @Override public void setup() throws Exception { super.setup(); Jenkins jenkins = Objects.requireNonNull(Jenkins.getInstanceOrNull()); jenkins.setSecurityRealm(new JenkinsRule().createDummySecurityRealm()); User admin = User.getById("admin", true); User user1 = User.getById("user1", true); User user2 = User.getById("user2", true); Computer agent1 = jenkins.getComputer("agent1"); Computer agent2 = jenkins.getComputer("agent2"); Folder folderA = jenkins.createProject(Folder.class, "A"); FreeStyleProject jobA1 = folderA.createProject(FreeStyleProject.class, "1"); Folder folderB = jenkins.createProject(Folder.class, "B"); folderB.createProject(FreeStyleProject.class, "2"); AuthorizationStrategy s = jenkins.getAuthorizationStrategy(); assertThat("Authorization Strategy has been read incorrectly", s, instanceOf(RoleBasedAuthorizationStrategy.class)); rbas = (RoleBasedAuthorizationStrategy) s; Map<Role, Set<PermissionEntry>> globalRoles = rbas.getGrantedRolesEntries(RoleType.Global); assertThat(Objects.requireNonNull(globalRoles).size(), equalTo(2)); // Admin has configuration access assertHasPermission(admin, jenkins, Jenkins.ADMINISTER, Jenkins.READ); assertHasPermission(user1, jenkins, Jenkins.READ); assertHasNoPermission(user1, jenkins, Jenkins.ADMINISTER); // Folder A is restricted to admin assertHasPermission(admin, folderA, Item.CONFIGURE); assertHasPermission(user1, folderA, Item.READ, Item.DISCOVER); assertHasNoPermission(user1, folderA, Item.CONFIGURE, Item.DELETE, Item.BUILD); // But they have access to jobs in Folder A assertHasPermission(admin, folderA, Item.CONFIGURE, Item.CANCEL); assertHasPermission(user1, jobA1, Item.READ, Item.DISCOVER, Item.CONFIGURE, Item.BUILD, Item.DELETE); assertHasPermission(user2, jobA1, Item.READ, Item.DISCOVER, Item.CONFIGURE, Item.BUILD, Item.DELETE); assertHasNoPermission(user1, folderA, Item.CANCEL); // FolderB is editable by user2, but he cannot delete it assertHasPermission(user2, folderB, Item.READ, Item.DISCOVER, Item.CONFIGURE, Item.BUILD); assertHasNoPermission(user2, folderB, Item.DELETE); assertHasNoPermission(user1, folderB, Item.CONFIGURE, Item.BUILD, Item.DELETE); // Only user1 can run on agent1, but he still cannot configure it assertHasPermission(admin, agent1, Computer.CONFIGURE, Computer.DELETE, Computer.BUILD); assertHasPermission(user1, agent1, Computer.BUILD); assertHasNoPermission(user1, agent1, Computer.CONFIGURE, Computer.DISCONNECT); // Same user still cannot build on agent2 assertHasNoPermission(user1, agent2, Computer.BUILD); folder = folderB; } @NonNull @Override protected String getResourcePath() { return "sample-casc.yml"; } @NonNull @Override protected Class<?> getEnclosingClass() { return CascBenchmark.class; } } @State(Scope.Thread) public static class AuthenticationThreadState { @Setup(Level.Iteration) public void setup() { ACL.as(User.getById("user2", true)); } } /** * Benchmark time to get the ACL object for a {@link Folder}. */ @Benchmark public void benchmark(CascJenkinsState state, Blackhole blackhole) { blackhole.consume(state.rbas.getACL(state.folder)); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/jmh/benchmarks/PermissionBenchmark.java
src/test/java/jmh/benchmarks/PermissionBenchmark.java
package jmh.benchmarks; import com.michelin.cio.hudson.plugins.rolestrategy.AuthorizationType; import com.michelin.cio.hudson.plugins.rolestrategy.PermissionEntry; import com.michelin.cio.hudson.plugins.rolestrategy.Role; import com.michelin.cio.hudson.plugins.rolestrategy.RoleBasedAuthorizationStrategy; import com.michelin.cio.hudson.plugins.rolestrategy.RoleMap; import hudson.model.User; import hudson.security.Permission; import java.util.Collections; import java.util.Objects; import java.util.Set; import java.util.TreeMap; import jenkins.benchmark.jmh.JmhBenchmark; import jenkins.benchmark.jmh.JmhBenchmarkState; import jenkins.model.Jenkins; import org.jvnet.hudson.test.JenkinsRule; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.infra.Blackhole; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; @JmhBenchmark public class PermissionBenchmark { @State(Scope.Benchmark) public static class JenkinsState extends JmhBenchmarkState { @Override public void setup() { Jenkins jenkins = Objects.requireNonNull(Jenkins.getInstanceOrNull()); Set<String> permissionSet = Collections.singleton("hudson.model.Hudson.Administer"); Role role = new Role("USERS", ".*", permissionSet, "description"); RoleMap roleMap = new RoleMap(new TreeMap<>(// expects a sorted map Collections.singletonMap(role, Collections.singleton(new PermissionEntry(AuthorizationType.USER, "alice"))))); jenkins.setAuthorizationStrategy( new RoleBasedAuthorizationStrategy(Collections.singletonMap(RoleBasedAuthorizationStrategy.GLOBAL, roleMap))); jenkins.setSecurityRealm(new JenkinsRule().createDummySecurityRealm()); } } @State(Scope.Thread) public static class AuthenticationState { private Authentication originalAuthentication = null; private SecurityContext securityContext = null; @Setup(Level.Iteration) public void setup() { securityContext = SecurityContextHolder.getContext(); originalAuthentication = securityContext.getAuthentication(); securityContext.setAuthentication(User.getById("alice", true).impersonate2()); } @TearDown(Level.Iteration) public void tearDown() { securityContext.setAuthentication(originalAuthentication); } } @Benchmark public void roleAssignmentBenchmark(JenkinsState jenkinsState, AuthenticationState authState, Blackhole blackhole) { blackhole.consume(jenkinsState.getJenkins().hasPermission(Permission.READ)); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/jmh/benchmarks/RoleMapBenchmark.java
src/test/java/jmh/benchmarks/RoleMapBenchmark.java
package jmh.benchmarks; import com.michelin.cio.hudson.plugins.rolestrategy.AuthorizationType; import com.michelin.cio.hudson.plugins.rolestrategy.PermissionEntry; import com.michelin.cio.hudson.plugins.rolestrategy.Role; import com.michelin.cio.hudson.plugins.rolestrategy.RoleMap; import com.synopsys.arc.jenkins.plugins.rolestrategy.RoleType; import hudson.security.AccessControlled; import hudson.security.Permission; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import jenkins.benchmark.jmh.JmhBenchmark; import jenkins.benchmark.jmh.JmhBenchmarkState; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.infra.Blackhole; @JmhBenchmark public class RoleMapBenchmark { public static class State50 extends RoleMapBenchmarkState { @Override int getRoleCount() { return 50; } } public static class State100 extends RoleMapBenchmarkState { @Override int getRoleCount() { return 100; } } public static class State200 extends RoleMapBenchmarkState { @Override int getRoleCount() { return 200; } } public static class State500 extends RoleMapBenchmarkState { @Override int getRoleCount() { return 500; } } // user3 does not have CREATE permission, so have to traverse through all of the Roles @Benchmark public void benchmark50(State50 state, Blackhole blackhole) throws Exception { blackhole.consume(state.hasPermission.invoke(state.roleMap, state.functionArgs)); } @Benchmark public void benchmark100(State100 state, Blackhole blackhole) throws Exception { blackhole.consume(state.hasPermission.invoke(state.roleMap, state.functionArgs)); } @Benchmark public void benchmark200(State200 state, Blackhole blackhole) throws Exception { blackhole.consume(state.hasPermission.invoke(state.roleMap, state.functionArgs)); } @Benchmark public void benchmark500(State500 state, Blackhole blackhole) throws Exception { blackhole.consume(state.hasPermission.invoke(state.roleMap, state.functionArgs)); } } @SuppressWarnings("checkstyle:OneTopLevelClass") abstract class RoleMapBenchmarkState extends JmhBenchmarkState { RoleMap roleMap = null; Method hasPermission = null; Object[] functionArgs = null; @Override public void setup() throws Exception { SortedMap<Role, Set<PermissionEntry>> map = new TreeMap<>(); final int roleCount = getRoleCount(); for (int i = 0; i < roleCount; i++) { Role role = new Role("role" + i, ".*", new HashSet<>(Arrays.asList("hudson.model.Item.Discover", "hudson.model.Item.Configure")), ""); map.put(role, Collections.singleton(new PermissionEntry(AuthorizationType.USER, "user" + i))); } roleMap = new RoleMap(map); // RoleMap#hasPermission is private in RoleMap hasPermission = Class.forName("com.michelin.cio.hudson.plugins.rolestrategy.RoleMap").getDeclaredMethod("hasPermission", PermissionEntry.class, Permission.class, RoleType.class, AccessControlled.class); hasPermission.setAccessible(true); functionArgs = new Object[] { new PermissionEntry(AuthorizationType.USER, "user3"), Permission.CREATE, null, null }; } abstract int getRoleCount(); }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/jmh/benchmarks/FolderAccessBenchmark.java
src/test/java/jmh/benchmarks/FolderAccessBenchmark.java
package jmh.benchmarks; import com.cloudbees.hudson.plugins.folder.Folder; import com.michelin.cio.hudson.plugins.rolestrategy.AuthorizationType; import com.michelin.cio.hudson.plugins.rolestrategy.PermissionEntry; import com.michelin.cio.hudson.plugins.rolestrategy.Role; import com.michelin.cio.hudson.plugins.rolestrategy.RoleBasedAuthorizationStrategy; import com.michelin.cio.hudson.plugins.rolestrategy.RoleMap; import hudson.model.FreeStyleProject; import hudson.model.TopLevelItem; import hudson.model.User; import hudson.security.ACL; import hudson.security.Permission; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Random; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import jenkins.benchmark.jmh.JmhBenchmark; import jenkins.benchmark.jmh.JmhBenchmarkState; import jenkins.model.Jenkins; import org.jvnet.hudson.test.JenkinsRule; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; @JmhBenchmark public class FolderAccessBenchmark { @State(Scope.Benchmark) public static class JenkinsState extends JmhBenchmarkState { List<Folder> topFolders = new ArrayList<>(); FreeStyleProject testProject = null; Map<String, TopLevelItem> items = null; RoleMap projectRoleMap = null; @Override public void setup() throws Exception { Jenkins jenkins = Objects.requireNonNull(Jenkins.getInstanceOrNull()); jenkins.setSecurityRealm(new JenkinsRule().createDummySecurityRealm()); SortedMap<Role, Set<PermissionEntry>> projectRoles = new TreeMap<>(); Set<String> userPermissions = new HashSet<>(); Collections.addAll(userPermissions, "hudson.model.Item.Discover", "hudson.model.Item.Read"); Set<String> maintainerPermissions = new HashSet<>(); Collections.addAll(maintainerPermissions, "hudson.model.Item.Discover", "hudson.model.Item.Read", "hudson.model.Item.Create"); Set<String> adminPermissions = new HashSet<>(); Collections.addAll(adminPermissions, "hudson.model.Item.Discover", "hudson.model.Item.Read", "hudson.model.Item.Create", "hudson.model.Item.Configure"); Random random = new Random(100L); /* * This configuration was provided by @Straber. * Structure: * - 10 parent folders each containing 5 child folders => total 50 child folders * - each child folder contains 5 projects * - For each child folder, there are 3 roles: admin, maintainer, user * Total 100 users */ for (int i = 0; i < 10; i++) { Folder folder = jenkins.createProject(Folder.class, "TopFolder" + i); for (int j = 0; j < 5; j++) { Folder child = folder.createProject(Folder.class, "BottomFolder" + j); // 5 projects for every child folder for (int k = 0; k < 5; k++) { FreeStyleProject project = child.createProject(FreeStyleProject.class, "Project" + k); if (i == 5 && j == 3) { testProject = project; } } Set<PermissionEntry> users = new HashSet<>(); for (int k = 0; k < random.nextInt(5); k++) { users.add(new PermissionEntry(AuthorizationType.USER, "user" + random.nextInt(100))); } Set<PermissionEntry> maintainers = new HashSet<>(2); maintainers.add(new PermissionEntry(AuthorizationType.USER, "user" + random.nextInt(100))); maintainers.add(new PermissionEntry(AuthorizationType.USER, "user" + random.nextInt(100))); Set<PermissionEntry> admin = Collections.singleton(new PermissionEntry(AuthorizationType.USER, "user" + random.nextInt(100))); Role userRole = new Role(String.format("user%d-%d", i, j), "TopFolder" + i + "(/BottomFolder" + j + "/.*)?", userPermissions, ""); Role maintainerRole = new Role(String.format("maintainer%d-%d", i, j), "TopFolder" + i + "/BottomFolder" + j + "(/.*)", maintainerPermissions, ""); Role adminRole = new Role(String.format("admin%d-%d", i, j), "TopFolder" + i + "/BottomFolder" + j + "(/.*)", adminPermissions, ""); projectRoles.put(userRole, users); projectRoles.put(maintainerRole, maintainers); projectRoles.put(adminRole, admin); } topFolders.add(folder); } Map<String, RoleMap> rbasMap = new HashMap<>(1); projectRoleMap = new RoleMap(projectRoles); rbasMap.put(RoleBasedAuthorizationStrategy.PROJECT, projectRoleMap); RoleBasedAuthorizationStrategy rbas = new RoleBasedAuthorizationStrategy(rbasMap); jenkins.setAuthorizationStrategy(rbas); Field itemField = Jenkins.class.getDeclaredField("items"); itemField.setAccessible(true); items = (Map<String, TopLevelItem>) itemField.get(jenkins); } } @org.openjdk.jmh.annotations.State(Scope.Thread) public static class ThreadState { @Setup(Level.Iteration) public void setup() { ACL.as(User.getById("user33", true)); } } @Benchmark public void benchmark(JenkinsState state, ThreadState threadState, Blackhole blackhole) { state.testProject.hasPermission(Permission.CREATE); } /** * Benchmark {@link RoleMap#newMatchingRoleMap(String)} since regex matching takes place there. */ @Benchmark public void benchmarkNewMatchingRoleMap(JenkinsState state, ThreadState threadState, Blackhole blackhole) { blackhole.consume(state.projectRoleMap.newMatchingRoleMap("TopFolder4/BottomFolder3/Project2")); } @Benchmark public void renderViewSimulation(JenkinsState state, ThreadState threadState, Blackhole blackhole) { List<TopLevelItem> viewableItems = new ArrayList<>(); for (TopLevelItem item : state.items.values()) { if (item.hasPermission(Permission.WRITE)) { viewableItems.add(item); } } blackhole.consume(viewableItems); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/com/synopsys/arc/jenkins/plugins/rolestrategy/MacroTest.java
src/test/java/com/synopsys/arc/jenkins/plugins/rolestrategy/MacroTest.java
/* * The MIT License * * Copyright 2013 Oleg Nenashev, Synopsys Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.synopsys.arc.jenkins.plugins.rolestrategy; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.fail; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Contains tests for Macro. * * @see Macro * @since 2.1.0 * @author Oleg Nenashev */ class MacroTest { @Test void correctFormatsSanityCheck() { parseMacro("@Dummy"); parseMacro("@Dummy:1"); parseMacro("@Dummy(aaa)"); parseMacro("@Dummy:1(aaa)"); parseMacro("@Dummy(aaa,bbb,ccc,ddd)"); parseMacro("@Dummy:1(aaa,bbb,ccc,ddd)"); } @Test void testValidUsers() { parseWrongMacro("test", MacroExceptionCode.Not_Macro); parseWrongMacro("logged_user", MacroExceptionCode.Not_Macro); parseWrongMacro("anonymous", MacroExceptionCode.Not_Macro); parseWrongMacro("_anonymous", MacroExceptionCode.Not_Macro); parseWrongMacro("dummy user with spaces", MacroExceptionCode.Not_Macro); } @Test void testWrongBrackets() { parseWrongMacro("@test:1(aaa,bbb(", MacroExceptionCode.WrongFormat); parseWrongMacro("@test:1(aaa,bbb(", MacroExceptionCode.WrongFormat); parseWrongMacro("@test:1()(aaa,bbb)", MacroExceptionCode.WrongFormat); parseWrongMacro("@test:1[aaa,bbb]", MacroExceptionCode.WrongFormat); parseWrongMacro("@test:1)aaa,bbb(", MacroExceptionCode.WrongFormat); parseWrongMacro("@test:1)(", MacroExceptionCode.WrongFormat); } @Test void err_WrongEnding() { parseWrongMacro("@test:1(aaa,bbb)error", MacroExceptionCode.WrongFormat); } @Test void err_Quotes() { parseWrongMacro("@test':1(aaa,bbb)", MacroExceptionCode.WrongFormat); parseWrongMacro("@'test':1(aaa,bbb)", MacroExceptionCode.WrongFormat); parseWrongMacro("@test:1('aaa',bbb)", MacroExceptionCode.WrongFormat); parseWrongMacro("@test:1'(aaa,bbb)'", MacroExceptionCode.WrongFormat); parseWrongMacro("@test:'1'(aaa,bbb)", MacroExceptionCode.WrongFormat); parseWrongMacro("'@test:1(aaa,bbb)'", MacroExceptionCode.Not_Macro); parseWrongMacro("@test\":1(aaa,bbb)", MacroExceptionCode.WrongFormat); parseWrongMacro("@test:1(aaa,\"bbb\")", MacroExceptionCode.WrongFormat); parseWrongMacro("\"@test:1(aaa,bbb)\"", MacroExceptionCode.Not_Macro); parseWrongMacro("\"@\"test:1(aaa,bbb)", MacroExceptionCode.Not_Macro); } @Test void emptyParameters() { parseMacro("@Dummy()"); parseMacro("@Dummy:1()"); } @Test void test_MacroSanity() { testCycle("test1", null, null); testCycle("test2", 1, null); testCycle("test3", -1, null); testCycle("test4", null, new String[] {}); testCycle("test5", null, new String[] { "aaa" }); testCycle("test6", -1, new String[] { "aaa" }); testCycle("test7", null, new String[] { "aaa", "bbb" }); testCycle("test8", null, new String[] { "aaa", "bbb", "ccc", "ddd" }); testCycle("test8", 123, new String[] { "aaa", "bbb", "ccc", "ddd" }); } private static void testCycle(String macroName, Integer macroId, String[] parameters) { // Create, get string and parse Macro macro = new Macro(macroName, macroId, parameters); String macroString = macro.toString(); Macro resMacro = parseMacro("Can't parse generated macro: " + macroString, macroString); // Compare assertEquals(macro, resMacro); } private static void assertEquals(Macro expected, Macro actual) { Assertions.assertEquals(expected.getName(), actual.getName(), "Wrong name"); Assertions.assertEquals(expected.getIndex(), actual.getIndex(), "Wrong index"); if (expected.hasParameters()) { assertArrayEquals(expected.getParameters(), actual.getParameters(), "Wrong parameters set"); } else { assertFalse(actual.hasParameters(), "Actual macro shouldn't have parameters"); } } private static Macro assertParseMacroDriver(String errorMessage, String macroString, boolean expectException, MacroExceptionCode expectedError) { Macro res = null; try { res = Macro.parse(macroString); } catch (MacroException ex) { ex.printStackTrace(); if (expectException) { Assertions.assertEquals(expectedError, ex.getErrorCode(), errorMessage + ". Wrong error code"); } else { fail(errorMessage + ". Got Macro Exception: " + ex.getMessage()); } return res; } if (expectException) { fail(errorMessage + ". Haven't got exception. Expected code is " + expectedError); } return res; } private static Macro parseMacro(String errorMessage, String macroString) { return assertParseMacroDriver(errorMessage, macroString, false, MacroExceptionCode.UnknownError); } private static Macro parseMacro(String macroString) { return parseMacro("Parse error", macroString); } private static void parseWrongMacro(String errorMessage, String macroString, MacroExceptionCode expectedCode) { assertParseMacroDriver(errorMessage, macroString, true, expectedCode); } private static void parseWrongMacro(String macroString, MacroExceptionCode expectedCode) { parseWrongMacro("Wrong macro parse error", macroString, expectedCode); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/com/synopsys/arc/jenkins/plugins/rolestrategy/ContainedInViewTest.java
src/test/java/com/synopsys/arc/jenkins/plugins/rolestrategy/ContainedInViewTest.java
package com.synopsys.arc.jenkins.plugins.rolestrategy; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import hudson.model.FreeStyleProject; import org.htmlunit.html.HtmlPage; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.JenkinsRule.DummySecurityRealm; import org.jvnet.hudson.test.JenkinsRule.WebClient; import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.jvnet.hudson.test.recipes.LocalData; @WithJenkins class ContainedInViewTest { private JenkinsRule jenkinsRule; @BeforeEach @LocalData void setup(JenkinsRule jenkinsRule) throws Exception { this.jenkinsRule = jenkinsRule; DummySecurityRealm sr = jenkinsRule.createDummySecurityRealm(); jenkinsRule.jenkins.setSecurityRealm(sr); } @Test @LocalData void userCanAccessJobInRootView() throws Exception { FreeStyleProject project = jenkinsRule.jenkins.getItemByFullName("testJob", FreeStyleProject.class); WebClient wc = jenkinsRule.createWebClient(); wc.withThrowExceptionOnFailingStatusCode(false); wc.login("tester", "tester"); HtmlPage managePage = wc.goTo(project.getUrl()); assertThat(managePage.getWebResponse().getStatusCode(), is(200)); } @Test @LocalData void userCantAccessJobNotInRootView() throws Exception { FreeStyleProject project = jenkinsRule.jenkins.getItemByFullName("hiddenJob", FreeStyleProject.class); WebClient wc = jenkinsRule.createWebClient(); wc.withThrowExceptionOnFailingStatusCode(false); wc.login("tester", "tester"); HtmlPage managePage = wc.goTo(project.getUrl()); assertThat(managePage.getWebResponse().getStatusCode(), is(404)); } @Test @LocalData void userCanAccessJobInFolderView() throws Exception { FreeStyleProject project = jenkinsRule.jenkins.getItemByFullName("folder/testjob2", FreeStyleProject.class); WebClient wc = jenkinsRule.createWebClient(); wc.withThrowExceptionOnFailingStatusCode(false); wc.login("tester", "tester"); HtmlPage managePage = wc.goTo(project.getUrl()); assertThat(managePage.getWebResponse().getStatusCode(), is(200)); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/com/michelin/cio/hudson/plugins/rolestrategy/RoleStrategyRootActionTest.java
src/test/java/com/michelin/cio/hudson/plugins/rolestrategy/RoleStrategyRootActionTest.java
package com.michelin.cio.hudson.plugins.rolestrategy; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.junit.jupiter.api.Assertions.assertEquals; import hudson.security.GlobalMatrixAuthorizationStrategy; import java.net.HttpURLConnection; import java.net.URL; import org.htmlunit.HttpMethod; import org.htmlunit.Page; import org.htmlunit.WebRequest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** * Tests for RoleStrategyRootAction visibility and access control. * This action should only be visible to users with ITEM_ROLES_ADMIN or AGENT_ROLES_ADMIN * but WITHOUT SYSTEM_READ permission. */ @WithJenkins class RoleStrategyRootActionTest { static { RoleBasedAuthorizationStrategy.ITEM_ROLES_ADMIN.setEnabled(true); RoleBasedAuthorizationStrategy.AGENT_ROLES_ADMIN.setEnabled(true); } private JenkinsRule jenkinsRule; private JenkinsRule.WebClient webClient; private RoleBasedAuthorizationStrategy rbas; private RoleStrategyRootAction rootAction; @BeforeEach void setUp(JenkinsRule jenkinsRule) throws Exception { this.jenkinsRule = jenkinsRule; JenkinsRule.DummySecurityRealm securityRealm = jenkinsRule.createDummySecurityRealm(); jenkinsRule.jenkins.setSecurityRealm(securityRealm); rbas = new RoleBasedAuthorizationStrategy(); jenkinsRule.jenkins.setAuthorizationStrategy(rbas); // Get the RootAction extension rootAction = jenkinsRule.jenkins.getExtensionList(RoleStrategyRootAction.class).get(0); // Setting up admin user with SYSTEM_READ rbas.doAddRole("globalRoles", "adminRole", "hudson.model.Hudson.Read,hudson.model.Hudson.Administer", "false", "", ""); rbas.doAssignUserRole("globalRoles", "adminRole", "adminUser"); // Setting up itemAdmin user with ITEM_ROLES_ADMIN but NO SYSTEM_READ rbas.doAddRole("globalRoles", "itemAdminRole", "hudson.model.Hudson.Read," + RoleBasedAuthorizationStrategy.ITEM_ROLES_ADMIN.getId(), "false", "", ""); rbas.doAssignUserRole("globalRoles", "itemAdminRole", "itemAdminUser"); // Setting up agentAdmin user with AGENT_ROLES_ADMIN but NO SYSTEM_READ rbas.doAddRole("globalRoles", "agentAdminRole", "hudson.model.Hudson.Read," + RoleBasedAuthorizationStrategy.AGENT_ROLES_ADMIN.getId(), "false", "", ""); rbas.doAssignUserRole("globalRoles", "agentAdminRole", "agentAdminUser"); // Setting up user with both ITEM and AGENT admin but NO SYSTEM_READ rbas.doAddRole("globalRoles", "bothAdminRole", "hudson.model.Hudson.Read," + RoleBasedAuthorizationStrategy.ITEM_ROLES_ADMIN.getId() + "," + RoleBasedAuthorizationStrategy.AGENT_ROLES_ADMIN.getId(), "false", "", ""); rbas.doAssignUserRole("globalRoles", "bothAdminRole", "bothAdminUser"); // Setting up user with SYSTEM_READ and ITEM_ROLES_ADMIN rbas.doAddRole("globalRoles", "itemAdminWithReadRole", "hudson.model.Hudson.Administer," + RoleBasedAuthorizationStrategy.ITEM_ROLES_ADMIN.getId(), "false", "", ""); rbas.doAssignUserRole("globalRoles", "itemAdminWithReadRole", "itemAdminWithReadUser"); // Setting up developer user with no admin permissions rbas.doAddRole("projectRoles", "developers", "hudson.model.Item.Read,hudson.model.Item.Build", "false", ".*", ""); rbas.doAssignUserRole("projectRoles", "developers", "developerUser"); webClient = jenkinsRule.createWebClient() .withThrowExceptionOnFailingStatusCode(false) .withJavaScriptEnabled(false); } @Test void testIconNotVisibleWhenRoleStrategyNotEnabled() throws Exception { // Change to different authorization strategy jenkinsRule.jenkins.setAuthorizationStrategy(new GlobalMatrixAuthorizationStrategy()); webClient.login("itemAdminUser", "itemAdminUser"); String iconFileName = rootAction.getIconFileName(); assertThat("Icon should not be visible when Role Strategy is not enabled", iconFileName, nullValue()); } @Test void testIconVisibleForItemAdminWithoutSystemRead() throws Exception { webClient.login("itemAdminUser", "itemAdminUser"); // Check visibility by fetching the root page and looking for the link Page page = webClient.goTo(""); String content = page.getWebResponse().getContentAsString(); assertThat("Root action link should be visible for itemAdmin without SYSTEM_READ", content.contains("role-strategy"), equalTo(true)); } @Test void testIconVisibleForAgentAdminWithoutSystemRead() throws Exception { webClient.login("agentAdminUser", "agentAdminUser"); Page page = webClient.goTo(""); String content = page.getWebResponse().getContentAsString(); assertThat("Root action link should be visible for agentAdmin without SYSTEM_READ", content.contains("role-strategy"), equalTo(true)); } @Test void testIconVisibleForBothAdminsWithoutSystemRead() throws Exception { webClient.login("bothAdminUser", "bothAdminUser"); Page page = webClient.goTo(""); String content = page.getWebResponse().getContentAsString(); assertThat("Root action link should be visible for user with both admin permissions but no SYSTEM_READ", content.contains("role-strategy"), equalTo(true)); } @Test void testIconNotVisibleForAdminWithSystemRead() throws Exception { webClient.login("adminUser", "adminUser"); // Admin should only see the management link, not the root action // The root action's getIconFileName should return null, so the link shouldn't appear at root level // (They'll access it via Manage Jenkins instead) Page page = webClient.goTo("manage"); String content = page.getWebResponse().getContentAsString(); assertThat("Management link should be visible for admin with SYSTEM_READ", content.contains("role-strategy"), equalTo(true)); } @Test void testIconNotVisibleForItemAdminWithSystemRead() throws Exception { webClient.login("itemAdminWithReadUser", "itemAdminWithReadUser"); Page page = webClient.goTo("manage"); String content = page.getWebResponse().getContentAsString(); assertThat("Management link should be visible for itemAdmin with SYSTEM_READ", content.contains("role-strategy"), equalTo(true)); } @Test void testIconNotVisibleForDeveloper() throws Exception { webClient.login("developerUser", "developerUser"); Page page = webClient.goTo(""); String content = page.getWebResponse().getContentAsString(); assertThat("Root action link should NOT be visible for user without admin permissions", content.contains("role-strategy"), equalTo(false)); } @Test void testRootActionAccessibleForItemAdmin() throws Exception { webClient.login("itemAdminUser", "itemAdminUser"); URL url = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/"); WebRequest request = new WebRequest(url, HttpMethod.GET); Page page = webClient.getPage(request); assertEquals(HttpURLConnection.HTTP_OK, page.getWebResponse().getStatusCode(), "itemAdmin should be able to access /role-strategy/"); } @Test void testRootActionAccessibleForAgentAdmin() throws Exception { webClient.login("agentAdminUser", "agentAdminUser"); URL url = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/"); WebRequest request = new WebRequest(url, HttpMethod.GET); Page page = webClient.getPage(request); assertEquals(HttpURLConnection.HTTP_OK, page.getWebResponse().getStatusCode(), "agentAdmin should be able to access /role-strategy/"); } @Test void testRootActionForbiddenForDeveloper() throws Exception { webClient.login("developerUser", "developerUser"); URL url = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/"); WebRequest request = new WebRequest(url, HttpMethod.GET); Page page = webClient.getPage(request); assertEquals(HttpURLConnection.HTTP_FORBIDDEN, page.getWebResponse().getStatusCode(), "Developer without admin permissions should get 403 when accessing /role-strategy/"); } @Test void testRootActionDelegatesToRoleStrategyConfig() throws Exception { webClient.login("itemAdminUser", "itemAdminUser"); // Test that subpages work through the root action URL url = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/assign-roles"); WebRequest request = new WebRequest(url, HttpMethod.GET); Page page = webClient.getPage(request); assertEquals(HttpURLConnection.HTTP_OK, page.getWebResponse().getStatusCode(), "itemAdmin should be able to access /role-strategy/assign-roles through RootAction delegation"); } @Test void testGetTarget() throws Exception { webClient.login("itemAdminUser", "itemAdminUser"); Object target = rootAction.getTarget(); assertThat("getTarget should return RoleStrategyConfig instance", target, notNullValue()); assertThat("getTarget should return RoleStrategyConfig class", target.getClass(), equalTo(RoleStrategyConfig.class)); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/com/michelin/cio/hudson/plugins/rolestrategy/ApiTest.java
src/test/java/com/michelin/cio/hudson/plugins/rolestrategy/ApiTest.java
package com.michelin.cio.hudson.plugins.rolestrategy; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import com.synopsys.arc.jenkins.plugins.rolestrategy.RoleType; import hudson.PluginManager; import hudson.model.Item; import hudson.model.User; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import jenkins.model.Jenkins; import net.sf.json.JSONObject; import org.htmlunit.HttpMethod; import org.htmlunit.Page; import org.htmlunit.WebRequest; import org.htmlunit.util.NameValuePair; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.JenkinsRule.DummySecurityRealm; import org.jvnet.hudson.test.MockFolder; import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.springframework.security.core.Authentication; /** * Tests for {@link RoleBasedAuthorizationStrategy} Web API Methods. */ @WithJenkins class ApiTest { // Note: Reading Global roles requires SYSTEM_READ, which itemAdminUser and agentAdminUser don't have private static final List<Map<String, Object>> getExecutions = Arrays.asList( Map.of("username", "adminUser", "expectedCode", HttpURLConnection.HTTP_OK, "roleType", RoleType.Global), Map.of("username", "adminUser", "expectedCode", HttpURLConnection.HTTP_OK, "roleType", RoleType.Project), Map.of("username", "adminUser", "expectedCode", HttpURLConnection.HTTP_OK, "roleType", RoleType.Slave), Map.of("username", "itemAdminUser", "expectedCode", HttpURLConnection.HTTP_FORBIDDEN, "roleType", RoleType.Global), Map.of("username", "itemAdminUser", "expectedCode", HttpURLConnection.HTTP_FORBIDDEN, "roleType", RoleType.Project), Map.of("username", "itemAdminUser", "expectedCode", HttpURLConnection.HTTP_FORBIDDEN, "roleType", RoleType.Slave), Map.of("username", "agentAdminUser", "expectedCode", HttpURLConnection.HTTP_FORBIDDEN, "roleType", RoleType.Global), Map.of("username", "agentAdminUser", "expectedCode", HttpURLConnection.HTTP_FORBIDDEN, "roleType", RoleType.Project), Map.of("username", "agentAdminUser", "expectedCode", HttpURLConnection.HTTP_FORBIDDEN, "roleType", RoleType.Slave), Map.of("username", "developerUser", "expectedCode", HttpURLConnection.HTTP_FORBIDDEN, "roleType", RoleType.Global), Map.of("username", "developerUser", "expectedCode", HttpURLConnection.HTTP_FORBIDDEN, "roleType", RoleType.Project), Map.of("username", "developerUser", "expectedCode", HttpURLConnection.HTTP_FORBIDDEN, "roleType", RoleType.Slave) ); private JenkinsRule jenkinsRule; private JenkinsRule.WebClient webClient; private DummySecurityRealm securityRealm; private RoleBasedAuthorizationStrategy rbas; private Map<String, String> roleTypeToPermissionIds = Map.of( RoleType.Global.getStringType(), "hudson.model.Hudson.Read,hudson.model.Hudson.Administer,hudson.security.Permission.GenericRead", RoleType.Project.getStringType(), "hudson.model.Item.Read,hudson.model.Item.Build,hudson.model.Item.Cancel", RoleType.Slave.getStringType(), "hudson.model.Computer.Connect,hudson.model.Computer.Create" ); @BeforeEach void setUp(JenkinsRule jenkinsRule) throws Exception { this.jenkinsRule = jenkinsRule; // Setting up jenkins configurations securityRealm = jenkinsRule.createDummySecurityRealm(); jenkinsRule.jenkins.setSecurityRealm(securityRealm); rbas = new RoleBasedAuthorizationStrategy(); jenkinsRule.jenkins.setAuthorizationStrategy(rbas); jenkinsRule.jenkins.setCrumbIssuer(null); // Adding admin role and assigning adminUser rbas.doAddRole("globalRoles", "adminRole", "hudson.model.Hudson.Read,hudson.model.Hudson.Administer,hudson.security.Permission.GenericRead", "false", "", ""); rbas.doAssignUserRole("globalRoles", "adminRole", "adminUser"); // Adding itemAdmin and assigning itemAdminUser rbas.doAddRole("globalRoles", "itemAdminRole", "hudson.model.Hudson.Read," + RoleBasedAuthorizationStrategy.ITEM_ROLES_ADMIN.getId(), "false", "", ""); rbas.doAssignUserRole("globalRoles", "itemAdminRole", "itemAdminUser"); // Adding agentAdmin and assigning agentAdminUser rbas.doAddRole("globalRoles", "agentAdminRole", "hudson.model.Hudson.Read," + RoleBasedAuthorizationStrategy.AGENT_ROLES_ADMIN.getId(), "false", "", ""); rbas.doAssignUserRole("globalRoles", "agentAdminRole", "agentAdminUser"); // Adding developer role and assigning developerUser rbas.doAddTemplate("developer", "hudson.model.Item.Read,hudson.model.Item.Build,hudson.model.Item.Cancel", false); rbas.doAddRole("projectRoles", "developers", "", "false", ".*", "developer"); rbas.doAssignUserRole("projectRoles", "developers", "developerUser"); // Adding developerAgent role and assigning developerAgentUser rbas.doAddRole("slaveRoles", "developerAgentRole", "hudson.model.Computer.Connect", "false", ".*", ""); rbas.doAssignUserRole("slaveRoles", "developerAgentRole", "developerUser"); webClient = jenkinsRule.createWebClient().withThrowExceptionOnFailingStatusCode(false); webClient.login("adminUser", "adminUser"); } private void performAsAndExpect(String username, WebRequest request, int expectedCode, String roleTypeStr) throws Exception { webClient.login(username, username); Page page = webClient.getPage(request); assertEquals(expectedCode, page.getWebResponse().getStatusCode(), "HTTP code mismatch for user " + username + " with roleType " + roleTypeStr); } @Test @Issue("JENKINS-61470") void testAddRole() throws IOException { String roleName = "new-role"; String pattern = "test-folder.*"; // Adding role via web request URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/addRole"); WebRequest request = new WebRequest(apiUrl, HttpMethod.POST); request.setRequestParameters( Arrays.asList(new NameValuePair("type", RoleType.Project.getStringType()), new NameValuePair("roleName", roleName), new NameValuePair("permissionIds", "hudson.model.Item.Configure,hudson.model.Item.Discover,hudson.model.Item.Build,hudson.model.Item.Read"), new NameValuePair("overwrite", "false"), new NameValuePair("pattern", pattern))); Page page = webClient.getPage(request); assertEquals(HttpURLConnection.HTTP_OK, page.getWebResponse().getStatusCode(), "Testing if request is successful"); // Verifying that the role is in RoleBasedAuthorizationStrategy strategy = RoleBasedAuthorizationStrategy.getInstance(); SortedMap<Role, Set<PermissionEntry>> grantedRoles = strategy.getGrantedRolesEntries(RoleType.Project); boolean foundRole = false; for (Map.Entry<Role, Set<PermissionEntry>> entry : grantedRoles.entrySet()) { Role role = entry.getKey(); if (role.getName().equals("new-role") && role.getPattern().pattern().equals(pattern)) { foundRole = true; break; } } assertTrue(foundRole, "Checking if the role is found."); } @Test void testAddRoleAs() throws Exception { String pattern = "test-folder.*"; // Loop through each execution and perform the request for (Map<String, Object> execution : getExecutions) { String username = (String) execution.get("username"); int expectedCode = (int) execution.get("expectedCode"); RoleType roleType = (RoleType) execution.get("roleType"); String roleTypeStr = roleType.getStringType(); String roleName = "testAddRoleAs" + username + roleType.getStringType(); URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/addRole"); WebRequest request = new WebRequest(apiUrl, HttpMethod.POST); request.setRequestParameters( Arrays.asList(new NameValuePair("type", roleTypeStr), new NameValuePair("roleName", roleName), new NameValuePair("permissionIds", roleTypeToPermissionIds.get(roleTypeStr)), new NameValuePair("overwrite", "false"), new NameValuePair("pattern", pattern))); performAsAndExpect(username, request, expectedCode, roleTypeStr); if (expectedCode == HttpURLConnection.HTTP_OK) { // Verifying that the role is in RoleBasedAuthorizationStrategy strategy = RoleBasedAuthorizationStrategy.getInstance(); Assertions.assertNotNull(strategy); SortedMap<Role, Set<PermissionEntry>> grantedRoles = strategy.getGrantedRolesEntries(roleType); boolean foundRole = false; for (Map.Entry<Role, Set<PermissionEntry>> entry : grantedRoles.entrySet()) { Role role = entry.getKey(); if (role.getName().equals(roleName)) { if (roleType != RoleType.Global && !role.getPattern().pattern().equals(pattern)) { // If the role is a project role, check if the pattern matches continue; } foundRole = true; break; } } assertTrue(foundRole, "Checking if the role is found for user: " + username); } } } @Test void testAddRoleWithTemplate() throws IOException { String roleName = "new-role"; String pattern = "test-folder.*"; String template = "developer"; // Adding role via web request URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/addRole"); WebRequest request = new WebRequest(apiUrl, HttpMethod.POST); request.setRequestParameters( Arrays.asList(new NameValuePair("type", RoleType.Project.getStringType()), new NameValuePair("roleName", roleName), new NameValuePair("permissionIds", "hudson.model.Item.Configure,hudson.model.Item.Read"), new NameValuePair("overwrite", "false"), new NameValuePair("pattern", pattern), new NameValuePair("template", template))); Page page = webClient.getPage(request); assertEquals(HttpURLConnection.HTTP_OK, page.getWebResponse().getStatusCode(), "Testing if request is successful"); // Verifying that the role is in SortedMap<Role, Set<PermissionEntry>> grantedRoles = rbas.getGrantedRolesEntries(RoleType.Project); Role role = null; for (Map.Entry<Role, Set<PermissionEntry>> entry : grantedRoles.entrySet()) { role = entry.getKey(); if (role.getName().equals("new-role") && role.getPattern().pattern().equals(pattern) && role.getTemplateName().equals(template)) { break; } role = null; } assertThat(role, notNullValue()); assertThat(role.hasPermission(Item.CONFIGURE), equalTo(false)); assertThat(role.hasPermission(Item.BUILD), equalTo(true)); } @Test void testAddRoleWithMissingTemplate() throws IOException { String roleName = "new-role"; String pattern = "test-folder.*"; String template = "quality"; // Adding role via web request URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/addRole"); WebRequest request = new WebRequest(apiUrl, HttpMethod.POST); request.setRequestParameters( Arrays.asList(new NameValuePair("type", RoleType.Project.getStringType()), new NameValuePair("roleName", roleName), new NameValuePair("permissionIds", "hudson.model.Item.Configure,hudson.model.Item.Discover,hudson.model.Item.Build,hudson.model.Item.Read"), new NameValuePair("overwrite", "false"), new NameValuePair("pattern", pattern), new NameValuePair("template", template))); Page page = webClient.getPage(request); assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, page.getWebResponse().getStatusCode(), "Testing if request failed"); } @Test void testAddTemplate() throws IOException { String template = "quality"; // Adding role via web request URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/addTemplate"); WebRequest request = new WebRequest(apiUrl, HttpMethod.POST); request.setRequestParameters( Arrays.asList(new NameValuePair("name", template), new NameValuePair("permissionIds", "hudson.model.Item.Read"), new NameValuePair("overwrite", "false"))); Page page = webClient.getPage(request); assertEquals(HttpURLConnection.HTTP_OK, page.getWebResponse().getStatusCode(), "Testing if request is successful"); // Verifying that the role is in PermissionTemplate pt = rbas.getPermissionTemplate(template); assertThat(pt, notNullValue()); assertThat(pt.getName(), equalTo(template)); assertThat(pt.hasPermission(Item.READ), equalTo(true)); } @Test void testAddExistingTemplate() throws IOException { String template = "developer"; // Adding role via web request URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/addTemplate"); WebRequest request = new WebRequest(apiUrl, HttpMethod.POST); request.setRequestParameters( Arrays.asList(new NameValuePair("name", template), new NameValuePair("permissionIds", "hudson.model.Item.Read"), new NameValuePair("overwrite", "false"))); Page page = webClient.getPage(request); assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, page.getWebResponse().getStatusCode(), "Testing if request is failed"); } @Test void testGetTemplate() throws IOException { String url = jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/getTemplate?name=developer"; URL apiUrl = new URL(url); WebRequest request = new WebRequest(apiUrl, HttpMethod.GET); Page page = webClient.getPage(request); // Verifying that web request is successful and that the role is found assertEquals(HttpURLConnection.HTTP_OK, page.getWebResponse().getStatusCode(), "Testing if request is successful"); String templateString = page.getWebResponse().getContentAsString(); JSONObject responseJson = JSONObject.fromObject(templateString); assertThat(responseJson.get("isUsed"), equalTo(true)); } @Test void testRemoveTemplate() throws IOException { String url = jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/removeTemplates"; rbas.doAddTemplate("quality", "Job/Read,Job/Workspace", false); rbas.doAddTemplate("unused", "hudson.model.Item.Read", false); rbas.doAddRole("projectRoles", "qa", "", "false", ".*", "quality"); URL apiUrl = new URL(url); WebRequest request = new WebRequest(apiUrl, HttpMethod.POST); request.setRequestParameters( Arrays.asList(new NameValuePair("names", "unused,quality"), new NameValuePair("force", "false"))); Page page = webClient.getPage(request); // Verifying that web request is successful assertEquals(HttpURLConnection.HTTP_OK, page.getWebResponse().getStatusCode(), "Testing if request is successful"); Role role = rbas.getRoleMap(RoleType.Project).getRole("qa"); assertThat(role.getTemplateName(), is("quality")); assertThat(role.hasPermission(Item.WORKSPACE), is(true)); assertThat(rbas.hasPermissionTemplate("unused"), is(false)); assertThat(rbas.hasPermissionTemplate("quality"), is(true)); } @Test void testForceRemoveTemplate() throws IOException { String url = jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/removeTemplates"; URL apiUrl = new URL(url); WebRequest request = new WebRequest(apiUrl, HttpMethod.POST); request.setRequestParameters( Arrays.asList(new NameValuePair("names", "developer,unknown"), new NameValuePair("force", "true"))); Page page = webClient.getPage(request); // Verifying that web request is successful assertEquals(HttpURLConnection.HTTP_OK, page.getWebResponse().getStatusCode(), "Testing if request is successful"); Role role = rbas.getRoleMap(RoleType.Project).getRole("developers"); assertThat(role.getTemplateName(), is(nullValue())); assertThat(role.hasPermission(Item.BUILD), is(true)); assertThat(rbas.hasPermissionTemplate("developer"), is(false)); } @Test void testGetRole() throws IOException { String url = jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/getRole?type=" + RoleType.Global.getStringType() + "&roleName=adminRole"; URL apiUrl = new URL(url); WebRequest request = new WebRequest(apiUrl, HttpMethod.GET); Page page = webClient.getPage(request); // Verifying that web request is successful and that the role is found assertEquals(HttpURLConnection.HTTP_OK, page.getWebResponse().getStatusCode(), "Testing if request is successful"); String roleString = page.getWebResponse().getContentAsString(); assertTrue(roleString.length() > 2); assertNotEquals("{}", roleString); // {} is returned when no role is found } @Test @Issue("JENKINS-61470") void testAssignRole() throws IOException { String roleName = "new-role"; String sid = "alice"; PermissionEntry sidEntry = new PermissionEntry(AuthorizationType.EITHER, sid); Authentication alice = User.getById(sid, true).impersonate2(); // Confirming that alice does not have access before assigning MockFolder folder = jenkinsRule.createFolder("test-folder"); assertFalse(folder.hasPermission2(alice, Item.CONFIGURE)); // Assigning role using web request testAddRole(); // adds a role "new-role" that has configure access on "test-folder.*" URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/assignRole"); WebRequest request = new WebRequest(apiUrl, HttpMethod.POST); request.setRequestParameters(Arrays.asList(new NameValuePair("type", RoleType.Project.getStringType()), new NameValuePair("roleName", roleName), new NameValuePair("sid", sid))); Page page = webClient.getPage(request); assertEquals(HttpURLConnection.HTTP_OK, page.getWebResponse().getStatusCode(), "Testing if request is successful"); // Verifying that alice is assigned to the role "new-role" SortedMap<Role, Set<PermissionEntry>> roles = rbas.getGrantedRolesEntries(RoleType.Project); boolean found = false; for (Map.Entry<Role, Set<PermissionEntry>> entry : roles.entrySet()) { Role role = entry.getKey(); Set<PermissionEntry> sids = entry.getValue(); if (role.getName().equals(roleName) && sids.contains(sidEntry)) { found = true; break; } } assertTrue(found); // Verifying that ACL is updated assertTrue(folder.hasPermission2(alice, Item.CONFIGURE)); } @Test @Issue("JENKINS-61470") void testUnassignRole() throws IOException { String roleName = "new-role"; String sid = "alice"; PermissionEntry sidEntry = new PermissionEntry(AuthorizationType.EITHER, sid); testAssignRole(); // assign alice to a role named "new-role" that has configure access to "test-folder.*" URL apiURL = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/unassignRole"); WebRequest request = new WebRequest(apiURL, HttpMethod.POST); request.setRequestParameters(Arrays.asList(new NameValuePair("type", RoleType.Project.getStringType()), new NameValuePair("roleName", roleName), new NameValuePair("sid", sid))); Page page = webClient.getPage(request); assertEquals(HttpURLConnection.HTTP_OK, page.getWebResponse().getStatusCode(), "Testing if request is successful"); // Verifying that alice no longer has permissions SortedMap<Role, Set<PermissionEntry>> roles = rbas.getGrantedRolesEntries(RoleType.Project); for (Map.Entry<Role, Set<PermissionEntry>> entry : roles.entrySet()) { Role role = entry.getKey(); Set<PermissionEntry> sids = entry.getValue(); assertFalse(role.getName().equals("new-role") && sids.contains(sidEntry), "Checking if Alice is still assigned to new-role"); } // Verifying that ACL is updated Authentication alice = User.getById("alice", false).impersonate2(); Item folder = jenkinsRule.jenkins.getItemByFullName("test-folder"); assertFalse(folder.hasPermission2(alice, Item.CONFIGURE)); } @Test void testAssignUserRole() throws IOException { String roleName = "new-role"; String sid = "alice"; PermissionEntry sidEntry = new PermissionEntry(AuthorizationType.USER, sid); Authentication alice = User.getById(sid, true).impersonate2(); // Confirming that alice does not have access before assigning MockFolder folder = jenkinsRule.createFolder("test-folder"); assertFalse(folder.hasPermission2(alice, Item.CONFIGURE)); // Assigning role using web request testAddRole(); // adds a role "new-role" that has configure access on "test-folder.*" URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/assignUserRole"); WebRequest request = new WebRequest(apiUrl, HttpMethod.POST); request.setRequestParameters(Arrays.asList(new NameValuePair("type", RoleType.Project.getStringType()), new NameValuePair("roleName", roleName), new NameValuePair("user", sid))); Page page = webClient.getPage(request); assertEquals(HttpURLConnection.HTTP_OK, page.getWebResponse().getStatusCode(), "Testing if request is successful"); // Verifying that alice is assigned to the role "new-role" SortedMap<Role, Set<PermissionEntry>> roles = rbas.getGrantedRolesEntries(RoleType.Project); boolean found = false; for (Map.Entry<Role, Set<PermissionEntry>> entry : roles.entrySet()) { Role role = entry.getKey(); Set<PermissionEntry> sids = entry.getValue(); if (role.getName().equals(roleName) && sids.contains(sidEntry)) { found = true; break; } } assertTrue(found); // Verifying that ACL is updated assertTrue(folder.hasPermission2(alice, Item.CONFIGURE)); } @Test void testUnassignUserRole() throws IOException { String roleName = "new-role"; String sid = "alice"; PermissionEntry sidEntry = new PermissionEntry(AuthorizationType.USER, sid); testAssignUserRole(); // assign alice to a role named "new-role" that has configure access to "test-folder.*" URL apiURL = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/unassignUserRole"); WebRequest request = new WebRequest(apiURL, HttpMethod.POST); request.setRequestParameters(Arrays.asList(new NameValuePair("type", RoleType.Project.getStringType()), new NameValuePair("roleName", roleName), new NameValuePair("user", sid))); Page page = webClient.getPage(request); assertEquals(HttpURLConnection.HTTP_OK, page.getWebResponse().getStatusCode(), "Testing if request is successful"); // Verifying that alice no longer has permissions SortedMap<Role, Set<PermissionEntry>> roles = rbas.getGrantedRolesEntries(RoleType.Project); for (Map.Entry<Role, Set<PermissionEntry>> entry : roles.entrySet()) { Role role = entry.getKey(); Set<PermissionEntry> sids = entry.getValue(); assertFalse(role.getName().equals("new-role") && sids.contains(sidEntry), "Checking if Alice is still assigned to new-role"); } // Verifying that ACL is updated Authentication alice = User.getById("alice", false).impersonate2(); Item folder = jenkinsRule.jenkins.getItemByFullName("test-folder"); assertFalse(folder.hasPermission2(alice, Item.CONFIGURE)); } @Test void testAssignGroupRole() throws IOException { String roleName = "new-role"; String sid = "alice"; String group = "group"; PermissionEntry sidEntry = new PermissionEntry(AuthorizationType.GROUP, group); User user = User.getById(sid, true); securityRealm.addGroups(sid, group); Authentication alice = user.impersonate2(); // Confirming that alice does not have access before assigning MockFolder folder = jenkinsRule.createFolder("test-folder"); assertFalse(folder.hasPermission2(alice, Item.CONFIGURE)); // Assigning role using web request testAddRole(); // adds a role "new-role" that has configure access on "test-folder.*" URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/assignGroupRole"); WebRequest request = new WebRequest(apiUrl, HttpMethod.POST); request.setRequestParameters(Arrays.asList(new NameValuePair("type", RoleType.Project.getStringType()), new NameValuePair("roleName", roleName), new NameValuePair("group", group))); Page page = webClient.getPage(request); assertEquals(HttpURLConnection.HTTP_OK, page.getWebResponse().getStatusCode(), "Testing if request is successful"); // Verifying that alice is assigned to the role "new-role" SortedMap<Role, Set<PermissionEntry>> roles = rbas.getGrantedRolesEntries(RoleType.Project); boolean found = false; for (Map.Entry<Role, Set<PermissionEntry>> entry : roles.entrySet()) { Role role = entry.getKey(); Set<PermissionEntry> sids = entry.getValue(); if (role.getName().equals(roleName) && sids.contains(sidEntry)) { found = true; break; } } assertTrue(found); // Verifying that ACL is updated assertTrue(folder.hasPermission2(alice, Item.CONFIGURE)); } @Test void testUnassignGroupRole() throws IOException { String roleName = "new-role"; String sid = "alice"; String group = "group"; PermissionEntry sidEntry = new PermissionEntry(AuthorizationType.USER, sid); testAssignGroupRole(); // assign alice to a role named "new-role" that has configure access to "test-folder.*" URL apiURL = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/unassignGroupRole"); WebRequest request = new WebRequest(apiURL, HttpMethod.POST); request.setRequestParameters(Arrays.asList(new NameValuePair("type", RoleType.Project.getStringType()), new NameValuePair("roleName", roleName), new NameValuePair("group", group))); Page page = webClient.getPage(request); assertEquals(HttpURLConnection.HTTP_OK, page.getWebResponse().getStatusCode(), "Testing if request is successful"); // Verifying that alice no longer has permissions SortedMap<Role, Set<PermissionEntry>> roles = rbas.getGrantedRolesEntries(RoleType.Project); for (Map.Entry<Role, Set<PermissionEntry>> entry : roles.entrySet()) { Role role = entry.getKey(); Set<PermissionEntry> sids = entry.getValue(); assertFalse(role.getName().equals("new-role") && sids.contains(sidEntry), "Checking if Alice is still assigned to new-role"); } // Verifying that ACL is updated Authentication alice = User.getById("alice", false).impersonate2(); Item folder = jenkinsRule.jenkins.getItemByFullName("test-folder"); assertFalse(folder.hasPermission2(alice, Item.CONFIGURE)); } @Test void ignoreDangerousPermissionInAddRole() throws IOException { String roleName = "new-role"; // Adding role via web request URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/addRole"); WebRequest request = new WebRequest(apiUrl, HttpMethod.POST); request.setRequestParameters( Arrays.asList(new NameValuePair("type", RoleType.Global.getStringType()), new NameValuePair("roleName", roleName), new NameValuePair("permissionIds", "hudson.model.Hudson.RunScripts,hudson.model.Hudson.ConfigureUpdateCenter," + "hudson.model.Hudson.UploadPlugins,hudson.model.Item.Read"), new NameValuePair("overwrite", "false"))); Page page = webClient.getPage(request); assertEquals(HttpURLConnection.HTTP_OK, page.getWebResponse().getStatusCode(), "Testing if request is successful"); // Verifying that the role is in assertThat(rbas.getRoleMap(RoleType.Global).getRole(roleName).hasPermission(PluginManager.CONFIGURE_UPDATECENTER), is(false)); assertThat(rbas.getRoleMap(RoleType.Global).getRole(roleName).hasPermission(PluginManager.UPLOAD_PLUGINS), is(false)); assertThat(rbas.getRoleMap(RoleType.Global).getRole(roleName).hasPermission(Jenkins.RUN_SCRIPTS), is(false)); assertThat(rbas.getRoleMap(RoleType.Global).getRole(roleName).hasPermission(Item.READ), is(true)); } @Test void testRemoveRolesAs() throws Exception { String pattern = "test-folder.*"; // Create roles first for (Map<String, Object> execution : getExecutions) { String username = (String) execution.get("username"); RoleType roleType = (RoleType) execution.get("roleType"); String roleTypeStr = roleType.getStringType(); String roleName = "testRemoveRolesAs" + username + roleType.getStringType(); rbas.doAddRole(roleTypeStr, roleName, roleTypeToPermissionIds.get(roleTypeStr), "false", pattern, ""); } // Now test removal with different users for (Map<String, Object> execution : getExecutions) { String username = (String) execution.get("username"); int expectedCode = (int) execution.get("expectedCode"); RoleType roleType = (RoleType) execution.get("roleType"); String roleTypeStr = roleType.getStringType(); String roleName = "testRemoveRolesAs" + username + roleType.getStringType(); URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/removeRoles"); WebRequest request = new WebRequest(apiUrl, HttpMethod.POST); request.setRequestParameters( Arrays.asList( new NameValuePair("type", roleTypeStr), new NameValuePair("roleNames", roleName) ) ); performAsAndExpect(username, request, expectedCode, roleTypeStr); // Verify the role state RoleBasedAuthorizationStrategy strategy = RoleBasedAuthorizationStrategy.getInstance(); Assertions.assertNotNull(strategy); Role role = strategy.getRoleMap(roleType).getRole(roleName); if (expectedCode == HttpURLConnection.HTTP_OK) { assertThat("Role should be removed for user: " + username, role, nullValue()); } else { assertThat("Role should still exist for user: " + username, role, notNullValue()); } } } @Test void testGetRoleAs() throws Exception { for (Map<String, Object> execution : getExecutions) { String username = (String) execution.get("username"); int expectedCode = (int) execution.get("expectedCode"); RoleType roleType = (RoleType) execution.get("roleType"); String roleTypeStr = roleType.getStringType(); // Use existing roles from setup String roleName = roleType == RoleType.Global ? "adminRole" : roleType == RoleType.Project ? "developers" : "developerAgentRole"; URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/getRole?type=" + roleTypeStr + "&roleName=" + roleName); WebRequest request = new WebRequest(apiUrl, HttpMethod.GET); performAsAndExpect(username, request, expectedCode, roleTypeStr); if (expectedCode == HttpURLConnection.HTTP_OK) { webClient.login(username, username); Page page = webClient.getPage(request); String content = page.getWebResponse().getContentAsString(); JSONObject json = JSONObject.fromObject(content); assertThat("Response should contain permissionIds for user: " + username, json.has("permissionIds"), is(true)); assertThat("Response should contain sids for user: " + username, json.has("sids"), is(true)); } } } @Test void testGetAllRolesAs() throws Exception { for (Map<String, Object> execution : getExecutions) { String username = (String) execution.get("username");
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
true
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/com/michelin/cio/hudson/plugins/rolestrategy/RoleTest.java
src/test/java/com/michelin/cio/hudson/plugins/rolestrategy/RoleTest.java
package com.michelin.cio.hudson.plugins.rolestrategy; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import hudson.security.Permission; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.junit.jupiter.api.Test; class RoleTest { @Test void testHasPermission() { Role role = new Role("name", new HashSet<>(Arrays.asList(Permission.CREATE, Permission.READ, Permission.DELETE))); assertTrue(role.hasPermission(Permission.READ)); assertFalse(role.hasPermission(Permission.WRITE)); } @Test void testHasAnyPermissions() { Role role = new Role("name", new HashSet<>((Arrays.asList(Permission.READ, Permission.DELETE)))); assertTrue(role.hasAnyPermission(new HashSet<>(Arrays.asList(Permission.READ, Permission.WRITE)))); assertFalse(role.hasAnyPermission(new HashSet<>(Arrays.asList(Permission.UPDATE, Permission.WRITE)))); } @Test void shouldNotAddNullPermToNewRole() { Permission permission = Permission.CREATE; Permission nullPerm = null; Set<Permission> perms = new HashSet<>(Arrays.asList(permission, nullPerm)); // Test with modifiable collections Role role = new Role("name", perms); assertThat("With modifiable set", role.getPermissions(), not(hasItem(nullPerm))); // Test with unmodifiable collections role = new Role("name", Collections.unmodifiableSet(perms)); assertThat("With unmodifiable set", role.getPermissions(), not(hasItem(nullPerm))); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/com/michelin/cio/hudson/plugins/rolestrategy/ApiWithFineGrainedRolesTest.java
src/test/java/com/michelin/cio/hudson/plugins/rolestrategy/ApiWithFineGrainedRolesTest.java
package com.michelin.cio.hudson.plugins.rolestrategy; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import com.synopsys.arc.jenkins.plugins.rolestrategy.RoleType; import java.net.HttpURLConnection; import java.net.URL; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import net.sf.json.JSONObject; import org.htmlunit.HttpMethod; import org.htmlunit.Page; import org.htmlunit.WebRequest; import org.htmlunit.util.NameValuePair; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.JenkinsRule.DummySecurityRealm; import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** * Tests for {@link RoleBasedAuthorizationStrategy} Web API Methods. */ @WithJenkins class ApiWithFineGrainedRolesTest { static { RoleBasedAuthorizationStrategy.ITEM_ROLES_ADMIN.setEnabled(true); RoleBasedAuthorizationStrategy.AGENT_ROLES_ADMIN.setEnabled(true); } // Note: Reading Global roles requires SYSTEM_READ, which itemAdminUser and agentAdminUser don't have private static final List<Map<String, Object>> getExecutions = Arrays.asList( Map.of("username", "adminUser", "expectedCode", HttpURLConnection.HTTP_OK, "roleType", RoleType.Global), Map.of("username", "adminUser", "expectedCode", HttpURLConnection.HTTP_OK, "roleType", RoleType.Project), Map.of("username", "adminUser", "expectedCode", HttpURLConnection.HTTP_OK, "roleType", RoleType.Slave), Map.of("username", "itemAdminUser", "expectedCode", HttpURLConnection.HTTP_FORBIDDEN, "roleType", RoleType.Global), Map.of("username", "itemAdminUser", "expectedCode", HttpURLConnection.HTTP_OK, "roleType", RoleType.Project), Map.of("username", "itemAdminUser", "expectedCode", HttpURLConnection.HTTP_FORBIDDEN, "roleType", RoleType.Slave), Map.of("username", "agentAdminUser", "expectedCode", HttpURLConnection.HTTP_FORBIDDEN, "roleType", RoleType.Global), Map.of("username", "agentAdminUser", "expectedCode", HttpURLConnection.HTTP_FORBIDDEN, "roleType", RoleType.Project), Map.of("username", "agentAdminUser", "expectedCode", HttpURLConnection.HTTP_OK, "roleType", RoleType.Slave), Map.of("username", "developerUser", "expectedCode", HttpURLConnection.HTTP_FORBIDDEN, "roleType", RoleType.Global), Map.of("username", "developerUser", "expectedCode", HttpURLConnection.HTTP_FORBIDDEN, "roleType", RoleType.Project), Map.of("username", "developerUser", "expectedCode", HttpURLConnection.HTTP_FORBIDDEN, "roleType", RoleType.Slave) ); private JenkinsRule jenkinsRule; private JenkinsRule.WebClient webClient; private DummySecurityRealm securityRealm; private RoleBasedAuthorizationStrategy rbas; private final Map<String, String> roleTypeToPermissionIds = Map.of( RoleType.Global.getStringType(), "hudson.model.Hudson.Read,hudson.model.Hudson.Administer,hudson.security.Permission.GenericRead", RoleType.Project.getStringType(), "hudson.model.Item.Read,hudson.model.Item.Build,hudson.model.Item.Cancel", RoleType.Slave.getStringType(), "hudson.model.Computer.Connect,hudson.model.Computer.Create" ); @BeforeEach void setUp(JenkinsRule jenkinsRule) throws Exception { this.jenkinsRule = jenkinsRule; // Setting up jenkins configurations securityRealm = jenkinsRule.createDummySecurityRealm(); jenkinsRule.jenkins.setSecurityRealm(securityRealm); rbas = new RoleBasedAuthorizationStrategy(); jenkinsRule.jenkins.setAuthorizationStrategy(rbas); jenkinsRule.jenkins.setCrumbIssuer(null); // Adding admin role and assigning adminUser rbas.doAddRole("globalRoles", "adminRole", "hudson.model.Hudson.Read,hudson.model.Hudson.Administer,hudson.security.Permission.GenericRead", "false", "", ""); rbas.doAssignUserRole("globalRoles", "adminRole", "adminUser"); // Adding itemAdmin and assigning itemAdminUser rbas.doAddRole("globalRoles", "itemAdminRole", "hudson.model.Hudson.Read," + RoleBasedAuthorizationStrategy.ITEM_ROLES_ADMIN.getId(), "false", "", ""); rbas.doAssignUserRole("globalRoles", "itemAdminRole", "itemAdminUser"); // Adding agentAdmin and assigning agentAdminUser rbas.doAddRole("globalRoles", "agentAdminRole", "hudson.model.Hudson.Read," + RoleBasedAuthorizationStrategy.AGENT_ROLES_ADMIN.getId(), "false", "", ""); rbas.doAssignUserRole("globalRoles", "agentAdminRole", "agentAdminUser"); // Adding developer role and assigning developerUser rbas.doAddTemplate("developer", "hudson.model.Item.Read,hudson.model.Item.Build,hudson.model.Item.Cancel", false); rbas.doAddRole("projectRoles", "developers", "", "false", ".*", "developer"); rbas.doAssignUserRole("projectRoles", "developers", "developerUser"); // Adding developerAgent role and assigning developerAgentUser rbas.doAddRole("slaveRoles", "developerAgentRole", "hudson.model.Computer.Connect", "false", ".*", ""); rbas.doAssignUserRole("slaveRoles", "developerAgentRole", "developerUser"); webClient = jenkinsRule.createWebClient().withThrowExceptionOnFailingStatusCode(false); webClient.login("adminUser", "adminUser"); } private void performAsAndExpect(String username, WebRequest request, int expectedCode, String roleTypeStr) throws Exception { webClient.login(username, username); Page page = webClient.getPage(request); assertEquals(expectedCode, page.getWebResponse().getStatusCode(), "HTTP code mismatch for user " + username + " with roleType " + roleTypeStr); } @Test void testAddRoleAs() throws Exception { String pattern = "test-folder.*"; // Loop through each execution and perform the request for (Map<String, Object> execution : getExecutions) { String username = (String) execution.get("username"); int expectedCode = (int) execution.get("expectedCode"); RoleType roleType = (RoleType) execution.get("roleType"); String roleTypeStr = roleType.getStringType(); String roleName = "testAddRoleAs" + username + roleType.getStringType(); URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/addRole"); WebRequest request = new WebRequest(apiUrl, HttpMethod.POST); request.setRequestParameters( Arrays.asList(new NameValuePair("type", roleTypeStr), new NameValuePair("roleName", roleName), new NameValuePair("permissionIds", roleTypeToPermissionIds.get(roleTypeStr)), new NameValuePair("overwrite", "false"), new NameValuePair("pattern", pattern))); performAsAndExpect(username, request, expectedCode, roleTypeStr); if (expectedCode == HttpURLConnection.HTTP_OK) { // Verifying that the role is in RoleBasedAuthorizationStrategy strategy = RoleBasedAuthorizationStrategy.getInstance(); Assertions.assertNotNull(strategy); SortedMap<Role, Set<PermissionEntry>> grantedRoles = strategy.getGrantedRolesEntries(roleType); boolean foundRole = false; for (Map.Entry<Role, Set<PermissionEntry>> entry : grantedRoles.entrySet()) { Role role = entry.getKey(); if (role.getName().equals(roleName)) { if (roleType != RoleType.Global && !role.getPattern().pattern().equals(pattern)) { // If the role is a project role, check if the pattern matches continue; } foundRole = true; break; } } assertTrue(foundRole, "Checking if the role is found for user: " + username); } } } @Test void testRemoveRolesAs() throws Exception { String pattern = "test-folder.*"; // Create roles first for (Map<String, Object> execution : getExecutions) { String username = (String) execution.get("username"); RoleType roleType = (RoleType) execution.get("roleType"); String roleTypeStr = roleType.getStringType(); String roleName = "testRemoveRolesAs" + username + roleType.getStringType(); rbas.doAddRole(roleTypeStr, roleName, roleTypeToPermissionIds.get(roleTypeStr), "false", pattern, ""); } // Now test removal with different users for (Map<String, Object> execution : getExecutions) { String username = (String) execution.get("username"); int expectedCode = (int) execution.get("expectedCode"); RoleType roleType = (RoleType) execution.get("roleType"); String roleTypeStr = roleType.getStringType(); String roleName = "testRemoveRolesAs" + username + roleType.getStringType(); URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/removeRoles"); WebRequest request = new WebRequest(apiUrl, HttpMethod.POST); request.setRequestParameters( Arrays.asList( new NameValuePair("type", roleTypeStr), new NameValuePair("roleNames", roleName) ) ); performAsAndExpect(username, request, expectedCode, roleTypeStr); // Verify the role state RoleBasedAuthorizationStrategy strategy = RoleBasedAuthorizationStrategy.getInstance(); Assertions.assertNotNull(strategy); Role role = strategy.getRoleMap(roleType).getRole(roleName); if (expectedCode == HttpURLConnection.HTTP_OK) { assertThat("Role should be removed for user: " + username, role, nullValue()); } else { assertThat("Role should still exist for user: " + username, role, notNullValue()); } } } @Test void testGetRoleAs() throws Exception { for (Map<String, Object> execution : getExecutions) { String username = (String) execution.get("username"); int expectedCode = (int) execution.get("expectedCode"); RoleType roleType = (RoleType) execution.get("roleType"); String roleTypeStr = roleType.getStringType(); // Use existing roles from setup String roleName = roleType == RoleType.Global ? "adminRole" : roleType == RoleType.Project ? "developers" : "developerAgentRole"; URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/getRole?type=" + roleTypeStr + "&roleName=" + roleName); WebRequest request = new WebRequest(apiUrl, HttpMethod.GET); performAsAndExpect(username, request, expectedCode, roleTypeStr); if (expectedCode == HttpURLConnection.HTTP_OK) { webClient.login(username, username); Page page = webClient.getPage(request); String content = page.getWebResponse().getContentAsString(); JSONObject json = JSONObject.fromObject(content); assertThat("Response should contain permissionIds for user: " + username, json.has("permissionIds"), is(true)); assertThat("Response should contain sids for user: " + username, json.has("sids"), is(true)); } } } @Test void testGetAllRolesAs() throws Exception { for (Map<String, Object> execution : getExecutions) { String username = (String) execution.get("username"); int expectedCode = (int) execution.get("expectedCode"); RoleType roleType = (RoleType) execution.get("roleType"); String roleTypeStr = roleType.getStringType(); URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/getAllRoles?type=" + roleTypeStr); WebRequest request = new WebRequest(apiUrl, HttpMethod.GET); performAsAndExpect(username, request, expectedCode, roleTypeStr); if (expectedCode == HttpURLConnection.HTTP_OK) { webClient.login(username, username); Page page = webClient.getPage(request); String content = page.getWebResponse().getContentAsString(); JSONObject json = JSONObject.fromObject(content); assertThat("Response should be a JSON object for user: " + username, json.isEmpty(), is(false)); } } } @Test void testGetRoleAssignmentsAs() throws Exception { for (Map<String, Object> execution : getExecutions) { String username = (String) execution.get("username"); int expectedCode = (int) execution.get("expectedCode"); RoleType roleType = (RoleType) execution.get("roleType"); String roleTypeStr = roleType.getStringType(); URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/getRoleAssignments?type=" + roleTypeStr); WebRequest request = new WebRequest(apiUrl, HttpMethod.GET); performAsAndExpect(username, request, expectedCode, roleTypeStr); if (expectedCode == HttpURLConnection.HTTP_OK) { webClient.login(username, username); Page page = webClient.getPage(request); String content = page.getWebResponse().getContentAsString(); net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(content); // Should return an array of user/group assignments with their roles assertThat("Response should be a JSON array for user: " + username, jsonArray, notNullValue()); } } } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/com/michelin/cio/hudson/plugins/rolestrategy/GrantingDisabledPermissionTest.java
src/test/java/com/michelin/cio/hudson/plugins/rolestrategy/GrantingDisabledPermissionTest.java
package com.michelin.cio.hudson.plugins.rolestrategy; import static org.junit.jupiter.api.Assertions.assertFalse; import hudson.model.User; import hudson.security.ACL; import hudson.security.ACLContext; import hudson.security.HudsonPrivateSecurityRealm; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import jenkins.model.Jenkins; import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.junit.jupiter.WithJenkins; @WithJenkins class GrantingDisabledPermissionTest { @Test void grantDisabledPermissionTest(JenkinsRule r) throws Exception { HudsonPrivateSecurityRealm realm = new HudsonPrivateSecurityRealm(true, false, null); realm.createAccount("admin", "admin"); realm.createAccount("alice", "alice"); r.jenkins.setSecurityRealm(realm); RoleMap roleMap = new RoleMap(); Role adminRole = new Role("admin-role", new HashSet<>(Collections.singletonList(Jenkins.ADMINISTER))); roleMap.addRole(adminRole); Role manage = new Role("system-read-role", new HashSet<>(Collections.singletonList(Jenkins.SYSTEM_READ))); roleMap.addRole(manage); roleMap.assignRole(adminRole, "admin"); roleMap.assignRole(manage, "alice"); Map<String, RoleMap> constructorArg = new HashMap<>(); constructorArg.put("globalRoles", roleMap); r.jenkins.setAuthorizationStrategy(new RoleBasedAuthorizationStrategy(constructorArg)); try (ACLContext ctx = ACL.as2(User.get("alice").impersonate2())) { assertFalse(Jenkins.get().hasPermission(Jenkins.SYSTEM_READ)); } } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/org/jenkinsci/plugins/rolestrategy/FormSubmissionPermissionsTest.java
src/test/java/org/jenkinsci/plugins/rolestrategy/FormSubmissionPermissionsTest.java
package org.jenkinsci.plugins.rolestrategy; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; import static org.junit.jupiter.api.Assertions.assertEquals; import com.michelin.cio.hudson.plugins.rolestrategy.Role; import com.michelin.cio.hudson.plugins.rolestrategy.RoleBasedAuthorizationStrategy; import com.synopsys.arc.jenkins.plugins.rolestrategy.RoleType; import java.net.HttpURLConnection; import java.net.URL; import org.htmlunit.HttpMethod; import org.htmlunit.Page; import org.htmlunit.WebRequest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** * Tests for permission-based access control on form submission wrapper methods. * These tests verify that the entry-level permission checks work correctly. * The actual form processing logic is tested through the REST API endpoints. * * Note: Form submission handlers (doRolesSubmit, doAssignSubmit, doTemplatesSubmit) * check minimum permissions at entry, then delegate to descriptor methods that use * selective filtering (processing sections the user has permission for, copying * unauthorized sections from the old strategy). This selective filtering behavior * is complex to test at the form submission level and is better verified through * the REST API tests. */ @WithJenkins class FormSubmissionPermissionsTest { static { RoleBasedAuthorizationStrategy.ITEM_ROLES_ADMIN.setEnabled(true); RoleBasedAuthorizationStrategy.AGENT_ROLES_ADMIN.setEnabled(true); } private JenkinsRule jenkinsRule; private JenkinsRule.WebClient webClient; private RoleBasedAuthorizationStrategy rbas; @BeforeEach void setUp(JenkinsRule jenkinsRule) throws Exception { this.jenkinsRule = jenkinsRule; // Setting up jenkins configurations JenkinsRule.DummySecurityRealm securityRealm = jenkinsRule.createDummySecurityRealm(); jenkinsRule.jenkins.setSecurityRealm(securityRealm); rbas = new RoleBasedAuthorizationStrategy(); jenkinsRule.jenkins.setAuthorizationStrategy(rbas); jenkinsRule.jenkins.setCrumbIssuer(null); // Adding admin role and assigning adminUser rbas.doAddRole("globalRoles", "adminRole", "hudson.model.Hudson.Read,hudson.model.Hudson.Administer,hudson.security.Permission.GenericRead", "false", "", ""); rbas.doAssignUserRole("globalRoles", "adminRole", "adminUser"); // Adding itemAdmin role and assigning itemAdminUser rbas.doAddRole("globalRoles", "itemAdminRole", "hudson.model.Hudson.Read," + RoleBasedAuthorizationStrategy.ITEM_ROLES_ADMIN.getId(), "false", "", ""); rbas.doAssignUserRole("globalRoles", "itemAdminRole", "itemAdminUser"); // Adding agentAdmin role and assigning agentAdminUser rbas.doAddRole("globalRoles", "agentAdminRole", "hudson.model.Hudson.Read," + RoleBasedAuthorizationStrategy.AGENT_ROLES_ADMIN.getId(), "false", "", ""); rbas.doAssignUserRole("globalRoles", "agentAdminRole", "agentAdminUser"); // Adding developer role (no admin permissions) rbas.doAddRole("projectRoles", "developers", "hudson.model.Item.Read,hudson.model.Item.Build", "false", ".*", ""); rbas.doAssignUserRole("projectRoles", "developers", "developerUser"); webClient = jenkinsRule.createWebClient().withThrowExceptionOnFailingStatusCode(false); webClient.login("adminUser", "adminUser"); } private void performAsAndExpect(String username, WebRequest request, int expectedCode) throws Exception { webClient.login(username, username); Page page = webClient.getPage(request); assertEquals(expectedCode, page.getWebResponse().getStatusCode(), "HTTP code mismatch for user " + username); } @Test void testRolesSubmitAccessControl() throws Exception { // Test that doRolesSubmit entry point correctly checks for ADMINISTER_AND_SOME_ROLES_ADMIN URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/rolesSubmit"); WebRequest request = new WebRequest(apiUrl, HttpMethod.POST); // adminUser has Jenkins.ADMINISTER - should pass entry check (but will fail on empty form) performAsAndExpect("adminUser", request, HttpURLConnection.HTTP_BAD_REQUEST); // itemAdminUser has ITEM_ROLES_ADMIN - should pass entry check (but will fail on empty form) performAsAndExpect("itemAdminUser", request, HttpURLConnection.HTTP_BAD_REQUEST); // agentAdminUser has AGENT_ROLES_ADMIN - should pass entry check (but will fail on empty form) performAsAndExpect("agentAdminUser", request, HttpURLConnection.HTTP_BAD_REQUEST); // developerUser has no admin permissions - should get 403 at entry performAsAndExpect("developerUser", request, HttpURLConnection.HTTP_FORBIDDEN); } @Test void testAssignSubmitAccessControl() throws Exception { // Test that doAssignSubmit entry point correctly checks for ADMINISTER_AND_SOME_ROLES_ADMIN URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/assignSubmit"); WebRequest request = new WebRequest(apiUrl, HttpMethod.POST); // adminUser has Jenkins.ADMINISTER - should pass entry check (but will fail on empty form) performAsAndExpect("adminUser", request, HttpURLConnection.HTTP_BAD_REQUEST); // itemAdminUser has ITEM_ROLES_ADMIN - should pass entry check (but will fail on empty form) performAsAndExpect("itemAdminUser", request, HttpURLConnection.HTTP_BAD_REQUEST); // agentAdminUser has AGENT_ROLES_ADMIN - should pass entry check (but will fail on empty form) performAsAndExpect("agentAdminUser", request, HttpURLConnection.HTTP_BAD_REQUEST); // developerUser has no admin permissions - should get 403 at entry performAsAndExpect("developerUser", request, HttpURLConnection.HTTP_FORBIDDEN); } @Test void testTemplatesSubmitAccessControl() throws Exception { // Test that doTemplatesSubmit entry point correctly checks for ITEM_ROLES_ADMIN URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/templatesSubmit"); WebRequest request = new WebRequest(apiUrl, HttpMethod.POST); // adminUser has Jenkins.ADMINISTER (which implies ITEM_ROLES_ADMIN) - should pass (but will fail on empty form) performAsAndExpect("adminUser", request, HttpURLConnection.HTTP_BAD_REQUEST); // itemAdminUser has ITEM_ROLES_ADMIN - should pass entry check (but will fail on empty form) performAsAndExpect("itemAdminUser", request, HttpURLConnection.HTTP_BAD_REQUEST); // agentAdminUser does NOT have ITEM_ROLES_ADMIN - should get 403 performAsAndExpect("agentAdminUser", request, HttpURLConnection.HTTP_FORBIDDEN); // developerUser has no admin permissions - should get 403 performAsAndExpect("developerUser", request, HttpURLConnection.HTTP_FORBIDDEN); } @Test void testSelectiveFilteringBehaviorThroughRestAPI() throws Exception { // Demonstrate selective filtering by using the REST API which shares the same underlying logic // itemAdminUser can modify Project roles via REST API, which uses the same permission checks webClient.login("itemAdminUser", "itemAdminUser"); // itemAdminUser can add a project role rbas.doAddRole("projectRoles", "testRole", "hudson.model.Item.Read", "false", ".*", ""); Role projectRole = rbas.getRoleMap(RoleType.Project).getRole("testRole"); assertThat("itemAdminUser should be able to create project roles", projectRole, notNullValue()); // But trying to add a global role should fail with 403 URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/addRole"); WebRequest request = new WebRequest(apiUrl, HttpMethod.POST); request.setRequestParameters(java.util.Arrays.asList( new org.htmlunit.util.NameValuePair("type", "globalRoles"), new org.htmlunit.util.NameValuePair("roleName", "unauthorizedRole"), new org.htmlunit.util.NameValuePair("permissionIds", "hudson.model.Hudson.Read"), new org.htmlunit.util.NameValuePair("overwrite", "false") )); Page page = webClient.getPage(request); assertEquals(HttpURLConnection.HTTP_FORBIDDEN, page.getWebResponse().getStatusCode(), "itemAdminUser should not be able to create global roles"); Role globalRole = rbas.getRoleMap(RoleType.Global).getRole("unauthorizedRole"); assertThat("Unauthorized global role should not exist", globalRole, equalTo(null)); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/org/jenkinsci/plugins/rolestrategy/ConfigurationAsCodeTest.java
src/test/java/org/jenkinsci/plugins/rolestrategy/ConfigurationAsCodeTest.java
package org.jenkinsci.plugins.rolestrategy; import static io.jenkins.plugins.casc.misc.Util.getJenkinsRoot; import static io.jenkins.plugins.casc.misc.Util.toStringFromYamlFile; import static io.jenkins.plugins.casc.misc.Util.toYamlString; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.jenkinsci.plugins.rolestrategy.PermissionAssert.assertHasNoPermission; import static org.jenkinsci.plugins.rolestrategy.PermissionAssert.assertHasPermission; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import com.cloudbees.hudson.plugins.folder.Folder; import com.michelin.cio.hudson.plugins.rolestrategy.PermissionEntry; import com.michelin.cio.hudson.plugins.rolestrategy.Role; import com.michelin.cio.hudson.plugins.rolestrategy.RoleBasedAuthorizationStrategy; import com.synopsys.arc.jenkins.plugins.rolestrategy.RoleType; import hudson.PluginManager; import hudson.model.Computer; import hudson.model.FreeStyleProject; import hudson.model.Item; import hudson.model.User; import hudson.security.AuthorizationStrategy; import io.jenkins.plugins.casc.ConfigurationContext; import io.jenkins.plugins.casc.Configurator; import io.jenkins.plugins.casc.ConfiguratorRegistry; import io.jenkins.plugins.casc.misc.ConfiguredWithCode; import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule; import io.jenkins.plugins.casc.misc.junit.jupiter.WithJenkinsConfiguredWithCode; import io.jenkins.plugins.casc.model.CNode; import java.util.Map; import java.util.Set; import jenkins.model.Jenkins; import org.jenkinsci.plugins.rolestrategy.casc.RoleBasedAuthorizationStrategyConfigurator; import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; /** * Configuration as code test. * * @author Oleg Nenashev * @since 2.11 */ @WithJenkinsConfiguredWithCode class ConfigurationAsCodeTest { static { RoleBasedAuthorizationStrategy.ITEM_ROLES_ADMIN.setEnabled(true); RoleBasedAuthorizationStrategy.AGENT_ROLES_ADMIN.setEnabled(true); } @Test void shouldReturnCustomConfigurator(JenkinsConfiguredWithCodeRule jcwcRule) { ConfiguratorRegistry registry = ConfiguratorRegistry.get(); Configurator<?> c = registry.lookup(RoleBasedAuthorizationStrategy.class); assertNotNull(c, "Failed to find configurator for RoleBasedAuthorizationStrategy"); assertEquals(RoleBasedAuthorizationStrategyConfigurator.class, c.getClass(), "Retrieved wrong configurator"); } @Test @Issue("Issue #48") @ConfiguredWithCode("Configuration-as-Code.yml") void shouldReadRolesCorrectly(JenkinsConfiguredWithCodeRule jcwcRule) throws Exception { jcwcRule.jenkins.setSecurityRealm(jcwcRule.createDummySecurityRealm()); User admin = User.getById("admin", false); User user1 = User.getById("user1", false); User user2 = User.getById("user2", true); assertNotNull(admin); assertNotNull(user1); Computer agent1 = jcwcRule.jenkins.getComputer("agent1"); Computer agent2 = jcwcRule.jenkins.getComputer("agent2"); Folder folderA = jcwcRule.jenkins.createProject(Folder.class, "A"); FreeStyleProject jobA1 = folderA.createProject(FreeStyleProject.class, "1"); Folder folderB = jcwcRule.jenkins.createProject(Folder.class, "B"); FreeStyleProject jobB2 = folderB.createProject(FreeStyleProject.class, "2"); AuthorizationStrategy s = jcwcRule.jenkins.getAuthorizationStrategy(); assertThat("Authorization Strategy has been read incorrectly", s, instanceOf(RoleBasedAuthorizationStrategy.class)); RoleBasedAuthorizationStrategy rbas = (RoleBasedAuthorizationStrategy) s; Map<Role, Set<PermissionEntry>> globalRoles = rbas.getGrantedRolesEntries(RoleType.Global); assertThat(globalRoles.size(), equalTo(2)); // Admin has configuration access assertHasPermission(admin, jcwcRule.jenkins, Jenkins.ADMINISTER, Jenkins.READ); assertHasPermission(user1, jcwcRule.jenkins, Jenkins.READ); assertHasNoPermission(user1, jcwcRule.jenkins, Jenkins.ADMINISTER); assertHasNoPermission(user2, jcwcRule.jenkins, Jenkins.ADMINISTER); // Folder A is restricted to admin assertHasPermission(admin, folderA, Item.CONFIGURE); assertHasPermission(user1, folderA, Item.READ, Item.DISCOVER); assertHasNoPermission(user1, folderA, Item.CONFIGURE, Item.DELETE, Item.BUILD); // But they have access to jobs in Folder A assertHasPermission(admin, folderA, Item.CONFIGURE, Item.CANCEL); assertHasPermission(user1, jobA1, Item.READ, Item.DISCOVER, Item.CONFIGURE, Item.BUILD, Item.DELETE); assertHasPermission(user2, jobA1, Item.READ, Item.DISCOVER, Item.CONFIGURE, Item.BUILD, Item.DELETE); assertHasNoPermission(user1, folderA, Item.CANCEL); // FolderB is editable by user2, but he cannot delete it assertHasPermission(user2, folderB, Item.READ, Item.DISCOVER, Item.CONFIGURE, Item.BUILD); assertHasNoPermission(user2, folderB, Item.DELETE); assertHasNoPermission(user1, folderB, Item.CONFIGURE, Item.BUILD, Item.DELETE); // Only user1 can run on agent1, but he still cannot configure it assertHasPermission(admin, agent1, Computer.CONFIGURE, Computer.DELETE, Computer.BUILD); assertHasPermission(user1, agent1, Computer.BUILD); assertHasNoPermission(user1, agent1, Computer.CONFIGURE, Computer.DISCONNECT); // Same user still cannot build on agent2 assertHasNoPermission(user1, agent2, Computer.BUILD); } @Test @ConfiguredWithCode("Configuration-as-Code.yml") void shouldExportRolesCorrect(JenkinsConfiguredWithCodeRule jcwcRule) throws Exception { ConfiguratorRegistry registry = ConfiguratorRegistry.get(); ConfigurationContext context = new ConfigurationContext(registry); CNode yourAttribute = getJenkinsRoot(context).get("authorizationStrategy"); String exported = toYamlString(yourAttribute); String expected = toStringFromYamlFile(this, "Configuration-as-Code-Export.yml"); assertThat(exported, is(expected)); } @Test @Issue("Issue #214") @ConfiguredWithCode("Configuration-as-Code2.yml") void shouldHandleNullItemsAndAgentsCorrectly(JenkinsConfiguredWithCodeRule jcwcRule) { AuthorizationStrategy s = jcwcRule.jenkins.getAuthorizationStrategy(); assertThat("Authorization Strategy has been read incorrectly", s, instanceOf(RoleBasedAuthorizationStrategy.class)); RoleBasedAuthorizationStrategy rbas = (RoleBasedAuthorizationStrategy) s; Map<Role, Set<PermissionEntry>> globalRoles = rbas.getGrantedRolesEntries(RoleType.Global); assertThat(globalRoles.size(), equalTo(2)); } @Test @ConfiguredWithCode("Configuration-as-Code3.yml") void dangerousPermissionsAreIgnored(JenkinsConfiguredWithCodeRule jcwcRule) { AuthorizationStrategy s = jcwcRule.jenkins.getAuthorizationStrategy(); assertThat("Authorization Strategy has been read incorrectly", s, instanceOf(RoleBasedAuthorizationStrategy.class)); RoleBasedAuthorizationStrategy rbas = (RoleBasedAuthorizationStrategy) s; assertThat(rbas.getRoleMap(RoleType.Global).getRole("dangerous").hasPermission(PluginManager.CONFIGURE_UPDATECENTER), is(false)); assertThat(rbas.getRoleMap(RoleType.Global).getRole("dangerous").hasPermission(PluginManager.UPLOAD_PLUGINS), is(false)); assertThat(rbas.getRoleMap(RoleType.Global).getRole("dangerous").hasPermission(Jenkins.RUN_SCRIPTS), is(false)); } @Test @ConfiguredWithCode("Configuration-as-Code-no-permissions.yml") void exportWithEmptyRole(JenkinsConfiguredWithCodeRule jcwcRule) throws Exception { ConfiguratorRegistry registry = ConfiguratorRegistry.get(); ConfigurationContext context = new ConfigurationContext(registry); CNode yourAttribute = getJenkinsRoot(context).get("authorizationStrategy"); String exported = toYamlString(yourAttribute); String expected = toStringFromYamlFile(this, "Configuration-as-Code-no-permissions-export.yml"); assertThat(exported, is(expected)); } @Test @ConfiguredWithCode("Configuration-as-Code-granular-permissions.yml") void shouldLoadGranularPermissions(JenkinsConfiguredWithCodeRule jcwcRule) { AuthorizationStrategy s = jcwcRule.jenkins.getAuthorizationStrategy(); assertThat("Authorization Strategy has been read incorrectly", s, instanceOf(RoleBasedAuthorizationStrategy.class)); RoleBasedAuthorizationStrategy rbas = (RoleBasedAuthorizationStrategy) s; // Verify itemAdmin role has ITEM_ROLES_ADMIN permission Role itemAdminRole = rbas.getRoleMap(RoleType.Global).getRole("itemAdmin"); assertNotNull(itemAdminRole, "itemAdmin role should exist"); assertThat("itemAdmin role should have ITEM_ROLES_ADMIN permission", itemAdminRole.hasPermission(RoleBasedAuthorizationStrategy.ITEM_ROLES_ADMIN), is(true)); assertThat("itemAdmin role should NOT have ADMINISTER permission", itemAdminRole.hasPermission(Jenkins.ADMINISTER), is(false)); // Verify agentAdmin role has AGENT_ROLES_ADMIN permission Role agentAdminRole = rbas.getRoleMap(RoleType.Global).getRole("agentAdmin"); assertNotNull(agentAdminRole, "agentAdmin role should exist"); assertThat("agentAdmin role should have AGENT_ROLES_ADMIN permission", agentAdminRole.hasPermission(RoleBasedAuthorizationStrategy.AGENT_ROLES_ADMIN), is(true)); assertThat("agentAdmin role should NOT have ADMINISTER permission", agentAdminRole.hasPermission(Jenkins.ADMINISTER), is(false)); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/org/jenkinsci/plugins/rolestrategy/UserAuthoritiesAsRolesTest.java
src/test/java/org/jenkinsci/plugins/rolestrategy/UserAuthoritiesAsRolesTest.java
package org.jenkinsci.plugins.rolestrategy; import static org.junit.jupiter.api.Assertions.assertTrue; import hudson.model.User; import hudson.security.ACL; import hudson.security.ACLContext; import hudson.security.AbstractPasswordBasedSecurityRealm; import hudson.security.GroupDetails; import hudson.security.Permission; import java.util.Collections; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.jvnet.hudson.test.recipes.LocalData; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; @WithJenkins class UserAuthoritiesAsRolesTest { private JenkinsRule jenkinsRule; @BeforeEach void enableUserAuthorities(JenkinsRule jenkinsRule) { this.jenkinsRule = jenkinsRule; Settings.TREAT_USER_AUTHORITIES_AS_ROLES = true; } @AfterEach void disableUserAuthorities() { Settings.TREAT_USER_AUTHORITIES_AS_ROLES = false; } @LocalData @Test void testRoleAuthority() { jenkinsRule.jenkins.setSecurityRealm(new MockSecurityRealm()); try (ACLContext c = ACL.as(User.getById("alice", true))) { assertTrue(jenkinsRule.jenkins.hasPermission(Permission.READ)); } } private static class MockSecurityRealm extends AbstractPasswordBasedSecurityRealm { @Override protected org.springframework.security.core.userdetails.UserDetails authenticate2(String username, String password) throws org.springframework.security.core.AuthenticationException { // TODO Auto-generated method stub throw new UnsupportedOperationException(); } @Override public UserDetails loadUserByUsername2(String username) throws org.springframework.security.core.userdetails.UsernameNotFoundException { return new org.springframework.security.core.userdetails.User(username, "", Collections.singletonList(new SimpleGrantedAuthority("USERS"))); } @Override public GroupDetails loadGroupByGroupname2(String groupname, boolean fetchMembers) throws org.springframework.security.core.userdetails.UsernameNotFoundException { throw new UnsupportedOperationException(); } } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/org/jenkinsci/plugins/rolestrategy/PermissionTemplatesApiTest.java
src/test/java/org/jenkinsci/plugins/rolestrategy/PermissionTemplatesApiTest.java
package org.jenkinsci.plugins.rolestrategy; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import com.michelin.cio.hudson.plugins.rolestrategy.PermissionTemplate; import com.michelin.cio.hudson.plugins.rolestrategy.RoleBasedAuthorizationStrategy; import hudson.model.Item; import java.net.HttpURLConnection; import java.net.URL; import java.util.Arrays; import java.util.List; import java.util.Map; import net.sf.json.JSONObject; import org.htmlunit.HttpMethod; import org.htmlunit.Page; import org.htmlunit.WebRequest; import org.htmlunit.util.NameValuePair; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** * Tests for permission-based access control on template API operations. * These tests verify that the ITEM_ROLES_ADMIN permission is properly enforced * for template management operations. */ @WithJenkins class PermissionTemplatesApiTest { static { RoleBasedAuthorizationStrategy.ITEM_ROLES_ADMIN.setEnabled(true); RoleBasedAuthorizationStrategy.AGENT_ROLES_ADMIN.setEnabled(true); } private JenkinsRule jenkinsRule; private JenkinsRule.WebClient webClient; private RoleBasedAuthorizationStrategy rbas; // List of executions for different users and expected results private static final List<Map<String, Object>> getExecutions = Arrays.asList( Map.of("username", "adminUser", "expectedCode", HttpURLConnection.HTTP_OK), Map.of("username", "itemAdminUser", "expectedCode", HttpURLConnection.HTTP_OK), Map.of("username", "agentAdminUser", "expectedCode", HttpURLConnection.HTTP_FORBIDDEN), Map.of("username", "developerUser", "expectedCode", HttpURLConnection.HTTP_FORBIDDEN) ); @BeforeEach void setUp(JenkinsRule jenkinsRule) throws Exception { this.jenkinsRule = jenkinsRule; // Setting up jenkins configurations JenkinsRule.DummySecurityRealm securityRealm = jenkinsRule.createDummySecurityRealm(); jenkinsRule.jenkins.setSecurityRealm(securityRealm); rbas = new RoleBasedAuthorizationStrategy(); jenkinsRule.jenkins.setAuthorizationStrategy(rbas); jenkinsRule.jenkins.setCrumbIssuer(null); // Adding admin role and assigning adminUser rbas.doAddRole("globalRoles", "adminRole", "hudson.model.Hudson.Read,hudson.model.Hudson.Administer,hudson.security.Permission.GenericRead", "false", "", ""); rbas.doAssignUserRole("globalRoles", "adminRole", "adminUser"); // Adding itemAdmin role and assigning itemAdminUser rbas.doAddRole("globalRoles", "itemAdminRole", "hudson.model.Hudson.Read," + RoleBasedAuthorizationStrategy.ITEM_ROLES_ADMIN.getId(), "false", "", ""); rbas.doAssignUserRole("globalRoles", "itemAdminRole", "itemAdminUser"); // Adding agentAdmin role and assigning agentAdminUser (should NOT have template access) rbas.doAddRole("globalRoles", "agentAdminRole", "hudson.model.Hudson.Read," + RoleBasedAuthorizationStrategy.AGENT_ROLES_ADMIN.getId(), "false", "", ""); rbas.doAssignUserRole("globalRoles", "agentAdminRole", "agentAdminUser"); // Adding developer role (no admin permissions) rbas.doAddRole("projectRoles", "developers", "hudson.model.Item.Read,hudson.model.Item.Build", "false", ".*", ""); rbas.doAssignUserRole("projectRoles", "developers", "developerUser"); // Create a base template for testing rbas.doAddTemplate("baseTemplate", "hudson.model.Item.Read,hudson.model.Item.Build", false); webClient = jenkinsRule.createWebClient().withThrowExceptionOnFailingStatusCode(false); webClient.login("adminUser", "adminUser"); } private void performAsAndExpect(String username, WebRequest request, int expectedCode, String expectedContent) throws Exception { webClient.login(username, username); Page page = webClient.getPage(request); assertEquals(expectedCode, page.getWebResponse().getStatusCode(), "HTTP code mismatch for user " + username); String body = page.getWebResponse().getContentAsString(); if (expectedContent != null) { assertTrue(body.contains(expectedContent), "Expected content not found: " + expectedContent); } } @Test void testAddTemplateAs() throws Exception { // Loop through each execution and perform the request for (Map<String, Object> execution : getExecutions) { String username = (String) execution.get("username"); int expectedCode = (int) execution.get("expectedCode"); String templateName = username + "_testTemplate"; URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/addTemplate"); WebRequest request = new WebRequest(apiUrl, HttpMethod.POST); request.setRequestParameters( Arrays.asList( new NameValuePair("name", templateName), new NameValuePair("permissionIds", "hudson.model.Item.Read,hudson.model.Item.Configure"), new NameValuePair("overwrite", "false") ) ); performAsAndExpect(username, request, expectedCode, null); if (expectedCode == HttpURLConnection.HTTP_OK) { // Verify that the template was created PermissionTemplate template = rbas.getPermissionTemplate(templateName); assertThat("Template should exist for user: " + username, template, notNullValue()); assertThat("Template name should match for user: " + username, template.getName(), equalTo(templateName)); assertThat("Template should have READ permission", template.hasPermission(Item.READ), is(true)); assertThat("Template should have CONFIGURE permission", template.hasPermission(Item.CONFIGURE), is(true)); } else { // Verify that the template was NOT created PermissionTemplate template = rbas.getPermissionTemplate(templateName); assertThat("Template should not exist for user: " + username, template, equalTo(null)); } } } @Test void testRemoveTemplatesAs() throws Exception { // Create templates to remove for (Map<String, Object> execution : getExecutions) { String username = (String) execution.get("username"); String templateName = username + "_testTemplateToRemove"; rbas.doAddTemplate(templateName, "hudson.model.Item.Read", false); } // Loop through each execution and perform the request for (Map<String, Object> execution : getExecutions) { String username = (String) execution.get("username"); int expectedCode = (int) execution.get("expectedCode"); String templateName = username + "_testTemplateToRemove"; URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/removeTemplates"); WebRequest request = new WebRequest(apiUrl, HttpMethod.POST); request.setRequestParameters( Arrays.asList( new NameValuePair("names", templateName), new NameValuePair("force", "false") ) ); performAsAndExpect(username, request, expectedCode, null); if (expectedCode == HttpURLConnection.HTTP_OK) { // Verify that the template was removed assertThat("Template should be removed for user: " + username, rbas.hasPermissionTemplate(templateName), is(false)); } else { // Verify that the template still exists assertThat("Template should still exist for user: " + username, rbas.hasPermissionTemplate(templateName), is(true)); } } } @Test void testGetTemplateAs() throws Exception { // Loop through each execution and perform the request for (Map<String, Object> execution : getExecutions) { String username = (String) execution.get("username"); int expectedCode = (int) execution.get("expectedCode"); URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/getTemplate?name=baseTemplate"); WebRequest request = new WebRequest(apiUrl, HttpMethod.GET); performAsAndExpect(username, request, expectedCode, null); if (expectedCode == HttpURLConnection.HTTP_OK) { // Verify the response contains template data webClient.login(username, username); Page page = webClient.getPage(request); String content = page.getWebResponse().getContentAsString(); JSONObject json = JSONObject.fromObject(content); assertThat("Response should contain permissionIds for user: " + username, json.has("permissionIds"), is(true)); assertThat("Response should contain isUsed for user: " + username, json.has("isUsed"), is(true)); } } } @Test void testAddTemplateWithOverwrite() throws Exception { // Create a template String templateName = "overwriteTest"; String lastSuccessfulPerms = "hudson.model.Item.Read"; for (Map<String, Object> execution : getExecutions) { // reset if needed rbas.doAddTemplate(templateName, "hudson.model.Item.Read", true); String username = (String) execution.get("username"); int expectedCode = (int) execution.get("expectedCode"); String overwrite = "true"; String newPerms = "hudson.model.Item.Configure"; URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/addTemplate"); WebRequest request = new WebRequest(apiUrl, HttpMethod.POST); request.setRequestParameters( Arrays.asList( new NameValuePair("name", templateName), new NameValuePair("permissionIds", newPerms), new NameValuePair("overwrite", overwrite) ) ); performAsAndExpect(username, request, expectedCode, null); if (expectedCode == HttpURLConnection.HTTP_OK) { // Verify the template was updated PermissionTemplate template = rbas.getPermissionTemplate(templateName); Assertions.assertNotNull(template); assertThat("Template should have new permission for user: " + username, template.hasPermission(hudson.security.Permission.fromId(newPerms)), is(true)); } else { // Verify the template was NOT updated (still has last successful permissions) PermissionTemplate template = rbas.getPermissionTemplate(templateName); Assertions.assertNotNull(template); assertThat("Template should still have old permission for user: " + username, template.hasPermission(hudson.security.Permission.fromId(lastSuccessfulPerms)), is(true)); assertThat("Template should not have new permission for user: " + username, template.hasPermission(hudson.security.Permission.fromId(newPerms)), is(false)); } } } @Test void testRemoveTemplateInUse() throws Exception { // Create a template and use it in a role rbas.doAddTemplate("inUseTemplate", "hudson.model.Item.Read,hudson.model.Item.Build", false); rbas.doAddRole("projectRoles", "roleUsingTemplate", "", "false", ".*", "inUseTemplate"); // Test removing with force=false (should not remove) URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/removeTemplates"); WebRequest request = new WebRequest(apiUrl, HttpMethod.POST); request.setRequestParameters( Arrays.asList( new NameValuePair("names", "inUseTemplate"), new NameValuePair("force", "false") ) ); webClient.login("itemAdminUser", "itemAdminUser"); Page page = webClient.getPage(request); assertEquals(HttpURLConnection.HTTP_OK, page.getWebResponse().getStatusCode()); // Template should still exist assertThat("Template should still exist when in use and force=false", rbas.hasPermissionTemplate("inUseTemplate"), is(true)); // Test removing with force=true (should remove) request = new WebRequest(apiUrl, HttpMethod.POST); request.setRequestParameters( Arrays.asList( new NameValuePair("names", "inUseTemplate"), new NameValuePair("force", "true") ) ); page = webClient.getPage(request); assertEquals(HttpURLConnection.HTTP_OK, page.getWebResponse().getStatusCode()); // Template should be removed assertThat("Template should be removed when force=true", rbas.hasPermissionTemplate("inUseTemplate"), is(false)); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/org/jenkinsci/plugins/rolestrategy/OwnershipTest.java
src/test/java/org/jenkinsci/plugins/rolestrategy/OwnershipTest.java
package org.jenkinsci.plugins.rolestrategy; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.oneOf; import com.synopsys.arc.jenkins.plugins.ownership.OwnershipDescription; import com.synopsys.arc.jenkins.plugins.ownership.nodes.OwnerNodeProperty; import hudson.model.Node; import io.jenkins.plugins.casc.misc.ConfiguredWithCode; import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule; import io.jenkins.plugins.casc.misc.junit.jupiter.WithJenkinsConfiguredWithCode; import java.net.URL; import java.util.Collections; import org.htmlunit.HttpMethod; import org.htmlunit.WebRequest; import org.htmlunit.WebResponse; import org.htmlunit.html.HtmlPage; import org.htmlunit.util.NameValuePair; import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule.WebClient; @WithJenkinsConfiguredWithCode class OwnershipTest { @Test @ConfiguredWithCode("OwnershipTest.yml") void currentUserIsPrimaryOwnerGrantsPermissions(JenkinsConfiguredWithCodeRule jcwcRule) throws Exception { Node n = jcwcRule.createOnlineSlave(); n.getNodeProperties().add(new OwnerNodeProperty(n, new OwnershipDescription(true, "nodePrimaryTester", null))); String nodeUrl = n.toComputer().getUrl(); WebClient wc = jcwcRule.createWebClient(); wc.withThrowExceptionOnFailingStatusCode(false); wc.login("nodePrimaryTester", "nodePrimaryTester"); HtmlPage managePage = wc.withThrowExceptionOnFailingStatusCode(false).goTo(String.format("%sconfigure", nodeUrl)); assertThat(managePage.getWebResponse().getStatusCode(), is(200)); URL testUrl = wc.createCrumbedUrl(String.format("%sdisconnect", nodeUrl)); WebRequest request = new WebRequest(testUrl, HttpMethod.POST); NameValuePair param = new NameValuePair("offlineMessage", "Disconnect for Test"); request.setRequestParameters(Collections.singletonList(param)); WebResponse response = wc.loadWebResponse(request); assertThat(response.getStatusCode(), is(200)); testUrl = wc.createCrumbedUrl(String.format("%slaunchSlaveAgent", nodeUrl)); request = new WebRequest(testUrl, HttpMethod.POST); response = wc.loadWebResponse(request); assertThat(response.getStatusCode(), is(oneOf(200, 302))); testUrl = wc.createCrumbedUrl(String.format("%sdoDelete", nodeUrl)); request = new WebRequest(testUrl, HttpMethod.POST); response = wc.loadWebResponse(request); assertThat(response.getStatusCode(), is(200)); } @Test @ConfiguredWithCode("OwnershipTest.yml") void currentUserIsSecondaryOwnerGrantsPermissions(JenkinsConfiguredWithCodeRule jcwcRule) throws Exception { Node n = jcwcRule.createOnlineSlave(); n.getNodeProperties() .add(new OwnerNodeProperty(n, new OwnershipDescription(true, "nodePrimaryTester", Collections.singleton("nodeSecondaryTester")))); String nodeUrl = n.toComputer().getUrl(); WebClient wc = jcwcRule.createWebClient(); wc.withThrowExceptionOnFailingStatusCode(false); wc.login("nodeSecondaryTester", "nodeSecondaryTester"); HtmlPage managePage = wc.withThrowExceptionOnFailingStatusCode(false).goTo(String.format("%sconfigure", nodeUrl)); assertThat(managePage.getWebResponse().getStatusCode(), is(200)); URL testUrl = wc.createCrumbedUrl(String.format("%sdisconnect", nodeUrl)); WebRequest request = new WebRequest(testUrl, HttpMethod.POST); NameValuePair param = new NameValuePair("offlineMessage", "Disconnect for Test"); request.setRequestParameters(Collections.singletonList(param)); WebResponse response = wc.loadWebResponse(request); assertThat(response.getStatusCode(), is(200)); testUrl = wc.createCrumbedUrl(String.format("%slaunchSlaveAgent", nodeUrl)); request = new WebRequest(testUrl, HttpMethod.POST); response = wc.loadWebResponse(request); assertThat(response.getStatusCode(), is(oneOf(200, 302))); testUrl = wc.createCrumbedUrl(String.format("%sdoDelete", nodeUrl)); request = new WebRequest(testUrl, HttpMethod.POST); response = wc.loadWebResponse(request); assertThat(response.getStatusCode(), is(200)); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/org/jenkinsci/plugins/rolestrategy/PermissionAssert.java
src/test/java/org/jenkinsci/plugins/rolestrategy/PermissionAssert.java
/* * Copyright (c) 2018 Oleg Nenashev * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to * whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.rolestrategy; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import hudson.model.User; import hudson.security.ACL; import hudson.security.ACLContext; import hudson.security.AccessControlled; import hudson.security.Permission; /** * Provides asserts for {@link hudson.security.Permission} checks. * * @author Oleg Nenashev */ public class PermissionAssert { public static void assertHasPermission(User user, final Permission permission, final AccessControlled... items) { for (AccessControlled item : items) { assertPermission(user, item, permission); } } public static void assertHasPermission(User user, final AccessControlled item, final Permission... permissions) { for (Permission permission : permissions) { assertPermission(user, item, permission); } } public static void assertHasNoPermission(User user, final Permission permission, final AccessControlled... items) { for (AccessControlled item : items) { assertNoPermission(user, item, permission); } } public static void assertHasNoPermission(User user, final AccessControlled item, final Permission... permissions) { for (Permission permission : permissions) { assertNoPermission(user, item, permission); } } private static void assertPermission(User user, final AccessControlled item, final Permission p) { assertThat("User '" + user + "' has no " + p.getId() + " permission for " + item + ", but it should according to security settings", hasPermission(user, item, p), equalTo(true)); } private static void assertNoPermission(User user, final AccessControlled item, final Permission p) { assertThat( "User '" + user + "' has the " + p.getId() + " permission for " + item + ", but it should not according to security settings", hasPermission(user, item, p), equalTo(false)); } private static boolean hasPermission(User user, final AccessControlled item, final Permission p) { try (ACLContext c = ACL.as(user)) { return item.hasPermission(p); } } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/org/jenkinsci/plugins/rolestrategy/RoleBasedProjectNamingStrategyTest.java
src/test/java/org/jenkinsci/plugins/rolestrategy/RoleBasedProjectNamingStrategyTest.java
package org.jenkinsci.plugins.rolestrategy; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.jenkinsci.plugins.rolestrategy.PermissionAssert.assertHasNoPermission; import static org.jenkinsci.plugins.rolestrategy.PermissionAssert.assertHasPermission; import static org.junit.jupiter.api.Assertions.assertThrows; import com.michelin.cio.hudson.plugins.rolestrategy.RoleBasedAuthorizationStrategy; import hudson.model.Failure; import hudson.model.Item; import hudson.model.User; import hudson.security.ACL; import hudson.security.ACLContext; import hudson.security.AuthorizationStrategy; import io.jenkins.plugins.casc.misc.ConfiguredWithCode; import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule; import io.jenkins.plugins.casc.misc.junit.jupiter.WithJenkinsConfiguredWithCode; import jenkins.model.ProjectNamingStrategy; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule.DummySecurityRealm; @WithJenkinsConfiguredWithCode class RoleBasedProjectNamingStrategyTest { private JenkinsConfiguredWithCodeRule j; private DummySecurityRealm securityRealm; private User userGlobal; private User userJobCreate; private User userRead; private User userGlobalGroup; private User userJobCreateGroup; private User userReadGroup; private User eitherGlobal; private User eitherJobCreate; private User eitherRead; private User userEitherGlobalGroup; private User userEitherJobCreateGroup; private User userEitherReadGroup; @BeforeEach void setup(JenkinsConfiguredWithCodeRule j) { this.j = j; securityRealm = j.createDummySecurityRealm(); j.jenkins.setSecurityRealm(securityRealm); userGlobal = User.getById("userGlobal", true); userJobCreate = User.getById("userJobCreate", true); userRead = User.getById("userRead", true); userGlobalGroup = User.getById("userGlobalGroup", true); userJobCreateGroup = User.getById("userJobCreateGroup", true); userReadGroup = User.getById("userReadGroup", true); eitherGlobal = User.getById("eitherGlobal", true); eitherJobCreate = User.getById("eitherJobCreate", true); eitherRead = User.getById("eitherRead", true); userEitherGlobalGroup = User.getById("userEitherGlobalGroup", true); userEitherReadGroup = User.getById("userEitherReadGroup", true); userEitherJobCreateGroup = User.getById("userEitherJobCreateGroup", true); securityRealm.addGroups("userGlobalGroup", "groupGlobal"); securityRealm.addGroups("userJobCreateGroup", "groupJobCreate"); securityRealm.addGroups("userReadGroup", "groupRead"); securityRealm.addGroups("userEitherGlobalGroup", "eitherGlobal"); securityRealm.addGroups("userEitherJobCreateGroup", "eitherJobCreate"); securityRealm.addGroups("userEitherReadGroup", "eitherRead"); } @Test @ConfiguredWithCode("Configuration-as-Code-Naming.yml") void createPermission() { AuthorizationStrategy s = j.jenkins.getAuthorizationStrategy(); assertThat("Authorization Strategy has been read incorrectly", s, instanceOf(RoleBasedAuthorizationStrategy.class)); assertHasPermission(userGlobal, j.jenkins, Item.CREATE); assertHasPermission(userJobCreate, j.jenkins, Item.CREATE); assertHasNoPermission(userRead, j.jenkins, Item.CREATE); assertHasPermission(userGlobalGroup, j.jenkins, Item.CREATE); assertHasPermission(userJobCreateGroup, j.jenkins, Item.CREATE); assertHasNoPermission(userReadGroup, j.jenkins, Item.CREATE); assertHasPermission(eitherGlobal, j.jenkins, Item.CREATE); assertHasPermission(eitherJobCreate, j.jenkins, Item.CREATE); assertHasPermission(userEitherGlobalGroup, j.jenkins, Item.CREATE); assertHasPermission(userEitherJobCreateGroup, j.jenkins, Item.CREATE); assertHasNoPermission(eitherRead, j.jenkins, Item.CREATE); assertHasNoPermission(userEitherReadGroup, j.jenkins, Item.CREATE); } @Test @ConfiguredWithCode("Configuration-as-Code-Naming.yml") void globalUserCanCreateAnyJob() { AuthorizationStrategy s = j.jenkins.getAuthorizationStrategy(); assertThat("Authorization Strategy has been read incorrectly", s, instanceOf(RoleBasedAuthorizationStrategy.class)); checkName(userGlobal, "anyJobName", null); checkName(userGlobalGroup, "anyJobName", null); checkName(eitherGlobal, "anyJobName", null); checkName(userEitherGlobalGroup, "anyJobName", null); } @Test @ConfiguredWithCode("Configuration-as-Code-Naming.yml") void itemUserCanCreateOnlyAllowedJobs() { AuthorizationStrategy s = j.jenkins.getAuthorizationStrategy(); assertThat("Authorization Strategy has been read incorrectly", s, instanceOf(RoleBasedAuthorizationStrategy.class)); checkName(userJobCreate, "jobAllowed", null); checkName(userJobCreate, "jobAllowed", "folder"); checkName(userJobCreateGroup, "jobAllowed", null); checkName(userJobCreateGroup, "jobAllowed", "folder"); checkName(eitherJobCreate, "jobAllowed", null); checkName(userEitherJobCreateGroup, "jobAllowed", "folder"); Failure f = assertThrows(Failure.class, () -> checkName(userJobCreate, "notAllowed", null)); assertThat(f.getMessage(), containsString("does not match the job name convention")); f = assertThrows(Failure.class, () -> checkName(userJobCreate, "notAllowed", "folder")); assertThat(f.getMessage(), containsString("does not match the job name convention")); f = assertThrows(Failure.class, () -> checkName(userJobCreate, "jobAllowed", "folder2")); assertThat(f.getMessage(), containsString("does not match the job name convention")); f = assertThrows(Failure.class, () -> checkName(userJobCreateGroup, "notAllowed", null)); assertThat(f.getMessage(), containsString("does not match the job name convention")); f = assertThrows(Failure.class, () -> checkName(userJobCreateGroup, "notAllowed", "folder")); assertThat(f.getMessage(), containsString("does not match the job name convention")); f = assertThrows(Failure.class, () -> checkName(userJobCreateGroup, "jobAllowed", "folder2")); assertThat(f.getMessage(), containsString("does not match the job name convention")); f = assertThrows(Failure.class, () -> checkName(eitherJobCreate, "notAllowed", null)); assertThat(f.getMessage(), containsString("does not match the job name convention")); f = assertThrows(Failure.class, () -> checkName(eitherJobCreate, "notAllowed", "folder")); assertThat(f.getMessage(), containsString("does not match the job name convention")); f = assertThrows(Failure.class, () -> checkName(eitherJobCreate, "jobAllowed", "folder2")); assertThat(f.getMessage(), containsString("does not match the job name convention")); f = assertThrows(Failure.class, () -> checkName(userEitherJobCreateGroup, "notAllowed", null)); assertThat(f.getMessage(), containsString("does not match the job name convention")); f = assertThrows(Failure.class, () -> checkName(userEitherJobCreateGroup, "notAllowed", "folder")); assertThat(f.getMessage(), containsString("does not match the job name convention")); f = assertThrows(Failure.class, () -> checkName(userEitherJobCreateGroup, "jobAllowed", "folder2")); assertThat(f.getMessage(), containsString("does not match the job name convention")); } @Test @ConfiguredWithCode("Configuration-as-Code-Macro.yml") void macroRolesDoNotGrantCreate() { AuthorizationStrategy s = j.jenkins.getAuthorizationStrategy(); assertThat("Authorization Strategy has been read incorrectly", s, instanceOf(RoleBasedAuthorizationStrategy.class)); checkName(userJobCreate, "jobAllowed", null); checkName(userJobCreate, "jobAllowed", "folder"); checkName(userJobCreateGroup, "jobAllowed", null); checkName(userJobCreateGroup, "jobAllowed", "folder"); Failure f = assertThrows(Failure.class, () -> checkName(userJobCreate, "notAllowed", null)); assertThat(f.getMessage(), containsString("does not match the job name convention")); f = assertThrows(Failure.class, () -> checkName(userJobCreate, "notAllowed", "folder")); assertThat(f.getMessage(), containsString("does not match the job name convention")); f = assertThrows(Failure.class, () -> checkName(userJobCreate, "jobAllowed", "folder2")); assertThat(f.getMessage(), containsString("does not match the job name convention")); f = assertThrows(Failure.class, () -> checkName(userJobCreateGroup, "notAllowed", null)); assertThat(f.getMessage(), containsString("does not match the job name convention")); f = assertThrows(Failure.class, () -> checkName(userJobCreateGroup, "notAllowed", "folder")); assertThat(f.getMessage(), containsString("does not match the job name convention")); f = assertThrows(Failure.class, () -> checkName(userJobCreateGroup, "jobAllowed", "folder2")); assertThat(f.getMessage(), containsString("does not match the job name convention")); } @Test @ConfiguredWithCode("Configuration-as-Code-Naming.yml") void readUserCantCreateAllowedJobs() { AuthorizationStrategy s = j.jenkins.getAuthorizationStrategy(); assertThat("Authorization Strategy has been read incorrectly", s, instanceOf(RoleBasedAuthorizationStrategy.class)); Failure f = assertThrows(Failure.class, () -> checkName(userRead, "jobAllowed", null)); assertThat(f.getMessage(), is("No Create Permissions!")); f = assertThrows(Failure.class, () -> checkName(userRead, "jobAllowed", "folder")); assertThat(f.getMessage(), is("No Create Permissions!")); f = assertThrows(Failure.class, () -> checkName(userReadGroup, "jobAllowed", null)); assertThat(f.getMessage(), is("No Create Permissions!")); f = assertThrows(Failure.class, () -> checkName(userReadGroup, "jobAllowed", "folder")); assertThat(f.getMessage(), is("No Create Permissions!")); f = assertThrows(Failure.class, () -> checkName(eitherRead, "jobAllowed", null)); assertThat(f.getMessage(), is("No Create Permissions!")); f = assertThrows(Failure.class, () -> checkName(eitherRead, "jobAllowed", "folder")); assertThat(f.getMessage(), is("No Create Permissions!")); f = assertThrows(Failure.class, () -> checkName(userEitherReadGroup, "jobAllowed", null)); assertThat(f.getMessage(), is("No Create Permissions!")); f = assertThrows(Failure.class, () -> checkName(userEitherReadGroup, "jobAllowed", "folder")); assertThat(f.getMessage(), is("No Create Permissions!")); } @Test @Issue("JENKINS-69625") @ConfiguredWithCode("Configuration-as-Code-Naming.yml") void systemUserCanCreateAnyJob() { checkName("jobAllowed", null); checkName("jobAllowed", "folder"); checkName("anyJob", null); checkName("anyJob", "folder"); checkName("anyJob", "AnyFolder"); } private void checkName(User user, final String jobName, final String parentName) { try (ACLContext c = ACL.as(user)) { checkName(jobName, parentName); } } private void checkName(final String jobName, final String parentName) { ProjectNamingStrategy pns = j.jenkins.getProjectNamingStrategy(); assertThat(pns, instanceOf(RoleBasedProjectNamingStrategy.class)); RoleBasedProjectNamingStrategy rbpns = (RoleBasedProjectNamingStrategy) pns; rbpns.checkName(parentName, jobName); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/org/jenkinsci/plugins/rolestrategy/PatternMatchingApiTest.java
src/test/java/org/jenkinsci/plugins/rolestrategy/PatternMatchingApiTest.java
package org.jenkinsci.plugins.rolestrategy; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import com.michelin.cio.hudson.plugins.rolestrategy.RoleBasedAuthorizationStrategy; import java.net.HttpURLConnection; import java.net.URL; import net.sf.json.JSONObject; import org.htmlunit.HttpMethod; import org.htmlunit.Page; import org.htmlunit.WebRequest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** * Tests for permission-based access control on pattern matching API endpoints. * These endpoints are used by the UI to show which items/agents match a given pattern. * They require Jenkins.ADMINISTER permission. */ @WithJenkins class PatternMatchingApiTest { static { RoleBasedAuthorizationStrategy.ITEM_ROLES_ADMIN.setEnabled(true); RoleBasedAuthorizationStrategy.AGENT_ROLES_ADMIN.setEnabled(true); } private JenkinsRule jenkinsRule; private JenkinsRule.WebClient webClient; private RoleBasedAuthorizationStrategy rbas; @BeforeEach void setUp(JenkinsRule jenkinsRule) throws Exception { this.jenkinsRule = jenkinsRule; // Setting up jenkins configurations JenkinsRule.DummySecurityRealm securityRealm = jenkinsRule.createDummySecurityRealm(); jenkinsRule.jenkins.setSecurityRealm(securityRealm); rbas = new RoleBasedAuthorizationStrategy(); jenkinsRule.jenkins.setAuthorizationStrategy(rbas); jenkinsRule.jenkins.setCrumbIssuer(null); // Adding admin role and assigning adminUser rbas.doAddRole("globalRoles", "adminRole", "hudson.model.Hudson.Read,hudson.model.Hudson.Administer,hudson.security.Permission.GenericRead", "false", "", ""); rbas.doAssignUserRole("globalRoles", "adminRole", "adminUser"); // Adding itemAdmin role and assigning itemAdminUser (should NOT have access to pattern matching) rbas.doAddRole("globalRoles", "itemAdminRole", "hudson.model.Hudson.Read," + RoleBasedAuthorizationStrategy.ITEM_ROLES_ADMIN.getId(), "false", "", ""); rbas.doAssignUserRole("globalRoles", "itemAdminRole", "itemAdminUser"); // Adding agentAdmin role and assigning agentAdminUser (should NOT have access to pattern matching) rbas.doAddRole("globalRoles", "agentAdminRole", "hudson.model.Hudson.Read," + RoleBasedAuthorizationStrategy.AGENT_ROLES_ADMIN.getId(), "false", "", ""); rbas.doAssignUserRole("globalRoles", "agentAdminRole", "agentAdminUser"); // Adding developer role (no admin permissions) rbas.doAddRole("projectRoles", "developers", "hudson.model.Item.Read,hudson.model.Item.Build", "false", ".*", ""); rbas.doAssignUserRole("projectRoles", "developers", "developerUser"); webClient = jenkinsRule.createWebClient().withThrowExceptionOnFailingStatusCode(false); webClient.login("adminUser", "adminUser"); } private void performAsAndExpect(String username, WebRequest request, int expectedCode) throws Exception { webClient.login(username, username); Page page = webClient.getPage(request); assertEquals(expectedCode, page.getWebResponse().getStatusCode(), "HTTP code mismatch for user " + username); } @Test void testGetMatchingJobsWithAdminUser() throws Exception { // Create some jobs jenkinsRule.createFreeStyleProject("test-job-1"); jenkinsRule.createFreeStyleProject("test-job-2"); jenkinsRule.createFreeStyleProject("other-job"); // adminUser has Jenkins.ADMINISTER and should be able to call this endpoint webClient.login("adminUser", "adminUser"); URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/getMatchingJobs?pattern=.*"); WebRequest request = new WebRequest(apiUrl, HttpMethod.GET); Page page = webClient.getPage(request); assertEquals(HttpURLConnection.HTTP_OK, page.getWebResponse().getStatusCode()); String content = page.getWebResponse().getContentAsString(); JSONObject json = JSONObject.fromObject(content); assertTrue(json.has("matchingJobs"), "Response should contain matchingJobs"); assertTrue(json.has("itemCount"), "Response should contain itemCount"); // Verify response structure - should have at least the jobs we created int itemCount = json.getInt("itemCount"); assertThat("Should have at least 3 items", itemCount >= 3, is(true)); } @Test void testGetMatchingJobsPermissions() throws Exception { URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/getMatchingJobs?pattern=.*"); WebRequest request = new WebRequest(apiUrl, HttpMethod.GET); // adminUser has Jenkins.ADMINISTER - should succeed performAsAndExpect("adminUser", request, HttpURLConnection.HTTP_OK); // itemAdminUser does NOT have Jenkins.ADMINISTER - should fail performAsAndExpect("itemAdminUser", request, HttpURLConnection.HTTP_FORBIDDEN); // agentAdminUser does NOT have Jenkins.ADMINISTER - should fail performAsAndExpect("agentAdminUser", request, HttpURLConnection.HTTP_FORBIDDEN); // developerUser has no admin permissions - should fail performAsAndExpect("developerUser", request, HttpURLConnection.HTTP_FORBIDDEN); } @Test void testGetMatchingAgentsWithAdminUser() throws Exception { // Create some agents jenkinsRule.createSlave("agent-1", null, null); jenkinsRule.createSlave("agent-2", null, null); jenkinsRule.createSlave("agent-3", null, null); // adminUser has Jenkins.ADMINISTER and should be able to call this endpoint webClient.login("adminUser", "adminUser"); URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/getMatchingAgents?pattern=.*"); WebRequest request = new WebRequest(apiUrl, HttpMethod.GET); Page page = webClient.getPage(request); assertEquals(HttpURLConnection.HTTP_OK, page.getWebResponse().getStatusCode()); String content = page.getWebResponse().getContentAsString(); JSONObject json = JSONObject.fromObject(content); assertTrue(json.has("matchingAgents"), "Response should contain matchingAgents"); assertTrue(json.has("agentCount"), "Response should contain agentCount"); // Verify response structure - should have at least the agents we created int agentCount = json.getInt("agentCount"); assertThat("Should have at least 3 agents", agentCount >= 3, is(true)); } @Test void testGetMatchingAgentsPermissions() throws Exception { URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/getMatchingAgents?pattern=.*"); WebRequest request = new WebRequest(apiUrl, HttpMethod.GET); // adminUser has Jenkins.ADMINISTER - should succeed performAsAndExpect("adminUser", request, HttpURLConnection.HTTP_OK); // itemAdminUser does NOT have Jenkins.ADMINISTER - should fail performAsAndExpect("itemAdminUser", request, HttpURLConnection.HTTP_FORBIDDEN); // agentAdminUser does NOT have Jenkins.ADMINISTER - should fail performAsAndExpect("agentAdminUser", request, HttpURLConnection.HTTP_FORBIDDEN); // developerUser has no admin permissions - should fail performAsAndExpect("developerUser", request, HttpURLConnection.HTTP_FORBIDDEN); } @Test void testGetMatchingJobsWithMaxLimit() throws Exception { // Create more jobs than the limit for (int i = 0; i < 5; i++) { jenkinsRule.createFreeStyleProject("test-job-" + i); } webClient.login("adminUser", "adminUser"); URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/getMatchingJobs?pattern=^test.*&maxJobs=3"); WebRequest request = new WebRequest(apiUrl, HttpMethod.GET); Page page = webClient.getPage(request); assertEquals(HttpURLConnection.HTTP_OK, page.getWebResponse().getStatusCode()); String content = page.getWebResponse().getContentAsString(); JSONObject json = JSONObject.fromObject(content); // Should have at most 3 jobs in the response (limited by maxJobs parameter) int matchingJobsCount = json.getJSONArray("matchingJobs").size(); assertThat("Should respect maxJobs limit", matchingJobsCount <= 3, is(true)); // itemCount should reflect total number of matching items int itemCount = json.getInt("itemCount"); assertThat("itemCount should be >= returned jobs", itemCount >= matchingJobsCount, is(true)); } @Test void testGetMatchingAgentsWithMaxLimit() throws Exception { // Create more agents than the limit for (int i = 0; i < 5; i++) { jenkinsRule.createSlave("agent-" + i, null, null); } webClient.login("adminUser", "adminUser"); URL apiUrl = new URL(jenkinsRule.jenkins.getRootUrl() + "role-strategy/strategy/getMatchingAgents?pattern=^agent.*&maxAgents=3"); WebRequest request = new WebRequest(apiUrl, HttpMethod.GET); Page page = webClient.getPage(request); assertEquals(HttpURLConnection.HTTP_OK, page.getWebResponse().getStatusCode()); String content = page.getWebResponse().getContentAsString(); JSONObject json = JSONObject.fromObject(content); // Should have at most 3 agents in the response (limited by maxAgents parameter) int matchingAgentsCount = json.getJSONArray("matchingAgents").size(); assertThat("Should respect maxAgents limit", matchingAgentsCount <= 3, is(true)); // agentCount should reflect total number of matching agents int agentCount = json.getInt("agentCount"); assertThat("agentCount should be >= returned agents", agentCount >= matchingAgentsCount, is(true)); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/org/jenkinsci/plugins/rolestrategy/Security2182Test.java
src/test/java/org/jenkinsci/plugins/rolestrategy/Security2182Test.java
package org.jenkinsci.plugins.rolestrategy; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.not; import static org.junit.jupiter.api.Assertions.assertEquals; import com.cloudbees.hudson.plugins.folder.Folder; import com.michelin.cio.hudson.plugins.rolestrategy.RoleMap; import hudson.model.Cause; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.User; import hudson.model.queue.QueueTaskFuture; import jenkins.model.Jenkins; import org.htmlunit.Page; import org.htmlunit.html.HtmlPage; import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.SleepBuilder; import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.jvnet.hudson.test.recipes.LocalData; @WithJenkins class Security2182Test { private static final String BUILD_CONTENT = "Started by user"; private static final String JOB_CONTENT = "Full project name: folder/job"; @Test @LocalData void testQueuePath(JenkinsRule jenkinsRule) throws Exception { jenkinsRule.jenkins.setSecurityRealm(jenkinsRule.createDummySecurityRealm()); Folder folder = jenkinsRule.jenkins.createProject(Folder.class, "folder"); FreeStyleProject job = folder.createProject(FreeStyleProject.class, "job"); job.save(); job.scheduleBuild2(1000, new Cause.UserIdCause("admin")); assertEquals(1, Jenkins.get().getQueue().getItems().length); final JenkinsRule.WebClient webClient = jenkinsRule.createWebClient().withThrowExceptionOnFailingStatusCode(false); final HtmlPage htmlPage = webClient.goTo("queue/items/0/task/"); final String contentAsString = htmlPage.getWebResponse().getContentAsString(); assertThat(contentAsString, not(containsString(JOB_CONTENT))); // Fails while unfixed } @Test @LocalData void testQueueContent(JenkinsRule jenkinsRule) throws Exception { jenkinsRule.jenkins.setSecurityRealm(jenkinsRule.createDummySecurityRealm()); Folder folder = jenkinsRule.jenkins.createProject(Folder.class, "folder"); FreeStyleProject job = folder.createProject(FreeStyleProject.class, "job"); job.save(); job.scheduleBuild2(1000, new Cause.UserIdCause("admin")); assertEquals(1, Jenkins.get().getQueue().getItems().length); final JenkinsRule.WebClient webClient = jenkinsRule.createWebClient(); final Page page = webClient.goTo("queue/api/xml/", "application/xml"); final String xml = page.getWebResponse().getContentAsString(); assertThat(xml, not(containsString("job/folder/job/job"))); // Fails while unfixed } @Test @LocalData void testExecutorsPath(JenkinsRule jenkinsRule) throws Exception { jenkinsRule.jenkins.setSecurityRealm(jenkinsRule.createDummySecurityRealm()); Folder folder = jenkinsRule.jenkins.createProject(Folder.class, "folder"); FreeStyleProject job = folder.createProject(FreeStyleProject.class, "job"); job.getBuildersList().add(new SleepBuilder(100000)); job.save(); final FreeStyleBuild build = job.scheduleBuild2(0, new Cause.UserIdCause("admin")).waitForStart(); final int number = build.getExecutor().getNumber(); final JenkinsRule.WebClient webClient = jenkinsRule.createWebClient().withThrowExceptionOnFailingStatusCode(false); final HtmlPage htmlPage = webClient.goTo("computer/(master)/executors/" + number + "/currentExecutable/"); final String contentAsString = htmlPage.getWebResponse().getContentAsString(); assertThat(contentAsString, not(containsString(BUILD_CONTENT))); // Fails while unfixed build.doStop(); } @Test @LocalData void testExecutorsContent(JenkinsRule jenkinsRule) throws Exception { jenkinsRule.jenkins.setSecurityRealm(jenkinsRule.createDummySecurityRealm()); Folder folder = jenkinsRule.jenkins.createProject(Folder.class, "folder"); FreeStyleProject job = folder.createProject(FreeStyleProject.class, "job"); job.getBuildersList().add(new SleepBuilder(10000)); job.save(); FreeStyleBuild build = job.scheduleBuild2(0, new Cause.UserIdCause("admin")).waitForStart(); final JenkinsRule.WebClient webClient = jenkinsRule.createWebClient(); final Page page = webClient.goTo("computer/(master)/api/xml?depth=1", "application/xml"); final String xml = page.getWebResponse().getContentAsString(); assertThat(xml, not(containsString("job/folder/job/job"))); // Fails while unfixed build.doStop(); } @Test @LocalData void testWidgets(JenkinsRule jenkinsRule) throws Exception { jenkinsRule.jenkins.setSecurityRealm(jenkinsRule.createDummySecurityRealm()); Folder folder = jenkinsRule.jenkins.createProject(Folder.class, "folder"); FreeStyleProject job = folder.createProject(FreeStyleProject.class, "job"); job.getBuildersList().add(new SleepBuilder(100000)); job.save(); FreeStyleBuild b1 = job.scheduleBuild2(0, new Cause.UserIdCause("admin")).waitForStart(); // schedule one build now QueueTaskFuture<?> f2 = job.scheduleBuild2(0, new Cause.UserIdCause("admin")); // schedule an additional queue item assertEquals(1, Jenkins.get().getQueue().getItems().length); // expect there to be one queue item final JenkinsRule.WebClient webClient = jenkinsRule.createWebClient().withThrowExceptionOnFailingStatusCode(false); final HtmlPage htmlPage = webClient.goTo(""); final String contentAsString = htmlPage.getWebResponse().getContentAsString(); assertThat(contentAsString, not(containsString("job/folder/job/job"))); // Fails while unfixed f2.cancel(true); b1.doStop(); } @Test @LocalData void testEscapeHatch(JenkinsRule jenkinsRule) throws Exception { final String propertyName = RoleMap.class.getName() + ".checkParentPermissions"; try { System.setProperty(propertyName, "false"); jenkinsRule.jenkins.setSecurityRealm(jenkinsRule.createDummySecurityRealm()); User.getOrCreateByIdOrFullName("admin"); Folder folder = jenkinsRule.jenkins.createProject(Folder.class, "folder"); FreeStyleProject job = folder.createProject(FreeStyleProject.class, "job"); job.getBuildersList().add(new SleepBuilder(100000)); job.save(); job.scheduleBuild2(1000, new Cause.UserIdCause("admin")); assertEquals(1, Jenkins.get().getQueue().getItems().length); final JenkinsRule.WebClient webClient = jenkinsRule.createWebClient().withThrowExceptionOnFailingStatusCode(false); { // queue related assertions final HtmlPage htmlPage = webClient.goTo("queue/items/0/task/"); final String contentAsString = htmlPage.getWebResponse().getContentAsString(); assertThat(contentAsString, containsString(JOB_CONTENT)); // Fails while unfixed final Page page = webClient.goTo("queue/api/xml/", "application/xml"); final String xml = page.getWebResponse().getContentAsString(); assertThat(xml, containsString("job/folder/job/job")); // Fails while unfixed } final FreeStyleBuild build = job.scheduleBuild2(0, new Cause.UserIdCause("admin")).waitForStart(); final int number = build.getExecutor().getNumber(); assertEquals(0, Jenkins.get().getQueue().getItems().length); // collapsed queue items { // executor related assertions final HtmlPage htmlPage = webClient.goTo("computer/(master)/executors/" + number + "/currentExecutable/"); final String contentAsString = htmlPage.getWebResponse().getContentAsString(); assertThat(contentAsString, containsString(BUILD_CONTENT)); // Fails while unfixed final Page page = webClient.goTo("computer/(master)/api/xml?depth=1", "application/xml"); final String xml = page.getWebResponse().getContentAsString(); assertThat(xml, containsString("job/folder/job/job")); // Fails while unfixed } { // widget related assertions final HtmlPage htmlPage = webClient.goTo(""); final String contentAsString = htmlPage.getWebResponse().getContentAsString(); assertThat(contentAsString, containsString("job/folder/job/job")); // Fails while unfixed } build.doStop(); } finally { System.clearProperty(propertyName); } } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/org/jenkinsci/plugins/rolestrategy/RoleStrategyTest.java
src/test/java/org/jenkinsci/plugins/rolestrategy/RoleStrategyTest.java
package org.jenkinsci.plugins.rolestrategy; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import com.michelin.cio.hudson.plugins.rolestrategy.RoleBasedAuthorizationStrategy; import com.michelin.cio.hudson.plugins.rolestrategy.RoleMap; import com.synopsys.arc.jenkins.plugins.rolestrategy.RoleType; import hudson.PluginManager; import hudson.model.User; import hudson.security.ACL; import hudson.security.ACLContext; import hudson.security.Permission; import jenkins.model.Jenkins; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.jvnet.hudson.test.recipes.LocalData; @WithJenkins class RoleStrategyTest { private JenkinsRule jenkinsRule; @BeforeEach void initSecurityRealm(JenkinsRule jenkinsRule) { this.jenkinsRule = jenkinsRule; jenkinsRule.jenkins.setSecurityRealm(jenkinsRule.createDummySecurityRealm()); } @LocalData @Test void testRoleAssignment() { RoleMap.FORCE_CASE_SENSITIVE = false; try (ACLContext c = ACL.as(User.getById("alice", true))) { assertTrue(jenkinsRule.jenkins.hasPermission(Permission.READ)); } } @LocalData @Test void testRoleAssignmentCaseInsensitiveNoMatchSucceeds() { RoleMap.FORCE_CASE_SENSITIVE = false; try (ACLContext c = ACL.as(User.getById("Alice", true))) { assertTrue(jenkinsRule.jenkins.hasPermission(Permission.READ)); } } @LocalData @Test void testRoleAssignmentCaseSensitiveMatch() { RoleMap.FORCE_CASE_SENSITIVE = true; try (ACLContext c = ACL.as(User.getById("alice", true))) { assertTrue(jenkinsRule.jenkins.hasPermission(Permission.READ)); } } @LocalData @Test void testRoleAssignmentCaseSensitiveNoMatchFails() { RoleMap.FORCE_CASE_SENSITIVE = true; try (ACLContext c = ACL.as(User.getById("Alice", true))) { assertFalse(jenkinsRule.jenkins.hasPermission(Permission.READ)); } } @LocalData @Test void dangerousPermissionsAreIgnored() { RoleBasedAuthorizationStrategy rbas = (RoleBasedAuthorizationStrategy) jenkinsRule.jenkins.getAuthorizationStrategy(); assertThat(rbas.getRoleMap(RoleType.Global).getRole("POWERUSERS").hasPermission(PluginManager.CONFIGURE_UPDATECENTER), is(false)); assertThat(rbas.getRoleMap(RoleType.Global).getRole("POWERUSERS").hasPermission(PluginManager.UPLOAD_PLUGINS), is(false)); assertThat(rbas.getRoleMap(RoleType.Global).getRole("POWERUSERS").hasPermission(Jenkins.RUN_SCRIPTS), is(false)); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/org/jenkinsci/plugins/rolestrategy/UserGroupSeparationTest.java
src/test/java/org/jenkinsci/plugins/rolestrategy/UserGroupSeparationTest.java
package org.jenkinsci.plugins.rolestrategy; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import hudson.model.User; import hudson.security.ACL; import hudson.security.ACLContext; import jenkins.model.Jenkins; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.JenkinsRule.DummySecurityRealm; import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.jvnet.hudson.test.recipes.LocalData; @WithJenkins class UserGroupSeparationTest { private JenkinsRule jenkinsRule; private User user; private User group; private User either; private User userWithGroup; private User groupAsUser; private User eitherGroup; @BeforeEach void setup(JenkinsRule jenkinsRule) { this.jenkinsRule = jenkinsRule; DummySecurityRealm securityRealm = jenkinsRule.createDummySecurityRealm(); jenkinsRule.jenkins.setSecurityRealm(securityRealm); user = User.getById("user", true); group = User.getById("group", true); userWithGroup = User.getById("userWithGroup", true); groupAsUser = User.getById("groupAsUser", true); either = User.getById("either", true); eitherGroup = User.getById("eitherGroup", true); securityRealm.addGroups("userWithGroup", "group"); securityRealm.addGroups("groupAsUser", "user"); securityRealm.addGroups("eitherGroup", "either"); } /** * A user that matches an entry of type user should be granted access. */ @LocalData @Test void user_matches_user_has_access() { try (ACLContext c = ACL.as(User.getById("user", false))) { assertTrue(jenkinsRule.jenkins.hasPermission(Jenkins.ADMINISTER)); } } /** * A user that is in a group that matches an entry of type group should be granted access. */ @LocalData @Test void usergroup_matches_group_has_acess() { try (ACLContext c = ACL.as(User.getById("userWithGroup", false))) { assertTrue(jenkinsRule.jenkins.hasPermission(Jenkins.ADMINISTER)); } } /** * A user that has a name matching a group should not have access. */ @LocalData @Test void user_matches_group_has_no_access() { try (ACLContext c = ACL.as(User.getById("group", false))) { assertFalse(jenkinsRule.jenkins.hasPermission(Jenkins.ADMINISTER)); } } /** * A user that is in a group that matches an entry of type user should not have access. */ @LocalData @Test void group_matches_user_has_no_acess() { try (ACLContext c = ACL.as(User.getById("groupAsUser", false))) { assertFalse(jenkinsRule.jenkins.hasPermission(Jenkins.ADMINISTER)); } } /** * A user that matches an entry of type either should have access. */ @LocalData @Test void user_matches_either_has_access() { try (ACLContext c = ACL.as(User.getById("either", false))) { assertTrue(jenkinsRule.jenkins.hasPermission(Jenkins.ADMINISTER)); } } /** * A user that is in a group matches an entry of type either should have access. */ @LocalData @Test void group_matches_either_has_access() { try (ACLContext c = ACL.as(User.getById("eitherGroup", false))) { assertTrue(jenkinsRule.jenkins.hasPermission(Jenkins.ADMINISTER)); } } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/org/jenkinsci/plugins/rolestrategy/Security2374Test.java
src/test/java/org/jenkinsci/plugins/rolestrategy/Security2374Test.java
/* * The MIT License * * Copyright (c) Red Hat, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.rolestrategy; import static com.michelin.cio.hudson.plugins.rolestrategy.AuthorizationType.EITHER; import static com.michelin.cio.hudson.plugins.rolestrategy.AuthorizationType.GROUP; import static com.michelin.cio.hudson.plugins.rolestrategy.AuthorizationType.USER; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertTrue; import com.michelin.cio.hudson.plugins.rolestrategy.PermissionEntry; import com.michelin.cio.hudson.plugins.rolestrategy.RoleBasedAuthorizationStrategy; import hudson.model.User; import hudson.security.ACL; import hudson.security.SidACL; import io.jenkins.plugins.casc.misc.ConfiguredWithCode; import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule; import io.jenkins.plugins.casc.misc.junit.jupiter.WithJenkinsConfiguredWithCode; import java.io.File; import java.io.FileReader; import java.io.Reader; import java.util.Arrays; import java.util.Collections; import java.util.List; import jenkins.model.Jenkins; import org.apache.commons.io.IOUtils; import org.hamcrest.Matchers; import org.htmlunit.html.HtmlPage; import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.WithoutJenkins; import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.jvnet.hudson.test.recipes.LocalData; @WithJenkins class Security2374Test { @Test @WithJenkinsConfiguredWithCode @ConfiguredWithCode("Security2374Test/casc.yaml") void readFromCasc(JenkinsConfiguredWithCodeRule j) throws Exception { RoleBasedAuthorizationStrategy rbas = (RoleBasedAuthorizationStrategy) j.jenkins.getAuthorizationStrategy(); // So we can log in JenkinsRule.DummySecurityRealm dsr = j.createDummySecurityRealm(); dsr.addGroups("gerry", "groupname"); dsr.addGroups("intruderA", "username"); dsr.addGroups("intruderB", "eitherSID"); dsr.addGroups("intruderC", "indifferentSID"); j.jenkins.setSecurityRealm(dsr); ACL acl = j.jenkins.getACL(); assertTrue(acl.hasPermission2(User.getById("indifferentSID", true).impersonate2(), Jenkins.ADMINISTER)); assertTrue(acl.hasPermission2(User.getById("username", true).impersonate2(), Jenkins.ADMINISTER)); assertTrue(acl.hasPermission2(User.getById("gerry", true).impersonate2(), Jenkins.ADMINISTER)); assertFalse(acl.hasPermission2(User.getById("intruderA", true).impersonate2(), Jenkins.ADMINISTER)); // Users with group named after one of the EITHER sids (explicit or implicit) are let in assertTrue(acl.hasPermission2(User.getById("intruderB", true).impersonate2(), Jenkins.ADMINISTER)); assertTrue(acl.hasPermission2(User.getById("intruderC", true).impersonate2(), Jenkins.ADMINISTER)); AmbiguousSidsAdminMonitor am = AmbiguousSidsAdminMonitor.get(); assertTrue(am.isActivated()); assertThat(am.getAmbiguousEntries(), Matchers.containsInAnyOrder("eitherSID", "indifferentSID")); HtmlPage manage; try (JenkinsRule.WebClient wc = j.createWebClient()) { wc.login("gerry", "gerry"); manage = wc.goTo("manage"); String source = manage.getWebResponse().getContentAsString(); assertThat(source, Matchers.containsString("'USER:username' or 'GROUP:groupname'")); assertThat(source, Matchers.containsString("indifferentSID")); assertThat(source, Matchers.containsString("eitherSID")); } } @Test @WithoutJenkins void createPermissionEntry() { assertThat(PermissionEntry.user("foo"), equalTo(permissionEntry("USER:foo"))); assertThat(PermissionEntry.group("foo"), equalTo(permissionEntry("GROUP:foo"))); assertThat(permissionEntry(""), nullValue()); assertThat(permissionEntry(":-)"), nullValue()); assertThat(permissionEntry("Re:"), nullValue()); assertThat(permissionEntry("GROUP:"), nullValue()); assertThat(permissionEntry("USER:"), nullValue()); } public PermissionEntry permissionEntry(String in) { return PermissionEntry.fromString(in); } @Test void adminMonitor(JenkinsRule j) throws Exception { AmbiguousSidsAdminMonitor am = AmbiguousSidsAdminMonitor.get(); assertFalse(am.isActivated()); assertThat(am.getAmbiguousEntries(), Matchers.emptyIterable()); am.updateEntries(Collections.singletonList(new PermissionEntry(EITHER, "foo"))); assertTrue(am.isActivated()); assertThat(am.getAmbiguousEntries(), equalTo(Collections.singletonList("foo"))); am.updateEntries(Collections.emptyList()); assertFalse(am.isActivated()); assertThat(am.getAmbiguousEntries(), Matchers.emptyIterable()); am.updateEntries(Arrays.asList(new PermissionEntry(USER, "foo"), new PermissionEntry(GROUP, "bar"))); assertFalse(am.isActivated()); assertThat(am.getAmbiguousEntries(), Matchers.emptyIterable()); am.updateEntries(Arrays.asList(new PermissionEntry(USER, "foo"), new PermissionEntry(GROUP, "bar"), new PermissionEntry(EITHER, "baz"))); assertTrue(am.isActivated()); assertThat(am.getAmbiguousEntries(), equalTo(Collections.singletonList("baz"))); } @LocalData @Test void test3xDataMigration(JenkinsRule j) throws Exception { assertInstanceOf(RoleBasedAuthorizationStrategy.class, j.jenkins.getAuthorizationStrategy()); final RoleBasedAuthorizationStrategy authorizationStrategy = (RoleBasedAuthorizationStrategy) j.jenkins.getAuthorizationStrategy(); final SidACL acl = authorizationStrategy.getRootACL(); final File configXml = new File(j.jenkins.getRootDir(), "config.xml"); List<String> configLines; try (Reader reader = new FileReader(configXml)) { configLines = IOUtils.readLines(reader); } assertFalse(acl.hasPermission2(User.getById("markus", true).impersonate2(), Jenkins.ADMINISTER)); assertTrue(acl.hasPermission2(User.getById("markus", true).impersonate2(), Jenkins.READ)); assertTrue(acl.hasPermission2(User.getById("admin", true).impersonate2(), Jenkins.ADMINISTER)); assertTrue(configLines.stream().anyMatch(line -> line.contains("<sid type=\"EITHER\">admin</sid>"))); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/org/jenkinsci/plugins/rolestrategy/PermissionTemplatesTest.java
src/test/java/org/jenkinsci/plugins/rolestrategy/PermissionTemplatesTest.java
package org.jenkinsci.plugins.rolestrategy; import static org.jenkinsci.plugins.rolestrategy.PermissionAssert.assertHasNoPermission; import static org.jenkinsci.plugins.rolestrategy.PermissionAssert.assertHasPermission; import com.cloudbees.hudson.plugins.folder.Folder; import com.michelin.cio.hudson.plugins.rolestrategy.RoleBasedAuthorizationStrategy; import hudson.model.FreeStyleProject; import hudson.model.Item; import hudson.model.User; import io.jenkins.plugins.casc.misc.ConfiguredWithCode; import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule; import io.jenkins.plugins.casc.misc.junit.jupiter.WithJenkinsConfiguredWithCode; import org.junit.jupiter.api.Test; @WithJenkinsConfiguredWithCode class PermissionTemplatesTest { @Test @ConfiguredWithCode("PermissionTemplatesTest/casc.yaml") void readFromCasc(JenkinsConfiguredWithCodeRule j) throws Exception { RoleBasedAuthorizationStrategy rbas = (RoleBasedAuthorizationStrategy) j.jenkins.getAuthorizationStrategy(); // So we can log in j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); User creator = User.getById("creator", true); User builder = User.getById("builder", true); Folder folderA = j.jenkins.createProject(Folder.class, "folder"); FreeStyleProject jobA1 = folderA.createProject(FreeStyleProject.class, "project"); assertHasPermission(creator, folderA, Item.READ); assertHasNoPermission(creator, folderA, Item.CONFIGURE); assertHasPermission(creator, jobA1, Item.READ); assertHasPermission(creator, jobA1, Item.CONFIGURE); assertHasPermission(builder, jobA1, Item.READ); assertHasNoPermission(builder, jobA1, Item.CONFIGURE); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/org/jenkinsci/plugins/rolestrategy/AuthorizeProjectTest.java
src/test/java/org/jenkinsci/plugins/rolestrategy/AuthorizeProjectTest.java
package org.jenkinsci.plugins.rolestrategy; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.model.Cause; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.Queue.Item; import hudson.model.Slave; import hudson.model.User; import hudson.security.ACL; import hudson.security.ACLContext; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.Builder; import java.io.IOException; import java.util.Collections; import java.util.concurrent.TimeUnit; import jenkins.model.Jenkins; import jenkins.security.QueueItemAuthenticatorConfiguration; import org.jenkinsci.plugins.authorizeproject.AuthorizeProjectProperty; import org.jenkinsci.plugins.authorizeproject.ProjectQueueItemAuthenticator; import org.jenkinsci.plugins.authorizeproject.strategy.TriggeringUsersAuthorizationStrategy; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.JenkinsRule.DummySecurityRealm; import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.jvnet.hudson.test.recipes.LocalData; @WithJenkins class AuthorizeProjectTest { private JenkinsRule jenkinsRule; private Slave node; private FreeStyleProject project; private AuthorizationCheckBuilder checker; @BeforeEach @LocalData void setup(JenkinsRule jenkinsRule) throws Exception { this.jenkinsRule = jenkinsRule; QueueItemAuthenticatorConfiguration.get().getAuthenticators().add(new ProjectQueueItemAuthenticator(Collections.emptyMap())); node = jenkinsRule.createSlave("TestAgent", null, null); jenkinsRule.waitOnline(node); project = jenkinsRule.createFreeStyleProject(); project.setAssignedNode(node); project.addProperty(new AuthorizeProjectProperty(new TriggeringUsersAuthorizationStrategy())); checker = new AuthorizationCheckBuilder(); project.getBuildersList().add(checker); DummySecurityRealm sr = jenkinsRule.createDummySecurityRealm(); jenkinsRule.jenkins.setSecurityRealm(sr); } @Test @LocalData void agentBuildPermissionsAllowsToBuildOnAgent() throws Exception { try (ACLContext c = ACL.as(User.getById("tester", true))) { project.scheduleBuild2(0, new Cause.UserIdCause()); } jenkinsRule.waitUntilNoActivity(); FreeStyleBuild b = project.getLastBuild(); assertThat(b, is(not(nullValue()))); jenkinsRule.assertBuildStatusSuccess(b); assertThat(checker.userName, is("tester")); } @Test @LocalData void missingAgentBuildPermissionsBlockBuild() throws Exception { try (ACLContext c = ACL.as(User.getById("reader", true))) { project.scheduleBuild2(0, new Cause.UserIdCause()); } TimeUnit.SECONDS.sleep(15); Item qi = project.getQueueItem(); assertThat(qi.getCauseOfBlockage().toString(), containsString("‘reader’ lacks permission to run on ‘TestAgent’")); } public static class AuthorizationCheckBuilder extends Builder { // "transient" is required for exclusion from serialization - see https://jenkins.io/redirect/class-filter/ public transient String userName = null; @Override public boolean prebuild(AbstractBuild<?, ?> build, BuildListener listener) { userName = null; return true; } @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { userName = Jenkins.getAuthentication2().getName(); return true; } public static class DescriptorImpl extends BuildStepDescriptor<Builder> { @Override public boolean isApplicable(Class<? extends AbstractProject> jobType) { return true; } @NonNull @Override public String getDisplayName() { return "AuthorizationCheckBuilder"; } } } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/org/jenkinsci/plugins/rolestrategy/pipeline/UserItemRolesTest.java
src/test/java/org/jenkinsci/plugins/rolestrategy/pipeline/UserItemRolesTest.java
package org.jenkinsci.plugins.rolestrategy.pipeline; import hudson.model.Cause; import hudson.model.User; import hudson.security.ACL; import hudson.security.ACLContext; import io.jenkins.plugins.casc.misc.ConfiguredWithCode; import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule; import io.jenkins.plugins.casc.misc.junit.jupiter.WithJenkinsConfiguredWithCode; import java.io.IOException; import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule.DummySecurityRealm; @WithJenkinsConfiguredWithCode class UserItemRolesTest { private JenkinsConfiguredWithCodeRule jenkinsRule; private WorkflowJob pipeline; @BeforeEach void setup(JenkinsConfiguredWithCodeRule jenkinsRule) throws IOException { this.jenkinsRule = jenkinsRule; DummySecurityRealm securityRealm = jenkinsRule.createDummySecurityRealm(); jenkinsRule.jenkins.setSecurityRealm(securityRealm); securityRealm.addGroups("builder1", "readers"); securityRealm.addGroups("builder2", "readers"); User.getById("builder1", true); User.getById("builder2", true); pipeline = jenkinsRule.createProject(WorkflowJob.class, "pipeline"); } @Test @ConfiguredWithCode("Configuration-as-Code-pipeline.yml") void systemUserHasAllItemRoles() throws Exception { pipeline.setDefinition(new CpsFlowDefinition("roles = currentUserItemRoles showAllRoles: true\n" + "for (r in roles) {\n" + " echo(\"Item Role: \" + r)\n" + "}", true)); WorkflowRun run = jenkinsRule.buildAndAssertSuccess(pipeline); jenkinsRule.assertLogContains("builder1Role", run); jenkinsRule.assertLogContains("builder2Role", run); jenkinsRule.assertLogContains("reader1Role", run); jenkinsRule.assertLogContains("reader2Role", run); } @Test @ConfiguredWithCode("Configuration-as-Code-pipeline.yml") void systemUserHasAllMatchingItemRoles() throws Exception { pipeline.setDefinition(new CpsFlowDefinition("roles = currentUserItemRoles()\n" + "for (r in roles) {\n" + " echo(\"Item Role: \" + r)\n" + "}", true)); WorkflowRun run = jenkinsRule.buildAndAssertSuccess(pipeline); jenkinsRule.assertLogContains("builder1Role", run); jenkinsRule.assertLogNotContains("builder2Role", run); jenkinsRule.assertLogContains("reader1Role", run); jenkinsRule.assertLogNotContains("reader2Role", run); } @Test @ConfiguredWithCode("Configuration-as-Code-pipeline.yml") void builderUserHasItemRoles() throws Exception { pipeline.setDefinition(new CpsFlowDefinition("roles = currentUserItemRoles showAllRoles: true\n" + "for (r in roles) {\n" + " echo(\"Item Role: \" + r)\n" + "}", true)); try (ACLContext c = ACL.as(User.getById("builder1", true))) { pipeline.scheduleBuild(0, new Cause.UserIdCause()); } jenkinsRule.waitUntilNoActivity(); WorkflowRun run = pipeline.getLastBuild(); jenkinsRule.assertLogContains("builder1Role", run); jenkinsRule.assertLogNotContains("builder2Role", run); jenkinsRule.assertLogContains("reader1Role", run); jenkinsRule.assertLogContains("reader2Role", run); } @Test @ConfiguredWithCode("Configuration-as-Code-pipeline.yml") void builderUserHasMatchingItemRoles() throws Exception { pipeline.setDefinition(new CpsFlowDefinition("roles = currentUserItemRoles()\n" + "for (r in roles) {\n" + " echo(\"Item Role: \" + r)\n" + "}", true)); try (ACLContext c = ACL.as(User.getById("builder1", true))) { pipeline.scheduleBuild(0, new Cause.UserIdCause()); } jenkinsRule.waitUntilNoActivity(); WorkflowRun run = pipeline.getLastBuild(); jenkinsRule.assertLogContains("builder1Role", run); jenkinsRule.assertLogNotContains("builder2Role", run); jenkinsRule.assertLogContains("reader1Role", run); jenkinsRule.assertLogNotContains("reader2Role", run); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/test/java/org/jenkinsci/plugins/rolestrategy/pipeline/UserGlobalRolesTest.java
src/test/java/org/jenkinsci/plugins/rolestrategy/pipeline/UserGlobalRolesTest.java
package org.jenkinsci.plugins.rolestrategy.pipeline; import hudson.model.Cause; import hudson.model.User; import hudson.security.ACL; import hudson.security.ACLContext; import hudson.triggers.TimerTrigger; import io.jenkins.plugins.casc.misc.ConfiguredWithCode; import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule; import io.jenkins.plugins.casc.misc.junit.jupiter.WithJenkinsConfiguredWithCode; import java.io.IOException; import jenkins.security.QueueItemAuthenticatorConfiguration; import org.jenkinsci.plugins.authorizeproject.GlobalQueueItemAuthenticator; import org.jenkinsci.plugins.authorizeproject.strategy.AnonymousAuthorizationStrategy; import org.jenkinsci.plugins.authorizeproject.strategy.SpecificUsersAuthorizationStrategy; import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule.DummySecurityRealm; @WithJenkinsConfiguredWithCode class UserGlobalRolesTest { private JenkinsConfiguredWithCodeRule jenkinsRule; private WorkflowJob pipeline; @BeforeEach void setup(JenkinsConfiguredWithCodeRule jenkinsRule) throws IOException { this.jenkinsRule = jenkinsRule; DummySecurityRealm securityRealm = jenkinsRule.createDummySecurityRealm(); jenkinsRule.jenkins.setSecurityRealm(securityRealm); securityRealm.addGroups("builder1", "readers"); securityRealm.addGroups("builder2", "readers"); User.getById("builder1", true); User.getById("builder2", true); pipeline = jenkinsRule.createProject(WorkflowJob.class, "pipeline"); } @Test @ConfiguredWithCode("Configuration-as-Code-pipeline.yml") void systemUserHasAllGlobalRoles() throws Exception { pipeline.setDefinition(new CpsFlowDefinition("roles = currentUserGlobalRoles()\n" + "for (r in roles) {\n" + " echo(\"Global Role: \" + r)\n" + "}", true)); WorkflowRun run = jenkinsRule.buildAndAssertSuccess(pipeline); jenkinsRule.assertLogContains("adminRole", run); jenkinsRule.assertLogContains("readonlyRole", run); } @Test @ConfiguredWithCode("Configuration-as-Code-pipeline.yml") void builderUserHasGlobalRoles() throws Exception { pipeline.setDefinition(new CpsFlowDefinition("roles = currentUserGlobalRoles()\n" + "for (r in roles) {\n" + " echo(\"Global Role: \" + r)\n" + "}", true)); try (ACLContext c = ACL.as(User.getById("builder1", true))) { pipeline.scheduleBuild(0, new Cause.UserIdCause()); } jenkinsRule.waitUntilNoActivity(); WorkflowRun run = pipeline.getLastBuild(); jenkinsRule.assertLogContains("readonlyRole", run); jenkinsRule.assertLogNotContains("adminRole", run); } @Test @ConfiguredWithCode("Configuration-as-Code-pipeline.yml") void anonymousUserHasNoRoles() throws Exception { pipeline.setDefinition(new CpsFlowDefinition("roles = currentUserGlobalRoles()\n" + "for (r in roles) {\n" + " echo(\"Global Role: \" + r)\n" + "}\n" + "roles = currentUserItemRoles showAllRoles: true\n" + "for (r in roles) {\n" + " echo(\"Item Role: \" + r)\n" + "}", true)); QueueItemAuthenticatorConfiguration.get().getAuthenticators() .add(new GlobalQueueItemAuthenticator(new AnonymousAuthorizationStrategy())); pipeline.scheduleBuild(0, new Cause.UserIdCause()); jenkinsRule.waitUntilNoActivity(); WorkflowRun run = pipeline.getLastBuild(); jenkinsRule.assertLogNotContains("readonlyRole", run); jenkinsRule.assertLogNotContains("adminRole", run); jenkinsRule.assertLogNotContains("builder1Role", run); jenkinsRule.assertLogNotContains("builder2Role", run); jenkinsRule.assertLogNotContains("reader1Role", run); jenkinsRule.assertLogNotContains("reader2Role", run); } @Test @ConfiguredWithCode("Configuration-as-Code-pipeline.yml") void builderUserHasRoles() throws Exception { pipeline.setDefinition(new CpsFlowDefinition("roles = currentUserGlobalRoles()\n" + "for (r in roles) {\n" + " echo(\"Global Role: \" + r)\n" + "}\n" + "roles = currentUserItemRoles showAllRoles: true\n" + "for (r in roles) {\n" + " echo(\"Item Role: \" + r)\n" + "}", true)); QueueItemAuthenticatorConfiguration.get().getAuthenticators() .add(new GlobalQueueItemAuthenticator(new SpecificUsersAuthorizationStrategy("builder1"))); pipeline.scheduleBuild(0, new TimerTrigger.TimerTriggerCause()); jenkinsRule.waitUntilNoActivity(); WorkflowRun run = pipeline.getLastBuild(); jenkinsRule.assertLogContains("readonlyRole", run); jenkinsRule.assertLogNotContains("adminRole", run); jenkinsRule.assertLogContains("builder1Role", run); jenkinsRule.assertLogNotContains("builder2Role", run); jenkinsRule.assertLogContains("reader1Role", run); jenkinsRule.assertLogContains("reader2Role", run); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/com/synopsys/arc/jenkins/plugins/rolestrategy/MacroExceptionCode.java
src/main/java/com/synopsys/arc/jenkins/plugins/rolestrategy/MacroExceptionCode.java
/* * The MIT License * * Copyright 2013 Oleg Nenashev, Synopsys Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.synopsys.arc.jenkins.plugins.rolestrategy; /** * Contains type of macro exception. * * @author Oleg Nenashev * @since 2.1.0 */ public enum MacroExceptionCode { UnknownError, Not_Macro, WrongFormat, Wrong_arguments }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/com/synopsys/arc/jenkins/plugins/rolestrategy/MacroException.java
src/main/java/com/synopsys/arc/jenkins/plugins/rolestrategy/MacroException.java
/* * The MIT License * * Copyright 2013 Oleg Nenashev, Synopsys Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.synopsys.arc.jenkins.plugins.rolestrategy; /** * Macro exception. * * @author Oleg Nenashev * @since 2.1.0 */ @SuppressWarnings("serial") public class MacroException extends Exception { MacroExceptionCode errorCode; public MacroException(MacroExceptionCode code, String message) { super(message); this.errorCode = code; } public MacroExceptionCode getErrorCode() { return errorCode; } @Override public String getMessage() { return "<" + errorCode + ">: " + super.getMessage(); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/com/synopsys/arc/jenkins/plugins/rolestrategy/RoleType.java
src/main/java/com/synopsys/arc/jenkins/plugins/rolestrategy/RoleType.java
/* * The MIT License * * Copyright 2013 Oleg Nenashev, Synopsys Inc.. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.synopsys.arc.jenkins.plugins.rolestrategy; import com.michelin.cio.hudson.plugins.rolestrategy.RoleBasedAuthorizationStrategy; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; /** * Enumeration wrapper for {@link RoleBasedAuthorizationStrategy}'s items. * * @author Oleg Nenashev * @since 2.1.0 */ public enum RoleType { Global, Project, Slave; /** * Get RoleType from String. * * @deprecated Naming convention violation, use {@link #fromString(java.lang.String)}. */ @Deprecated @SuppressFBWarnings(value = "NM_METHOD_NAMING_CONVENTION", justification = "deprecated, just for API compatibility") @SuppressWarnings("checkstyle:MethodName") public static RoleType FromString(String roleName) { return fromString(roleName); } /** * Get Role Type for {@link RoleBasedAuthorizationStrategy}'s item. * * @param roleName String representation of {@link RoleBasedAuthorizationStrategy}'s item * @return Appropriate row type * @throws IllegalArgumentException Invalid roleName * @since 2.3.0 */ public static RoleType fromString(String roleName) { if (roleName.equals(RoleBasedAuthorizationStrategy.GLOBAL)) { return Global; } if (roleName.equals(RoleBasedAuthorizationStrategy.PROJECT)) { return Project; } if (roleName.equals(RoleBasedAuthorizationStrategy.SLAVE)) { return Slave; } throw new java.lang.IllegalArgumentException("Unexpected roleName=" + roleName); } /** * Converts role to the legacy {@link RoleBasedAuthorizationStrategy}'s string. * * @return {@link RoleBasedAuthorizationStrategy}'s string */ public String getStringType() { switch (this) { case Global: return RoleBasedAuthorizationStrategy.GLOBAL; case Project: return RoleBasedAuthorizationStrategy.PROJECT; case Slave: return RoleBasedAuthorizationStrategy.SLAVE; default: throw new java.lang.IllegalArgumentException("Unsupported Role: " + this); } } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/com/synopsys/arc/jenkins/plugins/rolestrategy/RoleStrategyConfigExtension.java
src/main/java/com/synopsys/arc/jenkins/plugins/rolestrategy/RoleStrategyConfigExtension.java
/* * The MIT License * * Copyright 2013 Oleg Nenashev, Synopsys Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.synopsys.arc.jenkins.plugins.rolestrategy; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; /** * Stub class, which stores jelly files for RoleStrategyPlugin. * * @author Oleg Nenashev * @since 2.1.0 * @deprecated the class is not used anywhere, just a stub */ @Deprecated @Restricted(NoExternalUse.class) public class RoleStrategyConfigExtension { public String getCompanyName() { return "Synopsys"; } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/com/synopsys/arc/jenkins/plugins/rolestrategy/Macro.java
src/main/java/com/synopsys/arc/jenkins/plugins/rolestrategy/Macro.java
/* * The MIT License * * Copyright 2013 Oleg Nenashev, Synopsys Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.synopsys.arc.jenkins.plugins.rolestrategy; import com.michelin.cio.hudson.plugins.rolestrategy.Role; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.Arrays; /** * Macro representation for roles and users. Implements following format: * {@code @macroId[:index][(parameter1, parameter2, ...)]}, * <ul> * <li>macroId - name of the macro. Supports alphanumeric symbols</li> * <li>index - optional integer, which allow to duplicate macro calls</li> * <li>parameters - optional set of strings. each parameter should be string without quotes</li> * </ul> * TODO: Macro parameters (ex, multiple usage of macro) * * @since 2.1.0 * @author Oleg Nenashev, Synopsys Inc. */ public class Macro { public static final String MACRO_PREFIX = "@"; private static final String PARAMS_LEFT_BORDER = "("; private static final String PARAMS_RIGHT_BORDER = ")"; private static final String PARAMS_DELIMITER = "\\\"*,\\\"*"; private static final String INDEX_DELIMITER = ":"; private static final int DEFAULT_MACRO_ID = Integer.MIN_VALUE; private final String name; private final String dispName; private final int index; // TODO: rework to list/set? @NonNull private final String[] parameters; /** * Create new Macro. * * @param name Name of Macro * @param index Index of Macro * @param parameters List of Parameters */ public Macro(String name, Integer index, String[] parameters) { this.name = name; this.dispName = MACRO_PREFIX + name; this.index = (index == null) ? DEFAULT_MACRO_ID : index; this.parameters = parameters != null ? Arrays.copyOf(parameters, parameters.length) : new String[0]; } /** * Get name of the macro. * * @return Name of the macro (without prefix) */ public String getName() { return name; } public String getDisplayName() { return dispName; } public int getIndex() { return index; } public boolean hasIndex() { return index != DEFAULT_MACRO_ID; } public String[] getParameters() { return Arrays.copyOf(parameters, parameters.length); } public boolean hasParameters() { return parameters.length != 0; } @Override public String toString() { StringBuilder bldr = new StringBuilder(dispName); if (hasIndex()) { bldr.append(":"); bldr.append(index); } if (hasParameters()) { bldr.append("("); bldr.append(parameters[0]); for (int i = 1; i < parameters.length; i++) { bldr.append(","); bldr.append(parameters[i]); } bldr.append(")"); } return bldr.toString(); } /** * Check if role is a macro. * * @param role Role to be checked * @return true if role meets macro criteria */ public static boolean isMacro(Role role) { return isMacro(role.getName()); } public static boolean isMacro(String macroString) { return macroString.startsWith(MACRO_PREFIX); } /** * Parse Macro. * * @deprecated Use {@link #parse(java.lang.String)} */ @Deprecated @SuppressFBWarnings(value = "NM_METHOD_NAMING_CONVENTION", justification = "deprecated, just for API compatibility") @SuppressWarnings("checkstyle:MethodName") public static Macro Parse(String macroString) throws MacroException { return parse(macroString); } /** * Parse macro from string. * * @param macroString - macro string * @return Macro instance * @throws MacroException - Parse error * @since 2.3.0 */ public static Macro parse(String macroString) throws MacroException { if (!isMacro(macroString)) { throw new MacroException(MacroExceptionCode.Not_Macro, "Can't parse macro: Macro String should start from " + MACRO_PREFIX); } int leftBorder = macroString.indexOf(PARAMS_LEFT_BORDER); int rightBorder = macroString.lastIndexOf(PARAMS_RIGHT_BORDER); boolean hasParams = checkBorders(macroString, leftBorder, rightBorder); // Get macroName and id String macroIdStr = hasParams ? macroString.substring(0, leftBorder) : macroString; String[] macroIdItems = macroIdStr.split(INDEX_DELIMITER); if (macroIdItems.length > 2) { throw new MacroException(MacroExceptionCode.WrongFormat, "Macro string should contain only one '" + INDEX_DELIMITER + "' delimiter"); } // Macro name String macroName = macroIdItems[0].substring(MACRO_PREFIX.length()); if (macroName.isEmpty()) { throw new MacroException(MacroExceptionCode.WrongFormat, "Macro name is empty"); } // Macro id int macroId = DEFAULT_MACRO_ID; if (macroIdItems.length == 2) { try { macroId = Integer.parseInt(macroIdItems[1]); } catch (NumberFormatException ex) { throw new MacroException(MacroExceptionCode.WrongFormat, "Can't parse int from " + macroIdItems[1] + ": " + ex.getMessage()); } } // Parse parameters String[] params = null; if (hasParams) { String paramsStr = macroString.substring(leftBorder + 1, rightBorder); params = paramsStr.split(PARAMS_DELIMITER); } return new Macro(macroName, macroId, params); } private static boolean checkBorders(String macroStr, int leftBorder, int rightBorder) throws MacroException { if (leftBorder == -1 || rightBorder == -1) { if (leftBorder == rightBorder) { return false; // no borders } String missingBorder = (leftBorder == -1) ? "left" : "right"; throw new MacroException(MacroExceptionCode.WrongFormat, "Missing border: " + missingBorder); } // Check ending if (rightBorder != -1 && !macroStr.endsWith(PARAMS_RIGHT_BORDER)) { throw new MacroException(MacroExceptionCode.WrongFormat, "Parametrized Macro should end with '" + PARAMS_RIGHT_BORDER + "'"); } // Check duplicated borders if (leftBorder != macroStr.lastIndexOf(PARAMS_LEFT_BORDER)) { throw new MacroException(MacroExceptionCode.WrongFormat, "Duplicated left border ('" + PARAMS_LEFT_BORDER + "' symbol)"); } if (rightBorder != macroStr.indexOf(PARAMS_RIGHT_BORDER)) { throw new MacroException(MacroExceptionCode.WrongFormat, "Duplicated right border ('" + PARAMS_RIGHT_BORDER + "' symbol)"); } // Check quatas if (macroStr.contains("\"")) { throw new MacroException(MacroExceptionCode.WrongFormat, "Double quotes aren't supported"); } if (macroStr.contains("'")) { throw new MacroException(MacroExceptionCode.WrongFormat, "Single quotes aren't supported"); } return true; } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/com/synopsys/arc/jenkins/plugins/rolestrategy/RoleMacroExtension.java
src/main/java/com/synopsys/arc/jenkins/plugins/rolestrategy/RoleMacroExtension.java
/* * The MIT License * * Copyright 2013 Oleg Nenashev, Synopsys Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.synopsys.arc.jenkins.plugins.rolestrategy; import com.synopsys.arc.jenkins.plugins.rolestrategy.macros.StubMacro; import edu.umd.cs.findbugs.annotations.CheckForNull; import hudson.ExtensionList; import hudson.ExtensionPoint; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Extension for macro roles (automatic membership handling). * * @author Oleg Nenashev * @since 2.1.0 */ public abstract class RoleMacroExtension implements ExtensionPoint, IMacroExtension { private static final Map<String, RoleMacroExtension> NAME_CACHE = new ConcurrentHashMap<>(); private static final Map<String, Macro> MACRO_CACHE = new ConcurrentHashMap<>(); private static void updateRegistry() { NAME_CACHE.clear(); for (RoleMacroExtension ext : all()) { NAME_CACHE.put(ext.getName(), ext); } } /** * Parse Macro and return it. * * @param unparsedMacroString String to parse * @return parsed Macro */ @CheckForNull public static Macro getMacro(String unparsedMacroString) { if (MACRO_CACHE.containsKey(unparsedMacroString)) { return MACRO_CACHE.get(unparsedMacroString); } try { Macro m = Macro.parse(unparsedMacroString); MACRO_CACHE.put(unparsedMacroString, m); return m; } catch (MacroException ex) { MACRO_CACHE.put(unparsedMacroString, null); return null; } } /** * Get Macro with the given name. * * @param macroName Name of Macro * @return RoleMacroExtension */ public static RoleMacroExtension getMacroExtension(String macroName) { // TODO: the method is not thread-safe if (NAME_CACHE.isEmpty()) { updateRegistry(); } RoleMacroExtension ext = NAME_CACHE.get(macroName); return ext != null ? ext : StubMacro.Instance; } /** * Get list of all registered {@link RoleMacroExtension}s. * * @return List of {@link RoleMacroExtension}s. */ public static ExtensionList<RoleMacroExtension> all() { return ExtensionList.lookup(RoleMacroExtension.class); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/com/synopsys/arc/jenkins/plugins/rolestrategy/IMacroExtension.java
src/main/java/com/synopsys/arc/jenkins/plugins/rolestrategy/IMacroExtension.java
/* * The MIT License * * Copyright 2013 Oleg Nenashev, Synopsys Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.synopsys.arc.jenkins.plugins.rolestrategy; import com.michelin.cio.hudson.plugins.rolestrategy.AuthorizationType; import com.michelin.cio.hudson.plugins.rolestrategy.PermissionEntry; import hudson.security.AccessControlled; import hudson.security.Permission; /** * Interface for Role-based plug-in Macro extensions. * * @see RoleMacroExtension * @author Oleg Nenashev * @since 2.1.0 */ @SuppressWarnings("checkstyle:AbbreviationAsWordInName") public interface IMacroExtension { /** * Get name of the appropriate macro. * * @return Name of the macro */ String getName(); /** * Check if the macro extension is applicable to specified role type. * * @param roleType Type to be checked * @return {@code true} if the macro is applicable to the specified role type */ // TODO: fix naming conventions @SuppressWarnings("checkstyle:MethodName") boolean IsApplicable(RoleType roleType); /** * Returns description of the macro (including parameters). * * @return Description of the macro */ String getDescription(); /** * Check if user belongs to specified Macro. * * @param sid SID to be checked * @param p Permission * @param type Type of the role to be checked * @param item Item * @param macro Macro with parameters * @return True if user satisfies macro's requirements */ boolean hasPermission(PermissionEntry sid, Permission p, RoleType type, AccessControlled item, Macro macro); default boolean hasPermission(String sid, Permission p, RoleType type, AccessControlled item, Macro macro) { return hasPermission(new PermissionEntry(AuthorizationType.EITHER, sid), p, type, item, macro); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/com/synopsys/arc/jenkins/plugins/rolestrategy/macros/FolderMacro.java
src/main/java/com/synopsys/arc/jenkins/plugins/rolestrategy/macros/FolderMacro.java
/* * The MIT License * * Copyright 2022 Markus Winter * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.synopsys.arc.jenkins.plugins.rolestrategy.macros; import com.cloudbees.hudson.plugins.folder.AbstractFolder; import com.michelin.cio.hudson.plugins.rolestrategy.PermissionEntry; import com.synopsys.arc.jenkins.plugins.rolestrategy.Macro; import com.synopsys.arc.jenkins.plugins.rolestrategy.RoleMacroExtension; import com.synopsys.arc.jenkins.plugins.rolestrategy.RoleType; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.security.AccessControlled; import hudson.security.Permission; /** * Applies permissions to folders only. * */ @Extension(optional = true) public class FolderMacro extends RoleMacroExtension { @Override public String getName() { return "Folder"; } // TODO: fix naming conventions @SuppressFBWarnings(value = "NM_METHOD_NAMING_CONVENTION", justification = "Old code, should be fixed later") @Override public boolean IsApplicable(RoleType roleType) { return roleType == RoleType.Project; } @Override public boolean hasPermission(PermissionEntry sid, Permission p, RoleType type, AccessControlled item, Macro macro) { return AbstractFolder.class.isAssignableFrom(item.getClass()); } @Override public String getDescription() { return "Filters out everything that is not a folder."; } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/com/synopsys/arc/jenkins/plugins/rolestrategy/macros/ContainedInViewMacro.java
src/main/java/com/synopsys/arc/jenkins/plugins/rolestrategy/macros/ContainedInViewMacro.java
/* * The MIT License * * Copyright 2022 Markus Winter * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.synopsys.arc.jenkins.plugins.rolestrategy.macros; import com.cloudbees.hudson.plugins.folder.AbstractFolder; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import com.michelin.cio.hudson.plugins.rolestrategy.PermissionEntry; import com.synopsys.arc.jenkins.plugins.rolestrategy.Macro; import com.synopsys.arc.jenkins.plugins.rolestrategy.RoleMacroExtension; import com.synopsys.arc.jenkins.plugins.rolestrategy.RoleType; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.model.Item; import hudson.model.ListView; import hudson.model.View; import hudson.security.ACL; import hudson.security.ACLContext; import hudson.security.AccessControlled; import hudson.security.Permission; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import jenkins.model.Jenkins; import org.jenkinsci.plugins.rolestrategy.Settings; /** * Checks if the item is contained in one of the views. * */ @Extension(optional = true) public class ContainedInViewMacro extends RoleMacroExtension { /* * Map of macro to view. * * Getting the items in a view is expensive so we need to cache that information */ private final Cache<Macro, Map<View, Set<String>>> cache = Caffeine.newBuilder().maximumSize(Settings.VIEW_CACHE_MAX_SIZE) .expireAfterWrite(Settings.VIEW_CACHE_EXPIRATION_TIME_SEC, TimeUnit.SECONDS).weakKeys().build(); /* * Map of view to items contained in the view. * * Getting the items in a view is expensive so we need to cache that information */ private final Cache<View, Set<String>> viewCache = Caffeine.newBuilder().maximumSize(Settings.VIEW_CACHE_MAX_SIZE) .expireAfterWrite(Settings.VIEW_CACHE_EXPIRATION_TIME_SEC, TimeUnit.SECONDS).weakKeys().build(); @Override public String getName() { return "ContainedInView"; } // TODO: fix naming conventions @SuppressFBWarnings(value = "NM_METHOD_NAMING_CONVENTION", justification = "Old code, should be fixed later") @Override public boolean IsApplicable(RoleType roleType) { return roleType == RoleType.Project; } @Override public boolean hasPermission(PermissionEntry sid, Permission p, RoleType type, AccessControlled accessControlledItem, Macro macro) { if (accessControlledItem instanceof Item) { Item item = (Item) accessControlledItem; Map<View, Set<String>> items = cache.get(macro, this::getItemsForMacro); for (Entry<View, Set<String>> entry : items.entrySet()) { if (entry.getValue().contains(item.getFullName())) { return true; } } } return false; } @Override public String getDescription() { return "Access items that are added to a ListView. Specify the views as parameter to the macro, e.g. " + "<code>@ContainedInView(view1, view2)</code>. " + "Prepend the folder name if the view is in a folder, e.g. <code>@ContainedInView(folder/view1)</code> " + "(To access views inside a folder, access to the folder itself is required).<br/>" + "When enabling the <dfn>Recurse in subfolders</dfn> option, make sure to also check the folders themselves for which you " + "add items.<br/>" + "NestedView plugin is not supported currently as this allows to create ambiguous names for views."; } /** * Returns a map of all items of all views this macro covers. * * @param macro The macro for which to get the items * @return Map of all items */ private Map<View, Set<String>> getItemsForMacro(Macro macro) { Map<View, Set<String>> viewList = new HashMap<>(); for (String viewName : macro.getParameters()) { View view = getViewFromFullName(viewName); if (view != null) { viewList.put(view, viewCache.get(view, this::getItemsForView)); } } return viewList; } /** * Returns the set of fullNames of all items contained in the view. * * @param view The View to get the items from * @return Set of item fullNames */ private Set<String> getItemsForView(View view) { Set<String> items = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); try (ACLContext c = ACL.as2(ACL.SYSTEM2)) { items.addAll(view.getItems().stream().map(Item::getFullName).collect(Collectors.toSet())); } return items; } /** * Gets the view for the given view name. * Currently only ListViews are supported that are directly under Jenkins or under a folder. * * @param viewName Full name of the view * @return the View matching the name or null of not found. */ @CheckForNull private View getViewFromFullName(String viewName) { Jenkins jenkins = Jenkins.get(); try (ACLContext c = ACL.as2(ACL.SYSTEM2)) { int index = viewName.lastIndexOf("/"); if (index > 0) { String folderFullName = viewName.substring(0, index); String viewBaseName = viewName.substring(index + 1); AbstractFolder<?> folder = jenkins.getItemByFullName(folderFullName, AbstractFolder.class); if (folder != null) { for (View view : folder.getViews()) { if (view instanceof ListView && view.getViewName().equals(viewBaseName) && view.getOwner() == folder) { return view; } } } } else { View view = jenkins.getView(viewName); if (view instanceof ListView && view.getOwner() == Jenkins.get()) { return view; } } } return null; } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/com/synopsys/arc/jenkins/plugins/rolestrategy/macros/StubMacro.java
src/main/java/com/synopsys/arc/jenkins/plugins/rolestrategy/macros/StubMacro.java
/* * The MIT License * * Copyright 2013 Oleg Nenashev, Synopsys Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.synopsys.arc.jenkins.plugins.rolestrategy.macros; import com.michelin.cio.hudson.plugins.rolestrategy.PermissionEntry; import com.synopsys.arc.jenkins.plugins.rolestrategy.Macro; import com.synopsys.arc.jenkins.plugins.rolestrategy.RoleMacroExtension; import com.synopsys.arc.jenkins.plugins.rolestrategy.RoleType; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.security.AccessControlled; import hudson.security.Permission; /** * A stub for non-existent macros. Always returns false during permissions check. * * @author Oleg Nenashev * @since 2.1.0 */ public final class StubMacro extends RoleMacroExtension { public static final StubMacro Instance = new StubMacro(); private StubMacro() { } @Override public String getName() { return "Stub"; } // TODO: fix naming conventions @SuppressFBWarnings(value = "NM_METHOD_NAMING_CONVENTION", justification = "Old code, should be fixed later") @Override public boolean IsApplicable(RoleType roleType) { return false; } @Override public boolean hasPermission(PermissionEntry sid, Permission p, RoleType type, AccessControlled item, Macro macro) { return false; } @Override public String getDescription() { return "Just a stub"; } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/com/synopsys/arc/jenkins/plugins/rolestrategy/macros/BuildableJobMacro.java
src/main/java/com/synopsys/arc/jenkins/plugins/rolestrategy/macros/BuildableJobMacro.java
/* * The MIT License * * Copyright 2013 Oleg Nenashev, Synopsys Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.synopsys.arc.jenkins.plugins.rolestrategy.macros; import com.michelin.cio.hudson.plugins.rolestrategy.PermissionEntry; import com.synopsys.arc.jenkins.plugins.rolestrategy.Macro; import com.synopsys.arc.jenkins.plugins.rolestrategy.RoleMacroExtension; import com.synopsys.arc.jenkins.plugins.rolestrategy.RoleType; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.model.Job; import hudson.security.AccessControlled; import hudson.security.Permission; /** * Applies permissions to buildable jobs only. * * @author Oleg Nenashev * @since 2.1.0 */ @Extension public class BuildableJobMacro extends RoleMacroExtension { @Override public String getName() { return "BuildableJob"; } // TODO: fix naming conventions @SuppressFBWarnings(value = "NM_METHOD_NAMING_CONVENTION", justification = "Old code, should be fixed later") @Override public boolean IsApplicable(RoleType roleType) { return roleType == RoleType.Project; } @Override public boolean hasPermission(PermissionEntry sid, Permission p, RoleType type, AccessControlled item, Macro macro) { if (Job.class.isAssignableFrom(item.getClass())) { Job<?, ?> job = (Job<?, ?>) item; return job.isBuildable(); } else { return false; } } @Override public String getDescription() { return "Filters out unbuildable items, e.g. folders"; } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/com/michelin/cio/hudson/plugins/rolestrategy/ValidationUtil.java
src/main/java/com/michelin/cio/hudson/plugins/rolestrategy/ValidationUtil.java
package com.michelin.cio.hudson.plugins.rolestrategy; import hudson.Functions; import hudson.Util; import hudson.model.User; import hudson.security.GroupDetails; import hudson.security.SecurityRealm; import hudson.security.UserMayOrMayNotExistException2; import hudson.util.FormValidation; import org.apache.commons.lang3.StringUtils; import org.jenkins.ui.symbol.Symbol; import org.jenkins.ui.symbol.SymbolRequest; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.UsernameNotFoundException; @Restricted(NoExternalUse.class) class ValidationUtil { private static String userSymbol; private static String groupSymbol; private static String warningSymbol; private ValidationUtil() { // do not use } static String formatNonExistentUserGroupValidationResponse(AuthorizationType type, String user, String tooltip) { return formatNonExistentUserGroupValidationResponse(type, user, tooltip, false); } static String formatNonExistentUserGroupValidationResponse(AuthorizationType type, String user, String tooltip, boolean alert) { return formatUserGroupValidationResponse(type, "<span class='rsp-entry-not-found'>" + user + "</span>", tooltip, alert); } private static String getSymbol(String symbol, String clazzes) { SymbolRequest.Builder builder = new SymbolRequest.Builder(); return Symbol.get(builder.withRaw("symbol-" + symbol + "-outline plugin-ionicons-api").withClasses(clazzes).build()); } private static void loadUserSymbol() { if (userSymbol == null) { userSymbol = getSymbol("person", "icon-sm"); } } private static void loadGroupSymbol() { if (groupSymbol == null) { groupSymbol = getSymbol("people", "icon-sm"); } } private static void loadWarningSymbol() { if (warningSymbol == null) { warningSymbol = getSymbol("warning", "icon-md rsp-table__icon-alert"); } } static String formatUserGroupValidationResponse(AuthorizationType type, String user, String tooltip) { return formatUserGroupValidationResponse(type, user, tooltip, false); } static String formatUserGroupValidationResponse(AuthorizationType type, String user, String tooltip, boolean alert) { String symbol; switch (type) { case GROUP: loadGroupSymbol(); symbol = groupSymbol; break; case EITHER: case USER: default: loadUserSymbol(); symbol = userSymbol; break; } if (alert) { loadWarningSymbol(); return String.format("<div tooltip='%s' class='rsp-table__cell'>%s%s%s</div>", tooltip, warningSymbol, symbol, user); } return String.format("<div tooltip='%s' class='rsp-table__cell'>%s%s</div>", tooltip, symbol, user); } static FormValidation validateGroup(String groupName, SecurityRealm sr, boolean ambiguous) { String escapedSid = Functions.escape(groupName); try { GroupDetails details = sr.loadGroupByGroupname2(groupName, false); escapedSid = Util.escape(StringUtils.abbreviate(details.getDisplayName(), 50)); if (ambiguous) { return FormValidation.respond(FormValidation.Kind.WARNING, formatUserGroupValidationResponse(AuthorizationType.GROUP, escapedSid, "Group found; but permissions would also be granted to a user of this name", true)); } else { return FormValidation.respond(FormValidation.Kind.OK, formatUserGroupValidationResponse(AuthorizationType.GROUP, escapedSid, "Group")); } } catch (UserMayOrMayNotExistException2 e) { // undecidable, meaning the group may exist if (ambiguous) { return FormValidation.respond(FormValidation.Kind.WARNING, formatUserGroupValidationResponse(AuthorizationType.GROUP, escapedSid, "Permissions would also be granted to a user or group of this name", true)); } else { return FormValidation.ok(escapedSid); } } catch (UsernameNotFoundException e) { // fall through next } catch (AuthenticationException e) { // other seemingly unexpected error. return FormValidation.error(e, "Failed to test the validity of the group name " + groupName); } return null; } static FormValidation validateUser(String userName, SecurityRealm sr, boolean ambiguous) { String escapedSid = Functions.escape(userName); try { sr.loadUserByUsername2(userName); User u = User.getById(userName, true); if (userName.equals(u.getFullName())) { // Sid and full name are identical, no need for tooltip if (ambiguous) { return FormValidation.respond(FormValidation.Kind.WARNING, formatUserGroupValidationResponse(AuthorizationType.EITHER, escapedSid, "User found; but permissions would also be granted to a group of this name", true)); } else { return FormValidation.respond(FormValidation.Kind.OK, formatUserGroupValidationResponse(AuthorizationType.USER, escapedSid, "User")); } } if (ambiguous) { return FormValidation.respond(FormValidation.Kind.WARNING, formatUserGroupValidationResponse(AuthorizationType.EITHER, Util.escape(StringUtils.abbreviate(u.getFullName(), 50)), "User " + escapedSid + " found, but permissions would also be granted to a group of this name", true)); } else { return FormValidation.respond(FormValidation.Kind.OK, formatUserGroupValidationResponse(AuthorizationType.USER, Util.escape(StringUtils.abbreviate(u.getFullName(), 50)), "User " + escapedSid)); } } catch (UserMayOrMayNotExistException2 e) { // undecidable, meaning the user may exist if (ambiguous) { return FormValidation.respond(FormValidation.Kind.WARNING, formatUserGroupValidationResponse(AuthorizationType.EITHER, escapedSid, "Permissions would also be granted to a user or group of this name", true)); } else { return FormValidation.ok(escapedSid); } } catch (UsernameNotFoundException e) { // fall through next } catch (AuthenticationException e) { // other seemingly unexpected error. return FormValidation.error(e, "Failed to test the validity of the user name " + escapedSid); } return null; } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/com/michelin/cio/hudson/plugins/rolestrategy/RoleStrategyRootAction.java
src/main/java/com/michelin/cio/hudson/plugins/rolestrategy/RoleStrategyRootAction.java
/* * The MIT License * * Copyright (c) 2025, CloudBees, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.michelin.cio.hudson.plugins.rolestrategy; import edu.umd.cs.findbugs.annotations.CheckForNull; import hudson.Extension; import hudson.model.RootAction; import jenkins.model.Jenkins; import org.kohsuke.stapler.StaplerProxy; /** * Provides a root-level link for users with ITEM_ROLES_ADMIN or AGENT_ROLES_ADMIN permissions * who do not have SYSTEM_READ permission (and thus cannot access Manage Jenkins). * <p> * This action delegates to the RoleStrategyConfig for actual page handling. */ @Extension public class RoleStrategyRootAction implements RootAction, StaplerProxy { @CheckForNull @Override public String getIconFileName() { // Only show this link if: // 1. The role-based authorization strategy is enabled // 2. User has ITEM_ROLES_ADMIN or AGENT_ROLES_ADMIN // 3. User does NOT have SYSTEM_READ (otherwise they can use ManagementLink) Jenkins jenkins = Jenkins.get(); if (!(jenkins.getAuthorizationStrategy() instanceof RoleBasedAuthorizationStrategy)) { return null; } boolean hasRoleAdmin = jenkins.hasAnyPermission( RoleBasedAuthorizationStrategy.AGENT_ROLES_ADMIN, RoleBasedAuthorizationStrategy.ITEM_ROLES_ADMIN ); boolean hasSystemRead = jenkins.hasPermission(Jenkins.SYSTEM_READ); // Only show if user has role admin permissions but NOT system read if (hasRoleAdmin && !hasSystemRead) { return "symbol-lock-closed-outline plugin-ionicons-api"; } return null; } @CheckForNull @Override public String getDisplayName() { return Messages.RoleBasedAuthorizationStrategy_ManageAndAssign(); } @CheckForNull @Override public String getUrlName() { return "role-strategy"; } /** * Delegate all page handling to RoleStrategyConfig. * This allows the RootAction to serve at /role-strategy while reusing all the logic. */ public Object getTarget() { Jenkins.get().checkAnyPermission(RoleBasedAuthorizationStrategy.ADMINISTER_AND_SOME_ROLES_ADMIN); return RoleStrategyConfig.get(); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/com/michelin/cio/hudson/plugins/rolestrategy/RoleBasedAuthorizationStrategy.java
src/main/java/com/michelin/cio/hudson/plugins/rolestrategy/RoleBasedAuthorizationStrategy.java
/* * The MIT License * * Copyright (c) 2010-2017, Manufacture Française des Pneumatiques Michelin, * Thomas Maurel, Romain Seguy, Synopsys Inc., Oleg Nenashev and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.michelin.cio.hudson.plugins.rolestrategy; import static com.michelin.cio.hudson.plugins.rolestrategy.ValidationUtil.formatNonExistentUserGroupValidationResponse; import static com.michelin.cio.hudson.plugins.rolestrategy.ValidationUtil.formatUserGroupValidationResponse; import com.synopsys.arc.jenkins.plugins.rolestrategy.RoleType; import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.ExtendedHierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.Functions; import hudson.Util; import hudson.init.InitMilestone; import hudson.init.Initializer; import hudson.model.AbstractItem; import hudson.model.Computer; import hudson.model.Descriptor; import hudson.model.Job; import hudson.model.Node; import hudson.security.ACL; import hudson.security.AuthorizationStrategy; import hudson.security.Permission; import hudson.security.PermissionGroup; import hudson.security.PermissionScope; import hudson.security.SecurityRealm; import hudson.security.SidACL; import hudson.util.FormValidation; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import java.util.stream.Collectors; import jenkins.model.Jenkins; import jenkins.util.SystemProperties; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.acegisecurity.acls.sid.PrincipalSid; import org.apache.commons.lang3.StringUtils; import org.jenkinsci.plugins.rolestrategy.AmbiguousSidsAdminMonitor; import org.jenkinsci.plugins.rolestrategy.permissions.PermissionHelper; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.DoNotUse; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.StaplerRequest2; import org.kohsuke.stapler.StaplerResponse2; import org.kohsuke.stapler.interceptor.RequirePOST; import org.kohsuke.stapler.verb.GET; import org.kohsuke.stapler.verb.POST; import org.springframework.security.access.AccessDeniedException; /** * Role-based authorization strategy. * * @author Thomas Maurel */ public class RoleBasedAuthorizationStrategy extends AuthorizationStrategy { private static Logger LOGGER = Logger.getLogger(RoleBasedAuthorizationStrategy.class.getName()); public static final String GLOBAL = "globalRoles"; public static final String PROJECT = "projectRoles"; public static final String SLAVE = "slaveRoles"; public static final String PERMISSION_TEMPLATES = "permissionTemplates"; public static final String MACRO_ROLE = "roleMacros"; public static final String MACRO_USER = "userMacros"; private final RoleMap agentRoles; private final RoleMap globalRoles; private final RoleMap itemRoles; private Map<String, PermissionTemplate> permissionTemplates; private static final boolean USE_ITEM_AND_AGENT_ROLES = SystemProperties.getBoolean( RoleBasedAuthorizationStrategy.class.getName() + ".useItemAndAgentRoles", false); /** * Create new RoleBasedAuthorizationStrategy. */ public RoleBasedAuthorizationStrategy() { agentRoles = new RoleMap(); globalRoles = new RoleMap(); itemRoles = new RoleMap(); permissionTemplates = new TreeMap<>(); } /** * Creates a new {@link RoleBasedAuthorizationStrategy}. * * @param grantedRoles the roles in the strategy */ public RoleBasedAuthorizationStrategy(Map<String, RoleMap> grantedRoles) { this(grantedRoles, null); } /** * Creates a new {@link RoleBasedAuthorizationStrategy}. * * @param grantedRoles the roles in the strategy * @param permissionTemplates the permission templates in the strategy */ public RoleBasedAuthorizationStrategy(Map<String, RoleMap> grantedRoles, @CheckForNull Set<PermissionTemplate> permissionTemplates) { this.permissionTemplates = new TreeMap<>(); if (permissionTemplates != null) { for (PermissionTemplate template : permissionTemplates) { this.permissionTemplates.put(template.getName(), template); } } RoleMap map = grantedRoles.get(SLAVE); agentRoles = map == null ? new RoleMap() : map; map = grantedRoles.get(GLOBAL); globalRoles = map == null ? new RoleMap() : map; map = grantedRoles.get(PROJECT); itemRoles = map == null ? new RoleMap() : map; refreshPermissionsFromTemplate(); } public static final PermissionGroup GROUP = new PermissionGroup(RoleBasedAuthorizationStrategy.class, Messages._RoleBasedAuthorizationStrategy_PermissionGroupTitle()); public static final Permission ITEM_ROLES_ADMIN = new Permission( GROUP, "ItemRoles", Messages._RoleBasedAuthorizationStrategy_ItemRolesAdminPermissionDescription(), Jenkins.ADMINISTER, USE_ITEM_AND_AGENT_ROLES, new PermissionScope[]{PermissionScope.JENKINS}); public static final Permission AGENT_ROLES_ADMIN = new Permission( GROUP, "AgentRoles", Messages._RoleBasedAuthorizationStrategy_AgentRolesAdminPermissionDescription(), Jenkins.ADMINISTER, USE_ITEM_AND_AGENT_ROLES, new PermissionScope[]{PermissionScope.JENKINS}); @Restricted(NoExternalUse.class) // called by jelly public static final Permission[] SYSTEM_READ_AND_ITEM_ROLES_ADMIN = new Permission[] { Jenkins.SYSTEM_READ, ITEM_ROLES_ADMIN }; @Restricted(NoExternalUse.class) // called by jelly public static final Permission[] SYSTEM_READ_AND_SOME_ROLES_ADMIN = new Permission[] { Jenkins.SYSTEM_READ, ITEM_ROLES_ADMIN, AGENT_ROLES_ADMIN }; @SuppressFBWarnings(value = "MS_PKGPROTECT", justification = "Used by jelly pages") @Restricted(NoExternalUse.class) // called by jelly public static final Permission[] ADMINISTER_AND_SOME_ROLES_ADMIN = new Permission[] { Jenkins.ADMINISTER, ITEM_ROLES_ADMIN, AGENT_ROLES_ADMIN }; /** * Refresh item permissions from templates. */ private void refreshPermissionsFromTemplate() { SortedMap<Role, Set<PermissionEntry>> roles = getGrantedRolesEntries(RoleBasedAuthorizationStrategy.PROJECT); for (Role role : roles.keySet()) { if (Util.fixEmptyAndTrim(role.getTemplateName()) != null) { role.refreshPermissionsFromTemplate(permissionTemplates.get(role.getTemplateName())); } } } /** * Get the root ACL. * * @return The global ACL */ @Override @NonNull public SidACL getRootACL() { return globalRoles.getACL(RoleType.Global, null); } /** * Get the {@link RoleMap} corresponding to the {@link RoleType}. * * @param roleType the type of the role * @return the {@link RoleMap} corresponding to the {@code roleType} * @throws IllegalArgumentException for an invalid {@code roleType} */ @NonNull @Restricted(NoExternalUse.class) public RoleMap getRoleMap(RoleType roleType) { switch (roleType) { case Global: return globalRoles; case Project: return itemRoles; case Slave: return agentRoles; default: throw new IllegalArgumentException("Unknown RoleType: " + roleType); } } /** * Get the specific ACL for projects. * * @param project The access-controlled project * @return The project specific ACL */ @Override @NonNull public ACL getACL(@NonNull Job<?, ?> project) { return getACL((AbstractItem) project); } @Override @NonNull public ACL getACL(@NonNull AbstractItem project) { return itemRoles.newMatchingRoleMap(project.getFullName()).getACL(RoleType.Project, project).newInheritingACL(getRootACL()); } @Override @NonNull public ACL getACL(@NonNull Computer computer) { return agentRoles.newMatchingRoleMap(computer.getName()).getACL(RoleType.Slave, computer).newInheritingACL(getRootACL()); } @Override @NonNull public ACL getACL(@NonNull Node node) { return agentRoles.newMatchingRoleMap(node.getNodeName()).getACL(RoleType.Slave, node).newInheritingACL(getRootACL()); } /** * Used by the container realm. * * @return All the sids referenced by the strategy */ @Override @NonNull public Collection<String> getGroups() { Set<String> sids = new HashSet<>(); sids.addAll(filterRoleSids(globalRoles)); sids.addAll(filterRoleSids(itemRoles)); sids.addAll(filterRoleSids(agentRoles)); return sids; } private Set<String> filterRoleSids(RoleMap roleMap) { return roleMap.getSidEntries(false).stream().filter(entry -> entry.getType() != AuthorizationType.USER) .map(PermissionEntry::getSid).collect(Collectors.toSet()); } /** * Get the roles from the global {@link RoleMap}. * <p>The returned sorted map is unmodifiable. * </p> * * @param type The object type controlled by the {@link RoleMap} * @return All roles from the global {@link RoleMap}. * @deprecated Use {@link RoleBasedAuthorizationStrategy#getGrantedRolesEntries(RoleType)} */ @Nullable @Deprecated public SortedMap<Role, Set<String>> getGrantedRoles(String type) { return getRoleMap(RoleType.fromString(type)).getGrantedRoles(); } /** * Get the {@link Role}s and the sids assigned to them for the given {@link RoleType}. * * @param type the type of the role * @return roles mapped to the set of user sids assigned to that role * @since 2.12 * @deprecated use {@link #getGrantedRolesEntries(RoleType)} */ @Deprecated public SortedMap<Role, Set<String>> getGrantedRoles(@NonNull RoleType type) { return getRoleMap(type).getGrantedRoles(); } /** * Get the permission templates. * * @return set of permission templates. */ public Set<PermissionTemplate> getPermissionTemplates() { return Set.copyOf(permissionTemplates.values()); } @CheckForNull public PermissionTemplate getPermissionTemplate(String templateName) { return permissionTemplates.get(templateName); } public boolean hasPermissionTemplate(String name) { return permissionTemplates.containsKey(name); } /** * Get the {@link Role}s and the sids assigned to them for the given {@link RoleType}. * * @param type the type of the role * @return roles mapped to the set of user sids assigned to that role */ public SortedMap<Role, Set<PermissionEntry>> getGrantedRolesEntries(@NonNull String type) { return getGrantedRolesEntries(RoleType.fromString(type)); } /** * Get the {@link Role}s and the sids assigned to them for the given {@link RoleType}. * * @param type the type of the role * @return roles mapped to the set of user sids assigned to that role */ public SortedMap<Role, Set<PermissionEntry>> getGrantedRolesEntries(@NonNull RoleType type) { return getRoleMap(type).getGrantedRolesEntries(); } /** * Get all the SIDs referenced by specified {@link RoleMap} type. * * @param type The object type controlled by the {@link RoleMap} * @return All SIDs from the specified {@link RoleMap}. */ public Set<PermissionEntry> getSidEntries(String type) { return getRoleMap(RoleType.fromString(type)).getSidEntries(); } /** * Get all the SIDs referenced by specified {@link RoleMap} type. * * @param type The object type controlled by the {@link RoleMap} * @return All SIDs from the specified {@link RoleMap}. * @deprecated use {@link #getSidEntries(String)} */ @Deprecated @CheckForNull @SuppressWarnings("checkstyle:AbbreviationAsWordInName") public Set<String> getSIDs(String type) { return getRoleMap(RoleType.fromString(type)).getSids(); } /** * Returns a map associating a {@link RoleType} with each {@link RoleMap}. * <p> * This method is intended to be used for XML serialization purposes (take a look at the {@link ConverterImpl}) and, as * such, must remain private since it exposes all the security config. * </p> */ @NonNull private Map<RoleType, RoleMap> getRoleMaps() { Map<RoleType, RoleMap> roleMaps = new HashMap<>(); roleMaps.put(RoleType.Global, globalRoles); roleMaps.put(RoleType.Slave, agentRoles); roleMaps.put(RoleType.Project, itemRoles); return Collections.unmodifiableMap(roleMaps); } /** * Add the given {@link Role} to the {@link RoleMap} associated to the provided class. * * @param roleType The type of the {@link Role} to be added * @param role The {@link Role} to add */ private void addRole(RoleType roleType, Role role) { getRoleMap(roleType).addRole(role); } /** * Assign a role to a sid. * * @param type The type of role * @param role The role to assign * @param sid The sid to assign to */ private void assignRole(RoleType type, Role role, PermissionEntry sid) { RoleMap roleMap = getRoleMap(type); if (roleMap.hasRole(role)) { roleMap.assignRole(role, sid); } } private static void persistChanges() throws IOException { Jenkins j = instance(); j.save(); AuthorizationStrategy as = j.getAuthorizationStrategy(); if (as instanceof RoleBasedAuthorizationStrategy) { RoleBasedAuthorizationStrategy rbas = (RoleBasedAuthorizationStrategy) as; rbas.validateConfig(); } } private static Jenkins instance() { return Jenkins.get(); } private static void checkAdminPerm() { instance().checkPermission(Jenkins.ADMINISTER); } private static void checkPerms(@NonNull Permission... permission) { instance().checkAnyPermission(permission); } private static boolean hasPermissionByRoleTypeForUpdates(String roleTypeAsString) { switch (roleTypeAsString) { case RoleBasedAuthorizationStrategy.GLOBAL: return instance().hasPermission(Jenkins.ADMINISTER); case RoleBasedAuthorizationStrategy.PROJECT: return instance().hasAnyPermission(ITEM_ROLES_ADMIN); case RoleBasedAuthorizationStrategy.SLAVE: return instance().hasAnyPermission(AGENT_ROLES_ADMIN); default: throw new IllegalArgumentException("Unknown RoleType: " + roleTypeAsString); } } private static void checkPermByRoleTypeForUpdates(@NonNull String roleType) { switch (roleType) { case RoleBasedAuthorizationStrategy.GLOBAL: checkAdminPerm(); break; case RoleBasedAuthorizationStrategy.PROJECT: checkPerms(ITEM_ROLES_ADMIN); break; case RoleBasedAuthorizationStrategy.SLAVE: checkPerms(AGENT_ROLES_ADMIN); break; default: throw new IllegalArgumentException("Unknown RoleType: " + roleType); } } private static void checkPermByRoleTypeForReading(@NonNull String roleType) { switch (roleType) { case RoleBasedAuthorizationStrategy.GLOBAL: checkPerms(Jenkins.SYSTEM_READ); break; case RoleBasedAuthorizationStrategy.PROJECT: checkPerms(Jenkins.SYSTEM_READ, ITEM_ROLES_ADMIN); break; case RoleBasedAuthorizationStrategy.SLAVE: checkPerms(Jenkins.SYSTEM_READ, AGENT_ROLES_ADMIN); break; default: throw new IllegalArgumentException("Unknown RoleType: " + roleType); } } /** * API method to add a permission template. * * An existing template with the same will only be replaced when overwrite is set. Otherwise, the request will fail with status * <code>400</code> * * @param name The template nae * @param permissionIds Comma separated list of permission IDs * @param overwrite If an existing template should be overwritten */ @POST @Restricted(NoExternalUse.class) public void doAddTemplate(@QueryParameter(required = true) String name, @QueryParameter(required = true) String permissionIds, @QueryParameter(required = false) boolean overwrite) throws IOException { checkPermByRoleTypeForUpdates(PROJECT); List<String> permissionList = Arrays.asList(permissionIds.split(",")); Set<Permission> permissionSet = PermissionHelper.fromStrings(permissionList, true); PermissionTemplate template = new PermissionTemplate(permissionSet, name); if (!overwrite && hasPermissionTemplate(name)) { Stapler.getCurrentResponse2().sendError(HttpServletResponse.SC_BAD_REQUEST, "A template with name " + name + " already exists."); return; } permissionTemplates.put(name, template); refreshPermissionsFromTemplate(); persistChanges(); } /** * API method to remove templates. * * <p> * Example: {@code curl -X POST localhost:8080/role-strategy/strategy/removeTemplates --data "templates=developer,qualits"} * * @param names comma separated list of templates to remove * @param force If templates that are in use should be removed * @throws IOException in case saving changes fails */ @POST @Restricted(NoExternalUse.class) public void doRemoveTemplates(@QueryParameter(required = true) String names, @QueryParameter(required = false) boolean force) throws IOException { checkPermByRoleTypeForUpdates(PROJECT); String[] split = names.split(","); for (String templateName : split) { templateName = templateName.trim(); PermissionTemplate pt = getPermissionTemplate(templateName); if (pt != null && (!pt.isUsed() || force)) { permissionTemplates.remove(templateName); RoleMap roleMap = getRoleMap(RoleType.Project); for (Role role : roleMap.getRoles()) { if (templateName.equals(role.getTemplateName())) { role.setTemplateName(null); } } } } persistChanges(); } /** * API method to add a role. * * <p>Unknown and dangerous permissions are ignored. * * When specifying a <code>template</code> for an item role, the given permissions are ignored. The named template must exist, * otherwise the request fails with status <code>400</code>. * The <code>template</code> is ignored when adding global or agent roles. * * <p>Example: * {@code curl -X POST localhost:8080/role-strategy/strategy/addRole --data "type=globalRoles&amp;roleName=ADM&amp; * permissionIds=hudson.model.Item.Discover,hudson.model.Item.ExtendedRead&amp;overwrite=true"} * * * @param type (globalRoles, projectRoles, slaveRoles) * @param roleName Name of role * @param permissionIds Comma separated list of IDs for given roleName * @param overwrite Overwrite existing role * @param pattern Role pattern * @param template Name of template * @throws IOException In case saving changes fails * @since 2.5.0 */ @RequirePOST @Restricted(NoExternalUse.class) public void doAddRole(@QueryParameter(required = true) String type, @QueryParameter(required = true) String roleName, @QueryParameter(required = true) String permissionIds, @QueryParameter(required = true) String overwrite, @QueryParameter(required = false) String pattern, @QueryParameter(required = false) String template) throws IOException { checkPermByRoleTypeForUpdates(type); final boolean overwriteb = Boolean.parseBoolean(overwrite); String pttrn = ".*"; String templateName = Util.fixEmptyAndTrim(template); if (!type.equals(RoleBasedAuthorizationStrategy.GLOBAL) && pattern != null) { pttrn = pattern; } List<String> permissionList = Arrays.asList(permissionIds.split(",")); Set<Permission> permissionSet = PermissionHelper.fromStrings(permissionList, true); Role role = new Role(roleName, pttrn, permissionSet); if (RoleBasedAuthorizationStrategy.PROJECT.equals(type) && templateName != null) { if (!hasPermissionTemplate(template)) { Stapler.getCurrentResponse2().sendError( HttpServletResponse.SC_BAD_REQUEST, "A template with name " + template + " doesn't exists." ); return; } role.setTemplateName(templateName); role.refreshPermissionsFromTemplate(getPermissionTemplate(templateName)); } RoleType roleType = RoleType.fromString(type); if (overwriteb) { RoleMap roleMap = getRoleMap(roleType); Role role2 = roleMap.getRole(roleName); if (role2 != null) { roleMap.removeRole(role2); } } addRole(roleType, role); persistChanges(); } /** * API method to remove roles. * * <p> * Example: {@code curl -X POST localhost:8080/role-strategy/strategy/removeRoles --data "type=globalRoles&amp; * roleNames=ADM,DEV"} * * @param type (globalRoles, projectRoles, slaveRoles) * @param roleNames comma separated list of roles to remove from type * @throws IOException in case saving changes fails * @since 2.5.0 */ @RequirePOST @Restricted(NoExternalUse.class) public void doRemoveRoles(@QueryParameter(required = true) String type, @QueryParameter(required = true) String roleNames) throws IOException { checkPermByRoleTypeForUpdates(type); RoleMap roleMap = getRoleMap(RoleType.fromString(type)); String[] split = roleNames.split(","); for (String roleName : split) { Role role = roleMap.getRole(roleName); if (role != null) { roleMap.removeRole(role); } } persistChanges(); } /** * API method to assign a SID of type EITHER to role. * * This method should no longer be used. * <p> * Example: * {@code curl -X POST localhost:8080/role-strategy/strategy/assignRole --data "type=globalRoles&amp;roleName=ADM * &amp;sid=username"} * * @param type (globalRoles, projectRoles, slaveRoles) * @param roleName name of role (single, no list) * @param sid user ID (single, no list) * @throws IOException in case saving changes fails * @since 2.5.0 * @deprecated Use {@link #doAssignUserRole} or {@link #doAssignGroupRole} to create unambiguous entries */ @Deprecated @RequirePOST @Restricted(NoExternalUse.class) public void doAssignRole(@QueryParameter(required = true) String type, @QueryParameter(required = true) String roleName, @QueryParameter(required = true) String sid) throws IOException { checkPermByRoleTypeForUpdates(type); final RoleType roleType = RoleType.fromString(type); Role role = getRoleMap(roleType).getRole(roleName); if (role != null) { assignRole(roleType, role, new PermissionEntry(AuthorizationType.EITHER, sid)); } persistChanges(); } /** * API method to assign a User to role. * * <p> * Example: * {@code curl -X POST localhost:8080/role-strategy/strategy/assignUserRole --data "type=globalRoles&amp;roleName=ADM * &amp;user=username"} * * @param type (globalRoles, projectRoles, slaveRoles) * @param roleName name of role (single, no list) * @param user user ID (single, no list) * @throws IOException in case saving changes fails * @since TODO */ @RequirePOST @Restricted(NoExternalUse.class) public void doAssignUserRole(@QueryParameter(required = true) String type, @QueryParameter(required = true) String roleName, @QueryParameter(required = true) String user) throws IOException { checkPermByRoleTypeForUpdates(type); final RoleType roleType = RoleType.fromString(type); Role role = getRoleMap(roleType).getRole(roleName); if (role != null) { assignRole(roleType, role, new PermissionEntry(AuthorizationType.USER, user)); } persistChanges(); } /** * API method to assign a Group to role. * * <p> * Example: * {@code curl -X POST localhost:8080/role-strategy/strategy/assignGroupRole --data "type=globalRoles&amp;roleName=ADM * &amp;group=groupname"} * * @param type (globalRoles, projectRoles, slaveRoles) * @param roleName name of role (single, no list) * @param group group ID (single, no list) * @throws IOException in case saving changes fails * @since TODO */ @RequirePOST @Restricted(NoExternalUse.class) public void doAssignGroupRole(@QueryParameter(required = true) String type, @QueryParameter(required = true) String roleName, @QueryParameter(required = true) String group) throws IOException { checkPermByRoleTypeForUpdates(type); final RoleType roleType = RoleType.fromString(type); Role role = getRoleMap(roleType).getRole(roleName); if (role != null) { assignRole(roleType, role, new PermissionEntry(AuthorizationType.GROUP, group)); } persistChanges(); } /** * API method to delete a SID from all granted roles. * Only SIDS of type EITHER with the given name will be deleted. * * <p> * Example: * {@code curl -X POST localhost:8080/role-strategy/strategy/deleteSid --data "type=globalRoles&amp;sid=username"} * * @param type (globalRoles, projectRoles, slaveRoles) * @param sid user/group ID to remove * @throws IOException in case saving changes fails * @since 2.4.1 */ @RequirePOST @Restricted(NoExternalUse.class) public void doDeleteSid(@QueryParameter(required = true) String type, @QueryParameter(required = true) String sid) throws IOException { checkPermByRoleTypeForUpdates(type); getRoleMap(RoleType.fromString(type)).deleteSids(new PermissionEntry(AuthorizationType.EITHER, sid)); persistChanges(); } /** * API method to delete a user from all granted roles. * * <p> * Example: * {@code curl -X POST localhost:8080/role-strategy/strategy/deleteUser --data "type=globalRoles&amp;user=username"} * * @param type (globalRoles, projectRoles, slaveRoles) * @param user user ID to remove * @throws IOException in case saving changes fails * @since 2.4.1 */ @RequirePOST @Restricted(NoExternalUse.class) public void doDeleteUser(@QueryParameter(required = true) String type, @QueryParameter(required = true) String user) throws IOException { checkPermByRoleTypeForUpdates(type); getRoleMap(RoleType.fromString(type)).deleteSids(new PermissionEntry(AuthorizationType.USER, user)); persistChanges(); } /** * API method to delete a group from all granted roles. * * <p> * Example: * {@code curl -X POST localhost:8080/role-strategy/strategy/deleteGroup --data "type=globalRoles&amp;group=groupname"} * * @param type (globalRoles, projectRoles, slaveRoles) * @param group group ID to remove * @throws IOException in case saving changes fails * @since 2.4.1 */ @RequirePOST @Restricted(NoExternalUse.class) public void doDeleteGroup(@QueryParameter(required = true) String type, @QueryParameter(required = true) String group) throws IOException { checkPermByRoleTypeForUpdates(type); getRoleMap(RoleType.fromString(type)).deleteSids(new PermissionEntry(AuthorizationType.GROUP, group)); persistChanges(); } /** * API method to remove a SID from a role. * Only entries of type EITHER will be removed. * * use {@link #doUnassignUserRole(String, String, String)} or {@link #doUnassignGroupRole(String, String, String)} to unassign a * User or a Group. * * <p> * Example: * {@code curl -X POST localhost:8080/role-strategy/strategy/unassignRole --data "type=globalRoles&amp;roleName=AMD&amp;sid=username"} * * @param type (globalRoles, projectRoles, slaveRoles) * @param roleName unassign role with sid * @param sid user ID to remove * @throws IOException in case saving changes fails * * @since 2.6.0 */ @RequirePOST @Restricted(NoExternalUse.class) public void doUnassignRole(@QueryParameter(required = true) String type, @QueryParameter(required = true) String roleName, @QueryParameter(required = true) String sid) throws IOException { checkPermByRoleTypeForUpdates(type); RoleMap roleMap = getRoleMap(RoleType.fromString(type)); Role role = roleMap.getRole(roleName); if (role != null) { roleMap.deleteRoleSid(new PermissionEntry(AuthorizationType.EITHER, sid), role.getName()); } persistChanges(); } /** * API method to remove a user from a role. * * <p> * Example: * {@code curl -X POST localhost:8080/role-strategy/strategy/unassignUserRole --data * "type=globalRoles&amp;roleName=AMD&amp;user=username"} * * @param type (globalRoles, projectRoles, slaveRoles) * @param roleName unassign role with sid * @param user user ID to remove * @throws IOException in case saving changes fails * @since TODO */ @RequirePOST @Restricted(NoExternalUse.class) public void doUnassignUserRole(@QueryParameter(required = true) String type, @QueryParameter(required = true) String roleName, @QueryParameter(required = true) String user) throws IOException { checkPermByRoleTypeForUpdates(type); RoleMap roleMap = getRoleMap(RoleType.fromString(type)); Role role = roleMap.getRole(roleName); if (role != null) { roleMap.deleteRoleSid(new PermissionEntry(AuthorizationType.USER, user), role.getName()); } persistChanges(); } /** * API method to remove a user from a role. * * <p> * Example: * {@code curl -X POST localhost:8080/role-strategy/strategy/unassignGroupRole --data * "type=globalRoles&amp;roleName=AMD&amp;user=username"} * * @param type (globalRoles, projectRoles, slaveRoles) * @param roleName unassign role with sid * @param group user ID to remove * @throws IOException in case saving changes fails * @since TODO */ @RequirePOST @Restricted(NoExternalUse.class) public void doUnassignGroupRole(@QueryParameter(required = true) String type, @QueryParameter(required = true) String roleName, @QueryParameter(required = true) String group) throws IOException { checkPermByRoleTypeForUpdates(type); RoleMap roleMap = getRoleMap(RoleType.fromString(type)); Role role = roleMap.getRole(roleName); if (role != null) { roleMap.deleteRoleSid(new PermissionEntry(AuthorizationType.GROUP, group), role.getName()); } persistChanges(); } /** * API method to get the granted permissions of a template and if the template is used. * * <p> * Example: {@code curl -XGET 'http://localhost:8080/jenkins/role-strategy/strategy/getTemplate?name=developer'} * * <p> * Returns json with granted permissions and assigned sids.<br> * Example: * * <pre>{@code * { * "permissionIds": { * "hudson.model.Item.Read":true, * "hudson.model.Item.Build":true,
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
true
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/com/michelin/cio/hudson/plugins/rolestrategy/RoleMap.java
src/main/java/com/michelin/cio/hudson/plugins/rolestrategy/RoleMap.java
/* * The MIT License * * Copyright (c) 2010, Manufacture Française des Pneumatiques Michelin, Thomas Maurel * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.michelin.cio.hudson.plugins.rolestrategy; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import com.synopsys.arc.jenkins.plugins.rolestrategy.IMacroExtension; import com.synopsys.arc.jenkins.plugins.rolestrategy.Macro; import com.synopsys.arc.jenkins.plugins.rolestrategy.RoleMacroExtension; import com.synopsys.arc.jenkins.plugins.rolestrategy.RoleType; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Util; import hudson.model.Item; import hudson.model.ItemGroup; import hudson.model.Node; import hudson.model.User; import hudson.security.AccessControlled; import hudson.security.AuthorizationStrategy; import hudson.security.Permission; import hudson.security.SecurityRealm; import hudson.security.SidACL; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import jenkins.model.IdStrategy; import jenkins.model.Jenkins; import jenkins.model.ProjectNamingStrategy; import org.acegisecurity.acls.sid.PrincipalSid; import org.acegisecurity.acls.sid.Sid; import org.jenkinsci.plugins.rolestrategy.RoleBasedProjectNamingStrategy; import org.jenkinsci.plugins.rolestrategy.Settings; import org.jenkinsci.plugins.rolestrategy.permissions.PermissionHelper; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.kohsuke.stapler.DataBoundConstructor; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; /** * Class holding a map for each kind of {@link AccessControlled} object, associating each {@link Role} with the * concerned {@link User}s/groups. * * @author Thomas Maurel */ public class RoleMap { @SuppressFBWarnings("MS_SHOULD_BE_FINAL") // Used to allow old behaviour @Restricted(NoExternalUse.class) public static boolean FORCE_CASE_SENSITIVE = Boolean.getBoolean(RoleMap.class.getName() + ".FORCE_CASE_SENSITIVE"); /** * Map associating each {@link Role} with the concerned {@link User}s/groups. */ private final SortedMap<Role, Set<PermissionEntry>> grantedRoles; private static final Logger LOGGER = Logger.getLogger(RoleMap.class.getName()); private static final Cache<Permission, Set<Permission>> implyingPermissionCache = Caffeine.newBuilder().maximumSize(100) .expireAfterWrite(20, TimeUnit.SECONDS).build(); static { Permission.getAll().forEach(RoleMap::cacheImplyingPermissions); } private final Cache<String, UserDetails> cache = Caffeine.newBuilder().maximumSize(Settings.USER_DETAILS_CACHE_MAX_SIZE) .expireAfterWrite(Settings.USER_DETAILS_CACHE_EXPIRATION_TIME_SEC, TimeUnit.SECONDS).build(); /** * {@link RoleMap}s are created again and again using {@link RoleMap#newMatchingRoleMap(String)} for different * permissions for the same {@code itemNamePrefix}, so cache them and avoid wasting time matching regular expressions. */ private final Cache<String, RoleMap> matchingRoleMapCache = Caffeine.newBuilder().maximumSize(2048).expireAfterWrite(1, TimeUnit.HOURS) .build(); RoleMap() { this.grantedRoles = new ConcurrentSkipListMap<>(); } /** * Constructor. * * @param grantedRoles Roles to be granted. */ @DataBoundConstructor public RoleMap(@NonNull SortedMap<Role, Set<PermissionEntry>> grantedRoles) { this(); for (Map.Entry<Role, Set<PermissionEntry>> entry : grantedRoles.entrySet()) { this.grantedRoles.put(entry.getKey(), new HashSet<>(entry.getValue())); } } /** * Check if the given sid has the provided {@link Permission}. * * @return True if the sid's granted permission */ @Restricted(NoExternalUse.class) public boolean hasPermission(PermissionEntry sid, Permission permission, RoleType roleType, AccessControlled controlledItem) { final Set<Permission> permissions = getImplyingPermissions(permission); final boolean[] hasPermission = { false }; final SecurityRealm securityRealm = Jenkins.get().getSecurityRealm(); final boolean principal = sid.getType() == AuthorizationType.USER; final IdStrategy strategy = principal ? securityRealm.getUserIdStrategy() : securityRealm.getGroupIdStrategy(); // Walk through the roles, and only add the roles having the given permission, // or a permission implying the given permission new RoleWalker() { /** * Checks whether the given sid is granted permission. * First checks if there is a dedicated match for user/group. * If not checks if there is an entry for either. * * @param current The current role * @param entry The permission entry to check * @return The PermissionEntry that matched or null if nothing matched. */ @CheckForNull private PermissionEntry hasPermission(Role current, PermissionEntry entry) { Set<PermissionEntry> entries = grantedRoles.get(current); if (entries.contains(entry)) { return entry; } PermissionEntry eitherEntry = new PermissionEntry(AuthorizationType.EITHER, entry.getSid()); if (entries.contains(eitherEntry)) { return eitherEntry; } if (!FORCE_CASE_SENSITIVE) { for (PermissionEntry pe : entries) { if (pe.isApplicable(principal) && strategy.equals(pe.getSid(), entry.getSid())) { return pe; } } } return null; } @Override public void perform(Role current) { if (current.hasAnyPermission(permissions)) { PermissionEntry entry = hasPermission(current, sid); if (entry != null) { // Handle roles macro if (Macro.isMacro(current)) { Macro macro = RoleMacroExtension.getMacro(current.getName()); if (controlledItem != null && macro != null) { RoleMacroExtension macroExtension = RoleMacroExtension.getMacroExtension(macro.getName()); if (macroExtension.IsApplicable(roleType)) { if (Util.isOverridden(IMacroExtension.class, macroExtension.getClass(), "hasPermission", PermissionEntry.class, Permission.class, RoleType.class, AccessControlled.class, Macro.class)) { if (macroExtension.hasPermission(entry, permission, roleType, controlledItem, macro)) { hasPermission[0] = true; abort(); } } else { if (macroExtension.hasPermission(entry.getSid(), permission, roleType, controlledItem, macro)) { hasPermission[0] = true; abort(); } } } } } else { hasPermission[0] = true; abort(); } } else if (Settings.TREAT_USER_AUTHORITIES_AS_ROLES && sid.getType() == AuthorizationType.USER) { try { UserDetails userDetails = cache.getIfPresent(sid.getSid()); if (userDetails == null) { userDetails = Jenkins.get().getSecurityRealm().loadUserByUsername2(sid.getSid()); cache.put(sid.getSid(), userDetails); } for (GrantedAuthority grantedAuthority : userDetails.getAuthorities()) { if (grantedAuthority.getAuthority().equals(current.getName())) { hasPermission[0] = true; abort(); return; } } } catch (RuntimeException ex) { // There maybe issues in the logic, which lead to IllegalStateException in Acegi // Security (JENKINS-35652) // So we want to ensure this method does not fail horribly in such case LOGGER.log(Level.WARNING, "Unhandled exception during user authorities processing", ex); } } } } }; return hasPermission[0]; } /** * Get the set of permissions which imply the permission {@code p}. * * @param p find permissions that imply this permission * @return set of permissions which imply {@code p} */ private static Set<Permission> getImplyingPermissions(Permission p) { return implyingPermissionCache.get(p, RoleMap::cacheImplyingPermissions); } /** * Finds the implying permissions and caches them for future use. * * @param permission the permission for which to cache implying permissions * @return a set of permissions that imply this permission (including itself) */ private static Set<Permission> cacheImplyingPermissions(Permission permission) { Set<Permission> implyingPermissions; if (PermissionHelper.isDangerous(permission)) { /* * if this is a dangerous permission, fall back to Administer unless we're in compat mode */ implyingPermissions = getImplyingPermissions(Jenkins.ADMINISTER); } else { implyingPermissions = new HashSet<>(); // Get the implying permissions for (Permission p = permission; p != null; p = p.impliedBy) { if (!p.getEnabled()) { continue; } implyingPermissions.add(p); } } return implyingPermissions; } /** * Check if the {@link RoleMap} contains the given {@link Role}. * * @param role Role to be checked * @return {@code true} if the {@link RoleMap} contains the given role */ public boolean hasRole(@NonNull Role role) { return this.grantedRoles.containsKey(role); } /** * Get the ACL for the current {@link RoleMap}. * * @return ACL for the current {@link RoleMap} */ @SuppressWarnings("checkstyle:AbbreviationAsWordInName") public SidACL getACL(RoleType roleType, AccessControlled controlledItem) { return new AclImpl(roleType, controlledItem); } /** * Add the given role to this {@link RoleMap}. * * @param role The {@link Role} to add */ public void addRole(Role role) { if (this.getRole(role.getName()) == null) { this.grantedRoles.put(role, new CopyOnWriteArraySet<>()); matchingRoleMapCache.invalidateAll(); } } /** * Add the given role to this {@link RoleMap} and assign the sids to it. * If a role * * @param role The {@link Role} to add * @param sids The sids associated with the {@link Role} */ public void addRole(Role role, Set<PermissionEntry> sids) { this.grantedRoles.put(role, new CopyOnWriteArraySet<>(sids)); matchingRoleMapCache.invalidateAll(); } /** * Assign the sid to the given {@link Role}. * * @param role The {@link Role} to assign the sid to * @param sid The sid to assign */ public void assignRole(Role role, PermissionEntry sid) { if (this.hasRole(role)) { this.grantedRoles.get(role).add(sid); matchingRoleMapCache.invalidateAll(); } } /** * Assign the sid to the given {@link Role}. * Assigns are a {@link AuthorizationType#EITHER} * * @param role The {@link Role} to assign the sid to * @param sid The sid to assign * * @deprecated use {@link #assignRole(Role, PermissionEntry)} */ @Deprecated public void assignRole(Role role, String sid) { if (this.hasRole(role)) { this.grantedRoles.get(role).add(new PermissionEntry(AuthorizationType.EITHER, sid)); matchingRoleMapCache.invalidateAll(); } } /** * unAssign the sid from the given {@link Role}. * * @param role The {@link Role} to unassign the sid to * @param sid The sid to unassign */ public void unAssignRole(Role role, PermissionEntry sid) { Set<PermissionEntry> sids = grantedRoles.get(role); if (sids != null) { sids.remove(sid); matchingRoleMapCache.invalidateAll(); } } /** * unAssign the sid from the given {@link Role}. * This will only unassign entries of type {@link AuthorizationType#EITHER}. * * @param role The {@link Role} to unassign the sid to * @param sid The sid to unassign * @since 2.6.0 * @deprecated use {@link #unAssignRole(Role, PermissionEntry)} */ @Deprecated public void unAssignRole(Role role, String sid) { Set<PermissionEntry> sids = grantedRoles.get(role); if (sids != null) { sids.remove(new PermissionEntry(AuthorizationType.EITHER, sid)); matchingRoleMapCache.invalidateAll(); } } /** * Clear all the sids associated to the given {@link Role}. * * @param role The {@link Role} for which you want to clear the sids */ public void clearSidsForRole(Role role) { if (this.hasRole(role)) { this.grantedRoles.get(role).clear(); matchingRoleMapCache.invalidateAll(); } } /** * Clear all the roles associated to the given sid. * * @param sid The sid for which you want to clear the {@link Role}s */ public void deleteSids(PermissionEntry sid) { for (Map.Entry<Role, Set<PermissionEntry>> entry : grantedRoles.entrySet()) { Set<PermissionEntry> sids = entry.getValue(); sids.remove(sid); } matchingRoleMapCache.invalidateAll(); } /** * Clear all the roles associated to the given sid. * This will only find sids of type {@link AuthorizationType#EITHER} * * @param sid The sid for which you want to clear the {@link Role}s * * @deprecated use {@link #deleteSids(PermissionEntry)} */ @Deprecated public void deleteSids(String sid) { for (Map.Entry<Role, Set<PermissionEntry>> entry : grantedRoles.entrySet()) { Set<PermissionEntry> sids = entry.getValue(); sids.remove(new PermissionEntry(AuthorizationType.EITHER, sid)); } matchingRoleMapCache.invalidateAll(); } /** * Clear specific role associated to the given sid. * * @param sid The sid for which you want to clear the {@link Role}s * @param rolename The role for which you want to clear the {@link Role}s * @since 2.6.0 */ public void deleteRoleSid(PermissionEntry sid, String rolename) { for (Map.Entry<Role, Set<PermissionEntry>> entry : grantedRoles.entrySet()) { Role role = entry.getKey(); if (role.getName().equals(rolename)) { unAssignRole(role, sid); break; } } } /** * Clear specific role associated to the given sid. * This will only find sids of type {@link AuthorizationType#EITHER} * * @param sid The sid for which you want to clear the {@link Role}s * @param rolename The role for which you want to clear the {@link Role}s * @since 2.6.0 * @deprecated use {@link #deleteRoleSid(PermissionEntry, String)} */ @Deprecated public void deleteRoleSid(String sid, String rolename) { PermissionEntry sidEntry = new PermissionEntry(AuthorizationType.EITHER, sid); for (Map.Entry<Role, Set<PermissionEntry>> entry : grantedRoles.entrySet()) { Role role = entry.getKey(); if (role.getName().equals(rolename)) { unAssignRole(role, sidEntry); break; } } } /** * Clear all the sids for each {@link Role} of the {@link RoleMap}. */ public void clearSids() { for (Map.Entry<Role, Set<PermissionEntry>> entry : this.grantedRoles.entrySet()) { Role role = entry.getKey(); this.clearSidsForRole(role); } } /** * Get the {@link Role} object named after the given param. * * @param name The name of the {@link Role} * @return The {@link Role} named after the given param. {@code null} if the role is missing. */ @CheckForNull public Role getRole(String name) { for (Role role : this.getRoles()) { if (role.getName().equals(name)) { return role; } } return null; } /** * Removes a {@link Role}. * * @param role The {@link Role} which shall be removed */ public void removeRole(Role role) { this.grantedRoles.remove(role); matchingRoleMapCache.invalidateAll(); } /** * Get an unmodifiable sorted map containing {@link Role}s and their assigned sids. * * @return An unmodifiable sorted map containing the {@link Role}s and their associated sids */ public SortedMap<Role, Set<PermissionEntry>> getGrantedRolesEntries() { return Collections.unmodifiableSortedMap(this.grantedRoles); } /** * Get an unmodifiable sorted map containing {@link Role}s and their assigned sids. * All types are returned to keep the api as compatible as possible. * * @return An unmodifiable sorted map containing the {@link Role}s and their associated sids * @deprecated use {@link #getGrantedRolesEntries()} */ @Deprecated public SortedMap<Role, Set<String>> getGrantedRoles() { SortedMap<Role, Set<String>> ret = new TreeMap<>(); for (Map.Entry<Role, Set<PermissionEntry>> entry : this.grantedRoles.entrySet()) { Set<String> allGrants = entry.getValue().stream().map(PermissionEntry::getSid).collect(Collectors.toSet()); ret.put(entry.getKey(), allGrants); } return ret; } /** * Get an unmodifiable set containing all the {@link Role}s of this {@link RoleMap}. * * @return An unmodifiable set containing the {@link Role}s */ public Set<Role> getRoles() { return Collections.unmodifiableSet(this.grantedRoles.keySet()); } /** * Get all the sids referenced in this {@link RoleMap}, minus the {@code Anonymous} sid. * All types are returned to keep the api as compatible as possible. * * @return A sorted set containing all the sids, minus the {@code Anonymous} sid * @deprecated use {@link #getSidEntries()} */ @Deprecated public SortedSet<String> getSids() { return getSids(false); } /** * Get all the sids referenced in this {@link RoleMap}. * All types are returned to keep the api as compatible as possible. * * @param includeAnonymous True if you want the {@code Anonymous} sid to be included in the set * @return A sorted set containing all the sids * @deprecated use {@link #getSidEntries(Boolean)} */ @Deprecated public SortedSet<String> getSids(Boolean includeAnonymous) { SortedSet<String> ret = new TreeSet<>(this.getSidEntries(includeAnonymous) .stream().map(PermissionEntry::getSid).collect(Collectors.toSet())); return ret; } /** * Get all the sids referenced in this {@link RoleMap}, minus the {@code Anonymous} sid. * * @return A sorted set containing all the sids, minus the {@code Anonymous} sid */ public SortedSet<PermissionEntry> getSidEntries() { return this.getSidEntries(false); } /** * Get all the sids referenced in this {@link RoleMap}. * * @param includeAnonymous True if you want the {@code Anonymous} sid to be included in the set * @return A sorted set containing all the sids */ public SortedSet<PermissionEntry> getSidEntries(Boolean includeAnonymous) { TreeSet<PermissionEntry> sids = new TreeSet<>(); for (Map.Entry<Role, Set<PermissionEntry>> entry : this.grantedRoles.entrySet()) { sids.addAll(entry.getValue()); } // Remove the anonymous sid if asked to if (!includeAnonymous) { sids.remove(new PermissionEntry(AuthorizationType.USER, "anonymous")); } return Collections.unmodifiableSortedSet(sids); } /** * Get all the permission entries assigned to the {@link Role} named after the {@code roleName} param. * * @param roleName The name of the role * @return A sorted set containing all the sids. {@code null} if the role is missing. */ @CheckForNull public Set<PermissionEntry> getSidEntriesForRole(String roleName) { Role role = this.getRole(roleName); if (role != null) { return Collections.unmodifiableSet(this.grantedRoles.get(role)); } return null; } /** * Get all the sids assigned to the {@link Role} named after the {@code roleName} param. * All types are returned to keep the api as compatible as possible. * * @param roleName The name of the role * @return A sorted set containing all the sids. {@code null} if the role is missing. * @deprecated use {@link #getSidEntriesForRole(String)} */ @CheckForNull @Deprecated public Set<String> getSidsForRole(String roleName) { Role role = this.getRole(roleName); if (role != null) { Set<PermissionEntry> ret = this.grantedRoles.get(role); return ret.stream().map(PermissionEntry::getSid).collect(Collectors.toSet()); } return null; } /** * Get all roles associated with the given User. * * @param user The User for which to get the roles * @return a set of roles * @throws UsernameNotFoundException when user is not found */ @NonNull public Set<String> getRolesForUser(User user) throws UsernameNotFoundException { return getRolesForAuth(user.impersonate2()); } /** * Get all roles associated with the given Authentication. * * @param auth The Authentication for which to get the roles * @return a set of roles */ @NonNull @Restricted(NoExternalUse.class) public Set<String> getRolesForAuth(Authentication auth) { PermissionEntry userEntry = new PermissionEntry(AuthorizationType.USER, auth.getPrincipal().toString()); Set<String> roleSet = new HashSet<>(getRolesForSidEntry(userEntry)); for (GrantedAuthority group : auth.getAuthorities()) { PermissionEntry groupEntry = new PermissionEntry(AuthorizationType.GROUP, group.getAuthority()); roleSet.addAll(getRolesForSidEntry(groupEntry)); } return roleSet; } private Set<String> getRolesForSidEntry(PermissionEntry entry) { Set<String> roleSet = new HashSet<>(); new RoleWalker() { @Override public void perform(Role current) { if (grantedRoles.get(current).contains(entry)) { roleSet.add(current.getName()); } } }; return roleSet; } /** * Create a sub-map of this {@link RoleMap} containing {@link Role}s that are applicable on the given * {@code itemNamePrefix}. * * @param itemNamePrefix the name of the {@link hudson.model.AbstractItem} or {@link hudson.model.Computer} * @return A {@link RoleMap} containing roles that are applicable on the itemNamePrefix */ public RoleMap newMatchingRoleMap(String itemNamePrefix) { return matchingRoleMapCache.get(itemNamePrefix, this::createMatchingRoleMap); } private RoleMap createMatchingRoleMap(String itemNamePrefix) { SortedMap<Role, Set<PermissionEntry>> roleMap = new TreeMap<>(); new RoleWalker() { @Override public void perform(Role current) { Matcher m = current.getPattern().matcher(itemNamePrefix); if (m.matches()) { roleMap.put(current, grantedRoles.get(current)); } } }; return new RoleMap(roleMap); } /** * Get all job names matching the given pattern, viewable to the requesting user. * * @param pattern Pattern to match against * @param maxJobs Max matching jobs to look for * @return List of matching job names * @deprecated No replacement available. It was never intended for public usage. */ @Deprecated public static List<String> getMatchingJobNames(Pattern pattern, int maxJobs) { List<String> matchingJobNames = new ArrayList<>(); for (Item i : Jenkins.get().allItems(Item.class, i -> pattern.matcher(i.getFullName()).matches())) { if (matchingJobNames.size() >= maxJobs) { break; } matchingJobNames.add(i.getFullName()); } return matchingJobNames; } /** * Get all job names matching the given pattern, viewable to the requesting user. * * @param matchedItems List that will take the matched item names * @param pattern Pattern to match against * @param maxJobs Max matching jobs to look for * @return Number of matched jobs */ @Restricted(NoExternalUse.class) static int getMatchingItemNames(@NonNull List<String> matchedItems, Pattern pattern, int maxJobs) { int count = 0; for (Item i : Jenkins.get().allItems(Item.class, i -> pattern.matcher(i.getFullName()).matches())) { if (matchedItems.size() < maxJobs) { matchedItems.add(i.getFullDisplayName()); } count++; } return count; } /** * Get all agent names matching the given pattern, viewable to the requesting user. * * @param pattern Pattern to match against * @param maxAgents Max matching agents to look for * @return List of matching agent names * @deprecated No replacement available. It was never intended for public usage. */ @Deprecated public static List<String> getMatchingAgentNames(Pattern pattern, int maxAgents) { List<String> matchingAgentNames = new ArrayList<>(); for (Node node : Jenkins.get().getNodes()) { if (pattern.matcher(node.getNodeName()).matches()) { matchingAgentNames.add(node.getNodeName()); if (matchingAgentNames.size() >= maxAgents) { break; } } } return matchingAgentNames; } /** * Get the number of agent names matching the given pattern, viewable to the requesting user. * * @param matchingAgentNames List that will take the matched agent names * @param pattern Pattern to match against * @param maxAgents Max matching agents to look for * @return Number of matching agent names */ @Restricted(NoExternalUse.class) static int getMatchingAgentNames(@NonNull List<String> matchingAgentNames, Pattern pattern, int maxAgents) { int count = 0; for (Node node : Jenkins.get().getNodes()) { if (pattern.matcher(node.getNodeName()).matches()) { if (matchingAgentNames.size() < maxAgents) { matchingAgentNames.add(node.getNodeName()); } count++; } } return count; } /** * The Acl class that will delegate the permission check to the {@link RoleMap} object. */ private final class AclImpl extends SidACL { AccessControlled item; RoleType roleType; public AclImpl(RoleType roleType, AccessControlled item) { this.item = item; this.roleType = roleType; } /** * Checks if the sid has the given permission. * <p> * Actually only delegate the check to the {@link RoleMap} instance. * </p> * * @param sid The sid to check * @param permission The permission to check * @return True if the sid has the given permission */ @Override @CheckForNull protected Boolean hasPermission(Sid sid, Permission permission) { boolean principal = sid instanceof PrincipalSid ? true : false; PermissionEntry entry = new PermissionEntry(principal ? AuthorizationType.USER : AuthorizationType.GROUP, toString(sid)); if (RoleMap.this.hasPermission(entry, permission, roleType, item)) { if (item instanceof Item) { final ItemGroup parent = ((Item) item).getParent(); if (parent instanceof Item && (Item.DISCOVER.equals(permission) || Item.READ.equals(permission)) && shouldCheckParentPermissions()) { // For READ and DISCOVER permission checks, do the same permission check on the // parent Permission requiredPermissionOnParent = permission == Item.DISCOVER ? Item.DISCOVER : Item.READ; if (!((Item) parent).hasPermission(requiredPermissionOnParent)) { return null; } } } return true; } // For Item.CREATE // We need to find out if the given user has anywhere permission to create something // not just in the current roletype, this can only reliably work when the project naming // strategy is set to the role based naming strategy if (permission == Item.CREATE && item == null) { AuthorizationStrategy auth = Jenkins.get().getAuthorizationStrategy(); ProjectNamingStrategy pns = Jenkins.get().getProjectNamingStrategy(); if (auth instanceof RoleBasedAuthorizationStrategy && pns instanceof RoleBasedProjectNamingStrategy) { RoleBasedAuthorizationStrategy rbas = (RoleBasedAuthorizationStrategy) auth; RoleMap roleMapProject = rbas.getRoleMap(RoleType.Project); if (roleMapProject.hasPermission(entry, permission, RoleType.Project, item)) { return true; } } } return null; } } private static boolean shouldCheckParentPermissions() { // TODO Switch to SystemProperties in 2.236+ String propertyName = RoleMap.class.getName() + ".checkParentPermissions"; String value = System.getProperty(propertyName); if (value == null) { return true; } return Boolean.parseBoolean(value); } /** * A class to walk through all the {@link RoleMap}'s roles and perform an action on each one. */ private abstract class RoleWalker { boolean shouldAbort = false; RoleWalker() { walk(); } /** * Aborts the iterations. The method can be used from RoleWalker callbacks to preemptively abort the execution loops on * some conditions. * * @since 2.10 */ public void abort() { this.shouldAbort = true; } /** * Walk through the roles. */ public void walk() { Set<Role> roles = RoleMap.this.getRoles(); for (Role current : roles) { perform(current); if (shouldAbort) { break; } } } /** * The method to implement which will be called on each {@link Role}. */ public abstract void perform(Role current); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/com/michelin/cio/hudson/plugins/rolestrategy/PermissionEntry.java
src/main/java/com/michelin/cio/hudson/plugins/rolestrategy/PermissionEntry.java
/* * The MIT License * * Copyright (c) 2021 CloudBees, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.michelin.cio.hudson.plugins.rolestrategy; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import java.util.Objects; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.kohsuke.stapler.DataBoundConstructor; /** * Combines sid with {@link AuthorizationType type}. */ public class PermissionEntry implements Comparable<PermissionEntry> { private final AuthorizationType type; private final String sid; @DataBoundConstructor public PermissionEntry(@NonNull AuthorizationType type, @NonNull String sid) { this.type = type; this.sid = sid; } public AuthorizationType getType() { return type; } public String getSid() { return sid; } /** * Utility method checking whether this entry applies based on whether we're looking for a principal. */ protected boolean isApplicable(boolean principal) { if (getType() == AuthorizationType.EITHER) { return true; } return getType() == (principal ? AuthorizationType.USER : AuthorizationType.GROUP); } /** * Creates a {@code PermissionEntry} from a string. * * @param permissionEntryString String from which to create the entry * @return the PermissinoEntry */ @Restricted(NoExternalUse.class) @CheckForNull public static PermissionEntry fromString(@NonNull String permissionEntryString) { Objects.requireNonNull(permissionEntryString); int idx = permissionEntryString.indexOf(':'); if (idx < 0) { return null; } String typeString = permissionEntryString.substring(0, idx); AuthorizationType type; try { type = AuthorizationType.valueOf(typeString); } catch (RuntimeException ex) { return null; } String sid = permissionEntryString.substring(idx + 1); if (sid.isEmpty()) { return null; } return new PermissionEntry(type, sid); } public static PermissionEntry user(String sid) { return new PermissionEntry(AuthorizationType.USER, sid); } public static PermissionEntry group(String sid) { return new PermissionEntry(AuthorizationType.GROUP, sid); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PermissionEntry that = (PermissionEntry) o; return type == that.type && sid.equals(that.sid); } @Override public int hashCode() { return Objects.hash(type, sid); } @Override public String toString() { return "PermissionEntry{" + "type=" + type + ", sid='" + sid + "'" + '}'; } @Override public int compareTo(PermissionEntry o) { int typeCompare = this.type.compareTo(o.type); if (typeCompare == 0) { return this.sid.compareTo(o.sid); } return typeCompare; } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/com/michelin/cio/hudson/plugins/rolestrategy/Role.java
src/main/java/com/michelin/cio/hudson/plugins/rolestrategy/Role.java
/* * The MIT License * * Copyright (c) 2010, Manufacture Française des Pneumatiques Michelin, Thomas Maurel * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.michelin.cio.hudson.plugins.rolestrategy; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.Util; import hudson.security.AccessControlled; import hudson.security.Permission; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import org.apache.commons.collections.CollectionUtils; import org.jenkinsci.plugins.rolestrategy.permissions.PermissionHelper; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.kohsuke.stapler.DataBoundConstructor; /** * Class representing a role, which holds a set of {@link Permission}s. * * @author Thomas Maurel */ public final class Role implements Comparable { public static final String GLOBAL_ROLE_PATTERN = ".*"; private static final Logger LOGGER = Logger.getLogger(Role.class.getName()); /** * Name of the role. */ private final String name; /** * Pattern to match the {@link AccessControlled} object name. */ private final Pattern pattern; /** * Role description (optional). */ @CheckForNull private final String description; /** * Flag to indicate that the role is template based. */ @CheckForNull private String templateName; /** * {@link Permission}s hold by the role. */ private Set<Permission> permissions; private transient Integer cachedHashCode = null; /** * Constructor for a global role with no pattern (which is then defaulted to {@code .*}). * * @param name The role name * @param permissions The {@link Permission}s associated to the role */ Role(String name, Set<Permission> permissions) { this(name, GLOBAL_ROLE_PATTERN, permissions); } /** * Constructor for roles using a string pattern. * * @param name The role name * @param pattern A string representing the pattern matching {@link AccessControlled} objects names * @param permissions The {@link Permission}s associated to the role */ Role(String name, String pattern, Set<Permission> permissions) { this(name, Pattern.compile(pattern), permissions, null); } // TODO: comment is used for erasure cleanup only @DataBoundConstructor public Role(@NonNull String name, @CheckForNull String pattern, @CheckForNull Set<String> permissionIds, @CheckForNull String description, String templateName) { this(name, Pattern.compile(pattern != null ? pattern : GLOBAL_ROLE_PATTERN), PermissionHelper.fromStrings(permissionIds, true), description, templateName); } public Role(@NonNull String name, @CheckForNull String pattern, @CheckForNull Set<String> permissionIds, @CheckForNull String description) { this(name, Pattern.compile(pattern != null ? pattern : GLOBAL_ROLE_PATTERN), PermissionHelper.fromStrings(permissionIds, true), description, ""); } /** * Create a Role. * * @param name The role name * @param pattern The pattern matching {@link AccessControlled} objects names * @param permissions The {@link Permission}s associated to the role. {@code null} permissions will be ignored. * @param description A description for the role */ public Role(String name, Pattern pattern, Set<Permission> permissions, @CheckForNull String description) { this(name, pattern, permissions, description, ""); } /** * Create a Role. * * @param name The role name * @param pattern The pattern matching {@link AccessControlled} objects names * @param permissions The {@link Permission}s associated to the role. {@code null} permissions will be ignored. * @param description A description for the role * @param templateName True to mark this role as generated */ public Role(String name, Pattern pattern, Set<Permission> permissions, @CheckForNull String description, String templateName) { this.name = name; this.pattern = pattern; this.description = description; this.templateName = templateName; this.permissions = new HashSet<>(); for (Permission perm : permissions) { if (perm == null) { LOGGER.log(Level.WARNING, "Found some null permission(s) in role " + this.name, new IllegalArgumentException()); } else { this.permissions.add(perm); } } cachedHashCode = _hashCode(); } public void setTemplateName(@CheckForNull String templateName) { this.templateName = templateName; } public String getTemplateName() { return templateName; } /** * Getter for the role name. * * @return The role name */ public String getName() { return name; } /** * Getter for the regexp pattern. * * @return The pattern associated to the role */ public Pattern getPattern() { return pattern; } /** * Getter for the {@link Permission}s set. * * @return {@link Permission}s set */ public Set<Permission> getPermissions() { return Collections.unmodifiableSet(permissions); } /** * Update the permissions of the role. * * Internal use only. */ private synchronized void setPermissions(Set<Permission> permissions) { this.permissions = new HashSet<>(permissions); cachedHashCode = _hashCode(); } /** * Updates the permissions from the template matching the name. * * @param permissionTemplates List of templates to look for * @deprecated Use {@link #refreshPermissionsFromTemplate(PermissionTemplate)} */ @Deprecated public void refreshPermissionsFromTemplate(Collection<PermissionTemplate> permissionTemplates) { if (Util.fixEmptyAndTrim(templateName) != null) { boolean found = false; for (PermissionTemplate pt : permissionTemplates) { if (pt.getName().equals(templateName)) { setPermissions(pt.getPermissions()); found = true; break; } } if (! found) { this.templateName = null; } } } /** * Updates the permissions from the given template. * * The name of the given template must match the configured template name in the role. * * @param permissionTemplate PermissionTemplate */ @Restricted(NoExternalUse.class) public void refreshPermissionsFromTemplate(@CheckForNull PermissionTemplate permissionTemplate) { if (permissionTemplate != null && templateName != null && templateName.equals(permissionTemplate.getName())) { setPermissions(permissionTemplate.getPermissions()); } } /** * Gets the role description. * * @return Role description. {@code null} if not set */ @CheckForNull public String getDescription() { return description; } /** * Checks if the role holds the given {@link Permission}. * * @param permission The permission you want to check * @return True if the role holds this permission */ public Boolean hasPermission(Permission permission) { return permissions.contains(permission); } /** * Checks if the role holds any of the given {@link Permission}. * * @param permissions A {@link Permission}s set * @return True if the role holds any of the given {@link Permission}s */ public Boolean hasAnyPermission(Set<Permission> permissions) { return CollectionUtils.containsAny(this.permissions, permissions); } /** * Compare role names. Used to sort the sets. We presume that any role name is being used once and only once. * * @param o The object you want to compare this instance to * @return Comparison of role names */ @Override public int compareTo(@NonNull Object o) { Objects.requireNonNull(o); if (o instanceof Role) { return name.compareTo(((Role) o).name); } return -1; } @Override public int hashCode() { if (cachedHashCode == null) { cachedHashCode = _hashCode(); } return cachedHashCode; } @SuppressWarnings("checkstyle:MethodName") private int _hashCode() { int hash = 7; hash = 53 * hash + (this.name != null ? this.name.hashCode() : 0); hash = 53 * hash + (this.pattern != null ? this.pattern.hashCode() : 0); hash = 53 * hash + this.permissions.hashCode(); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Role other = (Role) obj; if (!Objects.equals(this.name, other.name)) { return false; } if (!Objects.equals(this.pattern, other.pattern)) { return false; } return Objects.equals(this.permissions, other.permissions); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/com/michelin/cio/hudson/plugins/rolestrategy/AuthorizationType.java
src/main/java/com/michelin/cio/hudson/plugins/rolestrategy/AuthorizationType.java
/* * The MIT License * * Copyright (c) 2021 CloudBees, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.michelin.cio.hudson.plugins.rolestrategy; /** * The type of object being granted authorization. */ public enum AuthorizationType { USER("User"), GROUP("Group"), /** * Either type is being granted permissions. * This is the legacy default. */ EITHER("User/Group"); private final String description; private AuthorizationType(String description) { this.description = description; } public String getDescription() { return description; } /** * The prefix used in the persistence of an permission entry. * * @return prefix */ public String toPrefix() { if (this == AuthorizationType.EITHER) { return ""; // Same as legacy format } return this + ":"; } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/com/michelin/cio/hudson/plugins/rolestrategy/RoleStrategyConfig.java
src/main/java/com/michelin/cio/hudson/plugins/rolestrategy/RoleStrategyConfig.java
/* * The MIT License * * Copyright (c) 2010-2011, Manufacture Française des Pneumatiques Michelin, * Thomas Maurel, Romain Seguy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.michelin.cio.hudson.plugins.rolestrategy; import com.synopsys.arc.jenkins.plugins.rolestrategy.RoleMacroExtension; import com.synopsys.arc.jenkins.plugins.rolestrategy.RoleType; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.Extension; import hudson.ExtensionList; import hudson.model.ManagementLink; import hudson.security.AuthorizationStrategy; import hudson.security.Permission; import hudson.util.FormApply; import jakarta.servlet.ServletException; import java.io.IOException; import jenkins.model.Jenkins; import jenkins.util.SystemProperties; import net.sf.json.JSONObject; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.kohsuke.stapler.StaplerRequest2; import org.kohsuke.stapler.StaplerResponse2; import org.kohsuke.stapler.interceptor.RequirePOST; /** * Add the role management link to the Manage Hudson page. * * @author Thomas Maurel */ @Extension public class RoleStrategyConfig extends ManagementLink { /** * Get the singleton instance of RoleStrategyConfig. * * @return The RoleStrategyConfig instance */ @NonNull public static RoleStrategyConfig get() { return ExtensionList.lookupSingleton(RoleStrategyConfig.class); } public static int getMaxRows() { return SystemProperties.getInteger(RoleStrategyConfig.class.getName() + ".MAX_ROWS", 30); } /** * Provides the icon for the Manage Hudson page link. * * @return Path to the icon, or {@code null} if not enabled */ @Override public String getIconFileName() { // Only show this link if the role-based authorization strategy has been enabled if (Jenkins.get().getAuthorizationStrategy() instanceof RoleBasedAuthorizationStrategy) { return "symbol-lock-closed-outline plugin-ionicons-api"; } return null; } @NonNull @Override public Permission getRequiredPermission() { return Jenkins.SYSTEM_READ; } /** * URL name for the strategy management. * * @return Path to the strategy admin panel */ @Override public String getUrlName() { return "role-strategy"; } @NonNull @Override public String getCategoryName() { return "SECURITY"; } /** * Text displayed in the Manage Hudson panel. * * @return Link text in the Admin panel */ @Override public String getDisplayName() { return Messages.RoleBasedAuthorizationStrategy_ManageAndAssign(); } /** * Text displayed for the roles assignment panel. * * @return Title of the Role assignment panel */ public String getAssignRolesName() { return Messages.RoleBasedAuthorizationStrategy_Assign(); } /** * Text displayed for the roles management panel. * * @return Title of the Role management panel */ public String getManageRolesName() { return Messages.RoleBasedAuthorizationStrategy_Manage(); } /** * The description of the link. * * @return The description of the link */ @Override public String getDescription() { return Messages.RoleBasedAuthorizationStrategy_Description(); } /** * Retrieve the {@link RoleBasedAuthorizationStrategy} object from the Hudson instance. * <p> * Used by the views to build matrix. * </p> * * @return The {@link RoleBasedAuthorizationStrategy} object. {@code null} if the strategy is not used. */ @CheckForNull public AuthorizationStrategy getStrategy() { AuthorizationStrategy strategy = Jenkins.get().getAuthorizationStrategy(); if (strategy instanceof RoleBasedAuthorizationStrategy) { return strategy; } else { return null; } } /** * Called on roles management form submission. */ @RequirePOST @Restricted(NoExternalUse.class) public void doRolesSubmit(StaplerRequest2 req, StaplerResponse2 rsp) throws IOException, ServletException { Jenkins.get().checkAnyPermission(RoleBasedAuthorizationStrategy.ADMINISTER_AND_SOME_ROLES_ADMIN); // Let the strategy descriptor handle the form RoleBasedAuthorizationStrategy.DESCRIPTOR.doRolesSubmit(req, rsp); // Redirect to the plugin index page FormApply.success(".").generateResponse(req, rsp, this); } /** * Called on roles generator form submission. */ @RequirePOST @Restricted(NoExternalUse.class) public void doTemplatesSubmit(StaplerRequest2 req, StaplerResponse2 rsp) throws IOException, ServletException { Jenkins.get().checkPermission(RoleBasedAuthorizationStrategy.ITEM_ROLES_ADMIN); // Let the strategy descriptor handle the form RoleBasedAuthorizationStrategy.DESCRIPTOR.doTemplatesSubmit(req, rsp); // Redirect to the plugin index page FormApply.success(".").generateResponse(req, rsp, this); } // no configuration on this page for submission // public void doMacrosSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, UnsupportedEncodingException, // ServletException, FormException { // Hudson.getInstance().checkPermission(Jenkins.ADMINISTER); // // // TODO: Macros Enable/Disable // // // Redirect to the plugin index page // FormApply.success(".").generateResponse(req, rsp, this); // } /** * Called on role's assignment form submission. */ @RequirePOST @Restricted(NoExternalUse.class) public void doAssignSubmit(StaplerRequest2 req, StaplerResponse2 rsp) throws IOException, ServletException { Jenkins.get().checkAnyPermission(RoleBasedAuthorizationStrategy.ADMINISTER_AND_SOME_ROLES_ADMIN); // Let the strategy descriptor handle the form req.setCharacterEncoding("UTF-8"); JSONObject json = req.getSubmittedForm(); JSONObject rolesMapping; if (json.has("submit")) { String rm = json.getString("rolesMapping"); rolesMapping = JSONObject.fromObject(rm); } else { rolesMapping = json.getJSONObject("rolesMapping"); } if (rolesMapping.has("agentRoles")) { rolesMapping.put(RoleBasedAuthorizationStrategy.SLAVE, rolesMapping.getJSONArray("agentRoles")); } RoleBasedAuthorizationStrategy.DESCRIPTOR.doAssignSubmit(rolesMapping); FormApply.success(".").generateResponse(req, rsp, this); } public ExtensionList<RoleMacroExtension> getRoleMacroExtensions() { return RoleMacroExtension.all(); } public final RoleType getGlobalRoleType() { return RoleType.Global; } public final RoleType getProjectRoleType() { return RoleType.Project; } public final RoleType getSlaveRoleType() { return RoleType.Slave; } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/com/michelin/cio/hudson/plugins/rolestrategy/PermissionTemplate.java
src/main/java/com/michelin/cio/hudson/plugins/rolestrategy/PermissionTemplate.java
package com.michelin.cio.hudson.plugins.rolestrategy; import com.synopsys.arc.jenkins.plugins.rolestrategy.RoleType; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.security.AuthorizationStrategy; import hudson.security.Permission; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import jenkins.model.Jenkins; import org.jenkinsci.plugins.rolestrategy.permissions.PermissionHelper; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.kohsuke.stapler.DataBoundConstructor; /** * Holds a set of permissions for the role generator. */ @Restricted(NoExternalUse.class) public class PermissionTemplate implements Comparable<PermissionTemplate> { private static final Logger LOGGER = Logger.getLogger(PermissionTemplate.class.getName()); private final String name; private final Set<Permission> permissions = new HashSet<>(); /** * Create a new PermissionTemplate. * * @param name the name of the template * @param permissions the set of permissions of this template */ @DataBoundConstructor public PermissionTemplate(String name, Set<String> permissions) { this(PermissionHelper.fromStrings(permissions, true), name); } /** * Create a new PermissionTemplate. * * @param name the name of the template * @param permissions the set of permissions of this template */ public PermissionTemplate(Set<Permission> permissions, String name) { this.name = name; for (Permission perm : permissions) { if (perm == null) { LOGGER.log(Level.WARNING, "Found some null permission(s) in role " + this.name, new IllegalArgumentException()); } else { this.permissions.add(perm); } } } /** * Checks whether the template is used by one or more roles. * * @return true when template is used. */ public boolean isUsed() { AuthorizationStrategy auth = Jenkins.get().getAuthorizationStrategy(); if (auth instanceof RoleBasedAuthorizationStrategy) { RoleBasedAuthorizationStrategy rbas = (RoleBasedAuthorizationStrategy) auth; Map<Role, Set<PermissionEntry>> roleMap = rbas.getGrantedRolesEntries(RoleType.Project); for (Role role : roleMap.keySet()) { if (Objects.equals(name, role.getTemplateName())) { return true; } } } return false; } public String getName() { return name; } public Set<Permission> getPermissions() { return Collections.unmodifiableSet(permissions); } /** * Checks if the role holds the given {@link Permission}. * * @param permission The permission you want to check * @return True if the role holds this permission */ public Boolean hasPermission(Permission permission) { return permissions.contains(permission); } @Override public int hashCode() { return name.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final PermissionTemplate other = (PermissionTemplate) obj; return Objects.equals(name, other.name); } @Override public int compareTo(@NonNull PermissionTemplate o) { return name.compareTo(o.name); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/org/jenkinsci/plugins/rolestrategy/Settings.java
src/main/java/org/jenkinsci/plugins/rolestrategy/Settings.java
/* * The MIT License * * Copyright (c) 2016 Oleg Nenashev. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.rolestrategy; import com.michelin.cio.hudson.plugins.rolestrategy.RoleMap; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; /** * Class for managing the strategy. This class will be converted to additional UI at some point. Now it stores System * properties only. * * @author Oleg Nenashev * @since 2.3.1 */ @Restricted(NoExternalUse.class) public class Settings { /** * Defines maximum size of the View cache. This cache is being used when * the macro {@code ContainedInView} is used. Changing of this option requires a Jenkins restart. * * @since 570 */ public static final int VIEW_CACHE_MAX_SIZE = Integer.getInteger(Settings.class.getName() + ".viewCacheMaxSize", 100); /** * Defines lifetime of entries in the View cache. This cache is being used when * the macro {@code ContainedInView} is used. Changing of this option requires a Jenkins restart. * * @since 570 */ public static final int VIEW_CACHE_EXPIRATION_TIME_SEC = Integer.getInteger( Settings.class.getName() + ".viewCacheExpircationTimeSec", 30); /** * Defines maximum size of the User details cache. This cache is being used when * {@link #TREAT_USER_AUTHORITIES_AS_ROLES} is enabled. Changing of this option requires Jenkins restart. * * @since 2.3.1 */ public static final int USER_DETAILS_CACHE_MAX_SIZE = Integer.getInteger(Settings.class.getName() + ".userDetailsCacheMaxSize", 100); /** * Defines lifetime of entries in the User details cache. This cache is being used when * {@link #TREAT_USER_AUTHORITIES_AS_ROLES} is enabled. Changing of this option requires Jenkins restart. * * @since 2.3.1 */ public static final int USER_DETAILS_CACHE_EXPIRATION_TIME_SEC = Integer .getInteger(Settings.class.getName() + ".userDetailsCacheExpircationTimeSec", 60); /** * Enabling processing of User Authorities. Alters the behavior of * {@link RoleMap#hasPermission(com.michelin.cio.hudson.plugins.rolestrategy.PermissionEntry, hudson.security.Permission, * com.synopsys.arc.jenkins.plugins.rolestrategy.RoleType, hudson.security.AccessControlled)}. * Since 2.3.0 this value was {@code true}, but it has been switched due to the performance reasons. The behavior can be * reverted (even dynamically via System Groovy Script). * * @since 2.3.1 */ @SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "We want to be it modifyable on the flight") public static boolean TREAT_USER_AUTHORITIES_AS_ROLES = Boolean.getBoolean(Settings.class.getName() + ".treatUserAuthoritiesAsRoles"); private Settings() { } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/org/jenkinsci/plugins/rolestrategy/RoleBasedProjectNamingStrategy.java
src/main/java/org/jenkinsci/plugins/rolestrategy/RoleBasedProjectNamingStrategy.java
package org.jenkinsci.plugins.rolestrategy; import com.michelin.cio.hudson.plugins.rolestrategy.AuthorizationType; import com.michelin.cio.hudson.plugins.rolestrategy.Messages; import com.michelin.cio.hudson.plugins.rolestrategy.PermissionEntry; import com.michelin.cio.hudson.plugins.rolestrategy.Role; import com.michelin.cio.hudson.plugins.rolestrategy.RoleBasedAuthorizationStrategy; import com.michelin.cio.hudson.plugins.rolestrategy.RoleMap; import com.synopsys.arc.jenkins.plugins.rolestrategy.Macro; import com.synopsys.arc.jenkins.plugins.rolestrategy.RoleType; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.Extension; import hudson.model.Failure; import hudson.model.Item; import hudson.model.ItemGroup; import hudson.security.ACL; import hudson.security.AuthorizationStrategy; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.SortedMap; import java.util.regex.Pattern; import java.util.stream.Collectors; import jenkins.model.Jenkins; import jenkins.model.ProjectNamingStrategy; import org.acegisecurity.acls.sid.PrincipalSid; import org.apache.commons.lang3.StringUtils; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.StaplerRequest2; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; /** * A Naming Strategy so that users with only item specific create permissions can create only items matching the role * pattern. * * @author Kanstantsin Shautsou * @since 2.2.0 */ public class RoleBasedProjectNamingStrategy extends ProjectNamingStrategy implements Serializable { private static final long serialVersionUID = 1L; private final boolean forceExistingJobs; @DataBoundConstructor public RoleBasedProjectNamingStrategy(boolean forceExistingJobs) { this.forceExistingJobs = forceExistingJobs; } @Override public void checkName(String name) throws Failure { StaplerRequest2 request = Stapler.getCurrentRequest2(); // Workaround until JENKINS-68602 is implemented // This works only for requests via the UI. In case this method is called due to // job creation request via the CLI, we have no way to determine the // the parent so just check the name String parentName = ""; if (request != null) { ItemGroup<?> i = Stapler.getCurrentRequest2().findAncestorObject(ItemGroup.class); parentName = i.getFullName(); } checkName(parentName, name); } /** * Checks if the given name and parentName match a role pattern. * * @param parentName Name of the parent item in which the new item should be created. * @param name The name of the item that should be created. * @throws Failure When the name is not allowed or {@code Item.CREATE} permission is missing */ // TODO: add Override once this method is implemented in Core and consumed here. public void checkName(String parentName, String name) throws Failure { if (StringUtils.isBlank(name)) { return; } String fullName = name; if (StringUtils.isNotBlank(parentName)) { fullName = parentName + "/" + name; } AuthorizationStrategy auth = Jenkins.get().getAuthorizationStrategy(); if (auth instanceof RoleBasedAuthorizationStrategy) { Authentication a = Jenkins.getAuthentication2(); if (a == ACL.SYSTEM2) { return; } PermissionEntry principal = new PermissionEntry(AuthorizationType.USER, new PrincipalSid(a).getPrincipal()); RoleBasedAuthorizationStrategy rbas = (RoleBasedAuthorizationStrategy) auth; RoleMap global = rbas.getRoleMap(RoleType.Global); List<String> authorities = a.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()); // first check global role if (hasCreatePermission(global, principal, authorities, RoleType.Global)) { return; } // check if user has anywhere else create permissions RoleMap item = rbas.getRoleMap(RoleType.Project); if (!hasCreatePermission(item, principal, authorities, RoleType.Project)) { throw new Failure(Messages.RoleBasedProjectNamingStrategy_NoPermissions()); } // check project role with pattern SortedMap<Role, Set<PermissionEntry>> roles = rbas.getGrantedRolesEntries(RoleType.Project); ArrayList<String> badList = new ArrayList<>(roles.size()); for (SortedMap.Entry<Role, Set<PermissionEntry>> entry : roles.entrySet()) { Role key = entry.getKey(); if (!Macro.isMacro(key) && key.hasPermission(Item.CREATE)) { Set<PermissionEntry> sids = entry.getValue(); Pattern namePattern = key.getPattern(); if (StringUtils.isNotBlank(namePattern.toString())) { if (namePattern.matcher(fullName).matches()) { if (hasAnyPermission(principal, authorities, sids)) { return; } } else { badList.add(namePattern.toString()); } } } } String error; if (badList != null && !badList.isEmpty()) { error = Messages.RoleBasedProjectNamingStrategy_JobNameConventionNotApplyed(fullName, badList.toString()); } else { error = Messages.RoleBasedProjectNamingStrategy_NoPermissions(); } throw new Failure(error); } } private boolean hasAnyPermission(PermissionEntry principal, List<String> authorities, Set<PermissionEntry> sids) { PermissionEntry eitherUser = new PermissionEntry(AuthorizationType.EITHER, principal.getSid()); if (sids.contains(principal) || sids.contains(eitherUser)) { return true; } else { for (String authority : authorities) { if (sids.contains(new PermissionEntry(AuthorizationType.GROUP, authority)) || sids.contains(new PermissionEntry(AuthorizationType.EITHER, authority))) { return true; } } } return false; } private boolean hasCreatePermission(RoleMap roleMap, PermissionEntry principal, List<String> authorities, RoleType roleType) { if (roleMap.hasPermission(principal, Item.CREATE, roleType, null)) { return true; } for (String group : authorities) { PermissionEntry groupEntry = new PermissionEntry(AuthorizationType.GROUP, group); if (roleMap.hasPermission(groupEntry, Item.CREATE, roleType, null)) { return true; } } return false; } @Override public boolean isForceExistingJobs() { return forceExistingJobs; } /** * Descriptor. */ @Extension public static final class DescriptorImpl extends ProjectNamingStrategyDescriptor { @NonNull @Override public String getDisplayName() { return Messages.RoleBasedAuthorizationStrategy_DisplayName(); } } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/org/jenkinsci/plugins/rolestrategy/AmbiguousSidsAdminMonitor.java
src/main/java/org/jenkinsci/plugins/rolestrategy/AmbiguousSidsAdminMonitor.java
package org.jenkinsci.plugins.rolestrategy; import com.michelin.cio.hudson.plugins.rolestrategy.AuthorizationType; import com.michelin.cio.hudson.plugins.rolestrategy.Messages; import com.michelin.cio.hudson.plugins.rolestrategy.PermissionEntry; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.Extension; import hudson.ExtensionList; import hudson.model.AdministrativeMonitor; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; /** * Alert administrators in case ambiguous SID are declared. * * @see <a href="https://issues.jenkins.io/browse/SECURITY-2374">SECURITY-2374</a> */ @Extension @Restricted(NoExternalUse.class) public class AmbiguousSidsAdminMonitor extends AdministrativeMonitor { private @NonNull List<String> ambiguousEntries = Collections.emptyList(); public static @NonNull AmbiguousSidsAdminMonitor get() { return ExtensionList.lookupSingleton(AmbiguousSidsAdminMonitor.class); } /** * To be called everytime Permission Entries are updated. * * @param entries All entries in the system. */ public void updateEntries(@NonNull Collection<PermissionEntry> entries) { List<String> ambiguous = new ArrayList<>(); for (PermissionEntry entry : entries) { try { if (entry.getType() == AuthorizationType.EITHER) { ambiguous.add(entry.getSid()); } } catch (IllegalArgumentException ex) { // Invalid, but not the problem we are looking for } } ambiguousEntries = ambiguous; } public @NonNull List<String> getAmbiguousEntries() { return ambiguousEntries; } @Override public boolean isActivated() { return !ambiguousEntries.isEmpty(); } @Override public String getDisplayName() { return Messages.RoleBasedProjectNamingStrategy_Ambiguous(); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/org/jenkinsci/plugins/rolestrategy/NamingStrategyAdministrativeMonitor.java
src/main/java/org/jenkinsci/plugins/rolestrategy/NamingStrategyAdministrativeMonitor.java
package org.jenkinsci.plugins.rolestrategy; import com.michelin.cio.hudson.plugins.rolestrategy.Messages; import com.michelin.cio.hudson.plugins.rolestrategy.RoleBasedAuthorizationStrategy; import hudson.Extension; import hudson.model.AdministrativeMonitor; import jenkins.model.Jenkins; /** * Monitors if the role based naming strategy is enabled when role based authorization is enabled. */ @Extension public class NamingStrategyAdministrativeMonitor extends AdministrativeMonitor { @Override public String getDisplayName() { return Messages.RoleBasedProjectNamingStrategy_NotConfigured(); } @Override public boolean isActivated() { Jenkins jenkins = Jenkins.get(); return (jenkins.getAuthorizationStrategy() instanceof RoleBasedAuthorizationStrategy && !(jenkins.getProjectNamingStrategy() instanceof RoleBasedProjectNamingStrategy)); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/org/jenkinsci/plugins/rolestrategy/casc/PermissionTemplateDefinition.java
src/main/java/org/jenkinsci/plugins/rolestrategy/casc/PermissionTemplateDefinition.java
package org.jenkinsci.plugins.rolestrategy.casc; import com.michelin.cio.hudson.plugins.rolestrategy.PermissionTemplate; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Objects; import java.util.Set; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.kohsuke.stapler.DataBoundConstructor; /** * PermissionTemplate definition. Used for custom formatting in Casc. */ @Restricted(NoExternalUse.class) public class PermissionTemplateDefinition implements Comparable<PermissionTemplateDefinition> { private transient PermissionTemplate permissionTemplate; private final String name; private final Set<String> permissions; @DataBoundConstructor public PermissionTemplateDefinition(@NonNull String name, @CheckForNull Collection<String> permissions) { this.name = name; this.permissions = permissions != null ? new HashSet<>(permissions) : Collections.emptySet(); } /** * Return the corresponding PermissionTemplate object. * * @return permission template */ public final PermissionTemplate getPermissionTemplate() { if (permissionTemplate == null) { permissionTemplate = new PermissionTemplate(name, permissions); } return permissionTemplate; } public String getName() { return name; } public Set<String> getPermissions() { return permissions; } @Override public int compareTo(@NonNull PermissionTemplateDefinition o) { return this.name.compareTo(o.name); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PermissionTemplateDefinition that = (PermissionTemplateDefinition) o; return Objects.equals(name, that.name); } @Override public int hashCode() { return Objects.hash(name); } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/org/jenkinsci/plugins/rolestrategy/casc/RoleBasedAuthorizationStrategyConfigurator.java
src/main/java/org/jenkinsci/plugins/rolestrategy/casc/RoleBasedAuthorizationStrategyConfigurator.java
package org.jenkinsci.plugins.rolestrategy.casc; import com.michelin.cio.hudson.plugins.rolestrategy.PermissionEntry; import com.michelin.cio.hudson.plugins.rolestrategy.PermissionTemplate; import com.michelin.cio.hudson.plugins.rolestrategy.Role; import com.michelin.cio.hudson.plugins.rolestrategy.RoleBasedAuthorizationStrategy; import com.synopsys.arc.jenkins.plugins.rolestrategy.RoleType; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.Extension; import io.jenkins.plugins.casc.Attribute; import io.jenkins.plugins.casc.BaseConfigurator; import io.jenkins.plugins.casc.ConfigurationContext; import io.jenkins.plugins.casc.Configurator; import io.jenkins.plugins.casc.ConfiguratorException; import io.jenkins.plugins.casc.impl.attributes.MultivaluedAttribute; import io.jenkins.plugins.casc.model.CNode; import io.jenkins.plugins.casc.model.Mapping; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeSet; import java.util.function.Function; import java.util.stream.Collectors; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; /** * Provides the configuration logic for Role Strategy plugin. * * @author Oleg Nenashev * @since 2.11 */ @Extension(optional = true, ordinal = 2) @Restricted({NoExternalUse.class}) public class RoleBasedAuthorizationStrategyConfigurator extends BaseConfigurator<RoleBasedAuthorizationStrategy> { @Override @NonNull public String getName() { return "roleStrategy"; } @Override public Class<RoleBasedAuthorizationStrategy> getTarget() { return RoleBasedAuthorizationStrategy.class; } @NonNull @Override public Class getImplementedAPI() { return GrantedRoles.class; } @Override protected RoleBasedAuthorizationStrategy instance(Mapping map, ConfigurationContext context) throws ConfiguratorException { final Configurator<GrantedRoles> c = context.lookupOrFail(GrantedRoles.class); final GrantedRoles roles = c.configure(map.remove("roles"), context); final Set<PermissionTemplate> permissionTemplates = getPermissionTemplates(map, context); return new RoleBasedAuthorizationStrategy(roles.toMap(), permissionTemplates); } private static Set<PermissionTemplate> getPermissionTemplates(Mapping map, ConfigurationContext context) throws ConfiguratorException { final Configurator<PermissionTemplateDefinition> c = context.lookupOrFail(PermissionTemplateDefinition.class); Set<PermissionTemplate> permissionTemplates = new TreeSet<>(); CNode sub = map.remove("permissionTemplates"); if (sub != null) { for (CNode o : sub.asSequence()) { PermissionTemplateDefinition template = c.configure(o, context); permissionTemplates.add(template.getPermissionTemplate()); } } return permissionTemplates; } @Override protected void configure(Mapping config, RoleBasedAuthorizationStrategy instance, boolean dryrun, ConfigurationContext context) throws ConfiguratorException { super.configure(config, instance, dryrun, context); if (!dryrun) { instance.validateConfig(); } } @Override @NonNull public Set<Attribute<RoleBasedAuthorizationStrategy, ?>> describe() { return new HashSet<>(Arrays.asList( new Attribute<RoleBasedAuthorizationStrategy, GrantedRoles>("roles", GrantedRoles.class).getter(target -> { SortedSet<RoleDefinition> globalRoles = getRoleDefinitions(target.getGrantedRolesEntries(RoleType.Global)); SortedSet<RoleDefinition> agentRoles = getRoleDefinitions(target.getGrantedRolesEntries(RoleType.Slave)); SortedSet<RoleDefinition> projectRoles = getRoleDefinitions(target.getGrantedRolesEntries(RoleType.Project)); return new GrantedRoles(globalRoles, projectRoles, agentRoles); }), new MultivaluedAttribute<RoleBasedAuthorizationStrategy, PermissionTemplateDefinition>("permissionTemplates", PermissionTemplateDefinition.class).getter(target -> getPermissionTemplateDefinitions(target.getPermissionTemplates())) )); } @CheckForNull @Override public CNode describe(RoleBasedAuthorizationStrategy instance, ConfigurationContext context) throws Exception { return compare(instance, new RoleBasedAuthorizationStrategy(Collections.emptyMap()), context); } private Set<PermissionTemplateDefinition> getPermissionTemplateDefinitions(Set<PermissionTemplate> permissionTemplates) { if (permissionTemplates == null) { return Collections.emptySortedSet(); } return new TreeSet<>(permissionTemplates.stream().map(RoleBasedAuthorizationStrategyConfigurator::getPermissionTemplateDefinition) .collect(Collectors.toSet())); } private static PermissionTemplateDefinition getPermissionTemplateDefinition(PermissionTemplate permissionTemplate) { List<String> permissions = permissionTemplate.getPermissions().stream() .map(permission -> permission.group.getId() + "/" + permission.name).collect(Collectors.toList()); return new PermissionTemplateDefinition(permissionTemplate.getName(), permissions); } private SortedSet<RoleDefinition> getRoleDefinitions(@CheckForNull SortedMap<Role, Set<PermissionEntry>> roleMap) { if (roleMap == null) { return Collections.emptySortedSet(); } return new TreeSet<>(roleMap.entrySet().stream().map(getRoleDefinition()).collect(Collectors.toSet())); } private Function<Map.Entry<Role, Set<PermissionEntry>>, RoleDefinition> getRoleDefinition() { return roleSetEntry -> { Role role = roleSetEntry.getKey(); List<String> permissions = role.getPermissions().stream() .map(permission -> permission.group.title.toString( Locale.US) + "/" + permission.name).collect(Collectors.toList()); Set<RoleDefinition.RoleDefinitionEntry> roleDefinitionEntries = roleSetEntry.getValue().stream() .map(RoleDefinition.RoleDefinitionEntry::fromPermissionEntry) .collect(Collectors.toSet()); final RoleDefinition roleDefinition = new RoleDefinition(role.getName(), role.getDescription(), role.getPattern().pattern(), permissions); roleDefinition.setEntries(roleDefinitionEntries); roleDefinition.setTemplateName(role.getTemplateName()); return roleDefinition; }; } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/org/jenkinsci/plugins/rolestrategy/casc/RoleDefinition.java
src/main/java/org/jenkinsci/plugins/rolestrategy/casc/RoleDefinition.java
package org.jenkinsci.plugins.rolestrategy.casc; import com.michelin.cio.hudson.plugins.rolestrategy.AuthorizationType; import com.michelin.cio.hudson.plugins.rolestrategy.PermissionEntry; import com.michelin.cio.hudson.plugins.rolestrategy.Role; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.security.Permission; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import org.jenkinsci.plugins.rolestrategy.permissions.PermissionHelper; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; /** * Role definition. Used for custom formatting * * @author Oleg Nenashev * @since 2.11 */ @Restricted(NoExternalUse.class) public class RoleDefinition implements Comparable<RoleDefinition> { public static final Logger LOGGER = Logger.getLogger(RoleDefinition.class.getName()); private transient Role role; @NonNull private final String name; @CheckForNull private final String description; @CheckForNull private final String pattern; private String templateName; private final Set<String> permissions; private SortedSet<RoleDefinitionEntry> entries = Collections.emptySortedSet(); /** * Creates a RoleDefinition. * * @param name Role name * @param description Role description * @param pattern Role pattern * @param permissions Assigned permissions */ @DataBoundConstructor public RoleDefinition(String name, String description, String pattern, Collection<String> permissions) { this.name = name; this.description = description; this.pattern = pattern; this.permissions = permissions != null ? new HashSet<>(permissions) : Collections.emptySet(); } /** * Legacy setter for string based assignments. * * @param assignments The assigned sids * @deprecated Use {@link #setEntries(java.util.Collection)} instead. */ @DataBoundSetter @Deprecated public void setAssignments(Collection<String> assignments) { LOGGER.log(Level.WARNING, "Loading ambiguous role assignments via via configuration-as-code support"); if (assignments != null) { SortedSet<RoleDefinitionEntry> entries = new TreeSet<>(); for (String assignment : assignments) { final RoleDefinitionEntry rde = new RoleDefinitionEntry(); rde.setEither(assignment); entries.add(rde); } this.entries = entries; } } /** * Setter for entries. * * @param entries The permission entries */ @DataBoundSetter public void setEntries(Collection<RoleDefinitionEntry> entries) { this.entries = entries != null ? new TreeSet<>(entries) : Collections.emptySortedSet(); } /** * Returns the corresponding Role object. * * @return Role */ public final Role getRole() { if (role == null) { Set<Permission> resolvedPermissions = PermissionHelper.fromStrings(permissions, false); Pattern p = Pattern.compile(pattern != null ? pattern : Role.GLOBAL_ROLE_PATTERN); role = new Role(name, p, resolvedPermissions, description, templateName); } return role; } @NonNull public String getName() { return name; } public String getDescription() { return description; } public String getPattern() { return pattern; } public String getTemplateName() { return templateName; } @DataBoundSetter public void setTemplateName(String templateName) { this.templateName = templateName; } public Set<String> getPermissions() { return Collections.unmodifiableSet(permissions); } /** * Deprecated, always returns null. * * @return null */ public Collection<String> getAssignments() { return null; } public SortedSet<RoleDefinitionEntry> getEntries() { return entries; } @Override public int compareTo(@NonNull RoleDefinition o) { return this.name.compareTo(o.name); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RoleDefinition that = (RoleDefinition) o; return Objects.equals(name, that.name); } @Override public int hashCode() { return Objects.hash(name); } /** * Maps a permission entry to the casc line. */ public static class RoleDefinitionEntry implements Comparable<RoleDefinitionEntry> { private /* quasi-final */ AuthorizationType type; private /* quasi-final */ String name; @DataBoundConstructor public RoleDefinitionEntry() { } private void setTypeIfUndefined(AuthorizationType type) { if (this.type == null) { this.type = type; } else { throw new IllegalStateException("Cannot set two different types for '" + name + "'"); // TODO Add test for this } } @DataBoundSetter public void setUser(String name) { this.name = name; setTypeIfUndefined(AuthorizationType.USER); } @DataBoundSetter public void setGroup(String name) { this.name = name; setTypeIfUndefined(AuthorizationType.GROUP); } @DataBoundSetter public void setEither(String name) { this.name = name; setTypeIfUndefined(AuthorizationType.EITHER); } public String getUser() { return type == AuthorizationType.USER ? name : null; } public String getGroup() { return type == AuthorizationType.GROUP ? name : null; } public String getEither() { return type == AuthorizationType.EITHER ? name : null; } public PermissionEntry asPermissionEntry() { return new PermissionEntry(type, name); } /** * Creates a RoleDefinitionEntry from a PermissionNetry. * * @param entry {@link PermissionEntry} * @return RoleDefinitionEntry */ public static RoleDefinitionEntry fromPermissionEntry(PermissionEntry entry) { final RoleDefinitionEntry roleDefinitionEntry = new RoleDefinitionEntry(); roleDefinitionEntry.type = entry.getType(); roleDefinitionEntry.name = entry.getSid(); return roleDefinitionEntry; } @Override public int hashCode() { return Objects.hash(type, name); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RoleDefinitionEntry that = (RoleDefinitionEntry) o; return type == that.type && name.equals(that.name); } @Override public int compareTo(@NonNull RoleDefinitionEntry o) { int typeCompare = this.type.compareTo(o.type); if (typeCompare == 0) { return this.name.compareTo(o.name); } return typeCompare; } } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/org/jenkinsci/plugins/rolestrategy/casc/GrantedRoles.java
src/main/java/org/jenkinsci/plugins/rolestrategy/casc/GrantedRoles.java
package org.jenkinsci.plugins.rolestrategy.casc; import com.michelin.cio.hudson.plugins.rolestrategy.PermissionEntry; import com.michelin.cio.hudson.plugins.rolestrategy.Role; import com.michelin.cio.hudson.plugins.rolestrategy.RoleBasedAuthorizationStrategy; import com.michelin.cio.hudson.plugins.rolestrategy.RoleMap; import edu.umd.cs.findbugs.annotations.NonNull; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.stream.Collectors; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.kohsuke.stapler.DataBoundConstructor; /** * Casc wrapper for Roles. * * @author <a href="mailto:nicolas.deloof@gmail.com">Nicolas De Loof</a> * @since 2.11 */ @Restricted(NoExternalUse.class) public class GrantedRoles { private final Set<RoleDefinition> global; private final Set<RoleDefinition> items; private final Set<RoleDefinition> agents; /** * Create GrantedRoles. * * @param global List of global Roles * @param items List of item Roles * @param agents List of agent Roles */ @DataBoundConstructor public GrantedRoles(Set<RoleDefinition> global, Set<RoleDefinition> items, Set<RoleDefinition> agents) { this.global = global != null ? new TreeSet<>(global) : Collections.emptySet(); this.items = items != null ? new TreeSet<>(items) : Collections.emptySet(); this.agents = agents != null ? new TreeSet<>(agents) : Collections.emptySet(); } protected Map<String, RoleMap> toMap() { Map<String, RoleMap> grantedRoles = new HashMap<>(); if (global != null) { grantedRoles.put(RoleBasedAuthorizationStrategy.GLOBAL, retrieveRoleMap(global)); } if (items != null) { grantedRoles.put(RoleBasedAuthorizationStrategy.PROJECT, retrieveRoleMap(items)); } if (agents != null) { grantedRoles.put(RoleBasedAuthorizationStrategy.SLAVE, retrieveRoleMap(agents)); } return grantedRoles; } @NonNull private RoleMap retrieveRoleMap(Set<RoleDefinition> definitions) { TreeMap<Role, Set<PermissionEntry>> resMap = new TreeMap<>(); for (RoleDefinition definition : definitions) { resMap.put(definition.getRole(), definition.getEntries().stream().map(RoleDefinition.RoleDefinitionEntry::asPermissionEntry).collect(Collectors.toSet())); } return new RoleMap(resMap); } public Set<RoleDefinition> getGlobal() { return global; } public Set<RoleDefinition> getItems() { return items; } public Set<RoleDefinition> getAgents() { return agents; } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/org/jenkinsci/plugins/rolestrategy/permissions/PermissionHelper.java
src/main/java/org/jenkinsci/plugins/rolestrategy/permissions/PermissionHelper.java
/* * The MIT License * * Copyright (c) 2017 CloudBees, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.rolestrategy.permissions; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.PluginManager; import hudson.security.Permission; import hudson.security.PermissionGroup; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import jenkins.model.Jenkins; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; /** * Helper methods for dangerous permission handling. * * @author Oleg Nenashev */ @Restricted(NoExternalUse.class) public class PermissionHelper { private static final Logger LOGGER = Logger.getLogger(PermissionHelper.class.getName()); private static final Pattern PERMISSION_PATTERN = Pattern.compile("^([^\\/]+)\\/(.+)$"); /** * List of the dangerous permissions, which need to be suppressed by the plugin. */ @SuppressWarnings("deprecation") @Restricted(NoExternalUse.class) public static final Set<Permission> DANGEROUS_PERMISSIONS = Collections.unmodifiableSet( new HashSet<>(Arrays.asList(Jenkins.RUN_SCRIPTS, PluginManager.CONFIGURE_UPDATECENTER, PluginManager.UPLOAD_PLUGINS))); private PermissionHelper() { // Cannot be constructed } /** * Convert a set of string to a collection of permissions. * Dangerous and non-solvable permissions are ignored * * @param permissionStrings A list of Permission IDs or UI names. * @param allowPermissionId Allow to resolve the permission from the ID. * @return Created set of permissions */ @NonNull public static Set<Permission> fromStrings(@CheckForNull Collection<String> permissionStrings, boolean allowPermissionId) { if (permissionStrings == null) { return Collections.emptySet(); } HashSet<Permission> res = new HashSet<>(permissionStrings.size()); for (String permission : permissionStrings) { final Permission p = allowPermissionId ? resolvePermissionFromString(permission) : findPermission(permission); if (p == null) { LOGGER.log(Level.WARNING, "Ignoring unresolved permission: " + permission); // throw IllegalArgumentException? continue; } res.add(p); } return res; } /** * Check if the permissions is dangerous. * * @param p Permission * @return {@code true} if the permission is considered as dangerous. */ public static boolean isDangerous(Permission p) { return DANGEROUS_PERMISSIONS.contains(p); } /** * Attempt to match a given permission to what is defined in the UI. * * @param id String of the form "Title/Permission" (Look in the UI) for a particular permission * @return a matched permission */ @CheckForNull public static Permission findPermission(String id) { final String resolvedId = findPermissionId(id); return resolvedId != null ? getSafePermission(resolvedId) : null; } /** * Attempt to match a given permission to what is defined in the UI. * * @param id String of the form "Title/Permission" (Look in the UI) for a particular permission * @return a matched permission ID */ @CheckForNull public static String findPermissionId(String id) { if (id == null) { return null; } List<PermissionGroup> pgs = PermissionGroup.getAll(); Matcher m = PERMISSION_PATTERN.matcher(id); if (m.matches()) { String owner = m.group(1); String name = m.group(2); for (PermissionGroup pg : pgs) { if (pg.owner.equals(Permission.class)) { continue; } if (pg.getId().equals(owner)) { return pg.owner.getName() + "." + name; } } } return null; } private static @CheckForNull Permission getSafePermission(String id) { Permission permission = Permission.fromId(id); if (permission != null && isDangerous(permission)) { LOGGER.log(Level.WARNING, "The permission: '" + permission + "' is dangerous and will be ignored."); return null; } return permission; } /** * Attempt to match a given permission to what is defined in the UI or from the ID representation used in the config.xml. * * @param id String of the form "Title/Permission" (Look in the UI) for a particular permission or in the form used in the config.xml * @return a matched permission, null if permission couldn't be resolved or is dangerous */ @CheckForNull public static Permission resolvePermissionFromString(String id) { Permission permission = getSafePermission(id); if (permission == null) { permission = PermissionHelper.findPermission(id); } return permission; } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/org/jenkinsci/plugins/rolestrategy/pipeline/AbstractUserRolesStep.java
src/main/java/org/jenkinsci/plugins/rolestrategy/pipeline/AbstractUserRolesStep.java
package org.jenkinsci.plugins.rolestrategy.pipeline; import com.michelin.cio.hudson.plugins.rolestrategy.Role; import com.michelin.cio.hudson.plugins.rolestrategy.RoleBasedAuthorizationStrategy; import com.michelin.cio.hudson.plugins.rolestrategy.RoleMap; import com.synopsys.arc.jenkins.plugins.rolestrategy.RoleType; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.model.Cause; import hudson.model.Run; import hudson.model.User; import hudson.security.ACL; import hudson.security.AuthorizationStrategy; import java.io.IOException; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import jenkins.model.Jenkins; import org.jenkinsci.plugins.workflow.steps.Step; import org.jenkinsci.plugins.workflow.steps.StepContext; import org.jenkinsci.plugins.workflow.steps.SynchronousNonBlockingStepExecution; import org.springframework.security.core.Authentication; /** * Base class for the pipeline steps. */ public abstract class AbstractUserRolesStep extends Step { /** * Step Execution. */ protected static class Execution extends SynchronousNonBlockingStepExecution<Set<String>> { protected final RoleType roleType; public Execution(@NonNull StepContext context, RoleType roleType) { super(context); this.roleType = roleType; } protected RoleMap getRoleMap() throws IOException, InterruptedException { AuthorizationStrategy strategy = Jenkins.get().getAuthorizationStrategy(); if (strategy instanceof RoleBasedAuthorizationStrategy) { RoleBasedAuthorizationStrategy rbas = (RoleBasedAuthorizationStrategy) strategy; return rbas.getRoleMap(roleType); } return null; } @Override protected Set<String> run() throws Exception { Set<String> roleSet = new HashSet<>(); Authentication auth = getAuthentication(); if (auth == null) { return roleSet; } RoleMap roleMap = getRoleMap(); if (roleMap != null) { if (auth == ACL.SYSTEM2) { return roleMap.getRoles().stream().map(Role::getName).collect(Collectors.toSet()); } return roleMap.getRolesForAuth(auth); } return roleSet; } private Authentication getAuthentication() throws IOException, InterruptedException { final Run<?, ?> run = Objects.requireNonNull(getContext().get(Run.class)); Cause.UserIdCause cause = run.getCause(Cause.UserIdCause.class); if (cause != null) { User causeUser = User.getById(cause.getUserId(), false); if (causeUser != null) { return causeUser.impersonate2(); } } Authentication auth = Jenkins.getAuthentication2(); if (ACL.isAnonymous2(auth)) { return null; } return auth; } } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/org/jenkinsci/plugins/rolestrategy/pipeline/UserGlobalRoles.java
src/main/java/org/jenkinsci/plugins/rolestrategy/pipeline/UserGlobalRoles.java
package org.jenkinsci.plugins.rolestrategy.pipeline; import com.synopsys.arc.jenkins.plugins.rolestrategy.RoleType; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.Extension; import hudson.model.Run; import java.util.Collections; import java.util.Set; import org.jenkinsci.plugins.workflow.steps.StepContext; import org.jenkinsci.plugins.workflow.steps.StepDescriptor; import org.jenkinsci.plugins.workflow.steps.StepExecution; import org.kohsuke.stapler.DataBoundConstructor; /** * Pipeline step that returns the users global roles. */ public class UserGlobalRoles extends AbstractUserRolesStep { @DataBoundConstructor public UserGlobalRoles() { } @Override public StepExecution start(StepContext context) throws Exception { return new Execution(context, RoleType.Global); } /** * The descriptor of the step. */ @Extension public static final class DescriptorImpl extends StepDescriptor { @Override public Set<? extends Class<?>> getRequiredContext() { return Collections.singleton(Run.class); } @NonNull @Override public String getDisplayName() { return "Current Users Global Roles"; } @Override public String getFunctionName() { return "currentUserGlobalRoles"; } } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
jenkinsci/role-strategy-plugin
https://github.com/jenkinsci/role-strategy-plugin/blob/aaea673cf0bc5897a95c7683627ccf0096094262/src/main/java/org/jenkinsci/plugins/rolestrategy/pipeline/UserItemRoles.java
src/main/java/org/jenkinsci/plugins/rolestrategy/pipeline/UserItemRoles.java
package org.jenkinsci.plugins.rolestrategy.pipeline; import com.michelin.cio.hudson.plugins.rolestrategy.RoleBasedAuthorizationStrategy; import com.michelin.cio.hudson.plugins.rolestrategy.RoleMap; import com.synopsys.arc.jenkins.plugins.rolestrategy.RoleType; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.Extension; import hudson.model.Job; import hudson.model.Run; import hudson.security.AuthorizationStrategy; import java.io.IOException; import java.util.Collections; import java.util.Objects; import java.util.Set; import jenkins.model.Jenkins; import org.jenkinsci.plugins.workflow.steps.StepContext; import org.jenkinsci.plugins.workflow.steps.StepDescriptor; import org.jenkinsci.plugins.workflow.steps.StepExecution; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; /** * Pipeline step that returns the users item roles. */ public class UserItemRoles extends AbstractUserRolesStep { private boolean showAllRoles; @DataBoundConstructor public UserItemRoles() { } public boolean isShowAllRoles() { return showAllRoles; } @DataBoundSetter public void setShowAllRoles(boolean showAllRoles) { this.showAllRoles = showAllRoles; } @Override public StepExecution start(StepContext context) throws Exception { return new ItemRolesExecution(context, RoleType.Project, showAllRoles); } /** * Step Execution. */ public static class ItemRolesExecution extends Execution { private final boolean showAllRoles; public ItemRolesExecution(@NonNull StepContext context, RoleType roleType, boolean showAllRoles) { super(context, roleType); this.showAllRoles = showAllRoles; } @Override protected RoleMap getRoleMap() throws IOException, InterruptedException { AuthorizationStrategy strategy = Jenkins.get().getAuthorizationStrategy(); if (strategy instanceof RoleBasedAuthorizationStrategy) { RoleBasedAuthorizationStrategy rbas = (RoleBasedAuthorizationStrategy) strategy; RoleMap roleMap = rbas.getRoleMap(roleType); if (showAllRoles) { return roleMap; } else { final Run<?, ?> run = Objects.requireNonNull(getContext().get(Run.class)); Job<?, ?> job = run.getParent(); return roleMap.newMatchingRoleMap(job.getFullName()); } } return null; } } /** * The descriptor. */ @Extension public static final class DescriptorImpl extends StepDescriptor { @Override public Set<? extends Class<?>> getRequiredContext() { return Collections.singleton(Run.class); } @NonNull @Override public String getDisplayName() { return "Current Users Item Roles"; } @Override public String getFunctionName() { return "currentUserItemRoles"; } } }
java
MIT
aaea673cf0bc5897a95c7683627ccf0096094262
2026-01-05T02:37:05.006037Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/tests/test.integration.ui/src/main/java/org/apache/directory/studio/test/integration/ui/NewConnectionWizardTest.java
tests/test.integration.ui/src/main/java/org/apache/directory/studio/test/integration/ui/NewConnectionWizardTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.studio.test.integration.ui; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.lang.reflect.Method; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Arrays; import org.apache.directory.api.ldap.model.constants.SaslQoP; import org.apache.directory.api.ldap.model.constants.SaslSecurityStrength; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.ConnectionCorePlugin; import org.apache.directory.studio.connection.core.ConnectionManager; import org.apache.directory.studio.connection.core.ConnectionParameter.AuthenticationMethod; import org.apache.directory.studio.connection.core.ConnectionParameter.EncryptionMethod; import org.apache.directory.studio.ldapbrowser.core.BrowserConnectionManager; import org.apache.directory.studio.ldapbrowser.core.BrowserCorePlugin; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.IRootDSE; import org.apache.directory.studio.test.integration.junit5.LdapServerType; import org.apache.directory.studio.test.integration.junit5.LdapServersSource; import org.apache.directory.studio.test.integration.junit5.LdapServersSource.Mode; import org.apache.directory.studio.test.integration.junit5.OpenLdapServer; import org.apache.directory.studio.test.integration.junit5.TestFixture; import org.apache.directory.studio.test.integration.junit5.TestLdapServer; import org.apache.directory.studio.test.integration.ui.bots.CertificateTrustDialogBot; import org.apache.directory.studio.test.integration.ui.bots.DialogBot.CheckResponse; import org.apache.directory.studio.test.integration.ui.bots.ErrorDialogBot; import org.apache.directory.studio.test.integration.ui.bots.NewConnectionWizardBot; import org.apache.mina.util.AvailablePortFinder; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; import org.junit.jupiter.params.ParameterizedTest; /** * Tests the new connection wizard. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> * @version $Rev$, $Date$ */ public class NewConnectionWizardTest extends AbstractTestBase { private NewConnectionWizardBot wizardBot; private TestInfo testInfo; @BeforeEach public void beforeEach( TestInfo testInfo ) { this.wizardBot = connectionsViewBot.openNewConnectionWizard(); this.testInfo = testInfo; } private String getConnectionName() { return testInfo.getTestMethod().map( Method::getName ).orElse( "null" ) + " " + testInfo.getDisplayName(); } /** * Tests enabled and disabled widgets, depending on the provided input. */ @Test public void testEnabledDisabledWidgets() { assertTrue( wizardBot.isVisible() ); // check network parameter buttons assertFalse( wizardBot.isViewCertificateButtonEnabled() ); assertFalse( wizardBot.isCheckNetworkParameterButtonEnabled() ); // ensure "Next >" and "Finish" buttons are disabled assertFalse( wizardBot.isBackButtonEnabled() ); assertFalse( wizardBot.isNextButtonEnabled() ); assertFalse( wizardBot.isFinishButtonEnabled() ); assertTrue( wizardBot.isCancelButtonEnabled() ); // enter connection parameter wizardBot.typeConnectionName( getConnectionName() ); wizardBot.typeHost( "test.example.com" ); wizardBot.typePort( 389 ); // check network parameter buttons assertFalse( wizardBot.isViewCertificateButtonEnabled() ); assertTrue( wizardBot.isCheckNetworkParameterButtonEnabled() ); // ensure "Next >" button is enabled assertFalse( wizardBot.isBackButtonEnabled() ); assertTrue( wizardBot.isNextButtonEnabled() ); assertFalse( wizardBot.isFinishButtonEnabled() ); assertTrue( wizardBot.isCancelButtonEnabled() ); // clear host wizardBot.typeHost( "" ); // check network parameter buttons assertFalse( wizardBot.isViewCertificateButtonEnabled() ); assertFalse( wizardBot.isCheckNetworkParameterButtonEnabled() ); // ensure "Next >" is disabled assertFalse( wizardBot.isBackButtonEnabled() ); assertFalse( wizardBot.isNextButtonEnabled() ); assertFalse( wizardBot.isFinishButtonEnabled() ); assertTrue( wizardBot.isCancelButtonEnabled() ); // enter host again wizardBot.typeHost( "test.example.com" ); // check network parameter buttons assertFalse( wizardBot.isViewCertificateButtonEnabled() ); assertTrue( wizardBot.isCheckNetworkParameterButtonEnabled() ); // ensure "Next >" button is enabled assertFalse( wizardBot.isBackButtonEnabled() ); assertTrue( wizardBot.isNextButtonEnabled() ); assertFalse( wizardBot.isFinishButtonEnabled() ); assertTrue( wizardBot.isCancelButtonEnabled() ); // set StartTLS encryption wizardBot.selectStartTlsEncryption(); // check network parameter buttons assertTrue( wizardBot.isViewCertificateButtonEnabled() ); assertTrue( wizardBot.isCheckNetworkParameterButtonEnabled() ); // check wizard buttons assertFalse( wizardBot.isBackButtonEnabled() ); assertTrue( wizardBot.isNextButtonEnabled() ); assertFalse( wizardBot.isFinishButtonEnabled() ); assertTrue( wizardBot.isCancelButtonEnabled() ); // set SSL encryption wizardBot.selectLdapsEncryption(); // check network parameter buttons assertTrue( wizardBot.isViewCertificateButtonEnabled() ); assertTrue( wizardBot.isCheckNetworkParameterButtonEnabled() ); // check wizard buttons assertFalse( wizardBot.isBackButtonEnabled() ); assertTrue( wizardBot.isNextButtonEnabled() ); assertFalse( wizardBot.isFinishButtonEnabled() ); assertTrue( wizardBot.isCancelButtonEnabled() ); // set no encryption wizardBot.selectNoEncryption(); // check network parameter buttons assertFalse( wizardBot.isViewCertificateButtonEnabled() ); assertTrue( wizardBot.isCheckNetworkParameterButtonEnabled() ); // check wizard buttons assertFalse( wizardBot.isBackButtonEnabled() ); assertTrue( wizardBot.isNextButtonEnabled() ); assertFalse( wizardBot.isFinishButtonEnabled() ); assertTrue( wizardBot.isCancelButtonEnabled() ); wizardBot.clickNextButton(); // check default settings assertTrue( wizardBot.isSimpleAuthenticationSelected() ); assertTrue( wizardBot.isUserEnabled() ); assertTrue( wizardBot.isPasswordEnabled() ); assertFalse( wizardBot.isRealmEnabled() ); assertTrue( wizardBot.isSavePasswordSelected() ); // ensure "<Back" is enabled, "Next >" and "Finish" is disabled assertTrue( wizardBot.isBackButtonEnabled() ); assertFalse( wizardBot.isNextButtonEnabled() ); assertFalse( wizardBot.isFinishButtonEnabled() ); assertTrue( wizardBot.isCancelButtonEnabled() ); // enter authentication parameters wizardBot.selectSimpleAuthentication(); wizardBot.typeUser( "uid=admin,ou=system" ); wizardBot.typePassword( "secret" ); // ensure "<Back" is enabled, "Next >" and "Finish" is enabled assertTrue( wizardBot.isBackButtonEnabled() ); assertTrue( wizardBot.isNextButtonEnabled() ); assertTrue( wizardBot.isFinishButtonEnabled() ); assertTrue( wizardBot.isCancelButtonEnabled() ); // clear user wizardBot.typeUser( "" ); // ensure "<Back" is enabled, "Next >" and "Finish" is disabled assertTrue( wizardBot.isBackButtonEnabled() ); assertFalse( wizardBot.isNextButtonEnabled() ); assertFalse( wizardBot.isFinishButtonEnabled() ); assertTrue( wizardBot.isCancelButtonEnabled() ); // enter user again wizardBot.typeUser( "uid=admin,ou=system" ); // ensure "<Back" is enabled, "Next >" and "Finish" is enabled assertTrue( wizardBot.isBackButtonEnabled() ); assertTrue( wizardBot.isNextButtonEnabled() ); assertTrue( wizardBot.isFinishButtonEnabled() ); assertTrue( wizardBot.isCancelButtonEnabled() ); // deselect password save wizardBot.deselectSavePassword(); // ensure password field is disabled assertFalse( wizardBot.isPasswordEnabled() ); // ensure "<Back" is enabled, "Next >" and "Finish" is enabled assertTrue( wizardBot.isBackButtonEnabled() ); assertTrue( wizardBot.isNextButtonEnabled() ); assertTrue( wizardBot.isFinishButtonEnabled() ); assertTrue( wizardBot.isCancelButtonEnabled() ); // select password save wizardBot.selectSavePassword(); // ensure password field is enabled but empty assertTrue( wizardBot.isPasswordEnabled() ); // ensure "<Back" is enabled, "Next >" and "Finish" is disabled assertTrue( wizardBot.isBackButtonEnabled() ); assertFalse( wizardBot.isNextButtonEnabled() ); assertFalse( wizardBot.isFinishButtonEnabled() ); assertTrue( wizardBot.isCancelButtonEnabled() ); // enter authentication parameters again wizardBot.selectSimpleAuthentication(); wizardBot.typeUser( "uid=admin,ou=system" ); wizardBot.typePassword( "secret" ); // ensure "<Back" is enabled, "Next >" and "Finish" is enabled assertTrue( wizardBot.isBackButtonEnabled() ); assertTrue( wizardBot.isNextButtonEnabled() ); assertTrue( wizardBot.isFinishButtonEnabled() ); assertTrue( wizardBot.isCancelButtonEnabled() ); // select no authentication wizardBot.selectNoAuthentication(); // ensure authentication parameter input fields are disabled assertTrue( wizardBot.isNoAuthenticationSelected() ); assertFalse( wizardBot.isUserEnabled() ); assertFalse( wizardBot.isPasswordEnabled() ); assertFalse( wizardBot.isRealmEnabled() ); assertFalse( wizardBot.isSavePasswordEnabled() ); // select DIGEST-MD5 wizardBot.selectDigestMD5Authentication(); // ensure authentication parameter input fields are enabled, including SASL Realm field assertTrue( wizardBot.isDigestMD5AuthenticationSelected() ); assertTrue( wizardBot.isUserEnabled() ); assertTrue( wizardBot.isPasswordEnabled() ); assertTrue( wizardBot.isSavePasswordEnabled() ); assertTrue( wizardBot.isRealmEnabled() ); // select CRAM-MD5 wizardBot.selectCramMD5Authentication(); // ensure authentication parameter input fields are enabled, excluding SASL Realm field assertTrue( wizardBot.isCramMD5AuthenticationSelected() ); assertTrue( wizardBot.isUserEnabled() ); assertTrue( wizardBot.isPasswordEnabled() ); assertTrue( wizardBot.isSavePasswordEnabled() ); assertFalse( wizardBot.isRealmEnabled() ); // select GSSAPI (Kerberos) wizardBot.selectGssApiAuthentication(); // ensure authentication parameter input fields are disabled by default assertTrue( wizardBot.isGssApiAuthenticationSelected() ); assertFalse( wizardBot.isUserEnabled() ); assertFalse( wizardBot.isPasswordEnabled() ); assertFalse( wizardBot.isSavePasswordEnabled() ); assertFalse( wizardBot.isRealmEnabled() ); // by default "Use native TGT" is selected assertTrue( wizardBot.isUseNativeTgtSelected() ); assertFalse( wizardBot.isObtainTgtFromKdcSelected() ); assertTrue( wizardBot.isUseNativeSystemConfigurationSelected() ); assertFalse( wizardBot.isUseConfigurationFileSelected() ); assertFalse( wizardBot.isUseManualConfigurationSelected() ); assertFalse( wizardBot.isKerberosRealmEnabled() ); assertFalse( wizardBot.isKdcHostEnabled() ); assertFalse( wizardBot.isKdcPortEnabled() ); // select GSSAPI (Kerberos) and "Obtain TGT from KDC" wizardBot.selectObtainTgtFromKdc(); // ensure authentication parameter input fields are enabled assertTrue( wizardBot.isGssApiAuthenticationSelected() ); assertTrue( wizardBot.isUserEnabled() ); assertTrue( wizardBot.isPasswordEnabled() ); assertTrue( wizardBot.isSavePasswordEnabled() ); assertFalse( wizardBot.isRealmEnabled() ); assertFalse( wizardBot.isUseNativeTgtSelected() ); // select GSSAPI (Kerberos) and "Use configuration file" wizardBot.selectUseConfigurationFile(); assertFalse( wizardBot.isUseNativeSystemConfigurationSelected() ); assertTrue( wizardBot.isUseConfigurationFileSelected() ); assertFalse( wizardBot.isUseManualConfigurationSelected() ); assertFalse( wizardBot.isKerberosRealmEnabled() ); assertFalse( wizardBot.isKdcHostEnabled() ); assertFalse( wizardBot.isKdcPortEnabled() ); // select GSSAPI (Kerberos) and "Use manual configuration" wizardBot.selectUseManualConfiguration(); assertFalse( wizardBot.isUseNativeSystemConfigurationSelected() ); assertFalse( wizardBot.isUseConfigurationFileSelected() ); assertTrue( wizardBot.isUseManualConfigurationSelected() ); assertTrue( wizardBot.isKerberosRealmEnabled() ); assertTrue( wizardBot.isKdcHostEnabled() ); assertTrue( wizardBot.isKdcPortEnabled() ); assertFalse( wizardBot.isNextButtonEnabled() ); // select GSSAPI (Kerberos) and "Use native system configuration" again wizardBot.selectUseNativeSystemConfiguration(); assertTrue( wizardBot.isUseNativeSystemConfigurationSelected() ); assertFalse( wizardBot.isUseConfigurationFileSelected() ); assertFalse( wizardBot.isUseManualConfigurationSelected() ); assertFalse( wizardBot.isKerberosRealmEnabled() ); assertFalse( wizardBot.isKdcHostEnabled() ); assertFalse( wizardBot.isKdcPortEnabled() ); wizardBot.clickNextButton(); // check default settings assertTrue( wizardBot.isGetBaseDnsFromRootDseSelected() ); assertFalse( wizardBot.isBaseDnEnabled() ); // ensure "<Back" and "Finish" is enabled, "Next >" enabled assertTrue( wizardBot.isBackButtonEnabled() ); assertTrue( wizardBot.isNextButtonEnabled() ); assertTrue( wizardBot.isFinishButtonEnabled() ); assertTrue( wizardBot.isCancelButtonEnabled() ); // deselect get base DNs from Root DSE wizardBot.deselectGetBaseDnsFromRootDse(); assertFalse( wizardBot.isGetBaseDnsFromRootDseSelected() ); assertTrue( wizardBot.isBaseDnEnabled() ); // select get base DNs from Root DSE wizardBot.selectGetBaseDnsFromRootDse(); assertTrue( wizardBot.isGetBaseDnsFromRootDseSelected() ); assertFalse( wizardBot.isBaseDnEnabled() ); wizardBot.clickCancelButton(); } @ParameterizedTest @LdapServersSource(mode = Mode.All) public void testCreateConnectionNoEncryptionNoAuthOK( TestLdapServer server ) { setConnectionParameters( server, EncryptionMethod.NONE ); wizardBot.selectNoAuthentication(); finishAndAssertConnection( server, EncryptionMethod.NONE, AuthenticationMethod.NONE, "", "" ); } @ParameterizedTest @LdapServersSource public void testCreateConnectionNoEncryptionNoAuthInvalidHostname( TestLdapServer server ) { setConnectionParameters( server, EncryptionMethod.NONE ); wizardBot.clickBackButton(); String hostname = getInvalidHostName(); wizardBot.typeHost( hostname ); wizardBot.clickNextButton(); wizardBot.selectNoAuthentication(); finishAndAssertConnectionError( hostname ); } @ParameterizedTest @LdapServersSource public void testCreateConnectionNoEncryptionSimpleAuthOK( TestLdapServer server ) throws UnknownHostException { // enter connection parameter wizardBot.typeConnectionName( getConnectionName() ); wizardBot.typeHost( server.getHost() ); wizardBot.typePort( server.getPort() ); // click "Check Network Parameter" button CheckResponse checkResponse = wizardBot.clickCheckNetworkParameterButton(); assertFalse( checkResponse.isError(), "Expected OK" ); assertThat( checkResponse.getMessage(), not( containsString( "Protocol" ) ) ); assertThat( checkResponse.getMessage(), not( containsString( "Cipher Suite" ) ) ); // enter IPv4 address as host wizardBot.typeHost( InetAddress.getByName( server.getHost() ).getHostAddress() ); // click "Check Network Parameter" button checkResponse = wizardBot.clickCheckNetworkParameterButton(); assertFalse( checkResponse.isError(), "Expected OK" ); assertThat( checkResponse.getMessage(), not( containsString( "Protocol" ) ) ); assertThat( checkResponse.getMessage(), not( containsString( "Cipher Suite" ) ) ); // enter hostname as host again wizardBot.typeHost( server.getHost() ); // jump to auth page wizardBot.clickNextButton(); // enter authentication parameters wizardBot.typeUser( server.getAdminDn() ); wizardBot.typePassword( server.getAdminPassword() ); // click "Check Network Parameter" button String result = wizardBot.clickCheckAuthenticationButton(); assertNull( result, "Expected OK" ); finishAndAssertConnection( server, EncryptionMethod.NONE, AuthenticationMethod.SIMPLE, server.getAdminDn(), server.getAdminPassword() ); } @ParameterizedTest @LdapServersSource(mode = Mode.All) public void testCreateConnectionNoEncryptionSimpleAuthConfidentialityRequired( TestLdapServer server ) { setConnectionParameters( server, EncryptionMethod.NONE ); wizardBot.selectSimpleAuthentication(); wizardBot.typeUser( server.getAdminDn() ); wizardBot.typePassword( server.getAdminPassword() ); server.setConfidentialityRequired( true ); String result = wizardBot.clickCheckAuthenticationButton(); assertThat( result, containsString( "[LDAP result code 13 - confidentialityRequired]" ) ); finishAndAssertConnectionError( "[LDAP result code 13 - confidentialityRequired]" ); } @ParameterizedTest @LdapServersSource public void testCreateConnectionNoEncryptionSaslCramMd5OK( TestLdapServer server ) { setConnectionParameters( server, EncryptionMethod.NONE ); wizardBot.selectCramMD5Authentication(); wizardBot.typeUser( "user.1" ); wizardBot.typePassword( "password" ); wizardBot.selectQualityOfProtection( SaslQoP.AUTH ); wizardBot.selectProtectionStrength( SaslSecurityStrength.HIGH ); String result = wizardBot.clickCheckAuthenticationButton(); assertNull( result, "Expected OK" ); finishAndAssertConnection( server, EncryptionMethod.NONE, AuthenticationMethod.SASL_CRAM_MD5, "user.1", "password" ); } @ParameterizedTest @LdapServersSource public void testCreateConnectionNoEncryptionSaslDigestMd5AuthOK( TestLdapServer server ) { setConnectionParameters( server, EncryptionMethod.NONE ); wizardBot.selectDigestMD5Authentication(); wizardBot.typeUser( "user.1" ); wizardBot.typePassword( "password" ); wizardBot.selectQualityOfProtection( SaslQoP.AUTH ); wizardBot.selectProtectionStrength( SaslSecurityStrength.HIGH ); String result = wizardBot.clickCheckAuthenticationButton(); assertNull( result, "Expected OK" ); finishAndAssertConnection( server, EncryptionMethod.NONE, AuthenticationMethod.SASL_DIGEST_MD5, "user.1", "password" ); } @ParameterizedTest @LdapServersSource(except = LdapServerType.ApacheDS, reason = "Bug in SASL filter in ApacheDS 2.0.0.M26") public void testCreateConnectionNoEncryptionSaslDigestMd5AuthIntOK( TestLdapServer server ) { // Configure OpenLDAP with ssf=1 (1 implies integrity protection only) if ( server instanceof OpenLdapServer ) { OpenLdapServer openLdapServer = ( OpenLdapServer ) server; openLdapServer.setSecurityProps( 1, 0 ); } setConnectionParameters( server, EncryptionMethod.NONE ); wizardBot.selectDigestMD5Authentication(); wizardBot.typeUser( "user.1" ); wizardBot.typePassword( "password" ); if ( server.getType() == LdapServerType.ApacheDS ) { wizardBot.typeRealm( "EXAMPLE.ORG" ); } wizardBot.selectQualityOfProtection( SaslQoP.AUTH_INT ); wizardBot.selectProtectionStrength( SaslSecurityStrength.HIGH ); String result = wizardBot.clickCheckAuthenticationButton(); assertNull( result, "Expected OK" ); finishAndAssertConnection( server, EncryptionMethod.NONE, AuthenticationMethod.SASL_DIGEST_MD5, "user.1", "password" ); } @ParameterizedTest @LdapServersSource(except = LdapServerType.ApacheDS, reason = "Bug in SASL filter in ApacheDS 2.0.0.M26.") public void testCreateConnectionNoEncryptionSaslDigestMd5AuthConfOK( TestLdapServer server ) { // Configure OpenLDAP with ssf=128 (128 allows RC4, Blowfish and other modern strong ciphers) if ( server instanceof OpenLdapServer ) { OpenLdapServer openLdapServer = ( OpenLdapServer ) server; openLdapServer.setSecurityProps( 128, 0 ); } setConnectionParameters( server, EncryptionMethod.NONE ); wizardBot.selectDigestMD5Authentication(); wizardBot.typeUser( "user.1" ); wizardBot.typePassword( "password" ); if ( server.getType() == LdapServerType.ApacheDS ) { wizardBot.typeRealm( "EXAMPLE.ORG" ); } wizardBot.selectQualityOfProtection( SaslQoP.AUTH_CONF ); wizardBot.selectProtectionStrength( SaslSecurityStrength.HIGH ); String result = wizardBot.clickCheckAuthenticationButton(); assertNull( result, "Expected OK" ); finishAndAssertConnection( server, EncryptionMethod.NONE, AuthenticationMethod.SASL_DIGEST_MD5, "user.1", "password" ); } @ParameterizedTest @LdapServersSource(except = LdapServerType.Fedora389ds, reason = "Only secure binds configured for 389ds") public void testCreateConnectionNoEncryptionSaslDigestMd5ConfidentialityRequired( TestLdapServer server ) { setConnectionParameters( server, EncryptionMethod.NONE ); wizardBot.selectDigestMD5Authentication(); wizardBot.typeUser( "user.1" ); wizardBot.typePassword( "password" ); wizardBot.selectQualityOfProtection( SaslQoP.AUTH ); wizardBot.selectProtectionStrength( SaslSecurityStrength.HIGH ); server.setConfidentialityRequired( true ); finishAndAssertConnectionError( "[LDAP result code 13 - confidentialityRequired]" ); } @ParameterizedTest @LdapServersSource(except = LdapServerType.ApacheDS, reason = "Missing OSGi import: org.apache.directory.server.kerberos.shared.store.PrincipalStoreEntryModifier cannot be found by org.apache.directory.server.protocol.shared_2.0.0.AM26") public void testCreateConnectionNoEncryptionSaslGssapiNativeTgtAuthOK( TestLdapServer server ) throws Exception { TestFixture.skipIfKdcServerIsNotAvailable(); // obtain native TGT String[] cmd = { "/bin/sh", "-c", "echo secret | /usr/bin/kinit hnelson" }; Process process = Runtime.getRuntime().exec( cmd ); int exitCode = process.waitFor(); assertEquals( 0, exitCode ); setConnectionParameters( server, EncryptionMethod.NONE ); wizardBot.selectGssApiAuthentication(); wizardBot.selectQualityOfProtection( SaslQoP.AUTH ); wizardBot.selectProtectionStrength( SaslSecurityStrength.HIGH ); wizardBot.selectUseNativeTgt(); wizardBot.selectUseNativeSystemConfiguration(); String result = wizardBot.clickCheckAuthenticationButton(); assertNull( result, "Expected OK" ); finishAndAssertConnection( server, EncryptionMethod.NONE, AuthenticationMethod.SASL_GSSAPI, "", "" ); } @ParameterizedTest @LdapServersSource(except = LdapServerType.ApacheDS, reason = "Missing OSGi import: org.apache.directory.server.kerberos.shared.store.PrincipalStoreEntryModifier cannot be found by org.apache.directory.server.protocol.shared_2.0.0.AM26") public void testCreateConnectionNoEncryptionSaslGssapiNativeTgtAuthConfOK( TestLdapServer server ) throws Exception { TestFixture.skipIfKdcServerIsNotAvailable(); // Configure OpenLDAP with ssf=128 (128 allows RC4, Blowfish and other modern strong ciphers) if ( server instanceof OpenLdapServer ) { OpenLdapServer openLdapServer = ( OpenLdapServer ) server; openLdapServer.setSecurityProps( 128, 0 ); } // obtain native TGT String[] cmd = { "/bin/sh", "-c", "echo secret | /usr/bin/kinit hnelson" }; Process process = Runtime.getRuntime().exec( cmd ); int exitCode = process.waitFor(); assertEquals( 0, exitCode ); setConnectionParameters( server, EncryptionMethod.NONE ); wizardBot.selectGssApiAuthentication(); wizardBot.selectQualityOfProtection( SaslQoP.AUTH_CONF ); wizardBot.selectProtectionStrength( SaslSecurityStrength.HIGH ); wizardBot.selectUseNativeTgt(); wizardBot.selectUseNativeSystemConfiguration(); String result = wizardBot.clickCheckAuthenticationButton(); assertNull( result, "Expected OK" ); finishAndAssertConnection( server, EncryptionMethod.NONE, AuthenticationMethod.SASL_GSSAPI, "", "" ); } @ParameterizedTest @LdapServersSource(except = LdapServerType.ApacheDS, reason = "Missing OSGi import: org.apache.directory.server.kerberos.shared.store.PrincipalStoreEntryModifier cannot be found by org.apache.directory.server.protocol.shared_2.0.0.AM26") public void testCreateConnectionNoEncryptionSaslGssapiObtainAuthOK( TestLdapServer server ) { TestFixture.skipIfKdcServerIsNotAvailable(); setConnectionParameters( server, EncryptionMethod.NONE ); wizardBot.selectGssApiAuthentication(); wizardBot.selectObtainTgtFromKdc(); wizardBot.typeUser( "hnelson" ); wizardBot.typePassword( "secret" ); wizardBot.selectQualityOfProtection( SaslQoP.AUTH ); wizardBot.selectProtectionStrength( SaslSecurityStrength.HIGH ); String result = wizardBot.clickCheckAuthenticationButton(); assertNull( result, "Expected OK" ); finishAndAssertConnection( server, EncryptionMethod.NONE, AuthenticationMethod.SASL_GSSAPI, "hnelson", "secret" ); } @ParameterizedTest @LdapServersSource(except = LdapServerType.ApacheDS, reason = "Missing OSGi import: org.apache.directory.server.kerberos.shared.store.PrincipalStoreEntryModifier cannot be found by org.apache.directory.server.protocol.shared_2.0.0.AM26") public void testCreateConnectionNoEncryptionSaslGssapiObtainAuthConfOK( TestLdapServer server ) { TestFixture.skipIfKdcServerIsNotAvailable(); // Configure OpenLDAP with ssf=128 (128 allows RC4, Blowfish and other modern strong ciphers) if ( server instanceof OpenLdapServer ) { OpenLdapServer openLdapServer = ( OpenLdapServer ) server; openLdapServer.setSecurityProps( 128, 0 ); } setConnectionParameters( server, EncryptionMethod.NONE ); wizardBot.selectGssApiAuthentication(); wizardBot.selectObtainTgtFromKdc(); wizardBot.typeUser( "hnelson" ); wizardBot.typePassword( "secret" ); wizardBot.selectQualityOfProtection( SaslQoP.AUTH_CONF ); wizardBot.selectProtectionStrength( SaslSecurityStrength.HIGH ); String result = wizardBot.clickCheckAuthenticationButton(); assertNull( result, "Expected OK" ); finishAndAssertConnection( server, EncryptionMethod.NONE, AuthenticationMethod.SASL_GSSAPI, "hnelson", "secret" ); } @ParameterizedTest @LdapServersSource public void testCreateConnectionLdapsEncryptionNoAuthOK( TestLdapServer server ) { setConnectionParameters( server, EncryptionMethod.LDAPS ); wizardBot.selectNoAuthentication(); finishAndAssertConnection( server, EncryptionMethod.LDAPS, AuthenticationMethod.NONE, "", "" ); } @ParameterizedTest @LdapServersSource public void testCreateConnectionLdapsEncryptionSimpleAuthOK( TestLdapServer server ) { setConnectionParameters( server, EncryptionMethod.LDAPS ); wizardBot.typeUser( server.getAdminDn() ); wizardBot.typePassword( server.getAdminPassword() ); finishAndAssertConnection( server, EncryptionMethod.LDAPS, AuthenticationMethod.SIMPLE, server.getAdminDn(), server.getAdminPassword() ); } @ParameterizedTest @LdapServersSource(mode = Mode.All) public void testCreateConnectionLdapsEncryptionSimpleAuthInvalidCredentials( TestLdapServer server ) { setConnectionParameters( server, EncryptionMethod.LDAPS ); wizardBot.selectSimpleAuthentication(); wizardBot.typeUser( "cn=invalid" ); wizardBot.typePassword( "invalid" ); String result = wizardBot.clickCheckAuthenticationButton(); assertThat( result, containsString( "[LDAP result code 49 - invalidCredentials]" ) ); finishAndAssertConnectionError( "[LDAP result code 49 - invalidCredentials]" ); } @ParameterizedTest @LdapServersSource public void testCreateConnectionLdapsEncryptionSaslDigestMd5AuthOk( TestLdapServer server ) { setConnectionParameters( server, EncryptionMethod.LDAPS ); wizardBot.selectDigestMD5Authentication(); wizardBot.typeUser( "user.1" ); wizardBot.typePassword( "password" ); wizardBot.selectQualityOfProtection( SaslQoP.AUTH ); wizardBot.selectProtectionStrength( SaslSecurityStrength.HIGH ); finishAndAssertConnection( server, EncryptionMethod.LDAPS, AuthenticationMethod.SASL_DIGEST_MD5, "user.1", "password" ); } @ParameterizedTest @LdapServersSource(except = LdapServerType.ApacheDS, reason = "Bug in SASL filter in ApacheDS 2.0.0.M26.") public void testCreateConnectionLdapsEncryptionSaslDigestMd5AuthIntOk( TestLdapServer server ) { setConnectionParameters( server, EncryptionMethod.LDAPS ); wizardBot.selectDigestMD5Authentication(); wizardBot.typeUser( "user.1" ); wizardBot.typePassword( "password" ); if ( server.getType() == LdapServerType.ApacheDS ) { wizardBot.typeRealm( "EXAMPLE.ORG" ); } wizardBot.selectQualityOfProtection( SaslQoP.AUTH_INT );
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
true
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/tests/test.integration.ui/src/main/java/org/apache/directory/studio/test/integration/ui/ImportExportTest.java
tests/test.integration.ui/src/main/java/org/apache/directory/studio/test/integration/ui/ImportExportTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.studio.test.integration.ui; import static org.apache.directory.studio.test.integration.junit5.TestFixture.ALIAS_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.GERMAN_UMLAUT_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.MISC111_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.MISC_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.REFERRAL_TO_USER1_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.SUBENTRY_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.USER1_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.USER2_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.USERS_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.dn; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.io.IOException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.function.Supplier; import org.apache.directory.api.ldap.model.entry.DefaultEntry; import org.apache.directory.api.ldap.model.message.SearchScope; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.api.util.FileUtils; import org.apache.directory.server.core.api.DirectoryService; import org.apache.directory.server.core.api.partition.Partition; import org.apache.directory.server.core.partition.impl.avl.AvlPartition; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.Connection.AliasDereferencingMethod; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreConstants; import org.apache.directory.studio.ldapbrowser.core.BrowserCorePlugin; import org.apache.directory.studio.ldapbrowser.core.events.EventRegistry; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.test.integration.junit5.ApacheDirectoryServer; import org.apache.directory.studio.test.integration.junit5.LdapServerType; import org.apache.directory.studio.test.integration.junit5.LdapServersSource; import org.apache.directory.studio.test.integration.junit5.TestLdapServer; import org.apache.directory.studio.test.integration.junit5.LdapServersSource.Mode; import org.apache.directory.studio.test.integration.ui.bots.BotUtils; import org.apache.directory.studio.test.integration.ui.bots.DeleteDialogBot; import org.apache.directory.studio.test.integration.ui.bots.EntryEditorBot; import org.apache.directory.studio.test.integration.ui.bots.ExportWizardBot; import org.apache.directory.studio.test.integration.ui.bots.ImportWizardBot; import org.apache.directory.studio.test.integration.ui.utils.Characters; import org.apache.directory.studio.test.integration.ui.utils.ResourceUtils; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Preferences; import org.junit.jupiter.params.ParameterizedTest; /** * Tests the import and export (LDIF, DSML). * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> * @version $Rev$, $Date$ */ public class ImportExportTest extends AbstractTestBase { /** * Test for DIRSTUDIO-395. * * <li>export an entry with German umlaut in DN to LDIF</li> <li>verify that * exported LDIF starts with the Base64 encoded DN</li> <li>delete the entry * </li> <li>import the exported LDIF</li> <li>verify that entry with umlaut * exists</li> * * @throws Exception * the exception */ @ParameterizedTest @LdapServersSource public void testExportImportLdifWithGermanUmlautInDN( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); URL url = Platform.getInstanceLocation().getURL(); final String file = url.getFile() + "ImportExportWithGermanUmlautInDnTest" + server.getType().name() + ".ldif"; browserViewBot.selectEntry( path( GERMAN_UMLAUT_DN ) ); // export LDIF ExportWizardBot wizardBot = browserViewBot.openExportLdifWizard(); assertTrue( wizardBot.isVisible() ); wizardBot.clickNextButton(); wizardBot.typeFile( file ); wizardBot.clickFinishButton(); wizardBot.waitTillExportFinished( file, 200 ); // is actually 217 bytes List<String> lines = FileUtils.readLines( new File( file ), StandardCharsets.UTF_8 ); // verify that the first line of exported LDIF is "version: 1" assertEquals( lines.get( 0 ), "version: 1", "LDIF must start with version: 1" ); // verify that the third line of exported LDIF is the Base64 encoded DN assertEquals( lines.get( 2 ), "dn:: Y249V29sZmdhbmcgS8O2bGJlbCxvdT1taXNjLGRjPWV4YW1wbGUsZGM9b3Jn", "Expected Base64 encoded DN" ); // delete entry DeleteDialogBot dialogBot = browserViewBot.openDeleteDialog(); assertTrue( dialogBot.isVisible() ); dialogBot.clickOkButton(); assertFalse( browserViewBot.existsEntry( path( GERMAN_UMLAUT_DN ) ) ); // import LDIF ImportWizardBot importWizardBot = browserViewBot.openImportLdifWizard(); importWizardBot.typeFile( file ); importWizardBot.clickFinishButton(); // verify that entry with umlaut exists assertTrue( browserViewBot.existsEntry( path( GERMAN_UMLAUT_DN ) ) ); browserViewBot.selectEntry( path( GERMAN_UMLAUT_DN ) ); } /** * Test for DIRSTUDIO-395. * * <li>export an entry with German umlaut in DN to DSML</li> <li>verify that * exported DSML starts with the Base64 encoded DN</li> <li>delete the entry * </li> <li>import the exported DSML</li> <li>verify that entry with umlaut * exists</li> * * @throws Exception * the exception */ @ParameterizedTest @LdapServersSource public void testExportImportDsmlWithGermanUmlautInDN( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); URL url = Platform.getInstanceLocation().getURL(); final String file = url.getFile() + "ImportExportWithGermanUmlautInDnTest" + server.getType().name() + ".dsml"; browserViewBot.selectEntry( path( GERMAN_UMLAUT_DN ) ); // export DSML ExportWizardBot wizardBot = browserViewBot.openExportDsmlWizard(); assertTrue( wizardBot.isVisible() ); wizardBot.clickNextButton(); wizardBot.typeFile( file ); wizardBot.selectDsmlRequest(); wizardBot.clickFinishButton(); wizardBot.waitTillExportFinished( file, 500 ); // is actually 542 bytes // verify that exported DSML contains the Base64 encoded DN String content = FileUtils.readFileToString( new File( file ), StandardCharsets.UTF_8 ); assertTrue( content.contains( "dn=\"" + GERMAN_UMLAUT_DN.getName() + "\"" ), "DSML must contain DN with umlaut." ); // delete entry DeleteDialogBot dialogBot = browserViewBot.openDeleteDialog(); assertTrue( dialogBot.isVisible() ); dialogBot.clickOkButton(); assertFalse( browserViewBot.existsEntry( path( GERMAN_UMLAUT_DN ) ) ); // import DSML ImportWizardBot importWizardBot = browserViewBot.openImportDsmlWizard(); importWizardBot.typeFile( file ); importWizardBot.clickFinishButton(); // verify that entry with umlaut exists assertTrue( browserViewBot.existsEntry( path( GERMAN_UMLAUT_DN ) ) ); browserViewBot.selectEntry( path( GERMAN_UMLAUT_DN ) ); } @ParameterizedTest @LdapServersSource public void testExportImportLdifAlias( TestLdapServer server ) throws Exception { Connection connection = connectionsViewBot.createTestConnection( server ); // disable alias dereferencing connection.getConnectionParameter().setExtendedIntProperty( IBrowserConnection.CONNECTION_PARAMETER_ALIASES_DEREFERENCING_METHOD, AliasDereferencingMethod.NEVER.ordinal() ); URL url = Platform.getInstanceLocation().getURL(); final String file = url.getFile() + "ImportExportAlias" + server.getType().name() + ".ldif"; browserViewBot.selectEntry( path( ALIAS_DN.getParent() ) ); // export to LDIF ExportWizardBot wizardBot = browserViewBot.openExportLdifWizard(); assertTrue( wizardBot.isVisible() ); wizardBot.setFilter( "(objectClass=alias)" ); wizardBot.setScope( SearchScope.ONELEVEL ); wizardBot.setAliasDereferencingMode( AliasDereferencingMethod.NEVER ); wizardBot.clickNextButton(); wizardBot.typeFile( file ); wizardBot.clickFinishButton(); wizardBot.waitTillExportFinished( file, 50 ); List<String> lines = FileUtils.readLines( new File( file ), StandardCharsets.UTF_8 ); assertEquals( lines.get( 0 ), "version: 1", "LDIF must start with version: 1" ); assertTrue( lines.contains( "dn: " + ALIAS_DN.getName() ) ); // delete entry browserViewBot.selectEntry( path( ALIAS_DN ) ); DeleteDialogBot dialogBot = browserViewBot.openDeleteDialog(); assertTrue( dialogBot.isVisible() ); dialogBot.clickOkButton(); waitAndAssert( false, () -> browserViewBot.existsEntry( path( ALIAS_DN ) ) ); // import LDIF ImportWizardBot importWizardBot = browserViewBot.openImportLdifWizard(); importWizardBot.typeFile( file ); importWizardBot.clickFinishButton(); // verify that entry exist assertTrue( browserViewBot.existsEntry( path( ALIAS_DN ) ) ); } @ParameterizedTest @LdapServersSource public void testExportImportLdifReferral( TestLdapServer server ) throws Exception { Connection connection = connectionsViewBot.createTestConnection( server ); // enable ManageDsaIT control connection.getConnectionParameter().setExtendedBoolProperty( IBrowserConnection.CONNECTION_PARAMETER_MANAGE_DSA_IT, true ); URL url = Platform.getInstanceLocation().getURL(); final String file = url.getFile() + "ImportExportReferral" + server.getType().name() + ".ldif"; browserViewBot.selectEntry( path( REFERRAL_TO_USER1_DN.getParent() ) ); // export to LDIF ExportWizardBot wizardBot = browserViewBot.openExportLdifWizard(); assertTrue( wizardBot.isVisible() ); wizardBot.setFilter( "(" + REFERRAL_TO_USER1_DN.getRdn().getName() + ")" ); wizardBot.setReturningAttributes( "ref" ); wizardBot.setScope( SearchScope.ONELEVEL ); wizardBot.setControlManageDsaIT( true ); wizardBot.clickNextButton(); wizardBot.typeFile( file ); wizardBot.clickFinishButton(); wizardBot.waitTillExportFinished( file, 20 ); List<String> lines = FileUtils.readLines( new File( file ), StandardCharsets.UTF_8 ); assertEquals( lines.get( 0 ), "version: 1", "LDIF must start with version: 1" ); assertTrue( lines.contains( "dn: " + REFERRAL_TO_USER1_DN.getName() ) ); assertTrue( lines.contains( "ref: " + server.getLdapUrl() + "/" + USER1_DN.getName() ) ); // delete entry browserViewBot.selectEntry( path( REFERRAL_TO_USER1_DN ) ); DeleteDialogBot dialogBot = browserViewBot.openDeleteDialog(); assertTrue( dialogBot.isVisible() ); dialogBot.clickOkButton(); waitAndAssert( false, () -> browserViewBot.existsEntry( path( REFERRAL_TO_USER1_DN ) ) ); // import LDIF ImportWizardBot importWizardBot = browserViewBot.openImportLdifWizard(); importWizardBot.typeFile( file ); importWizardBot.clickFinishButton(); // verify that entry exist assertTrue( browserViewBot.existsEntry( path( REFERRAL_TO_USER1_DN ) ) ); } @ParameterizedTest @LdapServersSource(only = LdapServerType.ApacheDS, reason = "ApacheDS specific test") public void testExportImportLdifSubentry( TestLdapServer server ) throws Exception { Connection connection = connectionsViewBot.createTestConnection( server ); // enable Subentries control connection.getConnectionParameter().setExtendedBoolProperty( IBrowserConnection.CONNECTION_PARAMETER_FETCH_SUBENTRIES, true ); URL url = Platform.getInstanceLocation().getURL(); final String file = url.getFile() + "ImportExportSubentry" + server.getType().name() + ".ldif"; browserViewBot.selectEntry( path( SUBENTRY_DN.getParent() ) ); // export to LDIF ExportWizardBot wizardBot = browserViewBot.openExportLdifWizard(); assertTrue( wizardBot.isVisible() ); wizardBot.setFilter( "(objectClass=subentry)" ); wizardBot.setReturningAttributes( "subtreeSpecification" ); wizardBot.setScope( SearchScope.ONELEVEL ); wizardBot.setControlSubentries( true ); wizardBot.clickNextButton(); wizardBot.typeFile( file ); wizardBot.clickFinishButton(); wizardBot.waitTillExportFinished( file, 20 ); List<String> lines = FileUtils.readLines( new File( file ), StandardCharsets.UTF_8 ); assertEquals( lines.get( 0 ), "version: 1", "LDIF must start with version: 1" ); assertTrue( lines.contains( "dn: " + SUBENTRY_DN.getName() ) ); assertTrue( lines.contains( "subtreeSpecification: {}" ) ); // delete entry browserViewBot.selectEntry( path( SUBENTRY_DN ) ); DeleteDialogBot dialogBot = browserViewBot.openDeleteDialog(); assertTrue( dialogBot.isVisible() ); dialogBot.clickOkButton(); waitAndAssert( false, () -> browserViewBot.existsEntry( path( SUBENTRY_DN ) ) ); // import LDIF ImportWizardBot importWizardBot = browserViewBot.openImportLdifWizard(); importWizardBot.typeFile( file ); importWizardBot.clickFinishButton(); // verify that entry exist assertTrue( browserViewBot.existsEntry( path( SUBENTRY_DN ) ) ); } @ParameterizedTest @LdapServersSource public void testExportImportDsmlAlias( TestLdapServer server ) throws Exception { Connection connection = connectionsViewBot.createTestConnection( server ); // disable alias dereferencing connection.getConnectionParameter().setExtendedIntProperty( IBrowserConnection.CONNECTION_PARAMETER_ALIASES_DEREFERENCING_METHOD, AliasDereferencingMethod.NEVER.ordinal() ); URL url = Platform.getInstanceLocation().getURL(); final String file = url.getFile() + "ImportExportAlias" + server.getType().name() + ".dsml"; browserViewBot.selectEntry( path( ALIAS_DN.getParent() ) ); // export to DSML ExportWizardBot wizardBot = browserViewBot.openExportDsmlWizard(); assertTrue( wizardBot.isVisible() ); wizardBot.setFilter( "(objectClass=alias)" ); wizardBot.setScope( SearchScope.ONELEVEL ); wizardBot.setAliasDereferencingMode( AliasDereferencingMethod.NEVER ); wizardBot.clickNextButton(); wizardBot.typeFile( file ); wizardBot.selectDsmlRequest(); wizardBot.clickFinishButton(); wizardBot.waitTillExportFinished( file, 50 ); // verify that exported DSML contains the entry String content = FileUtils.readFileToString( new File( file ), StandardCharsets.UTF_8 ); assertTrue( content.contains( "dn=\"" + ALIAS_DN.getName() + "\"" ) ); // delete entry browserViewBot.selectEntry( path( ALIAS_DN ) ); DeleteDialogBot dialogBot = browserViewBot.openDeleteDialog(); assertTrue( dialogBot.isVisible() ); dialogBot.clickOkButton(); waitAndAssert( false, () -> browserViewBot.existsEntry( path( ALIAS_DN ) ) ); // import DSML ImportWizardBot importWizardBot = browserViewBot.openImportDsmlWizard(); importWizardBot.typeFile( file ); importWizardBot.clickFinishButton(); // verify that entry exist assertTrue( browserViewBot.existsEntry( path( ALIAS_DN ) ) ); } @ParameterizedTest @LdapServersSource public void testExportImportDsmlReferral( TestLdapServer server ) throws Exception { Connection connection = connectionsViewBot.createTestConnection( server ); // enable ManageDsaIT control connection.getConnectionParameter().setExtendedBoolProperty( IBrowserConnection.CONNECTION_PARAMETER_MANAGE_DSA_IT, true ); URL url = Platform.getInstanceLocation().getURL(); final String file = url.getFile() + "ImportExportReferral" + server.getType().name() + ".dsml"; browserViewBot.selectEntry( path( REFERRAL_TO_USER1_DN.getParent() ) ); // export to DSML ExportWizardBot wizardBot = browserViewBot.openExportDsmlWizard(); assertTrue( wizardBot.isVisible() ); wizardBot.setFilter( "(" + REFERRAL_TO_USER1_DN.getRdn().getName() + ")" ); wizardBot.setReturningAttributes( "ref" ); wizardBot.setScope( SearchScope.ONELEVEL ); wizardBot.setControlManageDsaIT( true ); wizardBot.clickNextButton(); wizardBot.typeFile( file ); wizardBot.selectDsmlRequest(); wizardBot.clickFinishButton(); wizardBot.waitTillExportFinished( file, 50 ); // verify that exported DSML contains the entry String content = FileUtils.readFileToString( new File( file ), StandardCharsets.UTF_8 ); assertTrue( content.contains( "dn=\"" + REFERRAL_TO_USER1_DN.getName() + "\"" ) ); assertTrue( content.contains( "<attr name=\"ref\">" ) ); assertTrue( content.contains( "<value>" + server.getLdapUrl() + "/" + USER1_DN.getName() + "</value>" ) ); // delete entry browserViewBot.selectEntry( path( REFERRAL_TO_USER1_DN ) ); DeleteDialogBot dialogBot = browserViewBot.openDeleteDialog(); assertTrue( dialogBot.isVisible() ); dialogBot.clickOkButton(); waitAndAssert( false, () -> browserViewBot.existsEntry( path( REFERRAL_TO_USER1_DN ) ) ); // import DSML ImportWizardBot importWizardBot = browserViewBot.openImportDsmlWizard(); importWizardBot.typeFile( file ); importWizardBot.clickFinishButton(); // verify that entry exist assertTrue( browserViewBot.existsEntry( path( REFERRAL_TO_USER1_DN ) ) ); } @ParameterizedTest @LdapServersSource(only = LdapServerType.ApacheDS, reason = "ApacheDS specific test") public void testExportImportDsmlSubentry( TestLdapServer server ) throws Exception { Connection connection = connectionsViewBot.createTestConnection( server ); // enable Subentries control connection.getConnectionParameter().setExtendedBoolProperty( IBrowserConnection.CONNECTION_PARAMETER_FETCH_SUBENTRIES, true ); URL url = Platform.getInstanceLocation().getURL(); final String file = url.getFile() + "ImportExportSubentry" + server.getType().name() + ".dsml"; browserViewBot.selectEntry( path( SUBENTRY_DN.getParent() ) ); // export to DSML ExportWizardBot wizardBot = browserViewBot.openExportDsmlWizard(); assertTrue( wizardBot.isVisible() ); wizardBot.setFilter( "(objectClass=subentry)" ); wizardBot.setReturningAttributes( "subtreeSpecification" ); wizardBot.setScope( SearchScope.ONELEVEL ); wizardBot.setControlSubentries( true ); wizardBot.clickNextButton(); wizardBot.typeFile( file ); wizardBot.selectDsmlRequest(); wizardBot.clickFinishButton(); wizardBot.waitTillExportFinished( file, 50 ); // verify that exported DSML String content = FileUtils.readFileToString( new File( file ), StandardCharsets.UTF_8 ); assertTrue( content.contains( "dn=\"" + SUBENTRY_DN.getName() + "\"" ) ); assertTrue( content.contains( "<attr name=\"subtreespecification\">" ) ); assertTrue( content.contains( "<value>{}</value>" ) ); // delete entry browserViewBot.selectEntry( path( SUBENTRY_DN ) ); DeleteDialogBot dialogBot = browserViewBot.openDeleteDialog(); assertTrue( dialogBot.isVisible() ); dialogBot.clickOkButton(); waitAndAssert( false, () -> browserViewBot.existsEntry( path( SUBENTRY_DN ) ) ); // import DSML ImportWizardBot importWizardBot = browserViewBot.openImportDsmlWizard(); importWizardBot.typeFile( file ); importWizardBot.clickFinishButton(); // verify that entry exist assertTrue( browserViewBot.existsEntry( path( SUBENTRY_DN ) ) ); } private void waitAndAssert( boolean expectedResult, Supplier<Boolean> fn ) { for ( int i = 0; i < 30; i++ ) { if ( fn.get() == expectedResult ) { break; } BotUtils.sleep( 1000L ); } if ( expectedResult == true ) { assertTrue( fn.get() ); } else { assertFalse( fn.get() ); } } @ParameterizedTest @LdapServersSource(only = LdapServerType.ApacheDS, reason = "ApacheDS specific test") public void testExportWithPagedResultControl( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); URL url = Platform.getInstanceLocation().getURL(); final String file = url.getFile() + "ExportWithPagedResultControl.ldif"; browserViewBot.selectEntry( "DIT", "Root DSE", "ou=schema" ); // export LDIF ExportWizardBot wizardBot = browserViewBot.openExportLdifWizard(); assertTrue( wizardBot.isVisible() ); wizardBot.setScope( SearchScope.ONELEVEL ); wizardBot.setControlPagedSearch( true, 17, true ); wizardBot.clickNextButton(); wizardBot.typeFile( file ); wizardBot.clickFinishButton(); wizardBot.waitTillExportFinished( file, 2500 ); List<String> lines = FileUtils.readLines( new File( file ), StandardCharsets.UTF_8 ); assertEquals( lines.get( 0 ), "version: 1", "LDIF must start with version: 1" ); assertTrue( lines.contains( "dn: cn=adsconfig,ou=schema" ) ); assertTrue( lines.contains( "dn: cn=apachemeta,ou=schema" ) ); assertTrue( lines.contains( "dn: cn=core,ou=schema" ) ); assertTrue( lines.contains( "dn: cn=rfc2307bis,ou=schema" ) ); assertTrue( lines.contains( "dn: cn=system,ou=schema" ) ); searchLogsViewBot.getSearchLogsText().contains( "# numEntries : 17" ); searchLogsViewBot.getSearchLogsText().contains( "# control : 1.2.840.113556.1.4.319" ); } /** * Test for DIRSTUDIO-465. * * Import a new context entry must refresh the root DSE and * show the new context entry in the LDAP Browser view. */ @ParameterizedTest @LdapServersSource(only = LdapServerType.ApacheDS, reason = "ApacheDS specific test") public void testImportContextEntryRefreshesRootDSE( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); // add a new partition ApacheDirectoryServer apacheds = ( ApacheDirectoryServer ) server; DirectoryService service = apacheds.getService(); Partition partition = new AvlPartition( service.getSchemaManager(), service.getDnFactory() ); partition.setId( "example" ); partition.setSuffixDn( new Dn( "dc=example,dc=com" ) ); service.addPartition( partition ); // refresh root DSE and ensure that the partition is in root DSE browserViewBot.selectEntry( "DIT", "Root DSE" ); browserViewBot.refresh(); // ensure context entry is not there assertFalse( browserViewBot.existsEntry( "DIT", "Root DSE", "dc=example,dc=com" ) ); // import URL url = Platform.getInstanceLocation().getURL(); String file = url.getFile() + "ImportContextEntry.ldif"; String data = "dn:dc=example,dc=com\nobjectClass:top\nobjectClass:domain\ndc:example\n\n"; FileUtils.writeStringToFile( new File( file ), data, StandardCharsets.UTF_8, false ); ImportWizardBot importWizardBot = browserViewBot.openImportLdifWizard(); importWizardBot.typeFile( file ); importWizardBot.clickFinishButton(); // ensure context entry is there now, without a manual refresh assertTrue( browserViewBot.existsEntry( "DIT", "Root DSE", "dc=example,dc=com" ) ); browserViewBot.selectEntry( "DIT", "Root DSE", "dc=example,dc=com" ); } /** * Test for DIRSTUDIO-489. * * Verify that there are no UI updates when importing an LDIF. */ @ParameterizedTest @LdapServersSource public void testImportDoesNotUpdateUI( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); browserViewBot.selectEntry( path( MISC111_DN ) ); browserViewBot.expandEntry( path( MISC111_DN ) ); long fireCount0 = EventRegistry.getFireCount(); // import the LDIF String file = prepareInputFile( "ImportExportTest_User1to8.ldif" ); ImportWizardBot importWizardBot = browserViewBot.openImportLdifWizard(); importWizardBot.typeFile( file ); importWizardBot.clickFinishButton(); browserViewBot.waitForEntry( path( MISC111_DN, "uid=User.1" ) ); browserViewBot.selectEntry( path( MISC111_DN, "uid=User.1" ) ); long fireCount1 = EventRegistry.getFireCount(); // verify that only three two events were fired between Import long fireCount = fireCount1 - fireCount0; assertEquals( 2, fireCount, "Only 2 event firings expected when importing LDIF." ); } /** * Export to CSV and checks that spreadsheet formulas are prefixed with an apostrophe. */ @ParameterizedTest @LdapServersSource public void testExportCsvShouldPrefixFormulaWithApostrophe( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); // set CSV encoding explicit to UTF-8, otherwise platform default encoding would be used Preferences store = BrowserCorePlugin.getDefault().getPluginPreferences(); store.setDefault( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_ENCODING, "UTF-8" ); URL url = Platform.getInstanceLocation().getURL(); final String file = url.getFile() + "ImportExportShouldPrefixFormulaWithApostropheTest" + server.getType().name() + ".csv"; browserViewBot.selectEntry( path( GERMAN_UMLAUT_DN ) ); // export CSV ExportWizardBot wizardBot = browserViewBot.openExportCsvWizard(); assertTrue( wizardBot.isVisible() ); wizardBot.setReturningAttributes( "cn, description" ); wizardBot.clickNextButton(); wizardBot.typeFile( file ); wizardBot.clickFinishButton(); wizardBot.waitTillExportFinished( file, 80 ); // is actually 86 bytes List<String> lines = FileUtils.readLines( new File( file ), StandardCharsets.UTF_8 ); // verify that the first line is header assertEquals( "dn,cn,description", lines.get( 0 ) ); // verify that the second line is actual content and the formula is prefixed with an apostrophe assertEquals( "\"" + GERMAN_UMLAUT_DN.getName() + "\",\"Wolfgang K\u00f6lbel\",\"'=1+1\"", lines.get( 1 ) ); } /** * Export to CSV and checks that RFC 4517 Postal Address syntax is decoded. */ @ParameterizedTest @LdapServersSource public void testExportCsvShouldDecodePostalAddress( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); // set CSV encoding explicit to UTF-8, otherwise platform default encoding would be used Preferences store = BrowserCorePlugin.getDefault().getPluginPreferences(); store.setDefault( BrowserCoreConstants.PREFERENCE_FORMAT_CSV_ENCODING, "UTF-8" ); URL url = Platform.getInstanceLocation().getURL(); final String file = url.getFile() + "ImportExportShouldDecodePostalAddressTest" + server.getType().name() + ".csv"; browserViewBot.selectEntry( path( USER1_DN ) ); // export CSV ExportWizardBot wizardBot = browserViewBot.openExportCsvWizard(); assertTrue( wizardBot.isVisible() ); wizardBot.setReturningAttributes( "postalAddress" ); wizardBot.clickNextButton(); wizardBot.typeFile( file ); wizardBot.clickFinishButton(); wizardBot.waitTillExportFinished( file, 100 ); List<String> lines = FileUtils.readLines( new File( file ), StandardCharsets.UTF_8 ); // verify that the first line is header assertEquals( "dn,postalAddress", lines.get( 0 ) ); // verify that the postal address is broken into several lines assertEquals( "\"uid=user.1,ou=users,dc=example,dc=org\",\"Aaccf Amar", lines.get( 1 ) ); assertEquals( "27919 Broadway Street", lines.get( 2 ) ); assertEquals( "Tallahassee, DE 67698\"", lines.get( 3 ) ); } /** * Test for DIRSTUDIO-1160. * * Attributes silently dropped and not imported when import LDIF and provider is Apache Directory LDAP API. */ @ParameterizedTest @LdapServersSource public void testDIRSTUDIO_1160( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); Dn dn = dn( "cn=U0034692", MISC_DN ); // import the LDIF String file = prepareInputFile( "DIRSTUDIO-1160.ldif" ); ImportWizardBot importWizardBot = browserViewBot.openImportLdifWizard(); importWizardBot.typeFile( file ); importWizardBot.clickFinishButton(); browserViewBot.waitForEntry( path( dn ) ); browserViewBot.selectEntry( path( dn ) ); EntryEditorBot entryEditorBot = studioBot.getEntryEditorBot( dn.getName() ); entryEditorBot.activate(); assertTrue( entryEditorBot.getAttributeValues().contains( "description: Initial import" ) ); assertTrue( entryEditorBot.getAttributeValues().contains( "description: Good#Stuff" ) ); assertTrue( entryEditorBot.getAttributeValues().contains( "description: account#oldUserID#ABC123" ) ); assertTrue( entryEditorBot.getAttributeValues() .contains( "description: person#homeEmailAddress#jhon.doe@apache.com" ) ); assertTrue( entryEditorBot.getAttributeValues().contains( "description: Th\u00f6is \u00e5s a t\u00e4st yes" ) ); } /** * Test LDIF with several modifications. */ @ParameterizedTest @LdapServersSource(mode = Mode.All) public void testLdifModification( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); // import the LDIF String file = prepareInputFile( "ImportExportTest_Modifications.ldif" ); ImportWizardBot importWizardBot = browserViewBot.openImportLdifWizard(); importWizardBot.typeFile( file );
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
true
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/tests/test.integration.ui/src/main/java/org/apache/directory/studio/test/integration/ui/RcpAppTest.java
tests/test.integration.ui/src/main/java/org/apache/directory/studio/test/integration/ui/RcpAppTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.studio.test.integration.ui; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.directory.studio.test.integration.ui.bots.ExportWizardBot; import org.apache.directory.studio.test.integration.ui.bots.ImportWizardBot; import org.apache.directory.studio.test.integration.ui.bots.NewWizardBot; import org.apache.directory.studio.test.integration.ui.bots.PreferencesBot; import org.apache.directory.studio.test.integration.ui.bots.ShowViewsBot; import org.junit.jupiter.api.Test; /** * General tests of the Studio RCP application: layout of perspectives, visible menu items, etc. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> * @version $Rev$, $Date$ */ public class RcpAppTest extends AbstractTestBase { /** * Verify views in LDAP perspective. */ @Test public void testLdapPerspectiveViews() throws Exception { studioBot.resetLdapPerspective(); assertNotNull( bot.viewByTitle( "LDAP Browser" ) ); assertNotNull( bot.viewByTitle( "LDAP Servers" ) ); assertNotNull( bot.viewByTitle( "Connections" ) ); assertNotNull( bot.viewByTitle( "Outline" ) ); assertNotNull( bot.viewByTitle( "Progress" ) ); assertNotNull( bot.viewByTitle( "Modification Logs" ) ); assertNotNull( bot.viewByTitle( "Search Logs" ) ); assertNotNull( bot.viewByTitle( "Error Log" ) ); } /** * Verify views in Schema Editor perspective. */ @Test public void testSchemaEditorPerspectiveViews() throws Exception { studioBot.resetSchemaPerspective(); assertNotNull( bot.viewByTitle( "Schema" ) ); assertNotNull( bot.viewByTitle( "Hierarchy" ) ); assertNotNull( bot.viewByTitle( "Projects" ) ); assertNotNull( bot.viewByTitle( "Problems" ) ); assertNotNull( bot.viewByTitle( "Search" ) ); } /** * Verify visible items in 'Show Views' dialog. */ @Test public void testVisibleItemsInOpenViewsDialog() throws Exception { ShowViewsBot showViews = studioBot.openShowViews(); assertTrue( showViews.existsView( "General", "Console" ) ); assertTrue( showViews.existsView( "General", "Console" ) ); assertTrue( showViews.existsView( "General", "Error Log" ) ); assertTrue( showViews.existsView( "General", "Outline" ) ); assertTrue( showViews.existsView( "General", "Progress" ) ); assertTrue( showViews.existsView( "Help", "Help" ) ); assertTrue( showViews.existsView( "LDAP Browser", "Connections" ) ); assertTrue( showViews.existsView( "LDAP Browser", "LDAP Browser" ) ); assertTrue( showViews.existsView( "LDAP Browser", "Modification Logs" ) ); assertTrue( showViews.existsView( "LDAP Browser", "Search Logs" ) ); assertTrue( showViews.existsView( "LDAP Servers", "LDAP Servers" ) ); assertTrue( showViews.existsView( "Schema Editor", "Hierarchy" ) ); assertTrue( showViews.existsView( "Schema Editor", "Problems" ) ); assertTrue( showViews.existsView( "Schema Editor", "Projects" ) ); assertTrue( showViews.existsView( "Schema Editor", "Schema" ) ); assertTrue( showViews.existsView( "Schema Editor", "Search" ) ); showViews.clickCancelButton(); } /** * Verify hidden items in 'Show Views' dialog. Many unwanted views are contributed * by org.eclipse.* plugins, we configured to hide them in rcp/plugin.xml. */ @Test public void testHiddenItemsInOpenViewsDialog() throws Exception { ShowViewsBot showViews = studioBot.openShowViews(); assertFalse( showViews.existsView( "General", "Bookmarks" ) ); assertFalse( showViews.existsView( "General", "Problems" ) ); assertFalse( showViews.existsView( "General", "Navigator" ) ); assertFalse( showViews.existsView( "General", "Project Explorer" ) ); assertFalse( showViews.existsView( "General", "Properties" ) ); showViews.clickCancelButton(); } /** * Verify visible items in 'New' wizard. */ @Test public void testVisibleItemsInNewWizard() throws Exception { NewWizardBot newWizard = studioBot.openNewWizard(); assertTrue( newWizard.existsWizard( "ApacheDS", "ApacheDS 2.0 Configuration File" ) ); assertTrue( newWizard.existsWizard( "LDAP Browser", "LDAP Connection" ) ); assertTrue( newWizard.existsWizard( "LDAP Browser", "LDAP Entry" ) ); assertTrue( newWizard.existsWizard( "LDAP Browser", "LDAP Search" ) ); assertTrue( newWizard.existsWizard( "LDAP Browser", "LDAP Bookmark" ) ); assertTrue( newWizard.existsWizard( "LDAP Browser", "LDIF File" ) ); assertTrue( newWizard.existsWizard( "Schema Editor", "New Schema Project" ) ); assertTrue( newWizard.existsWizard( "Schema Editor", "New Schema" ) ); assertTrue( newWizard.existsWizard( "Schema Editor", "New Object Class" ) ); assertTrue( newWizard.existsWizard( "Schema Editor", "New Attribute Type" ) ); newWizard.clickCancelButton(); } /** * Verify hidden items in 'New' wizard. Many unwanted wizards are contributed * by org.eclipse.* plugins, we configured to hide them in rcp/plugin.xml. */ @Test public void testHiddenItemsInNewWizard() throws Exception { NewWizardBot newWizard = studioBot.openNewWizard(); assertFalse( newWizard.existsWizard( "General", "File" ) ); assertFalse( newWizard.existsWizard( "General", "Folder" ) ); assertFalse( newWizard.existsWizard( "General", "Project" ) ); newWizard.clickCancelButton(); } /** * Verify visible items in 'Export' wizard. */ @Test public void testVisibleItemsInExportWizard() throws Exception { ExportWizardBot exportWizard = studioBot.openExportWizard(); assertTrue( exportWizard.existsWizard( "LDAP Browser", "LDAP to CSV" ) ); assertTrue( exportWizard.existsWizard( "LDAP Browser", "LDAP to DSML" ) ); assertTrue( exportWizard.existsWizard( "LDAP Browser", "LDAP to Excel" ) ); assertTrue( exportWizard.existsWizard( "LDAP Browser", "LDAP to LDIF" ) ); assertTrue( exportWizard.existsWizard( "LDAP Browser", "LDAP to ODF" ) ); assertTrue( exportWizard.existsWizard( "Schema Editor", "Schema Projects" ) ); assertTrue( exportWizard.existsWizard( "Schema Editor", "Schemas as OpenLDAP files" ) ); assertTrue( exportWizard.existsWizard( "Schema Editor", "Schemas as XML file(s)" ) ); assertTrue( exportWizard.existsWizard( "Schema Editor", "Schemas for ApacheDS" ) ); exportWizard.clickCancelButton(); } /** * Verify hidden items in 'Export' wizard. Many unwanted wizards are contributed * by org.eclipse.* plugins, we configured to hide them in rcp/plugin.xml. */ @Test public void testHiddenItemsInExportWizard() throws Exception { ExportWizardBot exportWizard = studioBot.openExportWizard(); assertFalse( exportWizard.existsWizard( "General", "Archive File" ) ); assertFalse( exportWizard.existsWizard( "General", "Filesystem" ) ); assertFalse( exportWizard.existsCategory( "Install" ) ); assertFalse( exportWizard.existsCategory( "Team" ) ); assertFalse( exportWizard.existsCategory( "Java" ) ); exportWizard.clickCancelButton(); } /** * Verify visible items in 'Import' wizard. */ @Test public void testVisibleItemsInImportWizard() throws Exception { ImportWizardBot importWizard = studioBot.openImportWizard(); assertTrue( importWizard.existsWizard( "LDAP Browser", "DSML into LDAP" ) ); assertTrue( importWizard.existsWizard( "LDAP Browser", "LDIF into LDAP" ) ); assertTrue( importWizard.existsWizard( "Schema Editor", "Core schemas files" ) ); assertTrue( importWizard.existsWizard( "Schema Editor", "Schema Projects" ) ); assertTrue( importWizard.existsWizard( "Schema Editor", "Schemas from OpenLDAP files" ) ); assertTrue( importWizard.existsWizard( "Schema Editor", "Schemas from XML file(s)" ) ); importWizard.clickCancelButton(); } /** * Verify hidden items in 'Import' wizard. Many unwanted wizards are contributed * by org.eclipse.* plugins, we configured to hide them in rcp/plugin.xml. */ @Test public void testHiddenItemsInImportWizard() throws Exception { ImportWizardBot importWizard = studioBot.openImportWizard(); assertFalse( importWizard.existsWizard( "General", "Archive File" ) ); assertFalse( importWizard.existsWizard( "General", "Filesystem" ) ); assertFalse( importWizard.existsCategory( "Install" ) ); assertFalse( importWizard.existsCategory( "Team" ) ); assertFalse( importWizard.existsCategory( "Java" ) ); assertFalse( importWizard.existsCategory( "Maven" ) ); assertFalse( importWizard.existsCategory( "Git" ) ); assertFalse( importWizard.existsCategory( "CSV" ) ); importWizard.clickCancelButton(); } /** * Verify visible preference pages. */ @Test public void testVisiblePreferencePages() throws Exception { PreferencesBot prefs = studioBot.openPreferences(); assertTrue( prefs.pageExists( "Apache Directory Studio" ) ); assertTrue( prefs.pageExists( "Apache Directory Studio", "Connections" ) ); assertTrue( prefs.pageExists( "Apache Directory Studio", "Connections", "Certificate Validation" ) ); assertTrue( prefs.pageExists( "Apache Directory Studio", "Connections", "Passwords Keystore" ) ); assertTrue( prefs.pageExists( "Apache Directory Studio", "LDAP Browser" ) ); assertTrue( prefs.pageExists( "Apache Directory Studio", "LDAP Browser", "Attributes" ) ); assertTrue( prefs.pageExists( "Apache Directory Studio", "LDAP Browser", "Attributes", "Binary Attributes" ) ); assertTrue( prefs.pageExists( "Apache Directory Studio", "LDAP Browser", "Entry Editors" ) ); assertTrue( prefs.pageExists( "Apache Directory Studio", "LDAP Browser", "Entry Editors", "Table Entry Editor" ) ); assertTrue( prefs.pageExists( "Apache Directory Studio", "LDAP Browser", "Search Result Editor" ) ); assertTrue( prefs.pageExists( "Apache Directory Studio", "LDAP Browser", "Text Formats" ) ); assertTrue( prefs.pageExists( "Apache Directory Studio", "LDAP Browser", "Value Editors" ) ); assertTrue( prefs.pageExists( "Apache Directory Studio", "LDAP Browser", "Views" ) ); assertTrue( prefs.pageExists( "Apache Directory Studio", "LDAP Browser", "Views", "Browser View" ) ); assertTrue( prefs.pageExists( "Apache Directory Studio", "LDAP Browser", "Views", "Modification Logs View" ) ); assertTrue( prefs.pageExists( "Apache Directory Studio", "LDAP Browser", "Views", "Search Logs View" ) ); assertTrue( prefs.pageExists( "Apache Directory Studio", "LDIF Editor" ) ); assertTrue( prefs.pageExists( "Apache Directory Studio", "LDIF Editor", "Content Assist" ) ); assertTrue( prefs.pageExists( "Apache Directory Studio", "LDIF Editor", "Syntax Coloring" ) ); assertTrue( prefs.pageExists( "Apache Directory Studio", "LDIF Editor", "Templates" ) ); assertTrue( prefs.pageExists( "Apache Directory Studio", "Schema Editor" ) ); assertTrue( prefs.pageExists( "Apache Directory Studio", "Schema Editor", "Hierarchy View" ) ); assertTrue( prefs.pageExists( "Apache Directory Studio", "Schema Editor", "Schema View" ) ); assertTrue( prefs.pageExists( "Apache Directory Studio", "Schema Editor", "Search View" ) ); assertTrue( prefs.pageExists( "Apache Directory Studio", "Shutdown" ) ); assertTrue( prefs.pageExists( "General", "Appearance" ) ); assertTrue( prefs.pageExists( "General", "Appearance", "Text Editors" ) ); assertTrue( prefs.pageExists( "General", "Appearance", "Colors and Fonts" ) ); assertTrue( prefs.pageExists( "Help" ) ); assertTrue( prefs.pageExists( "Install/Update" ) ); prefs.clickCancelButton(); } /** * Verify hidden preference pages. Many unwanted preference pages are contributed * by org.eclipse.* plugins, we configured to hide them in rcp/plugin.xml. * * Note: This test fails when running from Eclipse IDE and all workspace plugins * are part of the target platform. */ @Test public void testHiddenPreferencePages() throws Exception { PreferencesBot prefs = studioBot.openPreferences(); assertFalse( prefs.pageExists( "Team" ) ); assertFalse( prefs.pageExists( "Maven" ) ); assertFalse( prefs.pageExists( "Java" ) ); assertFalse( prefs.pageExists( "General", "Quick Search" ) ); assertFalse( prefs.pageExists( "General", "Network Connections" ) ); prefs.clickCancelButton(); } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/tests/test.integration.ui/src/main/java/org/apache/directory/studio/test/integration/ui/AbstractTestBase.java
tests/test.integration.ui/src/main/java/org/apache/directory/studio/test/integration/ui/AbstractTestBase.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.studio.test.integration.ui; import static org.apache.directory.studio.test.integration.junit5.TestFixture.CONTEXT_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.REFERRALS_DN; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.lang3.ArrayUtils; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.api.ldap.model.name.Rdn; import org.apache.directory.studio.connection.core.ConnectionCorePlugin; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreConstants; import org.apache.directory.studio.ldapbrowser.core.BrowserCorePlugin; import org.apache.directory.studio.test.integration.junit5.SkipTestIfLdapServerIsNotAvailableInterceptor; import org.apache.directory.studio.test.integration.junit5.TestLdapServer; import org.apache.directory.studio.test.integration.ui.bots.ApacheDSServersViewBot; import org.apache.directory.studio.test.integration.ui.bots.BrowserViewBot; import org.apache.directory.studio.test.integration.ui.bots.ConnectionsViewBot; import org.apache.directory.studio.test.integration.ui.bots.ModificationLogsViewBot; import org.apache.directory.studio.test.integration.ui.bots.SearchLogsViewBot; import org.apache.directory.studio.test.integration.ui.bots.StudioBot; import org.apache.directory.studio.test.integration.ui.utils.Assertions; import org.eclipse.swtbot.eclipse.finder.SWTWorkbenchBot; import org.eclipse.swtbot.swt.finder.finders.UIThreadRunnable; import org.eclipse.swtbot.swt.finder.junit5.SWTBotJunit5Extension; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.extension.ExtendWith; @ExtendWith( { SWTBotJunit5Extension.class, SkipTestIfLdapServerIsNotAvailableInterceptor.class }) public class AbstractTestBase { protected SWTWorkbenchBot bot; protected StudioBot studioBot; protected ConnectionsViewBot connectionsViewBot; protected BrowserViewBot browserViewBot; protected SearchLogsViewBot searchLogsViewBot; protected ModificationLogsViewBot modificationLogsViewBot; protected ApacheDSServersViewBot serversViewBot; @BeforeEach final void setUpBase() throws Exception { bot = new SWTWorkbenchBot(); studioBot = new StudioBot(); studioBot.resetLdapPerspective(); connectionsViewBot = studioBot.getConnectionView(); browserViewBot = studioBot.getBrowserView(); searchLogsViewBot = studioBot.getSearchLogsViewBot(); modificationLogsViewBot = studioBot.getModificationLogsViewBot(); serversViewBot = studioBot.getApacheDSServersViewBot(); UIThreadRunnable.syncExec( () -> { BrowserCorePlugin.getDefault() .getPluginPreferences().setValue( BrowserCoreConstants.PREFERENCE_LDIF_LINE_WIDTH, 1000 ); } ); } @AfterEach final void tearDownBase() throws Exception { // clear custom trust stores X509Certificate[] permanentCertificates = ConnectionCorePlugin.getDefault().getPermanentTrustStoreManager() .getCertificates(); for ( X509Certificate certificate : permanentCertificates ) { ConnectionCorePlugin.getDefault().getPermanentTrustStoreManager().removeCertificate( certificate ); } X509Certificate[] temporaryCertificates = ConnectionCorePlugin.getDefault().getSessionTrustStoreManager() .getCertificates(); for ( X509Certificate certificate : temporaryCertificates ) { ConnectionCorePlugin.getDefault().getSessionTrustStoreManager().removeCertificate( certificate ); } connectionsViewBot.deleteTestConnections(); serversViewBot.deleteTestServers(); Assertions.genericTearDownAssertions(); } public static final String[] ROOT_DSE_PATH = { "DIT", "Root DSE" }; public static final String[] CONTEXT_PATH = path( ROOT_DSE_PATH, CONTEXT_DN.getName() ); public static String[] path( String[] parents, String leaf ) { return ArrayUtils.addAll( parents, leaf ); } /** * Gets the path to the DN in the LDAP browser tree. * The path starts with "DIT", "Root DSE", and the context entry. */ public static String[] path( Dn dn ) { List<String> l = new ArrayList<>(); l.addAll( Arrays.asList( CONTEXT_PATH ) ); List<Rdn> rdns = dn.getRdns(); for ( int i = rdns.size() - 3; i >= 0; i-- ) { l.add( rdns.get( i ).getName() ); } return l.toArray( new String[0] ); } /** * Gets the path to the RDN below the DN in the LDAP browser tree. * The path starts with "DIT", "Root DSE", and the context entry. */ public static String[] path( Dn dn, Rdn rdn ) { return path( dn, rdn.getName() ); } /** * Gets the path to the leaf below the DN in the LDAP browser tree. * The path starts with "DIT", "Root DSE", and the context entry. */ public static String[] path( Dn dn, String... leaf ) { return ArrayUtils.addAll( path( dn ), leaf ); } public static String[] pathWithRefLdapUrl( TestLdapServer ldapServer, Dn dn ) { String leaf = ldapServer.getLdapUrl() + "/" + dn.getName(); return path( REFERRALS_DN, leaf ); } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/tests/test.integration.ui/src/main/java/org/apache/directory/studio/test/integration/ui/RenameEntryTest.java
tests/test.integration.ui/src/main/java/org/apache/directory/studio/test/integration/ui/RenameEntryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.studio.test.integration.ui; import static org.apache.directory.studio.test.integration.junit5.TestFixture.DN_WITH_LEADING_SHARP_BACKSLASH_PREFIXED; import static org.apache.directory.studio.test.integration.junit5.TestFixture.DN_WITH_LEADING_SHARP_HEX_PAIR_ESCAPED; import static org.apache.directory.studio.test.integration.junit5.TestFixture.MULTI_VALUED_RDN_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.DN_WITH_ESCAPED_CHARACTERS_BACKSLASH_PREFIXED; import static org.apache.directory.studio.test.integration.junit5.TestFixture.DN_WITH_ESCAPED_CHARACTERS_HEX_PAIR_ESCAPED; import static org.apache.directory.studio.test.integration.junit5.TestFixture.dn; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.directory.api.ldap.model.name.Ava; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.api.ldap.model.name.Rdn; import org.apache.directory.studio.test.integration.junit5.LdapServerType; import org.apache.directory.studio.test.integration.junit5.LdapServersSource; import org.apache.directory.studio.test.integration.junit5.TestLdapServer; import org.apache.directory.studio.test.integration.junit5.LdapServersSource.Mode; import org.apache.directory.studio.test.integration.ui.bots.RenameEntryDialogBot; import org.junit.jupiter.params.ParameterizedTest; /** * Tests entry renaming (modrdn) and the rename dialog. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> * @version $Rev$, $Date$ */ public class RenameEntryTest extends AbstractTestBase { /** * Test for DIRSTUDIO-318. * * Renames a multi-valued RDN by changing both RDN attributes. */ @ParameterizedTest @LdapServersSource public void testRenameMultiValuedRdn( TestLdapServer server ) throws Exception { Dn oldDn = MULTI_VALUED_RDN_DN; Rdn newRdn = new Rdn( new Ava( "cn", "Babs Jensen" ), new Ava( "uid", "dj" ) ); Dn newDn = dn( newRdn, oldDn.getParent() ); connectionsViewBot.createTestConnection( server ); browserViewBot.selectEntry( path( oldDn ) ); RenameEntryDialogBot renameDialogBot = browserViewBot.openRenameDialog(); assertTrue( renameDialogBot.isVisible() ); for ( int i = 0; i < newRdn.size(); i++ ) { renameDialogBot.setRdnType( i + 1, newRdn.getAva( i ).getType() ); renameDialogBot.setRdnValue( i + 1, newRdn.getAva( i ).getValue().getString() ); } renameDialogBot.clickOkButton(); assertTrue( browserViewBot.existsEntry( path( newDn ) ) ); browserViewBot.selectEntry( path( newDn ) ); assertFalse( browserViewBot.existsEntry( path( oldDn ) ) ); } /** * Test for DIRSTUDIO-484. * * Renames a RDN with escaped characters. */ @ParameterizedTest @LdapServersSource(mode = Mode.All) public void testRenameRdnWithEscapedCharacters( TestLdapServer server ) throws Exception { Dn oldDn = DN_WITH_ESCAPED_CHARACTERS_BACKSLASH_PREFIXED; if ( server.getType() == LdapServerType.OpenLdap || server.getType() == LdapServerType.Fedora389ds ) { oldDn = DN_WITH_ESCAPED_CHARACTERS_HEX_PAIR_ESCAPED; } Dn newDn = dn( oldDn.getRdn().getName() + " renamed", oldDn.getParent() ); connectionsViewBot.createTestConnection( server ); browserViewBot.selectEntry( path( oldDn ) ); RenameEntryDialogBot renameDialogBot = browserViewBot.openRenameDialog(); assertTrue( renameDialogBot.isVisible() ); renameDialogBot.setRdnValue( 1, newDn.getRdn().getValue() ); renameDialogBot.clickOkButton(); assertTrue( browserViewBot.existsEntry( path( newDn ) ) ); browserViewBot.selectEntry( path( newDn ) ); assertFalse( browserViewBot.existsEntry( path( oldDn ) ) ); } /** * Test for DIRSTUDIO-589, DIRSTUDIO-591, DIRSHARED-38. * * Rename an entry with leading sharp in DN: cn=\#123456. */ @ParameterizedTest @LdapServersSource(mode = Mode.All) public void testRenameRdnWithLeadingSharp( TestLdapServer server ) throws Exception { Dn oldDn = DN_WITH_LEADING_SHARP_BACKSLASH_PREFIXED; Dn newDn = dn( "cn=\\#ABCDEF", oldDn.getParent() ); if ( server.getType() == LdapServerType.OpenLdap || server.getType() == LdapServerType.Fedora389ds ) { oldDn = DN_WITH_LEADING_SHARP_HEX_PAIR_ESCAPED; newDn = dn( "cn=\\23ABCDEF", oldDn.getParent() ); } connectionsViewBot.createTestConnection( server ); browserViewBot.selectEntry( path( oldDn ) ); RenameEntryDialogBot renameDialogBot = browserViewBot.openRenameDialog(); assertTrue( renameDialogBot.isVisible() ); renameDialogBot.setRdnValue( 1, "#ABCDEF" ); renameDialogBot.clickOkButton(); assertTrue( browserViewBot.existsEntry( path( newDn ) ) ); browserViewBot.selectEntry( path( newDn ) ); assertFalse( browserViewBot.existsEntry( path( oldDn ) ) ); } /** * Test for DIRSHARED-39. * * Rename an entry with leading and trailing space in RDN. */ @ParameterizedTest @LdapServersSource(mode = Mode.All, except = LdapServerType.Fedora389ds, reason = "Leading and trailing space is trimmed by 389ds") public void testRenameRdnWithTrailingSpace( TestLdapServer server ) throws Exception { Dn oldDn = DN_WITH_LEADING_SHARP_BACKSLASH_PREFIXED; Dn newDn = dn( "cn=\\#ABCDEF\\ ", oldDn.getParent() ); if ( server.getType() == LdapServerType.OpenLdap ) { oldDn = DN_WITH_LEADING_SHARP_HEX_PAIR_ESCAPED; newDn = dn( "cn=\\23ABCDEF\\20", oldDn.getParent() ); } connectionsViewBot.createTestConnection( server ); browserViewBot.selectEntry( path( oldDn ) ); RenameEntryDialogBot renameDialogBot = browserViewBot.openRenameDialog(); assertTrue( renameDialogBot.isVisible() ); renameDialogBot.setRdnValue( 1, "#ABCDEF " ); renameDialogBot.clickOkButton(); assertTrue( browserViewBot.existsEntry( path( newDn ) ) ); browserViewBot.selectEntry( path( newDn ) ); assertFalse( browserViewBot.existsEntry( path( oldDn ) ) ); } /** * Test for DIRSHARED-39. * * Rename an entry with leading and trailing space in RDN. */ @ParameterizedTest @LdapServersSource(mode = Mode.All, except = LdapServerType.Fedora389ds, reason = "Leading and trailing space is trimmed by 389ds") public void testRenameRdnWithLeadingAndTrailingSpace( TestLdapServer server ) throws Exception { Dn oldDn = DN_WITH_LEADING_SHARP_BACKSLASH_PREFIXED; Dn newDn = dn( "cn=\\ #ABCDEF \\ ", oldDn.getParent() ); if ( server.getType() == LdapServerType.OpenLdap ) { oldDn = DN_WITH_LEADING_SHARP_HEX_PAIR_ESCAPED; newDn = dn( "cn=\\20 #ABCDEF \\20", oldDn.getParent() ); } connectionsViewBot.createTestConnection( server ); browserViewBot.selectEntry( path( oldDn ) ); RenameEntryDialogBot renameDialogBot = browserViewBot.openRenameDialog(); assertTrue( renameDialogBot.isVisible() ); renameDialogBot.setRdnValue( 1, " #ABCDEF " ); renameDialogBot.clickOkButton(); assertTrue( browserViewBot.existsEntry( path( newDn ) ) ); browserViewBot.selectEntry( path( newDn ) ); assertFalse( browserViewBot.existsEntry( path( oldDn ) ) ); } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/tests/test.integration.ui/src/main/java/org/apache/directory/studio/test/integration/ui/ExtendedOperationsTest.java
tests/test.integration.ui/src/main/java/org/apache/directory/studio/test/integration/ui/ExtendedOperationsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.studio.test.integration.ui; import static org.apache.directory.studio.test.integration.junit5.TestFixture.USER1_DN; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.commons.lang3.RandomStringUtils; import org.apache.directory.studio.test.integration.junit5.LdapServerType; import org.apache.directory.studio.test.integration.junit5.LdapServersSource; import org.apache.directory.studio.test.integration.junit5.LdapServersSource.Mode; import org.apache.directory.studio.test.integration.junit5.TestLdapServer; import org.apache.directory.studio.test.integration.ui.bots.EntryEditorBot; import org.apache.directory.studio.test.integration.ui.bots.ErrorDialogBot; import org.apache.directory.studio.test.integration.ui.bots.GeneratedPasswordDialogBot; import org.apache.directory.studio.test.integration.ui.bots.PasswordEditorDialogBot; import org.apache.directory.studio.test.integration.ui.bots.PasswordModifyExtendedOperationDialogBot; import org.junit.jupiter.params.ParameterizedTest; /** * Tests the extended operations. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> * @version $Rev$, $Date$ */ public class ExtendedOperationsTest extends AbstractTestBase { @ParameterizedTest @LdapServersSource public void testPasswordModifyExtendedOperationDialogValidation( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); browserViewBot.selectEntry( path( USER1_DN ) ); // Open dialog PasswordModifyExtendedOperationDialogBot dialogBot = browserViewBot.openPasswordModifyExtendedOperationDialog(); assertTrue( dialogBot.isVisible() ); // Verify default UI state assertEquals( USER1_DN.getName(), dialogBot.getUserIdentity() ); assertFalse( dialogBot.useBindUserIdentity() ); assertEquals( "", dialogBot.getOldPassword() ); assertFalse( dialogBot.noOldPassword() ); assertEquals( "", dialogBot.getNewPassword() ); assertFalse( dialogBot.generateNewPassword() ); assertFalse( dialogBot.isOkButtonEnabled() ); // Enter passwords, should enable OK button dialogBot.setOldPassword( "old123" ); dialogBot.setNewPassword( "new456" ); assertTrue( dialogBot.isOkButtonEnabled() ); // Check "Use bind user identity" dialogBot.useBindUserIdentity( true ); assertEquals( "", dialogBot.getUserIdentity() ); assertTrue( dialogBot.isOkButtonEnabled() ); dialogBot.useBindUserIdentity( false ); assertEquals( "", dialogBot.getUserIdentity() ); assertFalse( dialogBot.isOkButtonEnabled() ); dialogBot.useBindUserIdentity( true ); // Check "No old password" dialogBot.noOldPassword( true ); assertEquals( "", dialogBot.getOldPassword() ); assertTrue( dialogBot.isOkButtonEnabled() ); dialogBot.noOldPassword( false ); assertEquals( "", dialogBot.getOldPassword() ); assertFalse( dialogBot.isOkButtonEnabled() ); dialogBot.noOldPassword( true ); // Check "Generate new password" dialogBot.generateNewPassword( true ); assertEquals( "", dialogBot.getNewPassword() ); assertTrue( dialogBot.isOkButtonEnabled() ); dialogBot.generateNewPassword( false ); assertEquals( "", dialogBot.getNewPassword() ); assertFalse( dialogBot.isOkButtonEnabled() ); dialogBot.generateNewPassword( true ); // Uncheck all again dialogBot.useBindUserIdentity( false ); dialogBot.noOldPassword( false ); dialogBot.generateNewPassword( false ); assertFalse( dialogBot.isOkButtonEnabled() ); // Fill data dialogBot.setNewPassword( "new123" ); dialogBot.setOldPassword( "old456" ); dialogBot.setUserIdentity( "foo=bar" ); assertTrue( dialogBot.isOkButtonEnabled() ); dialogBot.clickCancelButton(); } @ParameterizedTest @LdapServersSource(mode=Mode.All, except = LdapServerType.Fedora389ds, reason = "389ds requires secure connection") public void testPasswordModifyExtendedOperationDialogSetNewPassword( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); String random = RandomStringUtils.random( 20 ); browserViewBot.selectEntry( path( USER1_DN ) ); // Open dialog PasswordModifyExtendedOperationDialogBot dialogBot = browserViewBot.openPasswordModifyExtendedOperationDialog(); assertTrue( dialogBot.isVisible() ); assertEquals( USER1_DN.getName(), dialogBot.getUserIdentity() ); // Change password dialogBot.noOldPassword( true ); dialogBot.setNewPassword( random ); dialogBot.clickOkButton(); // Verify and bind with the correct password browserViewBot.refresh(); EntryEditorBot entryEditorBot = studioBot.getEntryEditorBot( USER1_DN.getName() ); entryEditorBot.activate(); PasswordEditorDialogBot pwdEditorBot = entryEditorBot.editValueExpectingPasswordEditor( "userPassword", null ); pwdEditorBot.activateCurrentPasswordTab(); pwdEditorBot.setVerifyPassword( random ); assertNull( pwdEditorBot.clickVerifyButton() ); assertNull( pwdEditorBot.clickBindButton() ); pwdEditorBot.clickCancelButton(); } @ParameterizedTest @LdapServersSource(mode=Mode.All, except = LdapServerType.Fedora389ds, reason = "389ds requires secure connection") public void testPasswordModifyExtendedOperationDialogGenerateNewPassword( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); browserViewBot.selectEntry( path( USER1_DN ) ); // Open dialog PasswordModifyExtendedOperationDialogBot dialogBot = browserViewBot.openPasswordModifyExtendedOperationDialog(); assertTrue( dialogBot.isVisible() ); assertEquals( USER1_DN.getName(), dialogBot.getUserIdentity() ); // Generate password dialogBot.noOldPassword( true ); dialogBot.generateNewPassword( true ); // ApacheDS does not support password generation if ( server.getType() == LdapServerType.ApacheDS ) { ErrorDialogBot errorBot = dialogBot.clickOkButtonExpectingErrorDialog(); assertThat( errorBot.getErrorMessage(), containsString( "null new password" ) ); errorBot.clickOkButton(); dialogBot.activate(); dialogBot.clickCancelButton(); } else { dialogBot.clickOkButton(); GeneratedPasswordDialogBot generatedPasswordDialogBot = new GeneratedPasswordDialogBot(); String generatedPassword = generatedPasswordDialogBot.getGeneratedPassword(); generatedPasswordDialogBot.clickOkButton(); // Verify and bind with the correct password browserViewBot.refresh(); EntryEditorBot entryEditorBot = studioBot.getEntryEditorBot( USER1_DN.getName() ); entryEditorBot.activate(); PasswordEditorDialogBot pwdEditorBot = entryEditorBot.editValueExpectingPasswordEditor( "userPassword", null ); pwdEditorBot.activateCurrentPasswordTab(); pwdEditorBot.setVerifyPassword( generatedPassword ); assertNull( pwdEditorBot.clickVerifyButton() ); assertNull( pwdEditorBot.clickBindButton() ); pwdEditorBot.clickCancelButton(); } } @ParameterizedTest @LdapServersSource(only = LdapServerType.Fedora389ds, reason = "389ds requires secure connection") public void testPasswordModifyExtendedOperationRequiresSecureConnection( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); String random = RandomStringUtils.random( 20 ); browserViewBot.selectEntry( path( USER1_DN ) ); // Open dialog PasswordModifyExtendedOperationDialogBot dialogBot = browserViewBot.openPasswordModifyExtendedOperationDialog(); assertTrue( dialogBot.isVisible() ); assertEquals( USER1_DN.getName(), dialogBot.getUserIdentity() ); // Change password dialogBot.noOldPassword( true ); dialogBot.setNewPassword( random ); ErrorDialogBot errorBot = dialogBot.clickOkButtonExpectingErrorDialog(); assertThat( errorBot.getErrorMessage(), containsString( "Operation requires a secure connection" ) ); errorBot.clickOkButton(); dialogBot.activate(); dialogBot.clickCancelButton(); } @ParameterizedTest @LdapServersSource(mode=Mode.All) public void testPasswordModifyExtendedOperationDialogError( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); String random = RandomStringUtils.random( 20 ); browserViewBot.selectEntry( path( USER1_DN ) ); String dn = USER1_DN.getName(); // Open dialog PasswordModifyExtendedOperationDialogBot dialogBot = browserViewBot.openPasswordModifyExtendedOperationDialog(); assertTrue( dialogBot.isVisible() ); assertEquals( dn, dialogBot.getUserIdentity() ); // Wrong old password dialogBot.activate(); dialogBot.setUserIdentity( dn ); dialogBot.setOldPassword( "wrong password" ); dialogBot.setNewPassword( random ); ErrorDialogBot errorBot = dialogBot.clickOkButtonExpectingErrorDialog(); if ( server.getType() == LdapServerType.OpenLdap ) { assertThat( errorBot.getErrorMessage(), containsString( "unwilling to verify old password" ) ); } else if ( server.getType() == LdapServerType.Fedora389ds ) { assertThat( errorBot.getErrorMessage(), containsString( "Operation requires a secure connection" ) ); } else { assertThat( errorBot.getErrorMessage(), containsString( "invalid credentials" ) ); } errorBot.clickOkButton(); // Not existing entry dialogBot.activate(); dialogBot.setUserIdentity( "cn=non-existing-entry" ); dialogBot.noOldPassword( true ); dialogBot.setNewPassword( random ); errorBot = dialogBot.clickOkButtonExpectingErrorDialog(); if ( server.getType() == LdapServerType.OpenLdap ) { assertThat( errorBot.getErrorMessage(), containsString( "unable to retrieve SASL username" ) ); } else if ( server.getType() == LdapServerType.Fedora389ds ) { assertThat( errorBot.getErrorMessage(), containsString( "Operation requires a secure connection" ) ); } else { assertThat( errorBot.getErrorMessage(), containsString( "The entry does not exist" ) ); } errorBot.clickOkButton(); // ApacheDS does not support password generation if ( server.getType() == LdapServerType.ApacheDS ) { dialogBot.activate(); dialogBot.setUserIdentity( dn ); dialogBot.noOldPassword( true ); dialogBot.generateNewPassword( true ); errorBot = dialogBot.clickOkButtonExpectingErrorDialog(); assertThat( errorBot.getErrorMessage(), containsString( "null new password" ) ); errorBot.clickOkButton(); } dialogBot.activate(); dialogBot.clickCancelButton(); } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/tests/test.integration.ui/src/main/java/org/apache/directory/studio/test/integration/ui/CopyEntryTest.java
tests/test.integration.ui/src/main/java/org/apache/directory/studio/test/integration/ui/CopyEntryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.studio.test.integration.ui; import static org.apache.directory.studio.test.integration.junit5.TestFixture.ALIAS_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.CONTEXT_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.TARGET_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.REFERRAL_TO_USER1_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.SUBENTRY_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.USER1_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.USERS_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.dn; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.Connection.AliasDereferencingMethod; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreConstants; import org.apache.directory.studio.ldapbrowser.core.BrowserCorePlugin; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldifparser.LdifParserConstants; import org.apache.directory.studio.test.integration.junit5.LdapServerType; import org.apache.directory.studio.test.integration.junit5.LdapServersSource; import org.apache.directory.studio.test.integration.junit5.TestLdapServer; import org.apache.directory.studio.test.integration.ui.bots.SelectCopyDepthDialogBot; import org.apache.directory.studio.test.integration.ui.bots.SelectCopyStrategyBot; import org.eclipse.swtbot.swt.finder.finders.UIThreadRunnable; import org.eclipse.swtbot.swt.finder.results.VoidResult; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.params.ParameterizedTest; /** * Tests copy/paste of entries * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> * @version $Rev$, $Date$ */ public class CopyEntryTest extends AbstractTestBase { @AfterEach public void resetPreferences() { // DIRSERVER-2133: reset check for children preference UIThreadRunnable.syncExec( () -> { BrowserCorePlugin.getDefault() .getPluginPreferences().setValue( BrowserCoreConstants.PREFERENCE_CHECK_FOR_CHILDREN, true ); } ); } @ParameterizedTest @LdapServersSource public void testCopyPasteSingleEntryWithoutCopyDepthDialog( TestLdapServer server ) throws Exception { Dn newDn = dn( USER1_DN.getRdn(), TARGET_DN ); // expand the entry to avoid copy depth dialog connectionsViewBot.createTestConnection( server ); browserViewBot.selectEntry( path( USER1_DN ) ); browserViewBot.expandEntry( path( USER1_DN ) ); // copy an entry browserViewBot.copy(); // select the parent entry where the copied entry should be pasted to browserViewBot.selectEntry( path( TARGET_DN ) ); assertFalse( browserViewBot.existsEntry( path( newDn ) ) ); // paste the entry browserViewBot.pasteEntry(); // verify the entry was copied assertTrue( browserViewBot.existsEntry( path( newDn ) ) ); browserViewBot.selectEntry( path( newDn ) ); // verify in modification logs modificationLogsViewBot.assertContainsOk( "dn: " + newDn.getName(), "changetype: add" ); } @ParameterizedTest @LdapServersSource public void testCopyPasteMultipleEntriesWithCopyDepthDialogObjectOnly( TestLdapServer server ) throws Exception { // DIRSERVER-2133: disable check for children for this test UIThreadRunnable.syncExec( () -> { BrowserCorePlugin.getDefault() .getPluginPreferences().setValue( BrowserCoreConstants.PREFERENCE_CHECK_FOR_CHILDREN, false ); } ); // select and copy multiple entries connectionsViewBot.createTestConnection( server ); browserViewBot.expandEntry( path( USERS_DN ) ); String[] children = { "uid=user.1", "uid=user.2", "uid=user.3", "uid=user.4" }; browserViewBot.selectChildrenOfEntry( children, path( USERS_DN ) ); browserViewBot.copy(); // select the parent entry where the copied entries should be pasted to browserViewBot.selectEntry( path( TARGET_DN ) ); assertFalse( browserViewBot.existsEntry( path( TARGET_DN, "uid=user.1" ) ) ); // paste the entry SelectCopyDepthDialogBot dialog = browserViewBot.pasteEntriesExpectingSelectCopyDepthDialog( 4 ); dialog.selectObject(); dialog.clickOkButton(); // verify the entries were copied assertTrue( browserViewBot.existsEntry( path( TARGET_DN, "uid=user.1" ) ) ); assertTrue( browserViewBot.existsEntry( path( TARGET_DN, "uid=user.2" ) ) ); assertTrue( browserViewBot.existsEntry( path( TARGET_DN, "uid=user.3" ) ) ); assertTrue( browserViewBot.existsEntry( path( TARGET_DN, "uid=user.4" ) ) ); // verify in modification logs modificationLogsViewBot.assertContainsOk( "dn: " + dn( "uid=user.1", TARGET_DN ), "changetype: add" ); modificationLogsViewBot.assertContainsOk( "dn: " + dn( "uid=user.2", TARGET_DN ), "changetype: add" ); modificationLogsViewBot.assertContainsOk( "dn: " + dn( "uid=user.3", TARGET_DN ), "changetype: add" ); modificationLogsViewBot.assertContainsOk( "dn: " + dn( "uid=user.4", TARGET_DN ), "changetype: add" ); } @ParameterizedTest @LdapServersSource public void testCopyPasteMultipleEntriesWithCopyDepthDialogSubtree( TestLdapServer server ) throws Exception { // select and copy multiple entries connectionsViewBot.createTestConnection( server ); browserViewBot.expandEntry( path( CONTEXT_DN ) ); String[] children = { "ou=users", "ou=groups" }; browserViewBot.selectChildrenOfEntry( children, path( CONTEXT_DN ) ); browserViewBot.copy(); // select the parent entry where the copied entries should be pasted to browserViewBot.selectEntry( path( TARGET_DN ) ); assertFalse( browserViewBot.existsEntry( path( TARGET_DN, "ou=users" ) ) ); assertFalse( browserViewBot.existsEntry( path( TARGET_DN, "ou=groups" ) ) ); // paste the entry SelectCopyDepthDialogBot dialog = browserViewBot.pasteEntriesExpectingSelectCopyDepthDialog( 2 ); dialog.selectSubTree(); dialog.clickOkButton(); // verify the entries were copied assertTrue( browserViewBot.existsEntry( path( TARGET_DN, "ou=users" ) ) ); assertTrue( browserViewBot.existsEntry( path( TARGET_DN, "ou=users", "uid=user.1" ) ) ); assertTrue( browserViewBot.existsEntry( path( TARGET_DN, "ou=users", "uid=user.8" ) ) ); assertTrue( browserViewBot.existsEntry( path( TARGET_DN, "ou=groups" ) ) ); assertTrue( browserViewBot.existsEntry( path( TARGET_DN, "ou=groups", "cn=group.1" ) ) ); // verify in modification logs modificationLogsViewBot.assertContainsOk( "dn: " + dn( "ou=users", TARGET_DN ), "changetype: add" ); modificationLogsViewBot.assertContainsOk( "dn: " + dn( "ou=groups", TARGET_DN ), "changetype: add" ); } @ParameterizedTest @LdapServersSource public void testCopyPasteSingleEntryOverwrite( TestLdapServer server ) throws Exception { // expand the entry to avoid copy depth dialog connectionsViewBot.createTestConnection( server ); browserViewBot.selectEntry( path( USER1_DN ) ); browserViewBot.expandEntry( path( USER1_DN ) ); // copy an entry browserViewBot.copy(); // select the parent entry where the copied entry should be pasted to browserViewBot.selectEntry( path( USERS_DN ) ); // paste the entry SelectCopyStrategyBot dialog = browserViewBot.pasteEntriesExpectingSelectCopyStrategy(); dialog.selectOverwriteEntryAndContinue(); dialog.clickOkButton(); // verify in modification logs modificationLogsViewBot.assertContainsError( "[LDAP result code 68 - entryAlreadyExists]", "dn: " + USER1_DN.getName(), "changetype: add", "uid: user.1" ); modificationLogsViewBot.assertContainsOk( "dn: " + USER1_DN.getName(), "changetype: modify", "replace: uid" + LdifParserConstants.LINE_SEPARATOR + "uid: user.1" + LdifParserConstants.LINE_SEPARATOR + "-", "replace: objectClass" ); } @ParameterizedTest @LdapServersSource public void testCopyPasteSingleEntryRename( TestLdapServer server ) throws Exception { // expand the entry to avoid copy depth dialog connectionsViewBot.createTestConnection( server ); browserViewBot.selectEntry( path( USER1_DN ) ); browserViewBot.expandEntry( path( USER1_DN ) ); // copy an entry browserViewBot.copy(); // select the parent entry where the copied entry should be pasted to browserViewBot.selectEntry( path( USERS_DN ) ); // paste the entry Dn renamedDn = dn( "uid=user.renamed", USERS_DN ); SelectCopyStrategyBot dialog = browserViewBot.pasteEntriesExpectingSelectCopyStrategy(); dialog.selectRenameEntryAndContinue(); dialog.setRdnValue( 1, "user.renamed" ); dialog.clickOkButton(); // verify the entry was copied assertTrue( browserViewBot.existsEntry( path( renamedDn ) ) ); browserViewBot.selectEntry( path( renamedDn ) ); // verify in modification logs modificationLogsViewBot.assertContainsError( "[LDAP result code 68 - entryAlreadyExists]", "dn: " + USER1_DN.getName(), "changetype: add", "uid: user.1" ); modificationLogsViewBot.assertContainsOk( "dn: " + renamedDn.getName(), "changetype: add", "uid: user.renamed" ); } @ParameterizedTest @LdapServersSource public void testCopyPasteAliasEntry( TestLdapServer server ) throws Exception { // disable alias dereferencing Connection connection = connectionsViewBot.createTestConnection( server ); connection.getConnectionParameter().setExtendedIntProperty( IBrowserConnection.CONNECTION_PARAMETER_ALIASES_DEREFERENCING_METHOD, AliasDereferencingMethod.NEVER.ordinal() ); // expand the entry to avoid copy depth dialog browserViewBot.expandEntry( path( ALIAS_DN ) ); browserViewBot.selectEntry( path( ALIAS_DN ) ); browserViewBot.copy(); // select the parent entry where the copied entry should be pasted to browserViewBot.selectEntry( path( TARGET_DN ) ); assertFalse( browserViewBot.existsEntry( path( TARGET_DN, ALIAS_DN.getRdn() ) ) ); // paste the entry browserViewBot.pasteEntries( 1 ); // verify the entyr was copied assertTrue( browserViewBot.existsEntry( path( TARGET_DN, ALIAS_DN.getRdn() ) ) ); // verify in modification logs modificationLogsViewBot.assertContainsOk( "dn: " + dn( ALIAS_DN.getRdn(), TARGET_DN ), "changetype: add" ); } @ParameterizedTest @LdapServersSource public void testCopyPasteReferralEntry( TestLdapServer server ) throws Exception { // enable ManageDsaIT control Connection connection = connectionsViewBot.createTestConnection( server ); connection.getConnectionParameter().setExtendedBoolProperty( IBrowserConnection.CONNECTION_PARAMETER_MANAGE_DSA_IT, true ); // expand the entry to avoid copy depth dialog browserViewBot.expandEntry( path( REFERRAL_TO_USER1_DN ) ); browserViewBot.selectEntry( path( REFERRAL_TO_USER1_DN ) ); browserViewBot.copy(); // select the parent entry where the copied entry should be pasted to browserViewBot.selectEntry( path( TARGET_DN ) ); assertFalse( browserViewBot.existsEntry( path( TARGET_DN, REFERRAL_TO_USER1_DN.getRdn() ) ) ); // paste the entry browserViewBot.pasteEntries( 1 ); // verify the entry was copied assertTrue( browserViewBot.existsEntry( path( TARGET_DN, REFERRAL_TO_USER1_DN.getRdn() ) ) ); // verify in modification logs modificationLogsViewBot.assertContainsOk( "dn: " + dn( REFERRAL_TO_USER1_DN.getRdn(), TARGET_DN ), "changetype: add" ); } @ParameterizedTest @LdapServersSource(only = LdapServerType.ApacheDS, reason = "ApacheDS specific test") public void testCopyPasteSubentry( TestLdapServer server ) throws Exception { // enable Subentries control Connection connection = connectionsViewBot.createTestConnection( server ); connection.getConnectionParameter().setExtendedBoolProperty( IBrowserConnection.CONNECTION_PARAMETER_FETCH_SUBENTRIES, true ); // expand the entry to avoid copy depth dialog browserViewBot.expandEntry( path( SUBENTRY_DN ) ); browserViewBot.selectEntry( path( SUBENTRY_DN ) ); browserViewBot.copy(); // select the parent entry where the copied entry should be pasted to browserViewBot.selectEntry( path( TARGET_DN ) ); assertFalse( browserViewBot.existsEntry( path( TARGET_DN, SUBENTRY_DN.getRdn() ) ) ); // paste the entry browserViewBot.pasteEntries( 1 ); // verify the entry was copied assertTrue( browserViewBot.existsEntry( path( TARGET_DN, SUBENTRY_DN.getRdn() ) ) ); // verify in modification logs modificationLogsViewBot.assertContainsOk( "dn: " + dn( SUBENTRY_DN.getRdn(), TARGET_DN ), "changetype: add" ); } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/tests/test.integration.ui/src/main/java/org/apache/directory/studio/test/integration/ui/NewEntryWizardTest.java
tests/test.integration.ui/src/main/java/org/apache/directory/studio/test/integration/ui/NewEntryWizardTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.studio.test.integration.ui; import static org.apache.directory.studio.test.integration.junit5.TestFixture.MISC_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.REFERRAL_TO_MISC_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.TARGET_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.USER1_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.dn; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.Connection.AliasDereferencingMethod; import org.apache.directory.studio.connection.core.Connection.ReferralHandlingMethod; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.test.integration.junit5.LdapServerType; import org.apache.directory.studio.test.integration.junit5.LdapServersSource; import org.apache.directory.studio.test.integration.junit5.TestLdapServer; import org.apache.directory.studio.test.integration.junit5.LdapServersSource.Mode; import org.apache.directory.studio.test.integration.ui.bots.CertificateEditorDialogBot; import org.apache.directory.studio.test.integration.ui.bots.DnEditorDialogBot; import org.apache.directory.studio.test.integration.ui.bots.EditAttributeWizardBot; import org.apache.directory.studio.test.integration.ui.bots.EntryEditorBot; import org.apache.directory.studio.test.integration.ui.bots.HexEditorDialogBot; import org.apache.directory.studio.test.integration.ui.bots.NewAttributeWizardBot; import org.apache.directory.studio.test.integration.ui.bots.NewEntryWizardBot; import org.apache.directory.studio.test.integration.ui.bots.ReferralDialogBot; import org.apache.directory.studio.test.integration.ui.bots.SubtreeSpecificationEditorDialogBot; import org.apache.directory.studio.test.integration.ui.utils.ResourceUtils; import org.eclipse.swtbot.swt.finder.exceptions.WidgetNotFoundException; import org.eclipse.swtbot.swt.finder.utils.SWTUtils; import org.junit.jupiter.params.ParameterizedTest; /** * Tests the new entry wizard. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> * @version $Rev$, $Date$ */ public class NewEntryWizardTest extends AbstractTestBase { /** * Test to create a single organization entry. */ @ParameterizedTest @LdapServersSource public void testCreateOrganizationEntry( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); browserViewBot.selectEntry( path( TARGET_DN ) ); NewEntryWizardBot wizardBot = browserViewBot.openNewEntryWizard(); assertTrue( wizardBot.isVisible() ); wizardBot.selectCreateEntryFromScratch(); assertFalse( wizardBot.isBackButtonEnabled() ); assertTrue( wizardBot.isNextButtonEnabled() ); assertFalse( wizardBot.isFinishButtonEnabled() ); assertTrue( wizardBot.isCancelButtonEnabled() ); wizardBot.clickNextButton(); assertTrue( wizardBot.isBackButtonEnabled() ); assertFalse( wizardBot.isNextButtonEnabled() ); assertFalse( wizardBot.isFinishButtonEnabled() ); assertTrue( wizardBot.isCancelButtonEnabled() ); wizardBot.addObjectClasses( "organization" ); assertTrue( wizardBot.isObjectClassSelected( "top" ) ); assertTrue( wizardBot.isObjectClassSelected( "organization" ) ); assertTrue( wizardBot.isBackButtonEnabled() ); assertTrue( wizardBot.isNextButtonEnabled() ); assertFalse( wizardBot.isFinishButtonEnabled() ); assertTrue( wizardBot.isCancelButtonEnabled() ); wizardBot.clickNextButton(); assertTrue( wizardBot.isBackButtonEnabled() ); assertFalse( wizardBot.isNextButtonEnabled() ); assertFalse( wizardBot.isFinishButtonEnabled() ); assertTrue( wizardBot.isCancelButtonEnabled() ); wizardBot.setRdnType( 1, "o" ); wizardBot.setRdnValue( 1, "testCreateOrganizationEntry" ); assertTrue( wizardBot.isBackButtonEnabled() ); assertTrue( wizardBot.isNextButtonEnabled() ); assertFalse( wizardBot.isFinishButtonEnabled() ); assertTrue( wizardBot.isCancelButtonEnabled() ); wizardBot.clickNextButton(); wizardBot.clickFinishButton(); assertTrue( browserViewBot.existsEntry( path( TARGET_DN, "o=testCreateOrganizationEntry" ) ) ); browserViewBot.selectEntry( path( TARGET_DN, "o=testCreateOrganizationEntry" ) ); } /** * Test to create a single person entry. */ @ParameterizedTest @LdapServersSource public void testCreatePersonEntry( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); browserViewBot.selectEntry( path( TARGET_DN ) ); NewEntryWizardBot wizardBot = browserViewBot.openNewEntryWizard(); wizardBot.selectCreateEntryFromScratch(); wizardBot.clickNextButton(); wizardBot.addObjectClasses( "inetOrgPerson" ); wizardBot.clickNextButton(); wizardBot.setRdnType( 1, "cn" ); wizardBot.setRdnValue( 1, "testCreatePersonEntry" ); wizardBot.clickNextButton(); wizardBot.typeValueAndFinish( "test" ); wizardBot.clickFinishButton(); assertTrue( browserViewBot.existsEntry( path( TARGET_DN, "cn=testCreatePersonEntry" ) ) ); browserViewBot.selectEntry( path( TARGET_DN, "cn=testCreatePersonEntry" ) ); } /** * Test for DIRSTUDIO-350. * * Create entries with upper case attribute types and ensures that the * retrieved entries still are in upper case. */ @ParameterizedTest @LdapServersSource(except = LdapServerType.OpenLdap, reason = "Attributes type is not case sensitive in OpenLDAP") public void testCreateUpperCaseOrganizationEntries( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); browserViewBot.selectEntry( path( TARGET_DN ) ); NewEntryWizardBot wizardBot = browserViewBot.openNewEntryWizard(); wizardBot.selectCreateEntryFromScratch(); wizardBot.clickNextButton(); wizardBot.addObjectClasses( "organization" ); wizardBot.clickNextButton(); wizardBot.setRdnType( 1, "O" ); wizardBot.setRdnValue( 1, "testCreateOrganizationEntry" ); wizardBot.clickNextButton(); wizardBot.clickFinishButton(); assertTrue( browserViewBot.existsEntry( path( TARGET_DN, "O=testCreateOrganizationEntry" ) ) ); browserViewBot.selectEntry( path( TARGET_DN, "O=testCreateOrganizationEntry" ) ); // Now create a second entry under the previously created entry // to ensure that the selected parent is also upper case. wizardBot = browserViewBot.openNewEntryWizard(); wizardBot.selectCreateEntryFromScratch(); wizardBot.clickNextButton(); wizardBot.addObjectClasses( "organization" ); wizardBot.clickNextButton(); wizardBot.setRdnType( 1, "O" ); wizardBot.setRdnValue( 1, "testCreateOrganizationEntry2" ); assertEquals( "O=testCreateOrganizationEntry2,O=testCreateOrganizationEntry," + TARGET_DN.getName(), wizardBot.getDnPreview() ); wizardBot.clickNextButton(); wizardBot.clickFinishButton(); assertTrue( browserViewBot .existsEntry( path( TARGET_DN, "O=testCreateOrganizationEntry", "O=testCreateOrganizationEntry2" ) ) ); browserViewBot .selectEntry( path( TARGET_DN, "O=testCreateOrganizationEntry", "O=testCreateOrganizationEntry2" ) ); } /** * Test for DIRSTUDIO-360. * * Create entries with a slash '/' in the RDN value. */ @ParameterizedTest @LdapServersSource public void testCreateEntryWithSlash( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); browserViewBot.selectEntry( path( TARGET_DN ) ); NewEntryWizardBot wizardBot = browserViewBot.openNewEntryWizard(); wizardBot.selectCreateEntryFromScratch(); wizardBot.clickNextButton(); wizardBot.addObjectClasses( "person" ); wizardBot.clickNextButton(); wizardBot.setRdnType( 1, "cn" ); wizardBot.setRdnValue( 1, "kadmin/changepw@DOMAIN" ); wizardBot.clickNextButton(); wizardBot.editValue( "sn", "" ); wizardBot.typeValueAndFinish( "test" ); wizardBot.clickFinishButton(); assertTrue( browserViewBot.existsEntry( path( TARGET_DN, "cn=kadmin/changepw@DOMAIN" ) ) ); browserViewBot.selectEntry( path( TARGET_DN, "cn=kadmin/changepw@DOMAIN" ) ); } @ParameterizedTest @LdapServersSource public void testCreateAliasEntry( TestLdapServer server ) throws Exception { // disable alias dereferencing Connection connection = connectionsViewBot.createTestConnection( server ); connection.getConnectionParameter().setExtendedIntProperty( IBrowserConnection.CONNECTION_PARAMETER_ALIASES_DEREFERENCING_METHOD, AliasDereferencingMethod.NEVER.ordinal() ); browserViewBot.selectEntry( path( TARGET_DN ) ); NewEntryWizardBot wizardBot = browserViewBot.openNewEntryWizard(); wizardBot.selectCreateEntryFromScratch(); wizardBot.clickNextButton(); wizardBot.addObjectClasses( "alias", "extensibleObject" ); wizardBot.clickNextButton(); wizardBot.setRdnType( 1, "cn" ); wizardBot.setRdnValue( 1, "alias" ); wizardBot.clickNextButton(); DnEditorDialogBot dnEditorBot = new DnEditorDialogBot(); dnEditorBot.setWaitAfterClickOkButton( false ); dnEditorBot.setDnText( USER1_DN.getName() ); dnEditorBot.clickOkButton(); wizardBot.clickFinishButton(); assertTrue( browserViewBot.existsEntry( path( TARGET_DN, "cn=alias" ) ) ); browserViewBot.selectEntry( path( TARGET_DN, "cn=alias" ) ); } @ParameterizedTest @LdapServersSource(only = LdapServerType.ApacheDS, reason = "ApacheDS specific test") public void testCreateSubEntry( TestLdapServer server ) throws Exception { // set Subentries control Connection connection = connectionsViewBot.createTestConnection( server ); connection.getConnectionParameter().setExtendedBoolProperty( IBrowserConnection.CONNECTION_PARAMETER_FETCH_SUBENTRIES, true ); browserViewBot.selectEntry( path( TARGET_DN ) ); NewEntryWizardBot wizardBot = browserViewBot.openNewEntryWizard(); wizardBot.selectCreateEntryFromScratch(); wizardBot.clickNextButton(); wizardBot.addObjectClasses( "subentry" ); wizardBot.clickNextButton(); wizardBot.setRdnType( 1, "cn" ); wizardBot.setRdnValue( 1, "subentry" ); wizardBot.clickNextButton(); SubtreeSpecificationEditorDialogBot subtreeEditorBot = new SubtreeSpecificationEditorDialogBot(); subtreeEditorBot.setWaitAfterClickOkButton( false ); subtreeEditorBot.clickOkButton(); wizardBot.clickFinishButton(); assertTrue( browserViewBot.existsEntry( path( TARGET_DN, "cn=subentry" ) ) ); browserViewBot.selectEntry( path( TARGET_DN, "cn=subentry" ) ); } @ParameterizedTest @LdapServersSource(mode = Mode.All) public void testCreateReferralEntry( TestLdapServer server ) throws Exception { // set ManageDsaIT control Connection connection = connectionsViewBot.createTestConnection( server ); connection.getConnectionParameter().setExtendedIntProperty( IBrowserConnection.CONNECTION_PARAMETER_REFERRALS_HANDLING_METHOD, ReferralHandlingMethod.IGNORE.ordinal() ); connection.getConnectionParameter().setExtendedBoolProperty( IBrowserConnection.CONNECTION_PARAMETER_MANAGE_DSA_IT, true ); browserViewBot.selectEntry( path( TARGET_DN ) ); NewEntryWizardBot wizardBot = browserViewBot.openNewEntryWizard(); wizardBot.selectCreateEntryFromScratch(); wizardBot.clickNextButton(); wizardBot.addObjectClasses( "referral", "extensibleObject" ); wizardBot.clickNextButton(); wizardBot.setRdnType( 1, "cn" ); wizardBot.setRdnValue( 1, "referral" ); wizardBot.clickNextButton(); // 389ds doesn't define ref as mandatory attribute if ( server.getType() == LdapServerType.Fedora389ds ) { NewAttributeWizardBot newAttributeWizardBot = wizardBot.openNewAttributeWizard(); assertTrue( newAttributeWizardBot.isVisible() ); newAttributeWizardBot.typeAttributeType( "ref" ); newAttributeWizardBot.clickFinishButton(); wizardBot.cancelEditValue(); wizardBot.activate(); } wizardBot.editValue( "ref", "" ); wizardBot.typeValueAndFinish( server.getLdapUrl() + "/" + USER1_DN.getName() ); wizardBot.clickFinishButton(); assertTrue( browserViewBot.existsEntry( path( TARGET_DN, "cn=referral" ) ) ); browserViewBot.selectEntry( path( TARGET_DN, "cn=referral" ) ); } /** * Test for DIRSTUDIO-409. * * Try to create an entry below an referral object. * The connection selection dialog pops up and we cancel the selection. * No error should occur and the wizard is not closed. */ @ParameterizedTest @LdapServersSource public void testCreateEntryBelowReferralObjectCancel( TestLdapServer server ) throws Exception { // set ManageDsaIT control Connection connection = connectionsViewBot.createTestConnection( server ); connection.getConnectionParameter().setExtendedIntProperty( IBrowserConnection.CONNECTION_PARAMETER_REFERRALS_HANDLING_METHOD, ReferralHandlingMethod.IGNORE.ordinal() ); connection.getConnectionParameter().setExtendedBoolProperty( IBrowserConnection.CONNECTION_PARAMETER_MANAGE_DSA_IT, true ); browserViewBot.selectEntry( path( REFERRAL_TO_MISC_DN ) ); NewEntryWizardBot wizardBot = browserViewBot.openNewEntryWizard(); wizardBot.selectCreateEntryFromScratch(); wizardBot.clickNextButton(); wizardBot.addObjectClasses( "organization" ); wizardBot.clickNextButton(); wizardBot.setRdnType( 1, "o" ); wizardBot.setRdnValue( 1, "orgBelowReferral" ); wizardBot.clickNextButton(); ReferralDialogBot referralDialogBot = wizardBot.clickFinishButtonExpectingReferralDialog(); assertTrue( referralDialogBot.isVisible() ); // click cancel button, check the wizard is not closed referralDialogBot.clickCancelButton(); // timing issues, use ugly sleep for now, should use some condition but have no idea. SWTUtils.sleep( 1000 ); assertTrue( wizardBot.isVisible() ); assertTrue( wizardBot.isFinishButtonEnabled() ); wizardBot.clickCancelButton(); assertFalse( browserViewBot.existsEntry( path( MISC_DN, "o=orgBelowReferral" ) ) ); } /** * Test for DIRSTUDIO-409. * * Try to create an entry below an referral object. * The connection selection dialog pops up and we select a connection. * The entry is created under the target entry. */ @ParameterizedTest @LdapServersSource public void testCreateEntryBelowReferralObjectFollow( TestLdapServer server ) throws Exception { // set ManageDsaIT control Connection connection = connectionsViewBot.createTestConnection( server ); connection.getConnectionParameter().setExtendedIntProperty( IBrowserConnection.CONNECTION_PARAMETER_REFERRALS_HANDLING_METHOD, ReferralHandlingMethod.IGNORE.ordinal() ); connection.getConnectionParameter().setExtendedBoolProperty( IBrowserConnection.CONNECTION_PARAMETER_MANAGE_DSA_IT, true ); browserViewBot.selectEntry( path( REFERRAL_TO_MISC_DN ) ); NewEntryWizardBot wizardBot = browserViewBot.openNewEntryWizard(); wizardBot.selectCreateEntryFromScratch(); wizardBot.clickNextButton(); wizardBot.addObjectClasses( "organization" ); wizardBot.clickNextButton(); wizardBot.setRdnType( 1, "o" ); wizardBot.setRdnValue( 1, "orgBelowReferral" ); wizardBot.clickNextButton(); ReferralDialogBot referralDialogBot = wizardBot.clickFinishButtonExpectingReferralDialog(); assertTrue( referralDialogBot.isVisible() ); // follow referral, click ok button referralDialogBot.selectConnection( connection.getName() ); referralDialogBot.clickOkButton(); // check entry was created under referral target entry assertTrue( browserViewBot.existsEntry( path( MISC_DN, "o=orgBelowReferral" ) ) ); browserViewBot.selectEntry( path( MISC_DN, "o=orgBelowReferral" ) ); } /** * Test for DIRSTUDIO-589, DIRSTUDIO-591, DIRSHARED-38. * * Create an entry with sharp in DN: cn=\#123456. */ @ParameterizedTest @LdapServersSource(mode = Mode.All) public void testCreateEntryWithSharp( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); browserViewBot.selectEntry( path( TARGET_DN ) ); NewEntryWizardBot wizardBot = browserViewBot.openNewEntryWizard(); wizardBot.selectCreateEntryFromScratch(); wizardBot.clickNextButton(); wizardBot.addObjectClasses( "inetOrgPerson" ); wizardBot.clickNextButton(); wizardBot.setRdnType( 1, "cn" ); wizardBot.setRdnValue( 1, "#123456" ); wizardBot.clickNextButton(); wizardBot.typeValueAndFinish( "#123456" ); wizardBot.clickFinishButton(); if ( server.getType() == LdapServerType.ApacheDS ) { assertTrue( browserViewBot.existsEntry( path( TARGET_DN, "cn=\\#123456" ) ) ); browserViewBot.selectEntry( path( TARGET_DN, "cn=\\#123456" ) ); } else { assertTrue( browserViewBot.existsEntry( path( TARGET_DN, "cn=\\23123456" ) ) ); browserViewBot.selectEntry( path( TARGET_DN, "cn=\\23123456" ) ); } } /** * Test for DIRSTUDIO-603, DIRSHARED-41. * * Create an entry with multi-valued RDN and numeric OID (IP address) in RDN value. */ @ParameterizedTest @LdapServersSource public void testCreateMvRdnWithNumericOid( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); browserViewBot.selectEntry( path( TARGET_DN ) ); NewEntryWizardBot wizardBot = browserViewBot.openNewEntryWizard(); wizardBot.selectCreateEntryFromScratch(); wizardBot.clickNextButton(); wizardBot.addObjectClasses( "device" ); wizardBot.addObjectClasses( "ipHost" ); wizardBot.clickNextButton(); wizardBot.clickAddRdnButton( 1 ); wizardBot.setRdnType( 1, "cn" ); wizardBot.setRdnValue( 1, "loopback" ); wizardBot.setRdnType( 2, "ipHostNumber" ); wizardBot.setRdnValue( 2, "127.0.0.1" ); wizardBot.clickNextButton(); wizardBot.clickFinishButton(); assertTrue( browserViewBot.existsEntry( path( TARGET_DN, "cn=loopback+ipHostNumber=127.0.0.1" ) ) ); browserViewBot.selectEntry( path( TARGET_DN, "cn=loopback+ipHostNumber=127.0.0.1" ) ); } /** * Test for DIRSTUDIO-987, DIRSTUDIO-271. * * Create and browse entry with multi-valued RDN with same attribute type. */ @ParameterizedTest @LdapServersSource(mode = Mode.All, except = LdapServerType.OpenLdap, reason = "Multi-valued RDN with same attribute is not supported by OpenLDAP") public void testCreateMvRdnWithSameAttribute( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); browserViewBot.selectEntry( path( TARGET_DN ) ); NewEntryWizardBot wizardBot = browserViewBot.openNewEntryWizard(); wizardBot.selectCreateEntryFromScratch(); wizardBot.clickNextButton(); wizardBot.addObjectClasses( "locality" ); wizardBot.clickNextButton(); wizardBot.clickAddRdnButton( 1 ); wizardBot.clickAddRdnButton( 2 ); wizardBot.setRdnType( 1, "l" ); wizardBot.setRdnValue( 1, "eu" ); wizardBot.setRdnType( 2, "l" ); wizardBot.setRdnValue( 2, "de" ); wizardBot.setRdnType( 3, "l" ); wizardBot.setRdnValue( 3, "Berlin" ); wizardBot.clickNextButton(); wizardBot.clickFinishButton(); if ( server.getType() == LdapServerType.Fedora389ds ) { // 389ds sorts the RDN assertTrue( browserViewBot.existsEntry( path( TARGET_DN, "l=Berlin+l=de+l=eu" ) ) ); browserViewBot.selectEntry( path( TARGET_DN, "l=Berlin+l=de+l=eu" ) ); } else { assertTrue( browserViewBot.existsEntry( path( TARGET_DN, "l=eu+l=de+l=Berlin" ) ) ); browserViewBot.selectEntry( path( TARGET_DN, "l=eu+l=de+l=Berlin" ) ); } } /** * DIRSTUDIO-1267: Test creation of new entry with binary option and language tags. */ @ParameterizedTest @LdapServersSource public void testCreateEntryWithBinaryOptionAndLanguageTags( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); String certFile = ResourceUtils.prepareInputFile( "rfc5280_cert1.cer" ); String crlFile = ResourceUtils.prepareInputFile( "rfc5280_crl.crl" ); browserViewBot.selectEntry( path( TARGET_DN ) ); NewEntryWizardBot wizardBot = browserViewBot.openNewEntryWizard(); wizardBot.selectCreateEntryFromScratch(); wizardBot.clickNextButton(); wizardBot.addObjectClasses( "organizationalRole" ); wizardBot.addObjectClasses( "certificationAuthority" ); wizardBot.clickNextButton(); wizardBot.setRdnType( 1, "cn" ); wizardBot.setRdnValue( 1, "asdf" ); wizardBot.clickNextButton(); // by default the hex or certificate editor is opened, close it try { new HexEditorDialogBot().clickCancelButton(); } catch ( WidgetNotFoundException e ) { } try { new CertificateEditorDialogBot().clickCancelButton(); } catch ( WidgetNotFoundException e ) { } wizardBot.activate(); NewAttributeWizardBot newAttributeWizardBot = wizardBot.openNewAttributeWizard(); assertTrue( newAttributeWizardBot.isVisible() ); newAttributeWizardBot.typeAttributeType( "description" ); newAttributeWizardBot.clickNextButton(); newAttributeWizardBot.setLanguageTag( "en", "us" ); newAttributeWizardBot.clickFinishButton(); wizardBot.cancelEditValue(); wizardBot.activate(); wizardBot.editValue( "description;lang-en-us", null ); SWTUtils.sleep( 1000 ); wizardBot.typeValueAndFinish( "English description" ); wizardBot.activate(); EditAttributeWizardBot editAttributeBot = wizardBot.editAttribute( "cACertificate", null ); editAttributeBot.clickNextButton(); editAttributeBot.selectBinaryOption(); editAttributeBot.clickFinishButton(); wizardBot.activate(); wizardBot.editValue( "cACertificate;binary", null ); CertificateEditorDialogBot certEditorBot = new CertificateEditorDialogBot(); certEditorBot.setWaitAfterClickOkButton( false ); assertTrue( certEditorBot.isVisible() ); certEditorBot.typeFile( certFile ); certEditorBot.clickOkButton(); wizardBot.activate(); editAttributeBot = wizardBot.editAttribute( "certificateRevocationList", null ); editAttributeBot.clickNextButton(); editAttributeBot.selectBinaryOption(); editAttributeBot.clickFinishButton(); wizardBot.activate(); wizardBot.editValue( "certificateRevocationList;binary", null ); HexEditorDialogBot hexEditorBot = new HexEditorDialogBot(); hexEditorBot.setWaitAfterClickOkButton( false ); assertTrue( hexEditorBot.isVisible() ); hexEditorBot.typeFile( crlFile ); hexEditorBot.clickOkButton(); wizardBot.activate(); editAttributeBot = wizardBot.editAttribute( "authorityRevocationList", null ); editAttributeBot.clickNextButton(); editAttributeBot.selectBinaryOption(); editAttributeBot.clickFinishButton(); wizardBot.activate(); wizardBot.editValue( "authorityRevocationList;binary", null ); assertTrue( hexEditorBot.isVisible() ); hexEditorBot.typeFile( crlFile ); hexEditorBot.clickOkButton(); wizardBot.activate(); wizardBot.clickFinishButton(); assertTrue( browserViewBot.existsEntry( path( TARGET_DN, "cn=asdf" ) ) ); browserViewBot.selectEntry( path( TARGET_DN, "cn=asdf" ) ); EntryEditorBot entryEditorBot = studioBot.getEntryEditorBot( dn( "cn=asdf", TARGET_DN ).getName() ); entryEditorBot.activate(); modificationLogsViewBot.waitForText( "cACertificate;binary:: MIICPjCCAaeg" ); assertTrue( entryEditorBot.getAttributeValues() .contains( "cACertificate;binary: X.509v3: CN=Example CA,DC=example,DC=com" ) ); modificationLogsViewBot.waitForText( "certificateRevocationList;binary:: MIIBYDCBygIB" ); assertTrue( entryEditorBot.getAttributeValues() .contains( "certificateRevocationList;binary: Binary Data (356 Bytes)" ) ); modificationLogsViewBot.waitForText( "authorityRevocationList;binary:: MIIBYDCBygIB" ); assertTrue( entryEditorBot.getAttributeValues() .contains( "authorityRevocationList;binary: Binary Data (356 Bytes)" ) ); modificationLogsViewBot.waitForText( "description;lang-en-us: English description" ); assertTrue( entryEditorBot.getAttributeValues() .contains( "description;lang-en-us: English description" ) ); } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/tests/test.integration.ui/src/main/java/org/apache/directory/studio/test/integration/ui/ProgressViewTest.java
tests/test.integration.ui/src/main/java/org/apache/directory/studio/test/integration/ui/ProgressViewTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.studio.test.integration.ui; import org.apache.directory.studio.test.integration.junit5.LdapServersSource; import org.apache.directory.studio.test.integration.junit5.TestLdapServer; import org.apache.directory.studio.test.integration.ui.bots.ProgressViewBot; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; /** * Tests the Progress view. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class ProgressViewTest extends AbstractTestBase { @Test public void testRemoveAllFinishedOperations() throws Exception { ProgressViewBot view = studioBot.getProgressView(); view.removeAllFinishedOperations(); } @ParameterizedTest @LdapServersSource public void testNoRemainingOpenConnectionJobs( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); connectionsViewBot.createTestConnection( server ); connectionsViewBot.createTestConnection( server ); // actual assertion is done in Assertions.genericTearDownAssertions() } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/tests/test.integration.ui/src/main/java/org/apache/directory/studio/test/integration/ui/SchemaBrowserTest.java
tests/test.integration.ui/src/main/java/org/apache/directory/studio/test/integration/ui/SchemaBrowserTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.studio.test.integration.ui; import static org.apache.directory.studio.test.integration.junit5.TestFixture.USER8_DN; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.ldapbrowser.core.BrowserCorePlugin; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.schema.Schema; import org.apache.directory.studio.test.integration.junit5.LdapServerType; import org.apache.directory.studio.test.integration.junit5.LdapServersSource; import org.apache.directory.studio.test.integration.junit5.TestLdapServer; import org.apache.directory.studio.test.integration.ui.bots.ErrorDialogBot; import org.apache.directory.studio.test.integration.ui.bots.SchemaBrowserBot; import org.junit.jupiter.params.ParameterizedTest; /** * Tests the Schema browser. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class SchemaBrowserTest extends AbstractTestBase { /** * Test for DIRSTUDIO-1061 (RawSchemaDefinition always shows single hyphen/dash) */ @ParameterizedTest @LdapServersSource public void testRawSchemaDefinitionIsFilled( TestLdapServer server ) throws Exception { Connection connection = connectionsViewBot.createTestConnection( server ); connectionsViewBot.select( connection.getName() ); SchemaBrowserBot schemaBrowser = connectionsViewBot.openSchemaBrowser(); //schemaBrowser.activateObjectClassesTab(); schemaBrowser.selectObjectClass( "account" ); String rawSchemaDefinition = schemaBrowser.getRawSchemaDefinition(); assertNotNull( rawSchemaDefinition ); assertTrue( rawSchemaDefinition.contains( "account" ) ); } @ParameterizedTest @LdapServersSource(only = LdapServerType.OpenLdap, reason = "OpenLDAP specific test") public void testNoPermissionToReadSchema( TestLdapServer server ) throws Exception { Connection connection = connectionsViewBot.createTestConnection( server ); // Close connection and reset cached schema connectionsViewBot.closeSelectedConnections(); IBrowserConnection browserConnection = BrowserCorePlugin.getDefault().getConnectionManager() .getBrowserConnection( connection ); browserConnection.setSchema( Schema.DEFAULT_SCHEMA ); // Open connection as uid=user.8 which is not allowed to read cn=subschema connection.setBindPrincipal( USER8_DN.getName() ); connection.setBindPassword( "password" ); ErrorDialogBot errorDialog = connectionsViewBot.openSelectedConnectionExpectingNoSchemaProvidedErrorDialog(); assertThat( errorDialog.getErrorDetails(), containsString( "No schema information returned by server, using default schema." ) ); errorDialog.clickOkButton(); // Verify default schema is used SchemaBrowserBot schemaBrowser = connectionsViewBot.openSchemaBrowser(); schemaBrowser.selectObjectClass( "DEFAULTSCHEMA" ); String rawSchemaDefinition = schemaBrowser.getRawSchemaDefinition(); assertNotNull( rawSchemaDefinition ); assertTrue( rawSchemaDefinition.contains( "This is the Default Schema" ) ); // Verify browser browserViewBot.selectEntry( ROOT_DSE_PATH ); } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/tests/test.integration.ui/src/main/java/org/apache/directory/studio/test/integration/ui/GssApiTest.java
tests/test.integration.ui/src/main/java/org/apache/directory/studio/test/integration/ui/GssApiTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.studio.test.integration.ui; import static org.apache.directory.studio.test.integration.ui.utils.Constants.LOCALHOST; import static org.junit.jupiter.api.Assertions.assertNull; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.net.URL; import java.nio.charset.StandardCharsets; import javax.security.auth.kerberos.KerberosPrincipal; import org.apache.directory.api.util.FileUtils; import org.apache.directory.api.util.IOUtils; import org.apache.directory.studio.test.integration.ui.bots.ApacheDSConfigurationEditorBot; import org.apache.directory.studio.test.integration.ui.bots.BrowserViewBot; import org.apache.directory.studio.test.integration.ui.bots.ImportWizardBot; import org.apache.directory.studio.test.integration.ui.bots.NewApacheDSServerWizardBot; import org.apache.directory.studio.test.integration.ui.bots.NewConnectionWizardBot; import org.apache.directory.studio.test.integration.ui.utils.Constants; import org.eclipse.core.runtime.Platform; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; import org.junit.jupiter.api.condition.DisabledForJreRange; import org.junit.jupiter.api.condition.JRE; /** * Tests secure connection handling. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> * @version $Rev$, $Date$ */ @DisabledForJreRange(min = JRE.JAVA_16) public class GssApiTest extends AbstractTestBase { private static final String serverName = "GssApiTest"; private static int ldapPort; private static int kdcPort; private TestInfo testInfo; @BeforeAll public static void skipGssApiTestIfNoDefaultRealmIsConfigured() { try { /* * When creating a KerberosPrincipial without realm the default realm is looked up. * If no default realm is defined (e.g. as not /etc/krb5.conf exists) an exception is throws. * The test is skipped in that case as it won't succeed anyway. */ new KerberosPrincipal( "hnelson" ); } catch ( IllegalArgumentException e ) { Assumptions.assumeTrue( false, "Skipping tests as no default realm (/etc/krb5.conf) is configured" ); } } @BeforeEach public void beforeEach( TestInfo testInfo ) { this.testInfo = testInfo; } @AfterEach public void afterEach() throws Exception { // stop ApacheDS serversViewBot.stopServer( serverName ); serversViewBot.waitForServerStop( serverName ); } private String getConnectionName() { return testInfo.getTestMethod().map( Method::getName ).orElse( "null" ) + " " + testInfo.getDisplayName(); } @Test public void testGssApiObtainTgtAndUseManualConfigurationAndObtainServiceTicket() throws Exception { // create the server createServer( serverName ); // configure ApacheDS and KDC server configureApacheDS( serverName ); // start ApacheDS serversViewBot.runServer( serverName ); serversViewBot.waitForServerStart( serverName ); // import KDC data connectionsViewBot.createTestConnection( "GssApiTest", ldapPort ); importData(); // connect with GSSAPI authentication NewConnectionWizardBot wizardBot = connectionsViewBot.openNewConnectionWizard(); wizardBot.typeConnectionName( getConnectionName() ); wizardBot.typeHost( LOCALHOST ); wizardBot.typePort( ldapPort ); wizardBot.clickNextButton(); wizardBot.selectGssApiAuthentication(); wizardBot.selectObtainTgtFromKdc(); wizardBot.typeUser( "hnelson" ); wizardBot.typePassword( "secret" ); wizardBot.selectUseManualConfiguration(); wizardBot.typeKerberosRealm( "EXAMPLE.COM" ); wizardBot.typeKdcHost( LOCALHOST ); wizardBot.typeKdcPort( kdcPort ); // check the connection String result = wizardBot.clickCheckAuthenticationButton(); assertNull( result, "Expected OK" ); wizardBot.clickCancelButton(); } private void createServer( String serverName ) { // Showing view serversViewBot.show(); // Opening wizard NewApacheDSServerWizardBot wizardBot = serversViewBot.openNewServerWizard(); // Filling fields of the wizard wizardBot.selectApacheDS200(); wizardBot.typeServerName( serverName ); // Closing wizard wizardBot.clickFinishButton(); serversViewBot.waitForServer( serverName ); } private void configureApacheDS( String serverName ) throws Exception { ApacheDSConfigurationEditorBot editorBot = serversViewBot.openConfigurationEditor( serverName ); editorBot.enableKerberosServer(); editorBot.setAvailablePorts(); ldapPort = editorBot.getLdapPort(); kdcPort = editorBot.getKerberosPort(); editorBot.setKdcRealm( "EXAMPLE.COM" ); editorBot.setKdcSearchBase( "dc=security,dc=example,dc=com" ); editorBot.setSaslHost( Constants.LOCALHOST ); editorBot.setSaslPrincipal( "ldap/" + Constants.LOCALHOST + "@EXAMPLE.COM" ); editorBot.setSaslSearchBase( "dc=security,dc=example,dc=com" ); editorBot.save(); editorBot.close(); } private void importData() throws IOException { URL url = Platform.getInstanceLocation().getURL(); String destFile = url.getFile() + "GssApiTest_" + System.currentTimeMillis() + ".ldif"; InputStream is = getClass().getResourceAsStream( "GssApiTest.ldif" ); String ldifContent = IOUtils.toString( is, StandardCharsets.UTF_8 ); ldifContent = ldifContent.replace( "HOSTNAME", Constants.LOCALHOST ); FileUtils.writeStringToFile( new File( destFile ), ldifContent, StandardCharsets.UTF_8, false ); BrowserViewBot browserViewBot = studioBot.getBrowserView(); browserViewBot.selectEntry( "DIT", "Root DSE", "dc=example,dc=com" ); ImportWizardBot importWizardBot = browserViewBot.openImportLdifWizard(); importWizardBot.typeFile( destFile ); importWizardBot.clickFinishButton(); browserViewBot.waitForEntry( "DIT", "Root DSE", "dc=example,dc=com", "dc=security" ); } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/tests/test.integration.ui/src/main/java/org/apache/directory/studio/test/integration/ui/ConnectionViewTest.java
tests/test.integration.ui/src/main/java/org/apache/directory/studio/test/integration/ui/ConnectionViewTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.studio.test.integration.ui; import static org.junit.jupiter.api.Assertions.assertEquals; import java.net.URL; import org.apache.directory.studio.test.integration.junit5.LdapServersSource; import org.apache.directory.studio.test.integration.junit5.TestLdapServer; import org.apache.directory.studio.test.integration.ui.bots.ExportConnectionsWizardBot; import org.apache.directory.studio.test.integration.ui.bots.ImportConnectionsWizardBot; import org.apache.directory.studio.test.integration.ui.bots.NewConnectionFolderDialogBot; import org.apache.directory.studio.test.integration.ui.bots.NewConnectionWizardBot; import org.eclipse.core.runtime.Platform; import org.junit.jupiter.params.ParameterizedTest; /** * Tests the LDAP browser. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> * @version $Rev$, $Date$ */ public class ConnectionViewTest extends AbstractTestBase { @ParameterizedTest @LdapServersSource public void testCreateAndDeleteConnections( TestLdapServer server ) { String connectionName = "Test connection 1"; createConnection( connectionName, server ); // ensure connection is visible in Connections view assertEquals( 1, connectionsViewBot.getCount() ); // delete connection connectionsViewBot.select( connectionName ); connectionsViewBot.openDeleteConnectionDialog().clickOkButton(); // ensure connection is no longer visible in Connections view assertEquals( 0, connectionsViewBot.getCount() ); } @ParameterizedTest @LdapServersSource public void testCreateAndDeleteConnectionFolders( TestLdapServer server ) { String folderName = "Connection folder 1"; String subFolder1Name = "Connection folder 2"; String subFolder2Name = "Connection folder 3"; // create one folder createConnectionFolder( folderName ); // ensure folder is visible assertEquals( 1, connectionsViewBot.getCount() ); // create two sub folders connectionsViewBot.select( folderName ); createConnectionFolder( subFolder1Name ); connectionsViewBot.select( folderName ); createConnectionFolder( subFolder2Name ); // ensure connection folders are visible assertEquals( 3, connectionsViewBot.getCount() ); // delete one sub folder connectionsViewBot.select( folderName, subFolder1Name ); connectionsViewBot.openDeleteConnectionFolderDialog().clickOkButton(); // ensure connection folders are visible assertEquals( 2, connectionsViewBot.getCount() ); // delete connection folder connectionsViewBot.select( folderName ); connectionsViewBot.openDeleteConnectionFolderDialog().clickOkButton(); // ensure folders no longer exist assertEquals( 0, connectionsViewBot.getCount() ); } @ParameterizedTest @LdapServersSource public void testExportImportConnections( TestLdapServer server ) throws Exception { String connection1Name = "Test connection 1"; String connection2Name = "Test connection 2"; String connection3Name = "Test connection 3"; String folderName = "Connection folder 1"; String subFolder1Name = "Connection folder 2"; String subFolder2Name = "Connection folder 3"; // create connections and folders createConnection( connection1Name, server ); createConnectionFolder( folderName ); connectionsViewBot.select( folderName ); createConnection( connection2Name, server ); connectionsViewBot.select( folderName ); createConnectionFolder( subFolder1Name ); connectionsViewBot.select( folderName, subFolder1Name ); createConnection( connection3Name, server ); connectionsViewBot.select( folderName ); createConnectionFolder( subFolder2Name ); // verify connections and folders exist assertEquals( 6, connectionsViewBot.getCount() ); connectionsViewBot.select( folderName ); connectionsViewBot.select( folderName, subFolder1Name ); connectionsViewBot.select( folderName, subFolder2Name ); connectionsViewBot.select( connection1Name ); connectionsViewBot.select( folderName, connection2Name ); connectionsViewBot.select( folderName, subFolder1Name, connection3Name ); // export connections and folders URL url = Platform.getInstanceLocation().getURL(); final String file = url.getFile() + "ImportExportConnections" + server.getType() + ".zip"; ExportConnectionsWizardBot exportConnectionsWizardBot = connectionsViewBot.openExportConnectionsWizard(); exportConnectionsWizardBot.typeFile( file ); exportConnectionsWizardBot.clickFinishButton(); // delete connections and folders connectionsViewBot.deleteTestConnections(); assertEquals( 0, connectionsViewBot.getCount() ); // import connections and folders ImportConnectionsWizardBot importConnectionsWizardBot = connectionsViewBot.openImportConnectionsWizard(); importConnectionsWizardBot.typeFile( file ); importConnectionsWizardBot.clickFinishButton(); // verify connections and folders exist assertEquals( 6, connectionsViewBot.getCount() ); connectionsViewBot.select( folderName ); connectionsViewBot.select( folderName, subFolder1Name ); connectionsViewBot.select( folderName, subFolder2Name ); connectionsViewBot.select( connection1Name ); connectionsViewBot.select( folderName, connection2Name ); connectionsViewBot.select( folderName, subFolder1Name, connection3Name ); } private void createConnection( String connectionName, TestLdapServer server ) { NewConnectionWizardBot wizardBot = connectionsViewBot.openNewConnectionWizard(); // enter connection parameter wizardBot.typeConnectionName( connectionName ); wizardBot.typeHost( server.getHost() ); wizardBot.typePort( server.getPort() ); // jump to auth page wizardBot.clickNextButton(); // enter authentication parameters wizardBot.typeUser( server.getAdminDn() ); wizardBot.typePassword( server.getAdminPassword() ); // finish dialog wizardBot.clickFinishButton( true ); } private void createConnectionFolder( String folderName ) { NewConnectionFolderDialogBot newConnectionFolderDialog = connectionsViewBot.openNewConnectionFolderDialog(); newConnectionFolderDialog.setConnectionFoldername( folderName ); newConnectionFolderDialog.clickOkButton(); } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/tests/test.integration.ui/src/main/java/org/apache/directory/studio/test/integration/ui/SwtResourcesTest.java
tests/test.integration.ui/src/main/java/org/apache/directory/studio/test/integration/ui/SwtResourcesTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.studio.test.integration.ui; import static org.apache.directory.studio.test.integration.junit5.TestFixture.MISC_DN; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import org.apache.directory.studio.test.integration.junit5.LdapServersSource; import org.apache.directory.studio.test.integration.junit5.TestLdapServer; import org.apache.directory.studio.test.integration.ui.bots.DeleteDialogBot; import org.apache.directory.studio.test.integration.ui.bots.NewEntryWizardBot; import org.eclipse.swt.graphics.DeviceData; import org.eclipse.swtbot.swt.finder.SWTBot; import org.eclipse.swtbot.swt.finder.finders.UIThreadRunnable; import org.eclipse.swtbot.swt.finder.results.IntResult; import org.junit.jupiter.params.ParameterizedTest; /** * Tests allocation of SWT Resources. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> * @version $Rev$, $Date$ */ public class SwtResourcesTest extends AbstractTestBase { /** * Test for DIRSTUDIO-319. * * Creates multiple entries using the New Entry wizard. Checks that we don't * allocate too much SWT resources during the run. */ @ParameterizedTest @LdapServersSource public void testSwtResourcesDelta( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); // run the new entry wizard once to ensure all SWT resources are created createAndDeleteEntry( "testSwtResourcesDelta" + 0 ); // remember the SWT objects before the run int beforeObjectCount = getSwtObjectCount(); // now lets run the new entry wizard it several times for ( int i = 1; i <= 8; i++ ) { createAndDeleteEntry( "testSwtResourcesDelta" + i ); } // get the SWT objects after the run int afterObjectCount = getSwtObjectCount(); // we expect none or only very few additional SWT objects assertTrue( afterObjectCount - beforeObjectCount < 5, "Too many SWT resources were allocated in testSwtResourcesDelta: before=" + beforeObjectCount + ", after=" + afterObjectCount ); } /** * Ensure that we have not allocated too many SWT resources during the * complete test suite. */ @ParameterizedTest @LdapServersSource public void testSwtResourcesCount( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); int swtObjectCount = getSwtObjectCount(); System.out.println( "### SWT resouces count: " + swtObjectCount ); assertTrue( swtObjectCount < 1500, "Too many SWT resources were allocated: " + swtObjectCount ); } private int getSwtObjectCount() { final SWTBot bot = new SWTBot(); return UIThreadRunnable.syncExec( bot.getDisplay(), new IntResult() { public Integer run() { DeviceData info = bot.getDisplay().getDeviceData(); if ( !info.tracking ) { fail( "To run this test options 'org.eclipse.ui/debug' and 'org.eclipse.ui/trace/graphics' must be true." ); } return info.objects.length; } } ); } private void createAndDeleteEntry( final String name ) throws Exception { browserViewBot.selectAndExpandEntry( path( MISC_DN ) ); NewEntryWizardBot wizardBot = browserViewBot.openNewEntryWizard(); wizardBot.selectCreateEntryFromScratch(); wizardBot.clickNextButton(); wizardBot.addObjectClasses( "organization" ); wizardBot.clickNextButton(); wizardBot.setRdnType( 1, "o" ); wizardBot.setRdnValue( 1, name ); wizardBot.clickNextButton(); wizardBot.clickFinishButton(); assertTrue( browserViewBot.existsEntry( path( MISC_DN, "o=" + name ) ) ); browserViewBot.selectEntry( path( MISC_DN, "o=" + name ) ); DeleteDialogBot dialog = browserViewBot.openDeleteDialog(); dialog.clickOkButton(); } }
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
false
apache/directory-studio
https://github.com/apache/directory-studio/blob/e55b93d729a60c986fc93e52f9519f4bbdf51252/tests/test.integration.ui/src/main/java/org/apache/directory/studio/test/integration/ui/BrowserTest.java
tests/test.integration.ui/src/main/java/org/apache/directory/studio/test/integration/ui/BrowserTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.studio.test.integration.ui; import static org.apache.directory.studio.test.integration.junit5.TestFixture.ALIAS_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.CONTEXT_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.DN_WITH_ESCAPED_CHARACTERS_BACKSLASH_PREFIXED; import static org.apache.directory.studio.test.integration.junit5.TestFixture.DN_WITH_ESCAPED_CHARACTERS_HEX_PAIR_ESCAPED; import static org.apache.directory.studio.test.integration.junit5.TestFixture.DN_WITH_IP_HOST_NUMBER; import static org.apache.directory.studio.test.integration.junit5.TestFixture.DN_WITH_LEADING_SHARP_BACKSLASH_PREFIXED; import static org.apache.directory.studio.test.integration.junit5.TestFixture.DN_WITH_LEADING_SHARP_HEX_PAIR_ESCAPED; import static org.apache.directory.studio.test.integration.junit5.TestFixture.DN_WITH_TRAILING_EQUALS_CHARACTER; import static org.apache.directory.studio.test.integration.junit5.TestFixture.DN_WITH_TRAILING_EQUALS_CHARACTER_HEX_PAIR_ESCAPED; import static org.apache.directory.studio.test.integration.junit5.TestFixture.MISC_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.MULTI_VALUED_RDN_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.REFERRAL_TO_USERS_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.USER1_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.USER2_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.USER3_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.USERS_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.dn; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.lang3.StringUtils; import org.apache.directory.api.ldap.model.entry.DefaultEntry; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.Connection.AliasDereferencingMethod; import org.apache.directory.studio.connection.core.Connection.ReferralHandlingMethod; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreMessages; import org.apache.directory.studio.ldapbrowser.core.BrowserCorePlugin; import org.apache.directory.studio.ldapbrowser.core.events.EventRegistry; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.impl.Bookmark; import org.apache.directory.studio.ldapbrowser.ui.BrowserUIConstants; import org.apache.directory.studio.ldapbrowser.ui.BrowserUIPlugin; import org.apache.directory.studio.ldapbrowser.ui.editors.entry.EntryEditor; import org.apache.directory.studio.test.integration.junit5.LdapServerType; import org.apache.directory.studio.test.integration.junit5.LdapServersSource; import org.apache.directory.studio.test.integration.junit5.LdapServersSource.Mode; import org.apache.directory.studio.test.integration.junit5.TestLdapServer; import org.apache.directory.studio.test.integration.ui.bots.DeleteDialogBot; import org.apache.directory.studio.test.integration.ui.bots.EntryEditorBot; import org.apache.directory.studio.test.integration.ui.bots.ReferralDialogBot; import org.apache.directory.studio.test.integration.ui.utils.JobWatcher; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.swtbot.swt.finder.finders.UIThreadRunnable; import org.eclipse.swtbot.swt.finder.results.VoidResult; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IPropertyListener; import org.eclipse.ui.PlatformUI; import org.junit.jupiter.params.ParameterizedTest; /** * Tests the LDAP browser. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> * @version $Rev$, $Date$ */ public class BrowserTest extends AbstractTestBase { /** * Test for DIRSTUDIO-463. * * When expanding an entry in the browser only one search request * should be send to the server */ @ParameterizedTest @LdapServersSource public void testOnlyOneSearchRequestWhenExpandingEntry( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); browserViewBot.selectEntry( path( CONTEXT_DN ) ); // get number of search requests before expanding the entry String text = searchLogsViewBot.getSearchLogsText(); int countMatchesBefore = StringUtils.countMatches( text, "#!SEARCH REQUEST" ); // expand browserViewBot.expandEntry( path( CONTEXT_DN ) ); browserViewBot.waitForEntry( path( USERS_DN ) ); // get number of search requests after expanding the entry text = searchLogsViewBot.getSearchLogsText(); int countMatchesAfter = StringUtils.countMatches( text, "#!SEARCH REQUEST" ); assertEquals( 1, countMatchesAfter - countMatchesBefore, "Expected exactly 1 search request" ); assertEquals( "", modificationLogsViewBot.getModificationLogsText(), "No modification expected" ); } /** * Test for DIRSTUDIO-512. * * Verify minimum UI updates when deleting multiple entries. */ @ParameterizedTest @LdapServersSource public void testDeleteDoesNotUpdateUI( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); browserViewBot.selectEntry( path( USERS_DN ) ); browserViewBot.expandEntry( path( USERS_DN ) ); long fireCount0 = EventRegistry.getFireCount(); // delete String[] children = new String[] { "uid=user.1", "uid=user.2", "uid=user.3", "uid=user.4", "uid=user.5", "uid=user.6", "uid=user.7", "uid=user.8" }; browserViewBot.selectChildrenOfEntry( children, path( USERS_DN ) ); DeleteDialogBot deleteDialog = browserViewBot.openDeleteDialog(); deleteDialog.clickOkButton(); browserViewBot.selectEntry( path( USERS_DN ) ); long fireCount1 = EventRegistry.getFireCount(); // verify that only two events were fired during deletion long fireCount = fireCount1 - fireCount0; assertEquals( 2, fireCount, "Only 2 event firings expected when deleting multiple entries." ); } /** * Test for DIRSTUDIO-575. * * When opening a bookmark the entry editor should be opened and the * bookmark entry's attributes should be displayed. */ @ParameterizedTest @LdapServersSource public void testBookmark( TestLdapServer server ) throws Exception { // create a bookmark Connection connection = connectionsViewBot.createTestConnection( server ); IBrowserConnection browserConnection = BrowserCorePlugin.getDefault().getConnectionManager() .getBrowserConnection( connection ); browserConnection.getBookmarkManager().addBookmark( new Bookmark( browserConnection, USER1_DN, "Existing Bookmark" ) ); // select the bookmark browserViewBot.selectEntry( "Bookmarks", "Existing Bookmark" ); // check that entry editor was opened and attributes are visible EntryEditorBot entryEditorBot = studioBot.getEntryEditorBot( USER1_DN.getName() ); String dn = entryEditorBot.getDnText(); assertEquals( "DN: " + USER1_DN.getName(), dn ); List<String> attributeValues = entryEditorBot.getAttributeValues(); assertEquals( 23, attributeValues.size() ); assertTrue( attributeValues.contains( "uid: user.1" ) ); assertEquals( "", modificationLogsViewBot.getModificationLogsText(), "No modification expected" ); } /** * Test for DIRSTUDIO-481. * * Check proper operation of refresh action. */ @ParameterizedTest @LdapServersSource public void testRefreshParent( TestLdapServer server ) throws Exception { // check the entry doesn't exist yet connectionsViewBot.createTestConnection( server ); browserViewBot.expandEntry( path( MISC_DN ) ); Dn refreshDn = dn( "cn=refresh", MISC_DN ); assertFalse( browserViewBot.existsEntry( path( refreshDn ) ) ); // add the entry directly in the server server.withAdminConnection( conn -> { Entry entry = new DefaultEntry( conn.getSchemaManager() ); entry.setDn( refreshDn ); entry.add( "objectClass", "top", "person" ); entry.add( "cn", "refresh" ); entry.add( "sn", "refresh" ); conn.add( entry ); } ); // check the entry still isn't visible in the tree assertFalse( browserViewBot.existsEntry( path( refreshDn ) ) ); // refresh parent browserViewBot.selectEntry( path( MISC_DN ) ); browserViewBot.refresh(); // check the entry exists now browserViewBot.expandEntry( path( MISC_DN ) ); assertTrue( browserViewBot.existsEntry( path( refreshDn ) ) ); browserViewBot.selectEntry( path( refreshDn ) ); // delete the entry directly in the server server.withAdminConnection( conn -> { conn.delete( refreshDn ); } ); // check the entry still is visible in the tree assertTrue( browserViewBot.existsEntry( path( refreshDn ) ) ); // refresh parent browserViewBot.selectEntry( path( MISC_DN ) ); browserViewBot.refresh(); // check the entry doesn't exist now browserViewBot.expandEntry( path( MISC_DN ) ); assertFalse( browserViewBot.existsEntry( path( refreshDn ) ) ); } /** * Test for DIRSTUDIO-481. * * Check proper operation of refresh action. * * @throws Exception */ @ParameterizedTest @LdapServersSource public void testRefreshContextEntry( TestLdapServer server ) throws Exception { // check the entry doesn't exist yet connectionsViewBot.createTestConnection( server ); browserViewBot.expandEntry( path( MISC_DN ) ); Dn refreshDn = dn( "cn=refresh", MISC_DN ); assertFalse( browserViewBot.existsEntry( path( refreshDn ) ) ); // add the entry directly in the server server.withAdminConnection( conn -> { Entry entry = new DefaultEntry( conn.getSchemaManager() ); entry.setDn( refreshDn ); entry.add( "objectClass", "top", "person" ); entry.add( "cn", "refresh" ); entry.add( "sn", "refresh" ); conn.add( entry ); } ); // check the entry still isn't visible in the tree assertFalse( browserViewBot.existsEntry( path( refreshDn ) ) ); // refresh context entry browserViewBot.selectEntry( path( CONTEXT_DN ) ); browserViewBot.refresh(); // check the entry exists now browserViewBot.expandEntry( path( MISC_DN ) ); assertTrue( browserViewBot.existsEntry( path( refreshDn ) ) ); browserViewBot.selectEntry( path( refreshDn ) ); // delete the entry directly in the server server.withAdminConnection( connection -> { connection.delete( refreshDn ); } ); // check the entry still is visible in the tree assertTrue( browserViewBot.existsEntry( path( refreshDn ) ) ); // refresh context entry browserViewBot.selectEntry( path( CONTEXT_DN ) ); browserViewBot.refresh(); // check the entry doesn't exist now browserViewBot.expandEntry( path( MISC_DN ) ); assertFalse( browserViewBot.existsEntry( path( refreshDn ) ) ); } /** * Test for DIRSTUDIO-481. * * Check proper operation of refresh action. */ @ParameterizedTest @LdapServersSource public void testRefreshRootDSE( TestLdapServer server ) throws Exception { // check the entry doesn't exist yet connectionsViewBot.createTestConnection( server ); browserViewBot.expandEntry( path( MISC_DN ) ); Dn refreshDn = dn( "cn=refresh", MISC_DN ); assertFalse( browserViewBot.existsEntry( path( refreshDn ) ) ); // add the entry directly in the server server.withAdminConnection( connection -> { Entry entry = new DefaultEntry( connection.getSchemaManager() ); entry.setDn( refreshDn ); entry.add( "objectClass", "top", "person" ); entry.add( "cn", "refresh" ); entry.add( "sn", "refresh" ); connection.add( entry ); } ); // check the entry still isn't visible in the tree assertFalse( browserViewBot.existsEntry( path( refreshDn ) ) ); // refresh Root DSE browserViewBot.selectEntry( ROOT_DSE_PATH ); browserViewBot.refresh(); // check the entry exists now browserViewBot.expandEntry( path( MISC_DN ) ); assertTrue( browserViewBot.existsEntry( path( refreshDn ) ) ); browserViewBot.selectEntry( path( refreshDn ) ); // delete the entry directly in the server server.withAdminConnection( connection -> { connection.delete( refreshDn ); } ); // check the entry still is now visible in the tree assertTrue( browserViewBot.existsEntry( path( refreshDn ) ) ); // refresh Root DSE browserViewBot.selectEntry( ROOT_DSE_PATH ); browserViewBot.refresh(); // check the entry doesn't exist now browserViewBot.expandEntry( path( MISC_DN ) ); assertFalse( browserViewBot.existsEntry( path( refreshDn ) ) ); } /** * Test for DIRSTUDIO-481. * * Check proper operation of refresh action. */ @ParameterizedTest @LdapServersSource public void testRefreshSearchContinuation( TestLdapServer server ) throws Exception { Connection connection = connectionsViewBot.createTestConnection( server ); Dn refreshDn = dn( "cn=refresh", MISC_DN ); String[] pathToReferral = pathWithRefLdapUrl( server, MISC_DN ); String[] pathToRefreshViaReferral = path( pathToReferral, "cn=refresh" ); connection.getConnectionParameter().setExtendedIntProperty( IBrowserConnection.CONNECTION_PARAMETER_REFERRALS_HANDLING_METHOD, ReferralHandlingMethod.FOLLOW_MANUALLY.ordinal() ); browserViewBot.selectEntry( ROOT_DSE_PATH ); browserViewBot.refresh(); // check the entry doesn't exist yet ReferralDialogBot refDialog = browserViewBot.expandEntryExpectingReferralDialog( pathToReferral ); refDialog.clickOkButton(); assertFalse( browserViewBot.existsEntry( pathToRefreshViaReferral ) ); // add the entry directly in the server server.withAdminConnection( conn -> { Entry entry = new DefaultEntry( conn.getSchemaManager() ); entry.setDn( refreshDn ); entry.add( "objectClass", "top", "person" ); entry.add( "cn", "refresh" ); entry.add( "sn", "refresh" ); conn.add( entry ); } ); // check the entry still isn't visible in the tree assertFalse( browserViewBot.existsEntry( pathToRefreshViaReferral ) ); // refresh search continuation browserViewBot.selectEntry( pathToReferral ); browserViewBot.refresh(); // check the entry exists now browserViewBot.expandEntry( pathToReferral ); assertTrue( browserViewBot.existsEntry( pathToRefreshViaReferral ) ); browserViewBot.selectEntry( pathToRefreshViaReferral ); // delete the entry directly in the server server.withAdminConnection( conn -> { conn.delete( refreshDn ); } ); // check the entry still is visible in the tree assertTrue( browserViewBot.existsEntry( pathToRefreshViaReferral ) ); // refresh search continuation browserViewBot.selectEntry( pathToReferral ); browserViewBot.refresh(); // check the entry doesn't exist now browserViewBot.expandEntry( pathToReferral ); assertFalse( browserViewBot.existsEntry( pathToRefreshViaReferral ) ); } /** * Test for DIRSTUDIO-591. * (Error reading objects with # in DN) */ @ParameterizedTest @LdapServersSource(mode = Mode.All) public void testBrowseDnWithSharpAndHexSequence( TestLdapServer server ) throws Exception { Dn dn = DN_WITH_LEADING_SHARP_BACKSLASH_PREFIXED; if ( server.getType() == LdapServerType.OpenLdap || server.getType() == LdapServerType.Fedora389ds ) { dn = DN_WITH_LEADING_SHARP_HEX_PAIR_ESCAPED; } connectionsViewBot.createTestConnection( server ); assertTrue( browserViewBot.existsEntry( path( dn ) ) ); browserViewBot.selectEntry( path( dn ) ); assertEquals( "", modificationLogsViewBot.getModificationLogsText(), "No modification expected" ); } /** * Test for DIRSTUDIO-1172: Studio doesn't display entries with trailing =. */ @ParameterizedTest @LdapServersSource(mode = Mode.All) public void testBrowseDnWithTrailingEqualsCharacter( TestLdapServer server ) throws Exception { Dn dn = DN_WITH_TRAILING_EQUALS_CHARACTER; if ( server.getType() == LdapServerType.OpenLdap ) { dn = DN_WITH_TRAILING_EQUALS_CHARACTER_HEX_PAIR_ESCAPED; } connectionsViewBot.createTestConnection( server ); assertTrue( browserViewBot.existsEntry( path( dn ) ) ); browserViewBot.selectEntry( path( dn ) ); } /** * Test for DIRSTUDIO-1172: Studio doesn't display entries with trailing =. */ @ParameterizedTest @LdapServersSource(except = { LdapServerType.OpenLdap, LdapServerType.Fedora389ds }, reason = "Empty RDN value is not supported by OpenLDAP and 389ds") public void testBrowseDnWithEmptyRdnValue( TestLdapServer server ) throws Exception { Dn dn = dn( "cn=nghZwwtHgxgyvVbTQCYyeY+email=", MISC_DN ); server.withAdminConnection( connection -> { Entry entry = new DefaultEntry( connection.getSchemaManager() ); entry.setDn( dn ); entry.add( "objectClass", "top", "person", "extensibleObject" ); entry.add( "cn", "nghZwwtHgxgyvVbTQCYyeY" ); entry.add( "sn", "nghZwwtHgxgyvVbTQCYyeY" ); entry.add( "email", "" ); connection.add( entry ); } ); connectionsViewBot.createTestConnection( server ); assertTrue( browserViewBot.existsEntry( path( dn ) ) ); browserViewBot.selectEntry( path( dn ) ); } /** * Test for DIRSTUDIO-1151: DN with backslash not displayed */ @ParameterizedTest @LdapServersSource(mode = Mode.All) public void testBrowseDnWithBackslash( TestLdapServer server ) throws Exception { Dn dn = DN_WITH_ESCAPED_CHARACTERS_BACKSLASH_PREFIXED; if ( server.getType() == LdapServerType.OpenLdap || server.getType() == LdapServerType.Fedora389ds ) { dn = DN_WITH_ESCAPED_CHARACTERS_HEX_PAIR_ESCAPED; } connectionsViewBot.createTestConnection( server ); // expand parent and verify entry is visible browserViewBot.expandEntry( path( dn.getParent() ) ); assertTrue( browserViewBot.existsEntry( path( dn ) ) ); browserViewBot.selectEntry( path( dn ) ); // refresh entry and verify child is still visible browserViewBot.selectEntry( path( dn.getParent() ) ); browserViewBot.refresh(); assertTrue( browserViewBot.existsEntry( path( dn ) ) ); } /** * Test for DIRSTUDIO-597. * (Modification sent to the server while browsing through the DIT and refreshing entries) * * @throws Exception */ @ParameterizedTest @LdapServersSource public void testNoModificationWhileBrowsingAndRefreshing( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); boolean errorDialogAutomatedMode = ErrorDialog.AUTOMATED_MODE; ErrorDialog.AUTOMATED_MODE = false; String text = modificationLogsViewBot.getModificationLogsText(); assertEquals( "", text ); try { assertTrue( browserViewBot.existsEntry( path( MULTI_VALUED_RDN_DN ) ) ); for ( int i = 0; i < 5; i++ ) { // select entry and refresh browserViewBot.selectEntry( path( MULTI_VALUED_RDN_DN ) ); browserViewBot.refresh(); // select parent and refresh browserViewBot.selectEntry( path( MULTI_VALUED_RDN_DN.getParent() ) ); browserViewBot.refresh(); } } finally { // reset flag ErrorDialog.AUTOMATED_MODE = errorDialogAutomatedMode; } // check that modification logs is still empty // to ensure that no modification was sent to the server assertEquals( "", modificationLogsViewBot.getModificationLogsText(), "No modification expected" ); } /** * Test for DIRSTUDIO-603, DIRSHARED-41. * (Error browsing/entering rfc2307 compliant host entry.) */ @ParameterizedTest @LdapServersSource public void testBrowseDnWithIpHostNumber( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); assertTrue( browserViewBot.existsEntry( path( DN_WITH_IP_HOST_NUMBER ) ) ); browserViewBot.selectEntry( path( DN_WITH_IP_HOST_NUMBER ) ); } /** * DIRSTUDIO-637: copy/paste of attributes no longer works. * Test copy/paste of a value to a bookmark. */ @ParameterizedTest @LdapServersSource public void testCopyPasteValueToBookmark( TestLdapServer server ) throws Exception { // create a bookmark Connection connection = connectionsViewBot.createTestConnection( server ); IBrowserConnection browserConnection = BrowserCorePlugin.getDefault().getConnectionManager() .getBrowserConnection( connection ); browserConnection.getBookmarkManager().addBookmark( new Bookmark( browserConnection, MULTI_VALUED_RDN_DN, "My Bookmark" ) ); // copy a value browserViewBot.selectEntry( path( USER1_DN ) ); EntryEditorBot entryEditorBot = studioBot.getEntryEditorBot( USER1_DN.getName() ); entryEditorBot.activate(); entryEditorBot.copyValue( "uid", "user.1" ); // select the bookmark browserViewBot.selectEntry( "Bookmarks", "My Bookmark" ); entryEditorBot = studioBot.getEntryEditorBot( MULTI_VALUED_RDN_DN.getName() ); entryEditorBot.activate(); assertEquals( 8, entryEditorBot.getAttributeValues().size() ); // paste the value JobWatcher watcher = new JobWatcher( BrowserCoreMessages.jobs__execute_ldif_name ); browserViewBot.paste(); watcher.waitUntilDone(); // assert pasted value visible in editor assertEquals( 9, entryEditorBot.getAttributeValues().size() ); entryEditorBot.getAttributeValues().contains( "uid: user.1" ); // assert pasted value was written to directory server.withAdminConnection( conn -> { Entry entry = conn.lookup( MULTI_VALUED_RDN_DN ); assertTrue( entry.contains( "uid", "user.1" ) ); } ); } /** * Test for DIRSTUDIO-1121. * * Verify input is set only once when entry is selected. */ @ParameterizedTest @LdapServersSource public void testSetInputOnlyOnce( TestLdapServer server ) throws Exception { /* * This test fails on Jenkins Windows Server, to be investigated... */ // Assume.assumeFalse( StudioSystemUtils.IS_OS_WINDOWS_SERVER ); connectionsViewBot.createTestConnection( server ); browserViewBot.selectEntry( path( USERS_DN ) ); browserViewBot.expandEntry( path( USERS_DN ) ); // verify link-with-editor is enabled assertTrue( BrowserUIPlugin.getDefault().getPreferenceStore() .getBoolean( BrowserUIConstants.PREFERENCE_BROWSER_LINK_WITH_EDITOR ) ); // setup counter and listener to record entry editor input changes final AtomicInteger counter = new AtomicInteger(); UIThreadRunnable.syncExec( new VoidResult() { public void run() { try { IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() .getActiveEditor(); editor.addPropertyListener( new IPropertyListener() { @Override public void propertyChanged( Object source, int propId ) { if ( source instanceof EntryEditor && propId == BrowserUIConstants.INPUT_CHANGED ) { counter.incrementAndGet(); } } } ); } catch ( Exception e ) { throw new RuntimeException( e ); } } } ); // select 3 different entries, select one twice should not set the input again browserViewBot.selectEntry( path( USER1_DN ) ); browserViewBot.selectEntry( path( USER1_DN ) ); browserViewBot.selectEntry( path( USER2_DN ) ); browserViewBot.selectEntry( path( USER2_DN ) ); browserViewBot.selectEntry( path( USER3_DN ) ); browserViewBot.selectEntry( path( USER3_DN ) ); // verify that input was only set 3 times. assertEquals( 3, counter.get(), "Only 3 input changes expected." ); // reset counter counter.set( 0 ); // use navigation history to go back and forth, each step should set input only once studioBot.navigationHistoryBack(); browserViewBot.waitUntilEntryIsSelected( USER2_DN.getRdn().getName() ); studioBot.navigationHistoryBack(); browserViewBot.waitUntilEntryIsSelected( USER1_DN.getRdn().getName() ); studioBot.navigationHistoryForward(); browserViewBot.waitUntilEntryIsSelected( USER2_DN.getRdn().getName() ); studioBot.navigationHistoryForward(); browserViewBot.waitUntilEntryIsSelected( USER3_DN.getRdn().getName() ); // verify that input was only set 4 times. assertEquals( 4, counter.get(), "Only 4 input changes expected." ); } /** * Test for DIRSTUDIO-987, DIRSTUDIO-271. * * Browse and refresh entry with multi-valued RDN with same attribute type. */ @ParameterizedTest @LdapServersSource(except = LdapServerType.OpenLdap, reason = "Multi-valued RDN with same attribute is not supported by OpenLDAP") public void testBrowseAndRefreshEntryWithMvRdn( TestLdapServer server ) throws Exception { Dn entryDn = dn( "l=Berlin+l=Brandenburger Tor+l=de+l=eu", MISC_DN ); Dn childDn = dn( "cn=A", entryDn ); server.withAdminConnection( connection -> { Entry entry1 = new DefaultEntry( connection.getSchemaManager() ); entry1.setDn( entryDn ); entry1.add( "objectClass", "top", "locality" ); entry1.add( "l", "eu", "de", "Berlin", "Brandenburger Tor" ); connection.add( entry1 ); Entry entry2 = new DefaultEntry( connection.getSchemaManager() ); entry2.setDn( childDn ); entry2.add( "objectClass", "top", "person" ); entry2.add( "cn", "A" ); entry2.add( "sn", "A" ); connection.add( entry2 ); } ); String[] pathToParent = path( entryDn.getParent() ); String[] pathToEntry = path( entryDn ); String[] pathToChild = path( childDn ); connectionsViewBot.createTestConnection( server ); // expand parent and verify entry is visible browserViewBot.expandEntry( pathToParent ); assertTrue( browserViewBot.existsEntry( pathToEntry ) ); browserViewBot.selectEntry( pathToEntry ); // expand entry and verify child is visible browserViewBot.expandEntry( pathToEntry ); assertTrue( browserViewBot.existsEntry( pathToChild ) ); browserViewBot.selectEntry( pathToChild ); // refresh entry and verify child is still visible browserViewBot.selectEntry( pathToEntry ); browserViewBot.refresh(); assertTrue( browserViewBot.existsEntry( pathToChild ) ); // refresh parent and verify entry is still visible browserViewBot.selectEntry( pathToParent ); browserViewBot.refresh(); assertTrue( browserViewBot.existsEntry( pathToEntry ) ); // expand entry and verify child is visible browserViewBot.expandEntry( pathToEntry ); assertTrue( browserViewBot.existsEntry( pathToChild ) ); } @ParameterizedTest @LdapServersSource public void testBrowseAliasEntry( TestLdapServer server ) throws Exception { // disable alias dereferencing Connection connection = connectionsViewBot.createTestConnection( server ); connection.getConnectionParameter().setExtendedIntProperty( IBrowserConnection.CONNECTION_PARAMETER_ALIASES_DEREFERENCING_METHOD, AliasDereferencingMethod.NEVER.ordinal() ); browserViewBot.expandEntry( path( ALIAS_DN.getParent() ) ); assertTrue( browserViewBot.existsEntry( path( ALIAS_DN ) ) ); browserViewBot.selectEntry( path( ALIAS_DN ) ); } @ParameterizedTest @LdapServersSource public void testBrowseReferralEntry( TestLdapServer server ) throws Exception { // enable ManageDsaIT control Connection connection = connectionsViewBot.createTestConnection( server ); connection.getConnectionParameter().setExtendedBoolProperty( IBrowserConnection.CONNECTION_PARAMETER_MANAGE_DSA_IT, true ); browserViewBot.expandEntry( path( REFERRAL_TO_USERS_DN.getParent() ) ); assertTrue( browserViewBot.existsEntry( path( REFERRAL_TO_USERS_DN ) ) ); browserViewBot.selectEntry( path( REFERRAL_TO_USERS_DN ) ); } @ParameterizedTest @LdapServersSource(only = LdapServerType.ApacheDS, reason = "ApacheDS specific test") public void testBrowseSubEntry( TestLdapServer server ) throws Exception { Dn subentryDn = dn( "cn=subentry", MISC_DN ); // enable Subentries control Connection connection = connectionsViewBot.createTestConnection( server ); connection.getConnectionParameter().setExtendedBoolProperty( IBrowserConnection.CONNECTION_PARAMETER_FETCH_SUBENTRIES, true ); browserViewBot.expandEntry( path( subentryDn.getParent() ) ); assertTrue( browserViewBot.existsEntry( path( subentryDn ) ) ); browserViewBot.selectEntry( path( subentryDn ) ); } @ParameterizedTest @LdapServersSource public void testBrowseWithPagingWithScrollMode( TestLdapServer server ) throws Exception {
java
Apache-2.0
e55b93d729a60c986fc93e52f9519f4bbdf51252
2026-01-05T02:32:00.866394Z
true