Example usage for java.util Map clear

List of usage examples for java.util Map clear

Introduction

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

Prototype

void clear();

Source Link

Document

Removes all of the mappings from this map (optional operation).

Usage

From source file:com.jaspersoft.jasperserver.war.helper.GenericParametersHelper.java

private static Map<String, Class<?>> getCurrentParameterValues(
        TypeVariable<? extends Class<?>>[] typeParameters, Type[] previousTypeArguments,
        Map<String, Class<?>> inputParameterValues) {
    Map<String, Class<?>> result = inputParameterValues != null ? inputParameterValues
            : new HashMap<String, Class<?>>();
    if (typeParameters != null && typeParameters.length > 0) {
        Map<String, Class<?>> currentParameterValues = new HashMap<String, Class<?>>();
        for (int i = 0; i < typeParameters.length; i++) {
            TypeVariable<? extends Class<?>> currentVariable = typeParameters[i];
            if (previousTypeArguments != null && previousTypeArguments.length > i) {
                // fill current type parameters with arguments from subclass declaration
                Type argumentType = previousTypeArguments[i];
                if (argumentType instanceof Class<?>) {
                    currentParameterValues.put(currentVariable.getName(), (Class<?>) argumentType);
                    continue;
                } else if (argumentType instanceof TypeVariable<?>
                        && result.containsKey(((TypeVariable<?>) argumentType).getName())) {
                    currentParameterValues.put(currentVariable.getName(),
                            result.get(((TypeVariable<?>) argumentType).getName()));
                    continue;
                }//from www  .ja v a 2 s .  co m
            }
            Class<?> variableClass = null;
            final Type[] bounds = currentVariable.getBounds();
            if (bounds != null && bounds.length > 0) {
                if (bounds[0] instanceof Class<?>) {
                    variableClass = (Class<?>) bounds[0];
                } else if (bounds[0] instanceof ParameterizedType) {
                    variableClass = (Class) ((ParameterizedType) bounds[0]).getRawType();
                }
            }
            currentParameterValues.put(currentVariable.getName(), variableClass);
        }
        result.clear();
        result.putAll(currentParameterValues);
    }
    return result;
}

From source file:com.gst.accounting.journalentry.service.JournalEntryWritePlatformServiceJpaRepositoryImpl.java

@Override
public String createProvisioningJournalEntries(ProvisioningEntry provisioningEntry) {
    Collection<LoanProductProvisioningEntry> provisioningEntries = provisioningEntry
            .getLoanProductProvisioningEntries();
    Map<OfficeCurrencyKey, List<LoanProductProvisioningEntry>> officeMap = new HashMap<>();

    for (LoanProductProvisioningEntry entry : provisioningEntries) {
        OfficeCurrencyKey key = new OfficeCurrencyKey(entry.getOffice(), entry.getCurrencyCode());
        if (officeMap.containsKey(key)) {
            List<LoanProductProvisioningEntry> list = officeMap.get(key);
            list.add(entry);/*from  w ww . ja v  a2s.  c om*/
        } else {
            List<LoanProductProvisioningEntry> list = new ArrayList<>();
            list.add(entry);
            officeMap.put(key, list);
        }
    }

    Set<OfficeCurrencyKey> officeSet = officeMap.keySet();
    Map<GLAccount, BigDecimal> liabilityMap = new HashMap<>();
    Map<GLAccount, BigDecimal> expenseMap = new HashMap<>();

    for (OfficeCurrencyKey key : officeSet) {
        liabilityMap.clear();
        expenseMap.clear();
        List<LoanProductProvisioningEntry> entries = officeMap.get(key);
        for (LoanProductProvisioningEntry entry : entries) {
            if (liabilityMap.containsKey(entry.getLiabilityAccount())) {
                BigDecimal amount = liabilityMap.get(entry.getLiabilityAccount());
                amount = amount.add(entry.getReservedAmount());
                liabilityMap.put(entry.getLiabilityAccount(), amount);
            } else {
                BigDecimal amount = BigDecimal.ZERO.add(entry.getReservedAmount());
                liabilityMap.put(entry.getLiabilityAccount(), amount);
            }

            if (expenseMap.containsKey(entry.getExpenseAccount())) {
                BigDecimal amount = expenseMap.get(entry.getExpenseAccount());
                amount = amount.add(entry.getReservedAmount());
                expenseMap.put(entry.getExpenseAccount(), amount);
            } else {
                BigDecimal amount = BigDecimal.ZERO.add(entry.getReservedAmount());
                expenseMap.put(entry.getExpenseAccount(), amount);
            }
        }
        createJournalEnry(provisioningEntry.getCreatedDate(), provisioningEntry.getId(), key.office,
                key.currency, liabilityMap, expenseMap);
    }
    return "P" + provisioningEntry.getId();
}

From source file:com.boundlessgeo.geoserver.bundle.BundleExporter.java

void persist(StoreInfo s) throws IOException {
    File storeDir = exportDataDir.get(s).dir();

    // create a "data" directory under the workspace
    File wsDataDir = exportDataDir.get(s.getWorkspace()).get("data").dir();

    //TODO: wms store
    File file = null;/*from   ww w  .  j  a v  a2 s .c  o  m*/
    if (s instanceof CoverageStoreInfo) {
        file = exportDataDir.config((CoverageStoreInfo) s).file();
    } else if (s instanceof DataStoreInfo) {
        file = exportDataDir.config((DataStoreInfo) s).file();
    } else {
        file = new File(storeDir, "store.xml");
    }

    if (s instanceof DataStoreInfo) {
        DataStoreInfo ds = (DataStoreInfo) s;

        FileParam dataFile = isFileBased(ds);
        if (dataFile != null && options.bounds() == null) {
            // optimize by copying files over directly
            File storeDataDir = new File(wsDataDir, s.getName());
            storeDataDir.mkdirs();

            copyFilesTo(dataFile.file, storeDataDir, ds);

            // update the store configuration to point to the newly copied files
            File newFileRef = null;
            if (dataFile.file.isDirectory()) {
                newFileRef = storeDataDir;
            } else {
                newFileRef = new File(storeDataDir, dataFile.file.getName());
            }

            // TODO: convert back to whatever format the parameter expects
            DataStoreInfo clone = copy(ds, catalog.getFactory().createDataStore(), DataStoreInfo.class);

            //clone.getConnectionParameters().put(dataFile.param.key, "file:%WORKSPACE%/"+newPath.toString());
            clone.getConnectionParameters().put(dataFile.param.key, toWorkspaceRelativePath(newFileRef));

            s = clone;
        } else {
            // copy into a new geopackage
            GeoPackage gpkg = new GeoPackage(new File(wsDataDir, ds.getName() + ".gpkg"));
            try {
                ingestInto(gpkg, ds);
            } finally {
                gpkg.close();
            }

            // update the connection parameters
            DataStoreInfo clone = copy(ds, catalog.getFactory().createDataStore(), DataStoreInfo.class);
            clone.setType("GeoPackage");

            Map<String, Serializable> oldParams = clone.getConnectionParameters();
            Map<String, Serializable> params = Maps.newHashMap();

            params.put(GeoPkgDataStoreFactory.DBTYPE.key, "geopkg");
            params.put(GeoPkgDataStoreFactory.DATABASE.key, toWorkspaceRelativePath(gpkg.getFile()));
            params.put(GeoPkgDataStoreFactory.NAMESPACE.key,
                    (Serializable) GeoPkgDataStoreFactory.NAMESPACE.lookUp(oldParams));

            oldParams.clear();
            oldParams.putAll(params);

            s = clone;
        }
    } else if (s instanceof CoverageStoreInfo) {

    }

    persist(s, file);

    try (CloseableIterator<ResourceInfo> rit = catalog.list(ResourceInfo.class, equal("store.id", s.getId()))) {
        while (rit.hasNext()) {
            ResourceInfo resource = rit.next();
            persist(resource);
        }
    }
}

From source file:com.linkedin.pinot.queries.RealtimeQueriesSentinelTest.java

@Test
public void testAggregationGroupBy() throws Exception {
    final List<TestGroupByAggreationQuery> groupByCalls = AVRO_QUERY_GENERATOR
            .giveMeNGroupByAggregationQueries(10000);
    int counter = 0;
    final Map<ServerInstance, DataTable> instanceResponseMap = new HashMap<ServerInstance, DataTable>();
    for (final TestGroupByAggreationQuery groupBy : groupByCalls) {
        LOGGER.info("running " + counter + " : " + groupBy.pql);
        final BrokerRequest brokerRequest = REQUEST_COMPILER.compileToBrokerRequest(groupBy.pql);
        InstanceRequest instanceRequest = new InstanceRequest(counter++, brokerRequest);
        instanceRequest.setSearchSegments(new ArrayList<String>());
        instanceRequest.getSearchSegments().add("testTable_testTable");
        QueryRequest queryRequest = new QueryRequest(instanceRequest);
        DataTable instanceResponse = QUERY_EXECUTOR.processQuery(queryRequest);
        instanceResponseMap.clear();
        instanceResponseMap.put(new ServerInstance("localhost:0000"), instanceResponse);
        Map<Object, Double> expected = groupBy.groupResults;
        LOGGER.info("Result from avro is : " + expected);
        BrokerResponseNative brokerResponse = REDUCE_SERVICE.reduceOnDataTable(brokerRequest,
                instanceResponseMap);/*ww w .j  a  va2  s.co  m*/
        JSONArray actual = brokerResponse.toJson().getJSONArray("aggregationResults").getJSONObject(0)
                .getJSONArray("groupByResult");
        try {
            assertGroupByResults(actual, expected);
        } catch (AssertionError e) {
            System.out.println("***************************************");
            System.out.println("query : " + groupBy.pql);
            System.out.println("actual : " + actual.toString(1));
            System.out.println("expected : " + groupBy.groupResults);
            System.out.println("***************************************");
            throw e;
        }

    }
}

From source file:cn.com.inhand.devicenetworks.ap.websocket.WSDNAccessPoint.java

/**
 * API???/*from w w w .j a v  a  2  s. c o m*/
 *
 * @param params ??
 * @return
 */
private int auth(DNMessage login) {
    Map map = new HashMap();
    String id = login.getParameter("id").getValue();
    String key = login.getParameter("key").getValue();
    String token = login.getParameter("tocken").getValue();
    if (id == null || key == null) {
        return 23007;
    }
    map.put("key", key);
    map.put("action", 1);

    String result = restTemplate.postForObject(
            "http://" + server_addr + "/api/asset_status/" + id + "?access_token=" + token, null, String.class,
            map);

    System.out.println("----Debug in WSDNAccessPoint.auth()[ln:246]:result:" + result);
    map.clear();
    if (!result.contains("error_code")) {
        try {
            //??
            //?_id,asset_id
            LoginResultPacket packet = mapper.readValue(result, LoginResultPacket.class);
            login.getParams().put("id", packet.getId());
            login.getParams().put("asset_id", packet.getAssetId());
            login.getParams().put("sn", packet.getSn());
            System.out.println("----Debug in WSDNAccessPoint.auth()[ln:251]:id=" + packet);
            return 0;
        } catch (IOException ex) {
            Logger.getLogger(WSDNAccessPoint.class.getName()).log(Level.SEVERE, null, ex);
            return -1;
        }
    } else {
        try {
            Error error = mapper.readValue(result, Error.class);
            System.out.println("----Debug in WSDNAccessPoint.auth()[ln:256]:Error=" + error.toString());

            return error.getErrorCode();
        } catch (IOException ex) {
            Logger.getLogger(WSDNAccessPoint.class.getName()).log(Level.SEVERE, null, ex);
            return -1;
        }
    }
}

From source file:org.eclipse.winery.repository.client.WineryRepositoryClient.java

/**
 * Caches the TEntityType data of a QName to avoid multiple get requests
 *
 * NOT thread safe/*www. ja v a 2s.c o  m*/
 */
private void cache(TEntityType et, QName qName) {
    Map<QName, TEntityType> map;
    if ((map = this.entityTypeDataCache.get(et.getClass())) == null) {
        map = new HashMap<>();
        this.entityTypeDataCache.put(et.getClass(), map);
    } else {
        // quick hack to keep cache size small
        if (map.size() > 1000) {
            map.clear();
        }
    }
    map.put(qName, et);
}

From source file:com.linkedin.pinot.queries.QueriesSentinelTest.java

@Test
public void testTrace() throws RecognitionException, Exception {
    String query = "select count(*) from testTable where column1='186154188'";
    LOGGER.info("running  : " + query);
    final Map<ServerInstance, DataTable> instanceResponseMap = new HashMap<ServerInstance, DataTable>();
    final BrokerRequest brokerRequest = REQUEST_COMPILER.compileToBrokerRequest(query);
    brokerRequest.setEnableTrace(true); //
    InstanceRequest instanceRequest = new InstanceRequest(1, brokerRequest);
    instanceRequest.setEnableTrace(true); // TODO: add trace settings consistency
    instanceRequest.setSearchSegments(new ArrayList<String>());
    instanceRequest.getSearchSegments().add(segmentName);
    QueryRequest queryRequest = new QueryRequest(instanceRequest);
    final DataTable instanceResponse = QUERY_EXECUTOR.processQuery(queryRequest);
    instanceResponseMap.clear();
    instanceResponseMap.put(new ServerInstance("localhost:0000"), instanceResponse);
    final BrokerResponseNative brokerResponse = REDUCE_SERVICE.reduceOnDataTable(brokerRequest,
            instanceResponseMap);/*from  ww w .  ja  v  a2 s. c o  m*/
    LOGGER.info("BrokerResponse is " + brokerResponse.getAggregationResults().get(0));
    LOGGER.info("TraceInfo is " + brokerResponse.getTraceInfo()); //
}

From source file:com.mycompany.sparkrentals.client.RentalSolrClientTest.java

/**
 * Test of searchRentals method, of class RentalSolrClient.
 *//*from w ww .j  a  v a 2s  .  c o m*/
@Test
public void testSearchRentalByNumericRange() throws IOException, SolrServerException {
    Map<String, Object> data = new HashMap<>();

    //roomsNumber 2 or above
    data.put("roomsNumberFrom", 2);
    List<Rental> rentals = client.searchRentals(data, 20).getBeans(Rental.class);
    assertTrue(rentals.size() > 0);
    boolean hasThreeRooms = false;
    for (Rental rental : rentals) {
        if (rental.getRoomsNumber() == 3) {
            hasThreeRooms = true;
        }
        assertTrue(rental.getRoomsNumber() >= 2);
    }
    assertTrue(hasThreeRooms);

    //roomsNumber from 2 to 2
    data.put("roomsNumberTo", 2);
    rentals = client.searchRentals(data, 20).getBeans(Rental.class);
    assertTrue(rentals.size() > 0);
    for (Rental rental : rentals) {
        assertTrue(rental.getRoomsNumber() == 2);
    }

    //daillyPrice range
    data.clear();
    data.put("dailyPriceFrom", 5.1f);
    data.put("dailyPriceTo", 7.8f);
    rentals = client.searchRentals(data, 20).getBeans(Rental.class);
    assertTrue(rentals.size() > 0);
    for (Rental rental : rentals) {
        float dailyPrice = rental.getDailyPrice();
        assertTrue(dailyPrice <= 7.8f && dailyPrice >= 5.1f);
    }

}

From source file:com.keybox.manage.socket.SecureShellWS.java

@OnClose
public void onClose() {

    if (SecureShellAction.getUserSchSessionMap() != null) {
        UserSchSessions userSchSessions = SecureShellAction.getUserSchSessionMap().get(sessionId);
        if (userSchSessions != null) {
            Map<Integer, SchSession> schSessionMap = userSchSessions.getSchSessionMap();

            for (Integer sessionKey : schSessionMap.keySet()) {

                SchSession schSession = schSessionMap.get(sessionKey);

                //disconnect ssh session
                schSession.getChannel().disconnect();
                schSession.getSession().disconnect();
                schSession.setChannel(null);
                schSession.setSession(null);
                schSession.setInputToChannel(null);
                schSession.setCommander(null);
                schSession.setOutFromChannel(null);
                schSession = null;//from  ww  w.j ava 2 s. c  om
                //remove from map
                schSessionMap.remove(sessionKey);
            }

            //clear and remove session map for user
            schSessionMap.clear();
            SecureShellAction.getUserSchSessionMap().remove(sessionId);
            SessionOutputUtil.removeUserSession(sessionId);
        }
    }

}

From source file:com.gst.portfolio.shareaccounts.service.ShareAccountWritePlatformServiceJpaRepositoryImpl.java

@Override
public CommandProcessingResult applyAddtionalShares(final Long accountId, JsonCommand jsonCommand) {
    try {//from ww w .  jav  a 2  s .c o m
        ShareAccount account = this.shareAccountRepository.findOneWithNotFoundDetection(accountId);
        Map<String, Object> changes = this.accountDataSerializer.validateAndApplyAddtionalShares(jsonCommand,
                account);
        ShareAccountTransaction transaction = null;
        if (!changes.isEmpty()) {
            this.shareAccountRepository.save(account);
            transaction = (ShareAccountTransaction) changes
                    .get(ShareAccountApiConstants.additionalshares_paramname);
            transaction = account.getShareAccountTransaction(transaction);
            if (transaction != null) {
                changes.clear();
                changes.put(ShareAccountApiConstants.additionalshares_paramname, transaction.getId());
                Set<ShareAccountTransaction> transactions = new HashSet<>();
                transactions.add(transaction);
                this.journalEntryWritePlatformService
                        .createJournalEntriesForShares(populateJournalEntries(account, transactions));
            }
        }

        return new CommandProcessingResultBuilder() //
                .withCommandId(jsonCommand.commandId()) //
                .withEntityId(accountId) //
                .with(changes) //
                .build();
    } catch (final DataIntegrityViolationException dve) {
        handleDataIntegrityIssues(jsonCommand, dve.getMostSpecificCause(), dve);
        return CommandProcessingResult.empty();
    }
}