CST-12174 Implemented data-service for the api calls

This commit is contained in:
Mattia Vianelli
2023-10-17 16:28:36 +02:00
parent 8de0e76b72
commit 1c376b2964
15 changed files with 704 additions and 727 deletions

View File

@@ -6,6 +6,7 @@ import { SharedModule } from '../../shared/shared.module';
import { LdnServiceNewComponent } from './ldn-service-new/ldn-service-new.component';
import { LdnServiceFormComponent } from './ldn-service-form/ldn-service-form.component';
import { LdnServiceFormEditComponent } from './ldn-service-form-edit/ldn-service-form-edit.component';
import { FormsModule } from '@angular/forms';
@@ -14,6 +15,7 @@ import { LdnServiceFormEditComponent } from './ldn-service-form-edit/ldn-service
CommonModule,
SharedModule,
AdminLdnServicesRoutingModule,
FormsModule
],
declarations: [
LdnServicesOverviewComponent,

View File

@@ -112,7 +112,7 @@
<div class="col-sm-1">
<button (click)="removeInboundPattern(i)" class="btn btn-outline-dark trash-button ml-2">
<button type="button" (click)="removeInboundPattern(i)" class="btn btn-outline-dark trash-button ml-2">
<i class="fas fa-trash"></i>
</button>
</div>
@@ -176,7 +176,7 @@
</div>
<div class="col-sm-1">
<button (click)="removeOutboundPattern(i)" class="btn btn-outline-dark trash-button ml-2">
<button type="button" (click)="removeOutboundPattern(i)" class="btn btn-outline-dark trash-button ml-2">
<i class="fas fa-trash"></i>
</button>
</div>
@@ -215,7 +215,7 @@
{{ 'service.overview.delete.body' | translate }}
</div>
<div class="mt-4">
<button (click)="this.createService()"
<button (click)="this.patchService()"
class="btn btn-primary mr-2 custom-btn">{{ 'service.detail.update' | translate }}</button>
<button (click)="closeModal()" class="btn btn-danger"
id="delete-confirm">{{ 'service.detail.return' | translate }}

View File

@@ -1,396 +1,381 @@
import { ChangeDetectorRef, Component, Input, TemplateRef, ViewChild } from '@angular/core';
import { ChangeDetectorRef, Component, Input, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { LDN_SERVICE } from '../ldn-services-model/ldn-service.resource-type';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { ActivatedRoute, Router } from '@angular/router';
import { LdnDirectoryService } from '../ldn-services-services/ldn-directory.service';
import { LdnServicesService } from '../ldn-services-data/ldn-services-data.service';
import { LdnServiceConstraint } from '../ldn-services-model/ldn-service-constraint.model';
import { notifyPatterns } from '../ldn-services-patterns/ldn-service-coar-patterns';
import { ActivatedRoute } from '@angular/router';
import { animate, state, style, transition, trigger } from '@angular/animations';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { TranslateService } from '@ngx-translate/core';
import { LdnService } from '../ldn-services-model/ldn-services.model';
import { RemoteData } from 'src/app/core/data/remote-data';
import { Operation } from 'fast-json-patch';
import { getFirstCompletedRemoteData } from '../../../core/shared/operators';
@Component({
selector: 'ds-ldn-service-form-edit',
templateUrl: './ldn-service-form-edit.component.html',
styleUrls: ['./ldn-service-form-edit.component.scss'],
animations: [
trigger('toggleAnimation', [
state('true', style({})),
state('false', style({})),
transition('true <=> false', animate('300ms ease-in')),
]),
],
selector: 'ds-ldn-service-form-edit',
templateUrl: './ldn-service-form-edit.component.html',
styleUrls: ['./ldn-service-form-edit.component.scss'],
animations: [
trigger('toggleAnimation', [
state('true', style({})),
state('false', style({})),
transition('true <=> false', animate('300ms ease-in')),
]),
],
})
export class LdnServiceFormEditComponent {
formModel: FormGroup;
@ViewChild('confirmModal', {static: true}) confirmModal: TemplateRef<any>;
export class LdnServiceFormEditComponent implements OnInit {
formModel: FormGroup;
@ViewChild('confirmModal', {static: true}) confirmModal: TemplateRef<any>;
showItemFilterDropdown = false;
public inboundPatterns: object[] = notifyPatterns;
public outboundPatterns: object[] = notifyPatterns;
public itemFilterList: any[];
@Input() public name: string;
@Input() public description: string;
@Input() public url: string;
@Input() public ldnUrl: string;
@Input() public inboundPattern: string;
@Input() public outboundPattern: string;
@Input() public constraint: string;
@Input() public automatic: boolean;
@Input() public headerKey: string;
private originalInboundPatterns: any[] = [];
private originalOutboundPatterns: any[] = [];
private modalRef: any;
private service: LdnService;
protected serviceId: string;
private originalInboundPatterns: any[] = [];
private originalOutboundPatterns: any[] = [];
public inboundPatterns: object[] = notifyPatterns;
public outboundPatterns: object[] = notifyPatterns;
public itemFilterList: LdnServiceConstraint[];
private modalRef: any;
constructor(
protected ldnServicesService: LdnServicesService,
private ldnDirectoryService: LdnDirectoryService,
private formBuilder: FormBuilder,
private router: Router,
private route: ActivatedRoute,
private cdRef: ChangeDetectorRef,
protected modalService: NgbModal,
private notificationService: NotificationsService,
private translateService: TranslateService,
) {
@Input() public name: string;
@Input() public description: string;
@Input() public url: string;
@Input() public ldnUrl: string;
@Input() public inboundPattern: string;
@Input() public outboundPattern: string;
@Input() public constraint: string;
@Input() public automatic: boolean;
this.formModel = this.formBuilder.group({
id: [''],
name: ['', Validators.required],
description: ['', Validators.required],
url: ['', Validators.required],
ldnUrl: ['', Validators.required],
inboundPattern: [''],
outboundPattern: [''],
constraintPattern: [''],
enabled: [''],
notifyServiceInboundPatterns: this.formBuilder.array([this.createInboundPatternFormGroup()]),
notifyServiceOutboundPatterns: this.formBuilder.array([this.createOutboundPatternFormGroup()]),
type: LDN_SERVICE.value,
});
}
@Input() public headerKey: string;
private serviceId: string;
ngOnInit(): void {
this.route.params.subscribe((params) => {
this.serviceId = params.serviceId;
if (this.serviceId) {
this.fetchServiceData(this.serviceId);
}
});
this.ldnDirectoryService.getItemFilters().subscribe((itemFilters) => {
this.itemFilterList = itemFilters._embedded.itemfilters.map((filter: { id: string; }) => ({
name: filter.id
}));
this.cdRef.detectChanges();
});
}
constructor(
private ldnServicesService: LdnServicesService,
private ldnDirectoryService: LdnDirectoryService,
private formBuilder: FormBuilder,
private http: HttpClient,
private router: Router,
private route: ActivatedRoute,
private cdRef: ChangeDetectorRef,
protected modalService: NgbModal,
private notificationService: NotificationsService,
private translateService: TranslateService,
fetchServiceData(serviceId: string): void {
this.ldnServicesService.findById(serviceId).pipe(
getFirstCompletedRemoteData()
).subscribe(
(data: RemoteData<LdnService>) => {
if (data.hasSucceeded) {
this.service = data.payload;
) {
console.log(this.service);
this.formModel = this.formBuilder.group({
id: [''],
name: ['', Validators.required],
description: ['', Validators.required],
url: ['', Validators.required],
ldnUrl: ['', Validators.required],
inboundPattern: [''],
outboundPattern: [''],
constraintPattern: [''],
enabled: [''],
notifyServiceInboundPatterns: this.formBuilder.array([this.createInboundPatternFormGroup()]),
notifyServiceOutboundPatterns: this.formBuilder.array([this.createOutboundPatternFormGroup()]),
type: LDN_SERVICE.value,
});
}
this.formModel.patchValue({
id: this.service.id,
name: this.service.name,
description: this.service.description,
url: this.service.url,
ldnUrl: this.service.ldnUrl,
type: this.service.type,
enabled: this.service.enabled
});
ngOnInit(): void {
this.route.params.subscribe((params) => {
this.serviceId = params.serviceId;
if (this.serviceId) {
this.fetchServiceData(this.serviceId);
}
});
this.ldnDirectoryService.getItemFilters().subscribe((itemFilters) => {
this.itemFilterList = itemFilters._embedded.itemfilters.map((filter: { id: string; }) => ({
name: filter.id
}));
const inboundPatternsArray = this.formModel.get('notifyServiceInboundPatterns') as FormArray;
inboundPatternsArray.clear();
this.service.notifyServiceInboundPatterns.forEach((pattern: any) => {
const patternFormGroup = this.initializeInboundPatternFormGroup();
patternFormGroup.patchValue(pattern);
inboundPatternsArray.push(patternFormGroup);
this.cdRef.detectChanges();
});
});
}
const outboundPatternsArray = this.formModel.get('notifyServiceOutboundPatterns') as FormArray;
outboundPatternsArray.clear();
private getOriginalPattern(formArrayName: string, patternId: number): any {
let originalPatterns: any[] = [];
this.service.notifyServiceOutboundPatterns.forEach((pattern: any) => {
const patternFormGroup = this.initializeOutboundPatternFormGroup();
patternFormGroup.patchValue(pattern);
outboundPatternsArray.push(patternFormGroup);
if (formArrayName === 'notifyServiceInboundPatterns') {
originalPatterns = this.originalInboundPatterns;
} else if (formArrayName === 'notifyServiceOutboundPatterns') {
originalPatterns = this.originalOutboundPatterns;
this.cdRef.detectChanges();
});
this.originalInboundPatterns = [...this.service.notifyServiceInboundPatterns];
this.originalOutboundPatterns = [...this.service.notifyServiceOutboundPatterns];
} else {
console.error('Error fetching service data:', data.errorMessage);
}
},
(error) => {
console.error('Error fetching service data:', error);
}
);
}
return originalPatterns.find((pattern) => pattern.id === patternId);
generatePatchOperations(): any[] {
const patchOperations: any[] = [];
this.createReplaceOperation(patchOperations, 'name', '/name');
this.createReplaceOperation(patchOperations, 'description', '/description');
this.createReplaceOperation(patchOperations, 'ldnUrl', '/ldnurl');
this.createReplaceOperation(patchOperations, 'url', '/url');
this.handlePatterns(patchOperations, 'notifyServiceInboundPatterns');
this.handlePatterns(patchOperations, 'notifyServiceOutboundPatterns');
return patchOperations;
}
submitForm() {
this.openConfirmModal(this.confirmModal);
}
addInboundPattern() {
const notifyServiceInboundPatternsArray = this.formModel.get('notifyServiceInboundPatterns') as FormArray;
notifyServiceInboundPatternsArray.push(this.createInboundPatternFormGroup());
}
removeInboundPattern(index: number): void {
const patternsArray = this.formModel.get('notifyServiceInboundPatterns') as FormArray;
const patternGroup = patternsArray.at(index) as FormGroup;
const patternValue = patternGroup.value;
if (index < 0 || index >= patternsArray.length || patternValue.isNew) {
patternsArray.removeAt(index);
return;
}
private patternsAreEqual(patternA: any, patternB: any): boolean {
return (
patternA.pattern === patternB.pattern &&
patternA.constraint === patternB.constraint &&
patternA.automatic === patternB.automatic
);
}
const patchOperation: Operation = {
op: 'remove',
path: `notifyServiceInboundPatterns[${index}]`
};
fetchServiceData(serviceId: string): void {
const apiUrl = `http://localhost:8080/server/api/ldn/ldnservices/${serviceId}`;
this.http.get(apiUrl).subscribe(
(data: any) => {
console.log(data);
this.formModel.patchValue({
id: data.id,
name: data.name,
description: data.description,
url: data.url,
ldnUrl: data.ldnUrl,
type: data.type,
enabled: data.enabled
});
const inboundPatternsArray = this.formModel.get('notifyServiceInboundPatterns') as FormArray;
inboundPatternsArray.clear(); // Clear existing rows
data.notifyServiceInboundPatterns.forEach((pattern: any) => {
console.log(pattern);
const patternFormGroup = this.initializeInboundPatternFormGroup();
console.log();
patternFormGroup.patchValue(pattern);
inboundPatternsArray.push(patternFormGroup);
this.cdRef.detectChanges();
});
const outboundPatternsArray = this.formModel.get('notifyServiceOutboundPatterns') as FormArray;
outboundPatternsArray.clear();
data.notifyServiceOutboundPatterns.forEach((pattern: any) => {
const patternFormGroup = this.initializeOutboundPatternFormGroup();
patternFormGroup.patchValue(pattern);
outboundPatternsArray.push(patternFormGroup);
this.cdRef.detectChanges();
});
this.originalInboundPatterns = [...data.notifyServiceInboundPatterns];
this.originalOutboundPatterns = [...data.notifyServiceOutboundPatterns];
},
(error) => {
console.error('Error fetching service data:', error);
}
);
}
generatePatchOperations(): any[] {
const patchOperations: any[] = [];
this.addReplaceOperation(patchOperations, 'name', '/name');
this.addReplaceOperation(patchOperations, 'description', '/description');
this.addReplaceOperation(patchOperations, 'ldnUrl', '/ldnurl');
this.addReplaceOperation(patchOperations, 'url', '/url');
this.handlePatterns(patchOperations, 'notifyServiceInboundPatterns');
this.handlePatterns(patchOperations, 'notifyServiceOutboundPatterns');
return patchOperations;
}
private addReplaceOperation(patchOperations: any[], formControlName: string, path: string): void {
if (this.formModel.get(formControlName).dirty) {
patchOperations.push({
op: 'replace',
path,
value: this.formModel.get(formControlName).value,
});
this.ldnServicesService.patch(this.service, [patchOperation]).pipe(
getFirstCompletedRemoteData()
).subscribe(
(data: RemoteData<LdnService>) => {
if (data.hasSucceeded) {
this.notificationService.success(this.translateService.get('ldn-service.notification.remove-inbound-pattern.success.title'),
this.translateService.get('ldn-service.notification.remove-inbound-pattern.success.content'));
} else {
this.notificationService.error(this.translateService.get('ldn-service.notification.remove-inbound-pattern.error.title'),
this.translateService.get('ldn-service.notification.remove-inbound-pattern.error.content'));
}
patternsArray.removeAt(index);
this.cdRef.detectChanges();
},
(error) => {
console.error('Error removing pattern:', error);
}
);
}
addOutboundPattern() {
const notifyServiceOutboundPatternsArray = this.formModel.get('notifyServiceOutboundPatterns') as FormArray;
notifyServiceOutboundPatternsArray.push(this.createOutboundPatternFormGroup());
}
removeOutboundPattern(index: number): void {
const patternsArray = this.formModel.get('notifyServiceOutboundPatterns') as FormArray;
const patternGroup = patternsArray.at(index) as FormGroup;
const patternValue = patternGroup.value;
if (index < 0 || index >= patternsArray.length || patternValue.isNew) {
patternsArray.removeAt(index);
return;
}
private handlePatterns(patchOperations: any[], formArrayName: string): void {
const patternsArray = this.formModel.get(formArrayName) as FormArray;
const patchOperation: Operation = {
op: 'remove',
path: `notifyServiceOutboundPatterns[${index}]`
};
if (patternsArray.dirty) {
for (let i = 0; i < patternsArray.length; i++) {
const patternGroup = patternsArray.at(i) as FormGroup;
const patternValue = patternGroup.value;
if (patternValue.isNew) {
console.log(this.getOriginalPatternsForFormArray(formArrayName));
console.log(patternGroup);
delete patternValue.isNew;
const addOperation = {
op: 'add',
path: `${formArrayName}/-`,
value: patternValue,
};
patchOperations.push(addOperation);
} else if (patternGroup.dirty) {
const replaceOperation = {
op: 'replace',
path: `${formArrayName}[${i}]`,
value: patternValue,
};
patchOperations.push(replaceOperation);
console.log(patternValue.id);
}
}
}
}
private getOriginalPatternsForFormArray(formArrayName: string): any[] {
if (formArrayName === 'notifyServiceInboundPatterns') {
return this.originalInboundPatterns;
} else if (formArrayName === 'notifyServiceOutboundPatterns') {
return this.originalOutboundPatterns;
}
return [];
}
submitForm() {
this.openConfirmModal(this.confirmModal);
}
addInboundPattern() {
const notifyServiceInboundPatternsArray = this.formModel.get('notifyServiceInboundPatterns') as FormArray;
notifyServiceInboundPatternsArray.push(this.createInboundPatternFormGroup());
}
removeInboundPattern(index: number) {
const notifyServiceInboundPatternsArray = this.formModel.get('notifyServiceInboundPatterns') as FormArray;
if (index >= 0 && index < notifyServiceInboundPatternsArray.length) {
const serviceId = this.formModel.get('id').value;
const patchOperation = [
{
op: 'remove',
path: `notifyServiceInboundPatterns[${index}]`
}
];
const apiUrl = `http://localhost:8080/server/api/ldn/ldnservices/${serviceId}`;
this.http.patch(apiUrl, patchOperation).subscribe(
(response) => {
console.log('Pattern removed successfully:', response);
notifyServiceInboundPatternsArray.removeAt(index);
},
(error) => {
console.error('Error removing pattern:', error);
}
);
}
}
addOutboundPattern() {
const notifyServiceOutboundPatternsArray = this.formModel.get('notifyServiceOutboundPatterns') as FormArray;
notifyServiceOutboundPatternsArray.push(this.createOutboundPatternFormGroup());
}
removeOutboundPattern(index: number) {
const notifyServiceOutboundPatternsArray = this.formModel.get('notifyServiceOutboundPatterns') as FormArray;
if (index >= 0 && index < notifyServiceOutboundPatternsArray.length) {
const serviceId = this.formModel.get('id').value;
const patchOperation = [
{
op: 'remove',
path: `notifyServiceOutboundPatterns[${index}]`
}
];
const apiUrl = `http://localhost:8080/server/api/ldn/ldnservices/${serviceId}`;
this.http.patch(apiUrl, patchOperation).subscribe(
(response) => {
console.log('Pattern removed successfully:', response);
notifyServiceOutboundPatternsArray.removeAt(index);
},
(error) => {
console.error('Error removing pattern:', error);
}
);
}
}
private sendBack() {
this.router.navigateByUrl('admin/ldn/services');
}
private createOutboundPatternFormGroup(): FormGroup {
return this.formBuilder.group({
pattern: '',
constraint: '',
isNew: true,
});
}
private createInboundPatternFormGroup(): FormGroup {
return this.formBuilder.group({
pattern: '',
constraint: '',
automatic: '',
isNew: true
});
}
private initializeOutboundPatternFormGroup(): FormGroup {
return this.formBuilder.group({
pattern: '',
constraint: '',
});
}
private initializeInboundPatternFormGroup(): FormGroup {
return this.formBuilder.group({
pattern: '',
constraint: '',
automatic: '',
});
}
toggleAutomatic(i: number) {
const automaticControl = this.formModel.get(`notifyServiceInboundPatterns.${i}.automatic`);
if (automaticControl) {
automaticControl.setValue(!automaticControl.value);
this.ldnServicesService.patch(this.service, [patchOperation]).pipe(
getFirstCompletedRemoteData()
).subscribe(
(data: RemoteData<LdnService>) => {
if (data.hasSucceeded) {
this.notificationService.success(this.translateService.get('ldn-service.notification.remove-outbound-pattern.success.title'),
this.translateService.get('ldn-service.notification.remove-outbound-pattern.success.content'));
} else {
this.notificationService.error(this.translateService.get('ldn-service.notification.remove-outbound-pattern.error.title'),
this.translateService.get('ldn-service.notification.remove-outbound-pattern.error.content'));
}
patternsArray.removeAt(index);
this.cdRef.detectChanges();
},
(error) => {
console.error('Error removing pattern:', error);
}
);
}
toggleAutomatic(i: number) {
const automaticControl = this.formModel.get(`notifyServiceInboundPatterns.${i}.automatic`);
if (automaticControl) {
automaticControl.setValue(!automaticControl.value);
}
}
toggleEnabled() {
const newStatus = !this.formModel.get('enabled').value;
const serviceId = this.formModel.get('id').value;
const status = this.formModel.get('enabled').value;
const apiUrl = `http://localhost:8080/server/api/ldn/ldnservices/${serviceId}`;
const patchOperation = {
const patchOperation: Operation = {
op: 'replace',
path: '/enabled',
value: newStatus,
};
this.http.patch(apiUrl, [patchOperation]).subscribe(
() => {
console.log('Status updated successfully.');
this.formModel.get('enabled').setValue(newStatus);
console.log(this.formModel.get('enabled'));
this.cdRef.detectChanges();
},
(error) => {
console.error('Error updating status:', error);
}
this.ldnServicesService.patch(this.service, [patchOperation]).pipe(
getFirstCompletedRemoteData()
).subscribe(
() => {
console.log('Status updated successfully.');
this.formModel.get('enabled').setValue(newStatus);
this.cdRef.detectChanges();
},
(error) => {
console.error('Error updating status:', error);
}
);
}
closeModal() {
this.modalRef.close();
this.cdRef.detectChanges();
this.modalRef.close();
this.cdRef.detectChanges();
}
openConfirmModal(content) {
this.modalRef = this.modalService.open(content);
this.modalRef = this.modalService.open(content);
}
createService(){
const apiUrl = `http://localhost:8080/server/api/ldn/ldnservices/${this.serviceId}`;
const patchOperations = this.generatePatchOperations();
this.http.patch(apiUrl, patchOperations).subscribe(
(response) => {
console.log('Service updated successfully:', response);
this.sendBack();
this.closeModal();
this.notificationService.success(this.translateService.get('admin.registries.services-formats.modify.success.head'),
this.translateService.get('admin.registries.services-formats.modify.success.content'));
},
(error) => {
this.notificationService.error(this.translateService.get('admin.registries.services-formats.modify.failure.head'),
patchService() {
const patchOperations = this.generatePatchOperations();
this.ldnServicesService.patch(this.service, patchOperations).subscribe(
(response) => {
console.log('Service updated successfully:', response);
this.closeModal();
this.sendBack();
this.notificationService.success(this.translateService.get('admin.registries.services-formats.modify.success.head'),
this.translateService.get('admin.registries.services-formats.modify.success.content'));
},
(error) => {
this.notificationService.error(this.translateService.get('admin.registries.services-formats.modify.failure.head'),
this.translateService.get('admin.registries.services-formats.modify.failure.content'));
console.error('Error updating service:', error);
}
);
console.error('Error updating service:', error);
}
);
}
private createReplaceOperation(patchOperations: any[], formControlName: string, path: string): void {
if (this.formModel.get(formControlName).dirty) {
patchOperations.push({
op: 'replace',
path,
value: this.formModel.get(formControlName).value,
});
}
}
private handlePatterns(patchOperations: any[], formArrayName: string): void {
const patternsArray = this.formModel.get(formArrayName) as FormArray;
for (let i = 0; i < patternsArray.length; i++) {
const patternGroup = patternsArray.at(i) as FormGroup;
const patternValue = patternGroup.value;
if (patternGroup.dirty) {
if (patternValue.isNew) {
delete patternValue.isNew;
const addOperation = {
op: 'add',
path: `${formArrayName}/-`,
value: patternValue,
};
patchOperations.push(addOperation);
} else {
const replaceOperation = {
op: 'replace',
path: `${formArrayName}[${i}]`,
value: patternValue,
};
patchOperations.push(replaceOperation);
}
}
}
}
private sendBack() {
this.router.navigateByUrl('admin/ldn/services');
}
private createOutboundPatternFormGroup(): FormGroup {
return this.formBuilder.group({
pattern: '',
constraint: '',
isNew: true,
});
}
private createInboundPatternFormGroup(): FormGroup {
return this.formBuilder.group({
pattern: '',
constraint: '',
automatic: false,
isNew: true
});
}
private initializeOutboundPatternFormGroup(): FormGroup {
return this.formBuilder.group({
pattern: '',
constraint: '',
});
}
private initializeInboundPatternFormGroup(): FormGroup {
return this.formBuilder.group({
pattern: '',
constraint: '',
automatic: '',
});
}
}

View File

@@ -1,4 +1,4 @@
<form (ngSubmit)="submitForm()" [formGroup]="formModel">
<form (ngSubmit)="onSubmit()" [formGroup]="formModel">
<!-- In the name section -->
<div class="mb-2">

View File

@@ -1,172 +1,203 @@
import { Component, Input, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormArray } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { LdnServicesService } from '../ldn-services-data/ldn-services-data.service';
import { LdnServiceConstraint } from '../ldn-services-model/ldn-service-constraint.model';
import { notifyPatterns } from '../ldn-services-patterns/ldn-service-coar-patterns';
import { LdnDirectoryService } from '../ldn-services-services/ldn-directory.service';
import { LDN_SERVICE } from '../ldn-services-model/ldn-service.resource-type';
import { animate, state, style, transition, trigger } from '@angular/animations';
import { getFirstCompletedRemoteData } from '../../../core/shared/operators';
import { RemoteData } from '../../../core/data/remote-data';
import { LdnService } from '../ldn-services-model/ldn-services.model';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'ds-ldn-service-form',
templateUrl: './ldn-service-form.component.html',
styleUrls: ['./ldn-service-form.component.scss'],
animations: [
trigger('toggleAnimation', [
state('true', style({})), // Define animation states (empty style)
state('false', style({})),
transition('true <=> false', animate('300ms ease-in')), // Define animation transition with duration
]),
],
selector: 'ds-ldn-service-form',
templateUrl: './ldn-service-form.component.html',
styleUrls: ['./ldn-service-form.component.scss'],
animations: [
trigger('toggleAnimation', [
state('true', style({})),
state('false', style({})),
transition('true <=> false', animate('300ms ease-in')),
]),
],
})
export class LdnServiceFormComponent implements OnInit {
formModel: FormGroup;
formModel: FormGroup;
public inboundPatterns: object[] = notifyPatterns;
public outboundPatterns: object[] = notifyPatterns;
public itemFilterList: any[];
//showItemFilterDropdown = false;
@Input() public name: string;
@Input() public description: string;
@Input() public url: string;
@Input() public ldnUrl: string;
@Input() public inboundPattern: string;
@Input() public outboundPattern: string;
@Input() public constraint: string;
@Input() public automatic: boolean;
public inboundPatterns: object[] = notifyPatterns;
public outboundPatterns: object[] = notifyPatterns;
public itemFilterList: LdnServiceConstraint[];
//additionalOutboundPatterns: FormGroup[] = [];
//additionalInboundPatterns: FormGroup[] = [];
@Input() public headerKey: string;
@Output() submitForm: EventEmitter<any> = new EventEmitter();
@Output() cancelForm: EventEmitter<any> = new EventEmitter();
constructor(
private ldnServicesService: LdnServicesService,
private ldnDirectoryService: LdnDirectoryService,
private formBuilder: FormBuilder,
private router: Router,
private notificationsService: NotificationsService,
private translateService: TranslateService
) {
//@Input() public status: boolean;
@Input() public name: string;
@Input() public description: string;
@Input() public url: string;
@Input() public ldnUrl: string;
@Input() public inboundPattern: string;
@Input() public outboundPattern: string;
@Input() public constraint: string;
@Input() public automatic: boolean;
this.formModel = this.formBuilder.group({
enabled: true,
id: [''],
name: ['', Validators.required],
description: [''],
url: ['', Validators.required],
ldnUrl: ['', Validators.required],
inboundPattern: [''],
outboundPattern: [''],
constraintPattern: [''],
notifyServiceInboundPatterns: this.formBuilder.array([this.createInboundPatternFormGroup()]),
notifyServiceOutboundPatterns: this.formBuilder.array([this.createOutboundPatternFormGroup()]),
type: LDN_SERVICE.value,
});
}
@Input() public headerKey: string;
ngOnInit(): void {
this.ldnDirectoryService.getItemFilters().subscribe((itemFilters) => {
console.log(itemFilters);
this.itemFilterList = itemFilters._embedded.itemfilters.map((filter: { id: string; }) => ({
name: filter.id
}));
});
/*
get notifyServiceInboundPatternsFormArray(): FormArray {
return this.formModel.get('notifyServiceInboundPatterns') as FormArray;
}
*/
}
constructor(
private ldnServicesService: LdnServicesService,
private ldnDirectoryService: LdnDirectoryService,
private formBuilder: FormBuilder,
private http: HttpClient,
private router: Router
) {
/*createLdnService(values: any) {
this.formModel.get('name').markAsTouched();
this.formModel.get('url').markAsTouched();
this.formModel.get('ldnUrl').markAsTouched();
this.formModel = this.formBuilder.group({
enabled: true,
id: [''],
name: ['', Validators.required],
description: [''],
url: ['', Validators.required],
ldnUrl: ['', Validators.required],
inboundPattern: [''],
outboundPattern: [''],
constraintPattern: [''],
notifyServiceInboundPatterns: this.formBuilder.array([this.createInboundPatternFormGroup()]),
notifyServiceOutboundPatterns: this.formBuilder.array([this.createOutboundPatternFormGroup()]),
type: LDN_SERVICE.value,
});
const ldnServiceData = this.ldnServicesService.create(this.formModel.value);
ldnServiceData.subscribe((ldnNewService) => {
console.log(ldnNewService);
const name = ldnNewService.payload.name;
const url = ldnNewService.payload.url;
const ldnUrl = ldnNewService.payload.ldnUrl;
if (!name || !url || !ldnUrl) {
return;
}
ldnServiceData.pipe(
getFirstCompletedRemoteData()
).subscribe((rd: RemoteData<LdnService>) => {
if (rd.hasSucceeded) {
this.notificationsService.success(this.translateService.get('notification.created.success'));
this.submitForm.emit(values);
} else {
this.notificationsService.error(this.translateService.get('notification.created.failure', ));
this.cancelForm.emit();
}
});
});
}*/
onSubmit() {
this.formModel.get('name').markAsTouched();
this.formModel.get('url').markAsTouched();
this.formModel.get('ldnUrl').markAsTouched();
const name = this.formModel.get('name').value;
const url = this.formModel.get('url').value;
const ldnUrl = this.formModel.get('ldnUrl').value;
if (!name || !url || !ldnUrl) {
return;
}
ngOnInit(): void {
this.ldnDirectoryService.getItemFilters().subscribe((itemFilters) => {
console.log(itemFilters);
this.itemFilterList = itemFilters._embedded.itemfilters.map((filter: { id: string; }) => ({
name: filter.id
}));
});
const values = this.formModel.value;
const ldnServiceData = this.ldnServicesService.create(values);
ldnServiceData.pipe(
getFirstCompletedRemoteData()
).subscribe((ldnNewService) => {
console.log(ldnNewService);
});
ldnServiceData.pipe(
getFirstCompletedRemoteData()
).subscribe((rd: RemoteData<LdnService>) => {
if (rd.hasSucceeded) {
this.notificationsService.success(this.translateService.get('notification.created.success'));
this.submitForm.emit();
this.sendBack();
} else {
this.notificationsService.error(this.translateService.get('notification.created.failure'));
this.cancelForm.emit();
}
});
}
addInboundPattern() {
const notifyServiceInboundPatternsArray = this.formModel.get('notifyServiceInboundPatterns') as FormArray;
notifyServiceInboundPatternsArray.push(this.createInboundPatternFormGroup());
}
removeInboundPattern(index: number) {
const notifyServiceInboundPatternsArray = this.formModel.get('notifyServiceInboundPatterns') as FormArray;
notifyServiceInboundPatternsArray.removeAt(index);
}
addOutboundPattern() {
const notifyServiceOutboundPatternsArray = this.formModel.get('notifyServiceOutboundPatterns') as FormArray;
notifyServiceOutboundPatternsArray.push(this.createOutboundPatternFormGroup());
}
removeOutboundPattern(index: number) {
const notifyServiceOutboundPatternsArray = this.formModel.get('notifyServiceOutboundPatterns') as FormArray;
notifyServiceOutboundPatternsArray.removeAt(index);
}
toggleAutomatic(i: number) {
const automaticControl = this.formModel.get(`notifyServiceInboundPatterns.${i}.automatic`);
if (automaticControl) {
automaticControl.setValue(!automaticControl.value);
}
}
submitForm() {
this.formModel.get('name').markAsTouched();
this.formModel.get('url').markAsTouched();
this.formModel.get('ldnUrl').markAsTouched();
private sendBack() {
this.router.navigateByUrl('admin/ldn/services');
}
const name = this.formModel.get('name').value;
const url = this.formModel.get('url').value;
const ldnUrl = this.formModel.get('ldnUrl').value;
private createOutboundPatternFormGroup(): FormGroup {
return this.formBuilder.group({
pattern: [''],
constraint: [''],
});
}
if (!name || !url || !ldnUrl) {
return;
}
this.formModel.removeControl('inboundPattern');
this.formModel.removeControl('outboundPattern');
this.formModel.removeControl('constraintPattern');
console.log('JSON Data:', this.formModel.value);
const apiUrl = 'http://localhost:8080/server/api/ldn/ldnservices';
this.http.post(apiUrl, this.formModel.value).subscribe(
(response) => {
console.log('Service created successfully:', response);
this.formModel.reset();
this.sendBack();
},
(error) => {
console.error('Error creating service:', error);
}
);
}
private sendBack() {
this.router.navigateByUrl('admin/ldn/services');
}
addInboundPattern() {
const notifyServiceInboundPatternsArray = this.formModel.get('notifyServiceInboundPatterns') as FormArray;
notifyServiceInboundPatternsArray.push(this.createInboundPatternFormGroup());
}
removeInboundPattern(index: number) {
const notifyServiceInboundPatternsArray = this.formModel.get('notifyServiceInboundPatterns') as FormArray;
notifyServiceInboundPatternsArray.removeAt(index);
}
addOutboundPattern() {
const notifyServiceOutboundPatternsArray = this.formModel.get('notifyServiceOutboundPatterns') as FormArray;
notifyServiceOutboundPatternsArray.push(this.createOutboundPatternFormGroup());
}
removeOutboundPattern(index: number) {
const notifyServiceOutboundPatternsArray = this.formModel.get('notifyServiceOutboundPatterns') as FormArray;
notifyServiceOutboundPatternsArray.removeAt(index);
}
private createOutboundPatternFormGroup(): FormGroup {
return this.formBuilder.group({
pattern: [''],
constraint: [''],
});
}
private createInboundPatternFormGroup(): FormGroup {
return this.formBuilder.group({
pattern: [''],
constraint: [''],
automatic: false
});
}
toggleAutomatic(i: number) {
const automaticControl = this.formModel.get(`notifyServiceInboundPatterns.${i}.automatic`);
if (automaticControl) {
automaticControl.setValue(!automaticControl.value);
}
}
private createInboundPatternFormGroup(): FormGroup {
return this.formBuilder.group({
pattern: [''],
constraint: [''],
automatic: false
});
}
}

View File

@@ -1,4 +1,4 @@
import { Injectable } from '@angular/core';
import { Injectable } from '@angular/core';
import { dataService } from '../../../core/data/base/data-service.decorator';
import { LDN_SERVICE } from '../ldn-services-model/ldn-service.resource-type';
import { IdentifiableDataService } from '../../../core/data/base/identifiable-data.service';
@@ -19,50 +19,63 @@ import { map, take } from 'rxjs/operators';
import { URLCombiner } from '../../../core/url-combiner/url-combiner';
import { MultipartPostRequest } from '../../../core/data/request.models';
import { RestRequest } from '../../../core/data/rest-request.model';
import { getFirstCompletedRemoteData } from '../../../core/shared/operators';
import { hasValue } from '../../../shared/empty.util';
import { LdnService } from '../ldn-services-model/ldn-services.model';
import { LdnServiceConstraint } from '../ldn-services-model/ldn-service-constraint.model';
import { PatchData, PatchDataImpl } from '../../../core/data/base/patch-data';
import { ChangeAnalyzer } from '../../../core/data/change-analyzer';
import { PatchData, PatchDataImpl } from '../../../core/data/base/patch-data';
import { ChangeAnalyzer } from '../../../core/data/change-analyzer';
import { Operation } from 'fast-json-patch';
import { RestRequestMethod } from 'src/app/core/data/rest-request-method';
import { CreateData, CreateDataImpl } from '../../../core/data/base/create-data';
import { ldnServiceConstrain } from '../ldn-services-model/ldn-service.constrain.model';
import { getFirstCompletedRemoteData } from 'src/app/core/shared/operators';
import { hasValue } from 'src/app/shared/empty.util';
@Injectable()
@dataService(LDN_SERVICE)
export class LdnServicesService extends IdentifiableDataService<LdnService> implements FindAllData<LdnService>, DeleteData<LdnService>, PatchData<LdnService> {
private findAllData: FindAllDataImpl<LdnService>;
private deleteData: DeleteDataImpl<LdnService>;
private patchData: PatchDataImpl<LdnService>;
private comparator: ChangeAnalyzer<LdnService>;
@Injectable()
@dataService(LDN_SERVICE)
export class LdnServicesService extends IdentifiableDataService<LdnService> implements FindAllData<LdnService>, DeleteData<LdnService>, PatchData<LdnService>, CreateData<LdnService> {
createData: CreateDataImpl<LdnService>;
private findAllData: FindAllDataImpl<LdnService>;
private deleteData: DeleteDataImpl<LdnService>;
private patchData: PatchDataImpl<LdnService>;
private comparator: ChangeAnalyzer<LdnService>;
constructor(
protected requestService: RequestService,
protected rdbService: RemoteDataBuildService,
protected objectCache: ObjectCacheService,
protected halService: HALEndpointService,
protected notificationsService: NotificationsService,
) {
super('ldnservices', requestService, rdbService, objectCache, halService);
constructor(
protected requestService: RequestService,
protected rdbService: RemoteDataBuildService,
protected objectCache: ObjectCacheService,
protected halService: HALEndpointService,
protected notificationsService: NotificationsService,
) {
super('ldnservices', requestService, rdbService, objectCache, halService);
this.findAllData = new FindAllDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, this.responseMsToLive);
this.deleteData = new DeleteDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, notificationsService, this.responseMsToLive, this.constructIdEndpoint);
this.patchData = new PatchDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, this.comparator, this.responseMsToLive, this.constructIdEndpoint);
}
this.findAllData = new FindAllDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, this.responseMsToLive);
this.deleteData = new DeleteDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, notificationsService, this.responseMsToLive, this.constructIdEndpoint);
this.patchData = new PatchDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, this.comparator, this.responseMsToLive, this.constructIdEndpoint);
this.createData = new CreateDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, notificationsService, this.responseMsToLive);
}
patch(object: LdnService, operations: Operation[]): Observable<RemoteData<LdnService>> {
throw new Error('Method not implemented.');
}
update(object: LdnService): Observable<RemoteData<LdnService>> {
throw new Error('Method not implemented.');
}
commitUpdates(method?: RestRequestMethod): void {
throw new Error('Method not implemented.');
}
createPatchFromCache(object: LdnService): Observable<Operation[]> {
throw new Error('Method not implemented.');
}
create(object: LdnService): Observable<RemoteData<LdnService>> {
return this.createData.create(object);
}
patch(object: LdnService, operations: Operation[]): Observable<RemoteData<LdnService>> {
return this.patchData.patch(object, operations);
}
update(object: LdnService): Observable<RemoteData<LdnService>> {
return this.patchData.update(object);
}
commitUpdates(method?: RestRequestMethod): void {
return this.patchData.commitUpdates(method);
}
createPatchFromCache(object: LdnService): Observable<Operation[]> {
return this.patchData.createPatchFromCache(object);
}
findAll(options?: FindListOptions, useCachedVersionIfAvailable?: boolean, reRequestOnStale?: boolean, ...linksToFollow: FollowLinkConfig<LdnService>[]): Observable<RemoteData<PaginatedList<LdnService>>> {
return this.findAllData.findAll(options, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow);
@@ -76,21 +89,22 @@ import { RestRequestMethod } from 'src/app/core/data/rest-request-method';
return this.deleteData.deleteByHref(href, copyVirtualMetadata);
}
public invoke(serviceName: string, parameters: LdnServiceConstraint[], files: File[]): Observable<RemoteData<LdnService>> {
public invoke(serviceName: string, serviceId: string, parameters: ldnServiceConstrain[], files: File[]): Observable<RemoteData<LdnService>> {
const requestId = this.requestService.generateRequestId();
this.getBrowseEndpoint().pipe(
take(1),
map((endpoint: string) => new URLCombiner(endpoint, serviceName, 'processes').toString()),
map((endpoint: string) => {
const body = this.getInvocationFormData(parameters, files);
return new MultipartPostRequest(requestId, endpoint, body);
})
take(1),
map((endpoint: string) => new URLCombiner(endpoint, serviceName, 'processes', serviceId).toString()),
map((endpoint: string) => {
const body = this.getInvocationFormData(parameters, files);
return new MultipartPostRequest(requestId, endpoint, body);
})
).subscribe((request: RestRequest) => this.requestService.send(request));
return this.rdbService.buildFromRequestUUID<LdnService>(requestId);
}
private getInvocationFormData(constrain: LdnServiceConstraint[], files: File[]): FormData {
private getInvocationFormData(constrain: ldnServiceConstrain[], files: File[]): FormData {
const form: FormData = new FormData();
form.set('properties', JSON.stringify(constrain));
files.forEach((file: File) => {

View File

@@ -23,12 +23,12 @@
</tr>
</thead>
<tbody>
<tr *ngFor="let ldnService of (ldnServicesRD$| async)?.payload?.page">
<tr *ngFor="let ldnService of (ldnServicesRD$ | async)?.payload?.page">
<td>{{ ldnService.name }}</td>
<td>{{ ldnService.description }}</td>
<td>
<span [ngClass]="{ 'status-enabled': ldnService.enabled, 'status-disabled': !ldnService.enabled }"
class="status-indicator" (click)="toggleStatus(ldnService)"
class="status-indicator" (click)="toggleStatus(ldnService, ldnServicesService)"
[title]="ldnService.enabled ? ('ldn-service.overview.table.clickToDisable' | translate) : ('ldn-service.overview.table.clickToEnable' | translate)">
{{ ldnService.enabled ? ('ldn-service.overview.table.enabled' | translate) : ('ldn-service.overview.table.disabled' | translate) }}
</span>
@@ -70,7 +70,7 @@
<div class="mt-4">
<button (click)="closeModal()"
class="btn btn-primary mr-2">{{ 'service.detail.delete.cancel' | translate }}</button>
<button (click)="deleteSelected()" class="btn btn-danger"
<button (click)="deleteSelected(this.selectedServiceId.toString(), ldnServicesService)" class="btn btn-danger"
id="delete-confirm">{{ 'service.overview.delete' | translate }}
</button>
</div>

View File

@@ -1,5 +1,4 @@
import { ChangeDetectorRef, Component, OnDestroy, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { LdnDirectoryService } from '../ldn-services-services/ldn-directory.service';
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { Observable, Subscription } from 'rxjs';
import { RemoteData } from '../../../core/data/remote-data';
import { PaginatedList } from '../../../core/data/paginated-list.model';
@@ -11,170 +10,122 @@ import { LdnServicesService } from 'src/app/admin/admin-ldn-services/ldn-service
import { PaginationService } from 'src/app/core/pagination/pagination.service';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { hasValue } from '../../../shared/empty.util';
import { HttpClient } from '@angular/common/http';
import { getFirstCompletedRemoteData } from "../../../core/shared/operators";
import { Operation } from 'fast-json-patch';
import { getFirstCompletedRemoteData } from '../../../core/shared/operators';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { TranslateService } from '@ngx-translate/core';
import { Router } from '@angular/router';
@Component({
selector: 'ds-ldn-services-directory',
templateUrl: './ldn-services-directory.component.html',
styleUrls: ['./ldn-services-directory.component.scss'],
selector: 'ds-ldn-services-directory',
templateUrl: './ldn-services-directory.component.html',
styleUrls: ['./ldn-services-directory.component.scss'],
changeDetection: ChangeDetectionStrategy.Default
})
export class LdnServicesOverviewComponent implements OnInit, OnDestroy {
selectedServiceId: number | null = null;
servicesData: any[] = [];
@ViewChild('deleteModal', {static: true}) deleteModal: TemplateRef<any>;
ldnServicesRD$: Observable<RemoteData<PaginatedList<LdnService>>>;
config: FindListOptions = Object.assign(new FindListOptions(), {
elementsPerPage: 20
selectedServiceId: string | number | null = null;
servicesData: any[] = [];
@ViewChild('deleteModal', {static: true}) deleteModal: TemplateRef<any>;
ldnServicesRD$: Observable<RemoteData<PaginatedList<LdnService>>>;
config: FindListOptions = Object.assign(new FindListOptions(), {
elementsPerPage: 20
});
pageConfig: PaginationComponentOptions = Object.assign(new PaginationComponentOptions(), {
id: 'po',
pageSize: 20
});
isProcessingSub: Subscription;
private modalRef: any;
constructor(
protected ldnServicesService: LdnServicesService,
protected paginationService: PaginationService,
protected modalService: NgbModal,
private cdRef: ChangeDetectorRef,
private notificationService: NotificationsService,
private translateService: TranslateService,
private router: Router,
) {
}
ngOnInit(): void {
this.setLdnServices();
}
setLdnServices() {
this.ldnServicesRD$ = this.paginationService.getFindListOptions(this.pageConfig.id, this.config).pipe(
switchMap((config) => this.ldnServicesService.findAll(config, true, false).pipe(
getFirstCompletedRemoteData()
))
);
this.ldnServicesRD$.subscribe((rd: RemoteData<PaginatedList<LdnService>>) => {
console.log(rd);
if (rd.hasSucceeded) {
this.notificationService.success(this.translateService.get('notification.loaded.success'));
} else {
this.notificationService.error(this.translateService.get('notification.loaded.failure'));
}
});
pageConfig: PaginationComponentOptions = Object.assign(new PaginationComponentOptions(), {
id: 'po',
pageSize: 20
});
isProcessingSub: Subscription;
private modalRef: any;
}
constructor(
protected processLdnService: LdnServicesService,
private ldnServicesService: LdnServicesService,
protected paginationService: PaginationService,
protected modalService: NgbModal,
public ldnDirectoryService: LdnDirectoryService,
private http: HttpClient,
private cdRef: ChangeDetectorRef
) {
ngOnDestroy(): void {
this.paginationService.clearPagination(this.pageConfig.id);
if (hasValue(this.isProcessingSub)) {
this.isProcessingSub.unsubscribe();
}
}
ngOnInit(): void {
this.setLdnServices2();
this.setLdnServices();
/*this.ldnDirectoryService.listLdnServices();*/
/*this.ldnServicesRD$.subscribe(data => {
console.log('searchByLdnUrl()', data);
});*/
openDeleteModal(content) {
this.modalRef = this.modalService.open(content);
}
/*this.ldnServicesRD$.pipe(
tap(data => {
console.log('ldnServicesRD$ data:', data);
})
).subscribe(() => {
this.searchByLdnUrl();
});*/
closeModal() {
this.modalRef.close();
this.cdRef.detectChanges();
}
}
selectServiceToDelete(serviceId: number) {
this.selectedServiceId = serviceId;
this.openDeleteModal(this.deleteModal);
}
setLdnServices() {
this.ldnServicesService.findAll().pipe(getFirstCompletedRemoteData()).subscribe((remoteData) => {
if (remoteData.hasSucceeded) {
const ldnservices = remoteData.payload.page;
console.log(ldnservices);
} else {
console.error('Error fetching LDN services:', remoteData.errorMessage);
}
});
}
setLdnServices2() {
this.ldnServicesRD$ = this.paginationService.getFindListOptions(this.pageConfig.id, this.config).pipe(
switchMap((config) => this.ldnServicesService.findAll(config, true, false))
);
}
ngOnDestroy(): void {
this.paginationService.clearPagination(this.pageConfig.id);
if (hasValue(this.isProcessingSub)) {
this.isProcessingSub.unsubscribe();
deleteSelected(serviceId: string, ldnServicesService: LdnServicesService): void {
if (this.selectedServiceId !== null) {
ldnServicesService.delete(serviceId).pipe(getFirstCompletedRemoteData()).subscribe((rd: RemoteData<LdnService>) => {
if (rd.hasSucceeded) {
this.servicesData = this.servicesData.filter(service => service.id !== serviceId);
this.cdRef.detectChanges();
this.closeModal();
this.notificationService.success(this.translateService.get('notification.created.success'));
} else {
this.notificationService.error(this.translateService.get('notification.created.failure'));
this.cdRef.detectChanges();
}
});
}
openDeleteModal(content) {
this.modalRef = this.modalService.open(content);
}
closeModal() {
this.modalRef.close();
this.cdRef.detectChanges();
}
}
findAllServices(): void {
this.retrieveAll().subscribe(
(response) => {
this.servicesData = response._embedded.ldnservices;
console.log('ServicesData =', this.servicesData);
this.cdRef.detectChanges();
},
(error) => {
console.error('Error:', error);
}
);
}
retrieveAll(): Observable<any> {
const url = 'http://localhost:8080/server/api/ldn/ldnservices';
return this.http.get(url);
}
deleteSelected() {
if (this.selectedServiceId !== null) {
const deleteUrl = `http://localhost:8080/server/api/ldn/ldnservices/${this.selectedServiceId}`;
this.http.delete(deleteUrl).subscribe(
() => {
this.closeModal();
this.findAllServices();
},
(error) => {
console.error('Error deleting service:', error);
}
);
toggleStatus(ldnService: any, ldnServicesService: LdnServicesService): void {
const newStatus = !ldnService.enabled;
let status = ldnService.enabled;
const patchOperation: Operation = {
op: 'replace',
path: '/enabled',
value: newStatus,
};
ldnServicesService.patch(ldnService, [patchOperation]).pipe(getFirstCompletedRemoteData()).subscribe(
() => {
if (status !== newStatus) {
this.notificationService.success(this.translateService.get('ldn-enable-service.notification.success.title'),
this.translateService.get('ldn-enable-service.notification.success.content'));
} else {
this.notificationService.error(this.translateService.get('ldn-enable-service.notification.error.title'),
this.translateService.get('ldn-enable-service.notification.error.content'));
}
}
}
selectServiceToDelete(serviceId: number) {
this.selectedServiceId = serviceId;
this.openDeleteModal(this.deleteModal);
}
toggleStatus(ldnService: any): void {
const newStatus = !ldnService.enabled;
const apiUrl = `http://localhost:8080/server/api/ldn/ldnservices/${ldnService.id}`;
const patchOperation = {
op: 'replace',
path: '/enabled',
value: newStatus,
};
this.http.patch(apiUrl, [patchOperation]).subscribe(
() => {
console.log('Status updated successfully.');
ldnService.enabled = newStatus;
this.cdRef.detectChanges();
},
(error) => {
console.error('Error updating status:', error);
}
);
}
fetchServiceData(serviceId: string): void {
const apiUrl = `http://localhost:8080/server/api/ldn/ldnservices/${serviceId}`;
this.http.get(apiUrl).subscribe(
(data: any) => {
console.log(data);
},
(error) => {
console.error('Error fetching service data:', error);
}
);
}
);
}
}

View File

@@ -1,7 +1,7 @@
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'

View File

@@ -1,26 +0,0 @@
/**
* A cosntrain that can be used when running a service
*/
export class LdnServiceConstraint {
/**
* The name of the constrain
*/
name: string;
/**
* The value of the constrain
*/
value: string;
}
export const EndorsmentConstrain = [
{
name: 'Type 1 Item',
value: 'Type1'
},
{
name: 'Type 2 Item',
value: 'Type2'
},
];

View File

@@ -0,0 +1,13 @@
import { autoserialize } from 'cerialize';
/**
* notify service patterns
*/
export class NotifyServicePattern {
@autoserialize
pattern: string;
@autoserialize
constraint: string;
@autoserialize
automatic: string;
}

View File

@@ -0,0 +1,3 @@
export class ldnServiceConstrain {
void: any;
}

View File

@@ -7,3 +7,4 @@
import { ResourceType } from '../../../core/shared/resource-type';
export const LDN_SERVICE = new ResourceType('ldnservice');
export const LDN_SERVICE_CONSTRAINT = new ResourceType('ldnservice');

View File

@@ -1,12 +1,16 @@
import { ResourceType } from '../../../core/shared/resource-type';
import { CacheableObject } from '../../../core/cache/cacheable-object.model';
import { autoserialize, deserialize } from 'cerialize';
import { autoserialize, deserialize, deserializeAs, inheritSerialization } from 'cerialize';
import { LDN_SERVICE } from './ldn-service.resource-type';
import { excludeFromEquals } from '../../../core/utilities/equals.decorators';
import { typedObject } from '../../../core/cache/builders/build-decorators';
import { NotifyServicePattern } from './ldn-service-patterns.model';
@typedObject
@inheritSerialization(CacheableObject)
export class LdnService extends CacheableObject {
static type = LDN_SERVICE;
@@ -15,7 +19,10 @@ export class LdnService extends CacheableObject {
type: ResourceType;
@autoserialize
id?: number;
id: number;
@deserializeAs('id')
uuid: string;
@autoserialize
name: string;
@@ -49,13 +56,3 @@ export class LdnService extends CacheableObject {
return this._links.self.href;
}
}
class NotifyServicePattern {
@autoserialize
pattern: string;
@autoserialize
constraint?: string;
@autoserialize
automatic?: boolean;
}

View File

@@ -4,6 +4,8 @@ import { getAdminModuleRoute } from '../app-routing-paths';
export const REGISTRIES_MODULE_PATH = 'registries';
export const NOTIFICATIONS_MODULE_PATH = 'notifications';
export const LDN_PATH = 'ldn';
export function getRegistriesModuleRoute() {
return new URLCombiner(getAdminModuleRoute(), REGISTRIES_MODULE_PATH).toString();
}
@@ -12,4 +14,8 @@ export function getNotificationsModuleRoute() {
return new URLCombiner(getAdminModuleRoute(), NOTIFICATIONS_MODULE_PATH).toString();
}
export const LDN_PATH = 'ldn';
export function getLdnServicesModuleRoute() {
return new URLCombiner(getAdminModuleRoute(), LDN_PATH).toString();
}