/*
 * Copyright 2017 Richard Thurston.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * 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.
 */
package com.northernwall.hadrian.handlers.vip;

import com.northernwall.hadrian.config.Config;
import com.northernwall.hadrian.config.ConfigHelper;
import com.northernwall.hadrian.handlers.routing.Http400BadRequestException;
import com.northernwall.hadrian.handlers.vip.dao.PostVipData;

/**
 *
 * @author Richard
 */
public class VipValidator {
    private final ConfigHelper configHelper;

    public VipValidator(ConfigHelper configHelper) {
        this.configHelper = configHelper;
    }
    
    public String checkVipName(PostVipData data) throws Http400BadRequestException {
        String dns = data.dns;
        if (dns == null || dns.isEmpty()) {
            throw new Http400BadRequestException("VIP name is missing");
        }
        dns = dns.trim();
        if (dns == null || dns.isEmpty()) {
            throw new Http400BadRequestException("VIP name is missing");
        }
        
        if (!dns.matches("^[a-zA-Z0-9/-]+$")) {
            throw new Http400BadRequestException("VIP name contains an illegal character");
        }
        
        Config config = configHelper.getConfig();
        for (String dataCenter : config.dataCenters) {
            if (dns.endsWith("-" + dataCenter)) {
                throw new Http400BadRequestException("VIP name can not end in -" + dataCenter);
            }
        }
        
        if (dns.length() < 2) {
            throw new Http400BadRequestException("VIP name is to short, minimum is 2");
        }
        
        if (dns.length() > 45) {
            throw new Http400BadRequestException("VIP name is to long, maximum is 45");
        }
        return dns;
    }

}

@@ -964,24 +964,26 @@
 alidator %7B%0D%0A
+%0D%0A
     private 
@@ -1122,22 +1122,18 @@
 %0A    %7D%0D%0A
-    
 %0D%0A
+
     publ
@@ -1525,34 +1525,26 @@
 %0A        %7D%0D%0A
-        
 %0D%0A
+
         if (
@@ -1680,32 +1680,24 @@
 %0A        %7D%0D%0A
-        
 %0D%0A        Co
@@ -1694,16 +1694,18 @@
         
+//
 Config c
@@ -1747,16 +1747,18 @@
         
+//
 for (Str
@@ -1801,24 +1801,26 @@
  %7B%0D%0A        
+//
     if (dns.
@@ -1854,24 +1854,26 @@
  %7B%0D%0A        
+//
         thro
@@ -1953,24 +1953,26 @@
 );%0D%0A        
+//
     %7D%0D%0A     
@@ -1966,32 +1966,34 @@
 /    %7D%0D%0A        
+//
 %7D%0D%0A        %0D%0A   
@@ -2122,24 +2122,16 @@
      %7D%0D%0A
-        
 %0D%0A      

Remove the ends with DC check