List of usage examples for java.lang Long intValue
public int intValue()
From source file:com.liusoft.dlog4j.upload.SecurityFCKUploadServlet.java
/** * ?/*from ww w . ja v a 2s.co m*/ */ protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { //??????(??) SessionUserObject loginUser = UserLoginManager.getLoginUser(req, res, true); if (loginUser != null) { super.doPost(req, res);//post?? Integer errno = (Integer) req.getAttribute("errno"); if (errno != null && errno.intValue() == 0) { //? FckUploadFileBean fbean = new FckUploadFileBean(); try { Long fileSize = (Long) req.getAttribute("file.size"); Integer fileType = (Integer) req.getAttribute("file.type"); String savePath = (String) req.getAttribute("file.path"); String uriPath = (String) req.getAttribute("file.uri"); if (fileSize != null) fbean.setFileSize(fileSize.intValue()); if (fileType != null) fbean.setFileType(fileType.intValue()); fbean.setSavePath(savePath); fbean.setUri(uriPath); HttpSession ssn = req.getSession(true); //SESSION_ID??Cookie RequestUtils.setCookie(req, res, Globals.SESSION_ID_KEY_IN_COOKIE, ssn.getId(), -1); fbean.setSessionId(ssn.getId()); fbean.setUser(new UserBean(loginUser.getId())); fbean.setUploadTime(new Date()); FCKUploadFileDAO.createUploadFileItem(fbean); } catch (Exception e) { log.error("Writting upload file info failed.", e); } } return; } res.sendError(HttpServletResponse.SC_FORBIDDEN); }
From source file:pl.exsio.frameset.vaadin.module.util.usergen.UserGenModule.java
private void generateUsers(Form form) { OptionGroup groups = (OptionGroup) form.getField("groups"); Set<Group> groupsSet = getGroupsSet(groups); Set<Role> rolesSet = getRolesSet(form); String usernamePrefix = (String) form.getField("usernamePrefix").getValue(); String usernameSuffix = (String) form.getField("usernameSuffix").getValue(); Long from = Long.parseLong((String) form.getField("from").getValue()); Long to = Long.parseLong((String) form.getField("to").getValue()); Table csvTable = createCsvTable();/*from w w w .jav a2s . c o m*/ for (int i = from.intValue(); i < to.intValue(); i++) { String username = usernamePrefix + i + "@" + usernameSuffix; byte[] byteArray = KeyGenerators.secureRandom(2).generateKey(); String passwordSuffix = ""; for (byte b : byteArray) { passwordSuffix += new Byte(b).toString(); } String password = usernamePrefix + passwordSuffix; User user = this.securityEntities.newUser(); user.setUsername(username); user.setPassword(this.encoder.encode(password)); user.setEmail(username); user.setEnabled(true); user.setGroups(groupsSet); user.setRoles(rolesSet); Item item = csvTable.addItem(username); item.getItemProperty("username").setValue(username); try { this.securityRepositories.getUserRepository().save(user); item.getItemProperty("password").setValue(password); } catch (DataIntegrityViolationException ex) { item.getItemProperty("password").setValue(t("username_exists")); } } CSVExporter exporter = createCsvExporter(csvTable); this.addComponent(exporter); Notification.show(t("generation_completed")); }
From source file:ch.heigvd.gamification.api.LeaderboardEndpoint.java
@Override public ResponseEntity<LeaderboardDTO> leaderboardGet( @ApiParam(value = "token that identifies the app sending the request", required = true) @RequestHeader(value = "X-Gamification-Token", required = true) String xGamificationToken) { AuthenKey apiKey = authenKeyRepository.findByAppKey(xGamificationToken); if (apiKey == null) { return new ResponseEntity("apikey not exist", HttpStatus.BAD_REQUEST); }/*from w w w. j av a2s. co m*/ Application app = apiKey.getApp(); if (app != null) { List<LeaderboardDTO> results = new ArrayList<>(); List<Object[]> endUsers = new ArrayList<>(); endUsers = endUserRepository.getBestUsers(app); if (endUsers.isEmpty()) { endUsers = endUserRepository.getBestBadgeUsers(app); for (int i = 0; i < endUsers.size(); ++i) { LeaderboardDTO tmp = new LeaderboardDTO(); EndUser enduser = (EndUser) endUsers.get(i)[0]; tmp.setName(enduser.getName()); tmp.setEndUserId(enduser.getId()); List<String> names = new ArrayList<>(); for (BadgeAward badge : enduser.getBadgeAwards()) { names.add(badge.getBadge().getName()); } tmp.setBadges(names); if (!results.contains(tmp)) { results.add(tmp); } } return new ResponseEntity(results, HttpStatus.OK); } System.out.println("la taille de l'objet" + endUsers.size()); PointScale pointscale = new PointScale(); for (int i = 0; i < endUsers.size(); ++i) { Long somme = 0l; LeaderboardDTO tmp = new LeaderboardDTO(); EndUser enduser = (EndUser) endUsers.get(i)[0]; tmp.setName(enduser.getName()); tmp.setEndUserId(enduser.getId()); somme = (Long) endUsers.get(i)[2]; tmp.setPoints(somme.intValue()); pointscale = (PointScale) endUsers.get(i)[1]; tmp.setNamePointscale(pointscale.getName()); List<String> names = new ArrayList<>(); System.err.println("version badge"); for (BadgeAward badge : enduser.getBadgeAwards()) { names.add(badge.getBadge().getName()); } tmp.setBadges(names); if (!results.contains(tmp)) { results.add(tmp); } } return new ResponseEntity(results, HttpStatus.OK); } return new ResponseEntity("content no available", HttpStatus.BAD_REQUEST); }
From source file:edu.brown.benchmark.auctionmark.TestAuctionMarkLoader.java
protected static void initTable(String tableName) throws Exception { String field_name = null;//from w w w. j a va2 s . com Field field_handle = null; Long tablesize = Long.MAX_VALUE; Long batchsize = Long.MAX_VALUE; // Not all tables will have a table size if (AuctionMarkConstants.DATAFILE_TABLES.contains(tableName) == false && AuctionMarkConstants.DYNAMIC_TABLES.contains(tableName) == false && tableName.equalsIgnoreCase(AuctionMarkConstants.TABLENAME_ITEM) == false) { LOG.debug("Retrieving TABLESIZE attribute for table '" + tableName + "'"); field_name = "TABLESIZE_" + tableName; field_handle = AuctionMarkConstants.class.getField(field_name); assertNotNull(field_handle); tablesize = (Long) field_handle.get(null); if (!AuctionMarkConstants.FIXED_TABLES.contains(tableName)) tablesize = Math.round(tablesize / SCALE_FACTOR); } // But all tables should have a batch size field_name = "BATCHSIZE_" + tableName; field_handle = AuctionMarkConstants.class.getField(field_name); assertNotNull(field_handle); batchsize = (Long) field_handle.get(null); // Make sure we reset the total number of rows we have loaded so far EXPECTED_TABLESIZES.put(tableName, tablesize); EXPECTED_BATCHSIZES.put(tableName, batchsize.intValue()); }
From source file:com.creditcloud.common.entities.dao.AbstractReadDAO.java
/** * count entity by ParamInfo// w w w . j a v a2 s .c om * * @param paramInfo * @return */ public int count(ParamInfo paramInfo) { EntityManager em = getEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery cq = cb.createQuery(entityClass); Root<T> userRoot = cq.from(entityClass); cq.select(cb.count(userRoot)); //build query for paramInfo if (paramInfo != null) { Set<Predicate> andCriteria = new HashSet(); Set<Predicate> orCriteria = new HashSet(); for (ParamItem item : paramInfo.getParamItems()) { Predicate predicate; if (item.getValue() instanceof String) { //fuzy search for string String regExp = "%" + item.getValue() + "%"; predicate = cb.like((Expression) (userRoot.get(item.getFieldName())), regExp); } else { predicate = cb.equal((userRoot.get(item.getFieldName())), item.getValue()); } switch (item.getOperator()) { case AND: andCriteria.add(predicate); break; case OR: orCriteria.add(predicate); break; } } if (orCriteria.size() > 0) { Predicate or = cb.or(orCriteria.toArray(new Predicate[orCriteria.size()])); andCriteria.add(or); } if (andCriteria.size() > 0) { Predicate and = cb.and(andCriteria.toArray(new Predicate[andCriteria.size()])); cq.where(and); } } TypedQuery<Long> query = em.createQuery(cq); Long result = query.getSingleResult(); return result == null ? 0 : result.intValue(); }
From source file:com.seajas.search.contender.jms.processor.FeedProcessor.java
/** * Process the given feed.//from ww w . j a v a 2 s .c om * * @param feed */ public void process(final Feed feed) { if (logger.isInfoEnabled()) logger.info(String.format("Retrieving feed '%s' with URL '%s'", feed.getName(), feed.getUri())); SyndFeed resultFeed = feedModifierService.getFeed(feed.getUri(), feed.getFeedEncodingOverride(), feed.getUserAgent(), feed.getResultParameters(), feed.getRetrievalRequestHeaders(), false); if (resultFeed == null) { logger.error(String.format("No feed created from feed '%s' with URL '%s' - discarding", feed.getName(), feed.getUri())); return; } List<SyndEntry> entries = resultFeed.getEntries(); if (logger.isInfoEnabled()) logger.info(String.format("Feed with name '%s' produced %d entries", feed.getName(), entries.size())); // Add, update or ignore should it already have been processed List<SourceElement> elements = new ArrayList<SourceElement>(); for (SyndEntry resultEntry : entries) { try { WebFeeds.validateEntry(resultEntry, resultFeed); // Make sure to strip out any unserializable components resultEntry.setForeignMarkup(null); ((SyndEntryImpl) resultEntry).setWireEntry(null); // Create a proper URI and use it for both the source element and the cache key generation to avoid any cache misses URI entryLink = URI.create(feedModifierService.getEntryLink(resultEntry)); String cacheKey = cacheService.createCompositeKey(entryLink.toString(), feed.getResultParameters()); if (!cacheService.isCached(cacheKey)) { SourceElement element = new SourceElement(); element.setUri(entryLink); element.setHostname( StringUtils.hasText(entryLink.getHost()) ? entryLink.getHost().replace("www.", "") : "localhost"); element.setEntry(resultEntry); element.setUserAgent(determineUserAgent(feed)); elements.add(element); } else { if (logger.isDebugEnabled()) logger.debug(String.format("Not injecting feed with entry link '%s' - already in cache", resultEntry.getLink())); } } catch (FeedException e) { logger.warn(String.format("Skipping entry in feed %s at %s", feed.getId(), feed.getUri()), e); } } if (logger.isInfoEnabled()) logger.info(String.format( "Finished retrieving feed '%s' with URL '%s' (and hostname %s) - injecting the %d result(s)", feed.getName(), feed.getUri(), feed.getHostname() != null ? "'" + feed.getHostname() + "'" : "(null)", elements.size())); // Don't consider injecting locally or remotely - everything goes over the queue - it's easier that way for (SourceElement element : elements) { Long elementDelay = feed.getElementDelay(); if (feed.isElementDelayRandomized() && elementDelay > 0) elementDelay = (long) randomGenerator.nextInt(elementDelay.intValue() - RANDOM_RANGE_MINIMUM + 1) + RANDOM_RANGE_MINIMUM; if (logger.isInfoEnabled()) logger.info(String.format("Injecting feed element with hostname %s%s - URI is %s", element.getHostname() != null ? "'" + element.getHostname() + "'" : "(null)", elementDelay != null ? " and delay " + elementDelay : "", element.getUri())); // This element might already exist in the storage back-end (cache-sync issues, etc.) // String compositeUrl = cacheService.createCompositeKey(element.getUri().toString(), feed.getResultParameters()); // CompositeEntry existingEntry = storageService.retrieveEntryByCompositeUrl(compositeUrl); // if (existingEntry != null) // logger.warn("The storage back-end already contains a fully processed element with composite (enricher) ID '" + compositeUrl + "' - probably due to cache sync - will reuse"); CompositeEntry existingEntry = null; // Create and inject a new CompositeEntry CompositeEntry entry = existingEntry != null ? existingEntry : new CompositeEntry(); if (existingEntry == null) entry.setId(ObjectId.get()); entry.setSource(feed); entry.setElement(element); entry.setCurrentState(CompositeState.SourceElement); storageService.saveEntry(entry); injectionService.injectElement(entry.getId(), element.getHostname(), elementDelay); } if (logger.isInfoEnabled()) logger.info(String.format("Finished injecting results for feed '%s' with URL '%s'", feed.getName(), feed.getUri())); }
From source file:fm.pattern.tokamak.server.service.AccountServiceImpl.java
@Transactional(readOnly = true) public Result<List<Account>> list(Criteria criteria) { Long count = super.count(super.query("select count(account.id) from Accounts account")); List<Account> data = super.query("from Accounts order by username") .setFirstResult(criteria.getFirstResult()).setMaxResults(criteria.getLimit()).getResultList(); return Result.accept((List<Account>) new PaginatedList<Account>(data, count.intValue(), criteria)); }
From source file:org.tonguetied.keywordmanagement.KeywordRepositoryImpl.java
public PaginatedList<Keyword> getKeywords(final Integer firstResult, final Integer maxResults, final Order order) { final String queryName; if (Order.desc == order) queryName = QUERY_GET_KEYWORDS_DESC; else/*from w w w. j av a 2s . co m*/ queryName = QUERY_GET_KEYWORDS; Query query = getSession().getNamedQuery(queryName); if (firstResult != null) query.setFirstResult(firstResult); if (maxResults != null) query.setMaxResults(maxResults); Long maxListSize = 0L; final List<Keyword> queryList = query.list(); if (queryList.size() > 0) maxListSize = (Long) getSession().getNamedQuery(QUERY_KEYWORD_COUNT).uniqueResult(); return new PaginatedList<Keyword>(queryList, maxListSize.intValue()); }
From source file:com.hmsinc.epicenter.service.data.DataQueryService.java
/** * @param <G>/*from w ww. j a v a 2 s.co m*/ * @param analysisParameters * @param raw * @param aggregateGeographyType * @return */ private <G extends Geography> Map<G, TimeSeries> doDataRepresentation( final AnalysisParameters analysisParameters, final Map<G, TimeSeries> raw, final Class<G> aggregateGeographyType) { final Map<G, TimeSeries> result; // Handle data representation if (DataRepresentation.PERCENTAGE_OF_TOTAL.equals(analysisParameters.getDataRepresentation())) { final Map<G, TimeSeries> totals = analysisRepository.getTotalCounts(analysisParameters, aggregateGeographyType); result = AnalysisUtils.normalize(raw, totals); } else if (DataRepresentation.POPULATION_RATE.equals(analysisParameters.getDataRepresentation())) { result = new HashMap<G, TimeSeries>(); for (Map.Entry<G, TimeSeries> node : raw.entrySet()) { final Long population = getPopulationForGeography(node.getKey()); final TimeSeries popn = populationRateNormalizer.normalize(node.getValue(), population.intValue()); result.put(node.getKey(), popn); } } else { result = raw; } return result; }
From source file:com.insoul.ti.controller.ContestProjectEntryController.java
@RequestMapping("/list") public ModelAndView list(@Valid ContestEntryListRequest request, BindingResult result) { ModelAndView mv = createModelView(CONTEST_PROJECT_LIST, request); PageQuery query = request.init().getQuery(); ContestEntryCriteria criteria = new ContestEntryCriteria(); criteria.setLimit(query.getPage_size()); criteria.setOffset(Long.valueOf(query.getIndex()).intValue()); criteria.setContestId(request.getContestId()); criteria.setUserId(request.getUserId()); List<ContestEntry> list = contestEntryDAO.queryContestEntry(criteria); Long count = contestEntryDAO.countContestEntry(criteria); query.setCount((count == null || count <= 0L) ? 0 : count.intValue()); List<ContestEntryVO> voList = new ArrayList<ContestEntryVO>(); if (CollectionUtils.isNotEmpty(list)) { for (ContestEntry contestEntry : list) { voList.add(toContestEntryVO(contestEntry)); }//from w ww . j av a 2s . c o m mv.addObject("query", query); mv.addObject("contestEntryList", voList); mv.addObject("success", true); mv.addObject("req", request); return mv; } mv.addObject("query", query); mv.addObject("contestEntryList", voList); mv.addObject("success", false); mv.addObject("req", request); return mv; }