auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private ConcurSAEDetailLineFixture(ConcurSAEDetailLineFixture baseFixture, ConcurSAEFileFixture extractFile, ConcurEmployeeFixture employee, String journalDebitCredit, double journalAmount, EnumMap<LineField,String> overrideMap) { this(extractFile, employee, overrideMap.getOrDefault(LineField.REPORT_ID, baseFixture.reportId), overrideMap.getOrDefault(LineField.PAYMENT_CODE, baseFixture.paymentCode), overrideMap.getOrDefault(LineField.CHART_OF_ACCOUNTS_CODE, baseFixture.chartOfAccountsCode), overrideMap.getOrDefault(LineField.JOURNAL_ACCOUNT_CODE, baseFixture.journalAccountCode), overrideMap.getOrDefault(LineField.ACCOUNT_NUMBER, baseFixture.accountNumber), overrideMap.getOrDefault(LineField.SUB_ACCOUNT_NUMBER, baseFixture.subAccountNumber), overrideMap.getOrDefault(LineField.SUB_OBJECT_CODE, baseFixture.subObjectCode), overrideMap.getOrDefault(LineField.PROJECT_CODE, baseFixture.projectCode), overrideMap.getOrDefault(LineField.ORG_REF_ID, baseFixture.orgRefId), journalDebitCredit, journalAmount, overrideMap.getOrDefault(LineField.REPORT_END_DATE, baseFixture.reportEndDate), overrideMap.getOrDefault(LineField.CASH_ADVANCE_CA_KEY, ""), overrideMap.getOrDefault(LineField.REPORT_ENTRY_ID, "")); }

Target:
private ConcurSAEDetailLineFixture(ConcurSAEDetailLineFixture baseFixture, ConcurSAEFileFixture extractFile, ConcurEmployeeFixture employee, String journalDebitCredit, double journalAmount, EnumMap<LineField,String> overrideMap) { this(extractFile, employee, overrideMap.getOrDefault(LineField.REPORT_ID, baseFixture.reportId), overrideMap.getOrDefault(LineField.PAYMENT_CODE, baseFixture.paymentCode), overrideMap.getOrDefault(LineField.CHART_OF_ACCOUNTS_CODE, baseFixture.chartOfAccountsCode), overrideMap.getOrDefault(LineField.JOURNAL_ACCOUNT_CODE, baseFixture.journalAccountCode), overrideMap.getOrDefault(LineField.ACCOUNT_NUMBER, baseFixture.accountNumber), overrideMap.getOrDefault(LineField.SUB_ACCOUNT_NUMBER, baseFixture.subAccountNumber), overrideMap.getOrDefault(LineField.SUB_OBJECT_CODE, baseFixture.subObjectCode), overrideMap.getOrDefault(LineField.PROJECT_CODE, baseFixture.projectCode), overrideMap.getOrDefault(LineField.ORG_REF_ID, baseFixture.orgRefId), journalDebitCredit, journalAmount, overrideMap.getOrDefault(LineField.REPORT_END_DATE, baseFixture.reportEndDate), overrideMap.getOrDefault(LineField.CASH_ADVANCE_KEY, baseFixture.cashAdvanceKey), overrideMap.getOrDefault(LineField.REPORT_ENTRY_ID, baseFixture.reportEntryId)); }
Source:
public void testSimpleFile() throws Exception { File file = atomicFileCreate("test.txt"); File hidden = atomicFileCreate("test.foo"); Message<?> received = messageCollector.forChannel(source.output()).poll(10, TimeUnit.SECONDS); assertNotNull(received); assertEquals(file, received.getPayload()); received = messageCollector.forChannel(source.output()).poll(300, TimeUnit.MILLISECONDS); assertNull(received); file.delete(); hidden.delete(); }

Target:
public void testSimpleFile() throws Exception { File file = atomicFileCreate("test.txt"); File hidden = atomicFileCreate("test.foo"); assertTrue(new File(ROOT_DIR, "test.foo").exists()); Message<?> received = messageCollector.forChannel(source.output()).poll(10, TimeUnit.SECONDS); assertNotNull(received); assertEquals(file, received.getPayload()); received = messageCollector.forChannel(source.output()).poll(300, TimeUnit.MILLISECONDS); assertNull(received); file.delete(); hidden.delete(); }
Source:
private IFormatReader setupReader(boolean flattened, boolean initialize) { IFormatReader ir = null; if (flattened) { ir = new ImageReader(); ir = new BufferedImageReader(new FileStitcher(new Memoizer(ir, Memoizer.DEFAULT_MINIMUM_ELAPSED, new File("")))); ir.setMetadataOptions(new DefaultMetadataOptions(MetadataLevel.NO_OVERLAYS)); } else { ir = new BufferedImageReader(new FileStitcher()); ir.setFlattenedResolutions(false); } MetadataStore store = null; try { store = omexmlService.createOMEXMLMetadata(); } catch (ServiceException e) { LOGGER.warn("Could not parse OME-XML", e); } ir.setMetadataStore(store); ir.setNormalized(true); ir.setOriginalMetadataPopulated(false); ir.setMetadataFiltered(true); if (initialize) { try { ir.setId(id); } catch (FormatException e) { LOGGER.error("Could not initialize " + id, e); } catch (IOException e) { LOGGER.error("Could not initialize " + id, e); } } if (flattened) { reader = (BufferedImageReader) ir; } return ir; }

Target:
private IFormatReader setupReader(boolean flattened, boolean initialize) { IFormatReader ir = null; if (flattened) { ir = new ImageReader(); ir = new BufferedImageReader(new FileStitcher(new Memoizer(ir, Memoizer.DEFAULT_MINIMUM_ELAPSED, new File("")))); ir.setMetadataOptions(new DefaultMetadataOptions(MetadataLevel.NO_OVERLAYS)); } else { ir = new BufferedImageReader(new FileStitcher()); ir.setFlattenedResolutions(false); } MetadataStore store = null; try { store = omexmlService.createOMEXMLMetadata(); } catch (ServiceException e) { LOGGER.warn("Could not parse OME-XML", e); } ir.setMetadataStore(store); ir.setNormalized(true); ir.setOriginalMetadataPopulated(false); ir.setMetadataFiltered(true); if (initialize) { try { ir.setId(id); } catch (FormatException | IOException e) { LOGGER.error("Could not initialize " + id, e); } } if (flattened) { reader = (BufferedImageReader) ir; } return ir; }
Source:
public void testTwoConnectionsSameIDThroughCFWithShareClientIDEnabeld() throws Exception { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616?clientID=myid;enableSharedClientID=true"); conn = connectionFactory.createConnection(); try { conn2 = connectionFactory.createConnection(); } catch (InvalidClientIDException expected) { Assert.fail("Should allow sharing of client IDs among the same CF"); } Session session1 = conn.createSession(); Session session2 = conn.createSession(); Session session3 = conn.createSession(); Session session4 = conn.createSession(); session1.close(); session2.close(); session3.close(); session4.close(); }

Target:
public void testTwoConnectionsSameIDThroughCFWithShareClientIDEnabeld() throws Exception { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616?clientID=myid;enableSharedClientID=true"); conn = connectionFactory.createConnection(); try { conn2 = connectionFactory.createConnection(); } catch (InvalidClientIDException expected) { Assert.fail("Should allow sharing of client IDs among the same CF"); } Session session1 = conn.createSession(); Session session2 = conn.createSession(); Session session3 = conn2.createSession(); Session session4 = conn2.createSession(); session1.close(); session2.close(); session3.close(); session4.close(); }
Source:
private static void incrementIV(byte[] iv, int i) { iv[i]++; if (iv[i] == 0) { if (i != 0) { incrementIV(iv, i - 1); } else return; } }

Target:
static void incrementIV(byte[] iv, int i) { iv[i]++; if (iv[i] == 0) { if (i != 0) { incrementIV(iv, i - 1); } else return; } }
Source:
private boolean isTargetRowFound() { try (ResultInterface rows = targetMatchQuery.query(0)) { if (!rows.next()) { return false; } Value targetRowId = rows.currentRow()[0]; Integer number = targetRowidsRemembered.get(targetRowId); if (number != null) { throw DbException.get(ErrorCode.DUPLICATE_KEY_1, "Merge using ON column expression, " + "duplicate _ROWID_ target record already updated, deleted or inserted:_ROWID_=" + targetRowId + ":in:" + targetTableFilter.getTable() + ":conflicting source row number:" + number); } targetRowidsRemembered.put(targetRowId, sourceQueryRowNumber); if (rows.next()) { throw DbException.get(ErrorCode.DUPLICATE_KEY_1, "Duplicate key updated " + rows.getRowCount() + " rows at once, only 1 expected:_ROWID_=" + targetRowId + ":in:" + targetTableFilter.getTable() + ":conflicting source row number:" + targetRowidsRemembered.get(targetRowId)); } return true; } }

Target:
private boolean isTargetRowFound() { try (ResultInterface rows = targetMatchQuery.query(0)) { if (!rows.next()) { return false; } Value targetRowId = rows.currentRow()[0]; Integer number = targetRowidsRemembered.get(targetRowId); if (number != null) { throw DbException.get(ErrorCode.DUPLICATE_KEY_1, "Merge using ON column expression, " + "duplicate _ROWID_ target record already updated, deleted or inserted:_ROWID_=" + targetRowId + ":in:" + targetTableFilter.getTable() + ":conflicting source row number:" + number); } targetRowidsRemembered.put(targetRowId, sourceQueryRowNumber); if (rows.next()) { int rowCount; if (rows.isLazy()) { for (rowCount = 2; rows.next(); rowCount++) { } } else { rowCount = rows.getRowCount(); } throw DbException.get(ErrorCode.DUPLICATE_KEY_1, "Duplicate key updated " + rowCount + " rows at once, only 1 expected:_ROWID_=" + targetRowId + ":in:" + targetTableFilter.getTable() + ":conflicting source row number:" + targetRowidsRemembered.get(targetRowId)); } return true; } }
Source:
public void unlock(T id) { log.trace("{} trying to unlock {}", Thread.currentThread().getName(), id.toString()); synchronized (locked) { if (locked.remove(id)) { log.trace("{} unlocked {}", Thread.currentThread().getName(), id.toString()); idsLocked.update(-1); locked.notifyAll(); } } }

Target:
public void unlock(T id) { log.trace("{} trying to unlock {}", Thread.currentThread().getName(), id.toString()); synchronized (locked) { if (locked.remove(id)) { log.trace("{} unlocked {}", Thread.currentThread().getName(), id.toString()); locked.notifyAll(); } } }
Source:
public void setMaxRowSize(int rowSize) { if (maxRowSize == -1) { maxRowSize = rowSize; } else { if (maxRowSize < rowSize) { maxRowSize = rowSize; } } }

Target:
public void setMaxRowSize(int rowSize) { if (rowSize > maxRowSize) { maxRowSize = rowSize; } }
Source:
public EhcacheEntityResponse invoke(ClientDescriptor clientDescriptor, EhcacheEntityMessage message) { try { switch (message.getType()) { case LIFECYCLE_OP: return invokeLifeCycleOperation(clientDescriptor, (LifecycleMessage) message); case SERVER_STORE_OP: return invokeServerStoreOperation(clientDescriptor, (ServerStoreOpMessage) message); default: throw new IllegalMessageException("Unknown message : " + message); } } catch (ClusteredEhcacheException e) { return responseFactory.failure(e); } catch (Exception e) { LOGGER.error("Unexpected exception raised during LifeCycle operation: " + e, e); return responseFactory.failure(e); } }

Target:
public EhcacheEntityResponse invoke(ClientDescriptor clientDescriptor, EhcacheEntityMessage message) { try { switch (message.getType()) { case LIFECYCLE_OP: return invokeLifeCycleOperation(clientDescriptor, (LifecycleMessage) message); case SERVER_STORE_OP: return invokeServerStoreOperation(clientDescriptor, (ServerStoreOpMessage) message); default: throw new IllegalMessageException("Unknown message : " + message); } } catch (ClusteredEhcacheException e) { return responseFactory.failure(e); } catch (Exception e) { LOGGER.error("Unexpected exception raised during operation: " + message, e); return responseFactory.failure(e); } }
Source:
public void testScanTableWithIterSetWithoutProfile() throws Exception { final String table = name.getMethodName(); ts.exec("createtable " + table, true); ts.exec("insert foo a b c", true); ts.exec("scan", true, "foo a:b c"); ts.input.set("\n5000\n\n"); ts.exec("setiter -scan -n itname -p 10 -ageoff", true); ts.exec("sleep 6", true); ts.exec("scan", true, "", true); ts.exec("deletetable -f " + table); ts.exec("createtable " + table, true); ts.exec("insert foo a b c", true); ts.exec("notable"); ts.exec("scan -t " + table, true, "foo a:b c"); ts.input.set("\n5000\n\n"); ts.exec("setiter -scan -n itname -p 10 -ageoff -t " + table, true); ts.exec("sleep 6", true); ts.exec("scan -t " + table, true, "", true); ts.exec("deletetable -f " + table); }

Target:
public void testScanTableWithIterSetWithoutProfile() throws Exception { final String table = name.getMethodName(); ts.exec("createtable " + table, true); ts.exec("insert foo a b c", true); ts.exec("scan", true, "foo a:b c"); ts.input.set("\n1000\n\n"); ts.exec("setiter -scan -n itname -p 10 -ageoff", true); ts.exec("sleep 2", true); ts.exec("scan", true, "", true); ts.exec("deletetable -f " + table); ts.exec("createtable " + table, true); ts.exec("insert foo a b c", true); ts.exec("notable"); ts.exec("scan -t " + table, true, "foo a:b c"); ts.input.set("\n1000\n\n"); ts.exec("setiter -scan -n itname -p 10 -ageoff -t " + table, true); ts.exec("sleep 2", true); ts.exec("scan -t " + table, true, "", true); ts.exec("deletetable -f " + table); }
Source:
public long countStocksByDatasetId(int datasetId) throws MiddlewareQueryException { final StringBuilder sql = new StringBuilder(); sql.append("SELECT COUNT(DISTINCT es.stock_id) FROM nd_experiment_project ep ") .append(" INNER JOIN nd_experiment_stock es ON es.nd_experiment_id = ep.nd_experiment_id ").append(" WHERE ep.project_id = ") .append(datasetId); try { SQLQuery query = this.getSession().createSQLQuery(sql.toString()); BigInteger count = (BigInteger) query.uniqueResult(); return count.longValue(); } catch (HibernateException e) { this.logAndThrowException("Error at countStocksByDatasetId=" + datasetId + " query at ExperimentDao: " + e.getMessage(), e); } return 0; }

Target:
public long countStocksByDatasetId(int datasetId) throws MiddlewareQueryException { final StringBuilder sql = new StringBuilder(); sql.append("SELECT COUNT(DISTINCT es.stock_id) FROM nd_experiment_project ep ") .append(" INNER JOIN nd_experiment_stock es ON es.nd_experiment_id = ep.nd_experiment_id ") .append(" WHERE ep.project_id = :datasetId"); try { SQLQuery query = this.getSession().createSQLQuery(sql.toString()); query.setParameter("datasetId", datasetId); BigInteger count = (BigInteger) query.uniqueResult(); return count.longValue(); } catch (HibernateException e) { this.logAndThrowException("Error at countStocksByDatasetId=" + datasetId + " query at ExperimentDao: " + e.getMessage(), e); } return 0; }
Source:
private MessageHandler createDirectHandlerIfPossible(final Object targetObject, String targetMethodName) { MessageHandler handler = null; if (targetObject instanceof MessageHandler && this.isHandleRequestMethod(targetMethodName)) { handler = new AbstractReplyProducingMessageHandler() { @Override protected Object handleRequestMessage(Message<?> requestMessage) { ((MessageHandler) targetObject).handleMessage(requestMessage); return null; } }; } return handler; }

Target:
private MessageHandler createDirectHandlerIfPossible(final Object targetObject, String targetMethodName) { MessageHandler handler = null; if (targetObject instanceof MessageHandler && this.methodIsHandleMessageOrEmpty(targetMethodName)) { if (targetObject instanceof AbstractReplyProducingMessageHandler) { return (MessageHandler) targetObject; } handler = new AbstractReplyProducingMessageHandler() { @Override protected Object handleRequestMessage(Message<?> requestMessage) { ((MessageHandler) targetObject).handleMessage(requestMessage); return null; } }; } return handler; }
Source:
public void testReplaceLabel() throws UnsupportedOperationException, Exception { PID pid = makePid(); String oldLabel = "old_work_label"; Model fileModel = ModelFactory.createDefaultModel(); fileModel.add(fileModel.createResource(pid.getRepositoryPath()), Ebucore.filename, oldLabel); Path file = createTempFile("test", "txt"); FileObject fileObj = repositoryObjectFactory.createFileObject(pid, fileModel); fileObj.addOriginalFile(file.toUri(), filename, mimetype, null, null); String newLabel = "new_work_filename"; MvcResult result = mvc.perform(put("/edit/filename/" + pid.getUUID()) .param("label", newLabel)) .andExpect(status().is2xxSuccessful()) .andReturn(); Map<String, Object> respMap = getMapFromResponse(result); assertEquals(pid.getUUID(), respMap.get("pid")); assertEquals("editLabel", respMap.get("action")); assertEquals(newLabel, fileObj.getOriginalFile().getModel().getRequiredProperty( fileObj.getOriginalFile().getResource(), Ebucore.filename).getLiteral().toString()); }

Target:
public void testReplaceLabel() throws UnsupportedOperationException, Exception { PID pid = makePid(); Path file = createTempFile("test", "txt"); FileObject fileObj = repositoryObjectFactory.createFileObject(pid, null); fileObj.addOriginalFile(file.toUri(), filename, mimetype, null, null); String newLabel = "new_work_filename"; MvcResult result = mvc.perform(put("/edit/filename/" + pid.getUUID()) .param("label", newLabel)) .andExpect(status().is2xxSuccessful()) .andReturn(); Map<String, Object> respMap = getMapFromResponse(result); assertEquals(pid.getUUID(), respMap.get("pid")); assertEquals("editLabel", respMap.get("action")); assertEquals(newLabel, fileObj.getOriginalFile().getResource().getProperty(Ebucore.filename) .getLiteral().toString()); }
Source:
public DeclarationGenerator(Options opts) { this.opts = opts; }

Target:
DeclarationGenerator(Options opts) { this.opts = opts; }
Source:
public void start() { if (listenBacklog > 0) { bootstrap.option(ChannelOption.SO_BACKLOG, listenBacklog); } LOG.info("binding to port {}", localAddress); parentChannel = bootstrap.bind(localAddress).syncUninterruptibly().channel(); localAddress = (InetSocketAddress) parentChannel.localAddress(); LOG.info("bound to port " + getLocalPort()); }

Target:
public void start() { if (listenBacklog != -1) { bootstrap.option(ChannelOption.SO_BACKLOG, listenBacklog); } LOG.info("binding to port {}", localAddress); parentChannel = bootstrap.bind(localAddress).syncUninterruptibly().channel(); localAddress = (InetSocketAddress) parentChannel.localAddress(); LOG.info("bound to port " + getLocalPort()); }
Source:
public String toString() { return new StringBuilder("SyncInvocationStage{").append(rv).append('}').toString(); }

Target:
public String toString() { return new StringBuilder("SyncInvocationStage(").append(rv).append(')').toString(); }
Source:
public CompletableFuture<PhysicalSlotRequest.Result> allocatePhysicalSlot(PhysicalSlotRequest physicalSlotRequest) { LOG.debug("Received a slot request {}.", physicalSlotRequest.getSlotRequestId()); SlotRequestId slotRequestId = physicalSlotRequest.getSlotRequestId(); SlotProfile slotProfile = physicalSlotRequest.getSlotProfile(); ResourceProfile resourceProfile = slotProfile.getPhysicalSlotResourceProfile(); LOG.debug("Received slot request with resource requirements: {}", slotRequestId, resourceProfile); Optional<PhysicalSlot> availablePhysicalSlot = tryAllocateFromAvailable(slotRequestId, slotProfile); CompletableFuture<PhysicalSlot> slotFuture; slotFuture = availablePhysicalSlot .map(CompletableFuture::completedFuture) .orElseGet(() -> requestNewSlot( slotRequestId, resourceProfile, physicalSlotRequest.willSlotBeOccupiedIndefinitely())); return slotFuture.thenApply(physicalSlot -> new PhysicalSlotRequest.Result(slotRequestId, physicalSlot)); }

Target:
public CompletableFuture<PhysicalSlotRequest.Result> allocatePhysicalSlot(PhysicalSlotRequest physicalSlotRequest) { SlotRequestId slotRequestId = physicalSlotRequest.getSlotRequestId(); SlotProfile slotProfile = physicalSlotRequest.getSlotProfile(); ResourceProfile resourceProfile = slotProfile.getPhysicalSlotResourceProfile(); LOG.debug("Received slot request with resource requirements: {}", slotRequestId, resourceProfile); Optional<PhysicalSlot> availablePhysicalSlot = tryAllocateFromAvailable(slotRequestId, slotProfile); CompletableFuture<PhysicalSlot> slotFuture; slotFuture = availablePhysicalSlot .map(CompletableFuture::completedFuture) .orElseGet(() -> requestNewSlot( slotRequestId, resourceProfile, physicalSlotRequest.willSlotBeOccupiedIndefinitely())); return slotFuture.thenApply(physicalSlot -> new PhysicalSlotRequest.Result(slotRequestId, physicalSlot)); }
Source:
public Response getXY(@PathParam(value = "name") String traceName, @PathParam(value = "providerId") String providerId, @QueryParam(value = "start") long start, @QueryParam(value = "end") long end, @QueryParam(value = "nb") @Min(1) int nb, @QueryParam(value = "ids") @NotNull Set<Long> ids) { TraceModel traceModel = traceManager.get(traceName); if (traceModel == null) { return Response.status(Status.NOT_FOUND).entity("No Such Trace").build(); } ITmfTreeXYDataProvider<@NonNull ITmfTreeDataModel> provider = manager.getDataProvider(traceModel.getTrace(), providerId, ITmfTreeXYDataProvider.class); if (provider == null) { return Response.status(Status.METHOD_NOT_ALLOWED).entity("Analysis cannot run").build(); } TmfModelResponse<@NonNull ITmfCommonXAxisModel> response = provider.fetchXY(new SelectionTimeQueryFilter(start, end, nb, ids), null); if (response.getStatus() == TmfModelResponse.Status.CANCELLED || response.getStatus() == TmfModelResponse.Status.FAILED) { return Response.serverError().entity(response.getStatusMessage()).build(); } return Response.ok().entity(new XYView(traceModel, response.getModel())).build(); }

Target:
public Response getXY(@PathParam(value = "name") String traceName, @PathParam(value = "providerId") String providerId, @QueryParam(value = "start") long start, @QueryParam(value = "end") long end, @QueryParam(value = "nb") @Min(1) int nb, @QueryParam(value = "ids") @NotNull Set<Long> ids) { TraceModel traceModel = traceManager.get(traceName); if (traceModel == null) { return Response.status(Status.NOT_FOUND).entity("No Such Trace").build(); } ITmfTreeXYDataProvider<@NonNull ITmfTreeDataModel> provider = manager.getDataProvider(traceModel.getTrace(), providerId, ITmfTreeXYDataProvider.class); if (provider == null) { return Response.status(Status.METHOD_NOT_ALLOWED).entity("Analysis cannot run").build(); } TmfModelResponse<@NonNull ITmfCommonXAxisModel> response = provider.fetchXY(new SelectionTimeQueryFilter(start, end, nb, ids), null); return Response.ok().entity(new XYView(traceModel, response)).build(); }
Source:
public Map<String, List<DataPointAssignmentDto>> listSomeOrAll( @RequestParam(value = "surveyAssignmentId", required = false) Long surveyAssignmentId, @RequestParam(value = "deviceId", required = false) Long deviceId ) { final HashMap<String, List<DataPointAssignmentDto>> response = new HashMap<String, List<DataPointAssignmentDto>>(); final List<DataPointAssignmentDto> results = new ArrayList<DataPointAssignmentDto>(); if (surveyAssignmentId != null) { for (DataPointAssignment dpa : dataPointAssignmentDao.listBySurveyAssignment(surveyAssignmentId)) { results.add(marshallToDto(dpa)); } } else if (deviceId != null) { for (DataPointAssignment dpa : dataPointAssignmentDao.listByDevice(deviceId)) { results.add(marshallToDto(dpa)); } } else { for (DataPointAssignment dpa : dataPointAssignmentDao.list(Constants.ALL_RESULTS)) { results.add(marshallToDto(dpa)); } } response.put("data_point_assignments", results); return response; }

Target:
public Map<String, List<DataPointAssignmentDto>> listSomeOrAll( @RequestParam(value = "surveyAssignmentId", required = false) Long surveyAssignmentId, @RequestParam(value = "deviceId", required = false) Long deviceId ) { final HashMap<String, List<DataPointAssignmentDto>> response = new HashMap<String, List<DataPointAssignmentDto>>(); final List<DataPointAssignmentDto> results = new ArrayList<DataPointAssignmentDto>(); if (deviceId != null && surveyAssignmentId != null) { for (DataPointAssignment dpa : dataPointAssignmentDao.listByDeviceAndSurveyAssignment(deviceId,surveyAssignmentId)) { results.add(marshallToDto(dpa)); } } else if (surveyAssignmentId != null) { for (DataPointAssignment dpa : dataPointAssignmentDao.listBySurveyAssignment(surveyAssignmentId)) { results.add(marshallToDto(dpa)); } } else if (deviceId != null) { for (DataPointAssignment dpa : dataPointAssignmentDao.listByDevice(deviceId)) { results.add(marshallToDto(dpa)); } } else { for (DataPointAssignment dpa : dataPointAssignmentDao.list(Constants.ALL_RESULTS)) { results.add(marshallToDto(dpa)); } } response.put("data_point_assignments", results); return response; }
Source:
public void focus() { widgets_.forEach(widget -> { if (widget.isVisible()) { widget.focus(); } }); }

Target:
public void focus() { widgets_.forEach(widget -> { if (widget.isVisible()) { widget.focus(); return; } }); }
Source:
private boolean backupTable(String fileName, UUID uuid) throws IOException { FileOutputStream fileOutput = null; try { fileOutput = new FileOutputStream(fileName); } catch (FileNotFoundException e) { log.error("failed to create the temp file for table {}", fileName, uuid); return false; } StreamOptions options = StreamOptions.builder() .ignoreTrimmed(false) .cacheEntries(false) .build(); Stream<OpaqueEntry> stream = (new OpaqueStream(runtime, runtime.getStreamsView().get(uuid, options))).streamUpTo(timestamp); Iterator<OpaqueEntry> iterator = stream.iterator(); try { while (iterator.hasNext()) { OpaqueEntry lastEntry = iterator.next(); List<SMREntry> smrEntries = lastEntry.getEntries().get(uuid); if (smrEntries != null) { Map<UUID, List<SMREntry>> map = new HashMap<>(); map.put(uuid, smrEntries); OpaqueEntry newOpaqueEntry = new OpaqueEntry(lastEntry.getVersion(), map); OpaqueEntry.write(fileOutput, newOpaqueEntry); } } fileOutput.flush(); fileOutput.close(); } catch (IOException e) { log.error("failed to write the table to temp backup file {}", uuid, fileName); return false; } log.debug("{} table is backed up and stored to temp file {}", uuid, fileName); return true; }

Target:
private void backupTable(String fileName, UUID uuid) throws IOException { try (FileOutputStream fileOutput = new FileOutputStream(fileName)) { StreamOptions options = StreamOptions.builder() .ignoreTrimmed(false) .cacheEntries(false) .build(); Stream<OpaqueEntry> stream = (new OpaqueStream(runtime, runtime.getStreamsView().get(uuid, options))).streamUpTo(timestamp); writeTableToFile(fileOutput, stream, uuid); } catch (IOException e) { log.error("failed to back up table to file {}", uuid, fileName); throw e; } catch (TrimmedException e) { log.error("failed to back up tables as log was trimmed after back up starts."); throw e; } log.info("{} table is backed up and stored to temp file {}", uuid, fileName); }
Source:
public static void main(String[] args) throws Exception { AbstractApplicationContext context = new AnnotationConfigApplicationContext(Launch.class.getPackage().getName()); ExampleService service = context.getBean(ExampleService.class); if(args.length == 1) { RecoveryManagerService recoveryManagerService = context.getBean(RecoveryManagerService.class); if(args[0].equals("-f")) { System.out.println("Generate something to recovery ..."); service.testRecovery(); } else if(args[0].equals("-r")) { System.out.println("start the recovery manager"); recoveryManagerService.create(); recoveryManagerService.start(); System.out.println("recovery manager scan ..."); recoveryManagerService.scan(); service.checkRecord(); recoveryManagerService.stop(); System.out.println("stop the recovery manager"); } } else { try { service.testRollback(); } catch (Exception e) { System.out.println("testRollback OK"); service.checkRecord(); } service.testCommit(); service.checkRecord(); try { service.testTimeout(); } catch (Exception e) { System.out.println("testTimeout OK"); service.checkRecord(); } } service.shutdownDatabase(); TxControl.disable(true); TransactionReaper.terminate(true); }

Target:
public static void main(String[] args) throws Exception { AbstractApplicationContext context = new AnnotationConfigApplicationContext(Launch.class.getPackage().getName()); ExampleService service = context.getBean(ExampleService.class); if (args.length == 1) { RecoveryManagerService recoveryManagerService = context.getBean(RecoveryManagerService.class); if (args[0].equals("-f")) { System.out.println("Generate something to recovery ..."); service.testRecovery(); } else if (args[0].equals("-r")) { System.out.println("start the recovery manager"); recoveryManagerService.start(); System.out.println("recovery manager scan ..."); while (DummyXAResource.getCommitRequests() == 0) { Thread.sleep(1000); } System.out.println("stop the recovery manager"); recoveryManagerService.stop(); } else if (args[0].equals("-c")) { service.checkRecord(); } } else { service.testCommit(); service.checkRecord(); } service.shutdownDatabase(); TxControl.disable(true); TransactionReaper.terminate(true); }
Source:
MetricConfigDTO generateMetricConfig(JsonNode payloadNode, String suffix) { MetricConfigDTO metricConfigDTO = new MetricConfigDTO(); metricConfigDTO.setName(DEFAULT_METRIC_NAME); metricConfigDTO.setDataset(DEFAULT_DATASET_NAME + suffix); metricConfigDTO.setAlias(ThirdEyeUtils .constructMetricAlias(DEFAULT_DATASET_NAME + suffix, DEFAULT_METRIC_NAME)); metricConfigDTO.setDatatype(MetricType.DOUBLE); metricConfigDTO.setDefaultAggFunction(MetricAggFunction.SUM); metricConfigDTO.setActive(true); if (payloadNode.has(METRIC_FIELD)) { Map<String, Object> metricYaml = ConfigUtils.getMap(yaml.load(payloadNode.get(METRIC_FIELD).textValue())); if (metricYaml.containsKey("metricColumn")) { metricConfigDTO.setName((String) metricYaml.get("metricColumn")); } if (metricYaml.containsKey("datatype")) { metricConfigDTO .setDatatype(MetricType.valueOf((String) metricYaml.get("datatype"))); } } metricConfigDAO.save(metricConfigDTO); LOG.info("Created metric with config {}", metricConfigDTO); return metricConfigDTO; }

Target:
MetricConfigDTO generateMetricConfig(JsonNode payloadNode, String suffix) { MetricConfigDTO metricConfigDTO = new MetricConfigDTO(); metricConfigDTO.setName(DEFAULT_METRIC_NAME); metricConfigDTO.setDataset(DEFAULT_DATASET_NAME + suffix); metricConfigDTO.setAlias(ThirdEyeUtils .constructMetricAlias(DEFAULT_DATASET_NAME + suffix, DEFAULT_METRIC_NAME)); metricConfigDTO.setDatatype(MetricType.DOUBLE); metricConfigDTO.setDefaultAggFunction(MetricAggFunction.SUM); metricConfigDTO.setActive(true); if (payloadNode.has(METRIC_FIELD)) { updateMetricCustomFields(payloadNode, metricConfigDTO); } metricConfigDAO.save(metricConfigDTO); LOG.info("Created metric with config {}", metricConfigDTO); return metricConfigDTO; }
Source:
private boolean isSelected(EditPart part) { boolean result; result = part != null && part.getSelected() == EditPart.SELECTED_PRIMARY || part.getSelected() == EditPart.SELECTED; return result; }

Target:
private boolean isSelected(EditPart part) { return part != null && part.getSelected() == EditPart.SELECTED_PRIMARY || part.getSelected() == EditPart.SELECTED; }
Source:
private byte[] draw(final List<String> infos) throws IOException { final BufferedImage img = ImageIO .read(this.getClass().getResourceAsStream("/build_health.png")); final BufferedImage image = new BufferedImage( img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_ARGB ); final Graphics2D gfx = image.createGraphics(); gfx.drawImage(img, 0, 0, null); gfx.setFont(new Font("Serif", Font.PLAIN, Tv.TEN)); this.drawString(gfx, infos); gfx.dispose(); final ByteArrayOutputStream stream = new ByteArrayOutputStream(); ImageIO.write(image, "png", stream); return stream.toByteArray(); }

Target:
private byte[] draw(final List<String> infos) throws IOException { final BufferedImage img = ImageIO.read( this.getClass().getResourceAsStream("build_health.png") ); final BufferedImage image = new BufferedImage( img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_ARGB ); final Graphics2D gfx = image.createGraphics(); gfx.drawImage(img, 0, 0, null); gfx.setFont(new Font("Serif", Font.PLAIN, Tv.TEN)); this.drawString(gfx, infos); gfx.dispose(); final ByteArrayOutputStream stream = new ByteArrayOutputStream(); ImageIO.write(image, "png", stream); return stream.toByteArray(); }
Source:
public String getIconFilePath(String size) { if (getIconFilePathPattern().isEmpty()) { return getIconFilePathPattern().replace(":size", size); } return null; }

Target:
public String getIconFilePath(String size) { if (!StringUtils.isBlank(getIconFilePathPattern())) { return getIconFilePathPattern().replace(":size", size); } return null; }
Source:
private static void validatePage(String pageNumber, List<String> validationErrors) { if (pageNumber!=null && Long.valueOf(pageNumber) < 1) { validationErrors.add(PAGE); } }

Target:
private static void validatePage(String pageNumber, List<String> validationErrors) { if (isNotBlank(pageNumber) && Integer.valueOf(pageNumber) < 1) { validationErrors.add(PAGE); } }
Source:
public V get(Object key) { InternalCacheEntry<K, V> ice = syncGet(key); if (ice != null) { return ice.getValue(); } return null; }

Target:
public V get(Object key) { InternalCacheEntry<K, V> ice = getCacheEntry(key); if (ice != null) { return ice.getValue(); } return null; }
Source:
public RelationalInput generateNewCopy() throws InputGenerationException { try { FileIterator iterator = new FileIterator(inputFile.getName()); return iterator.setSeparator(this.separator) .setQuoteChar(this.quotechar) .setEscapeChar(this.escape) .setSkipLines(this.skipLines) .setStrictQuotes(this.strictQuotes) .setIgnoreLeadingWhiteSpace(this.ignoreLeadingWhiteSpace) .setHasHeader(this.hasHeader) .setSkipDifferingLines(this.skipDifferingLines) .setReader(new FileReader(inputFile)); } catch (FileNotFoundException e) { throw new InputGenerationException("File not found.", e.getCause()); } catch (InputIterationException e) { throw new InputGenerationException("Could not iterate over the first line of the csv file.", e.getCause()); } }

Target:
public RelationalInput generateNewCopy() throws InputGenerationException { try { return new FileIterator(inputFile.getName(), new FileReader(inputFile), setting); } catch (FileNotFoundException e) { throw new InputGenerationException("File not found.", e.getCause()); } catch (InputIterationException e) { throw new InputGenerationException("Could not iterate over the first line of the csv file.", e.getCause()); } }
Source:
@Override public void onNewToken(String token) { super.onNewToken(token); ((Application) getApplicationContext()).getPreferenceManager().setToken(token); CountlyPush.onTokenRefresh(token); Log.i(TAG, "CountlyPush onNewToken " + token); }

Target:
public void onNewToken(String token) { super.onNewToken(token); ((Application) getApplicationContext()).getPreferenceManager().setToken(token); CountlyPush.onTokenRefresh(token); }
Source:
private List<EvalHierarchyRule> getAllByNodeID( Long nodeID ) { logIfDebugEnabled( "getAllByNodeID( " + nodeID + " )" ); Search searchObj = new Search(); searchObj.addRestriction( new Restriction( "nodeID", nodeID ) ); List<EvalHierarchyRule> rules = dao.findBySearch( EvalHierarchyRule.class, searchObj ); if( rules == null ) { return Collections.EMPTY_LIST; } else { return rules; } }

Target:
private List<EvalHierarchyRule> getAllByNodeID( Long nodeID ) { if( LOG.isDebugEnabled() ) { LOG.debug( "getAllByNodeID( " + nodeID + " )" ); } Search searchObj = new Search(); searchObj.addRestriction( new Restriction( "nodeID", nodeID ) ); List<EvalHierarchyRule> rules = dao.findBySearch( EvalHierarchyRule.class, searchObj ); if( rules == null ) { return Collections.emptyList(); } else { return rules; } }
Source:
protected boolean containsFilterExpressionChange(final ResourceSetChangeEvent event) { List<Notification> notifications = event.getNotifications(); for (Notification current : notifications) { if (current.getNotifier() instanceof TreeFillingConfiguration) { return true; } } return false; }

Target:
private boolean containsFilterExpressionChange(final ResourceSetChangeEvent event) { List<Notification> notifications = event.getNotifications(); for (Notification current : notifications) { if (current.getNotifier() instanceof TreeFillingConfiguration && current.getFeature() == NattableaxisconfigurationPackage.eINSTANCE.getTreeFillingConfiguration_FilterRule()) { return true; } } return false; }
Source:
private String digestToString(byte[] computedDigest) { StringBuilder sb = new StringBuilder(); for (byte aComputedDigest : computedDigest) { String res = Integer.toHexString(aComputedDigest & 0xFF); sb.append(res.length() == 1 ? "0" : "").append(res); } return sb.toString(); }

Target:
private String digestToString(byte[] computedDigest) { StringBuilder sb = new StringBuilder(); for (byte b : computedDigest) { sb.append(String.format(Locale.US, "%02x", b)); } return sb.toString(); }
Source:
TmfXmlStateAttribute(Element attribute, XmlStateProvider provider) { fProvider = provider; String type = attribute.getAttribute(TmfXmlStrings.TYPE); if (type.equals(TmfXmlStrings.TYPE_CONSTANT)) { fType = StateAttributeType.ATTRIBUTE_TYPE_CONSTANT; fName = fProvider.getAttributeValue(attribute.getAttribute(TmfXmlStrings.VALUE)); } else if (type.equals(TmfXmlStrings.EVENT_FIELD)) { fType = StateAttributeType.ATTRIBUTE_TYPE_EVENTFIELD; fName = fProvider.getAttributeValue(attribute.getAttribute(TmfXmlStrings.VALUE)); } else if (type.equals(TmfXmlStrings.TYPE_LOCATION)) { fType = StateAttributeType.ATTRIBUTE_TYPE_LOCATION; fName = fProvider.getAttributeValue(attribute.getAttribute(TmfXmlStrings.VALUE)); } else if (type.equals(TmfXmlStrings.TYPE_QUERY)) { List<Element> childElements = XmlUtils.getChildElements(attribute); for (Element subAttributeNode : childElements) { TmfXmlStateAttribute subAttribute = new TmfXmlStateAttribute(subAttributeNode, fProvider); fQueryList.add(subAttribute); } fType = StateAttributeType.ATTRIBUTE_TYPE_QUERY; fName = null; } else if (type.equals(TmfXmlStrings.NULL)) { fType = StateAttributeType.ATTRIBUTE_TYPE_NONE; fName = null; } else { throw new IllegalArgumentException("TmfXmlStateAttribute constructor: The XML element is not of the right type"); } }

Target:
public TmfXmlStateAttribute(Element attribute, XmlStateProvider provider) { fProvider = provider; switch (attribute.getAttribute(TmfXmlStrings.TYPE)) { case TmfXmlStrings.TYPE_CONSTANT: fType = StateAttributeType.CONSTANT; fName = fProvider.getAttributeValue(attribute.getAttribute(TmfXmlStrings.VALUE)); break; case TmfXmlStrings.EVENT_FIELD: fType = StateAttributeType.EVENTFIELD; fName = fProvider.getAttributeValue(attribute.getAttribute(TmfXmlStrings.VALUE)); break; case TmfXmlStrings.TYPE_LOCATION: fType = StateAttributeType.LOCATION; fName = fProvider.getAttributeValue(attribute.getAttribute(TmfXmlStrings.VALUE)); break; case TmfXmlStrings.TYPE_QUERY: List<Element> childElements = XmlUtils.getChildElements(attribute); for (Element subAttributeNode : childElements) { TmfXmlStateAttribute subAttribute = new TmfXmlStateAttribute(subAttributeNode, fProvider); fQueryList.add(subAttribute); } fType = StateAttributeType.QUERY; fName = null; break; case TmfXmlStrings.NULL: fType = StateAttributeType.NONE; fName = null; break; default: throw new IllegalArgumentException("TmfXmlStateAttribute constructor: The XML element is not of the right type"); } }
Source:
public void updateRunTimeDynamicData(VmDynamic vm, Guid vdsId, String vdsName) { setStatus(vm.getStatus()); setRunOnVds(vdsId); setRunOnVdsName(vdsName); setVmHost(vm.getVmHost()); setVmIp(vm.getVmIp()); setVmFQDN(vm.getVmFQDN()); if (vm.getCurrentCd() != null) { setCurrentCd(vm.getCurrentCd()); } setAppList(vm.getAppList()); setGuestOs(vm.getGuestOs()); getDynamicData().setVncKeyboardLayout(vm.getVncKeyboardLayout()); setKvmEnable(vm.getKvmEnable()); setAcpiEnable(vm.getAcpiEnable()); setGuestCurrentUserName(vm.getGuestCurrentUserName()); setWin2kHackEnable(vm.getWin2kHackEnable()); setUtcDiff(vm.getUtcDiff()); setExitStatus(vm.getExitStatus()); setExitMessage(vm.getExitMessage()); setExitReason(vm.getExitReason()); setClientIp(vm.getClientIp()); setVmPauseStatus(vm.getPauseStatus()); setLastWatchdogEvent(vm.getLastWatchdogEvent()); setGuestCpuCount(vm.getGuestCpuCount()); setGraphicsInfos(vm.getGraphicsInfos()); getDynamicData().setGuestMemoryBuffered(vm.getGuestMemoryBuffered()); getDynamicData().setGuestMemoryCached(vm.getGuestMemoryCached()); getDynamicData().setGuestMemoryFree(vm.getGuestMemoryFree()); setGuestOsArch(vm.getGuestOsArch()); setGuestOsCodename(vm.getGuestOsCodename()); setGuestOsDistribution(vm.getGuestOsDistribution()); setGuestOsKernelVersion(vm.getGuestOsKernelVersion()); setGuestOsType(vm.getGuestOsType()); setGuestOsVersion(vm.getGuestOsVersion()); setGuestOsTimezoneName(vm.getGuestOsTimezoneName()); setGuestOsTimezoneOffset(vm.getGuestOsTimezoneOffset()); }

Target:
public void updateRunTimeDynamicData(VmDynamic vm, Guid vdsId, String vdsName) { setStatus(vm.getStatus()); setRunOnVds(vdsId); setRunOnVdsName(vdsName); setVmHost(vm.getVmHost()); setVmIp(vm.getVmIp()); setVmFQDN(vm.getVmFQDN()); if (vm.getCurrentCd() != null) { setCurrentCd(vm.getCurrentCd()); } setAppList(vm.getAppList()); setGuestOs(vm.getGuestOs()); getDynamicData().setVncKeyboardLayout(vm.getVncKeyboardLayout()); setKvmEnable(vm.getKvmEnable()); setAcpiEnable(vm.getAcpiEnable()); setGuestCurrentUserName(vm.getGuestCurrentUserName()); setWin2kHackEnable(vm.getWin2kHackEnable()); setUtcDiff(vm.getUtcDiff()); setExitStatus(vm.getExitStatus()); setExitMessage(vm.getExitMessage()); setExitReason(vm.getExitReason()); setClientIp(vm.getClientIp()); setVmPauseStatus(vm.getPauseStatus()); setLastWatchdogEvent(vm.getLastWatchdogEvent()); setGuestCpuCount(vm.getGuestCpuCount()); setGraphicsInfos(new HashMap<>(vm.getGraphicsInfos())); getDynamicData().setGuestMemoryBuffered(vm.getGuestMemoryBuffered()); getDynamicData().setGuestMemoryCached(vm.getGuestMemoryCached()); getDynamicData().setGuestMemoryFree(vm.getGuestMemoryFree()); setGuestOsArch(vm.getGuestOsArch()); setGuestOsCodename(vm.getGuestOsCodename()); setGuestOsDistribution(vm.getGuestOsDistribution()); setGuestOsKernelVersion(vm.getGuestOsKernelVersion()); setGuestOsType(vm.getGuestOsType()); setGuestOsVersion(vm.getGuestOsVersion()); setGuestOsTimezoneName(vm.getGuestOsTimezoneName()); setGuestOsTimezoneOffset(vm.getGuestOsTimezoneOffset()); }
Source:
public void onLoad(MatrixRun run){ ParametersAction action = run.getParentBuild().getAction(ParametersAction.class); if(action!=null){ parameters = new ArrayList<ParameterValue>(action.getParameters()); } else{ parameters = Collections.EMPTY_LIST; } }

Target:
public void onLoad(MatrixRun run){ ParametersAction action = run.getParentBuild().getAction(ParametersAction.class); if (action != null){ parameters = new ArrayList<ParameterValue>(action.getParameters()); } else{ parameters = Collections.emptyList(); } }
Source:
public void execute(Environment environment, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { if (params.get("date") == null) { throw new TemplateModelException("date parameter is required"); } String jsonDate = params.get("date").toString(); if (params.get("format") == null) { throw new TemplateModelException("format parameter is required"); } DateTimeFormatter format = DateTimeFormatter.ofPattern(params.get("format").toString()); String formattedDate = (jsonDate.length() <= 10) ? LocalDate.parse(jsonDate).format(format) : ZonedDateTime.parse(jsonDate).format(format); environment.getOut().write(formattedDate); }

Target:
public void execute(Environment environment, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { if (params.get("date") == null) { throw new TemplateModelException("date parameter is required"); } String jsonDate = params.get("date").toString(); if (params.get("format") == null) { throw new TemplateModelException("format parameter is required"); } DateTimeFormatter format = DateTimeFormatter.ofPattern(params.get("format").toString()); String formattedDate = (jsonDate.length() <= 10) ? LocalDate.parse(jsonDate).format(format) : Instant.parse(jsonDate).atZone(GMT).format(format); environment.getOut().write(formattedDate); }
Source:
public void testUnmarshallTopLevelEmptyEventProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_START_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); StartErrorEvent emptyTop = getStartNodeById(diagram, EMPTY_TOP_LEVEL_EVENT_ID, getStartEventType()); assertGeneralSet(emptyTop.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertErrorEventExecutionSet(emptyTop.getExecutionSet(), EMPTY_VALUE, NON_INTERRUPTING, ""); assertDataIOSet(emptyTop.getDataIOSet(), EMPTY_VALUE); }

Target:
public void testUnmarshallTopLevelEmptyEventProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_START_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); StartErrorEvent emptyTop = getStartNodeById(diagram, EMPTY_TOP_LEVEL_EVENT_ID, getStartEventType()); assertGeneralSet(emptyTop.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertErrorEventExecutionSet(emptyTop.getExecutionSet(), EMPTY_VALUE, NON_INTERRUPTING, EMPTY_VALUE); assertDataIOSet(emptyTop.getDataIOSet(), EMPTY_VALUE); }
Source:
private void updateStates(Stack stack, Collection<InstanceMetaData> failedInstances, Set<String> newFailedNodeNames, Set<String> newHealtyHostNames, boolean hostCertExpiring) { clusterService.updateClusterCertExpirationState(stack.getCluster(), hostCertExpiring); clusterOperationService.reportHealthChange(stack.getResourceCrn(), newFailedNodeNames, newHealtyHostNames); if (!failedInstances.isEmpty()) { clusterService.updateClusterStatusByStackId(stack.getId(), Status.AMBIGUOUS); } else if (statesFromAvailabeAllowed().contains(stack.getCluster().getStatus())) { clusterService.updateClusterStatusByStackId(stack.getId(), Status.AVAILABLE); } }

Target:
private void updateStates(Stack stack, Collection<InstanceMetaData> failedInstances, Set<String> newFailedNodeNames, Set<String> newHealtyHostNames, boolean hostCertExpiring) { LOGGER.info("Updating status: Failed instances: New failed node names: New healthy host name: Host cert expiring: {}", failedInstances, newFailedNodeNames, newHealtyHostNames, hostCertExpiring); clusterService.updateClusterCertExpirationState(stack.getCluster(), hostCertExpiring); clusterOperationService.reportHealthChange(stack.getResourceCrn(), newFailedNodeNames, newHealtyHostNames); if (!failedInstances.isEmpty()) { clusterService.updateClusterStatusByStackId(stack.getId(), Status.AMBIGUOUS); } else if (statesFromAvailabeAllowed().contains(stack.getCluster().getStatus())) { clusterService.updateClusterStatusByStackId(stack.getId(), Status.AVAILABLE); } }
Source:
public void shouldSetMongoPrefsOnScanResult() throws Exception { SharedPreferences sharedPrefs = ShadowPreferenceManager.getDefaultSharedPreferences(Robolectric.application.getApplicationContext()); String mongoUri = "mongodb://user:pass@test.com/cgm_data"; String mongoCollection = "cgm_data"; String deviceStatusCollection = "devicestatus"; JSONObject json = new JSONObject(); JSONObject child = new JSONObject(); child.put(NSBarcodeConfigKeys.MONGO_URI,mongoUri); child.put(NSBarcodeConfigKeys.MONGO_COLLECTION, mongoCollection); child.put(NSBarcodeConfigKeys.MONGO_DEVICE_STATUS_COLLECTION,deviceStatusCollection); json.put(NSBarcodeConfigKeys.MONGO_CONFIG,child); System.out.println(json.toString()); Intent intent = createFakeScanIntent(json.toString()); new SettingsActivity().onActivityResult(IntentIntegrator.REQUEST_CODE,Activity.RESULT_OK, intent); assertThat(sharedPrefs.getBoolean(PreferenceKeys.MONGO_UPLOADER_ENABLED,false),is(true)); assertThat(sharedPrefs.getString(PreferenceKeys.MONGO_URI,null),is(mongoUri)); assertThat(sharedPrefs.getString(PreferenceKeys.MONGO_COLLECTION,null),is(mongoCollection)); assertThat(sharedPrefs.getString(PreferenceKeys.MONGO_DEVICE_STATUS_COLLECTION,null),is(deviceStatusCollection)); assertThat(sharedPrefs.getBoolean(PreferenceKeys.API_UPLOADER_ENABLED,true),is(false)); }

Target:
public void shouldSetMongoPrefsOnScanResult() throws Exception { String mongoUri = "mongodb://user:pass@test.com/cgm_data"; String mongoCollection = "cgm_data"; String deviceStatusCollection = "devicestatus"; JSONObject json = new JSONObject(); JSONObject child = new JSONObject(); child.put(NSBarcodeConfigKeys.MONGO_URI, mongoUri); child.put(NSBarcodeConfigKeys.MONGO_COLLECTION, mongoCollection); child.put(NSBarcodeConfigKeys.MONGO_DEVICE_STATUS_COLLECTION, deviceStatusCollection); json.put(NSBarcodeConfigKeys.MONGO_CONFIG,child); System.out.println(json.toString()); Intent intent = createFakeScanIntent(json.toString()); new SettingsActivity().onActivityResult(IntentIntegrator.REQUEST_CODE, Activity.RESULT_OK, intent); assertThat(sharedPrefs.getBoolean(PreferenceKeys.MONGO_UPLOADER_ENABLED, false), is(true)); assertThat(sharedPrefs.getString(PreferenceKeys.MONGO_URI, null), is(mongoUri)); assertThat(sharedPrefs.getString(PreferenceKeys.MONGO_COLLECTION, null), is(mongoCollection)); assertThat(sharedPrefs.getString(PreferenceKeys.MONGO_DEVICE_STATUS_COLLECTION, null), is(deviceStatusCollection)); assertThat(sharedPrefs.getBoolean(PreferenceKeys.API_UPLOADER_ENABLED, true), is(false)); }