Moved to better gradle layout

This commit is contained in:
MysaaJava 2024-01-12 15:51:58 +01:00
parent f8c170b29a
commit 42f9e60d84
Signed by: Mysaa
GPG Key ID: DBA23608F23F5A10
13 changed files with 399 additions and 405 deletions

43
build.gradle Normal file
View File

@ -0,0 +1,43 @@
plugins {
id 'eclipse'
id 'java-library'
}
repositories {
mavenCentral()
maven {
name 'm2-dv8tion'
url 'https://m2.dv8tion.net/releases'
}
}
dependencies {
testImplementation 'junit:junit:4.13.2'
testImplementation 'net.dv8tion:JDA:4.4.0_352'
implementation 'org.jopendocument:jOpenDocument:1.3'
implementation('xerces:xercesImpl') {
version {
strictly '2.12.2'
}
}
testRuntimeOnly "org.slf4j:slf4j-nop:1.7.36"
}
compileJava.options.encoding = "UTF-8"
compileTestJava.options.encoding = "UTF-8"
eclipse.classpath.file {
whenMerged {
entries.findAll { isModule(it) }.each { it.entryAttributes['module'] = 'true' }
}
}
boolean isModule(entry) {
// filter java 9 modules
entry.kind == 'lib' // Only libraries can be modules
}

1
settings.gradle Normal file
View File

@ -0,0 +1 @@
rootProject.name = 'BernardPermissions'

View File

@ -1,370 +0,0 @@
package com.bernard.permissions.tableured;
import java.io.File;
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.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.bernard.permissions.StringPermission;
import com.bernard.permissions.tableured.TPermissionContext.Inheritance;
import com.bernard.permissions.tableured.TPermissionContext.InheritancePolicy;
import com.bernard.permissions.tableured.TPermissionContext.Val;
import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.XPropertySet;
import com.sun.star.comp.helper.Bootstrap;
import com.sun.star.comp.helper.BootstrapException;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.frame.XStorable;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.sheet.XConditionalFormat;
import com.sun.star.sheet.XConditionalFormats;
import com.sun.star.sheet.XSheetCellRange;
import com.sun.star.sheet.XSheetCellRangeContainer;
import com.sun.star.sheet.XSheetCellRanges;
import com.sun.star.sheet.XSpreadsheet;
import com.sun.star.sheet.XSpreadsheetDocument;
import com.sun.star.sheet.XSpreadsheets;
import com.sun.star.table.CellRangeAddress;
import com.sun.star.table.XCell;
import com.sun.star.table.XCellRange;
import com.sun.star.table.XColumnRowRange;
import com.sun.star.uno.Exception;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import com.sun.star.util.XCloseable;
import com.sun.star.util.XMergeable;
public class FileManager {
private static XComponentContext xcc_noaccess;
public static final int MAX_ROW = 3141;
public static final int MAX_COL = 3141;
public static XComponentContext xcc() {
if (xcc_noaccess == null) {
try {
xcc_noaccess = Bootstrap.bootstrap();
System.out.println("Connected to a running office ...");
} catch (BootstrapException e) {
System.err.println("Couldn't connect to office, you won't be able to use ");
}
}
return xcc_noaccess;
}
//TODO: remove «throws Exception» for more precise exceptions
public static final TPermissionContext readFromFile(File f) throws Exception {
XComponentContext xcc = xcc();
XMultiComponentFactory xmcf;
XSpreadsheetDocument xsd;
xmcf = xcc.getServiceManager();
Object object = xmcf.createInstanceWithContext("com.sun.star.frame.Desktop", xcc);
XComponentLoader xComponentLoader = qi(XComponentLoader.class,object);
PropertyValue[] docLoadProperties = { new PropertyValue() };
docLoadProperties[0].Name = "Hidden";
docLoadProperties[0].Value = true;
xsd = qi(XSpreadsheetDocument.class,
xComponentLoader.loadComponentFromURL("file://"+f.getAbsolutePath(), "_blank", 0, docLoadProperties));
// Variables de sortie:
Set<StringPermission> defaultGiven = new HashSet<>();
Map<StringPermission, Map<String, Val>> specs = new HashMap<>();
Map<String, List<Inheritance>> inheritance = new HashMap<>();
String[] sheetNames = xsd.getSheets().getElementNames();
for (int s = 0; s < sheetNames.length; s++) {
String sheetName = sheetNames[s];
XSpreadsheet sheet = qi(XSpreadsheet.class,xsd.getSheets().getByName(sheetName));
// Si c'est des permissions
if(sheetName.startsWith("Permission")) {
// Parsing users/groups names
int defaultColIndex;
List<String> holders = new ArrayList<>();
// PermName,,,,Default
for(defaultColIndex = 1;!sheet.getCellByPosition(defaultColIndex+1, 0).getFormula().equals("#~END~#") && defaultColIndex<MAX_COL;defaultColIndex++) {
holders.add(sheet.getCellByPosition(defaultColIndex, 0).getFormula());
}
//Devrait être sur la bonne colonne.
System.out.println(holders);
// Parsing file names
for (int i = 1;!sheet.getCellByPosition(0, i).getFormula().equals("#~END~#") && i<=MAX_ROW; i++) {
String perm = sheet.getCellByPosition(0, i).getFormula();
if(!perm.isBlank()) {
Map<String, Val> thisSpec = new HashMap<>();
for(int hi=0;hi<holders.size();hi++) {
String holder = holders.get(hi);
if(holder==null)continue;
String value = sheet.getCellByPosition(hi+1, i).getFormula();
if(!value.isEmpty()) {
switch(value.charAt(0)) {
case 'x':
case 'X':
thisSpec.put(holder, TPermissionContext.Val.REVOKED);
break;
case 'o':
case 'O':
thisSpec.put(holder, TPermissionContext.Val.GRANTED);
break;
}
}
}
StringPermission perperm = StringPermission.parse(perm);
specs.put(perperm, thisSpec);
//Putting the default
String defaultValue = sheet.getCellByPosition(defaultColIndex, i).getFormula();
if(!defaultValue.isBlank()) {
char defaultValueChar = defaultValue.charAt(0);
if(defaultValueChar=='o' || defaultValueChar=='O')
defaultGiven.add(perperm);
}
}
}
}else if(sheetName.startsWith("Holder")) {
// Parsing file names
for (int i = 1;!sheet.getCellByPosition(0, i).getFormula().equals("#~END~#") && i<=MAX_ROW; i++) {
String holder = sheet.getCellByPosition(0, i).getFormula();
List<Inheritance> inhz = null;
for(int col = 1;!sheet.getCellByPosition(col, 0).getFormula().equals("#~END~#") && col <= MAX_COL;col++) {
String rule = sheet.getCellByPosition(col, i).getFormula();
if(!rule.isBlank()) {
InheritancePolicy ipol = InheritancePolicy.fromChar(rule.charAt(0));
String motherHolderName = (ipol==InheritancePolicy.ALL)?rule:rule.substring(1);
if(inhz==null)
inhz = new ArrayList<>();
inhz.add(new Inheritance(motherHolderName, ipol));
}
}
if(inhz!=null)
inheritance.put(holder, inhz);
}
}
}
System.out.println(defaultGiven);
System.out.println(specs);
System.out.println(inheritance);
TPermissionContext tpc = new TPermissionContext(defaultGiven, specs, inheritance);
if(tpc.anyCycle())
throw new IllegalArgumentException("Cycle detected !");
return tpc;
}
public static final void writeToFile(File f,TPermissionContext tpc) throws Exception {
XComponentContext xcc = xcc();
XMultiComponentFactory xmcf;
XSpreadsheetDocument xsd;
xmcf = xcc.getServiceManager();
xmcf = xcc.getServiceManager();
Object object = xmcf.createInstanceWithContext("com.sun.star.frame.Desktop", xcc);
XComponentLoader xcl = qi(XComponentLoader.class,object);
PropertyValue[] docLoadProperties = { new PropertyValue() };
docLoadProperties[0].Name = "Hidden";
docLoadProperties[0].Value = true;
String baseFile = new File("stringPermissionBase.ods").getAbsolutePath();
xsd = UnoRuntime.queryInterface(
XSpreadsheetDocument.class, xcl.loadComponentFromURL("file://"+baseFile, "_blank", 0, docLoadProperties ));
XSpreadsheets sheets = xsd.getSheets();
XSpreadsheet permissionsS = qi(XSpreadsheet.class,sheets.getByName("Permissions"));
XSpreadsheet permissionsCompleteS = qi(XSpreadsheet.class,sheets.getByName("Permissions-complete"));
XSpreadsheet holdersS = qi(XSpreadsheet.class,sheets.getByName("Holders"));
// ----- Permissions sheet -----
writePermissionsSheetOutline(tpc, permissionsS,false);
//TODO: Ajouter le support pour les holders qui commencent par un + ou un - (avec ++=+, +++=++, ...)
//TODO: Faire un tri qui «garde la structure du graphe d'héritage»
// ----- Heritance sheet -----
List<String> enfants = tpc.inheritance.keySet().stream().sorted().collect(Collectors.toList());
holdersS.getCellByPosition(0, 0).setFormula("Holder");;
holdersS.getCellByPosition(1, 0).setFormula("Héritages");;
System.out.println(tpc.inheritance);
int maxCol = 0;
for(int i=0;i<enfants.size();i++) {
XCell cellEnft = holdersS.getCellByPosition(0,i+1);
cellEnft.setFormula(enfants.get(i));
qi(XPropertySet.class, cellEnft).setPropertyValue("CellStyle", (i%2==0)?"HeritageHolderEven":"HeritageHolderOdd");
List<Inheritance> parents = tpc.inheritance.get(enfants.get(i));
for (int j = 0; j < parents.size(); j++) {
String toWrite = parents.get(j).policy.toChar()+parents.get(j).holder;
holdersS.getCellByPosition(j+1, i+1).setFormula(toWrite);
}
maxCol = Math.max(maxCol, parents.size());
}
// Adding the style on the heritance core.
XSheetCellRange xscr = qi(XSheetCellRange.class,holdersS.getCellRangeByPosition(1,0,maxCol,0));
System.out.println(xscr);
qi(XMergeable.class,xscr).merge(true);
for(int i=0;i<enfants.size();i++) {
XCellRange cellr = holdersS.getCellRangeByPosition(1,i+1,maxCol,i+1);
qi(XPropertySet.class, cellr).setPropertyValue("CellStyle", (i%2==0)?"HeritageEven":"HeritageOdd");
}
// Adding the #~END~# labels
holdersS.getCellByPosition(maxCol+1, 0).setFormula("#~END~#");;
holdersS.getCellByPosition(0, enfants.size()+1).setFormula("#~END~#");;
XCellRange cellrv = holdersS.getCellRangeByPosition(maxCol+1,0,maxCol+1,enfants.size()+1);
qi(XPropertySet.class, cellrv).setPropertyValue("CellStyle", "EndLine");
XCellRange cellrh = holdersS.getCellRangeByPosition(0,enfants.size()+1,maxCol+1,enfants.size()+1);
qi(XPropertySet.class, cellrh).setPropertyValue("CellStyle", "EndLine");
// Réduis les tailles des dernières colonnes et lignes
XColumnRowRange colignes = qi(XColumnRowRange.class,holdersS);
qi(XPropertySet.class,colignes.getColumns().getByIndex(maxCol+1)).setPropertyValue("Width", 420);;
qi(XPropertySet.class,colignes.getRows().getByIndex(enfants.size()+1)).setPropertyValue("Height", 420);;
// ----- Permissions-Complete sheet -----
// We have two implication graphes: one for holders with inheritance.
writePermissionsSheetOutline(tpc, permissionsCompleteS, true);
// ----- Écrit le fichier -----
String fileURL = "file://"+f.getAbsolutePath();
XStorable xst = qi(XStorable.class, xsd);
PropertyValue[] propertyValue = {new PropertyValue()};
propertyValue[0] = new com.sun.star.beans.PropertyValue();
propertyValue[0].Name = "Overwrite";
propertyValue[0].Value = Boolean.TRUE;
xst.storeAsURL( fileURL, propertyValue );
XCloseable xcloz = qi(XCloseable.class, xsd );
xcloz.close(false);
}
private static void writePermissionsSheetOutline(TPermissionContext tpc, XSpreadsheet permissionsS,boolean writeEverything) throws Exception {
//C'est de base des Sets, mais sont ordonnés, pour un affichage consistant.
List<StringPermission> permissions = Stream.concat(
tpc.specs.keySet().stream(),
tpc.defaultGiven.stream()
).distinct().sorted().collect(Collectors.toList());
List<String> permSpecHolders = Stream.concat(tpc.inheritance.keySet().stream(),tpc.specs.values().stream().flatMap(m -> m.keySet().stream())).distinct().sorted().collect(Collectors.toList());
//TODO: Find a way to distinct and sorted at the same time
for (int i = 0; i < permissions.size(); i++) {
XCell cell = permissionsS.getCellByPosition(0,i+1);
cell.setFormula(permissions.get(i).toString());
qi(XPropertySet.class, cell).setPropertyValue("CellStyle", (i%2==0)?"SpecPermissionEven":"SpecPermissionOdd");
}
for (int j = 0; j < permSpecHolders.size(); j++) {
XCell cell = permissionsS.getCellByPosition(j+1,0);
cell.setFormula(permSpecHolders.get(j));
qi(XPropertySet.class, cell).setPropertyValue("CellStyle", (j%2==0)?"SpecHolderEven":"SpecHolderOdd");
}
int defaultHolderCol = permSpecHolders.size()+1;
XCell celld = permissionsS.getCellByPosition(defaultHolderCol,0);
celld.setFormula("#~DEFAULT~#");
qi(XPropertySet.class, celld).setPropertyValue("CellStyle", "SpecHolderDefault");
for(Entry<StringPermission,Map<String,Val>> etry : tpc.specs.entrySet()) {
int permIndex = Collections.binarySearch(permissions, etry.getKey());
for(Entry<String,Val> ett : etry.getValue().entrySet()) {
int hldrIndex = Collections.binarySearch(permSpecHolders, ett.getKey());
if(ett.getValue()!=Val.UNSPECIFIED)
permissionsS.getCellByPosition(hldrIndex+1,permIndex+1).setFormula(String.valueOf(ett.getValue().toChar()));
}
}
// Writing the DEFAULT column
for(int i = 0;i<permissions.size();i++) {
StringPermission sp = StringPermission.parse(permissionsS.getCellByPosition(0, i+1).getFormula());
if(tpc.defaultGiven.contains(sp))
permissionsS.getCellByPosition(defaultHolderCol, i+1).setFormula("o");
else if(tpc.defaultGiven.stream().anyMatch(dg -> dg.implies(sp)))
permissionsS.getCellByPosition(defaultHolderCol, i+1).setFormula(".");
else
permissionsS.getCellByPosition(defaultHolderCol, i+1).setFormula("_");
}
if(writeEverything) {
for(int j = 0;j<permSpecHolders.size();j++) {
for(int i = 0;i<permissions.size();i++) {
if(permissionsS.getCellByPosition(j+1,i+1).getFormula().isBlank())
permissionsS.getCellByPosition(j+1,i+1).setFormula(tpc.can(permissions.get(i), permSpecHolders.get(j))?".":"_");
}
}
}
// Adding the #~END~# labels
permissionsS.getCellByPosition(0,permissions.size()+1).setFormula("#~END~#");;
permissionsS.getCellByPosition(defaultHolderCol+1, 0).setFormula("#~END~#");;
XCellRange cellrv = permissionsS.getCellRangeByPosition(defaultHolderCol+1,0,defaultHolderCol+1,permissions.size()+1);
qi(XPropertySet.class, cellrv).setPropertyValue("CellStyle", "EndLine");
XCellRange cellrh = permissionsS.getCellRangeByPosition(0,permissions.size()+1,defaultHolderCol+1,permissions.size()+1);
qi(XPropertySet.class, cellrh).setPropertyValue("CellStyle", "EndLine");
// Réduis les tailles des dernières colonnes et lignes
XColumnRowRange colignes = qi(XColumnRowRange.class,permissionsS);
qi(XPropertySet.class,colignes.getColumns().getByIndex(defaultHolderCol+1)).setPropertyValue("Width", 420);;
qi(XPropertySet.class,colignes.getRows().getByIndex(permissions.size()+1)).setPropertyValue("Height", 420);;
// Applique le formattage conditionel aux données
XConditionalFormats formats = qi(XConditionalFormats.class,qi(XPropertySet.class,permissionsS).getPropertyValue("ConditionalFormats"));
XConditionalFormat theFormat = formats.getConditionalFormats()[0];
XSheetCellRanges applicationRanges = qi(XSheetCellRanges.class,qi(XPropertySet.class,theFormat).getPropertyValue("Range"));
XSheetCellRangeContainer applicationRangesP = qi(XSheetCellRangeContainer.class,applicationRanges);
applicationRangesP.addRangeAddress(new CellRangeAddress((short)0, 1, 1, defaultHolderCol, permissions.size()), true);
qi(XPropertySet.class,theFormat).setPropertyValue("Range", applicationRangesP);
}
public static <T> T qi(Class<T> aType, Object o) {
return UnoRuntime.queryInterface(aType, o);
}
}

View File

@ -0,0 +1,313 @@
package com.bernard.permissions.tableured;
import java.io.File;
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.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.jopendocument.dom.ODPackage;
import org.jopendocument.dom.Style;
import org.jopendocument.dom.StyleDesc;
import org.jopendocument.dom.spreadsheet.MutableCell;
import org.jopendocument.dom.spreadsheet.Sheet;
import org.jopendocument.dom.spreadsheet.SpreadSheet;
import org.jopendocument.dom.spreadsheet.TableStyle;
import org.jopendocument.model.office.OfficeAutomaticStyles;
import org.jopendocument.model.style.StyleStyle;
import org.jopendocument.model.style.StyleTableRowProperties;
import com.bernard.permissions.StringPermission;
import com.bernard.permissions.tableured.TPermissionContext.Inheritance;
import com.bernard.permissions.tableured.TPermissionContext.InheritancePolicy;
import com.bernard.permissions.tableured.TPermissionContext.Val;
public class FileManager {
public static final int MAX_ROW = 3141;
public static final int MAX_COL = 3141;
//TODO: remove «throws Exception» for more precise exceptions
public static final TPermissionContext readFromFile(File f) throws Exception {
ODPackage odp;
SpreadSheet doc;
;
odp = ODPackage.createFromFile(f);
doc = odp.getSpreadSheet();
// Variables de sortie:
Set<StringPermission> defaultGiven = new HashSet<>();
Map<StringPermission, Map<String, Val>> specs = new HashMap<>();
Map<String, List<Inheritance>> inheritance = new HashMap<>();
for (int s=0;s<doc.getSheetCount();s++) {
Sheet table = doc.getSheet(s);
String tableName = table.getName();
// Si c'est des permissions
if(tableName.startsWith("Permission")) {
// Parsing users/groups names
int defaultColIndex;
List<String> holders = new ArrayList<>();
// PermName,,,,Default
for(defaultColIndex = 1;!table.getCellAt(defaultColIndex+1, 0).getTextValue().equals("#~END~#") && defaultColIndex<MAX_COL;defaultColIndex++) {
holders.add(table.getCellAt(defaultColIndex, 0).getTextValue());
}
//Devrait être sur la bonne colonne.
System.out.println(holders);
// Parsing file names
for (int i = 1;!table.getCellAt(0, i).getTextValue().equals("#~END~#") && i<=MAX_ROW; i++) {
String perm = table.getCellAt(0, i).getTextValue();
if(!perm.isBlank()) {
Map<String, Val> thisSpec = new HashMap<>();
for(int hi=0;hi<holders.size();hi++) {
String holder = holders.get(hi);
if(holder==null)continue;
String value = table.getCellAt(hi+1, i).getTextValue();
if(!value.isEmpty()) {
switch(value.charAt(0)) {
case 'x':
case 'X':
thisSpec.put(holder, TPermissionContext.Val.REVOKED);
break;
case 'o':
case 'O':
thisSpec.put(holder, TPermissionContext.Val.GRANTED);
break;
}
}
}
StringPermission perperm = StringPermission.parse(perm);
specs.put(perperm, thisSpec);
//Putting the default
String defaultValue = table.getCellAt(defaultColIndex, i).getTextValue();
if(!defaultValue.isBlank()) {
char defaultValueChar = defaultValue.charAt(0);
if(defaultValueChar=='o' || defaultValueChar=='O')
defaultGiven.add(perperm);
}
}
}
}else if(tableName.startsWith("Holder")) {
// Parsing file names
for (int i = 1;!table.getCellAt(0, i).getTextValue().equals("#~END~#") && i<=MAX_ROW; i++) {
String holder = table.getCellAt(0, i).getTextValue();
List<Inheritance> inhz = null;
for(int col = 1;!table.getCellAt(col, 0).getTextValue().equals("#~END~#") && col <= MAX_COL;col++) {
String rule = table.getCellAt(col, i).getTextValue();
if(!rule.isBlank()) {
InheritancePolicy ipol = InheritancePolicy.fromChar(rule.charAt(0));
String motherHolderName = (ipol==InheritancePolicy.ALL)?rule:rule.substring(1);
if(inhz==null)
inhz = new ArrayList<>();
inhz.add(new Inheritance(motherHolderName, ipol));
}
}
if(inhz!=null)
inheritance.put(holder, inhz);
}
}
}
System.out.println(defaultGiven);
System.out.println(specs);
System.out.println(inheritance);
TPermissionContext tpc = new TPermissionContext(defaultGiven, specs, inheritance);
if(tpc.anyCycle())
throw new IllegalArgumentException("Cycle detected !");
return tpc;
}
public static final void writeToFile(File f,TPermissionContext tpc) throws Exception {
File baseFile = new File(FileManager.class.getResource("/stringPermissionBase.ods").toURI());
ODPackage odp = ODPackage.createFromFile(baseFile);
SpreadSheet doc = odp.getSpreadSheet();
Sheet permissionsS = doc.getSheet("Permissions");
Sheet permissionsCompleteS = doc.getSheet("Permissions-complete");
Sheet holdersS = doc.getSheet("Holders");
// ----- Permissions sheet -----
writePermissionsSheetOutline(tpc, odp, permissionsS,false);
//TODO: Ajouter le support pour les holders qui commencent par un + ou un - (avec ++=+, +++=++, ...)
//TODO: Faire un tri qui «garde la structure du graphe d'héritage»
// ----- Heritance sheet -----
List<String> enfants = tpc.inheritance.keySet().stream().sorted().collect(Collectors.toList());
holdersS.getCellAt(0, 0).setValue("Holder");;
holdersS.getCellAt(1, 0).setValue("Héritages");;
System.out.println("TCP Inheritance: "+tpc.inheritance);
int maxCol = 0;
for(int i=0;i<enfants.size();i++) {
System.out.println("Enfant "+i);
MutableCell<SpreadSheet> cellEnft = holdersS.getCellAt(0,i+1);
System.out.println("Cell gotten;"+enfants.get(i));
cellEnft.setValue(enfants.get(i));
System.out.println("Cell value setted");
cellEnft.setStyleName((i%2==0)?"HeritageHolderEven":"HeritageHolderOdd");
System.out.println("Super writing");
List<Inheritance> parents = tpc.inheritance.get(enfants.get(i));
for (int j = 0; j < parents.size(); j++) {
String toWrite = parents.get(j).policy.toChar()+parents.get(j).holder;
holdersS.getCellAt(j+1, i+1).setValue(toWrite);
}
maxCol = Math.max(maxCol, parents.size());
}
System.out.println("Setting the style");
// Adding the style on the heritance core.
holdersS.getCellAt(1,0).merge(1, maxCol);
for(int i=0;i<enfants.size();i++) {
changeTableSheetRangeStyleName(holdersS,1,i+1,maxCol,i+1,(i%2==0)?"HeritageEven":"HeritageOdd");
}
// Adding the #~END~# labels
holdersS.getCellAt(maxCol+1, 0).setValue("#~END~#");;
holdersS.getCellAt(0, enfants.size()+1).setValue("#~END~#");;
changeTableSheetRangeStyleName(holdersS,maxCol+1,0,maxCol+1,enfants.size()+1, "EndLine");
changeTableSheetRangeStyleName(holdersS,0,enfants.size()+1,maxCol+1,enfants.size()+1, "EndLine");
// Réduis les tailles des dernières colonnes et lignes
holdersS.getColumn(maxCol+1).setWidth(420);
StyleStyle ss = ;
StyleTableRowProperties stRowP = ss.getStyleTableRowProperties();
stRowP.setRowHeight("420");
stRowP.setUseOptimalRowHeight("true");
ss.setTableRowProperties(stRowP);
// ----- Permissions-Complete sheet -----
// We have two implication graphes: one for holders with inheritance.
writePermissionsSheetOutline(tpc, odp, permissionsCompleteS, true);
// ----- Écrit le fichier -----
System.out.println("Preparing to save");
doc.saveAs(f);
System.out.println("Save successfull");
}
private static void writePermissionsSheetOutline(TPermissionContext tpc,ODPackage odp, Sheet permissionsS,boolean writeEverything) throws Exception {
//C'est de base des Sets, mais sont ordonnés, pour un affichage consistant.
List<StringPermission> permissions = Stream.concat(
tpc.specs.keySet().stream(),
tpc.defaultGiven.stream()
).distinct().sorted().collect(Collectors.toList());
List<String> permSpecHolders = Stream.concat(tpc.inheritance.keySet().stream(),tpc.specs.values().stream().flatMap(m -> m.keySet().stream())).distinct().sorted().collect(Collectors.toList());
//TODO: Find a way to distinct and sorted at the same time
for (int i = 0; i < permissions.size(); i++) {
MutableCell<SpreadSheet> cell = permissionsS.getCellAt(0,i+1);
cell.setValue(permissions.get(i).toString());
cell.setStyleName((i%2==0)?"SpecPermissionEven":"SpecPermissionOdd");
}
for (int j = 0; j < permSpecHolders.size(); j++) {
MutableCell<SpreadSheet> cell = permissionsS.getCellAt(j+1,0);
cell.setValue(permSpecHolders.get(j));
cell.setStyleName((j%2==0)?"SpecHolderEven":"SpecHolderOdd");
}
int defaultHolderCol = permSpecHolders.size()+1;
MutableCell<SpreadSheet> celld = permissionsS.getCellAt(defaultHolderCol,0);
celld.setValue("#~DEFAULT~#");
celld.setStyleName("SpecHolderDefault");
for(Entry<StringPermission,Map<String,Val>> etry : tpc.specs.entrySet()) {
int permIndex = Collections.binarySearch(permissions, etry.getKey());
for(Entry<String,Val> ett : etry.getValue().entrySet()) {
int hldrIndex = Collections.binarySearch(permSpecHolders, ett.getKey());
if(ett.getValue()!=Val.UNSPECIFIED)
permissionsS.getCellAt(hldrIndex+1,permIndex+1).setValue(String.valueOf(ett.getValue().toChar()));
}
}
// Writing the DEFAULT column
for(int i = 0;i<permissions.size();i++) {
StringPermission sp = permissions.get(i);
if(tpc.defaultGiven.contains(sp))
permissionsS.getCellAt(defaultHolderCol, i+1).setValue("o");
else if(tpc.defaultGiven.stream().anyMatch(dg -> dg.implies(sp)))
permissionsS.getCellAt(defaultHolderCol, i+1).setValue(".");
else
permissionsS.getCellAt(defaultHolderCol, i+1).setValue("_");
}
if(writeEverything) {
for(int j = 0;j<permSpecHolders.size();j++) {
for(int i = 0;i<permissions.size();i++) {
if(permissionsS.getCellAt(j+1,i+1).getTextValue().isBlank())
permissionsS.getCellAt(j+1,i+1).setValue(tpc.can(permissions.get(i), permSpecHolders.get(j))?".":"_");
}
}
}
// Adding the #~END~# labels
permissionsS.getCellAt(0,permissions.size()+1).setValue("#~END~#");;
permissionsS.getCellAt(defaultHolderCol+1, 0).setValue("#~END~#");;
changeTableSheetRangeStyleName(permissionsS,defaultHolderCol+1,0,defaultHolderCol+1,permissions.size()+1, "EndLine");
changeTableSheetRangeStyleName(permissionsS,0,permissions.size()+1,defaultHolderCol+1,permissions.size()+1, "EndLine");
// Réduis les tailles des dernières colonnes et lignes
permissionsS.getColumn(defaultHolderCol+1).setWidth(420);
StyleStyle ss = ;
StyleTableRowProperties stRowP = ss.getStyleTableRowProperties();
stRowP.setRowHeight("420");
stRowP.setUseOptimalRowHeight("true");
ss.setTableRowProperties(stRowP);
// Applique le formattage conditionel aux données
StyleDesc<TableStyle> autoStyles = permissionsS.getStyleDesc();
permissionsS.getStyleDesc().createAutoStyle(odp);
Style style = autoStyles.getAllStyles().iterator().next();
changeTableSheetRangeStyleName(permissionsS,1, 1, defaultHolderCol, permissions.size(), style.getName());
}
private static void changeTableSheetRangeStyleName(Sheet ot, int startCol, int startRow, int endCol, int endRow, String styleName) {
for(int col=startCol; col<=endCol;col++)
for(int row=startRow; row<=endRow;row++)
ot.getCellAt(col,row).setStyleName(styleName);
}
}

View File

@ -1,19 +1,22 @@
package com.bernard.permissions;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.security.auth.login.LoginException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.junit.rules.Timeout;
import com.bernard.permissions.tableured.FileManager;
import com.bernard.permissions.tableured.TPermissionContext;
import com.bernard.permissions.tableured.TPermissionContext.Inheritance;
import com.bernard.permissions.tableured.TPermissionContext.Val;
import com.sun.star.uno.Exception;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
@ -25,42 +28,40 @@ import net.dv8tion.jda.api.requests.GatewayIntent;
public class TestMain {
public static void main(String[] args) throws Exception, LoginException, InterruptedException{
@Rule
public final TestRule globalTimeout = Timeout.seconds(20);
testDiscordRead();
@Test public void testReadAndWrite() throws Exception {
System.out.println("OK, i'm done !");
System.exit(0);;
}
File readFrom = new File(TestMain.class.getResource("/test.ods").toURI());
TPermissionContext tpc = FileManager.readFromFile(readFrom);
public static void testReadAndWrite() {
try {
TPermissionContext tpc = FileManager.readFromFile(new File("test.ods"));
String[] perms = {"julia","julia.bdd","julia.bdd.read","julia.bdd.write","julia.messages","julia.coucou"};
String[] holders = {"Admin","Developeur","Client","Étranger","Mysaa","Bernard","Zlopeg","Ferbex","Pbalkany"};
for (String perm : perms) {
for (String holder : holders) {
System.out.println(holder+" can "+perm+" : "+tpc.can(StringPermission.parse(perm), holder));
}
System.out.println("=========================");
String[] perms = {"julia","julia.bdd","julia.bdd.read","julia.bdd.write","julia.messages","julia.coucou"};
String[] holders = {"Admin","Developeur","Client","Étranger","Mysaa","Bernard","Zlopeg","Ferbex","Pbalkany"};
for (String perm : perms) {
for (String holder : holders) {
System.out.println(holder+" can "+perm+" : "+tpc.can(StringPermission.parse(perm), holder));
}
System.out.println(tpc);
System.out.println("Writing back to file.");
new File("testout.ods").delete();
FileManager.writeToFile(new File("testout.ods"), tpc);
System.out.println("Re-reading it");
TPermissionContext newTPC = FileManager.readFromFile(new File("testout.ods"));
System.out.println(tpc);
System.out.println("Equals test: "+tpc.equals(newTPC));
System.out.println("Writing to another file");
FileManager.writeToFile(new File("testoutout.ods"), newTPC);
} catch (Exception e) {
e.printStackTrace();
System.out.println("=========================");
}
System.out.println(tpc);
System.out.println("Writing back to file.");
File testout = File.createTempFile("testout", "ods");
FileManager.writeToFile(testout, tpc);
System.out.println("Re-reading it");
TPermissionContext newTPC = FileManager.readFromFile(testout);
System.out.println(tpc);
System.out.println("Equals test: "+tpc.equals(newTPC));
System.out.println("Writing to another file");
File testoutout = File.createTempFile("testoutout", "ods");
FileManager.writeToFile(testoutout, newTPC);
}
public static void testStringPermissions() {
@Test public void testStringPermissions() {
System.out.println(StringPermission.spR);
System.out.println(StringPermission.optionsR);
@ -69,8 +70,13 @@ public class TestMain {
}
public static void testDiscordRead() throws LoginException, InterruptedException, Exception {
JDA jda = JDABuilder.createDefault("",GatewayIntent.GUILD_MEMBERS,GatewayIntent.values()).build();
@Test public void testDiscordRead() throws Exception {
FileInputStream fis = new FileInputStream("/home/mysaa/julia.token");
String token = new String(fis.readAllBytes());
fis.close();
JDA jda = JDABuilder.createDefault(token,GatewayIntent.GUILD_MEMBERS,GatewayIntent.values()).build();
jda.awaitReady();
Guild g = jda.getGuildById(222947179017404416L);
@ -121,6 +127,7 @@ public class TestMain {
FileManager.writeToFile(new File("discordout.ods"), tpc);
jda.shutdown();
}
}