001    /*
002     * Copyright (c) 1998-2014 ChemAxon Ltd. All Rights Reserved.
003     *
004     * This software is the confidential and proprietary information of
005     * ChemAxon. You shall not disclose such Confidential Information
006     * and shall use it only in accordance with the terms of the agreements
007     * you entered into with ChemAxon.
008     *
009     */
010    package com.chemaxon.overlap.io;
011    
012    import chemaxon.formats.MolExporter;
013    import chemaxon.struc.Molecule;
014    import com.google.common.annotations.Beta;
015    import com.google.common.base.Preconditions;
016    import java.lang.reflect.Array;
017    import java.util.Arrays;
018    
019    /**
020     * IO related utilities.
021     *
022     * @author Gabor Imre
023     */
024    @Beta
025    public final class Util {
026    
027        /**
028         * No constructor exposed.
029         */
030        private Util() {}
031    
032    
033        /**
034         * Convert molecule to human readable string.
035         *
036         * @param mol   Molecule
037         * @return      Human readable String (smiles or cxsmiles or cxsmarts)
038         */
039        public static String molToHumanReadable(Molecule mol) {
040            final String [] formats = new String [] {"smiles", "cxsmiles", "cxsmarts"};
041            Exception lastE = null;
042            for (String format : formats) {
043                try {
044                    final String s = MolExporter.exportToFormat(mol, format);
045                    return format + ": " + s;
046                } catch (Exception e) {
047                    lastE = e;
048                }
049            }
050            if (lastE == null) {
051                throw new IllegalStateException();
052            }
053            throw new IllegalArgumentException("None of the following formats supported: " + Arrays.toString(formats)
054                    + "Error when trying " + formats[formats.length - 1] + ": " + lastE.getMessage(), lastE);
055        }
056    
057        /**
058         * Array aware toString.
059         *
060         * @param o An Object
061         * @return If o is an array then list of its components or {@link Object#toString()} otherwise
062         */
063        public static String arrayAwareToString(Object o) {
064            Preconditions.checkNotNull(o);
065            if (!o.getClass().isArray()) {
066                return o.toString();
067            }
068            final StringBuilder ret = new StringBuilder();
069            ret.append('{');
070            final int len = Array.getLength(o);
071            for (int i = 0; i < len; i++) {
072                if (i != 0) {
073                    ret.append(", ");
074                }
075                ret.append(arrayAwareToString(Array.get(o, i)));
076            }
077            ret.append('}');
078            return ret.toString();
079        }
080    
081    }