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:io.mindmaps.graql.internal.analytics.AnalyticsTest.java

@Ignore
@Test// ww  w.j av a2  s  .  c om
public void testDegreesAndPersist() throws Exception {
    // create instances
    EntityType thing = graph.putEntityType("thing");
    EntityType anotherThing = graph.putEntityType("another");

    Entity entity1 = graph.putEntity("1", thing);
    Entity entity2 = graph.putEntity("2", thing);
    Entity entity3 = graph.putEntity("3", thing);
    Entity entity4 = graph.putEntity("4", anotherThing);

    RoleType relation1 = graph.putRoleType("relation1");
    RoleType relation2 = graph.putRoleType("relation2");
    thing.playsRole(relation1).playsRole(relation2);
    anotherThing.playsRole(relation1).playsRole(relation2);
    RelationType related = graph.putRelationType("related").hasRole(relation1).hasRole(relation2);

    // relate them
    String id1 = UUID.randomUUID().toString();
    graph.putRelation(id1, related).putRolePlayer(relation1, entity1).putRolePlayer(relation2, entity2);

    String id2 = UUID.randomUUID().toString();
    graph.putRelation(id2, related).putRolePlayer(relation1, entity2).putRolePlayer(relation2, entity3);

    String id3 = UUID.randomUUID().toString();
    graph.putRelation(id3, related).putRolePlayer(relation1, entity2).putRolePlayer(relation2, entity4);

    graph.commit();

    Map<Instance, Long> correctDegrees = new HashMap<>();

    // compute degrees on subgraph
    Analytics computer = new Analytics(keyspace, Sets.newHashSet(thing, related));
    computer.degreesAndPersist();

    // fetch instances
    graph = MindmapsClient.getGraph(keyspace);
    entity1 = graph.getEntity("1");
    entity2 = graph.getEntity("2");
    entity3 = graph.getEntity("3");

    correctDegrees.clear();
    correctDegrees.put(entity1, 1l);
    correctDegrees.put(entity2, 3l);
    correctDegrees.put(entity3, 1l);
    correctDegrees.put(graph.getRelation(id1), 2l);
    correctDegrees.put(graph.getRelation(id2), 2l);
    correctDegrees.put(graph.getRelation(id3), 1l);

    // assert persisted degrees are correct
    checkDegrees(graph, correctDegrees);

    long numVertices = 0;

    // compute again and again ...
    for (int i = 0; i < 2; i++) {
        graph.close();
        computer.degreesAndPersist();

        // refresh everything after commit
        graph = MindmapsClient.getGraph(keyspace);
        // fetch instances
        entity1 = graph.getEntity("1");
        entity2 = graph.getEntity("2");
        entity3 = graph.getEntity("3");

        correctDegrees.clear();
        correctDegrees.put(entity1, 1l);
        correctDegrees.put(entity2, 3l);
        correctDegrees.put(entity3, 1l);
        correctDegrees.put(graph.getRelation(id1), 2l);
        correctDegrees.put(graph.getRelation(id2), 2l);
        correctDegrees.put(graph.getRelation(id3), 1l);

        checkDegrees(graph, correctDegrees);

        // assert the number of vertices remain the same
        if (i == 0) {
            numVertices = computer.count();
        } else {
            assertEquals(numVertices, computer.count());
        }
    }

    // compute degrees on all types, again and again ...
    for (int i = 0; i < 2; i++) {

        graph.close();
        computer = new Analytics(keyspace);
        computer.degreesAndPersist();

        // after computation refresh concepts
        graph = MindmapsClient.getGraph(keyspace);

        // fetch instances
        entity1 = graph.getEntity("1");
        entity2 = graph.getEntity("2");
        entity3 = graph.getEntity("3");
        entity4 = graph.getEntity("4");

        correctDegrees.clear();
        correctDegrees.put(entity1, 1l);
        correctDegrees.put(entity2, 3l);
        correctDegrees.put(entity3, 1l);
        correctDegrees.put(graph.getRelation(id1), 2l);
        correctDegrees.put(graph.getRelation(id2), 2l);
        correctDegrees.put(entity4, 1l);
        correctDegrees.put(graph.getRelation(id3), 2l);

        checkDegrees(graph, correctDegrees);

        // assert the number of vertices remain the same
        if (i == 0) {
            assertEquals(1, computer.count() - numVertices);
            numVertices = computer.count();
        } else {
            assertEquals(numVertices, computer.count());
        }
    }
}

From source file:org.apache.camel.component.olingo2.api.impl.Olingo2AppImpl.java

private ODataResponse parseBatchRequest(final Edm edm, final List<Olingo2BatchRequest> batchParts)
        throws IOException, EntityProviderException, ODataApplicationException, EdmException,
        URISyntaxException {/*from  w w  w  .  j  ava 2  s  . co  m*/

    // create Batch request from parts
    final ArrayList<BatchPart> parts = new ArrayList<BatchPart>();
    final ArrayList<BatchChangeSetPart> changeSetParts = new ArrayList<BatchChangeSetPart>();

    final Map<String, String> contentIdMap = new HashMap<String, String>();

    for (Olingo2BatchRequest batchPart : batchParts) {

        if (batchPart instanceof Olingo2BatchQueryRequest) {

            // need to add change set parts collected so far??
            if (!changeSetParts.isEmpty()) {
                addChangeSetParts(parts, changeSetParts);
                changeSetParts.clear();
                contentIdMap.clear();
            }

            // add to request parts
            final UriInfoWithType uriInfo = parseUri(edm, batchPart.getResourcePath(), null);
            parts.add(createBatchQueryPart(uriInfo, (Olingo2BatchQueryRequest) batchPart));

        } else {

            // add to change set parts
            final BatchChangeSetPart changeSetPart = createBatchChangeSetPart(edm, contentIdMap,
                    (Olingo2BatchChangeRequest) batchPart);
            changeSetParts.add(changeSetPart);
        }
    }

    // add any remaining change set parts
    if (!changeSetParts.isEmpty()) {
        addChangeSetParts(parts, changeSetParts);
    }

    final String boundary = BOUNDARY_PREFIX + UUID.randomUUID();
    InputStream batchRequest = EntityProvider.writeBatchRequest(parts, boundary);
    // add two blank lines before all --batch boundaries
    // otherwise Olingo2 EntityProvider parser barfs in the server!!!
    final byte[] bytes = EntityProvider.readBinary(batchRequest);
    final String batchRequestBody = new String(bytes, Consts.UTF_8);
    batchRequest = new ByteArrayInputStream(
            batchRequestBody.replaceAll("--(batch_)", "\r\n\r\n--$1").getBytes(Consts.UTF_8));

    final String contentHeader = BATCH_CONTENT_TYPE + BOUNDARY_PARAMETER + boundary;
    return ODataResponse.entity(batchRequest).contentHeader(contentHeader).build();
}

From source file:com.china317.gmmp.gmmp_report_analysis.App.java

private static void LybcOverSpeedRecordsStoreIntoDB(Map<String, PtmOverSpeed> overSpeedRecords,
        ApplicationContext context) {//  www . j a  va 2s.c  o  m
    // INSERT INTO
    // TAB_ALARM_OVERSPEED(LICENCE,BEGIN_TIME,END_TIME,SPEED,IS_END,AREA,MAX_SPEED)
    // SELECT LICENSE,BEGINTIME,ENDTIME,AVGSPEED,'1',FLAG,MAXSPEED FROM
    // ALARMOVERSPEED_REA WHERE BUSINESSTYPE = '3'
    String sql = "";

    Connection conn = null;
    try {
        SqlMapClient sc = (SqlMapClient) context.getBean("sqlMapClientLybc");
        conn = sc.getDataSource().getConnection();
        conn.setAutoCommit(false);
        Statement st = conn.createStatement();
        Iterator<String> it = overSpeedRecords.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            PtmOverSpeed pos = overSpeedRecords.get(key);
            sql = "insert into TAB_ALARM_OVERSPEED "
                    + " (LICENCE,BEGIN_TIME,END_TIME,SPEED,IS_END,AREA,MAX_SPEED) " + " values ('"
                    + pos.getLicense() + "','" + pos.getBeginTime() + "','" + pos.getEndTIme() + "',"
                    + pos.getAvgSpeed() + "," + "1" + "," + pos.getFlag() + "," + pos.getMaxSpeed() + ")";
            log.info(sql);
            st.addBatch(sql);
        }
        st.executeBatch();
        conn.commit();
        log.info("[insertIntoDB OverSpeed success!!!]");
    } catch (Exception e) {
        e.printStackTrace();
        log.error(sql);
    } finally {
        overSpeedRecords.clear();
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

From source file:com.esd.ps.EmployerController.java

/**
 * list/*w  w w . j  a  v a  2 s.com*/
 * 
 * @param packId
 * @param page
 * @param taskStuts
 * @param taskNameCondition
 * @return
 */
@RequestMapping(value = "/packDetail", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> detailpagePost(int packId, int page, int taskStuts, String taskNameCondition) {
    Map<String, Object> map = new HashMap<String, Object>();

    List<taskTrans> list = new ArrayList<taskTrans>();
    int totle = taskService.getTaskCountByPackIdAndTaskStatus(packId, taskStuts, taskNameCondition);
    if (totle == 0) {
        map.clear();
        int totlePage = (int) Math.ceil((double) totle / (double) Constants.ROW);
        map.put(Constants.TOTLE_PAGE, totlePage);
        map.put(Constants.TOTLE, totle);
        map.put(Constants.LIST, list);
        return map;
    }
    List<task> listTask = null;
    listTask = taskService.getLikeTaskName(packId, page, taskStuts, taskNameCondition, Constants.ROW);
    for (Iterator<task> iterator = listTask.iterator(); iterator.hasNext();) {
        task task = (task) iterator.next();
        taskTrans taskTrans = new taskTrans();

        taskTrans.setTaskId(task.getTaskId());
        taskTrans.setTaskName(task.getTaskName());
        if (task.getTaskEffective() == null) {
            taskTrans.setTaskEffective(MSG_UNAUDIT);
        } else if (task.getTaskEffective()) {
            taskTrans.setTaskEffective(MSG_QUALIFY);
        } else if (task.getTaskEffective() == false) {
            taskTrans.setTaskEffective(MSG_UNQUALIFY);
        }
        if (task.getWorkerId() == null) {
            taskTrans.setTaskUploadTime(MSG_UNDO);
        } else if (task.getWorkerId() == 0) {
            taskTrans.setTaskUploadTime("");
        } else if (task.getWorkerId() > 0) {
            if (task.getTaskMarkTime() == null) {
                taskTrans.setTaskUploadTime(MSG_DOING);
            } else if (task.getTaskMarkTime() == 0) {
                taskTrans.setTaskUploadTime("");
            } else {
                taskTrans.setTaskUploadTime("");
            }
        }
        list.add(taskTrans);
    }
    map.clear();
    int totlePage = (int) Math.ceil((double) totle / (double) Constants.ROW);
    map.put(Constants.TOTLE_PAGE, totlePage);
    map.put(Constants.TOTLE, totle);
    map.put(Constants.LIST, list);
    return map;
}

From source file:com.ginger.Ginger4J.java

/**
 * Process the suggested correction from Ginger ProofReader.
 *
 * @param text/*from   w w w.  j  a v  a2 s .  c om*/
 *            The text that should be corrected.
 * @param suggestions
 *            The suggested correction.
 *
 * @return JSONObject
 *            A JSON object that contains the text, the result & the suggested corrections.
 */
private JSONObject processSuggestions(String text, JSONObject suggestions) {
    int start, end;
    int i = 0;

    JSONArray corrections = new JSONArray();
    JSONArray textResult = suggestions.getJSONArray("LightGingerTheTextResult");

    JSONObject lightGinger, suggestion;

    Map<String, Object> map = new HashMap<String, Object>();

    String result = "";

    for (int index = 0; index < textResult.length(); index++) {
        lightGinger = textResult.getJSONObject(index);
        start = lightGinger.getInt("From");
        end = lightGinger.getInt("To");
        suggestion = lightGinger.getJSONArray("Suggestions").getJSONObject(0);

        if (i <= end) {
            if (start != 0) {
                result += text.substring(i, start);
            }
            result += suggestion.getString("Text");

            map.put("text", text.substring(start, (end + 1)));
            map.put("correct", !suggestion.getString("Text").isEmpty() ? suggestion.getString("Text") : "");
            map.put("definition",
                    suggestion.has("Definition") && !suggestion.getString("Definition").isEmpty()
                            ? suggestion.getString("Definition")
                            : "");
            map.put("start", start);
            map.put("length", (end + 1) - start);

            corrections.put(new JSONObject(map));
            map.clear();
        }

        i = end + 1;
    }

    if (i < text.length()) {
        result += text.substring(i);
    }

    map.put("text", text);
    map.put("result", result);
    map.put("corrections", corrections);

    return new JSONObject(map);
}

From source file:ch.ralscha.extdirectspring.controller.RouterControllerPollTest.java

@Test
public void pollRequiredCookieWithValue() throws Exception {
    Map<String, String> params = new LinkedHashMap<String, String>();
    params.put("id", "1");

    List<Cookie> cookies = new ArrayList<Cookie>();
    cookies.add(new Cookie("cookie", "cookieValue"));
    cookies.add(new Cookie("anotherName", "cookieValue1"));
    cookies.add(new Cookie("anotherName", "cookieValue2"));

    ExtDirectPollResponse resp = ControllerUtil.performPollRequest(mockMvc, "pollProvider",
            "messageCookieValue2", "messageCookieValue2", params, null, cookies);

    assertThat(resp).isNotNull();/*  w  w  w.  j a v a  2  s. co  m*/
    assertThat(resp.getType()).isEqualTo("event");
    assertThat(resp.getName()).isEqualTo("messageCookieValue2");
    assertThat(resp.getData()).isEqualTo("1;cookieValue1");
    assertThat(resp.getWhere()).isNull();
    assertThat(resp.getMessage()).isNull();

    params.clear();
    params.put("id", "2");

    resp = ControllerUtil.performPollRequest(mockMvc, "pollProvider", "messageCookieValue2",
            "messageCookieValue2", params, null, null, true);

    assertThat(resp).isNotNull();
    assertThat(resp.getType()).isEqualTo("exception");
    assertThat(resp.getName()).isEqualTo("messageCookieValue2");
    assertThat(resp.getData()).isNull();
    assertThat(resp.getWhere()).isNull();
    assertThat(resp.getMessage()).isEqualTo("Server Error");

    params.clear();
    params.put("id", "3");
    cookies = new ArrayList<Cookie>();
    cookies.add(new Cookie("cookie", "cookieValue"));
    resp = ControllerUtil.performPollRequest(mockMvc, "pollProvider", "messageCookieValue2",
            "messageCookieValue2", params, null, cookies, true);

    assertThat(resp).isNotNull();
    assertThat(resp.getType()).isEqualTo("exception");
    assertThat(resp.getName()).isEqualTo("messageCookieValue2");
    assertThat(resp.getData()).isNull();
    assertThat(resp.getWhere()).isNull();
    assertThat(resp.getMessage()).isEqualTo("Server Error");
}

From source file:com.esd.ps.EmployerController.java

/**
 * ?/*from   w w w . ja  v a 2s. c o  m*/
 * 
 * @param packId
 * @return
 */
@RequestMapping(value = "/deletePack", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> deletePackPOST(int packId) {
    Map<String, Object> map = new HashMap<>();
    taskWithBLOBs task = new taskWithBLOBs();
    task.setPackId(packId);
    taskService.deleteByPackId(packId);

    packWithBLOBs pack = new packWithBLOBs();
    pack.setPackId(packId);
    packService.deleteByPrimaryKey(packId);
    map.clear();
    map.put(Constants.REPLAY, 1);
    return map;
}

From source file:com.microsoft.office.plugin.MetadataMojo.java

/**
 * Generates a single entity set.//w  w w.  jav a2  s  . co m
 * 
 * @param schema Schema which an entity set will be related to.
 * @param base Base directory for output classes.
 * @param pkg Package.
 * @param objs Objects to be put into velocity context.
 * @param generatedEntitySets Holds information if entity set for some type already generated to prevent multiple generations.
 * @param entitySetNames Maps entity type and its set name.
 * @param type Fully qualified enity type (contains schema namespace and class name).
 * @param paths Maps entity type and path to its set related to service root.
 * @param additionalSets List of all sets were generated.
 * @throws MojoExecutionException
 */
private void generateEntitySet(Schema schema, final File base, final String pkg, final Map<String, Object> objs,
        Map<String, Boolean> generatedEntitySets, Map<String, String> entitySetNames, String type,
        Map<String, String> paths, List<EntitySet> additionalSets) throws MojoExecutionException {
    Queue<String> typesQueue = new LinkedList<String>();

    for (NavigationProperty np : schema.getEntityType(utility.getNameFromNS(type)).getNavigationProperties()) {
        addTypeToQueue(entitySetNames, type, paths, typesQueue, np);
    }

    while (!typesQueue.isEmpty()) {
        String currentType = typesQueue.poll();
        if (generatedEntitySets.get(currentType)) {
            continue;
        }

        EntitySet generatedSet = new EntitySet();
        generatedSet.setEntityType(utility.getNameInNamespace(currentType));
        String name = entitySetNames.get(currentType);
        generatedSet.setName(name);
        additionalSets.add(generatedSet);

        objs.clear();
        objs.put("entitySet", generatedSet);

        EntityType currentEntityType = schema.getEntityType(currentType);
        while (true) {
            for (NavigationProperty np : currentEntityType.getNavigationProperties()) {
                addTypeToQueue(entitySetNames, currentType, paths, typesQueue, np);
            }
            if (currentEntityType.getBaseType() != null) {
                currentEntityType = schema
                        .getEntityType(utility.getNameFromNS(currentEntityType.getBaseType()));
            } else {
                break;
            }
        }

        /******************************* EXCHANGE-SPECIFIC ******************************************/
        // As we know from spec we cannot directly create a message inside /Me/Messages
        // we must create it inside /Me/path/to/some/folder/Messages
        // the path may be one of:
        // 1. Predefined folder name - as described in metadata in navigation properties of User entity
        // example: Inbox -> /Me/Inbox/Messages
        // 2. Folder with given id
        // example: Folders('abc') -> /Me/Folders('abc')/Messages
        // 3. A child folder (may be recursively)
        // example: Folders('abc')/ChildFolders('xyz') -> /Me/Folders('abc')/ChildFolders('xyz')/Messages

        if (name.equals("Messages")) {
            objs.put("pathToSet", "Me/");
            objs.put("createPath", "Me/%s/Messages");
            objs.put("overridePath", true);
        } else if (name.equals("Events")) {
            objs.put("pathToSet", "Me/");
            objs.put("createPath", "Me/Calendars('%s')/Events");
            objs.put("overridePath", true);
        }

        if (!paths.get(currentType).equals("")) {
            objs.put("pathToSet", paths.get(currentType));
        }
        if (utility.capitalize(name).equals("Folders")) {
            objs.put("userType", schema.getEntityType("User"));
        }

        /*************************** END OF EXCHANGE-SPECIFIC BLOCK ********************************/
        if (generateInterfaces) {
            parseObj(base, pkg, "entitySet", "I" + utility.capitalize(name) + ".java", objs);
        }
        if (generateClasses) {
            parseObj(base, pkg, "entitySetImpl", utility.capitalize(name) + ".java", objs);
        }
        generatedEntitySets.put(currentType, true);
    }
}

From source file:com.china317.gmmp.gmmp_report_analysis.App.java

private static void DgmOverSpeedRecordsStoreIntoDB(Map<String, PtmOverSpeed> overSpeedRecords,
        ApplicationContext context) {//from  ww w  .  j a va2  s .com
    // INSERT INTO
    // TAB_GPSEVENT_OVERSPEED(VID,TYPE,,BEGIN_TIME,END_TIME,DETAIL,AREA,MAX_SPEED,MIN_SPEED)
    // SELECT CODE,'overspeed',BEGINTIME,ENDTIME,AVGSPEED,FLAG,MAXSPEED,''
    // FROM ALARMOVERSPEED_REA WHERE BUSINESSTYPE = '1'

    String sql = "";
    Connection conn = null;
    try {
        SqlMapClient sc = (SqlMapClient) context.getBean("sqlMapClientDgm");
        conn = sc.getDataSource().getConnection();
        conn.setAutoCommit(false);
        Statement st = conn.createStatement();
        Iterator<String> it = overSpeedRecords.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            PtmOverSpeed pos = overSpeedRecords.get(key);
            sql = "INSERT INTO TAB_GPSEVENT_OVERSPEED (VID,TYPE,BEGIN_TIME,END_TIME,DETAIL,AREA,MAX_SPEED,MIN_SPEED) "
                    + " values ('" + pos.getCode() + "','" + "overspeed" + "','" + pos.getBeginTime() + "','"
                    + pos.getEndTIme() + "'," + pos.getAvgSpeed() + "," + pos.getFlag() + ","
                    + pos.getMaxSpeed() + "," + 0 + ")";
            log.info(sql);
            st.addBatch(sql);
        }
        st.executeBatch();
        conn.commit();
        log.info("[insertIntoDB OverSpeed success!!!]");
    } catch (Exception e) {
        e.printStackTrace();
        log.error(sql);
    } finally {
        overSpeedRecords.clear();
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

From source file:org.toobsframework.pres.doit.DoItRunner.java

public void runDoIt(IRequest request, DoIt doIt) throws Exception {
    // Run Actions
    Action thisAction = null;/*from   w  w w  . j a  v  a 2s  .  com*/
    if (doIt.getActions() != null) {
        Actions actionsObj = doIt.getActions();

        String multipleActionsKey = "defaultAction";
        String[] multipleActionsAry = new String[] { "" };
        Map<String, Object> paramMap = request.getParams();
        Map<String, Object> responseMap = request.getResponseParams();
        try {
            if (actionsObj.getMultipleActionsKey() != null && !actionsObj.getMultipleActionsKey().equals("")) {
                multipleActionsKey = actionsObj.getMultipleActionsKey();
                Object multActObj = paramMap.get(actionsObj.getMultipleActionsKey());
                if (multActObj != null && multActObj.getClass().isArray()) {
                    multipleActionsAry = (String[]) multActObj;
                } else if (multActObj != null) {
                    multipleActionsAry = new String[] { (String) multActObj };
                } else {
                    multipleActionsAry = new String[] { "" };
                }
            }

            for (int i = 0; i < multipleActionsAry.length; i++) {
                Map<String, Object> actionParams = new HashMap<String, Object>(paramMap);
                responseMap.clear();
                actionParams.put(multipleActionsKey, multipleActionsAry[i]);
                actionParams.put(PlatformConstants.MULTI_ACTION_INSTANCE, new Integer(i));
                Enumeration<Action> actions = doIt.getActions().enumerateAction();
                while (actions.hasMoreElements()) {
                    thisAction = actions.nextElement();
                    runAction(request, doIt.getName(), thisAction, actionParams, responseMap,
                            (i == (multipleActionsAry.length - 1)));
                }
            }
            Iterator<String> iter = responseMap.keySet().iterator();
            while (iter.hasNext()) {
                String key = iter.next();
                paramMap.put(key, responseMap.get(key));
                /*
                if (componentRequestManager.get().getHttpRequest() != null) {
                  componentRequestManager.get().getHttpRequest().setAttribute((String)key, responseMap.get(key));
                }
                */
            }
        }

        // if validation errors are thrown, make sure to correctly pull
        // error objects..
        catch (Exception e) {
            if (e.getCause() instanceof ValidationException) {
                log.warn("Caught validation exception.");
                this.pullErrorObjectsIntoRequest(request, doIt, paramMap, responseMap, multipleActionsKey,
                        multipleActionsAry, (ValidationException) e.getCause());
            }
            throw e;
        }
    }
}