Example usage for java.lang Long equals

List of usage examples for java.lang Long equals

Introduction

In this page you can find the example usage for java.lang Long equals.

Prototype

public boolean equals(Object obj) 

Source Link

Document

Compares this object to the specified object.

Usage

From source file:com.erudika.scoold.utils.CsrfFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;
    boolean isCSPReportRequest = request.getRequestURI().startsWith("/reports/cspv");

    if ("POST".equals(request.getMethod()) && !isCSPReportRequest) {
        String csrfToken = request.getParameter("_csrf");
        String csrfInCookie = HttpUtils.getStateParam(CSRF_COOKIE, request);

        Long time = NumberUtils.toLong(request.getParameter("_time"), 0);
        String timekey = request.getParameter("_timekey");

        if (timekey != null) {
            Long timeInSession = (Long) request.getSession().getAttribute(timekey);
            request.getSession().setAttribute(timekey, System.currentTimeMillis());
            if (!time.equals(timeInSession)) {
                logger.warn("Time token mismatch. {}, {}", request.getRemoteAddr(), request.getRequestURL());
                // response.sendError(403, "Time token mismatch.");
                response.sendRedirect(request.getRequestURI());
                return;
            }/*from   w w w. j  av  a2  s  .c  om*/
        }

        if (csrfToken == null) {
            csrfToken = request.getHeader("X-CSRF-TOKEN");
            if (csrfToken == null) {
                csrfToken = request.getHeader("X-XSRF-TOKEN");
            }
        }

        if (csrfToken == null || StringUtils.isBlank(csrfInCookie) || !csrfToken.equals(csrfInCookie)) {
            logger.warn("CSRF token mismatch. {}, {}", request.getRemoteAddr(), request.getRequestURL());
            response.sendError(403, "CSRF token mismatch.");
            return;
        }
    }
    chain.doFilter(request, response);
}

From source file:com.sun.socialsite.web.rest.core.GadgetHandler.java

/**
 * Handle a DELETE operation.  Note that unlike most of our operation-handling methods, this one
 * implements its own access-control logic.  Specifically, it enforces a requirement that a
 * request will only be honored if the token's moduleId matches the target <code>AppInstance</code>'s
 * moduleId.  In other words, a token is only empowered to delete its own <code>AppInstance</code>.
 *//*w  w  w  .  j a v a2  s.  c  o m*/
@Operation(httpMethods = "DELETE")
public Future<?> delete(SocialRequestItem reqItem) {

    authorizeRequest(reqItem);

    log.trace("BEGIN");
    Future<?> result = null;
    //reqItem.applyUrlTemplate(GADGET_DEL_PATH);

    try {
        Long id = Long.parseLong(reqItem.getParameter("gadgetId"));
        SecurityToken token = reqItem.getToken();
        if (!id.equals(token.getModuleId())) {
            String msg = String.format("token.moduleId[%s] != target.moduleId[%s]", token.getModuleId(), id);
            log.warn(msg);
            Exception e = new SocialSpiException(ResponseError.UNAUTHORIZED, msg);
            result = ImmediateFuture.errorInstance(e);
        } else {
            deleteAppInstance(id);
            result = ImmediateFuture
                    .newInstance(new JSONObject().put("code", 200).put("message", "AppInstance Deleted"));
        }
        log.trace("END");
    } catch (Exception e) {
        log.error("Unexpected Exception", e);
        result = ImmediateFuture.errorInstance(e);
    }
    return result;

}

From source file:net.kamhon.ieagle.function.user.service.impl.MenuFrameworkServiceImpl.java

public void updateUserMenu(UserMenu userMenu, Long orginalMenuId, Long version) {
    Long newMenuId = null;/*from  www. jav a  2 s. c  o  m*/

    boolean isMenuIdChanged = false;
    boolean isParentIdChanged = false;

    userMenu.setVersion(version);

    UserMenu userMenuDb = this.getUserMenu(orginalMenuId);
    VoUtil.checkVoBaseVersion(userMenu, userMenuDb);

    if (!orginalMenuId.equals(userMenu.getMenuId())) {
        isMenuIdChanged = true;
        newMenuId = userMenu.getMenuId();
    }
    // check on parentId
    if (userMenuDb.getParentId() != null) {
        if (!userMenuDb.getParentId().equals(userMenu.getParentId())) {
            isParentIdChanged = true;
        }
    } else if (userMenu.getParentId() != null) {
        isParentIdChanged = true;
    }

    // can not copy/update menuId because can not update hibernate object's primary key
    String[] properties = { "parentId", "menuName", "menuDesc", "menuUrl", "isAuthNeeded", "accessCode",
            "createMode", "readMode", "updateMode", "deleteMode", "adminMode", "treeLevel", "menuTarget",
            "status" };
    ReflectionUtil.copyPropertiesWithPropertiesList(userMenu, userMenuDb, properties);

    // if parent id changed, treeConfig need to re-generate again
    if (isParentIdChanged) {
        if (userMenuDb.getParentId() == null) {
            userMenuDb.setTreeConfig("");
        } else {
            UserMenu parentUserMenu = this.getUserMenu(userMenuDb.getParentId());
            this.setTreeConfig(userMenuDb, parentUserMenu);
        }
    }

    userMenuDao.update(userMenuDb);

    if (isParentIdChanged) {
        recursiveUpdateChildUserMenu(userMenuDb);
    }

    if (isMenuIdChanged) {
        updateMenuId(orginalMenuId, newMenuId);
    }
}

From source file:com.lcw.one.modules.sys.web.MenuController.java

@RequiresUser
@ResponseBody//from  w  w  w  .  j a  va2  s . c om
@RequestMapping(value = "treeData")
public List<Map<String, Object>> treeData(@RequestParam(required = false) Long extId,
        HttpServletResponse response) {
    response.setContentType("application/json; charset=UTF-8");
    List<Map<String, Object>> mapList = Lists.newArrayList();
    List<Menu> list = systemService.findAllMenu();
    for (int i = 0; i < list.size(); i++) {
        Menu e = list.get(i);
        if (extId == null || (extId != null && !extId.equals(e.getId())
                && e.getParentIds().indexOf("," + extId + ",") == -1)) {
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", e.getId());
            map.put("pId", e.getParent() != null ? e.getParent().getId() : 0);
            map.put("name", e.getName());
            mapList.add(map);
        }
    }
    return mapList;
}

From source file:com.wineaccess.wine.WineAdapterHelper.java

/**
 * Method to add/update wine logistic/*from   ww  w.j ava2s. c  o  m*/
 * @param addLogisticPO PO to add wine logistic 
 * @return
 */
public static Map<String, Object> addLogistic(final AddLogisticPO addLogisticPO) {

    Response response = new FailureResponse();
    response.setStatus(200);
    final WineLogisticBasicVO addWineVO = new WineLogisticBasicVO();
    final Long wineryId = Long.parseLong(addLogisticPO.getWineryId());
    final Long productId = Long.parseLong(addLogisticPO.getProductId());
    final Long contactId = Long.parseLong(addLogisticPO.getContactId());

    final Map<String, Object> outputAddLogistic = new ConcurrentHashMap<String, Object>();
    try {
        final WineryModel wineryModel = WineryRepository.getWineryById(wineryId);
        final ImporterModel importerModel = wineryModel.getActiveImporterId();
        ProductItemModel productModel = ProductItemRepository.getProductItemById(productId);
        WineModel wineModel = null;
        WineryImporterContacts contactModel = null;
        MasterData bottlePerBox = null;
        WarehouseModel warehouseModel = null;

        if (productModel != null) {
            wineModel = WineRepository.getWineById(productModel.getItemId());
            if (wineModel == null) {
                response.addError(new WineaccessError(SystemErrorCode.LOGISTIC_INVALID_WINE,
                        SystemErrorCode.LOGISTIC_INVALID_WINE_TEXT));
                logger.error("wine not exist");
            }
        }

        if (wineryModel == null) {
            response.addError(new WineaccessError(SystemErrorCode.LOGISTIC_INVALID_WINERY,
                    SystemErrorCode.LOGISTIC_INVALID_WINERY_TEXT));
            logger.error("winery not exist");
        }

        if (productModel == null) {
            response.addError(new WineaccessError(SystemErrorCode.LOGISTIC_INVALID_PRODUCT,
                    SystemErrorCode.LOGISTIC_INVALID_PRODUCT_TEXT));
            logger.error("product not exist");
        }

        if (productModel != null && wineModel != null && wineryModel != null) {
            if (addLogisticPO.getWarehouseId() != null
                    && !(StringUtils.EMPTY).equals(addLogisticPO.getWarehouseId())) {
                warehouseModel = WarehouseRepository
                        .getNonDeletedWarehouseById(Long.parseLong(addLogisticPO.getWarehouseId()));
                if (warehouseModel == null) {
                    response.addError(new WineaccessError(SystemErrorCode.LOGISTIC_INVALID_WAREHOUSE,
                            SystemErrorCode.LOGISTIC_INVALID_WAREHOUSE_TEXT));
                    logger.error("warehouse does not exist");
                }
            } else {
                wineModel.setWarehouseId(warehouseModel);
            }
            contactModel = WineryImporterContactRepository
                    .getContactById(Long.parseLong(addLogisticPO.getContactId()));

            //contactModel = WineryImporterContactRepository.getContactByContactIdWineryId(wineryId,contactId);
            bottlePerBox = MasterDataRepository
                    .getMasterDataById(Long.parseLong(addLogisticPO.getBottlePerBox()));
            final Long wineryIdFromModel = wineModel.getWineryId().getId();
            final Long wineIdFromModel = wineryModel.getId();
            if (!wineryIdFromModel.equals(wineIdFromModel)) {
                response.addError(new WineaccessError(SystemErrorCode.LOGISTIC_INVALID_WINE_WINERY,
                        SystemErrorCode.LOGISTIC_INVALID_WINE_WINERY_TEXT));
                logger.error("wine and winery combination not exist");
            }

            if (contactModel == null) {
                response.addError(new WineaccessError(SystemErrorCode.LOGISTIC_INVALID_CONTACT,
                        SystemErrorCode.LOGISTIC_INVALID_CONTACT_TEXT));
                logger.error("wine and winery combination not exist");
            }

            if (bottlePerBox == null) {
                response.addError(new WineaccessError(SystemErrorCode.LOGISTIC_INVALID_BOTTLE_PER_BOX,
                        SystemErrorCode.LOGISTIC_INVALID_BOTTLE_PER_BOX_TEXT));
                logger.error("wine and winery combination not exist");
            }
        }

        if (response.getErrors().isEmpty() && wineModel != null) {
            wineModel.setWarehouseId(warehouseModel);
            wineModel.setContactId(contactModel);
            wineModel.setIsFullCaseOnly(Boolean.valueOf(addLogisticPO.getIsFullCaseOnly()));
            wineModel.setBottleWeightInLBS(Long.parseLong(addLogisticPO.getBottleWeightInLBS()));
            wineModel.setBottlesPerBox(bottlePerBox);
            wineModel = WineRepository.update(wineModel);

            if (wineModel.getId() != null) {
                addWineVO.setWineId(wineModel.getId());
                addWineVO.setWineryId(wineModel.getWineryId().getId());
                addWineVO.setProductId(productModel.getId());
                addWineVO.setMessage("Logistic for Wine Created");
                response = new com.wineaccess.response.SuccessResponse(addWineVO, 200);
            } else {
                response.addError(new WineaccessError(SystemErrorCode.LOGISTIC_NOT_CREATED,
                        SystemErrorCode.LOGISTIC_NOT_CREATED_TEXT));
            }
        }

    } catch (Exception e) {
        response.addError(new WineaccessError(SystemErrorCode.LOGISTIC_NOT_CREATED,
                SystemErrorCode.LOGISTIC_NOT_CREATED_TEXT));
        logger.error("Some error occured", e.fillInStackTrace());
    }
    outputAddLogistic.put("FINAL-RESPONSE", response);

    return outputAddLogistic;

}

From source file:org.apache.ambari.server.controller.internal.StageResourceProvider.java

/**
 * Converts the {@link StageEntity} to a {@link Resource}.
 *
 * @param entity        the entity to convert (not {@code null})
 * @param requestedIds  the properties requested (not {@code null})
 *
 * @return the new resource//from   ww  w. j a  v a2 s  .c  om
 */
//todo: almost exactly the same as other toResource except how summaries are obtained
//todo: refactor to combine the two with the summary logic extracted
private Resource toResource(StageEntity entity, Set<String> requestedIds) {

    Resource resource = new ResourceImpl(Resource.Type.Stage);

    Long clusterId = entity.getClusterId();
    if (clusterId != null && !clusterId.equals(Long.valueOf(-1L))) {
        try {
            Cluster cluster = clustersProvider.get().getClusterById(clusterId);

            setResourceProperty(resource, STAGE_CLUSTER_NAME, cluster.getClusterName(), requestedIds);
        } catch (Exception e) {
            LOG.error("Can not get information for cluster " + clusterId + ".", e);
        }
    }

    Map<Long, HostRoleCommandStatusSummaryDTO> summary = topologyManager
            .getStageSummaries(entity.getRequestId());

    setResourceProperty(resource, STAGE_STAGE_ID, entity.getStageId(), requestedIds);
    setResourceProperty(resource, STAGE_REQUEST_ID, entity.getRequestId(), requestedIds);
    setResourceProperty(resource, STAGE_CONTEXT, entity.getRequestContext(), requestedIds);

    // this property is lazy loaded in JPA; don't use it unless requested
    if (isPropertyRequested(STAGE_CLUSTER_HOST_INFO, requestedIds)) {
        resource.setProperty(STAGE_CLUSTER_HOST_INFO, entity.getClusterHostInfo());
    }

    // this property is lazy loaded in JPA; don't use it unless requested
    if (isPropertyRequested(STAGE_COMMAND_PARAMS, requestedIds)) {
        resource.setProperty(STAGE_COMMAND_PARAMS, entity.getCommandParamsStage());
    }

    // this property is lazy loaded in JPA; don't use it unless requested
    if (isPropertyRequested(STAGE_HOST_PARAMS, requestedIds)) {
        resource.setProperty(STAGE_HOST_PARAMS, entity.getHostParamsStage());
    }

    setResourceProperty(resource, STAGE_SKIPPABLE, entity.isSkippable(), requestedIds);

    Long startTime = Long.MAX_VALUE;
    Long endTime = 0L;
    if (summary.containsKey(entity.getStageId())) {
        startTime = summary.get(entity.getStageId()).getStartTime();
        endTime = summary.get(entity.getStageId()).getEndTime();
    }

    setResourceProperty(resource, STAGE_START_TIME, startTime, requestedIds);
    setResourceProperty(resource, STAGE_END_TIME, endTime, requestedIds);

    CalculatedStatus status = CalculatedStatus.statusFromStageSummary(summary,
            Collections.singleton(entity.getStageId()));

    setResourceProperty(resource, STAGE_PROGRESS_PERCENT, status.getPercent(), requestedIds);
    setResourceProperty(resource, STAGE_STATUS, status.getStatus(), requestedIds);
    setResourceProperty(resource, STAGE_DISPLAY_STATUS, status.getDisplayStatus(), requestedIds);

    return resource;
}

From source file:io.smartspaces.util.io.directorywatcher.SimpleDirectoryWatcher.java

/**
 * Find all files added or modified since the last scan.
 * /*w  ww  .  j  a v  a  2 s. c o  m*/
 * <p>
 * This modifies the seen map.
 *
 * @param currentScan
 *          the files from the current scan
 */
private void findAddedFiles(Set<File> currentScan) {
    for (File fileFromCurrent : currentScan) {
        Long modifiedTime = fileFromCurrent.lastModified();
        Long lastModifiedTime = filesSeen.put(fileFromCurrent, modifiedTime);
        if (lastModifiedTime == null) {
            signalFileAdded(fileFromCurrent);
        } else if (!lastModifiedTime.equals(modifiedTime)) {
            signalFileModified(fileFromCurrent);
        }
    }
}

From source file:org.anhonesteffort.flock.CalendarCopyService.java

@Override
public void onCalendarCopyFailed(Exception e, Account fromAccount, Account toAccount, Long localId) {
    Log.e(TAG, "onCalendarCopyFailed() from " + fromAccount + ", " + localId + " to " + toAccount, e);

    int failedEvents = 0;
    boolean calendarWasFound = false;

    for (CalendarForCopy calendarForCopy : calendarsForCopy) {
        Account calendarAccount = calendarForCopy.fromAccount;
        Long calendarId = calendarForCopy.calendarId;
        Integer eventCount = calendarForCopy.eventCount;

        if (calendarAccount.equals(fromAccount) && calendarId.equals(localId)) {
            failedEvents = eventCount;//from ww  w  . j a  va  2  s .com
            calendarWasFound = true;
            break;
        }
    }

    if (calendarWasFound) {
        for (int i = 0; i < failedEvents; i++)
            handleEventCopyFailed(fromAccount);
    }
}

From source file:es.fcs.batch.integration.chunk.MyChunkMessageChannelItemWriter.java

/**
 * Get the next result if it is available (within the timeout specified in the gateway), otherwise do nothing.
 * /* www.j a  v  a2  s.  co m*/
 * @throws AsynchronousFailureException If there is a response and it contains a failed chunk response.
 * 
 * @throws IllegalStateException if the result contains the wrong job instance id (maybe we are sharing a channel
 * and we shouldn't be)
 */
private void getNextResult() throws AsynchronousFailureException {
    ChunkResponse payload = (ChunkResponse) messagingGateway.receive();
    if (payload != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Found result: " + payload);
        }
        Long jobInstanceId = payload.getJobId();
        Assert.state(jobInstanceId != null, "Message did not contain job instance id.");
        Assert.state(jobInstanceId.equals(localState.getJobId()), "Message contained wrong job instance id ["
                + jobInstanceId + "] should have been [" + localState.getJobId() + "].");
        if (payload.isRedelivered()) {
            logger.warn(
                    "Redelivered result detected, which may indicate stale state. In the best case, we just picked up a timed out message "
                            + "from a previous failed execution. In the worst case (and if this is not a restart), "
                            + "the step may now timeout.  In that case if you believe that all messages "
                            + "from workers have been sent, the business state "
                            + "is probably inconsistent, and the step will fail.");
            localState.incrementRedelivered();
        }
        localState.pushStepContribution(payload.getStepContribution());
        localState.incrementActual();
        if (!payload.isSuccessful()) {
            throw new AsynchronousFailureException(
                    "Failure or interrupt detected in handler: " + payload.getMessage());
        }
    }
}

From source file:org.apache.ambari.server.controller.internal.StageResourceProvider.java

/**
 * Converts the {@link StageEntity} to a {@link Resource}.
 *
 * @param entity        the entity to convert (not {@code null})
 * @param requestedIds  the properties requested (not {@code null})
 *
 * @return the new resource//  w w  w .j av a2  s  .co m
 */
private Resource toResource(Map<Long, Map<Long, HostRoleCommandStatusSummaryDTO>> cache, StageEntity entity,
        Set<String> requestedIds) {

    Resource resource = new ResourceImpl(Resource.Type.Stage);

    Long clusterId = entity.getClusterId();
    if (clusterId != null && !clusterId.equals(Long.valueOf(-1L))) {
        try {
            Cluster cluster = clustersProvider.get().getClusterById(clusterId);

            setResourceProperty(resource, STAGE_CLUSTER_NAME, cluster.getClusterName(), requestedIds);
        } catch (Exception e) {
            LOG.error("Can not get information for cluster " + clusterId + ".", e);
        }
    }

    if (!cache.containsKey(entity.getRequestId())) {
        cache.put(entity.getRequestId(), hostRoleCommandDAO.findAggregateCounts(entity.getRequestId()));
    }

    Map<Long, HostRoleCommandStatusSummaryDTO> summary = cache.get(entity.getRequestId());

    setResourceProperty(resource, STAGE_STAGE_ID, entity.getStageId(), requestedIds);
    setResourceProperty(resource, STAGE_REQUEST_ID, entity.getRequestId(), requestedIds);
    setResourceProperty(resource, STAGE_CONTEXT, entity.getRequestContext(), requestedIds);

    // this property is lazy loaded in JPA; don't use it unless requested
    if (isPropertyRequested(STAGE_CLUSTER_HOST_INFO, requestedIds)) {
        resource.setProperty(STAGE_CLUSTER_HOST_INFO, entity.getClusterHostInfo());
    }

    // this property is lazy loaded in JPA; don't use it unless requested
    if (isPropertyRequested(STAGE_COMMAND_PARAMS, requestedIds)) {
        String value = entity.getCommandParamsStage();
        if (!StringUtils.isBlank(value)) {
            value = SecretReference.maskPasswordInPropertyMap(value);
        }
        resource.setProperty(STAGE_COMMAND_PARAMS, value);
    }

    // this property is lazy loaded in JPA; don't use it unless requested
    if (isPropertyRequested(STAGE_HOST_PARAMS, requestedIds)) {
        String value = entity.getHostParamsStage();
        if (!StringUtils.isBlank(value)) {
            value = SecretReference.maskPasswordInPropertyMap(value);
        }
        resource.setProperty(STAGE_HOST_PARAMS, value);
    }

    setResourceProperty(resource, STAGE_SKIPPABLE, entity.isSkippable(), requestedIds);

    Long startTime = Long.MAX_VALUE;
    Long endTime = 0L;
    if (summary.containsKey(entity.getStageId())) {
        startTime = summary.get(entity.getStageId()).getStartTime();
        endTime = summary.get(entity.getStageId()).getEndTime();
    }

    setResourceProperty(resource, STAGE_START_TIME, startTime, requestedIds);
    setResourceProperty(resource, STAGE_END_TIME, endTime, requestedIds);

    CalculatedStatus status;
    if (summary.isEmpty()) {
        // Delete host might have cleared all HostRoleCommands
        status = CalculatedStatus.getCompletedStatus();
    } else {
        status = CalculatedStatus.statusFromStageSummary(summary, Collections.singleton(entity.getStageId()));
    }

    setResourceProperty(resource, STAGE_PROGRESS_PERCENT, status.getPercent(), requestedIds);
    setResourceProperty(resource, STAGE_STATUS, status.getStatus(), requestedIds);
    setResourceProperty(resource, STAGE_DISPLAY_STATUS, status.getDisplayStatus(), requestedIds);

    return resource;
}