Example usage for java.util LinkedHashMap containsKey

List of usage examples for java.util LinkedHashMap containsKey

Introduction

In this page you can find the example usage for java.util LinkedHashMap containsKey.

Prototype

boolean containsKey(Object key);

Source Link

Document

Returns true if this map contains a mapping for the specified key.

Usage

From source file:org.pentaho.reporting.platform.plugin.ParameterXmlContentHandler.java

public void createParameterContent(final OutputStream outputStream, final Serializable fileId,
        final String path, boolean overrideOutputType, MasterReport report) throws Exception {
    final Object rawSessionId = inputs.get(ParameterXmlContentHandler.SYS_PARAM_SESSION_ID);
    if ((rawSessionId instanceof String) == false || "".equals(rawSessionId)) {
        inputs.put(ParameterXmlContentHandler.SYS_PARAM_SESSION_ID, UUIDUtil.getUUIDAsString());
    }// w w  w. j  av a2s .  c o  m

    this.document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

    final IParameterProvider requestParams = getRequestParameters();

    final SimpleReportingComponent reportComponent = new SimpleReportingComponent();
    reportComponent.setReportFileId(fileId);
    if (report != null) {
        reportComponent.setReport(report);
    }
    reportComponent.setPaginateOutput(true);

    final boolean isMobile = "true".equals(requestParams.getStringParameter("mobile", "false")); //$NON-NLS-1$ //$NON-NLS-2$

    if (isMobile) {
        overrideOutputType = true;
        reportComponent.setForceDefaultOutputTarget(true);
    } else {
        reportComponent.setForceDefaultOutputTarget(overrideOutputType);
    }
    reportComponent.setDefaultOutputTarget(HtmlTableModule.TABLE_HTML_PAGE_EXPORT_TYPE);

    if (path.endsWith(".prpti")) {
        reportComponent.setForceUnlockPreferredOutput(true);
    }

    reportComponent.setInputs(inputs);

    report = reportComponent.getReport();

    final DefaultParameterContext parameterContext = new DefaultParameterContext(report);
    final ValidationResult vr;
    final Element parameters;
    try {
        // apply inputs to parameters
        final ValidationResult validationResult = ReportContentUtil.applyInputsToReportParameters(report,
                parameterContext, inputs, new ValidationResult());

        final ReportParameterDefinition reportParameterDefinition = report.getParameterDefinition();
        vr = reportParameterDefinition.getValidator().validate(validationResult, reportParameterDefinition,
                parameterContext);

        parameters = document.createElement(GROUP_PARAMETERS); //$NON-NLS-1$
        parameters.setAttribute("is-prompt-needed", String.valueOf(vr.isEmpty() == false)); //$NON-NLS-1$ //$NON-NLS-2$
        parameters.setAttribute("ignore-biserver-5538", "true");

        // check if pagination is allowed and turned on

        final Boolean autoSubmitFlag = requestFlag("autoSubmit", report, AttributeNames.Core.NAMESPACE,
                AttributeNames.Core.AUTO_SUBMIT_PARAMETER,
                "org.pentaho.reporting.engine.classic.core.ParameterAutoSubmit");
        if (Boolean.TRUE.equals(autoSubmitFlag)) {
            parameters.setAttribute("autoSubmit", "true");
        } else if (Boolean.FALSE.equals(autoSubmitFlag)) {
            parameters.setAttribute("autoSubmit", "false");
        }

        final Boolean autoSubmitUiFlag = requestFlag("autoSubmitUI", report, // NON-NLS
                AttributeNames.Core.NAMESPACE, AttributeNames.Core.AUTO_SUBMIT_DEFAULT,
                "org.pentaho.reporting.engine.classic.core.ParameterAutoSubmitUI");
        if (Boolean.FALSE.equals(autoSubmitUiFlag)) {
            parameters.setAttribute("autoSubmitUI", "false"); // NON-NLS
        } else {
            parameters.setAttribute("autoSubmitUI", "true"); // NON-NLS
        }

        parameters.setAttribute("layout", requestConfiguration("layout", report, // NON-NLS
                AttributeNames.Core.NAMESPACE, AttributeNames.Core.PARAMETER_UI_LAYOUT,
                "org.pentaho.reporting.engine.classic.core.ParameterUiLayout"));

        final ParameterDefinitionEntry[] parameterDefinitions = reportParameterDefinition
                .getParameterDefinitions();
        // Collect all parameter, but allow user-parameter to override system parameter.
        // It is the user's problem if the types do not match and weird errors occur, but
        // there are sensible usecases where this should be allowed.
        // System parameter must come last in the list, as this is how it was done in the original
        // version and this is how people expect it to be now.
        final LinkedHashMap<String, ParameterDefinitionEntry> reportParameters = new LinkedHashMap<String, ParameterDefinitionEntry>();
        for (final ParameterDefinitionEntry parameter : parameterDefinitions) {
            reportParameters.put(parameter.getName(), parameter);
        }
        for (final Map.Entry<String, ParameterDefinitionEntry> entry : getSystemParameter().entrySet()) {
            if (reportParameters.containsKey(entry.getKey()) == false) {
                reportParameters.put(entry.getKey(), entry.getValue());
            }
        }

        if (overrideOutputType) {
            final ParameterDefinitionEntry definitionEntry = reportParameters
                    .get(SimpleReportingComponent.OUTPUT_TARGET);
            if (definitionEntry instanceof AbstractParameter) {
                final AbstractParameter parameter = (AbstractParameter) definitionEntry;
                parameter.setHidden(true);
                parameter.setMandatory(false);
            }
        } else {
            hideOutputParameterIfLocked(report, reportParameters);
        }

        final Map<String, Object> inputs = computeRealInput(parameterContext, reportParameters,
                reportComponent.getComputedOutputTarget(), vr);

        final Boolean showParameterUI = requestFlag("showParameters", report, // NON-NLS
                AttributeNames.Core.NAMESPACE, AttributeNames.Core.SHOW_PARAMETER_UI, null);
        if (Boolean.FALSE.equals(showParameterUI)) {
            inputs.put("showParameters", Boolean.FALSE); // NON-NLS
        } else {
            inputs.put("showParameters", Boolean.TRUE); // NON-NLS
        }

        // Adding proportional width config parameter
        String proportionalWidth = report.getReportConfiguration()
                .getConfigProperty(CONFIG_PARAM_HTML_PROPORTIONAL_WIDTH);
        inputs.put(SYS_PARAM_HTML_PROPORTIONAL_WIDTH, Boolean.valueOf(proportionalWidth));

        for (final ParameterDefinitionEntry parameter : reportParameters.values()) {
            final Object selections = inputs.get(parameter.getName());
            final ParameterContextWrapper wrapper = new ParameterContextWrapper(parameterContext,
                    vr.getParameterValues());
            parameters.appendChild(createParameterElement(parameter, wrapper, selections));
        }

        if (vr.isEmpty() == false) {
            parameters.appendChild(createErrorElements(vr));
        }

        final String[] outputParameter = new OutputParameterCollector().collectParameter(report);
        for (int i = 0; i < outputParameter.length; i++) {
            final String outputParameterName = outputParameter[i];
            //  <output-parameter displayName="Territory" id="[Markets].[Territory]"/>
            final Element element = document.createElement("output-parameter");// NON-NLS
            element.setAttribute("displayName", outputParameterName);// NON-NLS
            element.setAttribute("id", outputParameterName);// NON-NLS
            parameters.appendChild(element);
        }

        if (vr.isEmpty() && reportComponent.getComputedOutputTarget()
                .equals(HtmlTableModule.TABLE_HTML_PAGE_EXPORT_TYPE)) //$NON-NLS-1$ //$NON-NLS-2$
        {
            appendPageCount(reportComponent, parameters);
        }
        document.appendChild(parameters);

        final DOMSource source = new DOMSource(document);
        final StreamResult result = new StreamResult(outputStream);
        final Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.transform(source, result);
        // close parameter context
    } finally {
        parameterContext.close();
    }
}

From source file:com.smartitengineering.dao.impl.hbase.CommonDao.java

protected void deleteNonOptimistically(Template[] states) throws IllegalStateException {
    LinkedHashMap<String, List<Delete>> allDels = new LinkedHashMap<String, List<Delete>>();
    for (Template state : states) {
        if (!state.isValid()) {
            throw new IllegalStateException("Entity not in valid state!");
        }//  ww  w  .  j a  va  2  s .  c  om
        LinkedHashMap<String, Delete> dels = getConverter().objectToDeleteableRows(state, executorService,
                getLockType().equals(LockType.PESSIMISTIC));
        for (Map.Entry<String, Delete> del : dels.entrySet()) {
            final List<Delete> putList;
            if (allDels.containsKey(del.getKey())) {
                putList = allDels.get(del.getKey());
            } else {
                putList = new ArrayList<Delete>();
                allDels.put(del.getKey(), putList);
            }
            putList.add(del.getValue());
        }
    }
    for (final Map.Entry<String, List<Delete>> dels : allDels.entrySet()) {
        try {
            executorService.execute(dels.getKey(), new Callback<Void>() {

                @Override
                public Void call(HTableInterface tableInterface) throws Exception {
                    final List<Delete> value = dels.getValue();
                    if (logger.isInfoEnabled()) {
                        logger.info("Attempting to DELETE " + value);
                    }
                    final ArrayList<Delete> list = new ArrayList<Delete>(value);
                    tableInterface.delete(list);
                    return null;
                }
            });
        } finally {
            for (Template state : states) {
                lockAttainer.unlockAndEvictFromCache(state);
            }
        }
    }
}

From source file:org.cerberus.servlet.crud.testexecution.ReadTestCaseExecution.java

private AnswerItem findExecutionListBySystem(String system, ApplicationContext appContext,
        HttpServletRequest request) throws ParseException, JSONException {
    AnswerItem answer = new AnswerItem(new MessageEvent(MessageEventEnum.DATA_OPERATION_OK));

    /**//  w ww  .  j  av a  2s  . co  m
     * Parse all parameters used in the search.
     */
    String charset = request.getCharacterEncoding();
    /**
     * Parse parameters - list of values
     */

    List<String> testList = ParameterParserUtil.parseListParamAndDecode(request.getParameterValues("test"),
            null, charset);
    List<String> applicationList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("application"), null, charset);
    List<String> projectList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("project"), null, charset);

    List<String> tcstatusList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("tcstatus"), null, charset);
    List<String> groupList = ParameterParserUtil.parseListParamAndDecode(request.getParameterValues("group"),
            null, charset);
    List<String> tcactiveList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("tcactive"), null, charset);
    List<String> priorityList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("priority"), null, charset);

    List<String> targetsprintList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("targetsprint"), null, charset);
    List<String> targetrevisionList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("targetrevision"), null, charset);
    List<String> creatorList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("creator"), null, charset);
    List<String> implementerList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("implementer"), null, charset);

    List<String> environmentList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("environment"), null, charset);
    List<String> buildList = ParameterParserUtil.parseListParamAndDecode(request.getParameterValues("build"),
            null, charset);
    List<String> revisionList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("revision"), null, charset);

    List<String> countryList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("country"), null, charset);
    List<String> browserList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("browser"), null, charset);
    List<String> tcestatusList = ParameterParserUtil
            .parseListParamAndDecode(request.getParameterValues("tcestatus"), null, charset);

    //Sorts the lists 
    if (countryList != null) {
        Collections.sort(countryList);
    }
    if (browserList != null) {
        Collections.sort(browserList);
    }

    /**
     * Parse parameters - free text
     */
    String bugid = StringEscapeUtils.escapeHtml4(request.getParameter("bugid"));
    String ticket = StringEscapeUtils.escapeHtml4(request.getParameter("ticket"));
    String ip = StringEscapeUtils.escapeHtml4(request.getParameter("ip"));
    String port = StringEscapeUtils.escapeHtml4(request.getParameter("port"));
    String tag = StringEscapeUtils.escapeHtml4(request.getParameter("tag"));
    String browserversion = StringEscapeUtils.escapeHtml4(request.getParameter("browserversion"));
    String comment = StringEscapeUtils.escapeHtml4(request.getParameter("comment"));

    /**
     * Gets regular executions (not in queue)
     */
    AnswerList answerExecutions = testCaseExecutionService.readBySystemByVarious(system, testList,
            applicationList, projectList, tcstatusList, groupList, tcactiveList, priorityList, targetsprintList,
            targetrevisionList, creatorList, implementerList, buildList, revisionList, environmentList,
            countryList, browserList, tcestatusList, ip, port, tag, browserversion, comment, bugid, ticket);

    List<TestCaseExecution> testCaseExecutions = (List<TestCaseExecution>) answerExecutions.getDataList();

    /**
     * Get list of Execution in Queue by Tag
     */
    ITestCaseExecutionInQueueService testCaseExecutionInQueueService = appContext
            .getBean(ITestCaseExecutionInQueueService.class);
    AnswerList answerExecutionsInQueue = testCaseExecutionInQueueService.readBySystemByVarious(system, testList,
            applicationList, projectList, tcstatusList, groupList, tcactiveList, priorityList, targetsprintList,
            targetrevisionList, creatorList, implementerList, buildList, revisionList, environmentList,
            countryList, browserList, tcestatusList, ip, port, tag, browserversion, comment, bugid, ticket);
    List<TestCaseExecutionInQueue> testCaseExecutionsInQueue = (List<TestCaseExecutionInQueue>) answerExecutionsInQueue
            .getDataList();

    /**
     * Merge Test Case Executions
     */
    List<TestCaseExecution> allTestCaseExecutions = hashExecution(testCaseExecutions,
            testCaseExecutionsInQueue);

    JSONArray executionList = new JSONArray();
    LinkedHashMap<String, JSONObject> ttc = new LinkedHashMap<String, JSONObject>();

    for (TestCaseExecution testCaseExecution : allTestCaseExecutions) {
        try {
            JSONObject execution = testCaseExecutionToJSONObject(testCaseExecution);
            String execKey = testCaseExecution.getCountry() + " " + testCaseExecution.getBrowser(); //the key is country and browser
            String testCaseKey = testCaseExecution.getTest() + "_" + testCaseExecution.getTestCase();
            JSONObject execTab = new JSONObject();

            executionList.put(testCaseExecutionToJSONObject(testCaseExecution));
            JSONObject ttcObject = new JSONObject();

            if (ttc.containsKey(testCaseKey)) {
                ttcObject = ttc.get(testCaseKey);
                execTab = ttcObject.getJSONObject("execTab");
                execTab.put(execKey, execution);
                ttcObject.put("execTab", execTab);
            } else {
                ttcObject.put("test", testCaseExecution.getTest());
                ttcObject.put("testCase", testCaseExecution.getTestCase());
                ttcObject.put("function", testCaseExecution.getTestCaseObj().getFunction());
                ttcObject.put("shortDesc", testCaseExecution.getTestCaseObj().getDescription());
                ttcObject.put("status", testCaseExecution.getTestCaseObj().getStatus());
                ttcObject.put("application", testCaseExecution.getApplication());
                ttcObject.put("bugId", testCaseExecution.getTestCaseObj().getBugID());
                ttcObject.put("ticket", testCaseExecution.getTestCaseObj().getTicket());
                ttcObject.put("comment", testCaseExecution.getTestCaseObj().getComment());
                ttcObject.put("priority", testCaseExecution.getTestCaseObj().getPriority());
                ttcObject.put("status", testCaseExecution.getStatus());
                ttcObject.put("group", testCaseExecution.getTestCaseObj().getGroup());
                execTab.put(execKey, execution);
                ttcObject.put("execTab", execTab);
            }
            ttc.put(testCaseExecution.getTest() + "_" + testCaseExecution.getTestCase(), ttcObject);
        } catch (JSONException ex) {
            Logger.getLogger(ReadTestCaseExecution.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    JSONObject jsonResponse = new JSONObject();
    jsonResponse.put("contentTable", ttc.values());
    jsonResponse.put("iTotalRecords", ttc.size());
    jsonResponse.put("iTotalDisplayRecords", ttc.size());

    answer.setItem(jsonResponse);
    answer.setResultMessage(new MessageEvent(MessageEventEnum.DATA_OPERATION_OK));
    return answer;
}

From source file:com.taobao.datax.plugins.writer.oraclejdbcwriter.OracleJdbcWriter.java

public String buildInsertString() {
    StringBuilder sb = new StringBuilder();
    sb.append("INSERT INTO ").append(this.schema + "." + this.table).append(" ");
    if (!StringUtils.isEmpty(this.colorder)) {
        sb.append("(").append(this.colorder).append(")");
    }//from w w w.j  a  v a  2s.c om
    sb.append(" VALUES(");
    try {
        ResultSet rs = this.connection.createStatement()
                .executeQuery("SELECT COLUMN_NAME,DATA_TYPE FROM USER_TAB_COLUMNS WHERE TABLE_NAME='"
                        + this.table.toUpperCase() + "'");
        LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
        while (rs.next()) {
            String colName = rs.getString(1);
            String colType = rs.getString(2);
            map.put(colName, colType);
        }
        logger.debug("Column map:size=" + map.size() + ";cols=" + map.toString());
        if (StringUtils.isEmpty(this.colorder)) {
            Iterator<Entry<String, String>> it = map.entrySet().iterator();
            while (it.hasNext()) {
                Entry<String, String> entry = it.next();
                String colType = entry.getValue();
                if (colType.toUpperCase().equals("DATE")) {
                    sb.append("to_date(?,'" + this.dtfmt + "'),");
                } else {
                    sb.append("?,");
                }
            }
            sb.deleteCharAt(sb.length() - 1);// remove last comma
            sb.append(")");
        } else {
            String[] arr = colorder.split(",");
            for (String colName : arr) {
                if (!map.containsKey(colName)) {
                    throw new DataExchangeException("col " + colName + " not in database");
                }
                String colType = map.get(colName);
                if (colType.toUpperCase().equals("DATE")) {
                    sb.append("to_date(?,'" + this.dtfmt + "'),");
                } else {
                    sb.append("?,");
                }
            }
            sb.deleteCharAt(sb.length() - 1);// remove last comma
            sb.append(")");
        }
    } catch (SQLException e) {
        e.printStackTrace();
        throw new DataExchangeException(e.getMessage());
    }

    return sb.toString();
}

From source file:org.tinymediamanager.core.movie.MovieRenamerPreview.java

public static MovieRenamerPreviewContainer renameMovie(Movie movie) {
    MovieRenamerPreviewContainer container = new MovieRenamerPreviewContainer(movie);

    LinkedHashMap<String, MediaFile> oldFiles = new LinkedHashMap<>();
    Set<MediaFile> newFiles = new LinkedHashSet<>();

    String newVideoBasename = "";
    if (MovieModuleManager.MOVIE_SETTINGS.getMovieRenamerFilename().trim().isEmpty()) {
        // we are NOT renaming any files, so we keep the same name on renaming ;)
        newVideoBasename = movie.getVideoBasenameWithoutStacking();
    } else {/*from   ww w  .  j  a  va2 s  . com*/
        // since we rename, generate the new basename
        MediaFile ftr = MovieRenamer
                .generateFilename(movie, movie.getMediaFiles(MediaFileType.VIDEO).get(0), newVideoBasename)
                .get(0);
        newVideoBasename = FilenameUtils.getBaseName(ftr.getFilenameWithoutStacking());
    }

    // VIDEO needs to be renamed first, since all others depend on that name!!!
    for (MediaFile mf : movie.getMediaFiles(MediaFileType.VIDEO)) {
        oldFiles.put(mf.getFileAsPath().toString(), new MediaFile(mf));
        MediaFile ftr = MovieRenamer.generateFilename(movie, mf, newVideoBasename).get(0); // there can be only one
        newFiles.add(ftr);
    }

    // all the other MFs...
    for (MediaFile mf : movie.getMediaFilesExceptType(MediaFileType.VIDEO)) {
        oldFiles.put(mf.getFileAsPath().toString(), new MediaFile(mf));
        newFiles.addAll(MovieRenamer.generateFilename(movie, mf, newVideoBasename)); // N:M
    }

    // movie folder needs a rename?
    Path oldMovieFolder = movie.getPathNIO();
    String pattern = MovieModuleManager.MOVIE_SETTINGS.getMovieRenamerPathname();
    if (pattern.isEmpty()) {
        // same
        container.newPath = Paths.get(movie.getDataSource()).relativize(movie.getPathNIO());
    } else {
        container.newPath = Paths.get(MovieRenamer.createDestinationForFoldername(pattern, movie));
    }
    Path newMovieFolder = Paths.get(movie.getDataSource()).resolve(container.newPath);

    if (!oldMovieFolder.equals(newMovieFolder)) {
        container.needsRename = true;
        // update already the "old" files with new path, so we can simply do a contains check ;)
        for (MediaFile omf : oldFiles.values()) {
            omf.replacePathForRenamedFolder(oldMovieFolder, newMovieFolder);
        }
    }

    // change status of MFs, if they have been added or not
    for (MediaFile mf : newFiles) {
        if (!oldFiles.containsKey(mf.getFileAsPath().toString())) {
            // System.out.println(mf);
            container.needsRename = true;
            break;
        }
    }

    for (MediaFile mf : oldFiles.values()) {
        if (!newFiles.contains(mf)) {
            // System.out.println(mf);
            container.needsRename = true;
            break;
        }
    }

    container.newMediaFiles.addAll(newFiles);
    return container;
}

From source file:es.uvigo.ei.sing.adops.datatypes.ProjectExperiment.java

private String checkFastaFile() throws IllegalArgumentException {
    final Set<Character> aminos = new HashSet<Character>(
            Arrays.asList('a', 'c', 't', 'g', 'A', 'C', 'T', 'G', '-'));
    BufferedReader br = null;/*from   w  ww. java2s  .com*/

    try {
        final StringBuilder sb = new StringBuilder();
        final LinkedHashMap<String, StringBuilder> replacements = new LinkedHashMap<String, StringBuilder>();

        br = new BufferedReader(new FileReader(this.fastaFile));

        String line = null;
        while ((line = br.readLine()) != null && !line.startsWith(">")) {
            sb.append(line).append('\n');
        }

        String seqId = null;
        String seq = null;
        while (line != null) {
            seqId = line;
            seq = "";
            while ((line = br.readLine()) != null && !line.startsWith(">")) {
                seq += line;
            }

            // Non ACTG characters replacement
            char[] charSequence = seq.toCharArray();
            String data = "";
            for (int i = 0; i < charSequence.length; i++) {
                if (aminos.contains(charSequence[i])) {
                    data += charSequence[i];
                } else {
                    if (replacements.containsKey(seqId)) {
                        replacements.get(seqId).append(String.format(", [%d,%c]", i + 1, charSequence[i]));
                    } else {
                        replacements.put(seqId,
                                new StringBuilder(String.format("[%d,%c]", i + 1, charSequence[i])));
                    }

                    data += '-';
                }
            }

            // Incomplete codons replacement
            charSequence = data.toCharArray();
            data = "";
            String codon = "";
            for (int i = 0; i < charSequence.length; i++) {
                codon += Character.toString(charSequence[i]);
                if ((i + 1) % 3 == 0) {
                    if (codon.contains("-")) {
                        data += "---";
                        if (replacements.containsKey(seqId)) {
                            replacements.get(seqId).append(String.format(", [%s,---]", codon));
                        } else {
                            replacements.put(seqId, new StringBuilder(String.format("[%s,---]", codon)));
                        }
                    } else {
                        data += codon;

                    }

                    codon = "";
                }
            }

            sb.append(seqId).append('\n');
            sb.append(data).append('\n');
        }

        FileUtils.write(this.fastaFile, sb.toString());

        if (replacements.isEmpty()) {
            return "";
        } else {
            final StringBuilder summary = new StringBuilder("Replacements done on input file\n");
            for (Map.Entry<String, StringBuilder> replacement : replacements.entrySet()) {
                summary.append(replacement.getKey()).append('\n');
                summary.append(replacement.getValue()).append('\n');
            }

            summary.append("\n-----\n");

            return summary.toString();
        }
    } catch (Exception e) {
        throw new IllegalArgumentException("Input file is not a valida Fasta file");
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException ioe) {
            }
        }
    }
}

From source file:edu.harvard.i2b2.adminTool.dataModel.ConceptTableModel.java

public void fillDataFromTable(ArrayList<ArrayList<ConceptTableRow>> list) {
    list.clear();// ww w. jav a2 s.c  o m
    ConceptTableRow row = null;
    ArrayList<ConceptTableRow> group = null;
    Integer curRow = null;
    LinkedHashMap<Integer, ArrayList<ConceptTableRow>> rowMap = new LinkedHashMap<Integer, ArrayList<ConceptTableRow>>();

    for (int i = 1; i < rowCount; i++) {
        row = new ConceptTableRow();
        curRow = new Integer((String) content.get("0/" + i));
        row.rowNumber = curRow.intValue();
        if (!rowMap.containsKey(curRow)) {
            group = new ArrayList<ConceptTableRow>();
            list.add(group);
            rowMap.put(curRow, group);
        } else {
            group = rowMap.get(curRow);
        }
        row.conceptName = (String) content.get("1/" + i);
        row.dateText = (String) content.get("2/" + i);
        row.valueText = (String) content.get("3/" + i);
        row.modifierText = (String) content.get("4/" + i);
        row.height = (String) content.get("5/" + i);
        row.color = (RGB) content.get("6/" + i);
        row.conceptXml = (String) content.get("7/" + i);
        row.data = (QueryModel) content.get("8/" + i);
        row.rowId = i;
        group.add(row);
    }
}

From source file:com.android.mtkex.chips.BaseRecipientAdapter.java

private static void putOneEntry(TemporaryEntry entry, boolean isAggregatedEntry,
        LinkedHashMap<Long, List<RecipientEntry>> entryMap, List<RecipientEntry> nonAggregatedEntries,
        Set<String> existingDestinations) {
    /// M: Let all entries which have same destination can be shown.
    if (!mShowDuplicateResults) {
        if (existingDestinations.contains(entry.destination)) {
            return;
        }/*from w w w  .  j  a va2s.co m*/
    }

    existingDestinations.add(entry.destination);

    if (!isAggregatedEntry) {
        nonAggregatedEntries.add(RecipientEntry.constructTopLevelEntry(entry.displayName,
                entry.displayNameSource, entry.destination, entry.destinationType, entry.destinationLabel,
                entry.contactId, entry.dataId, entry.thumbnailUriString, true, entry.isGalContact));
        /// M: Set destination kind of the recipient entry if the contact entry is queried from email. @{
        if (mQueryType == QUERY_TYPE_PHONE) {
            if (entry.getDestinationKind() == RecipientEntry.ENTRY_KIND_EMAIL) {
                nonAggregatedEntries.get(nonAggregatedEntries.size() - 1)
                        .setDestinationKind(RecipientEntry.ENTRY_KIND_EMAIL);
            } else if (entry.getDestinationKind() == RecipientEntry.ENTRY_KIND_PHONE) {
                nonAggregatedEntries.get(nonAggregatedEntries.size() - 1)
                        .setDestinationKind(RecipientEntry.ENTRY_KIND_PHONE);
            }
        }
        /// @}
    } else if (entryMap.containsKey(entry.contactId)) {
        // We already have a section for the person.
        final List<RecipientEntry> entryList = entryMap.get(entry.contactId);
        entryList.add(RecipientEntry.constructSecondLevelEntry(entry.displayName, entry.displayNameSource,
                entry.destination, entry.destinationType, entry.destinationLabel, entry.contactId, entry.dataId,
                entry.thumbnailUriString, true, entry.isGalContact));
        /// M: Set destination kind of the recipient entry if the contact entry is queried from email. @{
        if (mQueryType == QUERY_TYPE_PHONE) {
            if (entry.getDestinationKind() == RecipientEntry.ENTRY_KIND_EMAIL) {
                entryList.get(entryList.size() - 1).setDestinationKind(RecipientEntry.ENTRY_KIND_EMAIL);
            } else if (entry.getDestinationKind() == RecipientEntry.ENTRY_KIND_PHONE) {
                entryList.get(entryList.size() - 1).setDestinationKind(RecipientEntry.ENTRY_KIND_PHONE);
            }
        }
        /// @}
    } else {
        final List<RecipientEntry> entryList = new ArrayList<RecipientEntry>();
        entryList.add(RecipientEntry.constructTopLevelEntry(entry.displayName, entry.displayNameSource,
                entry.destination, entry.destinationType, entry.destinationLabel, entry.contactId, entry.dataId,
                entry.thumbnailUriString, true, entry.isGalContact));
        /// M: Set destination kind of the recipient entry if the contact entry is queried from email. @{
        if (mQueryType == QUERY_TYPE_PHONE) {
            if (entry.getDestinationKind() == RecipientEntry.ENTRY_KIND_EMAIL) {
                entryList.get(entryList.size() - 1).setDestinationKind(RecipientEntry.ENTRY_KIND_EMAIL);
            } else if (entry.getDestinationKind() == RecipientEntry.ENTRY_KIND_PHONE) {
                entryList.get(entryList.size() - 1).setDestinationKind(RecipientEntry.ENTRY_KIND_PHONE);
            }
        }
        /// @}
        entryMap.put(entry.contactId, entryList);
    }
}

From source file:com.espertech.esper.epl.spec.PatternStreamSpecRaw.java

private static void recursiveCompile(EvalFactoryNode evalNode, StatementContext context,
        ExprEvaluatorContext evaluatorContext, Set<String> eventTypeReferences, boolean isInsertInto,
        MatchEventSpec tags, Deque<Integer> subexpressionIdStack, Stack<EvalFactoryNode> parentNodeStack,
        LinkedHashSet<String> allTagNamesOrdered) throws ExprValidationException {
    int counter = 0;
    parentNodeStack.push(evalNode);//from   ww  w. j a v a2 s. c o  m
    for (EvalFactoryNode child : evalNode.getChildNodes()) {
        subexpressionIdStack.addLast(counter++);
        recursiveCompile(child, context, evaluatorContext, eventTypeReferences, isInsertInto, tags,
                subexpressionIdStack, parentNodeStack, allTagNamesOrdered);
        subexpressionIdStack.removeLast();
    }
    parentNodeStack.pop();

    LinkedHashMap<String, Pair<EventType, String>> newTaggedEventTypes = null;
    LinkedHashMap<String, Pair<EventType, String>> newArrayEventTypes = null;

    if (evalNode instanceof EvalFilterFactoryNode) {
        EvalFilterFactoryNode filterNode = (EvalFilterFactoryNode) evalNode;
        String eventName = filterNode.getRawFilterSpec().getEventTypeName();
        EventType resolvedEventType = FilterStreamSpecRaw.resolveType(context.getEngineURI(), eventName,
                context.getEventAdapterService(), context.getPlugInTypeResolutionURIs());
        EventType finalEventType = resolvedEventType;
        String optionalTag = filterNode.getEventAsName();
        boolean isPropertyEvaluation = false;
        boolean isParentMatchUntil = isParentMatchUntil(evalNode, parentNodeStack);

        // obtain property event type, if final event type is properties
        if (filterNode.getRawFilterSpec().getOptionalPropertyEvalSpec() != null) {
            PropertyEvaluator optionalPropertyEvaluator = PropertyEvaluatorFactory.makeEvaluator(
                    filterNode.getRawFilterSpec().getOptionalPropertyEvalSpec(), resolvedEventType,
                    filterNode.getEventAsName(), context.getEventAdapterService(),
                    context.getMethodResolutionService(), context.getSchedulingService(),
                    context.getVariableService(), context.getEngineURI(), context.getStatementId(),
                    context.getStatementName(), context.getAnnotations(), subexpressionIdStack,
                    context.getConfigSnapshot());
            finalEventType = optionalPropertyEvaluator.getFragmentEventType();
            isPropertyEvaluation = true;
        }

        if (finalEventType instanceof EventTypeSPI) {
            eventTypeReferences.add(((EventTypeSPI) finalEventType).getMetadata().getPrimaryName());
        }

        // If a tag was supplied for the type, the tags must stay with this type, i.e. a=BeanA -> b=BeanA -> a=BeanB is a no
        if (optionalTag != null) {
            Pair<EventType, String> pair = tags.getTaggedEventTypes().get(optionalTag);
            EventType existingType = null;
            if (pair != null) {
                existingType = pair.getFirst();
            }
            if (existingType == null) {
                pair = tags.getArrayEventTypes().get(optionalTag);
                if (pair != null) {
                    throw new ExprValidationException("Tag '" + optionalTag + "' for event '" + eventName
                            + "' used in the repeat-until operator cannot also appear in other filter expressions");
                }
            }
            if ((existingType != null) && (existingType != finalEventType)) {
                throw new ExprValidationException("Tag '" + optionalTag + "' for event '" + eventName
                        + "' has already been declared for events of type "
                        + existingType.getUnderlyingType().getName());
            }
            pair = new Pair<EventType, String>(finalEventType, eventName);

            // add tagged type
            if (isPropertyEvaluation || isParentMatchUntil) {
                newArrayEventTypes = new LinkedHashMap<String, Pair<EventType, String>>();
                newArrayEventTypes.put(optionalTag, pair);
            } else {
                newTaggedEventTypes = new LinkedHashMap<String, Pair<EventType, String>>();
                newTaggedEventTypes.put(optionalTag, pair);
            }
        }

        // For this filter, filter types are all known tags at this time,
        // and additionally stream 0 (self) is our event type.
        // Stream type service allows resolution by property name event if that name appears in other tags.
        // by defaulting to stream zero.
        // Stream zero is always the current event type, all others follow the order of the map (stream 1 to N).
        String selfStreamName = optionalTag;
        if (selfStreamName == null) {
            selfStreamName = "s_" + UuidGenerator.generate();
        }
        LinkedHashMap<String, Pair<EventType, String>> filterTypes = new LinkedHashMap<String, Pair<EventType, String>>();
        Pair<EventType, String> typePair = new Pair<EventType, String>(finalEventType, eventName);
        filterTypes.put(selfStreamName, typePair);
        filterTypes.putAll(tags.getTaggedEventTypes());

        // for the filter, specify all tags used
        LinkedHashMap<String, Pair<EventType, String>> filterTaggedEventTypes = new LinkedHashMap<String, Pair<EventType, String>>(
                tags.getTaggedEventTypes());
        filterTaggedEventTypes.remove(optionalTag);

        // handle array tags (match-until clause)
        LinkedHashMap<String, Pair<EventType, String>> arrayCompositeEventTypes = null;
        if (tags.getArrayEventTypes() != null && !tags.getArrayEventTypes().isEmpty()) {
            arrayCompositeEventTypes = new LinkedHashMap<String, Pair<EventType, String>>();
            String patternSubexEventType = getPatternSubexEventType(context.getStatementId(), "pattern",
                    subexpressionIdStack);

            for (Map.Entry<String, Pair<EventType, String>> entry : tags.getArrayEventTypes().entrySet()) {
                LinkedHashMap<String, Pair<EventType, String>> specificArrayType = new LinkedHashMap<String, Pair<EventType, String>>();
                specificArrayType.put(entry.getKey(), entry.getValue());
                EventType arrayTagCompositeEventType = context.getEventAdapterService()
                        .createSemiAnonymousMapType(patternSubexEventType,
                                Collections.<String, Pair<EventType, String>>emptyMap(), specificArrayType,
                                isInsertInto);

                String tag = entry.getKey();
                if (!filterTypes.containsKey(tag)) {
                    Pair<EventType, String> pair = new Pair<EventType, String>(arrayTagCompositeEventType, tag);
                    filterTypes.put(tag, pair);
                    arrayCompositeEventTypes.put(tag, pair);
                }
            }
        }

        StreamTypeService streamTypeService = new StreamTypeServiceImpl(filterTypes, context.getEngineURI(),
                true, false);
        List<ExprNode> exprNodes = filterNode.getRawFilterSpec().getFilterExpressions();

        FilterSpecCompiled spec = FilterSpecCompiler.makeFilterSpec(resolvedEventType, eventName, exprNodes,
                filterNode.getRawFilterSpec().getOptionalPropertyEvalSpec(), filterTaggedEventTypes,
                arrayCompositeEventTypes, streamTypeService, null, context, subexpressionIdStack);
        filterNode.setFilterSpec(spec);
    } else if (evalNode instanceof EvalObserverFactoryNode) {
        EvalObserverFactoryNode observerNode = (EvalObserverFactoryNode) evalNode;
        try {
            ObserverFactory observerFactory = context.getPatternResolutionService()
                    .create(observerNode.getPatternObserverSpec());

            StreamTypeService streamTypeService = getStreamTypeService(context.getEngineURI(),
                    context.getStatementId(), context.getEventAdapterService(), tags.getTaggedEventTypes(),
                    tags.getArrayEventTypes(), subexpressionIdStack, "observer");
            ExprValidationContext validationContext = new ExprValidationContext(streamTypeService,
                    context.getMethodResolutionService(), null, context.getSchedulingService(),
                    context.getVariableService(), evaluatorContext, context.getEventAdapterService(),
                    context.getStatementName(), context.getStatementId(), context.getAnnotations(),
                    context.getContextDescriptor());
            List<ExprNode> validated = validateExpressions(
                    observerNode.getPatternObserverSpec().getObjectParameters(), validationContext);

            MatchedEventConvertor convertor = new MatchedEventConvertorImpl(tags.getTaggedEventTypes(),
                    tags.getArrayEventTypes(), allTagNamesOrdered, context.getEventAdapterService());

            observerNode.setObserverFactory(observerFactory);
            observerFactory.setObserverParameters(validated, convertor);
        } catch (ObserverParameterException e) {
            throw new ExprValidationException("Invalid parameter for pattern observer: " + e.getMessage(), e);
        } catch (PatternObjectException e) {
            throw new ExprValidationException("Failed to resolve pattern observer: " + e.getMessage(), e);
        }
    } else if (evalNode instanceof EvalGuardFactoryNode) {
        EvalGuardFactoryNode guardNode = (EvalGuardFactoryNode) evalNode;
        try {
            GuardFactory guardFactory = context.getPatternResolutionService()
                    .create(guardNode.getPatternGuardSpec());

            StreamTypeService streamTypeService = getStreamTypeService(context.getEngineURI(),
                    context.getStatementId(), context.getEventAdapterService(), tags.getTaggedEventTypes(),
                    tags.getArrayEventTypes(), subexpressionIdStack, "guard");
            ExprValidationContext validationContext = new ExprValidationContext(streamTypeService,
                    context.getMethodResolutionService(), null, context.getSchedulingService(),
                    context.getVariableService(), evaluatorContext, context.getEventAdapterService(),
                    context.getStatementName(), context.getStatementId(), context.getAnnotations(),
                    context.getContextDescriptor());
            List<ExprNode> validated = validateExpressions(
                    guardNode.getPatternGuardSpec().getObjectParameters(), validationContext);

            MatchedEventConvertor convertor = new MatchedEventConvertorImpl(tags.getTaggedEventTypes(),
                    tags.getArrayEventTypes(), allTagNamesOrdered, context.getEventAdapterService());

            guardNode.setGuardFactory(guardFactory);
            guardFactory.setGuardParameters(validated, convertor);
        } catch (GuardParameterException e) {
            throw new ExprValidationException("Invalid parameter for pattern guard: " + e.getMessage(), e);
        } catch (PatternObjectException e) {
            throw new ExprValidationException("Failed to resolve pattern guard: " + e.getMessage(), e);
        }
    } else if (evalNode instanceof EvalEveryDistinctFactoryNode) {
        EvalEveryDistinctFactoryNode distinctNode = (EvalEveryDistinctFactoryNode) evalNode;
        MatchEventSpec matchEventFromChildNodes = analyzeMatchEvent(distinctNode);
        StreamTypeService streamTypeService = getStreamTypeService(context.getEngineURI(),
                context.getStatementId(), context.getEventAdapterService(),
                matchEventFromChildNodes.getTaggedEventTypes(), matchEventFromChildNodes.getArrayEventTypes(),
                subexpressionIdStack, "every-distinct");
        ExprValidationContext validationContext = new ExprValidationContext(streamTypeService,
                context.getMethodResolutionService(), null, context.getSchedulingService(),
                context.getVariableService(), evaluatorContext, context.getEventAdapterService(),
                context.getStatementName(), context.getStatementId(), context.getAnnotations(),
                context.getContextDescriptor());
        List<ExprNode> validated;
        try {
            validated = validateExpressions(distinctNode.getExpressions(), validationContext);
        } catch (ExprValidationPropertyException ex) {
            throw new ExprValidationPropertyException(ex.getMessage()
                    + ", every-distinct requires that all properties resolve from sub-expressions to the every-distinct",
                    ex.getCause());
        }

        MatchedEventConvertor convertor = new MatchedEventConvertorImpl(
                matchEventFromChildNodes.getTaggedEventTypes(), matchEventFromChildNodes.getArrayEventTypes(),
                allTagNamesOrdered, context.getEventAdapterService());

        distinctNode.setConvertor(convertor);

        // Determine whether some expressions are constants or time period
        List<ExprNode> distinctExpressions = new ArrayList<ExprNode>();
        Long msecToExpire = null;
        for (ExprNode expr : validated) {
            if (expr instanceof ExprTimePeriod) {
                Double secondsExpire = (Double) ((ExprTimePeriod) expr).evaluate(null, true, evaluatorContext);
                if ((secondsExpire != null) && (secondsExpire > 0)) {
                    msecToExpire = Math.round(1000d * secondsExpire);
                }
                log.debug("Setting every-distinct msec-to-expire to " + msecToExpire);
            } else if (expr.isConstantResult()) {
                log.warn(
                        "Every-distinct node utilizes an expression returning a constant value, please check expression '"
                                + expr.toExpressionString()
                                + "', not adding expression to distinct-value expression list");
            } else {
                distinctExpressions.add(expr);
            }
        }
        if (distinctExpressions.isEmpty()) {
            throw new ExprValidationException(
                    "Every-distinct node requires one or more distinct-value expressions that each return non-constant result values");
        }
        distinctNode.setDistinctExpressions(distinctExpressions, msecToExpire);
    } else if (evalNode instanceof EvalMatchUntilFactoryNode) {
        EvalMatchUntilFactoryNode matchUntilNode = (EvalMatchUntilFactoryNode) evalNode;

        // compile bounds expressions, if any
        MatchEventSpec untilMatchEventSpec = new MatchEventSpec(tags.getTaggedEventTypes(),
                tags.getArrayEventTypes());
        StreamTypeService streamTypeService = getStreamTypeService(context.getEngineURI(),
                context.getStatementId(), context.getEventAdapterService(),
                untilMatchEventSpec.getTaggedEventTypes(), untilMatchEventSpec.getArrayEventTypes(),
                subexpressionIdStack, "until");
        ExprValidationContext validationContext = new ExprValidationContext(streamTypeService,
                context.getMethodResolutionService(), null, context.getSchedulingService(),
                context.getVariableService(), evaluatorContext, context.getEventAdapterService(),
                context.getStatementName(), context.getStatementId(), context.getAnnotations(),
                context.getContextDescriptor());

        String message = "Match-until bounds value expressions must return a numeric value";
        if (matchUntilNode.getLowerBounds() != null) {
            ExprNode validated = ExprNodeUtility.getValidatedSubtree(matchUntilNode.getLowerBounds(),
                    validationContext);
            matchUntilNode.setLowerBounds(validated);
            if ((validated.getExprEvaluator().getType() == null)
                    || (!JavaClassHelper.isNumeric(validated.getExprEvaluator().getType()))) {
                throw new ExprValidationException(message);
            }
        }

        if (matchUntilNode.getUpperBounds() != null) {
            ExprNode validated = ExprNodeUtility.getValidatedSubtree(matchUntilNode.getUpperBounds(),
                    validationContext);
            matchUntilNode.setUpperBounds(validated);
            if ((validated.getExprEvaluator().getType() == null)
                    || (!JavaClassHelper.isNumeric(validated.getExprEvaluator().getType()))) {
                throw new ExprValidationException(message);
            }
        }

        MatchedEventConvertor convertor = new MatchedEventConvertorImpl(
                untilMatchEventSpec.getTaggedEventTypes(), untilMatchEventSpec.getArrayEventTypes(),
                allTagNamesOrdered, context.getEventAdapterService());
        matchUntilNode.setConvertor(convertor);

        // compile new tag lists
        Set<String> arrayTags = null;
        EvalNodeAnalysisResult matchUntilAnalysisResult = EvalNodeUtil
                .recursiveAnalyzeChildNodes(matchUntilNode.getChildNodes().get(0));
        for (EvalFilterFactoryNode filterNode : matchUntilAnalysisResult.getFilterNodes()) {
            String optionalTag = filterNode.getEventAsName();
            if (optionalTag != null) {
                if (arrayTags == null) {
                    arrayTags = new HashSet<String>();
                }
                arrayTags.add(optionalTag);
            }
        }

        if (arrayTags != null) {
            for (String arrayTag : arrayTags) {
                if (!tags.getArrayEventTypes().containsKey(arrayTag)) {
                    tags.getArrayEventTypes().put(arrayTag, tags.getTaggedEventTypes().get(arrayTag));
                    tags.getTaggedEventTypes().remove(arrayTag);
                }
            }
        }
        matchUntilNode.setTagsArrayedSet(getIndexesForTags(allTagNamesOrdered, arrayTags));
    } else if (evalNode instanceof EvalFollowedByFactoryNode) {
        EvalFollowedByFactoryNode followedByNode = (EvalFollowedByFactoryNode) evalNode;
        StreamTypeService streamTypeService = new StreamTypeServiceImpl(context.getEngineURI(), false);
        ExprValidationContext validationContext = new ExprValidationContext(streamTypeService,
                context.getMethodResolutionService(), null, context.getSchedulingService(),
                context.getVariableService(), evaluatorContext, context.getEventAdapterService(),
                context.getStatementName(), context.getStatementId(), context.getAnnotations(),
                context.getContextDescriptor());

        if (followedByNode.getOptionalMaxExpressions() != null) {
            List<ExprNode> validated = new ArrayList<ExprNode>();
            for (ExprNode maxExpr : followedByNode.getOptionalMaxExpressions()) {
                if (maxExpr == null) {
                    validated.add(null);
                } else {
                    ExprNodeSummaryVisitor visitor = new ExprNodeSummaryVisitor();
                    maxExpr.accept(visitor);
                    if (!visitor.isPlain()) {
                        String errorMessage = "Invalid maximum expression in followed-by, "
                                + visitor.getMessage() + " are not allowed within the expression";
                        log.error(errorMessage);
                        throw new ExprValidationException(errorMessage);
                    }

                    ExprNode validatedExpr = ExprNodeUtility.getValidatedSubtree(maxExpr, validationContext);
                    validated.add(validatedExpr);
                    if ((validatedExpr.getExprEvaluator().getType() == null)
                            || (!JavaClassHelper.isNumeric(validatedExpr.getExprEvaluator().getType()))) {
                        String message = "Invalid maximum expression in followed-by, the expression must return an integer value";
                        throw new ExprValidationException(message);
                    }
                }
            }
            followedByNode.setOptionalMaxExpressions(validated);
        }
    }

    if (newTaggedEventTypes != null) {
        tags.getTaggedEventTypes().putAll(newTaggedEventTypes);
    }
    if (newArrayEventTypes != null) {
        tags.getArrayEventTypes().putAll(newArrayEventTypes);
    }
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractBillingController.java

private void pushInvoiceToMap(LinkedHashMap<ServiceResourceType, ArrayList<Invoice>> chargesMap,
        ServiceResourceType serviceResourceType, Invoice invoice, List<Invoice> newServiceInvoices,
        List<Invoice> renewServiceInvoices) {
    if (serviceResourceType == null) {
        if (invoice.getType().equals(com.vmops.model.Invoice.Type.Subscription)) {
            newServiceInvoices.add(invoice);
        } else {/*from www  .java 2 s.  com*/
            renewServiceInvoices.add(invoice);
        }
        return;
    }
    if (chargesMap.containsKey(serviceResourceType)) {
        chargesMap.get(serviceResourceType).add(invoice);
    } else {
        ArrayList<Invoice> newInvoiceList = new ArrayList<Invoice>();
        newInvoiceList.add(invoice);
        chargesMap.put(serviceResourceType, newInvoiceList);
    }
}