Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • simonrose/naming-backend
  • anderslindh1/naming-backend
  • andersharrisson/naming-backend
3 results
Show changes
Showing
with 3031 additions and 1462 deletions
package org.openepics.names.service.security.util;
import org.openepics.names.service.security.dto.UserDetails;
import org.openepics.names.service.security.rbac.RBACToken;
/**
* @author <a href="mailto:zoltan.runyo@ess.eu">Zoltan Runyo</a>
* @author Lars Johansson
*/
public class SecurityUtil {
/**
* This class is not to be instantiated.
*/
private SecurityUtil() {
throw new IllegalStateException("Utility class");
}
/**
* Converts RBAC token to user details DTO
*
* @param rbacInfo RBAC token descriptor
* @return User details DTO
*/
public static UserDetails convertToUserDetails(RBACToken rbacInfo) {
UserDetails result = null;
if (rbacInfo != null) {
result = new UserDetails();
result.setUserName(rbacInfo.getUserName());
result.setFullName(rbacInfo.getFirstName() + " " + rbacInfo.getLastName());
result.setToken(rbacInfo.getId());
result.setRoles(rbacInfo.getRoles());
}
return result;
}
/**
* Return username for a user.
*
* @param userDetails user details
* @return username
*/
public static String getUsername(UserDetails userDetails) {
return userDetails != null ? userDetails.getUserName() : null;
}
}
/*
* Copyright (c) 2018 European Spallation Source ERIC.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.openepics.names.util;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
/**
* Utility class for encoding a value according to encoding scheme.
*
* @author Lars Johansson
*
* @see EncodingUtility#ENCODING_SCHEME
*/
public class EncodingUtility {
public static final String ENCODING_SCHEME = "UTF-8";
/**
* This class is not to be instantiated.
*/
private EncodingUtility() {
throw new IllegalStateException("Utility class");
}
/**
* Encode a <code>String</code> and return the encoded value.
*
* @param s the string to encode
* @return the encoded value
*
* @see EncodingUtility#ENCODING_SCHEME
* @see URLEncoder#encode(String, String)
*/
public static String encode(String s) {
try {
return URLEncoder.encode(s, ENCODING_SCHEME);
} catch (UnsupportedEncodingException e) {
return s;
}
}
/**
* Decode a <code>String</code> and return the decoded value.
*
* @param s the string to decode
* @return the decoded value
*
* @see EncodingUtility#ENCODING_SCHEME
* @see URLDecoder#decode(String, String)
*/
public static String decode(String s) {
try {
return URLDecoder.decode(s, ENCODING_SCHEME);
} catch (UnsupportedEncodingException e) {
return s;
}
}
}
......@@ -51,8 +51,6 @@ public class EssNamingConvention implements NamingConvention {
// mnemonic for instance index may be omitted for ess name
// ----------------------------------------------------------------------------------------------------
// Note revision history of file in repository.
private static final String MNEMONIC_ALPHABETIC_LOWERCASE = "^[a-z]+$";
private static final String MNEMONIC_ALPHANUMERIC = "^[a-zA-Z0-9]+$";
private static final String MNEMONIC_NUMERIC = "^[0-9]+$";
......@@ -76,6 +74,8 @@ public class EssNamingConvention implements NamingConvention {
@Override
public boolean isInstanceIndexValid(String conventionName, boolean overrideRuleset) {
// ability to override ruleset for administrator
String instanceIndex = NamingConventionUtil.extractInstanceIndex(conventionName);
if (overrideRuleset) {
// previous rules, less restrictions
......@@ -150,9 +150,10 @@ public class EssNamingConvention implements NamingConvention {
// valid if
// length 1, 2, 3
// same mnemonic only once in mnemonic path
if (!StringUtils.isEmpty(mnemonicPath)) {
String[] values = NamingConventionUtil.string2MnemonicPath(mnemonicPath.trim());
if (values.length < 0 || values.length > 3) {
if (values.length > 3) {
return false;
}
switch (values.length) {
......@@ -171,20 +172,17 @@ public class EssNamingConvention implements NamingConvention {
return false;
}
@Override
public boolean isMnemonicRequired(Type type) {
if (type != null
&& (Type.SYSTEM.equals(type)
|| Type.SUBSYSTEM.equals(type)
|| Type.DISCIPLINE.equals(type)
|| Type.DEVICETYPE.equals(type))) {
return true;
}
return false;
}
@Override
public MnemonicValidation validateMnemonic(Type type, String mnemonic) {
@Override
public boolean isMnemonicRequired(Type type) {
return type != null
&& (Type.SYSTEM.equals(type)
|| Type.SUBSYSTEM.equals(type)
|| Type.DISCIPLINE.equals(type)
|| Type.DEVICETYPE.equals(type));
}
@Override
public MnemonicValidation validateMnemonic(Type type, String mnemonic) {
// mnemonic validation for system and device structure elements
// rules for characters
// depends on system/device structure, required or not
......@@ -203,24 +201,24 @@ public class EssNamingConvention implements NamingConvention {
// accelerator as system
// system group as system, not required
if (type != null) {
boolean empty = StringUtils.isEmpty(mnemonic);
int length = empty ? 0 : mnemonic.length();
boolean length1to6 = (length >= 1) && (length <= 6);
boolean length1to8 = (length >= 1) && (length <= 8);
boolean matchMnemonic = !empty && mnemonic.matches(MNEMONIC_ALPHANUMERIC);
if (type != null) {
boolean empty = StringUtils.isEmpty(mnemonic);
int length = empty ? 0 : mnemonic.length();
boolean length1to6 = (length >= 1) && (length <= 6);
boolean length1to8 = (length >= 1) && (length <= 8);
boolean matchMnemonic = !empty && mnemonic.matches(MNEMONIC_ALPHANUMERIC);
MnemonicValidation result = MnemonicValidation.VALID;
MnemonicValidation result = MnemonicValidation.VALID;
if (Type.SYSTEMGROUP.equals(type)) {
if (Type.SYSTEMGROUP.equals(type)) {
if (empty) {
result = MnemonicValidation.VALID;
return result;
} else if (!length1to6) {
result = MnemonicValidation.TOO_LONG;
} else if (!matchMnemonic) {
result = MnemonicValidation.NON_ACCEPTABLE_CHARS;
}
} else if (Type.SYSTEM.equals(type) || Type.SUBSYSTEM.equals(type)) {
} else if (Type.SYSTEM.equals(type) || Type.SUBSYSTEM.equals(type)) {
if (empty) {
result = MnemonicValidation.EMPTY;
} else if (!length1to8) {
......@@ -228,7 +226,7 @@ public class EssNamingConvention implements NamingConvention {
} else if (!matchMnemonic) {
result = MnemonicValidation.NON_ACCEPTABLE_CHARS;
}
} else if (Type.DISCIPLINE.equals(type) || Type.DEVICETYPE.equals(type)) {
} else if (Type.DISCIPLINE.equals(type) || Type.DEVICETYPE.equals(type)) {
if (empty) {
result = MnemonicValidation.EMPTY;
} else if (!length1to6) {
......@@ -236,15 +234,15 @@ public class EssNamingConvention implements NamingConvention {
} else if (!matchMnemonic) {
result = MnemonicValidation.NON_ACCEPTABLE_CHARS;
}
} else if (Type.DEVICEGROUP.equals(type)) {
} else if (Type.DEVICEGROUP.equals(type)) {
if (!empty) {
result = MnemonicValidation.NON_ACCEPTABLE_CHARS;
}
}
}
return result;
}
return null;
}
return result;
}
return null;
}
}
/*
* Copyright (C) 2022 European Spallation Source ERIC.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.openepics.names.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openepics.names.exception.ServiceException;
import org.openepics.names.rest.beans.Type;
import org.openepics.names.rest.beans.element.NameElement;
import org.openepics.names.rest.beans.element.NameElementCommand;
import org.openepics.names.rest.beans.element.StructureElement;
import org.openepics.names.rest.beans.element.StructureElementCommand;
import org.springframework.web.multipart.MultipartFile;
import com.google.common.collect.Lists;
/**
* Utility class to assist in handling of Excel files.
*
* @author Lars Johansson
*/
public class ExcelUtil {
private static final Logger LOGGER = Logger.getLogger(ExcelUtil.class.getName());
public static final String MIME_TYPE_EXCEL = "application/vnd.ms-excel";
public static final String MIME_TYPE_OPENXML_SPREADSHEET = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
// width (in units of 1/256th of a character width)
// column width 3.44 inch (to fit header text and uuid)
private static final int SHEET_COLUMN_WIDTH = 35 * 256 + 64;
private static final int NAMEELEMENTCOMMAND_LENGTH = 5;
private static final String[][] NAMEELEMENT_HEADER_COMMENT = {
{"Uuid", "Identity (uuid) of the name entry. Value is created server-side."},
{"ParentSystemStructure", "Identity (uuid) for the system structure parent."},
{"ParentDeviceStructure", "Identity (uuid) for the device structure parent (if the name entry refers to device structure)."},
{"Index", "Index (instance) of the name entry (if the name entry refers to device structure)."},
{"Description", "Description (verbose) of the name entry."},
// above NameElementCommand
{"SystemStructure", "Mnemonic path for for the system structure."},
{"DeviceStructure", "Mnemonic path for for the device structure."},
{"Name", "Name (verbose) of the name entry."},
{"Status", "Status of the name entry."},
{"Deleted", "If the name entry is deleted."},
{"When", "Date and time when the name entry was created."},
{"Who", "Name (user) of who created the name entry."},
{"Comment", "Comment of the name entry command."} };
private static final int STRUCTUREELEMENTCOMMAND_LENGTH = 6;
private static final String[][] STRUCTUREELEMENT_HEADER_COMMENT = {
{"Uuid", "Identity (uuid) of the structure entry. Value is created server-side."},
{"Type", "Type of the structure entry. Valid values - SYSTEMGROUP, SYSTEM, SUBSYSTEM, DISCIPLINE, DEVICEGROUP, DEVICETYPE."},
{"Parent", "Identity (uuid) for the structure entry parent (if the structure entry has a parent)."},
{"Mnemonic", "Mnemonic of the structure entry."},
{"Ordering", "Ordering of the structure entry."},
{"Description", "Description (verbose) of the structure entry."},
// above StructureElementCommand
{"MnemonicPath", "Mnemonic path of the structure entry."},
{"Level", "Level of the structure entry."},
{"Status", "Status of the structure entry."},
{"Deleted", "If the structure entry is deleted."},
{"When", "Date and time when the structure entry was created."},
{"Who", "Name (user) of who created the structure entry."},
{"Comment", "Comment of the structure entry command."} };
private static final String ARIAL = "Arial";
private static final String SHEET = "Entries";
private static final String TEXT = "text";
private static final String FAILED_TO_EXPORT_VALUES_TO_FILE = "Failed to export values to file";
private static final String FILE_COULD_NOT_BE_PARSED_FOR_VALUE_AT_ROW_CELL = "File could not be parsed for value at row: {0} cell: {1}";
private static final String INVALID_SHEET_EXPECTED_SHEET = "Invalid sheet. Expected sheet: {0}";
private static final String INVALID_VALUE_EXPECTED_VALUE = "Invalid value: {0} Expected value: {1}";
private static final String INVALID_VALUE_UNEXPECTED_VALUE = "Invalid value: {0} Unexpected value.";
/**
* This class is not to be instantiated.
*/
private ExcelUtil() {
throw new IllegalStateException("Utility class");
}
/**
* Utility method to check if file has Excel format.
*
* @param file file
* @return boolean if file has Excel format
*/
public static boolean hasExcelFormat(MultipartFile file) {
return MIME_TYPE_OPENXML_SPREADSHEET.equals(file.getContentType());
}
/**
* Utility method to convert an Excel file to a list of name element commands given how Excel file is to be interpreted.
*
* @param is input stream
* @param nameCommand name command
* @return list of name elements
*/
public static List<NameElementCommand> excelToNameElementCommands(InputStream is, NameCommand nameCommand) {
// rules for conversion
// Excel as NameElementCommand accepted
// ( Excel as NameElement accepted )
// see validateHeaderNameElementCommand
// NameElementCommand
// create - parentSystemStructure, parentDeviceStructure, index, description
// update - uuid, parentSystemStructure, parentDeviceStructure, index, description
// delete - uuid
int rowIndex = 0;
int columnIndex = 0;
try {
Workbook workbook = new XSSFWorkbook(is);
validateSheet(workbook);
Sheet sheet = workbook.getSheet(SHEET);
Iterator<Row> rows = sheet.iterator();
List<NameElementCommand> list = Lists.newArrayList();
boolean hasCell = false;
// iterate over rows and columns (cells)
while (rows.hasNext()) {
Row row = rows.next();
Iterator<Cell> cells = row.iterator();
NameElementCommand nameElementCommand = new NameElementCommand();
while (cells.hasNext()) {
hasCell = true;
Cell cell = cells.next();
rowIndex = cell.getRowIndex();
columnIndex = cell.getColumnIndex();
// ensure header row with syntax
if (rowIndex == 0) {
validateHeaderNameElementCommand(cell);
continue;
}
String value = columnIndex < NAMEELEMENTCOMMAND_LENGTH ? cell.getStringCellValue() : null;
switch (columnIndex) {
case 0:
nameElementCommand.setUuid(!StringUtils.isEmpty(value) ? UUID.fromString(value) : null);
break;
case 1:
nameElementCommand.setParentSystemStructure(!StringUtils.isEmpty(value) ? UUID.fromString(value) : null);
break;
case 2:
nameElementCommand.setParentDeviceStructure(!StringUtils.isEmpty(value) ? UUID.fromString(value) : null);
break;
case 3:
nameElementCommand.setIndex(value);
break;
case 4:
nameElementCommand.setDescription(value);
break;
default:
if (columnIndex > NAMEELEMENT_HEADER_COMMENT.length - 1) {
throw new IllegalArgumentException(
MessageFormat.format(INVALID_VALUE_UNEXPECTED_VALUE, value));
}
break;
}
}
// not add header row
if (rowIndex > 0) {
list.add(nameElementCommand);
}
}
if (!hasCell) {
throw new ServiceException(
MessageFormat.format(FILE_COULD_NOT_BE_PARSED_FOR_VALUE_AT_ROW_CELL, rowIndex, columnIndex),
null, null, null);
}
workbook.close();
LOGGER.log(Level.FINE,
() -> MessageFormat.format(
TextUtil.DESCRIPTION_NUMBER_ELEMENTS,
"Excel to name element commands",
list.size()));
return list;
} catch (IllegalArgumentException | IOException e) {
throw new ServiceException(
MessageFormat.format(FILE_COULD_NOT_BE_PARSED_FOR_VALUE_AT_ROW_CELL, rowIndex, columnIndex),
e.getMessage(), null, e);
}
}
/**
* Utility method to convert an Excel file to a list of structure element commands given how Excel file is to be interpreted..
*
* @param is input stream
* @param structureCommand structure command
* @return list of structure elements
*/
public static List<StructureElementCommand> excelToStructureElementCommands(InputStream is, StructureCommand structureCommand) {
// rules for conversion
// Excel as StructureElementCommand accepted
// ( Excel as StructureElement accepted )
// see validateHeaderStructureElementCommand
// StructureElementCommand
// create - type, parent, mnemonic, ordering, description
// update - uuid, type, parent, mnemonic, ordering, description
// delete - uuid, type
int rowIndex = 0;
int columnIndex = 0;
try {
Workbook workbook = new XSSFWorkbook(is);
validateSheet(workbook);
Sheet sheet = workbook.getSheet(SHEET);
Iterator<Row> rows = sheet.iterator();
List<StructureElementCommand> list = Lists.newArrayList();
boolean hasCell = false;
// iterate over rows and columns (cells)
while (rows.hasNext()) {
Row row = rows.next();
Iterator<Cell> cells = row.iterator();
StructureElementCommand structureElementCommand = new StructureElementCommand();
while (cells.hasNext()) {
hasCell = true;
Cell cell = cells.next();
rowIndex = cell.getRowIndex();
columnIndex = cell.getColumnIndex();
// ensure header row with syntax
if (rowIndex == 0) {
validateHeaderStructureElementCommand(cell);
continue;
}
String value = columnIndex < STRUCTUREELEMENTCOMMAND_LENGTH ? cell.getStringCellValue() : null;
switch (columnIndex) {
case 0:
structureElementCommand.setUuid(!StringUtils.isEmpty(value) ? UUID.fromString(value) : null);
break;
case 1:
structureElementCommand.setType(Type.valueOf(value));
break;
case 2:
structureElementCommand.setParent(!StringUtils.isEmpty(value) ? UUID.fromString(value) : null);
break;
case 3:
structureElementCommand.setMnemonic(value);
break;
case 4:
structureElementCommand.setOrdering(!StringUtils.isEmpty(value) ? Integer.parseInt(value) : null);
break;
case 5:
structureElementCommand.setDescription(value);
break;
default:
if (columnIndex > STRUCTUREELEMENT_HEADER_COMMENT.length - 1) {
throw new IllegalArgumentException(
MessageFormat.format(INVALID_VALUE_UNEXPECTED_VALUE, value));
}
break;
}
}
// not add header row
if (rowIndex > 0) {
list.add(structureElementCommand);
}
}
if (!hasCell) {
throw new ServiceException(
MessageFormat.format(FILE_COULD_NOT_BE_PARSED_FOR_VALUE_AT_ROW_CELL, rowIndex, columnIndex),
null, null, null);
}
workbook.close();
LOGGER.log(Level.FINE,
() -> MessageFormat.format(
TextUtil.DESCRIPTION_NUMBER_ELEMENTS,
"Excel to structure element commands",
list.size()));
return list;
} catch (IllegalArgumentException | IOException e) {
throw new ServiceException(
MessageFormat.format(FILE_COULD_NOT_BE_PARSED_FOR_VALUE_AT_ROW_CELL, rowIndex, columnIndex),
e.getMessage(), null, e);
}
}
/**
* Validate that workbook has sheet with expected name.
*
* @param workbook workbook
*/
private static void validateSheet(Workbook workbook) {
if (workbook.getSheet(SHEET) == null) {
throw new IllegalArgumentException(MessageFormat.format(INVALID_SHEET_EXPECTED_SHEET, SHEET));
}
}
/**
* Validate that cell is a proper header cell for a name element.
*
* @param cell cell
*/
private static void validateHeaderNameElementCommand(Cell cell) {
// validate that columns are NameElementCommand
// nothing less or more
// have condition to allow NameElementCommand but not NameElement
// cell.getColumnIndex() >= NAMEELEMENTCOMMAND_LENGTH
// throw new IllegalArgumentException(
// MessageFormat.format(INVALID_VALUE_UNEXPECTED_VALUE, cell.getStringCellValue()))
if (cell.getColumnIndex() < NAMEELEMENTCOMMAND_LENGTH
&& !NAMEELEMENT_HEADER_COMMENT[cell.getColumnIndex()][0].equals(cell.getStringCellValue())) {
throw new IllegalArgumentException(
MessageFormat.format(
INVALID_VALUE_EXPECTED_VALUE,
cell.getStringCellValue(),
NAMEELEMENT_HEADER_COMMENT[cell.getColumnIndex()][0]));
}
}
/**
* Validate that cell is a proper header cell for a structure element.
*
* @param cell cell
*/
private static void validateHeaderStructureElementCommand(Cell cell) {
// validate that columns are StructureElementCommand
// nothing less or more
// have condition to allow StructureElementCommand but not StructureElement
// cell.getColumnIndex() >= STRUCTUREELEMENTCOMMAND_LENGTH
// throw new IllegalArgumentException(
// MessageFormat.format(INVALID_VALUE_UNEXPECTED_VALUE, cell.getStringCellValue()))
if (cell.getColumnIndex() < STRUCTUREELEMENTCOMMAND_LENGTH
&& !STRUCTUREELEMENT_HEADER_COMMENT[cell.getColumnIndex()][0].equals(cell.getStringCellValue())) {
throw new IllegalArgumentException(
MessageFormat.format(
INVALID_VALUE_EXPECTED_VALUE,
cell.getStringCellValue(),
STRUCTUREELEMENT_HEADER_COMMENT[cell.getColumnIndex()][0]));
}
}
/**
* Utility method to convert a list of name elements to an Excel file.
*
* @param nameElements name elements
* @return Excel file
*/
public static ByteArrayInputStream nameElementsToExcel(List<NameElement> nameElements) {
LOGGER.log(Level.FINE,
() -> MessageFormat.format(
TextUtil.DESCRIPTION_NUMBER_ELEMENTS,
"Name elements to Excel",
nameElements.size()));
try (Workbook workbook = new XSSFWorkbook(); ByteArrayOutputStream out = new ByteArrayOutputStream();) {
Sheet sheet = workbook.createSheet(SHEET);
// prepare
Drawing<?> drawing = sheet.createDrawingPatriarch();
CreationHelper factory = workbook.getCreationHelper();
ClientAnchor anchor = factory.createClientAnchor();
// format, font, style
DataFormat format = workbook.createDataFormat();
short textFormat = format.getFormat(TEXT);
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setFontHeightInPoints((short)12);
headerFont.setFontName(ARIAL);
Font dataFont = workbook.createFont();
dataFont.setBold(false);
dataFont.setFontHeightInPoints((short)12);
dataFont.setFontName(ARIAL);
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle.setDataFormat(textFormat);
headerCellStyle.setFont(headerFont);
CellStyle dataCellStyle = workbook.createCellStyle();
dataCellStyle.setDataFormat(textFormat);
dataCellStyle.setFont(dataFont);
// header
Row headerRow = sheet.createRow(0);
for (int columnIndex = 0; columnIndex < NAMEELEMENT_HEADER_COMMENT.length; columnIndex++) {
Cell cell = headerRow.createCell(columnIndex);
// value
cell.setCellValue(NAMEELEMENT_HEADER_COMMENT[columnIndex][0]);
// width
sheet.setColumnWidth(columnIndex, SHEET_COLUMN_WIDTH);
// style
cell.setCellStyle(headerCellStyle);
// comment
anchor.setRow1(headerRow.getRowNum());
anchor.setRow2(headerRow.getRowNum()+3);
anchor.setCol1(cell.getColumnIndex());
anchor.setCol2(cell.getColumnIndex()+1);
Comment cellComment = drawing.createCellComment(anchor);
RichTextString richTextString = factory.createRichTextString(NAMEELEMENT_HEADER_COMMENT[columnIndex][1]);
cellComment.setString(richTextString);
cellComment.setAuthor(TextUtil.NAMING);
cell.setCellComment(cellComment);
}
// data
int rowIndex = 1;
for (NameElement nameElement : nameElements) {
Row row = sheet.createRow(rowIndex++);
for (int columnIndex = 0; columnIndex < NAMEELEMENT_HEADER_COMMENT.length; columnIndex++) {
Cell cell = row.createCell(columnIndex);
cell.setCellStyle(dataCellStyle);
switch (columnIndex) {
case 0:
cell.setCellValue(nameElement.getUuid() != null ? nameElement.getUuid().toString() : null);
break;
case 1:
cell.setCellValue(nameElement.getParentSystemStructure() != null ? nameElement.getParentSystemStructure().toString() : null);
break;
case 2:
cell.setCellValue(nameElement.getParentDeviceStructure() != null ? nameElement.getParentDeviceStructure().toString() : null);
break;
case 3:
cell.setCellValue(nameElement.getIndex());
break;
case 4:
cell.setCellValue(nameElement.getDescription());
break;
case 5:
cell.setCellValue(nameElement.getSystemStructure());
break;
case 6:
cell.setCellValue(nameElement.getDeviceStructure());
break;
case 7:
cell.setCellValue(nameElement.getName());
break;
case 8:
cell.setCellValue(nameElement.getStatus() != null ? nameElement.getStatus().toString() : null);
break;
case 9:
cell.setCellValue(nameElement.isDeleted());
break;
case 10:
cell.setCellValue(DateFormat.getDateTimeInstance().format(nameElement.getWhen()));
break;
case 11:
cell.setCellValue(nameElement.getWho());
break;
case 12:
cell.setCellValue(nameElement.getComment());
break;
default:
break;
}
}
}
workbook.write(out);
return new ByteArrayInputStream(out.toByteArray());
} catch (IOException e) {
throw new ServiceException(FAILED_TO_EXPORT_VALUES_TO_FILE, e.getMessage(), null, e);
}
}
/**
* Utility method to convert a list of structure elements to an Excel file.
*
* @param structureElements structure elements
* @return Excel file
*/
public static ByteArrayInputStream structureElementsToExcel(List<StructureElement> structureElements) {
LOGGER.log(Level.FINE,
() -> MessageFormat.format(
TextUtil.DESCRIPTION_NUMBER_ELEMENTS,
"Structure elements to Excel",
structureElements.size()));
try (Workbook workbook = new XSSFWorkbook(); ByteArrayOutputStream out = new ByteArrayOutputStream();) {
Sheet sheet = workbook.createSheet(SHEET);
// prepare
Drawing<?> drawing = sheet.createDrawingPatriarch();
CreationHelper factory = workbook.getCreationHelper();
ClientAnchor anchor = factory.createClientAnchor();
// format, font, style
DataFormat format = workbook.createDataFormat();
short textFormat = format.getFormat(TEXT);
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setFontHeightInPoints((short)12);
headerFont.setFontName(ARIAL);
Font dataFont = workbook.createFont();
dataFont.setBold(false);
dataFont.setFontHeightInPoints((short)12);
dataFont.setFontName(ARIAL);
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle.setDataFormat(textFormat);
headerCellStyle.setFont(headerFont);
CellStyle dataCellStyle = workbook.createCellStyle();
dataCellStyle.setDataFormat(textFormat);
dataCellStyle.setFont(dataFont);
// header
Row headerRow = sheet.createRow(0);
for (int columnIndex = 0; columnIndex < STRUCTUREELEMENT_HEADER_COMMENT.length; columnIndex++) {
Cell cell = headerRow.createCell(columnIndex);
// value
cell.setCellValue(STRUCTUREELEMENT_HEADER_COMMENT[columnIndex][0]);
// width
sheet.setColumnWidth(columnIndex, SHEET_COLUMN_WIDTH);
// style
cell.setCellStyle(headerCellStyle);
// comment
anchor.setRow1(headerRow.getRowNum());
anchor.setRow2(headerRow.getRowNum()+3);
anchor.setCol1(cell.getColumnIndex());
anchor.setCol2(cell.getColumnIndex()+1);
Comment cellComment = drawing.createCellComment(anchor);
RichTextString richTextString = factory.createRichTextString(STRUCTUREELEMENT_HEADER_COMMENT[columnIndex][1]);
cellComment.setString(richTextString);
cellComment.setAuthor(TextUtil.NAMING);
cell.setCellComment(cellComment);
}
// data
int rowIndex = 1;
for (StructureElement structureElement : structureElements) {
Row row = sheet.createRow(rowIndex++);
for (int columnIndex = 0; columnIndex < NAMEELEMENT_HEADER_COMMENT.length; columnIndex++) {
Cell cell = row.createCell(columnIndex);
cell.setCellStyle(dataCellStyle);
switch (columnIndex) {
case 0:
cell.setCellValue(structureElement.getUuid() != null ? structureElement.getUuid().toString() : null);
break;
case 1:
cell.setCellValue(structureElement.getType() != null ? structureElement.getType().toString() : null);
break;
case 2:
cell.setCellValue(structureElement.getParent() != null ? structureElement.getParent().toString() : null);
break;
case 3:
cell.setCellValue(structureElement.getMnemonic());
break;
case 4:
cell.setCellValue(structureElement.getOrdering() != null ? structureElement.getOrdering().toString() : null);
break;
case 5:
cell.setCellValue(structureElement.getDescription());
break;
case 6:
cell.setCellValue(structureElement.getMnemonicPath());
break;
case 7:
cell.setCellValue(structureElement.getLevel());
break;
case 8:
cell.setCellValue(structureElement.getStatus() != null ? structureElement.getStatus().toString() : null);
break;
case 9:
cell.setCellValue(structureElement.isDeleted());
break;
case 10:
cell.setCellValue(DateFormat.getDateTimeInstance().format(structureElement.getWhen()));
break;
case 11:
cell.setCellValue(structureElement.getWho());
break;
case 12:
cell.setCellValue(structureElement.getComment());
break;
default:
break;
}
}
}
workbook.write(out);
return new ByteArrayInputStream(out.toByteArray());
} catch (IOException e) {
throw new ServiceException(FAILED_TO_EXPORT_VALUES_TO_FILE, e.getMessage(), null, e);
}
}
}
......@@ -18,30 +18,25 @@
package org.openepics.names.util;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
import org.openepics.names.exception.DataConflictException;
import org.openepics.names.exception.DataDeletedException;
import org.openepics.names.exception.DataExistException;
import org.openepics.names.exception.DataNotAvailableException;
import org.openepics.names.exception.DataNotCorrectException;
import org.openepics.names.exception.DataNotFoundException;
import org.openepics.names.exception.DataNotValidException;
import org.openepics.names.exception.InputNotAvailableException;
import org.openepics.names.exception.InputNotCorrectException;
import org.openepics.names.exception.InputNotEmptyException;
import org.openepics.names.exception.InputNotValidException;
/**
* Utility class to assist in handling of exceptions.
* <br/><br/>
* Note
* <ul>
* <li>400 {@link HttpStatus#BAD_REQUEST}</li>
* <li>401 {@link HttpStatus#UNAUTHORIZED}</li>
* <li>403 {@link HttpStatus#FORBIDDEN}</li>
* <li>404 {@link HttpStatus#NOT_FOUND}</li>
* <li>409 {@link HttpStatus#CONFLICT}</li>
* <li>500 {@link HttpStatus#INTERNAL_SERVER_ERROR}</li>
* <li>501 {@link HttpStatus#NOT_IMPLEMENTED}</li>
* </ul>
*
* @author Lars Johansson
*/
public class ExceptionUtil {
public static final String ONE_OR_MORE_ELEMENTS_ARE_NOT_CORRECT = "One or more elements are not correct.";
public static final String OPERATION_COULD_NOT_BE_PERFORMED = "Operation could not be performed.";
/**
* This class is not to be instantiated.
*/
......@@ -50,206 +45,310 @@ public class ExceptionUtil {
}
/**
* Convert service http status exception to response status exception.
*
* @param e service http status exception
* @return response status exception
*/
public static ResponseStatusException convertException(ServiceHttpStatusException e) {
switch (e.getHttpStatus()) {
case BAD_REQUEST:
throw ExceptionUtil.createResponseStatusExceptionBadRequest();
case UNAUTHORIZED:
throw ExceptionUtil.createResponseStatusExceptionUnauthorized();
case FORBIDDEN:
throw ExceptionUtil.createResponseStatusExceptionForbidden();
case NOT_FOUND:
throw ExceptionUtil.createResponseStatusExceptionNotFound();
case CONFLICT:
throw ExceptionUtil.createResponseStatusExceptionConflict();
case INTERNAL_SERVER_ERROR:
throw ExceptionUtil.createResponseStatusExceptionInternalServerError();
case NOT_IMPLEMENTED:
throw ExceptionUtil.createResponseStatusExceptionNotImplemented();
default:
throw ExceptionUtil.createResponseStatusExceptionInternalServerError();
}
* Create data conflict exception.
* Intended for communication inside server.
*
* @param message message
* @param details details
* @param field field
* @return data conflict exception
*/
public static DataConflictException createDataConflictException(String message, String details, String field) {
return new DataConflictException(message, details, field);
}
/**
* Create response status exception.
* Intended for communication from server to client.
* Create data deleted exception.
* Intended for communication inside server.
*
* @param status http status
* @param reason reason
* @param cause cause
* @return response status exception
* @param message message
* @param details details
* @param field field
* @return data deleted exception
*/
protected static ResponseStatusException createResponseStatusException(HttpStatus status, String reason, Throwable cause) {
return new ResponseStatusException(status, reason, cause);
public static DataDeletedException createDataDeletedException(String message, String details, String field) {
return new DataDeletedException(message, details, field);
}
/**
* Create response status exception for {@link HttpStatus#BAD_REQUEST}.
* Intended for communication from server to client.
* Create data exist exception.
* Intended for communication inside server.
*
* @return response status exception
* @param message message
* @param details details
* @param field field
* @return data exist exception
*/
protected static ResponseStatusException createResponseStatusExceptionBadRequest() {
return createResponseStatusException(HttpStatus.BAD_REQUEST, OPERATION_COULD_NOT_BE_PERFORMED, null);
public static DataExistException createDataExistException(String message, String details, String field) {
return new DataExistException(message, details, field);
}
/**
* Create response status exception for {@link HttpStatus#UNAUTHORIZED}.
* Intended for communication from server to client.
* Create data not available exception.
* Intended for communication inside server.
*
* @return response status exception
* @param message message
* @param details details
* @param field field
* @return data not available exception
*/
protected static ResponseStatusException createResponseStatusExceptionUnauthorized() {
return createResponseStatusException(HttpStatus.UNAUTHORIZED, OPERATION_COULD_NOT_BE_PERFORMED, null);
public static DataNotAvailableException createDataNotAvailableException(String message, String details, String field) {
return new DataNotAvailableException(message, details, field);
}
/**
* Create response status exception for {@link HttpStatus#FORBIDDEN}.
* Intended for communication from server to client.
* Create data not correct exception.
* Intended for communication inside server.
*
* @return response status exception
* @param message message
* @param details details
* @param field field
* @return data not correct exception
*/
protected static ResponseStatusException createResponseStatusExceptionForbidden() {
return createResponseStatusException(HttpStatus.FORBIDDEN, OPERATION_COULD_NOT_BE_PERFORMED, null);
public static DataNotCorrectException createDataNotCorrectException(String message, String details, String field) {
return new DataNotCorrectException(message, details, field);
}
/**
* Create response status exception for {@link HttpStatus#NOT_FOUND}.
* Intended for communication from server to client.
* Create data not found exception.
* Intended for communication inside server.
*
* @return response status exception
* @param message message
* @param details details
* @param field field
* @return data not found exception
*/
protected static ResponseStatusException createResponseStatusExceptionNotFound() {
return createResponseStatusException(HttpStatus.NOT_FOUND, OPERATION_COULD_NOT_BE_PERFORMED, null);
public static DataNotFoundException createDataNotFoundException(String message, String details, String field) {
return new DataNotFoundException(message, details, field);
}
/**
* Create response status exception for {@link HttpStatus#CONFLICT}.
* Intended for communication from server to client.
* Create data not valid exception.
* Intended for communication inside server.
*
* @return response status exception
* @param message message
* @param details details
* @param field field
* @return data not valid exception
*/
protected static ResponseStatusException createResponseStatusExceptionConflict() {
return createResponseStatusException(HttpStatus.CONFLICT, OPERATION_COULD_NOT_BE_PERFORMED, null);
public static DataNotValidException createDataNotValidException(String message, String details, String field) {
return new DataNotValidException(message, details, field);
}
/**
* Create response status exception for {@link HttpStatus#INTERNAL_SERVER_ERROR}.
* Intended for communication from server to client.
* Create input not available exception.
* Intended for communication inside server.
* Note that message is automatically generated if message is <tt>null</tt> and field <tt>not null</tt>.
*
* @return response status exception
* @param message message
* @param details details
* @param field field
* @return input not available exception
*/
public static ResponseStatusException createResponseStatusExceptionInternalServerError() {
return createResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, OPERATION_COULD_NOT_BE_PERFORMED, null);
public static InputNotAvailableException createInputNotAvailableException(String message, String details, String field) {
return new InputNotAvailableException(message, details, field);
}
/**
* Create response status exception for {@link HttpStatus#NOT_IMPLEMENTED}.
* Intended for communication from server to client.
* Create input not correct exception.
* Intended for communication inside server.
* Note that message is automatically generated if message is <tt>null</tt> and field <tt>not null</tt>.
*
* @return response status exception
* @param message message
* @param details details
* @param field field
* @return input not correct exception
*/
public static ResponseStatusException createResponseStatusExceptionNotImplemented() {
return createResponseStatusException(HttpStatus.NOT_IMPLEMENTED, OPERATION_COULD_NOT_BE_PERFORMED, null);
public static InputNotCorrectException createInputNotCorrectException(String message, String details, String field) {
return new InputNotCorrectException(message, details, field);
}
/**
* Create service http status exception.
* Create input not empty exception.
* Intended for communication inside server.
* Note that message is automatically generated if message is <tt>null</tt> and field <tt>not null</tt>.
*
* @param status http status
* @param message message
* @param details details
* @param userFriendly user friendly
* @param cause cause
* @return service http status exception
* @param field field
* @return input not empty exception
*/
protected static ServiceHttpStatusException createServiceHttpStatusException(HttpStatus status, String message, String details, String userFriendly, Throwable cause) {
return new ServiceHttpStatusException(status, message, details, userFriendly, cause);
public static InputNotEmptyException createInputNotEmptyException(String message, String details, String field) {
return new InputNotEmptyException(message, details, field);
}
/**
* Create service http status exception for {@link HttpStatus#BAD_REQUEST}.
* Create input not valid exception.
* Intended for communication inside server.
* Note that message is automatically generated if message is <tt>null</tt> and field <tt>not null</tt>.
*
* @param message message
* @return service http status exception
* @param details details
* @param field field
* @return input not valid exception
*/
public static ServiceHttpStatusException createServiceHttpStatusExceptionBadRequest(String message, String details, String userFriendly) {
return createServiceHttpStatusException(HttpStatus.BAD_REQUEST, message, details, userFriendly, null);
public static InputNotValidException createInputNotValidException(String message, String details, String field) {
return new InputNotValidException(message, details, field);
}
// ----------------------------------------------------------------------------------------------------
/**
* Create service http status exception for {@link HttpStatus#UNAUTHORIZED}.
* Intended for communication inside server.
* Validate condition and throw data conflict exception if condition not <tt>true</tt>.
*
* @param condition condition
* @param message message
* @return service http status exception
* @param details details
* @param field field
*/
public static ServiceHttpStatusException createServiceHttpStatusExceptionUnauthorized(String message, String details, String userFriendly) {
return createServiceHttpStatusException(HttpStatus.UNAUTHORIZED, message, details, userFriendly, null);
public static void validateConditionDataConflictException(boolean condition, String message, String details, String field) {
if (!condition) {
throw ExceptionUtil.createDataConflictException(message, details, field);
}
}
/**
* Create service http status exception for {@link HttpStatus#FORBIDDEN}.
* Intended for communication inside server.
* Validate condition and throw data deleted exception if condition not <tt>true</tt>.
*
* @param condition condition
* @param message message
* @return service http status exception
* @param details details
* @param field field
*/
public static ServiceHttpStatusException createServiceHttpStatusExceptionForbidden(String message, String details, String userFriendly) {
return createServiceHttpStatusException(HttpStatus.FORBIDDEN, message, details, userFriendly, null);
public static void validateConditionDataDeletedException(boolean condition, String message, String details, String field) {
if (!condition) {
throw ExceptionUtil.createDataDeletedException(message, details, field);
}
}
/**
* Create service http status exception for {@link HttpStatus#NOT_FOUND}.
* Intended for communication inside server.
* Validate condition and throw data exist exception if condition not <tt>true</tt>.
*
* @param condition condition
* @param message message
* @return service http status exception
* @param details details
* @param field field
*/
public static ServiceHttpStatusException createServiceHttpStatusExceptionNotFound(String message, String details, String userFriendly) {
return createServiceHttpStatusException(HttpStatus.NOT_FOUND, message, details, userFriendly, null);
public static void validateConditionDataExistException(boolean condition, String message, String details, String field) {
if (!condition) {
throw ExceptionUtil.createDataExistException(message, details, field);
}
}
/**
* Create service http status exception for {@link HttpStatus#CONFLICT}.
* Intended for communication inside server.
* Validate condition and throw data not available exception if condition not <tt>true</tt>.
*
* @param condition condition
* @param message message
* @param details details
* @param field field
*/
public static void validateConditionDataNotAvailableException(boolean condition, String message, String details, String field) {
if (!condition) {
throw ExceptionUtil.createDataNotAvailableException(message, details, field);
}
}
/**
* Validate condition and throw data not correct exception if condition not <tt>true</tt>.
*
* @param condition condition
* @param message message
* @return service http status exception
* @param details details
* @param field field
*/
public static ServiceHttpStatusException createServiceHttpStatusExceptionConflict(String message, String details, String userFriendly) {
return createServiceHttpStatusException(HttpStatus.CONFLICT, message, details, userFriendly, null);
public static void validateConditionDataNotCorrectException(boolean condition, String message, String details, String field) {
if (!condition) {
throw ExceptionUtil.createDataNotCorrectException(message, details, field);
}
}
/**
* Create service http status exception for {@link HttpStatus#INTERNAL_SERVER_ERROR}.
* Intended for communication inside server.
* Validate condition and throw data not found exception if condition not <tt>true</tt>.
*
* @param condition condition
* @param message message
* @return service http status exception
* @param details details
* @param field field
*/
public static ServiceHttpStatusException createServiceHttpStatusExceptionInternalServerError(String message, String details, String userFriendly) {
return createServiceHttpStatusException(HttpStatus.INTERNAL_SERVER_ERROR, message, details, userFriendly, null);
public static void validateConditionDataNotFoundException(boolean condition, String message, String details, String field) {
if (!condition) {
throw ExceptionUtil.createDataNotFoundException(message, details, field);
}
}
/**
* Create service http status exception for {@link HttpStatus#NOT_IMPLEMENTED}.
* Intended for communication inside server.
* Validate condition and throw data not valid exception if condition not <tt>true</tt>.
*
* @param condition condition
* @param message message
* @param details details
* @param field field
*/
public static void validateConditionDataNotValidException(boolean condition, String message, String details, String field) {
if (!condition) {
throw ExceptionUtil.createDataNotValidException(message, details, field);
}
}
/**
* Validate condition and throw input not available exception if condition not <tt>true</tt>.
* Note that message is automatically generated if message is <tt>null</tt> and field <tt>not null</tt>.
*
* @param condition condition
* @param message message
* @param details details
* @param field field
*/
public static void validateConditionInputNotAvailableException(boolean condition, String message, String details, String field) {
if (!condition) {
throw ExceptionUtil.createInputNotAvailableException(message, details, field);
}
}
/**
* Validate condition and throw input not correct exception if condition not <tt>true</tt>.
* Note that message is automatically generated if message is <tt>null</tt> and field <tt>not null</tt>.
*
* @param condition condition
* @param message message
* @return service http status exception
* @param details details
* @param field field
*/
public static ServiceHttpStatusException createServiceHttpStatusExceptionNotImplemented(String message, String details, String userFriendly) {
return createServiceHttpStatusException(HttpStatus.NOT_IMPLEMENTED, message, details, userFriendly, null);
public static void validateConditionInputNotCorrectException(boolean condition, String message, String details, String field) {
if (!condition) {
throw ExceptionUtil.createInputNotCorrectException(message, details, field);
}
}
/**
* Validate condition and throw input not empty exception if condition not <tt>true</tt>.
* Note that message is automatically generated if message is <tt>null</tt> and field <tt>not null</tt>.
*
* @param condition condition
* @param message message
* @param details details
* @param field field
*/
public static void validateConditionInputNotEmptyException(boolean condition, String message, String details, String field) {
if (!condition) {
throw ExceptionUtil.createInputNotEmptyException(message, details, field);
}
}
/**
* Validate condition and throw input not valid exception if condition not <tt>true</tt>.
* Note that message is automatically generated if message is <tt>null</tt> and field <tt>not null</tt>.
*
* @param condition condition
* @param message message
* @param details details
* @param field field
*/
public static void validateConditionInputNotValidException(boolean condition, String message, String details, String field) {
if (!condition) {
throw ExceptionUtil.createInputNotValidException(message, details, field);
}
}
}
/*
* Copyright (C) 2021 European Spallation Source ERIC.
* Copyright (C) 2024 European Spallation Source ERIC.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
......@@ -18,6 +18,8 @@
package org.openepics.names.util;
import org.openepics.names.repository.IAuditNameRepository;
import org.openepics.names.repository.IAuditStructureRepository;
import org.openepics.names.repository.IDeviceGroupRepository;
import org.openepics.names.repository.IDeviceTypeRepository;
import org.openepics.names.repository.IDisciplineRepository;
......@@ -27,107 +29,17 @@ import org.openepics.names.repository.ISystemGroupRepository;
import org.openepics.names.repository.ISystemRepository;
/**
* Utility class and holder of references to repositories (interfaces).
* Utility record to collect references to repositories (interfaces).
*
* @author Lars Johansson
*/
public class HolderIRepositories {
private INameRepository nameRepository;
private ISystemGroupRepository systemGroupRepository;
private ISystemRepository systemRepository;
private ISubsystemRepository subsystemRepository;
private IDisciplineRepository disciplineRepository;
private IDeviceGroupRepository deviceGroupRepository;
private IDeviceTypeRepository deviceTypeRepository;
/**
* Public constructor to populate references to repositories.
*
* @param nameRepository reference to name repository
* @param systemGroupRepository reference to system group repository
* @param systemRepository reference to system repository
* @param subsystemRepository reference to subsystem repository
* @param disciplineRepository reference to discipline repository
* @param deviceGroupRepository reference to device group repository
* @param deviceTypeRepository reference to device type repository
*/
public HolderIRepositories(
INameRepository nameRepository,
ISystemGroupRepository systemGroupRepository,
ISystemRepository systemRepository,
ISubsystemRepository subsystemRepository,
IDisciplineRepository disciplineRepository,
IDeviceGroupRepository deviceGroupRepository,
IDeviceTypeRepository deviceTypeRepository) {
this.nameRepository = nameRepository;
this.systemGroupRepository = systemGroupRepository;
this.systemRepository = systemRepository;
this.subsystemRepository = subsystemRepository;
this.disciplineRepository = disciplineRepository;
this.deviceGroupRepository = deviceGroupRepository;
this.deviceTypeRepository = deviceTypeRepository;
}
/**
* Return reference to name repository.
*
* @return reference to name repository
*/
public INameRepository getNameRepository() {
return nameRepository;
};
/**
* Return reference to system group repository.
*
* @return reference to system group repository
*/
public ISystemGroupRepository getSystemGroupRepository() {
return systemGroupRepository;
};
/**
* Return reference to system repository.
*
* @return reference to system repository
*/
public ISystemRepository getSystemRepository() {
return systemRepository;
};
/**
* Return reference to subsystem repository.
*
* @return reference to subsystem repository
*/
public ISubsystemRepository getSubsystemRepository() {
return subsystemRepository;
};
/**
* Return reference to discipline repository.
*
* @return reference to discipline repository
*/
public IDisciplineRepository getDisciplineRepository() {
return disciplineRepository;
};
/**
* Return reference to device group repository.
*
* @return reference to device group repository
*/
public IDeviceGroupRepository getDeviceGroupRepository() {
return deviceGroupRepository;
};
/**
* Return reference to device type repository.
*
* @return reference to device type repository
*/
public IDeviceTypeRepository getDeviceTypeRepository() {
return deviceTypeRepository;
};
}
public record HolderIRepositories (
INameRepository nameRepository,
ISystemGroupRepository systemGroupRepository,
ISystemRepository systemRepository,
ISubsystemRepository subsystemRepository,
IDisciplineRepository disciplineRepository,
IDeviceGroupRepository deviceGroupRepository,
IDeviceTypeRepository deviceTypeRepository,
IAuditNameRepository auditNameRepository,
IAuditStructureRepository auditStructureRepository) {}
/*
* Copyright (C) 2021 European Spallation Source ERIC.
* Copyright (C) 2024 European Spallation Source ERIC.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
......@@ -18,6 +18,8 @@
package org.openepics.names.util;
import org.openepics.names.repository.AuditNameRepository;
import org.openepics.names.repository.AuditStructureRepository;
import org.openepics.names.repository.DeviceGroupRepository;
import org.openepics.names.repository.DeviceTypeRepository;
import org.openepics.names.repository.DisciplineRepository;
......@@ -27,107 +29,17 @@ import org.openepics.names.repository.SystemGroupRepository;
import org.openepics.names.repository.SystemRepository;
/**
* Utility class and holder of references to repositories.
* Utility record to collect references to repositories.
*
* @author Lars Johansson
*/
public class HolderRepositories {
private NameRepository nameRepository;
private SystemGroupRepository systemGroupRepository;
private SystemRepository systemRepository;
private SubsystemRepository subsystemRepository;
private DisciplineRepository disciplineRepository;
private DeviceGroupRepository deviceGroupRepository;
private DeviceTypeRepository deviceTypeRepository;
/**
* Public constructor to populate references to repositories.
*
* @param nameRepository reference to name repository
* @param systemGroupRepository reference to system group repository
* @param systemRepository reference to system repository
* @param subsystemRepository reference to subsystem repository
* @param disciplineRepository reference to discipline repository
* @param deviceGroupRepository reference to device group repository
* @param deviceTypeRepository reference to device type repository
*/
public HolderRepositories(
NameRepository nameRepository,
SystemGroupRepository systemGroupRepository,
SystemRepository systemRepository,
SubsystemRepository subsystemRepository,
DisciplineRepository disciplineRepository,
DeviceGroupRepository deviceGroupRepository,
DeviceTypeRepository deviceTypeRepository) {
this.nameRepository = nameRepository;
this.systemGroupRepository = systemGroupRepository;
this.systemRepository = systemRepository;
this.subsystemRepository = subsystemRepository;
this.disciplineRepository = disciplineRepository;
this.deviceGroupRepository = deviceGroupRepository;
this.deviceTypeRepository = deviceTypeRepository;
}
/**
* Return reference to name repository.
*
* @return reference to name repository
*/
public NameRepository getNameRepository() {
return nameRepository;
};
/**
* Return reference to system group repository.
*
* @return reference to system group repository
*/
public SystemGroupRepository getSystemGroupRepository() {
return systemGroupRepository;
};
/**
* Return reference to system repository.
*
* @return reference to system repository
*/
public SystemRepository getSystemRepository() {
return systemRepository;
};
/**
* Return reference to subsystem repository.
*
* @return reference to subsystem repository
*/
public SubsystemRepository getSubsystemRepository() {
return subsystemRepository;
};
/**
* Return reference to discipline repository.
*
* @return reference to discipline repository
*/
public DisciplineRepository getDisciplineRepository() {
return disciplineRepository;
};
/**
* Return reference to device group repository.
*
* @return reference to device group repository
*/
public DeviceGroupRepository getDeviceGroupRepository() {
return deviceGroupRepository;
};
/**
* Return reference to device type repository.
*
* @return reference to device type repository
*/
public DeviceTypeRepository getDeviceTypeRepository() {
return deviceTypeRepository;
};
}
public record HolderRepositories (
NameRepository nameRepository,
SystemGroupRepository systemGroupRepository,
SystemRepository systemRepository,
SubsystemRepository subsystemRepository,
DisciplineRepository disciplineRepository,
DeviceGroupRepository deviceGroupRepository,
DeviceTypeRepository deviceTypeRepository,
AuditNameRepository auditNameRepository,
AuditStructureRepository auditStructureRepository) {}
/*
* Copyright (C) 2024 European Spallation Source ERIC.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.openepics.names.util;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.openepics.names.repository.model.DeviceGroup;
import org.openepics.names.repository.model.DeviceType;
import org.openepics.names.repository.model.Discipline;
import org.openepics.names.repository.model.Subsystem;
import org.openepics.names.repository.model.System;
import org.openepics.names.repository.model.SystemGroup;
/**
* Utility class and holder of system and device structure content that are used to populate REST API return elements.
* <p>
* Class is used for performance reasons to speed up preparation of what is to be returned.
* </p>
*
* @author Lars Johansson
*/
public class HolderStructures {
private HashMap<Long, SystemGroup> systemGroups;
private HashMap<Long, System> systems;
private HashMap<Long, Subsystem> subsystems;
private HashMap<Long, Discipline> disciplines;
private HashMap<Long, DeviceGroup> deviceGroups;
private HashMap<Long, DeviceType> deviceTypes;
private boolean includeDeleted = true;
/**
* Public constructor to prepare containers for system and device structure content.
*
* @param holderIRepositories
*/
public HolderStructures (HolderIRepositories holderIRepositories) {
this(holderIRepositories, true);
}
/**
* Public constructor to prepare containers for system and device structure content.
*
* @param holderIRepositories holder of references to repositories
* @param includeDeleted include deleted structure entries
*/
public HolderStructures (HolderIRepositories holderIRepositories, boolean includeDeleted) {
List<SystemGroup> systemGroupsRead = null;
List<System> systemsRead = null;
List<Subsystem> subsystemsRead = null;
List<Discipline> disciplinesRead = null;
List<DeviceGroup> deviceGroupsRead = null;
List<DeviceType> deviceTypesRead = null;
if (includeDeleted) {
systemGroupsRead = holderIRepositories.systemGroupRepository().findAll();
systemsRead = holderIRepositories.systemRepository().findAll();
subsystemsRead = holderIRepositories.subsystemRepository().findAll();
disciplinesRead = holderIRepositories.disciplineRepository().findAll();
deviceGroupsRead = holderIRepositories.deviceGroupRepository().findAll();
deviceTypesRead = holderIRepositories.deviceTypeRepository().findAll();
} else {
systemGroupsRead = holderIRepositories.systemGroupRepository().findNotDeleted();
systemsRead = holderIRepositories.systemRepository().findNotDeleted();
subsystemsRead = holderIRepositories.subsystemRepository().findNotDeleted();
disciplinesRead = holderIRepositories.disciplineRepository().findNotDeleted();
deviceGroupsRead = holderIRepositories.deviceGroupRepository().findNotDeleted();
deviceTypesRead = holderIRepositories.deviceTypeRepository().findNotDeleted();
}
// initial capacity
// default load factor 0.75
// set at proper size to avoid rehashing
// size/0.75+1 (may be rounded downwards so possibly +2 instead)
float loadFactor = 0.75f;
this.systemGroups = new HashMap<>((int)(systemGroupsRead.size()/loadFactor + 2), loadFactor);
this.systems = new HashMap<>((int)(systemsRead.size()/loadFactor + 2), loadFactor);
this.subsystems = new HashMap<>((int)(subsystemsRead.size()/loadFactor + 2), loadFactor);
this.disciplines = new HashMap<>((int)(disciplinesRead.size()/loadFactor + 2), loadFactor);
this.deviceGroups = new HashMap<>((int)(deviceGroupsRead.size()/loadFactor + 2), loadFactor);
this.deviceTypes = new HashMap<>((int)(deviceTypesRead.size()/loadFactor + 2), loadFactor);
for (SystemGroup systemGroup : systemGroupsRead) {
this.systemGroups.put(systemGroup.getId(), systemGroup);
}
for (System system : systemsRead) {
this.systems.put(system.getId(), system);
}
for (Subsystem subsystem : subsystemsRead) {
this.subsystems.put(subsystem.getId(), subsystem);
}
for (Discipline discipline : disciplinesRead) {
this.disciplines.put(discipline.getId(), discipline);
}
for (DeviceGroup deviceGroup : deviceGroupsRead) {
this.deviceGroups.put(deviceGroup.getId(), deviceGroup);
}
for (DeviceType deviceType : deviceTypesRead) {
this.deviceTypes.put(deviceType.getId(), deviceType);
}
}
/**
* Find system group name part by uuid.
*
* @param id id
* @return system group name part
*/
public SystemGroup findSystemGroupById(Long id) {
return systemGroups.get(id);
}
/**
* Find system name part by uuid.
*
* @param id id
* @return system name part
*/
public System findSystemById(Long id) {
return systems.get(id);
}
/**
* Find subsystem name part by uuid.
*
* @param id id
* @return subsystem name part
*/
public Subsystem findSubsystemById(Long id) {
return subsystems.get(id);
}
/**
* Find discipline name part by uuid.
*
* @param id id
* @return discipline name part
*/
public Discipline findDisciplineById(Long id) {
return disciplines.get(id);
}
/**
* Find device group name part by uuid.
*
* @param id id
* @return device group name part
*/
public DeviceGroup findDeviceGroupById(Long id) {
return deviceGroups.get(id);
}
/**
* Find device type name part by uuid.
*
* @param id id
* @return device type name part
*/
public DeviceType findDeviceTypeById(Long id) {
return deviceTypes.get(id);
}
/**
* Return if include deleted structure entries.
*
* @return if include deleted structure entries
*/
public boolean getIncludeDeleted() {
return includeDeleted;
}
/**
* Return map with key-value pairs (id and system group).
*
* @return map with key-value pairs (id and system group)
*/
public Map<Long, SystemGroup> getIdSystemGroups() {
return systemGroups;
}
/**
* Return map with key-value pairs (id and system).
*
* @return map with key-value pairs (id and system)
*/
public Map<Long, System> getIdSystems() {
return systems;
}
/**
* Return map with key-value pairs (id and subsystem).
*
* @return map with key-value pairs (id and subsystem)
*/
public Map<Long, Subsystem> getIdSubsystems() {
return subsystems;
}
/**
* Return map with key-value pairs (id and discipline).
*
* @return map with key-value pairs (id and discipline)
*/
public Map<Long, Discipline> getIdDisciplines() {
return disciplines;
}
/**
* Return map with key-value pairs (id and device group).
*
* @return map with key-value pairs (id and device group)
*/
public Map<Long, DeviceGroup> getIdDeviceGroups() {
return deviceGroups;
}
/**
* Return map with key-value pairs (id and device type).
*
* @return map with key-value pairs (id and device type)
*/
public Map<Long, DeviceType> getIdDeviceTypes() {
return deviceTypes;
}
}
/*
* Copyright (C) 2022 European Spallation Source ERIC.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.openepics.names.util;
/**
* Kind of name command and operation (server-side).
*
* @author Lars Johansson
*/
public enum NameCommand {
CREATE, UPDATE, DELETE;
}
......@@ -19,12 +19,24 @@
package org.openepics.names.util;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.openepics.names.repository.model.AuditName;
import org.openepics.names.repository.model.DeviceType;
import org.openepics.names.repository.model.Name;
import org.openepics.names.repository.model.NameStructure;
import org.openepics.names.rest.beans.NameElement;
import org.openepics.names.repository.model.Structure;
import org.openepics.names.repository.model.Subsystem;
import org.openepics.names.repository.model.System;
import org.openepics.names.repository.model.SystemGroup;
import org.openepics.names.rest.beans.Status;
import org.openepics.names.rest.beans.element.NameElement;
import org.openepics.names.rest.beans.element.NameElementCommand;
import org.openepics.names.rest.beans.element.NameElementCommandConfirm;
import org.openepics.names.rest.beans.element.NameElementCommandCreate;
import org.openepics.names.rest.beans.element.NameElementCommandUpdate;
import com.google.common.collect.Lists;
/**
* Utility class to assist in populating name elements based on repository content.
......@@ -36,6 +48,9 @@ import org.openepics.names.rest.beans.Status;
*/
public class NameElementUtil {
// note
// requested attributes for names are used, not processed attributes
/**
* This class is not to be instantiated.
*/
......@@ -43,42 +58,185 @@ public class NameElementUtil {
throw new IllegalStateException("Utility class");
}
/**
* Populate and return list of name elements for list of names.
*
* @param auditNames audit names
* @param holderStructures container for system and device structure content
* @return list of name elements
*/
public static List<NameElement> getNameElementsForAuditNames(List<AuditName> auditNames, HolderStructures holderStructures) {
List<NameElement> nameElements = Lists.newArrayList();
for (AuditName auditName : auditNames) {
nameElements.add(NameElementUtil.getNameElement(auditName.getNonAuditName(), holderStructures));
}
return nameElements;
}
/**
* Populate and return list of name elements for list of names.
*
* @param names names
* @param holderStructures container for system and device structure content
* @return list of name elements
*/
public static List<NameElement> getNameElements(List<Name> names, HolderStructures holderStructures) {
List<NameElement> nameElements = Lists.newArrayList();
for (Name name : names) {
nameElements.add(NameElementUtil.getNameElement(name, holderStructures));
}
return nameElements;
}
/**
* Populate and return name element for name.
*
* @param name name
* @param holderStructures container for system and device structure content
* @return name element
*/
public static NameElement getNameElement(Name name) {
if (name == null) {
public static NameElement getNameElement(Name name, HolderStructures holderStructures) {
return getNameElement(name, holderStructures, null);
}
/**
* Populate and return name element for name.
*
* @param name name
* @param structure (system) structure
* @return name element
*/
public static NameElement getNameElement(Name name, Structure structure) {
return getNameElement(name, null, structure);
}
/**
* Populate and return name element for name.
*
* @param name name
* @param holderStructures container for system and device structure content
* @param structure (system) structure
* @return name element
*/
public static NameElement getNameElement(Name name, HolderStructures holderStructures, Structure structure) {
if (name == null || (holderStructures == null && structure == null)) {
return null;
}
if (structure != null && !(structure instanceof SystemGroup || structure instanceof System || structure instanceof Subsystem)) {
return null;
}
UUID parentSystemStructureUuid = null;
UUID parentDeviceStructureUuid = null;
if (structure != null) {
parentSystemStructureUuid = structure.getUuid();
} else {
parentSystemStructureUuid = getParentSystemStructureUuid(name, holderStructures);
parentDeviceStructureUuid = name.getDeviceTypeId() != null ? holderStructures.findDeviceTypeById(name.getDeviceTypeId()).getUuid() : null;
}
return getNameElement(
name.getUuid(),
name.getSystemgroupUuid(), name.getSystemUuid(), name.getSubsystemUuid(), name.getDevicetypeUuid(),
name.getUuid(), parentSystemStructureUuid, parentDeviceStructureUuid,
name.getInstanceIndex(), name.getDescription(),
NamingConventionUtil.extractMnemonicPathSystemStructure(name.getConventionName()),
NamingConventionUtil.extractMnemonicPathDeviceStructure(name.getConventionName()),
name.getInstanceIndex(), name.getConventionName(),
name.getDescription(), Status.APPROVED, name.isLatest(), name.isDeleted(),
name.getConventionName(),
name.getStatus(), name.isDeleted(),
name.getRequested(), name.getRequestedBy(), name.getRequestedComment());
}
/**
* Return UUID for parent system structure.
*
* @param name name
* @param holderStructures container for system and device structure content
* @return uuid
*/
public static UUID getParentSystemStructureUuid(Name name, HolderStructures holderStructures) {
return name.getSubsystemId() != null
? holderStructures.findSubsystemById(name.getSubsystemId()).getUuid()
: name.getSystemId() != null
? holderStructures.findSystemById(name.getSystemId()).getUuid()
: name.getSystemGroupId() != null
? holderStructures.findSystemGroupById(name.getSystemGroupId()).getUuid()
: null;
}
/**
* Return UUID for system group or null if non-existent.
*
* @param name name
* @param holderStructures container for system and device structure content
* @return uuid
*/
public static UUID getSystemGroupUuid(Name name, HolderStructures holderStructures) {
if (name == null || name.getSystemGroupId() == null || holderStructures == null) {
return null;
}
return name.getSystemGroupId() != null
? holderStructures.findSystemGroupById(name.getSystemGroupId()).getUuid()
: null;
}
/**
* Return UUID for system or null if non-existent.
*
* @param name name
* @param holderStructures container for system and device structure content
* @return uuid
*/
public static UUID getSystemUuid(Name name, HolderStructures holderStructures) {
if (name == null || name.getSystemId() == null || holderStructures == null) {
return null;
}
return name.getSystemId() != null
? holderStructures.findSystemById(name.getSystemId()).getUuid()
: null;
}
/**
* Return UUID for subsystem or null if non-existent.
*
* @param name name
* @param holderStructures container for system and device structure content
* @return uuid
*/
public static UUID getSubsystemUuid(Name name, HolderStructures holderStructures) {
if (name == null || name.getSubsystemId() == null || holderStructures == null) {
return null;
}
return name.getSubsystemId() != null
? holderStructures.findSubsystemById(name.getSubsystemId()).getUuid()
: null;
}
/**
* Return UUID for device type or null if non-existent.
*
* @param name name
* @param holderStructures container for system and device structure content
* @return uuid
*/
public static UUID getDeviceTypeUuid(Name name, HolderStructures holderStructures) {
if (name == null || name.getDeviceTypeId() == null || holderStructures == null) {
return null;
}
return name.getDeviceTypeId() != null
? holderStructures.findDeviceTypeById(name.getDeviceTypeId()).getUuid()
: null;
}
/**
* Populate and return name element.
*
* @param uuid uuid
* @param systemgroup system group
* @param system system
* @param subsystem subsystem
* @param devicetype device type
* @param systemstructure system structure mnemonic path
* @param devicestructure device structure mnemonic path
* @param parentSystemStructure parent system structure uuid (system group, system, subsystem)
* @param parentDeviceStructure parent device structure uuid (device type)
* @param index instance index
* @param name name
* @param description description
* @param systemStructure system structure mnemonic path
* @param deviceStructure device structure mnemonic path
* @param name name
* @param status status
* @param latest latest
* @param deleted deleted
* @param when when
* @param who who
......@@ -86,191 +244,345 @@ public class NameElementUtil {
* @return name element
*/
protected static NameElement getNameElement(
UUID uuid,
UUID systemgroup, UUID system, UUID subsystem, UUID devicetype,
String systemstructure, String devicestructure,
String index, String name,
String description, Status status, Boolean latest, Boolean deleted,
UUID uuid, UUID parentSystemStructure, UUID parentDeviceStructure,
String index, String description,
String systemStructure, String deviceStructure, String name,
Status status, Boolean deleted,
Date when, String who, String comment) {
return new NameElement(
uuid,
systemgroup, system, subsystem, devicetype,
systemstructure, devicestructure,
index, name,
description, status, latest, deleted,
uuid, parentSystemStructure, parentDeviceStructure,
index, description,
systemStructure, deviceStructure, name,
status, deleted,
when, who, comment);
}
private static boolean hasSameContent(NameElement nameElement, NameStructure nameStructure) {
/*
NameElement
x uuid
x description
x status
x latest
x deleted
NameStructure
x uuid
x description
x status
x latest
x deleted
*/
if (nameElement == null && nameStructure == null)
return true;
if (nameElement == null)
return false;
if (nameStructure == null)
/**
* Check if name element and name have same content.
*
* @param nameElement name element
* @param name name
* @param holderIRepositories holder repositories
* @param holderStructures holder of system and device structure content
* @return true if name element and name have same content, false otherwise
*/
public static boolean hasSameContent(NameElementCommand nameElement, Name name, HolderIRepositories holderIRepositories, HolderStructures holderStructures) {
// NameElement
// x parentSystemStructure (system group, system, subsystem)
// x parentDeviceStructure (device type)
// x index
// x name
// NameElementCommand
// uuid
// parentSystemStructure
// parentDeviceStructure
// index
// description
// Name
// x systemgroup_uuid
// x system_uuid
// x subsystem_uuid
// x devicetype_uuid
// x instance_index
// x convention_name
// find out system group, system, subsystem
// one of the three expected to be non-null, other two expected to be null
SystemGroup systemGroup = holderIRepositories.systemGroupRepository().findByUuid(nameElement.getParentSystemStructure().toString());
System system = holderIRepositories.systemRepository().findByUuid(nameElement.getParentSystemStructure().toString());
Subsystem subsystem = holderIRepositories.subsystemRepository().findByUuid(nameElement.getParentSystemStructure().toString());
DeviceType deviceType = null;
if (nameElement.getParentDeviceStructure() != null) {
deviceType = holderIRepositories.deviceTypeRepository().findByUuid(nameElement.getParentDeviceStructure().toString());
}
String derivedName = null;
if (systemGroup != null) {
derivedName = NameUtil.getName(systemGroup, deviceType, nameElement.getIndex(), holderStructures);
} else if (system != null) {
derivedName = NameUtil.getName(system, deviceType, nameElement.getIndex(), holderStructures);
} else if (subsystem != null) {
derivedName = NameUtil.getName(subsystem, deviceType, nameElement.getIndex(), holderStructures);
} else {
return false;
}
if (nameElement.getUuid() == null) {
if (nameStructure.getUuid() != null)
if (name.getUuid() != null)
return false;
} else if (!nameElement.getUuid().equals(nameStructure.getUuid()))
} else if (!nameElement.getUuid().equals(name.getUuid()))
return false;
if (nameElement.getDescription() == null) {
if (nameStructure.getDescription() != null)
return false;
} else if (!nameElement.getDescription().equals(nameStructure.getDescription()))
return false;
if (nameElement.getStatus() == null) {
if (nameStructure.getStatus() != null)
return false;
} else if (!nameElement.getStatus().equals(nameStructure.getStatus()))
return false;
if (nameElement.isLatest() == null) {
if (nameStructure.isLatest() != null)
if (derivedName == null) {
if (name.getConventionName() != null)
return false;
} else if (!nameElement.isLatest().equals(nameStructure.isLatest()))
} else if (!derivedName.equals(name.getConventionName()))
return false;
if (nameElement.isDeleted() == null) {
if (nameStructure.isDeleted() != null)
if (nameElement.getDescription() == null) {
if (name.getDescription() != null)
return false;
} else if (!nameElement.isDeleted().equals(nameStructure.isDeleted()))
} else if (!nameElement.getDescription().equals(name.getDescription()))
return false;
return true;
}
public static boolean hasSameContent(NameElement nameElement, Name name) {
/*
NameElement
x systemgroup
x system
x subsystem
x devicetype
x index
x name
Name
x systemgroup_uuid
x system_uuid
x subsystem_uuid
x devicetype_uuid
x instance_index
x convention_name
*/
if (!hasSameContent(nameElement, (NameStructure) name))
return false;
// ----------------------------------------------------------------------------------------------------
if (nameElement.getSystemgroup() == null) {
if (name.getSystemgroupUuid() != null)
return false;
} else if (!nameElement.getSystemgroup().equals(name.getSystemgroupUuid()))
return false;
if (nameElement.getSystem() == null) {
if (name.getSystemUuid() != null)
return false;
} else if (!nameElement.getSystem().equals(name.getSystemUuid()))
return false;
if (nameElement.getSubsystem() == null) {
if (name.getSubsystemUuid() != null)
return false;
} else if (!nameElement.getSubsystem().equals(name.getSubsystemUuid()))
return false;
if (nameElement.getDevicetype() == null) {
if (name.getDevicetypeUuid() != null)
return false;
} else if (!nameElement.getDevicetype().equals(name.getDevicetypeUuid()))
return false;
if (nameElement.getIndex() == null) {
if (name.getInstanceIndex() != null)
return false;
} else if (!nameElement.getIndex().equals(name.getInstanceIndex()))
return false;
if (nameElement.getName() == null) {
if (name.getConventionName() != null)
return false;
} else if (!nameElement.getName().equals(name.getConventionName()))
return false;
/**
* Convert name element command for create to name element command.
*
* @param command name element command for create
* @return name element command
*/
public static NameElementCommand convertCommandCreate2Command(NameElementCommandCreate command) {
return new NameElementCommand(
null,
command.getParentSystemStructure(),
command.getParentDeviceStructure(),
command.getIndex(),
command.getDescription());
}
return true;
/**
* Convert list of name element commands for create to list of name element commands.
*
* @param commands list of name element commands for create
* @return list of name element commands
*/
public static List<NameElementCommand> convertCommandCreate2Command(List<NameElementCommandCreate> commands) {
List<NameElementCommand> nameElementCommands = Lists.newArrayList();
for (NameElementCommandCreate command : commands) {
nameElementCommands.add(NameElementUtil.convertCommandCreate2Command(command));
}
return nameElementCommands;
}
/**
* Convert name element command for update to name element command.
*
* @param command name element command for update
* @return name element command
*/
public static NameElementCommand convertCommandUpdate2Command(NameElementCommandUpdate command) {
return new NameElementCommand(
command.getUuid(),
command.getParentSystemStructure(),
command.getParentDeviceStructure(),
command.getIndex(),
command.getDescription());
}
/**
* Convert list of name element commands for update to list of name element commands.
*
* @param commands list of name element commands for update
* @return list of name element commands
*/
public static List<NameElementCommand> convertCommandUpdate2Command(List<NameElementCommandUpdate> commands) {
List<NameElementCommand> nameElementCommands = Lists.newArrayList();
for (NameElementCommandUpdate command : commands) {
nameElementCommands.add(NameElementUtil.convertCommandUpdate2Command(command));
}
return nameElementCommands;
}
/**
* Convert name element command for confirm to name element command.
*
* @param command name element command for confirm
* @return name element command
*/
public static NameElementCommand convertCommandConfirm2Command(NameElementCommandConfirm command) {
return new NameElementCommand(
command.getUuid(),
null,
null,
null,
null);
}
/**
* Convert list of name element commands for confirm to list of name element commands.
*
* @param commands list of name element commands for confirm
* @return list of name element commands
*/
public static List<NameElementCommand> convertCommandConfirm2Command(List<NameElementCommandConfirm> commands) {
List<NameElementCommand> nameElementCommands = Lists.newArrayList();
for (NameElementCommandConfirm command : commands) {
nameElementCommands.add(NameElementUtil.convertCommandConfirm2Command(command));
}
return nameElementCommands;
}
// ----------------------------------------------------------------------------------------------------
/**
* Convert name element command to name element command for create.
*
* @param command name element command
* @return name element command for create
*/
public static NameElementCommandCreate convertCommand2CommandCreate(NameElementCommand command) {
return new NameElementCommandCreate(
command.getParentSystemStructure(),
command.getParentDeviceStructure(),
command.getIndex(),
command.getDescription());
}
/**
* Convert array of name element commands to array of name element commands for create.
*
* @param commands array of name element commands
* @return array of name element commands for create
*/
public static NameElementCommandCreate[] convertCommand2CommandCreate(NameElementCommand[] commands) {
NameElementCommandCreate[] nameElementCommands = new NameElementCommandCreate[commands.length];
for (int i=0; i<commands.length; i++) {
nameElementCommands[i] = NameElementUtil.convertCommand2CommandCreate(commands[i]);
}
return nameElementCommands;
}
/**
* Convert name element command to name element command for update.
*
* @param command name element command
* @return name element command for update
*/
public static NameElementCommandUpdate convertCommand2CommandUpdate(NameElementCommand command) {
return new NameElementCommandUpdate(
command.getUuid(),
command.getParentSystemStructure(),
command.getParentDeviceStructure(),
command.getIndex(),
command.getDescription());
}
// /**
// * Populate and return name element for name.
// *
// * @param name name
// * @param holderSystemDeviceStructure holder of containers for system and device structure content
// * @return name element
// */
// public static NameElement getNameElement(Name name, HolderSystemDeviceStructure holderSystemDeviceStructure) {
// if (name == null) {
// return null;
// }
//
// // find out how to populate return element for system structure, device structure
// // levelSystemStructure -1 ---> error
// // levelDeviceStructure -1 ---> error
//
// return new NameElement(
// name.getUuid(),
// name.getSystemgroupUuid(), name.getSystemUuid(), name.getSubsystemUuid(), name.getDevicetypeUuid(),
// getMnemonicPathSystemStructure(
// name,
// StructureUtil.getLevelSystemStructure(name),
// holderSystemDeviceStructure),
// getMnemonicPathDeviceStructure(
// name,
// StructureUtil.getLevelDeviceStructure(name),
// holderSystemDeviceStructure),
// name.getInstanceIndex(), name.getConventionName(),
// name.getDescription(), Status.APPROVED, name.isLatest(), name.isDeleted(),
// name.getRequested(), name.getRequestedBy(), name.getRequestedComment());
// }
//
// /**
// * Populate and return name element for name.
// *
// * @param name name
// * @param holderIRepositories holder of references to repositories
// * @return name element
// */
// public static NameElement getNameElement(Name name, HolderIRepositories holderIRepositories) {
// if (name == null) {
// return null;
// }
//
// // find out how to populate return element for system structure, device structure
// // levelSystemStructure -1 ---> error
// // levelDeviceStructure -1 ---> error
//
// return new NameElement(
// name.getUuid(),
// name.getSystemgroupUuid(), name.getSystemUuid(), name.getSubsystemUuid(), name.getDevicetypeUuid(),
// getMnemonicPathSystemStructure(
// name,
// StructureUtil.getLevelSystemStructure(name),
// holderIRepositories),
// getMnemonicPathDeviceStructure(
// name,
// StructureUtil.getLevelDeviceStructure(name),
// holderIRepositories),
// name.getInstanceIndex(), name.getConventionName(),
// name.getDescription(), Status.APPROVED, name.isLatest(), name.isDeleted(),
// name.getRequested(), name.getRequestedBy(), name.getRequestedComment());
// }
/**
* Convert array of name element commands to array of name element commands for update.
*
* @param commands array of name element commands
* @return array of name element commands for update
*/
public static NameElementCommandUpdate[] convertCommand2CommandUpdate(NameElementCommand[] commands) {
NameElementCommandUpdate[] nameElementCommands = new NameElementCommandUpdate[commands.length];
for (int i=0; i<commands.length; i++) {
nameElementCommands[i] = NameElementUtil.convertCommand2CommandUpdate(commands[i]);
}
return nameElementCommands;
}
/**
* Convert name element command to name element command for confirm.
*
* @param command name element command
* @return name element command for confirm
*/
public static NameElementCommandConfirm convertCommand2CommandConfirm(NameElementCommand command) {
return new NameElementCommandConfirm(
command.getUuid());
}
/**
* Convert array of name element commands to array of name element commands for confirm.
*
* @param commands array of name element commands
* @return array of name element commands for confirm
*/
public static NameElementCommandConfirm[] convertCommand2CommandConfirm(NameElementCommand[] commands) {
NameElementCommandConfirm[] nameElementCommands = new NameElementCommandConfirm[commands.length];
for (int i=0; i<commands.length; i++) {
nameElementCommands[i] = NameElementUtil.convertCommand2CommandConfirm(commands[i]);
}
return nameElementCommands;
}
// ----------------------------------------------------------------------------------------------------
/**
* Convert name element to name element command for create.
*
* @param element name element
* @return name element command for create
*/
public static NameElementCommandCreate convertElement2CommandCreate(NameElement element) {
return new NameElementCommandCreate(
element.getParentSystemStructure(),
element.getParentDeviceStructure(),
element.getIndex(),
element.getDescription());
}
/**
* Convert array of name elements to array of name element commands for create.
*
* @param elements array of name elements
* @return array of name element commands for create
*/
public static NameElementCommandCreate[] convertElement2CommandCreate(NameElement[] elements) {
NameElementCommandCreate[] nameElementCommands = new NameElementCommandCreate[elements.length];
for (int i=0; i<elements.length; i++) {
nameElementCommands[i] = convertElement2CommandCreate(elements[i]);
}
return nameElementCommands;
}
/**
* Convert name element to name element command for update.
*
* @param element name element
* @return name element command for update
*/
public static NameElementCommandUpdate convertElement2CommandUpdate(NameElement element) {
return new NameElementCommandUpdate(
element.getUuid(),
element.getParentSystemStructure(),
element.getParentDeviceStructure(),
element.getIndex(),
element.getDescription());
}
/**
* Convert array of name elements to array of name element commands for update.
*
* @param elements array of name elements
* @return array of name element commands for update
*/
public static NameElementCommandUpdate[] convertElement2CommandUpdate(NameElement[] elements) {
NameElementCommandUpdate[] nameElementCommands = new NameElementCommandUpdate[elements.length];
for (int i=0; i<elements.length; i++) {
nameElementCommands[i] = convertElement2CommandUpdate(elements[i]);
}
return nameElementCommands;
}
/**
* Convert name element to name element command for confirm.
*
* @param element name element
* @return name element command for confirm
*/
public static NameElementCommandConfirm convertElement2CommandConfirm(NameElement element) {
return new NameElementCommandConfirm(
element.getUuid());
}
/**
* Convert array of name elements to array of name element commands for confirm.
*
* @param elements array of name elements
* @return array of name element commands for confirm
*/
public static NameElementCommandConfirm[] convertElement2CommandConfirm(NameElement[] elements) {
NameElementCommandConfirm[] nameElementCommands = new NameElementCommandConfirm[elements.length];
for (int i=0; i<elements.length; i++) {
nameElementCommands[i] = convertElement2CommandConfirm(elements[i]);
}
return nameElementCommands;
}
}
/*
* Copyright (C) 2021 European Spallation Source ERIC.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.openepics.names.util;
/**
* Utility record to collect information about convention name or process variable name, in particular parts of name.
*
* @author Lars Johansson
*/
public record NameInformation (
String name,
String conventionName,
String systemGroup,
String system,
String subsystem,
String discipline,
String deviceType,
String instanceIndex,
String property,
String mnemonicPathSystemStructure,
String mnemonicPathDeviceStructure,
String instanceIndexStyle,
boolean isDisciplinePID,
boolean isMnemonicPathDeviceStructurePIDNumeric,
boolean isOffsite,
boolean isConventionName,
boolean isProcessVariableName) {}
......@@ -18,7 +18,11 @@
package org.openepics.names.util;
import org.openepics.names.repository.model.Name;
import org.apache.commons.lang3.StringUtils;
import org.openepics.names.repository.model.DeviceType;
import org.openepics.names.repository.model.Subsystem;
import org.openepics.names.repository.model.System;
import org.openepics.names.repository.model.SystemGroup;
/**
* Utility class to assist in handling of name content.
......@@ -35,179 +39,69 @@ public class NameUtil {
}
/**
* Return level of system structure for name.
* <ul>
* <li>1 <--> system group</li>
* <li>2 <--> system</li>
* <li>3 <--> subsystem</li>
* <li>-1 <--> invalid</li>
* </ul>
* Return convention name for system and device structure mnemonic paths and index.
*
* @param name name content
* @return level of system structure
* @param systemStructure system structure mnemonic path
* @param deviceStructure device structure mnemonic path
* @param index index
* @return convention name
*/
public static int getLevelSystemStructure(Name name) {
if (name == null) {
return -1;
}
public static String getName(String systemStructure, String deviceStructure, String index) {
return !StringUtils.isEmpty(systemStructure)
? !StringUtils.isEmpty(deviceStructure) && !StringUtils.isEmpty(index)
? systemStructure + NamingConventionUtil.DELIMITER_EXTRA + deviceStructure + NamingConventionUtil.DELIMITER_INTRA + index
: systemStructure
: null;
}
int count = 0;
if (name.getSystemgroupUuid() != null) {
count++;
};
if (name.getSystemUuid() != null) {
count++;
}
if (name.getSubsystemUuid() != null) {
count++;
}
if (count != 1) {
return -1;
}
// ----------------------------------------------------------------------------------------------------
return name.getSubsystemUuid() != null
? 3
: name.getSystemUuid() != null
? 2
: name.getSystemgroupUuid() != null
? 1
: -1;
/**
* Return convention name given system group, device type and index.
*
* @param systemGroup system group
* @param deviceType device type
* @param index index
* @param holderStructures container for system and device structure content
* @return convention name
*/
public static String getName(SystemGroup systemGroup, DeviceType deviceType, String index, HolderStructures holderStructures) {
return getName(
StructureUtil.getMnemonicPath(systemGroup, holderStructures),
StructureUtil.getMnemonicPath(deviceType, holderStructures),
index);
}
/**
* Return level of device structure for name.
* <ul>
* <li>3 <--> device type</li>
* <li>-1 <--> invalid</li>
* </ul>
* Return convention name given system, device type and index.
*
* @param name content
* @return level of device structure
* @param system
* @param deviceType device type
* @param index index
* @param holderStructures container for system and device structure content
* @return convention name
*/
public static int getLevelDeviceStructure(Name name) {
if (name == null) {
return -1;
}
return name.getDevicetypeUuid() != null
? 3
: -1;
public static String getName(System system, DeviceType deviceType, String index, HolderStructures holderStructures) {
return getName(
StructureUtil.getMnemonicPath(system, holderStructures),
StructureUtil.getMnemonicPath(deviceType, holderStructures),
index);
}
// /**
// * Return system structure mnemonic path for name.
// *
// * @param name name
// * @param levelSystemStructure level of system structure
// * @param holderIRepositories holder of references to repositories
// * @return system structure mnemonic path
// */
// private static String getMnemonicPathSystemStructure(Name name, int levelSystemStructure, HolderIRepositories holderIRepositories) {
// // populate return element for system structure
// switch (levelSystemStructure) {
// case 3: {
// Subsystem subsystem = holderIRepositories.getSubsystemRepository().findLatestByUuid(name.getSubsystemUuid().toString());
// System system = holderIRepositories.getSystemRepository().findLatestByUuid(subsystem.getParentUuid().toString());
//
// return system.getMnemonic() + "-" + subsystem.getMnemonic();
// }
// case 2: {
// System system = holderIRepositories.getSystemRepository().findLatestByUuid(name.getSystemUuid().toString());
//
// return system.getMnemonic();
// }
// case 1: {
// SystemGroup systemGroup = holderIRepositories.getSystemGroupRepository().findLatestByUuid(name.getSystemgroupUuid().toString());
//
// return systemGroup.getMnemonic();
// }
// default:
// // error
// return null;
// }
// }
//
// /**
// * Return device structure mnemonic path for name.
// *
// * @param name name
// * @param levelDeviceStructure level of device structure
// * @param holderIRepositories holder of references to repositories
// * @return device structure mnemonic path
// */
// private static String getMnemonicPathDeviceStructure(Name name, int levelDeviceStructure, HolderIRepositories holderIRepositories) {
// // populate return element for device structure
// switch (levelDeviceStructure) {
// case 3: {
// DeviceType deviceType = holderIRepositories.getDeviceTypeRepository().findLatestByUuid(name.getDevicetypeUuid().toString());
// DeviceGroup deviceGroup = holderIRepositories.getDeviceGroupRepository().findLatestByUuid(deviceType.getParentUuid().toString());
// Discipline discipline = holderIRepositories.getDisciplineRepository().findLatestByUuid(deviceGroup.getParentUuid().toString());
//
// return discipline.getMnemonic() + "-" + deviceType.getMnemonic();
// }
// default:
// // error
// return null;
// }
//
// }
//
// /**
// * Return system structure mnemonic path for name.
// *
// * @param name name
// * @param levelSystemStructure level of system structure
// * @param holderSystemDeviceStructure holder of containers for system and device structure content
// * @return system structure mnemonic path
// */
// private static String getMnemonicPathSystemStructure(Name name, int levelSystemStructure, HolderSystemDeviceStructure holderSystemDeviceStructure) {
// // populate return element for system structure
// switch (levelSystemStructure) {
// case 3: {
// Subsystem subsystem = holderSystemDeviceStructure.findSubsystemByUuid(name.getSubsystemUuid());
// System system = holderSystemDeviceStructure.findSystemByUuid(subsystem.getParentUuid());
//
// return system.getMnemonic() + "-" + subsystem.getMnemonic();
// }
// case 2: {
// System system = holderSystemDeviceStructure.findSystemByUuid(name.getSystemUuid());
//
// return system.getMnemonic();
// }
// case 1: {
// SystemGroup systemGroup = holderSystemDeviceStructure.findSystemGroupByUuid(name.getSystemgroupUuid());
//
// return systemGroup.getMnemonic();
// }
// default:
// // error
// return null;
// }
// }
//
// /**
// * Return device structure mnemonic path for name.
// *
// * @param name name
// * @param levelDeviceStructure level of device structure
// * @param holderSystemDeviceStructure holder of containers for system and device structure content
// * @return device structure mnemonic path
// */
// private static String getMnemonicPathDeviceStructure(Name name, int levelDeviceStructure, HolderSystemDeviceStructure holderSystemDeviceStructure) {
// // populate return element for device structure
// switch (levelDeviceStructure) {
// case 3: {
// DeviceType deviceType = holderSystemDeviceStructure.findDeviceTypeByUuid(name.getDevicetypeUuid());
// DeviceGroup deviceGroup = holderSystemDeviceStructure.findDeviceGroupByUuid(deviceType.getParentUuid());
// Discipline discipline = holderSystemDeviceStructure.findDisciplineByUuid(deviceGroup.getParentUuid());
//
// return discipline.getMnemonic() + "-" + deviceType.getMnemonic();
// }
// default:
// // error
// return null;
// }
//
// }
/**
* Return convention name given subsystem, device type and index.
*
* @param subsystem
* @param deviceType device type
* @param index index
* @param holderStructures container for system and device structure content
* @return convention name
*/
public static String getName(Subsystem subsystem, DeviceType deviceType, String index, HolderStructures holderStructures) {
return getName(
StructureUtil.getMnemonicPath(subsystem, holderStructures),
StructureUtil.getMnemonicPath(deviceType, holderStructures),
index);
}
}
......@@ -35,20 +35,31 @@ import org.openepics.names.rest.beans.Type;
* <p>
* A device name consists of elements having general structure
* <ul>
* <li> <pre>Sys-Sub:Dis-Dev-Idx</pre>
* <li> <pre>Sup-Sys-Sub:Dis-Dev-Idx</pre>
* <li> System structure
* <ul>
* <li> Sg
* <li> Sys
* <li> Sys-Sub
* </ul>
* <li> System structure + Device structure + Index
* <ul>
* <li> Sg:Dis-Dev-Idx
* <li> Sys:Dis-Dev-Idx
* <li> Sys-Sub:Dis-Dev-Idx
* </ul>
* </ul>
* It consists of of <br/><br/>
* It consists of<br/><br/>
* <ul>
* <li> System structure
* <ul>
* <li> System group (Sup)(optional)
* <li> System (Sys)
* <li> Subsystem (Sub)
* <li> System group (Sg)(optional)
* <li> System (Sys)
* <li> Subsystem (Sub)
* </ul>
* <li> Device structure
* <ul>
* <li> Discipline (Dis)
* <li> Discipline (Dis)
* <li> Device group
* <li> Device type (Dev)
* </ul>
* <li> Device
......@@ -104,10 +115,8 @@ import org.openepics.names.rest.beans.Type;
* @author Karin Rathsman
* @author Lars Johansson
*
* @see <a href="https://confluence.esss.lu.se/display/NC/ESS+Naming+Convention"/>
* https://confluence.esss.lu.se/display/NC/ESS+Naming+Convention</a>
* @see <a href="https://chess.esss.lu.se/enovia/tvc-action/showObject/dmg_TechnicalSpecification/ESS-0000757/valid">
* https://chess.esss.lu.se/enovia/tvc-action/showObject/dmg_TechnicalSpecification/ESS-0000757/valid</a>
* @see <a href="https://chess.esss.lu.se/enovia/link/ESS-0000757/21308.51166.45568.45993/valid">
* https://chess.esss.lu.se/enovia/link/ESS-0000757/21308.51166.45568.45993/valid</a>
*
* @see NamingConventionUtil
*/
......
......@@ -19,20 +19,30 @@
package org.openepics.names.util;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.List;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.openepics.names.repository.model.Discipline;
/**
* Utility class to provide split of device name in naming convention into name parts
* for system structure and device structure.
* for system structure, device structure, instance index and process variable.
*
* <p>
* Note delimiter characters, in and between, system structure and device structure.
* Note delimiter characters, in and between, system structure and device structure and process variable.
* <ul>
* <li>-
* <li>:
* <li> -
* <li> :
* </ul>
* </p>
*
* <p>
* Performance is important!
* <br/>
* <ul>
* <li> indexOf somewhat faster than split
* <li> not noticeable unless tens of thousands of calls made in short time
* </ul>
*
* @author Lars Johansson
......@@ -43,51 +53,68 @@ public class NamingConventionUtil {
// Note
//
// ================================================================================
// This class handles system structure and device structure of name convention
// ================================================================================
// ====================================================================================================
// This class handles names in naming convention, which are convention name and process variable name.
// This class is to be able to handle past and present names.
// ====================================================================================================
// ESS Naming Convention
// system structure:device structure:process variable
// convention name = system structure
// = system structure:device structure-instance index
// ------------------------------------------------------------
// system structure part of convention name
// device structure may be part of convention name
// instance index may be part of convention name
// ------------------------------------------------------------
// system structure need to be part of name
// device structure need not to be part of name
// process variable not to be part of name
// property not part of convention name (!)
// pv name = name:property
// ------------------------------------------------------------
// system structure
// system group
// system
// subsystem
// system group Syg
// system Sys
// subsystem Sub
// device structure
// discipline
// device type
// instance index (name)
// discipline Dis
// device group
// device type Dev
// instance index Idx
// property Prop
// ------------------------------------------------------------
// system group optional
// device group not part of name
// instance index optional
// ====================================================================================================
// Kind of names handled - naming convention
// ------------------------------------------------------------
// (1) able to handle
// ------------------------------------------------------------
// Syg
// Sys
// Sys-Sub
// Syg:Dis-Dev-Idx
// Sys:Dis-Dev-Idx
// Sys-Sub:Dis-Dev-Idx
// ------------------------------------------------------------
// (2) able to handle - old naming / naming convention - such names may exist
// ------------------------------------------------------------
// Sys-Sys:Dis-Dev
// Syg-Sys-Sys:Dis-Dev
// Syg-Sys-Sys:Dis-Dev-Idx
// ------------------------------------------------------------
// system group is optional
// instance index is optional
// ================================================================================
// Kind of names handled
// CONVENTIONNAME_010
// CONVENTIONNAME_011
// CONVENTIONNAME_010_111
// CONVENTIONNAME_011_110
// CONVENTIONNAME_011_111
// CONVENTIONNAME_111_110
// CONVENTIONNAME_111_111
// (3) able to handle property with (1) and (2)
// ------------------------------------------------------------
// system
// system-subsystem
// system:discipline-deviceType-instanceIndex
// system-subsystem:discipline-deviceType
// system-subsystem:discipline-deviceType-instanceIndex
// systemGroup-system-subsystem:discipline-deviceType
// systemGroup-system-subsystem:discipline-deviceType-instanceIndex
// ================================================================================
// ====================================================================================================
// delimiters
// :
// -
// ================================================================================
// This class to be able to handle past and present names
// ================================================================================
// ------------------------------------------------------------
// 1 or 2 occurrence of : expected
// 1 convention name
// 2 pv name
// ====================================================================================================
// delimiter
public static final String DELIMITER_EXTRA = ":";
public static final String DELIMITER_INTRA = "-";
// p&id - pipeline & instrumentation diagram
public static final String DISCIPLINE_P_ID = "P&ID";
......@@ -96,8 +123,10 @@ public class NamingConventionUtil {
private static final String[] DISCIPLINES_P_ID = {"Cryo", "EMR", "HVAC", "Proc", "SC", "Vac", "WtrC"};
private static final String[] MNEMONIC_PATH_P_ID_NUMERIC = {"SC-IOC"};
private static final String DELIMITER_EXTRA = ":";
private static final String DELIMITER_INTRA = "-";
private static final String EMPTY = "";
private static final String[] EMPTY_ARRAY = new String[] {};
private static final String PV_NAME_VALIDATION_PROPERTY_CHARACTERS_NOT_ALLOWED = "!@$%^&*()+={}[]|\\:;'\"<>,.?/~`";
/**
* This class is not to be instantiated.
......@@ -125,22 +154,174 @@ public class NamingConventionUtil {
}
/**
* Extract system group from ESS convention name or <tt>null</tt> if it can not be extracted.
* Extract information about name.
*
* @param name convention name or process variable name
* @return name information record
*/
public static NameInformation extractNameInformation(String name) {
return new NameInformation(
name,
extractConventionName(name),
extractSystemGroup(name),
extractSystem(name),
extractSubsystem(name),
extractDiscipline(name),
extractDeviceType(name),
extractInstanceIndex(name),
extractProperty(name),
extractMnemonicPathSystemStructure(name),
extractMnemonicPathDeviceStructure(name),
getInstanceIndexStyle(name),
isDisciplinePID(extractDiscipline(name)),
isMnemonicPathDeviceStructurePIDNumeric(extractMnemonicPathDeviceStructure(name)),
isOffsite(name),
isConventionName(name),
isProcessVariableName(name)
);
}
/**
* Return information about process variable name, in particular about validation.
*
* @param name convention name or process variable name
* @return process variable name information
*/
public static ProcessVariableNameInformation extractProcessVariableNameInformation(String name) {
// rules
// name
// not empty
// process variable name
// property not empty
// name length
// > 60
// property min length
// > 0
// < 4
// property max length
// > 25
// > 20
// property characters
// PV_CHARACTERS_NOT_ALLOWED
// #
// digit
// upper case
//
// note
// focus is on property of process variable name - NOT on convention name (!)
// separate checks for property for length and illegal characters
// may return multiple messages
// only one message about property length
// potentially valid if one message only and about internal process variable property
List<String> messages = Lists.newArrayList();
if (nullIfEmpty(name) == null) {
messages.add(TextUtil.PV_NAME_VALIDATION_NAME_IS_EMPTY);
} else if (!isProcessVariableName(name)) {
messages.add(TextUtil.PV_NAME_VALIDATION_PROPERTY_IS_EMPTY);
} else {
if (name.length() > 60) {
messages.add(TextUtil.PV_NAME_VALIDATION_NAME_CONTAINS_MORE_THAN_60_CHARACTERS);
}
String property = extractProperty(name);
boolean hasLengthMessage = false;
int length = property.length();
if (!hasLengthMessage && length > 25) {
messages.add(TextUtil.PV_NAME_VALIDATION_PROPERTY_CONTAINS_MORE_THAN_25_CHARACTERS);
hasLengthMessage = true;
}
if (!hasLengthMessage && length > 20) {
if (!((property.endsWith("-R") || property.endsWith("-S")) && property.length() <= 22)
&& !(property.endsWith("-RB") && length <= 23)) {
messages.add(TextUtil.PV_NAME_VALIDATION_PROPERTY_CONTAINS_MORE_THAN_20_CHARACTERS);
hasLengthMessage = true;
}
}
if (!hasLengthMessage && length > 1 && length < 4 && !"Pwr".equals(property) ) {
messages.add(TextUtil.PV_NAME_VALIDATION_PROPERTY_CONTAINS_LESS_THAN_4_CHARACTERS);
hasLengthMessage = true;
}
for (int i=0; i<PV_NAME_VALIDATION_PROPERTY_CHARACTERS_NOT_ALLOWED.length(); i++) {
if (property.contains(PV_NAME_VALIDATION_PROPERTY_CHARACTERS_NOT_ALLOWED.substring(i, i+1) )) {
messages.add(TextUtil.PV_NAME_VALIDATION_PROPERTY_CONTAINS_CHARACTER_THAT_IS_NOT_ALLOWED);
break;
}
}
if (property.contains("#")) {
if (property.startsWith("#")) {
messages.add(TextUtil.PV_NAME_VALIDATION_PROPERTY_IS_INTERNAL);
} else {
messages.add(TextUtil.PV_NAME_VALIDATION_PROPERTY_CONTAINS_CHARACTER_IN_A_POSITION_THAT_IS_NOT_ALLOWED);
}
}
if (Character.isDigit(property.charAt(0))
|| property.startsWith("_")
|| property.startsWith("-")) {
messages.add(TextUtil.PV_NAME_VALIDATION_PROPERTY_DOES_NOT_START_WITH_WITH_A_LETTER);
}
if (Character.isLowerCase(property.charAt(0))) {
messages.add(TextUtil.PV_NAME_VALIDATION_PROPERTY_DOES_NOT_START_WITH_WITH_AN_UPPER_CASE_LETTER);
}
}
boolean isValidFormat = messages.isEmpty();
return new ProcessVariableNameInformation(name, isValidFormat, !messages.isEmpty() ? String.join(" ", messages) : null);
}
/**
* Extract convention name from given name.
*
* @param name convention name or process variable name
* @return convention name
*/
public static String extractConventionName(String name) {
if (!StringUtils.isEmpty(name)) {
// consider convention name
// focus on extract convention name
// not check if convention name is correct
String[] s1 = name.split(DELIMITER_EXTRA);
if (s1.length == 1 || s1.length == 2) {
String value = name;
if (value.endsWith(DELIMITER_EXTRA)) {
value = value.substring(0, value.length()-1);
}
return nullIfEmpty(value);
} else if (s1.length == 3) {
String value = StringUtils.reverse(name);
int index = value.indexOf(DELIMITER_EXTRA);
if (index != -1) {
value = StringUtils.reverse(value.substring(index + 1));
if (value.endsWith(DELIMITER_EXTRA)) {
value = value.substring(0, value.length()-1);
}
return nullIfEmpty(value);
}
}
}
return null;
}
/**
* Extract system group from ESS name or <tt>null</tt> if it can not be extracted.
*
* @param conventionName ESS convention name
* @param name convention name or process variable name
* @return system group
*/
public static String extractSystemGroup(String conventionName) {
if (!StringUtils.isEmpty(conventionName)) {
public static String extractSystemGroup(String name) {
if (!StringUtils.isEmpty(name)) {
// consider name
// system structure
// before first occurrence of DELIMITER_EXTRA
StringTokenizer st1 = new StringTokenizer(conventionName, DELIMITER_EXTRA, false);
if (st1.countTokens() == 1 || st1.countTokens() == 2 || st1.countTokens() == 3) {
StringTokenizer st2 = new StringTokenizer(st1.nextToken(), DELIMITER_INTRA, false);
if (st2.countTokens() == 3) {
return st2.nextToken();
String[] s1 = name.split(DELIMITER_EXTRA);
if (s1.length == 1 || s1.length == 2 || s1.length == 3) {
String[] s2 = s1[0].split(DELIMITER_INTRA);
if (s2.length == 3) {
return s2[0];
}
}
}
......@@ -148,25 +329,24 @@ public class NamingConventionUtil {
}
/**
* Extract system from ESS convention name or <tt>null</tt> if it can not be extracted.
* Extract system from ESS name or <tt>null</tt> if it can not be extracted.
*
* @param conventionName ESS convention name
* @param name convention name or process variable name
* @return system
*/
public static String extractSystem(String conventionName) {
if (!StringUtils.isEmpty(conventionName)) {
public static String extractSystem(String name) {
if (!StringUtils.isEmpty(name)) {
// consider name
// system structure
// before first occurrence of DELIMITER_EXTRA
StringTokenizer st1 = new StringTokenizer(conventionName, DELIMITER_EXTRA, false);
if (st1.countTokens() == 1 || st1.countTokens() == 2 || st1.countTokens() == 3) {
StringTokenizer st2 = new StringTokenizer(st1.nextToken(), DELIMITER_INTRA, false);
if (st2.countTokens() == 3) {
st2.nextToken();
return st2.nextToken();
} else if (st2.countTokens() == 2 || st2.countTokens() == 1) {
return st2.nextToken();
String[] s1 = name.split(DELIMITER_EXTRA);
if (s1.length == 1 || s1.length == 2 || s1.length == 3) {
String[] s2 = s1[0].split(DELIMITER_INTRA);
if (s2.length == 3) {
return s2[1];
} else if (s2.length == 2 || s2.length == 1) {
return nullIfEmpty(s2[0]);
}
}
}
......@@ -174,27 +354,24 @@ public class NamingConventionUtil {
}
/**
* Extract subsystem from ESS convention name or <tt>null</tt> if it can not be extracted.
* Extract subsystem from ESS name or <tt>null</tt> if it can not be extracted.
*
* @param conventionName ESS convention name
* @param name convention name or process variable name
* @return subsystem
*/
public static String extractSubsystem(String conventionName) {
if (!StringUtils.isEmpty(conventionName)) {
public static String extractSubsystem(String name) {
if (!StringUtils.isEmpty(name)) {
// consider name
// system structure
// before first occurrence of DELIMITER_EXTRA
StringTokenizer st1 = new StringTokenizer(conventionName, DELIMITER_EXTRA, false);
if (st1.countTokens() == 1 || st1.countTokens() == 2 || st1.countTokens() == 3) {
StringTokenizer st2 = new StringTokenizer(st1.nextToken(), DELIMITER_INTRA, false);
if (st2.countTokens() == 3) {
st2.nextToken();
st2.nextToken();
return st2.nextToken();
} else if (st2.countTokens() == 2) {
st2.nextToken();
return st2.nextToken();
String[] s1 = name.split(DELIMITER_EXTRA);
if (s1.length == 1 || s1.length == 2 || s1.length == 3) {
String[] s2 = s1[0].split(DELIMITER_INTRA);
if (s2.length == 3) {
return s2[2];
} else if (s2.length == 2) {
return s2[1];
}
}
}
......@@ -202,24 +379,23 @@ public class NamingConventionUtil {
}
/**
* Extract discipline from ESS convention name or <tt>null</tt> if it can not be extracted.
* Extract discipline from ESS name or <tt>null</tt> if it can not be extracted.
*
* @param conventionName ESS convention name
* @param name convention name or process variable name
* @return discipline
*/
public static String extractDiscipline(String conventionName) {
if (!StringUtils.isEmpty(conventionName)) {
public static String extractDiscipline(String name) {
if (!StringUtils.isEmpty(name)) {
// consider name
// device structure
// after first occurrence of DELIMITER_EXTRA
// before possible second occurrence of DELIMITER_EXTRA
StringTokenizer st1 = new StringTokenizer(conventionName, DELIMITER_EXTRA, false);
if (st1.countTokens() == 2 || st1.countTokens() == 3) {
st1.nextToken();
StringTokenizer st2 = new StringTokenizer(st1.nextToken(), DELIMITER_INTRA, false);
if (st2.countTokens() == 3 || st2.countTokens() == 2) {
return st2.nextToken();
String[] s1 = name.split(DELIMITER_EXTRA);
if (s1.length == 2 || s1.length == 3) {
String[] s2 = s1[1].split(DELIMITER_INTRA);
if (s2.length == 3 || s2.length == 2) {
return nullIfEmpty(s2[0]);
}
}
}
......@@ -227,25 +403,23 @@ public class NamingConventionUtil {
}
/**
* Extract device type from ESS convention name or <tt>null</tt> if it can not be extracted.
* Extract device type from ESS name or <tt>null</tt> if it can not be extracted.
*
* @param conventionName ESS convention name
* @param name convention name or process variable name
* @return device type
*/
public static String extractDeviceType(String conventionName) {
if (!StringUtils.isEmpty(conventionName)) {
public static String extractDeviceType(String name) {
if (!StringUtils.isEmpty(name)) {
// consider name
// device structure
// after first occurrence of DELIMITER_EXTRA
// before possible second occurrence of DELIMITER_EXTRA
StringTokenizer st1 = new StringTokenizer(conventionName, DELIMITER_EXTRA, false);
if (st1.countTokens() == 2 || st1.countTokens() == 3) {
st1.nextToken();
StringTokenizer st2 = new StringTokenizer(st1.nextToken(), DELIMITER_INTRA, false);
if (st2.countTokens() == 3 || st2.countTokens() == 2) {
st2.nextToken();
return st2.nextToken();
String[] s1 = name.split(DELIMITER_EXTRA);
if (s1.length == 2 || s1.length == 3) {
String[] s2 = s1[1].split(DELIMITER_INTRA);
if (s2.length == 3 || s2.length == 2) {
return s2[1];
}
}
}
......@@ -253,26 +427,23 @@ public class NamingConventionUtil {
}
/**
* Extract instance index from ESS convention name or <tt>null</tt> if it can not be extracted.
* Extract instance index from ESS name or <tt>null</tt> if it can not be extracted.
*
* @param conventionName ESS convention name
* @param name convention name or process variable name
* @return instance index
*/
public static String extractInstanceIndex(String conventionName) {
if (!StringUtils.isEmpty(conventionName)) {
public static String extractInstanceIndex(String name) {
if (!StringUtils.isEmpty(name)) {
// consider name
// device structure
// after first occurrence of DELIMITER_EXTRA
// before possible second occurrence of DELIMITER_EXTRA
StringTokenizer st1 = new StringTokenizer(conventionName, DELIMITER_EXTRA, false);
if (st1.countTokens() == 2 || st1.countTokens() == 3) {
st1.nextToken();
StringTokenizer st2 = new StringTokenizer(st1.nextToken(), DELIMITER_INTRA, false);
if (st2.countTokens() == 3) {
st2.nextToken();
st2.nextToken();
return st2.nextToken();
String[] s1 = name.split(DELIMITER_EXTRA);
if (s1.length == 2 || s1.length == 3) {
String[] s2 = s1[1].split(DELIMITER_INTRA);
if (s2.length == 3) {
return s2[2];
}
}
}
......@@ -280,43 +451,69 @@ public class NamingConventionUtil {
}
/**
* Extract mnemonic path for system structure from ESS convention name.
* Extract property from ESS name or <tt>null</tt> if it can not be extracted.
*
* @param conventionName ESS convention name
* @return mnemonic path for system structure
* @param name convention name or process variable name
* @return property
*/
public static String extractMnemonicPathSystemStructure(String conventionName) {
if (!StringUtils.isEmpty(conventionName)) {
int index = conventionName.indexOf(DELIMITER_EXTRA);
if (index != -1) {
return conventionName.substring(0, index);
} else {
return conventionName;
public static String extractProperty(String name) {
if (!StringUtils.isEmpty(name)) {
// consider name
// after second occurrence of DELIMITER_EXTRA
String[] s1 = name.split(DELIMITER_EXTRA);
if (s1.length == 3) {
return s1[2];
}
}
return null;
}
/**
* Extract mnemonic path for device structure from ESS convention name.
* Extract mnemonic path for system structure from ESS name.
*
* @param name convention name or process variable name
* @return mnemonic path for system structure
*/
public static String extractMnemonicPathSystemStructure(String name) {
// see documentation at top of class to learn about kind of names
// (according to current and old naming convention)
// that are to be handled
//
// performance is important!
if (!StringUtils.isEmpty(name)) {
String[] s1 = name.split(DELIMITER_EXTRA);
return s1.length > 0
? nullIfEmpty(s1[0])
: null;
}
return null;
}
/**
* Extract mnemonic path for device structure from ESS name.
* Instance index is not part of mnemonic path for device structure.
*
* @param conventionName ESS convention name
* @param name convention name or process variable name
* @return mnemonic path for device structure
*/
public static String extractMnemonicPathDeviceStructure(String conventionName) {
if (!StringUtils.isEmpty(conventionName)) {
int index = conventionName.indexOf(DELIMITER_EXTRA);
if (index != -1) {
String discipline = extractDiscipline(conventionName);
String deviceType = extractDeviceType(conventionName);
if (!StringUtils.isEmpty(discipline) && !StringUtils.isEmpty(deviceType)) {
return discipline + DELIMITER_INTRA + deviceType;
} else {
return null;
public static String extractMnemonicPathDeviceStructure(String name) {
// see documentation at top of class to learn about kind of names
// (according to current and old naming convention)
// that are to be handled
//
// performance is important!
if (!StringUtils.isEmpty(name)) {
String[] s1 = name.split(DELIMITER_EXTRA);
if (s1.length > 1) {
String[] s2 = s1[1].split(DELIMITER_INTRA);
if ((s2.length == 3 || s2.length == 2)
&& nullIfEmpty(s2[0]) != null
&& nullIfEmpty(s2[1]) != null) {
return s2[0] + DELIMITER_INTRA + s2[1];
}
} else {
return null;
}
}
return null;
......@@ -325,14 +522,14 @@ public class NamingConventionUtil {
/**
* Return instance index style.
*
* @param conventionName convention name
* @param name convention name or process variable name
* @return instance index style
*/
public static String getInstanceIndexStyle(String conventionName) {
public static String getInstanceIndexStyle(String name) {
String indexStyle = null;
String mnemonicPathDeviceStructure = extractMnemonicPathDeviceStructure(conventionName);
String mnemonicPathDeviceStructure = extractMnemonicPathDeviceStructure(name);
if (!StringUtils.isEmpty(mnemonicPathDeviceStructure)) {
String discipline = extractDiscipline(conventionName);
String discipline = extractDiscipline(name);
indexStyle = DISCIPLINE_SCIENTIFIC;
for (String str : getDisciplinesPID()) {
if (StringUtils.equals(str, discipline)) {
......@@ -399,15 +596,35 @@ public class NamingConventionUtil {
}
/**
* Return if convention name is considered OFFSITE.
* Return if ESS name is considered OFFSITE.
*
* @param name convention name or process variable name
* @return if name is considered OFFSITE
*/
public static boolean isOffsite(String name) {
return !StringUtils.isEmpty(extractSystemGroup(name))
&& !StringUtils.isEmpty(extractSystem(name))
&& !StringUtils.isEmpty(extractSubsystem(name));
}
/**
* Return if name is considered convention name.
*
* @param conventionName ESS convention name
* @return if convention name is considered OFFSITE
* @param name convention name or process variable name
* @return
*/
public static boolean isOffsite(String conventionName) {
return !StringUtils.isEmpty(extractSystemGroup(conventionName))
&& !StringUtils.isEmpty(extractSystem(conventionName))
&& !StringUtils.isEmpty(extractSubsystem(conventionName));
public static boolean isConventionName(String name) {
return extractConventionName(name) != null && extractProperty(name) == null;
}
/**
* Return if name is considered process variable name.
*
* @param name convention name or process variable name
* @return
*/
public static boolean isProcessVariableName(String name) {
return extractConventionName(name) != null && extractProperty(name) != null;
}
/**
......@@ -437,7 +654,7 @@ public class NamingConventionUtil {
if (name != null) {
return StringUtils.split(name, DELIMITER_INTRA);
}
return null;
return EMPTY_ARRAY;
}
/**
......@@ -458,4 +675,14 @@ public class NamingConventionUtil {
return mnemonicPathSystemStructure;
}
/**
* Return null for string that is null or empty, otherwise string itself.
*
* @param str string
* @return null for string that is null or empty, otherwise string itself
*/
private static String nullIfEmpty(String str) {
return EMPTY.equals(str) ? null : str;
}
}
/*
* Copyright (C) 2024 European Spallation Source ERIC.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.openepics.names.util;
/**
* Utility record to collect validation information about process variable name.
*
* @author Lars Johansson
*/
public record ProcessVariableNameInformation (
String name,
boolean isValidFormat,
String message) {}
/*
* Copyright (C) 2022 European Spallation Source ERIC.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.openepics.names.util;
import org.apache.commons.lang3.StringUtils;
/**
* Utility class to assist in handling of patterns for queries.
*
* @author Lars Johansson
*/
public class RepositoryUtil {
private static final String PERCENT = "%";
/**
* This class is not to be instantiated.
*/
private RepositoryUtil() {
throw new IllegalStateException("Utility class");
}
/**
* Prepare pattern for use in where clause (predicate).
* Purpose to remove excess characters and similar work.
*
* @param value value
* @return prepared pattern
*/
public static String preparePattern(String value) {
// jpa query characters % and _
// remove excess % characters
String queryValue = value;
if (!StringUtils.isEmpty(queryValue)) {
if (queryValue.startsWith(PERCENT)) {
while (queryValue.startsWith(PERCENT)) {
queryValue = queryValue.substring(1);
}
queryValue = PERCENT + queryValue;
}
if (queryValue.endsWith(PERCENT)) {
while (queryValue.endsWith(PERCENT)) {
queryValue = queryValue.substring(0, queryValue.length()-1);
}
queryValue = queryValue + PERCENT;
}
}
return queryValue;
}
}
/*
* Copyright (C) 2022 European Spallation Source ERIC.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.openepics.names.util;
/**
* Kind of structure choice. Used in how to handle structure entries, in particular for history of structure entries.
*
* @author Lars Johansson
*/
public enum StructureChoice {
HISTORY, STRUCTURE;
}
/*
* Copyright (C) 2022 European Spallation Source ERIC.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.openepics.names.util;
/**
* Kind of structure command and operation (server-side).
*
* @author Lars Johansson
*/
public enum StructureCommand {
CREATE, UPDATE, DELETE;
}
......@@ -22,18 +22,20 @@ import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import org.openepics.names.repository.model.AuditStructure;
import org.openepics.names.repository.model.DeviceGroup;
import org.openepics.names.repository.model.DeviceType;
import org.openepics.names.repository.model.Discipline;
import org.openepics.names.repository.model.NameStructure;
import org.openepics.names.repository.model.Structure;
import org.openepics.names.repository.model.Subsystem;
import org.openepics.names.repository.model.System;
import org.openepics.names.repository.model.SystemGroup;
import org.openepics.names.rest.beans.Status;
import org.openepics.names.rest.beans.StructureElement;
import org.openepics.names.rest.beans.Type;
import org.openepics.names.rest.beans.element.StructureElement;
import org.openepics.names.rest.beans.element.StructureElementCommand;
import org.openepics.names.rest.beans.element.StructureElementCommandConfirm;
import org.openepics.names.rest.beans.element.StructureElementCommandCreate;
import org.openepics.names.rest.beans.element.StructureElementCommandUpdate;
import com.google.common.collect.Lists;
......@@ -44,9 +46,9 @@ import com.google.common.collect.Lists;
*/
public class StructureElementUtil {
public static enum StructureChoice {HISTORY, STRUCTURE};
private static final long THOUSAND_MILLISECONDS = 1000;
// note
// processed attributes for structures are used, not requested attributes
// requested attributes also used prior to removal of use of status attribute
/**
* This class is not to be instantiated.
......@@ -55,41 +57,39 @@ public class StructureElementUtil {
throw new IllegalStateException("Utility class");
}
/**
* Populate and return list of structure elements for audit structures.
*
* @param auditStructures audit structures
* @param holderStructures holder of system and device structure content
* @param structureChoice whether to consider content from structure perspective or history perspective.
* Structure perspective will give mnemonic path.
* History perspective may give empty mnemonic path as non-trivial to find out for history.
* If choice not given then default as structure perspective (processed).
* @return list of structure elements
*/
public static List<StructureElement> getStructureElementsForAuditStructures(List<AuditStructure> auditStructures, HolderStructures holderStructures, StructureChoice structureChoice) {
List<StructureElement> structureElements = Lists.newArrayList();
for (AuditStructure auditStructure : auditStructures) {
structureElements.add(getStructureElementProcessed(auditStructure, holderStructures, structureChoice));
}
return structureElements;
}
/**
* Populate and return list of structure elements for system groups.
*
* @param systemGroups system groups
* @param holderSystemDeviceStructure holder of containers for system and device structure content
* @param holderStructures holder of system and device structure content
* @param structureChoice whether to consider content from structure perspective or history perspective.
* Structure perspective gives one StructureElement object (processed).
* History perspective gives two StructureElement objects (processed, requested).
* Structure perspective will give mnemonic path.
* History perspective may give empty mnemonic path as non-trivial to find out for history.
* If choice not given then default as structure perspective (processed).
* @return list of structure elements
*/
public static List<StructureElement> getStructureElementsForSystemGroups(List<SystemGroup> systemGroups, HolderSystemDeviceStructure holderSystemDeviceStructure, StructureChoice structureChoice) {
public static List<StructureElement> getStructureElementsForSystemGroups(List<SystemGroup> systemGroups, HolderStructures holderStructures, StructureChoice structureChoice) {
List<StructureElement> structureElements = Lists.newArrayList();
for (SystemGroup systemGroup : systemGroups) {
// one or two return elements
// processed != null and processed != requested (> 1s difference) --> two entries (processed, requested)
// processed != null and processed == requested (<= 1s difference) --> one entry (processed initial)
// processed == null --> one entry (requested)
if (StructureChoice.HISTORY.equals(structureChoice)) {
if (systemGroup.getProcessed() != null && ((systemGroup.getProcessed().getTime() - systemGroup.getRequested().getTime()) > THOUSAND_MILLISECONDS)) {
structureElements.add(getStructureElementProcessed(systemGroup, holderSystemDeviceStructure));
structureElements.add(getStructureElementRequested(systemGroup, holderSystemDeviceStructure));
} else if (systemGroup.getProcessed() != null && ((systemGroup.getProcessed().getTime() - systemGroup.getRequested().getTime()) <= THOUSAND_MILLISECONDS)) {
structureElements.add(getStructureElementProcessed(systemGroup, holderSystemDeviceStructure));
} else {
structureElements.add(getStructureElementRequested(systemGroup, holderSystemDeviceStructure));
}
} else {
if (Status.PENDING.equals(systemGroup.getStatus())) {
structureElements.add(getStructureElementRequested(systemGroup, holderSystemDeviceStructure));
} else {
structureElements.add(getStructureElementProcessed(systemGroup, holderSystemDeviceStructure));
}
}
structureElements.add(getStructureElementProcessed(systemGroup, holderStructures, structureChoice));
}
return structureElements;
}
......@@ -97,33 +97,17 @@ public class StructureElementUtil {
* Populate and return list of structure elements for systems.
*
* @param systems systems
* @param holderSystemDeviceStructure holder of containers for system and device structure content
* @param holderStructures holder of system and device structure content
* @param structureChoice whether to consider content from structure perspective or history perspective.
* Structure perspective will give mnemonic path.
* History perspective may give empty mnemonic path as non-trivial to find out for history.
* If choice not given then default as structure perspective (processed).
* @return list of structure elements
*/
public static List<StructureElement> getStructureElementsForSystems(List<System> systems, HolderSystemDeviceStructure holderSystemDeviceStructure, StructureChoice structureChoice) {
public static List<StructureElement> getStructureElementsForSystems(List<System> systems, HolderStructures holderStructures, StructureChoice structureChoice) {
List<StructureElement> structureElements = Lists.newArrayList();
for (System system : systems) {
// one or two return elements
// processed != null and processed != requested (> 1s difference) --> two entries (processed, requested)
// processed != null and processed == requested (<= 1s difference) --> one entry (processed initial)
// processed == null --> one entry (requested)
if (StructureChoice.HISTORY.equals(structureChoice)) {
if (system.getProcessed() != null && ((system.getProcessed().getTime() - system.getRequested().getTime()) > THOUSAND_MILLISECONDS)) {
structureElements.add(getStructureElementProcessed(system, holderSystemDeviceStructure));
structureElements.add(getStructureElementRequested(system, holderSystemDeviceStructure));
} else if (system.getProcessed() != null && ((system.getProcessed().getTime() - system.getRequested().getTime()) <= THOUSAND_MILLISECONDS)) {
structureElements.add(getStructureElementProcessed(system, holderSystemDeviceStructure));
} else {
structureElements.add(getStructureElementRequested(system, holderSystemDeviceStructure));
}
} else {
if (Status.PENDING.equals(system.getStatus())) {
structureElements.add(getStructureElementRequested(system, holderSystemDeviceStructure));
} else {
structureElements.add(getStructureElementProcessed(system, holderSystemDeviceStructure));
}
}
structureElements.add(getStructureElementProcessed(system, holderStructures, structureChoice));
}
return structureElements;
}
......@@ -131,33 +115,17 @@ public class StructureElementUtil {
* Populate and return list of structure elements for subsystems.
*
* @param subsystems subsystems
* @param holderSystemDeviceStructure holder of containers for system and device structure content
* @param holderStructures holder of system and device structure content
* @param structureChoice whether to consider content from structure perspective or history perspective.
* Structure perspective will give mnemonic path.
* History perspective may give empty mnemonic path as non-trivial to find out for history.
* If choice not given then default as structure perspective (processed).
* @return list of structure elements
*/
public static List<StructureElement> getStructureElementsForSubsystems(List<Subsystem> subsystems, HolderSystemDeviceStructure holderSystemDeviceStructure, StructureChoice structureChoice) {
public static List<StructureElement> getStructureElementsForSubsystems(List<Subsystem> subsystems, HolderStructures holderStructures, StructureChoice structureChoice) {
List<StructureElement> structureElements = Lists.newArrayList();
for (Subsystem subsystem : subsystems) {
// one or two return elements
// processed != null and processed != requested (> 1s difference) --> two entries (processed, requested)
// processed != null and processed == requested (<= 1s difference) --> one entry (processed initial)
// processed == null --> one entry (requested)
if (StructureChoice.HISTORY.equals(structureChoice)) {
if (subsystem.getProcessed() != null && ((subsystem.getProcessed().getTime() - subsystem.getRequested().getTime()) > THOUSAND_MILLISECONDS)) {
structureElements.add(getStructureElementProcessed(subsystem, holderSystemDeviceStructure));
structureElements.add(getStructureElementRequested(subsystem, holderSystemDeviceStructure));
} else if (subsystem.getProcessed() != null && ((subsystem.getProcessed().getTime() - subsystem.getRequested().getTime()) <= THOUSAND_MILLISECONDS)) {
structureElements.add(getStructureElementProcessed(subsystem, holderSystemDeviceStructure));
} else {
structureElements.add(getStructureElementRequested(subsystem, holderSystemDeviceStructure));
}
} else {
if (Status.PENDING.equals(subsystem.getStatus())) {
structureElements.add(getStructureElementRequested(subsystem, holderSystemDeviceStructure));
} else {
structureElements.add(getStructureElementProcessed(subsystem, holderSystemDeviceStructure));
}
}
structureElements.add(getStructureElementProcessed(subsystem, holderStructures, structureChoice));
}
return structureElements;
}
......@@ -166,33 +134,17 @@ public class StructureElementUtil {
* Populate and return list of structure elements for disciplines.
*
* @param disciplines disciplines
* @param holderSystemDeviceStructure holder of containers for system and device structure content
* @param holderStructures holder of system and device structure content
* @param structureChoice whether to consider content from structure perspective or history perspective.
* Structure perspective will give mnemonic path.
* History perspective may give empty mnemonic path as non-trivial to find out for history.
* If choice not given then default as structure perspective (processed).
* @return list of structure elements
*/
public static List<StructureElement> getStructureElementsForDisciplines(List<Discipline> disciplines, HolderSystemDeviceStructure holderSystemDeviceStructure, StructureChoice structureChoice) {
public static List<StructureElement> getStructureElementsForDisciplines(List<Discipline> disciplines, HolderStructures holderStructures, StructureChoice structureChoice) {
List<StructureElement> structureElements = Lists.newArrayList();
for (Discipline discipline : disciplines) {
// one or two return elements
// processed != null and processed != requested (> 1s difference) --> two entries (processed, requested)
// processed != null and processed == requested (<= 1s difference) --> one entry (processed initial)
// processed == null --> one entry (requested)
if (StructureChoice.HISTORY.equals(structureChoice)) {
if (discipline.getProcessed() != null && ((discipline.getProcessed().getTime() - discipline.getRequested().getTime()) > THOUSAND_MILLISECONDS)) {
structureElements.add(getStructureElementProcessed(discipline, holderSystemDeviceStructure));
structureElements.add(getStructureElementRequested(discipline, holderSystemDeviceStructure));
} else if (discipline.getProcessed() != null && ((discipline.getProcessed().getTime() - discipline.getRequested().getTime()) <= THOUSAND_MILLISECONDS)) {
structureElements.add(getStructureElementProcessed(discipline, holderSystemDeviceStructure));
} else {
structureElements.add(getStructureElementRequested(discipline, holderSystemDeviceStructure));
}
} else {
if (Status.PENDING.equals(discipline.getStatus())) {
structureElements.add(getStructureElementRequested(discipline, holderSystemDeviceStructure));
} else {
structureElements.add(getStructureElementProcessed(discipline, holderSystemDeviceStructure));
}
}
structureElements.add(getStructureElementProcessed(discipline, holderStructures, structureChoice));
}
return structureElements;
}
......@@ -200,33 +152,17 @@ public class StructureElementUtil {
* Populate and return list of structure elements for device groups.
*
* @param deviceGroups device groups
* @param holderSystemDeviceStructure holder of containers for system and device structure content
* @param holderStructures holder of system and device structure content
* @param structureChoice whether to consider content from structure perspective or history perspective.
* Structure perspective will give mnemonic path.
* History perspective may give empty mnemonic path as non-trivial to find out for history.
* If choice not given then default as structure perspective (processed).
* @return list of structure elements
*/
public static List<StructureElement> getStructureElementsForDeviceGroups(List<DeviceGroup> deviceGroups, HolderSystemDeviceStructure holderSystemDeviceStructure, StructureChoice structureChoice) {
public static List<StructureElement> getStructureElementsForDeviceGroups(List<DeviceGroup> deviceGroups, HolderStructures holderStructures, StructureChoice structureChoice) {
List<StructureElement> structureElements = Lists.newArrayList();
for (DeviceGroup deviceGroup : deviceGroups) {
// one or two return elements
// processed != null and processed != requested (> 1s difference) --> two entries (processed, requested)
// processed != null and processed == requested (<= 1s difference) --> one entry (processed initial)
// processed == null --> one entry (requested)
if (StructureChoice.HISTORY.equals(structureChoice)) {
if (deviceGroup.getProcessed() != null && ((deviceGroup.getProcessed().getTime() - deviceGroup.getRequested().getTime()) > THOUSAND_MILLISECONDS)) {
structureElements.add(getStructureElementProcessed(deviceGroup, holderSystemDeviceStructure));
structureElements.add(getStructureElementRequested(deviceGroup, holderSystemDeviceStructure));
} else if (deviceGroup.getProcessed() != null && ((deviceGroup.getProcessed().getTime() - deviceGroup.getRequested().getTime()) <= THOUSAND_MILLISECONDS)) {
structureElements.add(getStructureElementProcessed(deviceGroup, holderSystemDeviceStructure));
} else {
structureElements.add(getStructureElementRequested(deviceGroup, holderSystemDeviceStructure));
}
} else {
if (Status.PENDING.equals(deviceGroup.getStatus())) {
structureElements.add(getStructureElementRequested(deviceGroup, holderSystemDeviceStructure));
} else {
structureElements.add(getStructureElementProcessed(deviceGroup, holderSystemDeviceStructure));
}
}
structureElements.add(getStructureElementProcessed(deviceGroup, holderStructures, structureChoice));
}
return structureElements;
}
......@@ -234,336 +170,250 @@ public class StructureElementUtil {
* Populate and return list of structure elements for device types.
*
* @param deviceTypes device types
* @param holderSystemDeviceStructure holder of containers for system and device structure content
* @param holderStructures holder of system and device structure content
* @param structureChoice whether to consider content from structure perspective or history perspective.
* Structure perspective will give mnemonic path.
* History perspective may give empty mnemonic path as non-trivial to find out for history.
* If choice not given then default as structure perspective (processed).
* @return list of structure elements
*/
public static List<StructureElement> getStructureElementsForDeviceTypes(List<DeviceType> deviceTypes, HolderSystemDeviceStructure holderSystemDeviceStructure, StructureChoice structureChoice) {
public static List<StructureElement> getStructureElementsForDeviceTypes(List<DeviceType> deviceTypes, HolderStructures holderStructures, StructureChoice structureChoice) {
List<StructureElement> structureElements = Lists.newArrayList();
for (DeviceType deviceType : deviceTypes) {
// one or two return elements
// processed != null and processed != requested (> 1s difference) --> two entries (processed, requested)
// processed != null and processed == requested (<= 1s difference) --> one entry (processed initial)
// processed == null --> one entry (requested)
if (StructureChoice.HISTORY.equals(structureChoice)) {
if (deviceType.getProcessed() != null && ((deviceType.getProcessed().getTime() - deviceType.getRequested().getTime()) > THOUSAND_MILLISECONDS)) {
structureElements.add(getStructureElementProcessed(deviceType, holderSystemDeviceStructure));
structureElements.add(getStructureElementRequested(deviceType, holderSystemDeviceStructure));
} else if (deviceType.getProcessed() != null && ((deviceType.getProcessed().getTime() - deviceType.getRequested().getTime()) <= THOUSAND_MILLISECONDS)) {
structureElements.add(getStructureElementProcessed(deviceType, holderSystemDeviceStructure));
} else {
structureElements.add(getStructureElementRequested(deviceType, holderSystemDeviceStructure));
}
} else {
if (Status.PENDING.equals(deviceType.getStatus())) {
structureElements.add(getStructureElementRequested(deviceType, holderSystemDeviceStructure));
} else {
structureElements.add(getStructureElementProcessed(deviceType, holderSystemDeviceStructure));
}
}
structureElements.add(getStructureElementProcessed(deviceType, holderStructures, structureChoice));
}
return structureElements;
}
/**
* Populate and return structure element for system group with focus on processed.
* Populate and return structure element for audit structure with focus on processed.
*
* @param systemGroup system group
* @param holderSystemDeviceStructure holder of containers for system and device structure content
* @param auditStructure audit structure
* @param holderStructures holder of system and device structure content
* @param structureChoice whether to consider content from structure perspective or history perspective
* @return structure element
*/
public static StructureElement getStructureElementProcessed(SystemGroup systemGroup, HolderSystemDeviceStructure holderSystemDeviceStructure) {
if (systemGroup == null) {
public static StructureElement getStructureElementProcessed(AuditStructure auditStructure, HolderStructures holderStructures, StructureChoice structureChoice) {
if (auditStructure == null) {
return null;
}
// String mnemonicpath = holderSystemDeviceStructure != null
// ? systemGroup.getMnemonic()
// : null;
String mnemonicpath = !StringUtils.isEmpty(systemGroup.getMnemonic())
? systemGroup.getMnemonic()
: null;
// find out attributes as audit table is shared for system and device structure content
// mnemonic path ambiguous if considered in past
Type type = null;
UUID parent = null;
String mnemonicPath = null;
Integer level = null;
if (TextUtil.SYSTEMGROUP.equals(auditStructure.getAuditTable())) {
type = Type.SYSTEMGROUP;
level = 1;
} else if (TextUtil.SYSTEM.equals(auditStructure.getAuditTable())) {
type = Type.SYSTEM;
parent = holderStructures.findSystemGroupById(auditStructure.getParentId()).getUuid();
level = 2;
} else if (TextUtil.SUBSYSTEM.equals(auditStructure.getAuditTable())) {
type = Type.SUBSYSTEM;
parent = holderStructures.findSystemById(auditStructure.getParentId()).getUuid();
level = 3;
} else if (TextUtil.DISCIPLINE.equals(auditStructure.getAuditTable())) {
type = Type.DISCIPLINE;
level = 1;
} else if (TextUtil.DEVICEGROUP.equals(auditStructure.getAuditTable())) {
type = Type.DEVICEGROUP;
parent = holderStructures.findDisciplineById(auditStructure.getParentId()).getUuid();
level = 2;
} else if (TextUtil.DEVICETYPE.equals(auditStructure.getAuditTable())) {
type = Type.DEVICETYPE;
parent = holderStructures.findDeviceGroupById(auditStructure.getParentId()).getUuid();
level = 3;
}
return getStructureElement(
Type.SYSTEMGROUP,
systemGroup.getUuid(),
null,
systemGroup.getName(), systemGroup.getMnemonic(), mnemonicpath, 1,
systemGroup.getDescription(), systemGroup.getStatus(), systemGroup.isLatest(), systemGroup.isDeleted(),
systemGroup.getProcessed(), systemGroup.getProcessedBy(), systemGroup.getProcessedComment());
auditStructure.getUuid(), type, parent,
auditStructure.getMnemonic(), auditStructure.getOrdering(), auditStructure.getDescription(),
mnemonicPath, level,
auditStructure.getStatus(), auditStructure.isDeleted(),
auditStructure.getProcessed(), auditStructure.getProcessedBy(), auditStructure.getProcessedComment());
}
/**
* Populate and return structure element for system group with focus on requested.
* Populate and return structure element for system group with focus on processed.
*
* @param systemGroup system group
* @param holderSystemDeviceStructure holder of containers for system and device structure content
* @param holderStructures holder of system and device structure content
* @param structureChoice whether to consider content from structure perspective or history perspective
* @return structure element
*/
public static StructureElement getStructureElementRequested(SystemGroup systemGroup, HolderSystemDeviceStructure holderSystemDeviceStructure) {
public static StructureElement getStructureElementProcessed(SystemGroup systemGroup, HolderStructures holderStructures, StructureChoice structureChoice) {
if (systemGroup == null) {
return null;
}
// String mnemonicpath = holderSystemDeviceStructure != null
// ? systemGroup.getMnemonic()
// : null;
String mnemonicpath = !StringUtils.isEmpty(systemGroup.getMnemonic())
? systemGroup.getMnemonic()
: null;
// mnemonic path
// ambiguous if considered in past (requested, processed)
// not for history of structure (obsolete)
String mnemonicPath = StructureChoice.HISTORY.equals(structureChoice) || !Status.APPROVED.equals(systemGroup.getStatus())
? null
: StructureUtil.getMnemonicPath(systemGroup, holderStructures);
return getStructureElement(
Type.SYSTEMGROUP,
systemGroup.getUuid(),
null,
systemGroup.getName(), systemGroup.getMnemonic(), mnemonicpath, 1,
systemGroup.getDescription(), Status.PENDING, systemGroup.isLatest(), systemGroup.isDeleted(),
systemGroup.getRequested(), systemGroup.getRequestedBy(), systemGroup.getRequestedComment());
systemGroup.getUuid(), Type.SYSTEMGROUP, null,
systemGroup.getMnemonic(), systemGroup.getOrdering(), systemGroup.getDescription(),
mnemonicPath, 1,
systemGroup.getStatus(), systemGroup.isDeleted(),
systemGroup.getProcessed(), systemGroup.getProcessedBy(), systemGroup.getProcessedComment());
}
/**
* Populate and return structure element for system with focus on processed.
*
* @param system system
* @param holderSystemDeviceStructure holder of containers for system and device structure content
* @param holderStructures holder of system and device structure content
* @param structureChoice whether to consider content from structure perspective or history perspective
* @return structure element
*/
public static StructureElement getStructureElementProcessed(System system, HolderSystemDeviceStructure holderSystemDeviceStructure) {
public static StructureElement getStructureElementProcessed(System system, HolderStructures holderStructures, StructureChoice structureChoice) {
if (system == null) {
return null;
}
String mnemonicpath = StructureUtil.getMnemonicPath(system, holderSystemDeviceStructure);
// mnemonic path
// ambiguous if considered in past (requested, processed)
// not for history of structure (obsolete)
String mnemonicPath = StructureChoice.HISTORY.equals(structureChoice) || !Status.APPROVED.equals(system.getStatus())
? null
: StructureUtil.getMnemonicPath(system, holderStructures);
return getStructureElement(
Type.SYSTEM,
system.getUuid(),
system.getParentUuid(),
system.getName(), system.getMnemonic(), mnemonicpath, 2,
system.getDescription(), system.getStatus(), system.isLatest(), system.isDeleted(),
system.getUuid(), Type.SYSTEM, holderStructures.findSystemGroupById(system.getParentId()).getUuid(),
system.getMnemonic(), system.getOrdering(), system.getDescription(),
mnemonicPath, 2,
system.getStatus(), system.isDeleted(),
system.getProcessed(), system.getProcessedBy(), system.getProcessedComment());
}
/**
* Populate and return structure element for system group with focus on requested.
*
* @param system system
* @param holderSystemDeviceStructure holder of containers for system and device structure content
* @return structure element
*/
public static StructureElement getStructureElementRequested(System system, HolderSystemDeviceStructure holderSystemDeviceStructure) {
if (system == null) {
return null;
}
String mnemonicpath = StructureUtil.getMnemonicPath(system, holderSystemDeviceStructure);
return getStructureElement(
Type.SYSTEM,
system.getUuid(),
system.getParentUuid(),
system.getName(), system.getMnemonic(), mnemonicpath, 2,
system.getDescription(), Status.PENDING, system.isLatest(), system.isDeleted(),
system.getRequested(), system.getRequestedBy(), system.getRequestedComment());
}
/**
* Populate and return structure element for subsystem with focus on processed.
*
* @param subsystem subsystem
* @param holderSystemDeviceStructure holder of containers for system and device structure content
* @param holderStructures holder of system and device structure content
* @param structureChoice whether to consider content from structure perspective or history perspective
* @return structure element
*/
public static StructureElement getStructureElementProcessed(Subsystem subsystem, HolderSystemDeviceStructure holderSystemDeviceStructure) {
public static StructureElement getStructureElementProcessed(Subsystem subsystem, HolderStructures holderStructures, StructureChoice structureChoice) {
if (subsystem == null) {
return null;
}
String mnemonicpath = StructureUtil.getMnemonicPath(subsystem, holderSystemDeviceStructure);
// mnemonic path
// ambiguous if considered in past (requested, processed)
// not for history of structure (obsolete)
String mnemonicPath = StructureChoice.HISTORY.equals(structureChoice) || !Status.APPROVED.equals(subsystem.getStatus())
? null
: StructureUtil.getMnemonicPath(subsystem, holderStructures);
return getStructureElement(
Type.SUBSYSTEM,
subsystem.getUuid(),
subsystem.getParentUuid(),
subsystem.getName(), subsystem.getMnemonic(), mnemonicpath, 3,
subsystem.getDescription(), subsystem.getStatus(), subsystem.isLatest(), subsystem.isDeleted(),
subsystem.getUuid(), Type.SUBSYSTEM, holderStructures.findSystemById(subsystem.getParentId()).getUuid(),
subsystem.getMnemonic(), subsystem.getOrdering(), subsystem.getDescription(),
mnemonicPath, 3,
subsystem.getStatus(), subsystem.isDeleted(),
subsystem.getProcessed(), subsystem.getProcessedBy(), subsystem.getProcessedComment());
}
/**
* Populate and return structure element for subsystem with focus on requested.
*
* @param subsystem subsystem
* @param holderSystemDeviceStructure holder of containers for system and device structure content
* @return structure element
*/
public static StructureElement getStructureElementRequested(Subsystem subsystem, HolderSystemDeviceStructure holderSystemDeviceStructure) {
if (subsystem == null) {
return null;
}
String mnemonicpath = StructureUtil.getMnemonicPath(subsystem, holderSystemDeviceStructure);
return getStructureElement(
Type.SUBSYSTEM,
subsystem.getUuid(),
subsystem.getParentUuid(),
subsystem.getName(), subsystem.getMnemonic(), mnemonicpath, 3,
subsystem.getDescription(), Status.PENDING, subsystem.isLatest(), subsystem.isDeleted(),
subsystem.getRequested(), subsystem.getRequestedBy(), subsystem.getRequestedComment());
}
/**
* Populate and return structure element for discipline with focus on processed.
*
* @param discipline discipline
* @param holderSystemDeviceStructure holder of containers for system and device structure content
* @param holderStructures holder of system and device structure content
* @param structureChoice whether to consider content from structure perspective or history perspective
* @return structure element
*/
public static StructureElement getStructureElementProcessed(Discipline discipline, HolderSystemDeviceStructure holderSystemDeviceStructure) {
public static StructureElement getStructureElementProcessed(Discipline discipline, HolderStructures holderStructures, StructureChoice structureChoice) {
if (discipline == null) {
return null;
}
// String mnemonicpath = holderSystemDeviceStructure != null
// ? discipline.getMnemonic()
// : null;
String mnemonicpath = !StringUtils.isEmpty(discipline.getMnemonic())
? discipline.getMnemonic()
: null;
// mnemonic path
// ambiguous if considered in past (requested, processed)
// not for history of structure (obsolete)
String mnemonicPath = StructureChoice.HISTORY.equals(structureChoice) || !Status.APPROVED.equals(discipline.getStatus())
? null
: StructureUtil.getMnemonicPath(discipline, holderStructures);
return getStructureElement(
Type.DISCIPLINE,
discipline.getUuid(),
null,
discipline.getName(), discipline.getMnemonic(), mnemonicpath, 1,
discipline.getDescription(), discipline.getStatus(), discipline.isLatest(), discipline.isDeleted(),
discipline.getUuid(), Type.DISCIPLINE, null,
discipline.getMnemonic(), discipline.getOrdering(), discipline.getDescription(),
mnemonicPath, 1,
discipline.getStatus(), discipline.isDeleted(),
discipline.getProcessed(), discipline.getProcessedBy(), discipline.getProcessedComment());
}
/**
* Populate and return structure element for discipline with focus on requested.
*
* @param discipline discipline
* @param holderSystemDeviceStructure holder of containers for system and device structure content
* @return structure element
*/
public static StructureElement getStructureElementRequested(Discipline discipline, HolderSystemDeviceStructure holderSystemDeviceStructure) {
if (discipline == null) {
return null;
}
// String mnemonicpath = holderSystemDeviceStructure != null
// ? discipline.getMnemonic()
// : null;
String mnemonicpath = !StringUtils.isEmpty(discipline.getMnemonic())
? discipline.getMnemonic()
: null;
return getStructureElement(
Type.DISCIPLINE,
discipline.getUuid(),
null,
discipline.getName(), discipline.getMnemonic(), mnemonicpath, 1,
discipline.getDescription(), Status.PENDING, discipline.isLatest(), discipline.isDeleted(),
discipline.getRequested(), discipline.getRequestedBy(), discipline.getRequestedComment());
}
/**
* Populate and return structure element for device group with focus on processed.
*
* @param deviceGroup device group
* @param holderSystemDeviceStructure holder of containers for system and device structure content
* @param holderStructures holder of system and device structure content
* @param structureChoice whether to consider content from structure perspective or history perspective
* @return structure element
*/
public static StructureElement getStructureElementProcessed(DeviceGroup deviceGroup, HolderSystemDeviceStructure holderSystemDeviceStructure) {
public static StructureElement getStructureElementProcessed(DeviceGroup deviceGroup, HolderStructures holderStructures, StructureChoice structureChoice) {
if (deviceGroup == null) {
return null;
}
String mnemonicpath = StructureUtil.getMnemonicPath(deviceGroup, holderSystemDeviceStructure);
// mnemonic path
// ambiguous if considered in past (requested, processed)
// not for history of structure (obsolete)
String mnemonicPath = StructureChoice.HISTORY.equals(structureChoice) || !Status.APPROVED.equals(deviceGroup.getStatus())
? null
: StructureUtil.getMnemonicPath(deviceGroup, holderStructures);
return getStructureElement(
Type.DEVICEGROUP,
deviceGroup.getUuid(),
deviceGroup.getParentUuid(),
deviceGroup.getName(), deviceGroup.getMnemonic(), mnemonicpath, 2,
deviceGroup.getDescription(), deviceGroup.getStatus(), deviceGroup.isLatest(), deviceGroup.isDeleted(),
deviceGroup.getUuid(), Type.DEVICEGROUP, holderStructures.findDisciplineById(deviceGroup.getParentId()).getUuid(),
deviceGroup.getMnemonic(), deviceGroup.getOrdering(), deviceGroup.getDescription(),
mnemonicPath, 2,
deviceGroup.getStatus(), deviceGroup.isDeleted(),
deviceGroup.getProcessed(), deviceGroup.getProcessedBy(), deviceGroup.getProcessedComment());
}
/**
* Populate and return structure element for device group with focus on requested.
*
* @param deviceGroup device group
* @param holderSystemDeviceStructure holder of containers for system and device structure content
* @return structure element
*/
public static StructureElement getStructureElementRequested(DeviceGroup deviceGroup, HolderSystemDeviceStructure holderSystemDeviceStructure) {
if (deviceGroup == null) {
return null;
}
String mnemonicpath = StructureUtil.getMnemonicPath(deviceGroup, holderSystemDeviceStructure);
return getStructureElement(
Type.DEVICEGROUP,
deviceGroup.getUuid(),
deviceGroup.getParentUuid(),
deviceGroup.getName(), deviceGroup.getMnemonic(), mnemonicpath, 2,
deviceGroup.getDescription(), Status.PENDING, deviceGroup.isLatest(), deviceGroup.isDeleted(),
deviceGroup.getRequested(), deviceGroup.getRequestedBy(), deviceGroup.getRequestedComment());
}
/**
* Populate and return structure element for device type with focus on processed.
*
* @param deviceType device type
* @param holderSystemDeviceStructure holder of containers for system and device structure content
* @param holderStructures holder of system and device structure content
* @param structureChoice whether to consider content from structure perspective or history perspective
* @return structure element
*/
public static StructureElement getStructureElementProcessed(DeviceType deviceType, HolderSystemDeviceStructure holderSystemDeviceStructure) {
public static StructureElement getStructureElementProcessed(DeviceType deviceType, HolderStructures holderStructures, StructureChoice structureChoice) {
if (deviceType == null) {
return null;
}
String mnemonicpath = StructureUtil.getMnemonicPath(deviceType, holderSystemDeviceStructure);
// mnemonic path
// ambiguous if considered in past (requested, processed)
// not for history of structure (obsolete)
String mnemonicPath = StructureChoice.HISTORY.equals(structureChoice) || !Status.APPROVED.equals(deviceType.getStatus())
? null
: StructureUtil.getMnemonicPath(deviceType, holderStructures);
return getStructureElement(
Type.DEVICETYPE,
deviceType.getUuid(),
deviceType.getParentUuid(),
deviceType.getName(), deviceType.getMnemonic(), mnemonicpath, 3,
deviceType.getDescription(), deviceType.getStatus(), deviceType.isLatest(), deviceType.isDeleted(),
deviceType.getUuid(), Type.DEVICETYPE, holderStructures.findDeviceGroupById(deviceType.getParentId()).getUuid(),
deviceType.getMnemonic(), deviceType.getOrdering(), deviceType.getDescription(),
mnemonicPath, 3,
deviceType.getStatus(), deviceType.isDeleted(),
deviceType.getProcessed(), deviceType.getProcessedBy(), deviceType.getProcessedComment());
}
/**
* Populate and return structure element for device type with focus on requested.
*
* @param deviceType device type
* @param holderSystemDeviceStructure holder of containers for system and device structure content
* @return structure element
*/
public static StructureElement getStructureElementRequested(DeviceType deviceType, HolderSystemDeviceStructure holderSystemDeviceStructure) {
if (deviceType == null) {
return null;
}
String mnemonicpath = StructureUtil.getMnemonicPath(deviceType, holderSystemDeviceStructure);
return getStructureElement(
Type.DEVICETYPE,
deviceType.getUuid(),
deviceType.getParentUuid(),
deviceType.getName(), deviceType.getMnemonic(), mnemonicpath, 3,
deviceType.getDescription(), Status.PENDING, deviceType.isLatest(), deviceType.isDeleted(),
deviceType.getRequested(), deviceType.getRequestedBy(), deviceType.getRequestedComment());
}
// ----------------------------------------------------------------------------------------------------
/**
* Populate and return structure element.
*
* @param type type
* @param uuid uuid
* @param type type
* @param parent parent uuid
* @param name name
* @param mnemonic mnemonic
* @param mnemonicpath mnemonic path
* @param level level
* @param ordering ordering
* @param description description
* @param mnemonicPath mnemonic path
* @param level level
* @param status status
* @param latest latest
* @param deleted deleted
* @param when when
* @param who who
......@@ -571,230 +421,286 @@ public class StructureElementUtil {
* @return structure element
*/
protected static StructureElement getStructureElement(
Type type,
UUID uuid,
UUID parent,
String name, String mnemonic, String mnemonicpath, Integer level,
String description, Status status, Boolean latest, Boolean deleted,
UUID uuid, Type type, UUID parent,
String mnemonic, Integer ordering, String description,
String mnemonicPath, Integer level,
Status status, Boolean deleted,
Date when, String who, String comment) {
return new StructureElement(
type,
uuid,
parent,
name, mnemonic, mnemonicpath, level,
description, status, latest, deleted,
uuid, type, parent,
mnemonic, ordering, description,
mnemonicPath, level,
status, deleted,
when, who, comment);
}
// ----------------------------------------------------------------------------------------------------
/**
* Convert structure element command for create to structure element command.
*
* @param command structure element command for create
* @return structure element command
*/
public static StructureElementCommand convertCommandCreate2Command(StructureElementCommandCreate command) {
return new StructureElementCommand(
null,
command.getType(),
command.getParent(),
command.getMnemonic(),
command.getOrdering(),
command.getDescription());
}
private static boolean hasSameContent(StructureElement structureElement, NameStructure nameStructure) {
/*
StructureElement
x uuid
x description
x status
x latest
x deleted
NameStructure
x uuid
x description
x status
x latest
x deleted
*/
if (structureElement == null && nameStructure == null)
return true;
if (structureElement == null)
return false;
if (nameStructure == null)
return false;
if (structureElement.getUuid() == null) {
if (nameStructure.getUuid() != null)
return false;
} else if (!structureElement.getUuid().equals(nameStructure.getUuid()))
return false;
if (structureElement.getDescription() == null) {
if (nameStructure.getDescription() != null)
return false;
} else if (!structureElement.getDescription().equals(nameStructure.getDescription()))
return false;
if (structureElement.getStatus() == null) {
if (nameStructure.getStatus() != null)
return false;
} else if (!structureElement.getStatus().equals(nameStructure.getStatus()))
return false;
if (structureElement.isLatest() == null) {
if (nameStructure.isLatest() != null)
return false;
} else if (!structureElement.isLatest().equals(nameStructure.isLatest()))
return false;
if (structureElement.isDeleted() == null) {
if (nameStructure.isDeleted() != null)
return false;
} else if (!structureElement.isDeleted().equals(nameStructure.isDeleted()))
return false;
return true;
}
private static boolean hasSameContent(StructureElement structureElement, Structure structure) {
/*
StructureElement
x name
x mnemonic
Structure
x name
x mnemonic
*/
if (!hasSameContent(structureElement, (NameStructure) structure))
return false;
if (structureElement.getName() == null) {
if (structure.getName() != null)
return false;
} else if (!structureElement.getName().equals(structure.getName()))
return false;
if (structureElement.getMnemonic() == null) {
if (structure.getMnemonic() != null)
return false;
} else if (!structureElement.getMnemonic().equals(structure.getMnemonic()))
return false;
return true;
}
public static boolean hasSameContent(StructureElement structureElement, SystemGroup systemGroup) {
/*
StructureElement
x type
SystemGroup
*/
if (!hasSameContent(structureElement, (Structure) systemGroup))
return false;
if (!Type.SYSTEMGROUP.equals(structureElement.getType())) {
return false;
/**
* Convert list of structure element commands for create to list of structure element commands.
*
* @param commands list of structure element commands for create
* @return list of structure element commands
*/
public static List<StructureElementCommand> convertCommandCreate2Command(List<StructureElementCommandCreate> commands) {
List<StructureElementCommand> structureElementCommands = Lists.newArrayList();
for (StructureElementCommandCreate command : commands) {
structureElementCommands.add(StructureElementUtil.convertCommandCreate2Command(command));
}
return structureElementCommands;
}
return true;
/**
* Convert structure element command for update to structure element command.
*
* @param command structure element command for update
* @return structure element command
*/
public static StructureElementCommand convertCommandUpdate2Command(StructureElementCommandUpdate command) {
return new StructureElementCommand(
command.getUuid(),
command.getType(),
command.getParent(),
command.getMnemonic(),
command.getOrdering(),
command.getDescription());
}
public static boolean hasSameContent(StructureElement structureElement, System system) {
/*
StructureElement
x type
x parent
System
x parent_uuid
*/
/**
* Convert list of structure element commands for update to list of structure element commands.
*
* @param commands list of structure element commands for update
* @return list of structure element commands
*/
public static List<StructureElementCommand> convertCommandUpdate2Command(List<StructureElementCommandUpdate> commands) {
List<StructureElementCommand> structureElementCommands = Lists.newArrayList();
for (StructureElementCommandUpdate command : commands) {
structureElementCommands.add(StructureElementUtil.convertCommandUpdate2Command(command));
}
return structureElementCommands;
}
if (!hasSameContent(structureElement, (Structure) system))
return false;
/**
* Convert structure element command for confirm to structure element command.
*
* @param command structure element command for confirm
* @return structure element command
*/
public static StructureElementCommand convertCommandConfirm2Command(StructureElementCommandConfirm command) {
return new StructureElementCommand(
command.getUuid(),
command.getType(),
null,
null,
null,
null);
}
if (!Type.SYSTEMGROUP.equals(structureElement.getType())) {
return false;
/**
* Convert list of structure element commands for confirm to list of structure element commands.
*
* @param commands list of structure element commands for confirm
* @return list of structure element commands
*/
public static List<StructureElementCommand> convertCommandConfirm2Command(List<StructureElementCommandConfirm> commands) {
List<StructureElementCommand> structureElementCommands = Lists.newArrayList();
for (StructureElementCommandConfirm command : commands) {
structureElementCommands.add(StructureElementUtil.convertCommandConfirm2Command(command));
}
if (structureElement.getParent() == null) {
if (system.getParentUuid() != null)
return false;
} else if (!structureElement.getParent().equals(system.getParentUuid()))
return false;
return structureElementCommands;
}
// ----------------------------------------------------------------------------------------------------
return true;
/**
* Convert structure element command to structure element command for create.
*
* @param command structure element command
* @return structure element command for create
*/
public static StructureElementCommandCreate convertCommand2CommandCreate(StructureElementCommand command) {
return new StructureElementCommandCreate(
command.getType(),
command.getParent(),
command.getMnemonic(),
command.getOrdering(),
command.getDescription());
}
public static boolean hasSameContent(StructureElement structureElement, Subsystem subsystem) {
/*
StructureElement
x type
x parent
Subsystem
x parent_uuid
*/
/**
* Convert array of structure element commands to array of structure element commands for create.
*
* @param commands array of structure element commands
* @return array of structure element commands for create
*/
public static StructureElementCommandCreate[] convertCommand2CommandCreate(StructureElementCommand[] commands) {
StructureElementCommandCreate[] structureElementCommands = new StructureElementCommandCreate[commands.length];
for (int i=0; i<commands.length; i++) {
structureElementCommands[i] = StructureElementUtil.convertCommand2CommandCreate(commands[i]);
if (!hasSameContent(structureElement, (Structure) subsystem))
return false;
}
return structureElementCommands;
}
if (!Type.SYSTEMGROUP.equals(structureElement.getType())) {
return false;
/**
* Convert structure element command to structure element command for update.
*
* @param command structure element command
* @return structure element command for update
*/
public static StructureElementCommandUpdate convertCommand2CommandUpdate(StructureElementCommand command) {
return new StructureElementCommandUpdate(
command.getUuid(),
command.getType(),
command.getParent(),
command.getMnemonic(),
command.getOrdering(),
command.getDescription());
}
/**
* Convert array of structure element commands to array of structure element commands for update.
*
* @param commands array of structure element commands
* @return array of structure element commands for update
*/
public static StructureElementCommandUpdate[] convertCommand2CommandUpdate(StructureElementCommand[] commands) {
StructureElementCommandUpdate[] structureElementCommands = new StructureElementCommandUpdate[commands.length];
for (int i=0; i<commands.length; i++) {
structureElementCommands[i] = StructureElementUtil.convertCommand2CommandUpdate(commands[i]);
}
return structureElementCommands;
}
/**
* Convert structure element command to structure element command for confirm.
*
* @param command structure element command
* @return structure element command for confirm
*/
public static StructureElementCommandConfirm convertCommand2CommandConfirm(StructureElementCommand command) {
return new StructureElementCommandConfirm(
command.getUuid(),
command.getType());
}
/**
* Convert array of structure element commands to array of structure element commands for confirm.
*
* @param commands array of structure element commands
* @return array of structure element commands for confirm
*/
public static StructureElementCommandConfirm[] convertCommand2CommandConfirm(StructureElementCommand[] commands) {
StructureElementCommandConfirm[] structureElementCommands = new StructureElementCommandConfirm[commands.length];
for (int i=0; i<commands.length; i++) {
structureElementCommands[i] = StructureElementUtil.convertCommand2CommandConfirm(commands[i]);
}
if (structureElement.getParent() == null) {
if (subsystem.getParentUuid() != null)
return false;
} else if (!structureElement.getParent().equals(subsystem.getParentUuid()))
return false;
return structureElementCommands;
}
// ----------------------------------------------------------------------------------------------------
return true;
/**
* Convert structure element to structure element command for create.
*
* @param element structure element
* @return structure element command for create
*/
public static StructureElementCommandCreate convertElement2CommandCreate(StructureElement element) {
return new StructureElementCommandCreate(
element.getType(),
element.getParent(),
element.getMnemonic(),
element.getOrdering(),
element.getDescription());
}
public static boolean hasSameContent(StructureElement structureElement, Discipline discipline) {
/*
StructureElement
x type
Discipline
*/
/**
* Convert array of structure elements to array of structure element commands for create.
*
* @param elements array of structure elements
* @return array of structure element commands for create
*/
public static StructureElementCommandCreate[] convertElement2CommandCreate(StructureElement[] elements) {
StructureElementCommandCreate[] structureElementCommands = new StructureElementCommandCreate[elements.length];
for (int i=0; i<elements.length; i++) {
structureElementCommands[i] = convertElement2CommandCreate(elements[i]);
}
return structureElementCommands;
}
if (!hasSameContent(structureElement, (Structure) discipline))
return false;
/**
* Convert structure element to structure element command for update.
*
* @param element structure element
* @return structure element command for update
*/
public static StructureElementCommandUpdate convertElement2CommandUpdate(StructureElement element) {
return new StructureElementCommandUpdate(
element.getUuid(),
element.getType(),
element.getParent(),
element.getMnemonic(),
element.getOrdering(),
element.getDescription());
}
if (!Type.SYSTEMGROUP.equals(structureElement.getType())) {
return false;
/**
* Convert array of structure elements to array of structure element commands for update.
*
* @param elements array of structure elements
* @return array of structure element commands for update
*/
public static StructureElementCommandUpdate[] convertElement2CommandUpdate(StructureElement[] elements) {
StructureElementCommandUpdate[] structureElementCommands = new StructureElementCommandUpdate[elements.length];
for (int i=0; i<elements.length; i++) {
structureElementCommands[i] = convertElement2CommandUpdate(elements[i]);
}
return structureElementCommands;
}
return true;
}
public static boolean hasSameContent(StructureElement structureElement, DeviceGroup deviceGroup) {
/*
StructureElement
x type
x parent
Subsystem
x parent_uuid
*/
if (!hasSameContent(structureElement, (Structure) deviceGroup))
return false;
if (!Type.SYSTEMGROUP.equals(structureElement.getType())) {
return false;
}
if (structureElement.getParent() == null) {
if (deviceGroup.getParentUuid() != null)
return false;
} else if (!structureElement.getParent().equals(deviceGroup.getParentUuid()))
return false;
return true;
}
public static boolean hasSameContent(StructureElement structureElement, DeviceType deviceType) {
/*
StructureElement
x type
x parent
DeviceType
x parent_uuid
*/
if (!hasSameContent(structureElement, (Structure) deviceType))
return false;
if (!Type.SYSTEMGROUP.equals(structureElement.getType())) {
return false;
}
if (structureElement.getParent() == null) {
if (deviceType.getParentUuid() != null)
return false;
} else if (!structureElement.getParent().equals(deviceType.getParentUuid()))
return false;
return true;
/**
* Convert structure element to structure element command for confirm.
*
* @param element structure element
* @return structure element command for confirm
*/
public static StructureElementCommandConfirm convertElement2CommandConfirm(StructureElement element) {
return new StructureElementCommandConfirm(
element.getUuid(),
element.getType());
}
/**
* Convert array of structure elements to array of structure element commands for confirm.
*
* @param elements array of structure elements
* @return array of structure element commands for confirm
*/
public static StructureElementCommandConfirm[] convertElement2CommandConfirm(StructureElement[] elements) {
StructureElementCommandConfirm[] structureElementCommands = new StructureElementCommandConfirm[elements.length];
for (int i=0; i<elements.length; i++) {
structureElementCommands[i] = convertElement2CommandConfirm(elements[i]);
}
return structureElementCommands;
}
}
......@@ -31,6 +31,8 @@ import org.openepics.names.repository.model.Subsystem;
import org.openepics.names.repository.model.System;
import org.openepics.names.repository.model.SystemGroup;
import com.google.common.collect.Lists;
/**
* Utility class to assist in handling of structure (name part) content.
*
......@@ -45,61 +47,84 @@ public class StructureUtil {
throw new IllegalStateException("Utility class");
}
/**
* Return mnemonic path for system group.
*
* @param systemGroup system group
* @param holderStructures holder of system and device structure content
* @return mnemonic path
*/
public static String getMnemonicPath(SystemGroup systemGroup, HolderStructures holderStructures) {
if (ValidateUtil.isAnyNull(systemGroup, holderStructures)) {
return null;
}
return !StringUtils.isEmpty(systemGroup.getMnemonic())
? systemGroup.getMnemonic()
: null;
}
/**
* Return mnemonic path for system.
*
* @param system system
* @param holderSystemDeviceStructure holder of containers for system and device structure content
* @param holderStructures holder of system and device structure content
* @return mnemonic path
*/
public static String getMnemonicPath(System system, HolderSystemDeviceStructure holderSystemDeviceStructure) {
if (system == null || holderSystemDeviceStructure == null) {
public static String getMnemonicPath(System system, HolderStructures holderStructures) {
if (ValidateUtil.isAnyNull(system, holderStructures)) {
return null;
}
SystemGroup systemGroup = holderSystemDeviceStructure.findSystemGroupByUuid(system.getParentUuid());
return systemGroup != null && !StringUtils.isEmpty(systemGroup.getMnemonic())
? systemGroup.getMnemonic() + "-" + system.getMnemonic()
: system.getMnemonic();
return system.getMnemonic();
}
/**
* Return mnemonic path for subsystem.
*
* @param subsystem subsystem
* @param holderSystemDeviceStructure holder of containers for system and device structure content
* @param holderStructures holder of system and device structure content
* @return mnemonic path
*/
public static String getMnemonicPath(Subsystem subsystem, HolderSystemDeviceStructure holderSystemDeviceStructure) {
if (subsystem == null || holderSystemDeviceStructure == null) {
public static String getMnemonicPath(Subsystem subsystem, HolderStructures holderStructures) {
if (ValidateUtil.isAnyNull(subsystem, holderStructures)) {
return null;
}
System system = holderSystemDeviceStructure.findSystemByUuid(subsystem.getParentUuid());
SystemGroup systemGroup = system != null
? holderSystemDeviceStructure.findSystemGroupByUuid(system.getParentUuid())
System system = holderStructures.findSystemById(subsystem.getParentId());
return system != null
? system.getMnemonic() + "-" + subsystem.getMnemonic()
: null;
return systemGroup != null && !StringUtils.isEmpty(systemGroup.getMnemonic()) && system != null
? systemGroup.getMnemonic() + "-" + system.getMnemonic() + "-" + subsystem.getMnemonic()
: system != null
? system.getMnemonic() + "-" + subsystem.getMnemonic()
: subsystem.getMnemonic();
}
/**
* Return mnemonic path for discipline.
*
* @param discipline discipline
* @param holderStructures holder of system and device structure content
* @return mnemonic path
*/
public static String getMnemonicPath(Discipline discipline, HolderStructures holderStructures) {
if (ValidateUtil.isAnyNull(discipline, holderStructures)) {
return null;
}
return discipline.getMnemonic();
}
/**
* Return mnemonic path for device group.
*
* @param deviceGroup device group
* @param holderSystemDeviceStructure holder of containers for system and device structure content
* @param holderStructures holder of system and device structure content
* @return mnemonic path
*/
public static String getMnemonicPath(DeviceGroup deviceGroup, HolderSystemDeviceStructure holderSystemDeviceStructure) {
if (deviceGroup == null || holderSystemDeviceStructure == null) {
public static String getMnemonicPath(DeviceGroup deviceGroup, HolderStructures holderStructures) {
if (ValidateUtil.isAnyNull(deviceGroup, holderStructures)) {
return null;
}
Discipline discipline = holderSystemDeviceStructure.findDisciplineByUuid(deviceGroup.getParentUuid());
Discipline discipline = holderStructures.findDisciplineById(deviceGroup.getParentId());
return discipline != null
? discipline.getMnemonic()
: null;
......@@ -109,37 +134,37 @@ public class StructureUtil {
* Return mnemonic path for device type.
*
* @param deviceType device type
* @param holderSystemDeviceStructure holder of containers for system and device structure content
* @param holderStructures holder of system and device structure content
* @return mnemonic path
*/
public static String getMnemonicPath(DeviceType deviceType, HolderSystemDeviceStructure holderSystemDeviceStructure) {
if (deviceType == null || holderSystemDeviceStructure == null) {
public static String getMnemonicPath(DeviceType deviceType, HolderStructures holderStructures) {
if (ValidateUtil.isAnyNull(deviceType, holderStructures)) {
return null;
}
DeviceGroup deviceGroup = holderSystemDeviceStructure.findDeviceGroupByUuid(deviceType.getParentUuid());
DeviceGroup deviceGroup = holderStructures.findDeviceGroupById(deviceType.getParentId());
Discipline discipline = deviceGroup != null
? holderSystemDeviceStructure.findDisciplineByUuid(deviceGroup.getParentUuid())
? holderStructures.findDisciplineById(deviceGroup.getParentId())
: null;
return discipline != null && deviceGroup != null
? discipline.getMnemonic() + "-" + deviceType.getMnemonic()
: deviceType.getMnemonic();
: null;
}
// ---------------------------------------------------
// --------------------------------------------------
/**
* Return a list of mnemonic paths for system groups.
*
* @param holder holder of containers for system and device structure content
* @param holderStructures holder of system and device structure content
* @param mnemonicEquivalence use mnemonic equivalence instead of mnemonic
* @param namingConvention naming convention
* @return a list of mnemonic paths for system groups
*/
public static List<String> getMnemonicPathsSystemGroup(HolderSystemDeviceStructure holder, boolean mnemonicEquivalence, EssNamingConvention namingConvention) {
public static List<String> getMnemonicPathsSystemGroup(HolderStructures holderStructures, boolean mnemonicEquivalence, EssNamingConvention namingConvention) {
List<String> mnemonicPaths = new ArrayList<>();
String value = null;
for (Entry<UUID, SystemGroup> entry : holder.getUuidSystemGroups().entrySet()) {
for (Entry<Long, SystemGroup> entry : holderStructures.getIdSystemGroups().entrySet()) {
if (!StringUtils.isEmpty(entry.getValue().getMnemonic())) {
value = entry.getValue().getMnemonic();
}
......@@ -156,21 +181,16 @@ public class StructureUtil {
/**
* Return a list of mnemonic paths for systems.
*
* @param holder holder of containers for system and device structure content
* @param holderStructures holder of system and device structure content
* @param mnemonicEquivalence use mnemonic equivalence instead of mnemonic
* @param namingConvention naming convention
* @return a list of mnemonic paths for systems
*/
public static List<String> getMnemonicPathsSystem(HolderSystemDeviceStructure holder, boolean mnemonicEquivalence, EssNamingConvention namingConvention) {
public static List<String> getMnemonicPathsSystem(HolderStructures holderStructures, boolean mnemonicEquivalence, EssNamingConvention namingConvention) {
List<String> mnemonicPaths = new ArrayList<>();
String value = null;
for (Entry<UUID, System> entry : holder.getUuidSystems().entrySet()) {
SystemGroup systemGroup = holder.findSystemGroupByUuid(entry.getValue().getParentUuid());
if (!StringUtils.isEmpty(systemGroup.getMnemonic())) {
value = systemGroup.getMnemonic() + "-" + entry.getValue().getMnemonic();
} else {
value = entry.getValue().getMnemonic();
}
for (Entry<Long, System> entry : holderStructures.getIdSystems().entrySet()) {
value = entry.getValue().getMnemonic();
if (mnemonicEquivalence) {
mnemonicPaths.add(namingConvention.equivalenceClassRepresentative(value));
......@@ -184,22 +204,17 @@ public class StructureUtil {
/**
* Return a list of mnemonic paths for subsystems.
*
* @param holder holder of containers for system and device structure content
* @param holderStructures holder of system and device structure content
* @param mnemonicEquivalence use mnemonic equivalence instead of mnemonic
* @param namingConvention naming convention
* @return a list of mnemonic paths for subsystems
*/
public static List<String> getMnemonicPathsSubsystem(HolderSystemDeviceStructure holder, boolean mnemonicEquivalence, EssNamingConvention namingConvention) {
public static List<String> getMnemonicPathsSubsystem(HolderStructures holderStructures, boolean mnemonicEquivalence, EssNamingConvention namingConvention) {
List<String> mnemonicPaths = new ArrayList<>();
String value = null;
for (Entry<UUID, Subsystem> entry : holder.getUuidSubsystems().entrySet()) {
System system = holder.findSystemByUuid(entry.getValue().getParentUuid());
SystemGroup systemGroup = holder.findSystemGroupByUuid(system.getParentUuid());
if (!StringUtils.isEmpty(systemGroup.getMnemonic())) {
value = systemGroup.getMnemonic() + "-" + system.getMnemonic() + "-" + entry.getValue().getMnemonic();
} else {
value = system.getMnemonic() + "-" + entry.getValue().getMnemonic();
}
for (Entry<Long, Subsystem> entry : holderStructures.getIdSubsystems().entrySet()) {
System system = holderStructures.findSystemById(entry.getValue().getParentId());
value = system.getMnemonic() + "-" + entry.getValue().getMnemonic();
if (mnemonicEquivalence) {
mnemonicPaths.add(namingConvention.equivalenceClassRepresentative(value));
......@@ -213,15 +228,15 @@ public class StructureUtil {
/**
* Return a list of mnemonic paths for disciplines.
*
* @param holder holder of containers for system and device structure content
* @param holderStructures holder of system and device structure content
* @param mnemonicEquivalence use mnemonic equivalence instead of mnemonic
* @param namingConvention naming convention
* @return a list of mnemonic paths for disciplines
*/
public static List<String> getMnemonicPathsDiscipline(HolderSystemDeviceStructure holder, boolean mnemonicEquivalence, EssNamingConvention namingConvention) {
public static List<String> getMnemonicPathsDiscipline(HolderStructures holderStructures, boolean mnemonicEquivalence, EssNamingConvention namingConvention) {
List<String> mnemonicPaths = new ArrayList<>();
String value = null;
for (Entry<UUID, Discipline> entry : holder.getUuidDisciplines().entrySet()) {
for (Entry<Long, Discipline> entry : holderStructures.getIdDisciplines().entrySet()) {
if (!StringUtils.isEmpty(entry.getValue().getMnemonic())) {
value = entry.getValue().getMnemonic();
}
......@@ -238,17 +253,17 @@ public class StructureUtil {
/**
* Return a list of mnemonic paths for device types.
*
* @param holder holder of containers for system and device structure content
* @param holderStructures holder of system and device structure content
* @param mnemonicEquivalence use mnemonic equivalence instead of mnemonic
* @param namingConvention naming convention
* @return a list of mnemonic paths for device types
*/
public static List<String> getMnemonicPathsDeviceType(HolderSystemDeviceStructure holder, boolean mnemonicEquivalence, EssNamingConvention namingConvention) {
public static List<String> getMnemonicPathsDeviceType(HolderStructures holderStructures, boolean mnemonicEquivalence, EssNamingConvention namingConvention) {
List<String> mnemonicPaths = new ArrayList<>();
String value = null;
for (Entry<UUID, DeviceType> entry : holder.getUuidDeviceTypes().entrySet()) {
DeviceGroup deviceGroup = holder.findDeviceGroupByUuid(entry.getValue().getParentUuid());
Discipline discipline = holder.findDisciplineByUuid(deviceGroup.getParentUuid());
for (Entry<Long, DeviceType> entry : holderStructures.getIdDeviceTypes().entrySet()) {
DeviceGroup deviceGroup = holderStructures.findDeviceGroupById(entry.getValue().getParentId());
Discipline discipline = holderStructures.findDisciplineById(deviceGroup.getParentId());
value = discipline.getMnemonic() + "-" + entry.getValue().getMnemonic();
if (mnemonicEquivalence) {
......@@ -260,4 +275,50 @@ public class StructureUtil {
return mnemonicPaths;
}
// --------------------------------------------------
protected static List<UUID> listSystemGroup2Uuid(List<SystemGroup> systemGroups) {
final List<UUID> listUuid = Lists.newArrayList();
for (SystemGroup systemGroup : systemGroups) {
listUuid.add(systemGroup.getUuid());
}
return listUuid;
}
protected static List<UUID> listSystem2Uuid(List<System> systems) {
final List<UUID> listUuid = Lists.newArrayList();
for (System deviceType : systems) {
listUuid.add(deviceType.getUuid());
}
return listUuid;
}
protected static List<UUID> listSubsystem2Uuid(List<Subsystem> subsystems) {
final List<UUID> listUuid = Lists.newArrayList();
for (Subsystem subsystem : subsystems) {
listUuid.add(subsystem.getUuid());
}
return listUuid;
}
protected static List<UUID> listDiscipline2Uuid(List<Discipline> disciplines) {
final List<UUID> listUuid = Lists.newArrayList();
for (Discipline discipline : disciplines) {
listUuid.add(discipline.getUuid());
}
return listUuid;
}
protected static List<UUID> listDeviceGroup2Uuid(List<DeviceGroup> deviceGroups) {
final List<UUID> listUuid = Lists.newArrayList();
for (DeviceGroup deviceGroup : deviceGroups) {
listUuid.add(deviceGroup.getUuid());
}
return listUuid;
}
protected static List<UUID> listDeviceType2Uuid(List<DeviceType> deviceTypes) {
final List<UUID> listUuid = Lists.newArrayList();
for (DeviceType deviceType : deviceTypes) {
listUuid.add(deviceType.getUuid());
}
return listUuid;
}
}