Example usage for java.util LinkedHashMap entrySet

List of usage examples for java.util LinkedHashMap entrySet

Introduction

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

Prototype

public Set<Map.Entry<K, V>> entrySet() 

Source Link

Document

Returns a Set view of the mappings contained in this map.

Usage

From source file:org.bimserver.charting.SupportFunctions.java

public static ArrayList<LinkedHashMap<String, Object>> getIfcDataByClassWithTreeStructure(
        String structureKeyword, IfcModelInterface model, Chart chart, int superClassesToStepBackwardsThrough) {
    ArrayList<LinkedHashMap<String, Object>> rawData = new ArrayList<>();
    // Prepare for static iteration.
    LinkedHashMap<Class<? extends IfcProduct>, Integer> ifcProductClassCounts = new LinkedHashMap<>();
    // Iterate only the products.
    for (IfcProduct ifcProduct : model.getAllWithSubTypes(IfcProduct.class)) {
        Class<? extends IfcProduct> key = ifcProduct.getClass();
        Integer value = 0;//from ww  w  .j a va 2  s .com
        if (ifcProductClassCounts.containsKey(key))
            value = ifcProductClassCounts.get(key);
        ifcProductClassCounts.put(key, value + 1);
    }
    // Derive the column names.
    ArrayList<String> hierarchyColumnNames = new ArrayList<>();
    superClassesToStepBackwardsThrough = Math.max(0, superClassesToStepBackwardsThrough);
    String leafColumnName = String.format("%s%d", structureKeyword, superClassesToStepBackwardsThrough + 1);
    for (int i = 0; i < superClassesToStepBackwardsThrough + 1; i++)
        hierarchyColumnNames.add(String.format("%s%d", structureKeyword, i + 1));
    // Update the chart configuration.
    chart.setDimensionLookupKeys(structureKeyword, hierarchyColumnNames);
    chart.setDimensionLookupKey("size", "size");
    chart.setDimensionLookupKey("label", "label");
    chart.setDimensionLookupKey("color", "size");
    // Add each entry.
    for (Entry<Class<? extends IfcProduct>, Integer> countedEntry : ifcProductClassCounts.entrySet()) {
        // Prepare to store this raw data entry.
        LinkedHashMap<String, Object> dataEntry = new LinkedHashMap<>();
        //
        Integer count = countedEntry.getValue();
        Class<? extends IfcProduct> productClass = countedEntry.getKey();
        // Sanitize.
        String className = getSanitizedSimpleClassName(productClass);
        // Name the group.
        String name = String.format("%s (%s)", className, count);
        dataEntry.put(leafColumnName, name);
        // Step back through the inheritance of the IfcProduct.
        if (superClassesToStepBackwardsThrough > 0) {
            Class<?> childClass = productClass;
            for (int i = superClassesToStepBackwardsThrough - 1; i >= 0; i--) {
                String thisColumnName = String.format("%s%d", structureKeyword, i + 1);
                Class<?> superClass = childClass.getSuperclass();
                String enclosingClassName = getSanitizedSimpleClassName(superClass);
                dataEntry.put(thisColumnName, enclosingClassName);
                // Update pointer.
                childClass = superClass;
            }
        }
        dataEntry.put("size", count);
        dataEntry.put("label", name);
        // Push the entry into the data pool.
        rawData.add(dataEntry);
    }
    // Send it all back.
    return rawData;
}

From source file:org.finra.herd.service.helper.Hive13DdlGeneratorTest.java

@Test
public void testEscapeSingleQuotes() {
    // Create a test vector with key=input and value=output values.
    LinkedHashMap<String, String> testVector = new LinkedHashMap<>();
    testVector.put("some text without single quotes", "some text without single quotes");
    testVector.put("'some \\'text\\' with single 'quotes'", "\\'some \\'text\\' with single \\'quotes\\'");
    testVector.put("'", "\\'");
    testVector.put("''''", "\\'\\'\\'\\'");
    testVector.put("'", "\\'");
    testVector.put("'\'\\'", "\\'\\'\\'");

    // Loop over all entries in the test vector.
    for (Object set : testVector.entrySet()) {
        Map.Entry<?, ?> entry = (Map.Entry<?, ?>) set;
        assertEquals(entry.getValue(), hive13DdlGenerator.escapeSingleQuotes((String) entry.getKey()));
    }/*from   w w w .  j av  a  2s . co m*/
}

From source file:com.alibaba.wasp.plan.parser.druid.DruidDDLParser.java

/**
 * Process Create Table Statement and generate Execute Plan
 * //from   w w  w  . ja v  a  2s  .c  o m
 */
private void getCreateTablePlan(ParseContext context, WaspSqlCreateTableStatement waspSqlCreateTableStatement,
        MetaEventOperation metaEventOperation) throws IOException {
    /**
     * example String sql3 = "CREATE TABLE User {Required Int64 user_id;
     * Required String name; Optional String phone;} primary key(user_id),ENTITY
     * GROUP ROOT, Entity Group Key(user_id);" ; String sql4 = "CREATE TABLE
     * Photo { Required Int64 user_id columnfamily cf comment 'aaa'; Required
     * Int32 photo_id comment 'child primary key'; Required Int64 time; Required
     * String full_url; Optional String thumbnail_url; Repeated String tag; }
     * primary key(user_id, photo_id) IN TABLE user,ENTITY GROUP KEY(user_id)
     * references User;";
     */

    // Table Info
    SQLExprTableSource tableSource = waspSqlCreateTableStatement.getTableSource();
    String tableName = parseFromClause(tableSource);
    // Check Table Name is legal.
    metaEventOperation.isLegalTableName(tableName);
    // Check if the table exists
    boolean tableNotExit = metaEventOperation.checkTableNotExists(tableName, true);
    if (!tableNotExit) {
        if (waspSqlCreateTableStatement.isIfNotExiists()) {
            context.setPlan(new NotingTodoPlan());
            LOG.debug("table " + tableName + " exits , isIfNotExiists is true, ignore");
            return;
        } else {
            throw new TableExistsException(tableName + " is already exists!");
        }
    }

    // Table category.
    WaspSqlCreateTableStatement.TableCategory category = waspSqlCreateTableStatement.getCategory();
    FTable.TableType tableType = FTable.TableType.CHILD;
    if (category != null && category == WaspSqlCreateTableStatement.TableCategory.ROOT) {
        tableType = FTable.TableType.ROOT;
    }

    // Primary Key.
    List<SQLExpr> primaryKeysSQLExpr = waspSqlCreateTableStatement.getPrimaryKeys();
    // table columns.
    List<SQLTableElement> tableElementList = waspSqlCreateTableStatement.getTableElementList(); // columns info
    LinkedHashMap<String, Field> columns = new LinkedHashMap<String, Field>();
    for (SQLTableElement element : tableElementList) {
        Field field = parse(element);
        columns.put(field.getName(), field);
    }
    // Check if columns are legal.
    metaEventOperation.areLegalTableColumns(null, columns.values());
    checkFamilyLegal(columns.values(), metaEventOperation);

    // Primary keys check will be done in this following method
    LinkedHashMap<String, Field> primaryKeys = parse(primaryKeysSQLExpr, columns);

    long createTime = System.currentTimeMillis();
    long lastAccessTime = createTime;
    String owner = "me";
    FTable table = new FTable(null, tableName, tableType, owner, createTime, lastAccessTime, columns,
            primaryKeys, primaryKeys.entrySet().iterator().next().getValue());
    SQLExpr entityGroupKeySQLExpr = waspSqlCreateTableStatement.getEntityGroupKey();
    Field entityGroupKey = primaryKeys.get(parseName(entityGroupKeySQLExpr));
    if (entityGroupKey == null) {
        throw new UnsupportedException(entityGroupKeySQLExpr + " is ForeignKey, but don't in primaryKeys.");
    }
    table.setEntityGroupKey(entityGroupKey);

    if (tableType == FTable.TableType.CHILD) {
        String parentName = parseFromClause(waspSqlCreateTableStatement.getInTableName());
        table.setParentName(parentName);
        if (!parentName.equals(parseFromClause(waspSqlCreateTableStatement.getReferenceTable()))) {
            throw new UnsupportedException(" in table " + waspSqlCreateTableStatement.getInTableName()
                    + " != references table " + waspSqlCreateTableStatement.getReferenceTable());
        }

        // Check parent's EGK equals child's EGK.
        TableSchemaCacheReader reader = TableSchemaCacheReader.getInstance(configuration);
        FTable parentTable = reader.getSchema(parentName);
        if (parentTable == null) {
            parentTable = TableSchemaCacheReader.getService(reader.getConf()).getTable(tableName);
        }
        if (parentTable == null) {
            throw new TableNotFoundException("Not found parent table:" + parentName);
        }

        if (!parentTable.getEntityGroupKey().getName().equals(table.getEntityGroupKey().getName())) {
            throw new UnsupportedException(
                    "Parent" + parentName + "'s egk doesn't equals Child" + tableName + "'s egk.");
        }

        // Check child's PKS contains parent's PKS.
        for (Field parentPrimaryKey : parentTable.getPrimaryKeys().values()) {
            boolean found = table.getPrimaryKeys().containsKey(parentPrimaryKey.getName());
            if (!found) {
                throw new UnsupportedException("Child's pks must contains parent's pks.");
            }
        }
    }

    SQLPartitioningClause partitioning = waspSqlCreateTableStatement.getPartitioning();
    byte[][] splitKeys = null;
    if (partitioning != null) {
        if (table.isRootTable()) {
            if (partitioning instanceof WaspSqlPartitionByKey) {
                WaspSqlPartitionByKey partitionKey = (WaspSqlPartitionByKey) partitioning;
                byte[] start = convert(null, partitionKey.getStart());
                byte[] end = convert(null, partitionKey.getEnd());
                int partitionCount = convertToInt(partitionKey.getPartitionCount());
                splitKeys = Bytes.split(start, end, partitionCount - 3);
            } else {
                throw new UnsupportedException("Unsupported SQLPartitioningClause " + partitioning);
            }
        } else {
            throw new UnsupportedException("Partition by only supported for Root Table");
        }
    }
    CreateTablePlan createTable = new CreateTablePlan(table, splitKeys);
    context.setPlan(createTable);
    LOG.debug("CreateTablePlan " + createTable.toString());
}

From source file:nl.nn.adapterframework.webcontrol.api.ShowConfigurationStatus.java

@PUT
@RolesAllowed({ "ObserverAccess", "IbisTester", "AdminAccess" })
@Path("/adapters/{adapterName}")
@Consumes(MediaType.APPLICATION_JSON)/*from ww  w  .  j  a  va  2 s  .c o m*/
@Produces(MediaType.APPLICATION_JSON)
public Response updateAdapter(@PathParam("adapterName") String adapterName, LinkedHashMap<String, Object> json)
        throws ApiException {
    initBase(servletConfig);

    Adapter adapter = (Adapter) ibisManager.getRegisteredAdapter(adapterName);

    if (adapter == null) {
        throw new ApiException("Adapter not found!");
    }

    Response.ResponseBuilder response = Response.status(Response.Status.NO_CONTENT); //PUT defaults to no content

    for (Entry<String, Object> entry : json.entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();
        if (key.equalsIgnoreCase("action")) {//Start or stop an adapter!
            String action = null;

            if (value.equals("stop")) {
                action = "stopadapter";
            }
            if (value.equals("start")) {
                action = "startadapter";
            }

            ibisManager.handleAdapter(action, "", adapterName, null, null, false);

            response.entity("{\"status\":\"ok\"}");
        }
    }

    return response.build();
}

From source file:nl.nn.adapterframework.webcontrol.api.ShowConfigurationStatus.java

@PUT
@RolesAllowed({ "ObserverAccess", "IbisTester", "AdminAccess" })
@Path("/adapters/{adapterName}/receivers/{receiverName}")
@Consumes(MediaType.APPLICATION_JSON)//www  .  ja  v a 2s  .  c  om
@Produces(MediaType.APPLICATION_JSON)
public Response updateReceiver(@PathParam("adapterName") String adapterName,
        @PathParam("receiverName") String receiverName, LinkedHashMap<String, Object> json)
        throws ApiException {
    initBase(servletConfig);

    Adapter adapter = (Adapter) ibisManager.getRegisteredAdapter(adapterName);

    if (adapter == null) {
        throw new ApiException("Adapter not found!");
    }

    Response.ResponseBuilder response = Response.status(Response.Status.NO_CONTENT); //PUT defaults to no content

    for (Entry<String, Object> entry : json.entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();
        if (key.equalsIgnoreCase("action")) {//Start or stop an adapter!
            String action = null;

            if (value.equals("stop")) {
                action = "stopreceiver";
            }
            if (value.equals("start")) {
                action = "startreceiver";
            }

            ibisManager.handleAdapter(action, "", adapterName, receiverName, null, false);
            response.entity("{\"status\":\"ok\"}");
        }
    }

    return response.build();
}

From source file:jp.aegif.nemaki.cmis.service.impl.RepositoryServiceImpl.java

private TypeDefinition sortPropertyDefinitions(String repositoryId, NemakiTypeDefinition nemakiTypeDefinition,
        TypeDefinition criterion) {/*from   w  ww .  ja va  2  s.c om*/
    AbstractTypeDefinition tdf = typeManager.buildTypeDefinitionFromDB(repositoryId, nemakiTypeDefinition);
    Map<String, PropertyDefinition<?>> propDefs = tdf.getPropertyDefinitions();

    LinkedHashMap<String, PropertyDefinition<?>> map = new LinkedHashMap<String, PropertyDefinition<?>>();
    LinkedHashMap<String, PropertyDefinition<?>> sorted = new LinkedHashMap<String, PropertyDefinition<?>>();
    if (MapUtils.isNotEmpty(criterion.getPropertyDefinitions())) {
        // Not updated property definitions
        for (Entry<String, PropertyDefinition<?>> propDef : propDefs.entrySet()) {
            if (!criterion.getPropertyDefinitions().containsKey(propDef.getKey())) {
                map.put(propDef.getKey(), propDef.getValue());
            }
        }

        // Sorted updated property definitions
        for (Entry<String, PropertyDefinition<?>> entry : criterion.getPropertyDefinitions().entrySet()) {
            sorted.put(entry.getKey(), entry.getValue());
        }

        // Merge
        for (Entry<String, PropertyDefinition<?>> entry : sorted.entrySet()) {
            map.put(entry.getKey(), entry.getValue());
        }
        tdf.setPropertyDefinitions(map);
    }

    return tdf;
}

From source file:cm.confide.ex.chips.BaseRecipientAdapter.java

/**
 * Constructs an actual list for this Adapter using {@link #mEntryMap}. Also tries to
 * fetch a cached photo for each contact entry (other than separators), or request another
 * thread to get one from directories.//from w  w  w .ja  v  a2s  .c  om
 */
private List<RecipientEntry> constructEntryList(LinkedHashMap<Long, List<RecipientEntry>> entryMap,
        List<RecipientEntry> nonAggregatedEntries) {
    final List<RecipientEntry> entries = new ArrayList<RecipientEntry>();
    int validEntryCount = 0;
    for (Map.Entry<Long, List<RecipientEntry>> mapEntry : entryMap.entrySet()) {
        final List<RecipientEntry> entryList = mapEntry.getValue();
        final int size = entryList.size();
        for (int i = 0; i < size; i++) {
            RecipientEntry entry = entryList.get(i);
            entries.add(entry);
            validEntryCount++;
        }
        if (validEntryCount > mPreferredMaxResultCount) {
            break;
        }
    }
    if (validEntryCount <= mPreferredMaxResultCount) {
        for (RecipientEntry entry : nonAggregatedEntries) {
            if (validEntryCount > mPreferredMaxResultCount) {
                break;
            }
            entries.add(entry);

            validEntryCount++;
        }
    }

    return entries;
}

From source file:be.ugent.maf.cellmissy.gui.controller.analysis.doseresponse.area.AreaDRInputController.java

/**
 * Table model for bottom table: starts from analysis group.
 *
 * @param analysisGroup// ww  w .  j a  va2  s .c  o  m
 * @return
 */
private NonEditableTableModel createTableModel(AreaDoseResponseAnalysisGroup analysisGroup) {
    LinkedHashMap<Double, String> concentrationsMap = analysisGroup.getConcentrationsMap()
            .get(analysisGroup.getTreatmentToAnalyse());
    LinkedHashMap<PlateCondition, List<Double>> velocitiesMap = analysisGroup.getVelocitiesMap();
    //when removing all conditions
    if (velocitiesMap.isEmpty()) {
        return new NonEditableTableModel();
    }

    int maxReplicates = 0;
    for (List<Double> value : velocitiesMap.values()) {
        int replicates = value.size();
        if (replicates > maxReplicates) {
            maxReplicates = replicates;
        }
    }

    Object[][] data = new Object[velocitiesMap.size()][maxReplicates + 2];
    int i = 0;
    int controlIndex = 100;
    int rowIndex = 0;

    for (Map.Entry<PlateCondition, List<Double>> entry : velocitiesMap.entrySet()) {
        //check if this platecondition is the control, save index for table
        for (Treatment treatment : entry.getKey().getTreatmentList()) {
            if (treatment.getTreatmentType().getName().contains("ontrol")) {
                controlIndex = i;
            }
        }
        i++;

        int columnIndex = 2;
        for (Double velocity : entry.getValue()) {

            if (velocity != null && !velocity.isNaN()) {
                // round to three decimals slopes and coefficients
                Double slope = AnalysisUtils.roundThreeDecimals(velocity);
                // show in table slope + (coefficient)
                data[rowIndex][columnIndex] = slope;
            } else if (velocity == null) {
                data[rowIndex][columnIndex] = "excluded";
            } else if (velocity.isNaN()) {
                data[rowIndex][columnIndex] = "NaN";
            }

            columnIndex++;
        }
        rowIndex++;
    }

    if (controlIndex != 100) {
        data[controlIndex][0] = 0.0;
        data[controlIndex][1] = "--";
    }
    rowIndex = 0;
    //if user only selects control, the concentrationsmap is null
    if (concentrationsMap != null) {
        for (Map.Entry<Double, String> entry : concentrationsMap.entrySet()) {
            if (rowIndex >= controlIndex) {
                data[rowIndex + 1][0] = entry.getKey();
                data[rowIndex + 1][1] = entry.getValue();
            } else {
                data[rowIndex][0] = entry.getKey();
                data[rowIndex][1] = entry.getValue();
            }

            rowIndex++;
        }
    }
    // array of column names for table model
    String[] columnNames = new String[data[0].length];
    columnNames[0] = "Conc of " + analysisGroup.getTreatmentToAnalyse();
    columnNames[1] = "Unit";
    for (int x = 2; x < columnNames.length; x++) {
        columnNames[x] = "Repl " + (x - 1);
    }

    NonEditableTableModel nonEditableTableModel = new NonEditableTableModel();
    nonEditableTableModel.setDataVector(data, columnNames);
    return nonEditableTableModel;

}

From source file:com.DGSD.Teexter.UI.Recipient.BaseRecipientAdapter.java

/**
 * Constructs an actual list for this Adapter using {@link #mEntryMap}. Also tries to
 * fetch a cached photo for each contact entry (other than separators), or request another
 * thread to get one from directories.//from  www  . j  av  a  2  s  .co m
 */
private List<RecipientEntry> constructEntryList(boolean showMessageIfDirectoryLoadRemaining,
        LinkedHashMap<Long, List<RecipientEntry>> entryMap, List<RecipientEntry> nonAggregatedEntries,
        Set<String> existingDestinations) {
    final List<RecipientEntry> entries = new ArrayList<RecipientEntry>();
    int validEntryCount = 0;
    for (Map.Entry<Long, List<RecipientEntry>> mapEntry : entryMap.entrySet()) {
        final List<RecipientEntry> entryList = mapEntry.getValue();
        final int size = entryList.size();
        for (int i = 0; i < size; i++) {
            RecipientEntry entry = entryList.get(i);
            entries.add(entry);
            tryFetchPhoto(entry);
            validEntryCount++;
        }
        if (validEntryCount > mPreferredMaxResultCount) {
            break;
        }
    }
    if (validEntryCount <= mPreferredMaxResultCount) {
        for (RecipientEntry entry : nonAggregatedEntries) {
            if (validEntryCount > mPreferredMaxResultCount) {
                break;
            }
            entries.add(entry);
            tryFetchPhoto(entry);

            validEntryCount++;
        }
    }

    if (showMessageIfDirectoryLoadRemaining && mRemainingDirectoryCount > 0) {
        entries.add(RecipientEntry.WAITING_FOR_DIRECTORY_SEARCH);
    }

    return entries;
}

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

protected void put(Template[] states, final boolean merge) throws IllegalStateException {
    LinkedHashMap<String, List<Put>> allPuts = new LinkedHashMap<String, List<Put>>();
    for (Template state : states) {
        if (!state.isValid()) {
            throw new IllegalStateException("Entity not in valid state!");
        }//from ww w  . ja v  a 2 s  . c  om
        final LinkedHashMap<String, Put> puts;
        puts = getConverter().objectToRows(state, executorService, getLockType().equals(LockType.PESSIMISTIC));
        for (Map.Entry<String, Put> put : puts.entrySet()) {
            final List<Put> putList;
            if (allPuts.containsKey(put.getKey())) {
                putList = allPuts.get(put.getKey());
            } else {
                putList = new ArrayList<Put>();
                allPuts.put(put.getKey(), putList);
            }
            putList.add(put.getValue());
        }
    }
    for (Map.Entry<String, List<Put>> puts : allPuts.entrySet()) {
        if (LockType.OPTIMISTIC.equals(getLockType()) && infoProvider.getVersionColumnFamily() != null
                && infoProvider.getVersionColumnQualifier() != null) {
            putOptimistically(puts, merge, states);
        } else {
            putNonOptimistically(puts, merge, states);
        }
    }
}