<commit_before>/*
 * Copyright 2008-2012 Microarray Informatics Team, EMBL-European Bioinformatics Institute
 *
 * 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.
 *
 *
 * For further details of the Gene Expression Atlas project, including source code,
 * downloads and documentation, please see:
 *
 * http://gxa.github.com/gxa
 */

package uk.ac.ebi.gxa.annotator.annotationsrc;

import com.google.common.base.Function;
import com.google.common.base.Strings;
import com.google.common.collect.Collections2;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import uk.ac.ebi.gxa.annotator.annotationsrc.arraydesign.ArrayDesignService;
import uk.ac.ebi.gxa.annotator.dao.AnnotationSourceDAO;
import uk.ac.ebi.gxa.annotator.model.AnnotationSource;
import uk.ac.ebi.gxa.annotator.model.ExternalArrayDesign;
import uk.ac.ebi.gxa.annotator.model.ExternalBioEntityProperty;
import uk.ac.ebi.gxa.annotator.validation.ValidationReportBuilder;
import uk.ac.ebi.gxa.dao.OrganismDAO;
import uk.ac.ebi.gxa.dao.SoftwareDAO;
import uk.ac.ebi.gxa.dao.bioentity.BioEntityPropertyDAO;
import uk.ac.ebi.gxa.dao.bioentity.BioEntityTypeDAO;
import uk.ac.ebi.gxa.dao.exceptions.RecordNotFoundException;
import uk.ac.ebi.gxa.exceptions.LogUtil;
import uk.ac.ebi.microarray.atlas.model.ArrayDesign;
import uk.ac.ebi.microarray.atlas.model.bioentity.BioEntityProperty;
import uk.ac.ebi.microarray.atlas.model.bioentity.BioEntityType;

import java.io.*;
import java.net.URI;
import java.util.*;

import static com.google.common.collect.Sets.difference;
import static com.google.common.io.Closeables.closeQuietly;

/**
 * User: nsklyar
 * Date: 10/11/2011
 */
abstract class AnnotationSourceConverter<T extends AnnotationSource> {

    protected static final String SOFTWARE_NAME_PROPNAME = "software.name";
    protected static final String SOFTWARE_VERSION_PROPNAME = "software.version";
    protected static final String TYPES_PROPNAME = "types";
    protected static final String URL_PROPNAME = "url";

    protected static final List<String> PROPNAMES = Arrays.asList(SOFTWARE_NAME_PROPNAME,
            SOFTWARE_VERSION_PROPNAME,
            TYPES_PROPNAME,
            URL_PROPNAME);

    private static final String EXTPROPERTY_PROPNAME = "property";
    private static final String ARRAYDESIGN_PROPNAME = "arrayDesign";

    @Autowired
    protected AnnotationSourceDAO annSrcDAO;
    @Autowired
    protected OrganismDAO organismDAO;
    @Autowired
    protected SoftwareDAO softwareDAO;
    @Autowired
    protected BioEntityTypeDAO typeDAO;
    @Autowired
    protected BioEntityPropertyDAO propertyDAO;
    @Autowired
    protected ArrayDesignService arrayDesignService;

    public String convertToString(T annSrc) {
        if (annSrc == null) {
            return "";
        }

        Writer writer = new StringWriter();
        try {
            generateString(annSrc, writer);
            return writer.toString();
        } catch (ConfigurationException e) {
            throw LogUtil.createUnexpected("Cannot write Annotation Source " + annSrc.getAnnotationSrcId(), e);
        } finally {
            closeQuietly(writer);
        }
    }

    public T editOrCreateAnnotationSource(T annSrc, String text, ValidationReportBuilder reportBuilder) throws AnnotationLoaderException {
        Reader input = new StringReader(text);
        Properties properties = new Properties();
        try {
            properties.load(input);
            if (!isValidInputText(annSrc, properties, reportBuilder)) return null;

            if (annSrc == null) {
                annSrc = initAnnotationSource(properties);
                if (annSrcExists(annSrc)) {
                    reportBuilder.addMessage("Annotation source  " + annSrc.getName() + " already exists. If you need to " +
                            "change it use Edit button");
                    return null;
                }
            }
            updateAnnotationSource(properties, annSrc);
            return annSrc;
        } catch (IOException e) {
            throw new AnnotationLoaderException("Cannot read annotation properties", e);
        } finally {
            closeQuietly(input);
        }
    }

    protected boolean isValidInputText(T annSrc, Properties properties, ValidationReportBuilder reportBuilder) throws AnnotationLoaderException {

        validateRequiredFields(properties, reportBuilder);
        validateURL(properties, reportBuilder);
        validateTypes(properties, reportBuilder);
        if (annSrc != null) {
            validateStableFields(annSrc, properties, reportBuilder);
        }

        return reportBuilder.isEmpty();
    }

    protected abstract void validateStableFields(T annSrc, Properties properties, ValidationReportBuilder reportBuilder);

    private void validateRequiredFields(Properties properties, ValidationReportBuilder reportBuilder) {
        List<String> propertyNames = new ArrayList<String>(getRequiredProperties());

        for (String propertyName : propertyNames) {
            final String property = getProperty(propertyName, properties);
            if (Strings.isNullOrEmpty(property)) {
                reportBuilder.addMessage("Required property " + propertyName + " is missing");
            }
        }
    }

    private void validateTypes(Properties properties, ValidationReportBuilder reportBuilder) {
        String typesString = getProperty(TYPES_PROPNAME, properties);
        StringTokenizer tokenizer = new StringTokenizer(typesString, ",");
        String currentType = "";
        boolean valid = true;
        while (tokenizer.hasMoreElements()) {
            try {
                currentType = tokenizer.nextToken().trim();
                typeDAO.getByName(currentType);
            } catch (RecordNotFoundException e) {<commit_msg>fixed NPE when saving empty ann src<commit_after>/*
 * Copyright 2008-2012 Microarray Informatics Team, EMBL-European Bioinformatics Institute
 *
 * 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.
 *
 *
 * For further details of the Gene Expression Atlas project, including source code,
 * downloads and documentation, please see:
 *
 * http://gxa.github.com/gxa
 */

package uk.ac.ebi.gxa.annotator.annotationsrc;

import com.google.common.base.Function;
import com.google.common.base.Strings;
import com.google.common.collect.Collections2;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import uk.ac.ebi.gxa.annotator.annotationsrc.arraydesign.ArrayDesignService;
import uk.ac.ebi.gxa.annotator.dao.AnnotationSourceDAO;
import uk.ac.ebi.gxa.annotator.model.AnnotationSource;
import uk.ac.ebi.gxa.annotator.model.ExternalArrayDesign;
import uk.ac.ebi.gxa.annotator.model.ExternalBioEntityProperty;
import uk.ac.ebi.gxa.annotator.validation.ValidationReportBuilder;
import uk.ac.ebi.gxa.dao.OrganismDAO;
import uk.ac.ebi.gxa.dao.SoftwareDAO;
import uk.ac.ebi.gxa.dao.bioentity.BioEntityPropertyDAO;
import uk.ac.ebi.gxa.dao.bioentity.BioEntityTypeDAO;
import uk.ac.ebi.gxa.dao.exceptions.RecordNotFoundException;
import uk.ac.ebi.gxa.exceptions.LogUtil;
import uk.ac.ebi.microarray.atlas.model.ArrayDesign;
import uk.ac.ebi.microarray.atlas.model.bioentity.BioEntityProperty;
import uk.ac.ebi.microarray.atlas.model.bioentity.BioEntityType;

import java.io.*;
import java.net.URI;
import java.util.*;

import static com.google.common.collect.Sets.difference;
import static com.google.common.io.Closeables.closeQuietly;

/**
 * User: nsklyar
 * Date: 10/11/2011
 */
abstract class AnnotationSourceConverter<T extends AnnotationSource> {

    protected static final String SOFTWARE_NAME_PROPNAME = "software.name";
    protected static final String SOFTWARE_VERSION_PROPNAME = "software.version";
    protected static final String TYPES_PROPNAME = "types";
    protected static final String URL_PROPNAME = "url";

    protected static final List<String> PROPNAMES = Arrays.asList(SOFTWARE_NAME_PROPNAME,
            SOFTWARE_VERSION_PROPNAME,
            TYPES_PROPNAME,
            URL_PROPNAME);

    private static final String EXTPROPERTY_PROPNAME = "property";
    private static final String ARRAYDESIGN_PROPNAME = "arrayDesign";

    @Autowired
    protected AnnotationSourceDAO annSrcDAO;
    @Autowired
    protected OrganismDAO organismDAO;
    @Autowired
    protected SoftwareDAO softwareDAO;
    @Autowired
    protected BioEntityTypeDAO typeDAO;
    @Autowired
    protected BioEntityPropertyDAO propertyDAO;
    @Autowired
    protected ArrayDesignService arrayDesignService;

    public String convertToString(T annSrc) {
        if (annSrc == null) {
            return "";
        }

        Writer writer = new StringWriter();
        try {
            generateString(annSrc, writer);
            return writer.toString();
        } catch (ConfigurationException e) {
            throw LogUtil.createUnexpected("Cannot write Annotation Source " + annSrc.getAnnotationSrcId(), e);
        } finally {
            closeQuietly(writer);
        }
    }

    public T editOrCreateAnnotationSource(T annSrc, String text, ValidationReportBuilder reportBuilder) throws AnnotationLoaderException {
        Reader input = new StringReader(text);
        Properties properties = new Properties();
        try {
            properties.load(input);
            if (!isValidInputText(annSrc, properties, reportBuilder)) return null;

            if (annSrc == null) {
                annSrc = initAnnotationSource(properties);
                if (annSrcExists(annSrc)) {
                    reportBuilder.addMessage("Annotation source  " + annSrc.getName() + " already exists. If you need to " +
                            "change it use Edit button");
                    return null;
                }
            }
            updateAnnotationSource(properties, annSrc);
            return annSrc;
        } catch (IOException e) {
            throw new AnnotationLoaderException("Cannot read annotation properties", e);
        } finally {
            closeQuietly(input);
        }
    }

    protected boolean isValidInputText(T annSrc, Properties properties, ValidationReportBuilder reportBuilder) throws AnnotationLoaderException {

        validateRequiredFields(properties, reportBuilder);
        validateURL(properties, reportBuilder);
        validateTypes(properties, reportBuilder);
        if (annSrc != null) {
            validateStableFields(annSrc, properties, reportBuilder);
        }

        return reportBuilder.isEmpty();
    }

    protected abstract void validateStableFields(T annSrc, Properties properties, ValidationReportBuilder reportBuilder);

    private void validateRequiredFields(Properties properties, ValidationReportBuilder reportBuilder) {
        List<String> propertyNames = new ArrayList<String>(getRequiredProperties());

        for (String propertyName : propertyNames) {
            final String property = getProperty(propertyName, properties);
            if (Strings.isNullOrEmpty(property)) {
                reportBuilder.addMessage("Required property " + propertyName + " is missing");
            }
        }
    }

    private void validateTypes(Properties properties, ValidationReportBuilder reportBuilder) {
        String typesString = getProperty(TYPES_PROPNAME, properties);
        if (Strings.isNullOrEmpty(typesString)) {
            reportBuilder.addMessage("Required property \"types\" is missing");
            return;
        }
        StringTokenizer tokenizer = new StringTokenizer(typesString, ",");
        String currentType = "";
        boolean valid = true;
        while (tokenizer.hasMoreElements()) {
            try {
                currentType = tokenizer.nextToken().trim();
                typeDAO.getByName(currentType);
            } catch (RecordNotFoundException e) {
{'fraction_non_alphanumeric': 0.08541353383458647, 'fraction_numerical': 0.003157894736842105, 'mean_word_length': 3.2975767366720516, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4945081', 'n_tokens_mistral': 3534, 'n_tokens_neox': 3457, 'n_words': 866}