Fix all tslint warnings

1. Fix tslint warnings
2. Add tslint to travis
This commit is contained in:
Deng, Qian 2018-05-14 20:01:00 +08:00
parent 44006247a6
commit 43c8e9f589
236 changed files with 5401 additions and 4753 deletions

View File

@ -208,7 +208,7 @@ func (ctl *DefaultController) Replicate(policyID int64, metadata ...map[string]i
// prepare candidates for replication
candidates := getCandidates(&policy, ctl.sourcer, metadata...)
if len(candidates) == 0 {
log.Debugf("replicaton candidates are null, no further action needed")
log.Debugf("replication candidates are null, no further action needed")
}
targets := []*common_models.RepTarget{}

View File

@ -1 +1 @@
export * from './src/index';
export * from './src/index';

View File

@ -1,6 +1,6 @@
{
"name": "harbor-ui",
"version": "0.7.18-dev.6",
"version": "0.7.18-dev.8",
"description": "Harbor shared UI components based on Clarity and Angular4",
"author": "VMware",
"module": "index.js",

View File

@ -13,16 +13,17 @@
// limitations under the License.
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
// tslint:disable-next-line:no-unused-variable
import { Observable } from "rxjs/Observable";
@Injectable()
export class ChannelService {
//Declare for publishing scan event
// Declare for publishing scan event
scanCommandSource = new Subject<string>();
scanCommand$ = this.scanCommandSource.asObservable();
publishScanEvent(tagId: string): void {
this.scanCommandSource.next(tagId);
}
}
}

View File

@ -1 +1 @@
export * from './channel.service';
export * from './channel.service';

View File

@ -119,4 +119,4 @@ export class Configuration {
}, true);
this.read_only = new BoolValueItem(false, true);
}
}
}

View File

@ -16,4 +16,4 @@ export const CONFIGURATION_DIRECTIVES: Type<any>[] = [
SystemSettingsComponent,
VulnerabilityConfigComponent,
RegistryConfigComponent
];
];

View File

@ -114,4 +114,4 @@ describe('RegistryConfigComponent (inline template)', () => {
expect(saveSpy.calls.any).toBeTruthy();
}));
});
});

View File

@ -1,7 +1,11 @@
import { Component, OnInit, EventEmitter, Output, ViewChild, Input } from '@angular/core';
import { Component, OnInit, ViewChild, Input } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { Configuration, ComplexValueItem } from './config';
import { ConfigurationService, SystemInfoService, SystemInfo, ClairDBStatus } from '../service/index';
import { ConfirmationState, ConfirmationTargets } from '../shared/shared.const';
import { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation-dialog.component';
import { ConfirmationMessage } from '../confirmation-dialog/confirmation-message';
import { ConfirmationAcknowledgement } from '../confirmation-dialog/confirmation-state-message';
import { ConfigurationService, SystemInfoService, SystemInfo } from '../service/index';
import {
toPromise,
compareValue,
@ -9,17 +13,8 @@ import {
clone
} from '../utils';
import { ErrorHandler } from '../error-handler/index';
import {
SystemSettingsComponent,
VulnerabilityConfigComponent
} from './index';
import { ConfirmationState, ConfirmationTargets, ConfirmationButtons } from '../shared/shared.const';
import { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation-dialog.component';
import { ConfirmationMessage } from '../confirmation-dialog/confirmation-message';
import { ConfirmationAcknowledgement } from '../confirmation-dialog/confirmation-state-message';
import { TranslateService } from '@ngx-translate/core';
import { SystemSettingsComponent, VulnerabilityConfigComponent } from './index';
import { Configuration } from './config';
@Component({
selector: 'hbr-registry-config',
@ -62,7 +57,7 @@ export class RegistryConfigComponent implements OnInit {
ngOnInit(): void {
this.loadSystemInfo();
//Initialize
// Initialize
this.load();
}
@ -77,14 +72,14 @@ export class RegistryConfigComponent implements OnInit {
return !isEmptyObject(this.getChanges());
}
//Get system info
// Get system info
loadSystemInfo(): void {
toPromise<SystemInfo>(this.systemInfoService.getSystemInfo())
.then((info: SystemInfo) => this.systemInfo = info)
.catch(error => this.errorHandler.error(error));
}
//Load configurations
// Load configurations
load(): void {
this.onGoing = true;
toPromise<Configuration>(this.configService.getConfigurations())
@ -99,12 +94,12 @@ export class RegistryConfigComponent implements OnInit {
});
}
//Save configuration changes
// Save configuration changes
save(): void {
let changes: { [key: string]: any | any[] } = this.getChanges();
if (isEmptyObject(changes)) {
//Guard code, do nothing
// Guard code, do nothing
return;
}
@ -116,10 +111,10 @@ export class RegistryConfigComponent implements OnInit {
this.translate.get("CONFIG.SAVE_SUCCESS").subscribe((res: string) => {
this.errorHandler.info(res);
});
//Reload to fetch all the updates
// Reload to fetch all the updates
this.load();
//Reload all system info
//this.loadSystemInfo();
// Reload all system info
// this.loadSystemInfo();
})
.catch(error => {
this.onGoing = false;
@ -127,7 +122,7 @@ export class RegistryConfigComponent implements OnInit {
});
}
//Cancel the changes if have
// Cancel the changes if have
cancel(): void {
let msg = new ConfirmationMessage(
"CONFIG.CONFIRM_TITLE",
@ -139,7 +134,7 @@ export class RegistryConfigComponent implements OnInit {
this.confirmationDlg.open(msg);
}
//Confirm cancel
// Confirm cancel
confirmCancel(ack: ConfirmationAcknowledgement): void {
if (ack && ack.source === ConfirmationTargets.CONFIG &&
ack.state === ConfirmationState.CONFIRMED) {
@ -148,9 +143,9 @@ export class RegistryConfigComponent implements OnInit {
}
reset(): void {
//Reset to the values of copy
// Reset to the values of copy
let changes: { [key: string]: any | any[] } = this.getChanges();
for (let prop in changes) {
for (let prop of Object.keys(changes)) {
this.config[prop] = clone(this.configCopy[prop]);
}
}
@ -161,17 +156,17 @@ export class RegistryConfigComponent implements OnInit {
return changes;
}
for (let prop in this.config) {
for (let prop of Object.keys(this.config)) {
let field = this.configCopy[prop];
if (field && field.editable) {
if (!compareValue(field.value, this.config[prop].value)) {
changes[prop] = this.config[prop].value;
//Number
// Number
if (typeof field.value === "number") {
changes[prop] = +changes[prop];
}
//Trim string value
// Trim string value
if (typeof field.value === "string") {
changes[prop] = ('' + changes[prop]).trim();
}
@ -181,4 +176,4 @@ export class RegistryConfigComponent implements OnInit {
return changes;
}
}
}

View File

@ -21,7 +21,7 @@ export class ReplicationConfigComponent {
this.configChange.emit(this.config);
}
@Input() showSubTitle: boolean = false
@Input() showSubTitle: boolean = false;
@ViewChild("replicationConfigFrom") replicationConfigForm: NgForm;
@ -34,4 +34,4 @@ export class ReplicationConfigComponent {
get isValid(): boolean {
return this.replicationConfigForm && this.replicationConfigForm.valid;
}
}
}

View File

@ -53,4 +53,4 @@ export class SystemSettingsComponent {
this.downloadLink = this.configInfo.systemInfoEndpoint + "/getcert";
}
}
}
}

View File

@ -10,7 +10,7 @@ import {
import { ErrorHandler } from '../../error-handler/index';
import { toPromise } from '../../utils';
import { TranslateService } from '@ngx-translate/core';
import { ClairDBStatus, ClairDetail } from '../../service/interface';
import { ClairDetail } from '../../service/interface';
const ONE_HOUR_SECONDS: number = 3600;
const ONE_DAY_SECONDS: number = 24 * ONE_HOUR_SECONDS;
@ -85,7 +85,7 @@ export class VulnerabilityConfigComponent implements OnInit {
return [];
}
//UTC time
// UTC time
get dailyTime(): string {
if (!(this.config &&
this.config.scan_all_policy &&
@ -94,7 +94,7 @@ export class VulnerabilityConfigComponent implements OnInit {
return "00:00";
}
let timeOffset: number = 0;//seconds
let timeOffset: number = 0; // seconds
if (this.config.scan_all_policy.value.parameter) {
let daily_time = this.config.scan_all_policy.value.parameter.daily_time;
if (daily_time && typeof daily_time === "number") {
@ -102,9 +102,9 @@ export class VulnerabilityConfigComponent implements OnInit {
}
}
//Convert to current time
// Convert to current time
let timezoneOffset: number = this._localTime.getTimezoneOffset();
//Local time
// Local time
timeOffset = timeOffset - timezoneOffset * 60;
if (timeOffset < 0) {
timeOffset = timeOffset + ONE_DAY_SECONDS;
@ -114,7 +114,7 @@ export class VulnerabilityConfigComponent implements OnInit {
timeOffset -= ONE_DAY_SECONDS;
}
//To time string
// To time string
let hours: number = Math.floor(timeOffset / ONE_HOUR_SECONDS);
let minutes: number = Math.floor((timeOffset - hours * ONE_HOUR_SECONDS) / 60);
@ -143,7 +143,7 @@ export class VulnerabilityConfigComponent implements OnInit {
return;
}
//Double confirm inner parameter existing.
// Double confirm inner parameter existing.
if (!this.config.scan_all_policy.value.parameter) {
this.config.scan_all_policy.value.parameter = {
daily_time: 0
@ -157,7 +157,7 @@ export class VulnerabilityConfigComponent implements OnInit {
let hours: number = +values[0];
let minutes: number = +values[1];
//Convert to UTC time
// Convert to UTC time
let timezoneOffset: number = this._localTime.getTimezoneOffset();
let utcTimes: number = hours * ONE_HOUR_SECONDS + minutes * 60;
utcTimes += timezoneOffset * 60;
@ -172,14 +172,14 @@ export class VulnerabilityConfigComponent implements OnInit {
this.config.scan_all_policy.value.parameter.daily_time = utcTimes;
}
//Scanning type
// Scanning type
get scanningType(): string {
if (this.config &&
this.config.scan_all_policy &&
this.config.scan_all_policy.value) {
return this.config.scan_all_policy.value.type;
} else {
//default
// default
return "none";
}
}
@ -191,12 +191,12 @@ export class VulnerabilityConfigComponent implements OnInit {
let type: string = (v && v.trim() !== "") ? v : "none";
this.config.scan_all_policy.value.type = type;
if (type !== "daily") {
//No parameter
// No parameter
if (this.config.scan_all_policy.value.parameter) {
delete (this.config.scan_all_policy.value.parameter);
}
} else {
//Has parameter
// Has parameter
if (!this.config.scan_all_policy.value.parameter) {
this.config.scan_all_policy.value.parameter = {
daily_time: 0
@ -251,11 +251,11 @@ export class VulnerabilityConfigComponent implements OnInit {
scanNow(): void {
if (this.onSubmitting) {
return;//Aoid duplicated submitting
return; // Aoid duplicated submitting
}
if(!this.scanAvailable) {
return; //Aoid page hacking
if (!this.scanAvailable) {
return; // Aoid page hacking
}
this.onSubmitting = true;
@ -265,7 +265,7 @@ export class VulnerabilityConfigComponent implements OnInit {
this.errorHandler.info(res);
});
//Update system info
// Update system info
this.getSystemInfo().then(() => {
this.onSubmitting = false;
}).catch(() => {
@ -284,9 +284,9 @@ export class VulnerabilityConfigComponent implements OnInit {
});
}
getSystemInfo(): Promise<SystemInfo> {
getSystemInfo(): Promise<void | SystemInfo> {
return toPromise<SystemInfo>(this.systemInfoService.getSystemInfo())
.then((info: SystemInfo) => this.systemInfo = info)
.catch(error => this.errorHandler.error(error));
}
}
}

View File

@ -11,21 +11,31 @@
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { ConfirmationTargets, ConfirmationButtons } from '../shared/shared.const';
import {
ConfirmationTargets,
ConfirmationButtons
} from "../shared/shared.const";
export class ConfirmationMessage {
public constructor(title: string, message: string, param: string, data: any, targetId: ConfirmationTargets, buttons?: ConfirmationButtons) {
this.title = title;
this.message = message;
this.data = data;
this.targetId = targetId;
this.param = param;
this.buttons = buttons ? buttons : ConfirmationButtons.CONFIRM_CANCEL;
}
title: string;
message: string;
data: any = {};//default is empty
targetId: ConfirmationTargets = ConfirmationTargets.EMPTY;
param: string;
buttons: ConfirmationButtons;
}
public constructor(
title: string,
message: string,
param: string,
data: any,
targetId: ConfirmationTargets,
buttons?: ConfirmationButtons
) {
this.title = title;
this.message = message;
this.data = data;
this.targetId = targetId;
this.param = param;
this.buttons = buttons ? buttons : ConfirmationButtons.CONFIRM_CANCEL;
}
title: string;
message: string;
data: any = {}; // default is empty
targetId: ConfirmationTargets = ConfirmationTargets.EMPTY;
param: string;
buttons: ConfirmationButtons;
}

View File

@ -23,4 +23,4 @@ export class ConfirmationAcknowledgement {
state: ConfirmationState = ConfirmationState.NA;
data: any = {};
source: ConfirmationTargets = ConfirmationTargets.EMPTY;
}
}

View File

@ -1,6 +1,6 @@
import { Type } from '@angular/core';
import { Type } from "@angular/core";
import { ConfirmationDialogComponent } from './confirmation-dialog.component';
import { ConfirmationDialogComponent } from "./confirmation-dialog.component";
export * from "./confirmation-dialog.component";
export * from "./confirmation-batch-message";
@ -9,4 +9,4 @@ export * from "./confirmation-state-message";
export const CONFIRMATION_DIALOG_DIRECTIVES: Type<any>[] = [
ConfirmationDialogComponent
];
];

View File

@ -1,35 +1,39 @@
import { ComponentFixture, TestBed, async, fakeAsync, tick } from '@angular/core/testing';
import {
ComponentFixture,
TestBed,
async
} from "@angular/core/testing";
import { NoopAnimationsModule } from "@angular/platform-browser/animations";
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { SharedModule } from '../shared/shared.module';
import { SharedModule } from "../shared/shared.module";
import { FilterComponent } from '../filter/filter.component';
import { CreateEditEndpointComponent } from '../create-edit-endpoint/create-edit-endpoint.component';
import { InlineAlertComponent } from '../inline-alert/inline-alert.component';
import { ErrorHandler } from '../error-handler/error-handler';
import { Endpoint } from '../service/interface';
import { EndpointService, EndpointDefaultService } from '../service/endpoint.service';
import { IServiceConfig, SERVICE_CONFIG } from '../service.config';
describe('CreateEditEndpointComponent (inline template)', () => {
import { FilterComponent } from "../filter/filter.component";
import { CreateEditEndpointComponent } from "../create-edit-endpoint/create-edit-endpoint.component";
import { InlineAlertComponent } from "../inline-alert/inline-alert.component";
import { ErrorHandler } from "../error-handler/error-handler";
import { Endpoint } from "../service/interface";
import {
EndpointService,
EndpointDefaultService
} from "../service/endpoint.service";
import { IServiceConfig, SERVICE_CONFIG } from "../service.config";
describe("CreateEditEndpointComponent (inline template)", () => {
let mockData: Endpoint = {
"id": 1,
"endpoint": "https://10.117.4.151",
"name": "target_01",
"username": "admin",
"password": "",
"insecure": false,
"type": 0
id: 1,
endpoint: "https://10.117.4.151",
name: "target_01",
username: "admin",
password: "",
insecure: false,
type: 0
};
let comp: CreateEditEndpointComponent;
let fixture: ComponentFixture<CreateEditEndpointComponent>;
let config: IServiceConfig = {
systemInfoEndpoint: '/api/endpoints/testing'
systemInfoEndpoint: "/api/endpoints/testing"
};
let endpointService: EndpointService;
@ -38,14 +42,12 @@ describe('CreateEditEndpointComponent (inline template)', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
SharedModule,
NoopAnimationsModule
imports: [SharedModule, NoopAnimationsModule],
declarations: [
FilterComponent,
CreateEditEndpointComponent,
InlineAlertComponent
],
declarations: [
FilterComponent,
CreateEditEndpointComponent,
InlineAlertComponent ],
providers: [
ErrorHandler,
{ provide: SERVICE_CONFIG, useValue: config },
@ -54,24 +56,26 @@ describe('CreateEditEndpointComponent (inline template)', () => {
});
}));
beforeEach(()=>{
beforeEach(() => {
fixture = TestBed.createComponent(CreateEditEndpointComponent);
comp = fixture.componentInstance;
endpointService = fixture.debugElement.injector.get(EndpointService);
spy = spyOn(endpointService, 'getEndpoint').and.returnValue(Promise.resolve(mockData));
spy = spyOn(endpointService, "getEndpoint").and.returnValue(
Promise.resolve(mockData)
);
fixture.detectChanges();
comp.openCreateEditTarget(true, 1);
fixture.detectChanges();
});
it('should be created', () => {
it("should be created", () => {
fixture.detectChanges();
expect(comp).toBeTruthy();
});
it('should get endpoint be called', async(() => {
it("should get endpoint be called", async(() => {
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
@ -79,16 +83,16 @@ describe('CreateEditEndpointComponent (inline template)', () => {
});
}));
it('should get endpoint and open modal', async(() => {
it("should get endpoint and open modal", async(() => {
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(comp.target.name).toEqual('target_01');
expect(comp.target.name).toEqual("target_01");
});
}));
it('should endpoint be initialized', () => {
it("should endpoint be initialized", () => {
fixture.detectChanges();
expect(config.systemInfoEndpoint).toEqual('/api/endpoints/testing');
expect(config.systemInfoEndpoint).toEqual("/api/endpoints/testing");
});
});
});

View File

@ -12,371 +12,367 @@
// See the License for the specific language governing permissions and
// limitations under the License.
import {
Component,
Output,
EventEmitter,
ViewChild,
AfterViewChecked,
ChangeDetectorRef,
OnDestroy
} from '@angular/core';
import { NgForm } from '@angular/forms';
Component,
Output,
EventEmitter,
ViewChild,
AfterViewChecked,
ChangeDetectorRef,
OnDestroy
} from "@angular/core";
import { NgForm } from "@angular/forms";
import { Subscription } from "rxjs/Subscription";
import { TranslateService } from "@ngx-translate/core";
import { EndpointService } from '../service/endpoint.service';
import { ErrorHandler } from '../error-handler/index';
import { ActionType } from '../shared/shared.const';
import { EndpointService } from "../service/endpoint.service";
import { ErrorHandler } from "../error-handler/index";
import { InlineAlertComponent } from "../inline-alert/inline-alert.component";
import { Endpoint } from "../service/interface";
import { toPromise, clone, compareValue, isEmptyObject } from "../utils";
import { InlineAlertComponent } from '../inline-alert/inline-alert.component';
import { Endpoint } from '../service/interface';
import { TranslateService } from '@ngx-translate/core';
import { toPromise, clone, compareValue, isEmptyObject } from '../utils';
import { Subscription } from 'rxjs/Subscription';
const FAKE_PASSWORD = 'rjGcfuRu';
const FAKE_PASSWORD = "rjGcfuRu";
@Component({
selector: 'hbr-create-edit-endpoint',
templateUrl: './create-edit-endpoint.component.html',
styleUrls: ['./create-edit-endpoint.component.scss']
selector: "hbr-create-edit-endpoint",
templateUrl: "./create-edit-endpoint.component.html",
styleUrls: ["./create-edit-endpoint.component.scss"]
})
export class CreateEditEndpointComponent implements AfterViewChecked, OnDestroy {
modalTitle: string;
createEditDestinationOpened: boolean;
staticBackdrop: boolean = true;
closable: boolean = false;
editable: boolean;
export class CreateEditEndpointComponent
implements AfterViewChecked, OnDestroy {
modalTitle: string;
createEditDestinationOpened: boolean;
staticBackdrop: boolean = true;
closable: boolean = false;
editable: boolean;
target: Endpoint = this.initEndpoint();
initVal: Endpoint;
target: Endpoint = this.initEndpoint();
initVal: Endpoint;
targetForm: NgForm;
@ViewChild('targetForm')
currentForm: NgForm;
targetForm: NgForm;
@ViewChild("targetForm") currentForm: NgForm;
testOngoing: boolean;
onGoing: boolean;
endpointId: number | string;
testOngoing: boolean;
onGoing: boolean;
endpointId: number | string;
@ViewChild(InlineAlertComponent)
inlineAlert: InlineAlertComponent;
@ViewChild(InlineAlertComponent) inlineAlert: InlineAlertComponent;
@Output() reload = new EventEmitter<boolean>();
@Output() reload = new EventEmitter<boolean>();
timerHandler: any;
valueChangesSub: Subscription;
formValues: { [key: string]: string } | any;
timerHandler: any;
valueChangesSub: Subscription;
formValues: { [key: string]: string } | any;
constructor(
private endpointService: EndpointService,
private errorHandler: ErrorHandler,
private translateService: TranslateService,
private ref: ChangeDetectorRef
) { }
constructor(
private endpointService: EndpointService,
private errorHandler: ErrorHandler,
private translateService: TranslateService,
private ref: ChangeDetectorRef
) {}
public get isValid(): boolean {
return !this.testOngoing &&
!this.onGoing &&
this.targetForm &&
this.targetForm.valid &&
this.editable &&
!compareValue(this.target, this.initVal);
public get isValid(): boolean {
return (
!this.testOngoing &&
!this.onGoing &&
this.targetForm &&
this.targetForm.valid &&
this.editable &&
!compareValue(this.target, this.initVal)
);
}
public get inProgress(): boolean {
return this.onGoing || this.testOngoing;
}
setInsecureValue($event: any) {
this.target.insecure = !$event;
}
ngOnDestroy(): void {
if (this.valueChangesSub) {
this.valueChangesSub.unsubscribe();
}
}
public get inProgress(): boolean {
return this.onGoing || this.testOngoing;
initEndpoint(): Endpoint {
return {
endpoint: "",
name: "",
username: "",
password: "",
insecure: false,
type: 0
};
}
open(): void {
this.createEditDestinationOpened = true;
}
close(): void {
this.createEditDestinationOpened = false;
}
reset(): void {
// Reset status variables
this.testOngoing = false;
this.onGoing = false;
// Reset data
this.target = this.initEndpoint();
this.initVal = this.initEndpoint();
this.formValues = null;
this.endpointId = "";
this.inlineAlert.close();
}
// Forcely refresh the view
forceRefreshView(duration: number): void {
// Reset timer
if (this.timerHandler) {
clearInterval(this.timerHandler);
}
this.timerHandler = setInterval(() => this.ref.markForCheck(), 100);
setTimeout(() => {
if (this.timerHandler) {
clearInterval(this.timerHandler);
this.timerHandler = null;
}
}, duration);
}
setInsecureValue($event: any) {
this.target.insecure = !$event;
openCreateEditTarget(editable: boolean, targetId?: number | string) {
this.editable = editable;
// reset
this.reset();
if (targetId) {
this.endpointId = targetId;
this.translateService
.get("DESTINATION.TITLE_EDIT")
.subscribe(res => (this.modalTitle = res));
toPromise<Endpoint>(this.endpointService.getEndpoint(targetId))
.then(target => {
this.target = target;
// Keep data cache
this.initVal = clone(target);
this.initVal.password = FAKE_PASSWORD;
this.target.password = FAKE_PASSWORD;
// Open the modal now
this.open();
this.forceRefreshView(2000);
})
.catch(error => this.errorHandler.error(error));
} else {
this.endpointId = "";
this.translateService
.get("DESTINATION.TITLE_ADD")
.subscribe(res => (this.modalTitle = res));
// Directly open the modal
this.open();
}
}
ngOnDestroy(): void {
if (this.valueChangesSub) {
this.valueChangesSub.unsubscribe();
}
}
initEndpoint(): Endpoint {
return {
endpoint: "",
name: "",
username: "",
password: "",
insecure: false,
type: 0
};
}
open(): void {
this.createEditDestinationOpened = true;
}
close(): void {
this.createEditDestinationOpened = false;
}
reset(): void {
//Reset status variables
this.testOngoing = false;
this.onGoing = false;
//Reset data
this.target = this.initEndpoint();
this.initVal = this.initEndpoint();
this.formValues = null;
this.endpointId = '';
this.inlineAlert.close();
}
//Forcely refresh the view
forceRefreshView(duration: number): void {
//Reset timer
if (this.timerHandler) {
clearInterval(this.timerHandler);
}
this.timerHandler = setInterval(() => this.ref.markForCheck(), 100);
setTimeout(() => {
if (this.timerHandler) {
clearInterval(this.timerHandler);
this.timerHandler = null;
}
}, duration);
}
openCreateEditTarget(editable: boolean, targetId?: number | string) {
this.editable = editable;
//reset
this.reset();
if (targetId) {
this.endpointId = targetId;
this.translateService.get('DESTINATION.TITLE_EDIT').subscribe(res => this.modalTitle = res);
toPromise<Endpoint>(this.endpointService
.getEndpoint(targetId))
.then(
target => {
this.target = target;
//Keep data cache
this.initVal = clone(target);
this.initVal.password = FAKE_PASSWORD;
this.target.password = FAKE_PASSWORD;
//Open the modal now
this.open();
this.forceRefreshView(2000);
})
.catch(error => this.errorHandler.error(error));
} else {
this.endpointId = '';
this.translateService.get('DESTINATION.TITLE_ADD').subscribe(res => this.modalTitle = res);
//Directly open the modal
this.open();
}
}
testConnection() {
let payload: Endpoint = this.initEndpoint();
if (!this.endpointId) {
payload.endpoint = this.target.endpoint;
payload.username = this.target.username;
payload.password = this.target.password;
payload.insecure = this.target.insecure;
}else {
let changes: {[key: string]: any} = this.getChanges();
for (let prop in payload) {
delete payload[prop];
}
payload.id = this.target.id;
if (!isEmptyObject(changes)) {
let changekeys: {[key: string]: any} = Object.keys(this.getChanges());
changekeys.forEach((key: string) => {
payload[key] = changes[key];
});
}
}
this.testOngoing = true;
toPromise<Endpoint>(this.endpointService
.pingEndpoint(payload))
.then(
response => {
this.inlineAlert.showInlineSuccess({ message: "DESTINATION.TEST_CONNECTION_SUCCESS" });
this.forceRefreshView(2000);
this.testOngoing = false;
}).catch(
error => {
this.inlineAlert.showInlineError('DESTINATION.TEST_CONNECTION_FAILURE');
this.forceRefreshView(2000);
this.testOngoing = false;
});
}
onSubmit() {
if (this.endpointId) {
this.updateEndpoint();
} else {
this.addEndpoint();
}
}
addEndpoint() {
if (this.onGoing) {
return;//Avoid duplicated submitting
}
this.onGoing = true;
toPromise<number>(this.endpointService
.createEndpoint(this.target))
.then(response => {
this.translateService.get('DESTINATION.CREATED_SUCCESS')
.subscribe(res => this.errorHandler.info(res));
this.reload.emit(true);
this.onGoing = false;
this.close();
this.forceRefreshView(2000);
}).catch(error => {
this.onGoing = false;
let errorMessageKey = this.handleErrorMessageKey(error.status);
this.translateService
.get(errorMessageKey)
.subscribe(res => {
this.inlineAlert.showInlineError(res);
});
this.forceRefreshView(2000);
}
);
}
updateEndpoint() {
if (this.onGoing) {
return;//Avoid duplicated submitting
}
let payload: Endpoint = this.initEndpoint();
for (let prop in payload) {
delete payload[prop];
}
let changes: {[key: string]: any} = this.getChanges();
if (isEmptyObject(changes)) {
return;
}
let changekeys: {[key: string]: any} = Object.keys(changes);
testConnection() {
let payload: Endpoint = this.initEndpoint();
if (!this.endpointId) {
payload.endpoint = this.target.endpoint;
payload.username = this.target.username;
payload.password = this.target.password;
payload.insecure = this.target.insecure;
} else {
let changes: { [key: string]: any } = this.getChanges();
for (let prop of Object.keys(payload)) {
delete payload[prop];
}
payload.id = this.target.id;
if (!isEmptyObject(changes)) {
let changekeys: { [key: string]: any } = Object.keys(this.getChanges());
changekeys.forEach((key: string) => {
payload[key] = changes[key];
payload[key] = changes[key];
});
if (!this.target.id) { return; }
this.onGoing = true;
toPromise<number>(this.endpointService
.updateEndpoint(this.target.id, payload))
.then(
response => {
this.translateService.get('DESTINATION.UPDATED_SUCCESS')
.subscribe(res => this.errorHandler.info(res));
this.reload.emit(true);
this.close();
this.onGoing = false;
this.forceRefreshView(2000);
})
.catch(
error => {
let errorMessageKey = this.handleErrorMessageKey(error.status);
this.translateService
.get(errorMessageKey)
.subscribe(res => {
this.inlineAlert.showInlineError(res);
});
this.onGoing = false;
this.forceRefreshView(2000);
}
);
}
}
handleErrorMessageKey(status: number): string {
switch (status) {
case 409:
return 'DESTINATION.CONFLICT_NAME';
case 400:
return 'DESTINATION.INVALID_NAME';
default:
return 'UNKNOWN_ERROR';
}
this.testOngoing = true;
toPromise<Endpoint>(this.endpointService.pingEndpoint(payload))
.then(response => {
this.inlineAlert.showInlineSuccess({
message: "DESTINATION.TEST_CONNECTION_SUCCESS"
});
this.forceRefreshView(2000);
this.testOngoing = false;
})
.catch(error => {
this.inlineAlert.showInlineError("DESTINATION.TEST_CONNECTION_FAILURE");
this.forceRefreshView(2000);
this.testOngoing = false;
});
}
onSubmit() {
if (this.endpointId) {
this.updateEndpoint();
} else {
this.addEndpoint();
}
}
addEndpoint() {
if (this.onGoing) {
return; // Avoid duplicated submitting
}
onCancel() {
let changes: {[key: string]: any} = this.getChanges();
if (!isEmptyObject(changes)) {
this.inlineAlert.showInlineConfirmation({ message: 'ALERT.FORM_CHANGE_CONFIRMATION' });
}else {
this.close();
if (this.targetForm) {
this.targetForm.reset();
}
}
}
confirmCancel(confirmed: boolean) {
this.inlineAlert.close();
this.onGoing = true;
toPromise<number>(this.endpointService.createEndpoint(this.target))
.then(response => {
this.translateService
.get("DESTINATION.CREATED_SUCCESS")
.subscribe(res => this.errorHandler.info(res));
this.reload.emit(true);
this.onGoing = false;
this.close();
this.forceRefreshView(2000);
})
.catch(error => {
this.onGoing = false;
let errorMessageKey = this.handleErrorMessageKey(error.status);
this.translateService.get(errorMessageKey).subscribe(res => {
this.inlineAlert.showInlineError(res);
});
this.forceRefreshView(2000);
});
}
updateEndpoint() {
if (this.onGoing) {
return; // Avoid duplicated submitting
}
ngAfterViewChecked(): void {
if (this.targetForm != this.currentForm) {
this.targetForm = this.currentForm;
if (this.targetForm) {
this.valueChangesSub = this.targetForm.valueChanges.subscribe((data: { [key: string]: string } | any) => {
if (data) {
//To avoid invalid change publish events
let keyNumber: number = 0;
for (let key in data) {
//Empty string "" is accepted
if (data[key] !== null) {
keyNumber++;
}
}
if (keyNumber !== 5) {
return;
}
let payload: Endpoint = this.initEndpoint();
for (let prop of Object.keys(payload)) {
delete payload[prop];
}
let changes: { [key: string]: any } = this.getChanges();
if (isEmptyObject(changes)) {
return;
}
let changekeys: { [key: string]: any } = Object.keys(changes);
if (!compareValue(this.formValues, data)) {
this.formValues = data;
this.inlineAlert.close();
}
}
});
changekeys.forEach((key: string) => {
payload[key] = changes[key];
});
if (!this.target.id) {
return;
}
this.onGoing = true;
toPromise<number>(
this.endpointService.updateEndpoint(this.target.id, payload)
)
.then(response => {
this.translateService
.get("DESTINATION.UPDATED_SUCCESS")
.subscribe(res => this.errorHandler.info(res));
this.reload.emit(true);
this.close();
this.onGoing = false;
this.forceRefreshView(2000);
})
.catch(error => {
let errorMessageKey = this.handleErrorMessageKey(error.status);
this.translateService.get(errorMessageKey).subscribe(res => {
this.inlineAlert.showInlineError(res);
});
this.onGoing = false;
this.forceRefreshView(2000);
});
}
handleErrorMessageKey(status: number): string {
switch (status) {
case 409:
return "DESTINATION.CONFLICT_NAME";
case 400:
return "DESTINATION.INVALID_NAME";
default:
return "UNKNOWN_ERROR";
}
}
onCancel() {
let changes: { [key: string]: any } = this.getChanges();
if (!isEmptyObject(changes)) {
this.inlineAlert.showInlineConfirmation({
message: "ALERT.FORM_CHANGE_CONFIRMATION"
});
} else {
this.close();
if (this.targetForm) {
this.targetForm.reset();
}
}
}
confirmCancel(confirmed: boolean) {
this.inlineAlert.close();
this.close();
}
ngAfterViewChecked(): void {
if (this.targetForm !== this.currentForm) {
this.targetForm = this.currentForm;
if (this.targetForm) {
this.valueChangesSub = this.targetForm.valueChanges.subscribe(
(data: { [key: string]: string } | any) => {
if (data) {
// To avoid invalid change publish events
let keyNumber: number = 0;
for (let key in data) {
// Empty string "" is accepted
if (data[key] !== null) {
keyNumber++;
}
}
if (keyNumber !== 5) {
return;
}
if (!compareValue(this.formValues, data)) {
this.formValues = data;
this.inlineAlert.close();
}
}
}
}
);
}
}
getChanges(): { [key: string]: any | any[] } {
let changes: { [key: string]: any | any[] } = {};
if (!this.target || !this.initVal) {
return changes;
}
for (let prop in this.target) {
let field: any = this.initVal[prop];
if (!compareValue(field, this.target[prop])) {
changes[prop] = this.target[prop];
//Number
if (typeof field === "number") {
changes[prop] = +changes[prop];
}
//Trim string value
if (typeof field === "string") {
changes[prop] = ('' + changes[prop]).trim();
}
}
}
getChanges(): { [key: string]: any | any[] } {
let changes: { [key: string]: any | any[] } = {};
if (!this.target || !this.initVal) {
return changes;
}
for (let prop of Object.keys(this.target)) {
let field: any = this.initVal[prop];
if (!compareValue(field, this.target[prop])) {
changes[prop] = this.target[prop];
// Number
if (typeof field === "number") {
changes[prop] = +changes[prop];
}
return changes;
// Trim string value
if (typeof field === "string") {
changes[prop] = ("" + changes[prop]).trim();
}
}
}
return changes;
}
}

View File

@ -4,4 +4,4 @@ import { CreateEditEndpointComponent } from './create-edit-endpoint.component';
export const CREATE_EDIT_ENDPOINT_DIRECTIVES: Type<any>[] = [
CreateEditEndpointComponent
];
];

View File

@ -1,85 +1,84 @@
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { ComponentFixture, TestBed, async } from "@angular/core/testing";
import { NoopAnimationsModule } from "@angular/platform-browser/animations";
import { SharedModule } from '../shared/shared.module';
import { FilterComponent } from '../filter/filter.component';
import { SharedModule } from "../shared/shared.module";
import { FilterComponent } from "../filter/filter.component";
import { InlineAlertComponent } from "../inline-alert/inline-alert.component";
import { ErrorHandler } from "../error-handler/error-handler";
import { Label } from "../service/interface";
import { IServiceConfig, SERVICE_CONFIG } from "../service.config";
import { CreateEditLabelComponent } from "./create-edit-label.component";
import { LabelDefaultService, LabelService } from "../service/label.service";
import { InlineAlertComponent } from '../inline-alert/inline-alert.component';
import { ErrorHandler } from '../error-handler/error-handler';
import {Label} from '../service/interface';
import { IServiceConfig, SERVICE_CONFIG } from '../service.config';
import {CreateEditLabelComponent} from "./create-edit-label.component";
import {LabelDefaultService, LabelService} from "../service/label.service";
describe("CreateEditLabelComponent (inline template)", () => {
let mockOneData: Label = {
color: "#9b0d54",
creation_time: "",
description: "",
id: 1,
name: "label0-g",
project_id: 0,
scope: "g",
update_time: ""
};
describe('CreateEditLabelComponent (inline template)', () => {
let comp: CreateEditLabelComponent;
let fixture: ComponentFixture<CreateEditLabelComponent>;
let mockOneData: Label = {
color: "#9b0d54",
creation_time: "",
description: "",
id: 1,
name: "label0-g",
project_id: 0,
scope: "g",
update_time: "",
}
let config: IServiceConfig = {
systemInfoEndpoint: "/api/label/testing"
};
let comp: CreateEditLabelComponent;
let fixture: ComponentFixture<CreateEditLabelComponent>;
let labelService: LabelService;
let config: IServiceConfig = {
systemInfoEndpoint: '/api/label/testing'
};
let spy: jasmine.Spy;
let spyOne: jasmine.Spy;
let labelService: LabelService;
let spy: jasmine.Spy;
let spyOne: jasmine.Spy;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
SharedModule,
NoopAnimationsModule
],
declarations: [
FilterComponent,
CreateEditLabelComponent,
InlineAlertComponent ],
providers: [
ErrorHandler,
{ provide: SERVICE_CONFIG, useValue: config },
{ provide: LabelService, useClass: LabelDefaultService }
]
});
}));
beforeEach(() => {
fixture = TestBed.createComponent(CreateEditLabelComponent);
comp = fixture.componentInstance;
labelService = fixture.debugElement.injector.get(LabelService);
spy = spyOn(labelService, 'getLabels').and.returnValue(Promise.resolve(mockOneData));
spyOne = spyOn(labelService, 'createLabel').and.returnValue(Promise.resolve(mockOneData));
fixture.detectChanges();
comp.openModal();
fixture.detectChanges();
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [SharedModule, NoopAnimationsModule],
declarations: [
FilterComponent,
CreateEditLabelComponent,
InlineAlertComponent
],
providers: [
ErrorHandler,
{ provide: SERVICE_CONFIG, useValue: config },
{ provide: LabelService, useClass: LabelDefaultService }
]
});
}));
it('should be created', () => {
fixture.detectChanges();
expect(comp).toBeTruthy();
beforeEach(() => {
fixture = TestBed.createComponent(CreateEditLabelComponent);
comp = fixture.componentInstance;
labelService = fixture.debugElement.injector.get(LabelService);
spy = spyOn(labelService, "getLabels").and.returnValue(
Promise.resolve(mockOneData)
);
spyOne = spyOn(labelService, "createLabel").and.returnValue(
Promise.resolve(mockOneData)
);
fixture.detectChanges();
comp.openModal();
fixture.detectChanges();
});
it("should be created", () => {
fixture.detectChanges();
expect(comp).toBeTruthy();
});
it("should get label and open modal", async(() => {
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(comp.labelModel.name).toEqual("");
});
it('should get label and open modal', async(() => {
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(comp.labelModel.name).toEqual('');
});
}));
});
}));
});

View File

@ -12,163 +12,177 @@
// See the License for the specific language governing permissions and
// limitations under the License.
import {
Component,
Output,
EventEmitter,
OnDestroy,
Input, OnInit, ViewChild, ChangeDetectionStrategy, ChangeDetectorRef
} from '@angular/core';
Component,
Output,
EventEmitter,
OnDestroy,
Input,
OnInit,
ViewChild,
ChangeDetectionStrategy,
ChangeDetectorRef
} from "@angular/core";
import {Label} from '../service/interface';
import { Label } from "../service/interface";
import {toPromise, clone, compareValue} from '../utils';
import { toPromise, clone, compareValue } from "../utils";
import {LabelService} from "../service/label.service";
import {ErrorHandler} from "../error-handler/error-handler";
import {NgForm} from "@angular/forms";
import {Subject} from "rxjs/Subject";
import {LabelColor} from "../shared/shared.const";
import { LabelService } from "../service/label.service";
import { ErrorHandler } from "../error-handler/error-handler";
import { NgForm } from "@angular/forms";
import { Subject } from "rxjs/Subject";
import { LabelColor } from "../shared/shared.const";
@Component({
selector: 'hbr-create-edit-label',
templateUrl: './create-edit-label.component.html',
styleUrls: ['./create-edit-label.component.scss'],
changeDetection: ChangeDetectionStrategy.Default
selector: "hbr-create-edit-label",
templateUrl: "./create-edit-label.component.html",
styleUrls: ["./create-edit-label.component.scss"],
changeDetection: ChangeDetectionStrategy.Default
})
export class CreateEditLabelComponent implements OnInit, OnDestroy {
formShow: boolean;
inProgress: boolean;
copeLabelModel: Label;
labelModel: Label = this.initLabel();
labelId = 0;
formShow: boolean;
inProgress: boolean;
copeLabelModel: Label;
labelModel: Label = this.initLabel();
labelId = 0;
checkOnGoing: boolean;
isLabelNameExist = false;
panelHidden = true;
checkOnGoing: boolean;
isLabelNameExist = false;
panelHidden = true;
nameChecker = new Subject<string>();
nameChecker = new Subject<string>();
labelForm: NgForm;
@ViewChild('labelForm')
currentForm: NgForm;
labelForm: NgForm;
@ViewChild("labelForm") currentForm: NgForm;
@Input() projectId: number;
@Input() scope: string;
@Output() reload = new EventEmitter();
@Input() projectId: number;
@Input() scope: string;
@Output() reload = new EventEmitter();
constructor(
private labelService: LabelService,
private errorHandler: ErrorHandler,
private ref: ChangeDetectorRef
) { }
constructor(
private labelService: LabelService,
private errorHandler: ErrorHandler,
private ref: ChangeDetectorRef
) {}
ngOnInit(): void {
this.nameChecker.debounceTime(500).subscribe((name: string) => {
this.checkOnGoing = true;
let labelName = this.currentForm.controls['name'].value;
toPromise<Label[]>(this.labelService.getLabels(this.scope, this.projectId, labelName))
.then(targets => {
if (targets && targets.length) {
this.isLabelNameExist = true;
}else {
this.isLabelNameExist = false;
}
this.checkOnGoing = false;
}).catch(error => {
this.checkOnGoing = false;
this.errorHandler.error(error)
});
setTimeout(() => {
setInterval(() => this.ref.markForCheck(), 100);
}, 3000);
ngOnInit(): void {
this.nameChecker.debounceTime(500).subscribe((name: string) => {
this.checkOnGoing = true;
let labelName = this.currentForm.controls["name"].value;
toPromise<Label[]>(
this.labelService.getLabels(this.scope, this.projectId, labelName)
)
.then(targets => {
if (targets && targets.length) {
this.isLabelNameExist = true;
} else {
this.isLabelNameExist = false;
}
this.checkOnGoing = false;
})
.catch(error => {
this.checkOnGoing = false;
this.errorHandler.error(error);
});
setTimeout(() => {
setInterval(() => this.ref.markForCheck(), 100);
}, 3000);
});
}
ngOnDestroy(): void {
this.nameChecker.unsubscribe();
}
get labelColor() {
return LabelColor;
}
initLabel(): Label {
return {
name: "",
description: "",
color: "",
scope: "",
project_id: 0
};
}
openModal(): void {
this.labelModel = this.initLabel();
this.formShow = true;
this.isLabelNameExist = false;
this.labelId = 0;
this.copeLabelModel = null;
}
editModel(labelId: number, label: Label[]): void {
this.labelModel = clone(label[0]);
this.formShow = true;
this.labelId = labelId;
this.copeLabelModel = clone(label[0]);
}
openColorPanel(): void {
this.panelHidden = false;
}
closeColorPanel(): void {
this.panelHidden = true;
}
public get hasChanged(): boolean {
return !compareValue(this.copeLabelModel, this.labelModel);
}
public get isValid(): boolean {
return !(
this.checkOnGoing ||
this.isLabelNameExist ||
!(this.currentForm && this.currentForm.valid) ||
!this.hasChanged ||
this.inProgress
);
}
existValid(text: string): void {
if (text) {
this.nameChecker.next(text);
}
}
onSubmit(): void {
this.inProgress = true;
if (this.labelId <= 0) {
this.labelModel.scope = this.scope;
this.labelModel.project_id = this.projectId;
toPromise<Label>(this.labelService.createLabel(this.labelModel))
.then(res => {
this.inProgress = false;
this.reload.emit();
this.labelModel = this.initLabel();
})
.catch(err => {
this.inProgress = false;
this.errorHandler.error(err);
});
} else {
toPromise<Label>(
this.labelService.updateLabel(this.labelId, this.labelModel)
)
.then(res => {
this.inProgress = false;
this.reload.emit();
this.labelModel = this.initLabel();
})
.catch(err => {
this.inProgress = false;
this.errorHandler.error(err);
});
}
}
ngOnDestroy(): void {
this.nameChecker.unsubscribe();
}
get labelColor() {
return LabelColor;
}
initLabel(): Label {
return {
name: '',
description: '',
color: '',
scope: '',
project_id: 0
};
}
openModal(): void {
this.labelModel = this.initLabel();
this.formShow = true;
this.isLabelNameExist = false;
this.labelId = 0;
this.copeLabelModel = null;
}
editModel(labelId: number, label: Label[]): void {
this.labelModel = clone(label[0]);
this.formShow = true;
this.labelId = labelId;
this.copeLabelModel = clone(label[0]);
}
openColorPanel(): void {
this.panelHidden = false;
}
closeColorPanel(): void {
this.panelHidden = true;
}
public get hasChanged(): boolean {
return !compareValue(this.copeLabelModel, this.labelModel);
}
public get isValid(): boolean {
return !(this.checkOnGoing || this.isLabelNameExist || !(this.currentForm && this.currentForm.valid) || !this.hasChanged || this.inProgress);
}
existValid(text: string): void {
if (text) {
this.nameChecker.next(text);
}
}
onSubmit(): void {
this.inProgress = true;
if (this.labelId <= 0) {
this.labelModel.scope = this.scope;
this.labelModel.project_id = this.projectId;
toPromise<Label>(this.labelService.createLabel(this.labelModel))
.then(res => {
this.inProgress = false;
this.reload.emit();
this.labelModel = this.initLabel();
}).catch(err => {
this.inProgress = false;
this.errorHandler.error(err)
});
} else {
toPromise<Label>(this.labelService.updateLabel(this.labelId, this.labelModel))
.then(res => {
this.inProgress = false;
this.reload.emit();
this.labelModel = this.initLabel();
}).catch(err => {
this.inProgress = false;
this.errorHandler.error(err)
});
}
}
onCancel(): void {
this.inProgress = false;
this.labelModel = this.initLabel();
this.formShow = false;
}
onCancel(): void {
this.inProgress = false;
this.labelModel = this.initLabel();
this.formShow = false;
}
}

View File

@ -1,6 +1,6 @@
import { Type } from '@angular/core';
import {CreateEditLabelComponent} from "./create-edit-label.component";
import { Type } from "@angular/core";
import { CreateEditLabelComponent } from "./create-edit-label.component";
export const CREATE_EDIT_LABEL_DIRECTIVES: Type<any>[] = [
CreateEditLabelComponent
];
];

View File

@ -1,214 +1,211 @@
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { ComponentFixture, TestBed, async } from "@angular/core/testing";
import { By } from "@angular/platform-browser";
import { DebugElement } from "@angular/core";
import { NoopAnimationsModule } from "@angular/platform-browser/animations";
import { SharedModule } from '../shared/shared.module';
import { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation-dialog.component';
import { ReplicationComponent } from '../replication/replication.component';
import { SharedModule } from "../shared/shared.module";
import { ConfirmationDialogComponent } from "../confirmation-dialog/confirmation-dialog.component";
import { ReplicationComponent } from "../replication/replication.component";
import { ListReplicationRuleComponent } from '../list-replication-rule/list-replication-rule.component';
import { ListReplicationRuleComponent } from "../list-replication-rule/list-replication-rule.component";
import { CreateEditRuleComponent } from './create-edit-rule.component';
import { DatePickerComponent } from '../datetime-picker/datetime-picker.component';
import { DateValidatorDirective } from '../datetime-picker/date-validator.directive';
import { FilterComponent } from '../filter/filter.component';
import { InlineAlertComponent } from '../inline-alert/inline-alert.component';
import { ReplicationRule, ReplicationJob, Endpoint, ReplicationJobItem } from '../service/interface';
import { CreateEditRuleComponent } from "./create-edit-rule.component";
import { DatePickerComponent } from "../datetime-picker/datetime-picker.component";
import { FilterComponent } from "../filter/filter.component";
import { InlineAlertComponent } from "../inline-alert/inline-alert.component";
import {
ReplicationRule,
ReplicationJob,
Endpoint,
ReplicationJobItem
} from "../service/interface";
import { ErrorHandler } from '../error-handler/error-handler';
import { SERVICE_CONFIG, IServiceConfig } from '../service.config';
import {
ReplicationService,
import { ErrorHandler } from "../error-handler/error-handler";
import { SERVICE_CONFIG, IServiceConfig } from "../service.config";
import {
ReplicationService,
ReplicationDefaultService,
JobLogService,
JobLogDefaultService
} from '../service/index';
import { EndpointService, EndpointDefaultService } from '../service/endpoint.service';
import {ProjectDefaultService, ProjectService} from "../service/project.service";
import { JobLogViewerComponent } from '../job-log-viewer/job-log-viewer.component';
import {Project} from "../project-policy-config/project";
describe('CreateEditRuleComponent (inline template)', ()=>{
} from "../service/index";
import {
EndpointService,
EndpointDefaultService
} from "../service/endpoint.service";
import {
ProjectDefaultService,
ProjectService
} from "../service/project.service";
import { JobLogViewerComponent } from "../job-log-viewer/job-log-viewer.component";
describe("CreateEditRuleComponent (inline template)", () => {
let mockRules: ReplicationRule[] = [
{
"id": 1,
"name": "sync_01",
"description": "",
"projects": [{ "project_id": 1,
"owner_id": 0,
"name": 'project_01',
"creation_time": '',
"deleted": 0,
"owner_name": '',
"togglable": false,
"update_time": '',
"current_user_role_id": 0,
"repo_count": 0,
"has_project_admin_role": false,
"is_member": false,
"role_name": '',
"metadata": {
"public": '',
"enable_content_trust": '',
"prevent_vul": '',
"severity": '',
"auto_scan": '',
id: 1,
name: "sync_01",
description: "",
projects: [
{
project_id: 1,
owner_id: 0,
name: "project_01",
creation_time: "",
deleted: 0,
owner_name: "",
togglable: false,
update_time: "",
current_user_role_id: 0,
repo_count: 0,
has_project_admin_role: false,
is_member: false,
role_name: "",
metadata: {
public: "",
enable_content_trust: "",
prevent_vul: "",
severity: "",
auto_scan: ""
}
}],
"targets": [{
"id": 1,
"endpoint": "https://10.117.4.151",
"name": "target_01",
"username": "admin",
"password": "",
"insecure": false,
"type": 0
}],
"trigger": {
"kind": "Manual",
"schedule_param": null
},
"filters": [],
"replicate_existing_image_now": false,
"replicate_deletion": false,
}]
}
],
targets: [
{
id: 1,
endpoint: "https://10.117.4.151",
name: "target_01",
username: "admin",
password: "",
insecure: false,
type: 0
}
],
trigger: {
kind: "Manual",
schedule_param: null
},
filters: [],
replicate_existing_image_now: false,
replicate_deletion: false
}
];
let mockJobs: ReplicationJobItem[] = [
{
"id": 1,
"status": "stopped",
"repository": "library/busybox",
"policy_id": 1,
"operation": "transfer",
"tags": null
id: 1,
status: "stopped",
repository: "library/busybox",
policy_id: 1,
operation: "transfer",
tags: null
},
{
"id": 2,
"status": "stopped",
"repository": "library/busybox",
"policy_id": 1,
"operation": "transfer",
"tags": null
id: 2,
status: "stopped",
repository: "library/busybox",
policy_id: 1,
operation: "transfer",
tags: null
},
{
"id": 3,
"status": "stopped",
"repository": "library/busybox",
"policy_id": 2,
"operation": "transfer",
"tags": null
id: 3,
status: "stopped",
repository: "library/busybox",
policy_id: 2,
operation: "transfer",
tags: null
}
];
let mockJob: ReplicationJob = {
metadata: {xTotalCount: 3},
metadata: { xTotalCount: 3 },
data: mockJobs
};
let mockEndpoints: Endpoint[] = [
{
"id": 1,
"endpoint": "https://10.117.4.151",
"name": "target_01",
"username": "admin",
"password": "",
"insecure": false,
"type": 0
id: 1,
endpoint: "https://10.117.4.151",
name: "target_01",
username: "admin",
password: "",
insecure: false,
type: 0
},
{
"id": 2,
"endpoint": "https://10.117.5.142",
"name": "target_02",
"username": "AAA",
"password": "",
"insecure": false,
"type": 0
id: 2,
endpoint: "https://10.117.5.142",
name: "target_02",
username: "AAA",
password: "",
insecure: false,
type: 0
},
{
"id": 3,
"endpoint": "https://101.1.11.111",
"name": "target_03",
"username": "admin",
"password": "",
"insecure": false,
"type": 0
id: 3,
endpoint: "https://101.1.11.111",
name: "target_03",
username: "admin",
password: "",
insecure: false,
type: 0
},
{
"id": 4,
"endpoint": "http://4.4.4.4",
"name": "target_04",
"username": "",
"password": "",
"insecure": true,
"type": 0
id: 4,
endpoint: "http://4.4.4.4",
name: "target_04",
username: "",
password: "",
insecure: true,
type: 0
}
];
let mockRule: ReplicationRule = {
"id": 1,
"name": "sync_01",
"description": "",
"projects": [{ "project_id": 1,
"owner_id": 0,
"name": 'project_01',
"creation_time": '',
"deleted": 0,
"owner_name": '',
"togglable": false,
"update_time": '',
"current_user_role_id": 0,
"repo_count": 0,
"has_project_admin_role": false,
"is_member": false,
"role_name": '',
"metadata": {
"public": '',
"enable_content_trust": '',
"prevent_vul": '',
"severity": '',
"auto_scan": '',
}
}],
"targets": [{
"id": 1,
"endpoint": "https://10.117.4.151",
"name": "target_01",
"username": "admin",
"password": "",
"insecure": false,
"type": 0
}],
"trigger": {
"kind": "Manual",
"schedule_param": null
},
"filters": [],
"replicate_existing_image_now": false,
"replicate_deletion": false,
}
let mockProjects: Project[] = [
{ "project_id": 1,
"owner_id": 0,
"name": 'project_01',
"creation_time": '',
"deleted": 0,
"owner_name": '',
"togglable": false,
"update_time": '',
"current_user_role_id": 0,
"repo_count": 0,
"has_project_admin_role": false,
"is_member": false,
"role_name": '',
"metadata": {
"public": '',
"enable_content_trust": '',
"prevent_vul": '',
"severity": '',
"auto_scan": '',
}
}];
id: 1,
name: "sync_01",
description: "",
projects: [
{
project_id: 1,
owner_id: 0,
name: "project_01",
creation_time: "",
deleted: 0,
owner_name: "",
togglable: false,
update_time: "",
current_user_role_id: 0,
repo_count: 0,
has_project_admin_role: false,
is_member: false,
role_name: "",
metadata: {
public: "",
enable_content_trust: "",
prevent_vul: "",
severity: "",
auto_scan: ""
}
}
],
targets: [
{
id: 1,
endpoint: "https://10.117.4.151",
name: "target_01",
username: "admin",
password: "",
insecure: false,
type: 0
}
],
trigger: {
kind: "Manual",
schedule_param: null
},
filters: [],
replicate_existing_image_now: false,
replicate_deletion: false
};
let fixture: ComponentFixture<ReplicationComponent>;
let fixtureCreate: ComponentFixture<CreateEditRuleComponent>;
@ -226,16 +223,13 @@ describe('CreateEditRuleComponent (inline template)', ()=>{
let spyEndpoint: jasmine.Spy;
let config: IServiceConfig = {
replicationJobEndpoint: '/api/jobs/replication/testing',
targetBaseEndpoint: '/api/targets/testing'
replicationJobEndpoint: "/api/jobs/replication/testing",
targetBaseEndpoint: "/api/targets/testing"
};
beforeEach(async(() =>{
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
SharedModule,
NoopAnimationsModule
],
imports: [SharedModule, NoopAnimationsModule],
declarations: [
ReplicationComponent,
ListReplicationRuleComponent,
@ -257,7 +251,7 @@ describe('CreateEditRuleComponent (inline template)', ()=>{
});
}));
beforeEach(()=>{
beforeEach(() => {
fixture = TestBed.createComponent(ReplicationComponent);
fixtureCreate = TestBed.createComponent(CreateEditRuleComponent);
comp = fixture.componentInstance;
@ -267,47 +261,53 @@ describe('CreateEditRuleComponent (inline template)', ()=>{
replicationService = fixture.debugElement.injector.get(ReplicationService);
endpointService = fixtureCreate.debugElement.injector.get(EndpointService);
endpointService = fixtureCreate.debugElement.injector.get(EndpointService) ;
spyRules = spyOn(
replicationService,
"getReplicationRules"
).and.returnValues(Promise.resolve(mockRules));
spyOneRule = spyOn(
replicationService,
"getReplicationRule"
).and.returnValue(Promise.resolve(mockRule));
spyJobs = spyOn(replicationService, "getJobs").and.returnValues(
Promise.resolve(mockJob)
);
spyRules = spyOn(replicationService, 'getReplicationRules').and.returnValues(Promise.resolve(mockRules));
spyOneRule = spyOn(replicationService, 'getReplicationRule').and.returnValue(Promise.resolve(mockRule));
spyJobs = spyOn(replicationService, 'getJobs').and.returnValues(Promise.resolve(mockJob));
spyEndpoint = spyOn(endpointService, 'getEndpoints').and.returnValues(Promise.resolve(mockEndpoints));
spyEndpoint = spyOn(endpointService, "getEndpoints").and.returnValues(
Promise.resolve(mockEndpoints)
);
fixture.detectChanges();
});
it('Should open creation modal and load endpoints', async(()=>{
it("Should open creation modal and load endpoints", async(() => {
fixture.detectChanges();
compCreate.openCreateEditRule();
fixture.whenStable().then(()=>{
fixture.whenStable().then(() => {
fixture.detectChanges();
let de: DebugElement = fixture.debugElement.query(By.css('input'));
let de: DebugElement = fixture.debugElement.query(By.css("input"));
expect(de).toBeTruthy();
let deSelect: DebugElement = fixture.debugElement.query(By.css('select'));
let deSelect: DebugElement = fixture.debugElement.query(By.css("select"));
expect(deSelect).toBeTruthy();
let elSelect: HTMLElement = de.nativeElement;
expect(elSelect).toBeTruthy();
expect(elSelect.childNodes.item(0).textContent).toEqual('target_01');
expect(elSelect.childNodes.item(0).textContent).toEqual("target_01");
});
}));
it('Should open modal to edit replication rule', async(()=>{
it("Should open modal to edit replication rule", async(() => {
fixture.detectChanges();
compCreate.openCreateEditRule(mockRule.id);
fixture.whenStable().then(()=>{
compCreate.openCreateEditRule(mockRule.id);
fixture.whenStable().then(() => {
fixture.detectChanges();
let de: DebugElement = fixture.debugElement.query(By.css('input'));
let de: DebugElement = fixture.debugElement.query(By.css("input"));
expect(de).toBeTruthy();
fixture.detectChanges();
let el: HTMLElement = de.nativeElement;
expect(el).toBeTruthy();
expect(el.textContent.trim()).toEqual('sync_01');
expect(el.textContent.trim()).toEqual("sync_01");
});
}));
});
});

View File

@ -11,32 +11,37 @@
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {Component, OnInit, OnDestroy, ViewChild, ChangeDetectorRef, Input, EventEmitter, Output} from '@angular/core';
import {Filter, ReplicationRule, Endpoint} from "../service/interface";
import {Subject} from "rxjs/Subject";
import {Subscription} from "rxjs/Subscription";
import {FormArray, FormBuilder, FormGroup, Validators} from "@angular/forms";
import {CreateEditEndpointComponent} from "../create-edit-endpoint/create-edit-endpoint.component";
import {Router, ActivatedRoute} from "@angular/router";
import {compareValue, isEmptyObject, toPromise} from "../utils";
import { InlineAlertComponent } from '../inline-alert/inline-alert.component';
import {ReplicationService} from "../service/replication.service";
import {ErrorHandler} from "../error-handler/error-handler";
import {TranslateService} from "@ngx-translate/core";
import {EndpointService} from "../service/endpoint.service";
import {ProjectService} from "../service/project.service";
import {Project} from "../project-policy-config/project";
import {
Component,
OnInit,
OnDestroy,
ViewChild,
ChangeDetectorRef,
Input,
EventEmitter,
Output
} from "@angular/core";
import { Filter, ReplicationRule, Endpoint } from "../service/interface";
import { Subject } from "rxjs/Subject";
import { Subscription } from "rxjs/Subscription";
import { FormArray, FormBuilder, FormGroup, Validators } from "@angular/forms";
import { compareValue, isEmptyObject, toPromise } from "../utils";
import { InlineAlertComponent } from "../inline-alert/inline-alert.component";
import { ReplicationService } from "../service/replication.service";
import { ErrorHandler } from "../error-handler/error-handler";
import { TranslateService } from "@ngx-translate/core";
import { EndpointService } from "../service/endpoint.service";
import { ProjectService } from "../service/project.service";
import { Project } from "../project-policy-config/project";
const ONE_HOUR_SECONDS = 3600;
const ONE_DAY_SECONDS: number = 24 * ONE_HOUR_SECONDS;
@Component ({
selector: 'hbr-create-edit-rule',
templateUrl: './create-edit-rule.component.html',
styleUrls: ['./create-edit-rule.component.scss']
@Component({
selector: "hbr-create-edit-rule",
templateUrl: "./create-edit-rule.component.html",
styleUrls: ["./create-edit-rule.component.scss"]
})
export class CreateEditRuleComponent implements OnInit, OnDestroy {
_localTime: Date = new Date();
targetList: Endpoint[] = [];
@ -51,15 +56,23 @@ export class CreateEditRuleComponent implements OnInit, OnDestroy {
noSelectedProject = true;
noSelectedEndpoint = true;
filterCount = 0;
triggerNames: string[] = ['Manual', 'Immediate', 'Scheduled'];
scheduleNames: string[] = ['Daily', 'Weekly'];
weekly: string[] = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
filterSelect: string[] = ['repository', 'tag'];
ruleNameTooltip = 'TOOLTIP.EMPTY';
headerTitle = 'REPLICATION.ADD_POLICY';
triggerNames: string[] = ["Manual", "Immediate", "Scheduled"];
scheduleNames: string[] = ["Daily", "Weekly"];
weekly: string[] = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"
];
filterSelect: string[] = ["repository", "tag"];
ruleNameTooltip = "TOOLTIP.EMPTY";
headerTitle = "REPLICATION.ADD_POLICY";
createEditRuleOpened: boolean;
filterListData: {[key: string]: any}[] = [];
filterListData: { [key: string]: any }[] = [];
inProgress = false;
inNameChecking = false;
isRuleNameExist = false;
@ -78,30 +91,30 @@ export class CreateEditRuleComponent implements OnInit, OnDestroy {
@Output() goToRegistry = new EventEmitter<any>();
@Output() reload = new EventEmitter<boolean>();
@ViewChild(InlineAlertComponent)
inlineAlert: InlineAlertComponent;
@ViewChild(InlineAlertComponent) inlineAlert: InlineAlertComponent;
emptyProject = {
project_id: -1,
name: '',
}
name: ""
};
emptyEndpoint = {
id: -1,
endpoint: '',
name: '',
username: '',
password: '',
endpoint: "",
name: "",
username: "",
password: "",
insecure: true,
type: 0,
}
type: 0
};
constructor(
private fb: FormBuilder,
private repService: ReplicationService,
private endpointService: EndpointService,
private errorHandler: ErrorHandler,
private proService: ProjectService,
private translateService: TranslateService,
public ref: ChangeDetectorRef) {
private fb: FormBuilder,
private repService: ReplicationService,
private endpointService: EndpointService,
private errorHandler: ErrorHandler,
private proService: ProjectService,
private translateService: TranslateService,
public ref: ChangeDetectorRef
) {
this.createForm();
}
@ -115,85 +128,99 @@ export class CreateEditRuleComponent implements OnInit, OnDestroy {
}
ngOnInit(): void {
toPromise<Endpoint[]>(this.endpointService
.getEndpoints())
.then(targets => {
this.targetList = targets || [];
}).catch((error: any) => this.errorHandler.error(error));
toPromise<Endpoint[]>(this.endpointService.getEndpoints())
.then(targets => {
this.targetList = targets || [];
})
.catch((error: any) => this.errorHandler.error(error));
if (!this.projectId) {
toPromise<Project[]>(this.proService.listProjects("", undefined))
.then(targets => {
this.projectList = targets || [];
}).catch(error => this.errorHandler.error(error));
.then(targets => {
this.projectList = targets || [];
})
.catch(error => this.errorHandler.error(error));
}
this.nameChecker.debounceTime(500).distinctUntilChanged().subscribe((ruleName: string) => {
this.isRuleNameExist = false;
this.inNameChecking = true;
toPromise<ReplicationRule[]>(this.repService.getReplicationRules(0, ruleName))
this.nameChecker
.debounceTime(500)
.distinctUntilChanged()
.subscribe((ruleName: string) => {
this.isRuleNameExist = false;
this.inNameChecking = true;
toPromise<ReplicationRule[]>(
this.repService.getReplicationRules(0, ruleName)
)
.then(response => {
if (response.some(rule => rule.name === ruleName)) {
this.ruleNameTooltip = 'TOOLTIP.RULE_USER_EXISTING';
this.ruleNameTooltip = "TOOLTIP.RULE_USER_EXISTING";
this.isRuleNameExist = true;
}
this.inNameChecking = false;
}).catch(() => {
this.inNameChecking = false;
})
.catch(() => {
this.inNameChecking = false;
});
});
});
this.proNameChecker
.debounceTime(500)
.distinctUntilChanged()
.subscribe((name: string) => {
this.noProjectInfo = '';
this.selectedProjectList = [];
toPromise<Project[]>(this.proService.listProjects(name, undefined)).then((res: any) => {
if (res) {
this.selectedProjectList = res.slice(0, 10);
// if input value exit in project list
let pro = res.find((data: any) => data.name === name);
if (!pro) {
this.noProjectInfo = 'REPLICATION.NO_PROJECT_INFO';
this.noSelectedProject = true;
} else {
this.noProjectInfo = '';
this.noSelectedProject = false;
this.setProject([pro])
}
} else {
this.noProjectInfo = 'REPLICATION.NO_PROJECT_INFO';
.debounceTime(500)
.distinctUntilChanged()
.subscribe((name: string) => {
this.noProjectInfo = "";
this.selectedProjectList = [];
toPromise<Project[]>(this.proService.listProjects(name, undefined))
.then((res: any) => {
if (res) {
this.selectedProjectList = res.slice(0, 10);
// if input value exit in project list
let pro = res.find((data: any) => data.name === name);
if (!pro) {
this.noProjectInfo = "REPLICATION.NO_PROJECT_INFO";
this.noSelectedProject = true;
} else {
this.noProjectInfo = "";
this.noSelectedProject = false;
this.setProject([pro]);
}
}).catch((error: any) => {
this.errorHandler.error(error);
this.noProjectInfo = 'REPLICATION.NO_PROJECT_INFO';
} else {
this.noProjectInfo = "REPLICATION.NO_PROJECT_INFO";
this.noSelectedProject = true;
});
});
}
})
.catch((error: any) => {
this.errorHandler.error(error);
this.noProjectInfo = "REPLICATION.NO_PROJECT_INFO";
this.noSelectedProject = true;
});
});
}
ngOnDestroy(): void {
if (this.confirmSub) {
this.confirmSub.unsubscribe();
}
if (this.nameChecker) {
this.nameChecker.unsubscribe();
}
if (this.proNameChecker) {
this.proNameChecker.unsubscribe();
}
ngOnDestroy(): void {
if (this.confirmSub) {
this.confirmSub.unsubscribe();
}
if (this.nameChecker) {
this.nameChecker.unsubscribe();
}
if (this.proNameChecker) {
this.proNameChecker.unsubscribe();
}
}
get isValid() {
return !(this.isRuleNameExist || this.noSelectedProject || this.noSelectedEndpoint || this.inProgress );
return !(
this.isRuleNameExist ||
this.noSelectedProject ||
this.noSelectedEndpoint ||
this.inProgress
);
}
createForm() {
this.ruleForm = this.fb.group({
name: ['', Validators.required],
description: '',
name: ["", Validators.required],
description: "",
projects: this.fb.array([]),
targets: this.fb.array([]),
trigger: this.fb.group({
@ -201,8 +228,8 @@ export class CreateEditRuleComponent implements OnInit, OnDestroy {
schedule_param: this.fb.group({
type: this.scheduleNames[0],
weekday: 1,
offtime: '08:00'
}),
offtime: "08:00"
})
}),
filters: this.fb.array([]),
replicate_existing_image_now: true,
@ -212,13 +239,16 @@ export class CreateEditRuleComponent implements OnInit, OnDestroy {
initForm(): void {
this.ruleForm.reset({
name: '',
description: '',
trigger: {kind: this.triggerNames[0], schedule_param: {
name: "",
description: "",
trigger: {
kind: this.triggerNames[0],
schedule_param: {
type: this.scheduleNames[0],
weekday: 1,
offtime: '08:00'
}},
offtime: "08:00"
}
},
replicate_existing_image_now: true,
replicate_deletion: false
});
@ -254,49 +284,49 @@ export class CreateEditRuleComponent implements OnInit, OnDestroy {
}
get projects(): FormArray {
return this.ruleForm.get('projects') as FormArray;
return this.ruleForm.get("projects") as FormArray;
}
setProject(projects: Project[]) {
const projectFGs = projects.map(project => this.fb.group(project));
const projectFormArray = this.fb.array(projectFGs);
this.ruleForm.setControl('projects', projectFormArray);
this.ruleForm.setControl("projects", projectFormArray);
}
get filters(): FormArray {
return this.ruleForm.get('filters') as FormArray;
return this.ruleForm.get("filters") as FormArray;
}
setFilter(filters: Filter[]) {
const filterFGs = filters.map(filter => this.fb.group(filter));
const filterFormArray = this.fb.array(filterFGs);
this.ruleForm.setControl('filters', filterFormArray);
this.ruleForm.setControl("filters", filterFormArray);
}
get targets(): FormArray {
return this.ruleForm.get('targets') as FormArray;
return this.ruleForm.get("targets") as FormArray;
}
setTarget(targets: Endpoint[]) {
const targetFGs = targets.map(target => this.fb.group(target));
const targetFormArray = this.fb.array(targetFGs);
this.ruleForm.setControl('targets', targetFormArray);
this.ruleForm.setControl("targets", targetFormArray);
}
initFilter(name: string) {
return this.fb.group({
kind: name,
pattern: ['', Validators.required]
pattern: ["", Validators.required]
});
}
filterChange($event: any) {
if ($event && $event.target['value']) {
if ($event && $event.target["value"]) {
let id: number = $event.target.id;
let name: string = $event.target.name;
let value: string = $event.target['value'];
let value: string = $event.target["value"];
this.filterListData.forEach((data, index) => {
if (index === +id) {
data.name = $event.target.name = value;
}else {
} else {
data.options.splice(data.options.indexOf(value), 1);
}
if (data.options.indexOf(name) === -1) {
@ -308,30 +338,32 @@ export class CreateEditRuleComponent implements OnInit, OnDestroy {
targetChange($event: any) {
if ($event && $event.target) {
if ($event.target['value'] === '-1') {
if ($event.target["value"] === "-1") {
this.noSelectedEndpoint = true;
return;
}
let selecedTarget: Endpoint = this.targetList.find(target => target.id === +$event.target['value']);
let selecedTarget: Endpoint = this.targetList.find(
target => target.id === +$event.target["value"]
);
this.setTarget([selecedTarget]);
this.noSelectedEndpoint = false;
}
}
// Handle the form validation
handleValidation(): void {
let cont = this.ruleForm.controls["projects"];
if (cont && cont.valid) {
this.proNameChecker.next(cont.value[0].name);
}
// Handle the form validation
handleValidation(): void {
let cont = this.ruleForm.controls["projects"];
if (cont && cont.valid) {
this.proNameChecker.next(cont.value[0].name);
}
}
focusClear($event: any): void {
if (this.policyId < 0 && this.firstClick === 0) {
if ($event && $event.target && $event.target['value']) {
$event.target['value'] = '';
if ($event && $event.target && $event.target["value"]) {
$event.target["value"] = "";
}
this.firstClick ++;
this.firstClick++;
}
}
@ -339,18 +371,20 @@ export class CreateEditRuleComponent implements OnInit, OnDestroy {
this.selectedProjectList = [];
}
selectedProjectName(projectName: string) {
this.noSelectedProject = false;
let pro: Project = this.selectedProjectList.find(data => data.name === projectName);
this.setProject([pro]);
this.selectedProjectList = [];
this.noProjectInfo = "";
}
selectedProjectName(projectName: string) {
this.noSelectedProject = false;
let pro: Project = this.selectedProjectList.find(
data => data.name === projectName
);
this.setProject([pro]);
this.selectedProjectList = [];
this.noProjectInfo = "";
}
selectedProject(project: Project): void {
if (!project) {
this.noSelectedProject = true;
}else {
} else {
this.noSelectedProject = false;
this.setProject([project]);
}
@ -358,16 +392,21 @@ export class CreateEditRuleComponent implements OnInit, OnDestroy {
addNewFilter(): void {
if (this.filterCount === 0) {
this.filterListData.push(this.baseFilterData(this.filterSelect[0], this.filterSelect.slice(), true));
this.filterListData.push(
this.baseFilterData(
this.filterSelect[0],
this.filterSelect.slice(),
true
)
);
this.filters.push(this.initFilter(this.filterSelect[0]));
}else {
} else {
let nameArr: string[] = this.filterSelect.slice();
this.filterListData.forEach(data => {
nameArr.splice(nameArr.indexOf(data.name), 1);
});
// when add a new filter,the filterListData should change the options
this.filterListData.filter((data) => {
this.filterListData.filter(data => {
data.options.splice(data.options.indexOf(nameArr[0]), 1);
});
this.filterListData.push(this.baseFilterData(nameArr[0], nameArr, true));
@ -395,14 +434,14 @@ export class CreateEditRuleComponent implements OnInit, OnDestroy {
}
});
}
const control = <FormArray>this.ruleForm.controls['filters'];
const control = <FormArray>this.ruleForm.controls["filters"];
control.removeAt(i);
}
}
selectTrigger($event: any): void {
if ($event && $event.target && $event.target['value']) {
let val: string = $event.target['value'];
if ($event && $event.target && $event.target["value"]) {
let val: string = $event.target["value"];
if (val === this.triggerNames[2]) {
this.isScheduleOpt = true;
this.isImmediate = false;
@ -420,14 +459,14 @@ export class CreateEditRuleComponent implements OnInit, OnDestroy {
// Replication Schedule select value exchange
selectSchedule($event: any): void {
if ($event && $event.target && $event.target['value']) {
switch ($event.target['value']) {
if ($event && $event.target && $event.target["value"]) {
switch ($event.target["value"]) {
case this.scheduleNames[1]:
this.weeklySchedule = true;
this.ruleForm.patchValue({
trigger: {
schedule_param: {
weekday: 1,
weekday: 1
}
}
});
@ -440,11 +479,11 @@ export class CreateEditRuleComponent implements OnInit, OnDestroy {
}
checkRuleName(): void {
let ruleName: string = this.ruleForm.controls['name'].value;
let ruleName: string = this.ruleForm.controls["name"].value;
if (ruleName) {
this.nameChecker.next(ruleName);
} else {
this.ruleNameTooltip = 'TOOLTIP.EMPTY';
this.ruleNameTooltip = "TOOLTIP.EMPTY";
}
}
@ -454,7 +493,7 @@ export class CreateEditRuleComponent implements OnInit, OnDestroy {
opt.splice(opt.indexOf(filter.kind), 1);
});
filters.forEach((filter: any) => {
let option: string [] = opt.slice();
let option: string[] = opt.slice();
option.unshift(filter.kind);
this.filterListData.push(this.baseFilterData(filter.kind, option, true));
});
@ -465,41 +504,49 @@ export class CreateEditRuleComponent implements OnInit, OnDestroy {
}
updateTrigger(trigger: any) {
if (trigger['schedule_param']) {
if (trigger["schedule_param"]) {
this.isScheduleOpt = true;
this.isImmediate = false;
trigger['schedule_param']['offtime'] = this.getOfftime(trigger['schedule_param']['offtime']);
if (trigger['schedule_param']['weekday']) {
trigger["schedule_param"]["offtime"] = this.getOfftime(
trigger["schedule_param"]["offtime"]
);
if (trigger["schedule_param"]["weekday"]) {
this.weeklySchedule = true;
}else {
} else {
// set default
trigger['schedule_param']['weekday'] = 1;
trigger["schedule_param"]["weekday"] = 1;
}
}else {
if (trigger['kind'] === this.triggerNames[0]) {
} else {
if (trigger["kind"] === this.triggerNames[0]) {
this.isImmediate = false;
}
if (trigger['kind'] === this.triggerNames[1]) {
if (trigger["kind"] === this.triggerNames[1]) {
this.isImmediate = true;
}
trigger['schedule_param'] = { type: this.scheduleNames[0],
trigger["schedule_param"] = {
type: this.scheduleNames[0],
weekday: this.weekly[0],
offtime: '08:00'};
offtime: "08:00"
};
}
return trigger;
}
setTriggerVaule(trigger: any) {
if (!this.isScheduleOpt) {
delete trigger['schedule_param'];
delete trigger["schedule_param"];
return trigger;
}else {
} else {
if (!this.weeklySchedule) {
delete trigger['schedule_param']['weekday'];
}else {
trigger['schedule_param']['weekday'] = +trigger['schedule_param']['weekday'];
delete trigger["schedule_param"]["weekday"];
} else {
trigger["schedule_param"]["weekday"] = +trigger["schedule_param"][
"weekday"
];
}
trigger['schedule_param']['offtime'] = this.setOfftime(trigger['schedule_param']['offtime']);
trigger["schedule_param"]["offtime"] = this.setOfftime(
trigger["schedule_param"]["offtime"]
);
return trigger;
}
}
@ -514,29 +561,35 @@ export class CreateEditRuleComponent implements OnInit, OnDestroy {
let copyRuleForm: ReplicationRule = this.ruleForm.value;
copyRuleForm.trigger = this.setTriggerVaule(copyRuleForm.trigger);
if (this.policyId < 0) {
this.repService.createReplicationRule(copyRuleForm)
.then(() => {
this.translateService.get('REPLICATION.CREATED_SUCCESS')
.subscribe(res => this.errorHandler.info(res));
this.inProgress = false;
this.reload.emit(true);
this.close();
}).catch((error: any) => {
this.inProgress = false;
this.inlineAlert.showInlineError(error);
});
this.repService
.createReplicationRule(copyRuleForm)
.then(() => {
this.translateService
.get("REPLICATION.CREATED_SUCCESS")
.subscribe(res => this.errorHandler.info(res));
this.inProgress = false;
this.reload.emit(true);
this.close();
})
.catch((error: any) => {
this.inProgress = false;
this.inlineAlert.showInlineError(error);
});
} else {
this.repService.updateReplicationRule(this.policyId, this.ruleForm.value)
.then(() => {
this.translateService.get('REPLICATION.UPDATED_SUCCESS')
.subscribe(res => this.errorHandler.info(res));
this.inProgress = false;
this.reload.emit(true);
this.close();
}).catch((error: any) => {
this.inProgress = false;
this.inlineAlert.showInlineError(error);
});
this.repService
.updateReplicationRule(this.policyId, this.ruleForm.value)
.then(() => {
this.translateService
.get("REPLICATION.UPDATED_SUCCESS")
.subscribe(res => this.errorHandler.info(res));
this.inProgress = false;
this.reload.emit(true);
this.close();
})
.catch((error: any) => {
this.inProgress = false;
this.inlineAlert.showInlineError(error);
});
}
}
@ -559,34 +612,39 @@ export class CreateEditRuleComponent implements OnInit, OnDestroy {
this.noProjectInfo = "";
this.noEndpointInfo = "";
if (this.targetList.length === 0) {
this.noEndpointInfo = 'REPLICATION.NO_ENDPOINT_INFO';
this.noEndpointInfo = "REPLICATION.NO_ENDPOINT_INFO";
}
if (this.projectList.length === 0 && !this.projectName) {
this.noProjectInfo = 'REPLICATION.NO_PROJECT_INFO';
this.noProjectInfo = "REPLICATION.NO_PROJECT_INFO";
}
if (ruleId) {
this.policyId = +ruleId;
this.headerTitle = 'REPLICATION.EDIT_POLICY_TITLE';
this.headerTitle = "REPLICATION.EDIT_POLICY_TITLE";
toPromise(this.repService.getReplicationRule(ruleId))
.then((response) => {
this.copyUpdateForm = Object.assign({}, response);
// set filter value is [] if callback fiter value is null.
this.copyUpdateForm.filters = response.filters ? response.filters : [];
this.updateForm(response);
}).catch((error: any) => {
this.inlineAlert.showInlineError(error);
});
}else {
this.headerTitle = 'REPLICATION.ADD_POLICY';
if (this.projectId) {
this.setProject([{project_id: this.projectId, name: this.projectName}]);
this.noSelectedProject = false;
}
this.copyUpdateForm = Object.assign({}, this.ruleForm.value);
.then(response => {
this.copyUpdateForm = Object.assign({}, response);
// set filter value is [] if callback fiter value is null.
this.copyUpdateForm.filters = response.filters
? response.filters
: [];
this.updateForm(response);
})
.catch((error: any) => {
this.inlineAlert.showInlineError(error);
});
} else {
this.headerTitle = "REPLICATION.ADD_POLICY";
if (this.projectId) {
this.setProject([
{ project_id: this.projectId, name: this.projectName }
]);
this.noSelectedProject = false;
}
this.copyUpdateForm = Object.assign({}, this.ruleForm.value);
}
}
close(): void {
this.createEditRuleOpened = false;
@ -599,8 +657,10 @@ export class CreateEditRuleComponent implements OnInit, OnDestroy {
onCancel(): void {
if (this.hasFormChange()) {
this.inlineAlert.showInlineConfirmation({ message: 'ALERT.FORM_CHANGE_CONFIRMATION' });
}else {
this.inlineAlert.showInlineConfirmation({
message: "ALERT.FORM_CHANGE_CONFIRMATION"
});
} else {
this.close();
}
}
@ -611,9 +671,8 @@ export class CreateEditRuleComponent implements OnInit, OnDestroy {
// UTC time
public getOfftime(daily_time: any): string {
let timeOffset = 0; // seconds
if (daily_time && typeof daily_time === 'number') {
if (daily_time && typeof daily_time === "number") {
timeOffset = +daily_time;
}
@ -631,27 +690,29 @@ export class CreateEditRuleComponent implements OnInit, OnDestroy {
// To time string
let hours: number = Math.floor(timeOffset / ONE_HOUR_SECONDS);
let minutes: number = Math.floor((timeOffset - hours * ONE_HOUR_SECONDS) / 60);
let minutes: number = Math.floor(
(timeOffset - hours * ONE_HOUR_SECONDS) / 60
);
let timeStr: string = '' + hours;
let timeStr: string = "" + hours;
if (hours < 10) {
timeStr = '0' + timeStr;
timeStr = "0" + timeStr;
}
if (minutes < 10) {
timeStr += ':0';
timeStr += ":0";
} else {
timeStr += ':';
timeStr += ":";
}
timeStr += minutes;
return timeStr;
}
public setOfftime(v: string) {
if (!v || v === '') {
if (!v || v === "") {
return;
}
let values: string[] = v.split(':');
let values: string[] = v.split(":");
if (!values || values.length !== 2) {
return;
}
@ -679,13 +740,21 @@ export class CreateEditRuleComponent implements OnInit, OnDestroy {
if (!ruleValue || !this.copyUpdateForm) {
return changes;
}
for (let prop in ruleValue) {
for (let prop of Object.keys(ruleValue)) {
let field: any = this.copyUpdateForm[prop];
if (!compareValue(field, ruleValue[prop])) {
if (ruleValue[prop][0] && ruleValue[prop][0].project_id && (ruleValue[prop][0].project_id === field[0].project_id)) {
if (
ruleValue[prop][0] &&
ruleValue[prop][0].project_id &&
ruleValue[prop][0].project_id === field[0].project_id
) {
break;
}
if (ruleValue[prop][0] && ruleValue[prop][0].id && (ruleValue[prop][0].id === field[0].id)) {
if (
ruleValue[prop][0] &&
ruleValue[prop][0].id &&
ruleValue[prop][0].id === field[0].id
) {
break;
}
changes[prop] = ruleValue[prop];
@ -696,12 +765,11 @@ export class CreateEditRuleComponent implements OnInit, OnDestroy {
// Trim string value
if (typeof field === "string") {
changes[prop] = ('' + changes[prop]).trim();
changes[prop] = ("" + changes[prop]).trim();
}
}
}
return changes;
}
}
}

View File

@ -1,7 +1,7 @@
import { Type } from '@angular/core';
import { Type } from "@angular/core";
import { CreateEditRuleComponent } from './create-edit-rule.component';
import { CreateEditRuleComponent } from "./create-edit-rule.component";
export const CREATE_EDIT_RULE_DIRECTIVES: Type<any>[] = [
CreateEditRuleComponent
];
];

View File

@ -11,40 +11,49 @@
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Directive, OnChanges, Input, SimpleChanges } from '@angular/core';
import { NG_VALIDATORS, Validator, Validators, ValidatorFn, AbstractControl } from '@angular/forms';
import { Directive, OnChanges, Input, SimpleChanges } from "@angular/core";
import {
NG_VALIDATORS,
Validator,
Validators,
ValidatorFn,
AbstractControl
} from "@angular/forms";
@Directive({
selector: '[dateValidator]',
providers: [{provide: NG_VALIDATORS, useExisting: DateValidatorDirective, multi: true}]
selector: "[dateValidator]",
providers: [
{ provide: NG_VALIDATORS, useExisting: DateValidatorDirective, multi: true }
]
})
export class DateValidatorDirective implements Validator, OnChanges {
@Input() dateValidator: string;
private valFn = Validators.nullValidator;
ngOnChanges(changes: SimpleChanges): void {
const change = changes['dateValidator'];
const change = changes["dateValidator"];
if (change) {
this.valFn = dateValidator();
} else {
this.valFn = Validators.nullValidator;
}
}
validate(control: AbstractControl): {[key: string]: any} {
validate(control: AbstractControl): { [key: string]: any } {
return this.valFn(control) || Validators.nullValidator;
}
}
export function dateValidator(): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} => {
return (control: AbstractControl): { [key: string]: any } => {
let controlValue = control.value;
let valid = true;
if(controlValue) {
const regYMD=/^(19|20)\d\d([- /.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])$/g;
const regDMY=/^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$/g;
valid = (regYMD.test(controlValue) || regDMY.test(controlValue));
}
return valid ? Validators.nullValidator : {'dateValidator': { value: controlValue }};
if (controlValue) {
const regYMD = /^(19|20)\d\d([- /.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])$/g;
const regDMY = /^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$/g;
valid = regYMD.test(controlValue) || regDMY.test(controlValue);
}
return valid
? Validators.nullValidator
: { dateValidator: { value: controlValue } };
};
}
}

View File

@ -1,17 +1,22 @@
import {Component, Input, Output, EventEmitter, ViewChild, OnChanges} from '@angular/core';
import { NgModel } from '@angular/forms';
import {
Component,
Input,
Output,
EventEmitter,
ViewChild,
OnChanges
} from "@angular/core";
import { NgModel } from "@angular/forms";
@Component({
selector: 'hbr-datetime',
templateUrl: './datetime-picker.component.html'
selector: "hbr-datetime",
templateUrl: "./datetime-picker.component.html"
})
export class DatePickerComponent implements OnChanges{
export class DatePickerComponent implements OnChanges {
@Input() dateInput: string;
@Input() oneDayOffset: boolean;
@ViewChild('searchTime')
searchTime: NgModel;
@ViewChild("searchTime") searchTime: NgModel;
@Output() search = new EventEmitter<string>();
@ -20,26 +25,37 @@ export class DatePickerComponent implements OnChanges{
}
get dateInvalid(): boolean {
return (this.searchTime.errors && this.searchTime.errors.dateValidator && (this.searchTime.dirty || this.searchTime.touched)) || false;
return (
(this.searchTime.errors &&
this.searchTime.errors.dateValidator &&
(this.searchTime.dirty || this.searchTime.touched)) ||
false
);
}
convertDate(strDate: string): string {
if(/^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$/.test(strDate)) {
if (
/^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$/.test(
strDate
)
) {
let parts = strDate.split(/[-\/]/);
strDate = parts[2] /*Year*/ + '-' +parts[1] /*Month*/ + '-' + parts[0] /*Date*/;
strDate =
parts[2] /*Year*/ + "-" + parts[1] /*Month*/ + "-" + parts[0] /*Date*/;
}
return strDate;
}
doSearch() {
let searchTerm: string = '';
if(this.searchTime.valid && this.dateInput) {
let timestamp: number = new Date(this.convertDate(this.searchTime.value)).getTime() / 1000;
if(this.oneDayOffset) {
let searchTerm: string = "";
if (this.searchTime.valid && this.dateInput) {
let timestamp: number =
new Date(this.convertDate(this.searchTime.value)).getTime() / 1000;
if (this.oneDayOffset) {
timestamp += 3600 * 24;
}
searchTerm = timestamp.toString();
}
this.search.emit(searchTerm);
}
this.search.emit(searchTerm);
}
}
}

View File

@ -1,8 +1,8 @@
import { Type } from '@angular/core';
import { Type } from "@angular/core";
import { DatePickerComponent } from './datetime-picker.component';
import { DateValidatorDirective } from './date-validator.directive';
import { DatePickerComponent } from "./datetime-picker.component";
import { DateValidatorDirective } from "./date-validator.directive";
export const DATETIME_PICKER_DIRECTIVES: Type<any>[] = [
DatePickerComponent,
DateValidatorDirective
];
];

View File

@ -3,7 +3,7 @@
<div>
<div class="row flex-items-xs-between rightPos">
<div class="flex-items-xs-middle option-right">
<hbr-filter [withDivider]="true" filterPlaceholder='{{"REPLICATION.FILTER_TARGETS_PLACEHOLDER" | translate}}' (filter)="doSearchTargets($event)" [currentValue]="targetName"></hbr-filter>
<hbr-filter [withDivider]="true" filterPlaceholder='{{"REPLICATION.FILTER_TARGETS_PLACEHOLDER" | translate}}' (filterEvt)="doSearchTargets($event)" [currentValue]="targetName"></hbr-filter>
<span class="refresh-btn" (click)="refreshTargets()">
<clr-icon shape="refresh"></clr-icon>
</span>

View File

@ -1,76 +1,80 @@
import { ComponentFixture, TestBed, async, fakeAsync, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { ComponentFixture, TestBed, async } from "@angular/core/testing";
import { By } from "@angular/platform-browser";
import { NoopAnimationsModule } from "@angular/platform-browser/animations";
import { DebugElement } from '@angular/core';
import { DebugElement } from "@angular/core";
import { SharedModule } from '../shared/shared.module';
import { EndpointComponent } from './endpoint.component';
import { FilterComponent } from '../filter/filter.component';
import { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation-dialog.component';
import { CreateEditEndpointComponent } from '../create-edit-endpoint/create-edit-endpoint.component';
import { InlineAlertComponent } from '../inline-alert/inline-alert.component';
import { ErrorHandler } from '../error-handler/error-handler';
import { Endpoint } from '../service/interface';
import { EndpointService, EndpointDefaultService } from '../service/endpoint.service';
import { IServiceConfig, SERVICE_CONFIG } from '../service.config';
import { SharedModule } from "../shared/shared.module";
import { EndpointComponent } from "./endpoint.component";
import { FilterComponent } from "../filter/filter.component";
import { ConfirmationDialogComponent } from "../confirmation-dialog/confirmation-dialog.component";
import { CreateEditEndpointComponent } from "../create-edit-endpoint/create-edit-endpoint.component";
import { InlineAlertComponent } from "../inline-alert/inline-alert.component";
import { ErrorHandler } from "../error-handler/error-handler";
import { Endpoint } from "../service/interface";
import {
EndpointService,
EndpointDefaultService
} from "../service/endpoint.service";
import { IServiceConfig, SERVICE_CONFIG } from "../service.config";
import { click } from '../utils';
describe('EndpointComponent (inline template)', () => {
import { click } from "../utils";
describe("EndpointComponent (inline template)", () => {
let mockData: Endpoint[] = [
{
"id": 1,
"endpoint": "https://10.117.4.151",
"name": "target_01",
"username": "admin",
"password": "",
"insecure": true,
"type": 0
id: 1,
endpoint: "https://10.117.4.151",
name: "target_01",
username: "admin",
password: "",
insecure: true,
type: 0
},
{
"id": 2,
"endpoint": "https://10.117.5.142",
"name": "target_02",
"username": "AAA",
"password": "",
"insecure": false,
"type": 0
id: 2,
endpoint: "https://10.117.5.142",
name: "target_02",
username: "AAA",
password: "",
insecure: false,
type: 0
},
{
"id": 3,
"endpoint": "https://101.1.11.111",
"name": "target_03",
"username": "admin",
"password": "",
"insecure": false,
"type": 0
id: 3,
endpoint: "https://101.1.11.111",
name: "target_03",
username: "admin",
password: "",
insecure: false,
type: 0
},
{
"id": 4,
"endpoint": "http://4.4.4.4",
"name": "target_04",
"username": "",
"password": "",
"insecure": false,
"type": 0
id: 4,
endpoint: "http://4.4.4.4",
name: "target_04",
username: "",
password: "",
insecure: false,
type: 0
}
];
let mockOne: Endpoint[] = [{
"id": 1,
"endpoint": "https://10.117.4.151",
"name": "target_01",
"username": "admin",
"password": "",
"insecure": false,
"type": 0
}];
let mockOne: Endpoint[] = [
{
id: 1,
endpoint: "https://10.117.4.151",
name: "target_01",
username: "admin",
password: "",
insecure: false,
type: 0
}
];
let comp: EndpointComponent;
let fixture: ComponentFixture<EndpointComponent>;
let config: IServiceConfig = {
systemInfoEndpoint: '/api/endpoints/testing'
systemInfoEndpoint: "/api/endpoints/testing"
};
let endpointService: EndpointService;
@ -79,16 +83,14 @@ describe('EndpointComponent (inline template)', () => {
let spyOne: jasmine.Spy;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
SharedModule,
NoopAnimationsModule
imports: [SharedModule, NoopAnimationsModule],
declarations: [
FilterComponent,
ConfirmationDialogComponent,
CreateEditEndpointComponent,
InlineAlertComponent,
EndpointComponent
],
declarations: [
FilterComponent,
ConfirmationDialogComponent,
CreateEditEndpointComponent,
InlineAlertComponent,
EndpointComponent ],
providers: [
ErrorHandler,
{ provide: SERVICE_CONFIG, useValue: config },
@ -97,87 +99,96 @@ describe('EndpointComponent (inline template)', () => {
});
}));
beforeEach(()=>{
beforeEach(() => {
fixture = TestBed.createComponent(EndpointComponent);
comp = fixture.componentInstance;
endpointService = fixture.debugElement.injector.get(EndpointService);
spy = spyOn(endpointService, 'getEndpoints').and.returnValues(Promise.resolve(mockData));
spyOnRules = spyOn(endpointService, 'getEndpointWithReplicationRules').and.returnValue([]);
spyOne = spyOn(endpointService, 'getEndpoint').and.returnValue(Promise.resolve(mockOne[0]));
spy = spyOn(endpointService, "getEndpoints").and.returnValues(
Promise.resolve(mockData)
);
spyOnRules = spyOn(
endpointService,
"getEndpointWithReplicationRules"
).and.returnValue([]);
spyOne = spyOn(endpointService, "getEndpoint").and.returnValue(
Promise.resolve(mockOne[0])
);
fixture.detectChanges();
});
});
it('should retrieve endpoint data', () => {
it("should retrieve endpoint data", () => {
fixture.detectChanges();
expect(spy.calls.any()).toBeTruthy();
});
it('should endpoint be initialized', () => {
it("should endpoint be initialized", () => {
fixture.detectChanges();
expect(config.systemInfoEndpoint).toEqual('/api/endpoints/testing');
expect(config.systemInfoEndpoint).toEqual("/api/endpoints/testing");
});
it('should open create endpoint modal', async(() => {
it("should open create endpoint modal", async(() => {
fixture.detectChanges();
fixture.whenStable().then(()=>{
fixture.whenStable().then(() => {
fixture.detectChanges();
comp.editTargets(mockOne);
fixture.detectChanges();
expect(comp.target.name).toEqual('target_01');
expect(comp.target.name).toEqual("target_01");
});
}));
it('should filter endpoints by keyword', async(() => {
it("should filter endpoints by keyword", async(() => {
fixture.detectChanges();
fixture.whenStable().then(()=>{
fixture.whenStable().then(() => {
fixture.detectChanges();
comp.doSearchTargets('target_02');
comp.doSearchTargets("target_02");
fixture.detectChanges();
expect(comp.targets.length).toEqual(1);
});
}));
it('should render data', async(()=>{
it("should render data", async(() => {
fixture.detectChanges();
fixture.whenStable().then(()=>{
fixture.whenStable().then(() => {
fixture.detectChanges();
let de: DebugElement = fixture.debugElement.query(By.css('datagrid-cell'));
let de: DebugElement = fixture.debugElement.query(
By.css("datagrid-cell")
);
expect(de).toBeTruthy();
let el: HTMLElement = de.nativeElement;
expect(el.textContent).toEqual('target_01');
expect(el.textContent).toEqual("target_01");
});
}));
it('should open creation endpoint', async(()=>{
it("should open creation endpoint", async(() => {
fixture.detectChanges();
fixture.whenStable().then(()=>{
let de: DebugElement = fixture.debugElement.query(By.css('btn-link'));
fixture.whenStable().then(() => {
let de: DebugElement = fixture.debugElement.query(By.css("btn-link"));
expect(de).toBeTruthy();
fixture.detectChanges();
click(de);
fixture.detectChanges();
let deInput: DebugElement = fixture.debugElement.query(By.css('input'));
let deInput: DebugElement = fixture.debugElement.query(By.css("input"));
expect(deInput).toBeTruthy();
});
}));
it('should open to edit existing endpoint', async(()=>{
it("should open to edit existing endpoint", async(() => {
fixture.detectChanges();
fixture.whenStable().then(()=>{
let de: DebugElement = fixture.debugElement.query(del=>del.classes['action-item']);
fixture.whenStable().then(() => {
let de: DebugElement = fixture.debugElement.query(
del => del.classes["action-item"]
);
expect(de).toBeTruthy();
fixture.detectChanges();
click(de);
fixture.detectChanges();
let deInput: DebugElement = fixture.debugElement.query(By.css('input'));
let deInput: DebugElement = fixture.debugElement.query(By.css("input"));
expect(deInput).toBeTruthy();
let elInput: HTMLElement = deInput.nativeElement;
expect(elInput).toBeTruthy();
expect(elInput.textContent).toEqual('target_01');
expect(elInput.textContent).toEqual("target_01");
});
}));
});
});

View File

@ -11,214 +11,239 @@
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Component, OnInit, OnDestroy, ViewChild, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { Endpoint, ReplicationRule } from '../service/interface';
import { EndpointService } from '../service/endpoint.service';
import {
Component,
OnInit,
OnDestroy,
ViewChild,
ChangeDetectionStrategy,
ChangeDetectorRef
} from "@angular/core";
import { Endpoint } from "../service/interface";
import { EndpointService } from "../service/endpoint.service";
import { TranslateService } from '@ngx-translate/core';
import { TranslateService } from "@ngx-translate/core";
import { ErrorHandler } from '../error-handler/index';
import { ErrorHandler } from "../error-handler/index";
import { ConfirmationMessage } from '../confirmation-dialog/confirmation-message';
import { ConfirmationAcknowledgement } from '../confirmation-dialog/confirmation-state-message';
import { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation-dialog.component';
import { ConfirmationMessage } from "../confirmation-dialog/confirmation-message";
import { ConfirmationAcknowledgement } from "../confirmation-dialog/confirmation-state-message";
import { ConfirmationDialogComponent } from "../confirmation-dialog/confirmation-dialog.component";
import { ConfirmationTargets, ConfirmationState, ConfirmationButtons } from '../shared/shared.const';
import {
ConfirmationTargets,
ConfirmationState,
ConfirmationButtons
} from "../shared/shared.const";
import { Subscription } from 'rxjs/Subscription';
import { Subscription } from "rxjs/Subscription";
import { CreateEditEndpointComponent } from '../create-edit-endpoint/create-edit-endpoint.component';
import { CreateEditEndpointComponent } from "../create-edit-endpoint/create-edit-endpoint.component";
import { toPromise, CustomComparator } from '../utils';
import { toPromise, CustomComparator } from "../utils";
import { State, Comparator } from 'clarity-angular';
import {BatchInfo, BathInfoChanges} from "../confirmation-dialog/confirmation-batch-message";
import {Observable} from "rxjs/Observable";
import { Comparator } from "clarity-angular";
import {
BatchInfo,
BathInfoChanges
} from "../confirmation-dialog/confirmation-batch-message";
import { Observable } from "rxjs/Observable";
@Component({
selector: 'hbr-endpoint',
templateUrl: './endpoint.component.html',
styleUrls: ['./endpoint.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
selector: "hbr-endpoint",
templateUrl: "./endpoint.component.html",
styleUrls: ["./endpoint.component.scss"],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class EndpointComponent implements OnInit, OnDestroy {
@ViewChild(CreateEditEndpointComponent)
createEditEndpointComponent: CreateEditEndpointComponent;
@ViewChild(CreateEditEndpointComponent)
createEditEndpointComponent: CreateEditEndpointComponent;
@ViewChild("confirmationDialog")
confirmationDialogComponent: ConfirmationDialogComponent;
targets: Endpoint[];
target: Endpoint;
@ViewChild('confirmationDialog')
confirmationDialogComponent: ConfirmationDialogComponent;
targetName: string;
subscription: Subscription;
targets: Endpoint[];
target: Endpoint;
loading: boolean = false;
targetName: string;
subscription: Subscription;
creationTimeComparator: Comparator<Endpoint> = new CustomComparator<Endpoint>(
"creation_time",
"date"
);
loading: boolean = false;
timerHandler: any;
selectedRow: Endpoint[] = [];
batchDelectionInfos: BatchInfo[] = [];
creationTimeComparator: Comparator<Endpoint> = new CustomComparator<Endpoint>('creation_time', 'date');
get initEndpoint(): Endpoint {
return {
endpoint: "",
name: "",
username: "",
password: "",
insecure: false,
type: 0
};
}
timerHandler: any;
selectedRow: Endpoint[] = [];
batchDelectionInfos: BatchInfo[] = [];
constructor(
private endpointService: EndpointService,
private errorHandler: ErrorHandler,
private translateService: TranslateService,
private ref: ChangeDetectorRef
) {
this.forceRefreshView(1000);
}
get initEndpoint(): Endpoint {
return {
endpoint: "",
name: "",
username: "",
password: "",
insecure: false,
type: 0
};
ngOnInit(): void {
this.targetName = "";
this.retrieve();
}
ngOnDestroy(): void {
if (this.subscription) {
this.subscription.unsubscribe();
}
}
selectedChange(): void {
this.forceRefreshView(5000);
}
constructor(
private endpointService: EndpointService,
private errorHandler: ErrorHandler,
private translateService: TranslateService,
private ref: ChangeDetectorRef) {
retrieve(): void {
this.loading = true;
this.selectedRow = [];
toPromise<Endpoint[]>(this.endpointService.getEndpoints(this.targetName))
.then(targets => {
this.targets = targets || [];
this.forceRefreshView(1000);
}
this.loading = false;
})
.catch(error => {
this.errorHandler.error(error);
this.loading = false;
});
}
ngOnInit(): void {
this.targetName = '';
this.retrieve();
}
doSearchTargets(targetName: string) {
this.targetName = targetName;
this.retrieve();
}
ngOnDestroy(): void {
if (this.subscription) {
this.subscription.unsubscribe();
refreshTargets() {
this.retrieve();
}
reload($event: any) {
this.targetName = "";
this.retrieve();
}
openModal() {
this.createEditEndpointComponent.openCreateEditTarget(true);
this.target = this.initEndpoint;
}
editTargets(targets: Endpoint[]) {
if (targets && targets.length === 1) {
let target = targets[0];
let editable = true;
if (!target.id) {
return;
}
let id: number | string = target.id;
this.createEditEndpointComponent.openCreateEditTarget(editable, id);
}
}
deleteTargets(targets: Endpoint[]) {
if (targets && targets.length) {
let targetNames: string[] = [];
this.batchDelectionInfos = [];
targets.forEach(target => {
targetNames.push(target.name);
let initBatchMessage = new BatchInfo();
initBatchMessage.name = target.name;
this.batchDelectionInfos.push(initBatchMessage);
});
let deletionMessage = new ConfirmationMessage(
"REPLICATION.DELETION_TITLE_TARGET",
"REPLICATION.DELETION_SUMMARY_TARGET",
targetNames.join(", ") || "",
targets,
ConfirmationTargets.TARGET,
ConfirmationButtons.DELETE_CANCEL
);
this.confirmationDialogComponent.open(deletionMessage);
}
}
confirmDeletion(message: ConfirmationAcknowledgement) {
if (
message &&
message.source === ConfirmationTargets.TARGET &&
message.state === ConfirmationState.CONFIRMED
) {
let targetLists: Endpoint[] = message.data;
if (targetLists && targetLists.length) {
let promiseLists: any[] = [];
targetLists.forEach(target => {
promiseLists.push(this.delOperate(target.id, target.name));
});
Promise.all(promiseLists).then(item => {
this.selectedRow = [];
this.reload(true);
this.forceRefreshView(2000);
});
}
}
}
delOperate(id: number | string, name: string) {
let findedList = this.batchDelectionInfos.find(data => data.name === name);
return toPromise<number>(this.endpointService.deleteEndpoint(id))
.then(response => {
this.translateService.get("BATCH.DELETED_SUCCESS").subscribe(res => {
findedList = BathInfoChanges(findedList, res);
});
})
.catch(error => {
if (error && error.status === 412) {
Observable.forkJoin(
this.translateService.get("BATCH.DELETED_FAILURE"),
this.translateService.get(
"DESTINATION.FAILED_TO_DELETE_TARGET_IN_USED"
)
).subscribe(res => {
findedList = BathInfoChanges(
findedList,
res[0],
false,
true,
res[1]
);
});
} else {
this.translateService.get("BATCH.DELETED_FAILURE").subscribe(res => {
findedList = BathInfoChanges(findedList, res, false, true);
});
}
});
}
// Forcely refresh the view
forceRefreshView(duration: number): void {
// Reset timer
if (this.timerHandler) {
clearInterval(this.timerHandler);
}
selectedChange(): void {
this.forceRefreshView(5000);
}
retrieve(): void {
this.loading = true;
this.selectedRow = [];
toPromise<Endpoint[]>(this.endpointService
.getEndpoints(this.targetName))
.then(
targets => {
this.targets = targets || [];
this.forceRefreshView(1000);
this.loading = false;
}).catch(error => {
this.errorHandler.error(error);
this.loading = false;
});
}
doSearchTargets(targetName: string) {
this.targetName = targetName;
this.retrieve();
}
refreshTargets() {
this.retrieve();
}
reload($event: any) {
this.targetName = '';
this.retrieve();
}
openModal() {
this.createEditEndpointComponent.openCreateEditTarget(true);
this.target = this.initEndpoint;
}
editTargets(targets: Endpoint[]) {
if (targets && targets.length === 1) {
let target = targets[0];
let editable = true;
if (!target.id) {
return;
}
let id: number | string = target.id;
this.createEditEndpointComponent.openCreateEditTarget(editable, id);
}
}
deleteTargets(targets: Endpoint[]) {
if (targets && targets.length) {
let targetNames: string[] = [];
this.batchDelectionInfos = [];
targets.forEach(target => {
targetNames.push(target.name);
let initBatchMessage = new BatchInfo ();
initBatchMessage.name = target.name;
this.batchDelectionInfos.push(initBatchMessage);
});
let deletionMessage = new ConfirmationMessage(
'REPLICATION.DELETION_TITLE_TARGET',
'REPLICATION.DELETION_SUMMARY_TARGET',
targetNames.join(', ') || '',
targets,
ConfirmationTargets.TARGET,
ConfirmationButtons.DELETE_CANCEL);
this.confirmationDialogComponent.open(deletionMessage);
}
}
confirmDeletion(message: ConfirmationAcknowledgement) {
if (message &&
message.source === ConfirmationTargets.TARGET &&
message.state === ConfirmationState.CONFIRMED) {
let targetLists: Endpoint[] = message.data;
if (targetLists && targetLists.length) {
let promiseLists: any[] = [];
targetLists.forEach(target => {
promiseLists.push(this.delOperate(target.id, target.name));
})
Promise.all(promiseLists).then((item) => {
this.selectedRow = [];
this.reload(true);
this.forceRefreshView(2000);
});
}
}
}
delOperate(id: number | string, name: string) {
let findedList = this.batchDelectionInfos.find(data => data.name === name);
return toPromise<number>(this.endpointService
.deleteEndpoint(id))
.then(
response => {
this.translateService.get('BATCH.DELETED_SUCCESS')
.subscribe(res => {
findedList = BathInfoChanges(findedList, res);
});
}).catch(
error => {
if (error && error.status === 412) {
Observable.forkJoin(this.translateService.get('BATCH.DELETED_FAILURE'),
this.translateService.get('DESTINATION.FAILED_TO_DELETE_TARGET_IN_USED')).subscribe(res => {
findedList = BathInfoChanges(findedList, res[0], false, true, res[1]);
});
} else {
this.translateService.get('BATCH.DELETED_FAILURE').subscribe(res => {
findedList = BathInfoChanges(findedList, res, false, true);
});
}
});
}
//Forcely refresh the view
forceRefreshView(duration: number): void {
//Reset timer
if (this.timerHandler) {
clearInterval(this.timerHandler);
}
this.timerHandler = setInterval(() => this.ref.markForCheck(), 100);
setTimeout(() => {
if (this.timerHandler) {
clearInterval(this.timerHandler);
this.timerHandler = null;
}
}, duration);
}
}
this.timerHandler = setInterval(() => this.ref.markForCheck(), 100);
setTimeout(() => {
if (this.timerHandler) {
clearInterval(this.timerHandler);
this.timerHandler = null;
}
}, duration);
}
}

View File

@ -1,7 +1,4 @@
import { Type } from '@angular/core';
import { EndpointComponent } from './endpoint.component';
import { Type } from "@angular/core";
import { EndpointComponent } from "./endpoint.component";
export const ENDPOINT_DIRECTIVES: Type<any>[] = [
EndpointComponent
];
export const ENDPOINT_DIRECTIVES: Type<any>[] = [EndpointComponent];

View File

@ -2,69 +2,69 @@ import { Injectable } from "@angular/core";
/**
* Declare interface for error handling
*
*
* @export
* @abstract
* @class ErrorHandler
*/
export abstract class ErrorHandler {
/**
* Send message with error level
*
* @abstract
* @param {*} error
*
* @memberOf ErrorHandler
*/
abstract error(error: any): void;
/**
* Send message with error level
*
* @abstract
* @param {*} error
*
* @memberOf ErrorHandler
*/
abstract error(error: any): void;
/**
* Send message with warning level
*
* @abstract
* @param {*} warning
*
* @memberOf ErrorHandler
*/
abstract warning(warning: any): void;
/**
* Send message with warning level
*
* @abstract
* @param {*} warning
*
* @memberOf ErrorHandler
*/
abstract warning(warning: any): void;
/**
* Send message with info level
*
* @abstract
* @param {*} info
*
* @memberOf ErrorHandler
*/
abstract info(info: any): void;
/**
* Send message with info level
*
* @abstract
* @param {*} info
*
* @memberOf ErrorHandler
*/
abstract info(info: any): void;
/**
* Handle log message
*
* @abstract
* @param {*} log
*
* @memberOf ErrorHandler
*/
abstract log(log: any): void;
/**
* Handle log message
*
* @abstract
* @param {*} log
*
* @memberOf ErrorHandler
*/
abstract log(log: any): void;
}
@Injectable()
export class DefaultErrorHandler extends ErrorHandler {
public error(error: any): void {
console.error("[Default error handler]: ", error);
}
public error(error: any): void {
console.error("[Default error handler]: ", error);
}
public warning(warning: any): void {
console.warn("[Default warning handler]: ", warning);
}
public warning(warning: any): void {
console.warn("[Default warning handler]: ", warning);
}
public info(info: any): void {
console.info("[Default info handler]: ", info);
}
public info(info: any): void {
// tslint:disable-next-line:no-console
console.info("[Default info handler]: ", info);
}
public log(log: any): void {
console.log("[Default log handler]: ", log);
}
}
public log(log: any): void {
console.log("[Default log handler]: ", log);
}
}

View File

@ -1 +1 @@
export * from './error-handler';
export * from "./error-handler";

View File

@ -11,66 +11,60 @@
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Component, Input, Output, OnInit, EventEmitter } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import { Component, Input, Output, OnInit, EventEmitter } from "@angular/core";
import { Subject } from "rxjs/Subject";
import "rxjs/add/operator/debounceTime";
import "rxjs/add/operator/distinctUntilChanged";
@Component({
selector: 'hbr-filter',
templateUrl: './filter.component.html',
styleUrls: ['./filter.component.scss']
selector: "hbr-filter",
templateUrl: "./filter.component.html",
styleUrls: ["./filter.component.scss"]
})
export class FilterComponent implements OnInit {
placeHolder: string = "";
filterTerms = new Subject<string>();
isExpanded: boolean = false;
placeHolder: string = "";
filterTerms = new Subject<string>();
isExpanded: boolean = false;
@Output() private filterEvt = new EventEmitter<string>();
@Output() private openFlag = new EventEmitter<boolean>();
@Output("filter") private filterEvt = new EventEmitter<string>();
@Output() private openFlag = new EventEmitter<boolean>();
@Input() currentValue: string;
@Input("filterPlaceholder")
public set flPlaceholder(placeHolder: string) {
this.placeHolder = placeHolder;
}
@Input() expandMode: boolean = false;
@Input() withDivider: boolean = false;
@Input() currentValue: string;
@Input("filterPlaceholder")
public set flPlaceholder(placeHolder: string) {
this.placeHolder = placeHolder;
ngOnInit(): void {
this.filterTerms
.debounceTime(500)
.subscribe(terms => {
this.filterEvt.emit(terms);
});
}
valueChange(): void {
// Send out filter terms
this.filterTerms.next(this.currentValue.trim());
}
inputFocus(): void {
this.openFlag.emit(this.isExpanded);
}
onClick(): void {
// Only enabled when expandMode is set to false
if (this.expandMode) {
return;
}
@Input() expandMode: boolean = false;
@Input() withDivider: boolean = false;
this.isExpanded = !this.isExpanded;
this.openFlag.emit(this.isExpanded);
}
ngOnInit(): void {
this.filterTerms
.debounceTime(500)
//.distinctUntilChanged()
.subscribe(terms => {
this.filterEvt.emit(terms);
});
}
valueChange(): void {
//Send out filter terms
this.filterTerms.next(this.currentValue.trim());
}
inputFocus(): void {
this.openFlag.emit(this.isExpanded);
}
onClick(): void {
//Only enabled when expandMode is set to false
if(this.expandMode){
return;
}
this.isExpanded = !this.isExpanded;
this.openFlag.emit(this.isExpanded);
}
public get isShowSearchBox(): boolean {
return this.expandMode || (!this.expandMode && this.isExpanded);
}
}
public get isShowSearchBox(): boolean {
return this.expandMode || (!this.expandMode && this.isExpanded);
}
}

View File

@ -5,4 +5,4 @@ export * from "./filter.component";
export const FILTER_DIRECTIVES: Type<any>[] = [
FilterComponent
];
];

View File

@ -9,19 +9,28 @@
* conditions of the subcomponent's license, as noted in the LICENSE file.
*/
import { Component, Input, Output, SimpleChanges, ContentChild, ViewChild, ViewChildren,
TemplateRef, HostListener, ViewEncapsulation, EventEmitter, AfterViewInit } from '@angular/core';
import { CancelablePromise } from '../shared/shared.utils';
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';
import {
Component,
Input,
Output,
ContentChild,
ViewChild,
ViewChildren,
TemplateRef,
HostListener,
ViewEncapsulation,
EventEmitter,
AfterViewInit
} from "@angular/core";
import { Subscription } from "rxjs/Subscription";
import { TranslateService } from "@ngx-translate/core";
import { TranslateService } from '@ngx-translate/core';
import { ScrollPosition } from '../service/interface'
import { ScrollPosition } from "../service/interface";
@Component({
selector: 'hbr-gridview',
templateUrl: './grid-view.component.html',
styleUrls: ['./grid-view.component.scss'],
selector: "hbr-gridview",
templateUrl: "./grid-view.component.html",
styleUrls: ["./grid-view.component.scss"],
encapsulation: ViewEncapsulation.None
})
/**
@ -41,9 +50,9 @@ export class GridViewComponent implements AfterViewInit {
return this.cardStyles[index];
}
return {
opacity: '0',
overflow: 'hidden'
};
opacity: "0",
overflow: "hidden"
};
});
this.cardStyles = newCardStyles;
this._items = value;
@ -51,8 +60,8 @@ export class GridViewComponent implements AfterViewInit {
@Output() loadNextPageEvent = new EventEmitter<any>();
@ViewChildren('cardItem') cards: any;
@ViewChild('itemsHolder') itemsHolder: any;
@ViewChildren("cardItem") cards: any;
@ViewChild("itemsHolder") itemsHolder: any;
@ContentChild(TemplateRef) gridItemTmpl: any;
_items: any[] = [];
@ -78,7 +87,7 @@ export class GridViewComponent implements AfterViewInit {
preScrollPosition: ScrollPosition = null;
constructor(private translate: TranslateService) { }
constructor(private translate: TranslateService) {}
ngAfterViewInit() {
this.cards.changes.subscribe(() => {
@ -91,21 +100,22 @@ export class GridViewComponent implements AfterViewInit {
return this._items;
}
@HostListener('scroll', ['$event'])
@HostListener("scroll", ["$event"])
onScroll(event: any) {
this.preScrollPosition = this.CurrentScrollPosition;
this.CurrentScrollPosition = {
sH: event.target.scrollHeight,
sT: event.target.scrollTop,
cH: event.target.clientHeight
};
if (
!this.loading &&
this.isScrollDown() &&
this.isScrollExpectPercent() &&
this.currentPage * this.pageSize < this.totalCount
) {
this.loadNextPageEvent.emit();
}
if (!this.loading
&& this.isScrollDown()
&& this.isScrollExpectPercent()
&& (this.currentPage * this.pageSize < this.totalCount)) {
this.loadNextPageEvent.emit();
}
}
isScrollDown(): boolean {
@ -113,10 +123,14 @@ export class GridViewComponent implements AfterViewInit {
}
isScrollExpectPercent(): boolean {
return ((this.CurrentScrollPosition.sT + this.CurrentScrollPosition.cH) / this.CurrentScrollPosition.sH) > (this.expectScrollPercent / 100);
return (
(this.CurrentScrollPosition.sT + this.CurrentScrollPosition.cH) /
this.CurrentScrollPosition.sH >
this.expectScrollPercent / 100
);
}
@HostListener('window:resize')
@HostListener("window:resize")
onResize(event: any) {
this.throttleLayout();
}
@ -136,7 +150,7 @@ export class GridViewComponent implements AfterViewInit {
let el = this.itemsHolder.nativeElement;
let width = el.offsetWidth;
let items = el.querySelectorAll('.card-item');
let items = el.querySelectorAll(".card-item");
let items_count = items.length;
if (items_count === 0) {
el.height = 0;
@ -158,17 +172,24 @@ export class GridViewComponent implements AfterViewInit {
let maxWidth = parseInt(maxWidthStyle, 10);
let marginHeight: number =
parseInt(itemsStyle.marginTop, 10) + parseInt(itemsStyle.marginBottom, 10);
parseInt(itemsStyle.marginTop, 10) +
parseInt(itemsStyle.marginBottom, 10);
let marginWidth: number =
parseInt(itemsStyle.marginLeft, 10) + parseInt(itemsStyle.marginRight, 10);
parseInt(itemsStyle.marginLeft, 10) +
parseInt(itemsStyle.marginRight, 10);
let columns = Math.floor(width / (minWidth + marginWidth));
let columnsToUse = Math.max(Math.min(columns, items_count), 1);
let rows = Math.floor(items_count / columnsToUse);
let itemWidth = Math.min(Math.floor(width / columnsToUse) - marginWidth, maxWidth);
let itemSpacing = columnsToUse === 1 || columns > items_count ? marginWidth :
(width - marginWidth - columnsToUse * itemWidth) / (columnsToUse - 1);
let itemWidth = Math.min(
Math.floor(width / columnsToUse) - marginWidth,
maxWidth
);
let itemSpacing =
columnsToUse === 1 || columns > items_count
? marginWidth
: (width - marginWidth - columnsToUse * itemWidth) / (columnsToUse - 1);
if (!this.withAdmiral) {
// Fixed spacing and margin on standalone mode
itemSpacing = marginWidth;
@ -176,7 +197,11 @@ export class GridViewComponent implements AfterViewInit {
}
let visible = items_count;
if (this.hidePartialRows && this.totalItemsCount && items_count !== this.totalItemsCount) {
if (
this.hidePartialRows &&
this.totalItemsCount &&
items_count !== this.totalItemsCount
) {
visible = rows * columnsToUse;
}
@ -191,27 +216,27 @@ export class GridViewComponent implements AfterViewInit {
// trick to show nice apear animation, where the item is already positioned,
// but it will pop out
let oldTransform = itemStyle.transform;
if (!oldTransform || oldTransform === 'none') {
if (!oldTransform || oldTransform === "none") {
this.cardStyles[i] = {
transform: 'translate(' + left + 'px,' + top + 'px) scale(0)',
width: itemWidth + 'px',
transition: 'none',
overflow: 'hidden'
transform: "translate(" + left + "px," + top + "px) scale(0)",
width: itemWidth + "px",
transition: "none",
overflow: "hidden"
};
this.throttleLayout();
} else {
this.cardStyles[i] = {
transform: 'translate(' + left + 'px,' + top + 'px) scale(1)',
width: itemWidth + 'px',
transform: "translate(" + left + "px," + top + "px) scale(1)",
width: itemWidth + "px",
transition: null,
overflow: 'hidden'
overflow: "hidden"
};
this.throttleLayout();
}
if (!item.classList.contains('context-selected')) {
if (!item.classList.contains("context-selected")) {
let itemHeight = itemsHeight[i];
if (itemStyle.display === 'none' && itemHeight !== 0) {
if (itemStyle.display === "none" && itemHeight !== 0) {
this.cardStyles[i].display = null;
}
if (itemHeight !== 0) {
@ -222,20 +247,20 @@ export class GridViewComponent implements AfterViewInit {
for (let i = visible; i < items_count; i++) {
this.cardStyles[i] = {
display: 'none'
display: "none"
};
}
this.itemsHolderStyle = {
height: Math.ceil(count / columnsToUse) * (height + marginHeight) + 'px'
height: Math.ceil(count / columnsToUse) * (height + marginHeight) + "px"
};
}
onCardEnter(i: number) {
this.cardStyles[i].overflow = 'visible';
this.cardStyles[i].overflow = "visible";
}
onCardLeave(i: number) {
this.cardStyles[i].overflow = 'hidden';
this.cardStyles[i].overflow = "hidden";
}
trackByFn(index: number, item: any) {

View File

@ -5,4 +5,4 @@ export * from "./grid-view.component";
export const HBR_GRIDVIEW_DIRECTIVES: Type<any>[] = [
GridViewComponent
];
];

View File

@ -1,4 +1,4 @@
import { NgModule, ModuleWithProviders, Provider, APP_INITIALIZER, Inject } from '@angular/core';
import { NgModule, ModuleWithProviders, Provider, APP_INITIALIZER } from '@angular/core';
import { LOG_DIRECTIVES } from './log/index';
import { FILTER_DIRECTIVES } from './filter/index';
@ -99,43 +99,43 @@ export const DefaultServiceConfig: IServiceConfig = {
*/
export interface HarborModuleConfig {
// Service endpoints
config?: Provider,
config?: Provider;
// Handling error messages
errorHandler?: Provider,
errorHandler?: Provider;
// Service implementation for system info
systemInfoService?: Provider,
systemInfoService?: Provider;
// Service implementation for log
logService?: Provider,
logService?: Provider;
// Service implementation for endpoint
endpointService?: Provider,
endpointService?: Provider;
// Service implementation for replication
replicationService?: Provider,
replicationService?: Provider;
// Service implementation for repository
repositoryService?: Provider,
repositoryService?: Provider;
// Service implementation for tag
tagService?: Provider,
tagService?: Provider;
// Service implementation for vulnerability scanning
scanningService?: Provider,
scanningService?: Provider;
// Service implementation for configuration
configService?: Provider,
configService?: Provider;
// Service implementation for job log
jobLogService?: Provider,
jobLogService?: Provider;
// Service implementation for project policy
projectPolicyService?: Provider,
projectPolicyService?: Provider;
// Service implementation for label
labelService?: Provider,
labelService?: Provider;
}
/**
@ -263,4 +263,4 @@ export class HarborLibraryModule {
]
};
}
}
}

View File

@ -1,33 +1,33 @@
export interface i18nConfig {
/**
* The cookie key used to store the current used language preference.
*
* @type {string}
* @memberOf IServiceConfig
*/
langCookieKey?: string,
export interface I18nConfig {
/**
* The cookie key used to store the current used language preference.
*
* @type {string}
* @memberOf IServiceConfig
*/
langCookieKey?: string;
/**
* Declare what languages are supported.
*
* @type {string[]}
* @memberOf IServiceConfig
*/
supportedLangs?: string[],
/**
* Declare what languages are supported.
*
* @type {string[]}
* @memberOf IServiceConfig
*/
supportedLangs?: string[];
/**
* Define the default language the translate service uses.
*
* @type {string}
* @memberOf i18nConfig
*/
defaultLang?: string;
/**
* Define the default language the translate service uses.
*
* @type {string}
* @memberOf I18nConfig
*/
defaultLang?: string;
/**
* To determine whether or not to enable the i18 multiple languages supporting.
*
* @type {boolean}
* @memberOf IServiceConfig
*/
enablei18Support?: boolean;
}
/**
* To determine whether or not to enable the i18 multiple languages supporting.
*
* @type {boolean}
* @memberOf IServiceConfig
*/
enablei18Support?: boolean;
}

View File

@ -1,2 +1,2 @@
export * from './translate-init.service';
export * from './i18n-config';
export * from "./translate-init.service";
export * from "./i18n-config";

View File

@ -1,26 +1,28 @@
import { TranslateLoader } from '@ngx-translate/core';
import 'rxjs/add/observable/of';
import { Observable } from 'rxjs/Observable';
import { TranslateLoader } from "@ngx-translate/core";
import "rxjs/add/observable/of";
import { Observable } from "rxjs/Observable";
import { SERVICE_CONFIG, IServiceConfig } from '../service.config';
import { IServiceConfig } from "../service.config";
/**
* Declare a translation loader with local json object
*
*
* @export
* @class TranslatorJsonLoader
* @extends {TranslateLoader}
*/
export class TranslatorJsonLoader extends TranslateLoader {
constructor(private config: IServiceConfig) {
super();
}
constructor(private config: IServiceConfig) {
super();
}
getTranslation(lang: string): Observable<any> {
let dict: any = this.config &&
this.config.localI18nMessageVariableMap &&
this.config.localI18nMessageVariableMap[lang] ?
this.config.localI18nMessageVariableMap[lang] : {};
return Observable.of(dict);
}
}
getTranslation(lang: string): Observable<any> {
let dict: any =
this.config &&
this.config.localI18nMessageVariableMap &&
this.config.localI18nMessageVariableMap[lang]
? this.config.localI18nMessageVariableMap[lang]
: {};
return Observable.of(dict);
}
}

View File

@ -11,11 +11,14 @@
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { MissingTranslationHandler, MissingTranslationHandlerParams } from '@ngx-translate/core';
import {
MissingTranslationHandler,
MissingTranslationHandlerParams
} from "@ngx-translate/core";
export class MyMissingTranslationHandler implements MissingTranslationHandler {
handle(params: MissingTranslationHandlerParams) {
const missingText:string = "{Harbor}";
return params.key || missingText;
}
}
handle(params: MissingTranslationHandlerParams) {
const missingText: string = "{Harbor}";
return params.key || missingText;
}
}

View File

@ -1,40 +1,52 @@
import { Injectable } from "@angular/core";
import { i18nConfig } from "./i18n-config";
import { TranslateService } from '@ngx-translate/core';
import { DEFAULT_LANG_COOKIE_KEY, DEFAULT_SUPPORTING_LANGS, DEFAULT_LANG } from '../utils';
import { CookieService } from 'ngx-cookie';
import { I18nConfig } from "./i18n-config";
import { TranslateService } from "@ngx-translate/core";
import {
DEFAULT_LANG_COOKIE_KEY,
DEFAULT_SUPPORTING_LANGS,
DEFAULT_LANG
} from "../utils";
import { CookieService } from "ngx-cookie";
@Injectable()
export class TranslateServiceInitializer {
constructor(
private translateService: TranslateService,
private cookie: CookieService
) { }
constructor(
private translateService: TranslateService,
private cookie: CookieService
) {}
public init(config: i18nConfig = {}): void {
let selectedLang: string = config.defaultLang ? config.defaultLang : DEFAULT_LANG;
let supportedLangs: string[] = config.supportedLangs ? config.supportedLangs : DEFAULT_SUPPORTING_LANGS;
public init(config: I18nConfig = {}): void {
let selectedLang: string = config.defaultLang
? config.defaultLang
: DEFAULT_LANG;
let supportedLangs: string[] = config.supportedLangs
? config.supportedLangs
: DEFAULT_SUPPORTING_LANGS;
this.translateService.addLangs(supportedLangs);
this.translateService.setDefaultLang(selectedLang);
this.translateService.addLangs(supportedLangs);
this.translateService.setDefaultLang(selectedLang);
if (config.enablei18Support) {
//If user has selected lang, then directly use it
let langSetting: string = this.cookie.get(config.langCookieKey ? config.langCookieKey : DEFAULT_LANG_COOKIE_KEY);
if (!langSetting || langSetting.trim() === "") {
//Use browser lang
langSetting = this.translateService.getBrowserCultureLang().toLowerCase();
}
if (config.enablei18Support) {
// If user has selected lang, then directly use it
let langSetting: string = this.cookie.get(
config.langCookieKey ? config.langCookieKey : DEFAULT_LANG_COOKIE_KEY
);
if (!langSetting || langSetting.trim() === "") {
// Use browser lang
langSetting = this.translateService
.getBrowserCultureLang()
.toLowerCase();
}
if (langSetting && langSetting.trim() !== "") {
if (supportedLangs && supportedLangs.length > 0) {
if (supportedLangs.find(lang => lang === langSetting)) {
selectedLang = langSetting;
}
}
}
if (langSetting && langSetting.trim() !== "") {
if (supportedLangs && supportedLangs.length > 0) {
if (supportedLangs.find(lang => lang === langSetting)) {
selectedLang = langSetting;
}
}
this.translateService.use(selectedLang);
}
}
}
this.translateService.use(selectedLang);
}
}

View File

@ -1,25 +1,26 @@
import { TestBed, inject } from '@angular/core/testing';
import { SharedModule } from '../shared/shared.module';
import { TranslateService } from '@ngx-translate/core';
import { DEFAULT_LANG } from '../utils';
import { TestBed, inject } from "@angular/core/testing";
import { TranslateService } from "@ngx-translate/core";
import { SERVICE_CONFIG, IServiceConfig } from '../service.config';
import { SharedModule } from "../shared/shared.module";
import { DEFAULT_LANG } from "../utils";
import { SERVICE_CONFIG, IServiceConfig } from "../service.config";
const EN_US_LANG: any = {
"SIGN_UP": {
"TITLE": "Sign Up"
},
}
SIGN_UP: {
TITLE: "Sign Up"
}
};
const ZH_CN_LANG: any = {
"SIGN_UP": {
"TITLE": "注册"
},
}
SIGN_UP: {
TITLE: "注册"
}
};
describe('TranslateService', () => {
describe("TranslateService", () => {
let testConfig: IServiceConfig = {
langMessageLoader: 'local',
langMessageLoader: "local",
localI18nMessageVariableMap: {
"en-us": EN_US_LANG,
"zh-cn": ZH_CN_LANG
@ -27,37 +28,49 @@ describe('TranslateService', () => {
};
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
SharedModule
],
providers: [{
provide: SERVICE_CONFIG, useValue: testConfig
}]
imports: [SharedModule],
providers: [
{
provide: SERVICE_CONFIG,
useValue: testConfig
}
]
});
});
it('should be initialized', inject([TranslateService], (service: TranslateService) => {
expect(service).toBeTruthy();
}));
it(
"should be initialized",
inject([TranslateService], (service: TranslateService) => {
expect(service).toBeTruthy();
})
);
it('should use the specified lang', inject([TranslateService], (service: TranslateService) => {
service.use(DEFAULT_LANG).subscribe(() => {
expect(service.currentLang).toEqual(DEFAULT_LANG);
});
}));
it(
"should use the specified lang",
inject([TranslateService], (service: TranslateService) => {
service.use(DEFAULT_LANG).subscribe(() => {
expect(service.currentLang).toEqual(DEFAULT_LANG);
});
})
);
it('should translate key to text [en-us]', inject([TranslateService], (service: TranslateService) => {
service.use(DEFAULT_LANG);
service.get('SIGN_UP.TITLE').subscribe(text => {
expect(text).toEqual('Sign Up');
});
}));
it('should translate key to text [zh-cn]', inject([TranslateService], (service: TranslateService) => {
service.use('zh-cn');
service.get('SIGN_UP.TITLE').subscribe(text => {
expect(text).toEqual('注册');
});
}));
it(
"should translate key to text [en-us]",
inject([TranslateService], (service: TranslateService) => {
service.use(DEFAULT_LANG);
service.get("SIGN_UP.TITLE").subscribe(text => {
expect(text).toEqual("Sign Up");
});
})
);
it(
"should translate key to text [zh-cn]",
inject([TranslateService], (service: TranslateService) => {
service.use("zh-cn");
service.get("SIGN_UP.TITLE").subscribe(text => {
expect(text).toEqual("注册");
});
})
);
});

View File

@ -4,4 +4,4 @@ import { InlineAlertComponent } from './inline-alert.component';
export const INLINE_ALERT_DIRECTIVES: Type<any>[] = [
InlineAlertComponent
];
];

View File

@ -11,86 +11,92 @@
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Component, Input, Output, EventEmitter } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { Component, Output, EventEmitter } from "@angular/core";
import { TranslateService } from "@ngx-translate/core";
import { errorHandler } from '../shared/shared.utils';
import { Observable } from 'rxjs/Rx';
import { Subscription } from "rxjs";
import { errorHandler } from "../shared/shared.utils";
// tslint:disable-next-line:no-unused-variable
import { Observable } from "rxjs/Observable";
import { Subscription } from 'rxjs/Subscription';
@Component({
selector: 'hbr-inline-alert',
templateUrl: './inline-alert.component.html',
styleUrls: [ './inline-alert.component.scss' ]
selector: "hbr-inline-alert",
templateUrl: "./inline-alert.component.html",
styleUrls: ["./inline-alert.component.scss"]
})
export class InlineAlertComponent {
inlineAlertType: string = 'alert-danger';
inlineAlertClosable: boolean = false;
alertClose: boolean = true;
displayedText: string = "";
showCancelAction: boolean = false;
useAppLevelStyle: boolean = false;
timer: Subscription | null = null;
count: number = 0;
blinking: boolean = false;
inlineAlertType: string = "alert-danger";
inlineAlertClosable: boolean = false;
alertClose: boolean = true;
displayedText: string = "";
showCancelAction: boolean = false;
useAppLevelStyle: boolean = false;
timer: Subscription | null = null;
count: number = 0;
blinking: boolean = false;
@Output() confirmEvt = new EventEmitter<boolean>();
@Output() confirmEvt = new EventEmitter<boolean>();
constructor(private translate: TranslateService) { }
constructor(private translate: TranslateService) {}
public get errorMessage(): string {
return this.displayedText;
public get errorMessage(): string {
return this.displayedText;
}
// Show error message inline
public showInlineError(error: any): void {
this.displayedText = errorHandler(error);
if (this.displayedText) {
this.translate
.get(this.displayedText)
.subscribe((res: string) => (this.displayedText = res));
}
//Show error message inline
public showInlineError(error: any): void {
this.displayedText = errorHandler(error);
if (this.displayedText) {
this.translate.get(this.displayedText).subscribe((res: string) => this.displayedText = res);
}
this.inlineAlertType = "alert-danger";
this.showCancelAction = false;
this.inlineAlertClosable = true;
this.alertClose = false;
this.useAppLevelStyle = false;
}
this.inlineAlertType = 'alert-danger';
this.showCancelAction = false;
this.inlineAlertClosable = true;
this.alertClose = false;
this.useAppLevelStyle = false;
// Show confirmation info with action button
public showInlineConfirmation(warning: any): void {
this.displayedText = "";
if (warning && warning.message) {
this.translate
.get(warning.message)
.subscribe((res: string) => (this.displayedText = res));
}
this.inlineAlertType = "alert-warning";
this.showCancelAction = true;
this.inlineAlertClosable = false;
this.alertClose = false;
this.useAppLevelStyle = false;
}
//Show confirmation info with action button
public showInlineConfirmation(warning: any): void {
this.displayedText = "";
if (warning && warning.message) {
this.translate.get(warning.message).subscribe((res: string) => this.displayedText = res);
}
this.inlineAlertType = 'alert-warning';
this.showCancelAction = true;
this.inlineAlertClosable = false;
this.alertClose = false;
this.useAppLevelStyle = false;
// Show inline sccess info
public showInlineSuccess(info: any): void {
this.displayedText = "";
if (info && info.message) {
this.translate
.get(info.message)
.subscribe((res: string) => (this.displayedText = res));
}
this.inlineAlertType = "alert-success";
this.showCancelAction = false;
this.inlineAlertClosable = true;
this.alertClose = false;
this.useAppLevelStyle = false;
}
//Show inline sccess info
public showInlineSuccess(info: any): void {
this.displayedText = "";
if (info && info.message) {
this.translate.get(info.message).subscribe((res: string) => this.displayedText = res);
}
this.inlineAlertType = 'alert-success';
this.showCancelAction = false;
this.inlineAlertClosable = true;
this.alertClose = false;
this.useAppLevelStyle = false;
}
// Close alert
public close(): void {
this.alertClose = true;
}
//Close alert
public close(): void {
this.alertClose = true;
}
public blink() {}
public blink() {
}
confirmCancel(): void {
this.confirmEvt.emit(true);
}
}
confirmCancel(): void {
this.confirmEvt.emit(true);
}
}

View File

@ -6,4 +6,4 @@ export * from './job-log-viewer.component';
export const JOB_LOG_VIEWER_DIRECTIVES: Type<any>[] = [
JobLogViewerComponent
];
];

View File

@ -1,6 +1,6 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { DebugElement } from '@angular/core';
// tslint:disable-next-line:no-unused-variable
import { Observable } from 'rxjs/Observable';
import { JobLogService, JobLogDefaultService } from '../service/index';

View File

@ -11,76 +11,80 @@
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {ChangeDetectionStrategy, ChangeDetectorRef, Component, Input} from '@angular/core';
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
Input
} from "@angular/core";
import { JobLogService } from '../service/index';
import { ErrorHandler } from '../error-handler/index';
import { toPromise } from '../utils';
import { JobLogService } from "../service/index";
import { ErrorHandler } from "../error-handler/index";
import { toPromise } from "../utils";
const supportSet: string[] = ["replication", "scan"];
@Component({
selector: 'job-log-viewer',
templateUrl: './job-log-viewer.component.html',
styleUrls: ['./job-log-viewer.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
selector: "job-log-viewer",
templateUrl: "./job-log-viewer.component.html",
styleUrls: ["./job-log-viewer.component.scss"],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class JobLogViewerComponent {
_jobType: string = "replication";
_jobType: string = "replication";
opened: boolean = false;
log: string = '';
onGoing: boolean = true;
opened: boolean = false;
log: string = "";
onGoing: boolean = true;
@Input()
get jobType(): string {
return this._jobType;
@Input()
get jobType(): string {
return this._jobType;
}
set jobType(v: string) {
if (supportSet.find((t: string) => t === v)) {
this._jobType = v;
}
set jobType(v: string) {
if (supportSet.find((t: string) => t === v)) {
this._jobType = v;
}
}
get title(): string {
if (this.jobType === "scan") {
return "VULNERABILITY.JOB_LOG_VIEWER";
}
get title(): string {
if(this.jobType === "scan"){
return "VULNERABILITY.JOB_LOG_VIEWER";
}
return "REPLICATION.JOB_LOG_VIEWER";
}
return "REPLICATION.JOB_LOG_VIEWER";
}
constructor(
private jobLogService: JobLogService,
private errorHandler: ErrorHandler,
private ref: ChangeDetectorRef
) {}
constructor(
private jobLogService: JobLogService,
private errorHandler: ErrorHandler,
private ref: ChangeDetectorRef
) { }
open(jobId: number | string): void {
this.opened = true;
this.load(jobId);
}
open(jobId: number | string): void {
this.opened = true;
this.load(jobId);
}
close(): void {
this.opened = false;
this.log = "";
}
close(): void {
this.opened = false;
this.log = "";
}
load(jobId: number | string): void {
this.onGoing = true;
load(jobId: number | string): void {
this.onGoing = true;
toPromise<string>(this.jobLogService.getJobLog(this.jobType, jobId))
.then((log: string) => {
this.onGoing = false;
this.log = log;
})
.catch(error => {
this.onGoing = false;
this.errorHandler.error(error);
});
toPromise<string>(this.jobLogService.getJobLog(this.jobType, jobId))
.then((log: string) => {
this.onGoing = false;
this.log = log;
})
.catch(error => {
this.onGoing = false;
this.errorHandler.error(error);
});
let hnd = setInterval(()=>this.ref.markForCheck(), 100);
setTimeout(()=>clearInterval(hnd), 2000);
}
}
let hnd = setInterval(() => this.ref.markForCheck(), 100);
setTimeout(() => clearInterval(hnd), 2000);
}
}

View File

@ -5,4 +5,4 @@ import {LabelPieceComponent} from './label-piece.component';
export const LABEL_PIECE_DIRECTIVES: Type<any>[] = [
LabelPieceComponent
];
];

View File

@ -11,9 +11,7 @@
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {Component, Input, Output, OnInit, EventEmitter, OnChanges} from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
import {Component, Input, OnInit, OnChanges} from '@angular/core';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
@ -41,4 +39,4 @@ export class LabelPieceComponent implements OnInit, OnChanges {
}
ngOnInit(): void { }
}
}

View File

@ -3,4 +3,4 @@ import {LabelComponent} from "./label.component";
export const LABEL_DIRECTIVES: Type<any>[] = [
LabelComponent
];
];

View File

@ -3,7 +3,7 @@
<div>
<div class="row flex-items-xs-between rightPos">
<div class="flex-items-xs-middle option-right">
<hbr-filter [withDivider]="true" filterPlaceholder='{{"LABEL.FILTER_LABEL_PLACEHOLDER" | translate}}' (filter)="doSearchTargets($event)" [currentValue]="targetName"></hbr-filter>
<hbr-filter [withDivider]="true" filterPlaceholder='{{"LABEL.FILTER_LABEL_PLACEHOLDER" | translate}}' (filterEvt)="doSearchTargets($event)" [currentValue]="targetName"></hbr-filter>
<span class="refresh-btn" (click)="refreshTargets()">
<clr-icon shape="refresh"></clr-icon>
</span>

View File

@ -48,7 +48,7 @@ describe('LabelComponent (inline template)', () => {
project_id: 0,
scope: "g",
update_time: "",
}
};
let comp: LabelComponent;
let fixture: ComponentFixture<LabelComponent>;
@ -107,7 +107,7 @@ describe('LabelComponent (inline template)', () => {
comp.editLabel([mockOneData]);
fixture.detectChanges();
expect(comp.targets[0].name).toEqual('label0-g');
})
});
}));
/*it('should open to edit existing label', async() => {
@ -128,4 +128,4 @@ describe('LabelComponent (inline template)', () => {
})
})*/
})
});

View File

@ -12,162 +12,174 @@
// See the License for the specific language governing permissions and
// limitations under the License.
import {
Component, OnInit, OnDestroy, ViewChild, ChangeDetectionStrategy, ChangeDetectorRef,
Input
} from '@angular/core';
import {Label} from "../service/interface";
import {LabelDefaultService, LabelService} from "../service/label.service";
import {toPromise} from "../utils";
import {ErrorHandler} from "../error-handler/error-handler";
import {CreateEditLabelComponent} from "../create-edit-label/create-edit-label.component";
import {BatchInfo, BathInfoChanges} from "../confirmation-dialog/confirmation-batch-message";
import {ConfirmationMessage} from "../confirmation-dialog/confirmation-message";
import {ConfirmationButtons, ConfirmationState, ConfirmationTargets} from "../shared/shared.const";
import {ConfirmationAcknowledgement} from "../confirmation-dialog/confirmation-state-message";
import {TranslateService} from "@ngx-translate/core";
import {ConfirmationDialogComponent} from "../confirmation-dialog/confirmation-dialog.component";
Component,
OnInit,
ViewChild,
ChangeDetectionStrategy,
ChangeDetectorRef,
Input
} from "@angular/core";
import { Label } from "../service/interface";
import { LabelService } from "../service/label.service";
import { toPromise } from "../utils";
import { ErrorHandler } from "../error-handler/error-handler";
import { CreateEditLabelComponent } from "../create-edit-label/create-edit-label.component";
import {
BatchInfo,
BathInfoChanges
} from "../confirmation-dialog/confirmation-batch-message";
import { ConfirmationMessage } from "../confirmation-dialog/confirmation-message";
import {
ConfirmationButtons,
ConfirmationState,
ConfirmationTargets
} from "../shared/shared.const";
import { ConfirmationAcknowledgement } from "../confirmation-dialog/confirmation-state-message";
import { TranslateService } from "@ngx-translate/core";
import { ConfirmationDialogComponent } from "../confirmation-dialog/confirmation-dialog.component";
@Component({
selector: 'hbr-label',
templateUrl: './label.component.html',
styleUrls: ['./label.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
selector: "hbr-label",
templateUrl: "./label.component.html",
styleUrls: ["./label.component.scss"],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class LabelComponent implements OnInit {
timerHandler: any;
loading: boolean;
targets: Label[];
targetName: string;
timerHandler: any;
loading: boolean;
targets: Label[];
targetName: string;
selectedRow: Label[] = [];
batchDelectionInfos: BatchInfo[] = [];
selectedRow: Label[] = [];
batchDelectionInfos: BatchInfo[] = [];
@Input() scope: string;
@Input() projectId = 0;
@Input() hasProjectAdminRole: boolean;
@Input() scope: string;
@Input() projectId = 0;
@Input() hasProjectAdminRole: boolean;
@ViewChild(CreateEditLabelComponent)
createEditLabel: CreateEditLabelComponent;
@ViewChild('confirmationDialog')
confirmationDialogComponent: ConfirmationDialogComponent;
constructor(
private labelService: LabelService,
private errorHandler: ErrorHandler,
private translateService: TranslateService,
private ref: ChangeDetectorRef) {
@ViewChild(CreateEditLabelComponent)
createEditLabel: CreateEditLabelComponent;
@ViewChild("confirmationDialog")
confirmationDialogComponent: ConfirmationDialogComponent;
constructor(
private labelService: LabelService,
private errorHandler: ErrorHandler,
private translateService: TranslateService,
private ref: ChangeDetectorRef
) {}
ngOnInit(): void {
this.retrieve(this.scope);
}
retrieve(scope: string, name = "") {
this.loading = true;
this.selectedRow = [];
this.targetName = "";
toPromise<Label[]>(this.labelService.getLabels(scope, this.projectId, name))
.then(targets => {
this.targets = targets || [];
this.loading = false;
this.forceRefreshView(2000);
})
.catch(error => {
this.errorHandler.error(error);
this.loading = false;
});
}
openModal(): void {
this.createEditLabel.openModal();
}
reload(): void {
this.retrieve(this.scope);
}
doSearchTargets(targetName: string) {
this.retrieve(this.scope, targetName);
}
refreshTargets() {
this.retrieve(this.scope);
}
selectedChange(): void {
// this.forceRefreshView(5000);
}
editLabel(label: Label[]): void {
this.createEditLabel.editModel(label[0].id, label);
}
deleteLabels(targets: Label[]): void {
if (targets && targets.length) {
let targetNames: string[] = [];
this.batchDelectionInfos = [];
targets.forEach(target => {
targetNames.push(target.name);
let initBatchMessage = new BatchInfo();
initBatchMessage.name = target.name;
this.batchDelectionInfos.push(initBatchMessage);
});
let deletionMessage = new ConfirmationMessage(
"LABEL.DELETION_TITLE_TARGET",
"LABEL.DELETION_SUMMARY_TARGET",
targetNames.join(", ") || "",
targets,
ConfirmationTargets.TARGET,
ConfirmationButtons.DELETE_CANCEL
);
this.confirmationDialogComponent.open(deletionMessage);
}
}
ngOnInit(): void {
this.retrieve(this.scope);
confirmDeletion(message: ConfirmationAcknowledgement) {
if (
message &&
message.source === ConfirmationTargets.TARGET &&
message.state === ConfirmationState.CONFIRMED
) {
let targetLists: Label[] = message.data;
if (targetLists && targetLists.length) {
let promiseLists: any[] = [];
targetLists.forEach(target => {
promiseLists.push(this.delOperate(target.id, target.name));
});
Promise.all(promiseLists).then(item => {
this.selectedRow = [];
this.retrieve(this.scope);
});
}
}
}
retrieve(scope: string, name = '') {
this.loading = true;
this.selectedRow = [];
this.targetName = '';
toPromise<Label[]>(this.labelService.getLabels(scope, this.projectId, name))
.then(targets => {
this.targets = targets || [];
this.loading = false;
this.forceRefreshView(2000);
}).catch(error => {
this.errorHandler.error(error);
this.loading = false;
})
}
delOperate(id: number, name: string) {
let findedList = this.batchDelectionInfos.find(data => data.name === name);
return toPromise<number>(this.labelService.deleteLabel(id))
.then(response => {
this.translateService.get("BATCH.DELETED_SUCCESS").subscribe(res => {
findedList = BathInfoChanges(findedList, res);
});
})
.catch(error => {
this.translateService.get("BATCH.DELETED_FAILURE").subscribe(res => {
findedList = BathInfoChanges(findedList, res, false, true);
});
});
}
openModal(): void {
this.createEditLabel.openModal();
// Forcely refresh the view
forceRefreshView(duration: number): void {
// Reset timer
if (this.timerHandler) {
clearInterval(this.timerHandler);
}
reload(): void {
this.retrieve(this.scope);
}
doSearchTargets(targetName: string) {
this.retrieve(this.scope, targetName);
}
refreshTargets() {
this.retrieve(this.scope);
}
selectedChange(): void {
// this.forceRefreshView(5000);
}
editLabel(label: Label[]): void {
this.createEditLabel.editModel(label[0].id, label);
}
deleteLabels(targets: Label[]): void {
if (targets && targets.length) {
let targetNames: string[] = [];
this.batchDelectionInfos = [];
targets.forEach(target => {
targetNames.push(target.name);
let initBatchMessage = new BatchInfo ();
initBatchMessage.name = target.name;
this.batchDelectionInfos.push(initBatchMessage);
});
let deletionMessage = new ConfirmationMessage(
'LABEL.DELETION_TITLE_TARGET',
'LABEL.DELETION_SUMMARY_TARGET',
targetNames.join(', ') || '',
targets,
ConfirmationTargets.TARGET,
ConfirmationButtons.DELETE_CANCEL);
this.confirmationDialogComponent.open(deletionMessage);
}
}
confirmDeletion(message: ConfirmationAcknowledgement) {
if (message &&
message.source === ConfirmationTargets.TARGET &&
message.state === ConfirmationState.CONFIRMED) {
let targetLists: Label[] = message.data;
if (targetLists && targetLists.length) {
let promiseLists: any[] = [];
targetLists.forEach(target => {
promiseLists.push(this.delOperate(target.id, target.name));
})
Promise.all(promiseLists).then((item) => {
this.selectedRow = [];
this.retrieve(this.scope);
});
}
}
}
delOperate(id: number, name: string) {
let findedList = this.batchDelectionInfos.find(data => data.name === name);
return toPromise<number>(this.labelService
.deleteLabel(id))
.then(
response => {
this.translateService.get('BATCH.DELETED_SUCCESS')
.subscribe(res => {
findedList = BathInfoChanges(findedList, res);
});
}).catch(
error => {
this.translateService.get('BATCH.DELETED_FAILURE').subscribe(res => {
findedList = BathInfoChanges(findedList, res, false, true);
});
});
}
// Forcely refresh the view
forceRefreshView(duration: number): void {
// Reset timer
if (this.timerHandler) {
clearInterval(this.timerHandler);
}
this.timerHandler = setInterval(() => this.ref.markForCheck(), 100);
setTimeout(() => {
if (this.timerHandler) {
clearInterval(this.timerHandler);
this.timerHandler = null;
}
}, duration);
}
}
this.timerHandler = setInterval(() => this.ref.markForCheck(), 100);
setTimeout(() => {
if (this.timerHandler) {
clearInterval(this.timerHandler);
this.timerHandler = null;
}
}, duration);
}
}

View File

@ -6,4 +6,4 @@ export * from './list-replication-rule.component';
export const LIST_REPLICATION_RULE_DIRECTIVES: Type<any>[] = [
ListReplicationRuleComponent
];
];

View File

@ -1,4 +1,4 @@
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { NoopAnimationsModule } from "@angular/platform-browser/animations";
@ -14,7 +14,7 @@ import { ErrorHandler } from '../error-handler/error-handler';
import { SERVICE_CONFIG, IServiceConfig } from '../service.config';
import { ReplicationService, ReplicationDefaultService } from '../service/replication.service';
describe('ListReplicationRuleComponent (inline template)', ()=>{
describe('ListReplicationRuleComponent (inline template)', () => {
let mockRules: ReplicationRule[] = [
{
@ -100,20 +100,20 @@ describe('ListReplicationRuleComponent (inline template)', ()=>{
];
let fixture: ComponentFixture<ListReplicationRuleComponent>;
let comp: ListReplicationRuleComponent;
let replicationService: ReplicationService;
let spyRules: jasmine.Spy;
let config: IServiceConfig = {
replicationRuleEndpoint: '/api/policies/replication/testing'
};
beforeEach(async(()=>{
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
imports: [
SharedModule,
NoopAnimationsModule
],
@ -129,7 +129,7 @@ describe('ListReplicationRuleComponent (inline template)', ()=>{
});
}));
beforeEach(()=>{
beforeEach(() => {
fixture = TestBed.createComponent(ListReplicationRuleComponent);
comp = fixture.componentInstance;
replicationService = fixture.debugElement.injector.get(ReplicationService);
@ -137,9 +137,9 @@ describe('ListReplicationRuleComponent (inline template)', ()=>{
fixture.detectChanges();
});
it('Should load and render data', async(()=>{
it('Should load and render data', async(() => {
fixture.detectChanges();
fixture.whenStable().then(()=>{
fixture.whenStable().then(() => {
fixture.detectChanges();
let de: DebugElement = fixture.debugElement.query(By.css('datagrid-cell'));
expect(de).toBeTruthy();
@ -149,4 +149,4 @@ describe('ListReplicationRuleComponent (inline template)', ()=>{
});
}));
});
});

View File

@ -23,36 +23,40 @@ import {
OnChanges,
SimpleChange,
SimpleChanges
} from '@angular/core';
} from "@angular/core";
import { Observable } from "rxjs/Observable";
import { Comparator } from "clarity-angular";
import { TranslateService } from "@ngx-translate/core";
import { ReplicationService } from '../service/replication.service';
import {ReplicationJob, ReplicationJobItem, ReplicationRule} from '../service/interface';
import { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation-dialog.component';
import { ConfirmationMessage } from '../confirmation-dialog/confirmation-message';
import { ConfirmationAcknowledgement } from '../confirmation-dialog/confirmation-state-message';
import { ConfirmationState, ConfirmationTargets, ConfirmationButtons } from '../shared/shared.const';
import { TranslateService } from '@ngx-translate/core';
import { ErrorHandler } from '../error-handler/error-handler';
import { toPromise, CustomComparator } from '../utils';
import { State, Comparator } from 'clarity-angular';
import {BatchInfo, BathInfoChanges} from "../confirmation-dialog/confirmation-batch-message";
import {Observable} from "rxjs/Observable";
import { ReplicationService } from "../service/replication.service";
import {
ReplicationJob,
ReplicationJobItem,
ReplicationRule
} from "../service/interface";
import { ConfirmationDialogComponent } from "../confirmation-dialog/confirmation-dialog.component";
import { ConfirmationMessage } from "../confirmation-dialog/confirmation-message";
import { ConfirmationAcknowledgement } from "../confirmation-dialog/confirmation-state-message";
import {
ConfirmationState,
ConfirmationTargets,
ConfirmationButtons
} from "../shared/shared.const";
import { ErrorHandler } from "../error-handler/error-handler";
import { toPromise, CustomComparator } from "../utils";
import {
BatchInfo,
BathInfoChanges
} from "../confirmation-dialog/confirmation-batch-message";
@Component({
selector: 'hbr-list-replication-rule',
templateUrl: './list-replication-rule.component.html',
styleUrls: ['./list-replication-rule.component.scss'],
selector: "hbr-list-replication-rule",
templateUrl: "./list-replication-rule.component.html",
styleUrls: ["./list-replication-rule.component.scss"],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ListReplicationRuleComponent implements OnInit, OnChanges {
nullTime = '0001-01-01T00:00:00Z';
nullTime = "0001-01-01T00:00:00Z";
@Input() projectId: number;
@Input() isSystemAdmin: boolean;
@ -80,25 +84,30 @@ export class ListReplicationRuleComponent implements OnInit, OnChanges {
selectedRow: ReplicationRule;
batchDelectionInfos: BatchInfo[] = [];
@ViewChild('toggleConfirmDialog')
@ViewChild("toggleConfirmDialog")
toggleConfirmDialog: ConfirmationDialogComponent;
@ViewChild('deletionConfirmDialog')
@ViewChild("deletionConfirmDialog")
deletionConfirmDialog: ConfirmationDialogComponent;
startTimeComparator: Comparator<ReplicationRule> = new CustomComparator<ReplicationRule>('start_time', 'date');
enabledComparator: Comparator<ReplicationRule> = new CustomComparator<ReplicationRule>('enabled', 'number');
startTimeComparator: Comparator<ReplicationRule> = new CustomComparator<
ReplicationRule
>("start_time", "date");
enabledComparator: Comparator<ReplicationRule> = new CustomComparator<
ReplicationRule
>("enabled", "number");
constructor(
private replicationService: ReplicationService,
private translateService: TranslateService,
private errorHandler: ErrorHandler,
private ref: ChangeDetectorRef) {
private ref: ChangeDetectorRef
) {
setInterval(() => ref.markForCheck(), 500);
}
trancatedDescription(desc: string): string {
if (desc.length > 35 ) {
if (desc.length > 35) {
return desc.substr(0, 35);
} else {
return desc;
@ -126,19 +135,20 @@ export class ListReplicationRuleComponent implements OnInit, OnChanges {
}
}
retrieveRules(ruleName = ''): void {
retrieveRules(ruleName = ""): void {
this.loading = true;
/*this.selectedRow = null;*/
toPromise<ReplicationRule[]>(this.replicationService
.getReplicationRules(this.projectId, ruleName))
toPromise<ReplicationRule[]>(
this.replicationService.getReplicationRules(this.projectId, ruleName)
)
.then(rules => {
this.rules = rules || [];
// job list hidden
this.hideJobs.emit();
this.changedRules = this.rules;
this.loading = false;
}
).catch(error => {
})
.catch(error => {
this.errorHandler.error(error);
this.loading = false;
});
@ -149,16 +159,17 @@ export class ListReplicationRuleComponent implements OnInit, OnChanges {
}
deletionConfirm(message: ConfirmationAcknowledgement) {
if (message &&
if (
message &&
message.source === ConfirmationTargets.POLICY &&
message.state === ConfirmationState.CONFIRMED) {
message.state === ConfirmationState.CONFIRMED
) {
this.deleteOpe(message.data);
}
}
selectRule(rule: ReplicationRule): void {
this.selectedId = rule.id || '';
this.selectedId = rule.id || "";
this.selectOne.emit(rule);
}
@ -178,20 +189,23 @@ export class ListReplicationRuleComponent implements OnInit, OnChanges {
let ruleData: ReplicationJobItem[];
this.canDeleteRule = true;
let count = 0;
return toPromise<ReplicationJob>(this.replicationService
.getJobs(id))
.then(response => {
ruleData = response.data;
if (ruleData.length) {
ruleData.forEach(job => {
if ((job.status === 'pending') || (job.status === 'running') || (job.status === 'retrying')) {
count ++;
}
});
}
this.canDeleteRule = count > 0 ? false : true;
})
.catch(error => this.errorHandler.error(error));
return toPromise<ReplicationJob>(this.replicationService.getJobs(id))
.then(response => {
ruleData = response.data;
if (ruleData.length) {
ruleData.forEach(job => {
if (
job.status === "pending" ||
job.status === "running" ||
job.status === "retrying"
) {
count++;
}
});
}
this.canDeleteRule = count > 0 ? false : true;
})
.catch(error => this.errorHandler.error(error));
}
deleteRule(rule: ReplicationRule) {
@ -201,12 +215,13 @@ export class ListReplicationRuleComponent implements OnInit, OnChanges {
initBatchMessage.name = rule.name;
this.batchDelectionInfos.push(initBatchMessage);
let deletionMessage = new ConfirmationMessage(
'REPLICATION.DELETION_TITLE',
'REPLICATION.DELETION_SUMMARY',
rule.name,
rule,
ConfirmationTargets.POLICY,
ConfirmationButtons.DELETE_CANCEL);
"REPLICATION.DELETION_TITLE",
"REPLICATION.DELETION_SUMMARY",
rule.name,
rule,
ConfirmationTargets.POLICY,
ConfirmationButtons.DELETE_CANCEL
);
this.deletionConfirmDialog.open(deletionMessage);
}
}
@ -215,10 +230,20 @@ export class ListReplicationRuleComponent implements OnInit, OnChanges {
let promiseLists: any[] = [];
Promise.all([this.jobList(rule.id)]).then(items => {
if (!this.canDeleteRule) {
let findedList = this.batchDelectionInfos.find(data => data.name === rule.name);
Observable.forkJoin(this.translateService.get('BATCH.DELETED_FAILURE'),
this.translateService.get('REPLICATION.DELETION_SUMMARY_FAILURE')).subscribe(res => {
findedList = BathInfoChanges(findedList, res[0], false, true, res[1]);
let findedList = this.batchDelectionInfos.find(
data => data.name === rule.name
);
Observable.forkJoin(
this.translateService.get("BATCH.DELETED_FAILURE"),
this.translateService.get("REPLICATION.DELETION_SUMMARY_FAILURE")
).subscribe(res => {
findedList = BathInfoChanges(
findedList,
res[0],
false,
true,
res[1]
);
});
} else {
promiseLists.push(this.delOperate(+rule.id, rule.name));
@ -234,25 +259,35 @@ export class ListReplicationRuleComponent implements OnInit, OnChanges {
}
}
delOperate(ruleId: number, name: string) {
let findedList = this.batchDelectionInfos.find(data => data.name === name);
return toPromise<any>(this.replicationService
.deleteReplicationRule(ruleId))
.then(() => {
this.translateService.get('BATCH.DELETED_SUCCESS')
.subscribe(res => findedList = BathInfoChanges(findedList, res));
})
.catch(error => {
if (error && error.status === 412) {
Observable.forkJoin(this.translateService.get('BATCH.DELETED_FAILURE'),
this.translateService.get('REPLICATION.FAILED_TO_DELETE_POLICY_ENABLED')).subscribe(res => {
findedList = BathInfoChanges(findedList, res[0], false, true, res[1]);
});
} else {
this.translateService.get('BATCH.DELETED_FAILURE').subscribe(res => {
findedList = BathInfoChanges(findedList, res, false, true);
});
}
delOperate(ruleId: number, name: string) {
let findedList = this.batchDelectionInfos.find(data => data.name === name);
return toPromise<any>(this.replicationService.deleteReplicationRule(ruleId))
.then(() => {
this.translateService
.get("BATCH.DELETED_SUCCESS")
.subscribe(res => (findedList = BathInfoChanges(findedList, res)));
})
.catch(error => {
if (error && error.status === 412) {
Observable.forkJoin(
this.translateService.get("BATCH.DELETED_FAILURE"),
this.translateService.get(
"REPLICATION.FAILED_TO_DELETE_POLICY_ENABLED"
)
).subscribe(res => {
findedList = BathInfoChanges(
findedList,
res[0],
false,
true,
res[1]
);
});
}
} else {
this.translateService.get("BATCH.DELETED_FAILURE").subscribe(res => {
findedList = BathInfoChanges(findedList, res, false, true);
});
}
});
}
}

View File

@ -5,4 +5,4 @@ export * from "./recent-log.component";
export const LOG_DIRECTIVES: Type<any>[] = [
RecentLogComponent
];
];

View File

@ -11,7 +11,7 @@
<option value="operation">{{"AUDIT_LOG.OPERATION" | translate | lowercase}}</option>
</select>
</div>
<hbr-filter [withDivider]="true" filterPlaceholder='{{"AUDIT_LOG.FILTER_PLACEHOLDER" | translate}}' (filter)="doFilter($event)"
<hbr-filter [withDivider]="true" filterPlaceholder='{{"AUDIT_LOG.FILTER_PLACEHOLDER" | translate}}' (filterEvt)="doFilter($event)"
(openFlag)="openFilter($event)" [currentValue]="currentTerm"></hbr-filter>
<span (click)="refresh()" class="refresh-btn">
<clr-icon shape="refresh" [hidden]="inProgress" ng-disabled="inProgress"></clr-icon>

View File

@ -1,8 +1,5 @@
import { async, ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { DebugElement } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { AccessLog, AccessLogItem, RequestQueryParams } from '../service/index';
import { RecentLogComponent } from './recent-log.component';
@ -83,7 +80,7 @@ describe('RecentLogComponent (inline template)', () => {
if (params.get('page') === '1') {
mockData.data = mockItems.slice(0, 15);
} else {
mockData.data = mockItems.slice(15, 18)
mockData.data = mockItems.slice(15, 18);
}
return Promise.resolve(mockData);
}
@ -194,7 +191,7 @@ describe('RecentLogComponent (inline template)', () => {
let els: HTMLElement[] = fixture.nativeElement.querySelectorAll('.datagrid-row');
expect(els).toBeTruthy();
expect(els.length).toEqual(4)
expect(els.length).toEqual(4);
let refreshEl: HTMLElement = fixture.nativeElement.querySelector(".refresh-btn");
expect(refreshEl).toBeTruthy("Not found refresh button");

View File

@ -12,7 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
import { Component, OnInit, Input } from '@angular/core';
import { Router } from '@angular/router';
import { Comparator, State } from 'clarity-angular';
import {
AccessLogService,
AccessLog,
@ -20,7 +21,6 @@ import {
RequestQueryParams
} from '../service/index';
import { ErrorHandler } from '../error-handler/index';
import { Observable } from 'rxjs/Observable';
import { toPromise, CustomComparator } from '../utils';
import {
DEFAULT_PAGE_SIZE,
@ -29,8 +29,6 @@ import {
doSorting
} from '../utils';
import { Comparator, State } from 'clarity-angular';
@Component({
selector: 'hbr-log',
templateUrl: './recent-log.component.html',
@ -47,8 +45,8 @@ export class RecentLogComponent implements OnInit {
@Input() withTitle: boolean = false;
pageSize: number = DEFAULT_PAGE_SIZE;
currentPage: number = 1;//Double bound to pagination component
currentPagePvt: number = 0; //Used to confirm whether page is changed
currentPage: number = 1; // Double bound to pagination component
currentPagePvt: number = 0; // Used to confirm whether page is changed
currentState: State;
opTimeComparator: Comparator<AccessLogItem> = new CustomComparator<AccessLogItem>('op_time', 'date');
@ -70,11 +68,11 @@ export class RecentLogComponent implements OnInit {
public doFilter(terms: string): void {
this.currentTerm = terms.trim();
//Trigger data loading and start from first page
// Trigger data loading and start from first page
this.loading = true;
this.currentPage = 1;
if (this.currentPagePvt === 1) {
//Force reloading
// Force reloading
let st: State = this.currentState;
if (!st) {
st = {
@ -85,7 +83,7 @@ export class RecentLogComponent implements OnInit {
st.page.to = this.pageSize - 1;
st.page.size = this.pageSize;
this.currentPagePvt = 0;//Reset pvt
this.currentPagePvt = 0; // Reset pvt
this.load(st);
}
@ -109,12 +107,12 @@ export class RecentLogComponent implements OnInit {
}
load(state: State) {
//Keep it for future filter
// Keep it for future filter
this.currentState = state;
let pageNumber: number = calculatePage(state);
if (pageNumber !== this.currentPagePvt) {
//load data
// load data
let params: RequestQueryParams = new RequestQueryParams();
params.set("page", '' + pageNumber);
params.set("page_size", '' + this.pageSize);
@ -125,13 +123,13 @@ export class RecentLogComponent implements OnInit {
this.loading = true;
toPromise<AccessLog>(this.logService.getRecentLogs(params))
.then(response => {
this.logsCache = response; //Keep the data
this.recentLogs = this.logsCache.data.filter(log => log.username != "");//To display
this.logsCache = response; // Keep the data
this.recentLogs = this.logsCache.data.filter(log => log.username !== ""); // To display
//Do customized filter
// Do customized filter
this.recentLogs = doFiltering<AccessLogItem>(this.recentLogs, state);
//Do customized sorting
// Do customized sorting
this.recentLogs = doSorting<AccessLogItem>(this.recentLogs, state);
this.currentPagePvt = pageNumber;
@ -143,14 +141,14 @@ export class RecentLogComponent implements OnInit {
this.errorHandler.error(error);
});
} else {
//Column sorting and filtering
// Column sorting and filtering
this.recentLogs = this.logsCache.data.filter(log => log.username != "");//Reset data
this.recentLogs = this.logsCache.data.filter(log => log.username !== ""); // Reset data
//Do customized filter
// Do customized filter
this.recentLogs = doFiltering<AccessLogItem>(this.recentLogs, state);
//Do customized sorting
// Do customized sorting
this.recentLogs = doSorting<AccessLogItem>(this.recentLogs, state);
}
}
@ -162,4 +160,4 @@ export class RecentLogComponent implements OnInit {
reg.test(log.operation) ||
reg.test(log.repo_tag);
}
}
}

View File

@ -5,7 +5,7 @@ import { ProjectService } from '../service/project.service';
import { ErrorHandler } from '../error-handler/error-handler';
import { State } from 'clarity-angular';
import { ConfirmationState, ConfirmationTargets, ConfirmationButtons } from '../shared/shared.const';
import { ConfirmationState, ConfirmationTargets } from '../shared/shared.const';
import { ConfirmationMessage } from '../confirmation-dialog/confirmation-message';
import { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation-dialog.component';
import { ConfirmationAcknowledgement } from '../confirmation-dialog/confirmation-state-message';

View File

@ -8,4 +8,4 @@ export * from './copy-input.component';
export const PUSH_IMAGE_BUTTON_DIRECTIVES: Type<any>[] = [
CopyInputComponent,
PushImageButtonComponent
];
];

View File

@ -1,8 +1,4 @@
import { async, ComponentFixture, TestBed, fakeAsync } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { DebugElement } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { PushImageButtonComponent } from './push-image.component';
import { CopyInputComponent } from './copy-input.component';
@ -10,7 +6,6 @@ import { InlineAlertComponent } from '../inline-alert/inline-alert.component';
import { SERVICE_CONFIG, IServiceConfig } from '../service.config';
import { SharedModule } from '../shared/shared.module';
import { click } from '../utils';
describe('PushImageButtonComponent (inline template)', () => {
let component: PushImageButtonComponent;
@ -34,7 +29,7 @@ describe('PushImageButtonComponent (inline template)', () => {
fixture = TestBed.createComponent(PushImageButtonComponent);
component = fixture.componentInstance;
component.projectName = 'testing';
component.registryUrl = 'https://testing.harbor.com'
component.registryUrl = 'https://testing.harbor.com';
serviceConfig = TestBed.get(SERVICE_CONFIG);
fixture.detectChanges();
@ -57,9 +52,10 @@ describe('PushImageButtonComponent (inline template)', () => {
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(copyInputs.length).toEqual(2);
expect(copyInputs[0].value.trim()).toEqual(`docker tag SOURCE_IMAGE[:TAG] ${component.registryUrl}/${component.projectName}/IMAGE[:TAG]`);
expect(copyInputs[0].value.trim())
.toEqual(`docker tag SOURCE_IMAGE[:TAG] ${component.registryUrl}/${component.projectName}/IMAGE[:TAG]`);
expect(copyInputs[1].value.trim()).toEqual(`docker push ${component.registryUrl}/${component.projectName}/IMAGE[:TAG]`);
})
});
});
}));

View File

@ -1,49 +1,49 @@
import { Component, Input, ViewChild } from '@angular/core';
import { CopyInputComponent } from './copy-input.component';
import { InlineAlertComponent } from '../inline-alert/inline-alert.component';
import { Component, Input, ViewChild } from "@angular/core";
import { CopyInputComponent } from "./copy-input.component";
import { InlineAlertComponent } from "../inline-alert/inline-alert.component";
@Component({
selector: 'hbr-push-image-button',
templateUrl: './push-image.component.html',
styleUrls: ['./push-image.scss'],
selector: "hbr-push-image-button",
templateUrl: "./push-image.component.html",
styleUrls: ["./push-image.scss"],
providers: []
providers: []
})
export class PushImageButtonComponent {
@Input() registryUrl: string = "unknown";
@Input() projectName: string = "unknown";
@Input() registryUrl: string = "unknown";
@Input() projectName: string = "unknown";
@ViewChild("tagCopy") tagCopyInput: CopyInputComponent;
@ViewChild("pushCopy") pushCopyInput: CopyInputComponent;
@ViewChild("copyAlert") copyAlert: InlineAlertComponent;
@ViewChild("tagCopy") tagCopyInput: CopyInputComponent;
@ViewChild("pushCopy") pushCopyInput: CopyInputComponent;
@ViewChild("copyAlert") copyAlert: InlineAlertComponent;
public get tagCommand(): string {
return `docker tag SOURCE_IMAGE[:TAG] ${this.registryUrl}/${
this.projectName
}/IMAGE[:TAG]`;
}
public get tagCommand(): string {
return `docker tag SOURCE_IMAGE[:TAG] ${this.registryUrl}/${this.projectName}/IMAGE[:TAG]`;
public get pushCommand(): string {
return `docker push ${this.registryUrl}/${this.projectName}/IMAGE[:TAG]`;
}
onclick(): void {
if (this.tagCopyInput) {
this.tagCopyInput.reset();
}
public get pushCommand(): string {
return `docker push ${this.registryUrl}/${this.projectName}/IMAGE[:TAG]`;
if (this.pushCopyInput) {
this.pushCopyInput.reset();
}
onclick(): void {
if (this.tagCopyInput) {
this.tagCopyInput.reset();
}
if (this.pushCopyInput) {
this.pushCopyInput.reset();
}
if(this.copyAlert){
this.copyAlert.close();
}
if (this.copyAlert) {
this.copyAlert.close();
}
}
onCpError($event: any): void {
if(this.copyAlert){
this.copyAlert.showInlineError("PUSH_IMAGE.COPY_ERROR");
}
onCpError($event: any): void {
if (this.copyAlert) {
this.copyAlert.showInlineError("PUSH_IMAGE.COPY_ERROR");
}
}
}

View File

@ -5,4 +5,4 @@ export * from './replication.component';
export const REPLICATION_DIRECTIVES: Type<any>[] = [
ReplicationComponent
];
];

View File

@ -2,7 +2,7 @@
<div>
<div class="row flex-items-xs-between rightPos">
<div class="flex-xs-middle option-right">
<hbr-filter [withDivider]="true" filterPlaceholder='{{"REPLICATION.FILTER_POLICIES_PLACEHOLDER" | translate}}' (filter)="doSearchRules($event)" [currentValue]="search.ruleName"></hbr-filter>
<hbr-filter [withDivider]="true" filterPlaceholder='{{"REPLICATION.FILTER_POLICIES_PLACEHOLDER" | translate}}' (filterEvt)="doSearchRules($event)" [currentValue]="search.ruleName"></hbr-filter>
<span class="refresh-btn" (click)="refreshRules()">
<clr-icon shape="refresh"></clr-icon>
</span>
@ -18,7 +18,7 @@
<h5 class="flex-items-xs-bottom option-left-down" style="margin-left: 14px;">{{'REPLICATION.REPLICATION_JOBS' | translate}}</h5>
<div class="flex-items-xs-bottom option-right-down">
<button class="btn btn-link" (click)="toggleSearchJobOptionalName(currentJobSearchOption)">{{toggleJobSearchOption[currentJobSearchOption] | translate}}</button>
<hbr-filter [withDivider]="true" filterPlaceholder='{{"REPLICATION.FILTER_JOBS_PLACEHOLDER" | translate}}' (filter)="doSearchJobs($event)" [currentValue]="search.repoName" ></hbr-filter>
<hbr-filter [withDivider]="true" filterPlaceholder='{{"REPLICATION.FILTER_JOBS_PLACEHOLDER" | translate}}' (filterEvt)="doSearchJobs($event)" [currentValue]="search.repoName" ></hbr-filter>
<span class="refresh-btn" (click)="refreshJobs()">
<clr-icon shape="refresh"></clr-icon>
</span>

View File

@ -1,4 +1,4 @@
import { ComponentFixture, TestBed, async, inject } from '@angular/core/testing';
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { NoopAnimationsModule } from "@angular/platform-browser/animations";
@ -9,7 +9,6 @@ import { ReplicationComponent } from './replication.component';
import { ListReplicationRuleComponent } from '../list-replication-rule/list-replication-rule.component';
import { CreateEditRuleComponent } from '../create-edit-rule/create-edit-rule.component';
import { DatePickerComponent } from '../datetime-picker/datetime-picker.component';
import { DateValidatorDirective } from '../datetime-picker/date-validator.directive';
import { FilterComponent } from '../filter/filter.component';
import { InlineAlertComponent } from '../inline-alert/inline-alert.component';
import {ReplicationRule, ReplicationJob, Endpoint} from '../service/interface';
@ -20,7 +19,6 @@ import { ReplicationService, ReplicationDefaultService } from '../service/replic
import { EndpointService, EndpointDefaultService } from '../service/endpoint.service';
import { JobLogViewerComponent } from '../job-log-viewer/job-log-viewer.component';
import { JobLogService, JobLogDefaultService, ReplicationJobItem } from '../service/index';
import {Project} from "../project-policy-config/project";
import {ProjectDefaultService, ProjectService} from "../service/project.service";
describe('Replication Component (inline template)', () => {
@ -133,7 +131,7 @@ describe('Replication Component (inline template)', () => {
"repository": "library/busybox",
"policy_id": 2,
"operation": "transfer",
"update_time": new Date("2017-04-23 12:20:33"),
"update_time": new Date("2017-04-23 12:20:33"),
"tags": null
}
];
@ -159,28 +157,28 @@ describe('Replication Component (inline template)', () => {
},
];
let mockProjects: Project[] = [
{ "project_id": 1,
"owner_id": 0,
"name": 'project_01',
"creation_time": '',
"deleted": 0,
"owner_name": '',
"togglable": false,
"update_time": '',
"current_user_role_id": 0,
"repo_count": 0,
"has_project_admin_role": false,
"is_member": false,
"role_name": '',
"metadata": {
"public": '',
"enable_content_trust": '',
"prevent_vul": '',
"severity": '',
"auto_scan": '',
}
}];
// let mockProjects: Project[] = [
// { "project_id": 1,
// "owner_id": 0,
// "name": 'project_01',
// "creation_time": '',
// "deleted": 0,
// "owner_name": '',
// "togglable": false,
// "update_time": '',
// "current_user_role_id": 0,
// "repo_count": 0,
// "has_project_admin_role": false,
// "is_member": false,
// "role_name": '',
// "metadata": {
// "public": '',
// "enable_content_trust": '',
// "prevent_vul": '',
// "severity": '',
// "auto_scan": '',
// }
// }];
let mockJob: ReplicationJob = {
metadata: {xTotalCount: 3},
@ -191,14 +189,14 @@ describe('Replication Component (inline template)', () => {
let fixtureCreate: ComponentFixture<CreateEditRuleComponent>;
let comp: ReplicationComponent;
let compCreate: CreateEditRuleComponent;
let replicationService: ReplicationService;
let endpointService: EndpointService;
let spyRules: jasmine.Spy;
let spyJobs: jasmine.Spy;
let spyEndpoint: jasmine.Spy;
let deGrids: DebugElement[];
let deRules: DebugElement;
let deJobs: DebugElement;
@ -211,9 +209,9 @@ describe('Replication Component (inline template)', () => {
replicationJobEndpoint: '/api/jobs/replication/testing'
};
beforeEach(async(()=>{
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
imports: [
SharedModule,
NoopAnimationsModule
],
@ -256,9 +254,9 @@ describe('Replication Component (inline template)', () => {
spyEndpoint = spyOn(endpointService, 'getEndpoints').and.returnValues(Promise.resolve(mockEndpoints));
fixture.detectChanges();
fixture.whenStable().then(()=>{
fixture.whenStable().then(() => {
fixture.detectChanges();
deGrids = fixture.debugElement.queryAll(del=>del.classes['datagrid']);
deGrids = fixture.debugElement.queryAll(del => del.classes['datagrid']);
fixture.detectChanges();
expect(deGrids).toBeTruthy();
expect(deGrids.length).toEqual(2);
@ -266,9 +264,9 @@ describe('Replication Component (inline template)', () => {
});
it('Should load replication rules', async(()=>{
it('Should load replication rules', async(() => {
fixture.detectChanges();
fixture.whenStable().then(()=>{
fixture.whenStable().then(() => {
fixture.detectChanges();
deRules = deGrids[0].query(By.css('datagrid-cell'));
expect(deRules).toBeTruthy();
@ -279,9 +277,9 @@ describe('Replication Component (inline template)', () => {
});
}));
it('Should load replication jobs', async(()=>{
it('Should load replication jobs', async(() => {
fixture.detectChanges();
fixture.whenStable().then(()=>{
fixture.whenStable().then(() => {
fixture.detectChanges();
deJobs = deGrids[1].query(By.css('datagrid-cell'));
expect(deJobs).toBeTruthy();
@ -293,21 +291,21 @@ describe('Replication Component (inline template)', () => {
});
}));
it('Should filter replication rules by keywords', async(()=>{
it('Should filter replication rules by keywords', async(() => {
fixture.detectChanges();
fixture.whenStable().then(()=>{
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
comp.doSearchRules('sync_01');
fixture.detectChanges();
fixture.detectChanges();
let el: HTMLElement = deRules.nativeElement;
fixture.detectChanges();
expect(el.textContent.trim()).toEqual('sync_01');
});
}));
it('Should filter replication jobs by keywords', async(()=>{
it('Should filter replication jobs by keywords', async(() => {
fixture.detectChanges();
fixture.whenStable().then(()=>{
fixture.whenStable().then(() => {
fixture.detectChanges();
comp.doSearchJobs('nginx');
fixture.detectChanges();
@ -318,9 +316,9 @@ describe('Replication Component (inline template)', () => {
});
}));
it('Should filter replication jobs by status', async(()=>{
it('Should filter replication jobs by status', async(() => {
fixture.detectChanges();
fixture.whenStable().then(()=>{
fixture.whenStable().then(() => {
fixture.detectChanges();
comp.doFilterJobStatus('finished');
let el: HTMLElement = deJobs.nativeElement;
@ -330,16 +328,16 @@ describe('Replication Component (inline template)', () => {
});
}));
it('Should filter replication jobs by date range', async(()=>{
it('Should filter replication jobs by date range', async(() => {
fixture.detectChanges();
fixture.whenStable().then(()=>{
fixture.whenStable().then(() => {
fixture.detectChanges();
comp.doJobSearchByStartTime('2017-05-01');
comp.doJobSearchByEndTime('2015-05-25');
let el: HTMLElement = deJobs.nativeElement;
let el: HTMLElement = deJobs.nativeElement;
fixture.detectChanges();
expect(el).toBeTruthy();
expect(el.textContent.trim()).toEqual('library/nginx');
});
}))
});
}));
});

View File

@ -11,17 +11,29 @@
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Component, OnInit, ViewChild, Input, Output, OnDestroy, EventEmitter } from '@angular/core';
import {
Component,
OnInit,
ViewChild,
Input,
Output,
OnDestroy,
EventEmitter
} from "@angular/core";
import { TranslateService } from '@ngx-translate/core';
import { TranslateService } from "@ngx-translate/core";
import { ListReplicationRuleComponent } from '../list-replication-rule/list-replication-rule.component';
import { CreateEditRuleComponent } from '../create-edit-rule/create-edit-rule.component';
import { ErrorHandler } from '../error-handler/error-handler';
import { ListReplicationRuleComponent } from "../list-replication-rule/list-replication-rule.component";
import { CreateEditRuleComponent } from "../create-edit-rule/create-edit-rule.component";
import { ErrorHandler } from "../error-handler/error-handler";
import { ReplicationService } from '../service/replication.service';
import { RequestQueryParams } from '../service/RequestQueryParams';
import { ReplicationRule, ReplicationJob, ReplicationJobItem } from '../service/interface';
import { ReplicationService } from "../service/replication.service";
import { RequestQueryParams } from "../service/RequestQueryParams";
import {
ReplicationRule,
ReplicationJob,
ReplicationJobItem
} from "../service/interface";
import {
toPromise,
@ -30,59 +42,68 @@ import {
doFiltering,
doSorting,
calculatePage
} from '../utils';
} from "../utils";
import { Comparator } from 'clarity-angular';
import { Comparator } from "clarity-angular";
import { JobLogViewerComponent } from '../job-log-viewer/index';
import { JobLogViewerComponent } from "../job-log-viewer/index";
import { State } from "clarity-angular";
import {Observable} from "rxjs/Observable";
import {Subscription} from "rxjs/Subscription";
import {ConfirmationTargets, ConfirmationButtons, ConfirmationState} from "../shared/shared.const";
import {ConfirmationMessage} from "../confirmation-dialog/confirmation-message";
import {BatchInfo, BathInfoChanges} from "../confirmation-dialog/confirmation-batch-message";
import {ConfirmationDialogComponent} from "../confirmation-dialog/confirmation-dialog.component";
import {ConfirmationAcknowledgement} from "../confirmation-dialog/confirmation-state-message";
import { Observable } from "rxjs/Observable";
import { Subscription } from "rxjs/Subscription";
import {
ConfirmationTargets,
ConfirmationButtons,
ConfirmationState
} from "../shared/shared.const";
import { ConfirmationMessage } from "../confirmation-dialog/confirmation-message";
import {
BatchInfo,
BathInfoChanges
} from "../confirmation-dialog/confirmation-batch-message";
import { ConfirmationDialogComponent } from "../confirmation-dialog/confirmation-dialog.component";
import { ConfirmationAcknowledgement } from "../confirmation-dialog/confirmation-state-message";
const ruleStatus: { [key: string]: any } = [
{ 'key': 'all', 'description': 'REPLICATION.ALL_STATUS' },
{ 'key': '1', 'description': 'REPLICATION.ENABLED' },
{ 'key': '0', 'description': 'REPLICATION.DISABLED' }
{ key: "all", description: "REPLICATION.ALL_STATUS" },
{ key: "1", description: "REPLICATION.ENABLED" },
{ key: "0", description: "REPLICATION.DISABLED" }
];
const jobStatus: { [key: string]: any } = [
{ 'key': 'all', 'description': 'REPLICATION.ALL' },
{ 'key': 'pending', 'description': 'REPLICATION.PENDING' },
{ 'key': 'running', 'description': 'REPLICATION.RUNNING' },
{ 'key': 'error', 'description': 'REPLICATION.ERROR' },
{ 'key': 'retrying', 'description': 'REPLICATION.RETRYING' },
{ 'key': 'stopped', 'description': 'REPLICATION.STOPPED' },
{ 'key': 'finished', 'description': 'REPLICATION.FINISHED' },
{ 'key': 'canceled', 'description': 'REPLICATION.CANCELED' }
{ key: "all", description: "REPLICATION.ALL" },
{ key: "pending", description: "REPLICATION.PENDING" },
{ key: "running", description: "REPLICATION.RUNNING" },
{ key: "error", description: "REPLICATION.ERROR" },
{ key: "retrying", description: "REPLICATION.RETRYING" },
{ key: "stopped", description: "REPLICATION.STOPPED" },
{ key: "finished", description: "REPLICATION.FINISHED" },
{ key: "canceled", description: "REPLICATION.CANCELED" }
];
const optionalSearch: {} = { 0: 'REPLICATION.ADVANCED', 1: 'REPLICATION.SIMPLE' };
const optionalSearch: {} = {
0: "REPLICATION.ADVANCED",
1: "REPLICATION.SIMPLE"
};
export class SearchOption {
ruleId: number | string;
ruleName: string = '';
repoName: string = '';
status: string = '';
startTime: string = '';
startTimestamp: string = '';
endTime: string = '';
endTimestamp: string = '';
ruleName: string = "";
repoName: string = "";
status: string = "";
startTime: string = "";
startTimestamp: string = "";
endTime: string = "";
endTimestamp: string = "";
page: number = 1;
pageSize: number = DEFAULT_PAGE_SIZE;
}
@Component({
selector: 'hbr-replication',
templateUrl: './replication.component.html',
styleUrls: ['./replication.component.scss']
selector: "hbr-replication",
templateUrl: "./replication.component.html",
styleUrls: ["./replication.component.scss"]
})
export class ReplicationComponent implements OnInit, OnDestroy {
@Input() projectId: number | string;
@Input() projectName: string;
@Input() isSystemAdmin: boolean;
@ -96,10 +117,10 @@ export class ReplicationComponent implements OnInit, OnDestroy {
search: SearchOption = new SearchOption();
ruleStatus = ruleStatus;
currentRuleStatus: { key: string, description: string };
currentRuleStatus: { key: string; description: string };
jobStatus = jobStatus;
currentJobStatus: { key: string, description: string };
currentJobStatus: { key: string; description: string };
changedRules: ReplicationRule[];
@ -108,7 +129,6 @@ export class ReplicationComponent implements OnInit, OnDestroy {
isStopOnGoing: boolean;
hiddenJobList = true;
jobs: ReplicationJobItem[];
batchDelectionInfos: BatchInfo[] = [];
@ -124,13 +144,17 @@ export class ReplicationComponent implements OnInit, OnDestroy {
@ViewChild("replicationLogViewer")
replicationLogViewer: JobLogViewerComponent;
@ViewChild('replicationConfirmDialog')
@ViewChild("replicationConfirmDialog")
replicationConfirmDialog: ConfirmationDialogComponent;
creationTimeComparator: Comparator<ReplicationJob> = new CustomComparator<ReplicationJob>('creation_time', 'date');
updateTimeComparator: Comparator<ReplicationJob> = new CustomComparator<ReplicationJob>('update_time', 'date');
creationTimeComparator: Comparator<ReplicationJob> = new CustomComparator<
ReplicationJob
>("creation_time", "date");
updateTimeComparator: Comparator<ReplicationJob> = new CustomComparator<
ReplicationJob
>("update_time", "date");
//Server driven pagination
// Server driven pagination
currentPage: number = 1;
totalCount: number = 0;
pageSize: number = DEFAULT_PAGE_SIZE;
@ -141,9 +165,8 @@ export class ReplicationComponent implements OnInit, OnDestroy {
constructor(
private errorHandler: ErrorHandler,
private replicationService: ReplicationService,
private translateService: TranslateService) {
}
private translateService: TranslateService
) {}
public get showPaginationIndex(): boolean {
return this.totalCount > 0;
@ -177,7 +200,7 @@ export class ReplicationComponent implements OnInit, OnDestroy {
this.goToRegistry.emit();
}
//Server driven data loading
// Server driven data loading
clrLoadJobs(state: State): void {
if (!state || !state.page || !this.search.ruleId) {
return;
@ -185,66 +208,72 @@ export class ReplicationComponent implements OnInit, OnDestroy {
this.currentState = state;
let pageNumber: number = calculatePage(state);
if (pageNumber <= 0) { pageNumber = 1; }
if (pageNumber <= 0) {
pageNumber = 1;
}
let params: RequestQueryParams = new RequestQueryParams();
//Pagination
params.set("page", '' + pageNumber);
params.set("page_size", '' + this.pageSize);
//Search by status
// Pagination
params.set("page", "" + pageNumber);
params.set("page_size", "" + this.pageSize);
// Search by status
if (this.search.status.trim()) {
params.set('status', this.search.status);
params.set("status", this.search.status);
}
//Search by repository
// Search by repository
if (this.search.repoName.trim()) {
params.set('repository', this.search.repoName);
params.set("repository", this.search.repoName);
}
//Search by timestamps
// Search by timestamps
if (this.search.startTimestamp.trim()) {
params.set('start_time', this.search.startTimestamp);
params.set("start_time", this.search.startTimestamp);
}
if (this.search.endTimestamp.trim()) {
params.set('end_time', this.search.endTimestamp);
params.set("end_time", this.search.endTimestamp);
}
this.jobsLoading = true;
//Do filtering and sorting
// Do filtering and sorting
this.jobs = doFiltering<ReplicationJobItem>(this.jobs, state);
this.jobs = doSorting<ReplicationJobItem>(this.jobs, state);
this.jobsLoading = false;
toPromise<ReplicationJob>(this.replicationService
.getJobs(this.search.ruleId, params))
.then(
response => {
toPromise<ReplicationJob>(
this.replicationService.getJobs(this.search.ruleId, params)
)
.then(response => {
this.totalCount = response.metadata.xTotalCount;
this.jobs = response.data;
if (!this.timerDelay) {
this.timerDelay = Observable.timer(10000, 10000).subscribe(() => {
let count: number = 0;
this.jobs.forEach((job) => {
if ((job.status === 'pending') || (job.status === 'running') || (job.status === 'retrying')) {
count ++;
this.jobs.forEach(job => {
if (
job.status === "pending" ||
job.status === "running" ||
job.status === "retrying"
) {
count++;
}
});
if (count > 0) {
this.clrLoadJobs(this.currentState);
}else {
} else {
this.timerDelay.unsubscribe();
this.timerDelay = null;
}
});
}
//Do filtering and sorting
// Do filtering and sorting
this.jobs = doFiltering<ReplicationJobItem>(this.jobs, state);
this.jobs = doSorting<ReplicationJobItem>(this.jobs, state);
this.jobsLoading = false;
}).catch(error => {
})
.catch(error => {
this.jobsLoading = false;
this.errorHandler.error(error);
});
@ -267,11 +296,11 @@ export class ReplicationComponent implements OnInit, OnDestroy {
selectOneRule(rule: ReplicationRule) {
if (rule && rule.id) {
this.hiddenJobList = false;
this.search.ruleId = rule.id || '';
this.search.repoName = '';
this.search.status = '';
this.search.ruleId = rule.id || "";
this.search.repoName = "";
this.search.status = "";
this.currentJobSearchOption = 0;
this.currentJobStatus = { 'key': 'all', 'description': 'REPLICATION.ALL' };
this.currentJobStatus = { key: "all", description: "REPLICATION.ALL" };
this.loadFirstPage();
}
}
@ -279,30 +308,35 @@ export class ReplicationComponent implements OnInit, OnDestroy {
replicateManualRule(rule: ReplicationRule) {
if (rule) {
this.batchDelectionInfos = [];
let initBatchMessage = new BatchInfo ();
initBatchMessage.name = rule.name;
this.batchDelectionInfos.push(initBatchMessage);
let initBatchMessage = new BatchInfo();
initBatchMessage.name = rule.name;
this.batchDelectionInfos.push(initBatchMessage);
let replicationMessage = new ConfirmationMessage(
'REPLICATION.REPLICATION_TITLE',
'REPLICATION.REPLICATION_SUMMARY',
rule.name,
rule,
ConfirmationTargets.TARGET,
ConfirmationButtons.REPLICATE_CANCEL);
"REPLICATION.REPLICATION_TITLE",
"REPLICATION.REPLICATION_SUMMARY",
rule.name,
rule,
ConfirmationTargets.TARGET,
ConfirmationButtons.REPLICATE_CANCEL
);
this.replicationConfirmDialog.open(replicationMessage);
}
}
confirmReplication(message: ConfirmationAcknowledgement) {
if (message &&
message.source === ConfirmationTargets.TARGET &&
message.state === ConfirmationState.CONFIRMED) {
if (
message &&
message.source === ConfirmationTargets.TARGET &&
message.state === ConfirmationState.CONFIRMED
) {
let rule: ReplicationRule = message.data;
if (rule) {
Promise.all([this.replicationOperate(+rule.id, rule.name)]).then((item) => {
this.selectOneRule(rule);
});
Promise.all([this.replicationOperate(+rule.id, rule.name)]).then(
item => {
this.selectOneRule(rule);
}
);
}
}
}
@ -311,23 +345,33 @@ export class ReplicationComponent implements OnInit, OnDestroy {
let findedList = this.batchDelectionInfos.find(data => data.name === name);
return toPromise<any>(this.replicationService.replicateRule(ruleId))
.then(response => {
this.translateService.get('BATCH.REPLICATE_SUCCESS')
.subscribe(res => findedList = BathInfoChanges(findedList, res));
})
.catch(error => {
if (error && error.status === 412) {
Observable.forkJoin(this.translateService.get('BATCH.REPLICATE_FAILURE'),
this.translateService.get('REPLICATION.REPLICATE_SUMMARY_FAILURE'))
.subscribe(function (res) {
findedList = BathInfoChanges(findedList, res[0], false, true, res[1]);
});
} else {
this.translateService.get('BATCH.REPLICATE_FAILURE').subscribe(res => {
.then(response => {
this.translateService
.get("BATCH.REPLICATE_SUCCESS")
.subscribe(res => (findedList = BathInfoChanges(findedList, res)));
})
.catch(error => {
if (error && error.status === 412) {
Observable.forkJoin(
this.translateService.get("BATCH.REPLICATE_FAILURE"),
this.translateService.get("REPLICATION.REPLICATE_SUMMARY_FAILURE")
).subscribe(function(res) {
findedList = BathInfoChanges(
findedList,
res[0],
false,
true,
res[1]
);
});
} else {
this.translateService
.get("BATCH.REPLICATE_FAILURE")
.subscribe(res => {
findedList = BathInfoChanges(findedList, res, false, true);
});
}
});
}
});
}
customRedirect(rule: ReplicationRule) {
@ -344,12 +388,11 @@ export class ReplicationComponent implements OnInit, OnDestroy {
let status = $event.target["value"];
this.currentJobStatus = this.jobStatus.find((r: any) => r.key === status);
if (this.currentJobStatus.key === 'all') {
status = '';
if (this.currentJobStatus.key === "all") {
status = "";
}
this.search.status = status;
this.doSearchJobs(this.search.repoName);
}
}
@ -368,17 +411,17 @@ export class ReplicationComponent implements OnInit, OnDestroy {
if (this.jobs && this.jobs.length) {
this.isStopOnGoing = true;
toPromise(this.replicationService.stopJobs(this.jobs[0].policy_id))
.then(res => {
this.refreshJobs();
this.isStopOnGoing = false;
})
.catch(error => this.errorHandler.error(error));
.then(res => {
this.refreshJobs();
this.isStopOnGoing = false;
})
.catch(error => this.errorHandler.error(error));
}
}
reloadRules(isReady: boolean) {
if (isReady) {
this.search.ruleName = '';
this.search.ruleName = "";
this.listReplicationRule.retrieveRules(this.search.ruleName);
}
}
@ -387,11 +430,10 @@ export class ReplicationComponent implements OnInit, OnDestroy {
this.listReplicationRule.retrieveRules();
}
refreshJobs() {
this.currentJobStatus = this.jobStatus[0];
this.search.startTime = ' ';
this.search.endTime = ' ';
this.search.startTime = " ";
this.search.endTime = " ";
this.search.repoName = "";
this.search.startTimestamp = "";
this.search.endTimestamp = "";
@ -410,7 +452,9 @@ export class ReplicationComponent implements OnInit, OnDestroy {
}
toggleSearchJobOptionalName(option: number) {
(option === 1) ? this.currentJobSearchOption = 0 : this.currentJobSearchOption = 1;
option === 1
? (this.currentJobSearchOption = 0)
: (this.currentJobSearchOption = 1);
}
doJobSearchByStartTime(fromTimestamp: string) {
@ -428,4 +472,4 @@ export class ReplicationComponent implements OnInit, OnDestroy {
this.replicationLogViewer.open(jobId);
}
}
}
}

View File

@ -5,4 +5,4 @@ export * from "./repository-gridview.component";
export const REPOSITORY_GRIDVIEW_DIRECTIVES: Type<any>[] = [
RepositoryGridviewComponent
];
];

View File

@ -4,7 +4,7 @@
<div class="row flex-items-xs-right option-right rightPos">
<div class="flex-xs-middle">
<hbr-push-image-button style="display: inline-block;" [registryUrl]="registryUrl" [projectName]="projectName"></hbr-push-image-button>
<hbr-filter [withDivider]="true" filterPlaceholder="{{'REPOSITORY.FILTER_FOR_REPOSITORIES' | translate}}" (filter)="doSearchRepoNames($event)" [currentValue]="lastFilteredRepoName"></hbr-filter>
<hbr-filter [withDivider]="true" filterPlaceholder="{{'REPOSITORY.FILTER_FOR_REPOSITORIES' | translate}}" (filterEvt)="doSearchRepoNames($event)" [currentValue]="lastFilteredRepoName"></hbr-filter>
<span class="card-btn" (click)="showCard(true)" (mouseenter) ="mouseEnter('card') " (mouseleave) ="mouseLeave('card')">
<clr-icon [ngClass]="{'is-highlight': isCardView || isHovering('card') }" shape="view-cards"></clr-icon>
</span>

View File

@ -11,26 +11,23 @@ import { TagComponent } from '../tag/tag.component';
import { FilterComponent } from '../filter/filter.component';
import { ErrorHandler } from '../error-handler/error-handler';
import { Repository, RepositoryItem, Tag, SystemInfo } from '../service/interface';
import { Repository, RepositoryItem, SystemInfo } from '../service/interface';
import { SERVICE_CONFIG, IServiceConfig } from '../service.config';
import { RepositoryService, RepositoryDefaultService } from '../service/repository.service';
import { TagService, TagDefaultService } from '../service/tag.service';
import { SystemInfoService, SystemInfoDefaultService } from '../service/system-info.service';
import { VULNERABILITY_DIRECTIVES } from '../vulnerability-scanning/index';
import { HBR_GRIDVIEW_DIRECTIVES } from '../gridview/index'
import { HBR_GRIDVIEW_DIRECTIVES } from '../gridview/index';
import { PUSH_IMAGE_BUTTON_DIRECTIVES } from '../push-image/index';
import { INLINE_ALERT_DIRECTIVES } from '../inline-alert/index';
import { JobLogViewerComponent } from '../job-log-viewer/index';
import {LabelPieceComponent} from "../label-piece/label-piece.component";
import { click } from '../utils';
describe('RepositoryComponentGridview (inline template)', () => {
let compRepo: RepositoryGridviewComponent;
let fixtureRepo: ComponentFixture<RepositoryGridviewComponent>;
let repositoryService: RepositoryService;
let tagService: TagService;
let systemInfoService: SystemInfoService;
let spyRepos: jasmine.Spy;
@ -74,20 +71,20 @@ describe('RepositoryComponentGridview (inline template)', () => {
data: mockRepoData
};
let mockTagData: Tag[] = [
{
"digest": "sha256:e5c82328a509aeb7c18c1d7fb36633dc638fcf433f651bdcda59c1cc04d3ee55",
"name": "1.11.5",
"size": "2049",
"architecture": "amd64",
"os": "linux",
"docker_version": "1.12.3",
"author": "NGINX Docker Maintainers \"docker-maint@nginx.com\"",
"created": new Date("2016-11-08T22:41:15.912313785Z"),
"signature": null,
"labels": []
}
];
// let mockTagData: Tag[] = [
// {
// "digest": "sha256:e5c82328a509aeb7c18c1d7fb36633dc638fcf433f651bdcda59c1cc04d3ee55",
// "name": "1.11.5",
// "size": "2049",
// "architecture": "amd64",
// "os": "linux",
// "docker_version": "1.12.3",
// "author": "NGINX Docker Maintainers \"docker-maint@nginx.com\"",
// "created": new Date("2016-11-08T22:41:15.912313785Z"),
// "signature": null,
// "labels": []
// }
// ];
let config: IServiceConfig = {
repositoryBaseEndpoint: '/api/repository/testing',

View File

@ -1,36 +1,68 @@
import { Component, Input, Output, OnInit, ViewChild, ChangeDetectionStrategy, ChangeDetectorRef, EventEmitter, OnChanges, SimpleChanges } from '@angular/core';
import { Router } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';
import {Observable} from "rxjs/Observable";
import { TranslateService } from '@ngx-translate/core';
import { Comparator, State } from 'clarity-angular';
import { Repository, SystemInfo, SystemInfoService, RepositoryService, RequestQueryParams, RepositoryItem, TagService } from '../service/index';
import { ErrorHandler } from '../error-handler/error-handler';
import { toPromise, CustomComparator , DEFAULT_PAGE_SIZE, calculatePage, doFiltering, doSorting, clone} from '../utils';
import { ConfirmationState, ConfirmationTargets, ConfirmationButtons } from '../shared/shared.const';
import { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation-dialog.component';
import { ConfirmationMessage } from '../confirmation-dialog/confirmation-message';
import { ConfirmationAcknowledgement } from '../confirmation-dialog/confirmation-state-message';
import { Tag, CardItemEvent } from '../service/interface';
import {BatchInfo, BathInfoChanges} from "../confirmation-dialog/confirmation-batch-message";
import { GridViewComponent } from '../gridview/grid-view.component';
import {
Component,
Input,
Output,
OnInit,
ViewChild,
ChangeDetectionStrategy,
ChangeDetectorRef,
EventEmitter,
OnChanges,
SimpleChanges
} from "@angular/core";
import { Router } from "@angular/router";
import { Observable } from "rxjs/Observable";
import { TranslateService } from "@ngx-translate/core";
import { Comparator, State } from "clarity-angular";
import {
Repository,
SystemInfo,
SystemInfoService,
RepositoryService,
RequestQueryParams,
RepositoryItem,
TagService
} from "../service/index";
import { ErrorHandler } from "../error-handler/error-handler";
import {
toPromise,
CustomComparator,
DEFAULT_PAGE_SIZE,
calculatePage,
doFiltering,
doSorting,
clone
} from "../utils";
import {
ConfirmationState,
ConfirmationTargets,
ConfirmationButtons
} from "../shared/shared.const";
import { ConfirmationDialogComponent } from "../confirmation-dialog/confirmation-dialog.component";
import { ConfirmationMessage } from "../confirmation-dialog/confirmation-message";
import { ConfirmationAcknowledgement } from "../confirmation-dialog/confirmation-state-message";
import { Tag } from "../service/interface";
import {
BatchInfo,
BathInfoChanges
} from "../confirmation-dialog/confirmation-batch-message";
import { GridViewComponent } from "../gridview/grid-view.component";
@Component({
selector: 'hbr-repository-gridview',
templateUrl: './repository-gridview.component.html',
styleUrls: ['./repository-gridview.component.scss'],
selector: "hbr-repository-gridview",
templateUrl: "./repository-gridview.component.html",
styleUrls: ["./repository-gridview.component.scss"],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class RepositoryGridviewComponent implements OnChanges, OnInit {
signedCon: {[key: string]: any | string[]} = {};
signedCon: { [key: string]: any | string[] } = {};
@Input() projectId: number;
@Input() projectName = 'unknown';
@Input() projectName = "unknown";
@Input() urlPrefix: string;
@Input() hasSignedIn: boolean;
@Input() hasProjectAdminRole: boolean;
@Input() mode = 'admiral';
@Input() mode = "admiral";
@Output() repoClickEvent = new EventEmitter<RepositoryItem>();
@Output() repoProvisionEvent = new EventEmitter<RepositoryItem>();
@Output() addInfoEvent = new EventEmitter<RepositoryItem>();
@ -47,20 +79,22 @@ export class RepositoryGridviewComponent implements OnChanges, OnInit {
listHover = false;
batchDelectionInfos: BatchInfo[] = [];
pullCountComparator: Comparator<RepositoryItem> = new CustomComparator<RepositoryItem>('pull_count', 'number');
tagsCountComparator: Comparator<RepositoryItem> = new CustomComparator<RepositoryItem>('tags_count', 'number');
pullCountComparator: Comparator<RepositoryItem> = new CustomComparator<
RepositoryItem
>("pull_count", "number");
tagsCountComparator: Comparator<RepositoryItem> = new CustomComparator<
RepositoryItem
>("tags_count", "number");
pageSize: number = DEFAULT_PAGE_SIZE;
currentPage = 1;
totalCount = 0;
currentState: State;
@ViewChild('confirmationDialog')
@ViewChild("confirmationDialog")
confirmationDialog: ConfirmationDialogComponent;
@ViewChild('gridView')
gridView: GridViewComponent;
@ViewChild("gridView") gridView: GridViewComponent;
constructor(
private errorHandler: ErrorHandler,
@ -69,10 +103,11 @@ export class RepositoryGridviewComponent implements OnChanges, OnInit {
private systemInfoService: SystemInfoService,
private tagService: TagService,
private ref: ChangeDetectorRef,
private router: Router) { }
private router: Router
) {}
public get registryUrl(): string {
return this.systemInfo ? this.systemInfo.registry_url : '';
return this.systemInfo ? this.systemInfo.registry_url : "";
}
public get withClair(): boolean {
@ -80,13 +115,15 @@ export class RepositoryGridviewComponent implements OnChanges, OnInit {
}
public get isClairDBReady(): boolean {
return this.systemInfo &&
return (
this.systemInfo &&
this.systemInfo.clair_vulnerability_status &&
this.systemInfo.clair_vulnerability_status.overall_last_update > 0;
this.systemInfo.clair_vulnerability_status.overall_last_update > 0
);
}
public get withAdmiral(): boolean {
return this.mode === 'admiral'
return this.mode === "admiral";
}
public get showDBStatusWarning(): boolean {
@ -94,7 +131,7 @@ export class RepositoryGridviewComponent implements OnChanges, OnInit {
}
ngOnChanges(changes: SimpleChanges): void {
if (changes['projectId'] && changes['projectId'].currentValue) {
if (changes["projectId"] && changes["projectId"].currentValue) {
this.refresh();
}
}
@ -102,31 +139,32 @@ export class RepositoryGridviewComponent implements OnChanges, OnInit {
ngOnInit(): void {
// Get system info for tag views
toPromise<SystemInfo>(this.systemInfoService.getSystemInfo())
.then(systemInfo => this.systemInfo = systemInfo)
.then(systemInfo => (this.systemInfo = systemInfo))
.catch(error => this.errorHandler.error(error));
if (this.mode === 'admiral') {
if (this.mode === "admiral") {
this.isCardView = true;
} else {
this.isCardView = false;
}
this.lastFilteredRepoName = '';
this.lastFilteredRepoName = "";
}
confirmDeletion(message: ConfirmationAcknowledgement) {
if (message &&
message.source === ConfirmationTargets.REPOSITORY &&
message.state === ConfirmationState.CONFIRMED) {
if (
message &&
message.source === ConfirmationTargets.REPOSITORY &&
message.state === ConfirmationState.CONFIRMED
) {
let promiseLists: any[] = [];
let repoNames: string[] = message.data.split(',');
let repoNames: string[] = message.data.split(",");
repoNames.forEach(repoName => {
promiseLists.push(this.delOperate(repoName));
});
Promise.all(promiseLists).then((item) => {
Promise.all(promiseLists).then(item => {
this.selectedRow = [];
this.refresh();
let st: State = this.getStateAfterDeletion();
@ -139,40 +177,61 @@ export class RepositoryGridviewComponent implements OnChanges, OnInit {
}
}
delOperate(repoName: string) {
let findedList = this.batchDelectionInfos.find(data => data.name === repoName);
delOperate(repoName: string) {
let findedList = this.batchDelectionInfos.find(
data => data.name === repoName
);
if (this.signedCon[repoName].length !== 0) {
Observable.forkJoin(this.translateService.get('BATCH.DELETED_FAILURE'),
this.translateService.get('REPOSITORY.DELETION_TITLE_REPO_SIGNED')).subscribe(res => {
Observable.forkJoin(
this.translateService.get("BATCH.DELETED_FAILURE"),
this.translateService.get("REPOSITORY.DELETION_TITLE_REPO_SIGNED")
).subscribe(res => {
findedList = BathInfoChanges(findedList, res[0], false, true, res[1]);
});
} else {
return toPromise<number>(this.repositoryService
.deleteRepository(repoName))
.then(
response => {
this.translateService.get('BATCH.DELETED_SUCCESS').subscribe(res => {
findedList = BathInfoChanges(findedList, res);
});
}).catch(error => {
if (error.status === "412") {
Observable.forkJoin(this.translateService.get('BATCH.DELETED_FAILURE'),
this.translateService.get('REPOSITORY.TAGS_SIGNED')).subscribe(res => {
findedList = BathInfoChanges(findedList, res[0], false, true, res[1]);
});
return;
}
if (error.status === 503) {
Observable.forkJoin(this.translateService.get('BATCH.DELETED_FAILURE'),
this.translateService.get('REPOSITORY.TAGS_NO_DELETE')).subscribe(res => {
findedList = BathInfoChanges(findedList, res[0], false, true, res[1]);
});
return;
}
this.translateService.get('BATCH.DELETED_FAILURE').subscribe(res => {
findedList = BathInfoChanges(findedList, res, false, true);
});
return toPromise<number>(
this.repositoryService.deleteRepository(repoName)
)
.then(response => {
this.translateService.get("BATCH.DELETED_SUCCESS").subscribe(res => {
findedList = BathInfoChanges(findedList, res);
});
})
.catch(error => {
if (error.status === "412") {
Observable.forkJoin(
this.translateService.get("BATCH.DELETED_FAILURE"),
this.translateService.get("REPOSITORY.TAGS_SIGNED")
).subscribe(res => {
findedList = BathInfoChanges(
findedList,
res[0],
false,
true,
res[1]
);
});
return;
}
if (error.status === 503) {
Observable.forkJoin(
this.translateService.get("BATCH.DELETED_FAILURE"),
this.translateService.get("REPOSITORY.TAGS_NO_DELETE")
).subscribe(res => {
findedList = BathInfoChanges(
findedList,
res[0],
false,
true,
res[1]
);
});
return;
}
this.translateService.get("BATCH.DELETED_FAILURE").subscribe(res => {
findedList = BathInfoChanges(findedList, res, false, true);
});
});
}
}
@ -189,7 +248,7 @@ export class RepositoryGridviewComponent implements OnChanges, OnInit {
this.clrLoad(st);
}
saveSignatures(event: {[key: string]: string[]}): void {
saveSignatures(event: { [key: string]: string[] }): void {
Object.assign(this.signedCon, event);
}
@ -211,68 +270,92 @@ export class RepositoryGridviewComponent implements OnChanges, OnInit {
});
Promise.all(repArr).then(() => {
this.confirmationDialogSet('REPOSITORY.DELETION_TITLE_REPO', '', repoNames.join(','), 'REPOSITORY.DELETION_SUMMARY_REPO', ConfirmationButtons.DELETE_CANCEL);
this.confirmationDialogSet(
"REPOSITORY.DELETION_TITLE_REPO",
"",
repoNames.join(","),
"REPOSITORY.DELETION_SUMMARY_REPO",
ConfirmationButtons.DELETE_CANCEL
);
});
}
}
getTagInfo(repoName: string): Promise<void> {
this.signedCon[repoName] = [];
return toPromise<Tag[]>(this.tagService
.getTags(repoName))
.then(items => {
items.forEach((t: Tag) => {
if (t.signature !== null) {
this.signedCon[repoName].push(t.name);
}
});
})
.catch(error => this.errorHandler.error(error));
return toPromise<Tag[]>(this.tagService.getTags(repoName))
.then(items => {
items.forEach((t: Tag) => {
if (t.signature !== null) {
this.signedCon[repoName].push(t.name);
}
});
})
.catch(error => this.errorHandler.error(error));
}
signedDataSet(repoName: string): void {
let signature = '';
let signature = "";
if (this.signedCon[repoName].length === 0) {
this.confirmationDialogSet('REPOSITORY.DELETION_TITLE_REPO', signature, repoName, 'REPOSITORY.DELETION_SUMMARY_REPO', ConfirmationButtons.DELETE_CANCEL);
this.confirmationDialogSet(
"REPOSITORY.DELETION_TITLE_REPO",
signature,
repoName,
"REPOSITORY.DELETION_SUMMARY_REPO",
ConfirmationButtons.DELETE_CANCEL
);
return;
}
signature = this.signedCon[repoName].join(',');
this.confirmationDialogSet('REPOSITORY.DELETION_TITLE_REPO_SIGNED', signature, repoName, 'REPOSITORY.DELETION_SUMMARY_REPO_SIGNED', ConfirmationButtons.CLOSE);
signature = this.signedCon[repoName].join(",");
this.confirmationDialogSet(
"REPOSITORY.DELETION_TITLE_REPO_SIGNED",
signature,
repoName,
"REPOSITORY.DELETION_SUMMARY_REPO_SIGNED",
ConfirmationButtons.CLOSE
);
}
confirmationDialogSet(summaryTitle: string, signature: string, repoName: string, summaryKey: string, button: ConfirmationButtons): void {
this.translateService.get(summaryKey,
{
repoName: repoName,
signedImages: signature,
})
.subscribe((res: string) => {
summaryKey = res;
let message = new ConfirmationMessage(
summaryTitle,
summaryKey,
repoName,
repoName,
ConfirmationTargets.REPOSITORY,
button);
this.confirmationDialog.open(message);
confirmationDialogSet(
summaryTitle: string,
signature: string,
repoName: string,
summaryKey: string,
button: ConfirmationButtons
): void {
this.translateService
.get(summaryKey, {
repoName: repoName,
signedImages: signature
})
.subscribe((res: string) => {
summaryKey = res;
let message = new ConfirmationMessage(
summaryTitle,
summaryKey,
repoName,
repoName,
ConfirmationTargets.REPOSITORY,
button
);
this.confirmationDialog.open(message);
let hnd = setInterval(() => this.ref.markForCheck(), 100);
setTimeout(() => clearInterval(hnd), 5000);
});
let hnd = setInterval(() => this.ref.markForCheck(), 100);
setTimeout(() => clearInterval(hnd), 5000);
});
}
provisionItemEvent(evt: any, repo: RepositoryItem): void {
evt.stopPropagation();
let repoCopy = clone(repo)
repoCopy.name = this.registryUrl + ':443/' + repoCopy.name;
let repoCopy = clone(repo);
repoCopy.name = this.registryUrl + ":443/" + repoCopy.name;
this.repoProvisionEvent.emit(repoCopy);
}
itemAddInfoEvent(evt: any, repo: RepositoryItem): void {
evt.stopPropagation();
let repoCopy = clone(repo)
repoCopy.name = this.registryUrl + ':443/' + repoCopy.name;
let repoCopy = clone(repo);
repoCopy.name = this.registryUrl + ":443/" + repoCopy.name;
this.addInfoEvent.emit(repoCopy);
}
@ -287,33 +370,42 @@ export class RepositoryGridviewComponent implements OnChanges, OnInit {
}
refresh() {
this.doSearchRepoNames('');
this.doSearchRepoNames("");
}
loadNextPage() {
if (this.currentPage * this.pageSize >= this.totalCount) {
return
return;
}
this.currentPage = this.currentPage + 1;
// Pagination
let params: RequestQueryParams = new RequestQueryParams();
params.set("page", '' + this.currentPage);
params.set("page_size", '' + this.pageSize);
params.set("page", "" + this.currentPage);
params.set("page_size", "" + this.pageSize);
this.loading = true;
toPromise<Repository>(this.repositoryService.getRepositories(
this.projectId,
this.lastFilteredRepoName,
params))
toPromise<Repository>(
this.repositoryService.getRepositories(
this.projectId,
this.lastFilteredRepoName,
params
)
)
.then((repo: Repository) => {
this.totalCount = repo.metadata.xTotalCount;
this.repositoriesCopy = repo.data;
this.signedCon = {};
// Do filtering and sorting
this.repositoriesCopy = doFiltering<RepositoryItem>(this.repositoriesCopy, this.currentState);
this.repositoriesCopy = doSorting<RepositoryItem>(this.repositoriesCopy, this.currentState);
this.repositoriesCopy = doFiltering<RepositoryItem>(
this.repositoriesCopy,
this.currentState
);
this.repositoriesCopy = doSorting<RepositoryItem>(
this.repositoriesCopy,
this.currentState
);
this.repositories = this.repositories.concat(this.repositoriesCopy);
this.loading = false;
})
@ -321,8 +413,8 @@ export class RepositoryGridviewComponent implements OnChanges, OnInit {
this.loading = false;
this.errorHandler.error(error);
});
let hnd = setInterval(() => this.ref.markForCheck(), 500);
setTimeout(() => clearInterval(hnd), 5000);
let hnd = setInterval(() => this.ref.markForCheck(), 500);
setTimeout(() => clearInterval(hnd), 5000);
}
clrLoad(state: State): void {
@ -331,26 +423,34 @@ export class RepositoryGridviewComponent implements OnChanges, OnInit {
this.currentState = state;
let pageNumber: number = calculatePage(state);
if (pageNumber <= 0) { pageNumber = 1; }
if (pageNumber <= 0) {
pageNumber = 1;
}
// Pagination
let params: RequestQueryParams = new RequestQueryParams();
params.set("page", '' + pageNumber);
params.set("page_size", '' + this.pageSize);
params.set("page", "" + pageNumber);
params.set("page_size", "" + this.pageSize);
this.loading = true;
toPromise<Repository>(this.repositoryService.getRepositories(
this.projectId,
this.lastFilteredRepoName,
params))
toPromise<Repository>(
this.repositoryService.getRepositories(
this.projectId,
this.lastFilteredRepoName,
params
)
)
.then((repo: Repository) => {
this.totalCount = repo.metadata.xTotalCount;
this.repositories = repo.data;
this.signedCon = {};
// Do filtering and sorting
this.repositories = doFiltering<RepositoryItem>(this.repositories, state);
this.repositories = doFiltering<RepositoryItem>(
this.repositories,
state
);
this.repositories = doSorting<RepositoryItem>(this.repositories, state);
this.loading = false;
@ -367,7 +467,9 @@ export class RepositoryGridviewComponent implements OnChanges, OnInit {
getStateAfterDeletion(): State {
let total: number = this.totalCount - 1;
if (total <= 0) { return null; }
if (total <= 0) {
return null;
}
let totalPages: number = Math.ceil(total / this.pageSize);
let targetPageNumber: number = this.currentPage;
@ -392,25 +494,25 @@ export class RepositoryGridviewComponent implements OnChanges, OnInit {
}
getImgLink(repo: RepositoryItem): string {
return '/container-image-icons?container-image=' + repo.name
return "/container-image-icons?container-image=" + repo.name;
}
getRepoDescrition(repo: RepositoryItem): string {
if (repo && repo.description) {
return repo.description;
}
return "No description for this repo. You can add it to this repository."
return "No description for this repo. You can add it to this repository.";
}
showCard(cardView: boolean) {
if (this.isCardView === cardView) {
return
return;
}
this.isCardView = cardView;
this.refresh();
}
mouseEnter(itemName: string) {
if (itemName === 'card') {
if (itemName === "card") {
this.cardHover = true;
} else {
this.listHover = true;
@ -418,7 +520,7 @@ export class RepositoryGridviewComponent implements OnChanges, OnInit {
}
mouseLeave(itemName: string) {
if (itemName === 'card') {
if (itemName === "card") {
this.cardHover = false;
} else {
this.listHover = false;
@ -426,10 +528,10 @@ export class RepositoryGridviewComponent implements OnChanges, OnInit {
}
isHovering(itemName: string) {
if (itemName === 'card') {
if (itemName === "card") {
return this.cardHover;
} else {
return this.listHover;
}
}
}
}

View File

@ -1,6 +1,6 @@
import { ComponentFixture, TestBed, async, } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import {Component, DebugElement} from '@angular/core';
import { DebugElement} from '@angular/core';
import { RouterTestingModule } from '@angular/router/testing';
import { SharedModule } from '../shared/shared.module';
@ -118,7 +118,7 @@ describe('RepositoryComponent (inline template)', () => {
project_id: 0,
scope: "g",
update_time: "",
}]
}];
let mockLabels1: Label[] = [{
color: "#9b0d54",
@ -139,7 +139,7 @@ describe('RepositoryComponent (inline template)', () => {
project_id: 1,
scope: "p",
update_time: "",
}]
}];
let config: IServiceConfig = {
repositoryBaseEndpoint: '/api/repository/testing',

View File

@ -9,7 +9,7 @@ export interface IServiceConfig {
* Notary configurations
* Registry configuration
* Volume information
*
*
* @type {string}
* @memberOf IServiceConfig
*/
@ -22,8 +22,8 @@ export interface IServiceConfig {
* If the base endpoint is '/api/repositories',
* the repository endpoint will be '/api/repositories/:repo_id',
* the tag(s) endpoint will be '/api/repositories/:repo_id/tags[/:tag_id]'.
*
*
*
*
* @type {string}
* @memberOf IServiceConfig
*/
@ -31,7 +31,7 @@ export interface IServiceConfig {
/**
* The base endpoint of the service used to handle the recent access logs.
*
*
* @type {string}
* @memberOf IServiceConfig
*/
@ -44,7 +44,7 @@ export interface IServiceConfig {
* If the base endpoint is '/api/endpoints',
* the endpoint for registry target will be '/api/endpoints/:endpoint_id',
* the endpoint for pinging registry target will be '/api/endpoints/:endpoint_id/ping'.
*
*
* @type {string}
* @memberOf IServiceConfig
*/
@ -61,7 +61,7 @@ export interface IServiceConfig {
* E.g:
* If the base endpoint is '/api/replication/rules',
* the endpoint for rule will be '/api/replication/rules/:rule_id'.
*
*
* @type {string}
* @memberOf IServiceConfig
*/
@ -70,8 +70,8 @@ export interface IServiceConfig {
/**
* The base endpoint of the service used to handle the replication jobs.
*
*
*
*
* @type {string}
* @memberOf IServiceConfig
*/
@ -79,7 +79,7 @@ export interface IServiceConfig {
/**
* The base endpoint of the service used to handle vulnerability scanning.
*
*
* @type {string}
* @memberOf IServiceConfig
*/
@ -87,7 +87,7 @@ export interface IServiceConfig {
/**
* The base endpoint of the service used to handle project policy.
*
*
* @type {string}
* @memberOf IServiceConfig
*/
@ -102,7 +102,7 @@ export interface IServiceConfig {
/**
* To determine whether or not to enable the i18 multiple languages supporting.
*
*
* @type {boolean}
* @memberOf IServiceConfig
*/
@ -110,25 +110,25 @@ export interface IServiceConfig {
/**
* The cookie key used to store the current used language preference.
*
*
* @type {string}
* @memberOf IServiceConfig
*/
langCookieKey?: string,
langCookieKey?: string;
/**
* Declare what languages are supported.
*
*
* @type {string[]}
* @memberOf IServiceConfig
*/
supportedLangs?: string[],
supportedLangs?: string[];
/**
* Define the default language the translate service uses.
*
*
* @type {string}
* @memberOf i18nConfig
* @memberOf I18nConfig
*/
defaultLang?: string;
@ -137,7 +137,7 @@ export interface IServiceConfig {
* Support two loaders:
* One is 'http', use async http to load json files with the specified url/path.
* Another is 'local', use local json variable to store the lang message.
*
*
* @type {string}
* @memberOf IServiceConfig
*/
@ -146,7 +146,7 @@ export interface IServiceConfig {
/**
* Define the basic url/path prefix for the loader to find the json files if the 'langMessageLoader' is 'http'.
* For example, 'src/i18n/langs'.
*
*
* @type {string}
* @memberOf IServiceConfig
*/
@ -155,7 +155,7 @@ export interface IServiceConfig {
/**
* Define the suffix of the json file names without lang name if 'langMessageLoader' is 'http'.
* For example, '-lang.json' is suffix of message file 'en-us-lang.json'.
*
*
* @type {string}
* @memberOf IServiceConfig
*/
@ -166,28 +166,28 @@ export interface IServiceConfig {
* this property must be defined to tell local JSON loader where to get the related messages.
* E.g:
* If declare the following messages storage variables,
*
*
* export const EN_US_LANG: any = {
* "APP_TITLE": {
* "VMW_HARBOR": "VMware Harbor",
* "HARBOR": "Harbor"
* }
* }
*
*
* export const ZH_CN_LANG: any = {
* "APP_TITLE": {
* "VMW_HARBOR": "VMware Harbor中文版",
* "HARBOR": "Harbor"
* }
* }
*
*
* then this property should be set to:
* {
* "en-us": EN_US_LANG,
* "zh-cn": ZH_CN_LANG
* };
*
*
*
*
* @type {{ [key: string]: any }}
* @memberOf IServiceConfig
*/
@ -195,7 +195,7 @@ export interface IServiceConfig {
/**
* The base endpoint of configuration service.
*
*
* @type {string}
* @memberOf IServiceConfig
*/
@ -203,7 +203,7 @@ export interface IServiceConfig {
/**
* The base endpoint of scan job service.
*
*
* @type {string}
* @memberof IServiceConfig
*/
@ -220,4 +220,4 @@ export interface IServiceConfig {
* @memberOf IServiceConfig
*/
labelEndpoint?: string;
}
}

View File

@ -1,14 +1,15 @@
import { URLSearchParams } from '@angular/http';
import { URLSearchParams } from "@angular/http";
/**
* Wrap the class 'URLSearchParams' for future extending requirements.
* Currently no extra methods provided.
*
*
* @export
* @class RequestQueryParams
* @extends {URLSearchParams}
*/
export class RequestQueryParams extends URLSearchParams {
constructor() { super(); }
}
constructor() {
super();
}
}

View File

@ -1,94 +1,112 @@
import { Observable } from 'rxjs/Observable';
import { RequestQueryParams } from './RequestQueryParams';
import { AccessLog, AccessLogItem } from './interface';
import { Observable } from "rxjs/Observable";
import { RequestQueryParams } from "./RequestQueryParams";
import { AccessLog, AccessLogItem } from "./interface";
import { Injectable, Inject } from "@angular/core";
import 'rxjs/add/observable/of';
import { SERVICE_CONFIG, IServiceConfig } from '../service.config';
import { Http, URLSearchParams } from '@angular/http';
import { buildHttpRequestOptions, HTTP_GET_OPTIONS } from '../utils';
import "rxjs/add/observable/of";
import { SERVICE_CONFIG, IServiceConfig } from "../service.config";
import { Http } from "@angular/http";
import { buildHttpRequestOptions, HTTP_GET_OPTIONS } from "../utils";
/**
* Define service methods to handle the access log related things.
*
*
* @export
* @abstract
* @class AccessLogService
*/
export abstract class AccessLogService {
/**
* Get the audit logs for the specified project.
* Set query parameters through 'queryParams', support:
* - page
* - pageSize
*
* @abstract
* @param {(number | string)} projectId
* @param {RequestQueryParams} [queryParams]
* @returns {(Observable<AccessLog> | Promise<AccessLog> | AccessLog)}
*
* @memberOf AccessLogService
*/
abstract getAuditLogs(projectId: number | string, queryParams?: RequestQueryParams): Observable<AccessLog> | Promise<AccessLog> | AccessLog;
/**
* Get the audit logs for the specified project.
* Set query parameters through 'queryParams', support:
* - page
* - pageSize
*
* @abstract
* @param {(number | string)} projectId
* @param {RequestQueryParams} [queryParams]
* @returns {(Observable<AccessLog> | Promise<AccessLog> | AccessLog)}
*
* @memberOf AccessLogService
*/
abstract getAuditLogs(
projectId: number | string,
queryParams?: RequestQueryParams
): Observable<AccessLog> | Promise<AccessLog> | AccessLog;
/**
* Get the recent logs.
*
* @abstract
* @param {RequestQueryParams} [queryParams]
* @returns {(Observable<AccessLog> | Promise<AccessLog> | AccessLog)}
*
* @memberOf AccessLogService
*/
abstract getRecentLogs(queryParams?: RequestQueryParams): Observable<AccessLog> | Promise<AccessLog> | AccessLog;
/**
* Get the recent logs.
*
* @abstract
* @param {RequestQueryParams} [queryParams]
* @returns {(Observable<AccessLog> | Promise<AccessLog> | AccessLog)}
*
* @memberOf AccessLogService
*/
abstract getRecentLogs(
queryParams?: RequestQueryParams
): Observable<AccessLog> | Promise<AccessLog> | AccessLog;
}
/**
* Implement a default service for access log.
*
*
* @export
* @class AccessLogDefaultService
* @extends {AccessLogService}
*/
@Injectable()
export class AccessLogDefaultService extends AccessLogService {
constructor(
private http: Http,
@Inject(SERVICE_CONFIG) private config: IServiceConfig) {
super();
constructor(
private http: Http,
@Inject(SERVICE_CONFIG) private config: IServiceConfig
) {
super();
}
public getAuditLogs(
projectId: number | string,
queryParams?: RequestQueryParams
): Observable<AccessLog> | Promise<AccessLog> | AccessLog {
return Observable.of({} as AccessLog);
}
public getRecentLogs(
queryParams?: RequestQueryParams
): Observable<AccessLog> | Promise<AccessLog> | AccessLog {
let url: string = this.config.logBaseEndpoint
? this.config.logBaseEndpoint
: "";
if (url === "") {
url = "/api/logs";
}
public getAuditLogs(projectId: number | string, queryParams?: RequestQueryParams): Observable<AccessLog> | Promise<AccessLog> | AccessLog {
return Observable.of({});
}
public getRecentLogs(queryParams?: RequestQueryParams): Observable<AccessLog> | Promise<AccessLog> | AccessLog {
let url: string = this.config.logBaseEndpoint ? this.config.logBaseEndpoint : "";
if (url === '') {
url = '/api/logs';
return this.http
.get(
url,
queryParams ? buildHttpRequestOptions(queryParams) : HTTP_GET_OPTIONS
)
.toPromise()
.then(response => {
let result: AccessLog = {
metadata: {
xTotalCount: 0
},
data: []
};
let xHeader: string | null = "0";
if (response && response.headers) {
xHeader = response.headers.get("X-Total-Count");
}
return this.http.get(url, queryParams ? buildHttpRequestOptions(queryParams) : HTTP_GET_OPTIONS).toPromise()
.then(response => {
let result: AccessLog = {
metadata: {
xTotalCount: 0
},
data: []
};
let xHeader: string | null = "0";
if (response && response.headers) {
xHeader = response.headers.get("X-Total-Count");
}
if (result && result.metadata) {
result.metadata.xTotalCount = parseInt(xHeader ? xHeader : "0", 0);
if (result.metadata.xTotalCount > 0) {
result.data = response.json() as AccessLogItem[];
}
}
if (result && result.metadata) {
result.metadata.xTotalCount = parseInt(xHeader ? xHeader : "0", 0);
if (result.metadata.xTotalCount > 0) {
result.data = response.json() as AccessLogItem[];
}
}
return result;
})
.catch(error => Promise.reject(error));
}
}
return result;
})
.catch(error => Promise.reject(error));
}
}

View File

@ -1,69 +1,84 @@
import { Observable } from 'rxjs/Observable';
import { Injectable, Inject } from "@angular/core";
import 'rxjs/add/observable/of';
import { SERVICE_CONFIG, IServiceConfig } from '../service.config';
import { Http } from '@angular/http';
import { HTTP_JSON_OPTIONS, HTTP_GET_OPTIONS } from '../utils';
import { Configuration } from '../config/config';
import { Http } from "@angular/http";
import { Observable } from "rxjs/Observable";
import "rxjs/add/observable/of";
import { SERVICE_CONFIG, IServiceConfig } from "../service.config";
import { HTTP_JSON_OPTIONS, HTTP_GET_OPTIONS } from "../utils";
import { Configuration } from "../config/config";
/**
* Service used to get and save registry-related configurations.
*
*
* @export
* @abstract
* @class ConfigurationService
*/
export abstract class ConfigurationService {
/**
* Get configurations.
*
* @abstract
* @returns {(Observable<Configuration> | Promise<Configuration> | Configuration)}
*
* @memberOf ConfigurationService
*/
abstract getConfigurations():
| Observable<Configuration>
| Promise<Configuration>
| Configuration;
/**
* Get configurations.
*
* @abstract
* @returns {(Observable<Configuration> | Promise<Configuration> | Configuration)}
*
* @memberOf ConfigurationService
*/
abstract getConfigurations(): Observable<Configuration> | Promise<Configuration> | Configuration;
/**
* Save configurations.
*
* @abstract
* @returns {(Observable<Configuration> | Promise<Configuration> | Configuration)}
*
* @memberOf ConfigurationService
*/
abstract saveConfigurations(changedConfigs: any | { [key: string]: any | any[] }): Observable<any> | Promise<any> | any;
/**
* Save configurations.
*
* @abstract
* @returns {(Observable<Configuration> | Promise<Configuration> | Configuration)}
*
* @memberOf ConfigurationService
*/
abstract saveConfigurations(
changedConfigs: any | { [key: string]: any | any[] }
): Observable<any> | Promise<any> | any;
}
@Injectable()
export class ConfigurationDefaultService extends ConfigurationService {
_baseUrl: string;
_baseUrl: string;
constructor(
private http: Http,
@Inject(SERVICE_CONFIG) private config: IServiceConfig) {
super();
constructor(
private http: Http,
@Inject(SERVICE_CONFIG) private config: IServiceConfig
) {
super();
this._baseUrl = this.config && this.config.configurationEndpoint ?
this.config.configurationEndpoint : "/api/configurations";
this._baseUrl =
this.config && this.config.configurationEndpoint
? this.config.configurationEndpoint
: "/api/configurations";
}
getConfigurations():
| Observable<Configuration>
| Promise<Configuration>
| Configuration {
return this.http
.get(this._baseUrl, HTTP_GET_OPTIONS)
.toPromise()
.then(response => response.json() as Configuration)
.catch(error => Promise.reject(error));
}
saveConfigurations(
changedConfigs: any | { [key: string]: any | any[] }
): Observable<any> | Promise<any> | any {
if (!changedConfigs) {
return Promise.reject("Bad argument!");
}
getConfigurations(): Observable<Configuration> | Promise<Configuration> | Configuration {
return this.http.get(this._baseUrl, HTTP_GET_OPTIONS).toPromise()
.then(response => response.json() as Configuration)
.catch(error => Promise.reject(error));
}
saveConfigurations(changedConfigs: any | { [key: string]: any | any[] }): Observable<any> | Promise<any> | any {
if (!changedConfigs) {
return Promise.reject("Bad argument!");
}
return this.http.put(this._baseUrl, JSON.stringify(changedConfigs), HTTP_JSON_OPTIONS)
.toPromise()
.then(() => { })
.catch(error => Promise.reject(error));
}
}
return this.http
.put(this._baseUrl, JSON.stringify(changedConfigs), HTTP_JSON_OPTIONS)
.toPromise()
.then(() => {})
.catch(error => Promise.reject(error));
}
}

View File

@ -1,12 +1,13 @@
import { TestBed, inject } from '@angular/core/testing';
import { SharedModule } from '../shared/shared.module';
import { EndpointService, EndpointDefaultService } from './endpoint.service';
import { IServiceConfig, SERVICE_CONFIG } from '../service.config';
import { EndpointService, EndpointDefaultService } from './endpoint.service';
describe('EndpointService', () => {
let mockEndpoint:IServiceConfig = {
let mockEndpoint: IServiceConfig = {
targetBaseEndpoint: '/api/endpoint/testing'
};

View File

@ -1,207 +1,244 @@
import { Observable } from 'rxjs/Observable';
import { RequestQueryParams } from './RequestQueryParams';
import { Endpoint, ReplicationRule } from './interface';
import { Injectable, Inject } from "@angular/core";
import { Http } from '@angular/http';
import 'rxjs/add/observable/of';
import { Http } from "@angular/http";
import { Observable } from "rxjs/Observable";
import "rxjs/add/observable/of";
import { IServiceConfig, SERVICE_CONFIG } from '../service.config';
import {buildHttpRequestOptions, HTTP_JSON_OPTIONS, HTTP_GET_OPTIONS} from '../utils';
import { IServiceConfig, SERVICE_CONFIG } from "../service.config";
import {
buildHttpRequestOptions,
HTTP_JSON_OPTIONS,
HTTP_GET_OPTIONS
} from "../utils";
import { RequestQueryParams } from "./RequestQueryParams";
import { Endpoint, ReplicationRule } from "./interface";
/**
* Define the service methods to handle the endpoint related things.
*
*
* @export
* @abstract
* @class EndpointService
*/
export abstract class EndpointService {
/**
* Get all the endpoints.
* Set the argument 'endpointName' to return only the endpoints match the name pattern.
*
* @abstract
* @param {string} [endpointName]
* @param {RequestQueryParams} [queryParams]
* @returns {(Observable<Endpoint[]> | Endpoint[])}
*
* @memberOf EndpointService
*/
abstract getEndpoints(endpointName?: string, queryParams?: RequestQueryParams): Observable<Endpoint[]> | Promise<Endpoint[]> | Endpoint[];
/**
* Get all the endpoints.
* Set the argument 'endpointName' to return only the endpoints match the name pattern.
*
* @abstract
* @param {string} [endpointName]
* @param {RequestQueryParams} [queryParams]
* @returns {(Observable<Endpoint[]> | Endpoint[])}
*
* @memberOf EndpointService
*/
abstract getEndpoints(
endpointName?: string,
queryParams?: RequestQueryParams
): Observable<Endpoint[]> | Promise<Endpoint[]> | Endpoint[];
/**
* Get the specified endpoint.
*
* @abstract
* @param {(number | string)} endpointId
* @returns {(Observable<Endpoint> | Endpoint)}
*
* @memberOf EndpointService
*/
abstract getEndpoint(endpointId: number | string): Observable<Endpoint> | Promise<Endpoint> | Endpoint;
/**
* Get the specified endpoint.
*
* @abstract
* @param {(number | string)} endpointId
* @returns {(Observable<Endpoint> | Endpoint)}
*
* @memberOf EndpointService
*/
abstract getEndpoint(
endpointId: number | string
): Observable<Endpoint> | Promise<Endpoint> | Endpoint;
/**
* Create new endpoint.
*
* @abstract
* @param {Endpoint} endpoint
* @returns {(Observable<any> | any)}
*
* @memberOf EndpointService
*/
abstract createEndpoint(endpoint: Endpoint): Observable<any> | Promise<any> | any;
/**
* Create new endpoint.
*
* @abstract
* @param {Endpoint} endpoint
* @returns {(Observable<any> | any)}
*
* @memberOf EndpointService
*/
abstract createEndpoint(
endpoint: Endpoint
): Observable<any> | Promise<any> | any;
/**
* Update the specified endpoint.
*
* @abstract
* @param {(number | string)} endpointId
* @param {Endpoint} endpoint
* @returns {(Observable<any> | any)}
*
* @memberOf EndpointService
*/
abstract updateEndpoint(endpointId: number | string, endpoint: Endpoint): Observable<any> | Promise<any> | any;
/**
* Update the specified endpoint.
*
* @abstract
* @param {(number | string)} endpointId
* @param {Endpoint} endpoint
* @returns {(Observable<any> | any)}
*
* @memberOf EndpointService
*/
abstract updateEndpoint(
endpointId: number | string,
endpoint: Endpoint
): Observable<any> | Promise<any> | any;
/**
* Delete the specified endpoint.
*
* @abstract
* @param {(number | string)} endpointId
* @returns {(Observable<any> | any)}
*
* @memberOf EndpointService
*/
abstract deleteEndpoint(endpointId: number | string): Observable<any> | Promise<any> | any;
/**
* Delete the specified endpoint.
*
* @abstract
* @param {(number | string)} endpointId
* @returns {(Observable<any> | any)}
*
* @memberOf EndpointService
*/
abstract deleteEndpoint(
endpointId: number | string
): Observable<any> | Promise<any> | any;
/**
* Ping the specified endpoint.
*
* @abstract
* @param {Endpoint} endpoint
* @returns {(Observable<any> | any)}
*
* @memberOf EndpointService
*/
abstract pingEndpoint(endpoint: Endpoint): Observable<any> | Promise<any> | any;
/**
* Ping the specified endpoint.
*
* @abstract
* @param {Endpoint} endpoint
* @returns {(Observable<any> | any)}
*
* @memberOf EndpointService
*/
abstract pingEndpoint(
endpoint: Endpoint
): Observable<any> | Promise<any> | any;
/**
* Check endpoint whether in used with specific replication rule.
*
* @abstract
* @param {{number | string}} endpointId
* @returns {{Observable<any> | any}}
*/
abstract getEndpointWithReplicationRules(endpointId: number | string): Observable<any> | Promise<any> | any;
/**
* Check endpoint whether in used with specific replication rule.
*
* @abstract
* @param {{number | string}} endpointId
* @returns {{Observable<any> | any}}
*/
abstract getEndpointWithReplicationRules(
endpointId: number | string
): Observable<any> | Promise<any> | any;
}
/**
* Implement default service for endpoint.
*
*
* @export
* @class EndpointDefaultService
* @extends {EndpointService}
*/
@Injectable()
export class EndpointDefaultService extends EndpointService {
_endpointUrl: string;
_endpointUrl: string;
constructor(
@Inject(SERVICE_CONFIG) config: IServiceConfig,
private http: Http){
super();
this._endpointUrl = config.targetBaseEndpoint ? config.targetBaseEndpoint : '/api/targets';
}
constructor(
@Inject(SERVICE_CONFIG) config: IServiceConfig,
private http: Http
) {
super();
this._endpointUrl = config.targetBaseEndpoint
? config.targetBaseEndpoint
: "/api/targets";
}
public getEndpoints(endpointName?: string, queryParams?: RequestQueryParams): Observable<Endpoint[]> | Promise<Endpoint[]> | Endpoint[] {
if(!queryParams) {
queryParams = new RequestQueryParams();
}
if(endpointName) {
queryParams.set('name', endpointName);
}
let requestUrl: string = `${this._endpointUrl}`;
return this.http
.get(requestUrl, buildHttpRequestOptions(queryParams))
.toPromise()
.then(response=>response.json())
.catch(error=>Promise.reject(error));
public getEndpoints(
endpointName?: string,
queryParams?: RequestQueryParams
): Observable<Endpoint[]> | Promise<Endpoint[]> | Endpoint[] {
if (!queryParams) {
queryParams = new RequestQueryParams();
}
if (endpointName) {
queryParams.set("name", endpointName);
}
let requestUrl: string = `${this._endpointUrl}`;
return this.http
.get(requestUrl, buildHttpRequestOptions(queryParams))
.toPromise()
.then(response => response.json())
.catch(error => Promise.reject(error));
}
public getEndpoint(endpointId: number | string): Observable<Endpoint> | Promise<Endpoint> | Endpoint {
if(!endpointId || endpointId <= 0) {
return Promise.reject('Bad request argument.');
}
let requestUrl: string = `${this._endpointUrl}/${endpointId}`;
return this.http
.get(requestUrl, HTTP_GET_OPTIONS)
.toPromise()
.then(response=>response.json() as Endpoint)
.catch(error=>Promise.reject(error));
public getEndpoint(
endpointId: number | string
): Observable<Endpoint> | Promise<Endpoint> | Endpoint {
if (!endpointId || endpointId <= 0) {
return Promise.reject("Bad request argument.");
}
let requestUrl: string = `${this._endpointUrl}/${endpointId}`;
return this.http
.get(requestUrl, HTTP_GET_OPTIONS)
.toPromise()
.then(response => response.json() as Endpoint)
.catch(error => Promise.reject(error));
}
public createEndpoint(endpoint: Endpoint): Observable<any> | Promise<any> | any {
if(!endpoint) {
return Promise.reject('Invalid endpoint.');
}
let requestUrl: string = `${this._endpointUrl}`;
return this.http
.post(requestUrl, JSON.stringify(endpoint), HTTP_JSON_OPTIONS)
.toPromise()
.then(response=>response.status)
.catch(error=>Promise.reject(error));
public createEndpoint(
endpoint: Endpoint
): Observable<any> | Promise<any> | any {
if (!endpoint) {
return Promise.reject("Invalid endpoint.");
}
let requestUrl: string = `${this._endpointUrl}`;
return this.http
.post(requestUrl, JSON.stringify(endpoint), HTTP_JSON_OPTIONS)
.toPromise()
.then(response => response.status)
.catch(error => Promise.reject(error));
}
public updateEndpoint(endpointId: number | string, endpoint: Endpoint): Observable<any> | Promise<any> | any {
if(!endpointId || endpointId <= 0) {
return Promise.reject('Bad request argument.');
}
if(!endpoint) {
return Promise.reject('Invalid endpoint.');
}
let requestUrl: string = `${this._endpointUrl}/${endpointId}`;
return this.http
.put(requestUrl, JSON.stringify(endpoint), HTTP_JSON_OPTIONS)
.toPromise()
.then(response=>response.status)
.catch(error=>Promise.reject(error));
public updateEndpoint(
endpointId: number | string,
endpoint: Endpoint
): Observable<any> | Promise<any> | any {
if (!endpointId || endpointId <= 0) {
return Promise.reject("Bad request argument.");
}
if (!endpoint) {
return Promise.reject("Invalid endpoint.");
}
let requestUrl: string = `${this._endpointUrl}/${endpointId}`;
return this.http
.put(requestUrl, JSON.stringify(endpoint), HTTP_JSON_OPTIONS)
.toPromise()
.then(response => response.status)
.catch(error => Promise.reject(error));
}
public deleteEndpoint(endpointId: number | string): Observable<any> | Promise<any> | any {
if(!endpointId || endpointId <= 0) {
return Promise.reject('Bad request argument.');
}
let requestUrl: string = `${this._endpointUrl}/${endpointId}`;
return this.http
.delete(requestUrl)
.toPromise()
.then(response=>response.status)
.catch(error=>Promise.reject(error));
public deleteEndpoint(
endpointId: number | string
): Observable<any> | Promise<any> | any {
if (!endpointId || endpointId <= 0) {
return Promise.reject("Bad request argument.");
}
let requestUrl: string = `${this._endpointUrl}/${endpointId}`;
return this.http
.delete(requestUrl)
.toPromise()
.then(response => response.status)
.catch(error => Promise.reject(error));
}
public pingEndpoint(endpoint: Endpoint): Observable<any> | Promise<any> | any {
if(!endpoint) {
return Promise.reject('Invalid endpoint.');
}
let requestUrl: string = `${this._endpointUrl}/ping`;
return this.http
.post(requestUrl, endpoint, HTTP_JSON_OPTIONS)
.toPromise()
.then(response=>response.status)
.catch(error=>Promise.reject(error));
public pingEndpoint(
endpoint: Endpoint
): Observable<any> | Promise<any> | any {
if (!endpoint) {
return Promise.reject("Invalid endpoint.");
}
let requestUrl: string = `${this._endpointUrl}/ping`;
return this.http
.post(requestUrl, endpoint, HTTP_JSON_OPTIONS)
.toPromise()
.then(response => response.status)
.catch(error => Promise.reject(error));
}
public getEndpointWithReplicationRules(endpointId: number | string): Observable<any> | Promise<any> | any {
if(!endpointId || endpointId <= 0) {
return Promise.reject('Bad request argument.');
}
let requestUrl: string = `${this._endpointUrl}/${endpointId}/policies`;
return this.http
.get(requestUrl, HTTP_GET_OPTIONS)
.toPromise()
.then(response=>response.json() as ReplicationRule[])
.catch(error=>Promise.reject(error));
public getEndpointWithReplicationRules(
endpointId: number | string
): Observable<any> | Promise<any> | any {
if (!endpointId || endpointId <= 0) {
return Promise.reject("Bad request argument.");
}
}
let requestUrl: string = `${this._endpointUrl}/${endpointId}/policies`;
return this.http
.get(requestUrl, HTTP_GET_OPTIONS)
.toPromise()
.then(response => response.json() as ReplicationRule[])
.catch(error => Promise.reject(error));
}
}

View File

@ -1,291 +1,298 @@
import {Project} from "../project-policy-config/project";
import { Project } from "../project-policy-config/project";
/**
* The base interface contains the general properties
*
*
* @export
* @interface Base
*/
export interface Base {
id?: string | number;
name?: string;
creation_time?: Date;
update_time?: Date;
id?: string | number;
name?: string;
creation_time?: Date;
update_time?: Date;
}
/**
* Interface for Repository Info
*
*
* @export
* @interface Repository
* @extends {Base}
*/
export interface RepositoryItem extends Base {
[key: string]: any | any[]
name: string;
tags_count: number;
owner_id?: number;
project_id?: number;
description?: string;
star_count?: number;
pull_count?: number;
[key: string]: any | any[];
name: string;
tags_count: number;
owner_id?: number;
project_id?: number;
description?: string;
star_count?: number;
pull_count?: number;
}
/**
* Interface for repository
*
*
* @export
* @interface Repository
*/
export interface Repository {
metadata?: Metadata;
data: RepositoryItem[];
metadata?: Metadata;
data: RepositoryItem[];
}
/**
* Interface for the tag of repository
*
*
* @export
* @interface Tag
* @extends {Base}
*/
export interface Tag extends Base {
digest: string;
name: string;
size: string;
architecture: string;
os: string;
docker_version: string;
author: string;
created: Date;
signature?: string;
scan_overview?: VulnerabilitySummary;
labels: Label[];
digest: string;
name: string;
size: string;
architecture: string;
os: string;
docker_version: string;
author: string;
created: Date;
signature?: string;
scan_overview?: VulnerabilitySummary;
labels: Label[];
}
/**
* Interface for registry endpoints.
*
*
* @export
* @interface Endpoint
* @extends {Base}
*/
export interface Endpoint extends Base {
endpoint: string;
name: string;
username?: string;
password?: string;
insecure: boolean;
type: number;
[key: string]: any;
endpoint: string;
name: string;
username?: string;
password?: string;
insecure: boolean;
type: number;
[key: string]: any;
}
/**
* Interface for replication rule.
*
*
* @export
* @interface ReplicationRule
* @interface Filter
* @interface Trigger
*/
export interface ReplicationRule extends Base {
[key: string]: any;
id?: number;
name: string;
description: string;
projects: Project[];
targets: Endpoint[] ;
trigger: Trigger ;
filters: Filter[] ;
replicate_existing_image_now?: boolean;
replicate_deletion?: boolean;
[key: string]: any;
id?: number;
name: string;
description: string;
projects: Project[];
targets: Endpoint[];
trigger: Trigger;
filters: Filter[];
replicate_existing_image_now?: boolean;
replicate_deletion?: boolean;
}
export class Filter {
kind: string;
pattern: string;
constructor(kind: string, pattern: string) {
this.kind = kind;
this.pattern = pattern;
}
kind: string;
pattern: string;
constructor(kind: string, pattern: string) {
this.kind = kind;
this.pattern = pattern;
}
}
export class Trigger {
kind: string;
schedule_param: any | {
kind: string;
schedule_param:
| any
| {
[key: string]: any | any[];
};
constructor(kind: string, param: any | { [key: string]: any | any[]; }) {
this.kind = kind;
this.schedule_param = param;
}
};
constructor(kind: string, param: any | { [key: string]: any | any[] }) {
this.kind = kind;
this.schedule_param = param;
}
}
/**
* Interface for replication job.
*
*
* @export
* @interface ReplicationJob
*/
export interface ReplicationJob {
metadata?: Metadata;
data: ReplicationJobItem[];
metadata?: Metadata;
data: ReplicationJobItem[];
}
/**
* Interface for replication job item.
*
*
* @export
* @interface ReplicationJob
*/
export interface ReplicationJobItem extends Base {
[key: string]: any | any[];
status: string;
repository: string;
policy_id: number;
operation: string;
tags: string;
[key: string]: any | any[];
status: string;
repository: string;
policy_id: number;
operation: string;
tags: string;
}
/**
* Interface for storing metadata of response.
*
*
* @export
* @interface Metadata
*/
export interface Metadata {
xTotalCount: number;
xTotalCount: number;
}
/**
* Interface for access log.
*
*
* @export
* @interface AccessLog
*/
export interface AccessLog {
metadata?: Metadata;
data: AccessLogItem[];
metadata?: Metadata;
data: AccessLogItem[];
}
/**
* The access log data.
*
*
* @export
* @interface AccessLogItem
*/
export interface AccessLogItem {
[key: string]: any | any[];
log_id: number;
project_id: number;
repo_name: string;
repo_tag: string;
operation: string;
op_time: string | Date;
user_id: number;
username: string;
keywords?: string; //NOT used now
guid?: string; //NOT used now
[key: string]: any | any[];
log_id: number;
project_id: number;
repo_name: string;
repo_tag: string;
operation: string;
op_time: string | Date;
user_id: number;
username: string;
keywords?: string; // NOT used now
guid?: string; // NOT used now
}
/**
* Global system info.
*
* @export
*
* @export
* @interface SystemInfo
*
*
*/
export interface SystemInfo {
with_clair?: boolean;
with_notary?: boolean;
with_admiral?: boolean;
admiral_endpoint?: string;
auth_mode?: string;
registry_url?: string;
project_creation_restriction?: string;
self_registration?: boolean;
has_ca_root?: boolean;
harbor_version?: string;
clair_vulnerability_status?: ClairDBStatus;
next_scan_all?: number;
with_clair?: boolean;
with_notary?: boolean;
with_admiral?: boolean;
admiral_endpoint?: string;
auth_mode?: string;
registry_url?: string;
project_creation_restriction?: string;
self_registration?: boolean;
has_ca_root?: boolean;
harbor_version?: string;
clair_vulnerability_status?: ClairDBStatus;
next_scan_all?: number;
}
/**
* Clair database status info.
*
*
* @export
* @interface ClairDetail
*/
export interface ClairDetail {
namespace: string;
last_update: number;
namespace: string;
last_update: number;
}
export interface ClairDBStatus {
overall_last_update: number;
details: ClairDetail[];
overall_last_update: number;
details: ClairDetail[];
}
export enum VulnerabilitySeverity {
_SEVERITY, NONE, UNKNOWN, LOW, MEDIUM, HIGH
_SEVERITY,
NONE,
UNKNOWN,
LOW,
MEDIUM,
HIGH
}
export interface VulnerabilityBase {
id: string;
severity: VulnerabilitySeverity;
package: string;
version: string;
id: string;
severity: VulnerabilitySeverity;
package: string;
version: string;
}
export interface VulnerabilityItem extends VulnerabilityBase {
link: string;
fixedVersion: string;
layer?: string;
description: string;
link: string;
fixedVersion: string;
layer?: string;
description: string;
}
export interface VulnerabilitySummary {
image_digest?: string;
scan_status: string;
job_id?: number;
severity: VulnerabilitySeverity;
components: VulnerabilityComponents;
update_time: Date; // Use as complete timestamp
image_digest?: string;
scan_status: string;
job_id?: number;
severity: VulnerabilitySeverity;
components: VulnerabilityComponents;
update_time: Date; // Use as complete timestamp
}
export interface VulnerabilityComponents {
total: number;
summary: VulnerabilitySeverityMetrics[];
total: number;
summary: VulnerabilitySeverityMetrics[];
}
export interface VulnerabilitySeverityMetrics {
severity: VulnerabilitySeverity;
count: number;
severity: VulnerabilitySeverity;
count: number;
}
export interface TagClickEvent {
project_id: string | number;
repository_name: string;
tag_name: string;
project_id: string | number;
repository_name: string;
tag_name: string;
}
export interface Label {
[key: string]: any | any[];
name: string;
description: string;
color: string;
scope: string;
project_id: number;
[key: string]: any | any[];
name: string;
description: string;
color: string;
scope: string;
project_id: number;
}
export interface CardItemEvent {
event_type: string;
item: any;
additional_info?: any;
event_type: string;
item: any;
additional_info?: any;
}
export interface ScrollPosition {
sH: number;
sT: number;
cH: number;
};
sH: number;
sT: number;
cH: number;
}

View File

@ -1,84 +1,92 @@
import { Observable } from 'rxjs/Observable';
import { RequestQueryParams } from './RequestQueryParams';
import { ReplicationJob, ReplicationRule } from './interface';
import { Observable } from "rxjs/Observable";
import { Injectable, Inject } from "@angular/core";
import 'rxjs/add/observable/of';
import { Http, RequestOptions } from '@angular/http';
import { SERVICE_CONFIG, IServiceConfig } from '../service.config';
import { buildHttpRequestOptions, HTTP_JSON_OPTIONS, HTTP_GET_OPTIONS } from '../utils';
import "rxjs/add/observable/of";
import { Http } from "@angular/http";
import { SERVICE_CONFIG, IServiceConfig } from "../service.config";
import { HTTP_GET_OPTIONS } from "../utils";
/**
* Define the service methods to handle the job log related things.
*
*
* @export
* @abstract
* @class JobLogService
*/
export abstract class JobLogService {
/**
* Get the log of the specified job
*
* @abstract
* @param {string} jobType
* @param {(number | string)} jobId
* @returns {(Observable<string> | Promise<string> | string)}
* @memberof JobLogService
*/
abstract getJobLog(jobType: string, jobId: number | string): Observable<string> | Promise<string> | string;
/**
* Get the log of the specified job
*
* @abstract
* @param {string} jobType
* @param {(number | string)} jobId
* @returns {(Observable<string> | Promise<string> | string)}
* @memberof JobLogService
*/
abstract getJobLog(
jobType: string,
jobId: number | string
): Observable<string> | Promise<string> | string;
}
/**
* Implement default service for job log service.
*
*
* @export
* @class JobLogDefaultService
* @extends {ReplicationService}
*/
@Injectable()
export class JobLogDefaultService extends JobLogService {
_replicationJobBaseUrl: string;
_scanningJobBaseUrl: string;
_supportedJobTypes: string[];
_replicationJobBaseUrl: string;
_scanningJobBaseUrl: string;
_supportedJobTypes: string[];
constructor(
private http: Http,
@Inject(SERVICE_CONFIG) config: IServiceConfig
) {
super();
this._replicationJobBaseUrl = config.replicationJobEndpoint ?
config.replicationJobEndpoint : '/api/jobs/replication';
this._scanningJobBaseUrl = config.scanJobEndpoint ? config.scanJobEndpoint : "/api/jobs/scan";
this._supportedJobTypes = ["replication", "scan"];
constructor(
private http: Http,
@Inject(SERVICE_CONFIG) config: IServiceConfig
) {
super();
this._replicationJobBaseUrl = config.replicationJobEndpoint
? config.replicationJobEndpoint
: "/api/jobs/replication";
this._scanningJobBaseUrl = config.scanJobEndpoint
? config.scanJobEndpoint
: "/api/jobs/scan";
this._supportedJobTypes = ["replication", "scan"];
}
_getJobLog(logUrl: string): Observable<string> | Promise<string> | string {
return this.http
.get(logUrl, HTTP_GET_OPTIONS)
.toPromise()
.then(response => response.text())
.catch(error => Promise.reject(error));
}
_isSupportedJobType(jobType: string): boolean {
if (this._supportedJobTypes.find((t: string) => t === jobType)) {
return true;
}
_getJobLog(logUrl: string): Observable<string> | Promise<string> | string {
return this.http.get(logUrl, HTTP_GET_OPTIONS).toPromise()
.then(response => response.text())
.catch(error => Promise.reject(error));
return false;
}
public getJobLog(
jobType: string,
jobId: number | string
): Observable<string> | Promise<string> | string {
if (!this._isSupportedJobType(jobType)) {
return Promise.reject("Unsupport job type: " + jobType);
}
if (!jobId || jobId <= 0) {
return Promise.reject("Bad argument");
}
_isSupportedJobType(jobType: string): boolean {
if (this._supportedJobTypes.find((t: string) => t === jobType)) {
return true;
}
return false;
let logUrl: string = `${this._replicationJobBaseUrl}/${jobId}/log`;
if (jobType === "scan") {
logUrl = `${this._scanningJobBaseUrl}/${jobId}/log`;
}
public getJobLog(jobType: string, jobId: number | string): Observable<string> | Promise<string> | string {
if (!this._isSupportedJobType(jobType)) {
return Promise.reject("Unsupport job type: " + jobType);
}
if (!jobId || jobId <= 0) {
return Promise.reject('Bad argument');
}
let logUrl: string = `${this._replicationJobBaseUrl}/${jobId}/log`;
if (jobType === "scan") {
logUrl = `${this._scanningJobBaseUrl}/${jobId}/log`;
}
return this._getJobLog(logUrl);
}
}
return this._getJobLog(logUrl);
}
}

View File

@ -1,125 +1,170 @@
import {Observable} from "rxjs/Observable";
import {Label} from "./interface";
import {Inject, Injectable} from "@angular/core";
import {Http} from "@angular/http";
import {IServiceConfig, SERVICE_CONFIG} from "../service.config";
import {buildHttpRequestOptions, HTTP_JSON_OPTIONS} from "../utils";
import {RequestQueryParams} from "./RequestQueryParams";
import { Observable } from "rxjs/Observable";
import { Label } from "./interface";
import { Inject, Injectable } from "@angular/core";
import { Http } from "@angular/http";
import { IServiceConfig, SERVICE_CONFIG } from "../service.config";
import { buildHttpRequestOptions, HTTP_JSON_OPTIONS } from "../utils";
import { RequestQueryParams } from "./RequestQueryParams";
export abstract class LabelService {
abstract getGLabels(name?: string, queryParams?: RequestQueryParams): Observable<Label[]> | Promise<Label[]>;
abstract getGLabels(
name?: string,
queryParams?: RequestQueryParams
): Observable<Label[]> | Promise<Label[]>;
abstract getPLabels(projectId: number, name?: string, queryParams?: RequestQueryParams): Observable<Label[]> | Promise<Label[]>;
abstract getPLabels(
projectId: number,
name?: string,
queryParams?: RequestQueryParams
): Observable<Label[]> | Promise<Label[]>;
abstract getLabels(scope: string, projectId: number, name?: string, queryParams?: RequestQueryParams): Observable<Label[]> | Promise<Label[]>;
abstract getLabels(
scope: string,
projectId: number,
name?: string,
queryParams?: RequestQueryParams
): Observable<Label[]> | Promise<Label[]>;
abstract createLabel(label: Label): Observable<Label> | Promise<Label> | Label;
abstract createLabel(
label: Label
): Observable<Label> | Promise<Label> | Label;
abstract getLabel(id: number): Observable<Label> | Promise<Label> | Label;
abstract getLabel(id: number): Observable<Label> | Promise<Label> | Label;
abstract updateLabel(id: number, param: Label): Observable<any> | Promise<any> | any;
abstract updateLabel(
id: number,
param: Label
): Observable<any> | Promise<any> | any;
abstract deleteLabel(id: number): Observable<any> | Promise<any> | any;
abstract deleteLabel(id: number): Observable<any> | Promise<any> | any;
}
@Injectable()
export class LabelDefaultService extends LabelService {
_labelUrl: string;
_labelUrl: string;
constructor(
@Inject(SERVICE_CONFIG) config: IServiceConfig,
private http: Http
) {
super();
this._labelUrl = config.labelEndpoint ? config.labelEndpoint : "/api/labels";
}
constructor(
@Inject(SERVICE_CONFIG) config: IServiceConfig,
private http: Http
) {
super();
this._labelUrl = config.labelEndpoint
? config.labelEndpoint
: "/api/labels";
}
getLabels(scope: string, projectId: number, name?: string, queryParams?: RequestQueryParams): Observable<Label[]> | Promise<Label[]> {
if (!queryParams) {
queryParams = new RequestQueryParams();
}
if (scope) {
queryParams.set('scope', scope);
}
if (projectId) {
queryParams.set('project_id', '' + projectId);
}
if (name) {
queryParams.set('name', '' + name);
}
return this.http.get(this._labelUrl, buildHttpRequestOptions(queryParams)).toPromise()
.then(response => response.json())
.catch(error => Promise.reject(error));
getLabels(
scope: string,
projectId: number,
name?: string,
queryParams?: RequestQueryParams
): Observable<Label[]> | Promise<Label[]> {
if (!queryParams) {
queryParams = new RequestQueryParams();
}
if (scope) {
queryParams.set("scope", scope);
}
if (projectId) {
queryParams.set("project_id", "" + projectId);
}
if (name) {
queryParams.set("name", "" + name);
}
return this.http
.get(this._labelUrl, buildHttpRequestOptions(queryParams))
.toPromise()
.then(response => response.json())
.catch(error => Promise.reject(error));
}
getGLabels(name?: string, queryParams?: RequestQueryParams): Observable<Label[]> | Promise<Label[]> {
if (!queryParams) {
queryParams = new RequestQueryParams();
}
queryParams.set('scope', 'g');
getGLabels(
name?: string,
queryParams?: RequestQueryParams
): Observable<Label[]> | Promise<Label[]> {
if (!queryParams) {
queryParams = new RequestQueryParams();
}
queryParams.set("scope", "g");
if (name) {
queryParams.set('name', '' + name);
}
return this.http.get(this._labelUrl, buildHttpRequestOptions(queryParams)).toPromise()
.then(response => response.json())
.catch(error => Promise.reject(error));
if (name) {
queryParams.set("name", "" + name);
}
return this.http
.get(this._labelUrl, buildHttpRequestOptions(queryParams))
.toPromise()
.then(response => response.json())
.catch(error => Promise.reject(error));
}
getPLabels(projectId: number, name?: string, queryParams?: RequestQueryParams): Observable<Label[]> | Promise<Label[]> {
if (!queryParams) {
queryParams = new RequestQueryParams();
}
queryParams.set('scope', 'p');
if (projectId) {
queryParams.set('project_id', '' + projectId);
}
if (name) {
queryParams.set('name', '' + name);
}
return this.http.get(this._labelUrl, buildHttpRequestOptions(queryParams)).toPromise()
.then(response => response.json())
.catch(error => Promise.reject(error));
getPLabels(
projectId: number,
name?: string,
queryParams?: RequestQueryParams
): Observable<Label[]> | Promise<Label[]> {
if (!queryParams) {
queryParams = new RequestQueryParams();
}
queryParams.set("scope", "p");
if (projectId) {
queryParams.set("project_id", "" + projectId);
}
if (name) {
queryParams.set("name", "" + name);
}
return this.http
.get(this._labelUrl, buildHttpRequestOptions(queryParams))
.toPromise()
.then(response => response.json())
.catch(error => Promise.reject(error));
}
createLabel(label: Label): Observable<any> | Promise<any> | any {
if (!label) {
return Promise.reject('Invalid label.');
}
return this.http.post(this._labelUrl, JSON.stringify(label), HTTP_JSON_OPTIONS).toPromise()
.then(response => response.status)
.catch(error => Promise.reject(error));
createLabel(label: Label): Observable<any> | Promise<any> | any {
if (!label) {
return Promise.reject("Invalid label.");
}
return this.http
.post(this._labelUrl, JSON.stringify(label), HTTP_JSON_OPTIONS)
.toPromise()
.then(response => response.status)
.catch(error => Promise.reject(error));
}
getLabel(id: number): Observable<Label> | Promise<Label> | Label {
if (!id || id <= 0) {
return Promise.reject('Bad request argument.');
}
let reqUrl = `${this._labelUrl}/${id}`
return this.http.get(reqUrl).toPromise()
.then(response => response.json())
.catch(error => Promise.reject(error));
getLabel(id: number): Observable<Label> | Promise<Label> | Label {
if (!id || id <= 0) {
return Promise.reject("Bad request argument.");
}
let reqUrl = `${this._labelUrl}/${id}`;
return this.http
.get(reqUrl)
.toPromise()
.then(response => response.json())
.catch(error => Promise.reject(error));
}
updateLabel(id: number, label: Label): Observable<any> | Promise<any> | any {
if (!id || id <= 0) {
return Promise.reject('Bad request argument.');
}
if (!label) {
return Promise.reject('Invalid endpoint.');
}
let reqUrl = `${this._labelUrl}/${id}`
return this.http.put(reqUrl, JSON.stringify(label), HTTP_JSON_OPTIONS).toPromise()
.then(response => response.status)
.catch(error => Promise.reject(error));
updateLabel(id: number, label: Label): Observable<any> | Promise<any> | any {
if (!id || id <= 0) {
return Promise.reject("Bad request argument.");
}
deleteLabel(id: number): Observable<any> | Promise<any> | any {
if (!id || id <= 0) {
return Promise.reject('Bad request argument.');
}
let reqUrl = `${this._labelUrl}/${id}`
return this.http.delete(reqUrl).toPromise()
.then(response => response.status)
.catch(error => Promise.reject(error));
if (!label) {
return Promise.reject("Invalid endpoint.");
}
}
let reqUrl = `${this._labelUrl}/${id}`;
return this.http
.put(reqUrl, JSON.stringify(label), HTTP_JSON_OPTIONS)
.toPromise()
.then(response => response.status)
.catch(error => Promise.reject(error));
}
deleteLabel(id: number): Observable<any> | Promise<any> | any {
if (!id || id <= 0) {
return Promise.reject("Bad request argument.");
}
let reqUrl = `${this._labelUrl}/${id}`;
return this.http
.delete(reqUrl)
.toPromise()
.then(response => response.status)
.catch(error => Promise.reject(error));
}
}

View File

@ -1,13 +1,17 @@
import { Observable } from 'rxjs/Observable';
import { Injectable, Inject } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/observable/of';
import { Observable } from "rxjs/Observable";
import { Injectable, Inject } from "@angular/core";
import { Http } from "@angular/http";
import "rxjs/add/observable/of";
import { SERVICE_CONFIG, IServiceConfig } from '../service.config';
import { Project } from '../project-policy-config/project';
import { ProjectPolicy } from '../project-policy-config/project-policy-config.component';
import {HTTP_JSON_OPTIONS, HTTP_GET_OPTIONS, buildHttpRequestOptions} from "../utils";
import {RequestQueryParams} from "./RequestQueryParams";
import { SERVICE_CONFIG, IServiceConfig } from "../service.config";
import { Project } from "../project-policy-config/project";
import { ProjectPolicy } from "../project-policy-config/project-policy-config.component";
import {
HTTP_JSON_OPTIONS,
HTTP_GET_OPTIONS,
buildHttpRequestOptions
} from "../utils";
import { RequestQueryParams } from "./RequestQueryParams";
/**
* Define the service methods to handle the Prject related things.
@ -18,41 +22,51 @@ import {RequestQueryParams} from "./RequestQueryParams";
*/
export abstract class ProjectService {
/**
* Get Infomations of a specific Project.
*
* @abstract
* @param {string|number} [projectId]
* @returns {(Observable<Project> | Promise<Project> | Project)}
*
* @memberOf ProjectService
*/
abstract getProject(projectId: number | string): Observable<Project> | Promise<Project> | Project;
* Get Infomations of a specific Project.
*
* @abstract
* @param {string|number} [projectId]
* @returns {(Observable<Project> | Promise<Project> | Project)}
*
* @memberOf ProjectService
*/
abstract getProject(
projectId: number | string
): Observable<Project> | Promise<Project> | Project;
/**
* Update the specified project.
*
* @abstract
* @param {(number | string)} projectId
* @param {ProjectPolicy} projectPolicy
* @returns {(Observable<any> | Promise<any> | any)}
*
* @memberOf EndpointService
*/
abstract updateProjectPolicy(projectId: number | string, projectPolicy: ProjectPolicy): Observable<any> | Promise<any> | any;
/**
* Update the specified project.
*
* @abstract
* @param {(number | string)} projectId
* @param {ProjectPolicy} projectPolicy
* @returns {(Observable<any> | Promise<any> | any)}
*
* @memberOf EndpointService
*/
abstract updateProjectPolicy(
projectId: number | string,
projectPolicy: ProjectPolicy
): Observable<any> | Promise<any> | any;
/**
* Get all projects
*
* @abstract
* @param {string} name
* @param {number} isPublic
* @param {number} page
* @param {number} pageSize
* @returns {(Observable<any> | Promise<any> | any)}
*
* @memberOf EndpointService
*/
abstract listProjects(name: string, isPublic: number, page?: number, pageSize?: number): Observable<Project[]> | Promise<Project[]> | Project[];
/**
* Get all projects
*
* @abstract
* @param {string} name
* @param {number} isPublic
* @param {number} page
* @param {number} pageSize
* @returns {(Observable<any> | Promise<any> | any)}
*
* @memberOf EndpointService
*/
abstract listProjects(
name: string,
isPublic: number,
page?: number,
pageSize?: number
): Observable<Project[]> | Promise<Project[]> | Project[];
}
/**
@ -64,61 +78,78 @@ export abstract class ProjectService {
*/
@Injectable()
export class ProjectDefaultService extends ProjectService {
constructor(
private http: Http,
@Inject(SERVICE_CONFIG) private config: IServiceConfig
private http: Http,
@Inject(SERVICE_CONFIG) private config: IServiceConfig
) {
super();
super();
}
public getProject(projectId: number | string): Observable<Project> | Promise<Project> | Project {
public getProject(
projectId: number | string
): Observable<Project> | Promise<Project> | Project {
if (!projectId) {
return Promise.reject('Bad argument');
return Promise.reject("Bad argument");
}
let baseUrl: string = this.config.projectBaseEndpoint ? this.config.projectBaseEndpoint : '/api/projects';
let baseUrl: string = this.config.projectBaseEndpoint
? this.config.projectBaseEndpoint
: "/api/projects";
return this.http
.get(`${baseUrl}/${projectId}`, HTTP_GET_OPTIONS)
.map(response => response.json())
.catch(error => Observable.throw(error));
.get(`${baseUrl}/${projectId}`, HTTP_GET_OPTIONS)
.map(response => response.json())
.catch(error => Observable.throw(error));
}
public listProjects(name: string, isPublic: number, page?: number, pageSize?: number): Observable<Project[]> | Promise<Project[]> | Project[] {
let baseUrl: string = this.config.projectBaseEndpoint ? this.config.projectBaseEndpoint : '/api/projects';
let params = new RequestQueryParams();
if (page && pageSize) {
params.set('page', page + '');
params.set('page_size', pageSize + '');
}
if (name && name.trim() !== "") {
params.set('name', name);
}
if (isPublic !== undefined) {
params.set('public', '' + isPublic);
}
// let options = new RequestOptions({ headers: this.getHeaders, search: params });
return this.http
.get(baseUrl, buildHttpRequestOptions(params))
.map(response => response.json())
.catch(error => Observable.throw(error));
public listProjects(
name: string,
isPublic: number,
page?: number,
pageSize?: number
): Observable<Project[]> | Promise<Project[]> | Project[] {
let baseUrl: string = this.config.projectBaseEndpoint
? this.config.projectBaseEndpoint
: "/api/projects";
let params = new RequestQueryParams();
if (page && pageSize) {
params.set("page", page + "");
params.set("page_size", pageSize + "");
}
if (name && name.trim() !== "") {
params.set("name", name);
}
if (isPublic !== undefined) {
params.set("public", "" + isPublic);
}
public updateProjectPolicy(projectId: number | string, projectPolicy: ProjectPolicy): any {
let baseUrl: string = this.config.projectBaseEndpoint ? this.config.projectBaseEndpoint : '/api/projects';
// let options = new RequestOptions({ headers: this.getHeaders, search: params });
return this.http
.put(`${baseUrl}/${projectId}`, {
'metadata': {
'public': projectPolicy.Public ? 'true' : 'false',
'enable_content_trust': projectPolicy.ContentTrust ? 'true' : 'false',
'prevent_vul': projectPolicy.PreventVulImg ? 'true' : 'false',
'severity': projectPolicy.PreventVulImgSeverity,
'auto_scan': projectPolicy.ScanImgOnPush ? 'true' : 'false'
}
},
HTTP_JSON_OPTIONS)
.map(response => response.status)
.catch(error => Observable.throw(error));
.get(baseUrl, buildHttpRequestOptions(params))
.map(response => response.json())
.catch(error => Observable.throw(error));
}
public updateProjectPolicy(
projectId: number | string,
projectPolicy: ProjectPolicy
): any {
let baseUrl: string = this.config.projectBaseEndpoint
? this.config.projectBaseEndpoint
: "/api/projects";
return this.http
.put(
`${baseUrl}/${projectId}`,
{
metadata: {
public: projectPolicy.Public ? "true" : "false",
enable_content_trust: projectPolicy.ContentTrust ? "true" : "false",
prevent_vul: projectPolicy.PreventVulImg ? "true" : "false",
severity: projectPolicy.PreventVulImgSeverity,
auto_scan: projectPolicy.ScanImgOnPush ? "true" : "false"
}
},
HTTP_JSON_OPTIONS
)
.map(response => response.status)
.catch(error => Observable.throw(error));
}
}

View File

@ -1,310 +1,420 @@
import { Observable } from 'rxjs/Observable';
import { RequestQueryParams } from './RequestQueryParams';
import {ReplicationJob, ReplicationRule, ReplicationJobItem} from './interface';
import { Http } from "@angular/http";
import { Injectable, Inject } from "@angular/core";
import 'rxjs/add/observable/of';
import { Http, RequestOptions } from '@angular/http';
import { SERVICE_CONFIG, IServiceConfig } from '../service.config';
import { buildHttpRequestOptions, HTTP_JSON_OPTIONS, HTTP_GET_OPTIONS } from '../utils';
import { Observable } from "rxjs/Observable";
import "rxjs/add/observable/of";
import { SERVICE_CONFIG, IServiceConfig } from "../service.config";
import {
buildHttpRequestOptions,
HTTP_JSON_OPTIONS,
HTTP_GET_OPTIONS
} from "../utils";
import {
ReplicationJob,
ReplicationRule,
ReplicationJobItem
} from "./interface";
import { RequestQueryParams } from "./RequestQueryParams";
/**
* Define the service methods to handle the replication (rule and job) related things.
*
*
* @export
* @abstract
* @class ReplicationService
*/
export abstract class ReplicationService {
/**
* Get the replication rules.
* Set the argument 'projectId' to limit the data scope to the specified project;
* set the argument 'ruleName' to return the rule only match the name pattern;
* if pagination needed, use the queryParams to add query parameters.
*
* @abstract
* @param {(number | string)} [projectId]
* @param {string} [ruleName]
* @param {RequestQueryParams} [queryParams]
* @returns {(Observable<ReplicationRule[]> | Promise<ReplicationRule[]> | ReplicationRule[])}
*
* @memberOf ReplicationService
*/
abstract getReplicationRules(projectId?: number | string, ruleName?: string, queryParams?: RequestQueryParams): Observable<ReplicationRule[]> | Promise<ReplicationRule[]> | ReplicationRule[];
/**
* Get the replication rules.
* Set the argument 'projectId' to limit the data scope to the specified project;
* set the argument 'ruleName' to return the rule only match the name pattern;
* if pagination needed, use the queryParams to add query parameters.
*
* @abstract
* @param {(number | string)} [projectId]
* @param {string} [ruleName]
* @param {RequestQueryParams} [queryParams]
* @returns {(Observable<ReplicationRule[]> | Promise<ReplicationRule[]> | ReplicationRule[])}
*
* @memberOf ReplicationService
*/
abstract getReplicationRules(
projectId?: number | string,
ruleName?: string,
queryParams?: RequestQueryParams
):
| Observable<ReplicationRule[]>
| Promise<ReplicationRule[]>
| ReplicationRule[];
/**
* Get the specified replication rule.
*
* @abstract
* @param {(number | string)} ruleId
* @returns {(Observable<ReplicationRule> | Promise<ReplicationRule> | ReplicationRule)}
*
* @memberOf ReplicationService
*/
abstract getReplicationRule(ruleId: number | string): Observable<ReplicationRule> | Promise<ReplicationRule> | ReplicationRule;
/**
* Get the specified replication rule.
*
* @abstract
* @param {(number | string)} ruleId
* @returns {(Observable<ReplicationRule> | Promise<ReplicationRule> | ReplicationRule)}
*
* @memberOf ReplicationService
*/
abstract getReplicationRule(
ruleId: number | string
): Observable<ReplicationRule> | Promise<ReplicationRule> | ReplicationRule;
/**
* Create new replication rule.
*
* @abstract
* @param {ReplicationRule} replicationRule
* @returns {(Observable<any> | Promise<any> | any)}
*
* @memberOf ReplicationService
*/
abstract createReplicationRule(replicationRule: ReplicationRule): Observable<any> | Promise<any> | any;
/**
* Create new replication rule.
*
* @abstract
* @param {ReplicationRule} replicationRule
* @returns {(Observable<any> | Promise<any> | any)}
*
* @memberOf ReplicationService
*/
abstract createReplicationRule(
replicationRule: ReplicationRule
): Observable<any> | Promise<any> | any;
/**
* Update the specified replication rule.
*
* @abstract
* @param {ReplicationRule} replicationRule
* @returns {(Observable<any> | Promise<any> | any)}
*
* @memberOf ReplicationService
*/
abstract updateReplicationRule(id: number, rep: ReplicationRule): Observable<any> | Promise<any> | any;
/**
* Update the specified replication rule.
*
* @abstract
* @param {ReplicationRule} replicationRule
* @returns {(Observable<any> | Promise<any> | any)}
*
* @memberOf ReplicationService
*/
abstract updateReplicationRule(
id: number,
rep: ReplicationRule
): Observable<any> | Promise<any> | any;
/**
* Delete the specified replication rule.
*
* @abstract
* @param {(number | string)} ruleId
* @returns {(Observable<any> | Promise<any> | any)}
*
* @memberOf ReplicationService
*/
abstract deleteReplicationRule(ruleId: number | string): Observable<any> | Promise<any> | any;
/**
* Delete the specified replication rule.
*
* @abstract
* @param {(number | string)} ruleId
* @returns {(Observable<any> | Promise<any> | any)}
*
* @memberOf ReplicationService
*/
abstract deleteReplicationRule(
ruleId: number | string
): Observable<any> | Promise<any> | any;
/**
* Enable the specified replication rule.
*
* @abstract
* @param {(number | string)} ruleId
* @returns {(Observable<any> | Promise<any> | any)}
*
* @memberOf ReplicationService
*/
abstract enableReplicationRule(ruleId: number | string, enablement: number): Observable<any> | Promise<any> | any;
/**
* Enable the specified replication rule.
*
* @abstract
* @param {(number | string)} ruleId
* @returns {(Observable<any> | Promise<any> | any)}
*
* @memberOf ReplicationService
*/
abstract enableReplicationRule(
ruleId: number | string,
enablement: number
): Observable<any> | Promise<any> | any;
/**
* Disable the specified replication rule.
*
* @abstract
* @param {(number | string)} ruleId
* @returns {(Observable<any> | Promise<any> | any)}
*
* @memberOf ReplicationService
*/
abstract disableReplicationRule(ruleId: number | string): Observable<any> | Promise<any> | any;
/**
* Disable the specified replication rule.
*
* @abstract
* @param {(number | string)} ruleId
* @returns {(Observable<any> | Promise<any> | any)}
*
* @memberOf ReplicationService
*/
abstract disableReplicationRule(
ruleId: number | string
): Observable<any> | Promise<any> | any;
abstract replicateRule(
ruleId: number | string
): Observable<any> | Promise<any> | any;
abstract replicateRule(ruleId: number | string): Observable<any> | Promise<any> | any;
/**
* Get the jobs for the specified replication rule.
* Set query parameters through 'queryParams', support:
* - status
* - repository
* - startTime and endTime
* - page
* - pageSize
*
* @abstract
* @param {(number | string)} ruleId
* @param {RequestQueryParams} [queryParams]
* @returns {(Observable<ReplicationJob> | Promise<ReplicationJob> | ReplicationJob)}
*
* @memberOf ReplicationService
*/
abstract getJobs(
ruleId: number | string,
queryParams?: RequestQueryParams
): Observable<ReplicationJob> | Promise<ReplicationJob> | ReplicationJob;
/**
* Get the jobs for the specified replication rule.
* Set query parameters through 'queryParams', support:
* - status
* - repository
* - startTime and endTime
* - page
* - pageSize
*
* @abstract
* @param {(number | string)} ruleId
* @param {RequestQueryParams} [queryParams]
* @returns {(Observable<ReplicationJob> | Promise<ReplicationJob> | ReplicationJob)}
*
* @memberOf ReplicationService
*/
abstract getJobs(ruleId: number | string, queryParams?: RequestQueryParams): Observable<ReplicationJob> | Promise<ReplicationJob> | ReplicationJob;
/**
* Get the log of the specified job.
*
* @abstract
* @param {(number | string)} jobId
* @returns {(Observable<string> | Promise<string> | string)}
* @memberof ReplicationService
*/
abstract getJobLog(
jobId: number | string
): Observable<string> | Promise<string> | string;
/**
* Get the log of the specified job.
*
* @abstract
* @param {(number | string)} jobId
* @returns {(Observable<string> | Promise<string> | string)}
* @memberof ReplicationService
*/
abstract getJobLog(jobId: number | string): Observable<string> | Promise<string> | string;
abstract stopJobs(jobId: number | string): Observable<string> | Promise<string> | string;
abstract stopJobs(
jobId: number | string
): Observable<string> | Promise<string> | string;
}
/**
* Implement default service for replication rule and job.
*
*
* @export
* @class ReplicationDefaultService
* @extends {ReplicationService}
*/
@Injectable()
export class ReplicationDefaultService extends ReplicationService {
_ruleBaseUrl: string;
_jobBaseUrl: string;
_replicateUrl: string;
_ruleBaseUrl: string;
_jobBaseUrl: string;
_replicateUrl: string;
constructor(
private http: Http,
@Inject(SERVICE_CONFIG) config: IServiceConfig
) {
super();
this._ruleBaseUrl = config.replicationRuleEndpoint ? config.replicationRuleEndpoint : '/api/policies/replication';
this._jobBaseUrl = config.replicationJobEndpoint ? config.replicationJobEndpoint : '/api/jobs/replication';
this._replicateUrl = config.replicationBaseEndpoint ? config.replicationBaseEndpoint : '/api/replications';
constructor(
private http: Http,
@Inject(SERVICE_CONFIG) config: IServiceConfig
) {
super();
this._ruleBaseUrl = config.replicationRuleEndpoint
? config.replicationRuleEndpoint
: "/api/policies/replication";
this._jobBaseUrl = config.replicationJobEndpoint
? config.replicationJobEndpoint
: "/api/jobs/replication";
this._replicateUrl = config.replicationBaseEndpoint
? config.replicationBaseEndpoint
: "/api/replications";
}
// Private methods
// Check if the rule object is valid
_isValidRule(rule: ReplicationRule): boolean {
return (
rule !== undefined &&
rule != null &&
rule.name !== undefined &&
rule.name.trim() !== "" &&
rule.targets.length !== 0
);
}
public getReplicationRules(
projectId?: number | string,
ruleName?: string,
queryParams?: RequestQueryParams
):
| Observable<ReplicationRule[]>
| Promise<ReplicationRule[]>
| ReplicationRule[] {
if (!queryParams) {
queryParams = new RequestQueryParams();
}
//Private methods
//Check if the rule object is valid
_isValidRule(rule: ReplicationRule): boolean {
return rule !== undefined && rule != null && rule.name !== undefined && rule.name.trim() !== '' && rule.targets.length !== 0;
if (projectId) {
queryParams.set("project_id", "" + projectId);
}
public getReplicationRules(projectId?: number | string, ruleName?: string, queryParams?: RequestQueryParams): Observable<ReplicationRule[]> | Promise<ReplicationRule[]> | ReplicationRule[] {
if (!queryParams) {
queryParams = new RequestQueryParams();
}
if (projectId) {
queryParams.set('project_id', '' + projectId);
}
if (ruleName) {
queryParams.set('name', ruleName);
}
return this.http.get(this._ruleBaseUrl, buildHttpRequestOptions(queryParams)).toPromise()
.then(response => response.json() as ReplicationRule[])
.catch(error => Promise.reject(error));
if (ruleName) {
queryParams.set("name", ruleName);
}
public getReplicationRule(ruleId: number | string): Observable<ReplicationRule> | Promise<ReplicationRule> | ReplicationRule {
if (!ruleId) {
return Promise.reject("Bad argument");
}
return this.http
.get(this._ruleBaseUrl, buildHttpRequestOptions(queryParams))
.toPromise()
.then(response => response.json() as ReplicationRule[])
.catch(error => Promise.reject(error));
}
let url: string = `${this._ruleBaseUrl}/${ruleId}`;
return this.http.get(url, HTTP_GET_OPTIONS).toPromise()
.then(response => response.json() as ReplicationRule)
.catch(error => Promise.reject(error));
public getReplicationRule(
ruleId: number | string
): Observable<ReplicationRule> | Promise<ReplicationRule> | ReplicationRule {
if (!ruleId) {
return Promise.reject("Bad argument");
}
public createReplicationRule(replicationRule: ReplicationRule): Observable<any> | Promise<any> | any {
if (!this._isValidRule(replicationRule)) {
return Promise.reject('Bad argument');
}
let url: string = `${this._ruleBaseUrl}/${ruleId}`;
return this.http
.get(url, HTTP_GET_OPTIONS)
.toPromise()
.then(response => response.json() as ReplicationRule)
.catch(error => Promise.reject(error));
}
return this.http.post(this._ruleBaseUrl, JSON.stringify(replicationRule), HTTP_JSON_OPTIONS).toPromise()
.then(response => response)
.catch(error => Promise.reject(error));
public createReplicationRule(
replicationRule: ReplicationRule
): Observable<any> | Promise<any> | any {
if (!this._isValidRule(replicationRule)) {
return Promise.reject("Bad argument");
}
public updateReplicationRule(id: number, rep: ReplicationRule): Observable<any> | Promise<any> | any {
if (!this._isValidRule(rep)) {
return Promise.reject('Bad argument');
}
return this.http
.post(
this._ruleBaseUrl,
JSON.stringify(replicationRule),
HTTP_JSON_OPTIONS
)
.toPromise()
.then(response => response)
.catch(error => Promise.reject(error));
}
let url = `${this._ruleBaseUrl}/${id}`;
return this.http.put(url, JSON.stringify(rep), HTTP_JSON_OPTIONS).toPromise()
.then(response => response)
.catch(error => Promise.reject(error));
public updateReplicationRule(
id: number,
rep: ReplicationRule
): Observable<any> | Promise<any> | any {
if (!this._isValidRule(rep)) {
return Promise.reject("Bad argument");
}
public deleteReplicationRule(ruleId: number | string): Observable<any> | Promise<any> | any {
if (!ruleId || ruleId <= 0) {
return Promise.reject('Bad argument');
}
let url = `${this._ruleBaseUrl}/${id}`;
return this.http
.put(url, JSON.stringify(rep), HTTP_JSON_OPTIONS)
.toPromise()
.then(response => response)
.catch(error => Promise.reject(error));
}
let url: string = `${this._ruleBaseUrl}/${ruleId}`;
return this.http.delete(url, HTTP_JSON_OPTIONS).toPromise()
.then(response => response)
.catch(error => Promise.reject(error));
public deleteReplicationRule(
ruleId: number | string
): Observable<any> | Promise<any> | any {
if (!ruleId || ruleId <= 0) {
return Promise.reject("Bad argument");
}
public replicateRule(ruleId: number | string): Observable<any> | Promise<any> | any {
if (!ruleId) {
return Promise.reject("Bad argument");
}
let url: string = `${this._ruleBaseUrl}/${ruleId}`;
return this.http
.delete(url, HTTP_JSON_OPTIONS)
.toPromise()
.then(response => response)
.catch(error => Promise.reject(error));
}
let url: string = `${this._replicateUrl}`;
return this.http.post(url, {policy_id: ruleId}, HTTP_JSON_OPTIONS).toPromise()
.then(response => response)
.catch(error => Promise.reject(error));
public replicateRule(
ruleId: number | string
): Observable<any> | Promise<any> | any {
if (!ruleId) {
return Promise.reject("Bad argument");
}
public enableReplicationRule(ruleId: number | string, enablement: number): Observable<any> | Promise<any> | any {
if (!ruleId || ruleId <= 0) {
return Promise.reject('Bad argument');
}
let url: string = `${this._replicateUrl}`;
return this.http
.post(url, { policy_id: ruleId }, HTTP_JSON_OPTIONS)
.toPromise()
.then(response => response)
.catch(error => Promise.reject(error));
}
let url: string = `${this._ruleBaseUrl}/${ruleId}/enablement`;
return this.http.put(url, { enabled: enablement }, HTTP_JSON_OPTIONS).toPromise()
.then(response => response)
.catch(error => Promise.reject(error));
public enableReplicationRule(
ruleId: number | string,
enablement: number
): Observable<any> | Promise<any> | any {
if (!ruleId || ruleId <= 0) {
return Promise.reject("Bad argument");
}
public disableReplicationRule(ruleId: number | string): Observable<any> | Promise<any> | any {
if (!ruleId || ruleId <= 0) {
return Promise.reject('Bad argument');
}
let url: string = `${this._ruleBaseUrl}/${ruleId}/enablement`;
return this.http
.put(url, { enabled: enablement }, HTTP_JSON_OPTIONS)
.toPromise()
.then(response => response)
.catch(error => Promise.reject(error));
}
let url: string = `${this._ruleBaseUrl}/${ruleId}/enablement`;
return this.http.put(url, { enabled: 0 }, HTTP_JSON_OPTIONS).toPromise()
.then(response => response)
.catch(error => Promise.reject(error));
public disableReplicationRule(
ruleId: number | string
): Observable<any> | Promise<any> | any {
if (!ruleId || ruleId <= 0) {
return Promise.reject("Bad argument");
}
public getJobs(ruleId: number | string, queryParams?: RequestQueryParams): Observable<ReplicationJob> | Promise<ReplicationJob> | ReplicationJob {
if (!ruleId || ruleId <= 0) {
return Promise.reject('Bad argument');
}
let url: string = `${this._ruleBaseUrl}/${ruleId}/enablement`;
return this.http
.put(url, { enabled: 0 }, HTTP_JSON_OPTIONS)
.toPromise()
.then(response => response)
.catch(error => Promise.reject(error));
}
if (!queryParams) {
queryParams = new RequestQueryParams();
}
queryParams.set('policy_id', '' + ruleId);
return this.http.get(this._jobBaseUrl, buildHttpRequestOptions(queryParams)).toPromise()
.then(response => {
let result: ReplicationJob = {
metadata: {
xTotalCount: 0
},
data: []
};
if (response && response.headers) {
let xHeader: string = response.headers.get("X-Total-Count");
if (xHeader) {
result.metadata.xTotalCount = parseInt(xHeader, 0);
}
}
result.data = response.json() as ReplicationJobItem[];
if (result.metadata.xTotalCount === 0) {
if (result.data && result.data.length > 0) {
result.metadata.xTotalCount = result.data.length;
}
}
return result;
})
.catch(error => Promise.reject(error));
public getJobs(
ruleId: number | string,
queryParams?: RequestQueryParams
): Observable<ReplicationJob> | Promise<ReplicationJob> | ReplicationJob {
if (!ruleId || ruleId <= 0) {
return Promise.reject("Bad argument");
}
public getJobLog(jobId: number | string): Observable<string> | Promise<string> | string {
if (!jobId || jobId <= 0) {
return Promise.reject('Bad argument');
if (!queryParams) {
queryParams = new RequestQueryParams();
}
queryParams.set("policy_id", "" + ruleId);
return this.http
.get(this._jobBaseUrl, buildHttpRequestOptions(queryParams))
.toPromise()
.then(response => {
let result: ReplicationJob = {
metadata: {
xTotalCount: 0
},
data: []
};
if (response && response.headers) {
let xHeader: string = response.headers.get("X-Total-Count");
if (xHeader) {
result.metadata.xTotalCount = parseInt(xHeader, 0);
}
}
result.data = response.json() as ReplicationJobItem[];
if (result.metadata.xTotalCount === 0) {
if (result.data && result.data.length > 0) {
result.metadata.xTotalCount = result.data.length;
}
}
let logUrl = `${this._jobBaseUrl}/${jobId}/log`;
return this.http.get(logUrl, HTTP_GET_OPTIONS).toPromise()
.then(response => response.text())
.catch(error => Promise.reject(error));
return result;
})
.catch(error => Promise.reject(error));
}
public getJobLog(
jobId: number | string
): Observable<string> | Promise<string> | string {
if (!jobId || jobId <= 0) {
return Promise.reject("Bad argument");
}
public stopJobs(jobId: number | string): Observable<any> | Promise<any> | any {
return this.http.put(this._jobBaseUrl, JSON.stringify({'policy_id': jobId, 'status': 'stop' }), HTTP_JSON_OPTIONS).toPromise()
.then(response => response)
.catch(error => Promise.reject(error));
}
}
let logUrl = `${this._jobBaseUrl}/${jobId}/log`;
return this.http
.get(logUrl, HTTP_GET_OPTIONS)
.toPromise()
.then(response => response.text())
.catch(error => Promise.reject(error));
}
public stopJobs(
jobId: number | string
): Observable<any> | Promise<any> | any {
return this.http
.put(
this._jobBaseUrl,
JSON.stringify({ policy_id: jobId, status: "stop" }),
HTTP_JSON_OPTIONS
)
.toPromise()
.then(response => response)
.catch(error => Promise.reject(error));
}
}

View File

@ -1,114 +1,161 @@
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import { Http } from "@angular/http";
import { Injectable, Inject } from "@angular/core";
import { SERVICE_CONFIG, IServiceConfig } from '../service.config';
import { Http, URLSearchParams } from '@angular/http';
import { buildHttpRequestOptions, HTTP_JSON_OPTIONS } from '../utils';
import { RequestQueryParams } from './RequestQueryParams';
import { Observable } from "rxjs/Observable";
import "rxjs/add/observable/of";
import {
VulnerabilityItem,
VulnerabilitySummary
} from './interface';
import { SERVICE_CONFIG, IServiceConfig } from "../service.config";
import { buildHttpRequestOptions, HTTP_JSON_OPTIONS } from "../utils";
import { RequestQueryParams } from "./RequestQueryParams";
import { VulnerabilityItem, VulnerabilitySummary } from "./interface";
/**
* Get the vulnerabilities scanning results for the specified tag.
*
*
* @export
* @abstract
* @class ScanningResultService
*/
export abstract class ScanningResultService {
/**
* Get the summary of vulnerability scanning result.
*
* @abstract
* @param {string} tagId
* @returns {(Observable<VulnerabilitySummary> | Promise<VulnerabilitySummary> | VulnerabilitySummary)}
*
* @memberOf ScanningResultService
*/
abstract getVulnerabilityScanningSummary(repoName: string, tagId: string, queryParams?: RequestQueryParams): Observable<VulnerabilitySummary> | Promise<VulnerabilitySummary> | VulnerabilitySummary;
/**
* Get the summary of vulnerability scanning result.
*
* @abstract
* @param {string} tagId
* @returns {(Observable<VulnerabilitySummary> | Promise<VulnerabilitySummary> | VulnerabilitySummary)}
*
* @memberOf ScanningResultService
*/
abstract getVulnerabilityScanningSummary(
repoName: string,
tagId: string,
queryParams?: RequestQueryParams
):
| Observable<VulnerabilitySummary>
| Promise<VulnerabilitySummary>
| VulnerabilitySummary;
/**
* Get the detailed vulnerabilities scanning results.
*
* @abstract
* @param {string} tagId
* @returns {(Observable<VulnerabilityItem[]> | Promise<VulnerabilityItem[]> | VulnerabilityItem[])}
*
* @memberOf ScanningResultService
*/
abstract getVulnerabilityScanningResults(repoName: string, tagId: string, queryParams?: RequestQueryParams): Observable<VulnerabilityItem[]> | Promise<VulnerabilityItem[]> | VulnerabilityItem[];
/**
* Get the detailed vulnerabilities scanning results.
*
* @abstract
* @param {string} tagId
* @returns {(Observable<VulnerabilityItem[]> | Promise<VulnerabilityItem[]> | VulnerabilityItem[])}
*
* @memberOf ScanningResultService
*/
abstract getVulnerabilityScanningResults(
repoName: string,
tagId: string,
queryParams?: RequestQueryParams
):
| Observable<VulnerabilityItem[]>
| Promise<VulnerabilityItem[]>
| VulnerabilityItem[];
/**
* Start a new vulnerability scanning
*
* @abstract
* @param {string} repoName
* @param {string} tagId
* @returns {(Observable<any> | Promise<any> | any)}
*
* @memberOf ScanningResultService
*/
abstract startVulnerabilityScanning(
repoName: string,
tagId: string
): Observable<any> | Promise<any> | any;
/**
* Start a new vulnerability scanning
*
* @abstract
* @param {string} repoName
* @param {string} tagId
* @returns {(Observable<any> | Promise<any> | any)}
*
* @memberOf ScanningResultService
*/
abstract startVulnerabilityScanning(repoName: string, tagId: string): Observable<any> | Promise<any> | any;
/**
* Trigger the scanning all action.
*
* @abstract
* @returns {(Observable<any> | Promise<any> | any)}
*
* @memberOf ScanningResultService
*/
abstract startScanningAll(): Observable<any> | Promise<any> | any;
/**
* Trigger the scanning all action.
*
* @abstract
* @returns {(Observable<any> | Promise<any> | any)}
*
* @memberOf ScanningResultService
*/
abstract startScanningAll(): Observable<any> | Promise<any> | any;
}
@Injectable()
export class ScanningResultDefaultService extends ScanningResultService {
_baseUrl: string = '/api/repositories';
_baseUrl: string = "/api/repositories";
constructor(
private http: Http,
@Inject(SERVICE_CONFIG) private config: IServiceConfig) {
super();
if (this.config && this.config.vulnerabilityScanningBaseEndpoint) {
this._baseUrl = this.config.vulnerabilityScanningBaseEndpoint;
}
constructor(
private http: Http,
@Inject(SERVICE_CONFIG) private config: IServiceConfig
) {
super();
if (this.config && this.config.vulnerabilityScanningBaseEndpoint) {
this._baseUrl = this.config.vulnerabilityScanningBaseEndpoint;
}
}
getVulnerabilityScanningSummary(
repoName: string,
tagId: string,
queryParams?: RequestQueryParams
):
| Observable<VulnerabilitySummary>
| Promise<VulnerabilitySummary>
| VulnerabilitySummary {
if (!repoName || repoName.trim() === "" || !tagId || tagId.trim() === "") {
return Promise.reject("Bad argument");
}
getVulnerabilityScanningSummary(repoName: string, tagId: string, queryParams?: RequestQueryParams): Observable<VulnerabilitySummary> | Promise<VulnerabilitySummary> | VulnerabilitySummary {
if (!repoName || repoName.trim() === '' || !tagId || tagId.trim() === '') {
return Promise.reject('Bad argument');
}
return Observable.of({} as VulnerabilitySummary);
}
return Observable.of({});
getVulnerabilityScanningResults(
repoName: string,
tagId: string,
queryParams?: RequestQueryParams
):
| Observable<VulnerabilityItem[]>
| Promise<VulnerabilityItem[]>
| VulnerabilityItem[] {
if (!repoName || repoName.trim() === "" || !tagId || tagId.trim() === "") {
return Promise.reject("Bad argument");
}
getVulnerabilityScanningResults(repoName: string, tagId: string, queryParams?: RequestQueryParams): Observable<VulnerabilityItem[]> | Promise<VulnerabilityItem[]> | VulnerabilityItem[] {
if (!repoName || repoName.trim() === '' || !tagId || tagId.trim() === '') {
return Promise.reject('Bad argument');
}
return this.http
.get(
`${this._baseUrl}/${repoName}/tags/${tagId}/vulnerability/details`,
buildHttpRequestOptions(queryParams)
)
.toPromise()
.then(response => response.json() as VulnerabilityItem[])
.catch(error => Promise.reject(error));
}
return this.http.get(`${this._baseUrl}/${repoName}/tags/${tagId}/vulnerability/details`, buildHttpRequestOptions(queryParams)).toPromise()
.then(response => response.json() as VulnerabilityItem[])
.catch(error => Promise.reject(error));
startVulnerabilityScanning(
repoName: string,
tagId: string
): Observable<any> | Promise<any> | any {
if (!repoName || repoName.trim() === "" || !tagId || tagId.trim() === "") {
return Promise.reject("Bad argument");
}
startVulnerabilityScanning(repoName: string, tagId: string): Observable<any> | Promise<any> | any {
if (!repoName || repoName.trim() === '' || !tagId || tagId.trim() === '') {
return Promise.reject('Bad argument');
}
return this.http
.post(
`${this._baseUrl}/${repoName}/tags/${tagId}/scan`,
HTTP_JSON_OPTIONS
)
.toPromise()
.then(() => {
return true;
})
.catch(error => Promise.reject(error));
}
return this.http.post(`${this._baseUrl}/${repoName}/tags/${tagId}/scan`, HTTP_JSON_OPTIONS).toPromise()
.then(() => { return true })
.catch(error => Promise.reject(error));
}
startScanningAll(): Observable<any> | Promise<any> | any {
return this.http.post(`${this._baseUrl}/scanAll`, HTTP_JSON_OPTIONS).toPromise()
.then(() => {return true})
.catch(error => Promise.reject(error));
}
}
startScanningAll(): Observable<any> | Promise<any> | any {
return this.http
.post(`${this._baseUrl}/scanAll`, HTTP_JSON_OPTIONS)
.toPromise()
.then(() => {
return true;
})
.catch(error => Promise.reject(error));
}
}

View File

@ -1,29 +1,25 @@
import { TestBed, inject, async } from '@angular/core/testing';
import { TestBed, inject } from '@angular/core/testing';
import { TagService, TagDefaultService } from './tag.service';
import { SharedModule } from '../shared/shared.module';
import { SERVICE_CONFIG, IServiceConfig } from '../service.config';
import { TagService, TagDefaultService } from './tag.service';
import { Tag } from './interface';
import { VerifiedSignature } from './tag.service';
import { toPromise } from '../utils';
describe('TagService', () => {
let mockTags: Tag[] = [
{
"digest": "sha256:e5c82328a509aeb7c18c1d7fb36633dc638fcf433f651bdcda59c1cc04d3ee55",
"name": "1.11.5",
"size": "2049",
"architecture": "amd64",
"os": "linux",
"docker_version": "1.12.3",
"author": "NGINX Docker Maintainers \"docker-maint@nginx.com\"",
"created": new Date("2016-11-08T22:41:15.912313785Z"),
"signature": null,
'labels': []
}
];
// let mockTags: Tag[] = [
// {
// "digest": "sha256:e5c82328a509aeb7c18c1d7fb36633dc638fcf433f651bdcda59c1cc04d3ee55",
// "name": "1.11.5",
// "size": "2049",
// "architecture": "amd64",
// "os": "linux",
// "docker_version": "1.12.3",
// "author": "NGINX Docker Maintainers \"docker-maint@nginx.com\"",
// "created": new Date("2016-11-08T22:41:15.912313785Z"),
// "signature": null,
// 'labels': []
// }
// ];
const mockConfig: IServiceConfig = {
repositoryBaseEndpoint: "/api/repositories/testing"

View File

@ -1,167 +1,229 @@
import { Observable } from 'rxjs/Observable';
import { RequestQueryParams } from './RequestQueryParams';
import {Label, Tag} from './interface';
import { Injectable, Inject } from "@angular/core";
import 'rxjs/add/observable/of';
import { Http } from '@angular/http';
import { SERVICE_CONFIG, IServiceConfig } from '../service.config';
import { buildHttpRequestOptions, HTTP_JSON_OPTIONS, HTTP_GET_OPTIONS } from '../utils';
import { Http } from "@angular/http";
import { Observable } from "rxjs/Observable";
import "rxjs/add/observable/of";
import { SERVICE_CONFIG, IServiceConfig } from "../service.config";
import {
buildHttpRequestOptions,
HTTP_JSON_OPTIONS,
HTTP_GET_OPTIONS
} from "../utils";
import { RequestQueryParams } from "./RequestQueryParams";
import { Tag } from "./interface";
/**
* For getting tag signatures.
* This is temporary, will be removed in future.
*
*
* @export
* @class VerifiedSignature
*/
export class VerifiedSignature {
tag: string;
hashes: {
sha256: string;
}
tag: string;
hashes: {
sha256: string;
};
}
/**
* Define the service methods to handle the repository tag related things.
*
*
* @export
* @abstract
* @class TagService
*/
export abstract class TagService {
/**
* Get all the tags under the specified repository.
* NOTES: If the Notary is enabled, the signatures should be included in the returned data.
*
* @abstract
* @param {string} repositoryName
* @param {RequestQueryParams} [queryParams]
* @returns {(Observable<Tag[]> | Promise<Tag[]> | Tag[])}
*
* @memberOf TagService
*/
abstract getTags(repositoryName: string, queryParams?: RequestQueryParams): Observable<Tag[]> | Promise<Tag[]> | Tag[];
/**
* Get all the tags under the specified repository.
* NOTES: If the Notary is enabled, the signatures should be included in the returned data.
*
* @abstract
* @param {string} repositoryName
* @param {RequestQueryParams} [queryParams]
* @returns {(Observable<Tag[]> | Promise<Tag[]> | Tag[])}
*
* @memberOf TagService
*/
abstract getTags(
repositoryName: string,
queryParams?: RequestQueryParams
): Observable<Tag[]> | Promise<Tag[]> | Tag[];
/**
* Delete the specified tag.
*
* @abstract
* @param {string} repositoryName
* @param {string} tag
* @returns {(Observable<any> | any)}
*
* @memberOf TagService
*/
abstract deleteTag(repositoryName: string, tag: string): Observable<any> | Promise<any> | any;
/**
* Delete the specified tag.
*
* @abstract
* @param {string} repositoryName
* @param {string} tag
* @returns {(Observable<any> | any)}
*
* @memberOf TagService
*/
abstract deleteTag(
repositoryName: string,
tag: string
): Observable<any> | Promise<any> | any;
/**
* Get the specified tag.
*
* @abstract
* @param {string} repositoryName
* @param {string} tag
* @returns {(Observable<Tag> | Promise<Tag> | Tag)}
*
* @memberOf TagService
*/
abstract getTag(repositoryName: string, tag: string, queryParams?: RequestQueryParams): Observable<Tag> | Promise<Tag> | Tag;
/**
* Get the specified tag.
*
* @abstract
* @param {string} repositoryName
* @param {string} tag
* @returns {(Observable<Tag> | Promise<Tag> | Tag)}
*
* @memberOf TagService
*/
abstract getTag(
repositoryName: string,
tag: string,
queryParams?: RequestQueryParams
): Observable<Tag> | Promise<Tag> | Tag;
abstract addLabelToImages(repoName: string, tagName: string, labelId: number): Observable<any> | Promise<any> | any;
abstract deleteLabelToImages(repoName: string, tagName: string, labelId: number): Observable<any> | Promise<any> | any;
abstract addLabelToImages(
repoName: string,
tagName: string,
labelId: number
): Observable<any> | Promise<any> | any;
abstract deleteLabelToImages(
repoName: string,
tagName: string,
labelId: number
): Observable<any> | Promise<any> | any;
}
/**
* Implement default service for tag.
*
*
* @export
* @class TagDefaultService
* @extends {TagService}
*/
@Injectable()
export class TagDefaultService extends TagService {
_baseUrl: string;
_labelUrl: string;
constructor(
private http: Http,
@Inject(SERVICE_CONFIG) private config: IServiceConfig
) {
super();
this._baseUrl = this.config.repositoryBaseEndpoint ? this.config.repositoryBaseEndpoint : '/api/repositories';
this._labelUrl = this.config.labelEndpoint? this.config.labelEndpoint : '/api/labels';
_baseUrl: string;
_labelUrl: string;
constructor(
private http: Http,
@Inject(SERVICE_CONFIG) private config: IServiceConfig
) {
super();
this._baseUrl = this.config.repositoryBaseEndpoint
? this.config.repositoryBaseEndpoint
: "/api/repositories";
this._labelUrl = this.config.labelEndpoint
? this.config.labelEndpoint
: "/api/labels";
}
// Private methods
// These two methods are temporary, will be deleted in future after API refactored
_getTags(
repositoryName: string,
queryParams?: RequestQueryParams
): Promise<Tag[]> {
if (!queryParams) {
queryParams = new RequestQueryParams();
}
//Private methods
//These two methods are temporary, will be deleted in future after API refactored
_getTags(repositoryName: string, queryParams?: RequestQueryParams): Promise<Tag[]> {
if (!queryParams) {
queryParams = new RequestQueryParams();
}
queryParams.set("detail", "1");
let url: string = `${this._baseUrl}/${repositoryName}/tags`;
queryParams.set('detail', '1');
let url: string = `${this._baseUrl}/${repositoryName}/tags`;
return this.http
.get(url, buildHttpRequestOptions(queryParams))
.toPromise()
.then(response => response.json() as Tag[])
.catch(error => Promise.reject(error));
}
return this.http.get(url, buildHttpRequestOptions(queryParams)).toPromise()
.then(response => response.json() as Tag[])
.catch(error => Promise.reject(error));
_getSignatures(repositoryName: string): Promise<VerifiedSignature[]> {
let url: string = `${this._baseUrl}/${repositoryName}/signatures`;
return this.http
.get(url, HTTP_GET_OPTIONS)
.toPromise()
.then(response => response.json() as VerifiedSignature[])
.catch(error => Promise.reject(error));
}
public getTags(
repositoryName: string,
queryParams?: RequestQueryParams
): Observable<Tag[]> | Promise<Tag[]> | Tag[] {
if (!repositoryName) {
return Promise.reject("Bad argument");
}
return this._getTags(repositoryName, queryParams);
}
public deleteTag(
repositoryName: string,
tag: string
): Observable<any> | Promise<Tag> | any {
if (!repositoryName || !tag) {
return Promise.reject("Bad argument");
}
_getSignatures(repositoryName: string): Promise<VerifiedSignature[]> {
let url: string = `${this._baseUrl}/${repositoryName}/signatures`;
return this.http.get(url, HTTP_GET_OPTIONS).toPromise()
.then(response => response.json() as VerifiedSignature[])
.catch(error => Promise.reject(error))
let url: string = `${this._baseUrl}/${repositoryName}/tags/${tag}`;
return this.http
.delete(url, HTTP_JSON_OPTIONS)
.toPromise()
.then(response => response)
.catch(error => Promise.reject(error));
}
public getTag(
repositoryName: string,
tag: string,
queryParams?: RequestQueryParams
): Observable<Tag> | Promise<Tag> | Tag {
if (!repositoryName || !tag) {
return Promise.reject("Bad argument");
}
public getTags(repositoryName: string, queryParams?: RequestQueryParams): Observable<Tag[]> | Promise<Tag[]> | Tag[] {
if (!repositoryName) {
return Promise.reject("Bad argument");
}
return this._getTags(repositoryName, queryParams);
let url: string = `${this._baseUrl}/${repositoryName}/tags/${tag}`;
return this.http
.get(url, HTTP_GET_OPTIONS)
.toPromise()
.then(response => response.json() as Tag)
.catch(error => Promise.reject(error));
}
public addLabelToImages(
repoName: string,
tagName: string,
labelId: number
): Observable<any> | Promise<any> | any {
if (!labelId || !tagName || !repoName) {
return Promise.reject("Invalid parameters.");
}
public deleteTag(repositoryName: string, tag: string): Observable<any> | Promise<Tag> | any {
if (!repositoryName || !tag) {
return Promise.reject("Bad argument");
}
let _addLabelToImageUrl = `${
this._baseUrl
}/${repoName}/tags/${tagName}/labels`;
return this.http
.post(_addLabelToImageUrl, { id: labelId }, HTTP_JSON_OPTIONS)
.toPromise()
.then(response => response.status)
.catch(error => Promise.reject(error));
}
let url: string = `${this._baseUrl}/${repositoryName}/tags/${tag}`;
return this.http.delete(url, HTTP_JSON_OPTIONS).toPromise()
.then(response => response)
.catch(error => Promise.reject(error));
public deleteLabelToImages(
repoName: string,
tagName: string,
labelId: number
): Observable<any> | Promise<any> | any {
if (!labelId || !tagName || !repoName) {
return Promise.reject("Invalid parameters.");
}
public getTag(repositoryName: string, tag: string, queryParams?: RequestQueryParams): Observable<Tag> | Promise<Tag> | Tag {
if (!repositoryName || !tag) {
return Promise.reject("Bad argument");
}
let url: string = `${this._baseUrl}/${repositoryName}/tags/${tag}`;
return this.http.get(url, HTTP_GET_OPTIONS).toPromise()
.then(response => response.json() as Tag)
.catch(error => Promise.reject(error));
}
public addLabelToImages(repoName: string, tagName: string, labelId: number): Observable<any> | Promise<any> | any {
if (!labelId || !tagName || !repoName) {
return Promise.reject('Invalid parameters.');
}
let _addLabelToImageUrl = `${this._baseUrl}/${repoName}/tags/${tagName}/labels`;
return this.http.post(_addLabelToImageUrl, {id: labelId}, HTTP_JSON_OPTIONS).toPromise()
.then(response => response.status)
.catch(error => Promise.reject(error));
}
public deleteLabelToImages(repoName: string, tagName: string, labelId: number): Observable<any> | Promise<any> | any {
if (!labelId || !tagName || !repoName) {
return Promise.reject('Invalid parameters.');
}
let _addLabelToImageUrl = `${this._baseUrl}/${repoName}/tags/${tagName}/labels/${labelId}`;
return this.http.delete(_addLabelToImageUrl).toPromise()
.then(response => response.status)
.catch(error => Promise.reject(error));
}
}
let _addLabelToImageUrl = `${
this._baseUrl
}/${repoName}/tags/${tagName}/labels/${labelId}`;
return this.http
.delete(_addLabelToImageUrl)
.toPromise()
.then(response => response.status)
.catch(error => Promise.reject(error));
}
}

View File

@ -29,15 +29,15 @@ export const httpStatusCode = {
"Forbidden": 403
};
export const enum ConfirmationTargets {
EMPTY,
PROJECT,
PROJECT_MEMBER,
USER,
POLICY,
EMPTY,
PROJECT,
PROJECT_MEMBER,
USER,
POLICY,
TOGGLE_CONFIRM,
TARGET,
REPOSITORY,
TAG,
TARGET,
REPOSITORY,
TAG,
CONFIG,
CONFIG_ROUTE,
CONFIG_TAB
@ -70,12 +70,20 @@ export const enum ConfirmationButtons {
};
export const LabelColor = [
{'color': '#000000', 'textColor' : 'white'}, {'color': '#61717D', 'textColor': 'white'}, {'color': '#737373', 'textColor' : 'white'}, {'color': '#80746D', 'textColor': 'white'},
{'color': '#FFFFFF', 'textColor' : 'black'}, {'color': '#A9B6BE', 'textColor': 'black'}, {'color': '#DDDDDD', 'textColor' : 'black'}, {'color': '#BBB3A9', 'textColor': 'black'},
{'color': '#0065AB', 'textColor' : 'white'}, {'color': '#343DAC', 'textColor': 'white'}, {'color': '#781DA0', 'textColor' : 'white'}, {'color': '#9B0D54', 'textColor': 'white'},
{'color': '#0095D3', 'textColor' : 'black'}, {'color': '#9DA3DB', 'textColor': 'black'}, {'color': '#BE90D6', 'textColor' : 'black'}, {'color': '#F1428A', 'textColor': 'black'},
{'color': '#1D5100', 'textColor' : 'white'}, {'color': '#006668', 'textColor': 'white'}, {'color': '#006690', 'textColor' : 'white'}, {'color': '#004A70', 'textColor': 'white'},
{'color': '#48960C', 'textColor' : 'black'}, {'color': '#00AB9A', 'textColor': 'black'}, {'color': '#00B7D6', 'textColor' : 'black'}, {'color': '#0081A7', 'textColor': 'black'},
{'color': '#C92100', 'textColor' : 'white'}, {'color': '#CD3517', 'textColor': 'white'}, {'color': '#C25400', 'textColor' : 'white'}, {'color': '#D28F00', 'textColor': 'white'},
{'color': '#F52F52', 'textColor' : 'black'}, {'color': '#FF5501', 'textColor': 'black'}, {'color': '#F57600', 'textColor' : 'black'}, {'color': '#FFDC0B', 'textColor': 'black'},
{ 'color': '#000000', 'textColor': 'white' }, { 'color': '#61717D', 'textColor': 'white' },
{ 'color': '#737373', 'textColor': 'white' }, { 'color': '#80746D', 'textColor': 'white' },
{ 'color': '#FFFFFF', 'textColor': 'black' }, { 'color': '#A9B6BE', 'textColor': 'black' },
{ 'color': '#DDDDDD', 'textColor': 'black' }, { 'color': '#BBB3A9', 'textColor': 'black' },
{ 'color': '#0065AB', 'textColor': 'white' }, { 'color': '#343DAC', 'textColor': 'white' },
{ 'color': '#781DA0', 'textColor': 'white' }, { 'color': '#9B0D54', 'textColor': 'white' },
{ 'color': '#0095D3', 'textColor': 'black' }, { 'color': '#9DA3DB', 'textColor': 'black' },
{ 'color': '#BE90D6', 'textColor': 'black' }, { 'color': '#F1428A', 'textColor': 'black' },
{ 'color': '#1D5100', 'textColor': 'white' }, { 'color': '#006668', 'textColor': 'white' },
{ 'color': '#006690', 'textColor': 'white' }, { 'color': '#004A70', 'textColor': 'white' },
{ 'color': '#48960C', 'textColor': 'black' }, { 'color': '#00AB9A', 'textColor': 'black' },
{ 'color': '#00B7D6', 'textColor': 'black' }, { 'color': '#0081A7', 'textColor': 'black' },
{ 'color': '#C92100', 'textColor': 'white' }, { 'color': '#CD3517', 'textColor': 'white' },
{ 'color': '#C25400', 'textColor': 'white' }, { 'color': '#D28F00', 'textColor': 'white' },
{ 'color': '#F52F52', 'textColor': 'black' }, { 'color': '#FF5501', 'textColor': 'black' },
{ 'color': '#F57600', 'textColor': 'black' }, { 'color': '#FFDC0B', 'textColor': 'black' },
];

View File

@ -11,8 +11,6 @@
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { NgForm } from '@angular/forms';
import { httpStatusCode, AlertType } from './shared.const';
/**
* To handle the error message body
*
@ -46,7 +44,7 @@ export const errorHandler = function (error: any): string {
return "UNKNOWN_ERROR";
}
}
}
};
export class CancelablePromise<T> {
@ -70,4 +68,4 @@ export class CancelablePromise<T> {
cancel() {
this.isCanceled = true;
}
}
}

View File

@ -8,4 +8,4 @@ export * from './tag-detail.component';
export const TAG_DIRECTIVES: Type<any>[] = [
TagComponent,
TagDetailComponent
];
];

View File

@ -148,4 +148,4 @@ describe('TagDetailComponent (inline template)', () => {
});
}));
});
});

View File

@ -70,7 +70,7 @@ export class TagDetailComponent implements OnInit {
});
}
})
.catch(error => this.errorHandler.error(error))
.catch(error => this.errorHandler.error(error));
}
}

View File

@ -17,7 +17,7 @@
<div id="filterArea">
<div class='filterLabelPiece' *ngIf="!withAdmiral" [hidden]="!openLabelFilterPiece" [style.left.px]='filterLabelPieceWidth' ><hbr-label-piece [hidden]='!filterOneLabel' [label]="filterOneLabel" [labelWidth]="130"></hbr-label-piece></div>
<div class="flex-xs-middle">
<hbr-filter [withDivider]="true" filterPlaceholder="{{'TAG.FILTER_FOR_TAGS' | translate}}" (filter)="doSearchTagNames($event)" (openFlag)="openFlagEvent($event)" [currentValue]="lastFilteredTagName"></hbr-filter>
<hbr-filter [withDivider]="true" filterPlaceholder="{{'TAG.FILTER_FOR_TAGS' | translate}}" (filterEvt)="doSearchTagNames($event)" (openFlag)="openFlagEvent($event)" [currentValue]="lastFilteredTagName"></hbr-filter>
<div class="labelFilterPanel" *ngIf="!withAdmiral" [hidden]="!openLabelFilterPanel">
<a class="filterClose" (click)="closeFilter()">&times;</a>
<label class="filterLabelHeader">{{'REPOSITORY.FILTER_BY_LABEL' | translate}}</label>

View File

@ -1,7 +1,5 @@
import { ComponentFixture, TestBed, async, fakeAsync, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { DebugElement } from '@angular/core';
import { Router } from '@angular/router';
import { SharedModule } from '../shared/shared.module';
import { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation-dialog.component';
@ -12,9 +10,8 @@ import {Label, Tag} from '../service/interface';
import { SERVICE_CONFIG, IServiceConfig } from '../service.config';
import { TagService, TagDefaultService, ScanningResultService, ScanningResultDefaultService } from '../service/index';
import { VULNERABILITY_DIRECTIVES } from '../vulnerability-scanning/index';
import { FILTER_DIRECTIVES } from '../filter/index'
import { FILTER_DIRECTIVES } from '../filter/index';
import { Observable, Subscription } from 'rxjs/Rx';
import { ChannelService } from '../channel/index';
import { JobLogViewerComponent } from '../job-log-viewer/index';
@ -163,4 +160,4 @@ describe('TagComponent (inline template)', () => {
});
}));
});
});

View File

@ -18,9 +18,8 @@ import {
Input,
Output,
EventEmitter,
ChangeDetectionStrategy,
ChangeDetectorRef,
ElementRef, AfterContentInit, AfterViewInit
ElementRef, AfterViewInit
} from "@angular/core";
import { TagService, VulnerabilitySeverity, RequestQueryParams } from "../service/index";
@ -193,7 +192,7 @@ export class TagComponent implements OnInit, AfterViewInit {
}else {
data.show = false;
}
})
});
setTimeout(() => {
setInterval(() => this.ref.markForCheck(), 200);
}, 1000);
@ -303,7 +302,7 @@ export class TagComponent implements OnInit, AfterViewInit {
this.imageStickLabels.forEach(data => {
data.iconsShow = false;
data.show = true;
})
});
if (tag[0].labels.length) {
tag[0].labels.forEach((labelInfo: Label) => {
let findedLabel = this.imageStickLabels.find(data => labelInfo.id === data['label'].id);
@ -388,7 +387,6 @@ export class TagComponent implements OnInit, AfterViewInit {
}
filterLabel(labelInfo: LabelState): void {
let labelName = labelInfo.label.name;
let labelId = labelInfo.label.id;
// insert the unselected label to groups with the same icons
let preLabelInfo = this.imageFilterLabels.find(data => data.label.id === this.filterOneLabel.id);
@ -613,7 +611,8 @@ export class TagComponent implements OnInit, AfterViewInit {
if (signature) {
Observable.forkJoin(this.translateService.get("BATCH.DELETED_FAILURE"),
this.translateService.get("REPOSITORY.DELETION_SUMMARY_TAG_DENIED")).subscribe(res => {
let wrongInfo: string = res[1] + "notary -s https://" + this.registryUrl + ":4443 -d ~/.docker/trust remove -p " + this.registryUrl + "/" + this.repoName + " " + name;
let wrongInfo: string = res[1] + "notary -s https://" + this.registryUrl + ":4443 -d ~/.docker/trust remove -p " +
this.registryUrl + "/" + this.repoName + " " + name;
findedList = BathInfoChanges(findedList, res[0], false, true, wrongInfo);
});
} else {

View File

@ -1,2 +1,2 @@
export * from './ngx-window-token/index';
export * from './ngx-clipboard/index';
export * from './ngx-clipboard/index';

View File

@ -5,6 +5,7 @@ import { Directive, EventEmitter, HostListener, Input, OnDestroy, OnInit, Output
selector: '[ngxClipboard]'
})
export class ClipboardDirective implements OnInit, OnDestroy {
// tslint:disable-next-line:no-input-rename
@Input('ngxClipboard') public targetElm: HTMLInputElement;
@Input() public cbContent: string;
@ -24,7 +25,9 @@ export class ClipboardDirective implements OnInit, OnDestroy {
this.clipboardSrv.destroy();
}
@HostListener('click', ['$event.target']) private onClick(button: ElementRef) {
@HostListener('click', ['$event.target'])
// tslint:disable-next-line:no-unused-variable
private onClick(button: ElementRef) {
if (!this.clipboardSrv.isSupported) {
this.handleResult(false, undefined);
} else if (this.targetElm && this.clipboardSrv.isTargetValid(this.targetElm)) {
@ -46,4 +49,4 @@ export class ClipboardDirective implements OnInit, OnDestroy {
this.cbOnError.emit({ isSuccess: false });
}
}
}
}

View File

@ -1,110 +1,144 @@
import { Inject, InjectionToken, Injectable, Optional, Renderer, SkipSelf } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';
import {
Inject,
// tslint:disable-next-line:no-unused-variable
InjectionToken,
Injectable,
Optional,
Renderer,
SkipSelf
} from "@angular/core";
import { DOCUMENT } from "@angular/platform-browser";
import { WINDOW } from "../ngx-window-token/index";
@Injectable()
export class ClipboardService {
private tempTextArea: HTMLTextAreaElement;
constructor(
@Inject(DOCUMENT) private document: any,
@Inject(WINDOW) private window: any,
) { }
public get isSupported(): boolean {
return !!this.document.queryCommandSupported && !!this.document.queryCommandSupported('copy');
}
private tempTextArea: HTMLTextAreaElement;
constructor(
@Inject(DOCUMENT) private document: any,
@Inject(WINDOW) private window: any
) {}
public get isSupported(): boolean {
return (
!!this.document.queryCommandSupported &&
!!this.document.queryCommandSupported("copy")
);
}
public isTargetValid(element: HTMLInputElement | HTMLTextAreaElement): boolean {
if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) {
if (element.hasAttribute('disabled')) {
// tslint:disable-next-line:max-line-length
throw new Error('Invalid "target" attribute. Please use "readonly" instead of "disabled" attribute');
}
return true;
}
throw new Error('Target should be input or textarea');
public isTargetValid(
element: HTMLInputElement | HTMLTextAreaElement
): boolean {
if (
element instanceof HTMLInputElement ||
element instanceof HTMLTextAreaElement
) {
if (element.hasAttribute("disabled")) {
throw new Error(
'Invalid "target" attribute. Please use "readonly" instead of "disabled" attribute'
);
}
return true;
}
throw new Error("Target should be input or textarea");
}
/**
* copyFromInputElement
*/
public copyFromInputElement(targetElm: HTMLInputElement | HTMLTextAreaElement, renderer: Renderer): boolean {
try {
this.selectTarget(targetElm, renderer);
const re = this.copyText();
this.clearSelection(targetElm, this.window);
return re;
} catch (error) {
return false;
}
/**
* copyFromInputElement
*/
public copyFromInputElement(
targetElm: HTMLInputElement | HTMLTextAreaElement,
renderer: Renderer
): boolean {
try {
this.selectTarget(targetElm, renderer);
const re = this.copyText();
this.clearSelection(targetElm, this.window);
return re;
} catch (error) {
return false;
}
}
/**
* Creates a fake textarea element, sets its value from `text` property,
* and makes a selection on it.
*/
public copyFromContent(content: string, renderer: Renderer) {
if (!this.tempTextArea) {
this.tempTextArea = this.createTempTextArea(this.document, this.window);
this.document.body.appendChild(this.tempTextArea);
}
this.tempTextArea.value = content;
return this.copyFromInputElement(this.tempTextArea, renderer);
/**
* Creates a fake textarea element, sets its value from `text` property,
* and makes a selection on it.
*/
public copyFromContent(content: string, renderer: Renderer) {
if (!this.tempTextArea) {
this.tempTextArea = this.createTempTextArea(this.document, this.window);
this.document.body.appendChild(this.tempTextArea);
}
this.tempTextArea.value = content;
return this.copyFromInputElement(this.tempTextArea, renderer);
}
// remove temporary textarea if any
public destroy() {
if (this.tempTextArea) {
this.document.body.removeChild(this.tempTextArea);
this.tempTextArea = undefined;
}
// remove temporary textarea if any
public destroy() {
if (this.tempTextArea) {
this.document.body.removeChild(this.tempTextArea);
this.tempTextArea = undefined;
}
}
// select the target html input element
private selectTarget(inputElement: HTMLInputElement | HTMLTextAreaElement, renderer: Renderer): number | undefined {
renderer.invokeElementMethod(inputElement, 'select');
renderer.invokeElementMethod(inputElement, 'setSelectionRange', [0, inputElement.value.length]);
return inputElement.value.length;
}
// select the target html input element
private selectTarget(
inputElement: HTMLInputElement | HTMLTextAreaElement,
renderer: Renderer
): number | undefined {
renderer.invokeElementMethod(inputElement, "select");
renderer.invokeElementMethod(inputElement, "setSelectionRange", [
0,
inputElement.value.length
]);
return inputElement.value.length;
}
private copyText(): boolean {
return this.document.execCommand('copy');
}
// Removes current selection and focus from `target` element.
private clearSelection(inputElement: HTMLInputElement | HTMLTextAreaElement, window: Window) {
// tslint:disable-next-line:no-unused-expression
inputElement && inputElement.blur();
window.getSelection().removeAllRanges();
}
private copyText(): boolean {
return this.document.execCommand("copy");
}
// Removes current selection and focus from `target` element.
private clearSelection(
inputElement: HTMLInputElement | HTMLTextAreaElement,
window: Window
) {
if (inputElement) { inputElement.blur(); }
window.getSelection().removeAllRanges();
}
// create a fake textarea for copy command
private createTempTextArea(doc: Document, window: Window): HTMLTextAreaElement {
const isRTL = doc.documentElement.getAttribute('dir') === 'rtl';
let ta: HTMLTextAreaElement;
ta = doc.createElement('textarea');
// Prevent zooming on iOS
ta.style.fontSize = '12pt';
// Reset box model
ta.style.border = '0';
ta.style.padding = '0';
ta.style.margin = '0';
// Move element out of screen horizontally
ta.style.position = 'absolute';
ta.style[isRTL ? 'right' : 'left'] = '-9999px';
// Move element to the same position vertically
let yPosition = window.pageYOffset || doc.documentElement.scrollTop;
ta.style.top = yPosition + 'px';
ta.setAttribute('readonly', '');
return ta;
}
// create a fake textarea for copy command
private createTempTextArea(
doc: Document,
window: Window
): HTMLTextAreaElement {
const isRTL = doc.documentElement.getAttribute("dir") === "rtl";
let ta: HTMLTextAreaElement;
ta = doc.createElement("textarea");
// Prevent zooming on iOS
ta.style.fontSize = "12pt";
// Reset box model
ta.style.border = "0";
ta.style.padding = "0";
ta.style.margin = "0";
// Move element out of screen horizontally
ta.style.position = "absolute";
ta.style[isRTL ? "right" : "left"] = "-9999px";
// Move element to the same position vertically
let yPosition = window.pageYOffset || doc.documentElement.scrollTop;
ta.style.top = yPosition + "px";
ta.setAttribute("readonly", "");
return ta;
}
}
// this pattern is mentioned in https://github.com/angular/angular/issues/13854 in #43
export function CLIPBOARD_SERVICE_PROVIDER_FACTORY(doc: Document, win: Window, parentDispatcher: ClipboardService) {
return parentDispatcher || new ClipboardService(doc, win);
};
export function CLIPBOARD_SERVICE_PROVIDER_FACTORY(
doc: Document,
win: Window,
parentDispatcher: ClipboardService
) {
return parentDispatcher || new ClipboardService(doc, win);
}
export const CLIPBOARD_SERVICE_PROVIDER = {
provide: ClipboardService,
deps: [DOCUMENT, WINDOW, [new Optional(), new SkipSelf(), ClipboardService]],
useFactory: CLIPBOARD_SERVICE_PROVIDER_FACTORY
};
provide: ClipboardService,
deps: [DOCUMENT, WINDOW, [new Optional(), new SkipSelf(), ClipboardService]],
useFactory: CLIPBOARD_SERVICE_PROVIDER_FACTORY
};

Some files were not shown because too many files have changed in this diff Show More