Example usage for java.util HashMap size

List of usage examples for java.util HashMap size

Introduction

In this page you can find the example usage for java.util HashMap size.

Prototype

int size

To view the source code for java.util HashMap size.

Click Source Link

Document

The number of key-value mappings contained in this map.

Usage

From source file:com.stgmastek.core.logic.ExecutionOrder.java

/**
 * Static method to setup the execution order.
 * This method essentially looks up in to the setup table BATCH_COLUMN_MAP to 
 * get the details.Using the details it would setup the execution order for the batch 
 * Once the execution order is set, it sets the order into the {@link BatchInfo#setOrderedMap(TreeMap)}
 * for all other objects to derive knowledge from. 
 * Note: The batch could be run for - /* w  w w .  j ava 2  s .c  o  m*/
 * <OL>
 * <LI> For a date i.e. all entities and all values for those entities. 
 * <LI> For an entity i.e. batch for only policy records and all its values 
 *        i.e. P1, P2 ... Pn
 * <LI> For a single object identified as GENERAL type of job with a 
 *       sequence number i.e. JOB_SCHEDULE.job_seq
 * <LI> For only Meta events like ALL PRE and ALL POST
 * <LI> For any combination of above, a few given - 
 *       <UL>
 *          <LI> Policy P1 and ALL PRE 
 *          <LI> ALL Agency records and Policy P1
 *         <LI> Policy P1 and Agency A1
 *       </UL>  
 * </OL>
 *  
 * Every step has inline comments associated with it. 
 * 
 * @param batchContext
 *         The context for the batch 
 * @return true 
 *          If the setup is done successfully 
 * @throws BatchException
 *          Any database I/O exception 
 */
public synchronized static Boolean setExecutionOrder(BatchContext batchContext) throws BatchException {

    //Get request parameters
    HashMap<String, Object> params = batchContext.getRequestParams().getProcessRequestParams();

    //Check whether it is a date batch run or specific batch run         
    if (params.size() < 1) {
        batchContext.getBatchInfo().setDateRun(true);
    }
    Connection con = batchContext.getBATCHConnection();
    IBatchDao bDao = DaoFactory.getBatchDao();
    try {
        //Query the setup table to get the setup values
        LookupTable lookupTable = bDao.getLookupTable(con);
        Map<String, String> orderByLookupTable = bDao.getOrderByLookupTable(con);

        TreeMap<Integer, EntityParams> orderedMap = new TreeMap<Integer, EntityParams>();

        //If it is date batch run, then for all entities, populate "ALL" 
        if (batchContext.getBatchInfo().isDateRun()) {
            Iterator<String> lTableIter = lookupTable.keySet().iterator();
            while (lTableIter.hasNext()) {
                String entity = lTableIter.next();
                params.put(entity + "_1", "ALL");
            }
        }

        //Iterate over each parameters set 
        for (Entry<String, Object> entry : params.entrySet()) {
            String paramName = entry.getKey();
            Object paramValue = entry.getValue();
            if (logger.isDebugEnabled()) {
                logger.debug("In ExecutionOrder >>>> paramName  ==>" + paramName);
            }

            String entity = null;

            //Strip the last occurrence of _ and get the entity name
            entity = paramName.substring(0, paramName.lastIndexOf("_"));
            if (logger.isDebugEnabled()) {
                logger.debug("In ExecutionOrder >>>> Entity  ==>" + entity);
            }
            //Validate whether the entity is setup appropriately in 
            //the BATCH_COLUMN_MAP table 
            if (!lookupTable.containsKey(entity)) {
                //If the entity is not set, raise an exception and exit 
                throw new BatchException("The entity " + entity + " is not set up in the COLUMN_MAP table.");
            } else {

                //Get the lookup record 
                //Once found, get the details and set it against the entity 
                List<ColumnLookup> lookupColumns = lookupTable.get(entity);
                Integer order = lookupColumns.get(0).getPrecedenceOrder();
                if (!orderedMap.containsKey(order)) {
                    EntityParams entityParams = new EntityParams(entity);
                    orderedMap.put(order, entityParams);
                }
                EntityParams entityParams = orderedMap.get(order);
                entityParams.setLookupColumns(lookupColumns);
                entityParams.setOrderByMap(orderByLookupTable);//Added on 01-OCT-2013 - Mandar

                //Check 'ALL' or for specific entity values. 
                //Note: Batch could be run for a date i.e. all entities (and all values) 
                // or for any combination of entity and values 
                if (!paramValue.equals("ALL")) {
                    List<GroupInfo> list = entityParams.getValues();
                    //check if all exists. If exists do not write the new value
                    if (list.size() == 0 || !list.get(0).getEntityValue().equals("ALL"))
                        entityParams.getValues().add(new GroupInfo((String) paramValue));
                } else {
                    entityParams.setAll(new GroupInfo((String) paramValue));
                }
            }
        }

        batchContext.getBatchInfo().setOrderedMap(orderedMap);
    } finally {
        bDao.releaseResources(null, null, con);
    }

    return true;
}

From source file:com.likya.myra.jef.utils.JobQueueOperations.java

public static boolean persistDisabledJobQueue(ConfigurationManager configurationManager,
        HashMap<String, String> jobQueue) {

    FileOutputStream fos = null;/*from  ww  w  . j  ava  2s  .c  om*/
    ObjectOutputStream out = null;

    if (jobQueue.size() == 0) {
        return true;
    }

    try {

        File fileTemp = new File(configurationManager.getFileToPersist() + "_disabled.temp"); //$NON-NLS-1$
        fos = new FileOutputStream(fileTemp);

        out = new ObjectOutputStream(fos);

        out.writeObject(jobQueue);
        out.close();

        File file = new File(configurationManager.getFileToPersist() + "_disabled");

        if (file.exists()) {
            file.delete();
        }

        fileTemp.renameTo(file);

    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return true;

}

From source file:com.wso2telco.gsma.authenticators.util.OutboundMessage.java

/**
 * Prepare the USSD/SMS message from database config table for service provider, operator specific message or
 * default message stored in mobile-connect.xml. Message template can have ${variable} and relevant data to apply
 * to the template should be passed with map parameter.
 *
 * @param clientId    sp client id/*w w w .j a  v  a2  s .c  o  m*/
 * @param messageType ussd/sms message type
 * @param map         additional variable data map for the message template
 * @param operator    operator name
 * @return prepared ussd message
 */
public static String prepare(String clientId, MessageType messageType, HashMap<String, String> map,
        String operator) {

    MobileConnectConfig.OperatorSpecificMessage operatorSpecificMessage = null;
    String template = null;

    Map<String, String> data = new HashMap<String, String>();
    // add default map values here
    // data.put("key", "value");

    if (map != null && map.size() > 0) {
        for (Map.Entry<String, String> entry : map.entrySet()) {
            data.put(entry.getKey(), entry.getValue());
        }
    }

    // Load operator specific message from hash map
    if (operator != null) {
        if (messageType == MessageType.USSD_LOGIN || messageType == MessageType.USSD_REGISTRATION) {
            operatorSpecificMessage = operatorSpecificMessageMap.get(operator);
        } else if (messageType == MessageType.USSD_PIN_LOGIN
                || messageType == MessageType.USSD_PIN_REGISTRATION) {
            operatorSpecificMessage = operatorSpecificPinMessageMap.get(operator);
        } else if (messageType == MessageType.SMS_LOGIN || messageType == MessageType.SMS_REGISTRATION) {
            operatorSpecificMessage = operatorSpecificSmsMessageMap.get(operator);
        } else if (messageType == MessageType.SMS_OTP) {
            operatorSpecificMessage = operatorSpecificSmsotpMessageMap.get(operator);
        }

        data.put("operator", operator);
    }

    // RULE 1 : first try to get login/registration messages from sp config table
    if (messageType == MessageType.USSD_LOGIN) {
        template = spConfigService.getUSSDLoginMessage(clientId);
    } else if (messageType == MessageType.USSD_REGISTRATION) {
        template = spConfigService.getUSSDRegistrationMessage(clientId);
    } else if (messageType == MessageType.USSD_PIN_LOGIN) {
        template = spConfigService.getUSSDPinLoginMessage(clientId);
    } else if (messageType == MessageType.USSD_PIN_REGISTRATION) {
        template = spConfigService.getUSSDPinRegistrationMessage(clientId);
    } else if (messageType == MessageType.SMS_LOGIN) {
        template = spConfigService.getSMSLoginMessage(clientId);
    } else if (messageType == MessageType.SMS_REGISTRATION) {
        template = spConfigService.getSMSRegistrationMessage(clientId);
    } else if (messageType == MessageType.SMS_OTP) {
        template = spConfigService.getSMSOTPMessage(clientId);
    }

    if (template == null) {
        // RULE 2 : if message template is not found, try loading them from operator specific config from xml
        if (operatorSpecificMessage != null) {
            if (messageType == MessageType.USSD_LOGIN) {
                template = operatorSpecificMessage.getLoginMessage();
            } else if (messageType == MessageType.USSD_REGISTRATION) {
                template = operatorSpecificMessage.getRegistrationMessage();
            } else if (messageType == MessageType.USSD_PIN_LOGIN) {
                template = operatorSpecificMessage.getLoginMessage();
            } else if (messageType == MessageType.USSD_PIN_REGISTRATION) {
                template = operatorSpecificMessage.getRegistrationMessage();
            } else if (messageType == MessageType.SMS_LOGIN) {
                template = operatorSpecificMessage.getLoginMessage();
            } else if (messageType == MessageType.SMS_REGISTRATION) {
                template = operatorSpecificMessage.getRegistrationMessage();
            } else if (messageType == MessageType.SMS_OTP) {
                template = operatorSpecificMessage.getSmsotpMessage();
            }
        } else {
            // RULE 3 : if no operator specific message is found, try loading from common messages
            if (messageType == MessageType.USSD_LOGIN) {
                template = ussdConfig.getUssdLoginMessage();
            } else if (messageType == MessageType.USSD_REGISTRATION) {
                template = ussdConfig.getUssdRegistrationMessage();
            } else if (messageType == MessageType.USSD_PIN_LOGIN) {
                template = ussdConfig.getPinLoginMessage();
            } else if (messageType == MessageType.USSD_PIN_REGISTRATION) {
                template = ussdConfig.getPinRegistrationMessage();
            } else if (messageType == MessageType.SMS_LOGIN) {
                template = smsConfig.getLoginMessage();
            } else if (messageType == MessageType.SMS_REGISTRATION) {
                template = smsConfig.getRegistrationMessage();
            } else if (messageType == MessageType.SMS_OTP) {
                template = smsConfig.getSmsotpMessage();
            }
        }
    }

    return template == null ? null : StrSubstitutor.replace(template, data);
}

From source file:nl.wur.plantbreeding.www.marker2seq.GoDistribution.java

/**
 * Generate the Pie chart for a set of given Go terms.
 * @param distrib a HashMap of GO name and GO frequency
 * @param title the title of the GO graph
 * @param url the url used for the tooltips
 * @param session the HttpSession used to save the file
 * @param legend Print the legend or not
 * @param tooltips Add tooltip or not/*  ww  w. j  a v a  2s .c om*/
 * @param urls Add urls or not (link in the graph)
 * @param max Maximum number of item to display
 * @return a list containing the filename and the map for the figure
 * @throws IOException when something happens while writting the image
 */
public static String[] generateDistribution(final HashMap<String, Integer> distrib, final String title,
        final String url, final HttpSession session, final boolean legend, final boolean tooltips,
        final boolean urls, final int max) throws IOException {

    final PieChart piec = new PieChart();
    final PieDataset piedata = piec.createDataset(distrib);

    final JFreeChart chart = piec.createChart(piedata, title, legend, tooltips, urls);
    final PiePlot plot = (PiePlot) chart.getPlot();
    if (distrib.size() >= max) {
        plot.setLabelGenerator(null);
    }
    plot.setURLGenerator(new StandardPieURLGenerator(url, "section"));

    final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());

    final String filename = ServletUtilities.saveChartAsPNG(chart, 500, 400, info, session);

    final String map = ChartUtilities.getImageMap(filename, info);

    final String[] output = { filename, map };
    return output;
}

From source file:eu.sisob.uma.crawler.MatrixResultBuilder.java

public static void writeResultsList(File file, HashMap<String, Integer> universities_axis,
        HashMap<String, Integer> dept_axis,
        HashMap<String, HashMap<String, Map.Entry<Integer, Integer>>> resultsMatrix) {
    Map.Entry<Integer, Integer>[][] matrix = (Map.Entry<Integer, Integer>[][]) new Map.Entry[universities_axis
            .size()][dept_axis.size()];//from  w w w .j  ava 2 s  .  com
    String[] cols = new String[universities_axis.size()];
    String[] rows = new String[dept_axis.size()];

    int total_researchers = 0;
    int success_researchers = 0;

    for (String j : resultsMatrix.keySet()) {
        cols[universities_axis.get(j)] = j;
        for (String k : resultsMatrix.get(j).keySet()) {
            rows[dept_axis.get(k)] = k;
        }
    }

    for (String j : resultsMatrix.keySet()) {
        for (String k : resultsMatrix.get(j).keySet()) {
            Map.Entry<Integer, Integer> r = resultsMatrix.get(j).get(k);

            int x = universities_axis.get(j);
            int y = dept_axis.get(k);

            matrix[x][y] = r;

            success_researchers += r.getKey();
            total_researchers += r.getValue();
        }
    }

    String s = "\"UNIVERSITY\"\t\"SUBJECT\"\t\"RESEARCHERS FOUND\"\t\"TOTAL RESEARCHERS\"";
    s += "\r\n";

    try {
        FileUtils.write(file, s, "UTF-8", false);
    } catch (IOException ex) {
        ProjectLogger.LOGGER.error("Error writing results list");
    }

    s = "";

    for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix[i].length; j++) {
            if (matrix[i][j] != null) {
                s += "\"" + cols[i] + "\"\t\"" + rows[j] + "\"\t" + matrix[i][j].getKey() + "\t"
                        + matrix[i][j].getValue();
                s += "\r\n";
            }
        }

        if (s.length() > 1000) {
            try {
                FileUtils.write(file, s, "UTF-8", true);
            } catch (IOException ex) {
                ProjectLogger.LOGGER.error("Error writing matrix results");
            }
            s = "";
        }
    }

    s += "\r\nRESEARCHERS FOUND\t" + success_researchers;
    s += "\r\nNUMBER OF RESEARCHERS\t" + total_researchers;

    if (!s.equals("")) {
        try {
            FileUtils.write(file, s, "UTF-8", true);
        } catch (IOException ex) {
            ProjectLogger.LOGGER.error("Error writing matrix results");
        }
    }
}

From source file:eu.sisob.uma.crawler.MatrixResultBuilder.java

public static void writeResultsMatrix(File file, HashMap<String, Integer> universities_axis,
        HashMap<String, Integer> dept_axis,
        HashMap<String, HashMap<String, Map.Entry<Integer, Integer>>> resultsMatrix) {
    Map.Entry<Integer, Integer>[][] matrix = (Map.Entry<Integer, Integer>[][]) new Map.Entry[universities_axis
            .size()][dept_axis.size()];/*  w  w w . j av a2 s .  c  o m*/
    String[] cols = new String[universities_axis.size()];
    String[] rows = new String[dept_axis.size()];

    int total_researchers = 0;
    int success_researchers = 0;

    for (String j : resultsMatrix.keySet()) {
        cols[universities_axis.get(j)] = j;
        for (String k : resultsMatrix.get(j).keySet()) {
            rows[dept_axis.get(k)] = k;
        }
    }

    for (String j : resultsMatrix.keySet()) {
        for (String k : resultsMatrix.get(j).keySet()) {
            Map.Entry<Integer, Integer> r = resultsMatrix.get(j).get(k);

            int x = universities_axis.get(j);
            int y = dept_axis.get(k);

            matrix[x][y] = r;

            success_researchers += r.getKey();
            total_researchers += r.getValue();
        }
    }

    try {
        FileUtils.write(file, "RESULTS TABLE\r\n", "UTF-8", false);
    } catch (IOException ex) {
        ProjectLogger.LOGGER.error("Error writing results matrix");
    }

    String s = "#\t";
    for (int i = 0; i < rows.length; i++) {
        s += rows[i] + "\t";
    }
    s += "\r\n";
    for (int i = 0; i < matrix.length; i++) {
        s += cols[i] + "\t";
        for (int j = 0; j < matrix[i].length; j++) {
            if (matrix[i][j] != null)
                s += matrix[i][j].getKey() + "/" + matrix[i][j].getValue() + "\t";
            else
                s += "\t";
        }
        s += "\r\n";
        if (s.length() > 1000) {
            try {
                FileUtils.write(file, s, "UTF-8", true);
            } catch (IOException ex) {
                ProjectLogger.LOGGER.error("Error writing matrix results");
            }
            s = "";
        }
    }

    if (!s.equals("")) {
        try {
            FileUtils.write(file, s, "UTF-8", true);
        } catch (IOException ex) {
            ProjectLogger.LOGGER.error("Error writing matrix results");
        }
    }

    s = "\r\nTOTAL RESEARCHER = " + total_researchers + " - RESEARCHERS WITH RESULTS: " + success_researchers;
    try {
        FileUtils.write(file, s, "UTF-8", true);
    } catch (IOException ex) {
        ProjectLogger.LOGGER.error("Error writing matrix results");
    }
}

From source file:fr.paris.lutece.plugins.workflow.modules.ticketingfacilfamilles.web.task.AutomaticAssignmentTaskComponent.java

/**
 * build and return display Config Form Url
 * //  w  ww  . ja v a2 s . c  o m
 * @param task
 *            task
 * @param mapParams
 *            map of parameters to add to redirect url
 * @return display Config Form Url
 */
private static String getDisplayConfigFormUrl(ITask task, HashMap<String, String> mapParams) {
    UrlItem url = new UrlItem(URL_DISPLAY_CONFIG_FORM);
    url.addParameter(PARAMETER_TASK_ID, task.getId());

    if ((mapParams != null) && (mapParams.size() > 0)) {
        for (Map.Entry<String, String> entry : mapParams.entrySet()) {
            url.addParameter(entry.getKey(), entry.getValue());
        }
    }

    return url.toString();
}

From source file:info.mtgdb.api.Db.java

/**
 * //from   www .j a  v  a 2s.  c  om
 * @param filters HashMap<String, String> containing a mapping of keys to values.  For example colors and black.
 * @return ArrayList
 */
public static ArrayList<Card> filterCards(HashMap<String, String> filters) {
    StringBuilder sb = new StringBuilder();
    sb.append(API_URL + "/cards/?");
    for (String key : filters.keySet()) {
        String value = filters.get(key);
        sb.append(key + "=" + value + "&");
    }
    if (filters.size() > 0)
        sb.deleteCharAt(sb.length() - 1);
    return getCardsFromUrl(sb.toString());
}

From source file:DIA_Umpire_Quant.DIA_Umpire_ProtQuant.java

/**
 * @param args the command line arguments
 *//*from   w  w  w. j ava 2s . c o  m*/
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:info.unyttig.helladroid.newzbin.NewzBinController.java

/**
 * Sends HTTP POST requests to Newzbin with given parameters. 
 * /*  w  ww. j a v a  2 s . co m*/
 * @param url Type:String - The url to connect to
 * @param kvPairs Type:Map - The map of parameters to post
 * @return Returns a HttpResponse with results 
 * @throws ClientProtocolException
 * @throws IOException
 */
public static HttpResponse doPost(String url, HashMap<String, String> kvPairs)
        throws ClientProtocolException, IOException {

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    httppost.addHeader("Content-type", "application/x-www-form-urlencoded");

    if (kvPairs != null && kvPairs.isEmpty() == false) {
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(kvPairs.size() + 4);
        nameValuePairs
                .add(new BasicNameValuePair("limit", preferences.getString("newzbin_search_limit", "10")));
        nameValuePairs
                .add(new BasicNameValuePair("retention", preferences.getString("newzbin_retention", "7")));
        nameValuePairs.add(new BasicNameValuePair("username", preferences.getString("newzbin_username", "")));
        nameValuePairs.add(new BasicNameValuePair("password", preferences.getString("newzbin_password", "")));
        String k, v;
        Iterator<String> itKeys = kvPairs.keySet().iterator();
        while (itKeys.hasNext()) {
            k = itKeys.next();
            v = kvPairs.get(k);
            nameValuePairs.add(new BasicNameValuePair(k, v));
        }
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    }
    return httpclient.execute(httppost);
}