Unnamed: 0
int64
0
9.45k
cwe_id
stringclasses
1 value
source
stringlengths
37
2.53k
target
stringlengths
19
2.4k
400
private synchronized void loadQueue(){ if (!isQueueLoaderActive()) { queueFuture = schedExecutor.submit(new Callable<List<FeedItem>>() { @Override public List<FeedItem> call() throws Exception { return DBReader.getQueue(); } }); } }
private synchronized void loadQueue(){ if (!isQueueLoaderActive()) { queueFuture = schedExecutor.submit(DBReader::getQueue); } }
401
public void editInformation(){ String newName = txtFullName.getText(); String newPassword = txtPassword.getText(); String newEmail = txtEmail.getText(); String newBirthDate = txtDOB.getText(); if (!RegController.validFullNamePattern(txtFullName.getText())) { updateStatus.setText("Invalid name input!"); updateStatus.setTextFill(Paint.valueOf("red")); } else if (!RegController.validPSWDPattern(txtPassword.getText())) { updateStatus.setText("Password must not contain special characters!"); updateStatus.setTextFill(Paint.valueOf("red")); } else if (!RegController.validEmailPattern(txtEmail.getText())) { updateStatus.setText("Must be a valid email address!"); updateStatus.setTextFill(Paint.valueOf("red")); } else if (!RegController.validDOBPattern(txtDOB.getText())) { updateStatus.setText("DOB Pattern: MM/DD/YYYY"); updateStatus.setTextFill(Paint.valueOf("red")); } else { try { Class.forName(LogInController.driver); Connection loginConnection = DriverManager.getConnection(LogInController.url); PreparedStatement update = loginConnection.prepareStatement(updateSQL); update.setString(1, newName); update.setString(2, newPassword); update.setString(3, newEmail); update.setString(4, newBirthDate); update.setString(5, txtUserName.getText()); update.executeUpdate(); updateStatus.setTextFill(Paint.valueOf("green")); update.close(); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } }
public void editInformation(){ String newName = txtFullName.getText(); String newPassword = txtPassword.getText(); String newEmail = txtEmail.getText(); String newBirthDate = txtDOB.getText(); if (validFullNamePattern(txtFullName.getText())) { updateStatus.setText("Invalid name input!"); updateStatus.setTextFill(Paint.valueOf("red")); } else if (validPSWDPattern(txtPassword.getText())) { updateStatus.setText("Password must not contain special characters!"); updateStatus.setTextFill(Paint.valueOf("red")); } else if (validEmailPattern(txtEmail.getText())) { updateStatus.setText("Must be a valid email address!"); updateStatus.setTextFill(Paint.valueOf("red")); } else if (validDOBPattern(txtDOB.getText())) { updateStatus.setText("DOB Pattern: MM/DD/YYYY"); updateStatus.setTextFill(Paint.valueOf("red")); } else { try { String username = txtUserName.getText(); update(newName, newPassword, newEmail, newBirthDate, username, updateSQL, updateStatus); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } }
402
public void onTimer(String timerId, BoundedWindow window, Instant timestamp, TimeDomain timeDomain){ Preconditions.checkNotNull(currentTimerKey, "Key for timer needs to be set before calling onTimer"); Preconditions.checkNotNull(remoteBundle, "Call to onTimer outside of a bundle"); LOG.debug("timer callback: {} {} {} {}", timerId, window, timestamp, timeDomain); FnDataReceiver<WindowedValue<?>> timerReceiver = Preconditions.checkNotNull(remoteBundle.getInputReceivers().get(timerId), "No receiver found for timer %s", timerId); WindowedValue<KV<Object, Timer>> timerValue = WindowedValue.of(KV.of(currentTimerKey, Timer.of(timestamp, new byte[0])), timestamp, Collections.singleton(window), PaneInfo.NO_FIRING); try { timerReceiver.accept(timerValue); } catch (Exception e) { throw new RuntimeException(String.format(Locale.ENGLISH, "Failed to process timer %s", timerReceiver), e); } finally { currentTimerKey = null; } }
public void onTimer(String timerId, BoundedWindow window, Instant timestamp, TimeDomain timeDomain){ Object timerKey = keyForTimer.get(); Preconditions.checkNotNull(timerKey, "Key for timer needs to be set before calling onTimer"); Preconditions.checkNotNull(remoteBundle, "Call to onTimer outside of a bundle"); LOG.debug("timer callback: {} {} {} {}", timerId, window, timestamp, timeDomain); FnDataReceiver<WindowedValue<?>> timerReceiver = Preconditions.checkNotNull(remoteBundle.getInputReceivers().get(timerId), "No receiver found for timer %s", timerId); WindowedValue<KV<Object, Timer>> timerValue = WindowedValue.of(KV.of(timerKey, Timer.of(timestamp, new byte[0])), timestamp, Collections.singleton(window), PaneInfo.NO_FIRING); try { timerReceiver.accept(timerValue); } catch (Exception e) { throw new RuntimeException(String.format(Locale.ENGLISH, "Failed to process timer %s", timerReceiver), e); } }
403
public void getDefinitions_CachedNotCachedWordsGiven_OriginalCall() throws Exception{ String words = "home,car"; Set<String> validWords = new HashSet<>(); validWords.add("home"); validWords.add("car"); Set<String> cachedWord = new HashSet<>(); cachedWord.add("home"); String word = "car"; Set<String> notCached = new HashSet<>(); notCached.add(word); List<OriginalCall> cachedWords = buildOriginalCalls(cachedWord); List<OriginalCall> notCachedOriginalCall = buildOriginalCalls(notCached); List<DefinitionsResource> definitionsResources = buildDefinitionsResource(cachedWords, notCachedOriginalCall); when(mockProcessWordsService.splitWords(words)).thenReturn(validWords); when(mockProcessWordsService.getValidWords(validWords)).thenReturn(validWords); when(mockProcessWordsService.getCachedWords(validWords)).thenReturn(cachedWords); when(mockProcessWordsService.getNotCachedWords(cachedWords, validWords)).thenReturn(notCached); when(mockManageWordService.createOriginalCall(word)).thenReturn(notCachedOriginalCall.iterator().next()); when(mockBuildDefinitionsResourceService.loadResource(cachedWords)).thenReturn(definitionsResources); List<DefinitionsResource> result = controller.getDefinitions(words); verify(mockProcessWordsService).splitWords(words); verify(mockProcessWordsService).getValidWords(validWords); verify(mockProcessWordsService).getCachedWords(validWords); verify(mockProcessWordsService).getNotCachedWords(cachedWords, validWords); Assert.assertNotNull(result); Assert.assertEquals(2, result.size()); assertThat(result, is(definitionsResources)); }
public void getDefinitions_CachedNotCachedWordsGiven_OriginalCall() throws Exception{ Set<String> validWords = new HashSet<>(); validWords.add("home"); validWords.add("car"); validWords.add("drive"); DefinitionsResource resource = new DefinitionResourceBuilder().words(validWords).build(); Set<String> cachedWord = new HashSet<>(); cachedWord.add("home"); String word = "car"; Set<String> notCached = new HashSet<>(); notCached.add(word); List<OriginalCall> cachedWords = buildOriginalCalls(cachedWord); List<OriginalCall> notCachedOriginalCall = buildOriginalCalls(notCached); List<DefinitionsResource> definitionsResources = buildDefinitionsResource(cachedWords, notCachedOriginalCall); when(mockProcessWordsService.getValidWords(validWords)).thenReturn(validWords); when(mockProcessWordsService.getCachedWords(validWords)).thenReturn(cachedWords); when(mockProcessWordsService.getNotCachedWords(cachedWords, validWords)).thenReturn(notCached); when(mockManageWordService.createOriginalCall(word)).thenReturn(notCachedOriginalCall.iterator().next()); when(mockBuildDefinitionsResourceService.loadResource(cachedWords)).thenReturn(definitionsResources); List<DefinitionsResource> result = controller.getDefinitions(resource); verify(mockProcessWordsService).getValidWords(validWords); verify(mockProcessWordsService).getCachedWords(validWords); verify(mockProcessWordsService).getNotCachedWords(cachedWords, validWords); Assert.assertNotNull(result); Assert.assertEquals(2, result.size()); assertThat(result, is(definitionsResources)); }
404
public static void storeUserCookie(HttpServletResponse response, UserAccount user){ System.out.println("Store user cookie"); Cookie cookieUserName = new Cookie(ATT_NAME_USER_NAME, user.getNickName()); cookieUserName.setMaxAge(24 * 60 * 60); response.addCookie(cookieUserName); }
public static void storeUserCookie(HttpServletResponse response, UserAccount user){ Cookie cookieUserName = new Cookie(ATT_NAME_USER_NAME, user.getNickName()); cookieUserName.setMaxAge(24 * 60 * 60); response.addCookie(cookieUserName); }
405
public void runBreadthFirstSearch(int startingIndex){ MyQueue paths = new MyQueue(); int[] initialPath = { startingIndex }; paths.enqueue(initialPath); int[] nextPath; while (!paths.empty()) { nextPath = paths.dequeue(); if (nextPath.length == vertices.length) { System.out.println("HERE ARE THE PATHS: \n" + MyArrays.toString(nextPath)); while (!paths.empty()) { int[] currentCompletePath = paths.dequeue(); double currentCompletePathDistance = calculatePathDistance(currentCompletePath); if (currentCompletePathDistance < minimumDistance && finishedSearching(currentCompletePath)) { minimumDistance = currentCompletePathDistance; minimumPath = currentCompletePath; System.out.println("NEW MIN: " + minimumDistance); } } break; } addPathsFromPoint(paths, nextPath); } }
public void runBreadthFirstSearch(int startingIndex){ MyQueue paths = new MyQueue(); int[] initialPath = { startingIndex }; paths.enqueue(initialPath); int[] nextPath; while (!paths.empty()) { nextPath = paths.dequeue(); if (nextPath.length == vertices.length) { while (!paths.empty()) { int[] currentCompletePath = paths.dequeue(); double currentCompletePathDistance = calculatePathDistance(currentCompletePath); if (currentCompletePathDistance < minimumDistance && finishedSearching(currentCompletePath)) { minimumDistance = currentCompletePathDistance; minimumPath = currentCompletePath; } } break; } addPathsFromPoint(paths, nextPath); } }
406
public Result authedDatasource(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam("userId") Integer userId){ logger.info("authorized data source, login user:{}, authorized useId:{}", loginUser.getUserName(), userId); Map<String, Object> result = dataSourceService.authedDatasource(loginUser, userId); return returnDataList(result); }
public Result<List<DataSource>> authedDatasource(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam("userId") Integer userId){ logger.info("authorized data source, login user:{}, authorized useId:{}", loginUser.getUserName(), userId); return dataSourceService.authedDatasource(loginUser, userId); }
407
public void testInsert(){ GeneratedAlwaysRecord record = new GeneratedAlwaysRecord(); record.setId(100); record.setFirstName("Bob"); record.setLastName("Jones"); InsertStatementProvider<GeneratedAlwaysRecord> insertStatement = insert(record).into(generatedAlways).map(id).toProperty("id").map(firstName).toProperty("firstName").map(lastName).toProperty("lastName").build().render(RenderingStrategy.SPRING_NAMED_PARAMETER); SqlParameterSource parameterSource = new BeanPropertySqlParameterSource(insertStatement.getRecord()); KeyHolder keyHolder = new GeneratedKeyHolder(); int rows = template.update(insertStatement.getInsertStatement(), parameterSource, keyHolder); String generatedKey = (String) keyHolder.getKeys().get("FULL_NAME"); assertThat(rows).isEqualTo(1); assertThat(generatedKey).isEqualTo("Bob Jones"); }
public void testInsert(){ GeneratedAlwaysRecord record = new GeneratedAlwaysRecord(); record.setId(100); record.setFirstName("Bob"); record.setLastName("Jones"); InsertStatementProvider<GeneratedAlwaysRecord> insertStatement = insert(record).into(generatedAlways).map(id).toProperty("id").map(firstName).toProperty("firstName").map(lastName).toProperty("lastName").build().render(RenderingStrategy.SPRING_NAMED_PARAMETER); SqlParameterSource parameterSource = new BeanPropertySqlParameterSource(insertStatement.getRecord()); KeyHolder keyHolder = new GeneratedKeyHolder(); }
408
public void testFindLatestDumpFileException() throws FileNotFoundException{ File dumpFolder = Mockito.mock(File.class); File[] files = new File[0]; Mockito.when(dumpFolder.listFiles(Mockito.any(FilenameFilter.class))).thenReturn(files); DumpFinder dumpFinder = new DumpFinder(); dumpFinder.setDumpFolder(dumpFolder); dumpFinder.findLatestDumpFile(); }
public void testFindLatestDumpFileException() throws FileNotFoundException{ File dumpFolder = Mockito.mock(File.class); File[] files = new File[0]; Mockito.when(dumpFolder.listFiles(Mockito.any(FilenameFilter.class))).thenReturn(files); DumpFinder dumpFinder = new DumpFinder(); dumpFinder.findLatestDumpFile(dumpFolder); }
409
public String deleteCaseTask(InforContext context, String caseTaskID) throws InforException{ MP3657_DeleteCaseManagementTask_001 deleteCaseTask = new MP3657_DeleteCaseManagementTask_001(); CASEMANAGEMENTTASKID_Type caseManagementTaskIdType = new CASEMANAGEMENTTASKID_Type(); caseManagementTaskIdType.setCASEMANAGEMENTTASKCODE(caseTaskID); deleteCaseTask.setCASEMANAGEMENTTASKID(caseManagementTaskIdType); if (context.getCredentials() != null) { inforws.deleteCaseManagementTaskOp(deleteCaseTask, tools.getOrganizationCode(context), tools.createSecurityHeader(context), "TERMINATE", null, tools.createMessageConfig(), tools.getTenant(context)); } else { inforws.deleteCaseManagementTaskOp(deleteCaseTask, tools.getOrganizationCode(context), null, "", new Holder<SessionType>(tools.createInforSession(context)), tools.createMessageConfig(), tools.getTenant(context)); } return deleteCaseTask.getCASEMANAGEMENTTASKID().getCASEMANAGEMENTTASKCODE(); }
public String deleteCaseTask(InforContext context, String caseTaskID) throws InforException{ MP3657_DeleteCaseManagementTask_001 deleteCaseTask = new MP3657_DeleteCaseManagementTask_001(); CASEMANAGEMENTTASKID_Type caseManagementTaskIdType = new CASEMANAGEMENTTASKID_Type(); caseManagementTaskIdType.setCASEMANAGEMENTTASKCODE(caseTaskID); deleteCaseTask.setCASEMANAGEMENTTASKID(caseManagementTaskIdType); tools.performInforOperation(context, inforws::deleteCaseManagementTaskOp, deleteCaseTask); return deleteCaseTask.getCASEMANAGEMENTTASKID().getCASEMANAGEMENTTASKCODE(); }
410
protected static Material getFirstMaterialItemWillTouchOnUse(Entity user, World world, Set<Material> materials, double itemReach, @Nullable EnumFacing facing, @Nullable BlockPos targetPos){ final Vec3d posVec = user.getPositionEyes(1.0F); final Vec3d lookVec = user.getLook(1.0F); final byte scanSensitivity = 5; final Vec3d destinationVec = posVec.addVector(lookVec.xCoord * itemReach, lookVec.yCoord * itemReach, lookVec.zCoord * itemReach); final Vec3d distanceVec = destinationVec.subtract(posVec); final int incrementRounds = (int) Math.round((double) itemReach * (double) scanSensitivity); final Vec3d factorVec = new Vec3d(distanceVec.xCoord / incrementRounds, distanceVec.yCoord / incrementRounds, distanceVec.zCoord / incrementRounds); Material targetBlockMaterial = targetPos != null && facing != null ? world.getBlockState(targetPos.offset(facing)).getMaterial() : null; for (int i = 0; i <= incrementRounds; i++) { Vec3d vec32 = posVec.addVector(factorVec.xCoord * i, factorVec.yCoord * i, factorVec.zCoord * i); BlockPos blockpos = new BlockPos(vec32.xCoord, vec32.yCoord, vec32.zCoord); Block thisBlock = world.getBlockState(blockpos).getBlock(); Material blockMaterial = world.getBlockState(blockpos).getMaterial(); if (materials.contains(blockMaterial)) return blockMaterial; else if (blockMaterial.blocksMovement()) { if (targetBlockMaterial != null && materials.contains(targetBlockMaterial)) return targetBlockMaterial; else return null; } } return null; }
protected static Material getFirstMaterialItemWillTouchOnUse(Entity user, World world, Set<Material> materials, double itemReach, @Nullable EnumFacing facing, @Nullable BlockPos targetPos){ final Vec3d posVec = user.getPositionEyes(1.0F); final Vec3d lookVec = user.getLook(1.0F); final byte scanSensitivity = 5; final Vec3d destinationVec = posVec.addVector(lookVec.xCoord * itemReach, lookVec.yCoord * itemReach, lookVec.zCoord * itemReach); final Vec3d distanceVec = destinationVec.subtract(posVec); final int incrementRounds = (int) Math.round((double) itemReach * (double) scanSensitivity); final Vec3d factorVec = new Vec3d(distanceVec.xCoord / incrementRounds, distanceVec.yCoord / incrementRounds, distanceVec.zCoord / incrementRounds); Material targetBlockMaterial = targetPos != null && facing != null ? world.getBlockState(targetPos.offset(facing)).getMaterial() : null; for (int i = 0; i <= incrementRounds; i++) { Vec3d vec32 = posVec.addVector(factorVec.xCoord * i, factorVec.yCoord * i, factorVec.zCoord * i); BlockPos blockpos = new BlockPos(vec32.xCoord, vec32.yCoord, vec32.zCoord); Material blockMaterial = world.getBlockState(blockpos).getMaterial(); if (materials.contains(blockMaterial)) return blockMaterial; else if (blockMaterial.blocksMovement()) { if (targetBlockMaterial != null && materials.contains(targetBlockMaterial)) return targetBlockMaterial; else return null; } } return null; }
411
void initializeInstantiationMetric(final boolean instantiated){ helixClusterManagerInstantiationFailed = new Gauge<Long>() { @Override public Long getValue() { return instantiated ? 0L : 1L; } }; registry.register(MetricRegistry.name(HelixClusterManager.class, "instantiationFailed"), helixClusterManagerInstantiationFailed); }
void initializeInstantiationMetric(final boolean instantiated){ helixClusterManagerInstantiationFailed = () -> instantiated ? 0L : 1L; registry.register(MetricRegistry.name(HelixClusterManager.class, "instantiationFailed"), helixClusterManagerInstantiationFailed); }
412
void should_return_P2_car_when_parking_boy_fetch_car_given_parking_boy_P2_ticket_parking_lot(){ ParkingBoy parkingBoy = new ParkingBoy(); ParkingTicket parkingTicket = new ParkingTicket("P2"); ParkingLot parkingLot = new ParkingLot(); Car carInParkingLot = new Car("P2"); parkingLot.parkingCar(carInParkingLot); Car correctCar = parkingBoy.parkingBoyFetchCar(parkingTicket, parkingLot); assertEquals(carInParkingLot.getCarId(), correctCar.getCarId()); }
void should_return_P2_car_when_parking_boy_fetch_car_given_parking_boy_P2_ticket_parking_lot(){ ParkingBoy parkingBoy = new ParkingBoy(); Car carInParkingLot = new Car("P2"); ParkingTicket parkingTicket = parkingBoy.parkingBoyParkingCar(carInParkingLot); Car correctCar = parkingBoy.parkingBoyFetchCar(parkingTicket); assertEquals(carInParkingLot.getCarId(), correctCar.getCarId()); }
413
private RoleConfig buildRoleConfig(ServiceProvider application){ RoleConfig roleConfig = new RoleConfig(); if (application.getClaimConfig() != null) { String roleClaimId = application.getClaimConfig().getRoleClaimURI(); if (StringUtils.isBlank(roleClaimId) && application.getClaimConfig().isLocalClaimDialect()) { roleClaimId = FrameworkConstants.LOCAL_ROLE_CLAIM_URI; } roleConfig.claim(buildClaimModel(roleClaimId)); } if (application.getLocalAndOutBoundAuthenticationConfig() != null) { roleConfig.includeUserDomain(application.getLocalAndOutBoundAuthenticationConfig().isUseUserstoreDomainInRoles()); } if (application.getPermissionAndRoleConfig() != null) { RoleMapping[] roleMappings = application.getPermissionAndRoleConfig().getRoleMappings(); if (roleMappings != null) { Arrays.stream(roleMappings).forEach(roleMapping -> roleConfig.addMappingsItem(new org.wso2.carbon.identity.api.server.application.management.v1.RoleMapping().applicationRole(roleMapping.getRemoteRole()).localRole(roleMapping.getLocalRole().getLocalRoleName()))); } } return roleConfig; }
private RoleConfig buildRoleConfig(ServiceProvider application){ RoleConfig roleConfig = new RoleConfig(); if (application.getClaimConfig() != null) { String roleClaimId = application.getClaimConfig().getRoleClaimURI(); if (StringUtils.isBlank(roleClaimId) && application.getClaimConfig().isLocalClaimDialect()) { roleClaimId = FrameworkConstants.LOCAL_ROLE_CLAIM_URI; } roleConfig.claim(buildClaimModel(roleClaimId)); } if (application.getLocalAndOutBoundAuthenticationConfig() != null) { roleConfig.includeUserDomain(application.getLocalAndOutBoundAuthenticationConfig().isUseUserstoreDomainInRoles()); } if (application.getPermissionAndRoleConfig() != null) { RoleMapping[] roleMappings = application.getPermissionAndRoleConfig().getRoleMappings(); arrayToStream(roleMappings).forEach(roleMapping -> roleConfig.addMappingsItem(new org.wso2.carbon.identity.api.server.application.management.v1.RoleMapping().applicationRole(roleMapping.getRemoteRole()).localRole(roleMapping.getLocalRole().getLocalRoleName()))); } return roleConfig; }
414
public Color getColor(){ if (this.color == null) { return null; } return this.color; }
public Color getColor(){ if (this.color == null) return null; return this.color; }
415
private synchronized void generateDeviceID(){ String generatedDeviceID; if (googleAdID != null) { synchronized (adIDLock) { generatedDeviceID = Constants.GUID_PREFIX_GOOGLE_AD_ID + googleAdID; } } else { synchronized (deviceIDLock) { generatedDeviceID = provisionalGUID; getConfigLogger().verbose(this.config.getAccountId(), "Made provisional ID permanent"); } } if (generatedDeviceID != null && generatedDeviceID.trim().length() > 2) { forceUpdateDeviceId(generatedDeviceID); if (sl != null) { sl.profileDidInitialize(generatedDeviceID); } } else { getConfigLogger().verbose(this.config.getAccountId(), "Unable to generate device ID"); } }
private synchronized void generateDeviceID(){ String generatedDeviceID; if (googleAdID != null) { synchronized (adIDLock) { generatedDeviceID = Constants.GUID_PREFIX_GOOGLE_AD_ID + googleAdID; } } else { synchronized (deviceIDLock) { generatedDeviceID = generateGUID(); getConfigLogger().verbose(this.config.getAccountId(), "Made provisional ID permanent"); } } if (generatedDeviceID.trim().length() > 2) { forceUpdateDeviceId(generatedDeviceID); } else { getConfigLogger().verbose(this.config.getAccountId(), "Unable to generate device ID"); } }
416
public static void addRecipe(Recipe recipe){ String recipeJSON = gson.toJson(recipe); try { java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); JSch jsch = new JSch(); jsch.addIdentity(DBUtils.ENV_SSH_KEY); ssh = null; ssh = jsch.getSession("ubuntu", DBUtils.ENV_DB_ADDRESS, DBUtils.SSH_PORT); ssh.setConfig(config); ssh.connect(); ssh.setPortForwardingL(6666, DBUtils.ENV_DB_ADDRESS, DBUtils.ENV_DB_PORT); MongoClient mongo = new MongoClient("localhost", 6666); MongoDatabase database = mongo.getDatabase(DBUtils.ENV_DB_NAME); MongoCollection<Document> recipes = database.getCollection("recipes"); recipes.insertOne(Document.parse(recipeJSON)); } catch (JSchException ex) { Logger.getLogger(VirtualRefrigerator.class.getName()).log(Level.SEVERE, null, ex); } finally { try { ssh.delPortForwardingL(6666); } catch (JSchException ex) { Logger.getLogger(VirtualRefrigerator.class.getName()).log(Level.SEVERE, null, ex); } ssh.disconnect(); } }
public static void addRecipe(Recipe recipe){ String recipeJSON = gson.toJson(recipe); try { java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); JSch jsch = new JSch(); jsch.addIdentity(DBUtils.ENV_SSH_KEY); ssh = jsch.getSession("ubuntu", DBUtils.ENV_DB_ADDRESS, DBUtils.SSH_PORT); ssh.setConfig(config); ssh.connect(); ssh.setPortForwardingL(DBUtils.DB_PORT_FORWARDING, DBUtils.ENV_DB_ADDRESS, DBUtils.ENV_DB_PORT); MongoClient mongo = new MongoClient("localhost", DBUtils.DB_PORT_FORWARDING); MongoDatabase database = mongo.getDatabase(DBUtils.ENV_DB_NAME); MongoCollection<Document> recipes = database.getCollection("recipes"); recipes.insertOne(Document.parse(recipeJSON)); } catch (JSchException ex) { Logger.getLogger(VirtualRefrigerator.class.getName()).log(Level.SEVERE, null, ex); } finally { try { ssh.delPortForwardingL(DBUtils.DB_PORT_FORWARDING); } catch (JSchException ex) { Logger.getLogger(VirtualRefrigerator.class.getName()).log(Level.SEVERE, null, ex); } ssh.disconnect(); } }
417
public String search(){ Session session = model.Util.sessionFactory.openSession(); Criteria c = session.createCriteria(Repertory.class); if (sDevice.equals("")) { } else { c.add(Restrictions.eq("rtDevice", this.sDevice)); if (sDevice.equals("主要设备")) { if (sMainDevice.equals("")) { } else { c.add(Restrictions.eq("rtType", this.sMainDevice)); } } else if (sDevice.equals("耗材设备")) { if (sCostDevice.equals("")) { } else { c.add(Restrictions.eq("rtType", this.sCostDevice)); } } } if (sDeviceStatus.equals("")) { } else { c.add(Restrictions.eq("rtDeviceStatus", this.sDeviceStatus)); } c.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); List tmp_rtSearch_list = c.list(); rtSearch_list = new ArrayList<T_Repertory>(); for (int i = 0; i < tmp_rtSearch_list.size(); ++i) { Repertory r = (Repertory) tmp_rtSearch_list.get(i); rtSearch_list.add(new T_Repertory(r)); } if (rtSearch_list.isEmpty()) { this.status = "0"; } else { Collections.reverse(rtSearch_list); this.status = "1"; this.add_repertory_html = util.Util.fileToString("/jsp/admin/widgets/add_repertory.html"); } session.close(); return SUCCESS; }
public String search() throws Exception{ Session session = model.Util.sessionFactory.openSession(); Criteria c = session.createCriteria(Repertory.class); if (sDevice.equals("")) { } else { c.add(Restrictions.eq("rtDevice", this.sDevice)); if (sDevice.equals("主要设备")) { if (sMainDevice.equals("")) { } else { c.add(Restrictions.eq("rtType", this.sMainDevice)); } } else if (sDevice.equals("耗材设备")) { if (sCostDevice.equals("")) { } else { c.add(Restrictions.eq("rtType", this.sCostDevice)); } } } if (sDeviceStatus.equals("")) { } else { c.add(Restrictions.eq("rtDeviceStatus", this.sDeviceStatus)); } c.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); repertory_list = c.list(); if (repertory_list.isEmpty()) { this.status = "0"; } else { Collections.reverse(repertory_list); this.status = "1"; HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); repertory_table = util.Util.getJspOutput("/jsp/admin/widgets/repertoryTable.jsp", request, response); } session.close(); return SUCCESS; }
418
public Map<String, Object> queryWorker(User loginUser){ Map<String, Object> result = new HashMap<>(); List<WorkerServerModel> workerServers = getServerListFromZK(false).stream().map((Server server) -> { WorkerServerModel model = new WorkerServerModel(); model.setId(server.getId()); model.setHost(server.getHost()); model.setPort(server.getPort()); model.setZkDirectories(Sets.newHashSet(server.getZkDirectory())); model.setResInfo(server.getResInfo()); model.setCreateTime(server.getCreateTime()); model.setLastHeartbeatTime(server.getLastHeartbeatTime()); return model; }).collect(Collectors.toList()); Map<String, WorkerServerModel> workerHostPortServerMapping = workerServers.stream().collect(Collectors.toMap((WorkerServerModel worker) -> { String[] s = worker.getZkDirectories().iterator().next().split("/"); return s[s.length - 1]; }, Function.identity(), (WorkerServerModel oldOne, WorkerServerModel newOne) -> { oldOne.getZkDirectories().addAll(newOne.getZkDirectories()); return oldOne; })); result.put(Constants.DATA_LIST, workerHostPortServerMapping.values()); putMsg(result, Status.SUCCESS); return result; }
public Result<Collection<WorkerServerModel>> queryWorker(User loginUser){ List<WorkerServerModel> workerServers = getServerListFromZK(false).stream().map((Server server) -> { WorkerServerModel model = new WorkerServerModel(); model.setId(server.getId()); model.setHost(server.getHost()); model.setPort(server.getPort()); model.setZkDirectories(Sets.newHashSet(server.getZkDirectory())); model.setResInfo(server.getResInfo()); model.setCreateTime(server.getCreateTime()); model.setLastHeartbeatTime(server.getLastHeartbeatTime()); return model; }).collect(Collectors.toList()); Map<String, WorkerServerModel> workerHostPortServerMapping = workerServers.stream().collect(Collectors.toMap((WorkerServerModel worker) -> { String[] s = worker.getZkDirectories().iterator().next().split("/"); return s[s.length - 1]; }, Function.identity(), (WorkerServerModel oldOne, WorkerServerModel newOne) -> { oldOne.getZkDirectories().addAll(newOne.getZkDirectories()); return oldOne; })); return Result.success(workerHostPortServerMapping.values()); }
419
public void takePicture(View view){ Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(getPackageManager()) != null) { File photoFile = null; try { photoFile = createImageFile(); } catch (IOException e) { e.printStackTrace(); Toast.makeText(this, "Unable to create image path.", Toast.LENGTH_SHORT).show(); } if (photoFile != null) { Uri photoURI = FileProvider.getUriForFile(this, "com.example.android.fileprovider", photoFile); takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI); startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); } } }
public void takePicture(View view){ Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(getPackageManager()) != null) { try { mCurrentImageFile = ImageUtils.createImageFile(this); } catch (IOException e) { e.printStackTrace(); Toast.makeText(this, "Unable to create image path.", Toast.LENGTH_SHORT).show(); } if (mCurrentImageFile != null) { Uri photoURI = FileProvider.getUriForFile(this, "com.example.android.fileprovider", mCurrentImageFile); takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI); startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); } } }
420
void getAndSetCantidadStock(){ Producto tester = new Producto(); final int cantidadStock = 2562; tester.setCantidadStock(cantidadStock); final int getCantidadStock = tester.getCantidadStock(); assertEquals(cantidadStock, getCantidadStock, "setCantidadStock must be 2562"); }
void getAndSetCantidadStock(){ final int cantidadStock = 2562; tester.setCantidadStock(cantidadStock); final int getCantidadStock = tester.getCantidadStock(); assertEquals(cantidadStock, getCantidadStock, "setCantidadStock must be 2562"); }
421
public Result queryDataSource(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam("id") int id){ logger.info("login user {}, query datasource: {}", loginUser.getUserName(), id); Map<String, Object> result = dataSourceService.queryDataSource(id); return returnDataList(result); }
public Result queryDataSource(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam("id") int id){ logger.info("login user {}, query datasource: {}", loginUser.getUserName(), id); return dataSourceService.queryDataSource(id); }
422
public void actionPerformed(ActionEvent arg0){ EspeakNg espeakNg = new EspeakNg(mainW); espeakNg.makeAction("translate"); }
public void actionPerformed(ActionEvent arg0){ espeakNg.makeAction("translate"); }
423
public static void filterByIncludedString(boolean isNewFilter, String[] includedStrings, int printLimit){ if (isNewFilter) { filteredWords.clear(); addTagsToFilteredList(FilterType.INCLUDING_STRING, includedStrings); } else { ArrayList<Words> wordsToRemove = new ArrayList<>(); generateListOfRemoveWords(FilterType.INCLUDING_STRING, includedStrings, wordsToRemove); removeRedundantWords(wordsToRemove); } printFilterList(printLimit); }
public static void filterByIncludedString(boolean isNewFilter, String[] includedStrings){ if (isNewFilter) { filteredWords.clear(); addTagsToFilteredList(FilterType.INCLUDING_STRING, includedStrings); } else { ArrayList<Words> wordsToRemove = new ArrayList<>(); generateListOfRemoveWords(FilterType.INCLUDING_STRING, includedStrings, wordsToRemove); removeRedundantWords(wordsToRemove); } }
424
public void onInitialize(){ try { MyItems.registerItems(); MyBlocks.registerBlocks(); MyFeatures.registerFeatures(); MyEntityType.class.getDeclaredConstructor().newInstance(); MyEntityType.registerEntities(); MyRecipeSerializer.registerRecipeSerializers(); FermentingRecipeRegistry.registerFermentingRecipes(); LootModify.modifyLoot(); VillagerModify.modify(); AxeModify.addStrippedBlocks(); } catch (Exception e) { e.printStackTrace(); } }
public void onInitialize(){ try { MyItems.registerItems(); MyBlocks.registerBlocks(); MyFeatures.registerFeatures(); MyEntityType.class.getDeclaredConstructor().newInstance(); MyEntityType.registerEntities(); MyRecipeSerializer.registerRecipeSerializers(); FermentingRecipeRegistry.registerFermentingRecipes(); MiscModifies.modify(); } catch (Exception e) { e.printStackTrace(); } }
425
public void createMessageUsingMessageBuilder(){ final Message<String> theMessage; theMessage = MessageBuilder.withPayload(GREETING_STRING).setHeader(MESSAGE_HEADER_NAME, MESSAGE_HEADER_VALUE).build(); Assert.assertTrue("Message should be a GenericMessage", theMessage instanceof GenericMessage); Assert.assertEquals("Message payload should be the greeting string", GREETING_STRING, theMessage.getPayload()); Assert.assertEquals("Message should contain three message headers", 3, theMessage.getHeaders().size()); Assert.assertTrue("Message should contain expected header", theMessage.getHeaders().containsKey(MESSAGE_HEADER_NAME)); Assert.assertEquals("Message header value should be expected value", MESSAGE_HEADER_VALUE, theMessage.getHeaders().get(MESSAGE_HEADER_NAME)); Assert.assertTrue("Message should contain an id header", theMessage.getHeaders().containsKey(MessageHeaders.ID)); Assert.assertTrue("Message should contain a timestamp header", theMessage.getHeaders().containsKey(MessageHeaders.TIMESTAMP)); }
public void createMessageUsingMessageBuilder(){ final Message<String> theMessage; theMessage = MessageBuilder.withPayload(GREETING_STRING).setHeader(MESSAGE_HEADER_NAME, MESSAGE_HEADER_VALUE).build(); Assert.assertTrue("Message should be a GenericMessage", theMessage instanceof GenericMessage); Assert.assertEquals("Message payload should be the greeting string", GREETING_STRING, theMessage.getPayload()); Assert.assertEquals("Message should contain three message headers", 3, theMessage.getHeaders().size()); Assert.assertTrue("Message should contain the expected header", theMessage.getHeaders().containsKey(MESSAGE_HEADER_NAME)); Assert.assertEquals("Message header value should be expected value", MESSAGE_HEADER_VALUE, theMessage.getHeaders().get(MESSAGE_HEADER_NAME)); assertContainsTimestampAndIdHeaders(theMessage); }
426
public List<MealView> getAll(@RequestParam(value = "page", defaultValue = "0") int page, @RequestParam(value = "limit", defaultValue = "25") int limit){ if (page > 0) page = page - 1; return mealService.getAll(page, limit); }
public List<MealView> getAll(@RequestParam(value = "page", defaultValue = "0") int page, @RequestParam(value = "limit", defaultValue = "25") int limit){ return mealService.getAll(page, limit); }
427
public void removeConsumerApplication(String consumerKey) throws IdentityOAuthAdminException{ Connection connection = null; PreparedStatement prepStmt = null; try { connection = JDBCPersistenceManager.getInstance().getDBConnection(); prepStmt = connection.prepareStatement(SQLQueries.OAuthAppDAOSQLQueries.REMOVE_APPLICATION); prepStmt.setString(1, consumerKey); prepStmt.execute(); connection.commit(); } catch (IdentityException e) { String errorMsg = "Error when getting an Identity Persistence Store instance."; log.error(errorMsg, e); throw new IdentityOAuthAdminException(errorMsg, e); } catch (SQLException e) { log.error("Error when executing the SQL : " + SQLQueries.OAuthAppDAOSQLQueries.REMOVE_APPLICATION); log.error(e.getMessage(), e); throw new IdentityOAuthAdminException("Error removing the consumer application."); } finally { IdentityDatabaseUtil.closeAllConnections(connection, null, prepStmt); } }
public void removeConsumerApplication(String consumerKey) throws IdentityOAuthAdminException{ Connection connection = null; PreparedStatement prepStmt = null; try { connection = JDBCPersistenceManager.getInstance().getDBConnection(); prepStmt = connection.prepareStatement(SQLQueries.OAuthAppDAOSQLQueries.REMOVE_APPLICATION); prepStmt.setString(1, consumerKey); prepStmt.execute(); connection.commit(); } catch (IdentityException e) { throw new IdentityOAuthAdminException("Error when getting an Identity Persistence Store instance.", e); } catch (SQLException e) { ; throw new IdentityOAuthAdminException("Error when executing the SQL : " + SQLQueries.OAuthAppDAOSQLQueries.REMOVE_APPLICATION, e); } finally { IdentityDatabaseUtil.closeAllConnections(connection, null, prepStmt); } }
428
private void closeSocket(long socket){ connections.remove(Long.valueOf(socket)); Poller poller = this.poller; if (poller != null) { poller.close(socket); } }
private void closeSocket(long socket){ SocketWrapperBase<Long> wrapper = connections.remove(Long.valueOf(socket)); if (wrapper != null) { ((AprSocketWrapper) wrapper).close(); } }
429
public Player apply(Score aScore){ requireNonNull(aScore); if (aScore.player1TennisPoints() == WIN) { return PLAYER1; } else if (aScore.player2TennisPoints() == WIN) { return PLAYER2; } else { throw new RuntimeException("there can't be a winner with this score: " + aScore); } }
public Player apply(Score aScore){ requireNonNull(aScore); checkArgument(hasAWinner.test(aScore), "there is no winner with a such score %s", aScore); if (aScore.player1Points() > aScore.player2Points()) { return PLAYER1; } else { return PLAYER2; } }
430
void listFiles(String uri){ try { Log.v(TAG, "listFiles(" + uri + ")"); AssetManager assetManager = this.getAssets(); String[] fileList = assetManager.list(uri); Log.v(TAG, "listFiles(" + uri + ") - " + fileList.length + " files found"); for (int i = 0; i < fileList.length; i++) { Log.v(TAG, "File " + i + " = " + fileList[i]); } } catch (Exception ioe) { Log.v(TAG, "Error Listing Files - Error = " + ioe.toString()); } }
void listFiles(String uri){ try { AssetManager assetManager = this.getAssets(); String[] fileList = assetManager.list(uri); } catch (Exception ioe) { Log.v(TAG, "Error Listing Files - Error = " + ioe.toString()); } }
431
protected void onEnsureDebugId(String baseID){ super.onEnsureDebugId(baseID); toolsMenuButton.ensureDebugId(baseID + ToolsModule.ToolIds.MENU_TOOLS); addTool.ensureDebugId(baseID + ToolsModule.ToolIds.MENU_ITEM_ADD_TOOLS); edit.ensureDebugId(baseID + ToolsModule.ToolIds.MENU_ITEM_EDIT); requestTool.ensureDebugId(baseID + ToolsModule.ToolIds.MENU_ITEM_REQUEST_TOOL); delete.ensureDebugId(baseID + ToolsModule.ToolIds.MENU_ITEM_DELETE); useInApp.ensureDebugId(baseID + ToolsModule.ToolIds.MENU_ITEM_USE_IN_APPS); shareMenuButton.ensureDebugId(baseID + ToolsModule.ToolIds.MENU_SHARE); shareCollab.ensureDebugId(baseID + ToolsModule.ToolIds.MENU_ITEM_SHARE_COLLABS); sharePublic.ensureDebugId(baseID + ToolsModule.ToolIds.MENU_ITEM_SHARE_PUBLIC); refreshButton.ensureDebugId(baseID + ToolsModule.ToolIds.MENU_ITEM_REFRESH); toolSearch.ensureDebugId(baseID + ToolsModule.ToolIds.TOOL_SEARCH); }
protected void onEnsureDebugId(String baseID){ super.onEnsureDebugId(baseID); toolsMenuButton.ensureDebugId(baseID + ToolsModule.ToolIds.MENU_TOOLS); addTool.ensureDebugId(baseID + ToolsModule.ToolIds.MENU_ITEM_ADD_TOOLS); edit.ensureDebugId(baseID + ToolsModule.ToolIds.MENU_ITEM_EDIT); requestTool.ensureDebugId(baseID + ToolsModule.ToolIds.MENU_ITEM_REQUEST_TOOL); delete.ensureDebugId(baseID + ToolsModule.ToolIds.MENU_ITEM_DELETE); useInApp.ensureDebugId(baseID + ToolsModule.ToolIds.MENU_ITEM_USE_IN_APPS); shareCollab.ensureDebugId(baseID + ToolsModule.ToolIds.MENU_SHARE); shareCollab.ensureDebugId(baseID + ToolsModule.ToolIds.MENU_ITEM_SHARE_COLLABS); refreshButton.ensureDebugId(baseID + ToolsModule.ToolIds.MENU_ITEM_REFRESH); toolSearch.ensureDebugId(baseID + ToolsModule.ToolIds.TOOL_SEARCH); }
432
public static ArrayList<String> extractPreRequisites(ArrayList<String> commandFlags){ ArrayList<String> preRequisites = new ArrayList<>(); for (int i = 0; i < commandFlags.size(); i++) { if (commandFlags.get(i).equals("-p")) { String trimmedCommandFlag = commandFlags.get(i + 1).trim(); ArrayList<String> moduleCodes = new ArrayList<String>(Arrays.asList(trimmedCommandFlag.split(","))); for (String moduleCode : moduleCodes) { preRequisites.add(moduleCode.toUpperCase()); } break; } } return preRequisites; }
public static ArrayList<String> extractPreRequisites(ArrayList<String> commandFlags){ ArrayList<String> preRequisites = new ArrayList<>(); int index = commandFlags.indexOf("-p"); if (index >= 0) { String trimmedCommandFlag = commandFlags.get(index + 1).trim(); ArrayList<String> moduleCodes = new ArrayList<String>(Arrays.asList(trimmedCommandFlag.split(","))); for (String moduleCode : moduleCodes) { preRequisites.add(moduleCode.toUpperCase()); } } return preRequisites; }
433
public Connection getConnection() throws SQLException, ClassNotFoundException{ try { Class.forName("org.postgresql.Driver"); } catch (ClassNotFoundException e) { throw e; } if (connection == null) { connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/" + databaseName, login, password); } return connection; }
public Connection getConnection() throws SQLException, ClassNotFoundException{ Class.forName("org.postgresql.Driver"); if (connection == null) { connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/" + databaseName, login, password); } return connection; }
434
public static String getJsonDataAsString() throws Exception{ String filePath = "src/main/java/Persistence/weatherForecast.json"; String result = readJSONFileAsString(filePath); return result; }
public static String getJsonDataAsString() throws Exception{ String filePath = "src/main/java/Persistence/weatherForecast.json"; return readJSONFileAsString(filePath); }
435
private void exit() throws Exception{ System.out.println(); System.out.print("\tExit after 10 seconds"); Thread.sleep(5000); System.exit(0); }
private void exit() throws Exception{ System.out.println(); System.exit(0); }
436
public static com.vaadin.ui.TextArea createTextArea(String name){ com.vaadin.ui.TextArea textArea = new com.vaadin.ui.TextArea(name); return textArea; }
public static TextArea createTextArea(String name){ return new TextArea(name); }
437
private void initSpinner(){ String[] array = { STYLE_NO, STYLE_BIG_TEXT, STYLE_BIG_PICTURE, STYLE_INBOX, STYLE_MEDIA, STYLE_MESSAGING }; ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.spinner_item_style); adapter.addAll(array); binding.spinner.setAdapter(adapter); }
private void initSpinner(){ ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.spinner_item_style); adapter.addAll(NotificationStyle.createStyleNameList()); binding.spinner.setAdapter(adapter); }
438
public void start(Stage primaryStage){ try { Configuration configuration = getConfigurationFromCommandLineArgs(); SidPlay2Section section = configuration.getSidplay2Section(); IWhatsSidSection whatsSidSection = configuration.getWhatsSidSection(); String url = whatsSidSection.getUrl(); String username = whatsSidSection.getUsername(); String password = whatsSidSection.getPassword(); player = new Player(configuration); player.setMenuHook(menuHook); player.setFingerPrintMatcher(new FingerprintJsonClient(url, username, password)); Optional<String> filename = filenames.stream().findFirst(); if (filename.isPresent()) { try { new Convenience(player).autostart(new File(filename.get()), Convenience.LEXICALLY_FIRST_MEDIA, null); } catch (IOException | SidTuneError e) { System.err.println(e.getMessage()); } } jSidplay2 = new JSidPlay2(primaryStage, player); Scene scene = primaryStage.getScene(); if (scene != null) { Window window = scene.getWindow(); window.setX(section.getFrameX()); section.frameXProperty().bind(window.xProperty()); window.setY(section.getFrameY()); section.frameYProperty().bind(window.yProperty()); window.setWidth(section.getFrameWidth()); section.frameWidthProperty().bind(window.widthProperty()); window.setHeight(section.getFrameHeight()); section.frameHeightProperty().bind(window.heightProperty()); } jSidplay2.open(); } catch (Throwable t) { t.printStackTrace(); } }
public void start(Stage primaryStage){ try { Configuration configuration = getConfigurationFromCommandLineArgs(); SidPlay2Section sidplay2Section = configuration.getSidplay2Section(); WhatsSidSection whatsSidSection = configuration.getWhatsSidSection(); String url = whatsSidSection.getUrl(); String username = whatsSidSection.getUsername(); String password = whatsSidSection.getPassword(); player = new Player(configuration); player.setMenuHook(menuHook); player.setFingerPrintMatcher(new FingerprintJsonClient(url, username, password)); autostartFilenames(); jSidplay2 = new JSidPlay2(primaryStage, player); Scene scene = primaryStage.getScene(); if (scene != null) { Window window = scene.getWindow(); window.setX(sidplay2Section.getFrameX()); sidplay2Section.frameXProperty().bind(window.xProperty()); window.setY(sidplay2Section.getFrameY()); sidplay2Section.frameYProperty().bind(window.yProperty()); window.setWidth(sidplay2Section.getFrameWidth()); sidplay2Section.frameWidthProperty().bind(window.widthProperty()); window.setHeight(sidplay2Section.getFrameHeight()); sidplay2Section.frameHeightProperty().bind(window.heightProperty()); } jSidplay2.open(); } catch (Throwable t) { t.printStackTrace(); } }
439
public Response getBridges(@DefaultValue(PAGE_DEFAULT) @Min(PAGE_MIN) @QueryParam(PAGE) int page, @DefaultValue(SIZE_DEFAULT) @Min(SIZE_MIN) @Max(SIZE_MAX) @QueryParam(PAGE_SIZE) int pageSize){ ListResult<Bridge> bridges = bridgesService.getBridges(customerIdResolver.resolveCustomerId(identity.getPrincipal()), page, pageSize); List<BridgeResponse> bridgeResponses = bridges.getItems().stream().map(bridgesService::toResponse).collect(Collectors.toList()); BridgeListResponse response = new BridgeListResponse(); response.setItems(bridgeResponses); response.setPage(bridges.getPage()); response.setSize(bridges.getSize()); response.setTotal(bridges.getTotal()); return Response.ok(response).build(); }
public Response getBridges(@Valid @BeanParam QueryInfo queryInfo){ return Response.ok(ListResponse.fill(bridgesService.getBridges(customerIdResolver.resolveCustomerId(identity.getPrincipal()), queryInfo), new BridgeListResponse(), bridgesService::toResponse)).build(); }
440
public void process1Test(){ String locale_ = "en"; String folder_ = "messages"; String relative_ = "sample/file"; String content_ = "one=Description one\ntwo=Description two\nthree=desc &lt;{0}&gt;"; String html_ = "<html><body><c:for className=\"$int\" var=\"k\" from=\"0\" to=\"2\" eq=\"true\" step=\"1\">{k} - {([k])}<br/></c:for></body></html>"; StringMap<String> files_ = new StringMap<String>(); files_.put(EquallableExUtil.formatFile(folder_, locale_, relative_), content_); Configuration conf_ = contextElFive(); conf_.setBeans(new StringMap<Bean>()); conf_.setMessagesFolder(folder_); conf_.setProperties(new StringMap<String>()); conf_.getProperties().put("msg_example", relative_); RendDocumentBlock rendDocumentBlock_ = build(html_, conf_); assertTrue(conf_.isEmptyErrors()); assertEq("<html><body>0 - 0<br/>1 - 1<br/>2 - 2<br/></body></html>", RendBlock.getRes(rendDocumentBlock_, conf_)); assertNull(getException(conf_)); }
public void process1Test(){ String locale_ = "en"; String folder_ = "messages"; String relative_ = "sample/file"; String content_ = "one=Description one\ntwo=Description two\nthree=desc &lt;{0}&gt;"; String html_ = "<html><body><c:for className=\"$int\" var=\"k\" from=\"0\" to=\"2\" eq=\"true\" step=\"1\">{k} - {([k])}<br/></c:for></body></html>"; StringMap<String> files_ = new StringMap<String>(); files_.put(EquallableExUtil.formatFile(folder_, locale_, relative_), content_); Configuration conf_ = contextElFive(); conf_.setMessagesFolder(folder_); conf_.setProperties(new StringMap<String>()); conf_.getProperties().put("msg_example", relative_); RendDocumentBlock rendDocumentBlock_ = build(html_, conf_); assertTrue(conf_.isEmptyErrors()); assertEq("<html><body>0 - 0<br/>1 - 1<br/>2 - 2<br/></body></html>", RendBlock.getRes(rendDocumentBlock_, conf_)); assertNull(getException(conf_)); }
441
public static void checkLength(final int lengthArray){ CheckerBoundNumber.isInRange(lengthArray, LOWER_BOUND_LENGTH, UPPER_BOUND_LENGTH); if (lengthArray < LOWER_BOUND_LENGTH || lengthArray > UPPER_BOUND_LENGTH) { throw new LengthOutOfRangeException("Length value out of range(" + LOWER_BOUND_LENGTH + "-" + UPPER_BOUND_LENGTH + ")."); } }
public static void checkLength(final int lengthArray){ if (lengthArray < LOWER_BOUND_LENGTH || lengthArray > UPPER_BOUND_LENGTH) { throw new LengthOutOfRangeException("Length value out of range(" + LOWER_BOUND_LENGTH + "-" + UPPER_BOUND_LENGTH + ")."); } }
442
public void encodeThreeElementsFlux() throws InterruptedException{ JsonObjectEncoder encoder = new JsonObjectEncoder(); Flux<ByteBuffer> source = Flux.just(Buffer.wrap("{\"foo\": \"foofoo\", \"bar\": \"barbar\"}").byteBuffer(), Buffer.wrap("{\"foo\": \"foofoofoo\", \"bar\": \"barbarbar\"}").byteBuffer(), Buffer.wrap("{\"foo\": \"foofoofoofoo\", \"bar\": \"barbarbarbar\"}").byteBuffer()); Iterable<String> results = Flux.from(encoder.encode(source, null, null)).map(chunk -> { byte[] b = new byte[chunk.remaining()]; chunk.get(b); return new String(b, StandardCharsets.UTF_8); }).toIterable(); String result = String.join("", results); assertEquals("[{\"foo\": \"foofoo\", \"bar\": \"barbar\"},{\"foo\": \"foofoofoo\", \"bar\": \"barbarbar\"},{\"foo\": \"foofoofoofoo\", \"bar\": \"barbarbarbar\"}]", result); }
public void encodeThreeElementsFlux() throws InterruptedException{ Flux<DataBuffer> source = Flux.just(stringBuffer("{\"foo\": \"foofoo\", \"bar\": \"barbar\"}"), stringBuffer("{\"foo\": \"foofoofoo\", \"bar\": \"barbarbar\"}"), stringBuffer("{\"foo\": \"foofoofoofoo\", \"bar\": \"barbarbarbar\"}")); Iterable<String> results = Flux.from(encoder.encode(source, null, null)).map(chunk -> { byte[] b = new byte[chunk.readableByteCount()]; chunk.read(b); return new String(b, StandardCharsets.UTF_8); }).toIterable(); String result = String.join("", results); assertEquals("[{\"foo\": \"foofoo\", \"bar\": \"barbar\"},{\"foo\": \"foofoofoo\", \"bar\": \"barbarbar\"},{\"foo\": \"foofoofoofoo\", \"bar\": \"barbarbarbar\"}]", result); }
443
public void onClick(View v){ String currentSetting = satelitebtn.getText().toString(); if (currentSetting.equalsIgnoreCase("Satellite View")) { Point initialView = new Point(-76.927, 38.996, SpatialReferences.getWebMercator()); mMapView = findViewById(R.id.mapView); satelitebtn.setText("Normal View"); ArcGISMap map = new ArcGISMap(Basemap.Type.IMAGERY, initialView.getY(), initialView.getX(), 5); mMapView.setMap(map); } else { Point initialView = new Point(-76.927, 38.996, SpatialReferences.getWebMercator()); mMapView = findViewById(R.id.mapView); satelitebtn.setText("Satellite View"); ArcGISMap map = new ArcGISMap(Basemap.Type.TOPOGRAPHIC, initialView.getY(), initialView.getX(), 5); mMapView.setMap(map); } }
public void onClick(View v){ String currentSetting = satelitebtn.getText().toString(); if (currentSetting.equals(getString(R.string.satellite_view))) { mMapView.getMap().setBasemap(Basemap.createImagery()); satelitebtn.setText(R.string.normal_view); } else { mMapView.getMap().setBasemap(Basemap.createTopographic()); satelitebtn.setText(R.string.satellite_view); } }
444
private void baseCheckUpdate(boolean toastResult){ MergeAppUpdateChecker auc = MergeAppUpdateChecker.getSingleton(this); if (mOnCheckUpdateResultListener == null) { mOnCheckUpdateResultListener = new MergeAppUpdateChecker.OnResultListener() { @Override public void onResult(boolean findNewVersion) { mCheckUpdateResultText = findNewVersion ? mFindNewVersion : mIsTheLatestVersion; if (mDrawerListAdapter != null) { mDrawerListAdapter.notifyItemChanged(0); } } }; auc.addOnResultListener(mOnCheckUpdateResultListener); } auc.checkUpdate(toastResult); }
private void baseCheckUpdate(boolean toastResult){ MergeAppUpdateChecker auc = MergeAppUpdateChecker.getSingleton(this); if (mOnCheckUpdateResultListener == null) { mOnCheckUpdateResultListener = findNewVersion -> { mCheckUpdateResultText = findNewVersion ? mFindNewVersion : mIsTheLatestVersion; if (mDrawerListAdapter != null) { mDrawerListAdapter.notifyItemChanged(0); } }; auc.addOnResultListener(mOnCheckUpdateResultListener); } auc.checkUpdate(toastResult); }
445
public List<ExchangeRate> readAllExchangeRates(){ ObjectMapper mapper = new ObjectMapper(); List<ExchangeRate> rates = new ArrayList<>(); try { for (BankName bankName : BankName.values()) { String path = new JsonExchangeRatesPathFactory().getExchangeRatesPath(String.valueOf(bankName)); rates.addAll(Arrays.asList(mapper.readValue(new FileInputStream(path), ExchangeRate[].class))); } } catch (IOException e) { e.printStackTrace(); } return rates; }
public List<ExchangeRate> readAllExchangeRates(){ List<ExchangeRate> rates = new ArrayList<>(); for (BankName bankName : BankName.values()) { rates.addAll(readExchangeRatesByBankName(String.valueOf(bankName))); } return rates; }
446
protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); ((MyApplication) getApplication()).getAppComponent().inject(this); listView = findViewById(R.id.listView); projectApi.getAllProjects().observeOn(AndroidSchedulers.mainThread()).subscribe(this::displayProjects, throwable -> { Log.e(TAG, "oops", throwable); }); }
protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); ((MyApplication) getApplication()).getAppComponent().inject(this); listView = findViewById(R.id.listView); projectApi.getAllProjects().observeOn(AndroidSchedulers.mainThread()).subscribe(this::displayProjects, throwable -> Log.e(TAG, "oops", throwable)); }
447
int findEntry(PackageGroup group, int typeIndex, String name, Ref<Integer> outTypeSpecFlags){ List<Type> typeList = group.types.get(typeIndex); for (Type type : typeList) { int ei = type._package_.keyStrings.indexOfString(name); if (ei < 0) { continue; } for (ResTableType resTableType : type.configs) { List<ResTableEntry> entries = resTableType.entries; for (int entryIndex = 0; entryIndex < entries.size(); entryIndex++) { ResTableEntry entry = entries.get(entryIndex); if (entry == null) { continue; } if (dtohl(entry.key.index) == ei) { int resId = Res_MAKEID(group.id - 1, typeIndex, entryIndex); if (outTypeSpecFlags != null) { Ref<Entry> result = new Ref<>(null); if (getEntry(group, typeIndex, entryIndex, null, result) != NO_ERROR) { ALOGW("Failed to find spec flags for 0x%08x", resId); return 0; } outTypeSpecFlags.set(result.get().specFlags); } return resId; } } } } return 0; }
int findEntry(PackageGroup group, int typeIndex, String name, Ref<Integer> outTypeSpecFlags){ List<Type> typeList = group.types.get(typeIndex); for (Type type : typeList) { int ei = type._package_.keyStrings.indexOfString(name); if (ei < 0) { continue; } for (ResTable_type resTableType : type.configs) { int entryIndex = resTableType.findEntryByResName(ei); int resId = Res_MAKEID(group.id - 1, typeIndex, entryIndex); if (outTypeSpecFlags != null) { Entry result = new Entry(); if (getEntry(group, typeIndex, entryIndex, null, result) != NO_ERROR) { ALOGW("Failed to find spec flags for 0x%08x", resId); return 0; } outTypeSpecFlags.set(result.specFlags); } return resId; } } return 0; }
448
private Map<String, Object> countStateByProject(User loginUser, int projectId, String startDate, String endDate, TriFunction<Date, Date, Integer[], List<ExecuteStatusCount>> instanceStateCounter){ Map<String, Object> result = new HashMap<>(); boolean checkProject = checkProject(loginUser, projectId, result); if (!checkProject) { return result; } Date start = null; Date end = null; if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate)) { start = DateUtils.getScheduleDate(startDate); end = DateUtils.getScheduleDate(endDate); if (Objects.isNull(start) || Objects.isNull(end)) { putMsg(result, Status.REQUEST_PARAMS_NOT_VALID_ERROR, Constants.START_END_DATE); return result; } } Integer[] projectIdArray = getProjectIdsArrays(loginUser, projectId); List<ExecuteStatusCount> processInstanceStateCounts = instanceStateCounter.apply(start, end, projectIdArray); if (processInstanceStateCounts != null) { TaskCountDto taskCountResult = new TaskCountDto(processInstanceStateCounts); result.put(Constants.DATA_LIST, taskCountResult); putMsg(result, Status.SUCCESS); } return result; }
private Result<TaskCountDto> countStateByProject(User loginUser, int projectId, String startDate, String endDate, TriFunction<Date, Date, Integer[], List<ExecuteStatusCount>> instanceStateCounter){ CheckParamResult checkResult = checkProject(loginUser, projectId); if (!Status.SUCCESS.equals(checkResult.getStatus())) { return Result.error(checkResult); } Date start = null; Date end = null; if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate)) { start = DateUtils.getScheduleDate(startDate); end = DateUtils.getScheduleDate(endDate); if (Objects.isNull(start) || Objects.isNull(end)) { putMsg(checkResult, Status.REQUEST_PARAMS_NOT_VALID_ERROR, Constants.START_END_DATE); return Result.error(checkResult); } } Integer[] projectIdArray = getProjectIdsArrays(loginUser, projectId); List<ExecuteStatusCount> processInstanceStateCounts = instanceStateCounter.apply(start, end, projectIdArray); if (processInstanceStateCounts != null) { TaskCountDto taskCountResult = new TaskCountDto(processInstanceStateCounts); return Result.success(taskCountResult); } return Result.success(null); }
449
public void checkForceIncrement(){ int k = 100; ReservoirLongsSketch rls = ReservoirLongsSketch.getInstance(k); for (int i = 0; i < 2 * k; ++i) { rls.update(i); } assertEquals(rls.getN(), 2 * k); rls.forceIncrementItemsSeen(k); assertEquals(rls.getN(), 3 * k); try { rls.forceIncrementItemsSeen((1 << 48) - 1); fail(); } catch (SketchesStateException e) { ; } }
public void checkForceIncrement(){ int k = 100; ReservoirLongsSketch rls = ReservoirLongsSketch.getInstance(k); for (int i = 0; i < 2 * k; ++i) { rls.update(i); } assertEquals(rls.getN(), 2 * k); rls.forceIncrementItemsSeen(k); assertEquals(rls.getN(), 3 * k); try { rls.forceIncrementItemsSeen(0xFFFFFFFFFFFFL - 1); fail(); } catch (SketchesStateException e) { } }
450
public void mouseClicked(MouseEvent e){ Set<String> vertices = graph.vertexSet(); Object cell = graphComponent.getCellAt(e.getX(), e.getY()); if (cell != null && cell instanceof mxCell) { String v = ((mxCell) cell).getValue().toString(); if (vertices.contains(((mxCell) cell).getValue().toString())) { System.out.println(((mxCell) cell).getStyle()); if (robberChoose) { uncolorVertex(jgxAdapter, robberColor); jgxAdapter.setCellStyles(mxConstants.STYLE_FILLCOLOR, robberColor, new Object[] { cell }); } else { if (winText != null) { jgxAdapter.removeCells(new Object[] { winText }); } uncolorVertex(jgxAdapter, copColor); String oldColor = ((mxCell) cell).getStyle(); jgxAdapter.setCellStyles(mxConstants.STYLE_FILLCOLOR, copColor, new Object[] { cell }); if (oldColor.contains(robberColor)) { robberChoose = true; double xCenter = jgxAdapter.getGraphBounds().getCenterX() - winTextWidth / 2; double yCenter = jgxAdapter.getGraphBounds().getCenterY() - winTextHeight / 2; winText = (mxCell) jgxAdapter.insertVertex(jgxAdapter.getDefaultParent(), "winText", "Cop wins!", xCenter, yCenter, winTextWidth, winTextHeight); } } robberChoose = !robberChoose; graphComponent.refresh(); System.out.println("click"); } } }
public void mouseClicked(MouseEvent e){ Set<String> vertices = graph.vertexSet(); Object cell = graphComponent.getCellAt(e.getX(), e.getY()); if (cell != null && cell instanceof mxCell) { if (vertices.contains(((mxCell) cell).getValue().toString())) { System.out.println(((mxCell) cell).getStyle()); if (robberChoose) { uncolorVertex(jgxAdapter, robberColor); jgxAdapter.setCellStyles(mxConstants.STYLE_FILLCOLOR, robberColor, new Object[] { cell }); } else { if (winText != null) { jgxAdapter.removeCells(new Object[] { winText }); } uncolorVertex(jgxAdapter, copColor); String oldColor = ((mxCell) cell).getStyle(); jgxAdapter.setCellStyles(mxConstants.STYLE_FILLCOLOR, copColor, new Object[] { cell }); if (oldColor.contains(robberColor)) { robberChoose = true; double xCenter = jgxAdapter.getGraphBounds().getCenterX() - winTextWidth / 2; double yCenter = jgxAdapter.getGraphBounds().getCenterY() - winTextHeight / 2; winText = (mxCell) jgxAdapter.insertVertex(jgxAdapter.getDefaultParent(), "winText", "Cop wins!", xCenter, yCenter, winTextWidth, winTextHeight); } } robberChoose = !robberChoose; graphComponent.refresh(); System.out.println("click"); } } }
451
public User loadByPrimaryKey(Integer key){ User user = userRepository.findOne(key); if (user == null) { String message = String.format(this.getClass() + " with primary key '%d' not found"); throw new DataNotFoundException(message, String.valueOf(key)); } return user; }
public User loadByPrimaryKey(Integer key){ User user = userRepository.findOne(key); if (user == null) throw new DataNotFoundException(String.format(this.getClass() + " with primary key '%d' not found"), String.valueOf(key)); return user; }
452
public void processTasks(){ if (pool.isShuttingDown()) { return; } synchronized (waitingSystemTasks) { DBBroker broker = null; Subject oldUser = null; try { broker = pool.get(null); oldUser = broker.getSubject(); broker.setSubject(pool.getSecurityManager().getSystemSubject()); while (!waitingSystemTasks.isEmpty()) { final SystemTask task = waitingSystemTasks.pop(); if (task.afterCheckpoint()) { pool.sync(broker, Sync.MAJOR_SYNC); } runSystemTask(task, broker); } } catch (final Exception e) { SystemTask.LOG.warn("System maintenance task reported error: " + e.getMessage(), e); } finally { if (oldUser != null) { broker.setSubject(oldUser); } pool.release(broker); } } }
public void processTasks(){ if (pool.isShuttingDown()) { return; } synchronized (waitingSystemTasks) { try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()))) { while (!waitingSystemTasks.isEmpty()) { final SystemTask task = waitingSystemTasks.pop(); if (task.afterCheckpoint()) { pool.sync(broker, Sync.MAJOR_SYNC); } runSystemTask(task, broker); } } catch (final Exception e) { SystemTask.LOG.warn("System maintenance task reported error: " + e.getMessage(), e); } } }
453
private void sendChannelVerificationRequest(TextChannel targetChannel, Message originChannelMessage, User tunnelInstantiator){ String targetChannelID = targetChannel.getId(); String originChannelID = originChannelMessage.getChannel().getId(); addToMap(targetChannel, originChannelMessage); targetChannel.getGuild().retrieveMember(tunnelInstantiator).queue(member -> { if (member == null) { originChannelMessage.getChannel().sendMessage("**You need to be in that guild to dig a tunnel there!**").queue(); } else { if (member.hasPermission(Permission.MANAGE_CHANNEL)) { targetChannel.sendMessage("**Incoming tunnel request from " + originChannelMessage.getGuild().getName() + " > " + originChannelMessage.getChannel().getName() + "**\nSay 'accept' within 30 seconds to allow this tunnel to be dug!").queue(); waiter.waitForEvent(MessageReceivedEvent.class, event -> tunnelAcceptedStatement(((MessageReceivedEvent) event), targetChannel), event -> { boolean allowTunnel = event.getMessage().getContentRaw().toLowerCase().equals("accept"); if (allowTunnel) { digTunnel(targetChannel, originChannelMessage.getChannel()); } else { denyTunnel(originChannelMessage); } removeFromMap(targetChannelID, originChannelID); }, 30, TimeUnit.SECONDS, () -> { originChannelMessage.getChannel().sendMessage("**Request timed out**").queue(); removeFromMap(targetChannelID, originChannelID); }); } else { originChannelMessage.getChannel().sendMessage("**You do not have permission to do that there!**").queue(); } } }); }
private void sendChannelVerificationRequest(TextChannel targetChannel, Message originChannelMessage, User tunnelInstantiator){ String targetChannelID = targetChannel.getId(); String originChannelID = originChannelMessage.getChannel().getId(); addToMap(targetChannel, originChannelMessage); targetChannel.getGuild().retrieveMember(tunnelInstantiator).queue(member -> { if (member == null) originChannelMessage.getChannel().sendMessage("**You need to be in that guild to dig a tunnel there!**").queue(); else { if (member.hasPermission(Permission.MANAGE_CHANNEL)) { targetChannel.sendMessage("**Incoming tunnel request from " + originChannelMessage.getGuild().getName() + " > " + originChannelMessage.getChannel().getName() + "**\nSay 'accept' within 30 seconds to allow this tunnel to be dug!").queue(); waiter.waitForEvent(MessageReceivedEvent.class, event -> tunnelAcceptedStatement(((MessageReceivedEvent) event), targetChannel), event -> { boolean allowTunnel = event.getMessage().getContentRaw().toLowerCase().equals("accept"); if (allowTunnel) digTunnel(targetChannel, originChannelMessage.getChannel()); else denyTunnel(originChannelMessage); removeFromMap(targetChannelID, originChannelID); }, 30, TimeUnit.SECONDS, () -> { originChannelMessage.getChannel().sendMessage("**Request timed out**").queue(); removeFromMap(targetChannelID, originChannelID); }); } else originChannelMessage.getChannel().sendMessage("**You do not have permission to do that there!**").queue(); } }); }
454
void Draw(Canvas canvas){ if (skin != null) { width = (int) (skin.getWidth() * scale); height = (int) (skin.getHeight() * scale); dst.set((int) pos_x, (int) pos_y, (int) pos_x + width, (int) pos_y + height); canvas.drawBitmap(skin, null, dst, null); } }
void Draw(Canvas canvas){ if (skin != null) { dst.set((int) pos_x, (int) pos_y, (int) pos_x + width - 1, (int) pos_y + height - 1); canvas.drawBitmap(skin, null, dst, null); } }
455
public void equals(){ Friend aliceCopy = new FriendBuilder(ALICE).build(); assertTrue(ALICE.equals(aliceCopy)); assertTrue(ALICE.equals(ALICE)); assertFalse(ALICE.equals(null)); assertFalse(ALICE.equals(5)); assertFalse(ALICE.equals(BOB)); Friend editedAlice = new FriendBuilder(ALICE).withFriendId(VALID_FRIEND_ID_BOB).build(); assertFalse(ALICE.equals(editedAlice)); editedAlice = new FriendBuilder(ALICE).withFriendName(VALID_NAME_BOB).build(); assertFalse(ALICE.equals(editedAlice)); editedAlice = new FriendBuilder(ALICE).withGames(VALID_GAME_APEX_LEGENDS).build(); assertFalse(ALICE.equals(editedAlice)); }
public void equals(){ Friend aliceCopy = new FriendBuilder(ALICE).build(); assertTrue(ALICE.equals(aliceCopy)); assertTrue(ALICE.equals(ALICE)); assertFalse(ALICE.equals(null)); assertFalse(ALICE.equals(5)); assertFalse(ALICE.equals(BOB)); Friend editedAlice = new FriendBuilder(ALICE).withFriendId(VALID_FRIEND_ID_BOB).build(); assertFalse(ALICE.equals(editedAlice)); editedAlice = new FriendBuilder(ALICE).withFriendName(VALID_NAME_BOB).build(); assertFalse(ALICE.equals(editedAlice)); }
456
public Reply replyToMessage(){ Consumer<Update> action = upd -> { try { responseHandler.replyToMessage(upd); } catch (URISyntaxException e) { e.printStackTrace(); } }; return Reply.of(action, Flag.MESSAGE); }
public Reply replyToMessage(){ Consumer<Update> action = upd -> responseHandler.replyToMessage(upd); return Reply.of(action, Flag.MESSAGE); }
457
public Result deleteAlertPluginInstance(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam(value = "id") int id){ logger.info("login user {},delete alert plugin instance id {}", RegexUtils.escapeNRT(loginUser.getUserName()), id); Map<String, Object> result = alertPluginInstanceService.delete(loginUser, id); return returnDataList(result); }
public Result<Void> deleteAlertPluginInstance(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam(value = "id") int id){ logger.info("login user {},delete alert plugin instance id {}", RegexUtils.escapeNRT(loginUser.getUserName()), id); return alertPluginInstanceService.delete(loginUser, id); }
458
public void onBackPressed(){ if (mIsPresentingImmersive) { queueRunnable(() -> exitImmersiveNative()); return; } if (mBackHandlers.size() > 0) { mBackHandlers.getLast().run(); return; } if (SessionStore.get().canGoBack()) { SessionStore.get().goBack(); } else if (SessionStore.get().canUnstackSession()) { SessionStore.get().unstackSession(); } else if (SessionStore.get().isCurrentSessionPrivate()) { SessionStore.get().exitPrivateMode(); } else { super.onBackPressed(); } }
public void onBackPressed(){ if (mIsPresentingImmersive) { queueRunnable(() -> exitImmersiveNative()); return; } if (mBackHandlers.size() > 0) { mBackHandlers.getLast().run(); return; } SessionStore activeStore = SessionManager.get().getActiveStore(); if (activeStore.canGoBack()) { activeStore.goBack(); } else if (activeStore.isPrivateMode()) { activeStore.exitPrivateMode(); } else { super.onBackPressed(); } }
459
public Vector<String> toGo(){ StringBuilder out = new StringBuilder(); out.append("map["); out.append(keyType.toGo()); out.append("]"); out.append(valueType.toGo()); out.append("{"); boolean first = true; for (Map.Entry<Expression, Expression> pair : pairs.entrySet()) { if (first) { first = false; } else { out.append(","); } Vector<String> tmp = pair.getKey().toGo(); for (String s : tmp) { out.append(s); } out.append(":"); tmp = pair.getValue().toGo(); for (String s : tmp) { out.append(s); } } out.append("}"); Vector<String> result = new Vector<>(); result.add(out.toString()); return result; }
public List<String> toGo(){ StringBuilder out = new StringBuilder(); out.append("map["); out.append(keyType.toGo()); out.append("]"); out.append(valueType.toGo()); out.append("{"); boolean first = true; for (Map.Entry<Expression, Expression> pair : pairs.entrySet()) { if (first) { first = false; } else { out.append(","); } List<String> tmp = pair.getKey().toGo(); for (String s : tmp) { out.append(s); } out.append(":"); tmp = pair.getValue().toGo(); for (String s : tmp) { out.append(s); } } out.append("}"); return Collections.singletonList(out.toString()); }
460
public double GetExchangeRate(Currency currency) throws IOException{ double rate = 0; CloseableHttpResponse response = null; try { response = this.httpclient.execute(httpget); switch(response.getStatusLine().getStatusCode()) { case 200: HttpEntity entity = response.getEntity(); InputStream inputStream = response.getEntity().getContent(); var json = new BufferedReader(new InputStreamReader(inputStream)); @SuppressWarnings("deprecation") JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject(); String n = jsonObject.get("bpi").getAsJsonObject().get(currency.toString()).getAsJsonObject().get("rate").getAsString(); NumberFormat nf = NumberFormat.getInstance(); rate = nf.parse(n).doubleValue(); break; default: rate = -1; } } catch (Exception ex) { rate = -1; } finally { response.close(); } return rate; }
public double GetExchangeRate(Currency currency){ double rate = 0; try (CloseableHttpResponse response = this.httpclient.execute(httpget)) { switch(response.getStatusLine().getStatusCode()) { case 200: HttpEntity entity = response.getEntity(); InputStream inputStream = response.getEntity().getContent(); var json = new BufferedReader(new InputStreamReader(inputStream)); @SuppressWarnings("deprecation") JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject(); String n = jsonObject.get("bpi").getAsJsonObject().get(currency.toString()).getAsJsonObject().get("rate").getAsString(); NumberFormat nf = NumberFormat.getInstance(); rate = nf.parse(n).doubleValue(); break; default: rate = -1; } response.close(); } catch (Exception ex) { rate = -1; } return rate; }
461
public void testBatchCopyProcessDefinition() throws Exception{ String projectName = "test"; int targetProjectId = 2; String id = "1"; Map<String, Object> result = new HashMap<>(); putMsg(result, Status.SUCCESS); Mockito.when(processDefinitionService.batchCopyProcessDefinition(user, projectName, id, targetProjectId)).thenReturn(result); Result response = processDefinitionController.copyProcessDefinition(user, projectName, id, targetProjectId); Assert.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); }
public void testBatchCopyProcessDefinition() throws Exception{ String projectName = "test"; int targetProjectId = 2; String id = "1"; Result<Void> result = Result.success(null); Mockito.when(processDefinitionService.batchCopyProcessDefinition(user, projectName, id, targetProjectId)).thenReturn(result); Result response = processDefinitionController.copyProcessDefinition(user, projectName, id, targetProjectId); Assert.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); }
462
public Collection<AuthorDTO> getAuthorsOffBook(Integer bookId){ Collection<AuthorEntity> authorDTOS = dao.getAllAuthorOfBook(bookId); try { return authorDTOS.stream().peek(author -> author.getBooks().size()).map(toDTOFunc).collect(Collectors.toList()); } catch (Exception ex) { ex.printStackTrace(); } return null; }
public Collection<AuthorDTO> getAuthorsOffBook(Integer bookId){ Collection<AuthorEntity> authorDTOS = dao.getAllAuthorOfBook(bookId); return authorDTOS.stream().peek(author -> author.getBooks().size()).map(toDTOFunc).collect(Collectors.toList()); }
463
protected void onResume(){ super.onResume(); final Intent intent = getIntent(); final String locName; if (intent != null) { locName = intent.getStringExtra("name"); if (intent.hasExtra("longitude") && intent.hasExtra("latitude")) { final double longitude = intent.getDoubleExtra("longitude", 0); final double latitude = intent.getDoubleExtra("latitude", 0); this.loc = new GeoPoint(latitude, longitude); if (this.mapController != null) { mapController.animateTo(this.loc); mapController.setZoom(Config.FINAL_ZOOM_LEVEL); this.map.getOverlays().add(new Marker(this, this.loc)); } } } else { locName = null; } }
protected void onResume(){ super.onResume(); final Intent intent = getIntent(); if (intent != null) { if (intent.hasExtra("longitude") && intent.hasExtra("latitude")) { final double longitude = intent.getDoubleExtra("longitude", 0); final double latitude = intent.getDoubleExtra("latitude", 0); this.loc = new GeoPoint(latitude, longitude); if (this.mapController != null) { mapController.animateTo(this.loc); mapController.setZoom(Config.FINAL_ZOOM_LEVEL); this.map.getOverlays().add(new Marker(this, this.loc)); } } } }
464
protected IParticleData makeParticle(){ Color tint = getTint(GeneralUtilities.getRandomNumber(0, 2)); double diameter = getDiameter(GeneralUtilities.getRandomNumber(1.0d, 5.5d)); SmokeBombParticleData smokeBombParticleData = new SmokeBombParticleData(tint, diameter); return smokeBombParticleData; }
protected IParticleData makeParticle(){ Color tint = getTint(GeneralUtilities.getRandomNumber(0, 2)); double diameter = getDiameter(GeneralUtilities.getRandomNumber(1.0d, 5.5d)); return new SmokeBombParticleData(tint, diameter); }
465
public SendSmsResponse sendSms(String templateId, String phoneNumber, HashMap<String, String> personalisation, String reference) throws NotificationClientException{ HttpsURLConnection conn = null; try { JSONObject body = createBodyForSmsRequest(templateId, phoneNumber, personalisation, reference); Authentication tg = new Authentication(); String token = tg.create(serviceId, apiKey); URL url = new URL(baseUrl + "/v2/notifications/sms"); conn = postConnection(token, url); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(body.toString()); wr.flush(); int httpResult = conn.getResponseCode(); if (httpResult == HttpsURLConnection.HTTP_CREATED) { StringBuilder sb = readStream(new InputStreamReader(conn.getInputStream(), "utf-8")); return new SendSmsResponse(sb.toString()); } else { StringBuilder sb = readStream(new InputStreamReader(conn.getErrorStream(), "utf-8")); throw new NotificationClientException(httpResult, sb.toString()); } } catch (IOException e) { LOGGER.log(Level.SEVERE, e.toString(), e); throw new NotificationClientException(e); } finally { if (conn != null) { conn.disconnect(); } } }
public SendSmsResponse sendSms(String templateId, String phoneNumber, HashMap<String, String> personalisation, String reference) throws NotificationClientException{ JSONObject body = createBodyForSmsRequest(templateId, phoneNumber, personalisation, reference); HttpsURLConnection conn = createConnectionAndSetHeaders(baseUrl + "/v2/notifications/sms", "POST"); String response = performPostRequest(conn, body); return new SendSmsResponse(response); }
466
private List<StorageItem> getAllFromCache(T store, Boolean onlyFiles){ StorageItem storageItem = null; List<StorageItem> storageItems = null; String storagePath = getStoragePath(store); if (storagePath != null) { Set<Entry<String, T>> entrySet = FILE_PATH_IMAGE_MAP.entrySet(); for (Iterator<Entry<String, T>> iterator = entrySet.iterator(); iterator.hasNext(); ) { Entry<String, T> entry = iterator.next(); String key = entry.getKey(); if (!key.startsWith(storagePath)) { continue; } String path = key.substring(0, key.lastIndexOf(FILE_SEPARATOR)); if (!path.matches(storagePath)) { continue; } T file = FILE_PATH_IMAGE_MAP.get(key); if (onlyFiles != null) { if ((onlyFiles == Boolean.TRUE && isFolder(file) || (onlyFiles == Boolean.FALSE && !isFolder(file)))) { continue; } } try { if (storageItems == null) { storageItems = new ArrayList<StorageItem>(); } String name = key.substring(storagePath.length() + 1); storageItem = createStorageItem(file); storageItems.add(storageItem); } catch (StorageAccessException storageAccessException) { LOGGER.error(storageAccessException.getMessage(), storageAccessException); } } } return storageItems; }
private List<StorageItem> getAllFromCache(T store, Boolean onlyFiles){ StorageItem storageItem = null; List<StorageItem> storageItems = null; String storagePath = getStoragePath(store); if (storagePath != null) { Set<Entry<String, T>> entrySet = FILE_PATH_IMAGE_MAP.entrySet(); for (Iterator<Entry<String, T>> iterator = entrySet.iterator(); iterator.hasNext(); ) { Entry<String, T> entry = iterator.next(); String key = entry.getKey(); if (!key.startsWith(storagePath)) { continue; } String path = key.substring(0, key.lastIndexOf(FILE_SEPARATOR)); if (!path.matches(storagePath)) { continue; } T file = FILE_PATH_IMAGE_MAP.get(key); if (onlyFiles != null) { if ((onlyFiles == Boolean.TRUE && isFolder(file) || (onlyFiles == Boolean.FALSE && !isFolder(file)))) { continue; } } try { if (storageItems == null) { storageItems = new ArrayList<StorageItem>(); } storageItem = createStorageItem(file); storageItems.add(storageItem); } catch (StorageAccessException storageAccessException) { LOGGER.error(storageAccessException.getMessage(), storageAccessException); } } } return storageItems; }
467
public void activate(boolean redo){ if (SageConstants.ENFORCE_EMBEDDED_RESTRICTIONS && Sage.EMBEDDED && (!System.getProperty("java.version").startsWith("phoneme_advanced") || System.getProperty("os.name").indexOf("Linux") == -1 || System.getProperty("os.version").indexOf("sigma") == -1) && Math.random() < 0.05) System.exit(0); active = true; if (!comp.hasFreshlyLoadedContext() && !redo) comp.reloadAttributeContext(); Catbert.processUISpecificHook("BeforeMenuLoad", new Object[] { Boolean.valueOf(redo) }, uiMgr, false); if (!active) { comp.unfreshAttributeContext(); return; } comp.setMenuLoadedState(true); comp.evaluateTree(true, false); comp.evaluateTree(false, true); comp.recalculateDynamicFonts(); comp.invalidateAll(); if (comp.getWidth() > 0 && comp.getHeight() > 0) comp.doLayout(); if ((comp.hasFocusableChildren() || uiMgr.allowHiddenFocus()) && (!redo || !comp.doesHierarchyHaveFocus())) { Catbert.processUISpecificHook("MenuNeedsDefaultFocus", new Object[] { Boolean.valueOf(redo) }, uiMgr, false); if (!comp.doesHierarchyHaveFocus()) { if (!comp.checkForcedFocus()) comp.setDefaultFocus(); } } int numTextInputs = comp.getNumTextInputs(0); multipleTextInputs = numTextInputs > 1; uiMgr.getRootPanel().getRenderEngine().setMenuHint(widg.getName(), null, numTextInputs > 0); }
public void activate(boolean redo){ active = true; if (!comp.hasFreshlyLoadedContext() && !redo) comp.reloadAttributeContext(); Catbert.processUISpecificHook("BeforeMenuLoad", new Object[] { Boolean.valueOf(redo) }, uiMgr, false); if (!active) { comp.unfreshAttributeContext(); return; } comp.setMenuLoadedState(true); comp.evaluateTree(true, false); comp.evaluateTree(false, true); comp.recalculateDynamicFonts(); comp.invalidateAll(); if (comp.getWidth() > 0 && comp.getHeight() > 0) comp.doLayout(); if ((comp.hasFocusableChildren() || uiMgr.allowHiddenFocus()) && (!redo || !comp.doesHierarchyHaveFocus())) { Catbert.processUISpecificHook("MenuNeedsDefaultFocus", new Object[] { Boolean.valueOf(redo) }, uiMgr, false); if (!comp.doesHierarchyHaveFocus()) { if (!comp.checkForcedFocus()) comp.setDefaultFocus(); } } int numTextInputs = comp.getNumTextInputs(0); multipleTextInputs = numTextInputs > 1; uiMgr.getRootPanel().getRenderEngine().setMenuHint(widg.getName(), null, numTextInputs > 0); }
468
public void testMissingLowerCorner() throws CswException{ HierarchicalStreamReader reader = mock(HierarchicalStreamReader.class); Stack<String> boundingBoxNodes = new Stack<String>(); boundingBoxNodes.push("-2.228 51.126"); boundingBoxNodes.push("UpperCorner"); boundingBoxNodes.push("-6.171 44.792"); boundingBoxNodes.push("MISSING LOWER CORNER"); boundingBoxNodes.push("BoundingBox"); boundingBoxNodes.push("BoundingBox"); Answer<String> answer = new Answer<String>() { @Override public String answer(InvocationOnMock invocationOnMock) throws Throwable { return boundingBoxNodes.pop(); } }; when(reader.getNodeName()).thenAnswer(answer); when(reader.getValue()).thenAnswer(answer); BoundingBoxReader boundingBoxReader = new BoundingBoxReader(reader, CswAxisOrder.LON_LAT); boundingBoxReader.getWkt(); }
public void testMissingLowerCorner() throws CswException{ HierarchicalStreamReader reader = mock(HierarchicalStreamReader.class); Stack<String> boundingBoxNodes = new Stack<>(); boundingBoxNodes.push("-2.228 51.126"); boundingBoxNodes.push("UpperCorner"); boundingBoxNodes.push("-6.171 44.792"); boundingBoxNodes.push("MISSING LOWER CORNER"); boundingBoxNodes.push("BoundingBox"); boundingBoxNodes.push("BoundingBox"); Answer<String> answer = invocationOnMock -> boundingBoxNodes.pop(); when(reader.getNodeName()).thenAnswer(answer); when(reader.getValue()).thenAnswer(answer); BoundingBoxReader boundingBoxReader = new BoundingBoxReader(reader, CswAxisOrder.LON_LAT); boundingBoxReader.getWkt(); }
469
public void onDataChange(@NonNull DataSnapshot snapshot){ if (snapshot.hasChild(Database.CHILD_DISCOVERED_PEAKS)) syncGetDiscoveredPeaksFromProfile(snapshot.child(Database.CHILD_DISCOVERED_PEAKS)); else discoveredPeaks = new HashSet<>(); if (snapshot.hasChild(Database.CHILD_USERNAME)) syncGetUsernameFromProfile(snapshot.child(Database.CHILD_USERNAME).getValue(String.class)); else username = "null"; if (snapshot.hasChild(Database.CHILD_FRIENDS)) syncFriendsFromProfile(snapshot.child(Database.CHILD_FRIENDS)); else friends = new ArrayList<>(); if (snapshot.hasChild(Database.CHILD_SCORE)) syncGetUserScoreFromProfile(snapshot.child(Database.CHILD_SCORE).getValue(long.class)); else score = 0; if (snapshot.hasChild(Database.CHILD_COUNTRY_HIGH_POINT)) syncGetCountryHighPointsFromProfile(snapshot.child(Database.CHILD_COUNTRY_HIGH_POINT)); else discoveredCountryHighPoint = new HashMap<String, CountryHighPoint>(); if (snapshot.hasChild(Database.CHILD_DISCOVERED_PEAKS_HEIGHTS)) syncGetDiscoveredHeight(snapshot.child(Database.CHILD_DISCOVERED_PEAKS_HEIGHTS)); else discoveredPeakHeights = new HashSet<>(); }
public void onDataChange(@NonNull DataSnapshot snapshot){ if (snapshot.hasChild(Database.CHILD_DISCOVERED_PEAKS)) syncGetDiscoveredPeaksFromProfile(snapshot.child(Database.CHILD_DISCOVERED_PEAKS)); else discoveredPeaks = new HashSet<>(); if (snapshot.hasChild(Database.CHILD_USERNAME)) syncGetUsernameFromProfile(snapshot.child(Database.CHILD_USERNAME).getValue(String.class)); else username = "null"; syncFriendsFromProfile(snapshot.child(Database.CHILD_FRIENDS)); if (snapshot.hasChild(Database.CHILD_SCORE)) syncGetUserScoreFromProfile(snapshot.child(Database.CHILD_SCORE).getValue(long.class)); else score = 0; if (snapshot.hasChild(Database.CHILD_COUNTRY_HIGH_POINT)) syncGetCountryHighPointsFromProfile(snapshot.child(Database.CHILD_COUNTRY_HIGH_POINT)); else discoveredCountryHighPoint = new HashMap<String, CountryHighPoint>(); if (snapshot.hasChild(Database.CHILD_DISCOVERED_PEAKS_HEIGHTS)) syncGetDiscoveredHeight(snapshot.child(Database.CHILD_DISCOVERED_PEAKS_HEIGHTS)); else discoveredPeakHeights = new HashSet<>(); }
470
public Value visit(Division value){ Value left = value.getLeft().accept(this); Value right = value.getRight().accept(this); if (debug) { System.out.println("Division"); } return left.division(right); }
public Value visit(Division value){ Value left = value.getLeft().accept(this); Value right = value.getRight().accept(this); return left.division(right); }
471
public Car fetching(Ticket ticket){ Car car = null; if (ticket == null) { FailMsg.FAIL_MSG.setMsg("Please provide your parking ticket."); notifyObserver("Please provide your parking ticket.", this); return car; } if (!ticket.isValid() || ticket.getState() == TicketState.usedTicket.getIndex()) { FailMsg.FAIL_MSG.setMsg("Unrecognized parking ticket."); notifyObserver("Unrecognized parking ticket.", this); return car; } for (ParkingLot parkingLot : parkingLotList) { if (ticket.getParkingLotID() == parkingLot.getID()) { if (parkingLot.getCarByID(ticket.getCarID()).getState() == CarState.parkedCar.getIndex()) { car = parkingLot.fetching(ticket); ticket.setState(TicketState.usedTicket.getIndex()); return car; } } } return car; }
public Car fetching(Ticket ticket){ Car car = null; if (ticket == null) { FailMsg.FAIL_MSG.setMsg("Please provide your parking ticket."); notifyObserver("Please provide your parking ticket.", this); return car; } if (!ticket.isValid() || ticket.getState() == TicketState.usedTicket.getIndex()) { FailMsg.FAIL_MSG.setMsg("Unrecognized parking ticket."); notifyObserver("Unrecognized parking ticket.", this); return car; } ParkingLot parkingLot = parkingLotList.stream().filter(item -> item.getID() == ticket.getParkingLotID()).findFirst().get(); if (parkingLot.getCarByID(ticket.getCarID()).getState() == CarState.parkedCar.getIndex()) { car = parkingLot.fetching(ticket); ticket.setState(TicketState.usedTicket.getIndex()); return car; } return car; }
472
protected UUID execute(){ return null; }
protected void execute(){ }
473
public void delete(String topic, boolean force, boolean deleteSchema) throws PulsarAdminException{ try { deleteAsync(topic, force, deleteSchema).get(this.readTimeoutMs, TimeUnit.MILLISECONDS); } catch (ExecutionException e) { throw (PulsarAdminException) e.getCause(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new PulsarAdminException(e); } catch (TimeoutException e) { throw new PulsarAdminException.TimeoutException(e); } }
public void delete(String topic, boolean force, boolean deleteSchema) throws PulsarAdminException{ sync(() -> deleteAsync(topic, force, deleteSchema)); }
474
private void saveScreenshotAndToast(Consumer<Uri> finisher){ mScreenshotHandler.post(() -> { switch(mAudioManager.getRingerMode()) { case AudioManager.RINGER_MODE_SILENT: break; case AudioManager.RINGER_MODE_VIBRATE: if (mVibrator != null && mVibrator.hasVibrator()) { mVibrator.vibrate(VibrationEffect.createOneShot(50, VibrationEffect.DEFAULT_AMPLITUDE)); } break; case AudioManager.RINGER_MODE_NORMAL: mCameraSound.play(MediaActionSound.SHUTTER_CLICK); break; } }); saveScreenshotInWorkerThread(finisher, new ActionsReadyListener() { @Override void onActionsReady(SavedImageData imageData) { finisher.accept(imageData.uri); if (imageData.uri == null) { mUiEventLogger.log(ScreenshotEvent.SCREENSHOT_NOT_SAVED); mNotificationsController.notifyScreenshotError(R.string.screenshot_failed_to_capture_text); } else { mUiEventLogger.log(ScreenshotEvent.SCREENSHOT_SAVED); mScreenshotHandler.post(() -> { Toast.makeText(mContext, R.string.screenshot_saved_title, Toast.LENGTH_SHORT).show(); }); } } }); }
private void saveScreenshotAndToast(Consumer<Uri> finisher){ mScreenshotHandler.post(() -> { playShutterSound(); }); saveScreenshotInWorkerThread(finisher, new ActionsReadyListener() { @Override void onActionsReady(SavedImageData imageData) { finisher.accept(imageData.uri); if (imageData.uri == null) { mUiEventLogger.log(ScreenshotEvent.SCREENSHOT_NOT_SAVED); mNotificationsController.notifyScreenshotError(R.string.screenshot_failed_to_capture_text); } else { mUiEventLogger.log(ScreenshotEvent.SCREENSHOT_SAVED); mScreenshotHandler.post(() -> { Toast.makeText(mContext, R.string.screenshot_saved_title, Toast.LENGTH_SHORT).show(); }); } } }); }
475
private SourceResponse createSourceResponse(GetRecordsType request, int resultCount){ int first = 1; int last = 2; int max = 0; if (request != null) { first = request.getStartPosition().intValue(); max = request.getMaxRecords().intValue(); int next = request.getMaxRecords().intValue() + first; last = next - 1; if (last >= resultCount) { last = resultCount; next = 0; } } int returned = last - first + 1; QueryImpl query = new QueryImpl(filter, first, max, null, true, 0); SourceResponseImpl sourceResponse = new SourceResponseImpl(new QueryRequestImpl(query), createResults(first, last)); sourceResponse.setHits(resultCount); return sourceResponse; }
private SourceResponse createSourceResponse(GetRecordsType request, int resultCount){ int first = 1; int last = 2; int max = 0; if (request != null) { first = request.getStartPosition().intValue(); max = request.getMaxRecords().intValue(); int next = request.getMaxRecords().intValue() + first; last = next - 1; if (last >= resultCount) { last = resultCount; } } QueryImpl query = new QueryImpl(filter, first, max, null, true, 0); SourceResponseImpl sourceResponse = new SourceResponseImpl(new QueryRequestImpl(query), createResults(first, last)); sourceResponse.setHits(resultCount); return sourceResponse; }
476
public Response get(){ EntityManager entityManager1 = EntityManagerListener.createEntityManager(); EntityManager entityManager2 = EntityManagerListener.createEntityManager(); EntityTransaction transaction = null; try { StatelessSession session = entityManager1.unwrap(Session.class).getSessionFactory().openStatelessSession(); final EntityTransaction finalTransaction = session.beginTransaction(); transaction = finalTransaction; Query contextQuery = session.createQuery("SELECT c.id FROM Context c ORDER BY c.keyword, c.location"); contextQuery.setReadOnly(true).setCacheable(false).setFetchSize(Integer.MIN_VALUE); ScrollableResults results = contextQuery.scroll(ScrollMode.FORWARD_ONLY); StreamingOutput streamingOutput = new StreamingOutput() { @Override public void write(OutputStream outputStream) throws IOException, WebApplicationException { JsonGenerator jsonGenerator = new ObjectMapper().configure(MapperFeature.USE_ANNOTATIONS, true).getFactory().createGenerator(outputStream, JsonEncoding.UTF8); jsonGenerator.writeStartArray(); while (results.next()) { Context context = entityManager2.find(Context.class, results.get(0)); jsonGenerator.writeObject(context); } jsonGenerator.writeEndArray(); jsonGenerator.flush(); jsonGenerator.close(); entityManager2.close(); results.close(); finalTransaction.commit(); } }; return Response.ok(streamingOutput).type(MediaType.APPLICATION_JSON).header("Content-Disposition", "attachment; filename=\"contexts.json\"").build(); } catch (RuntimeException e) { e.printStackTrace(); if (transaction != null && transaction.isActive()) { transaction.rollback(); } throw e; } finally { entityManager1.close(); } }
public Response get(){ EntityManager entityManager = EntityManagerListener.createEntityManager(); EntityTransaction transaction = null; try { StatelessSession session = entityManager.unwrap(Session.class).getSessionFactory().openStatelessSession(); transaction = session.beginTransaction(); Query query = session.createQuery("SELECT DISTINCT c.keyword FROM Context c ORDER BY c.keyword"); query.setReadOnly(true).setCacheable(false).setFetchSize(Integer.MIN_VALUE); ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY); StreamingOutput streamingOutput = new StreamingOutput() { @Override public void write(OutputStream outputStream) throws IOException, WebApplicationException { JsonGenerator jsonGenerator = new ObjectMapper().configure(MapperFeature.USE_ANNOTATIONS, true).getFactory().createGenerator(outputStream, JsonEncoding.UTF8); jsonGenerator.writeStartArray(); while (results.next()) { writeJsonResult(jsonGenerator, results.getString(0)); } jsonGenerator.writeEndArray(); jsonGenerator.flush(); jsonGenerator.close(); results.close(); session.getTransaction().commit(); } }; return Response.ok(streamingOutput).type("text/json").header("Content-Disposition", "attachment; filename=\"contexts.json\"").build(); } catch (RuntimeException e) { e.printStackTrace(); if (transaction != null && transaction.isActive()) { transaction.rollback(); } throw e; } finally { entityManager.close(); } }
477
public boolean equals(Object obj){ if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final OAuth2AllowDomain other = (OAuth2AllowDomain) obj; if (!Objects.equals(this.id, other.id)) { return false; } return true; }
public boolean equals(Object obj){ return ObjectEquals.of(this).equals(obj, (origin, other) -> { return Objects.equals(origin.getId(), other.getId()); }); }
478
public PowerShellResponse executeScript(String scriptPath, String params){ BufferedReader srcReader = null; File scriptToExecute = new File(scriptPath); if (!scriptToExecute.exists()) { return new PowerShellResponse(true, "Wrong script path: " + scriptToExecute, false); } try { srcReader = new BufferedReader(new FileReader(scriptToExecute)); } catch (FileNotFoundException fnfex) { Logger.getLogger(PowerShell.class.getName()).log(Level.SEVERE, "Unexpected error when processing PowerShell script: file not found", fnfex); } File tmpFile = createWriteTempFile(srcReader); if (tmpFile != null) { this.scriptMode = true; return executeCommand(tmpFile.getAbsolutePath() + " " + params); } else { return new PowerShellResponse(true, "Cannot create temp script file", false); } }
public PowerShellResponse executeScript(String scriptPath, String params){ BufferedReader srcReader = null; File scriptToExecute = new File(scriptPath); if (!scriptToExecute.exists()) { return new PowerShellResponse(true, "Wrong script path: " + scriptToExecute, false); } try { srcReader = new BufferedReader(new FileReader(scriptToExecute)); } catch (FileNotFoundException fnfex) { Logger.getLogger(PowerShell.class.getName()).log(Level.SEVERE, "Unexpected error when processing PowerShell script: file not found", fnfex); } return executeScript(srcReader, params); }
479
protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_restaurant); setupToolbar(); setupViewPager(); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show(); } }); }
protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_restaurant); setupToolbar(); setupViewPager(); }
480
boolean isSink(Board board, Computer computer){ int shipCoordinatesHit = 0; int isShipHit = 1; for (int xPositionOfShip = shipLocation[0]; xPositionOfShip <= shipLocation[2]; xPositionOfShip++) { for (int yPositionOfShip = shipLocation[1]; yPositionOfShip <= shipLocation[3]; yPositionOfShip++) { if (board.board[xPositionOfShip][yPositionOfShip].equals(board.hit)) shipCoordinatesHit++; else { isShipHit = 0; break; } } if (isShipHit == 0) { break; } } if (shipCoordinatesHit == shipSize) { sinkShip(board); computer.listOfShipsOnBoard.remove(this); System.out.println("Number of ships remaining : " + computer.listOfShipsOnBoard.size()); return true; } return false; }
boolean isSink(Board board, Computer computer){ int shipCoordinatesHit = 0; int isShipHit = 1; for (int xPositionOfShip = shipLocation[0]; xPositionOfShip <= shipLocation[2]; xPositionOfShip++) { for (int yPositionOfShip = shipLocation[1]; yPositionOfShip <= shipLocation[3]; yPositionOfShip++) { if (board.board[xPositionOfShip][yPositionOfShip].equals(board.hit)) shipCoordinatesHit++; else { isShipHit = 0; break; } } if (isShipHit == 0) { break; } } if (shipCoordinatesHit == shipSize) { sinkShip(board); computer.listOfShipsOnBoard.remove(this); return true; } return false; }
481
public void transactions(ThreadState state) throws IOException{ ClassLoader classLoader = getClass().getClassLoader(); BufferedReader reader = TestUtil.getExportedTransactionFile(classLoader, "insynSample1.csv"); Stream<Transaction> transactions = state.registry.parseTransactionResponse(reader); long nofTransactions = transactions.count(); System.out.println("Number of transactions: " + nofTransactions); }
public void transactions(ThreadState state) throws IOException{ ClassLoader classLoader = getClass().getClassLoader(); BufferedReader reader = TestUtil.getExportedTransactionFile(classLoader, "insynSample1.csv"); Stream<Transaction> transactions = state.registry.parseTransactionResponse(reader); long nofTransactions = transactions.count(); }
482
private int inflate(byte[] b, int off, int len) throws DataFormatException, ZipException{ checkState(inflater != null, "inflater is null"); try { int inflaterTotalIn = inflater.getTotalIn(); int n = inflater.inflate(b, off, len); int bytesConsumedDelta = inflater.getTotalIn() - inflaterTotalIn; bytesConsumed += bytesConsumedDelta; deflatedBytesConsumed += bytesConsumedDelta; inflaterInputStart += bytesConsumedDelta; crc.update(b, off, n); if (inflater.finished()) { expectedGzipTrailerIsize = (inflater.getBytesWritten() & 0xffffffffL); if (gzipMetadataReader.readableBytes() <= GZIP_HEADER_MIN_SIZE + GZIP_TRAILER_SIZE) { inflater.end(); inflater = null; } state = State.TRAILER; } else if (inflater.needsInput()) { state = State.INFLATER_NEEDS_INPUT; } return n; } catch (DataFormatException e) { throw new DataFormatException("Inflater data format exception: " + e.getMessage()); } }
private int inflate(byte[] b, int off, int len) throws DataFormatException, ZipException{ checkState(inflater != null, "inflater is null"); try { int inflaterTotalIn = inflater.getTotalIn(); int n = inflater.inflate(b, off, len); int bytesConsumedDelta = inflater.getTotalIn() - inflaterTotalIn; bytesConsumed += bytesConsumedDelta; deflatedBytesConsumed += bytesConsumedDelta; inflaterInputStart += bytesConsumedDelta; crc.update(b, off, n); if (inflater.finished()) { expectedGzipTrailerIsize = (inflater.getBytesWritten() & 0xffffffffL); state = State.TRAILER; } else if (inflater.needsInput()) { state = State.INFLATER_NEEDS_INPUT; } return n; } catch (DataFormatException e) { throw new DataFormatException("Inflater data format exception: " + e.getMessage()); } }
483
public double calculateFare(double distance, int time){ double totalFare = distance * MIN_COST_PER_KM + time * COST_PER_MIN; if (totalFare < MINIMUM_FARE) return MINIMUM_FARE; else return totalFare; }
public double calculateFare(double distance, int time){ double totalFare = distance * MIN_COST_PER_KM + time * COST_PER_MIN; return Math.max(totalFare, MINIMUM_FARE); }
484
public void values(){ assertEquals(map.values(), mapOrig.values()); }
public void values(){ }
485
private static void sendFile(InputStream file, OutputStream out){ System.out.println("Starting file sending"); try { byte[] buffer = new byte[1024 * 1024]; int i = 0; while (file.available() > 0) { out.write(buffer, 0, file.read(buffer)); System.out.println(String.format("[HTTP Server] Send file:I väärtus %s", String.valueOf(i))); i++; } System.out.println("File sending is complete"); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
private static void sendFile(InputStream file, OutputStream out){ System.out.println("Starting file sending"); try { byte[] buffer = new byte[1024 * 1024]; int i = 0; while (file.available() > 0) { out.write(buffer, 0, file.read(buffer)); System.out.println(String.format("[HTTP Server] Send file:I väärtus %s", String.valueOf(i))); i++; } System.out.println("File sending is complete"); } catch (IOException e) { e.printStackTrace(); } }
486
public static int getNeuronCount(){ int count = -1; final OkHttpClient client = new OkHttpClient(); final MediaType mediaType = MediaType.parse("application/json"); final RequestBody body = RequestBody.create(mediaType, "{\"query\":\"{systemSettings{neuronCount}}\"}"); final Request request = new Request.Builder().url("https://ml-neuronbrowser.janelia.org/graphql").post(body).addHeader("Content-Type", "application/json").addHeader("cache-control", "no-cache").build(); try { final Response response = client.newCall(request).execute(); final JSONObject json = new JSONObject(response.body().string()); count = json.getJSONObject("data").getJSONObject("systemSettings").getInt("neuronCount"); } catch (IOException | JSONException ignored) { } return count; }
public static int getNeuronCount(){ int count = -1; final OkHttpClient client = new OkHttpClient(); final RequestBody body = RequestBody.create("{\"query\":\"{systemSettings{neuronCount}}\"}", MEDIA_TYPE); final Request request = new Request.Builder().url("https://ml-neuronbrowser.janelia.org/graphql").post(body).addHeader("Content-Type", "application/json").addHeader("cache-control", "no-cache").build(); try { final Response response = client.newCall(request).execute(); final JSONObject json = new JSONObject(response.body().string()); count = json.getJSONObject("data").getJSONObject("systemSettings").getInt("neuronCount"); } catch (IOException | JSONException ignored) { } return count; }
487
private LibrisDatabase buildTestDatabase(File testDatabaseFileCopy) throws IOException{ rootDb = null; ui = null; try { rootDb = Libris.buildAndOpenDatabase(testDatabaseFileCopy); ui = rootDb.getUi(); } catch (Throwable e) { e.printStackTrace(); fail("Cannot open database"); } return rootDb; }
private LibrisDatabase buildTestDatabase(File testDatabaseFileCopy) throws IOException{ rootDb = null; try { rootDb = Libris.buildAndOpenDatabase(testDatabaseFileCopy); rootDb.getUi(); } catch (Throwable e) { e.printStackTrace(); fail("Cannot open database"); } return rootDb; }
488
protected Boolean doInBackground(AuthParams... authParamses){ AuthParams authParams = authParamses[0]; if (authParams == null) { return false; } int slotNumber = authParams.getSlotNumber(); final NFCReader reader = authParams.getReader(); LoadAuthentication load = new LoadAuthentication(reader); if (authParams.getKeyA() != null && !"".equals(authParams.getKeyA())) { Log.d(TAG, authParams.getKeyA().getClass().getName()); Log.d(TAG, authParams.getKeyA()); Log.d(TAG, Util.toHexString(Util.toNFCByte(authParams.getKeyA(), 6))); load.setPassword(authParams.getKeyA()); load.setOnGetResultListener(authParams.getOnGetResultListener()); if (!load.run(slotNumber)) { return false; } Authentication auth = new Authentication(reader, authParams.getBlock(), Authentication.KEY_A); auth.setOnGetResultListener(authParams.getOnGetResultListener()); if (!auth.run(slotNumber)) { return false; } } return true; }
protected Boolean doInBackground(AuthParams... authParamses){ AuthParams authParams = authParamses[0]; if (authParams == null) { return false; } LoadAuthentication load = new LoadAuthentication(authParams); if (authParams.getKeyA() != null && !"".equals(authParams.getKeyA())) { Log.d(TAG, authParams.getKeyA().getClass().getName()); Log.d(TAG, authParams.getKeyA()); Log.d(TAG, Util.toHexString(Util.toNFCByte(authParams.getKeyA(), 6))); if (!load.run()) { return false; } Authentication auth = new Authentication(authParams); if (!auth.run()) { return false; } } return true; }
489
private boolean checkForUpdates(boolean force){ if (force || (Math.abs(System.currentTimeMillis() - prefs.getLong(PREF_LAST_CHECK_ATTEMPT_TIME_NAME, PREF_LAST_CHECK_ATTEMPT_TIME_DEFAULT)) > CHECK_THRESHOLD_MS)) { if (onWantUpdateCheckListener != null) { if (onWantUpdateCheckListener.onWantUpdateCheck()) { prefs.edit().putLong(PREF_LAST_CHECK_ATTEMPT_TIME_NAME, System.currentTimeMillis()).commit(); } } } else { Logger.i("Skip checkForUpdates"); } return false; }
private void checkForUpdates(boolean force){ if (force || (Math.abs(System.currentTimeMillis() - prefs.getLong(PREF_LAST_CHECK_ATTEMPT_TIME_NAME, PREF_LAST_CHECK_ATTEMPT_TIME_DEFAULT)) > CHECK_THRESHOLD_MS)) { if (onWantUpdateCheckListener != null) { if (onWantUpdateCheckListener.onWantUpdateCheck()) { prefs.edit().putLong(PREF_LAST_CHECK_ATTEMPT_TIME_NAME, System.currentTimeMillis()).commit(); } } } else { Logger.i("Skip checkForUpdates"); } }
490
public void shouldBeAbleToDisplayUserHistoryForDefaulters(){ Book book = new Book("Raj", "Comics", 2000); HashMap<String, Book> bookUserHistory = new HashMap<String, Book>(); bookUserHistory.put("user333", book); Movie movie = new Movie("Art Of living", 1945, "Director", 4); HashMap<String, Movie> movieUserHistory = new HashMap<String, Movie>(); movieUserHistory.put("user222", movie); userHistory = new UserHistory(bookUserHistory, movieUserHistory); String actualOutput = userHistory.toString(); System.out.println(actualOutput); String expectedOutput = "\nuser222: \nArt Of living\tDirector\t1945\trating:4\nuser333: Raj\tComics\t2000"; assertThat(actualOutput, is(expectedOutput)); }
public void shouldBeAbleToDisplayUserHistoryForDefaulters(){ Book book = new Book("Raj", "Comics", 2000); HashMap<String, Book> bookUserHistory = new HashMap<String, Book>(); bookUserHistory.put("user333", book); Movie movie = new Movie("Art Of living", 1945, "Director", 4); HashMap<String, Movie> movieUserHistory = new HashMap<String, Movie>(); movieUserHistory.put("user222", movie); userHistory = new UserHistory(bookUserHistory, movieUserHistory); String actualOutput = userHistory.toString(); String expectedOutput = "\nuser222: \nArt Of living\tDirector\t1945\trating:4\nuser333: Raj\tComics\t2000"; assertThat(actualOutput, is(expectedOutput)); }
491
public static MaterialShowcaseView.Builder createSequenceItem(final Activity mainAct, int idTargetView, String tooltipText, String title, CharSequence content, IShowcaseListener showcaseListener){ ShowcaseTooltip tooltip = ShowcaseTooltip.build(mainAct).arrowHeight(30).corner(30).textColor(Color.parseColor("#007686")).textSize(TypedValue.COMPLEX_UNIT_SP, 16).text("<b>" + tooltipText + "</b>"); int darkGreen = mainAct.getResources().getColor(R.color.dark_green); MaterialShowcaseView.Builder builder = new MaterialShowcaseView.Builder(mainAct).setTitleText(title).setSkipText(mainAct.getString(R.string.cancel_tourguide)).setTarget(mainAct.findViewById(idTargetView)).setDismissText(mainAct.getString(R.string.tieptuc)).setSkipBtnBackground(darkGreen, Color.BLACK).setDismissBtnBackground(darkGreen, Color.BLACK).setContentText(content).setContentTextColor(mainAct.getResources().getColor(R.color.green)).setToolTip(tooltip).setListener(showcaseListener).setShapePadding(10); return builder; }
public static MaterialShowcaseView.Builder createSequenceItem(final Activity mainAct, int idTargetView, String tooltipText, String title, CharSequence content, IShowcaseListener showcaseListener){ ShowcaseTooltip tooltip = ShowcaseTooltip.build(mainAct).arrowHeight(30).corner(30).textColor(Color.parseColor("#007686")).textSize(TypedValue.COMPLEX_UNIT_SP, 16).text("<b>" + tooltipText + "</b>"); int darkGreen = mainAct.getResources().getColor(R.color.dark_green); return new MaterialShowcaseView.Builder(mainAct).setTitleText(title).setSkipText(mainAct.getString(R.string.cancel_tourguide)).setTarget(mainAct.findViewById(idTargetView)).setDismissText(mainAct.getString(R.string.tieptuc)).setSkipBtnBackground(darkGreen, Color.BLACK).setDismissBtnBackground(darkGreen, Color.BLACK).setContentText(content).setContentTextColor(mainAct.getResources().getColor(R.color.green)).setToolTip(tooltip).setListener(showcaseListener).setShapePadding(10); }
492
private void convertChildRelation(SubProcess subProcess, TSubProcess tSubProcess, Hashtable context){ if (subProcess.getSequenceFlows() != null && subProcess.getSequenceFlows().size() > 0) { for (SequenceFlow subProcessSequenceFlow : subProcess.getSequenceFlows()) { SequenceFlowAdapter sequenceFlowAdapter = new SequenceFlowAdapter(); sequenceFlowAdapter.setChildActivities(subProcess.getChildActivities()); try { TSequenceFlow subProcessTSequenceFlow = sequenceFlowAdapter.convert(subProcessSequenceFlow, context); if (tSubProcess.getFlowElement() != null && tSubProcess.getFlowElement().size() > 0) { List<JAXBElement<? extends TFlowElement>> listTFlowElement = tSubProcess.getFlowElement(); for (JAXBElement<? extends TFlowElement> tFlowElement : listTFlowElement) { if (tFlowElement.getValue().getId().equals(subProcessSequenceFlow.getSourceRef())) { subProcessTSequenceFlow.setSourceRef(tFlowElement.getValue()); } if (tFlowElement.getValue().getId().equals(subProcessSequenceFlow.getTargetRef())) { subProcessTSequenceFlow.setTargetRef(tFlowElement.getValue()); } } } if (subProcessSequenceFlow.getCondition() != null) { ConditionAdapter conditionAdapter = new ConditionAdapter(); try { TExpression tExpression = conditionAdapter.convert(subProcessSequenceFlow.getCondition(), null); subProcessTSequenceFlow.setConditionExpression(tExpression); } catch (Exception e) { e.printStackTrace(); } } JAXBElement<TSequenceFlow> subProcessSequenceShapeElement = ObjectFactoryUtil.createDefaultJAXBElement(TSequenceFlow.class, subProcessTSequenceFlow); tSubProcess.getFlowElement().add(subProcessSequenceShapeElement); } catch (Exception e) { e.printStackTrace(); } } } }
private void convertChildRelation(SubProcess subProcess, TSubProcess tSubProcess, Hashtable context){ if (subProcess.getSequenceFlows() != null && subProcess.getSequenceFlows().size() > 0) { for (SequenceFlow subProcessSequenceFlow : subProcess.getSequenceFlows()) { context.put("childActivities", subProcess.getChildActivities()); try { TSequenceFlow subProcessTSequenceFlow = (TSequenceFlow) BPMNUtil.exportAdapt(subProcessSequenceFlow, context); if (tSubProcess.getFlowElement() != null && tSubProcess.getFlowElement().size() > 0) { List<JAXBElement<? extends TFlowElement>> listTFlowElement = tSubProcess.getFlowElement(); for (JAXBElement<? extends TFlowElement> tFlowElement : listTFlowElement) { if (tFlowElement.getValue().getId().equals(subProcessSequenceFlow.getSourceRef())) { subProcessTSequenceFlow.setSourceRef(tFlowElement.getValue()); } if (tFlowElement.getValue().getId().equals(subProcessSequenceFlow.getTargetRef())) { subProcessTSequenceFlow.setTargetRef(tFlowElement.getValue()); } } } if (subProcessSequenceFlow.getCondition() != null) { try { TExpression tExpression = (TExpression) BPMNUtil.exportAdapt(subProcessSequenceFlow.getCondition()); subProcessTSequenceFlow.setConditionExpression(tExpression); } catch (Exception e) { e.printStackTrace(); } } JAXBElement<TSequenceFlow> subProcessSequenceShapeElement = ObjectFactoryUtil.createDefaultJAXBElement(TSequenceFlow.class, subProcessTSequenceFlow); tSubProcess.getFlowElement().add(subProcessSequenceShapeElement); } catch (Exception e) { e.printStackTrace(); } } } }
493
public Key max(){ if (isEmpty()) throw new NoSuchElementException("calls max() with empty symbol table"); return st.lastKey(); }
public Key max(){ noSuchElement(isEmpty(), "calls max() with empty symbol table"); return st.lastKey(); }
494
Label updateCurrentBlockForJumpInstruction(int opcode, @Nonnull Label label){ Label nextInsn = null; if (currentBlock != null) { if (computeFrames) { currentBlock.frame.executeJUMP(opcode); label.getFirst().markAsTarget(); addSuccessor(Edge.NORMAL, label); if (opcode != GOTO) { nextInsn = new Label(); } } else { if (opcode == JSR) { if (label.markAsSubroutine()) { subroutines++; } currentBlock.markAsJSR(); addSuccessor(stackSize + 1, label); nextInsn = new Label(); } else { stackSize += Frame.SIZE[opcode]; addSuccessor(stackSize, label); } } } return nextInsn; }
Label updateCurrentBlockForJumpInstruction(int opcode, @Nonnull Label label){ Label nextInsn = null; if (currentBlock != null) { if (computeFrames) { currentBlock.frame.executeJUMP(opcode); label.getFirst().markAsTarget(); addSuccessor(Edge.NORMAL, label); if (opcode != GOTO) { nextInsn = new Label(); } } else { stackSize += Frame.SIZE[opcode]; addSuccessor(stackSize, label); } } return nextInsn; }
495
public int onStartCommand(Intent intent, int flags, int startId){ Log_OC.d(TAG, "Starting command " + intent); if (intent == null || ACTION_START_OBSERVE.equals(intent.getAction())) { startObservation(); return Service.START_STICKY; } else if (ACTION_ADD_OBSERVED_FILE.equals(intent.getAction())) { OCFile file = intent.getParcelableExtra(ARG_FILE); Account account = intent.getParcelableExtra(ARG_ACCOUNT); addObservedFile(file, account); } else if (ACTION_DEL_OBSERVED_FILE.equals(intent.getAction())) { removeObservedFile((OCFile) intent.getParcelableExtra(ARG_FILE), (Account) intent.getParcelableExtra(ARG_ACCOUNT)); } else if (ACTION_UPDATE_AUTO_UPLOAD_OBSERVERS.equals(intent.getAction())) { } else { Log_OC.e(TAG, "Unknown action received; ignoring it: " + intent.getAction()); } return Service.START_STICKY; }
public int onStartCommand(Intent intent, int flags, int startId){ Log_OC.d(TAG, "Starting command " + intent); if (intent == null || ACTION_START_OBSERVE.equals(intent.getAction())) { startObservation(); return Service.START_STICKY; } else if (ACTION_ADD_OBSERVED_FILE.equals(intent.getAction())) { OCFile file = intent.getParcelableExtra(ARG_FILE); Account account = intent.getParcelableExtra(ARG_ACCOUNT); addObservedFile(file, account); } else if (ACTION_DEL_OBSERVED_FILE.equals(intent.getAction())) { removeObservedFile((OCFile) intent.getParcelableExtra(ARG_FILE), (Account) intent.getParcelableExtra(ARG_ACCOUNT)); } else { Log_OC.e(TAG, "Unknown action received; ignoring it: " + intent.getAction()); } return Service.START_STICKY; }
496
public static boolean copyImage(Bitmap bitmap, String path, String fileName){ File file = new File(path, fileName); boolean isSucceed = false; FileOutputStream out = null; try { out = new FileOutputStream(file); isSucceed = bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } return isSucceed; }
public static boolean copyImage(Bitmap bitmap, String path, String fileName){ File file = new File(path, fileName); boolean isSucceed = false; FileOutputStream out = null; try { out = new FileOutputStream(file); isSucceed = bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); } catch (Exception e) { } finally { try { if (out != null) { out.close(); } } catch (IOException e) { } } return isSucceed; }
497
private void dynamicWaiting(WebDriver driver){ String[] keyExtentions = { "crdownload" }; try { do { Thread.sleep(100); } while (!org.apache.commons.io.FileUtils.listFiles(new File(downloadFilePath), keyExtentions, false).isEmpty()); } catch (InterruptedException e) { } driver.close(); }
private void dynamicWaiting(){ String[] keyExtentions = { "crdownload" }; try { do { Thread.sleep(100); } while (!org.apache.commons.io.FileUtils.listFiles(new File(downloadFilePath), keyExtentions, false).isEmpty()); } catch (InterruptedException e) { } }
498
public int loadIndiaCensusData(String csvFilePath) throws CensusAnalyserException{ this.checkValidCSVFile(csvFilePath); try (Reader reader = Files.newBufferedReader(Paths.get(csvFilePath))) { IcsvBuilder csvBuilder = CSVBuilderFactory.createCSVBuilder(); csvFileMap = new HashMap<String, IndiaCensusCSV>(); csvFileList = new ArrayList<IndiaCensusCSV>(); Iterator<IndiaCensusCSV> indiaCensusCSVIterator = csvBuilder.getCSVFileIterator(reader, IndiaCensusCSV.class); while (indiaCensusCSVIterator.hasNext()) { CensusDAO censusDAO = new CensusDAO(indiaCensusCSVIterator.next()); this.csvFileMap.put(censusDAO.getState(), censusDAO); this.csvFileList = (List) csvFileMap.values().stream().collect(Collectors.toList()); } return csvFileMap.size(); } catch (IOException e) { throw new CensusAnalyserException(e.getMessage(), CensusAnalyserException.ExceptionType.CENSUS_FILE_PROBLEM); } catch (RuntimeException e) { if (e.getMessage().contains("header!")) ; throw new CensusAnalyserException(e.getMessage(), CensusAnalyserException.ExceptionType.INVALID_FILE_HEADER); } }
public int loadIndiaCensusData(String csvFilePath) throws CensusAnalyserException{ this.checkValidCSVFile(csvFilePath); try (Reader reader = Files.newBufferedReader(Paths.get(csvFilePath))) { IcsvBuilder csvBuilder = CSVBuilderFactory.createCSVBuilder(); csvFileMap = new HashMap<String, IndiaCensusCSV>(); csvFileList = new ArrayList<IndiaCensusCSV>(); Iterator<IndiaCensusCSV> indiaCensusCSVIterator = csvBuilder.getCSVFileIterator(reader, IndiaCensusCSV.class); Iterable<IndiaCensusCSV> indiaCensusCSVIterable = () -> indiaCensusCSVIterator; StreamSupport.stream(indiaCensusCSVIterable.spliterator(), false).forEach(indiaCensusCSV -> csvFileMap.put(indiaCensusCSV.state, new CensusDAO(indiaCensusCSV))); this.csvFileList = (List) csvFileMap.values().stream().collect(Collectors.toList()); return csvFileMap.size(); } catch (IOException e) { throw new CensusAnalyserException(e.getMessage(), CensusAnalyserException.ExceptionType.CENSUS_FILE_PROBLEM); } catch (RuntimeException e) { if (e.getMessage().contains("header!")) ; throw new CensusAnalyserException(e.getMessage(), CensusAnalyserException.ExceptionType.INVALID_FILE_HEADER); } }
499
public final boolean equals(final Object o){ if (Arez.areNativeComponentsEnabled()) { if (this == o) { return true; } else if (null == o || !(o instanceof Arez_NameVariationsModel)) { return false; } else { final Arez_NameVariationsModel that = (Arez_NameVariationsModel) o; return $$arezi$$_id() == that.$$arezi$$_id(); } } else { return super.equals(o); } }
public final boolean equals(final Object o){ if (Arez.areNativeComponentsEnabled()) { if (o instanceof Arez_NameVariationsModel) { final Arez_NameVariationsModel that = (Arez_NameVariationsModel) o; return this.$$arezi$$_id() == that.$$arezi$$_id(); } else { return false; } } else { return super.equals(o); } }