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.mnt.base.web.DigestAuthenticator.java

public static boolean authenticate(HttpServletRequest req, HttpServletResponse resp) {

    boolean result = false;

    HttpSession session = req.getSession();

    if (session != null) {

        result = session.getAttribute(AUTHENTICATED_FLAG_KEY) != null;

        if (!result) {

            session.setMaxInactiveInterval(60);

            Map<String, Object> authInfoMap = CommonUtil.uncheckedMapCast(session.getAttribute(AUTH_INFO_MAP));

            if (authInfoMap == null) {
                authInfoMap = new HashMap<String, Object>();
                session.setAttribute(AUTH_INFO_MAP, authInfoMap);
            }/*from w  ww.jav a2s . co  m*/

            String authentication = req.getHeader("Authorization");

            if (CommonUtil.isEmpty(authentication) || !authentication.startsWith("Digest ")) {

                postAuthRequired(req, resp, authInfoMap);

            } else {
                result = authenticate(req.getMethod(), authentication, authInfoMap);

                if (result) {

                    if (authProvider != null) {
                        try {
                            authProvider.authenticated(authUser.get(), true);
                        } catch (Exception e) {
                            log.error("error while invoke the authProvider.authenticated: " + authUser.get(),
                                    e);
                        }
                    }
                    session.setAttribute(AUTHENTICATED_FLAG_KEY, true);
                    session.removeAttribute(AUTH_INFO_MAP);
                    authInfoMap.clear();
                    authInfoMap = null;

                    session.setMaxInactiveInterval(1800);
                } else {
                    authProvider.authenticated(authUser.get(), false);
                    authInfoMap.clear();
                    postAuthRequired(req, resp, authInfoMap);
                }
            }
        }
    } else {
        System.err.println("Just support session available authentication.");
    }

    return result;
}

From source file:com.nec.harvest.service.impl.PurchaseServiceImlp.java

/** {@inheritDoc} */
@Override//from  w ww. java  2 s.c  o  m
public Map<String, PurchaseBean> findByOrgCodeAndMonth(String orgCode, String getSudo, String sql)
        throws ServiceException {
    if (StringUtils.isEmpty(orgCode)) {
        throw new IllegalArgumentException("Orginazation code must not be null or empty");
    }
    if (StringUtils.isEmpty(getSudo)) {
        throw new IllegalArgumentException("Month must not be null or empty");
    }
    if (StringUtils.isEmpty(sql)) {
        throw new IllegalArgumentException("Sql must not be null or empty");
    }

    Connection connection = null;
    PreparedStatement preSmt = null;
    ResultSet rs = null;

    final String HAZELCAST_PURCHASES = "PURCHASES";
    final String UNDERSCORE_CHAR = "_";

    // Get a reference to the shared system metadata map as a cluster member
    // NOTE: this loads the map from the backing store and can take a long time for large collections
    Map<String, PurchaseBean> purchases = hzInstance.getMap(HAZELCAST_PURCHASES);
    if (hzInstance.getLifecycleService().isRunning()) {
        try {
            purchases.clear();
        } catch (HazelcastInstanceNotActiveException ex) {
            logger.debug(ex.getMessage(), ex);
        }
    }

    try {
        connection = HibernateSessionManager.getConnection();
        preSmt = connection.prepareStatement(sql);
        preSmt.setString(1, getSudo);
        preSmt.setString(2, orgCode);

        rs = preSmt.executeQuery();
        while (rs.next()) {
            String srsCode = rs.getString("srsCode");
            String ctgCode = rs.getString("ctgCode");
            String wakuNum = rs.getString("wakuNum");

            int updNo = rs.getInt("updNo");
            int kingaku = rs.getBigDecimal("kingaku").intValue();

            Date srDate = rs.getDate("srDate");
            String gnrKbn1 = rs.getString("gnrKbn1");

            StringBuilder keyBuilder = new StringBuilder();
            keyBuilder.append(DateFormatUtil.format(srDate, DateFormat.DATE_SHORT_DAY));
            keyBuilder.append(UNDERSCORE_CHAR);
            keyBuilder.append(srsCode);
            keyBuilder.append(UNDERSCORE_CHAR);
            keyBuilder.append(ctgCode);
            keyBuilder.append(UNDERSCORE_CHAR);
            keyBuilder.append(wakuNum);

            // New an instance
            PurchaseBean purchase = new PurchaseBean(srsCode, null, null, ctgCode, null, null, wakuNum, updNo,
                    srDate, kingaku, gnrKbn1);
            purchases.put(keyBuilder.toString(), purchase);
        }
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }

            if (preSmt != null) {
                preSmt.close();
            }

            if (connection != null) {
                connection.close();
            }
        } catch (SQLException ex) {
            logger.error(ex.getMessage(), ex);
        }
    }

    if (purchases.size() <= 0) {
        throw new ObjectNotFoundException(
                "Could not find any purchase in the database for the organization's code " + orgCode
                        + " in month " + getSudo);
    }

    logger.info("Size of Hazelcast Map: {} items", purchases.size());
    return purchases;
}

From source file:com.ppp.prm.portal.server.service.gwt.HibernateDetachUtility.java

public static void nullOutUninitializedFields(Object value, SerializationType serializationType)
        throws Exception {
    long start = System.currentTimeMillis();
    Map<Integer, Object> checkedObjectMap = new HashMap<Integer, Object>();
    Map<Integer, List<Object>> checkedObjectCollisionMap = new HashMap<Integer, List<Object>>();
    nullOutUninitializedFields(value, checkedObjectMap, checkedObjectCollisionMap, 0, serializationType);
    long duration = System.currentTimeMillis() - start;

    if (dumpStackOnThresholdLimit) {
        int numObjectsProcessed = checkedObjectMap.size();
        if (duration > millisThresholdLimit || numObjectsProcessed > sizeThresholdLimit) {
            String rootObjectString = (value != null) ? value.getClass().toString() : "null";
            LOG.warn("Detached [" + numObjectsProcessed + "] objects in [" + duration + "]ms from root object ["
                    + rootObjectString + "]", new Throwable("HIBERNATE DETACH UTILITY STACK TRACE"));
        }/*  w  ww  .  j a v a 2 s  .  c o m*/
    } else {
        // 10s is really long, log SOMETHING
        if (duration > 10000L && LOG.isDebugEnabled()) {
            LOG.debug("Detached [" + checkedObjectMap.size() + "] objects in [" + duration + "]ms");
        }
    }

    // help the garbage collector be clearing these before we leave
    checkedObjectMap.clear();
    checkedObjectCollisionMap.clear();
}

From source file:com.liferay.portlet.InvokerPortletImpl.java

public void render(RenderRequest renderRequest, RenderResponse renderResponse)
        throws IOException, PortletException {

    PortletException portletException = (PortletException) renderRequest
            .getAttribute(_portletId + PortletException.class.getName());

    if (portletException != null) {
        throw portletException;
    }//from  www  .  j  a va 2  s  . co  m

    StopWatch stopWatch = null;

    if (_log.isDebugEnabled()) {
        stopWatch = new StopWatch();

        stopWatch.start();
    }

    String remoteUser = renderRequest.getRemoteUser();

    if ((remoteUser == null) || (_expCache == null) || (_expCache.intValue() == 0)) {

        invokeRender(renderRequest, renderResponse);
    } else {
        RenderResponseImpl renderResponseImpl = (RenderResponseImpl) renderResponse;

        StringServletResponse stringResponse = (StringServletResponse) renderResponseImpl
                .getHttpServletResponse();

        PortletSession portletSession = renderRequest.getPortletSession();

        long now = System.currentTimeMillis();

        Layout layout = (Layout) renderRequest.getAttribute(WebKeys.LAYOUT);

        Map<String, InvokerPortletResponse> sessionResponses = getResponses(portletSession);

        String sessionResponseId = encodeResponseKey(layout.getPlid(), _portletId,
                LanguageUtil.getLanguageId(renderRequest));

        InvokerPortletResponse response = sessionResponses.get(sessionResponseId);

        if (response == null) {
            String title = invokeRender(renderRequest, renderResponse);

            response = new InvokerPortletResponse(title, stringResponse.getString(),
                    now + Time.SECOND * _expCache.intValue());

            sessionResponses.put(sessionResponseId, response);
        } else if ((response.getTime() < now) && (_expCache.intValue() > 0)) {
            String title = invokeRender(renderRequest, renderResponse);

            response.setTitle(title);
            response.setContent(stringResponse.getString());
            response.setTime(now + Time.SECOND * _expCache.intValue());
        } else {
            renderResponseImpl.setTitle(response.getTitle());
            stringResponse.getWriter().print(response.getContent());
        }
    }

    Map<String, String[]> properties = ((RenderResponseImpl) renderResponse).getProperties();

    if (properties.containsKey("clear-request-parameters")) {
        Map<String, String[]> renderParameters = ((RenderRequestImpl) renderRequest).getRenderParameters();

        renderParameters.clear();
    }

    if (_log.isDebugEnabled()) {
        _log.debug("render for " + _portletId + " takes " + stopWatch.getTime() + " ms");
    }
}

From source file:com.streamsets.datacollector.stagelibrary.ClassLoaderStageLibraryTask.java

@Inject
public ClassLoaderStageLibraryTask(RuntimeInfo runtimeInfo, Configuration configuration) {
    super("stageLibrary");
    this.runtimeInfo = runtimeInfo;
    this.configuration = configuration;
    Map<String, String> aliases = new HashMap<>();
    for (Map.Entry<String, String> entry : configuration.getSubSetConfiguration(CONFIG_LIBRARY_ALIAS_PREFIX)
            .getValues().entrySet()) {//from  w ww.j  a v  a2s  .com
        aliases.put(entry.getKey().substring(CONFIG_LIBRARY_ALIAS_PREFIX.length()), entry.getValue());
    }
    libraryNameAliases = ImmutableMap.copyOf(aliases);
    aliases.clear();
    for (Map.Entry<String, String> entry : configuration.getSubSetConfiguration(CONFIG_STAGE_ALIAS_PREFIX)
            .getValues().entrySet()) {
        aliases.put(entry.getKey().substring(CONFIG_STAGE_ALIAS_PREFIX.length()), entry.getValue());
    }
    stageNameAliases = ImmutableMap.copyOf(aliases);
}

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

/**
 * ?/*w w  w .j a  va2  s. c  om*/
 * 
 * @param userId
 * @param userType
 * @param page
 * @param month
 * @param statu
 * @param taskNameCondition
 * @return
 */
@RequestMapping(value = "/workerDetail", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> workerDetailPOST(HttpSession session, int userId, int userType, int page,
        String beginDate, String endDate, int statu, String taskNameCondition, int dateType) {
    Map<String, Object> map = new HashMap<>();
    if (userType == 2) {
        employer employer = employerService.getEmployerByUserId(userId);
        map.clear();
        map.put(Constants.USER_DETAIL, employer);
    }
    if (userType == 4) {
        int workerId = workerService.getWorkerIdByUserId(userId);
        int totle = workerRecordService.getAllCountByWorkerId(workerId, statu, beginDate, endDate,
                taskNameCondition, dateType);
        Double taskMarkTimeMonth = workerRecordService.getTaskMarkTimeMonthByWorkerIdAndMonth(workerId,
                beginDate, endDate, taskNameCondition, 1, 1, dateType);
        List<workerRecord> workerRecordList = workerRecordService.getAllByWorkerId(workerId, 1, statu,
                beginDate, endDate, taskNameCondition, page, Constants.ROW, dateType);
        List<WorkerRecordTrans> list = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATETIME_FORMAT);
        for (Iterator<workerRecord> iterator = workerRecordList.iterator(); iterator.hasNext();) {
            workerRecord workerRecord = (workerRecord) iterator.next();
            WorkerRecordTrans workerRecordTrans = new WorkerRecordTrans();

            workerRecordTrans.setTaskDownTime(sdf.format(workerRecord.getTaskDownTime()));
            if (workerRecord.getTaskEffective() == 0) {
                workerRecordTrans.setTaskEffective(MSG_UNAUDIT);
            } else if (workerRecord.getTaskEffective() == 1) {
                workerRecordTrans.setTaskEffective(MSG_QUALIFY);
            } else if (workerRecord.getTaskEffective() == 2) {
                workerRecordTrans.setTaskEffective(MSG_UNQUALIFY);
            } else if (workerRecord.getTaskEffective() == 3) {
                workerRecordTrans.setTaskEffective(MSG_GIVEUP);
            }
            if (workerRecord.getTaskMarkTime() == null) {
                workerRecordTrans.setTaskMarkTime(0.00);
            } else {
                workerRecordTrans.setTaskMarkTime(workerRecord.getTaskMarkTime());
            }
            workerRecordTrans.setTaskName(workerRecord.getTaskName());
            if (workerRecord.getTaskStatu() == 1) {
                workerRecordTrans.setTaskStatu(MSG_UPLOADED);
            } else if (workerRecord.getTaskStatu() == 0) {
                workerRecordTrans.setTaskStatu(MSG_UNUPLOAD);
            } else if (workerRecord.getTaskStatu() == 2) {
                workerRecordTrans.setTaskStatu(MSG_TIME_OUT);
            } else if (workerRecord.getTaskStatu() == 3) {
                workerRecordTrans.setTaskStatu("");
            }

            if (workerRecord.getTaskUploadTime() == null) {
                workerRecordTrans.setTaskUploadTime(Constants.EMPTY);
            } else {
                workerRecordTrans.setTaskUploadTime(sdf.format(workerRecord.getTaskUploadTime()));
            }

            list.add(workerRecordTrans);
        }

        map.clear();
        int totlePage = (int) Math.ceil((double) totle / (double) Constants.ROW);
        map.put(Constants.LIST, list);
        map.put(Constants.TOTLE, totle);// totleG
        map.put(Constants.TOTLE_PAGE, totlePage);
        if (taskMarkTimeMonth == null) {
            map.put("taskMarkTimeMonth", 0.00);
        } else {
            map.put("taskMarkTimeMonth", taskMarkTimeMonth);
        }
    }
    return map;
}

From source file:ch.flashcard.HibernateDetachUtility.java

public static void nullOutUninitializedFields(Object value, SerializationType serializationType)
        throws Exception {
    long start = System.currentTimeMillis();
    Map<Integer, Object> checkedObjectMap = new HashMap<Integer, Object>();
    Map<Integer, List<Object>> checkedObjectCollisionMap = new HashMap<Integer, List<Object>>();
    nullOutUninitializedFields(value, checkedObjectMap, checkedObjectCollisionMap, 10, serializationType);
    long duration = System.currentTimeMillis() - start;

    if (dumpStackOnThresholdLimit) {
        int numObjectsProcessed = checkedObjectMap.size();
        if (duration > millisThresholdLimit || numObjectsProcessed > sizeThresholdLimit) {
            String rootObjectString = (value != null) ? value.getClass().toString() : "null";
            LOG.warn("Detached [" + numObjectsProcessed + "] objects in [" + duration + "]ms from root object ["
                    + rootObjectString + "]", new Throwable("HIBERNATE DETACH UTILITY STACK TRACE"));
        }//  w w w.  ja  va  2 s.  c  o m
    } else {
        // 10s is really long, log SOMETHING
        if (duration > 10000L && LOG.isDebugEnabled()) {
            LOG.debug("Detached [" + checkedObjectMap.size() + "] objects in [" + duration + "]ms");
        }
    }

    // help the garbage collector be clearing these before we leave
    checkedObjectMap.clear();
    checkedObjectCollisionMap.clear();
}

From source file:jenkins.plugins.logstash.persistence.BuildData.java

public BuildData(AbstractBuild<?, ?> build, Date currentTime) {
    result = build.getResult() == null ? null : build.getResult().toString();
    id = build.getId();//from   w w w  .j  a va2  s . c o  m
    projectName = build.getProject().getName();
    displayName = build.getDisplayName();
    fullDisplayName = build.getFullDisplayName();
    description = build.getDescription();
    url = build.getUrl();

    Action testResultAction = build.getAction(AbstractTestResultAction.class);
    if (testResultAction != null) {
        testResults = new TestData(testResultAction);
    }

    Node node = build.getBuiltOn();
    if (node == null) {
        buildHost = "master";
        buildLabel = "master";
    } else {
        buildHost = StringUtils.isBlank(node.getDisplayName()) ? "master" : node.getDisplayName();
        buildLabel = StringUtils.isBlank(node.getLabelString()) ? "master" : node.getLabelString();
    }

    buildNum = build.getNumber();
    // build.getDuration() is always 0 in Notifiers
    buildDuration = currentTime.getTime() - build.getStartTimeInMillis();
    timestamp = DATE_FORMATTER.format(build.getTimestamp().getTime());
    rootProjectName = build.getRootBuild().getProject().getName();
    rootProjectDisplayName = build.getRootBuild().getDisplayName();
    rootBuildNum = build.getRootBuild().getNumber();
    buildVariables = build.getBuildVariables();

    // Get environment build variables and merge them into the buildVariables map
    Map<String, String> buildEnvVariables = new HashMap<String, String>();
    List<Environment> buildEnvironments = build.getEnvironments();
    if (buildEnvironments != null) {
        for (Environment env : buildEnvironments) {
            if (env == null) {
                continue;
            }

            env.buildEnvVars(buildEnvVariables);
            if (!buildEnvVariables.isEmpty()) {
                buildVariables.putAll(buildEnvVariables);
                buildEnvVariables.clear();
            }
        }
    }
}

From source file:io.smartspaces.util.process.BaseNativeApplicationRunner.java

/**
 * Attempt the run./*from www.  j  av a2 s  . c  o  m*/
 *
 * @param firstTime
 *          {@code true} if this is the first attempt
 *
 * @return the process that was created
 *
 * @throws SmartSpacesException
 *           was not able to start the process the first time
 */
private Process attemptRun(boolean firstTime) throws SmartSpacesException {
    try {
        ProcessBuilder builder = new ProcessBuilder(commandLine);

        Map<String, String> processEnvironment = builder.environment();
        if (cleanEnvironment) {
            processEnvironment.clear();
        }
        modifyEnvironment(processEnvironment, environment);

        // If don't know the executable folder, the executable will be run in the
        // process directory of the Java program.
        if (executableFolder != null) {
            builder.directory(executableFolder);
            log.info(String.format("Starting up native code in folder %s", executableFolder.getAbsolutePath()));
        }

        return builder.start();
    } catch (Exception e) {
        // Placed here so we can get the exception when thrown.
        if (firstTime) {
            runnerState.set(NativeApplicationRunnerState.STARTUP_FAILED);
            handleApplicationStartupFailed();

            throw SmartSpacesException.newFormattedException(e,
                    "Can't start up native application " + executablePath);
        }

        return null;
    }
}

From source file:com.silverwrist.dynamo.security.SRMObject.java

public DynamoAcl createAcl(String name, Principal owner) throws DatabaseException {
    int owner_id = 0;
    boolean owner_group = false;
    if (owner instanceof DynamoUser)
        owner_id = ((DynamoUser) owner).getUID();
    else if (owner instanceof DynamoGroup) { // get the group ID
        owner_id = ((DynamoGroup) owner).getGID();
        owner_group = true;/*from   www  . j  a  v a  2  s . co m*/

    } // end else if
    else
        throw new IllegalArgumentException("owner must be DynamoUser or DynamoGroup");

    // create the ACL in the database, then create a new ACL object
    Map acl_data = m_ops.createAcl(name, owner_id, owner_group);
    DynamoAcl rc = new AclObject(m_ops.getAclOperations(), m_ns_cache, m_proxy, m_ace, acl_data);
    synchronized (m_cache_sync) { // add the new ACL to the cache - note that an Integer representing the ACL id is
                                  // already in our returned map!
        m_cache.put(acl_data.get(SRMOperations.HMKEY_ACLID), rc);

    } // end synchronized block

    acl_data.clear();
    return rc;

}