Skip to content
URIUtils.java 2.15 KiB
Newer Older
/*
 * This file is part of vospace-rest
 * Copyright (C) 2021 Istituto Nazionale di Astrofisica
 * SPDX-License-Identifier: GPL-3.0-or-later
 */
package it.inaf.oats.vospace;

import it.inaf.oats.vospace.exception.InvalidArgumentException;
import it.inaf.oats.vospace.exception.InvalidURIException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.regex.Pattern;

public class URIUtils {

    // It's different from the one in NodeUtils!
    // Slashes are treated separately
    private static final Pattern FORBIDDEN_CHARS = Pattern.compile("[\\x00\\x08\\x0B\\x0C\\x0E-\\x1F" + Pattern.quote("<>?\":\\|'`*") + "]");

    // This method validates the URI too
    public static String returnVosPathFromNodeURI(String nodeURI, String authority) {
        
        String scheme = "vos";
        String resultPath = null;
        
        try{
        URI uri = new URI(nodeURI);
        
        // Check scheme
        if(!uri.isAbsolute() || 
                uri.isOpaque() || 
                !uri.getRawSchemeSpecificPart().startsWith("//") ||
                !uri.getScheme().equalsIgnoreCase(scheme))
            throw new InvalidURIException(nodeURI);
        
        // Check authority
        if(!uri.getAuthority().replace("~", "!").equals(authority))
            throw new InvalidURIException(nodeURI);
        
        // Check path
        String rawPath = uri.getRawPath();
        
        // Check if raw Path is null or contains percent encoded slashes or multiple
        // separators
        if(rawPath == null ||                 
                rawPath.contains("//") ||
                rawPath.contains("%2F") || 
                rawPath.contains("%2f"))
            throw new InvalidURIException(nodeURI);
        
        resultPath = uri.getPath();
        
        if(resultPath.isBlank() || 
                FORBIDDEN_CHARS.matcher(resultPath).find() ||
                (!resultPath.equals("/") && resultPath.endsWith("/")))
            throw new InvalidURIException(nodeURI);        
        
        } catch(URISyntaxException e) {
            throw new InvalidURIException(nodeURI);
        }
        
        return resultPath;      

    }

}