auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public TestingSourceOperator( SourceReader<T, MockSourceSplit> reader, WatermarkStrategy<T> watermarkStrategy, ProcessingTimeService timeService, OperatorEventGateway eventGateway, int subtaskIndex, int parallelism, boolean emitProgressiveWatermarks) { super( (context) -> reader, eventGateway, new MockSourceSplitSerializer(), watermarkStrategy, timeService, new Configuration(), "localhost", emitProgressiveWatermarks); this.subtaskIndex = subtaskIndex; this.parallelism = parallelism; this.metrics = UnregisteredMetricGroups.createUnregisteredOperatorMetricGroup(); this.readerCreated = false; this.sourceMetricGroup = new TestingSourceMetricGroup(); }

Target:
public TestingSourceOperator( SourceReader<T, MockSourceSplit> reader, WatermarkStrategy<T> watermarkStrategy, ProcessingTimeService timeService, OperatorEventGateway eventGateway, int subtaskIndex, int parallelism, boolean emitProgressiveWatermarks) { super( (context) -> reader, eventGateway, new MockSourceSplitSerializer(), watermarkStrategy, timeService, new Configuration(), "localhost", emitProgressiveWatermarks, new TestingSourceMetricGroup()); this.subtaskIndex = subtaskIndex; this.parallelism = parallelism; this.metrics = UnregisteredMetricGroups.createUnregisteredOperatorMetricGroup(); this.readerCreated = false; }
Source:
public void connect(String connectionString, Properties info) throws SQLException { registerDriver(); if (currentConnection != null) { closeConnection(); } currentConnection = DriverManager.getConnection(connectionString, info); afterConnectionEstablished(); }

Target:
public void connect(String connectionString, Properties info) throws SQLException { registerDriver(); closeConnection(); currentConnection = DriverManager.getConnection(connectionString, info); afterConnectionEstablished(); }
Source:
public String getImage(String imageKey, IMAGE_SIZE_TYPE sizeType) throws MambuApiException { ParamsMap params = new ParamsMap(); if (sizeType != null) params.put(SIZE, sizeType.name()); String urlString = new String(mambuAPIService.createUrl(IMAGES + "/" + imageKey)); String apiResponse = mambuAPIService.executeRequest(urlString, params, Method.GET); final String encodingStartsAfter = "base64,"; final int dataStart = apiResponse.indexOf(encodingStartsAfter) + encodingStartsAfter.length(); String base64EncodedString = apiResponse.substring(dataStart); base64EncodedString = base64EncodedString.replaceAll("(\\\\r)?\\\\n", ""); return base64EncodedString; }

Target:
public String getImage(String imageKey, IMAGE_SIZE_TYPE sizeType) throws MambuApiException { if (imageKey == null) { throw new IllegalArgumentException("Image key cannot be null"); } ParamsMap params = new ParamsMap(); if (sizeType != null) { params.put(SIZE, sizeType.name()); } String urlString = new String(mambuAPIService.createUrl(IMAGES + "/" + imageKey)); String apiResponse = mambuAPIService.executeRequest(urlString, params, Method.GET); final String encodingStartsAfter = "base64,"; String base64EncodedString = null; if (apiResponse != null && apiResponse.contains(encodingStartsAfter)) { final int dataStart = apiResponse.indexOf(encodingStartsAfter) + encodingStartsAfter.length(); base64EncodedString = apiResponse.substring(dataStart); base64EncodedString = base64EncodedString.replaceAll("(\\\\r)?\\\\n", ""); } return base64EncodedString; }
Source:
private Set<String> getReadGroups(SingularityRequest request) { Set<String> allowedReadGroups = new HashSet<>( authConfiguration.getGlobalReadOnlyGroups() ); allowedReadGroups.addAll(authConfiguration.getGlobalReadWriteGroups()); if (request.getActionPermissions().isPresent()) { request .getActionPermissions() .get() .entrySet() .stream() .filter( e -> e.getValue().contains(SingularityAuthorizationScope.READ) || e.getValue().contains(SingularityAuthorizationScope.WRITE) ) .map(Entry::getKey) .forEach(allowedReadGroups::add); } else { if (!request.getReadOnlyGroups().isPresent()) { allowedReadGroups.addAll(authConfiguration.getDefaultReadOnlyGroups()); } request.getReadOnlyGroups().ifPresent(allowedReadGroups::addAll); request.getReadWriteGroups().ifPresent(allowedReadGroups::addAll); } request.getGroup().ifPresent(allowedReadGroups::add); if (allowedReadGroups.isEmpty()) { LOG.warn("No read-enabled groups set for {}", request.getId()); } return allowedReadGroups; }

Target:
private Set<String> getReadGroups(SingularityRequest request) { Set<String> allowedReadGroups = new HashSet<>( authConfiguration.getGlobalReadOnlyGroups() ); allowedReadGroups.addAll(authConfiguration.getGlobalReadWriteGroups()); if (!request.getReadOnlyGroups().isPresent()) { allowedReadGroups.addAll(authConfiguration.getDefaultReadOnlyGroups()); } request.getReadOnlyGroups().ifPresent(allowedReadGroups::addAll); request.getReadWriteGroups().ifPresent(allowedReadGroups::addAll); request.getGroup().ifPresent(allowedReadGroups::add); if (allowedReadGroups.isEmpty()) { LOG.warn("No read-enabled groups set for {}", request.getId()); } return allowedReadGroups; }
Source:
private byte[] handleBeginDownloadMessage(byte[] message, byte[] msgNumber) { boolean msgValid = true; if (message.length < 25 || message.length > 65534) { msgValid = false; } else { fileLength = message[4] & 0xFF | (message[5] & 0xFF) << 8 | (message[6] & 0xFF) << 16 | (message[7] & 0xFF) << 24; } replyRequired = true; return getDownloadReply(msgValid, msgNumber, message[3]); }

Target:
private byte[] handleBeginDownloadMessage(byte[] message, byte[] msgNumber) { boolean msgValid = true; if (message.length < MIN_BEGIN_DOWNLOAD_LENGTH || message.length > MAX_MESSAGE_LENGTH) { msgValid = false; } else { fileLength = message[4] & 0xFF | (message[5] & 0xFF) << 8 | (message[6] & 0xFF) << 16 | (message[7] & 0xFF) << 24; } replyRequired = true; return getDownloadReply(msgValid, msgNumber, message[3]); }
Source:
protected boolean subdirectoryExists(String subdirectoryName) { String fullSubdirectory = String.format("%s%s", rootPath, subdirectoryName); try (JarFile jar = new JarFile(jarFile)) { Enumeration<JarEntry> jarEntries = jar.entries(); while (jarEntries.hasMoreElements()) { JarEntry entry = jarEntries.nextElement(); String entryName = entry.getName(); if (entryName.startsWith(fullSubdirectory)) { return true; } } return false; } catch (Exception e) { throw new IllegalArgumentException( Messages.format("Error loading resource from JAR file: {}", jarFile), e); } }

Target:
protected boolean subdirectoryExists(String subdirectoryName) { String resolvedName = subdirectoryName.startsWith(File.separator) ? subdirectoryName.substring(1) : subdirectoryName; if (resolvedName.endsWith(File.separator)) { resolvedName = resolvedName.substring(0, resolvedName.length() - 1); } return entries.contains(resolvedName); }
Source:
public CompletableFuture<String> callGreeting(String name) { if (ms != null) { return this.greetingService.greeting(name); } else { return CompletableFuture.completedFuture("microservices is not set"); } }

Target:
public CompletableFuture<String> callGreeting(String name) { return this.greetingService.greeting(name); }
Source:
private int access(Parameters requireCapabilities) { return requireCapabilities.entrySet() .stream() .filter(entry -> Header.removeDuplicateMarker(entry.getKey()) .equals(EXTENDER_NAMESPACE)) .findAny() .map(entry -> ModuleAttribute.ACC_OPEN) .orElse(0); }

Target:
private int access(Parameters requireCapabilities) { return requireCapabilities.entrySet() .stream() .filter(entry -> Header.removeDuplicateMarker(entry.getKey()) .equals(EXTENDER_NAMESPACE)) .mapToInt(entry -> ModuleAttribute.ACC_OPEN) .findAny() .orElse(0); }
Source:
private Response delete(BaseDataAccessor zkBaseDataAccessor, String path) { Stat stat = zkBaseDataAccessor.getStat(path, AccessOption.PERSISTENT); if (stat != null && stat.getEphemeralOwner() <= 0) { throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN) .entity(String.format("Deleting a non ephemeral node is not allowed", path)).build()); } Boolean ret = zkBaseDataAccessor.remove(path, AccessOption.PERSISTENT); Map<String, String> result = ImmutableMap.of(ZooKeeperCommand.delete.name(), ret.toString(), PATH_STR, path); return JSONRepresentation(result); }

Target:
private Response delete(BaseDataAccessor zkBaseDataAccessor, String path) { Stat stat = zkBaseDataAccessor.getStat(path, AccessOption.PERSISTENT); if (stat == null) { return notFound(); } else if (stat.getEphemeralOwner() <= 0) { throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN) .entity(String.format("Deleting a non-ephemeral node is not allowed.")).build()); } if (zkBaseDataAccessor.remove(path, AccessOption.PERSISTENT)) { return OK(); } else { throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(String.format("Failed to delete %s.", path)).build()); } }
Source:
public void requestHandleWithGoodInputTest() throws Exception { doRequestHandleTest(HttpMethod.POST, "POST", false, false); doRequestHandleTest(HttpMethod.GET, "GET", false, false); doRequestHandleTest(HttpMethod.DELETE, "DELETE", false, false); doRequestHandleTest(HttpMethod.GET, "GET", false, true); }

Target:
public void requestHandleWithGoodInputTest() throws Exception { doRequestHandleTest(HttpMethod.POST, "POST", false, false); doRequestHandleTest(HttpMethod.GET, "GET", false, false); doRequestHandleTest(HttpMethod.DELETE, "DELETE", false, false); doRequestHandleTest(HttpMethod.POST, "POST", false, true); doRequestHandleTest(HttpMethod.GET, "GET", false, true); doRequestHandleTest(HttpMethod.DELETE, "DELETE", false, true); }
Source:
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); try { if (evt instanceof IdleStateEvent) { logger.info("IdleStateEvent triggered, close channel " + channel); channel.close(); } super.userEventTriggered(ctx, evt); } finally { NettyChannel.removeChannelIfDisconnected(ctx.channel()); } }

Target:
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); try { logger.info("IdleStateEvent triggered, close channel " + channel); channel.close(); } finally { NettyChannel.removeChannelIfDisconnected(ctx.channel()); } } super.userEventTriggered(ctx, evt); }
Source:
public void setProfilerMode(boolean profilerMode) { if (profilerMode == profilerMode_) { return; } profilerMode_ = profilerMode; setSecondaryToolbarVisible(debugMode_ || profilerMode_); secondaryToolbar_.removeAllWidgets(); if (profilerMode_) { if (debugMode_) { loadDebugToolsIntoSecondaryToolbar(); } loadProfilerToolsIntoSecondaryToolbar(); } else if (debugMode_) { loadDebugToolsIntoSecondaryToolbar(); } }

Target:
public void setProfilerMode(boolean profilerMode) { if (profilerMode == profilerMode_) { return; } profilerMode_ = profilerMode; loadDebugToolsIntoSecondaryToolbar(); }
Source:
private void assertCopy(FullBinaryMemcacheRequest expected, ByteBuf expectedContent, FullBinaryMemcacheRequest actual) { assertNotSame(expected, actual); assertTrue(ByteBufUtil.equals(expected.key(), actual.key())); assertTrue(ByteBufUtil.equals(expected.extras(), actual.extras())); assertTrue(ByteBufUtil.equals(expectedContent, actual.content())); assertEquals(expected.reserved(), actual.reserved()); assertEquals(expected.magic(), actual.magic()); assertEquals(expected.opcode(), actual.opcode()); assertEquals(expected.keyLength(), actual.keyLength()); assertEquals(expected.extrasLength(), actual.extrasLength()); assertEquals(expected.dataType(), actual.dataType()); assertEquals(expected.totalBodyLength(), actual.totalBodyLength()); assertEquals(expected.opaque(), actual.opaque()); assertEquals(expected.cas(), actual.cas()); }

Target:
private void assertCopy(FullBinaryMemcacheRequest expected, ByteBuf expectedContent, FullBinaryMemcacheRequest actual) { assertNotSame(expected, actual); assertEquals(expected.key(), actual.key()); assertEquals(expected.extras(), actual.extras()); assertEquals(expectedContent, actual.content()); assertEquals(expected.reserved(), actual.reserved()); assertEquals(expected.magic(), actual.magic()); assertEquals(expected.opcode(), actual.opcode()); assertEquals(expected.keyLength(), actual.keyLength()); assertEquals(expected.extrasLength(), actual.extrasLength()); assertEquals(expected.dataType(), actual.dataType()); assertEquals(expected.totalBodyLength(), actual.totalBodyLength()); assertEquals(expected.opaque(), actual.opaque()); assertEquals(expected.cas(), actual.cas()); }
Source:
public ChargeQueryResponse queryPaymentStatus(ChargeEntity charge) throws GatewayException { logger.info("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); GatewayClient.Response response = inquiryClient.postRequestFor( gatewayUrlMap.get(charge.getGatewayAccount().getType()), charge.getGatewayAccount(), buildQuery(charge), getGatewayAccountCredentialsAsAuthHeader(charge.getGatewayAccount()) ); GatewayResponse<WorldpayQueryResponse> worldpayGatewayResponse = getWorldpayGatewayResponse(response, WorldpayQueryResponse.class); return worldpayGatewayResponse.getBaseResponse() .map(ChargeQueryResponse::from) .orElseThrow(() -> new WebApplicationException(format( "Unable to query charge %s - an error occurred: %s", charge.getExternalId(), worldpayGatewayResponse ))); }

Target:
public ChargeQueryResponse queryPaymentStatus(ChargeEntity charge) throws GatewayException { GatewayClient.Response response = inquiryClient.postRequestFor( gatewayUrlMap.get(charge.getGatewayAccount().getType()), charge.getGatewayAccount(), buildQuery(charge), getGatewayAccountCredentialsAsAuthHeader(charge.getGatewayAccount()) ); GatewayResponse<WorldpayQueryResponse> worldpayGatewayResponse = getWorldpayGatewayResponse(response, WorldpayQueryResponse.class); return worldpayGatewayResponse.getBaseResponse() .map(ChargeQueryResponse::from) .orElseThrow(() -> new WebApplicationException(format( "Unable to query charge %s - an error occurred: %s", charge.getExternalId(), worldpayGatewayResponse ))); }
Source:
public void setUserSharingScope(Context context, String scope) { userSessionInfo.setSharingScope(scope); saveUserSession(context, userSessionInfo); service.dataSharing(new SharingOptionBody(scope)) .compose(ObservableUtils.applyDefault()).subscribe(response -> LogExt.d(getClass(), "Response: " + response.code() + ", message: " + response.message()), error -> { LogExt.e(getClass(), error.getMessage()); }); }

Target:
public void setUserSharingScope(Context context, String scope) { service.dataSharing(new SharingOptionBody(scope)) .compose(ObservableUtils.applyDefault()) .doOnNext(response -> { if(response.isSuccess()) { userSessionInfo.setSharingScope(scope); saveUserSession(context, userSessionInfo); } }) .subscribe(response -> LogExt.d(getClass(), "Response: " + response.code() + ", message: " + response.message()), error -> { LogExt.e(getClass(), error.getMessage()); }); }
Source:
public void sendMessage(Message... messages) { List<String> s = new ArrayList<String>(); for (Message message : messages) { if (message instanceof Message.Text) s.add((String) message.getContent()); } this.sendMessage(s.toArray(new String[s.size()])); }

Target:
public void sendMessage(Message... messages) { for (Message message : messages) { if (message instanceof Message.Text) { this.addChatMessage(new ChatComponentText((String) message.getContent())); } else { this.addChatMessage(new ChatComponentText(message.toLegacy())); } } }
Source:
private boolean isDomainAttachedToDifferentStoragePool() { if (getStoragePool().getStatus() == StoragePoolStatus.Uninitialized) { for (Guid storageDomainId : getParameters().getStorages()) { StorageDomain domain = DbFacade.getInstance().getStorageDomainDao().get(storageDomainId); if (domain.getStorageDomainType().isDataDomain() && isStorageDomainAttachedToStoragePool(domain)) { return failCanDoAction(VdcBllMessages.ERROR_CANNOT_ADD_STORAGE_DOMAIN_WITH_ATTACHED_DATA_DOMAIN); } } } return true; }

Target:
private boolean isDomainAttachedToDifferentStoragePool() { if (getStoragePool().getStatus() == StoragePoolStatus.Uninitialized) { for (Guid storageDomainId : getParameters().getStorages()) { StorageDomain domain = getStorageDomainDAO().get(storageDomainId); if (domain.getStorageDomainType().isDataDomain() && isStorageDomainAttachedToStoragePool(domain)) { return failCanDoAction(VdcBllMessages.ERROR_CANNOT_ADD_STORAGE_DOMAIN_WITH_ATTACHED_DATA_DOMAIN); } } } return true; }
Source:
public void getCheckRuns() throws Exception { GHCheckRuns checkRuns = getRepository().getCheckRuns("8051615eff597f4e49f4f47625e6fc2b49f26bfc"); assertThat(checkRuns.getTotalCount(), equalTo(2)); assertThat(checkRuns.getCheckRuns(), hasSize(2)); assertThat(checkRuns.getCheckRuns().get(0).getName(), equalTo("Travis CI - Pull Request")); assertThat(checkRuns.getCheckRuns().get(1).getName(), equalTo("Travis CI - Branch")); }

Target:
public void getCheckRuns() throws Exception { final int expectedCount = 8; PagedIterable<GHCheckRun> checkRuns = gitHub.getOrganization("github-api") .getRepository("github-api") .getCheckRuns("78b9ff49d47daaa158eb373c4e2e040f739df8b9"); assertThat(checkRuns.withPageSize(2).iterator().nextPage(), hasSize(2)); int checkRunsCount = 0; for (GHCheckRun checkRun : checkRuns) { assertThat(checkRun.getConclusion(), equalTo("success")); checkRunsCount++; } assertThat(checkRunsCount, equalTo(expectedCount)); }
Source:
public static boolean isProvider(URL url) { return PROVIDERS_CATEGORY.equals(url.getParameter(Constants.CATEGORY_KEY, PROVIDERS_CATEGORY)) && !OVERRIDE_PROTOCOL.equals(url.getProtocol()) && !ROUTE_PROTOCOL.equals(url.getProtocol()); }

Target:
public static boolean isProvider(URL url) { return !OVERRIDE_PROTOCOL.equals(url.getProtocol()) && !ROUTE_PROTOCOL.equals(url.getProtocol()) && PROVIDERS_CATEGORY.equals(url.getParameter(CATEGORY_KEY, PROVIDERS_CATEGORY)); }
Source:
synchronized public FirebaseAnalytics getAnalyticsInstance() { analyticsInstance.setUserId(getUserIdOrNull()); return this.analyticsInstance; }

Target:
synchronized public FirebaseAnalytics getAnalyticsInstance() { if (analyticsInstance == null) { analyticsInstance = FirebaseAnalytics.getInstance(this); } analyticsInstance.setUserId(getUserIdOrNull()); return analyticsInstance; }
Source:
@Nullable protected ITmfTreeViewerEntry updateElements(long start, long end, boolean isSelection) { if (isSelection || (start == end)) { return null; } TmfAbstractAnalysisModule analysisModule = getStatisticsAnalysisModule(); if (getTrace() == null || !(analysisModule instanceof LatencyStatisticsAnalysisModule)) { return null; } LatencyStatisticsAnalysisModule module = (LatencyStatisticsAnalysisModule) analysisModule; module.waitForCompletion(); LatencyStatistics entry = module.getTotalStats(); TmfTreeViewerEntry root = new TmfTreeViewerEntry(""); List<ITmfTreeViewerEntry> entryList = root.getChildren(); TmfTreeViewerEntry child = new LatencyTreeViewerEntry(checkNotNull(Messages.LatencyStatistics_TotalLabel), checkNotNull(entry)); entryList.add(child); HiddenTreeViewerEntry syscalls = new HiddenTreeViewerEntry(checkNotNull(SYSCALL_LEVEL)); child.addChild(syscalls); Map<String, LatencyStatistics> perSyscallStats = module.getPerSyscallStats(); if (perSyscallStats != null) { Iterator<Entry<@NonNull String, @NonNull LatencyStatistics>> stats = perSyscallStats.entrySet().iterator(); while (stats.hasNext()) { Entry<String, LatencyStatistics> statsEntry = stats.next(); syscalls.addChild(new LatencyTreeViewerEntry(statsEntry.getKey(), statsEntry.getValue())); } } return root; }

Target:
@Nullable protected ITmfTreeViewerEntry updateElements(long start, long end, boolean isSelection) { if (isSelection || (start == end)) { return null; } TmfAbstractAnalysisModule analysisModule = getStatisticsAnalysisModule(); if (getTrace() == null || !(analysisModule instanceof LatencyStatisticsAnalysisModule)) { return null; } LatencyStatisticsAnalysisModule module = (LatencyStatisticsAnalysisModule) analysisModule; module.waitForCompletion(); LatencyStatistics entry = module.getTotalStats(); TmfTreeViewerEntry root = new TmfTreeViewerEntry(""); List<ITmfTreeViewerEntry> entryList = root.getChildren(); TmfTreeViewerEntry child = new LatencyTreeViewerEntry(checkNotNull(Messages.LatencyStatistics_TotalLabel), checkNotNull(entry)); entryList.add(child); HiddenTreeViewerEntry syscalls = new HiddenTreeViewerEntry(checkNotNull(SYSCALL_LEVEL)); child.addChild(syscalls); Map<String, LatencyStatistics> perSyscallStats = module.getPerSyscallStats(); if (perSyscallStats != null) { Iterator<Entry<String, LatencyStatistics>> stats = perSyscallStats.entrySet().iterator(); while (stats.hasNext()) { Entry<String, LatencyStatistics> statsEntry = stats.next(); syscalls.addChild(new LatencyTreeViewerEntry(statsEntry.getKey(), statsEntry.getValue())); } } return root; }
Source:
private Data getNextBlock() { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; boolean abortTransaction = false; try { con = DbConnectionManager.getTransactionConnection(); pstmt = con.prepareStatement(LOAD_ID); pstmt.setInt(1, type); rs = pstmt.executeQuery(); long currentID = 1; if (rs.next()) { currentID = rs.getLong(1); } else { createNewID(con, type); } DbConnectionManager.fastcloseStmt(rs, pstmt); long newID = currentID + blockSize; pstmt = con.prepareStatement(UPDATE_ID); pstmt.setLong(1, newID); pstmt.setInt(2, type); pstmt.setLong(3, currentID); if (pstmt.executeUpdate() == 1) { final Data result = new Data(currentID, newID); sequenceBlocks.put(type, result); return result; } else { throw new IllegalStateException("Failed at attempt to obtain an ID, aborting..."); } } catch (SQLException e) { Log.error("An exception occurred while trying to obtain new sequence values from the database for type {}", type, e); abortTransaction = true; throw new IllegalStateException("Failed at attempt to obtain an ID, aborting...", e); } finally { DbConnectionManager.closeStatement(rs, pstmt); DbConnectionManager.closeTransactionConnection(con, abortTransaction); } }

Target:
private Data getNextBlock() { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(LOAD_ID); pstmt.setInt(1, type); rs = pstmt.executeQuery(); long currentID = 1; if (rs.next()) { currentID = rs.getLong(1); } else { createNewID(con, type); } DbConnectionManager.fastcloseStmt(rs, pstmt); long newID = currentID + blockSize; pstmt = con.prepareStatement(UPDATE_ID); pstmt.setLong(1, newID); pstmt.setInt(2, type); pstmt.setLong(3, currentID); if (pstmt.executeUpdate() == 1) { final Data result = new Data(currentID, newID); sequenceBlocks.put(type, result); return result; } else { throw new IllegalStateException("Failed at attempt to obtain an ID, aborting..."); } } catch (SQLException e) { Log.error("An exception occurred while trying to obtain new sequence values from the database for type {}", type, e); throw new IllegalStateException("Failed at attempt to obtain an ID, aborting...", e); } finally { DbConnectionManager.closeConnection(rs, pstmt, con); } }
Source:
public void adDisplayed(final AppLovinAd ad) { ApplovinAdapter.log( DEBUG, adType + " displayed" ); runOnUiThread(new Runnable() { @Override public void run() { if ( isRewarded ) { rewardedListener.onAdOpened( adapter ); reward = null; } else { interstitialListener.onAdOpened( adapter ); } } }); fullyWatched = false; }

Target:
public void adDisplayed(final AppLovinAd ad) { ApplovinAdapter.log( DEBUG, adType + " displayed" ); runOnUiThread(new Runnable() { @Override public void run() { if ( isRewarded ) { rewardedListener.onAdOpened( adapter ); } else { interstitialListener.onAdOpened( adapter ); } } }); fullyWatched = false; }
Source:
protected void handleHMSMessage(String data) { if (data.startsWith("H")) { String device = data.substring(1, 5); String woHeader = data.substring(5, data.length() - 1); String s1 = woHeader.substring(0, 1); String batteryStatus = "ok"; boolean isEmpty = (s1.charAt(0) & 2) == 2; boolean isReplaced = (s1.charAt(0) & 4) == 4; if (isEmpty) { batteryStatus = "empty"; } else if (isReplaced) { batteryStatus = "replaced"; } double temperature = Integer.parseInt(woHeader.substring(5, 6) + woHeader.substring(2, 4)) / 10.0; boolean isNegative = (s1.charAt(0) & 8) == 8; if (isNegative) { temperature = -temperature; } double humidity = Integer.parseInt(woHeader.substring(6, 8) + woHeader.substring(4, 5)) / 10.0; logger.info("device: " + device + ", T: " +(!isNegative?" ":"")+ temperature + ",\tH: " + humidity + ", Bat.: " + batteryStatus); HMSBindingConfig temperatureConfig = findConfig(device, HMSBindingConfig.Datapoint.TEMPERATURE); if (temperatureConfig != null) { updateItem(temperatureConfig.item, temperature); } HMSBindingConfig humidityConfig = findConfig(device, HMSBindingConfig.Datapoint.HUMIDITY); if (humidityConfig != null) { updateItem(humidityConfig.item, humidity); } } else { logger.warn("Received unparseable message: " + data); } }

Target:
protected void handleHMSMessage(String data) { if (data.startsWith("H")) { String device = data.substring(1, 5); String woHeader = data.substring(5, data.length() - 1); String s1 = woHeader.substring(0, 1); String batteryStatus = "ok"; boolean isEmpty = (s1.charAt(0) & 2) == 2; boolean isReplaced = (s1.charAt(0) & 4) == 4; if (isEmpty) { batteryStatus = "empty"; } else if (isReplaced) { batteryStatus = "replaced"; } double temperature = Integer.parseInt(woHeader.substring(5, 6) + woHeader.substring(2, 4)) / 10.0; boolean isNegative = (s1.charAt(0) & 8) == 8; if (isNegative) { temperature = -temperature; } double humidity = Integer.parseInt(woHeader.substring(6, 8) + woHeader.substring(4, 5)) / 10.0; logger.info("device: {}, T: {},\tH: {}, Bat.: {}", device, (!isNegative ? " " : "") + temperature, humidity, batteryStatus); HMSBindingConfig temperatureConfig = findConfig(device, HMSBindingConfig.Datapoint.TEMPERATURE); if (temperatureConfig != null) { updateItem(temperatureConfig.item, temperature); } HMSBindingConfig humidityConfig = findConfig(device, HMSBindingConfig.Datapoint.HUMIDITY); if (humidityConfig != null) { updateItem(humidityConfig.item, humidity); } } else { logger.warn("Received unparseable message: " + data); } }
Source:
public void salvageUnit(int i) { TestUnit salvageUnit = getPotentialSalvage().get(i); getActualSalvage().add(salvageUnit); }

Target:
public void salvageUnit(int i) { if (i < getPotentialSalvage().size()) { TestUnit salvageUnit = getPotentialSalvage().get(i); getActualSalvage().add(salvageUnit); } }
Source:
private List<ProcessorNode> getAllProcessorNodes() { List<String> processorZNodes = getSortedActiveProcessorsZnodes(); LOG.debug("Active ProcessorZNodes in zookeeper: {}.", processorZNodes); return processorZNodes.stream() .map(processorZNode -> { String ephemeralProcessorPath = String.format("%s/%s", keyBuilder.getProcessorsPath(), processorZNode); String data = zkClient.readData(ephemeralProcessorPath); return new ProcessorNode(new ProcessorData(data), ephemeralProcessorPath); }).collect(Collectors.toList()); }

Target:
private List<ProcessorNode> getAllProcessorNodes() { List<String> processorZNodes = getSortedActiveProcessorsZnodes(); LOG.debug("Active ProcessorZNodes in zookeeper: {}.", processorZNodes); return processorZNodes.stream() .map(processorZNode -> { String ephemeralProcessorPath = String.format("%s/%s", keyBuilder.getProcessorsPath(), processorZNode); String data = readProcessorData(ephemeralProcessorPath); return new ProcessorNode(new ProcessorData(data), ephemeralProcessorPath); }).collect(Collectors.toList()); }
Source:
public void testNonStraddlingJoinExpression() { assertPlan("SELECT * FROM orders JOIN lineitem ON orders.orderkey = lineitem.orderkey AND cast(lineitem.linenumber AS varchar) = '2'", anyTree( join(INNER, ImmutableList.of(equiJoinClause("ORDERS_OK", "LINEITEM_OK")), anyTree( filter("ORDERS_OK IS NOT NULL", tableScan("orders", ImmutableMap.of("ORDERS_OK", "orderkey")))), anyTree( filter("LINEITEM_OK IS NOT NULL AND cast(LINEITEM_LINENUMBER as varchar) = cast('2' as varchar)", tableScan("lineitem", ImmutableMap.of( "LINEITEM_OK", "orderkey", "LINEITEM_LINENUMBER", "linenumber"))))))); }

Target:
public void testNonStraddlingJoinExpression() { assertPlan("SELECT * FROM orders JOIN lineitem ON orders.orderkey = lineitem.orderkey AND cast(lineitem.linenumber AS varchar) = '2'", anyTree( join(INNER, ImmutableList.of(equiJoinClause("ORDERS_OK", "LINEITEM_OK")), any( tableScan("orders", ImmutableMap.of("ORDERS_OK", "orderkey"))), anyTree( filter("cast('2' as varchar) = cast(LINEITEM_LINENUMBER as varchar)", tableScan("lineitem", ImmutableMap.of( "LINEITEM_OK", "orderkey", "LINEITEM_LINENUMBER", "linenumber"))))))); }
Source:
public void write(ResultSet resultSet) throws SQLException { while (resultSet.next()) { connection.setAutoCommit(false); try (PreparedStatement statement = connection.prepareStatement("INSERT INTO " + indexedEntriesTableName + "(ENTRY) VALUES(?)")) { statement.setObject(1, jsonbObject(resultSet.getBytes("ENTRY"))); statement.executeUpdate(); } try (PreparedStatement statement = connection.prepareStatement("UPDATE " + waterMarkTableName + " SET ID = ID + 1, time=now()")) { statement.executeUpdate(); } connection.setAutoCommit(true); } }

Target:
public void write(ResultSet resultSet) throws SQLException { while (resultSet.next()) { connection.setAutoCommit(false); try (PreparedStatement statement = connection.prepareStatement("INSERT INTO " + indexedEntriesTableName + "(ENTRY) VALUES(?)")) { statement.setObject(1, jsonbObject(resultSet.getBytes("ENTRY"))); statement.executeUpdate(); } try (PreparedStatement statement = connection.prepareStatement("UPDATE " + waterMarkTableName + " SET ID = ID + 1, time=now()")) { statement.executeUpdate(); } connection.commit(); } }
Source:
private List<ActivityLogEntry> filterLogsForActivityLogPage(List<AppLogLine> appLogLines, AdminActivityLogPageData data) { List<ActivityLogEntry> appLogs = new LinkedList<ActivityLogEntry>(); for (AppLogLine appLog : appLogLines) { String logMsg = appLog.getLogMessage(); boolean isNotTeammatesLog = !logMsg.contains("TEAMMATESLOG"); boolean isLogFromAdminActivityLogPage = logMsg.contains("adminActivityLogPage"); if (isNotTeammatesLog || isLogFromAdminActivityLogPage) { continue; } ActivityLogEntry activityLogEntry = new ActivityLogEntry(appLog); if (!data.filterLogs(activityLogEntry)) { continue; } if (activityLogEntry.isTestingData() && !data.getIfShowTestData()) { continue; } appLogs.add(activityLogEntry); } return appLogs; }

Target:
private List<ActivityLogEntry> filterLogsForActivityLogPage(List<AppLogLine> appLogLines, AdminActivityLogPageData data) { List<ActivityLogEntry> appLogs = new LinkedList<ActivityLogEntry>(); for (AppLogLine appLog : appLogLines) { String logMsg = appLog.getLogMessage(); boolean isNotTeammatesLog = !logMsg.contains("TEAMMATESLOG"); boolean isLogFromAdminActivityLogPage = logMsg.contains("adminActivityLogPage"); if (isNotTeammatesLog || isLogFromAdminActivityLogPage) { continue; } ActivityLogEntry activityLogEntry = new ActivityLogEntry(appLog); boolean isToShow = data.filterLog(activityLogEntry) && (!activityLogEntry.isTestingData() || data.getIfShowTestData()); if (!isToShow) { continue; } appLogs.add(activityLogEntry); } return appLogs; }
Source:
public void testListTags_404() throws Exception { server.enqueue(response404()); api.getTagApi().listTags(PaginationOptions.Builder.pageSize(100)); assertSent(GET, "/caas/2.4/6ac1e746-b1ea-4da5-a24e-caf1a978789d/tag/tag?pageSize=100"); }

Target:
public void testListTags_404() throws Exception { server.enqueue(response404()); final ImmutableList<Tag> emptyList = api.getTagApi().listTags().concat().toList(); assertSent(GET, expectedListTagsUriBuilder().toString()); assertTrue(emptyList.isEmpty()); }
Source:
private boolean isKitSpecialVariants(Alteration alteration) { boolean isSpecial = false; if (alteration != null && alteration.getGene().getEntrezGeneId() == 3815) { if (!isSpecial) { String[] speicalVariants = {"V654A", "T670I"}; VariantConsequence consequence = VariantConsequenceUtils.findVariantConsequenceByTerm("missense_variant"); for (int i = 0; i < speicalVariants.length; i++) { if (alteration.getGene() != null && alteration.getGene().getEntrezGeneId() == 3815 && alteration.getAlteration() != null && alteration.getAlteration().equals(speicalVariants[i]) && alteration.getConsequence().equals(consequence)) { isSpecial = true; } } } if(!isSpecial) { isSpecial = isInExon17(alteration); } } return isSpecial; }

Target:
private boolean isKitSpecialVariants(Alteration alteration) { boolean isSpecial = false; if (alteration != null && alteration.getGene().getEntrezGeneId() == 3815) { String[] speicalVariants = {"V654A", "T670I"}; VariantConsequence consequence = VariantConsequenceUtils.findVariantConsequenceByTerm("missense_variant"); for (int i = 0; i < speicalVariants.length; i++) { if (alteration.getGene() != null && alteration.getGene().getEntrezGeneId() == 3815 && alteration.getAlteration() != null && alteration.getAlteration().equals(speicalVariants[i]) && alteration.getConsequence().equals(consequence)) { isSpecial = true; break; } } if(!isSpecial) { isSpecial = isInExon17(alteration); } } return isSpecial; }
Source:
public void listOverlapModifyingBatch() { Date startDate = createDate(2010, 1, 1); Date endDate = createDate(2050, 1, 1); Entitlement ent = setUpModifyingEntitlements(startDate, endDate, 3, "1"); Date startDate1 = createDate(2030, 1, 1); Date endDate1 = createDate(2040, 1, 1); Entitlement ent1 = setUpModifyingEntitlements(startDate1, endDate1, 2, "2"); Set<Entitlement> ents = entitlementCurator.listModifying(Arrays.asList(ent, ent1)); assertEquals(5, ents.size()); assertTrue(!ents.contains(ent)); assertTrue(!ents.contains(ent1)); }

Target:
public void listOverlapModifyingBatch() { Date startDate = createDate(2010, 1, 1); Date endDate = createDate(2050, 1, 1); Entitlement ent = setUpModifyingEntitlements(startDate, endDate, 3, "1"); Date startDate1 = createDate(2030, 1, 1); Date endDate1 = createDate(2040, 1, 1); Entitlement ent1 = setUpModifyingEntitlements(startDate1, endDate1, 2, "2"); Set<Entitlement> ents = entitlementCurator.listModifying(Arrays.asList(ent, ent1)); assertEquals(5, ents.size()); assertThat(ents, not(hasItems(ent))); assertThat(ents, not(hasItems(ent1))); }
Source:
public HiveBasicStatistics( OptionalLong fileCount, OptionalLong rowCount, OptionalLong inMemoryDataSizeInBytes, OptionalLong onDiskDataSizeInBytes) { this.fileCount = requireNonNull(fileCount, "fileCount is null"); fileCount.ifPresent(count -> checkArgument(count >= 0, "fileCount must be greater or equal than zero")); this.rowCount = requireNonNull(rowCount, "rowCount is null"); rowCount.ifPresent(count -> checkArgument(count >= 0, "rowCount must be greater or equal than zero")); this.inMemoryDataSizeInBytes = requireNonNull(inMemoryDataSizeInBytes, "inMemoryDataSizeInBytes is null"); inMemoryDataSizeInBytes.ifPresent(size -> checkArgument(size >= 0, "inMemoryDataSizeInBytes must be greater or equal than zero")); this.onDiskDataSizeInBytes = requireNonNull(onDiskDataSizeInBytes, "onDiskDataSizeInBytes is null"); onDiskDataSizeInBytes.ifPresent(size -> checkArgument(size >= 0, "onDiskDataSizeInBytes must be greater or equal than zero")); }

Target:
public HiveBasicStatistics( OptionalLong fileCount, OptionalLong rowCount, OptionalLong inMemoryDataSizeInBytes, OptionalLong onDiskDataSizeInBytes) { this.fileCount = requireNonNull(fileCount, "fileCount is null"); fileCount.ifPresent(count -> checkArgument(count >= 0, "fileCount is negative: %d", count)); this.rowCount = requireNonNull(rowCount, "rowCount is null"); rowCount.ifPresent(count -> checkArgument(count >= 0, "rowCount is negative: %d", count)); this.inMemoryDataSizeInBytes = requireNonNull(inMemoryDataSizeInBytes, "inMemoryDataSizeInBytes is null"); inMemoryDataSizeInBytes.ifPresent(size -> checkArgument(size >= 0, "inMemoryDataSizeInBytes is negative: %d", size)); this.onDiskDataSizeInBytes = requireNonNull(onDiskDataSizeInBytes, "onDiskDataSizeInBytes is null"); onDiskDataSizeInBytes.ifPresent(size -> checkArgument(size >= 0, "onDiskDataSizeInBytes is negative: %d", size)); }
Source:
public <VT> MessageOut<T> withParameter(ParameterType type, VT value) { List<Object> newParameters = new ArrayList<>(parameters.size() + 3); newParameters.addAll(parameters); newParameters.add(type); newParameters.add(value); return new MessageOut<T>(verb, payload, serializer, newParameters); }

Target:
public <VT> MessageOut<T> withParameter(ParameterType type, VT value) { List<Object> newParameters = new ArrayList<>(parameters.size() + 2); newParameters.addAll(parameters); newParameters.add(type); newParameters.add(value); return new MessageOut<T>(verb, payload, serializer, newParameters); }
Source:
public MapValue properties() { MapValue m = properties; if ( m == null ) { synchronized ( propLock ) { m = properties; if ( m == null ) { m = properties = ValueUtils.asMapValue( node.getAllProperties() ); } } } return m; }

Target:
public MapValue properties() { MapValue m = properties; if ( m == null ) { synchronized ( this ) { m = properties; if ( m == null ) { m = properties = ValueUtils.asMapValue( node.getAllProperties() ); } } } return m; }
Source:
private void onComplete() { try { final MetricsFile<IlluminaBasecallingMetrics, Comparable<?>> file = getMetricsFile(); final IlluminaMetricCounts allLaneCounts = new IlluminaMetricCounts(null, null, LANE); for (final String s : barcodeToMetricCounts.keySet()) { final IlluminaMetricCounts counts = barcodeToMetricCounts.get(s); counts.addMetricsToFile(file); allLaneCounts.addIlluminaMetricCounts(counts); } if (!barcodeToMetricCounts.keySet().contains("")) allLaneCounts.addMetricsToFile(file); file.write(OUTPUT); } catch (final Exception ex) { throw new PicardException("Error writing output file " + OUTPUT.getPath(), ex); } }

Target:
private void onComplete() { try { final MetricsFile<IlluminaBasecallingMetrics, Comparable<?>> file = getMetricsFile(); final IlluminaMetricCounts allLaneCounts = new IlluminaMetricCounts(null, null, LANE); for (final String s : barcodeToMetricCounts.keySet()) { final IlluminaMetricCounts counts = barcodeToMetricCounts.get(s); counts.addMetricsToFile(file); allLaneCounts.addIlluminaMetricCounts(counts); } if (!barcodeToMetricCounts.keySet().contains("")) { allLaneCounts.addMetricsToFile(file); } file.write(OUTPUT); } catch (final Exception ex) { throw new PicardException("Error writing output file " + OUTPUT.getPath(), ex); } }
Source:
buildJobUUID(Configuration conf, JobID jobId) throws PathCommitException { String jobUUID = conf.getTrimmed(FS_S3A_COMMITTER_UUID, ""); if (!jobUUID.isEmpty()) { return Pair.of(jobUUID, JobUUIDSource.CommitterUUIDProperty); } jobUUID = conf.getTrimmed(SPARK_WRITE_UUID, ""); if (!jobUUID.isEmpty()) { return Pair.of(jobUUID, JobUUIDSource.SparkWriteUUID); } if (conf.getBoolean(FS_S3A_COMMITTER_REQUIRE_UUID, false)) { throw new PathCommitException("", E_NO_SPARK_UUID); } if (conf.getBoolean(FS_S3A_COMMITTER_GENERATE_UUID, false)) { String newId = UUID.randomUUID().toString(); LOG.warn("No job ID in configuration; generating a randem ID: {}", newId); return Pair.of(newId, JobUUIDSource.GeneratedLocally); } return Pair.of(jobId.toString(), JobUUIDSource.JobID); }

Target:
buildJobUUID(Configuration conf, JobID jobId) throws PathCommitException { String jobUUID = conf.getTrimmed(FS_S3A_COMMITTER_UUID, ""); if (!jobUUID.isEmpty()) { return Pair.of(jobUUID, JobUUIDSource.CommitterUUIDProperty); } jobUUID = conf.getTrimmed(SPARK_WRITE_UUID, ""); if (!jobUUID.isEmpty()) { return Pair.of(jobUUID, JobUUIDSource.SparkWriteUUID); } if (conf.getBoolean(FS_S3A_COMMITTER_REQUIRE_UUID, DEFAULT_S3A_COMMITTER_REQUIRE_UUID)) { throw new PathCommitException("", E_NO_SPARK_UUID); } if (conf.getBoolean(FS_S3A_COMMITTER_GENERATE_UUID, DEFAULT_S3A_COMMITTER_GENERATE_UUID)) { String newId = UUID.randomUUID().toString(); LOG.warn("No job ID in configuration; generating a random ID: {}", newId); return Pair.of(newId, JobUUIDSource.GeneratedLocally); } return Pair.of(jobId.toString(), JobUUIDSource.JobID); }
Source:
private static Filter[] partitionFilterWith(Filter current, Predicate<Filter> predicate) { if (current == null) { return new Filter[]{null, null}; } System.out.println("[Filters/partitionFilterWith] 1 " + current); current = pushDownNot(current); System.out.println("[Filters/partitionFilterWith] 2 " + current); current = convertToCNF(current); System.out.println("[Filters/partitionFilterWith] 3 " + current); List<Filter> support = Lists.newArrayList(); List<Filter> notSupport = Lists.newArrayList(); traverse(current, predicate, support, notSupport) ; return new Filter[]{andFilter(support), andFilter(notSupport)}; }

Target:
private static Filter[] partitionFilterWith(Filter current, Predicate<Filter> predicate) { if (current == null) { return null; } current = pushDownNot(current); current = flatten(current); current = convertToCNF(current); current = flatten(current); List<Filter> bitmapIndexSupported = Lists.newArrayList(); List<Filter> bitmapIndexNotSupported = Lists.newArrayList(); traverse(current, predicate, bitmapIndexSupported, bitmapIndexNotSupported); return new Filter[]{andFilter(bitmapIndexSupported), andFilter(bitmapIndexNotSupported)}; }
Source:
public void testTimeout() throws DatabaseFactoryException, ClassNotFoundException, InterruptedException, RecoveryException, RetryLimitExceededException, SQLException { final int socketTimeout = 60; final int loginTimeout = 30; final Properties properties = new Properties() { { setProperty(JDBC, config.jdbc); setProperty(USERNAME, config.username); setProperty(PASSWORD, config.password); setProperty(ENGINE, config.engine); setProperty(SCHEMA_POLICY, "create"); setProperty(SOCKET_TIMEOUT, Integer.toString(socketTimeout)); setProperty(LOGIN_TIMEOUT, Integer.toString(loginTimeout)); } }; final DatabaseEngine de = DatabaseFactory.getConnection(properties); final int connectionTimeoutInMs = de.getConnection().getNetworkTimeout(); assertEquals("timeout in db connection ok?", socketTimeout * 1000, connectionTimeoutInMs); }

Target:
public void testTimeout() throws DatabaseFactoryException, ClassNotFoundException, InterruptedException, RecoveryException, RetryLimitExceededException, SQLException { final int socketTimeout = 60; final int loginTimeout = 30; final Properties properties = new Properties() { { setProperty(JDBC, config.jdbc); setProperty(USERNAME, config.username); setProperty(PASSWORD, config.password); setProperty(ENGINE, config.engine); setProperty(SCHEMA_POLICY, "create"); setProperty(SOCKET_TIMEOUT, Integer.toString(socketTimeout)); setProperty(LOGIN_TIMEOUT, Integer.toString(loginTimeout)); } }; final DatabaseEngine de = DatabaseFactory.getConnection(properties); final int connectionTimeoutInMs = de.getConnection().getNetworkTimeout(); assertEquals("Is the timeout of the DB connection the expected?", socketTimeout * 1000, connectionTimeoutInMs); }
Source:
public boolean shouldThrottle(RestRequest restRequest) { boolean shouldThrottle; RejectThrottler throttler = quotaMap.get(restRequest.getRestMethod()); shouldThrottle = (throttler != null && throttler.shouldThrottle(1)); if (!shouldThrottle && hardwareThresholdMap.containsKey(HardwareResource.MEMORY)) { shouldThrottle = !hardwareThresholdMap.get(HardwareResource.MEMORY) .meetRequirement((long) hardwareUsageMeter.getMemoryPercentage()); if (shouldThrottle) { logger.warn("Throttle because of Memory: {}%", hardwareUsageMeter.getMemoryPercentage()); } } if (!shouldThrottle && hardwareThresholdMap.containsKey(HardwareResource.CPU)) { shouldThrottle = !hardwareThresholdMap.get(HardwareResource.MEMORY) .meetRequirement((long) hardwareUsageMeter.getCpuPercentage()); if (shouldThrottle) { logger.warn("Throttle because of CPU: {}%", hardwareUsageMeter.getCpuPercentage()); } } return shouldThrottle; }

Target:
public boolean shouldThrottle(RestRequest restRequest) { boolean shouldThrottle; RejectThrottler throttler = quotaMap.get(restRequest.getRestMethod()); shouldThrottle = (throttler != null && throttler.shouldThrottle(1)); for (HardwareResource hardwareResource : HardwareResource.values()) { if (!shouldThrottle && hardwareThresholdMap.containsKey(hardwareResource)) { shouldThrottle = !hardwareThresholdMap.get(hardwareResource) .meetRequirement((long) hardwareUsageMeter.getHardwareResourcePercentage(hardwareResource)); if (shouldThrottle) { logger.warn("Throttle because of : {}%", hardwareResource, hardwareUsageMeter.getHardwareResourcePercentage(hardwareResource)); } } } return shouldThrottle; }
Source:
public void search_shouldReturnAllRadiologyReportsIncludingDiscontinuedMatchingTheSearchQueryIfIncludeAllIsSet() throws Exception { MockHttpServletRequest request = request(RequestMethod.GET, getURI()); request.setParameter(RadiologyReportSearchHandler.REQUEST_PARAM_PRINCIPAL_RESULT_INTERPRETER, PROVIDER_WITH_RADIOLOGY_REPORTS); request.setParameter(RestConstants.REQUEST_PROPERTY_FOR_INCLUDE_ALL, "true"); SimpleObject result = deserialize(handle(request)); assertNotNull(result); List<Object> hits = (List<Object>) result.get("results"); assertThat(hits.size(), is(3)); }

Target:
public void search_shouldReturnAllRadiologyReportsIncludingDiscontinuedMatchingTheSearchQueryIfIncludeAllIsSet() throws Exception { MockHttpServletRequest request = request(RequestMethod.GET, getURI()); request.setParameter(RadiologyReportSearchHandler.REQUEST_PARAM_PRINCIPAL_RESULT_INTERPRETER, PROVIDER_WITH_RADIOLOGY_REPORTS); request.setParameter(RestConstants.REQUEST_PROPERTY_FOR_INCLUDE_ALL, "true"); request.setParameter("v", Representation.FULL.getRepresentation()); SimpleObject result = deserialize(handle(request)); assertNotNull(result); List<Object> hits = (List<Object>) result.get("results"); assertThat(hits.size(), is(3)); assertThat(PropertyUtils.getProperty(hits.get(2), "uuid"), is(RADIOLOGY_REPORT_UUID_OF_DISCONTINUED)); assertThat(PropertyUtils.getProperty(hits.get(2), "reportStatus"), is(RadiologyReportStatus.DISCONTINUED.toString())); }
Source:
public void testProcessCommonProperties() { NodeDetailsDeriver deriver = new NodeDetailsDeriver(); Trace trace = new Trace(); Consumer consumer = new Consumer(); consumer.setEndpointType("HTTP"); consumer.getProperties().add(new Property(Constants.PROP_BUILD_STAMP, "myBuild")); consumer.getProperties().add(new Property(Constants.PROP_PRINCIPAL, "jdoe")); trace.getNodes().add(consumer); Component component = new Component(); component.getProperties().add(new Property(Constants.PROP_SERVICE_NAME, "myService")); component.getProperties().add(new Property("LocalProp", "LocalValue")); consumer.getNodes().add(component); List<NodeDetails> details = null; try { details = deriver.processOneToMany(null, trace); } catch (Exception e) { fail("Failed: " + e); } assertNotNull(details); assertEquals(2, details.size()); assertEquals(3, details.get(0).getProperties().size()); assertEquals(4, details.get(1).getProperties().size()); }

Target:
public void testProcessCommonProperties() throws RetryAttemptException { NodeDetailsDeriver deriver = new NodeDetailsDeriver(); Trace trace = new Trace(); Property p1 = new Property(Constants.PROP_BUILD_STAMP, "myBuild"); Property p2 = new Property(Constants.PROP_PRINCIPAL, "jdoe"); Property p3 = new Property(Constants.PROP_SERVICE_NAME, "myService"); Property p4 = new Property("LocalProp", "LocalValue"); Consumer consumer = new Consumer(); consumer.setEndpointType("HTTP"); consumer.getProperties().add(p1); consumer.getProperties().add(p2); trace.getNodes().add(consumer); Component component1 = new Component(); component1.getProperties().add(p3); consumer.getNodes().add(component1); Component component2 = new Component(); component2.getProperties().add(p4); component1.getNodes().add(component2); List<NodeDetails> details = deriver.processOneToMany(null, trace); assertEquals(3, details.size()); assertEquals(new HashSet<>(Arrays.asList(p1,p2,p3,p4)), details.get(0).getProperties()); assertEquals(new HashSet<>(Arrays.asList(p1,p2,p3)), details.get(1).getProperties()); assertEquals(new HashSet<>(Arrays.asList(p1,p2,p3,p4)), details.get(2).getProperties()); }
Source:
public static HashMap<String, Integer> getLoginUserIds() { TypeToken<HashMap<String, Integer>> type = new TypeToken<HashMap<String, Integer>>(){}; return GsonUnmarshaller.unmarshal(type, getString(R.string.preference_key_login_user_id_map, "{}")); }

Target:
public static Map<String, Integer> getLoginUserIds() { TypeToken<HashMap<String, Integer>> type = new TypeToken<HashMap<String, Integer>>(){}; return GsonUnmarshaller.unmarshal(type, getString(R.string.preference_key_login_user_id_map, "{}")); }