Example usage for java.util LinkedHashSet add

List of usage examples for java.util LinkedHashSet add

Introduction

In this page you can find the example usage for java.util LinkedHashSet add.

Prototype

boolean add(E e);

Source Link

Document

Adds the specified element to this set if it is not already present (optional operation).

Usage

From source file:com.cwctravel.hudson.plugins.extended_choice_parameter.ExtendedChoiceParameterDefinition.java

LinkedHashMap<String, LinkedHashSet<String>> calculateChoicesByDropdownId() throws Exception {
    File file = new File(propertyFile);
    List<String[]> fileLines = Collections.emptyList();
    if (file.isFile()) {
        CSVReader csvReader = null;//from  w w w.jav  a  2  s  .  c o  m
        try {
            csvReader = new CSVReader(new FileReader(file), '\t');
            fileLines = csvReader.readAll();
        } finally {
            csvReader.close();
        }
    } else {
        URL propertyFileUrl = new URL(propertyFile);
        CSVReader csvReader = null;
        try {
            csvReader = new CSVReader(new InputStreamReader(propertyFileUrl.openStream()), '\t');
            fileLines = csvReader.readAll();
        } finally {
            csvReader.close();
        }
    }

    if (fileLines.size() < 2) {
        throw new Exception("Multi level tab delimited file must have at least 2 "
                + "lines (one for the header, and one or more for the data)");
    }

    ArrayList<Integer> columnIndicesForDropDowns = columnIndicesForDropDowns(fileLines.get(0));

    List<String[]> dataLines = fileLines.subList(1, fileLines.size());

    LinkedHashMap<String, LinkedHashSet<String>> choicesByDropdownId = new LinkedHashMap<String, LinkedHashSet<String>>();

    String prefix = getName() + " dropdown MultiLevelMultiSelect 0";
    choicesByDropdownId.put(prefix, new LinkedHashSet<String>());

    for (int i = 0; i < columnIndicesForDropDowns.size(); ++i) {
        String prettyCurrentColumnName = value.split(",")[i];
        prettyCurrentColumnName = prettyCurrentColumnName.toLowerCase();
        prettyCurrentColumnName = prettyCurrentColumnName.replace("_", " ");

        for (String[] dataLine : dataLines) {
            String priorLevelDropdownId = prefix;
            String currentLevelDropdownId = prefix;

            int column = 0;
            for (int j = 0; j <= i; ++j) {
                column = columnIndicesForDropDowns.get(j);

                if (j < i) {
                    priorLevelDropdownId += " " + dataLine[column];
                }
                currentLevelDropdownId += " " + dataLine[column];
            }
            if (i != columnIndicesForDropDowns.size() - 1) {
                choicesByDropdownId.put(currentLevelDropdownId, new LinkedHashSet<String>());
            }
            LinkedHashSet<String> choicesForPriorDropdown = choicesByDropdownId.get(priorLevelDropdownId);
            choicesForPriorDropdown.add("Select a " + prettyCurrentColumnName + "...");
            choicesForPriorDropdown.add(dataLine[column]);
        }
    }

    return choicesByDropdownId;
}

From source file:ubic.gemma.core.loader.expression.geo.model.GeoValues.java

/**
 * Only call this to add a sample for which there are no data.
 *
 * @param sample geo sample/*from w ww  .  ja  va2s  .c o m*/
 */
public void addSample(GeoSample sample) {
    GeoPlatform platform = sample.getPlatforms().iterator().next();

    if (platform.getTechnology().equals(PlatformType.MPSS)
            || platform.getTechnology().equals(PlatformType.SAGE)) {
        /*
         * We're not going to add data for this. Setting this false is a bit redundant (see
         * GeoPlatform.useDataFromGeo) but can't hurt.
         */
        platform.setUseDataFromGEO(false);

    } else if (!sampleDimensions.containsKey(platform)) {
        /*
         * Problem: if this is the first sample, we don't know how many quantitation types to expect. However, for
         * some data sets, there is no data provided in the SOFT file (e.g., RNA-seq), so this would be okay.
         */
        if (sample.isMightNotHaveDataInFile()) {
            this.addSample(sample, 0);
            GeoValues.log
                    .warn("Data not anticipated to be present (RNA-seq etc.), adding dummy quantitation type");
            return;
            // throw new IllegalStateException( "Samples must have a platform assigned." );
        }

        // exon array data sets are sometimes missing the data, which we compute later anyway from CEL files.
        // See bug 3981 and GSE28383 and GSE28886
        if (GeoPlatform.isAffymetrixExonArray(platform.getGeoAccession())) {
            this.addSample(sample, 0);
            sample.setMightNotHaveDataInFile(true);
            GeoValues.log
                    .warn("Data not anticipated to be usable (exon arrays), adding dummy quantitation type");
            return;
        }

        this.addSample(sample, 0);
        sample.setMightNotHaveDataInFile(true);
        GeoValues.log.warn("Sample lacks data, no data will be imported for this data set");
        platform.setUseDataFromGEO(false);

        // throw new UnsupportedOperationException(
        // "Can't deal with empty samples when that sample is the first one on its platform." );

    } else {
        Map<Integer, LinkedHashSet<GeoSample>> samplePlatformMap = sampleDimensions.get(platform);
        for (Integer quantitationTypeIndex : samplePlatformMap.keySet()) {
            LinkedHashSet<GeoSample> sampleQtMap = samplePlatformMap.get(quantitationTypeIndex);
            sampleQtMap.add(sample);
        }
    }

}

From source file:com.evolveum.midpoint.test.ldap.OpenDJController.java

private LinkedHashSet<String> getSearchAttributes() {
    LinkedHashSet<String> attrs = new LinkedHashSet<String>();
    attrs.add("*");
    attrs.add("ds-pwp-account-disabled");
    return attrs;
}

From source file:com.aurel.track.teamgeist.TeamgeistServicesTest.java

/**
 * This method returns a Set containing all action names used by Teamgeist.
 * This actions are in: TEAMGEIST_SRC_DIR/services/Services.cpp
 * @return/*from  w ww . j  av a  2  s .  c o m*/
 */
LinkedHashSet<String> getActinNames() {
    String srcPath = getSrcPath();
    File file = new File(srcPath);
    LinkedHashSet<String> actionNameSet = null;
    try {
        if (file.exists() && !file.isDirectory()) {
            BufferedReader br = new BufferedReader(new FileReader(file));
            String line;
            Pattern pattern = Pattern.compile(".*[\"]{1}((.*[.]{1}action)[?]?.*)\".*");
            Matcher matcher;
            while ((line = br.readLine()) != null) {
                if (line.contains(".action")) {
                    if (actionNameSet == null) {
                        actionNameSet = new LinkedHashSet<String>();
                    }
                    matcher = pattern.matcher(line);
                    if (matcher.find()) {
                        String actionName = matcher.group(2);
                        actionNameSet.add(actionName);
                    }
                }
            }
            br.close();
        }
    } catch (IOException ioEx) {
        ioEx.printStackTrace();
    }
    return actionNameSet;
}

From source file:ubic.gemma.loader.expression.geo.model.GeoValues.java

/**
 * Only needs to be called 'externally' if you know there is no data for the sample.
 * // w  w w  .jav  a 2  s .  c  om
 * @param sample
 * @param quantitationTypeIndex
 * @return
 */
private GeoPlatform addSample(GeoSample sample, Integer quantitationTypeIndex) {
    if (sample.getPlatforms().size() > 1) {
        throw new IllegalArgumentException(sample + ": Can't handle samples that use multiple platforms");
    }

    GeoPlatform platform = sample.getPlatforms().iterator().next();
    if (!sampleDimensions.containsKey(platform)) {
        sampleDimensions.put(platform, new HashMap<Object, LinkedHashSet<GeoSample>>());
    }

    Map<Object, LinkedHashSet<GeoSample>> samplePlatformMap = sampleDimensions.get(platform);
    if (!samplePlatformMap.containsKey(quantitationTypeIndex)) {
        samplePlatformMap.put(quantitationTypeIndex, new LinkedHashSet<GeoSample>());
    }

    LinkedHashSet<GeoSample> sampleQtMap = samplePlatformMap.get(quantitationTypeIndex);
    if (!sampleQtMap.contains(sample)) {
        sampleQtMap.add(sample);
    }
    return platform;
}

From source file:org.pentaho.reporting.engine.classic.extensions.datasources.olap4j.AbstractMDXDataFactory.java

public String[] getReferencedFields(final String queryName, final DataRow parameter)
        throws ReportDataFactoryException {
    final boolean isNewConnection = connection == null;
    try {//w w  w.jav  a2  s  .co  m
        if (connection == null) {
            connection = connectionProvider.createConnection(computeJdbcUser(parameter),
                    computeJdbcPassword(parameter));
            connection.setLocale(getLocale());

            final String role = computeRole(parameter);
            if (role != null) {
                connection.setRoleName(role);
            }
        }

        final MDXCompiler compiler = new MDXCompiler(parameter, getLocale());
        final String value = computedQuery(queryName, parameter);
        final String translatedQuery = compiler.translateAndLookup(value, parameter);
        final LinkedHashSet<String> params = new LinkedHashSet<String>();
        params.addAll(compiler.getParameter());
        if (getRoleField() != null) {
            params.add(getRoleField());
        }
        if (getJdbcPasswordField() != null) {
            params.add(getJdbcPasswordField());
        }
        if (getJdbcUserField() != null) {
            params.add(getJdbcUserField());
        }
        final PreparedOlapStatement statement = connection.prepareOlapStatement(translatedQuery);

        final OlapParameterMetaData data = statement.getParameterMetaData();
        final int count = data.getParameterCount();
        for (int i = 0; i < count; i++) {
            final String parameterName = data.getParameterName(i + 1);
            params.add(parameterName);
        }
        params.add(DataFactory.QUERY_LIMIT);
        return params.toArray(new String[params.size()]);
    } catch (final Throwable e) {
        throw new ReportDataFactoryException("Failed to obtain a connection", e);
    } finally {
        if (isNewConnection) {
            close();
        }
    }
}

From source file:com.android.phone.common.mail.store.ImapFolder.java

public void fetchInternal(Message[] messages, FetchProfile fp, MessageRetrievalListener listener)
        throws MessagingException {
    if (messages.length == 0) {
        return;/*w  ww  . j a v  a2s .c  om*/
    }
    checkOpen();
    HashMap<String, Message> messageMap = new HashMap<String, Message>();
    for (Message m : messages) {
        messageMap.put(m.getUid(), m);
    }

    /*
     * Figure out what command we are going to run:
     * FLAGS     - UID FETCH (FLAGS)
     * ENVELOPE  - UID FETCH (INTERNALDATE UID RFC822.SIZE FLAGS BODY.PEEK[
     *                            HEADER.FIELDS (date subject from content-type to cc)])
     * STRUCTURE - UID FETCH (BODYSTRUCTURE)
     * BODY_SANE - UID FETCH (BODY.PEEK[]<0.N>) where N = max bytes returned
     * BODY      - UID FETCH (BODY.PEEK[])
     * Part      - UID FETCH (BODY.PEEK[ID]) where ID = mime part ID
     */

    final LinkedHashSet<String> fetchFields = new LinkedHashSet<String>();

    fetchFields.add(ImapConstants.UID);
    if (fp.contains(FetchProfile.Item.FLAGS)) {
        fetchFields.add(ImapConstants.FLAGS);
    }
    if (fp.contains(FetchProfile.Item.ENVELOPE)) {
        fetchFields.add(ImapConstants.INTERNALDATE);
        fetchFields.add(ImapConstants.RFC822_SIZE);
        fetchFields.add(ImapConstants.FETCH_FIELD_HEADERS);
    }
    if (fp.contains(FetchProfile.Item.STRUCTURE)) {
        fetchFields.add(ImapConstants.BODYSTRUCTURE);
    }

    if (fp.contains(FetchProfile.Item.BODY_SANE)) {
        fetchFields.add(ImapConstants.FETCH_FIELD_BODY_PEEK_SANE);
    }
    if (fp.contains(FetchProfile.Item.BODY)) {
        fetchFields.add(ImapConstants.FETCH_FIELD_BODY_PEEK);
    }

    // TODO Why are we only fetching the first part given?
    final Part fetchPart = fp.getFirstPart();
    if (fetchPart != null) {
        final String[] partIds = fetchPart.getHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA);
        // TODO Why can a single part have more than one Id? And why should we only fetch
        // the first id if there are more than one?
        if (partIds != null) {
            fetchFields.add(ImapConstants.FETCH_FIELD_BODY_PEEK_BARE + "[" + partIds[0] + "]");
        }
    }

    try {
        mConnection.sendCommand(String.format(Locale.US, ImapConstants.UID_FETCH + " %s (%s)",
                ImapStore.joinMessageUids(messages),
                Utility.combine(fetchFields.toArray(new String[fetchFields.size()]), ' ')), false);
        ImapResponse response;
        do {
            response = null;
            try {
                response = mConnection.readResponse();

                if (!response.isDataResponse(1, ImapConstants.FETCH)) {
                    continue; // Ignore
                }
                final ImapList fetchList = response.getListOrEmpty(2);
                final String uid = fetchList.getKeyedStringOrEmpty(ImapConstants.UID).getString();
                if (TextUtils.isEmpty(uid))
                    continue;

                ImapMessage message = (ImapMessage) messageMap.get(uid);
                if (message == null)
                    continue;

                if (fp.contains(FetchProfile.Item.FLAGS)) {
                    final ImapList flags = fetchList.getKeyedListOrEmpty(ImapConstants.FLAGS);
                    for (int i = 0, count = flags.size(); i < count; i++) {
                        final ImapString flag = flags.getStringOrEmpty(i);
                        if (flag.is(ImapConstants.FLAG_DELETED)) {
                            message.setFlagInternal(Flag.DELETED, true);
                        } else if (flag.is(ImapConstants.FLAG_ANSWERED)) {
                            message.setFlagInternal(Flag.ANSWERED, true);
                        } else if (flag.is(ImapConstants.FLAG_SEEN)) {
                            message.setFlagInternal(Flag.SEEN, true);
                        } else if (flag.is(ImapConstants.FLAG_FLAGGED)) {
                            message.setFlagInternal(Flag.FLAGGED, true);
                        }
                    }
                }
                if (fp.contains(FetchProfile.Item.ENVELOPE)) {
                    final Date internalDate = fetchList.getKeyedStringOrEmpty(ImapConstants.INTERNALDATE)
                            .getDateOrNull();
                    final int size = fetchList.getKeyedStringOrEmpty(ImapConstants.RFC822_SIZE)
                            .getNumberOrZero();
                    final String header = fetchList
                            .getKeyedStringOrEmpty(ImapConstants.BODY_BRACKET_HEADER, true).getString();

                    message.setInternalDate(internalDate);
                    message.setSize(size);
                    message.parse(Utility.streamFromAsciiString(header));
                }
                if (fp.contains(FetchProfile.Item.STRUCTURE)) {
                    ImapList bs = fetchList.getKeyedListOrEmpty(ImapConstants.BODYSTRUCTURE);
                    if (!bs.isEmpty()) {
                        try {
                            parseBodyStructure(bs, message, ImapConstants.TEXT);
                        } catch (MessagingException e) {
                            LogUtils.v(TAG, e, "Error handling message");
                            message.setBody(null);
                        }
                    }
                }
                if (fp.contains(FetchProfile.Item.BODY) || fp.contains(FetchProfile.Item.BODY_SANE)) {
                    // Body is keyed by "BODY[]...".
                    // Previously used "BODY[..." but this can be confused with "BODY[HEADER..."
                    // TODO Should we accept "RFC822" as well??
                    ImapString body = fetchList.getKeyedStringOrEmpty("BODY[]", true);
                    InputStream bodyStream = body.getAsStream();
                    message.parse(bodyStream);
                }
                if (fetchPart != null) {
                    InputStream bodyStream = fetchList.getKeyedStringOrEmpty("BODY[", true).getAsStream();
                    String encodings[] = fetchPart.getHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING);

                    String contentTransferEncoding = null;
                    if (encodings != null && encodings.length > 0) {
                        contentTransferEncoding = encodings[0];
                    } else {
                        // According to http://tools.ietf.org/html/rfc2045#section-6.1
                        // "7bit" is the default.
                        contentTransferEncoding = "7bit";
                    }

                    try {
                        // TODO Don't create 2 temp files.
                        // decodeBody creates BinaryTempFileBody, but we could avoid this
                        // if we implement ImapStringBody.
                        // (We'll need to share a temp file.  Protect it with a ref-count.)
                        fetchPart.setBody(decodeBody(mStore.getContext(), bodyStream, contentTransferEncoding,
                                fetchPart.getSize(), listener));
                    } catch (Exception e) {
                        // TODO: Figure out what kinds of exceptions might actually be thrown
                        // from here. This blanket catch-all is because we're not sure what to
                        // do if we don't have a contentTransferEncoding, and we don't have
                        // time to figure out what exceptions might be thrown.
                        LogUtils.e(TAG, "Error fetching body %s", e);
                    }
                }

                if (listener != null) {
                    listener.messageRetrieved(message);
                }
            } finally {
                destroyResponses();
            }
        } while (!response.isTagged());
    } catch (IOException ioe) {
        throw ioExceptionHandler(mConnection, ioe);
    }
}

From source file:eionet.cr.web.util.columns.ReferringPredicatesColumn.java

@Override
public String format(Object object) {

    if (object instanceof SubjectDTO) {

        SubjectDTO subjectDTO = (SubjectDTO) object;

        // Collect labels of all predicates pointing to referringToHash (ignore derived object values).

        LinkedHashSet<String> labels = new LinkedHashSet<String>();
        Map<String, Collection<ObjectDTO>> predicatesObjects = subjectDTO.getPredicates();
        if (predicatesObjects != null && !predicatesObjects.isEmpty()) {

            for (String predicate : predicatesObjects.keySet()) {

                Collection<ObjectDTO> objects = predicatesObjects.get(predicate);
                if (objects != null && !objects.isEmpty()) {

                    for (ObjectDTO objectDTO : objects) {

                        if (objectDTO.getSourceObjectHash() == 0 && objectDTO.getHash() == referringToHash) {

                            String predicateLabel = JstlFunctions
                                    .getPredicateLabel(actionBean.getPredicateLabels(), predicate);
                            labels.add(predicateLabel);
                        }/*from  ww  w  .  j a v  a2 s.c om*/
                    }
                }
            }
        }

        // Return the above-found labels as a comma-separated list.
        return labels.isEmpty() ? StringUtils.EMPTY : Util.toCSV(labels);
    } else {
        return object == null ? StringUtils.EMPTY : object.toString();
    }
}

From source file:com.rapidminer.gui.plotter.charts.SeriesChartPlotter.java

@Override
protected void updatePlotter() {
    int categoryCount = prepareData();
    String maxClassesProperty = ParameterService
            .getParameterValue(MainFrame.PROPERTY_RAPIDMINER_GUI_PLOTTER_COLORS_CLASSLIMIT);
    int maxClasses = 20;
    try {//from ww  w  .j  ava  2  s  .co m
        if (maxClassesProperty != null) {
            maxClasses = Integer.parseInt(maxClassesProperty);
        }
    } catch (NumberFormatException e) {
        // LogService.getGlobal().log("Series plotter: cannot parse property 'rapidminer.gui.plotter.colors.classlimit', using maximal 20 different classes.",
        // LogService.WARNING);
        LogService.getRoot().log(Level.WARNING,
                "com.rapidminer.gui.plotter.charts.SeriesChartPlotter.parsing_property_error");
    }
    boolean createLegend = categoryCount > 0 && categoryCount < maxClasses;

    JFreeChart chart = createChart(this.dataset, createLegend);

    // set the background color for the chart...
    chart.setBackgroundPaint(Color.white);

    // domain axis
    if (axis[INDEX] >= 0) {
        if (!dataTable.isNominal(axis[INDEX])) {
            if (dataTable.isDate(axis[INDEX]) || dataTable.isDateTime(axis[INDEX])) {
                DateAxis domainAxis = new DateAxis(dataTable.getColumnName(axis[INDEX]));
                domainAxis.setTimeZone(Tools.getPreferredTimeZone());
                chart.getXYPlot().setDomainAxis(domainAxis);
                if (getRangeForDimension(axis[INDEX]) != null) {
                    domainAxis.setRange(getRangeForDimension(axis[INDEX]));
                }
                domainAxis.setLabelFont(LABEL_FONT_BOLD);
                domainAxis.setTickLabelFont(LABEL_FONT);
                domainAxis.setVerticalTickLabels(isLabelRotating());
            }
        } else {
            LinkedHashSet<String> values = new LinkedHashSet<String>();
            for (DataTableRow row : dataTable) {
                String stringValue = dataTable.mapIndex(axis[INDEX], (int) row.getValue(axis[INDEX]));
                if (stringValue.length() > 40) {
                    stringValue = stringValue.substring(0, 40);
                }
                values.add(stringValue);
            }
            ValueAxis categoryAxis = new SymbolAxis(dataTable.getColumnName(axis[INDEX]),
                    values.toArray(new String[values.size()]));
            categoryAxis.setLabelFont(LABEL_FONT_BOLD);
            categoryAxis.setTickLabelFont(LABEL_FONT);
            categoryAxis.setVerticalTickLabels(isLabelRotating());
            chart.getXYPlot().setDomainAxis(categoryAxis);
        }
    }

    // legend settings
    LegendTitle legend = chart.getLegend();
    if (legend != null) {
        legend.setPosition(RectangleEdge.TOP);
        legend.setFrame(BlockBorder.NONE);
        legend.setHorizontalAlignment(HorizontalAlignment.LEFT);
        legend.setItemFont(LABEL_FONT);
    }

    AbstractChartPanel panel = getPlotterPanel();
    if (panel == null) {
        panel = createPanel(chart);
    } else {
        panel.setChart(chart);
    }

    // ATTENTION: WITHOUT THIS WE GET SEVERE MEMORY LEAKS!!!
    panel.getChartRenderingInfo().setEntityCollection(null);
}

From source file:com.moded.extendedchoiceparameter.ExtendedChoiceParameterDefinition.java

LinkedHashMap<String, LinkedHashSet<String>> calculateChoicesByDropdownId() throws Exception {
    List<String[]> fileLines = new CSVReader(new FileReader(propertyFile), '\t').readAll();

    if (fileLines.size() < 2) {
        throw new Exception("Multi level tab delimited file must have at least 2 "
                + "lines (one for the header, and one or more for the data)");
    }//from   ww w  . jav  a  2s.c  o m

    ArrayList<Integer> columnIndicesForDropDowns = columnIndicesForDropDowns(fileLines.get(0));

    List<String[]> dataLines = fileLines.subList(1, fileLines.size());

    LinkedHashMap<String, LinkedHashSet<String>> choicesByDropdownId = new LinkedHashMap<String, LinkedHashSet<String>>();

    String prefix = getName() + " dropdown MultiLevelMultiSelect 0";
    choicesByDropdownId.put(prefix, new LinkedHashSet<String>());

    for (int i = 0; i < columnIndicesForDropDowns.size(); ++i) {
        String prettyCurrentColumnName = value.split(",")[i];
        prettyCurrentColumnName = prettyCurrentColumnName.toLowerCase();
        prettyCurrentColumnName = prettyCurrentColumnName.replace("_", " ");

        for (String[] dataLine : dataLines) {
            String priorLevelDropdownId = prefix;
            String currentLevelDropdownId = prefix;

            int column = 0;
            for (int j = 0; j <= i; ++j) {
                column = columnIndicesForDropDowns.get(j);

                if (j < i) {
                    priorLevelDropdownId += " " + dataLine[column];
                }
                currentLevelDropdownId += " " + dataLine[column];
            }
            if (i != columnIndicesForDropDowns.size() - 1) {
                choicesByDropdownId.put(currentLevelDropdownId, new LinkedHashSet<String>());
            }
            LinkedHashSet<String> choicesForPriorDropdown = choicesByDropdownId.get(priorLevelDropdownId);
            choicesForPriorDropdown.add("Select a " + prettyCurrentColumnName + "...");
            choicesForPriorDropdown.add(dataLine[column]);
        }
    }

    return choicesByDropdownId;
}