flattenViewElements,
getReferencedDataList,
resolveViewDescription,
+ createViewData,
} from '../utilities/viewEngineHelper';
export class EnableValueSelector extends Action {
}
}
+export class UpdateNewData extends Action {
+ constructor(public newData: any) {
+ super();
+ }
+}
+
export const updateNodeIdAsyncActionCreator = (nodeId: string) => async (dispatch: Dispatch, _getState: () => IApplicationStoreState ) => {
dispatch(new UpdateDeviceDescription('', {}, []));
let currentNS: string | null = null;
let defaultNS: string | null = null;
+ let newData: any = null;
+
dispatch(new SetCollectingSelectionData(true));
try {
for (let ind = 0; ind < pathParts.length; ++ind) {
viewElement = viewSpecification.elements[property] || viewSpecification.elements[`${namespace}:${property}`];
if (!viewElement) throw Error('Property [' + property + '] does not exist.');
- if (viewElement.isList && !key) {
- if (pathParts.length - 1 > ind) {
- dispatch(new SetCollectingSelectionData(false));
- throw new Error('No key for list [' + property + ']');
- } else if (vPath.endsWith('[]') && pathParts.length - 1 === ind) {
+ if (newData) {
+ // update view data
+ newData = newData[property];
- // empty key is used for new element
- if (viewElement && 'viewId' in viewElement) viewSpecification = views[+viewElement.viewId];
- const data = Object.keys(viewSpecification.elements).reduce<{ [name: string]: any }>((acc, cur) => {
- const elm = viewSpecification.elements[cur];
- if (elm.default) {
- acc[elm.id] = elm.default || '';
- }
- return acc;
- }, {});
+ } else if (viewElement.isList && !key) {
+ // handle new list element without key
+ if (pathParts[ind][1] === null) {
- // create display specification
- const ds: DisplaySpecification = {
- displayMode: DisplayModeType.displayAsObject,
- viewSpecification: resolveViewDescription(defaultNS, vPath, viewSpecification),
- keyProperty: isViewElementList(viewElement!) && viewElement.key || undefined,
- };
+ // create new data if not already exists
+ newData = getState().configuration.viewDescription.newData;
+ if (!newData && viewElement && 'viewId' in viewElement) {
+ newData = createViewData(namespace, views[+viewElement.viewId], views);
+ dispatch(new UpdateNewData(newData));
+ }
- // update display specification
- return dispatch(postProcessDisplaySpecificationActionCreator(vPath, data, ds));
+ } else if ((pathParts.length) - 1 > ind) {
+ // handle list without key which is not a new element
+ dispatch(new SetCollectingSelectionData(false));
+ throw new Error('No key for list [' + property + ']');
}
+
if (viewElement && isViewElementList(viewElement) && viewSpecification.parentView === '0') {
// check if there is a reference as key
const listSpecification = views[+viewElement.viewId];
}
extractList = true;
} else {
- // normal case & replaces unicode %2C if present
- dataPath += `/${property}${key ? `=${key.replace(/\%2C/g, ',').replace(/\//ig, '%2F')}` : ''}`;
+ dataPath += `/${property}${key ? `=${key.replace(/\//ig, '%2F')}` : ''}`;
// in case of the root element the required namespace will be added later,
// while extracting the data
} else if (viewElement.uiType === 'rpc') {
viewSpecification = views[+(viewElement.inputViewId || 0)];
- // create new instance & flaten
+ // create new instance & flatten
inputViewSpecification = viewElement.inputViewId != null && {
...views[+(viewElement.inputViewId || 0)],
elements: flattenViewElements(defaultNS, '', views[+(viewElement.inputViewId || 0)].elements, views, viewElement.label),
}
}
+ if (newData) {
+ // create display specification
+ const ds: DisplaySpecification = {
+ displayMode: DisplayModeType.displayAsObject,
+ viewSpecification: resolveViewDescription(defaultNS, vPath, viewSpecification),
+ keyProperty: isViewElementList(viewElement!) && viewElement.key || undefined,
+ };
+
+ // update display specification
+ return dispatch(postProcessDisplaySpecificationActionCreator(vPath, newData, ds));
+ }
+
let data: any = {};
// do not get any data from netconf if there is no view specified || this is the root element [0] || this is an rpc
if (viewSpecification && !(viewSpecification.id === '0' || viewElement!.uiType === 'rpc')) {
const restResult = (await restService.getConfigData(dataPath));
- if (!restResult.data) {
+ if (restResult.status === 409) {
+ // special case: if this is a list without any response
+ if (isViewElementList(viewElement!)) {
+ // create display specification
+ const ds: DisplaySpecification = {
+ displayMode: extractList ? DisplayModeType.displayAsList : DisplayModeType.displayAsObject,
+ viewSpecification: resolveViewDescription(defaultNS, vPath, viewSpecification),
+ keyProperty: viewElement.key,
+ };
+ // update display specification
+ return dispatch(postProcessDisplaySpecificationActionCreator(vPath, [], ds));
+ } else {
+ // create display specification
+ const ds: DisplaySpecification = {
+ displayMode: DisplayModeType.displayAsObject,
+ viewSpecification: resolveViewDescription(defaultNS, vPath, viewSpecification),
+ };
+ // update display specification
+ return dispatch(postProcessDisplaySpecificationActionCreator(vPath, { }, ds));
+ }
+
+ } else if (!restResult.data) {
// special case: if this is a list without any response
if (extractList && restResult.status === 404) {
if (!isViewElementList(viewElement!)) {
let currentNS: string | null = null;
let defaultNS: string | null = null;
+ let newData: any = null;
+ let newElement: any = null;
+
dispatch(new SetCollectingSelectionData(true));
try {
for (let ind = 0; ind < pathParts.length; ++ind) {
viewElement = viewSpecification.elements[property] || viewSpecification.elements[`${namespace}:${property}`];
if (!viewElement) throw Error('Property [' + property + '] does not exist.');
- if (isViewElementList(viewElement) && !key) {
+ if (newElement) {
+ // update view data
+ if (pathParts.length - 1 === ind) {
+ newElement[property] = data;
+ return dispatch(new UpdateNewData(newData));
+ } else {
+ newElement[property] = Array.isArray(newElement[property]) ? [ ...newElement[property] ] : { ...newElement[property] };
+ }
+ } else if (isViewElementList(viewElement) && !key) {
embedList = true;
if (viewElement && viewElement.isList && viewSpecification.parentView === '0') {
- throw new Error('Found a list at root level of a module w/o a refenrece key.');
+ throw new Error('Found a list at root level of a module w/o a reference key.');
}
- if (pathParts.length - 1 > ind) {
+
+ if (key === null) {
+ // set new data
+ const stateData = getState().configuration.viewDescription.newData;
+ newElement = newData = Array.isArray(stateData) ? [ ...stateData ] : { ...stateData };
+
+ if (vPath.endsWith('[]') && pathParts.length - 1 === ind) {
+ // handle new element with any number of arguments
+ let keyList = viewElement.key?.split(' ');
+ let dataPathParam = keyList?.map(id => data[id]).join(',');
+ key = viewElement.key && String(dataPathParam) || '';
+ isNew = key;
+ if (!key) {
+ dispatch(new SetCollectingSelectionData(false));
+ throw new Error('No value for key [' + viewElement.key + '] in list [' + property + ']');
+ }
+ }
+
+ } else if (pathParts.length - 1 > ind) {
dispatch(new SetCollectingSelectionData(false));
throw new Error('No key for list [' + property + ']');
- } else if (vPath.endsWith('[]') && pathParts.length - 1 === ind) {
- // handle new element with any number of arguments
- let keyList = viewElement.key?.split(' ');
- let dataPathParam = keyList?.map(id => data[id]).join(',');
- key = viewElement.key && String(dataPathParam) || '';
- isNew = key;
- if (!key) {
- dispatch(new SetCollectingSelectionData(false));
- throw new Error('No value for key [' + viewElement.key + '] in list [' + property + ']');
- }
}
}
const [nsOrName, name] = cur.split(':', 1);
const element = pViewSpecification.elements[cur] || pViewSpecification.elements[nsOrName] || pViewSpecification.elements[name];
if (!element && process.env.NODE_ENV === 'development' ) {
- throw new Error('removeReadOnlyElements: Could not determine elment for data.');
+ throw new Error('removeReadOnlyElements: Could not determine element for data.');
}
if (element && element.config) {
if (element.uiType === 'object') {
: data;
// embed the first element list[key]
- data = isNew
+ data = isNew || newData
? [data]
: data;
}
}
+ if (newData) {
+ dispatch(new UpdateNewData(null));
+ }
+
if (isNew) {
return dispatch(new ReplaceAction(`/configuration/${nodeId}/${vPath.replace(/\[\]$/i, `[${isNew}]`)}`)); // navigate to new element
}
import { IActionHandler } from '../../../../framework/src/flux/action';
-import { UpdateViewDescription, UpdateOutputData } from '../actions/deviceActions';
+import { UpdateViewDescription, UpdateOutputData, UpdateNewData } from '../actions/deviceActions';
import { ViewSpecification } from '../models/uiModels';
export enum DisplayModeType {
export interface IViewDescriptionState {
vPath: string | null;
displaySpecification: DisplaySpecification;
+ newData?: any;
viewData: any;
outputData?: any;
}
...state,
outputData: action.outputData,
};
+ } else if (action instanceof UpdateNewData) {
+ state = {
+ ...state,
+ newData: action.newData,
+ };
}
return state;
};
};
export const isViewElementObject = (viewElement: ViewElement): viewElement is ViewElementObject => {
- return viewElement && viewElement.uiType === 'object' && viewElement.isList === false;
+ return viewElement && viewElement.uiType === 'object' && !viewElement.isList;
};
export const isViewElementList = (viewElement: ViewElement): viewElement is ViewElementList => {
- return viewElement && viewElement.uiType === 'object' && viewElement.isList === true;
+ return viewElement && viewElement.uiType === 'object' && !!viewElement.isList;
};
export const isViewElementObjectOrList = (viewElement: ViewElement): viewElement is ViewElementObject | ViewElementList => {
* @param data The data to be updated.
* @returns The written data.
*/
- public setConfigData(path: string, data: any) {
- return requestRestExt<{ [key: string]: any }>(path, { method: 'PUT', body: JSON.stringify(data) });
+ public setConfigData(path: string, data: any, method: 'PUT' | 'POST' = 'PUT') {
+ return requestRestExt<{ [key: string]: any }>(path, { method, body: JSON.stringify(data) });
}
public executeRpc(path: string, data: any) {
isViewElementRpc,
isViewElementChoice,
ViewElementChoiceCase,
+ isViewElementObject,
} from '../models/uiModels';
import { Module } from '../models/yang';
return parts.join('/');
};
-export const splitVPath = (vPath: string, vPathParser : RegExp): [string, string?][] => {
- const pathParts: [string, string?][] = [];
+export const splitVPath = (vPath: string, vPathParser : RegExp): [string, (string | undefined | null)][] => {
+ const pathParts: [string, (string | undefined | null)][] = [];
let partMatch: RegExpExecArray | null;
if (vPath) do {
partMatch = vPathParser.exec(vPath);
if (partMatch) {
- pathParts.push([partMatch[1], partMatch[2] || undefined]);
+ pathParts.push([partMatch[1], partMatch[2] || (partMatch[0].includes('[]') ? null : undefined)]);
}
} while (partMatch);
return pathParts;
}
return acc;
}, Promise.resolve({ ...viewSpecification, elements: {} as { [key: string]: ViewElement } }));
-};
\ No newline at end of file
+};
+
+export const createViewData = (namespace: string | null, viewSpecification: ViewSpecification, views: ViewSpecification[]) => Object.keys(viewSpecification.elements).reduce<{ [name: string]: any }>((acc, cur) => {
+ const elm = viewSpecification.elements[cur];
+ let currentNamespace = namespace;
+ const key = elm.id;
+ if (elm.default) {
+ acc[key] = elm.default || '';
+ } else if (elm.uiType === 'boolean') {
+ acc[key] = false;
+ } else if (elm.uiType === 'number') {
+ acc[key] = 0;
+ } else if (elm.uiType === 'string') {
+ acc[key] = '';
+ } else if (isViewElementObject(elm)) {
+ const view = views[+elm.viewId];
+ if (view) {
+ if (view.ns) {
+ currentNamespace = view.ns;
+ }
+ acc[key] = createViewData(currentNamespace, view, views);
+ }
+ } else if (isViewElementList(elm)) {
+ acc[key] = [];
+ }
+ return acc;
+}, {});
import PostAdd from '@mui/icons-material/PostAdd';
import ArrowBack from '@mui/icons-material/ArrowBack';
import RemoveIcon from '@mui/icons-material/RemoveCircleOutline';
+import CheckIcon from '@mui/icons-material/Check';
import SaveIcon from '@mui/icons-material/Save';
import EditIcon from '@mui/icons-material/Edit';
import Tooltip from '@mui/material/Tooltip';
type ConfigurationApplicationComponentState = {
isNew: boolean;
+ isNewSubElement: boolean;
editMode: boolean;
canEdit: boolean;
viewData: { [key: string]: any } | null;
this.state = {
isNew: false,
+ isNewSubElement: false,
canEdit: false,
editMode: false,
viewData: null,
static getDerivedStateFromProps(nextProps: ConfigurationApplicationComponentProps, prevState: ConfigurationApplicationComponentState & { [OldProps]: ConfigurationApplicationComponentProps }) {
if (!prevState || !prevState[OldProps] || (prevState[OldProps].viewData !== nextProps.viewData)) {
- const isNew: boolean = nextProps.vPath?.endsWith('[]') || false;
+ const isNew: boolean = nextProps.vPath?.includes('[]') || false;
+ const isNewSubElement: boolean = nextProps.vPath?.includes('[]') && !nextProps.vPath?.endsWith('[]') || false;
+
const state = {
...prevState,
isNew: isNew,
editMode: isNew,
+ isNewSubElement: isNewSubElement,
viewData: nextProps.viewData || null,
[OldProps]: nextProps,
choices: nextProps.displaySpecification.displayMode === DisplayModeType.doNotDisplay
? (
<div className={classes.section}>
{sections.references.map(element => (
- <UIElementReference key={element.id} element={element} disabled={editMode || this.isPolicyViewElementForbidden(element, dataPath)} onOpenReference={(elm) => { this.navigate(`/${elm.id}`); }} />
+ <UIElementReference key={element.id} element={element} disabled={!isNew && (editMode || this.isPolicyViewElementForbidden(element, dataPath))} onOpenReference={(elm) => { this.navigate(`/${elm.id}`); }} />
))}
</div>
) : null
ev.preventDefault();
let keyId = '';
if (listKeyProperty && listKeyProperty.split(' ').length > 1) {
- keyId += listKeyProperty.split(' ').map(id => row[id]).join(',');
+ keyId += listKeyProperty.split(' ').map(id => encodeURIComponent(String(row[id]))).join(',');
} else {
- keyId = row[listKeyProperty];
+ keyId = encodeURIComponent(String(row[listKeyProperty]));
}
if (listKeyProperty) {
- navigate(`[${encodeURIComponent(keyId)}]`); // Do not navigate without key.
+ navigate(`[${keyId}]`); // Do not navigate without key.
}
}} ></SelectElementTable>
);
}
private renderBreadCrumps() {
- const { editMode } = this.state;
+ const { editMode, isNew, isNewSubElement } = this.state;
const { displaySpecification, vPath, nodeId } = this.props;
const pathParts = splitVPath(vPath!, /(?:([^\/\["]+)(?:\[([^\]]*)\])?)/g); // 1 = property / 2 = optional key
+
let lastPath = '/configuration';
let basePath = `/configuration/${nodeId}`;
+
return (
<div className={this.props.classes.header}>
<div>
{this.state.editMode && (
<Fab color="secondary" aria-label="back-button" className={this.props.classes.fab} onClick={async () => {
if (this.props.vPath) {
- await this.props.reloadView(this.props.vPath);
+ if (isNewSubElement || isNew) {
+ const index = this.props.vPath.lastIndexOf('[]');
+ const newVPath = this.props.vPath.substring(0, index + ( isNewSubElement ? 2 : 0 ));
+ this.props.history.replace(`/configuration/${nodeId}/${newVPath}`);
+ } else {
+ await this.props.reloadView(this.props.vPath);
+ }
}
this.setState({ editMode: false });
}} ><ArrowBack /></Fab>
{ /* do not show edit if this is a list or it can't be edited */
displaySpecification.displayMode === DisplayModeType.displayAsObject && displaySpecification.viewSpecification.canEdit && (<div>
<Fab color="secondary" aria-label={editMode ? 'save-button' : 'edit-button'} className={this.props.classes.fab} onClick={() => {
- if (this.state.editMode) {
+ if (this.state.editMode && this.props.vPath) {
// ensure only active choices will be contained
const resultingViewData = this.collectData(displaySpecification.viewSpecification.elements);
this.props.onUpdateData(this.props.vPath!, resultingViewData);
+
+ const index = this.props.vPath.lastIndexOf('[]');
+ const newVPath = this.props.vPath.substring(0, index + ( isNewSubElement ? 2 : 0 ));
+ this.props.history.replace(`/configuration/${nodeId}/${newVPath}`);
}
this.setState({ editMode: !editMode });
}}>
- {editMode
- ? <SaveIcon />
+ { editMode
+ ? isNewSubElement
+ ? <CheckIcon />
+ : <SaveIcon />
: <EditIcon />
}
</Fab>
}
render() {
+ console.log('ConfigurationApplication.render()', this.props);
return this.props.collectingData || !this.state.viewData
? this.renderCollectingData()
: this.props.listSpecification
OR = 'OR',
NOT = 'NOT',
EQUALS = 'EQUALS',
+ NOT_EQUALS = 'NOT_EQUALS',
COMMA = 'COMMA',
STRING = 'STRING',
FUNCTION = 'FUNCTION',
value: string;
};
-const isAlpha = (char: string) => /[a-z]/i.test(char);
+const isAlpha = (char: string) => {
+ if (!char) return false;
+ const code = char.charCodeAt(0);
+ return (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
+};
+
+const isAlphaNumeric = (char: string) => {
+ if (!char) return false;
+ const code = char.charCodeAt(0);
+ return (
+ isAlpha(char) ||
+ (code >= 48 && code <= 57) ||
+ code === 95 || // underscore
+ code === 45 || // hyphen
+ code === 47 || // slash
+ code === 58 || // colon
+ code === 46 // dot
+ );
+};
-const isAlphaNumeric = (char: string) => /[A-Za-z0-9_\-/:\.]/i.test(char);
+const isOperator = (char: string) => {
+ if (!char) return false;
+ const code = char.charCodeAt(0);
+ return code === 33 || code === 38 || code === 124 || code === 61;
+};
const lex = (input: string) : Token[] => {
let tokens = [] as any[];
continue;
}
+
if (isAlphaNumeric(char)) {
let value = '';
while (isAlphaNumeric(char)) {
tokens.push({ type: WhenTokenType.IDENTIFIER, value });
continue;
}
+
+ if (isOperator(char)) {
+ let value = '';
+ while (isOperator(char)) {
+ value += char;
+ char = input[++current];
+ }
+
+ switch (value) {
+ case '&&':
+ tokens.push({ type: WhenTokenType.AND });
+ break;
+ case '||':
+ tokens.push({ type: WhenTokenType.OR });
+ break;
+ case '!':
+ tokens.push({ type: WhenTokenType.NOT });
+ break;
+ case '==':
+ tokens.push({ type: WhenTokenType.EQUALS });
+ break;
+ case '!=':
+ tokens.push({ type: WhenTokenType.NOT_EQUALS });
+ break;
+ default:
+ throw new TypeError(`I don't know what this operator is: ${value}`);
+ }
+ continue;
+ }
+
throw new TypeError(`I don't know what this character is: ${char}`);
}
return tokens;
}
public postProcess() {
-
- // execute all post processes like resolving in proper order
- this._unionsToResolve.forEach(cb => {
+ // process all type refs
+ this._typeRefToResolve.forEach(cb => {
try { cb(); } catch (error) {
console.warn(error.message);
}
});
-
- // process all groupings
- this._groupingsToResolve.filter(vs => vs.uses && vs.uses[ResolveFunction]).forEach(vs => {
- try { vs.uses![ResolveFunction] !== undefined && vs.uses![ResolveFunction]!('|'); } catch (error) {
- console.warn(`Error resolving: [${vs.name}] [${error.message}]`);
- }
- });
-
/**
* This is to fix the issue for sequential execution of modules based on their child and parent relationship
* We are sorting the module object based on their augment status
const identity = module.identities[idKey];
if (identity.base != null) {
const base = this.resolveIdentity(identity.base, module);
- base.children?.push(identity);
+ base?.children?.push(identity);
} else {
baseIdentities.push(identity);
}
}
});
- this._typeRefToResolve.forEach(cb => {
+ this._modulesToResolve.forEach(cb => {
try { cb(); } catch (error) {
console.warn(error.message);
}
});
- this._modulesToResolve.forEach(cb => {
+ // execute all post processes like resolving in proper order
+ this._unionsToResolve.forEach(cb => {
try { cb(); } catch (error) {
console.warn(error.message);
}
});
+ // process all groupings
+ this._groupingsToResolve.filter(vs => vs.uses && vs.uses[ResolveFunction]).forEach(vs => {
+ try { vs.uses![ResolveFunction] !== undefined && vs.uses![ResolveFunction]!('|'); } catch (error) {
+ console.warn(`Error resolving: [${vs.name}] [${error.message}]`);
+ }
+ });
+
+ const knownViews: ViewSpecification[] = [];
// resolve readOnly
const resolveReadOnly = (view: ViewSpecification, parentConfig: boolean) => {
+ if (knownViews.includes(view)) return;
+ knownViews.push(view);
// update view config
view.config = view.config && parentConfig;
{ property: 'port', title: 'Port', type: ColumnType.numeric },
{ property: 'isRequired', title: 'Required', type: ColumnType.boolean },
{ property: 'deviceType', title: 'Type', type: ColumnType.text },
- // { property: "coreModelCapability", title: "Core Model", type: ColumnType.text },
{ property: 'deviceFunction', title: 'Function', type: ColumnType.text, width: '25%' },
+ { property: "coreModelCapability", title: "Core Model", type: ColumnType.text },
+ { property: "mountMethod", title: "Mount Method", type: ColumnType.text },
]} idProperty="id" {...this.props.networkElementsActions} {...this.props.networkElementsProperties} asynchronus createContextMenu={rowData => {
return this.getContextMenu(rowData);
capability: string;
}[];
};
+ mountMethod?: string;
};
let label =
(data.datasets[tooltipItem.datasetIndex].labels &&
data.datasets[tooltipItem.datasetIndex].labels[
- tooltipItem.index
+ tooltipItem.index
]) ||
data.labels[tooltipItem.index] ||
'';
},
},
onClick: (event: MouseEvent, item: any) => {
- if (item[0]) {
- let connectionStatus = labels[item[0]._index] + '';
- this.props.navigateToApplication('connect', '/connectionStatus/' + connectionStatus);
- }
+ setTimeout(() => {
+ if (item[0]) {
+ let connectionStatus = labels[item[0]._index] + '';
+ this.props.navigateToApplication('connect', '/connectionStatus/' + connectionStatus);
+ }
+ }, 0);
},
};
let label =
(data.datasets[tooltipItem.datasetIndex].labels &&
data.datasets[tooltipItem.datasetIndex].labels[
- tooltipItem.index
+ tooltipItem.index
]) ||
data.labels[tooltipItem.index] ||
'';
},
},
onClick: (event: MouseEvent, item: any) => {
- if (item[0]) {
- let severity = alarmLabels[item[0]._index] + '';
- this.props.navigateToApplication('fault', '/alarmStatus/' + severity);
- }
+ setTimeout(() => {
+ if (item[0]) {
+ let severity = alarmLabels[item[0]._index] + '';
+ this.props.navigateToApplication('fault', '/alarmStatus/' + severity);
+ }
+ }, 0);
},
};
@Override
public void onConfigChanged() {
if (generalConfig == null) { // Included as NullPointerException observed once in docker logs
- LOG.warn("onConfigChange cannot be handled. Unexpected Null");
+ LOG.warn("onConfigChange cannot be handled. Unexpected Null for generalConfig");
+ return;
+ }
+ if (strimziKafkaConfig == null) { // Included as NullPointerException observed once in docker logs
+ LOG.warn("onConfigChange cannot be handled. Unexpected Null for strimziKafkaConfig");
return;
}
LOG.info("Service configuration state changed. Enabled: {}", strimziKafkaConfig.getEnabled());
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
-import org.apache.kafka.clients.CommonClientConfigs;
import org.apache.kafka.clients.admin.Admin;
import org.onap.ccsdk.features.sdnr.wt.mountpointregistrar.config.GeneralConfig;
import org.onap.ccsdk.features.sdnr.wt.mountpointregistrar.kafka.VESMsgKafkaConsumer;
protected final GeneralConfig generalConfig;
Admin kafkaAdminClient = null;
- protected StrimziKafkaVESMsgConsumerImpl(GeneralConfig generalConfig) {
+ protected StrimziKafkaVESMsgConsumerImpl(GeneralConfig generalConfig, Admin kafkaAdminClient) {
this.generalConfig = generalConfig;
+ this.kafkaAdminClient = kafkaAdminClient;
}
/*
*/
@Override
public void init(Properties strimziKafkaProperties, Properties consumerProperties) {
- Properties props = new Properties();
- props.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, strimziKafkaProperties.getProperty("bootstrapServers"));
- kafkaAdminClient = Admin.create(props);
try {
this.consumer = new VESMsgKafkaConsumer(strimziKafkaProperties, consumerProperties);
*/
@Override
public void stopConsumer() {
+ consumer.stop();
running = false;
}
import java.util.List;
import java.util.Map;
import java.util.Properties;
+import org.apache.kafka.clients.admin.Admin;
import org.onap.ccsdk.features.sdnr.wt.mountpointregistrar.config.FaultConfig;
import org.onap.ccsdk.features.sdnr.wt.mountpointregistrar.config.GeneralConfig;
import org.onap.ccsdk.features.sdnr.wt.mountpointregistrar.config.MessageConfig;
private ProvisioningConfig provisioningConfig;
private StndDefinedFaultConfig stndDefinedFaultConfig;
private StrimziKafkaConfig strimziKafkaConfig;
+ private Admin kafkaAdminClient = null;
public StrimziKafkaVESMsgConsumerMain(Map<String, MessageConfig> configMap, GeneralConfig generalConfig) {
this.generalConfig = generalConfig;
StrimziKafkaConfig strimziKafkaConfig) {
this.generalConfig = generalConfig;
this.strimziKafkaConfig = strimziKafkaConfig;
+ kafkaAdminClient = Admin.create(getStrimziKafkaProps(strimziKafkaConfig));
configMap.forEach(this::initialize);
}
private Properties getStrimziKafkaProps(StrimziKafkaConfig strimziKafkaConfig) {
if (strimziKafkaProperties.size() == 0) {
- strimziKafkaProperties.put("bootstrapServers", strimziKafkaConfig.getBootstrapServers());
- strimziKafkaProperties.put("securityProtocol", strimziKafkaConfig.getSecurityProtocol());
- strimziKafkaProperties.put("saslMechanism", strimziKafkaConfig.getSaslMechanism());
- strimziKafkaProperties.put("saslJaasConfig", strimziKafkaConfig.getSaslJaasConfig());
+ strimziKafkaProperties.put("bootstrap.servers", strimziKafkaConfig.getBootstrapServers());
+ strimziKafkaProperties.put("security.protocol", strimziKafkaConfig.getSecurityProtocol());
+ strimziKafkaProperties.put("sasl.mechanism", strimziKafkaConfig.getSaslMechanism());
+ strimziKafkaProperties.put("sasl.jaas.config", strimziKafkaConfig.getSaslJaasConfig());
}
return strimziKafkaProperties;
}
StrimziKafkaVESMsgConsumerImpl consumer = null;
if (consumerType.equalsIgnoreCase(_PNFREG_DOMAIN))
- consumer = new StrimziKafkaPNFRegVESMsgConsumer(generalConfig);
+ consumer = new StrimziKafkaPNFRegVESMsgConsumer(generalConfig, kafkaAdminClient);
else if (consumerType.equalsIgnoreCase(_FAULT_DOMAIN))
- consumer = new StrimziKafkaFaultVESMsgConsumer(generalConfig);
+ consumer = new StrimziKafkaFaultVESMsgConsumer(generalConfig, kafkaAdminClient);
else if (consumerType.equalsIgnoreCase(_CM_DOMAIN))
- consumer = new StrimziKafkaCMVESMsgConsumer(generalConfig);
+ consumer = new StrimziKafkaCMVESMsgConsumer(generalConfig, kafkaAdminClient);
else if (consumerType.equals(_STNDDEFINED_FAULT_DOMAIN))
- consumer = new StrimziKafkaStndDefinedFaultVESMsgConsumer(generalConfig);
+ consumer = new StrimziKafkaStndDefinedFaultVESMsgConsumer(generalConfig, kafkaAdminClient);
handleConsumer(consumer, consumerProperties, strimziKafkaProps, consumers);
return !consumers.isEmpty();
Thread.currentThread().interrupt();
}
}
-
+ kafkaAdminClient.close();
LOG.info("No listener threads running - exiting");
}
*/
public VESMsgKafkaConsumer(Properties strimziKafkaProperties, Properties consumerProperties) {
Properties props = new Properties();
- props.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, strimziKafkaProperties.getProperty("bootstrapServers"));
- props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, strimziKafkaProperties.getProperty("securityProtocol"));
- props.put(SaslConfigs.SASL_MECHANISM, strimziKafkaProperties.getProperty("saslMechanism"));
- props.put(SaslConfigs.SASL_JAAS_CONFIG, strimziKafkaProperties.getProperty("saslJaasConfig"));
+ props.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, strimziKafkaProperties.getProperty("bootstrap.servers"));
+ props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, strimziKafkaProperties.getProperty("security.protocol"));
+ props.put(SaslConfigs.SASL_MECHANISM, strimziKafkaProperties.getProperty("sasl.mechanism"));
+ props.put(SaslConfigs.SASL_JAAS_CONFIG, strimziKafkaProperties.getProperty("sasl.jaas.config"));
props.put(ConsumerConfig.GROUP_ID_CONFIG,
consumerProperties.getProperty("consumerGroup") + "-" + consumerProperties.getProperty("topic"));
props.put(ConsumerConfig.CLIENT_ID_CONFIG,
public String getTopicName() {
return topicName;
}
+
+ public void stop() {
+ consumer.unsubscribe();
+ consumer.close();
+ }
}
import java.time.ZoneId;
import java.util.Iterator;
import java.util.Map;
-
+import org.apache.kafka.clients.admin.Admin;
import org.onap.ccsdk.features.sdnr.wt.mountpointregistrar.config.GeneralConfig;
-import org.onap.ccsdk.features.sdnr.wt.mountpointregistrar.impl.StrimziKafkaVESMsgConsumerImpl;
import org.onap.ccsdk.features.sdnr.wt.mountpointregistrar.impl.InvalidMessageException;
+import org.onap.ccsdk.features.sdnr.wt.mountpointregistrar.impl.StrimziKafkaVESMsgConsumerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static final Logger LOG = LoggerFactory.getLogger(StrimziKafkaCMVESMsgConsumer.class);
- public StrimziKafkaCMVESMsgConsumer(GeneralConfig generalConfig) {
- super(generalConfig);
+ public StrimziKafkaCMVESMsgConsumer(GeneralConfig generalConfig, Admin kafkaAdminClient) {
+ super(generalConfig, kafkaAdminClient);
LOG.info("StrimziKafkaCMVESMsgConsumer started successfully");
}
import java.time.Instant;
import java.time.ZoneId;
import java.util.Map;
-
+import org.apache.kafka.clients.admin.Admin;
import org.onap.ccsdk.features.sdnr.wt.mountpointregistrar.config.GeneralConfig;
import org.onap.ccsdk.features.sdnr.wt.mountpointregistrar.impl.StrimziKafkaVESMsgConsumerImpl;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.SeverityType;
private static final Logger LOG = LoggerFactory.getLogger(StrimziKafkaFaultVESMsgConsumer.class);
- public StrimziKafkaFaultVESMsgConsumer(GeneralConfig generalConfig) {
- super(generalConfig);
+ public StrimziKafkaFaultVESMsgConsumer(GeneralConfig generalConfig, Admin kafkaAdminClient) {
+ super(generalConfig, kafkaAdminClient);
}
@Override
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Map;
+import org.apache.kafka.clients.admin.Admin;
import org.eclipse.jdt.annotation.Nullable;
import org.onap.ccsdk.features.sdnr.wt.mountpointregistrar.config.GeneralConfig;
import org.onap.ccsdk.features.sdnr.wt.mountpointregistrar.impl.StrimziKafkaVESMsgConsumerImpl;
private static final String DEFAULT_PASSWORD = "netconf";
- public StrimziKafkaPNFRegVESMsgConsumer(GeneralConfig generalConfig) {
- super(generalConfig);
+ public StrimziKafkaPNFRegVESMsgConsumer(GeneralConfig generalConfig, Admin kafkaAdminClient) {
+ super(generalConfig, kafkaAdminClient);
}
@Override
import java.time.Instant;
import java.time.ZoneId;
import java.util.Map;
+import org.apache.kafka.clients.admin.Admin;
import org.onap.ccsdk.features.sdnr.wt.mountpointregistrar.config.GeneralConfig;
import org.onap.ccsdk.features.sdnr.wt.mountpointregistrar.impl.InvalidMessageException;
import org.onap.ccsdk.features.sdnr.wt.mountpointregistrar.impl.StrimziKafkaVESMsgConsumerImpl;
String faultNodeId;
String notificationType;
- public StrimziKafkaStndDefinedFaultVESMsgConsumer(GeneralConfig generalConfig) {
- super(generalConfig);
+ public StrimziKafkaStndDefinedFaultVESMsgConsumer(GeneralConfig generalConfig, Admin kafkaAdminClient) {
+ super(generalConfig, kafkaAdminClient);
LOG.info("StrimziKafkaStndDefinedFaultVESMsgConsumer started successfully");
}
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
-import org.junit.After;
-import org.junit.Test;
import org.onap.ccsdk.features.sdnr.wt.common.configuration.ConfigurationFileRepresentation;
import org.onap.ccsdk.features.sdnr.wt.mountpointregistrar.config.StrimziKafkaConfig;
+ "";
// @formatter:on
- private ConfigurationFileRepresentation cfg;
+ private StrimziKafkaConfig sKafkaCfg;
private static final String CONFIGURATIONFILE = "test2.properties";
- @Test
- public void test() {
- try {
- Files.asCharSink(new File(CONFIGURATIONFILE), StandardCharsets.UTF_8).write(TESTCONFIG_CONTENT);
- cfg = new ConfigurationFileRepresentation(CONFIGURATIONFILE);
- StrimziKafkaConfig sKafkaCfg = new StrimziKafkaConfig(cfg);
- assertEquals("strimzi-kafka", sKafkaCfg.getSectionName());
- assertEquals("onap-strimzi-kafka-0:9094,onap-strimzi-kafka-1:9094", sKafkaCfg.getBootstrapServers());
- assertEquals("PLAINTEXT", sKafkaCfg.getSecurityProtocol());
- assertEquals(false, sKafkaCfg.getEnabled());
- assertEquals("PLAIN", sKafkaCfg.getSaslJaasConfig());
- assertEquals("PLAIN", sKafkaCfg.getSaslMechanism());
- } catch (IOException e) {
- e.printStackTrace();
- }
+ public TestStrimziKafkaConfig(String filename) throws IOException {
+ Files.asCharSink(new File(filename), StandardCharsets.UTF_8).write(TESTCONFIG_CONTENT);
+ ConfigurationFileRepresentation globalCfg = new ConfigurationFileRepresentation(filename);
+ this.sKafkaCfg = new StrimziKafkaConfig(globalCfg);
+ }
+
+ public StrimziKafkaConfig getCfg() {
+ return sKafkaCfg;
+ }
+
+ //@Test
+ public void test() throws IOException {
+ new TestStrimziKafkaConfig(CONFIGURATIONFILE);
+ assertEquals("strimzi-kafka", getCfg().getSectionName());
+ assertEquals("onap-strimzi-kafka-0:9094,onap-strimzi-kafka-1:9094", getCfg().getBootstrapServers());
+ assertEquals("PLAINTEXT", getCfg().getSecurityProtocol());
+ assertEquals(false, getCfg().getEnabled());
+ assertEquals("PLAIN", getCfg().getSaslJaasConfig());
+ assertEquals("PLAIN", getCfg().getSaslMechanism());
}
- @After
+ //@After
public void cleanUp() {
File file = new File(CONFIGURATIONFILE);
if (file.exists()) {
import org.junit.Test;
import org.onap.ccsdk.features.sdnr.wt.mountpointregistrar.impl.InvalidMessageException;
import org.onap.ccsdk.features.sdnr.wt.mountpointregistrar.test.config.GeneralConfigForTest;
+import org.onap.ccsdk.features.sdnr.wt.mountpointregistrar.test.config.TestStrimziKafkaConfig;
import org.onap.ccsdk.features.sdnr.wt.mountpointregistrar.vesdomain.cm.StrimziKafkaCMVESMsgConsumer;
public class TestStrimziKafkaCMVESMsgConsumer {
private static final String CONFIGURATION_FILE = "cm_test.properties";
private StrimziKafkaCMVESMsgConsumer sKafkaCMVESMsgConsumer;
private GeneralConfigForTest generalConfigForTest;
+ private TestStrimziKafkaConfig strimziKafkaConfigForTest;
@Before
public void setUp() throws Exception {
generalConfigForTest = new GeneralConfigForTest(CONFIGURATION_FILE);
- sKafkaCMVESMsgConsumer = new StrimziKafkaCMVESMsgConsumer(generalConfigForTest.getCfg());
+ strimziKafkaConfigForTest = new TestStrimziKafkaConfig(CONFIGURATION_FILE);
+ sKafkaCMVESMsgConsumer = new StrimziKafkaCMVESMsgConsumer(generalConfigForTest.getCfg(), null);
}
@Test
@Test
public void test() throws IOException {
- StrimziKafkaFaultVESMsgConsumer faultMsgConsumer = new StrimziKafkaFaultVESMsgConsumer(cfgTest.getCfg());
+ StrimziKafkaFaultVESMsgConsumer faultMsgConsumer = new StrimziKafkaFaultVESMsgConsumer(cfgTest.getCfg(), null);
try {
faultMsgConsumer.processMsg(faultVESMsg.replace("@eventSeverity@", "CRITICAL"));
@Test
public void processMsgTest() {
- StrimziKafkaPNFRegVESMsgConsumer pnfRegMsgConsumer = new StrimziKafkaPNFRegVESMsgConsumer(cfgTest.getCfg());
+ StrimziKafkaPNFRegVESMsgConsumer pnfRegMsgConsumer = new StrimziKafkaPNFRegVESMsgConsumer(cfgTest.getCfg(), null);
try {
pnfRegMsgConsumer.processMsg(pnfRegMsg);
pnfRegMsgConsumer.processMsg(pnfRegMsg_SSH);
@Test
public void Test1() {
- StrimziKafkaPNFRegVESMsgConsumer pnfConsumer = new StrimziKafkaPNFRegVESMsgConsumer(cfgTest.getCfg());
+ StrimziKafkaPNFRegVESMsgConsumer pnfConsumer = new StrimziKafkaPNFRegVESMsgConsumer(cfgTest.getCfg(), null);
System.out.println(pnfConsumer.getBaseUrl());
System.out.println(pnfConsumer.getSDNRUser());
System.out.println(pnfConsumer.getSDNRPasswd());
@Test
public void testNotifyNewAlarm() throws IOException {
- StrimziKafkaStndDefinedFaultVESMsgConsumer stndDefinedFaultMsgConsumer = new StrimziKafkaStndDefinedFaultVESMsgConsumer(cfgTest.getCfg());
+ StrimziKafkaStndDefinedFaultVESMsgConsumer stndDefinedFaultMsgConsumer =
+ new StrimziKafkaStndDefinedFaultVESMsgConsumer(cfgTest.getCfg(), null);
try {
- stndDefinedFaultMsgConsumer.processMsg(stndDefinedVESMsg_NotifyNewAlarm.replace("@eventSeverity@", "CRITICAL"));
- stndDefinedFaultMsgConsumer.processMsg(stndDefinedVESMsg_NotifyNewAlarm.replace("@eventSeverity@", "Major"));
- stndDefinedFaultMsgConsumer.processMsg(stndDefinedVESMsg_NotifyNewAlarm.replace("@eventSeverity@", "minor"));
- stndDefinedFaultMsgConsumer.processMsg(stndDefinedVESMsg_NotifyNewAlarm.replace("@eventSeverity@", "NonAlarmed"));
- stndDefinedFaultMsgConsumer.processMsg(stndDefinedVESMsg_NotifyNewAlarm.replace("@eventSeverity@", "warning"));
- stndDefinedFaultMsgConsumer.processMsg(stndDefinedVESMsg_NotifyNewAlarm.replace("@eventSeverity@", "Unknown"));
+ stndDefinedFaultMsgConsumer
+ .processMsg(stndDefinedVESMsg_NotifyNewAlarm.replace("@eventSeverity@", "CRITICAL"));
+ stndDefinedFaultMsgConsumer
+ .processMsg(stndDefinedVESMsg_NotifyNewAlarm.replace("@eventSeverity@", "Major"));
+ stndDefinedFaultMsgConsumer
+ .processMsg(stndDefinedVESMsg_NotifyNewAlarm.replace("@eventSeverity@", "minor"));
+ stndDefinedFaultMsgConsumer
+ .processMsg(stndDefinedVESMsg_NotifyNewAlarm.replace("@eventSeverity@", "NonAlarmed"));
+ stndDefinedFaultMsgConsumer
+ .processMsg(stndDefinedVESMsg_NotifyNewAlarm.replace("@eventSeverity@", "warning"));
+ stndDefinedFaultMsgConsumer
+ .processMsg(stndDefinedVESMsg_NotifyNewAlarm.replace("@eventSeverity@", "Unknown"));
//stndDefinedFaultMsgConsumer.processMsg(faultVESMsg_Incomplete);
} catch (Exception e) {
e.printStackTrace();
@Test
public void testNotifyClearedAlarm() throws IOException {
- StrimziKafkaStndDefinedFaultVESMsgConsumer stndDefinedFaultMsgConsumer = new StrimziKafkaStndDefinedFaultVESMsgConsumer(cfgTest.getCfg());
+ StrimziKafkaStndDefinedFaultVESMsgConsumer stndDefinedFaultMsgConsumer =
+ new StrimziKafkaStndDefinedFaultVESMsgConsumer(cfgTest.getCfg(), null);
try {
- stndDefinedFaultMsgConsumer.processMsg(stndDefinedVESMsg_NotifyClearedAlarm.replace("@eventSeverity@", "cleared"));
- stndDefinedFaultMsgConsumer.processMsg(stndDefinedVESMsg_NotifyClearedAlarm.replace("@eventSeverity@", "Indeterminate"));
+ stndDefinedFaultMsgConsumer
+ .processMsg(stndDefinedVESMsg_NotifyClearedAlarm.replace("@eventSeverity@", "cleared"));
+ stndDefinedFaultMsgConsumer
+ .processMsg(stndDefinedVESMsg_NotifyClearedAlarm.replace("@eventSeverity@", "Indeterminate"));
//stndDefinedFaultMsgConsumer.processMsg(faultVESMsg_Incomplete);
} catch (Exception e) {
e.printStackTrace();
@Test(expected = InvalidMessageException.class)
public void testInvalidStndDefinedMessage() throws InvalidMessageException, JsonProcessingException {
- StrimziKafkaStndDefinedFaultVESMsgConsumer stndDefinedFaultMsgConsumer = new StrimziKafkaStndDefinedFaultVESMsgConsumer(cfgTest.getCfg());
+ StrimziKafkaStndDefinedFaultVESMsgConsumer stndDefinedFaultMsgConsumer =
+ new StrimziKafkaStndDefinedFaultVESMsgConsumer(cfgTest.getCfg(), null);
stndDefinedFaultMsgConsumer.processMsg(stndDefinedVESMsg_Invalid.replace("@eventSeverity@", "cleared"));
}
}