List of usage examples for java.lang Long intValue
public int intValue()
From source file:org.venice.piazza.servicecontroller.data.mongodb.accessors.MongoAccessor.java
/** * Gets the complete list of all Jobs in the Service's Service Queue that have exceeded the length of time for * processing, and are thus considered timed out. * //from w w w . ja va 2 s .c o m * @param serviceId * The ID of the Service whose Queue to check * @return The list of timed out Jobs */ public List<ServiceJob> getTimedOutServiceJobs(String serviceId) { // Get the Service details to find out the timeout information Service service = getServiceById(serviceId); Long timeout = service.getTimeout(); if (timeout == null) { // If no timeout is specified for the Service, then we can't check for timeouts. return new ArrayList<ServiceJob>(); } // The timeout is in seconds. Get the current time and subtract the number of seconds to find the timestamp of a // timed out service. long timeoutEpoch = new DateTime().minusSeconds(timeout.intValue()).getMillis(); // Query the database for Jobs whose startedOn field is older than the timeout date. JacksonDBCollection<ServiceJob, String> collection = getServiceJobCollection(serviceId); DBCursor<ServiceJob> jobs = collection.find(DBQuery.exists("startedOn")); jobs = jobs.and(DBQuery.lessThan("startedOn", timeoutEpoch)); // Return the list return jobs.toArray(); }
From source file:com.glaf.core.service.impl.MxSysDataTableServiceImpl.java
@Transactional public void saveDataList(String datatableId, List<Map<String, Object>> dataList) { SysDataTable dataTable = this.getDataTableById(datatableId); Map<String, Object> newData = new HashMap<String, Object>(); SysDataField idField = null;/*from w w w. ja v a 2 s . c om*/ List<SysDataField> fields = dataTable.getFields(); if (fields != null && !fields.isEmpty()) { for (SysDataField field : fields) { if (StringUtils.equalsIgnoreCase("1", field.getPrimaryKey()) || StringUtils.equalsIgnoreCase("y", field.getPrimaryKey()) || StringUtils.equalsIgnoreCase("true", field.getPrimaryKey())) { idField = field; break; } } } if (idField == null) { throw new java.lang.RuntimeException("primary key not found."); } for (Map<String, Object> dataMap : dataList) { newData.clear(); Set<Entry<String, Object>> entrySet = dataMap.entrySet(); for (Entry<String, Object> entry : entrySet) { String key = entry.getKey(); Object value = entry.getValue(); if (value != null) { newData.put(key, value); newData.put(key.toUpperCase(), value); } } Object idValue = newData.get(idField.getColumnName().toUpperCase()); if (idValue == null) { idValue = newData.get(idField.getName().toUpperCase()); } TableModel row = new TableModel(); row.setTableName(dataTable.getTablename()); ColumnModel col01 = new ColumnModel(); col01.setColumnName(idField.getColumnName()); if (idValue == null) { if (StringUtils.equalsIgnoreCase(idField.getDataType(), "Integer")) { col01.setJavaType("Long"); Long id = idGenerator.nextId(); col01.setIntValue(id.intValue()); col01.setValue(Integer.valueOf(id.intValue())); } else if (StringUtils.equalsIgnoreCase(idField.getDataType(), "Long")) { col01.setJavaType("Long"); Long id = idGenerator.nextId(); col01.setLongValue(id); col01.setValue(id); } else { col01.setJavaType("String"); String id = idGenerator.getNextId(); col01.setStringValue(id); col01.setValue(id); } row.setIdColumn(col01); } else { if (StringUtils.equalsIgnoreCase(idField.getDataType(), "Integer")) { col01.setJavaType("Long"); String id = idValue.toString(); col01.setIntValue(Integer.parseInt(id)); col01.setValue(col01.getIntValue()); } else if (StringUtils.equalsIgnoreCase(idField.getDataType(), "Long")) { col01.setJavaType("Long"); String id = idValue.toString(); col01.setLongValue(Long.parseLong(id)); col01.setValue(col01.getLongValue()); } else { col01.setJavaType("String"); String id = idValue.toString(); col01.setStringValue(id); col01.setValue(id); } row.setIdColumn(col01); } if (fields != null && !fields.isEmpty()) { for (SysDataField field : fields) { if (StringUtils.equalsIgnoreCase(idField.getColumnName(), field.getColumnName())) { continue; } String name = field.getColumnName().toUpperCase(); String javaType = field.getDataType(); ColumnModel c = new ColumnModel(); c.setColumnName(field.getColumnName()); c.setJavaType(javaType); Object value = newData.get(name); if (value != null) { if ("Integer".equals(javaType)) { value = ParamUtils.getInt(newData, name); } else if ("Long".equals(javaType)) { value = ParamUtils.getLong(newData, name); } else if ("Double".equals(javaType)) { value = ParamUtils.getDouble(newData, name); } else if ("Date".equals(javaType)) { value = ParamUtils.getTimestamp(newData, name); } else if ("String".equals(javaType)) { value = ParamUtils.getString(newData, name); } else if ("Clob".equals(javaType)) { value = ParamUtils.getString(newData, name); } c.setValue(value); row.addColumn(c); } else { name = field.getName().toUpperCase(); value = newData.get(name); if (value != null) { if ("Integer".equals(javaType)) { value = ParamUtils.getInt(newData, name); } else if ("Long".equals(javaType)) { value = ParamUtils.getLong(newData, name); } else if ("Double".equals(javaType)) { value = ParamUtils.getDouble(newData, name); } else if ("Date".equals(javaType)) { value = ParamUtils.getTimestamp(newData, name); } else if ("String".equals(javaType)) { value = ParamUtils.getString(newData, name); } else if ("Clob".equals(javaType)) { value = ParamUtils.getString(newData, name); } c.setValue(value); row.addColumn(c); } } } } if (idValue == null) { tableDataMapper.insertTableData(row); } else { tableDataMapper.updateTableDataByPrimaryKey(row); } } }
From source file:com.multimedia.service.wallpaper.CmsWallpaperService.java
@Override public void optimizeWallpaper(Long id) { Wallpaper p = wallpaper_service.getById(id); if (p.getOptimized_manual() || p.getOptimized()) return;//from www.ja v a 2s . co m List<Pages> parents = pages_service.getAllPagesParents(p.getId_pages(), PAGES_PROP_NAMES); //selecting random optimization phrase(page pseudonym) for each parent StringBuilder title = new StringBuilder(); String name = null; StringBuilder tags = new StringBuilder(); String rop = null; Random r = new Random(); int size = parents.size() - 1; for (int i = 0; i < size; i++) { Object[] where_vals = new Object[] { parents.get(i).getId(), Boolean.TRUE }; Long count = pages_pseudo_service.getRowCount(PAGES_PSEDO_WHERE, where_vals); if (count > 0) { //random optimization phrase String ROP = (String) pages_pseudo_service.getSinglePropertyU("text", PAGES_PSEDO_WHERE, where_vals, r.nextInt(count.intValue())); if (ROP != null && !ROP.equals("")) { title.append(ROP); title.append(" - "); rop = ROP; } tags.append(parents.get(i).getName()); tags.append(", "); } } size++; if (size > 0) { size--; Object[] where_vals = new Object[] { parents.get(size).getId(), Boolean.TRUE }; Long count = pages_pseudo_service.getRowCount(PAGES_PSEDO_WHERE, where_vals); if (count > 0) { //random optimization phrase String ROP = (String) pages_pseudo_service.getSinglePropertyU("text", PAGES_PSEDO_WHERE, where_vals, r.nextInt(count.intValue())); if (ROP != null && !ROP.equals("")) { title.append(ROP); name = ROP; } else if (rop != null) { name = rop; } else { name = parents.get(size).getName(); } tags.append(parents.get(size).getName()); } } p.setDescription(name.toString()); p.setTags(tags.toString()); p.setTitle(title.toString()); p.setOptimized(Boolean.TRUE); }
From source file:com.founder.fix.fixflow.service.impl.FlowCenterServiceImpl.java
public Map<String, Object> queryMyTaskNotEnd(Map<String, Object> filter) throws SQLException { Map<String, Object> result = new HashMap<String, Object>(); ProcessEngine engine = getProcessEngine(filter.get("userId")); String whereSql = " 1=1 "; String leftJoinStr = ""; QueryExpandTo queryExpandTo = new QueryExpandTo(); try {//from www . j a v a 2 s . c om TaskQuery tq = engine.getTaskService().createTaskQuery(); tq.taskAssignee(StringUtil.getString(filter.get("userId"))); tq.taskCandidateUser(StringUtil.getString(filter.get("userId"))); // tq.processDefinitionKey(StringUtil.getString(filter.get("pdkey"))); String descritpion = StringUtil.getString(filter.get("title")); if (StringUtil.isNotEmpty(descritpion)) tq.taskDescriptionLike(descritpion); String initor = StringUtil.getString(filter.get("initor")); if (StringUtil.isNotEmpty(initor)) tq.initiator(initor); //?? String initorName = StringUtil.getString(filter.get("initorName")); if (StringUtil.isNotEmpty(initorName)) { initorName = initorName.replace("'", ""); ProcessEngine processEngine = ProcessEngineManagement.getDefaultProcessEngine(); AllUserInfo userInfoConfig = processEngine.getProcessEngineConfiguration().getUserDefinition() .getUserInfoConfig(); leftJoinStr += " LEFT JOIN (" + userInfoConfig.getSqlText() + ") UT on UT." + userInfoConfig.getUserIdField() + " = P.INITIATOR "; whereSql += " and (UT." + userInfoConfig.getUserNameField() + " LIKE '%" + initorName + "%' or UT." + userInfoConfig.getUserIdField() + " = '" + initorName + "')"; } String bizKey = StringUtil.getString(filter.get("bizKey")); if (StringUtil.isNotEmpty(bizKey)) tq.businessKeyLike(bizKey); String processDefinitionName = StringUtil.getString(filter.get("processDefinitionName")); if (StringUtil.isNotEmpty(processDefinitionName)) tq.processDefinitionNameLike(processDefinitionName); Date dates = null; Date datee = null; String dss = StringUtil.getString(filter.get("arrivalTimeS")); String dse = StringUtil.getString(filter.get("arrivalTimeE")); if (StringUtil.isNotEmpty(dss)) { dates = DateUtil.stringToDate(dss, "yyyy-MM-dd"); } if (StringUtil.isNotEmpty(dse)) { String endTime = "235959999"; dse += endTime; datee = DateUtil.stringToDate(dse, "yyyy-MM-ddHHmmssSSS"); } if (dates != null) tq.taskCreatedAfter(datee); if (datee != null) tq.taskCreatedBefore(dates); String pageI = StringUtil.getString(filter.get("pageIndex")); String rowI = StringUtil.getString(filter.get("pageSize")); int pageIndex = 1; int rowNum = 15; if (StringUtil.isNotEmpty(pageI)) { pageIndex = Integer.valueOf(pageI); } if (StringUtil.isNotEmpty(rowI)) { rowNum = Integer.valueOf(rowI); } if (filter.get("ended") == null) tq.taskNotEnd(); if (StringUtil.isNotEmpty(StringUtil.getString(filter.get("agentUserId")))) { tq.isAgent(true); if (filter.get("agentType").equals("1")) { tq.taskAssignee(StringUtil.getString(filter.get("userId"))); tq.taskCandidateUser(StringUtil.getString(filter.get("userId"))); tq.agentId(StringUtil.getString(filter.get("agentUserId"))); } else { tq.taskAssignee(StringUtil.getString(filter.get("agentUserId"))); tq.taskCandidateUser(StringUtil.getString(filter.get("agentUserId"))); tq.agentId(StringUtil.getString(filter.get("userId"))); } } else { tq.taskAssignee(StringUtil.getString(filter.get("userId"))); tq.taskCandidateUser(StringUtil.getString(filter.get("userId"))); } if (StringUtil.isNotEmpty(leftJoinStr)) { queryExpandTo.setLeftJoinSql(leftJoinStr); } queryExpandTo.setWhereSql(whereSql); tq.queryExpandTo(queryExpandTo); List<TaskInstance> lts = tq.orderByTaskCreateTime().desc().listPagination(pageIndex, rowNum); Long count = tq.count(); List<Map<String, Object>> instanceMaps = new ArrayList<Map<String, Object>>(); Pagination page = new Pagination(pageIndex, rowNum); page.setTotal(count.intValue()); IdentityService identsvz = engine.getIdentityService(); for (TaskInstance tmp : lts) { Map<String, Object> instances = tmp.getPersistentState(); // String path = StringUtil.getString(filter.get("path")); // path = path+"/icon/"; // File newFile = new File(path); // FileUtil.makeParent(new File(path+"ss.ss")); // // String[] icons = newFile.list(); String userId = StringUtil.getString(instances.get("PI_START_AUTHOR")); // for(String tmp2:icons){ // if(tmp2.startsWith(userId)){ // instances.put("icon", "icon/"+tmp2); // } // } // instances.put("icon", "icon/"+userId+"_small.png"); if (StringUtil.isNotEmpty(userId)) { UserTo user = identsvz.getUserTo(userId); if (user != null) { instances.put("userName", user.getUserName()); } else { instances.put("userName", userId + "()"); } } else { instances.put("userName", "(??)"); } instanceMaps.add(instances); } result.put("dataList", instanceMaps); result.put("pageInfo", page); result.put("agentUsers", getAgentUsers(engine, StringUtil.getString(filter.get("userId")))); result.put("agentToUsers", getAgentToUsers(engine, StringUtil.getString(filter.get("userId")))); } finally { closeProcessEngine(); } return result; }
From source file:kr.co.exsoft.external.controller.ExternalPublicController.java
/** * <pre>//www .j a v a 2s . c o m * 1. :[1000] * 2. : ? * </pre> * @Method Name : interfaceFiledownloadHandler * @param paraMap * @param response * @return ResponseEntity<byte[]> */ @SuppressWarnings({ "unchecked", "rawtypes" }) @RequestMapping(value = "/interfaceFiledownload", method = RequestMethod.POST, produces = "applicaion/json; charset=utf8") @ResponseBody public ResponseEntity<byte[]> interfaceFiledownloadHandler(@RequestParam HashMap<String, Object> paraMap, HttpServletRequest request, HttpServletResponse response) { interfacelogger.info("==================== interfaceFiledownloadHandler ====================="); String errorMsg = ""; HttpHeaders headers = new HttpHeaders(); File toServeUp = null; InputStream inputStream = null; Map<String, Object> list = new HashMap<String, Object>(); String downFile = ""; InputStreamResource inputStreamResource = null; try { SessionVO sessionVO = externalService.interfaceSessionVO(request, paraMap.get("authId").toString()); list = externalService.interfaceTypePage(paraMap, null, sessionVO); toServeUp = (File) list.get("file"); downFile = list.get("downFile").toString(); inputStream = new FileInputStream(toServeUp); inputStreamResource = new InputStreamResource(inputStream); Long fileSize = toServeUp.length(); headers.setContentLength(fileSize.intValue()); response.setContentType("application/octer-stream;charset=utf-8"); response.setCharacterEncoding("utf-8"); //? ? response.setHeader("filename", java.net.URLEncoder.encode(downFile, "UTF-8")); } catch (BizException e) { response.setHeader("errorMsg", e.getMessage()); interfacelogger.debug(StringUtil.getHashMap(paraMap)); interfacelogger.debug(StringUtil.getErrorTrace(e)); } catch (FileNotFoundException e) { errorMsg = "Not Found DownLoadFile"; response.setHeader("errorMsg", errorMsg); interfacelogger.debug(StringUtil.getHashMap(paraMap)); interfacelogger.debug(StringUtil.getErrorTrace(e)); } catch (UnsupportedEncodingException e) { errorMsg = "Can't Not Encoding FileName"; response.setHeader("errorMsg", errorMsg); interfacelogger.debug(StringUtil.getHashMap(paraMap)); interfacelogger.debug(StringUtil.getErrorTrace(e)); } catch (Exception e) { errorMsg = "Not Connected FileServer"; response.setHeader("errorMsg", errorMsg); interfacelogger.debug(StringUtil.getHashMap(paraMap)); interfacelogger.debug(StringUtil.getErrorTrace(e)); } return new ResponseEntity(inputStreamResource, headers, HttpStatus.OK); }
From source file:com.redhat.rhn.domain.server.test.ServerFactoryTest.java
public void testAddRemove() throws Exception { //Test adding/removing server from group ServerGroupTestUtils.createManaged(user); Server testServer = createTestServer(user); Org org = user.getOrg();// w w w . j a va 2 s. co m ManagedServerGroup group = org.getManagedServerGroups().iterator().next(); assertNotNull(group); ServerGroupFactory.save(group); Long membersBefore = group.getCurrentMembers(); ServerFactory.addServerToGroup(testServer, group); //HibernateFactory.getSession().refresh(group); Long membersAfter = group.getCurrentMembers(); assertTrue(membersBefore.intValue() < membersAfter.intValue()); ServerFactory.removeServerFromGroup(testServer.getId(), group.getId()); group = (ManagedServerGroup) reload(group); Long membersFinally = group.getCurrentMembers(); assertEquals(membersBefore, membersFinally); }
From source file:kr.co.exsoft.external.controller.ExternalPublicController.java
@SuppressWarnings({ "unchecked", "rawtypes" }) @RequestMapping(value = "/restful.postwithfiledown", method = RequestMethod.POST, produces = "applicaion/json; charset=utf8") @ResponseBody//w w w. j a v a 2s. c o m //@PathVariable String fileID public ResponseEntity<byte[]> downloadFile(HttpServletRequest request, HttpServletResponse response) { String errorMsg = ""; //??? ?? PageId String pageId = request.getParameter("pageId"); PageDao pageDao = sqlSession.getMapper(PageDao.class); PageVO ret = new PageVO(); HashMap<String, Object> param = new HashMap<String, Object>(); param.put("page_id", pageId); ret = pageDao.pageDetailInfo(param); HttpHeaders headers = new HttpHeaders(); File toServeUp = null; InputStream inputStream = null; // EXREP ? . :: eXrep C/S Client ?. EXrepClient eXrepClient = new EXrepClient(); // ?? String downPath = ConfigData.getString("FILE_DOWN_PATH") + UUID.randomUUID().toString() + "/"; String downFile = ret.getPage_name();//"word.docx"; String savePath = downPath + downFile; try { UtilFileApp.createDir(downPath); } catch (SecurityException | IOException e2) { // TODO Auto-generated catch block e2.printStackTrace(); errorMsg = "Can't Not Create Directory"; response.setHeader("errorMsg", errorMsg); } try { // 5. eXrep C/S ?. eXrepClient.connect(); if (eXrepClient.getFile(ret.getVolume_id(), ret.getContent_path(), savePath)) { toServeUp = new File(savePath); System.out.println("FILE DOWN LOAD COMPLITE"); } // 6. eXrep C/S Client Close eXrepClient.disconnect(); } catch (ExrepClientException e1) { // TODO Auto-generated catch block e1.printStackTrace(); errorMsg = "Not Connected FileServer"; response.setHeader("errorMsg", errorMsg); } try { inputStream = new FileInputStream(toServeUp); } catch (FileNotFoundException e) { e.printStackTrace(); errorMsg = "Not Found DownLoadFile"; response.setHeader("errorMsg", errorMsg); } InputStreamResource inputStreamResource = new InputStreamResource(inputStream); Long fileSize = toServeUp.length(); headers.setContentLength(fileSize.intValue()); response.setContentType("application/octer-stream;charset=utf-8"); response.setCharacterEncoding("utf-8"); try { //? ? response.setHeader("filename", java.net.URLEncoder.encode(downFile, "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); errorMsg = "Can't Not Encoding File"; response.setHeader("errorMsg", errorMsg); } return new ResponseEntity(inputStreamResource, headers, HttpStatus.OK); }
From source file:org.openregistry.core.service.DefaultPersonServiceIntegrationTests.java
/** * Tests for Delete SorRole//from w w w. j a v a 2s . c o m */ @Test @Rollback public void testDeleteSorRoleNoMistake() throws ReconciliationException, SorPersonAlreadyExistsException { final ReconciliationCriteria criteria1 = constructReconciliationCriteria(RUDYARD, KIPLING, null, EMAIL_ADDRESS, PHONE_NUMBER, new Date(0), "FOO", null); final ServiceExecutionResult<Person> serviceExecutionResult1 = this.personService.addPerson(criteria1); final SorPerson sorPerson1 = this.personService .findByPersonIdAndSorIdentifier(serviceExecutionResult1.getTargetObject().getId(), "FOO"); assertEquals(1, countRowsInTable("prc_persons")); assertEquals(1, countRowsInTable("prc_names")); assertEquals(1, countRowsInTable("prs_sor_persons")); assertEquals(1, countRowsInTable("prs_names")); final SorRole role = sorPerson1.createRole(this.referenceRepository.getTypeById(new Long(6))); role.setSorId("1"); role.setSystemOfRecord(this.referenceRepository.findSystemOfRecord("test")); role.setPercentage(50); role.setStart(new Date()); role.setPersonStatus(this.referenceRepository.getTypeById(1L)); role.setSponsorId(1L); role.setSponsorType(this.referenceRepository.getTypeById(1L)); role.setOrganizationalUnit(this.referenceRepository.getOrganizationalUnitById(new Long(1))); role.setTitle("Application Developer"); sorPerson1.addRole(role); final ServiceExecutionResult<SorRole> ser = this.personService.validateAndSaveRoleForSorPerson(sorPerson1, role); entityManager.flush(); assertEquals(1, countRowsInTable("prs_role_records")); assertEquals(1, countRowsInTable("prc_role_records")); final boolean deleted = personService.deleteSystemOfRecordRole(sorPerson1, ser.getTargetObject(), false, Type.TerminationTypes.FIRED.name()); assertTrue("Delete SorRole failed", deleted); entityManager.flush(); assertEquals(0, countRowsInTable("prs_role_records")); assertEquals(1, countRowsInTable("prc_role_records")); final Long termination = this.simpleJdbcTemplate.queryForObject( "select termination_t from prc_role_records where person_id = ?", Long.class, serviceExecutionResult1.getTargetObject().getId()); assertEquals(4, termination.intValue()); }
From source file:com.seajas.search.profiler.task.FeedInjectionTask.java
/** * {@inheritDoc}/*from ww w . j av a 2 s . c o m*/ */ @Override public void inject(final String triggerName, final Long intervalTotal, final InjectionJobInterrupted interrupted) { Date currentTime = new Date(); List<Feed> enabledFeeds = getInjectableFeeds(triggerName, intervalTotal, currentTime); // Only log when we're not doing distributed injection - so to not get this every second if (logger.isInfoEnabled() && intervalTotal == null) logger.info("Performing feed injection under trigger '" + triggerName + "' (" + enabledFeeds.size() + " feed" + (enabledFeeds.size() != 1 ? "s" : "") + ")"); // We report on the number of feeds first, and then move on to potentially canceling the operation if (Boolean.getBoolean("profiler.indexing.disabled")) { if (logger.isInfoEnabled()) logger.info( "Indexing has been explicitly disabled using 'profiler.indexing.disabled=true'. Skipping injection."); return; } for (Feed feed : enabledFeeds) { if (interrupted.isInterrupted()) { logger.warn("This job was interrupted - not continuing with feed injection"); break; } // Mark this feed's injection date (ahead of the actual injection - but then this is not such a critical matter) profilerService.updateFeedLastInjected(feed.getId(), currentTime); // Determine whether this feed falls within the anonymization run from / until range if (feed.getFeedAnonymization() != null) { Date currentDate = Calendar.getInstance().getTime(), runFrom = feed.getFeedAnonymization().getRunFrom(), runUntil = feed.getFeedAnonymization().getRunUntil(); if ((runFrom != null && currentDate.before(runFrom)) || (runUntil != null && currentDate.after(runUntil))) { logger.info("The feed with name '" + feed.getName() + "' falls outside of its anonymization run from/until date - skipping"); continue; } } // Create a map out of the feed result parameters Map<String, String> resultParameters = new HashMap<String, String>(); if (feed.getFeedResultParameters() != null && feed.getFeedResultParameters().size() > 0) for (FeedResultParameter feedResultParameter : feed.getFeedResultParameters()) { if (resultParameters.containsKey(feedResultParameter.getFieldName())) logger.warn("The result map already contains a parameter named '" + feedResultParameter.getFieldName() + "' - it will be overwritten"); resultParameters.put(feedResultParameter.getFieldName(), feedResultParameter.getFieldValue()); } // Now inject each feed URL for (FeedUrl feedUrl : feed.getFeedUrls()) { if (interrupted.isInterrupted()) { logger.warn("This job was interrupted - not continuing with feed injection"); break; } try { Long feedDelay = 0L, resultDelay = 0L; // Determine the feed-URL specific anonymization settings if (feed.getFeedAnonymization() != null) { // Determine the feed delay feedDelay = feed.getFeedAnonymization() != null && feed.getFeedAnonymization().getFeedDelay() != null ? feed.getFeedAnonymization().getFeedDelay() : 0L; if (feed.getFeedAnonymization().getIsFeedDelayRandomized()) feedDelay = (long) randomGenerator .nextInt(feedDelay.intValue() - RANDOM_RANGE_MINIMUM + 1) + RANDOM_RANGE_MINIMUM; // Don't randomize the result delay here, but instead do this on the contender-side resultDelay = feed.getFeedAnonymization() != null && feed.getFeedAnonymization().getFeedElementDelay() != null ? feed.getFeedAnonymization().getFeedElementDelay() : 0L; } // Perform the optional authentication step String authenticatedUrl = feedUrl.getUrl(); Map<String, String> authenticatedResultParameters = resultParameters; if (feed.getFeedConnection() != null) { if (feed.getFeedConnection().getAuthenticationStrategy() != null) { AuthenticationResult authenticationResult = profilerService.applyAuthenticationStrategy( feed.getFeedConnection().getAuthenticationStrategy(), authenticatedUrl, authenticatedResultParameters); authenticatedUrl = authenticationResult.getUrl(); authenticatedResultParameters = authenticationResult.getResultParameters(); } } URI uri = new URI(authenticatedUrl); String hostname = StringUtils.hasText(uri.getHost()) ? uri.getHost().replace("www.", "") : "localhost"; logger.info("Injecting feed with name '" + feed.getName() + "' and URI '" + uri + "' into bridge layer"); // Determine which of the result parameters to turn into headers Map<String, String> resultHeaders = null; if (StringUtils.hasText(resultMappingParameter) && StringUtils.hasText(resultMappingHeader)) { if (!authenticatedResultParameters.containsKey(resultMappingParameter)) { if (logger.isDebugEnabled()) logger.debug("Result mapping was requested, but result mapping parameter '" + resultMappingParameter + "' is not present in the result parameter map - not adding header '" + resultMappingHeader + "'"); } else { resultHeaders = new HashMap<String, String>(); resultHeaders.put(resultMappingHeader, authenticatedResultParameters.get(resultMappingParameter)); } } // Inject it into the queue com.seajas.search.bridge.jms.model.Feed resultFeed = new com.seajas.search.bridge.jms.model.Feed(); resultFeed.setUri(uri); resultFeed.setId(feed.getId()); resultFeed.setName(feed.getName()); resultFeed.setHostname(hostname); resultFeed.setCollection(feed.getCollection()); resultFeed.setFeedEncodingOverride(feed.getFeedEncodingOverride()); resultFeed.setResultEncodingOverride(feed.getResultEncodingOverride()); resultFeed.setLanguageOverride(feed.getLanguage()); resultFeed.setSummaryBased(feed.getIsSummaryBased()); resultFeed.setDelay(feedDelay); resultFeed.setElementDelay(resultDelay); resultFeed.setElementDelayRandomized(feed.getFeedAnonymization() != null && Boolean.TRUE.equals(feed.getFeedAnonymization().getIsFeedElementDelayRandomized())); resultFeed.setUserAgent(determineUserAgent(feed)); resultFeed.setUserAgentsOverride(feed.getFeedAnonymization() != null ? feed.getFeedAnonymization().getPreferredUserAgents() : null); resultFeed.setUserAgentsOverrideRandomized(feed.getFeedAnonymization() != null && Boolean.TRUE .equals(feed.getFeedAnonymization().getIsPreferredUserAgentsRandomized())); resultFeed.setResultParameters(authenticatedResultParameters); resultFeed.setRetrievalRequestHeaders(resultHeaders); injectionService.inject(resultFeed, GroupIdDecorator.decorate(hostname), feedDelay); } catch (URISyntaxException e) { logger.error("The given " + (feed.getFeedConnection() != null && feed.getFeedConnection().getAuthenticationStrategy() != null ? "(unauthenticated) " : "") + "feed URI '" + feedUrl.getUrl() + "' is not valid"); } } } if (logger.isTraceEnabled()) logger.trace("Finished feed injection for trigger '" + triggerName + "'"); }
From source file:com.abiquo.server.core.cloud.VirtualDatacenterDAO.java
public DefaultEntityCurrentUsed getCurrentResourcesAllocated(final int virtualDatacenterId) { Object[] vmResources = (Object[]) getSession().createSQLQuery(SUM_VM_RESOURCES) .setParameter("virtualDatacenterId", virtualDatacenterId).uniqueResult(); Long cpu = vmResources[0] == null ? 0 : ((BigDecimal) vmResources[0]).longValue(); Long ram = vmResources[1] == null ? 0 : ((BigDecimal) vmResources[1]).longValue(); Long hd = vmResources[2] == null ? 0 : ((BigDecimal) vmResources[2]).longValue(); BigDecimal extraHd = (BigDecimal) getSession().createSQLQuery(SUM_EXTRA_HD_RESOURCES) .setParameter("virtualDatacenterId", virtualDatacenterId).uniqueResult(); Long hdTot = extraHd == null ? hd : hd + extraHd.longValue() * 1024 * 1024; BigDecimal storage = (BigDecimal) getSession().createSQLQuery(SUM_VOLUMES_RESOURCES) .setParameter("virtualDatacenterId", virtualDatacenterId).uniqueResult(); BigInteger publicIps = (BigInteger) getSession().createSQLQuery(COUNT_PUBLIC_IP_RESOURCES) .setParameter("virtualDatacenterId", virtualDatacenterId).uniqueResult(); DefaultEntityCurrentUsed used = new DefaultEntityCurrentUsed(cpu.intValue(), ram, hdTot); // Storage usage is stored in MB used.setStorage(storage == null ? 0 : storage.longValue() * 1024 * 1024); used.setPublicIp(publicIps == null ? 0 : publicIps.longValue()); used.setVlanCount(getVLANUsage(virtualDatacenterId).size()); return used;/*from w w w .j a v a 2s. c om*/ }