Example usage for java.util HashMap clear

List of usage examples for java.util HashMap clear

Introduction

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

Prototype

public void clear() 

Source Link

Document

Removes all of the mappings from this map.

Usage

From source file:com.insprise.common.lang.StringUtilities.java

/**
  * Returns a properly formatted string representation of the given table (a list of lists of strings).
  * <p><code><pre>{@code List<List<Object>> lists = new ArrayList<List<Object>>();
  * List<Object> list = new ArrayList<Object>();
  * list.add("ID");/*from  w  w w . jav a2 s.c  o m*/
  * list.add("Name");
  * list.add("Remarks");
  * lists.add(list);
  *
  * list = new ArrayList<Object>();
  * list.add("A");
  * list.add("Jack");
  * list.add("Employee group");
  * list.add("8");
  * lists.add(list);
  *
  * System.out.println(StringUtilities.displayTable(lists, true, 10));
  *
  * [Results]
  * +----+------+------------+-------+
  * | ID | Name | Remarks    | Score |
  * +----+------+------------+-------+
  * | A  | Jack | Employee   | 8     |
  * |    |      | group      |       |
  * +----+------+------------+-------+}</pre></code>
  * @param table
  * @param firstRowHeadRead is the first row the head read?
  *          if set to <code>true</code>, a line separator will be inserted after the first line.
  * @param maxColumnLength the max. length of a column. If the data is longer, it will be wrapped.
  * @return a properly formatted string representation of the given table (a list of lists of strings).
  */
 public static String displayTable(List<List<Object>> table, boolean firstRowHeadRead, int maxColumnLength) {
     List<Integer> lengths = new ArrayList<Integer>();

     // first, find column length.
     for (int r = 0; r < table.size(); r++) { // for each row
         for (int c = 0; table.get(r) != null && c < table.get(r).size(); c++) { // for each col
             String s = null;
             if (table.get(r).get(c) != null) {
                 s = table.get(r).get(c).toString();
             }
             Integer oldLength = null;
             if (lengths.size() > c) {
                 oldLength = lengths.get(c);
             } else {
                 lengths.add(null);
             }

             if (s != null) {

                 if (oldLength == null) {
                     lengths.set(c, Math.min(s.length(), maxColumnLength));
                 } else {
                     lengths.set(c, Math.min(maxColumnLength, Math.max(s.length(), oldLength)));
                 }
             } else if (oldLength == null || oldLength == 0) {
                 lengths.set(c, 0);
             }
         }
     }

     StringBuilder sb = new StringBuilder("\n"); // always starts with a new line to avoid misplacement.
     Formatter formatter = new Formatter(sb);

     // ------ starts print separator line.
     for (int i = 0; i < lengths.size(); i++) {
         sb.append("+-"); // margin is 2.

         int colLength = lengths.get(i);

         for (int j = 0; j < colLength + 1; j++) {
             sb.append("-");
         }
     }
     sb.append("+");
     // ------ finishes print separator line.

     HashMap<Integer, String[]> wraps = new HashMap<Integer, String[]>(); // used to contain wraps.

     for (int r = 0; r < table.size(); r++) { // for each row
         int rowHeight = 1;
         wraps.clear();

         for (int c = 0; table.get(r) != null && c < table.get(r).size(); c++) { // for each col
             int colLength = lengths.get(c);
             if (c == 0) {
                 sb.append("\n"); // first col.
             }
             sb.append(c == 0 && (!firstRowHeadRead || (firstRowHeadRead && r != 0)) ? "> " : "| ");
             String s = null;
             if (table.get(r).get(c) != null) {
                 s = table.get(r).get(c).toString();
             }
             if (s == null) {
                 formatter.format("%-" + colLength + "s", "");
             } else {
                 if (s.length() > colLength) {
                     String[] wrap = wrap(s, colLength, true);
                     rowHeight = Math.max(rowHeight, wrap.length);
                     wraps.put(c, wrap);

                     formatter.format("%-" + colLength + "s", wrap[0]);
                 } else {
                     formatter.format("%-" + (colLength == 0 ? 1 : colLength) + "s", s);
                 }
             }

             sb.append(" "); // margin.
             if (c == table.get(r).size() - 1) { // last row
                 sb.append("|");
             }
         }

         for (int k = 1; k < rowHeight; k++) { // rowHeight > 1
             for (int c = 0; table.get(r) != null && c < table.get(r).size(); c++) { // for each col
                 int colLength = lengths.get(c);
                 if (c == 0) {
                     sb.append("\n"); // first col.
                 }
                 sb.append("| ");
                 String s = null;
                 String[] wrap = wraps.get(c);
                 if (wrap != null && wrap.length > k) {
                     s = wrap[k];
                 }
                 if (s == null) {
                     formatter.format("%-" + (colLength == 0 ? 1 : colLength) + "s", "");
                 } else {
                     formatter.format("%-" + colLength + "s", s);
                 }

                 sb.append(" "); // margin.
                 if (c == table.get(r).size() - 1) { // last row
                     sb.append("|");
                 }
             }
         } // end for // rowHeight > 1.

         if (firstRowHeadRead && r == 0) {
             // ------ starts print separator line.
             sb.append("\n");
             for (int i = 0; i < lengths.size(); i++) {
                 sb.append("+-"); // margin is 2.

                 int colLength = lengths.get(i);

                 for (int j = 0; j < colLength + 1; j++) {
                     sb.append("-");
                 }
             }
             sb.append("+");
             // ------ finishes print separator line.
         }
     } // end for each row

     // ------ starts print separator line.
     sb.append("\n");
     for (int i = 0; i < lengths.size(); i++) {
         sb.append("+-"); // margin is 2.

         int colLength = lengths.get(i);

         for (int j = 0; j < colLength + 1; j++) {
             sb.append("-");
         }
     }
     sb.append("+"); // ends
     // ------ finishes print separator line.

     return sb.toString();
 }

From source file:com.kenshoo.facts.FactsToJsonFileTest.java

@Test
public void writeFactsFileAndOverrideIt() throws Exception {
    HashMap<String, String> props = new HashMap<String, String>();
    props.put("Dog", "Labrador");
    props.put("Cat", "Lion");

    Set<String> obfuscateEntities = new HashSet<String>();
    obfuscateEntities.add("Fish");
    factsToJsonFile = prepareMock(props, obfuscateEntities);
    factsToJsonFile.toJsonFileFromMapFacts(props, FACTS_JSON_FILE_NAME, obfuscateEntities);

    props.clear();
    props.put("Fish", "Jawless");
    props.put("Monkey", "Gorilla");
    props.put("Snake", "Mamba");

    File factsFile = factsToJsonFile.toJsonFileFromMapFacts(props, FACTS_JSON_FILE_NAME, obfuscateEntities);
    String jsonFacts = FileUtils.readFileToString(factsFile);
    HashMap<String, String> factsFromFile = new Gson().fromJson(jsonFacts, HashMap.class);

    Assert.assertEquals("Facts file is not same as expected", factsFile,
            new File(FACTS_LOCATION, FACTS_JSON_FILE_NAME + FactsToJsonFile.JSON_FILE_EXTENSION));
    Assert.assertEquals("Number of facts got from file is wrong", factsFromFile.size(), 3);
    Assert.assertEquals("Number of facts got from file is wrong", factsFromFile.size(), 3);
    Assert.assertEquals("Fact is different", factsFromFile.get("Monkey"), "Gorilla");
    Assert.assertEquals("Fact is different", factsFromFile.get("Fish"), FactsToJsonFile.OBFUSCATE_VALUE);
    Assert.assertEquals("Fact is different", factsFromFile.get("Snake"), "Mamba");
    verify(factsToJsonFile, times(2)).getExternalFactsFolder();
    verify(factsToJsonFile, times(2)).toJsonFileFromMapFacts(any(HashMap.class), same(FACTS_JSON_FILE_NAME),
            same(obfuscateEntities));//from  ww w. ja va  2s .  c  o  m
}

From source file:org.craftercms.cstudio.alfresco.activityfeed.CStudioActivityFeedDaoServiceImpl.java

@Override
public void updateUrl(String oldUrl, String newUrl, String site) throws SQLException {
    SqlMapClient sqlClient = getSqlMapClient();
    sqlClient.startTransaction();/*from   w w w  . j  ava  2  s .  co  m*/
    HashMap<String, String> params = new HashMap<String, String>();
    try {
        params.put("site", site);
        params.put("newUrl", newUrl);
        sqlClient.delete(STATEMENT_DELETE_OLD_ACTIVITY, params);
        params.clear();
        params.put("site", site);
        params.put("oldUrl", oldUrl);
        params.put("newUrl", newUrl);
        sqlClient.update(STATEMENT_UPDATE_URL, params);
        sqlClient.commitTransaction();
    } catch (SQLException ex) {
        LOGGER.error("Unable to update url ", ex);
    } finally {
        sqlClient.endTransaction();
    }

}

From source file:org.deegree.services.wms.StyleRegistry.java

/**
 * @param layerName//from ww  w.ja  v a  2  s.com
 * @param style
 * @param clear
 *            if true, all other styles will be removed for the layer
 */
public void put(String layerName, Style style, boolean clear) {
    HashMap<String, Style> styles = registry.get(layerName);
    if (styles == null) {
        styles = new HashMap<String, Style>();
        registry.put(layerName, styles);
        styles.put("default", style);
    } else if (clear) {
        styles.clear();
        styles.put("default", style);
    }
    if (style.getName() == null) {
        LOG.debug("Overriding default style since new style does not have name.");
        styles.put("default", style);
    } else {
        styles.put(style.getName(), style);
    }
}

From source file:org.kuali.kfs.module.ld.businessobject.lookup.BenefitsCalculationLookupableHelperServiceImpl.java

/**
 * @see org.kuali.rice.kns.lookup.AbstractLookupableHelperServiceImpl#validateSearchParameters(java.util.Map)
 *///  w w w  . j ava 2 s .  c  o  m
@Override
public void validateSearchParameters(Map fieldValues) {
    super.validateSearchParameters(fieldValues);

    HashMap<String, String> fieldsMap = new HashMap<String, String>();

    String accountNumber = (String) fieldValues.get("accountCodeOffset");
    String objectCode = (String) fieldValues.get("objectCodeOffset");

    // Validate the Account Number field is a valid Account Number in the DB
    if (StringUtils.isNotEmpty(accountNumber)) {
        fieldsMap.clear();
        fieldsMap.put(GeneralLedgerConstants.ColumnNames.ACCOUNT_NUMBER, accountNumber);
        List<Account> accountNums = (List<Account>) SpringContext.getBean(BusinessObjectService.class)
                .findMatching(Account.class, fieldsMap);

        if (accountNums == null || accountNums.size() <= 0) {
            GlobalVariables.getMessageMap().putError("accountNumber", KFSKeyConstants.ERROR_CUSTOM,
                    new String[] { "Invalid Account Number: " + accountNumber });
            throw new ValidationException("errors in search criteria");
        }
    }

    // Validate the Object Code field is a valid Object Code in the DB
    if (StringUtils.isNotEmpty(objectCode)) {
        fieldsMap.clear();
        fieldsMap.put(GeneralLedgerConstants.ColumnNames.OBJECT_CODE, objectCode);
        List<ObjectCode> objCodes = (List<ObjectCode>) SpringContext.getBean(BusinessObjectService.class)
                .findMatching(ObjectCode.class, fieldsMap);

        if (objCodes == null || objCodes.size() <= 0) {
            GlobalVariables.getMessageMap().putError(KFSPropertyConstants.OBJECT_CODE,
                    KFSKeyConstants.ERROR_CUSTOM, new String[] { "Invalid Object Code: " + objectCode });
            throw new ValidationException("errors in search criteria");
        }
    }
}

From source file:org.deegree.services.wms.StyleRegistry.java

/**
 * @param layerName/* w w  w . j av  a  2s  .co  m*/
 * @param style
 * @param clear
 */
public void putLegend(String layerName, Style style, boolean clear) {
    HashMap<String, Style> styles = legendRegistry.get(layerName);
    if (styles == null) {
        styles = new HashMap<String, Style>();
        legendRegistry.put(layerName, styles);
        styles.put("default", style);
    } else if (clear) {
        styles.clear();
        styles.put("default", style);
    }
    if (style.getName() == null) {
        LOG.debug("Overriding default style since new style does not have name.");
        styles.put("default", style);
    } else {
        styles.put(style.getName(), style);
    }
}

From source file:com.datatorrent.lib.util.AbstractBaseFrequentKey.java

/**
 * Emits the result.//  ww  w  . j ava 2s.co m
 */
@Override
public void endWindow() {
    // Compute least frequent
    K key = null;
    int kval = -1;
    HashMap<K, Object> map = new HashMap<K, Object>();
    for (Map.Entry<K, MutableInt> e : keycount.entrySet()) {
        if ((kval == -1)) {
            key = e.getKey();
            kval = e.getValue().intValue();
            map.put(key, null);
        } else if (compareCount(e.getValue().intValue(), kval)) {
            key = e.getKey();
            kval = e.getValue().intValue();
            map.clear();
            map.put(key, null);
        } else if (e.getValue().intValue() == kval) {
            map.put(e.getKey(), null);
        }
    }

    // Emit least frequent key, emit all least frequent keys list
    // on other ports.
    HashMap<K, Integer> tuple;
    if ((key != null) && (kval > 0)) {
        tuple = new HashMap<K, Integer>(1);
        tuple.put(key, new Integer(kval));
        emitTuple(tuple);
        ArrayList<HashMap<K, Integer>> elist = new ArrayList<HashMap<K, Integer>>();
        for (Map.Entry<K, Object> e : map.entrySet()) {
            tuple = new HashMap<K, Integer>(1);
            tuple.put(e.getKey(), kval);
            elist.add(tuple);
        }
        emitList(elist);
    }
    keycount.clear();
}

From source file:org.jdto.impl.SimpleBinderDelegate.java

private void populateSourceBeans(HashMap<String, Object> sourceBeans, BeanMetadata metadata,
        FieldMetadata fieldMetadata, Object[] bos) {

    //clear the mappings
    sourceBeans.clear();

    //populate, by default the mapping on the field or else, the one on the ben.
    String[] names = (ArrayUtils.isEmpty(fieldMetadata.getSourceBeanNames())) ? metadata.getDefaultBeanNames()
            : fieldMetadata.getSourceBeanNames();

    for (int i = 0; i < names.length; i++) {
        String name = names[i];/*from  w  w  w. jav  a  2s . com*/
        Object bean = bos[i];
        sourceBeans.put(name, bean);
    }

    //add the default bean name.
    sourceBeans.put("", bos[0]);
}

From source file:com.netcrest.pado.tools.pado.command.cp.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override//from w w w .j  a v  a  2 s  .  co m
public void run(CommandLine commandLine, String command) throws Exception {
    boolean isRecursive = commandLine.hasOption("-r") || commandLine.hasOption("-R");

    List<String> argList = (List<String>) commandLine.getArgList();
    if (argList.size() < 3) {
        PadoShell.printlnError(this, "Invalid number of arguments.");
        return;
    }
    String sourcePath = argList.get(1);
    String targetPath = argList.get(2);

    String sourceGridId = padoShell.getGridId(sourcePath);
    String targetGridId = padoShell.getGridId(targetPath);
    String sourceGridPath = padoShell.getGridPath(sourcePath);
    String targetGridPath = padoShell.getGridPath(targetPath);
    String sourceFullPath = padoShell.getFullPath(sourcePath);
    String targetFullPath = padoShell.getFullPath(targetPath);

    // If source and target are in the same grid then do copy in the grid,
    // otherwise, do it from here.
    if (sourceGridId.equals(targetGridId)) {

        // Do copy in the grid.
        IPathBiz pathBiz = SharedCache.getSharedCache().getPado().getCatalog().newInstance(IPathBiz.class);
        pathBiz.copy(sourceGridId, sourceGridPath, targetGridPath);

    } else {

        IPathBiz pathBiz = SharedCache.getSharedCache().getPado().getCatalog().newInstance(IPathBiz.class);
        if (pathBiz.exists(sourceGridId, sourceGridPath) == false) {
            PadoShell.printlnError(this, sourcePath + ": Source path does not exist.");
            return;
        }
        IGridMapBiz gridMapBiz = SharedCache.getSharedCache().getPado().getCatalog()
                .newInstance(IGridMapBiz.class);
        gridMapBiz.setGridPath(sourceGridPath);
        gridMapBiz.getBizContext().getGridContextClient().setGridIds(sourceGridId);
        Map.Entry sourceEntry = gridMapBiz.getRandomEntry();
        if (sourceEntry == null) {
            return;
        }

        // Get target entry if the target grid path exists
        if (pathBiz.exists(targetGridId, targetGridPath) == false) {
            // See if we can create the path
            IPathBiz.PathType pathType = pathBiz.getPathType(sourceGridId, sourceGridPath);
            if (pathType == IPathBiz.PathType.NOT_SUPPORTED) {
                PadoShell.printlnError(this, "Unable to copy. Path type not supported.");
                return;
            }
            boolean created = pathBiz.createPath(targetGridId, targetGridPath, pathType, false);
            if (created == false) {
                PadoShell.printlnError(this, targetGridPath + ": Target path creation failed.");
                return;
            }
            // refresh required to get the newly created path info
            SharedCache.getSharedCache().refresh();
        } else {

            // Get a target entry to determine the key and value types.
            gridMapBiz.setGridPath(targetGridPath);
            gridMapBiz.getBizContext().getGridContextClient().setGridIds(targetGridId);
            Map.Entry targetEntry = gridMapBiz.getRandomEntry();
            if (targetEntry != null) {
                checkIncompatibleTypes(sourceEntry.getKey(), sourceEntry.getValue(), targetEntry.getKey(),
                        targetEntry.getValue());
            }
        }

        gridMapBiz.setGridPath(targetGridPath);
        gridMapBiz.getBizContext().getGridContextClient().setGridIds(targetGridId);
        IIndexMatrixBiz imBiz = SharedCache.getSharedCache().getPado().getCatalog()
                .newInstance(IIndexMatrixBiz.class, true);
        imBiz.setQueryType(QueryType.OQL);
        imBiz.setGridIds(sourceGridId);
        // imBiz.setFetchSize(10000);
        String queryString = String.format(less.QUERY_KEYS_VALUES, sourceFullPath);
        IScrollableResultSet rs = imBiz.execute(queryString);
        HashMap map = new HashMap(imBiz.getFetchSize());
        do {
            List<Struct> list = rs.toList();
            for (Struct struct : list) {
                map.put(struct.getFieldValues()[0], struct.getFieldValues()[1]);
            }
            gridMapBiz.putAll(map);
            map.clear();
        } while (rs.nextSet());
        SharedCache.getSharedCache().refresh();
    }
}

From source file:com.philliphsu.bottomsheetpickers.date.PagingMonthAdapter.java

@Override
public Object instantiateItem(ViewGroup container, int position) {
    MonthView v;/*ww  w  .  j a  v a 2 s.c  o m*/
    HashMap<String, Integer> drawingParams = null;
    v = createMonthView(mContext, mThemeDark, mAccentColor);
    // Set up the new view
    v.setClickable(true);
    v.setOnDayClickListener(this);
    if (drawingParams == null) {
        drawingParams = new HashMap<>();
    }
    drawingParams.clear();

    final int month = getMonth(position);
    final int year = getYear(position);

    int selectedDay = -1;
    if (isSelectedDayInMonth(year, month)) {
        selectedDay = mSelectedDay.day;
    }

    // Invokes requestLayout() to ensure that the recycled view is set with the appropriate
    // height/number of weeks before being displayed.
    v.reuse();

    drawingParams.put(MonthView.VIEW_PARAMS_SELECTED_DAY, selectedDay);
    drawingParams.put(MonthView.VIEW_PARAMS_YEAR, year);
    drawingParams.put(MonthView.VIEW_PARAMS_MONTH, month);
    drawingParams.put(MonthView.VIEW_PARAMS_WEEK_START, mController.getFirstDayOfWeek());
    v.setMonthParams(drawingParams);
    v.invalidate();
    container.addView(v, new LayoutParams(MATCH_PARENT, MATCH_PARENT));
    mMonthYearTitles.append(position, v.getMonthAndYearString());
    mMonthViews.add(v);
    return v;
}