<commit_before>/*
 * Copyright 2011 Red Hat inc. and third party contributors as noted 
 * by the author tags.
 * 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.redhat.ceylon.cmr.impl;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

import javax.xml.bind.DatatypeConverter;

import com.redhat.ceylon.common.log.Logger;
import com.redhat.ceylon.cmr.api.ModuleDependencyInfo;
import com.redhat.ceylon.cmr.api.ModuleQuery;
import com.redhat.ceylon.cmr.api.ModuleQuery.Type;
import com.redhat.ceylon.cmr.api.ModuleSearchResult;
import com.redhat.ceylon.cmr.api.ModuleVersionArtifact;
import com.redhat.ceylon.cmr.api.ModuleVersionDetails;
import com.redhat.ceylon.cmr.api.ModuleVersionQuery;
import com.redhat.ceylon.cmr.api.ModuleVersionResult;
import com.redhat.ceylon.cmr.spi.ContentHandle;
import com.redhat.ceylon.cmr.spi.Node;
import com.redhat.ceylon.cmr.spi.OpenNode;
import com.redhat.ceylon.cmr.util.WS;
import com.redhat.ceylon.cmr.util.WS.Link;
import com.redhat.ceylon.cmr.util.WS.Parser;
import com.redhat.ceylon.cmr.util.WS.XMLHandler;

/**
 * URL based content store.
 *
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 */
public abstract class URLContentStore extends AbstractRemoteContentStore {

    public final static String HERD_COMPLETE_MODULES_REL = "http://modules.ceylon-lang.org/rel/complete-modules";
    public final static String HERD_COMPLETE_VERSIONS_REL = "http://modules.ceylon-lang.org/rel/complete-versions";
    public final static String HERD_SEARCH_MODULES_REL = "http://modules.ceylon-lang.org/rel/search-modules";

    private static final String HERD_ORIGIN = "The Herd";
    
    protected final String root;
    protected String username;
    protected String password;
    private Boolean _isHerd = null;
    private Boolean _isLocalMachine = null;
    private String herdCompleteModulesURL;
    private String herdCompleteVersionsURL;
    private String herdSearchModulesURL;
    private String herdRequestedApi;
    private int herdVersion = 1; // assume 1 until we find otherwise

    protected URLContentStore(String root, Logger log, boolean offline) {
        this(root, log, offline, null);
    }
    protected URLContentStore(String root, Logger log, boolean offline, String apiVersion) {
        super(log, offline);
        if (root == null)
            throw new IllegalArgumentException("Null root url");
        this.root = root;
        this.herdRequestedApi = apiVersion != null ? apiVersion : "4";
        if(apiVersion != null
                && !apiVersion.equals("1")
                && !apiVersion.equals("2")
                && !apiVersion.equals("3")
                && !apiVersion.equals("4"))
            throw new IllegalArgumentException("Only Herd APIs 1 to 4 are supported: requested API "+apiVersion);
    }

    @Override
    public boolean isHerd(){
        if(_isHerd == null){
            synchronized(this){
                if(_isHerd == null){
                    _isHerd = testHerd();
                }
            }
        }
        return _isHerd;
    }

    private boolean testHerd() {
        if (!connectionAllowed()) {
            // We should never come here, but just in case
            return false;
        }
        try{
            // we support both API 1 to 3
            URL rootURL = getURL("?version="+herdRequestedApi);
            HttpURLConnection con = (HttpURLConnection) rootURL.openConnection();
            try{
                con.setRequestMethod("OPTIONS");
                if(con.getResponseCode() != HttpURLConnection.HTTP_OK)
                    return false;
                String herdVersion = con.getHeaderField("X-Herd-Version");
                log.debug("Herd version: "+herdVersion);
                try{
                    this.herdVersion = Integer.parseInt(herdVersion);
                }catch(NumberFormatException x){
                    log.debug("Non-integer Herd version: "+herdVersion);
                }
                boolean ret = herdVersion != null && !herdVersion.isEmpty();
                if(ret){
                    collectHerdLinks(con);
                }
                return ret;
            }finally{
                con.disconnect();
            }
        }catch(Exception x){
            log.debug("Failed to determine if remote host is a Herd repo: "+x.getMessage());
            return false;
        }
    }

    private void collectHerdLinks(HttpURLConnection con) {
        // collect the links
        try{
            List<Link> links = WS.collectLinks(con);
            herdCompleteModulesURL = WS.getLink(links, HERD_COMPLETE_MODULES_REL);
            herdCompleteVersionsURL = WS.getLink(links, HERD_COMPLETE_VERSIONS_REL);
            herdSearchModulesURL = WS.getLink(links, HERD_SEARCH_MODULES_REL);
            log.debug("Got complete-modules link: " + herdCompleteModulesURL);
            log.debug("Got complete-versions link: " + herdCompleteVersionsURL);
            log.debug("Got search-modules link: " + herdSearchModulesURL);
        }catch(Exception x){
            log.debug("Failed to read links from Herd repo: "+x.getMessage());
        }
    }

    
    protected boolean connectionAllowed() {
        return !offline || rootIsLocalMachine();
    }
    
    private boolean rootIsLocalMachine() {
        if (_isLocalMachine == null) {
            URL url = getURL("");
            _isLocalMachine = hostIsLocalMachine(url.getHost());
        }
        return _isLocalMachine;
    }
    
    private boolean hostIsLocalMachine(String host) {
//        return "localhost".equals(host) || "127.0.0.1".equals(host) || "::1".equals(host);
        Enumeration<NetworkInterface> interfaces;
        try {
            interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface nic = interfaces.nextElement();
                Enumeration<InetAddress> addresses = nic.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();
                    if (host.equalsIgnoreCase(address.getHostName()) || host.equalsIgnoreCase(address.getHostAddress())) {
                        return true;
                    }
                }
            }
        } catch (SocketException e) {
            // Ignore error
        }
        return false;
    }
    
    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public OpenNode find(Node parent, String child) {
        final String path = getFullPath(parent, child);
        // only test the URL if we are looking at the child level
        // otherwise, pretend that folders exist, we'll find out soon
        // enough
        if (hasContent(child) && !urlExists(path)) {
            return null;
        }
        final RemoteNode node = createNode(child);
        ContentHandle handle;
        if (hasContent(child))
            handle = createContentHandle(parent, child, path, node);
        else
            handle = DefaultNode.HANDLE_MARKER;
        node.setHandle(handle);
        return node;
    }

    protected abstract ContentHandle createContentHandle(Node parent, String child, String path, Node node);

    protected String getUrlAsString(Node node) {
        return getUrlAsString(NodeUtils.getFullPath(node, SEPARATOR));
    }

    protected String getUrlAsString(String path) {
        return root + path;<commit_msg>Trying to retrieve `module-doc` from Herd would result in a web page being stored in the repository. This is a quick hack to fix that.<commit_after>/*
 * Copyright 2011 Red Hat inc. and third party contributors as noted 
 * by the author tags.
 * 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.redhat.ceylon.cmr.impl;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

import javax.xml.bind.DatatypeConverter;

import com.redhat.ceylon.common.log.Logger;
import com.redhat.ceylon.cmr.api.ArtifactContext;
import com.redhat.ceylon.cmr.api.ModuleDependencyInfo;
import com.redhat.ceylon.cmr.api.ModuleQuery;
import com.redhat.ceylon.cmr.api.ModuleQuery.Type;
import com.redhat.ceylon.cmr.api.ModuleSearchResult;
import com.redhat.ceylon.cmr.api.ModuleVersionArtifact;
import com.redhat.ceylon.cmr.api.ModuleVersionDetails;
import com.redhat.ceylon.cmr.api.ModuleVersionQuery;
import com.redhat.ceylon.cmr.api.ModuleVersionResult;
import com.redhat.ceylon.cmr.spi.ContentHandle;
import com.redhat.ceylon.cmr.spi.Node;
import com.redhat.ceylon.cmr.spi.OpenNode;
import com.redhat.ceylon.cmr.util.WS;
import com.redhat.ceylon.cmr.util.WS.Link;
import com.redhat.ceylon.cmr.util.WS.Parser;
import com.redhat.ceylon.cmr.util.WS.XMLHandler;

/**
 * URL based content store.
 *
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 */
public abstract class URLContentStore extends AbstractRemoteContentStore {

    public final static String HERD_COMPLETE_MODULES_REL = "http://modules.ceylon-lang.org/rel/complete-modules";
    public final static String HERD_COMPLETE_VERSIONS_REL = "http://modules.ceylon-lang.org/rel/complete-versions";
    public final static String HERD_SEARCH_MODULES_REL = "http://modules.ceylon-lang.org/rel/search-modules";

    private static final String HERD_ORIGIN = "The Herd";
    
    protected final String root;
    protected String username;
    protected String password;
    private Boolean _isHerd = null;
    private Boolean _isLocalMachine = null;
    private String herdCompleteModulesURL;
    private String herdCompleteVersionsURL;
    private String herdSearchModulesURL;
    private String herdRequestedApi;
    private int herdVersion = 1; // assume 1 until we find otherwise

    protected URLContentStore(String root, Logger log, boolean offline) {
        this(root, log, offline, null);
    }
    protected URLContentStore(String root, Logger log, boolean offline, String apiVersion) {
        super(log, offline);
        if (root == null)
            throw new IllegalArgumentException("Null root url");
        this.root = root;
        this.herdRequestedApi = apiVersion != null ? apiVersion : "4";
        if(apiVersion != null
                && !apiVersion.equals("1")
                && !apiVersion.equals("2")
                && !apiVersion.equals("3")
                && !apiVersion.equals("4"))
            throw new IllegalArgumentException("Only Herd APIs 1 to 4 are supported: requested API "+apiVersion);
    }

    @Override
    public boolean isHerd(){
        if(_isHerd == null){
            synchronized(this){
                if(_isHerd == null){
                    _isHerd = testHerd();
                }
            }
        }
        return _isHerd;
    }

    private boolean testHerd() {
        if (!connectionAllowed()) {
            // We should never come here, but just in case
            return false;
        }
        try{
            // we support both API 1 to 3
            URL rootURL = getURL("?version="+herdRequestedApi);
            HttpURLConnection con = (HttpURLConnection) rootURL.openConnection();
            try{
                con.setRequestMethod("OPTIONS");
                if(con.getResponseCode() != HttpURLConnection.HTTP_OK)
                    return false;
                String herdVersion = con.getHeaderField("X-Herd-Version");
                log.debug("Herd version: "+herdVersion);
                try{
                    this.herdVersion = Integer.parseInt(herdVersion);
                }catch(NumberFormatException x){
                    log.debug("Non-integer Herd version: "+herdVersion);
                }
                boolean ret = herdVersion != null && !herdVersion.isEmpty();
                if(ret){
                    collectHerdLinks(con);
                }
                return ret;
            }finally{
                con.disconnect();
            }
        }catch(Exception x){
            log.debug("Failed to determine if remote host is a Herd repo: "+x.getMessage());
            return false;
        }
    }

    private void collectHerdLinks(HttpURLConnection con) {
        // collect the links
        try{
            List<Link> links = WS.collectLinks(con);
            herdCompleteModulesURL = WS.getLink(links, HERD_COMPLETE_MODULES_REL);
            herdCompleteVersionsURL = WS.getLink(links, HERD_COMPLETE_VERSIONS_REL);
            herdSearchModulesURL = WS.getLink(links, HERD_SEARCH_MODULES_REL);
            log.debug("Got complete-modules link: " + herdCompleteModulesURL);
            log.debug("Got complete-versions link: " + herdCompleteVersionsURL);
            log.debug("Got search-modules link: " + herdSearchModulesURL);
        }catch(Exception x){
            log.debug("Failed to read links from Herd repo: "+x.getMessage());
        }
    }

    
    protected boolean connectionAllowed() {
        return !offline || rootIsLocalMachine();
    }
    
    private boolean rootIsLocalMachine() {
        if (_isLocalMachine == null) {
            URL url = getURL("");
            _isLocalMachine = hostIsLocalMachine(url.getHost());
        }
        return _isLocalMachine;
    }
    
    private boolean hostIsLocalMachine(String host) {
//        return "localhost".equals(host) || "127.0.0.1".equals(host) || "::1".equals(host);
        Enumeration<NetworkInterface> interfaces;
        try {
            interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface nic = interfaces.nextElement();
                Enumeration<InetAddress> addresses = nic.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();
                    if (host.equalsIgnoreCase(address.getHostName()) || host.equalsIgnoreCase(address.getHostAddress())) {
                        return true;
                    }
                }
            }
        } catch (SocketException e) {
            // Ignore error
        }
        return false;
    }
    
    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public OpenNode find(Node parent, String child) {
        final String path = getFullPath(parent, child);
        // only test the URL if we are looking at the child level
        // otherwise, pretend that folders exist, we'll find out soon
        // enough
        if (hasContent(child) && !urlExists(path)) {
            return null;
        }
        // FIXME Crappy fix to make sure we don't try to return the "module-doc" folder
        // at least until we properly support auto-zipping and unzipping of folders
        // to and from the Herd
        if (ArtifactContext.DOCS.equals(child) && isHerd()) {
            return null;
        }
        final RemoteNode node = createNode(child);
        ContentHandle handle;
        if (hasContent(child))
            handle = createContentHandle(parent, child, path, node);
        else
            handle = DefaultNode.HANDLE_MARKER;
        node.setHandle(handle);
        return node;
    }

    protected abstract ContentHandle createContentHandle(Node parent, String child, String path, Node node);

    protected String getUrlAsString(Node node) {
        return getUrlAsString(NodeUtils.getFullPath(node, SEPARATOR));
    }

    protected String getUrlAsString(String path) {
        return root + path;
{'fraction_non_alphanumeric': 0.09676480856511113, 'fraction_numerical': 0.0030257186081694403, 'mean_word_length': 2.4429086538461537, 'pattern_counts': {'":': 2, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 2}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4940115', 'n_tokens_mistral': 4771, 'n_tokens_neox': 4630, 'n_words': 1204}