Example usage for java.lang String substring

List of usage examples for java.lang String substring

Introduction

In this page you can find the example usage for java.lang String substring.

Prototype

public String substring(int beginIndex) 

Source Link

Document

Returns a string that is a substring of this string.

Usage

From source file:mlbench.pagerank.PagerankNaive.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) throws IOException, InterruptedException {
    try {//from w  w w  .j  ava  2s . c o m
        parseArgs(args);
        HashMap<String, String> conf = new HashMap<String, String>();
        initConf(conf);
        MPI_D.Init(args, MPI_D.Mode.Common, conf);

        JobConf jobConf = new JobConf(confPath);
        if (MPI_D.COMM_BIPARTITE_O != null) {
            // O communicator
            int rank = MPI_D.Comm_rank(MPI_D.COMM_BIPARTITE_O);
            int size = MPI_D.Comm_size(MPI_D.COMM_BIPARTITE_O);
            if (rank == 0) {
                LOG.info(PagerankNaive.class.getSimpleName() + " O start.");
            }
            FileSplit[] inputs1 = DataMPIUtil.HDFSDataLocalLocator.getTaskInputs(MPI_D.COMM_BIPARTITE_O,
                    jobConf, edgeDir, rank);
            FileSplit[] inputs2 = DataMPIUtil.HDFSDataLocalLocator.getTaskInputs(MPI_D.COMM_BIPARTITE_O,
                    jobConf, vecDir, rank);
            FileSplit[] inputs = (FileSplit[]) ArrayUtils.addAll(inputs2, inputs1);
            for (int i = 0; i < inputs.length; i++) {
                FileSplit fsplit = inputs[i];
                LineRecordReader kvrr = new LineRecordReader(jobConf, fsplit);

                LongWritable key = kvrr.createKey();
                Text value = kvrr.createValue();
                {
                    IntWritable k = new IntWritable();
                    Text v = new Text();
                    while (kvrr.next(key, value)) {
                        String line_text = value.toString();
                        // ignore comments in edge file
                        if (line_text.startsWith("#"))
                            continue;

                        final String[] line = line_text.split("\t");
                        if (line.length < 2)
                            continue;

                        // vector : ROWID VALUE('vNNNN')
                        if (line[1].charAt(0) == 'v') {
                            k.set(Integer.parseInt(line[0]));
                            v.set(line[1]);
                            MPI_D.Send(k, v);
                        } else {
                            /*
                             * In other matrix-vector multiplication, we
                            * output (dst, src) here However, In PageRank,
                            * the matrix-vector computation formula is M^T
                            * * v. Therefore, we output (src,dst) here.
                            */
                            int src_id = Integer.parseInt(line[0]);
                            int dst_id = Integer.parseInt(line[1]);
                            k.set(src_id);
                            v.set(line[1]);
                            MPI_D.Send(k, v);

                            if (make_symmetric == 1) {
                                k.set(dst_id);
                                v.set(line[0]);
                                MPI_D.Send(k, v);
                            }
                        }
                    }
                }
            }

        } else if (MPI_D.COMM_BIPARTITE_A != null) {
            // A communicator
            int rank = MPI_D.Comm_rank(MPI_D.COMM_BIPARTITE_A);
            if (rank == 0) {
                LOG.info(PagerankNaive.class.getSimpleName() + " A start.");
            }

            HadoopWriter<IntWritable, Text> outrw = HadoopIOUtil.getNewWriter(jobConf, outDir,
                    IntWritable.class, Text.class, TextOutputFormat.class, null, rank, MPI_D.COMM_BIPARTITE_A);

            IntWritable oldKey = null;
            int i;
            double cur_rank = 0;
            ArrayList<Integer> dst_nodes_list = new ArrayList<Integer>();
            Object[] keyValue = MPI_D.Recv();
            while (keyValue != null) {
                IntWritable key = (IntWritable) keyValue[0];
                Text value = (Text) keyValue[1];
                if (oldKey == null) {
                    oldKey = key;
                }
                // A new key arrives
                if (!key.equals(oldKey)) {
                    outrw.write(oldKey, new Text("s" + cur_rank));
                    int outdeg = dst_nodes_list.size();
                    if (outdeg > 0) {
                        cur_rank = cur_rank / (double) outdeg;
                    }
                    for (i = 0; i < outdeg; i++) {
                        outrw.write(new IntWritable(dst_nodes_list.get(i)), new Text("v" + cur_rank));
                    }
                    oldKey = key;
                    cur_rank = 0;
                    dst_nodes_list = new ArrayList<Integer>();
                }
                // common record
                String line_text = value.toString();
                final String[] line = line_text.split("\t");
                if (line.length == 1) {
                    if (line_text.charAt(0) == 'v') { // vector : VALUE
                        cur_rank = Double.parseDouble(line_text.substring(1));
                    } else { // edge : ROWID
                        dst_nodes_list.add(Integer.parseInt(line[0]));
                    }
                }
                keyValue = MPI_D.Recv();
            }
            // write the left part
            if (cur_rank != 0) {
                outrw.write(oldKey, new Text("s" + cur_rank));
                int outdeg = dst_nodes_list.size();
                if (outdeg > 0) {
                    cur_rank = cur_rank / (double) outdeg;
                }
                for (i = 0; i < outdeg; i++) {
                    outrw.write(new IntWritable(dst_nodes_list.get(i)), new Text("v" + cur_rank));
                }
            }
            outrw.close();
        }
        MPI_D.Finalize();
    } catch (MPI_D_Exception e) {
        e.printStackTrace();
    }
}

From source file:DIA_Umpire_Quant.DIA_Umpire_ProtQuant.java

/**
 * @param args the command line arguments
 *///from   ww w.  ja  va  2  s.c om
public static void main(String[] args) throws FileNotFoundException, IOException, Exception {
    System.out.println(
            "=================================================================================================");
    System.out.println(
            "DIA-Umpire protein quantitation module (version: " + UmpireInfo.GetInstance().Version + ")");
    if (args.length != 1) {
        System.out.println(
                "command format error, the correct format should be: java -jar -Xmx10G DIA_Umpire_PortQuant.jar diaumpire_module.params");
        return;
    }
    try {
        ConsoleLogger.SetConsoleLogger(Level.INFO);
        ConsoleLogger.SetFileLogger(Level.DEBUG,
                FilenameUtils.getFullPath(args[0]) + "diaumpire_orotquant.log");
    } catch (Exception e) {
    }

    Logger.getRootLogger().info("Version: " + UmpireInfo.GetInstance().Version);
    Logger.getRootLogger().info("Parameter file:" + args[0]);

    BufferedReader reader = new BufferedReader(new FileReader(args[0]));
    String line = "";
    String WorkFolder = "";
    int NoCPUs = 2;

    String Combined_Prot = "";
    boolean DefaultProtFiltering = true;

    float Freq = 0f;
    int TopNPep = 6;
    int TopNFrag = 6;
    String FilterWeight = "GW";
    float MinWeight = 0.9f;

    TandemParam tandemPara = new TandemParam(DBSearchParam.SearchInstrumentType.TOF5600);
    HashMap<String, File> AssignFiles = new HashMap<>();

    boolean ExportSaint = false;
    boolean SAINT_MS1 = false;
    boolean SAINT_MS2 = true;

    HashMap<String, String[]> BaitList = new HashMap<>();
    HashMap<String, String> BaitName = new HashMap<>();
    HashMap<String, String[]> ControlList = new HashMap<>();
    HashMap<String, String> ControlName = new HashMap<>();

    //<editor-fold defaultstate="collapsed" desc="Reading parameter file">
    while ((line = reader.readLine()) != null) {
        line = line.trim();
        Logger.getRootLogger().info(line);
        if (!"".equals(line) && !line.startsWith("#")) {
            //System.out.println(line);
            if (line.equals("==File list begin")) {
                do {
                    line = reader.readLine();
                    line = line.trim();
                    if (line.equals("==File list end")) {
                        continue;
                    } else if (!"".equals(line)) {
                        File newfile = new File(line);
                        if (newfile.exists()) {
                            AssignFiles.put(newfile.getAbsolutePath(), newfile);
                        } else {
                            Logger.getRootLogger().info("File: " + newfile + " does not exist.");
                        }
                    }
                } while (!line.equals("==File list end"));
            }
            if (line.split("=").length < 2) {
                continue;
            }
            String type = line.split("=")[0].trim();
            String value = line.split("=")[1].trim();
            switch (type) {
            case "Path": {
                WorkFolder = value;
                break;
            }
            case "path": {
                WorkFolder = value;
                break;
            }
            case "Thread": {
                NoCPUs = Integer.parseInt(value);
                break;
            }
            case "Fasta": {
                tandemPara.FastaPath = value;
                break;
            }
            case "Combined_Prot": {
                Combined_Prot = value;
                break;
            }
            case "DefaultProtFiltering": {
                DefaultProtFiltering = Boolean.parseBoolean(value);
                break;
            }
            case "DecoyPrefix": {
                if (!"".equals(value)) {
                    tandemPara.DecoyPrefix = value;
                }
                break;
            }
            case "ProteinFDR": {
                tandemPara.ProtFDR = Float.parseFloat(value);
                break;
            }
            case "FilterWeight": {
                FilterWeight = value;
                break;
            }
            case "MinWeight": {
                MinWeight = Float.parseFloat(value);
                break;
            }
            case "TopNFrag": {
                TopNFrag = Integer.parseInt(value);
                break;
            }
            case "TopNPep": {
                TopNPep = Integer.parseInt(value);
                break;
            }
            case "Freq": {
                Freq = Float.parseFloat(value);
                break;
            }
            //<editor-fold defaultstate="collapsed" desc="SaintOutput">
            case "ExportSaintInput": {
                ExportSaint = Boolean.parseBoolean(value);
                break;
            }
            case "QuantitationType": {
                switch (value) {
                case "MS1": {
                    SAINT_MS1 = true;
                    SAINT_MS2 = false;
                    break;
                }
                case "MS2": {
                    SAINT_MS1 = false;
                    SAINT_MS2 = true;
                    break;
                }
                case "BOTH": {
                    SAINT_MS1 = true;
                    SAINT_MS2 = true;
                    break;
                }
                }
                break;
            }
            //                    case "BaitInputFile": {
            //                        SaintBaitFile = value;
            //                        break;
            //                    }
            //                    case "PreyInputFile": {
            //                        SaintPreyFile = value;
            //                        break;
            //                    }
            //                    case "InterationInputFile": {
            //                        SaintInteractionFile = value;
            //                        break;
            //                    }
            default: {
                if (type.startsWith("BaitName_")) {
                    BaitName.put(type.substring(9), value);
                }
                if (type.startsWith("BaitFile_")) {
                    BaitList.put(type.substring(9), value.split("\t"));
                }
                if (type.startsWith("ControlName_")) {
                    ControlName.put(type.substring(12), value);
                }
                if (type.startsWith("ControlFile_")) {
                    ControlList.put(type.substring(12), value.split("\t"));
                }
                break;
            }
            //</editor-fold>                    
            }
        }
    }
    //</editor-fold>

    //Initialize PTM manager using compomics library
    PTMManager.GetInstance();

    //Check if the fasta file can be found
    if (!new File(tandemPara.FastaPath).exists()) {
        Logger.getRootLogger().info("Fasta file :" + tandemPara.FastaPath
                + " cannot be found, the process will be terminated, please check.");
        System.exit(1);
    }

    //Check if the prot.xml file can be found
    if (!new File(Combined_Prot).exists()) {
        Logger.getRootLogger().info("ProtXML file: " + Combined_Prot
                + " cannot be found, the export protein summary table will be empty.");
    }
    LCMSID protID = null;

    //Parse prot.xml and generate protein master list given an FDR 
    if (Combined_Prot != null && !Combined_Prot.equals("")) {
        protID = LCMSID.ReadLCMSIDSerialization(Combined_Prot);
        if (!"".equals(Combined_Prot) && protID == null) {
            protID = new LCMSID(Combined_Prot, tandemPara.DecoyPrefix, tandemPara.FastaPath);
            ProtXMLParser protxmlparser = new ProtXMLParser(protID, Combined_Prot, 0f);
            //Use DIA-Umpire default protein FDR calculation
            if (DefaultProtFiltering) {
                protID.RemoveLowLocalPWProtein(0.8f);
                protID.RemoveLowMaxIniProbProtein(0.9f);
                protID.FilterByProteinDecoyFDRUsingMaxIniProb(tandemPara.DecoyPrefix, tandemPara.ProtFDR);
            }
            //Get protein FDR calculation without other filtering
            else {
                protID.FilterByProteinDecoyFDRUsingLocalPW(tandemPara.DecoyPrefix, tandemPara.ProtFDR);
            }
            protID.LoadSequence();
            protID.WriteLCMSIDSerialization(Combined_Prot);
        }
        Logger.getRootLogger().info("Protein No.:" + protID.ProteinList.size());
    }
    HashMap<String, HashMap<String, FragmentPeak>> IDSummaryFragments = new HashMap<>();

    //Generate DIA file list
    ArrayList<DIAPack> FileList = new ArrayList<>();
    try {
        File folder = new File(WorkFolder);
        if (!folder.exists()) {
            Logger.getRootLogger().info("The path : " + WorkFolder + " cannot be found.");
            System.exit(1);
        }
        for (final File fileEntry : folder.listFiles()) {
            if (fileEntry.isFile()
                    && (fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                            | fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzml"))
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
                AssignFiles.put(fileEntry.getAbsolutePath(), fileEntry);
            }
            if (fileEntry.isDirectory()) {
                for (final File fileEntry2 : fileEntry.listFiles()) {
                    if (fileEntry2.isFile()
                            && (fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                                    | fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzml"))
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
                        AssignFiles.put(fileEntry2.getAbsolutePath(), fileEntry2);
                    }
                }
            }
        }

        Logger.getRootLogger().info("No. of files assigned :" + AssignFiles.size());
        for (File fileEntry : AssignFiles.values()) {
            Logger.getRootLogger().info(fileEntry.getAbsolutePath());
        }

        for (File fileEntry : AssignFiles.values()) {
            String mzXMLFile = fileEntry.getAbsolutePath();
            if (mzXMLFile.toLowerCase().endsWith(".mzxml") | mzXMLFile.toLowerCase().endsWith(".mzml")) {
                DIAPack DiaFile = new DIAPack(mzXMLFile, NoCPUs);
                Logger.getRootLogger().info(
                        "=================================================================================================");
                Logger.getRootLogger().info("Processing " + mzXMLFile);
                if (!DiaFile.LoadDIASetting()) {
                    Logger.getRootLogger().info("Loading DIA setting failed, job is incomplete");
                    System.exit(1);
                }
                if (!DiaFile.LoadParams()) {
                    Logger.getRootLogger().info("Loading parameters failed, job is incomplete");
                    System.exit(1);
                }
                Logger.getRootLogger().info("Loading identification results " + mzXMLFile + "....");

                //If the serialization file for ID file existed
                if (DiaFile.ReadSerializedLCMSID()) {
                    DiaFile.IDsummary.ReduceMemoryUsage();
                    DiaFile.IDsummary.ClearAssignPeakCluster();
                    FileList.add(DiaFile);
                    HashMap<String, FragmentPeak> FragMap = new HashMap<>();
                    IDSummaryFragments.put(FilenameUtils.getBaseName(mzXMLFile), FragMap);
                }
            }
        }

        //<editor-fold defaultstate="collapsed" desc="Peptide and fragment selection">

        Logger.getRootLogger().info("Peptide and fragment selection across the whole dataset");
        ArrayList<LCMSID> SummaryList = new ArrayList<>();
        for (DIAPack diafile : FileList) {
            if (protID != null) {
                //Generate protein list according to mapping of peptide ions for each DIA file to the master protein list
                diafile.IDsummary.GenerateProteinByRefIDByPepSeq(protID, true);
                diafile.IDsummary.ReMapProPep();
            }
            if ("GW".equals(FilterWeight)) {
                diafile.IDsummary.SetFilterByGroupWeight();
            } else if ("PepW".equals(FilterWeight)) {
                diafile.IDsummary.SetFilterByWeight();
            }
            SummaryList.add(diafile.IDsummary);
        }
        FragmentSelection fragselection = new FragmentSelection(SummaryList);
        fragselection.freqPercent = Freq;
        fragselection.GeneratePepFragScoreMap();
        fragselection.GenerateTopFragMap(TopNFrag);
        fragselection.GenerateProtPepScoreMap(MinWeight);
        fragselection.GenerateTopPepMap(TopNPep);
        //</editor-fold>

        //<editor-fold defaultstate="collapsed" desc="Writing general reports">                 
        ExportTable export = new ExportTable(WorkFolder, SummaryList, IDSummaryFragments, protID,
                fragselection);
        export.Export(TopNPep, TopNFrag, Freq);
        //</editor-fold>

        //<editor-fold defaultstate="collapsed" desc="//<editor-fold defaultstate="collapsed" desc="Generate SAINT input files">
        if (ExportSaint && protID != null) {
            HashMap<String, DIAPack> Filemap = new HashMap<>();
            for (DIAPack DIAfile : FileList) {
                Filemap.put(DIAfile.GetBaseName(), DIAfile);
            }

            FileWriter baitfile = new FileWriter(WorkFolder + "SAINT_Bait_" + DateTimeTag.GetTag() + ".txt");
            FileWriter preyfile = new FileWriter(WorkFolder + "SAINT_Prey_" + DateTimeTag.GetTag() + ".txt");
            FileWriter interactionfileMS1 = null;
            FileWriter interactionfileMS2 = null;
            if (SAINT_MS1) {
                interactionfileMS1 = new FileWriter(
                        WorkFolder + "SAINT_Interaction_MS1_" + DateTimeTag.GetTag() + ".txt");
            }
            if (SAINT_MS2) {
                interactionfileMS2 = new FileWriter(
                        WorkFolder + "SAINT_Interaction_MS2_" + DateTimeTag.GetTag() + ".txt");
            }
            HashMap<String, String> PreyID = new HashMap<>();

            for (String samplekey : ControlName.keySet()) {
                String name = ControlName.get(samplekey);
                for (String file : ControlList.get(samplekey)) {
                    baitfile.write(FilenameUtils.getBaseName(file) + "\t" + name + "\t" + "C\n");
                    LCMSID IDsummary = Filemap.get(FilenameUtils.getBaseName(file)).IDsummary;
                    if (SAINT_MS1) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS1, file, name, PreyID,
                                1);
                    }
                    if (SAINT_MS2) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS2, file, name, PreyID,
                                2);
                    }
                }
            }
            for (String samplekey : BaitName.keySet()) {
                String name = BaitName.get(samplekey);
                for (String file : BaitList.get(samplekey)) {
                    baitfile.write(FilenameUtils.getBaseName(file) + "\t" + name + "\t" + "T\n");
                    LCMSID IDsummary = Filemap.get(FilenameUtils.getBaseName(file)).IDsummary;
                    if (SAINT_MS1) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS1, file, name, PreyID,
                                1);
                    }
                    if (SAINT_MS2) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS2, file, name, PreyID,
                                2);
                    }
                }
            }
            baitfile.close();
            if (SAINT_MS1) {
                interactionfileMS1.close();
            }
            if (SAINT_MS2) {
                interactionfileMS2.close();
            }
            for (String AccNo : PreyID.keySet()) {
                preyfile.write(AccNo + "\t" + PreyID.get(AccNo) + "\n");
            }
            preyfile.close();
        }

        //</editor-fold>

        Logger.getRootLogger().info("Job done");
        Logger.getRootLogger().info(
                "=================================================================================================");

    } catch (Exception e) {
        Logger.getRootLogger().error(ExceptionUtils.getStackTrace(e));
        throw e;
    }
}

From source file:com.moviejukebox.MovieJukebox.java

public static void main(String[] args) throws Throwable {
    JukeboxStatistics.setTimeStart(System.currentTimeMillis());

    // Create the log file name here, so we can change it later (because it's locked
    System.setProperty("file.name", LOG_FILENAME);
    PropertyConfigurator.configure("properties/log4j.properties");

    LOG.info("Yet Another Movie Jukebox {}", GitRepositoryState.getVersion());
    LOG.info("~~~ ~~~~~~~ ~~~~~ ~~~~~~~ {}", StringUtils.repeat("~", GitRepositoryState.getVersion().length()));
    LOG.info("https://github.com/YAMJ/yamj-v2");
    LOG.info("Copyright (c) 2004-2016 YAMJ Members");
    LOG.info("");
    LOG.info("This software is licensed under the GNU General Public License v3+");
    LOG.info("See this page: https://github.com/YAMJ/yamj-v2/wiki/License");
    LOG.info("");
    LOG.info(" Revision SHA: {} {}", GIT.getCommitId(), GIT.getDirty() ? "(Custom Build)" : "");
    LOG.info("  Commit Date: {}", GIT.getCommitTime());
    LOG.info("   Build Date: {}", GIT.getBuildTime());
    LOG.info("");
    LOG.info(" Java Version: {}", GitRepositoryState.getJavaVersion());
    LOG.info("");

    if (!SystemTools.validateInstallation()) {
        LOG.info("ABORTING.");
        return;//from w w  w .  j ava  2s  .c o m
    }

    String movieLibraryRoot = null;
    String jukeboxRoot = null;
    Map<String, String> cmdLineProps = new LinkedHashMap<>();

    try {
        for (int i = 0; i < args.length; i++) {
            String arg = args[i];
            if ("-v".equalsIgnoreCase(arg)) {
                // We've printed the version, so quit now
                return;
            } else if ("-t".equalsIgnoreCase(arg)) {
                String pin = args[++i];

                // load the apikeys.properties file
                if (!setPropertiesStreamName("./properties/apikeys.properties", Boolean.TRUE)) {
                    return;
                }

                // authorize to Trakt.TV
                TraktTV.getInstance().initialize().authorizeWithPin(pin);

                // We've authorized access to Trakt.TV, so quit now
                return;
            } else if ("-o".equalsIgnoreCase(arg)) {
                jukeboxRoot = args[++i];
                PropertiesUtil.setProperty("mjb.jukeboxRoot", jukeboxRoot);
            } else if ("-c".equalsIgnoreCase(arg)) {
                jukeboxClean = Boolean.TRUE;
                PropertiesUtil.setProperty("mjb.jukeboxClean", TRUE);
            } else if ("-k".equalsIgnoreCase(arg)) {
                setJukeboxPreserve(Boolean.TRUE);
            } else if ("-p".equalsIgnoreCase(arg)) {
                userPropertiesName = args[++i];
            } else if ("-i".equalsIgnoreCase(arg)) {
                skipIndexGeneration = Boolean.TRUE;
                PropertiesUtil.setProperty("mjb.skipIndexGeneration", TRUE);
            } else if ("-h".equalsIgnoreCase(arg)) {
                skipHtmlGeneration = Boolean.TRUE;
                PropertiesUtil.setProperty("mjb.skipHtmlGeneration", Boolean.TRUE);
            } else if ("-dump".equalsIgnoreCase(arg)) {
                dumpLibraryStructure = Boolean.TRUE;
            } else if ("-memory".equalsIgnoreCase(arg)) {
                showMemory = Boolean.TRUE;
                PropertiesUtil.setProperty("mjb.showMemory", Boolean.TRUE);
            } else if (arg.startsWith("-D")) {
                String propLine = arg.length() > 2 ? arg.substring(2) : args[++i];
                int propDiv = propLine.indexOf('=');
                if (-1 != propDiv) {
                    cmdLineProps.put(propLine.substring(0, propDiv), propLine.substring(propDiv + 1));
                }
            } else if (arg.startsWith("-")) {
                help();
                return;
            } else {
                movieLibraryRoot = args[i];
            }
        }
    } catch (Exception error) {
        LOG.error("Wrong arguments specified");
        help();
        return;
    }

    // Save the name of the properties file for use later
    setProperty("userPropertiesName", userPropertiesName);

    LOG.info("Processing started at {}", new Date());
    LOG.info("");

    // Load the moviejukebox-default.properties file
    if (!setPropertiesStreamName("./properties/moviejukebox-default.properties", Boolean.TRUE)) {
        return;
    }

    // Load the user properties file "moviejukebox.properties"
    // No need to abort if we don't find this file
    // Must be read before the skin, because this may contain an override skin
    setPropertiesStreamName(userPropertiesName, Boolean.FALSE);

    // Grab the skin from the command-line properties
    if (cmdLineProps.containsKey(SKIN_DIR)) {
        setProperty(SKIN_DIR, cmdLineProps.get(SKIN_DIR));
    }

    // Load the skin.properties file
    if (!setPropertiesStreamName(getProperty(SKIN_DIR, SKIN_DEFAULT) + "/skin.properties", Boolean.TRUE)) {
        return;
    }

    // Load the skin-user.properties file (ignore the error)
    setPropertiesStreamName(getProperty(SKIN_DIR, SKIN_DEFAULT) + "/skin-user.properties", Boolean.FALSE);

    // Load the overlay.properties file (ignore the error)
    String overlayRoot = getProperty("mjb.overlay.dir", Movie.UNKNOWN);
    overlayRoot = (PropertiesUtil.getBooleanProperty("mjb.overlay.skinroot", Boolean.TRUE)
            ? (getProperty(SKIN_DIR, SKIN_DEFAULT) + File.separator)
            : "") + (StringTools.isValidString(overlayRoot) ? (overlayRoot + File.separator) : "");
    setPropertiesStreamName(overlayRoot + "overlay.properties", Boolean.FALSE);

    // Load the apikeys.properties file
    if (!setPropertiesStreamName("./properties/apikeys.properties", Boolean.TRUE)) {
        return;
    }

    // This is needed to update the static reference for the API Keys in the pattern formatter
    // because the formatter is initialised before the properties files are read
    FilteringLayout.addApiKeys();

    // Load the rest of the command-line properties
    for (Map.Entry<String, String> propEntry : cmdLineProps.entrySet()) {
        setProperty(propEntry.getKey(), propEntry.getValue());
    }

    // Read the information about the skin
    SkinProperties.readSkinVersion();
    // Display the information about the skin
    SkinProperties.printSkinVersion();

    StringBuilder properties = new StringBuilder("{");
    for (Map.Entry<Object, Object> propEntry : PropertiesUtil.getEntrySet()) {
        properties.append(propEntry.getKey());
        properties.append("=");
        properties.append(propEntry.getValue());
        properties.append(",");
    }
    properties.replace(properties.length() - 1, properties.length(), "}");

    // Print out the properties to the log file.
    LOG.debug("Properties: {}", properties.toString());

    // Check for mjb.skipIndexGeneration and set as necessary
    // This duplicates the "-i" functionality, but allows you to have it in the property file
    skipIndexGeneration = PropertiesUtil.getBooleanProperty("mjb.skipIndexGeneration", Boolean.FALSE);

    if (PropertiesUtil.getBooleanProperty("mjb.people", Boolean.FALSE)) {
        peopleScan = Boolean.TRUE;
        peopleScrape = PropertiesUtil.getBooleanProperty("mjb.people.scrape", Boolean.TRUE);
        peopleMax = PropertiesUtil.getIntProperty("mjb.people.maxCount", 10);
        popularity = PropertiesUtil.getIntProperty("mjb.people.popularity", 5);

        // Issue 1947: Cast enhancement - option to save all related files to a specific folder
        peopleFolder = PropertiesUtil.getProperty("mjb.people.folder", "");
        if (isNotValidString(peopleFolder)) {
            peopleFolder = "";
        } else if (!peopleFolder.endsWith(File.separator)) {
            peopleFolder += File.separator;
        }
        StringTokenizer st = new StringTokenizer(
                PropertiesUtil.getProperty("photo.scanner.photoExtensions", "jpg,jpeg,gif,bmp,png"), ",;| ");
        while (st.hasMoreTokens()) {
            PHOTO_EXTENSIONS.add(st.nextToken());
        }
    }

    // Check for mjb.skipHtmlGeneration and set as necessary
    // This duplicates the "-h" functionality, but allows you to have it in the property file
    skipHtmlGeneration = PropertiesUtil.getBooleanProperty("mjb.skipHtmlGeneration", Boolean.FALSE);

    // Look for the parameter in the properties file if it's not been set on the command line
    // This way we don't overwrite the setting if it's not found and defaults to FALSE
    showMemory = PropertiesUtil.getBooleanProperty("mjb.showMemory", Boolean.FALSE);

    // This duplicates the "-c" functionality, but allows you to have it in the property file
    jukeboxClean = PropertiesUtil.getBooleanProperty("mjb.jukeboxClean", Boolean.FALSE);

    MovieFilenameScanner.setSkipKeywords(
            tokenizeToArray(getProperty("filename.scanner.skip.keywords", ""), ",;| "),
            PropertiesUtil.getBooleanProperty("filename.scanner.skip.caseSensitive", Boolean.TRUE));
    MovieFilenameScanner.setSkipRegexKeywords(
            tokenizeToArray(getProperty("filename.scanner.skip.keywords.regex", ""), ","),
            PropertiesUtil.getBooleanProperty("filename.scanner.skip.caseSensitive.regex", Boolean.TRUE));
    MovieFilenameScanner.setExtrasKeywords(
            tokenizeToArray(getProperty("filename.extras.keywords", "trailer,extra,bonus"), ",;| "));
    MovieFilenameScanner.setMovieVersionKeywords(tokenizeToArray(
            getProperty("filename.movie.versions.keywords", "remastered,directors cut,extended cut,final cut"),
            ",;|"));
    MovieFilenameScanner.setLanguageDetection(
            PropertiesUtil.getBooleanProperty("filename.scanner.language.detection", Boolean.TRUE));
    final KeywordMap languages = PropertiesUtil.getKeywordMap("filename.scanner.language.keywords", null);
    if (!languages.isEmpty()) {
        MovieFilenameScanner.clearLanguages();
        for (String lang : languages.getKeywords()) {
            String values = languages.get(lang);
            if (values != null) {
                MovieFilenameScanner.addLanguage(lang, values, values);
            } else {
                LOG.info("No values found for language code '{}'", lang);
            }
        }
    }
    final KeywordMap sourceKeywords = PropertiesUtil.getKeywordMap("filename.scanner.source.keywords",
            "HDTV,PDTV,DVDRip,DVDSCR,DSRip,CAM,R5,LINE,HD2DVD,DVD,DVD5,DVD9,HRHDTV,MVCD,VCD,TS,VHSRip,BluRay,HDDVD,D-THEATER,SDTV");
    MovieFilenameScanner.setSourceKeywords(sourceKeywords.getKeywords(), sourceKeywords);

    String temp = getProperty("sorting.strip.prefixes");
    if (temp != null) {
        StringTokenizer st = new StringTokenizer(temp, ",");
        while (st.hasMoreTokens()) {
            String token = st.nextToken().trim();
            if (token.startsWith("\"") && token.endsWith("\"")) {
                token = token.substring(1, token.length() - 1);
            }
            Movie.addSortIgnorePrefixes(token.toLowerCase());
        }
    }

    enableWatchScanner = PropertiesUtil.getBooleanProperty("watched.scanner.enable", Boolean.TRUE);
    enableWatchTraktTv = PropertiesUtil.getBooleanProperty("watched.trakttv.enable", Boolean.FALSE);
    enableCompleteMovies = PropertiesUtil.getBooleanProperty("complete.movies.enable", Boolean.TRUE);

    // Check to see if don't have a root, check the property file
    if (StringTools.isNotValidString(movieLibraryRoot)) {
        movieLibraryRoot = getProperty("mjb.libraryRoot");
        if (StringTools.isValidString(movieLibraryRoot)) {
            LOG.info("Got libraryRoot from properties file: {}", movieLibraryRoot);
        } else {
            LOG.error("No library root found!");
            help();
            return;
        }
    }

    if (jukeboxRoot == null) {
        jukeboxRoot = getProperty("mjb.jukeboxRoot");
        if (jukeboxRoot == null) {
            LOG.info("jukeboxRoot is null in properties file. Please fix this as it may cause errors.");
        } else {
            LOG.info("Got jukeboxRoot from properties file: {}", jukeboxRoot);
        }
    }

    File f = new File(movieLibraryRoot);
    if (f.exists() && f.isDirectory() && jukeboxRoot == null) {
        jukeboxRoot = movieLibraryRoot;
    }

    if (movieLibraryRoot == null) {
        help();
        return;
    }

    if (jukeboxRoot == null) {
        LOG.info("Wrong arguments specified: you must define the jukeboxRoot property (-o) !");
        help();
        return;
    }

    if (!f.exists()) {
        LOG.error("Directory or library configuration file '{}', not found.", movieLibraryRoot);
        return;
    }

    FileTools.initUnsafeChars();
    FileTools.initSubtitleExtensions();

    // make canonical names
    jukeboxRoot = FileTools.getCanonicalPath(jukeboxRoot);
    movieLibraryRoot = FileTools.getCanonicalPath(movieLibraryRoot);
    MovieJukebox ml = new MovieJukebox(movieLibraryRoot, jukeboxRoot);
    if (dumpLibraryStructure) {
        LOG.warn(
                "WARNING !!! A dump of your library directory structure will be generated for debug purpose. !!! Library won't be built or updated");
        ml.makeDumpStructure();
    } else {
        ml.generateLibrary();
    }

    // Now rename the log files
    renameLogFile();

    if (ScanningLimit.isLimitReached()) {
        LOG.warn("Scanning limit of {} was reached, please re-run to complete processing.",
                ScanningLimit.getLimit());
        System.exit(EXIT_SCAN_LIMIT);
    } else {
        System.exit(EXIT_NORMAL);
    }
}

From source file:com.github.wshackle.java4cpp.J4CppMain.java

public static void main(String[] args) throws IOException, ClassNotFoundException {
    main_completed = false;//from   w w w  .  j  a  v  a2 s  .com

    Options options = new Options();
    options.addOption(Option.builder("?").desc("Print this message").longOpt("help").build());
    options.addOption(Option.builder("n").hasArg().desc("C++ namespace for newly generated classes.")
            .longOpt("namespace").build());
    options.addOption(
            Option.builder("c").hasArgs().desc("Single Java class to extract.").longOpt("classes").build());
    options.addOption(
            Option.builder("p").hasArgs().desc("Java Package prefix to extract").longOpt("packages").build());
    options.addOption(Option.builder("o").hasArg().desc("Output C++ source file.").longOpt("output").build());
    options.addOption(Option.builder("j").hasArg().desc("Input jar file").longOpt("jar").build());
    options.addOption(Option.builder("h").hasArg().desc("Output C++ header file.").longOpt("header").build());
    options.addOption(Option.builder("l").hasArg()
            .desc("Maximum limit on classes to extract from jars.[default=200]").longOpt("limit").build());
    options.addOption(Option.builder("v").desc("enable verbose output").longOpt("verbose").build());
    options.addOption(Option.builder().hasArg().desc("Classes per output file.[default=10]")
            .longOpt(CLASSESPEROUTPUT).build());
    options.addOption(Option.builder().hasArgs().desc(
            "Comma seperated list of nativeclass=javaclass native where nativeclass will be generated as an extension/implementation of the java class.")
            .longOpt("natives").build());
    options.addOption(Option.builder().hasArg()
            .desc("library name for System.loadLibrary(...) for native extension classes")
            .longOpt("loadlibname").build());
    String output = null;
    String header = null;
    String jar = null;
    Set<String> classnamesToFind = null;
    Set<String> packageprefixes = null;
    String loadlibname = null;

    Map<String, String> nativesNameMap = null;
    Map<String, Class> nativesClassMap = null;
    int limit = DEFAULT_LIMIT;
    int classes_per_file = 10;
    List<Class> classes = new ArrayList<>();

    String limitstring = Integer.toString(limit);

    try {
        // parse the command line arguments
        System.out.println("args = " + Arrays.toString(args));
        CommandLine line = new DefaultParser().parse(options, args);
        loadlibname = line.getOptionValue("loadlibname");
        verbose = line.hasOption("verbose");
        if (line.hasOption(CLASSESPEROUTPUT)) {
            String cpoStr = line.getOptionValue(CLASSESPEROUTPUT);
            try {
                int cpoI = Integer.valueOf(cpoStr);
                classes_per_file = cpoI;
            } catch (Exception e) {
                System.err.println("Option for " + CLASSESPEROUTPUT + "=\"" + cpoStr + "\"");
                printHelpAndExit(options, args);
            }
        }

        if (line.hasOption("natives")) {
            String natives[] = line.getOptionValues("natives");
            if (verbose) {
                System.out.println("natives = " + Arrays.toString(natives));
            }
            nativesNameMap = new HashMap<>();
            nativesClassMap = new HashMap<>();
            for (int i = 0; i < natives.length; i++) {
                int eq_index = natives[i].indexOf('=');
                String nativeClassName = natives[i].substring(0, eq_index).trim();
                String javaClassName = natives[i].substring(eq_index + 1).trim();
                Class javaClass = null;
                try {
                    javaClass = Class.forName(javaClassName);
                } catch (ClassNotFoundException e) {
                    //e.printStackTrace();
                    System.err.println("Class for " + javaClassName
                            + " not found. (It may be found later in jar if specified.)");
                }
                nativesNameMap.put(javaClassName, nativeClassName);
                if (javaClass != null) {
                    nativesClassMap.put(nativeClassName, javaClass);
                    if (!classes.contains(javaClass)) {
                        classes.add(javaClass);
                    }
                }
            }
        }
        //            // validate that block-size has been set
        //            if (line.hasOption("block-size")) {
        //                // print the value of block-size
        //                if(verbose) System.out.println(line.getOptionValue("block-size"));
        //            }
        jar = line.getOptionValue("jar", jar);
        if (verbose) {
            System.out.println("jar = " + jar);
        }
        if (null != jar) {
            if (jar.startsWith("~/")) {
                jar = new File(new File(getHomeDir()), jar.substring(2)).getCanonicalPath();
            }
            if (jar.startsWith("./")) {
                jar = new File(new File(getCurrentDir()), jar.substring(2)).getCanonicalPath();
            }
            if (jar.startsWith("../")) {
                jar = new File(new File(getCurrentDir()).getParentFile(), jar.substring(3)).getCanonicalPath();
            }
        }
        if (line.hasOption("classes")) {
            classnamesToFind = new HashSet<String>();
            String classStrings[] = line.getOptionValues("classes");
            if (verbose) {
                System.out.println("classStrings = " + Arrays.toString(classStrings));
            }
            classnamesToFind.addAll(Arrays.asList(classStrings));
            if (verbose) {
                System.out.println("classnamesToFind = " + classnamesToFind);
            }
        }
        //                if (!line.hasOption("namespace")) {
        //                    if (classname != null && classname.length() > 0) {
        //                        namespace = classname.toLowerCase().replace(".", "_");
        //                    } else if (jar != null && jar.length() > 0) {
        //                        int lastSep = jar.lastIndexOf(File.separator);
        //                        int start = Math.max(0, lastSep + 1);
        //                        int period = jar.indexOf('.', start + 1);
        //                        int end = Math.max(start + 1, period);
        //                        namespace = jar.substring(start, end).toLowerCase();
        //                        namespace = namespace.replace(" ", "_");
        //                        if (namespace.indexOf("-") > 0) {
        //                            namespace = namespace.substring(0, namespace.indexOf("-"));
        //                        }
        //                    }
        //                }

        namespace = line.getOptionValue("namespace", namespace);
        if (verbose) {
            System.out.println("namespace = " + namespace);
        }
        if (null != namespace) {
            output = namespace + ".cpp";
        }
        output = line.getOptionValue("output", output);
        if (verbose) {
            System.out.println("output = " + output);
        }
        if (null != output) {
            if (output.startsWith("~/")) {
                output = System.getProperty("user.home") + output.substring(1);
            }
            header = output.substring(0, output.lastIndexOf('.')) + ".h";
        } else {
            output = "out.cpp";
        }
        header = line.getOptionValue("header", header);
        if (verbose) {
            System.out.println("header = " + header);
        }
        if (null != header) {
            if (header.startsWith("~/")) {
                header = System.getProperty("user.home") + header.substring(1);
            }
        } else {
            header = "out.h";
        }

        if (line.hasOption("packages")) {
            packageprefixes = new HashSet<String>();
            packageprefixes.addAll(Arrays.asList(line.getOptionValues("packages")));
        }
        if (line.hasOption("limit")) {
            limitstring = line.getOptionValue("limit", Integer.toString(DEFAULT_LIMIT));
            limit = Integer.valueOf(limitstring);
        }
        if (line.hasOption("help")) {
            printHelpAndExit(options, args);
        }
    } catch (ParseException exp) {
        if (verbose) {
            System.out.println("Unexpected exception:" + exp.getMessage());
        }
        printHelpAndExit(options, args);
    }

    Set<Class> excludedClasses = new HashSet<>();
    Set<String> foundClassNames = new HashSet<>();
    excludedClasses.add(Object.class);
    excludedClasses.add(String.class);
    excludedClasses.add(void.class);
    excludedClasses.add(Void.class);
    excludedClasses.add(Class.class);
    excludedClasses.add(Enum.class);
    Set<String> packagesSet = new TreeSet<>();
    List<URL> urlsList = new ArrayList<>();
    String cp = System.getProperty("java.class.path");
    if (verbose) {
        System.out.println("System.getProperty(\"java.class.path\") = " + cp);
    }
    if (null != cp) {
        for (String cpe : cp.split(File.pathSeparator)) {
            if (verbose) {
                System.out.println("class path element = " + cpe);
            }
            File f = new File(cpe);
            if (f.isDirectory()) {
                urlsList.add(new URL("file:" + f.getCanonicalPath() + File.separator));
            } else if (cpe.endsWith(".jar")) {
                urlsList.add(new URL("jar:file:" + f.getCanonicalPath() + "!/"));
            }
        }
    }
    cp = System.getenv("CLASSPATH");
    if (verbose) {
        System.out.println("System.getenv(\"CLASSPATH\") = " + cp);
    }
    if (null != cp) {
        for (String cpe : cp.split(File.pathSeparator)) {
            if (verbose) {
                System.out.println("class path element = " + cpe);
            }
            File f = new File(cpe);
            if (f.isDirectory()) {
                urlsList.add(new URL("file:" + f.getCanonicalPath() + File.separator));
            } else if (cpe.endsWith(".jar")) {
                urlsList.add(new URL("jar:file:" + f.getCanonicalPath() + "!/"));
            }
        }
    }
    if (verbose) {
        System.out.println("urlsList = " + urlsList);
    }

    if (null != jar && jar.length() > 0) {
        Path jarPath = FileSystems.getDefault().getPath(jar);
        ZipInputStream zip = new ZipInputStream(Files.newInputStream(jarPath, StandardOpenOption.READ));

        URL jarUrl = new URL("jar:file:" + jarPath.toFile().getCanonicalPath() + "!/");
        urlsList.add(jarUrl);
        URL[] urls = urlsList.toArray(new URL[urlsList.size()]);
        if (verbose) {
            System.out.println("urls = " + Arrays.toString(urls));
        }
        URLClassLoader cl = URLClassLoader.newInstance(urls);
        for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
            // This ZipEntry represents a class. Now, what class does it represent?
            String entryName = entry.getName();
            if (verbose) {
                System.out.println("entryName = " + entryName);
            }

            if (!entry.isDirectory() && entryName.endsWith(".class")) {

                if (entryName.indexOf('$') >= 0) {
                    continue;
                }
                String classFileName = entry.getName().replace('/', '.');
                String className = classFileName.substring(0, classFileName.length() - ".class".length());
                if (classnamesToFind != null && classnamesToFind.size() > 0
                        && !classnamesToFind.contains(className)) {
                    if (verbose) {
                        System.out.println("skipping className=" + className + " because it does not found in="
                                + classnamesToFind);
                    }
                    continue;
                }
                try {
                    Class clss = cl.loadClass(className);
                    if (null != nativesClassMap && null != nativesNameMap
                            && nativesNameMap.containsKey(className)) {
                        nativesClassMap.put(nativesNameMap.get(className), clss);
                        if (!classes.contains(clss)) {
                            classes.add(clss);
                        }
                    }
                    if (packageprefixes != null && packageprefixes.size() > 0) {
                        if (null == clss.getPackage()) {
                            continue;
                        }
                        final String pkgName = clss.getPackage().getName();
                        boolean matchFound = false;
                        for (String prefix : packageprefixes) {
                            if (pkgName.startsWith(prefix)) {
                                matchFound = true;
                                break;
                            }
                        }
                        if (!matchFound) {
                            continue;
                        }
                    }
                    Package p = clss.getPackage();
                    if (null != p) {
                        packagesSet.add(clss.getPackage().getName());
                    }
                    if (!classes.contains(clss) && isAddableClass(clss, excludedClasses)) {
                        if (null != classnamesToFind && classnamesToFind.contains(className)
                                && !foundClassNames.contains(className)) {
                            foundClassNames.add(className);
                            if (verbose) {
                                System.out.println("foundClassNames = " + foundClassNames);
                            }
                        }
                        //                        if(verbose) System.out.println("clss = " + clss);
                        classes.add(clss);
                        //                        Class superClass = clss.getSuperclass();
                        //                        while (null != superClass
                        //                                && !classes.contains(superClass)
                        //                                && isAddableClass(superClass, excludedClasses)) {
                        //                            classes.add(superClass);
                        //                            superClass = superClass.getSuperclass();
                        //                        }
                    }
                } catch (ClassNotFoundException | NoClassDefFoundError ex) {
                    System.err.println(
                            "Caught " + ex.getClass().getName() + ":" + ex.getMessage() + " for className="
                                    + className + ", entryName=" + entryName + ", jarPath=" + jarPath);
                }
            }
        }
    }
    if (null != classnamesToFind) {
        if (verbose) {
            System.out.println("Checking classnames arguments");
        }
        for (String classname : classnamesToFind) {
            if (verbose) {
                System.out.println("classname = " + classname);
            }
            if (foundClassNames.contains(classname)) {
                if (verbose) {
                    System.out.println("foundClassNames.contains(" + classname + ")");
                }
                continue;
            }
            try {
                if (classes.contains(Class.forName(classname))) {
                    if (verbose) {
                        System.out.println("Classes list already contains:  " + classname);
                    }
                    continue;
                }
            } catch (Exception e) {

            }

            if (null != classname && classname.length() > 0) {
                urlsList.add(new URL("file://" + System.getProperty("user.dir") + "/"));

                URL[] urls = urlsList.toArray(new URL[urlsList.size()]);
                if (verbose) {
                    System.out.println("urls = " + Arrays.toString(urls));
                }
                URLClassLoader cl = URLClassLoader.newInstance(urls);
                Class c = null;
                try {
                    c = cl.loadClass(classname);
                } catch (ClassNotFoundException e) {
                    System.err.println("Class " + classname + " not found ");
                }
                if (verbose) {
                    System.out.println("c = " + c);
                }
                if (null == c) {
                    try {
                        c = ClassLoader.getSystemClassLoader().loadClass(classname);
                    } catch (ClassNotFoundException e) {
                        if (verbose) {
                            System.out.println("System ClassLoader failed to find " + classname);
                        }
                    }
                }
                if (null != c) {
                    classes.add(c);
                } else {
                    System.err.println("Class " + classname + " not found");
                }
            }
        }
        if (verbose) {
            System.out.println("Finished checking classnames arguments");
        }
    }
    if (classes == null || classes.size() < 1) {
        if (null == nativesClassMap || nativesClassMap.keySet().size() < 1) {
            System.err.println("No Classes specified or found.");
            System.exit(1);
        }
    }
    if (verbose) {
        System.out.println("Classes found = " + classes.size());
    }
    if (classes.size() > limit) {
        System.err.println("limit=" + limit);
        System.err.println(
                "Too many classes please use -c or -p options to limit classes or -l to increase limit.");
        if (verbose) {
            System.out.println("packagesSet = " + packagesSet);
        }
        System.exit(1);
    }
    List<Class> newClasses = new ArrayList<Class>();
    for (Class clss : classes) {
        Class superClass = clss.getSuperclass();
        while (null != superClass && !classes.contains(superClass) && !newClasses.contains(superClass)
                && isAddableClass(superClass, excludedClasses)) {
            newClasses.add(superClass);
            superClass = superClass.getSuperclass();
        }
        try {
            Field fa[] = clss.getDeclaredFields();
            for (Field f : fa) {
                if (Modifier.isPublic(f.getModifiers())) {
                    Class fClass = f.getType();
                    if (!classes.contains(fClass) && !newClasses.contains(fClass)
                            && isAddableClass(fClass, excludedClasses)) {
                        newClasses.add(fClass);
                    }
                }
            }
        } catch (NoClassDefFoundError e) {
            e.printStackTrace();
        }
        for (Method m : clss.getDeclaredMethods()) {
            if (m.isSynthetic()) {
                continue;
            }
            if (!Modifier.isPublic(m.getModifiers()) || Modifier.isAbstract(m.getModifiers())) {
                continue;
            }
            Class retType = m.getReturnType();
            if (verbose) {
                System.out.println("Checking dependancies for Method = " + m);
            }
            if (!classes.contains(retType) && !newClasses.contains(retType)
                    && isAddableClass(retType, excludedClasses)) {
                newClasses.add(retType);
                superClass = retType.getSuperclass();
                while (null != superClass && !classes.contains(superClass) && !newClasses.contains(superClass)
                        && isAddableClass(superClass, excludedClasses)) {
                    newClasses.add(superClass);
                    superClass = superClass.getSuperclass();
                }
            }
            for (Class paramType : m.getParameterTypes()) {
                if (!classes.contains(paramType) && !newClasses.contains(paramType)
                        && isAddableClass(paramType, excludedClasses)) {
                    newClasses.add(paramType);
                    superClass = paramType.getSuperclass();
                    while (null != superClass && !classes.contains(superClass)
                            && !newClasses.contains(superClass) && !excludedClasses.contains(superClass)) {
                        newClasses.add(superClass);
                        superClass = superClass.getSuperclass();
                    }
                }
            }
        }
    }
    if (null != nativesClassMap) {
        for (Class clss : nativesClassMap.values()) {
            if (null != clss) {
                Class superClass = clss.getSuperclass();
                while (null != superClass && !classes.contains(superClass) && !newClasses.contains(superClass)
                        && !excludedClasses.contains(superClass)) {
                    newClasses.add(superClass);
                    superClass = superClass.getSuperclass();
                }
            }
        }
    }
    if (verbose) {
        System.out.println("Dependency classes needed = " + newClasses.size());
    }
    classes.addAll(newClasses);
    List<Class> newOrderClasses = new ArrayList<>();
    for (Class clss : classes) {
        if (newOrderClasses.contains(clss)) {
            continue;
        }
        Class superClass = clss.getSuperclass();
        Stack<Class> stack = new Stack<>();
        while (null != superClass && !newOrderClasses.contains(superClass)
                && !superClass.equals(java.lang.Object.class)) {
            stack.push(superClass);
            superClass = superClass.getSuperclass();
        }
        while (!stack.empty()) {
            newOrderClasses.add(stack.pop());
        }
        newOrderClasses.add(clss);
    }
    classes = newOrderClasses;
    if (verbose) {
        System.out.println("Total number of classes = " + classes.size());
        System.out.println("classes = " + classes);
    }

    String forward_header = header.substring(0, header.lastIndexOf('.')) + "_fwd.h";
    Map<String, String> map = new HashMap<>();
    map.put(JAR, jar != null ? jar : "");
    map.put("%CLASSPATH_PREFIX%",
            getCurrentDir() + ((jar != null)
                    ? (File.pathSeparator + ((new File(jar).getCanonicalPath()).replace("\\", "\\\\")))
                    : ""));
    map.put("%FORWARD_HEADER%", forward_header);
    map.put("%HEADER%", header);
    map.put("%PATH_SEPERATOR%", File.pathSeparator);
    String tabs = "";
    String headerDefine = forward_header.substring(Math.max(0, forward_header.indexOf(File.separator)))
            .replace(".", "_");
    map.put(HEADER_DEFINE, headerDefine);
    map.put(NAMESPACE, namespace);
    if (null != nativesClassMap) {
        for (Entry<String, Class> e : nativesClassMap.entrySet()) {
            final Class javaClass = e.getValue();
            final String nativeClassName = e.getKey();
            try (PrintWriter pw = new PrintWriter(new FileWriter(nativeClassName + ".java"))) {
                if (javaClass.isInterface()) {
                    pw.println("public class " + nativeClassName + " implements " + javaClass.getCanonicalName()
                            + ", AutoCloseable{");
                } else {
                    pw.println("public class " + nativeClassName + " extends " + javaClass.getCanonicalName()
                            + " implements AutoCloseable{");
                }
                if (null != loadlibname && loadlibname.length() > 0) {
                    pw.println(TAB_STRING + "static {");
                    pw.println(TAB_STRING + TAB_STRING + "System.loadLibrary(\"" + loadlibname + "\");");
                    pw.println(TAB_STRING + "}");
                    pw.println();
                }
                pw.println(TAB_STRING + "public " + nativeClassName + "() {");
                pw.println(TAB_STRING + "}");
                pw.println();
                pw.println(TAB_STRING + "private long nativeAddress=0;");
                pw.println(TAB_STRING + "private boolean nativeDeleteOnClose=false;");
                pw.println();

                pw.println(TAB_STRING + "protected " + nativeClassName + "(final long nativeAddress) {");
                pw.println(TAB_STRING + TAB_STRING + "this.nativeAddress = nativeAddress;");
                pw.println(TAB_STRING + "}");

                pw.println(TAB_STRING + "private native void nativeDelete();");
                pw.println();
                pw.println(TAB_STRING + "@Override");
                pw.println(TAB_STRING + "public synchronized void  close() {");
                //                        pw.println(TAB_STRING + TAB_STRING + "if(nativeAddress != 0 && nativeDeleteOnClose) {");
                pw.println(TAB_STRING + TAB_STRING + "nativeDelete();");
                //                        pw.println(TAB_STRING + TAB_STRING + "}");
                //                        pw.println(TAB_STRING + TAB_STRING + "nativeAddress=0;");
                //                        pw.println(TAB_STRING + TAB_STRING + "nativeDeleteOnClose=false;");
                pw.println(TAB_STRING + "}");

                pw.println();
                pw.println(TAB_STRING + "protected void finalizer() {");
                pw.println(TAB_STRING + TAB_STRING + "close();");
                pw.println(TAB_STRING + "}");

                pw.println();
                Method ma[] = javaClass.getDeclaredMethods();
                for (Method m : ma) {
                    int modifiers = m.getModifiers();
                    if (Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers)
                            && !Modifier.isStatic(modifiers)
                            //                                && !m.isDefault()
                            && !m.isSynthetic()) {
                        pw.println();
                        pw.println(TAB_STRING + "@Override");
                        String params = "";
                        for (int i = 0; i < m.getParameterTypes().length; i++) {
                            params += m.getParameterTypes()[i].getCanonicalName() + " param" + i;
                            if (i < m.getParameterTypes().length - 1) {
                                params += ",";
                            }
                        }
                        pw.println(TAB_STRING + "native public " + m.getReturnType().getCanonicalName() + " "
                                + m.getName() + "(" + params + ");");
                        //                                    + IntStream.range(0, m.getParameterTypes().length)
                        //                                    .mapToObj(i -> m.getParameterTypes()[i].getCanonicalName() + " param" + i)
                        //                                    .collect(Collectors.joining(",")) + ");");
                    }
                }
                pw.println("}");
            }
        }
    }
    try (PrintWriter pw = new PrintWriter(new FileWriter(forward_header))) {
        tabs = "";
        processTemplate(pw, map, "header_fwd_template_start.h", tabs);
        Class lastClass = null;
        for (int class_index = 0; class_index < classes.size(); class_index++) {
            Class clss = classes.get(class_index);
            String clssOnlyName = getCppClassName(clss);
            tabs = openClassNamespace(clss, pw, tabs, lastClass);
            tabs += TAB_STRING;
            pw.println(tabs + "class " + clssOnlyName + ";");
            tabs = tabs.substring(0, tabs.length() - 1);
            Class nextClass = (class_index < (classes.size() - 1)) ? classes.get(class_index + 1) : null;
            tabs = closeClassNamespace(clss, pw, tabs, nextClass);
            lastClass = clss;
        }
        processTemplate(pw, map, "header_fwd_template_end.h", tabs);
    }
    headerDefine = header.substring(Math.max(0, header.indexOf(File.separator))).replace(".", "_");
    map.put(HEADER_DEFINE, headerDefine);
    map.put(NAMESPACE, namespace);
    if (classes_per_file < 1) {
        classes_per_file = classes.size();
    }
    final int num_class_segments = (classes.size() > 1)
            ? ((classes.size() + classes_per_file - 1) / classes_per_file)
            : 1;
    String fmt = "%d";
    if (num_class_segments > 10) {
        fmt = "%02d";
    }
    if (num_class_segments > 100) {
        fmt = "%03d";
    }
    String header_file_base = header;
    if (header_file_base.endsWith(".h")) {
        header_file_base = header_file_base.substring(0, header_file_base.length() - 2);
    } else if (header_file_base.endsWith(".hh")) {
        header_file_base = header_file_base.substring(0, header_file_base.length() - 3);
    } else if (header_file_base.endsWith(".hpp")) {
        header_file_base = header_file_base.substring(0, header_file_base.length() - 4);
    }
    try (PrintWriter pw = new PrintWriter(new FileWriter(header))) {
        tabs = "";
        processTemplate(pw, map, HEADER_TEMPLATE_STARTH, tabs);
        for (int segment_index = 0; segment_index < num_class_segments; segment_index++) {
            String header_segment_file = header_file_base + String.format(fmt, segment_index) + ".h";
            pw.println("#include \"" + header_segment_file + "\"");
        }
        if (null != nativesClassMap) {
            tabs = TAB_STRING;
            for (Entry<String, Class> e : nativesClassMap.entrySet()) {
                final Class javaClass = e.getValue();
                final String nativeClassName = e.getKey();
                pw.println();
                pw.println(tabs + "class " + nativeClassName + "Context;");
                pw.println();
                map.put(CLASS_NAME, nativeClassName);
                map.put("%BASE_CLASS_FULL_NAME%",
                        "::" + namespace + "::" + getModifiedClassName(javaClass).replace(".", "::"));
                map.put(OBJECT_CLASS_FULL_NAME, "::" + namespace + "::java::lang::Object");
                processTemplate(pw, map, HEADER_CLASS_STARTH, tabs);
                tabs += TAB_STRING;
                pw.println(tabs + nativeClassName + "Context *context;");
                pw.println(tabs + nativeClassName + "();");
                pw.println(tabs + "~" + nativeClassName + "();");
                Method methods[] = javaClass.getDeclaredMethods();
                for (int j = 0; j < methods.length; j++) {
                    Method method = methods[j];
                    int modifiers = method.getModifiers();
                    if (!Modifier.isPublic(modifiers)) {
                        continue;
                    }
                    if (Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers)
                            && !Modifier.isStatic(modifiers)
                            //                                && !method.isDefault()
                            && !method.isSynthetic()) {
                        pw.println(tabs + getNativeMethodCppDeclaration(method, javaClass));
                    }
                }
                pw.println(tabs + "void initContext(" + nativeClassName + "Context *ctx,bool isref);");
                pw.println(tabs + "void deleteContext();");
                tabs = tabs.substring(TAB_STRING.length());
                pw.println(tabs + "}; // end class " + nativeClassName);
            }
        }
        tabs = "";
        processTemplate(pw, map, HEADER_TEMPLATE_ENDH, tabs);
    }
    for (int segment_index = 0; segment_index < num_class_segments; segment_index++) {
        String header_segment_file = header_file_base + String.format(fmt, segment_index) + ".h";
        try (PrintWriter pw = new PrintWriter(new FileWriter(header_segment_file))) {
            tabs = "";
            //processTemplate(pw, map, HEADER_TEMPLATE_STARTH, tabs);
            pw.println("// Never include this file (" + header_segment_file + ") directly. include " + header
                    + " instead.");
            pw.println();
            Class lastClass = null;
            final int start_segment_index = segment_index * classes_per_file;
            final int end_segment_index = Math.min(segment_index * classes_per_file + classes_per_file,
                    classes.size());
            List<Class> classesSegList = classes.subList(start_segment_index, end_segment_index);
            pw.println();
            pw.println(tabs + "// start_segment_index = " + start_segment_index);
            pw.println(tabs + "// start_segment_index = " + end_segment_index);
            pw.println(tabs + "// segment_index = " + segment_index);
            pw.println(tabs + "// classesSegList=" + classesSegList);
            pw.println();
            for (int class_index = 0; class_index < classesSegList.size(); class_index++) {
                Class clss = classesSegList.get(class_index);
                pw.println();
                pw.println(tabs + "// class_index = " + class_index + " clss=" + clss);
                pw.println();
                String clssName = clss.getCanonicalName();
                tabs = openClassNamespace(clss, pw, tabs, lastClass);
                String clssOnlyName = getCppClassName(clss);
                map.put(CLASS_NAME, clssOnlyName);
                map.put("%BASE_CLASS_FULL_NAME%", classToCppBase(clss));
                map.put(OBJECT_CLASS_FULL_NAME, getCppRelativeName(Object.class, clss));
                tabs += TAB_STRING;
                processTemplate(pw, map, HEADER_CLASS_STARTH, tabs);
                tabs += TAB_STRING;

                Constructor constructors[] = clss.getDeclaredConstructors();
                if (!hasNoArgConstructor(constructors)) {
                    if (Modifier.isAbstract(clss.getModifiers()) || clss.isInterface()) {
                        pw.println(tabs + "protected:");
                        pw.println(tabs + clssOnlyName + "() {};");
                        pw.println(tabs + "public:");
                    } else {
                        if (constructors.length > 0) {
                            pw.println(tabs + "protected:");
                        }
                        pw.println(tabs + clssOnlyName + "();");
                        if (constructors.length > 0) {
                            pw.println(tabs + "public:");
                        }
                    }
                }
                for (Constructor c : constructors) {
                    if (c.getParameterTypes().length == 0 && Modifier.isProtected(c.getModifiers())) {
                        pw.println(tabs + "protected:");
                        pw.println(tabs + clssOnlyName + "();");
                        pw.println(tabs + "public:");
                    }
                    if (checkConstructor(c, clss, classes)) {
                        continue;
                    }

                    if (c.getParameterTypes().length == 1 && clss.isAssignableFrom(c.getParameterTypes()[0])) {
                        continue;
                    }
                    if (!Modifier.isPublic(c.getModifiers())) {
                        continue;
                    }
                    if (c.getParameterTypes().length == 1) {
                        if (c.getParameterTypes()[0].getName().equals(clss.getName())) {
                            //                                    if(verbose) System.out.println("skipping constructor.");
                            continue;
                        }
                    }

                    if (!checkParameters(c.getParameterTypes(), classes)) {
                        continue;
                    }
                    pw.println(
                            tabs + clssOnlyName + getCppParamDeclarations(c.getParameterTypes(), clss) + ";");
                    if (isConstructorToMakeEasy(c, clss)) {
                        pw.println(tabs + clssOnlyName
                                + getEasyCallCppParamDeclarations(c.getParameterTypes(), clss) + ";");
                    }
                }

                pw.println(tabs + "~" + clssOnlyName + "();");
                Field fa[] = clss.getDeclaredFields();
                for (int findex = 0; findex < fa.length; findex++) {
                    Field field = fa[findex];
                    if (addGetterMethod(field, clss, classes)) {
                        pw.println(tabs + getCppFieldGetterDeclaration(field, clss));
                    }
                    if (addSetterMethod(field, clss, classes)) {
                        pw.println(tabs + getCppFieldSetterDeclaration(field, clss));
                    }
                }
                Method methods[] = clss.getDeclaredMethods();
                for (int j = 0; j < methods.length; j++) {
                    Method method = methods[j];
                    if (!checkMethod(method, classes)) {
                        continue;
                    }
                    if ((method.getModifiers() & Modifier.PUBLIC) == Modifier.PUBLIC) {
                        pw.println(tabs + getCppDeclaration(method, clss));
                    }
                    if (isArrayStringMethod(method)) {
                        pw.println(tabs + getCppModifiers(method.getModifiers())
                                + getCppType(method.getReturnType(), clss) + " " + fixMethodName(method)
                                + "(int argc,const char **argv);");
                    }
                    if (isMethodToMakeEasy(method)) {
                        pw.println(tabs + getEasyCallCppDeclaration(method, clss));
                    }
                }
                tabs = tabs.substring(TAB_STRING.length());
                pw.println(tabs + "}; // end class " + clssOnlyName);
                tabs = tabs.substring(0, tabs.length() - 1);
                Class nextClass = (class_index < (classesSegList.size() - 1))
                        ? classesSegList.get(class_index + 1)
                        : null;
                tabs = closeClassNamespace(clss, pw, tabs, nextClass);
                pw.println();
                lastClass = clss;
            }
            //processTemplate(pw, map, HEADER_TEMPLATE_ENDH, tabs);
        }
    }
    for (int segment_index = 0; segment_index < num_class_segments; segment_index++) {
        String output_segment_file = output;
        if (output_segment_file.endsWith(".cpp")) {
            output_segment_file = output_segment_file.substring(0, output_segment_file.length() - 4);
        } else if (output_segment_file.endsWith(".cc")) {
            output_segment_file = output_segment_file.substring(0, output_segment_file.length() - 3);
        }
        output_segment_file += "" + String.format(fmt, segment_index) + ".cpp";
        try (PrintWriter pw = new PrintWriter(new FileWriter(output_segment_file))) {
            tabs = "";
            if (segment_index < 1) {
                processTemplate(pw, map, "cpp_template_start_first.cpp", tabs);
            } else {
                processTemplate(pw, map, CPP_TEMPLATE_STARTCPP, tabs);
            }
            final int start_segment_index = segment_index * classes_per_file;
            final int end_segment_index = Math.min(segment_index * classes_per_file + classes_per_file,
                    classes.size());
            List<Class> classesSegList = classes.subList(start_segment_index, end_segment_index);
            pw.println();
            pw.println(tabs + "// start_segment_index = " + start_segment_index);
            pw.println(tabs + "// start_segment_index = " + end_segment_index);
            pw.println(tabs + "// segment_index = " + segment_index);
            pw.println(tabs + "// classesSegList=" + classesSegList);
            pw.println();
            Class lastClass = null;
            for (int class_index = 0; class_index < classesSegList.size(); class_index++) {
                Class clss = classesSegList.get(class_index);
                pw.println();
                pw.println(tabs + "// class_index = " + class_index + " clss=" + clss);
                pw.println();
                String clssName = clss.getCanonicalName();
                tabs = openClassNamespace(clss, pw, tabs, lastClass);
                String clssOnlyName = getCppClassName(clss);
                map.put(CLASS_NAME, clssOnlyName);
                map.put("%BASE_CLASS_FULL_NAME%", classToCppBase(clss));

                map.put(FULL_CLASS_NAME, clssName);
                String fcjs = classToJNISignature(clss);
                fcjs = fcjs.substring(1, fcjs.length() - 1);
                map.put(FULL_CLASS_JNI_SIGNATURE, fcjs);
                if (verbose) {
                    System.out.println("fcjs = " + fcjs);
                }
                map.put(OBJECT_CLASS_FULL_NAME, getCppRelativeName(Object.class, clss));
                map.put("%INITIALIZE_CONTEXT%", "");
                map.put("%INITIALIZE_CONTEXT_REF%", "");
                processTemplate(pw, map, CPP_START_CLASSCPP, tabs);
                Constructor constructors[] = clss.getDeclaredConstructors();

                if (!hasNoArgConstructor(constructors)) {
                    if (!Modifier.isAbstract(clss.getModifiers()) && !clss.isInterface()) {
                        pw.println(tabs + clssOnlyName + "::" + clssOnlyName + "() : " + classToCppBase(clss)
                                + "((jobject)NULL,false) {");
                        map.put(JNI_SIGNATURE, "()V");
                        map.put(CONSTRUCTOR_ARGS, "");
                        processTemplate(pw, map, CPP_NEWCPP, tabs);
                        pw.println(tabs + "}");
                        pw.println();
                    }

                }
                for (Constructor c : constructors) {
                    if (checkConstructor(c, clss, classes)) {
                        continue;
                    }
                    Class[] paramClasses = c.getParameterTypes();
                    pw.println(tabs + clssOnlyName + "::" + clssOnlyName
                            + getCppParamDeclarations(paramClasses, clss) + " : " + classToCppBase(clss)
                            + "((jobject)NULL,false) {");
                    tabs = tabs + TAB_STRING;
                    map.put(JNI_SIGNATURE, "(" + getJNIParamSignature(paramClasses) + ")V");
                    map.put(CONSTRUCTOR_ARGS,
                            (paramClasses.length > 0 ? "," : "") + getCppParamNames(paramClasses));
                    processTemplate(pw, map, CPP_NEWCPP, tabs);
                    tabs = tabs.substring(0, tabs.length() - 1);
                    pw.println(tabs + "}");
                    pw.println();
                    if (isConstructorToMakeEasy(c, clss)) {
                        pw.println(tabs + clssOnlyName + "::" + clssOnlyName
                                + getEasyCallCppParamDeclarations(c.getParameterTypes(), clss) + " : "
                                + classToCppBase(clss) + "((jobject)NULL,false) {");
                        processTemplate(pw, map, "cpp_start_easy_constructor.cpp", tabs);
                        for (int paramIndex = 0; paramIndex < paramClasses.length; paramIndex++) {
                            Class paramClasse = paramClasses[paramIndex];
                            String parmName = getParamNameIn(paramClasse, paramIndex);
                            if (isString(paramClasse)) {
                                pw.println(tabs + "jstring " + parmName + " = env->NewStringUTF(easyArg_"
                                        + paramIndex + ");");
                            } else if (isPrimitiveArray(paramClasse)) {
                                String callString = getMethodCallString(paramClasse.getComponentType());
                                pw.println(tabs + getCppArrayType(paramClasse.getComponentType()) + " "
                                        + classToParamNameDecl(paramClasse, paramIndex) + "= env->New"
                                        + callString + "Array(easyArg_" + paramIndex + "_length);");
                                pw.println(tabs + "env->Set" + callString + "ArrayRegion("
                                        + classToParamNameDecl(paramClasse, paramIndex) + ",0,easyArg_"
                                        + paramIndex + "_length,easyArg_" + paramIndex + ");");
                            } else {
                                pw.println(tabs + getCppType(paramClasse, clss) + " "
                                        + classToParamNameDecl(paramClasse, paramIndex) + "= easyArg_"
                                        + paramIndex + ";");
                            }
                        }
                        processTemplate(pw, map, "cpp_new_easy_internals.cpp", tabs);
                        for (int paramIndex = 0; paramIndex < paramClasses.length; paramIndex++) {
                            Class paramClasse = paramClasses[paramIndex];
                            String parmName = getParamNameIn(paramClasse, paramIndex);
                            if (isString(paramClasse)) {
                                pw.println(tabs + "jobjectRefType ref_" + paramIndex
                                        + " = env->GetObjectRefType(" + parmName + ");");
                                pw.println(tabs + "if(ref_" + paramIndex + " == JNIGlobalRefType) {");
                                pw.println(tabs + TAB_STRING + "env->DeleteGlobalRef(" + parmName + ");");
                                pw.println(tabs + "}");
                            } else if (isPrimitiveArray(paramClasse)) {
                                String callString = getMethodCallString(paramClasse.getComponentType());
                                pw.println(tabs + "env->Get" + callString + "ArrayRegion("
                                        + classToParamNameDecl(paramClasse, paramIndex) + ",0,easyArg_"
                                        + paramIndex + "_length,easyArg_" + paramIndex + ");");
                                pw.println(tabs + "jobjectRefType ref_" + paramIndex
                                        + " = env->GetObjectRefType(" + parmName + ");");
                                pw.println(tabs + "if(ref_" + paramIndex + " == JNIGlobalRefType) {");
                                pw.println(tabs + TAB_STRING + "env->DeleteGlobalRef(" + parmName + ");");
                                pw.println(tabs + "}");
                            } else {

                            }
                        }
                        processTemplate(pw, map, "cpp_end_easy_constructor.cpp", tabs);
                        pw.println(tabs + "}");
                    }
                }

                pw.println();
                pw.println(tabs + "// Destructor for " + clssName);
                pw.println(tabs + clssOnlyName + "::~" + clssOnlyName + "() {");
                pw.println(tabs + "\t// Place-holder for later extensibility.");
                pw.println(tabs + "}");
                pw.println();
                Field fa[] = clss.getDeclaredFields();
                for (int findex = 0; findex < fa.length; findex++) {
                    Field field = fa[findex];
                    if (addGetterMethod(field, clss, classes)) {
                        pw.println();
                        pw.println(tabs + "// Field getter for " + field.getName());
                        pw.println(getCppFieldGetterDefinitionStart(tabs, clssOnlyName, field, clss));
                        map.put("%FIELD_NAME%", field.getName());
                        map.put(JNI_SIGNATURE, classToJNISignature(field.getType()));
                        Class returnClass = field.getType();
                        map.put(METHOD_ONFAIL, getOnFailString(returnClass, clss));
                        map.put(METHOD_ARGS, "");
                        map.put("%METHOD_RETURN%", isVoid(returnClass) ? "" : "return");
                        map.put("%METHOD_CALL_TYPE%", getMethodCallString(returnClass));
                        map.put("%METHOD_RETURN_TYPE%", getCppType(returnClass, clss));
                        map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclare(returnClass));
                        String retStore = isVoid(returnClass) ? ""
                                : "retVal= (" + getMethodReturnVarType(returnClass) + ") ";
                        map.put("%METHOD_RETURN_STORE%", retStore);
                        map.put("%METHOD_RETURN_GET%", getMethodReturnGet(tabs, returnClass, clss));

                        if (Modifier.isStatic(field.getModifiers())) {
                            processTemplate(pw, map, "cpp_static_getfield.cpp", tabs);
                        } else {
                            processTemplate(pw, map, "cpp_getfield.cpp", tabs);
                        }

                        pw.println(tabs + "}");
                    }
                    if (addSetterMethod(field, clss, classes)) {
                        pw.println();
                        pw.println(tabs + "// Field setter for " + field.getName());
                        pw.println(getCppFieldSetterDefinitionStart(tabs, clssOnlyName, field, clss));
                        map.put("%FIELD_NAME%", field.getName());
                        map.put(JNI_SIGNATURE, classToJNISignature(field.getType()));
                        Class returnClass = void.class;
                        map.put(METHOD_ONFAIL, getOnFailString(returnClass, clss));
                        Class[] paramClasses = new Class[] { field.getType() };
                        String methodArgs = getCppParamNames(paramClasses);
                        map.put(METHOD_ARGS, (paramClasses.length > 0 ? "," : "") + methodArgs);
                        map.put("%METHOD_RETURN%", isVoid(returnClass) ? "" : "return");
                        map.put("%METHOD_CALL_TYPE%", getMethodCallString(field.getType()));
                        map.put("%METHOD_RETURN_TYPE%", getCppType(returnClass, clss));
                        map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclare(returnClass));
                        String retStore = isVoid(returnClass) ? ""
                                : "retVal= (" + getMethodReturnVarType(returnClass) + ") ";
                        map.put("%METHOD_RETURN_STORE%", retStore);
                        map.put("%METHOD_RETURN_GET%", getMethodReturnGet(tabs, returnClass, clss));

                        if (Modifier.isStatic(field.getModifiers())) {
                            processTemplate(pw, map, "cpp_static_setfield.cpp", tabs);
                        } else {
                            processTemplate(pw, map, "cpp_setfield.cpp", tabs);
                        }

                        pw.println(tabs + "}");
                    }
                }
                Method methods[] = clss.getDeclaredMethods();
                for (int j = 0; j < methods.length; j++) {
                    Method method = methods[j];

                    if (checkMethod(method, classes)) {
                        pw.println();
                        pw.println(getCppMethodDefinitionStart(tabs, clssOnlyName, method, clss));
                        map.put(METHOD_NAME, method.getName());
                        if (fixMethodName(method).contains("equals2")) {
                            if (verbose) {
                                System.out.println("debug me");
                            }
                        }
                        map.put("%JAVA_METHOD_NAME%", method.getName());
                        Class[] paramClasses = method.getParameterTypes();
                        String methodArgs = getCppParamNames(paramClasses);
                        map.put(METHOD_ARGS, (paramClasses.length > 0 ? "," : "") + methodArgs);
                        Class returnClass = method.getReturnType();
                        map.put(JNI_SIGNATURE, "(" + getJNIParamSignature(paramClasses) + ")"
                                + classToJNISignature(returnClass));
                        map.put(METHOD_ONFAIL, getOnFailString(returnClass, clss));
                        map.put("%METHOD_RETURN%", isVoid(returnClass) ? "" : "return");
                        map.put("%METHOD_CALL_TYPE%", getMethodCallString(returnClass));
                        map.put("%METHOD_RETURN_TYPE%", getCppType(returnClass, clss));
                        map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclare(returnClass));
                        String retStore = isVoid(returnClass) ? ""
                                : "retVal= (" + getMethodReturnVarType(returnClass) + ") ";
                        map.put("%METHOD_RETURN_STORE%", retStore);
                        map.put("%METHOD_RETURN_GET%", getMethodReturnGet(tabs, returnClass, clss));
                        tabs += TAB_STRING;
                        if (!Modifier.isStatic(method.getModifiers())) {
                            processTemplate(pw, map, CPP_METHODCPP, tabs);
                        } else {
                            processTemplate(pw, map, CPP_STATIC_METHODCPP, tabs);
                        }
                        tabs = tabs.substring(0, tabs.length() - TAB_STRING.length());
                        pw.println(tabs + "}");
                        if (isArrayStringMethod(method)) {
                            map.put(METHOD_RETURN_STORE,
                                    isVoid(returnClass) ? "" : getCppType(returnClass, clss) + " returnVal=");
                            map.put(METHOD_RETURN_GET, isVoid(returnClass) ? "return ;" : "return returnVal;");
                            processTemplate(pw, map, CPP_EASY_STRING_ARRAY_METHODCPP, tabs);
                        } else if (isMethodToMakeEasy(method)) {
                            pw.println();
                            pw.println(tabs + "// Easy call alternative for " + method.getName());
                            pw.println(getEasyCallCppMethodDefinitionStart(tabs, clssOnlyName, method, clss));
                            tabs += TAB_STRING;
                            map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclareOut(returnClass, clss));
                            processTemplate(pw, map, "cpp_start_easy_method.cpp", tabs);
                            for (int paramIndex = 0; paramIndex < paramClasses.length; paramIndex++) {
                                Class paramClasse = paramClasses[paramIndex];
                                String parmName = getParamNameIn(paramClasse, paramIndex);
                                if (isString(paramClasse)) {
                                    pw.println(tabs + "jstring " + parmName + " = env->NewStringUTF(easyArg_"
                                            + paramIndex + ");");
                                } else if (isPrimitiveArray(paramClasse)) {
                                    String callString = getMethodCallString(paramClasse.getComponentType());
                                    pw.println(tabs + getCppArrayType(paramClasse.getComponentType()) + " "
                                            + classToParamNameDecl(paramClasse, paramIndex) + "= env->New"
                                            + callString + "Array(easyArg_" + paramIndex + "_length);");
                                    pw.println(tabs + "env->Set" + callString + "ArrayRegion("
                                            + classToParamNameDecl(paramClasse, paramIndex) + ",0,easyArg_"
                                            + paramIndex + "_length,easyArg_" + paramIndex + ");");
                                } else {
                                    pw.println(tabs + getCppType(paramClasse, clss) + " "
                                            + classToParamNameDecl(paramClasse, paramIndex) + "= easyArg_"
                                            + paramIndex + ";");
                                }
                            }
                            String methodArgsIn = getCppParamNamesIn(paramClasses);
                            String retStoreOut = isVoid(returnClass) ? ""
                                    : "retVal= (" + getMethodReturnOutVarType(returnClass, clss) + ") ";

                            pw.println(tabs + retStoreOut + fixMethodName(method) + "(" + methodArgsIn + ");");
                            for (int paramIndex = 0; paramIndex < paramClasses.length; paramIndex++) {
                                Class paramClasse = paramClasses[paramIndex];
                                String parmName = getParamNameIn(paramClasse, paramIndex);
                                if (isString(paramClasse)) {
                                    pw.println(tabs + "jobjectRefType ref_" + paramIndex
                                            + " = env->GetObjectRefType(" + parmName + ");");
                                    pw.println(tabs + "if(ref_" + paramIndex + " == JNIGlobalRefType) {");
                                    pw.println(tabs + TAB_STRING + "env->DeleteGlobalRef(" + parmName + ");");
                                    pw.println(tabs + "}");
                                } else if (isPrimitiveArray(paramClasse)) {
                                    String callString = getMethodCallString(paramClasse.getComponentType());
                                    pw.println(tabs + "env->Get" + callString + "ArrayRegion("
                                            + classToParamNameDecl(paramClasse, paramIndex) + ",0,easyArg_"
                                            + paramIndex + "_length,easyArg_" + paramIndex + ");");
                                    pw.println(tabs + "jobjectRefType ref_" + paramIndex
                                            + " = env->GetObjectRefType(" + parmName + ");");
                                    pw.println(tabs + "if(ref_" + paramIndex + " == JNIGlobalRefType) {");
                                    pw.println(tabs + TAB_STRING + "env->DeleteGlobalRef(" + parmName + ");");
                                    pw.println(tabs + "}");
                                } else {

                                }
                            }
                            processTemplate(pw, map, "cpp_end_easy_method.cpp", tabs);
                            if (!isVoid(returnClass)) {
                                pw.println(tabs + "return retVal;");
                            }
                            tabs = tabs.substring(TAB_STRING.length());
                            pw.println(tabs + "}");
                            pw.println();
                        }
                    }
                }
                processTemplate(pw, map, CPP_END_CLASSCPP, tabs);
                tabs = tabs.substring(0, tabs.length() - 1);
                Class nextClass = (class_index < (classesSegList.size() - 1))
                        ? classesSegList.get(class_index + 1)
                        : null;
                tabs = closeClassNamespace(clss, pw, tabs, nextClass);
                lastClass = clss;
            }

            if (segment_index < 1) {
                if (null != nativesClassMap) {
                    for (Entry<String, Class> e : nativesClassMap.entrySet()) {
                        final Class javaClass = e.getValue();
                        final String nativeClassName = e.getKey();
                        map.put(CLASS_NAME, nativeClassName);
                        map.put(FULL_CLASS_NAME, nativeClassName);
                        map.put(FULL_CLASS_JNI_SIGNATURE, nativeClassName);
                        map.put("%BASE_CLASS_FULL_NAME%",
                                "::" + namespace + "::" + getModifiedClassName(javaClass).replace(".", "::"));
                        map.put(OBJECT_CLASS_FULL_NAME, "::" + namespace + "::java::lang::Object");
                        map.put("%INITIALIZE_CONTEXT%", "context=NULL; initContext(NULL,false);");
                        map.put("%INITIALIZE_CONTEXT_REF%", "context=NULL; initContext(objref.context,true);");
                        tabs += TAB_STRING;

                        processTemplate(pw, map, CPP_START_CLASSCPP, tabs);
                        pw.println();
                        pw.println(tabs + nativeClassName + "::" + nativeClassName + "() : "
                                + getModifiedClassName(javaClass).replace(".", "::")
                                + "((jobject)NULL,false) {");
                        tabs += TAB_STRING;
                        pw.println(tabs + "context=NULL;");
                        pw.println(tabs + "initContext(NULL,false);");
                        map.put(JNI_SIGNATURE, "()V");
                        map.put(CONSTRUCTOR_ARGS, "");
                        processTemplate(pw, map, "cpp_new_native.cpp", tabs);
                        tabs = tabs.substring(TAB_STRING.length());
                        pw.println(tabs + "}");
                        pw.println();
                        pw.println(tabs + "// Destructor for " + nativeClassName);
                        pw.println(tabs + nativeClassName + "::~" + nativeClassName + "() {");
                        pw.println(tabs + TAB_STRING + "if(NULL != context) {");
                        pw.println(tabs + TAB_STRING + TAB_STRING + "deleteContext();");
                        pw.println(tabs + TAB_STRING + "}");
                        pw.println(tabs + TAB_STRING + "context=NULL;");
                        pw.println(tabs + "}");
                        pw.println();
                        //                            pw.println(tabs + "public:");
                        //                            pw.println(tabs + nativeClassName + "();");
                        //                            pw.println(tabs + "~" + nativeClassName + "();");
                        tabs = tabs.substring(TAB_STRING.length());
                        //                            Method methods[] = javaClass.getDeclaredMethods();
                        //                            for (int j = 0; j < methods.length; j++) {
                        //                                Method method = methods[j];
                        //                                int modifiers = method.getModifiers();
                        //                                if (!Modifier.isPublic(modifiers)) {
                        //                                    continue;
                        //                                }
                        //                                pw.println(tabs + getCppDeclaration(method, javaClass));
                        //                            }
                        //                            pw.println(tabs + "}; // end class " + nativeClassName);
                        processTemplate(pw, map, CPP_END_CLASSCPP, tabs);
                    }
                }
                processTemplate(pw, map, "cpp_template_end_first.cpp", tabs);
                tabs = "";
                if (null != nativesClassMap) {
                    pw.println("using namespace " + namespace + ";");
                    pw.println("#ifdef __cplusplus");
                    pw.println("extern \"C\" {");
                    pw.println("#endif");
                    int max_method_count = 0;
                    tabs = "";
                    for (Entry<String, Class> e : nativesClassMap.entrySet()) {
                        final Class javaClass = e.getValue();
                        final String nativeClassName = e.getKey();
                        map.put(CLASS_NAME, nativeClassName);
                        map.put(FULL_CLASS_NAME, nativeClassName);
                        map.put("%BASE_CLASS_FULL_NAME%",
                                "::" + namespace + "::" + getModifiedClassName(javaClass).replace(".", "::"));
                        map.put(OBJECT_CLASS_FULL_NAME, "::" + namespace + "::java::lang::Object");
                        map.put(FULL_CLASS_JNI_SIGNATURE, nativeClassName);
                        map.put(METHOD_ONFAIL, "return;");
                        Method methods[] = javaClass.getDeclaredMethods();
                        if (max_method_count < methods.length) {
                            max_method_count = methods.length;
                        }
                        for (int j = 0; j < methods.length; j++) {
                            Method method = methods[j];
                            int modifiers = method.getModifiers();
                            if (!Modifier.isPublic(modifiers)) {
                                continue;
                            }
                            if (Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers)
                                    && !Modifier.isStatic(modifiers)
                                    //                                        && !method.isDefault()
                                    && !method.isSynthetic()) {
                                Class[] paramClasses = method.getParameterTypes();
                                String methodArgs = getCppParamNames(paramClasses);
                                map.put(METHOD_ARGS, methodArgs);
                                map.put(METHOD_NAME, method.getName());
                                Class returnClass = method.getReturnType();
                                String retStore = isVoid(returnClass) ? ""
                                        : "retVal= (" + getMethodReturnVarType(returnClass) + ") ";
                                map.put(METHOD_ONFAIL, getOnFailString(returnClass, javaClass));
                                map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclare(returnClass));
                                map.put("%METHOD_RETURN_STORE%", retStore);
                                map.put("%METHOD_RETURN_GET%",
                                        getMethodReturnGet(tabs, returnClass, javaClass));
                                pw.println();
                                String paramDecls = getCppParamDeclarations(paramClasses, javaClass);
                                String argsToAdd = method.getParameterTypes().length > 0
                                        ? "," + paramDecls.substring(1, paramDecls.length() - 1)
                                        : "";
                                pw.println("JNIEXPORT " + getCppType(returnClass, javaClass) + " JNICALL Java_"
                                        + nativeClassName + "_" + method.getName()
                                        + "(JNIEnv *env, jobject jthis" + argsToAdd + ") {");
                                tabs = TAB_STRING;
                                processTemplate(pw, map, "cpp_native_wrap.cpp", tabs);
                                tabs = tabs.substring(TAB_STRING.length());
                                pw.println("}");
                                pw.println();
                            }
                        }
                        pw.println("JNIEXPORT void JNICALL Java_" + nativeClassName
                                + "_nativeDelete(JNIEnv *env, jobject jthis) {");
                        tabs += TAB_STRING;
                        map.put(METHOD_ONFAIL, getOnFailString(void.class, javaClass));
                        processTemplate(pw, map, "cpp_native_delete.cpp", tabs);
                        tabs = tabs.substring(TAB_STRING.length());
                        pw.println(tabs + "}");
                        pw.println();
                    }
                    pw.println("#ifdef __cplusplus");
                    pw.println("} // end extern \"C\"");
                    pw.println("#endif");
                    map.put("%MAX_METHOD_COUNT%", Integer.toString(max_method_count + 1));
                    processTemplate(pw, map, "cpp_start_register_native.cpp", tabs);
                    for (Entry<String, Class> e : nativesClassMap.entrySet()) {
                        final Class javaClass = e.getValue();
                        final String nativeClassName = e.getKey();
                        map.put(CLASS_NAME, nativeClassName);
                        map.put(FULL_CLASS_NAME, nativeClassName);
                        map.put("%BASE_CLASS_FULL_NAME%",
                                "::" + namespace + "::" + getModifiedClassName(javaClass).replace(".", "::"));
                        map.put(OBJECT_CLASS_FULL_NAME, "::" + namespace + "::java::lang::Object");
                        processTemplate(pw, map, "cpp_start_register_native_class.cpp", tabs);
                        tabs += TAB_STRING;
                        Method methods[] = javaClass.getDeclaredMethods();
                        int method_number = 0;
                        for (int j = 0; j < methods.length; j++) {
                            Method method = methods[j];
                            int modifiers = method.getModifiers();
                            if (!Modifier.isPublic(modifiers)) {
                                continue;
                            }
                            if (Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers)
                                    && !Modifier.isStatic(modifiers)
                                    //                                        && !method.isDefault()
                                    && !method.isSynthetic()) {
                                map.put("%METHOD_NUMBER%", Integer.toString(method_number));
                                map.put(METHOD_NAME, method.getName());

                                map.put(JNI_SIGNATURE, "(" + getJNIParamSignature(method.getParameterTypes())
                                        + ")" + classToJNISignature(method.getReturnType()));
                                processTemplate(pw, map, "cpp_register_native_item.cpp", tabs);
                                method_number++;
                            }
                        }
                        map.put("%METHOD_NUMBER%", Integer.toString(method_number));
                        map.put(METHOD_NAME, "nativeDelete");
                        map.put(JNI_SIGNATURE, "()V");
                        processTemplate(pw, map, "cpp_register_native_item.cpp", tabs);
                        map.put("%NUM_NATIVE_METHODS%", Integer.toString(method_number));
                        processTemplate(pw, map, "cpp_end_register_native_class.cpp", tabs);
                        tabs = tabs.substring(TAB_STRING.length());
                    }
                    processTemplate(pw, map, "cpp_end_register_native.cpp", tabs);
                } else {
                    pw.println("// No Native classes : registerNativMethods not needed.");
                    pw.println("static void registerNativeMethods(JNIEnv *env) {}");
                }

            } else {
                processTemplate(pw, map, CPP_TEMPLATE_ENDCPP, tabs);
            }
        }
        if (null != nativesClassMap) {
            tabs = "";
            for (Entry<String, Class> e : nativesClassMap.entrySet()) {
                String nativeClassName = e.getKey();
                File nativeClassHeaderFile = new File(
                        namespace.toLowerCase() + "_" + nativeClassName.toLowerCase() + ".h");
                map.put("%NATIVE_CLASS_HEADER%", nativeClassHeaderFile.getName());
                map.put(CLASS_NAME, nativeClassName);
                if (nativeClassHeaderFile.exists()) {
                    if (verbose) {
                        System.out.println("skipping " + nativeClassHeaderFile.getCanonicalPath()
                                + " since it already exists.");
                    }
                } else {
                    try (PrintWriter pw = new PrintWriter(new FileWriter(nativeClassHeaderFile))) {
                        processTemplate(pw, map, "header_native_imp.h", tabs);
                    }
                }
                File nativeClassCppFile = new File(
                        namespace.toLowerCase() + "_" + nativeClassName.toLowerCase() + ".cpp");
                if (nativeClassCppFile.exists()) {
                    if (verbose) {
                        System.out.println("skipping " + nativeClassCppFile.getCanonicalPath()
                                + " since it already exists.");
                    }
                } else {
                    try (PrintWriter pw = new PrintWriter(new FileWriter(nativeClassCppFile))) {
                        processTemplate(pw, map, "cpp_native_imp_start.cpp", tabs);
                        Class javaClass = e.getValue();
                        Method methods[] = javaClass.getDeclaredMethods();
                        int method_number = 0;
                        for (int j = 0; j < methods.length; j++) {
                            Method method = methods[j];
                            int modifiers = method.getModifiers();
                            if (!Modifier.isPublic(modifiers)) {
                                continue;
                            }
                            if (Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers)
                                    && !Modifier.isStatic(modifiers)
                                    //                                        && !method.isDefault()
                                    && !method.isSynthetic()) {
                                Class[] paramClasses = method.getParameterTypes();
                                //                                    String methodArgs = getCppParamNames(paramClasses);
                                String paramDecls = getCppParamDeclarations(paramClasses, javaClass);
                                String methodArgs = method.getParameterTypes().length > 0
                                        ? paramDecls.substring(1, paramDecls.length() - 1)
                                        : "";
                                map.put(METHOD_ARGS, methodArgs);
                                map.put(METHOD_NAME, method.getName());
                                Class returnClass = method.getReturnType();
                                String retStore = isVoid(returnClass) ? ""
                                        : "retVal= (" + getMethodReturnVarType(returnClass) + ") ";
                                map.put(METHOD_ONFAIL, getOnFailString(returnClass, javaClass));
                                map.put("%RETURN_TYPE%", getCppType(returnClass, javaClass));
                                map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclare(returnClass));
                                map.put("%METHOD_RETURN_STORE%", retStore);
                                map.put("%METHOD_RETURN_GET%",
                                        getMethodReturnGet(tabs, returnClass, javaClass));
                                processTemplate(pw, map, "cpp_native_imp_stub.cpp", tabs);
                            }
                        }
                        processTemplate(pw, map, "cpp_native_imp_end.cpp", tabs);
                    }
                }
            }
        }
    }

    main_completed = true;
}

From source file:Main.java

public static String trimString(String val) {
    return val.substring(val.indexOf('['));
}

From source file:Main.java

public static String GetFileName(String path) {
    return path.substring(path.lastIndexOf("/") + 1);
}

From source file:Main.java

public static String getUrlFileName(String url) {
    return url.substring(url.lastIndexOf("/") + 1);
}

From source file:Main.java

public static String getFileName(String path) {
    return path.substring(path.lastIndexOf("/") + 1);
}

From source file:Main.java

private static String removeLeftBracket(String value) {
    return value.substring(1);
}

From source file:Main.java

public static String convertToDate(String datenf) {
    return datenf.substring(6) + "-" + datenf.substring(4, 6) + "-" + datenf.substring(0, 4);
}