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, int endIndex) 

Source Link

Document

Returns a string that is a substring of this string.

Usage

From source file:com.netscape.cmstools.CRMFPopClient.java

public static void main(String args[]) throws Exception {

    Options options = createOptions();/*from   w  w  w. j  ava 2s. com*/
    CommandLine cmd = null;

    try {
        CommandLineParser parser = new PosixParser();
        cmd = parser.parse(options, args);

    } catch (Exception e) {
        printError(e.getMessage());
        System.exit(1);
    }

    if (cmd.hasOption("help")) {
        printHelp();
        System.exit(0);
    }

    boolean verbose = cmd.hasOption("v");

    String databaseDir = cmd.getOptionValue("d", ".");
    String tokenPassword = cmd.getOptionValue("p");
    String tokenName = cmd.getOptionValue("h");

    String algorithm = cmd.getOptionValue("a", "rsa");
    int keySize = Integer.parseInt(cmd.getOptionValue("l", "2048"));

    String profileID = cmd.getOptionValue("f");
    String subjectDN = cmd.getOptionValue("n");
    boolean encodingEnabled = Boolean.parseBoolean(cmd.getOptionValue("k", "false"));

    // if transportCertFilename is not specified then assume no key archival
    String transportCertFilename = cmd.getOptionValue("b");

    String popOption = cmd.getOptionValue("q", "POP_SUCCESS");

    String curve = cmd.getOptionValue("c", "nistp256");
    boolean sslECDH = Boolean.parseBoolean(cmd.getOptionValue("x", "false"));
    boolean temporary = Boolean.parseBoolean(cmd.getOptionValue("t", "true"));
    int sensitive = Integer.parseInt(cmd.getOptionValue("s", "-1"));
    int extractable = Integer.parseInt(cmd.getOptionValue("e", "-1"));

    boolean self_sign = cmd.hasOption("y");

    // get the keywrap algorithm
    KeyWrapAlgorithm keyWrapAlgorithm = null;
    String kwAlg = KeyWrapAlgorithm.AES_KEY_WRAP_PAD.toString();
    if (cmd.hasOption("w")) {
        kwAlg = cmd.getOptionValue("w");
    } else {
        String alg = System.getenv("KEY_ARCHIVAL_KEYWRAP_ALGORITHM");
        if (alg != null) {
            kwAlg = alg;
        }
    }

    String output = cmd.getOptionValue("o");

    String hostPort = cmd.getOptionValue("m");
    String username = cmd.getOptionValue("u");
    String requestor = cmd.getOptionValue("r");

    if (hostPort != null) {
        if (cmd.hasOption("w")) {
            printError("Any value specified for the key wrap parameter (-w) "
                    + "will be overriden.  CRMFPopClient will contact the "
                    + "CA to determine the supported algorithm when " + "hostport is specified");
        }
    }

    if (subjectDN == null) {
        printError("Missing subject DN");
        System.exit(1);
    }

    if (tokenPassword == null) {
        printError("Missing token password");
        System.exit(1);
    }

    if (algorithm.equals("rsa")) {
        if (cmd.hasOption("c")) {
            printError("Illegal parameter for RSA: -c");
            System.exit(1);
        }

        if (cmd.hasOption("t")) {
            printError("Illegal parameter for RSA: -t");
            System.exit(1);
        }

        if (cmd.hasOption("s")) {
            printError("Illegal parameter for RSA: -s");
            System.exit(1);
        }

        if (cmd.hasOption("e")) {
            printError("Illegal parameter for RSA: -e");
            System.exit(1);
        }

        if (cmd.hasOption("x")) {
            printError("Illegal parameter for RSA: -x");
            System.exit(1);
        }

    } else if (algorithm.equals("ec")) {
        if (cmd.hasOption("l")) {
            printError("Illegal parameter for ECC: -l");
            System.exit(1);
        }

        if (sensitive != 0 && sensitive != 1 && sensitive != -1) {
            printError("Illegal input parameters for -s: " + sensitive);
            System.exit(1);
        }

        if (extractable != 0 && extractable != 1 && extractable != -1) {
            printError("Illegal input parameters for -e: " + extractable);
            System.exit(1);
        }

    } else {
        printError("Invalid algorithm: " + algorithm);
        System.exit(1);
    }

    if (!popOption.equals("POP_SUCCESS") && !popOption.equals("POP_FAIL") && !popOption.equals("POP_NONE")) {
        printError("Invalid POP option: " + popOption);
        System.exit(1);
    }

    if (profileID == null) {
        if (algorithm.equals("rsa")) {
            profileID = "caEncUserCert";

        } else if (algorithm.equals("ec")) {
            profileID = "caEncECUserCert";

        } else {
            throw new Exception("Unknown algorithm: " + algorithm);
        }
    }

    try {
        if (verbose)
            System.out.println("Initializing security database: " + databaseDir);
        CryptoManager.initialize(databaseDir);

        CryptoManager manager = CryptoManager.getInstance();

        CryptoToken token = CryptoUtil.getKeyStorageToken(tokenName);
        tokenName = token.getName();
        manager.setThreadToken(token);

        Password password = new Password(tokenPassword.toCharArray());
        try {
            token.login(password);
        } catch (Exception e) {
            throw new Exception("Unable to login: " + e, e);
        }

        CRMFPopClient client = new CRMFPopClient();
        client.setVerbose(verbose);

        String encoded = null;
        X509Certificate transportCert = null;
        if (transportCertFilename != null) {
            if (verbose)
                System.out.println("archival option enabled");
            if (verbose)
                System.out.println("Loading transport certificate");
            encoded = new String(Files.readAllBytes(Paths.get(transportCertFilename)));
            byte[] transportCertData = Cert.parseCertificate(encoded);
            transportCert = manager.importCACertPackage(transportCertData);
        } else {
            if (verbose)
                System.out.println("archival option not enabled");
        }

        if (verbose)
            System.out.println("Parsing subject DN");
        Name subject = client.createName(subjectDN, encodingEnabled);

        if (subject == null) {
            subject = new Name();
            subject.addCommonName("Me");
            subject.addCountryName("US");
            subject.addElement(
                    new AVA(new OBJECT_IDENTIFIER("0.9.2342.19200300.100.1.1"), new PrintableString("MyUid")));
        }

        if (verbose)
            System.out.println("Generating key pair");
        KeyPair keyPair;
        if (algorithm.equals("rsa")) {
            keyPair = CryptoUtil.generateRSAKeyPair(token, keySize);
        } else if (algorithm.equals("ec")) {
            keyPair = client.generateECCKeyPair(token, curve, sslECDH, temporary, sensitive, extractable);

        } else {
            throw new Exception("Unknown algorithm: " + algorithm);
        }

        // print out keyid to be used in cmc decryptPOP
        PrivateKey privateKey = (PrivateKey) keyPair.getPrivate();
        @SuppressWarnings("deprecation")
        byte id[] = privateKey.getUniqueID();
        String kid = CryptoUtil.encodeKeyID(id);
        System.out.println("Keypair private key id: " + kid);

        if ((transportCert != null) && (hostPort != null)) {
            // check the CA for the required key wrap algorithm
            // if found, override whatever has been set by the command line
            // options for the key wrap algorithm

            ClientConfig config = new ClientConfig();
            String host = hostPort.substring(0, hostPort.indexOf(':'));
            int port = Integer.parseInt(hostPort.substring(hostPort.indexOf(':') + 1));
            config.setServerURL("http", host, port);

            PKIClient pkiclient = new PKIClient(config);
            kwAlg = getKeyWrapAlgotihm(pkiclient);
        }

        if (verbose && (transportCert != null))
            System.out.println("Using key wrap algorithm: " + kwAlg);
        if (transportCert != null) {
            keyWrapAlgorithm = KeyWrapAlgorithm.fromString(kwAlg);
        }

        if (verbose)
            System.out.println("Creating certificate request");
        CertRequest certRequest = client.createCertRequest(self_sign, token, transportCert, algorithm, keyPair,
                subject, keyWrapAlgorithm);

        ProofOfPossession pop = null;

        if (!popOption.equals("POP_NONE")) {

            if (verbose)
                System.out.println("Creating signer");
            Signature signer = client.createSigner(token, algorithm, keyPair);

            if (popOption.equals("POP_SUCCESS")) {

                ByteArrayOutputStream bo = new ByteArrayOutputStream();
                certRequest.encode(bo);
                signer.update(bo.toByteArray());

            } else if (popOption.equals("POP_FAIL")) {

                byte[] data = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 };

                signer.update(data);
            }

            byte[] signature = signer.sign();

            if (verbose)
                System.out.println("Creating POP");
            pop = client.createPop(algorithm, signature);
        }

        if (verbose)
            System.out.println("Creating CRMF request");
        String request = client.createCRMFRequest(certRequest, pop);

        StringWriter sw = new StringWriter();
        try (PrintWriter out = new PrintWriter(sw)) {
            out.println(Cert.REQUEST_HEADER);
            out.print(request);
            out.println(Cert.REQUEST_FOOTER);
        }
        String csr = sw.toString();

        if (hostPort != null) {
            System.out.println("Submitting CRMF request to " + hostPort);
            client.submitRequest(request, hostPort, username, profileID, requestor);

        } else if (output != null) {
            System.out.println("Storing CRMF request into " + output);
            try (FileWriter out = new FileWriter(output)) {
                out.write(csr);
            }

        } else {
            System.out.println(csr);
        }

    } catch (Exception e) {
        if (verbose)
            e.printStackTrace();
        printError(e.getMessage());
        System.exit(1);
    }
}

From source file:DIA_Umpire_Quant.DIA_Umpire_Quant.java

/**
 * @param args the command line arguments
 *///from www. j  a  va2  s . c o  m
public static void main(String[] args) throws FileNotFoundException, IOException, Exception {
    System.out.println(
            "=================================================================================================");
    System.out.println("DIA-Umpire quantitation with targeted re-extraction analysis (version: "
            + UmpireInfo.GetInstance().Version + ")");
    if (args.length != 1) {
        System.out.println(
                "command format error, it should be like: java -jar -Xmx10G DIA_Umpire_Quant.jar diaumpire_quant.params");
        return;
    }
    try {
        ConsoleLogger.SetConsoleLogger(Level.INFO);
        ConsoleLogger.SetFileLogger(Level.DEBUG, FilenameUtils.getFullPath(args[0]) + "diaumpire_quant.log");
    } catch (Exception e) {
    }

    try {

        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 UserMod = "";
        String Combined_Prot = "";
        String InternalLibID = "";
        String ExternalLibPath = "";
        String ExternalLibDecoyTag = "DECOY";
        boolean DefaultProtFiltering = true;
        boolean DataSetLevelPepFDR = false;
        float ProbThreshold = 0.99f;
        float ExtProbThreshold = 0.99f;
        float Freq = 0f;
        int TopNPep = 6;
        int TopNFrag = 6;
        float MinFragMz = 200f;
        String FilterWeight = "GW";
        float MinWeight = 0.9f;
        float RTWindow_Int = -1f;
        float RTWindow_Ext = -1f;

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

        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 "TargetedExtraction": {
                    InternalLibSearch = Boolean.parseBoolean(value);
                    break;
                }
                case "InternalLibSearch": {
                    InternalLibSearch = Boolean.parseBoolean(value);
                    break;
                }
                case "ExternalLibSearch": {
                    ExternalLibSearch = Boolean.parseBoolean(value);
                    break;
                }

                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 "UserMod": {
                    UserMod = value;
                    break;
                }
                case "ProteinFDR": {
                    tandemPara.ProtFDR = Float.parseFloat(value);
                    break;
                }
                case "PeptideFDR": {
                    tandemPara.PepFDR = Float.parseFloat(value);
                    break;
                }
                case "DataSetLevelPepFDR": {
                    DataSetLevelPepFDR = Boolean.parseBoolean(value);
                    break;
                }
                case "InternalLibID": {
                    InternalLibID = value;
                    break;
                }
                case "ExternalLibPath": {
                    ExternalLibPath = value;
                    break;
                }
                case "ExtProbThreshold": {
                    ExtProbThreshold = Float.parseFloat(value);
                    break;
                }
                case "RTWindow_Int": {
                    RTWindow_Int = Float.parseFloat(value);
                    break;
                }
                case "RTWindow_Ext": {
                    RTWindow_Ext = Float.parseFloat(value);
                    break;
                }
                case "ExternalLibDecoyTag": {
                    ExternalLibDecoyTag = value;
                    if (ExternalLibDecoyTag.endsWith("_")) {
                        ExternalLibDecoyTag = ExternalLibDecoyTag.substring(0,
                                ExternalLibDecoyTag.length() - 1);
                    }
                    break;
                }
                case "ProbThreshold": {
                    ProbThreshold = Float.parseFloat(value);
                    break;
                }
                case "ReSearchProb": {
                    //ReSearchProb = 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;
                }
                case "MinFragMz": {
                    MinFragMz = 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();
        if (!UserMod.equals("")) {
            PTMManager.GetInstance().ImportUserMod(UserMod);
        }

        //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<>();

        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());
            String mzXMLFile = fileEntry.getAbsolutePath();
            if (mzXMLFile.toLowerCase().endsWith(".mzxml") | mzXMLFile.toLowerCase().endsWith(".mzml")) {
                DIAPack DiaFile = new DIAPack(mzXMLFile, NoCPUs);
                FileList.add(DiaFile);
                HashMap<String, FragmentPeak> FragMap = new HashMap<>();
                IDSummaryFragments.put(FilenameUtils.getBaseName(mzXMLFile), FragMap);
                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);
                }
            }
        }

        LCMSID combinePepID = null;
        if (DataSetLevelPepFDR) {
            combinePepID = LCMSID.ReadLCMSIDSerialization(WorkFolder + "combinePepID.SerFS");
            if (combinePepID == null) {
                FDR_DataSetLevel fdr = new FDR_DataSetLevel();
                fdr.GeneratePepIonList(FileList, tandemPara, WorkFolder + "combinePepID.SerFS");
                combinePepID = fdr.combineID;
                combinePepID.WriteLCMSIDSerialization(WorkFolder + "combinePepID.SerFS");
            }
        }

        //process each DIA file for quantification based on untargeted identifications
        for (DIAPack DiaFile : FileList) {
            long time = System.currentTimeMillis();
            Logger.getRootLogger().info("Loading identification results " + DiaFile.Filename + "....");

            //If the LCMSID serialization is found
            if (!DiaFile.ReadSerializedLCMSID()) {
                DiaFile.ParsePepXML(tandemPara, combinePepID);
                DiaFile.BuildStructure();
                if (!DiaFile.MS1FeatureMap.ReadPeakCluster()) {
                    Logger.getRootLogger().info("Loading peak and structure failed, job is incomplete");
                    System.exit(1);
                }
                DiaFile.MS1FeatureMap.ClearMonoisotopicPeakOfCluster();
                //Generate mapping between index of precursor feature and pseudo MS/MS scan index 
                DiaFile.GenerateClusterScanNomapping();
                //Doing quantification
                DiaFile.AssignQuant();
                DiaFile.ClearStructure();
            }
            DiaFile.IDsummary.ReduceMemoryUsage();
            time = System.currentTimeMillis() - time;
            Logger.getRootLogger().info(DiaFile.Filename + " processed time:"
                    + String.format("%d hour, %d min, %d sec", TimeUnit.MILLISECONDS.toHours(time),
                            TimeUnit.MILLISECONDS.toMinutes(time)
                                    - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(time)),
                            TimeUnit.MILLISECONDS.toSeconds(time)
                                    - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time))));
        }

        //<editor-fold defaultstate="collapsed" desc="Targete re-extraction using internal library">            
        Logger.getRootLogger().info(
                "=================================================================================================");
        if (InternalLibSearch && FileList.size() > 1) {
            Logger.getRootLogger().info("Module C: Targeted extraction using internal library");

            FragmentLibManager libManager = FragmentLibManager.ReadFragmentLibSerialization(WorkFolder,
                    InternalLibID);
            if (libManager == null) {
                Logger.getRootLogger().info("Building internal spectral library");
                libManager = new FragmentLibManager(InternalLibID);
                ArrayList<LCMSID> LCMSIDList = new ArrayList<>();
                for (DIAPack dia : FileList) {
                    LCMSIDList.add(dia.IDsummary);
                }
                libManager.ImportFragLibTopFrag(LCMSIDList, Freq, TopNFrag);
                libManager.WriteFragmentLibSerialization(WorkFolder);
            }
            libManager.ReduceMemoryUsage();

            Logger.getRootLogger()
                    .info("Building retention time prediction model and generate candidate peptide list");
            for (int i = 0; i < FileList.size(); i++) {
                FileList.get(i).IDsummary.ClearMappedPep();
            }
            for (int i = 0; i < FileList.size(); i++) {
                for (int j = i + 1; j < FileList.size(); j++) {
                    RTAlignedPepIonMapping alignment = new RTAlignedPepIonMapping(WorkFolder,
                            FileList.get(i).GetParameter(), FileList.get(i).IDsummary,
                            FileList.get(j).IDsummary);
                    alignment.GenerateModel();
                    alignment.GenerateMappedPepIon();
                }
                FileList.get(i).ExportID();
                FileList.get(i).IDsummary = null;
            }

            Logger.getRootLogger().info("Targeted matching........");
            for (DIAPack diafile : FileList) {
                if (diafile.IDsummary == null) {
                    diafile.ReadSerializedLCMSID();
                }
                if (!diafile.IDsummary.GetMappedPepIonList().isEmpty()) {
                    diafile.UseMappedIon = true;
                    diafile.FilterMappedIonByProb = false;
                    diafile.BuildStructure();
                    diafile.MS1FeatureMap.ReadPeakCluster();
                    diafile.MS1FeatureMap.ClearMonoisotopicPeakOfCluster();
                    diafile.GenerateMassCalibrationRTMap();
                    diafile.TargetedExtractionQuant(false, libManager, 1.1f, RTWindow_Int);
                    diafile.MS1FeatureMap.ClearAllPeaks();
                    diafile.IDsummary.ReduceMemoryUsage();
                    diafile.IDsummary.RemoveLowProbMappedIon(ProbThreshold);
                    diafile.ExportID();
                    Logger.getRootLogger().info("Peptide ions: " + diafile.IDsummary.GetPepIonList().size()
                            + " Mapped ions: " + diafile.IDsummary.GetMappedPepIonList().size());
                    diafile.ClearStructure();
                }
                diafile.IDsummary = null;
                System.gc();
            }
            Logger.getRootLogger().info(
                    "=================================================================================================");
        }
        //</editor-fold>

        //<editor-fold defaultstate="collapsed" desc="Targeted re-extraction using external library">
        //External library search
        if (ExternalLibSearch) {
            Logger.getRootLogger().info("Module C: Targeted extraction using external library");

            //Read exteranl library
            FragmentLibManager ExlibManager = FragmentLibManager.ReadFragmentLibSerialization(WorkFolder,
                    FilenameUtils.getBaseName(ExternalLibPath));
            if (ExlibManager == null) {
                ExlibManager = new FragmentLibManager(FilenameUtils.getBaseName(ExternalLibPath));

                //Import traML file
                ExlibManager.ImportFragLibByTraML(ExternalLibPath, ExternalLibDecoyTag);
                //Check if there are decoy spectra
                ExlibManager.CheckDecoys();
                //ExlibManager.ImportFragLibBySPTXT(ExternalLibPath);
                ExlibManager.WriteFragmentLibSerialization(WorkFolder);
            }
            Logger.getRootLogger()
                    .info("No. of peptide ions in external lib:" + ExlibManager.PeptideFragmentLib.size());
            for (DIAPack diafile : FileList) {
                if (diafile.IDsummary == null) {
                    diafile.ReadSerializedLCMSID();
                }
                //Generate RT mapping
                RTMappingExtLib RTmap = new RTMappingExtLib(diafile.IDsummary, ExlibManager,
                        diafile.GetParameter());
                RTmap.GenerateModel();
                RTmap.GenerateMappedPepIon();

                diafile.BuildStructure();
                diafile.MS1FeatureMap.ReadPeakCluster();
                diafile.GenerateMassCalibrationRTMap();
                //Perform targeted re-extraction
                diafile.TargetedExtractionQuant(false, ExlibManager, ProbThreshold, RTWindow_Ext);
                diafile.MS1FeatureMap.ClearAllPeaks();
                diafile.IDsummary.ReduceMemoryUsage();
                //Remove target IDs below the defined probability threshold
                diafile.IDsummary.RemoveLowProbMappedIon(ExtProbThreshold);
                diafile.ExportID();
                diafile.ClearStructure();
                Logger.getRootLogger().info("Peptide ions: " + diafile.IDsummary.GetPepIonList().size()
                        + " Mapped ions: " + diafile.IDsummary.GetMappedPepIonList().size());
            }
        }
        //</editor-fold>

        //<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 (diafile.IDsummary == null) {
                diafile.ReadSerializedLCMSID();
                diafile.IDsummary.ClearAssignPeakCluster();
                //diafile.IDsummary.ClearPSMs();                    
            }
            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.MinFragMZ = MinFragMz;
        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.adobe.aem.demo.communities.Loader.java

public static void main(String[] args) {

    String hostname = null;//ww  w .  j a va  2  s.  co  m
    String port = null;
    String altport = null;
    String csvfile = null;
    String location = null;
    String language = "en";
    String analytics = null;
    String adminPassword = "admin";
    String[] url = new String[10]; // Handling 10 levels maximum for nested comments 
    boolean reset = false;
    boolean configure = false;
    int urlLevel = 0;
    int row = 0;
    HashMap<String, ArrayList<String>> learningpaths = new HashMap<String, ArrayList<String>>();

    // Command line options for this tool
    Options options = new Options();
    options.addOption("h", true, "Hostname");
    options.addOption("p", true, "Port");
    options.addOption("a", true, "Alternate Port");
    options.addOption("f", true, "CSV file");
    options.addOption("r", false, "Reset");
    options.addOption("u", true, "Admin Password");
    options.addOption("c", false, "Configure");
    options.addOption("s", true, "Analytics Endpoint");
    options.addOption("t", false, "Analytics Tracking");
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("h")) {
            hostname = cmd.getOptionValue("h");
        }

        if (cmd.hasOption("p")) {
            port = cmd.getOptionValue("p");
        }

        if (cmd.hasOption("a")) {
            altport = cmd.getOptionValue("a");
        }

        if (cmd.hasOption("f")) {
            csvfile = cmd.getOptionValue("f");
        }

        if (cmd.hasOption("u")) {
            adminPassword = cmd.getOptionValue("u");
        }

        if (cmd.hasOption("t")) {
            if (cmd.hasOption("s")) {
                analytics = cmd.getOptionValue("s");
            }
        }

        if (cmd.hasOption("r")) {
            reset = true;
        }

        if (cmd.hasOption("c")) {
            configure = true;
        }

        if (csvfile == null || port == null || hostname == null) {
            System.out.println(
                    "Request parameters: -h hostname -p port -a alternateport -u adminPassword -f path_to_CSV_file -r (true|false, delete content before import) -c (true|false, post additional properties)");
            System.exit(-1);
        }

    } catch (ParseException ex) {

        logger.error(ex.getMessage());

    }

    String componentType = null;

    try {

        logger.debug("AEM Demo Loader: Processing file " + csvfile);

        // Reading the CSV file, line by line
        Reader in = new FileReader(csvfile);

        Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
        for (CSVRecord record : records) {

            row = row + 1;
            logger.info("Row: " + row + ", new record: " + record.get(0));

            // Let's see if we deal with a comment
            if (record.get(0).startsWith("#")) {

                // We can ignore the comment line and move on
                continue;

            }

            // Let's see if we need to terminate this process
            if (record.get(0).equals(KILL)) {

                System.exit(1);

            }

            // Let's see if we need to create a new Community site
            if (record.get(0).equals(SITE)) {

                // Building the form entity to be posted
                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.setCharset(MIME.UTF8_CHARSET);
                builder.addTextBody(":operation", "social:createSite",
                        ContentType.create("text/plain", MIME.UTF8_CHARSET));
                builder.addTextBody("_charset_", "UTF-8", ContentType.create("text/plain", MIME.UTF8_CHARSET));

                String urlName = null;

                for (int i = 2; i < record.size() - 1; i = i + 2) {

                    if (record.get(i) != null && record.get(i + 1) != null && record.get(i).length() > 0) {

                        String name = record.get(i).trim();
                        String value = record.get(i + 1).trim();
                        if (value.equals("TRUE")) {
                            value = "true";
                        }
                        if (value.equals("FALSE")) {
                            value = "false";
                        }
                        if (name.equals("urlName")) {
                            urlName = value;
                        }
                        if (name.equals(LANGUAGE)) {
                            language = value;
                        }
                        if (name.equals(BANNER)) {

                            File attachment = new File(
                                    csvfile.substring(0, csvfile.indexOf(".csv")) + File.separator + value);
                            builder.addBinaryBody(BANNER, attachment, ContentType.MULTIPART_FORM_DATA,
                                    attachment.getName());

                        } else if (name.equals(THUMBNAIL)) {

                            File attachment = new File(
                                    csvfile.substring(0, csvfile.indexOf(".csv")) + File.separator + value);
                            builder.addBinaryBody(THUMBNAIL, attachment, ContentType.MULTIPART_FORM_DATA,
                                    attachment.getName());

                        } else {

                            builder.addTextBody(name, value,
                                    ContentType.create("text/plain", MIME.UTF8_CHARSET));

                        }
                    }
                }

                // Site creation
                String siteId = doPost(hostname, port, "/content.social.json", "admin", adminPassword,
                        builder.build(), "response/siteId");

                // Site publishing, if there's a publish instance to publish to
                if (!port.equals(altport)) {

                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                    nameValuePairs.add(new BasicNameValuePair("id", "nobot"));
                    nameValuePairs.add(new BasicNameValuePair(":operation", "social:publishSite"));
                    nameValuePairs
                            .add(new BasicNameValuePair("path", "/content/sites/" + urlName + "/" + language));

                    doPost(hostname, port, "/communities/sites.html", "admin", adminPassword,
                            new UrlEncodedFormEntity(nameValuePairs), null);

                    // Wait for site to be available on Publish
                    doWait(hostname, altport, "admin", adminPassword,
                            (siteId != null ? siteId : urlName) + "-groupadministrators");
                }

                continue;
            }

            // Let's see if we need to create a new Tag
            if (record.get(0).equals(TAG)) {

                // Building the form entity to be posted
                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.setCharset(MIME.UTF8_CHARSET);
                builder.addTextBody("_charset_", "UTF-8", ContentType.create("text/plain", MIME.UTF8_CHARSET));

                for (int i = 1; i < record.size() - 1; i = i + 2) {

                    if (record.get(i) != null && record.get(i + 1) != null && record.get(i).length() > 0
                            && record.get(i + 1).length() > 0) {

                        String name = record.get(i).trim();
                        String value = record.get(i + 1).trim();
                        builder.addTextBody(name, value, ContentType.create("text/plain", MIME.UTF8_CHARSET));

                    }
                }

                // Tag creation
                doPost(hostname, port, "/bin/tagcommand", "admin", adminPassword, builder.build(), null);

                continue;
            }

            // Let's see if we need to create a new Community site template, and if we can do it (script run against author instance)
            if (record.get(0).equals(SITETEMPLATE)) {

                // Building the form entity to be posted
                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.setCharset(MIME.UTF8_CHARSET);
                builder.addTextBody(":operation", "social:createSiteTemplate",
                        ContentType.create("text/plain", MIME.UTF8_CHARSET));
                builder.addTextBody("_charset_", "UTF-8", ContentType.create("text/plain", MIME.UTF8_CHARSET));

                for (int i = 2; i < record.size() - 1; i = i + 2) {

                    if (record.get(i) != null && record.get(i + 1) != null && record.get(i).length() > 0) {

                        String name = record.get(i).trim();
                        String value = record.get(i + 1).trim();
                        builder.addTextBody(name, value, ContentType.create("text/plain", MIME.UTF8_CHARSET));

                    }
                }

                // Site template creation
                doPost(hostname, port, "/content.social.json", "admin", adminPassword, builder.build(), null);

                continue;
            }

            // Let's see if we need to create a new Community group
            if (record.get(0).equals(GROUP)) {

                // Building the form entity to be posted
                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.setCharset(MIME.UTF8_CHARSET);
                builder.addTextBody(":operation", "social:createCommunityGroup",
                        ContentType.create("text/plain", MIME.UTF8_CHARSET));
                builder.addTextBody("_charset_", "UTF-8", ContentType.create("text/plain", MIME.UTF8_CHARSET));

                for (int i = 3; i < record.size() - 1; i = i + 2) {

                    if (record.get(i) != null && record.get(i + 1) != null && record.get(i).length() > 0) {

                        String name = record.get(i).trim();
                        String value = record.get(i + 1).trim();
                        if (value.equals("TRUE")) {
                            value = "true";
                        }
                        if (value.equals("FALSE")) {
                            value = "false";
                        }
                        if (name.equals(IMAGE)) {

                            File attachment = new File(
                                    csvfile.substring(0, csvfile.indexOf(".csv")) + File.separator + value);
                            builder.addBinaryBody(IMAGE, attachment, ContentType.MULTIPART_FORM_DATA,
                                    attachment.getName());

                        } else {

                            builder.addTextBody(name, value,
                                    ContentType.create("text/plain", MIME.UTF8_CHARSET));

                        }
                    }
                }

                // Group creation
                String memberGroupId = doPost(hostname, port, record.get(1), getUserName(record.get(2)),
                        getPassword(record.get(2), adminPassword), builder.build(), "response/memberGroupId");

                // Wait for group to be available on Publish, if available
                logger.debug("Waiting for completion of Community Group creation");
                doWait(hostname, port, "admin", adminPassword, memberGroupId);

                continue;

            }

            // Let's see if it's simple Sling Delete request
            if (record.get(0).equals(SLINGDELETE)) {

                doDelete(hostname, port, record.get(1), "admin", adminPassword);

                continue;

            }

            // Let's see if we need to add users to an AEM Group
            if ((record.get(0).equals(GROUPMEMBERS) || record.get(0).equals(SITEMEMBERS))
                    && record.get(GROUP_INDEX_NAME) != null) {

                // Checking if we have a member group for this site
                String groupName = record.get(GROUP_INDEX_NAME);
                if (record.get(0).equals(SITEMEMBERS)) {

                    // Let's fetch the siteId for this Community Site Url
                    String siteConfig = doGet(hostname, port, groupName, "admin", adminPassword, null);

                    try {

                        String siteId = new JSONObject(siteConfig).getString("siteId");
                        if (siteId != null)
                            groupName = "community-" + siteId + "-members";
                        logger.debug("Member group name is " + groupName);

                    } catch (Exception e) {

                        logger.error(e.getMessage());

                    }

                }

                // Pause until the group can found
                doWait(hostname, port, "admin", adminPassword, groupName);

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("filter",
                        "[{\"operation\":\"like\",\"rep:principalName\":\"" + groupName + "\"}]"));
                nameValuePairs.add(new BasicNameValuePair("type", "groups"));
                String groupList = doGet(hostname, port,
                        "/libs/social/console/content/content/userlist.social.0.10.json", "admin",
                        adminPassword, nameValuePairs);

                logger.debug("List of groups" + groupList);

                if (groupList.indexOf(groupName) > 0) {

                    logger.debug("Group was found on " + port);
                    try {
                        JSONArray jsonArray = new JSONObject(groupList).getJSONArray("items");
                        if (jsonArray.length() == 1) {
                            JSONObject jsonObject = jsonArray.getJSONObject(0);
                            String groupPath = jsonObject.getString("path");

                            logger.debug("Group path is " + groupPath);

                            // Constructing a multi-part POST for group membership
                            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                            builder.setCharset(MIME.UTF8_CHARSET);
                            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

                            List<NameValuePair> groupNameValuePairs = buildNVP(record, 2);
                            for (NameValuePair nameValuePair : groupNameValuePairs) {
                                builder.addTextBody(nameValuePair.getName(), nameValuePair.getValue(),
                                        ContentType.create("text/plain", MIME.UTF8_CHARSET));
                            }

                            // Adding the list of group members
                            doPost(hostname, port, groupPath + ".rw.userprops.html", "admin", adminPassword,
                                    builder.build(), null);

                        } else {
                            logger.info("We have more than one match for a group with this name!");
                        }
                    } catch (Exception e) {
                        logger.error(e.getMessage());
                    }
                }

                continue;

            }

            // Let's see if it's user related
            if (record.get(0).equals(USERS)) {

                //First we need to get the path to the user node
                String json = doGet(hostname, port, "/libs/granite/security/currentuser.json",
                        getUserName(record.get(1)), getPassword(record.get(1), adminPassword), null);

                if (json != null) {

                    try {

                        // Fetching the home property
                        String home = new JSONObject(json).getString("home");
                        if (record.get(2).equals(PREFERENCES)) {
                            home = home + "/preferences";
                        } else {
                            home = home + "/profile";
                        }
                        logger.debug(home);

                        // Now we can post all the preferences or the profile
                        List<NameValuePair> nameValuePairs = buildNVP(record, 3);
                        doPost(hostname, port, home, "admin", adminPassword,
                                new UrlEncodedFormEntity(nameValuePairs), null);

                    } catch (Exception e) {
                        logger.error(e.getMessage());
                    }

                }

                continue;

            }

            // Let's see if we deal with a new block of content or just a new entry
            if (record.get(0).equals(CALENDAR) || record.get(0).equals(SLINGPOST)
                    || record.get(0).equals(RATINGS) || record.get(0).equals(BLOG)
                    || record.get(0).equals(JOURNAL) || record.get(0).equals(COMMENTS)
                    || record.get(0).equals(REVIEWS) || record.get(0).equals(FILES)
                    || record.get(0).equals(SUMMARY) || record.get(0).equals(ACTIVITIES)
                    || record.get(0).equals(JOIN) || record.get(0).equals(FOLLOW)
                    || record.get(0).equals(MESSAGE) || record.get(0).equals(ASSET)
                    || record.get(0).equals(AVATAR) || record.get(0).equals(RESOURCE)
                    || record.get(0).equals(LEARNING) || record.get(0).equals(QNA)
                    || record.get(0).equals(FORUM)) {

                // New block of content, we need to reset the processing to first Level
                componentType = record.get(0);
                url[0] = record.get(1);
                urlLevel = 0;

                if (!componentType.equals(SLINGPOST) && reset) {

                    int pos = record.get(1).indexOf("/jcr:content");
                    if (pos > 0)
                        doDelete(hostname, port, "/content/usergenerated" + record.get(1).substring(0, pos),
                                "admin", adminPassword);

                }

                // If the Configure command line flag is set, we try to configure the component with all options enabled
                if (componentType.equals(SLINGPOST) || configure) {

                    String configurePath = getConfigurePath(record.get(1));

                    List<NameValuePair> nameValuePairs = buildNVP(record, 2);
                    if (nameValuePairs.size() > 2) // Only do this when really have configuration settings
                        doPost(hostname, port, configurePath, "admin", adminPassword,
                                new UrlEncodedFormEntity(nameValuePairs), null);

                }

                // We're done with this line, moving on to the next line in the CSV file
                continue;
            }

            // Let's see if we need to indent the list, if it's a reply or a reply to a reply
            if (record.get(1).length() != 1)
                continue; // We need a valid level indicator

            if (Integer.parseInt(record.get(1)) > urlLevel) {
                url[++urlLevel] = location;
                logger.debug("Incremented urlLevel to: " + urlLevel + ", with a new location:" + location);
            } else if (Integer.parseInt(record.get(1)) < urlLevel) {
                urlLevel = Integer.parseInt(record.get(1));
                logger.debug("Decremented urlLevel to: " + urlLevel);
            }

            // Get the credentials or fall back to password
            String password = getPassword(record.get(0), adminPassword);
            String userName = getUserName(record.get(0));

            // Adding the generic properties for all POST requests
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

            if (!componentType.equals(RESOURCE))
                nameValuePairs.add(new BasicNameValuePair("id", "nobot"));

            nameValuePairs.add(new BasicNameValuePair("_charset_", "UTF-8"));

            // Setting some specific fields depending on the content type
            if (componentType.equals(COMMENTS)) {

                nameValuePairs.add(new BasicNameValuePair(":operation", "social:createComment"));
                nameValuePairs.add(new BasicNameValuePair("message", record.get(2)));

            }

            // Creates a forum post (or reply)
            if (componentType.equals(FORUM)) {

                nameValuePairs.add(new BasicNameValuePair(":operation", "social:createForumPost"));
                nameValuePairs.add(new BasicNameValuePair("subject", record.get(2)));
                nameValuePairs.add(new BasicNameValuePair("message", record.get(3)));

            }

            // Follows a user (followedId) for the user posting the request
            if (componentType.equals(FOLLOW)) {

                nameValuePairs.add(new BasicNameValuePair(":operation", "social:follow"));
                nameValuePairs.add(new BasicNameValuePair("userId", "/social/authors/" + userName));
                nameValuePairs.add(new BasicNameValuePair("followedId", "/social/authors/" + record.get(2)));

            }

            // Uploading Avatar picture
            if (componentType.equals(AVATAR)) {

                nameValuePairs.add(new BasicNameValuePair(":operation", "social:changeAvatar"));

            }

            // Joins a user (posting the request) to a Community Group (path)
            if (componentType.equals(JOIN)) {
                nameValuePairs.add(new BasicNameValuePair(":operation", "social:joinCommunityGroup"));
                int pos = url[0].indexOf("/configuration.social.json");
                if (pos > 0)
                    nameValuePairs.add(new BasicNameValuePair("path", url[0].substring(0, pos) + ".html"));
                else
                    continue; // Invalid record
            }

            // Creates a new private message
            if (componentType.equals(MESSAGE)) {
                nameValuePairs.add(new BasicNameValuePair(":operation", "social:createMessage"));
                nameValuePairs.add(new BasicNameValuePair("sendMail", "Sending..."));
                nameValuePairs.add(new BasicNameValuePair("content", record.get(4)));
                nameValuePairs.add(new BasicNameValuePair("subject", record.get(3)));
                nameValuePairs.add(new BasicNameValuePair("serviceSelector", "/bin/community"));
                nameValuePairs.add(new BasicNameValuePair("to", "/social/authors/" + record.get(2)));
                nameValuePairs.add(new BasicNameValuePair("userId", "/social/authors/" + record.get(2)));
                nameValuePairs.add(new BasicNameValuePair(":redirect", "//messaging.html"));
                nameValuePairs.add(new BasicNameValuePair(":formid", "generic_form"));
                nameValuePairs.add(new BasicNameValuePair(":formstart",
                        "/content/sites/communities/messaging/compose/jcr:content/content/primary/start"));
            }

            // Creates a file or a folder
            if (componentType.equals(FILES)) {

                // Top level is always assumed to be a folder, second level files, and third and subsequent levels comments on files
                if (urlLevel == 0) {
                    nameValuePairs.add(new BasicNameValuePair(":operation", "social:createFileLibraryFolder"));
                    nameValuePairs.add(new BasicNameValuePair("name", record.get(2)));
                    nameValuePairs.add(new BasicNameValuePair("message", record.get(3)));
                } else if (urlLevel == 1) {
                    nameValuePairs.add(new BasicNameValuePair(":operation", "social:createComment"));
                }

            }

            // Creates a question, a reply or mark a reply as the best answer
            if (componentType.equals(QNA)) {
                if (urlLevel == 0) {
                    nameValuePairs.add(new BasicNameValuePair(":operation", "social:createQnaPost"));
                    nameValuePairs.add(new BasicNameValuePair("subject", record.get(2)));
                    nameValuePairs.add(new BasicNameValuePair("message", record.get(3)));
                } else if (urlLevel == 1) {
                    nameValuePairs.add(new BasicNameValuePair(":operation", "social:createQnaPost"));
                    nameValuePairs.add(new BasicNameValuePair("message", record.get(3)));
                } else if (urlLevel == 2) {
                    nameValuePairs.add(new BasicNameValuePair(":operation", "social:selectAnswer"));
                }
            }

            // Creates an article or a comment
            if (componentType.equals(JOURNAL) || componentType.equals(BLOG)) {

                nameValuePairs.add(new BasicNameValuePair(":operation", "social:createJournalComment"));
                nameValuePairs.add(new BasicNameValuePair("subject", record.get(2)));
                StringBuffer message = new StringBuffer("<p>" + record.get(3) + "</p>");

                //We might have more paragraphs to add to the blog or journal article
                for (int i = 6; i < record.size(); i++) {
                    if (record.get(i).length() > 0) {
                        message.append("<p>" + record.get(i) + "</p>");
                    }
                }

                //We might have some tags to add to the blog or journal article
                if (record.get(5).length() > 0) {
                    nameValuePairs.add(new BasicNameValuePair("tags", record.get(5)));
                }

                nameValuePairs.add(new BasicNameValuePair("message", message.toString()));

            }

            // Creates a review or a comment
            if (componentType.equals(REVIEWS)) {

                nameValuePairs.add(new BasicNameValuePair("message", record.get(2)));

                // This might be a top level review, or a comment on a review or another comment
                if (urlLevel == 0) {
                    nameValuePairs.add(new BasicNameValuePair(":operation", "social:createReview"));
                    nameValuePairs.add(new BasicNameValuePair("ratings", record.get(3)));
                    if (record.size() > 4 && record.get(4).length() > 0) {
                        // If we are dealing with a non-existent resource, then the design drives the behavior
                        nameValuePairs.add(new BasicNameValuePair("scf:resourceType",
                                "social/reviews/components/hbs/reviews"));
                        nameValuePairs.add(new BasicNameValuePair("scf:included", record.get(4)));
                    }
                } else {
                    nameValuePairs.add(new BasicNameValuePair(":operation", "social:createComment"));
                }

            }

            // Creates a rating
            if (componentType.equals(RATINGS)) {

                nameValuePairs.add(new BasicNameValuePair(":operation", "social:postTallyResponse"));
                nameValuePairs.add(new BasicNameValuePair("tallyType", "Rating"));
                nameValuePairs.add(new BasicNameValuePair("response", record.get(2)));

            }

            // Creates a DAM asset
            if (componentType.equals(ASSET) && record.get(ASSET_INDEX_NAME).length() > 0) {

                nameValuePairs.add(new BasicNameValuePair("fileName", record.get(ASSET_INDEX_NAME)));

            }

            // Creates an enablement resource
            if (componentType.equals(RESOURCE)) {

                nameValuePairs.add(new BasicNameValuePair(":operation", "se:createResource"));

                List<NameValuePair> otherNameValuePairs = buildNVP(record, RESOURCE_INDEX_PROPERTIES);
                nameValuePairs.addAll(otherNameValuePairs);

                // Adding the site
                nameValuePairs.add(new BasicNameValuePair("site",
                        "/content/sites/" + record.get(RESOURCE_INDEX_SITE) + "/resources/en"));

                // Building the cover image fragment
                if (record.get(RESOURCE_INDEX_THUMBNAIL).length() > 0) {
                    nameValuePairs.add(new BasicNameValuePair("cover-image", doThumbnail(hostname, port,
                            adminPassword, csvfile, record.get(RESOURCE_INDEX_THUMBNAIL))));
                } else {
                    nameValuePairs.add(new BasicNameValuePair("cover-image", ""));
                }

                // Building the asset fragment
                String coverPath = "/content/dam/" + record.get(RESOURCE_INDEX_SITE) + "/resource-assets/"
                        + record.get(2) + "/jcr:content/renditions/cq5dam.thumbnail.319.319.png";
                String coverSource = "dam";
                String assets = "[{\"cover-img-path\":\"" + coverPath + "\",\"thumbnail-source\":\""
                        + coverSource
                        + "\",\"asset-category\":\"enablementAsset:dam\",\"resource-asset-name\":null,\"state\":\"A\",\"asset-path\":\"/content/dam/"
                        + record.get(RESOURCE_INDEX_SITE) + "/resource-assets/" + record.get(2) + "\"}]";
                nameValuePairs.add(new BasicNameValuePair("assets", assets));

                logger.debug("assets:" + assets);

            }

            // Creates a learning path
            if (componentType.equals(LEARNING)) {

                nameValuePairs.add(new BasicNameValuePair(":operation", "se:editLearningPath"));

                List<NameValuePair> otherNameValuePairs = buildNVP(record, RESOURCE_INDEX_PROPERTIES);
                nameValuePairs.addAll(otherNameValuePairs);

                // Adding the site
                nameValuePairs.add(new BasicNameValuePair("site",
                        "/content/sites/" + record.get(RESOURCE_INDEX_SITE) + "/resources/en"));

                // Building the cover image fragment
                if (record.get(RESOURCE_INDEX_THUMBNAIL).length() > 0) {
                    nameValuePairs.add(new BasicNameValuePair("card-image", doThumbnail(hostname, port,
                            adminPassword, csvfile, record.get(RESOURCE_INDEX_THUMBNAIL))));
                }

                // Building the learning path fragment
                StringBuffer assets = new StringBuffer("[\"");
                if (learningpaths.get(record.get(2)) != null) {

                    ArrayList<String> paths = learningpaths.get(record.get(2));
                    int i = 0;
                    for (String path : paths) {
                        assets.append("{\\\"type\\\":\\\"linked-resource\\\",\\\"path\\\":\\\"");
                        assets.append(path);
                        assets.append("\\\"}");
                        if (i++ < paths.size() - 1) {
                            assets.append("\",\"");
                        }
                    }

                } else {
                    logger.debug("No asset for this learning path");
                }
                assets.append("\"]");
                nameValuePairs.add(new BasicNameValuePair("learningpath-items", assets.toString()));
                logger.debug("Learning path:" + assets.toString());

            }

            // Creates a calendar event
            if (componentType.equals(CALENDAR)) {

                nameValuePairs.add(new BasicNameValuePair(":operation", "social:createEvent"));
                try {
                    JSONObject event = new JSONObject();

                    // Building the JSON fragment for a new calendar event
                    event.accumulate("subject", record.get(2));
                    event.accumulate("message", record.get(3));
                    event.accumulate("location", record.get(4));
                    event.accumulate("tags", "");
                    event.accumulate("undefined", "update");

                    String startDate = record.get(5);
                    startDate = startDate.replaceAll("YYYY",
                            Integer.toString(Calendar.getInstance().get(Calendar.YEAR)));
                    startDate = startDate.replaceAll("MM",
                            Integer.toString(1 + Calendar.getInstance().get(Calendar.MONTH)));
                    event.accumulate("start", startDate);

                    String endDate = record.get(6);
                    endDate = endDate.replaceAll("YYYY",
                            Integer.toString(Calendar.getInstance().get(Calendar.YEAR)));
                    endDate = endDate.replaceAll("MM",
                            Integer.toString(1 + Calendar.getInstance().get(Calendar.MONTH)));
                    event.accumulate("end", endDate);
                    nameValuePairs.add(new BasicNameValuePair("event", event.toString()));

                } catch (Exception ex) {

                    logger.error(ex.getMessage());

                }

            }

            // Constructing a multi-part POST request
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(MIME.UTF8_CHARSET);
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            for (NameValuePair nameValuePair : nameValuePairs) {
                builder.addTextBody(nameValuePair.getName(), nameValuePair.getValue(),
                        ContentType.create("text/plain", MIME.UTF8_CHARSET));
            }

            // See if we have attachments for this new post - or some other actions require a form nonetheless
            if ((componentType.equals(ASSET) || componentType.equals(AVATAR) || componentType.equals(FORUM)
                    || (componentType.equals(JOURNAL)) || componentType.equals(BLOG)) && record.size() > 4
                    && record.get(ASSET_INDEX_NAME).length() > 0) {

                File attachment = new File(csvfile.substring(0, csvfile.indexOf(".csv")) + File.separator
                        + record.get(ASSET_INDEX_NAME));

                ContentType ct = ContentType.MULTIPART_FORM_DATA;
                if (record.get(ASSET_INDEX_NAME).indexOf(".mp4") > 0) {
                    ct = ContentType.create("video/mp4", MIME.UTF8_CHARSET);
                } else if (record.get(ASSET_INDEX_NAME).indexOf(".jpg") > 0
                        || record.get(ASSET_INDEX_NAME).indexOf(".jpeg") > 0) {
                    ct = ContentType.create("image/jpeg", MIME.UTF8_CHARSET);
                } else if (record.get(ASSET_INDEX_NAME).indexOf(".png") > 0) {
                    ct = ContentType.create("image/png", MIME.UTF8_CHARSET);
                } else if (record.get(ASSET_INDEX_NAME).indexOf(".pdf") > 0) {
                    ct = ContentType.create("application/pdf", MIME.UTF8_CHARSET);
                } else if (record.get(ASSET_INDEX_NAME).indexOf(".zip") > 0) {
                    ct = ContentType.create("application/zip", MIME.UTF8_CHARSET);
                }
                builder.addBinaryBody("file", attachment, ct, attachment.getName());
                logger.debug("Adding file to payload with name: " + attachment.getName() + " and type: "
                        + ct.getMimeType());

            }

            // If it's a resource or a learning path, we need the path to the resource for subsequent publishing
            String jsonElement = "location";
            if (componentType.equals(RESOURCE)) {
                jsonElement = "changes/argument";
            }
            if (componentType.equals(LEARNING)) {
                jsonElement = "path";
            }
            if (componentType.equals(ASSET)) {
                jsonElement = null;
            }

            // This call generally returns the path to the content fragment that was just created
            location = Loader.doPost(hostname, port, url[urlLevel], userName, password, builder.build(),
                    jsonElement);

            // If we are loading a DAM asset, we are waiting for all renditions to be generated before proceeding
            if (componentType.equals(ASSET)) {
                int pathIndex = url[urlLevel].lastIndexOf(".createasset.html");
                if (pathIndex > 0)
                    doWaitPath(hostname, port, adminPassword, url[urlLevel].substring(0, pathIndex) + "/"
                            + record.get(ASSET_INDEX_NAME) + "/jcr:content/renditions", "nt:file");
            }

            // Let's see if it needs to be added to a learning path
            if (componentType.equals(RESOURCE) && record.get(RESOURCE_INDEX_PATH).length() > 0
                    && location != null) {

                // Adding the location to a list of a resources for this particular Learning Path
                if (learningpaths.get(record.get(RESOURCE_INDEX_PATH)) == null)
                    learningpaths.put(record.get(RESOURCE_INDEX_PATH), new ArrayList<String>());
                logger.debug("Adding resource to Learning path: " + record.get(RESOURCE_INDEX_PATH));
                ArrayList<String> locations = learningpaths.get(record.get(RESOURCE_INDEX_PATH));
                locations.add(location);
                learningpaths.put(record.get(RESOURCE_INDEX_PATH), locations);

            }

            // If it's a Learning Path, we publish it when possible
            if (componentType.equals(LEARNING) && !port.equals(altport) && location != null) {

                // Publishing the learning path 
                List<NameValuePair> publishNameValuePairs = new ArrayList<NameValuePair>();
                publishNameValuePairs.add(new BasicNameValuePair(":operation", "se:publishEnablementContent"));
                publishNameValuePairs.add(new BasicNameValuePair("replication-action", "activate"));
                logger.debug("Publishing a learning path from: " + location);
                Loader.doPost(hostname, port, location, userName, password,
                        new UrlEncodedFormEntity(publishNameValuePairs), null);

                // Waiting for the learning path to be published
                Loader.doWait(hostname, altport, "admin", adminPassword,
                        location.substring(1 + location.lastIndexOf("/")) // Only search for groups with the learning path in it
                );

                // Decorate the resources within the learning path with comments and ratings, randomly generated
                ArrayList<String> paths = learningpaths.get(record.get(2));
                for (String path : paths) {
                    doDecorate(hostname, altport, path, record, analytics);
                }

            }

            // If it's an Enablement Resource, a lot of things need to happen...
            // Step 1. If it's a SCORM resource, we wait for the SCORM metadata workflow to be complete before proceeding
            // Step 2. We publish the resource
            // Step 3. We set a new first published date on the resource (3 weeks earlier) so that reporting data is more meaningful
            // Step 4. We wait for the resource to be available on publish (checking that associated groups are available)
            // Step 5. We retrieve the json for the resource on publish to retrieve the Social endpoints
            // Step 6. We post ratings and comments for each of the enrollees on publish
            if (componentType.equals(RESOURCE) && !port.equals(altport) && location != null) {

                // Wait for the data to be fully copied
                doWaitPath(hostname, port, adminPassword, location + "/assets/asset", "nt:file");

                // If we are dealing with a SCORM asset, we wait a little bit before publishing the resource to that the SCORM workflow is completed 
                if (record.get(2).indexOf(".zip") > 0) {
                    doSleep(10000, "SCORM Resource, waiting for workflow to complete");
                }

                // Publishing the resource 
                List<NameValuePair> publishNameValuePairs = new ArrayList<NameValuePair>();
                publishNameValuePairs.add(new BasicNameValuePair(":operation", "se:publishEnablementContent"));
                publishNameValuePairs.add(new BasicNameValuePair("replication-action", "activate"));
                logger.debug("Publishing a resource from: " + location);
                Loader.doPost(hostname, port, location, userName, password,
                        new UrlEncodedFormEntity(publishNameValuePairs), null);

                // Waiting for the resource to be published
                Loader.doWait(hostname, altport, "admin", adminPassword,
                        location.substring(1 + location.lastIndexOf("/")) // Only search for groups with the resource path in it
                );

                // Setting the first published timestamp so that reporting always comes with 3 weeks of data after building a new demo instance
                DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.DATE, REPORTINGDAYS);
                List<NameValuePair> publishDateNameValuePairs = new ArrayList<NameValuePair>();
                publishDateNameValuePairs
                        .add(new BasicNameValuePair("date-first-published", dateFormat.format(cal.getTime())));
                logger.debug("Setting the publish date for a resource from: " + location);
                doPost(hostname, port, location, userName, password,
                        new UrlEncodedFormEntity(publishDateNameValuePairs), null);

                // Adding comments and ratings for this resource
                doDecorate(hostname, altport, location, record, analytics);

            }

        }
    } catch (IOException e) {

        logger.error(e.getMessage());

    }

}

From source file:Main.java

private static String removeLastChar(String str) {
    return str.substring(0, str.length() - 1);
}

From source file:Main.java

public static String removeCharAt(String s, int pos) {
    return s.substring(0, pos) + s.substring(pos + 1);
}

From source file:Main.java

private static String capitalizeFirstLetter(String in) {
    return in.substring(0, 1).toUpperCase() + in.substring(1);
}

From source file:Main.java

public static String replaceCharAt(String s, int pos, char c) {
    return s.substring(0, pos) + c + s.substring(pos + 1);
}

From source file:Main.java

License:asdf

public static String removeCharAt(int pos, String text) {
    return text.substring(0, pos) + text.substring(pos + 1, text.length());
}

From source file:Main.java

private static String delQuot(String s) {
    return s.substring(s.indexOf('"') + 1, s.lastIndexOf('"'));
}

From source file:Main.java

public static String capitalize(String s) {
    return s.substring(0, 1).toUpperCase() + s.substring(1);
}