auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void updateFullyQualifiedReference(String newName) { HaxeReferenceExpression referenceExpression = HaxeElementGenerator.createReferenceExpressionFromText(getProject(), newName); assert referenceExpression != null; replace(referenceExpression); }

Target:
private void updateFullyQualifiedReference(String newName) { HaxeReferenceExpression referenceExpression = HaxeElementGenerator.createReferenceExpressionFromText(getProject(), newName); if (referenceExpression == null) { LOG.error("ReferenceExpression generated by HaxeElementGenerator is null!"); } else { replace(referenceExpression); } }
Source:
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.channel().close(); HttpServerImpl.this.connectionExceptionHandler.handle(cause); }

Target:
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { Channel channel = ctx.channel(); channel.close(); HandlerHolder<HttpHandler> reqHandler = reqHandlerManager.chooseHandler(channel.eventLoop()); reqHandler.context.executeFromIO(() -> HttpServerImpl.this.connectionExceptionHandler.handle(cause)); }
Source:
public boolean cancelOrder(CancelOrderParams orderParams) throws IOException { if (orderParams instanceof CancelOrderByPairAndIdParams) { final CancelOrderByPairAndIdParams params = (CancelOrderByPairAndIdParams) orderParams; return cancelBithumbOrder(Long.valueOf(params.getOrderId()), params.getCurrencyPair()); } else { throw new NotYetImplementedForExchangeException( "Only CancelOrderByPairAndIdParams supported"); } }

Target:
public boolean cancelOrder(CancelOrderParams orderParams) throws IOException { if (orderParams instanceof CancelOrderByPairAndIdParams) { try { final CancelOrderByPairAndIdParams params = (CancelOrderByPairAndIdParams) orderParams; return cancelBithumbOrder(Long.valueOf(params.getOrderId()), params.getCurrencyPair()); } catch (BithumbException e) { throw BithumbErrorAdapter.adapt(e); } } else { throw new NotYetImplementedForExchangeException( "Only CancelOrderByPairAndIdParams supported"); } }
Source:
public CompletableFuture<Void> visitEntrySetCommand(InvocationContext ctx, EntrySetCommand command) throws Throwable { ctx.onReturn((ctx1, command1, rv, throwable) -> { if (throwable != null) throw throwable; CacheSet<CacheEntry<K, V>> entrySet = (CacheSet<CacheEntry<K, V>>) rv; if (!enabled || hasSkipLoadFlag(command)) { return CompletableFuture.completedFuture(entrySet); } CacheSet<CacheEntry<K, V>> wrappedEntrySet = new WrappedEntrySet(command, entrySet); return CompletableFuture.completedFuture(wrappedEntrySet); }); return ctx.continueInvocation(); }

Target:
public CompletableFuture<Void> visitEntrySetCommand(InvocationContext ctx, EntrySetCommand command) throws Throwable { return ctx.onReturn((rCtx, rCommand, rv, throwable) -> { if (throwable != null || !enabled || hasSkipLoadFlag(command)) { return null; } CacheSet<CacheEntry<K, V>> entrySet = (CacheSet<CacheEntry<K, V>>) rv; CacheSet<CacheEntry<K, V>> wrappedEntrySet = new WrappedEntrySet(command, entrySet); return CompletableFuture.completedFuture(wrappedEntrySet); }); }
Source:
public boolean isCertChainValid() { return false; }

Target:
public boolean isCertChainValid() throws ScriptSignatureException { return isCertChainValid(null, null); }
Source:
private static void setScores(DynamicEndpointSnitch dsnitch, int rounds, List<InetAddressAndPort> hosts, Integer... scores) throws InterruptedException { for (int round = 0; round < rounds; round++) { for (int i = 0; i < hosts.size(); i++) dsnitch.receiveTiming(hosts.get(i), scores[i], LatencyMeasurementType.READ); } Thread.sleep(UPDATE_INTERVAL_MS + 10); }

Target:
private static void setScores(DynamicEndpointSnitch dsnitch, int rounds, List<InetAddressAndPort> hosts, Integer... scores) throws InterruptedException { for (int round = 0; round < rounds; round++) { for (int i = 0; i < hosts.size(); i++) dsnitch.receiveTiming(hosts.get(i), scores[i], LatencyMeasurementType.READ); } dsnitch.updateScores(); }
Source:
static Map<String, String> getDefaultDevDependencies() { Map<String, String> defaults = new HashMap<>(); defaults.put("html-webpack-plugin", "3.2.0"); defaults.put("script-ext-html-webpack-plugin", "2.1.4"); defaults.put("typescript", "4.0.3"); defaults.put("awesome-typescript-loader", "5.2.1"); defaults.put("webpack", "4.42.0"); defaults.put("webpack-cli", "3.3.11"); defaults.put("webpack-dev-server", "3.11.0"); defaults.put("copy-webpack-plugin", "5.1.2"); defaults.put("compression-webpack-plugin", "4.0.1"); defaults.put("webpack-merge", "4.2.2"); defaults.put("css-loader", "4.2.1"); defaults.put("file-loader", "6.1.0"); defaults.put("extract-loader", "5.1.0"); defaults.put("lit-css-loader", "0.0.4"); defaults.put("file-loader", "6.1.0"); defaults.put("loader-utils", "1.4.0"); defaults.put("lit-element", "2.3.1"); defaults.put("lit-html", "1.2.1"); defaults.put("@types/validator", "13.1.0"); defaults.put("validator", "13.1.17"); defaults.put("construct-style-sheets-polyfill", "2.4.2"); defaults.put("chokidar", "^3.4.0"); return defaults; }

Target:
static Map<String, String> getDefaultDevDependencies() { Map<String, String> defaults = new HashMap<>(); defaults.put("html-webpack-plugin", "3.2.0"); defaults.put("script-ext-html-webpack-plugin", "2.1.4"); defaults.put("typescript", "4.0.3"); defaults.put("awesome-typescript-loader", "5.2.1"); defaults.put("webpack", "4.42.0"); defaults.put("webpack-cli", "3.3.11"); defaults.put("webpack-dev-server", "3.11.0"); defaults.put("copy-webpack-plugin", "5.1.2"); defaults.put("compression-webpack-plugin", "4.0.1"); defaults.put("webpack-merge", "4.2.2"); defaults.put("css-loader", "4.2.1"); defaults.put("extract-loader", "5.1.0"); defaults.put("lit-css-loader", "0.0.4"); defaults.put("file-loader", "6.1.0"); defaults.put("loader-utils", "1.4.0"); defaults.put("lit-element", "2.3.1"); defaults.put("lit-html", "1.2.1"); defaults.put("@types/validator", "13.1.0"); defaults.put("validator", "13.1.17"); defaults.put("construct-style-sheets-polyfill", "2.4.2"); defaults.put("chokidar", "^3.4.0"); return defaults; }
Source:
public String translate(final StringAgg stringAgg) { inject(stringAgg.column); if (stringAgg.isDistinct()) { return String.format( "string_agg(DISTINCT CAST (%s AS TEXT), CAST ('%c' AS TEXT))", stringAgg.getColumn().translate(), stringAgg.getDelimiter() ); } else { return String.format( "string_agg(CAST (%s AS TEXT), CAST ('%c' AS TEXT))", stringAgg.getColumn().translate(), stringAgg.getDelimiter() ); } }

Target:
public String translate(final StringAgg stringAgg) { inject(stringAgg.column); return String.format( "STRING_AGG(%s %s, '%c')", stringAgg.isDistinct() ? "DISTINCT" : "", stringAgg.getColumn().translate(), stringAgg.getDelimiter() ); }
Source:
private static OutputWrapper connectMySql(String param) throws IOException { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection conn = DriverManager.getConnection("jdbc:mysql:" + param); return new OutputWrapper(conn); } catch (Exception e) { throw (IOException)new IOException(e.getMessage()).initCause(e); } }

Target:
private static OutputWrapper connectMySql(String param) throws IOException { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection conn = DriverManager.getConnection("jdbc:mysql:" + param); return new OutputWrapper(conn); } catch (Exception e) { throw new IOException(e); } }
Source:
public void testMultipleAttributes() throws Exception { IASTTranslationUnit tu = parseAndCheckBindings(); List<IASTAttribute> attributes = getAttributes(tu); assertEquals(1, attributes.size()); }

Target:
public void testMultipleAttributes() throws Exception { ICPPASTAttribute[] attributes = getAttributes(); assertEquals(2, attributes.length); ICPPASTAttribute attr1 = attributes[0]; assertEquals("attr1", String.valueOf(attr1.getName())); ICPPASTAttribute attr2 = attributes[1]; assertEquals("attr2", String.valueOf(attr2.getName())); }
Source:
public void testNumberLargerThanMaxLongInEvents() { final String events = "[{\"number\": 9223372036854775808 }]"; try { BatchFactory.from(events); fail(); } catch (JSONException e) }

Target:
public void testNumberLargerThanMaxLongInEvents() { final String events = "[{\"number\": 9223372036854775808 }]"; BatchFactory.from(events); }
Source:
public boolean removeUserFromTenant(String tenantId, String userId) { PreConditions.notNullOrEmpty(tenantId, "tenantId"); PreConditions.notNullOrEmpty(userId, "userId"); Tenant tenant = tenantRepo.findByTenantId(tenantId); PreConditions.notNull(tenant, "Tenant with given tenantId doesnt exists"); Optional<TenantUser> maybeUser = tenant.getUser(userId); boolean userIsPresent = false; if (maybeUser.isPresent()) { userIsPresent = tenant.hasUser(maybeUser.get().getUser().getUsername()); if (userIsPresent) { tenant.removeUser(maybeUser.get()); } } tenantRepo.save(tenant); return userIsPresent; }

Target:
public boolean removeUserFromTenant(String tenantId, String userId) { PreConditions.notNullOrEmpty(tenantId, "tenantId"); PreConditions.notNullOrEmpty(userId, "userId"); Tenant tenant = tenantRepo.findByTenantId(tenantId); PreConditions.notNull(tenant, "Tenant with given tenantId doesnt exists"); Optional<TenantUser> maybeUser = tenant.getUser(userId); boolean userIsPresent = false; if (maybeUser.isPresent()) { userIsPresent = true; tenant.removeUser(maybeUser.get()); } tenantRepo.save(tenant); return userIsPresent; }
Source:
protected String doInBackground(NetParam... params) { start_time = System.currentTimeMillis(); try{ switch(params[0].type){ case PING: try{ String result = output(Runtime.getRuntime().exec(String.format(PING_CMD, params[0].address))); if(result.isEmpty()){ result = context.getString(R.string.network_connection_not_available); } return result; }catch (Exception eex){ try{ if(InetAddress.getByAddress(params[0].address.getBytes()).isReachable(G.logPingTimeout())){ return String.format(context.getString(R.string.reachable_timeout), finish_time()); } }catch(UnknownHostException ex){ return String.format("Currently IP(%s) is not Reachable, timeout: %d ms", params[0].address, finish_time()); } } case RESOLVE: try{ return InetAddress.getByName(params[0].address).getCanonicalHostName(); }catch(UnknownHostException ex){ return String.format("Currently can not resolve Host for IP(%s), timeout: %d ms", params[0].address, finish_time()); } } }catch (Exception e){ e.printStackTrace(); } return context.getString(R.string.error_or_unknown_category); }

Target:
protected String doInBackground(NetParam... params) { start_time = System.currentTimeMillis(); try{ switch(params[0].type){ case PING: try{ String shell_result = ""; String command = ""; try{ command = String.format(PING_CMD, "", G.logPingTimeout(), params[0].address); Log.d(TAG, "Execute CMD: " + command); Process process = Runtime.getRuntime().exec(command); process.waitFor(); Log.d(TAG, "CMD exit code: " + process.exitValue()); if(process.exitValue() == 0){ shell_result = parse(process); }else{ shell_result = su_busyboox_ping(params[0].address); } }catch (Exception ping_cmd_ex){ Log.e(TAG, "Exception(00): " + ping_cmd_ex.getMessage()); shell_result = su_busyboox_ping(params[0].address); } return shell_result; }catch (Exception eex){ Log.e(TAG, "Exception(01): " + eex.getMessage()); return normal_ping(params[0].address); } case RESOLVE: try{ return InetAddress.getByName(params[0].address).getCanonicalHostName(); }catch(UnknownHostException ex){ Log.e(TAG, "Exception(02): " + ex.getMessage()); return String.format("Currently can not resolve Host for IP(%s), timeout: %d ms", params[0].address, finish_time()); } } }catch (Exception e){ Log.e(TAG, "Exception(03): " + e.getMessage()); } return context.getString(R.string.error_or_unknown_category); }
Source:
private void createClient() { if (ribbonEtc.containsKey("eureka")) { ribbonEtc.setProperty( clientName + ".ribbon.AppName", clientName); ribbonEtc.setProperty( clientName + ".ribbon.NIWSServerListClassName", "com.netflix.niws.loadbalancer.DiscoveryEnabledNIWSServerList"); ribbonEtc.setProperty( clientName + ".ribbon.ServerListRefreshInterval", "60000"); String[] host_port = addressList.get(0).split(":"); ribbonEtc.setProperty( clientName + ".ribbon.DeploymentContextBasedVipAddresses", host_port[0]); ribbonEtc.setProperty( clientName + ".ribbon.Port", host_port[1]); } else { ribbonEtc.setProperty(clientName + ".ribbon.listOfServers", Joiner.on(",").join(addressList)); } ConfigurationManager.loadProperties(ribbonEtc); client = (RestClient) ClientFactory.getNamedClient(clientName); }

Target:
private void createClient() { if (ribbonEtc.containsKey("eureka")) { ribbonEtc.setProperty( clientName + ".ribbon.AppName", clientName); ribbonEtc.setProperty( clientName + ".ribbon.NIWSServerListClassName", "com.netflix.niws.loadbalancer.DiscoveryEnabledNIWSServerList"); String[] host_port = addressList.get(0).split(":"); ribbonEtc.setProperty( clientName + ".ribbon.DeploymentContextBasedVipAddresses", host_port[0]); ribbonEtc.setProperty( clientName + ".ribbon.Port", host_port[1]); } else { ribbonEtc.setProperty(clientName + ".ribbon.listOfServers", Joiner.on(",").join(addressList)); } ribbonEtc.setProperty( clientName + ".ribbon.EnablePrimeConnections", "true"); ConfigurationManager.loadProperties(ribbonEtc); client = (RestClient) ClientFactory.getNamedClient(clientName); }
Source:
private void remove() { if (getWindow() != null) { return; } ConfirmationModel window = new ConfirmationModel(); setWindow(window); window.setTitle(ConstantsManager.getInstance().getConstants().removeVirtualMachinesTitle()); window.setHelpTag(HelpTag.remove_virtual_machine); window.setHashName("remove_virtual_machine"); vmsRemoveMap = new HashMap<>(); for (Object selectedItem : getSelectedItems()) { VM vm = (VM) selectedItem; if (vm.getStatus() == VMStatus.Down) { EntityModel removeDisksCheckbox = new EntityModel(true); removeDisksCheckbox.setTitle(ConstantsManager.getInstance().getConstants().removeDisksTitle()); removeDisksCheckbox.setMessage(vm.getName()); if (!Guid.Empty.equals(vm.getVmtGuid())) { updateRemoveDisksCheckBox(removeDisksCheckbox, true, false, ConstantsManager.getInstance() .getConstants() .removeVmDisksTemplateMsg()); } vmsRemoveMap.put(vm.getId(), removeDisksCheckbox); } } window.setItems(vmsRemoveMap.entrySet()); initRemoveDisksCheckboxes(vmsRemoveMap); UICommand tempVar = UICommand.createDefaultOkUiCommand("OnRemove", this); window.getCommands().add(tempVar); UICommand tempVar2 = UICommand.createCancelUiCommand("Cancel", this); window.getCommands().add(tempVar2); }

Target:
private void remove() { if (getWindow() != null) { return; } ConfirmationModel window = new ConfirmationModel(); setWindow(window); window.setTitle(ConstantsManager.getInstance().getConstants().removeVirtualMachinesTitle()); window.setHelpTag(HelpTag.remove_virtual_machine); window.setHashName("remove_virtual_machine"); vmsRemoveMap = new HashMap<>(); for (Object selectedItem : getSelectedItems()) { VM vm = (VM) selectedItem; if (VdcActionUtils.canExecute(Arrays.asList(vm), VM.class, VdcActionType.RemoveVm)) { EntityModel removeDisksCheckbox = new EntityModel(true); removeDisksCheckbox.setTitle(ConstantsManager.getInstance().getConstants().removeDisksTitle()); removeDisksCheckbox.setMessage(vm.getName()); if (!Guid.Empty.equals(vm.getVmtGuid())) { updateRemoveDisksCheckBox(removeDisksCheckbox, true, false, ConstantsManager.getInstance() .getConstants() .removeVmDisksTemplateMsg()); } vmsRemoveMap.put(vm.getId(), removeDisksCheckbox); } } window.setItems(vmsRemoveMap.entrySet()); initRemoveDisksCheckboxes(vmsRemoveMap); UICommand tempVar = UICommand.createDefaultOkUiCommand("OnRemove", this); window.getCommands().add(tempVar); UICommand tempVar2 = UICommand.createCancelUiCommand("Cancel", this); window.getCommands().add(tempVar2); }
Source:
public SimpleMergedByteBuffers(boolean readOnly, ByteBuffer ...bbs) { super(readOnly); for(ByteBuffer bb: bbs) { if(bb == null) { throw new IllegalArgumentException("Can not add null buffers!"); } } if(bbs.length > 0) { bba = bbs; } else { bba = new ByteBuffer[] {EMPTY_BYTEBUFFER}; } }

Target:
public SimpleMergedByteBuffers(boolean readOnly, ByteBuffer ...bbs) { super(readOnly); for(ByteBuffer bb: bbs) { if(bb == null) { throw new IllegalArgumentException("Can not add null buffers!"); } } if(bbs.length > 0) { bba = bbs; } else { bba = EMPTY_BUFFER_ARRAY; } }
Source:
public static CinderDisk volumeToCinderDisk(Volume volume, Guid storageDomainId) { CinderDisk cinderDisk = new CinderDisk(); cinderDisk.setId(Guid.createGuidFromString(volume.getId())); cinderDisk.setImageId(Guid.createGuidFromString(volume.getId())); cinderDisk.setDiskAlias(volume.getName()); cinderDisk.setDescription(volume.getDescription()); cinderDisk.setSizeInGigabytes(volume.getSize()); cinderDisk.setCinderVolumeType(volume.getVolumeType()); cinderDisk.setStorageIds(new ArrayList<>(Arrays.asList(storageDomainId))); cinderDisk.setActive(true); cinderDisk.setImageStatus(ImageStatus.OK); cinderDisk.setvolumeFormat(VolumeFormat.RAW); cinderDisk.setDiskInterface(DiskInterface.VirtIO); try { cinderDisk.setCreationDate(new SimpleDateFormat(DATE_FORMAT).parse(volume.getCreatedAt())); } catch (ParseException e) { cinderDisk.setCreationDate(null); } return cinderDisk; }

Target:
public static CinderDisk volumeToCinderDisk(Volume volume, Guid storageDomainId) { CinderDisk cinderDisk = new CinderDisk(); cinderDisk.setId(Guid.createGuidFromString(volume.getId())); cinderDisk.setImageId(Guid.createGuidFromString(volume.getId())); cinderDisk.setDiskAlias(volume.getName()); cinderDisk.setDescription(volume.getDescription()); cinderDisk.setSizeInGigabytes(volume.getSize()); cinderDisk.setCinderVolumeType(volume.getVolumeType()); cinderDisk.setStorageIds(new ArrayList<>(Arrays.asList(storageDomainId))); cinderDisk.setActive(true); cinderDisk.setImageStatus(ImageStatus.OK); cinderDisk.setvolumeFormat(VolumeFormat.RAW); cinderDisk.setDiskInterface(DiskInterface.VirtIO); try { cinderDisk.setCreationDate(new SimpleDateFormat(DATE_FORMAT).parse(volume.getCreatedAt())); } catch (ParseException e) { cinderDisk.setCreationDate(null); log.error("Invalid disk creation date format", e); } return cinderDisk; }
Source:
public void checkParameters(Command command, ExecutionHandlerContext executionHandlerContext) { List<byte[]> parameters = command.getProcessedCommand(); String commandType = command.getCommandType().name(); parameters.forEach(parameter -> { String parameterString = parameter.toString(); if (isNotAllowed(parameterString) && !parameterString.equalsIgnoreCase(commandType)) { throw new RedisParametersMismatchException(""); } }); }

Target:
public void checkParameters(Command command, ExecutionHandlerContext executionHandlerContext) { List<byte[]> parameters = command.getProcessedCommand(); String commandType = command.getCommandType().name(); parameters.forEach(parameter -> { String parameterString = new String(parameter); if (isNotAllowed(parameterString) && !parameterString.equalsIgnoreCase(commandType)) { throw new RedisParametersMismatchException(ERROR_MESSAGE); } }); }
Source:
public void testID3v2Metadata() { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); try { Resources resources = getContext().getResources(); AssetFileDescriptor afd = resources.openRawResourceFd( R.raw.video_480x360_mp4_h264_500kbps_25fps_aac_stereo_128kbps_44100hz); retriever.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); afd.close(); } catch (Exception e) { fail("Unable to open file"); } assertEquals("Title was other than expected", "Title", retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE)); assertEquals("Artist was other than expected", "UTF16LE エンディアン ", retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST)); assertEquals("Album was other than expected", "Test album", retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM)); assertEquals("Track number was other than expected", "10", retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CD_TRACK_NUMBER)); assertEquals("Year was other than expected", "2013", retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_YEAR)); assertNull("Writer was unexpected present", retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_WRITER)); }

Target:
public void testID3v2Metadata() { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); try { Resources resources = getContext().getResources(); AssetFileDescriptor afd = resources.openRawResourceFd( R.raw.video_480x360_mp4_h264_500kbps_25fps_aac_stereo_128kbps_44100hz); retriever.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); afd.close(); } catch (Exception e) { fail("Unable to open file"); } assertEquals("Title was other than expected", "Title", retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE)); assertEquals("Artist was other than expected", "UTF16LE エンディアン ", retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST)); assertEquals("Album was other than expected", "Test album", retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM)); assertEquals("Track number was other than expected", "10", retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CD_TRACK_NUMBER)); assertEquals("Year was other than expected", "2013", retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_YEAR)); assertNull("Writer was unexpectedly present", retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_WRITER)); }
Source:
public void testNegatedPackagesFiltering() throws Exception { Builder b = new Builder(); try { b.setIncludePackage("test.packageinfo.*"); b.setProperty("X-Not-Versioned", "${packages;ANNOTATED;!org.osgi.annotation.versioning.Version}"); b.addClasspath(new File("bin_test")); Jar jar = b.build(); Manifest m = jar.getManifest(); m.write(System.err); assertTrue(b.check()); Parameters notVersioned = Domain.domain(m) .getParameters("X-Not-Versioned"); assertThat(notVersioned).containsKeys("test.packageinfo", "test.packageinfo.both_no_version", "test.packageinfo.nopackageinfo", "test.packageinfo.ref"); } finally { b.close(); } }

Target:
public void testNegatedPackagesFiltering() throws Exception { Builder b = new Builder(); try { b.setIncludePackage("test.packageinfo.*"); b.setProperty("X-Not-Versioned", "${packages;ANNOTATED;!org.osgi.annotation.versioning.Version}"); b.addClasspath(new File("bin_test")); Jar jar = b.build(); Manifest m = jar.getManifest(); m.write(System.err); assertTrue(b.check()); Parameters notVersioned = Domain.domain(m) .getParameters("X-Not-Versioned"); assertThat(notVersioned) .containsKeys("test.packageinfo", "test.packageinfo.both_no_version", "test.packageinfo.nopackageinfo", "test.packageinfo.ref") .doesNotContainKeys("test.packageinfo.annotated", "test.packageinfo.notannotated"); } finally { b.close(); } }
Source:
public void filterImageDisksForVM(VM vm) { List<DiskImage> filteredDisks = DisksFilter.filterImageDisks(vm.getDiskMap().values(), ONLY_ACTIVE); List<CinderDisk> filteredCinderDisks = DisksFilter.filterCinderDisks(vm.getDiskMap().values()); List<ManagedBlockStorageDisk> filteredManagedBlockStorageDisks = DisksFilter.filterManagedBlockStorageDisks(vm.getDiskMap().values()); filteredDisks.addAll(filteredCinderDisks); filteredDisks.addAll(filteredManagedBlockStorageDisks); @SuppressWarnings("unchecked") Collection<? extends Disk> vmDisksToRemove = CollectionUtils.subtract(vm.getDiskMap().values(), filteredDisks); vm.clearDisks(); updateDisksForVm(vm, filteredDisks); for (Disk diskToRemove : vmDisksToRemove) { vm.getManagedVmDeviceMap().remove(diskToRemove.getId()); } }

Target:
public void filterImageDisksForVM(VM vm) { List<DiskImage> filteredDisks = DisksFilter.filterImageDisks(vm.getDiskMap().values(), ONLY_ACTIVE); List<CinderDisk> filteredCinderDisks = DisksFilter.filterCinderDisks(vm.getDiskMap().values()); filteredDisks.addAll(filteredCinderDisks); filteredDisks.addAll(DisksFilter.filterManagedBlockStorageDisks(vm.getDiskMap().values())); @SuppressWarnings("unchecked") Collection<? extends Disk> vmDisksToRemove = CollectionUtils.subtract(vm.getDiskMap().values(), filteredDisks); vm.clearDisks(); updateDisksForVm(vm, filteredDisks); for (Disk diskToRemove : vmDisksToRemove) { vm.getManagedVmDeviceMap().remove(diskToRemove.getId()); } }
Source:
public Drug getDrugByMapping(String code, ConceptSource conceptSource, Collection<ConceptMapType> withAnyOfTheseTypesOrOrderOfPreference, boolean includeRetired) throws DAOException { Criteria searchCriteria = sessionFactory.getCurrentSession().createCriteria(DrugReferenceMap.class); searchCriteria.setProjection(Projections.property("drug")); searchCriteria.createAlias("conceptReferenceTerm", "term"); searchCriteria.add(Restrictions.eq("term.code", code)); searchCriteria.createAlias("term.conceptSource", "source"); searchCriteria.add(Restrictions.or(Restrictions.eq("source.name", conceptSource.getName()), Restrictions.eq("source.hl7Code", conceptSource.getHl7Code()))); for(ConceptMapType conceptMapType : withAnyOfTheseTypesOrOrderOfPreference) { if(conceptMapType != null) { searchCriteria.add(Restrictions.eq("conceptMapType", conceptMapType)); } } searchCriteria.createAlias("drug", "drug"); if (includeRetired == false) { searchCriteria.add(Restrictions.eq("drug.retired", false)); } return (Drug) searchCriteria.uniqueResult(); }

Target:
public Drug getDrugByMapping(String code, ConceptSource conceptSource, Collection<ConceptMapType> withAnyOfTheseTypesOrOrderOfPreference, boolean includeRetired) throws DAOException { Criteria criteria = createSearchDrugByMappingCriteria(code,conceptSource,includeRetired); if(withAnyOfTheseTypesOrOrderOfPreference !=null) { for(ConceptMapType conceptMapType : withAnyOfTheseTypesOrOrderOfPreference) { criteria.add(Restrictions.eq("map.conceptMapType", conceptMapType)); if(criteria.list().size() > 1) { throw new DAOException("There are multiple matches for the highest-priority ConceptMapType"); } else if(criteria.list().size() == 1) { return (Drug)criteria.list().get(0); } } } return null; }
Source:
private void deleteDir(Path dir) { try (Stream<Path> entries = Files.list(dir)) { if (dir.getFileName().toString().length() == 2 && entries.count() == 0) { Files.deleteIfExists(dir); } } catch (IOException e) { LOG.error(e.getMessage(), e); } }

Target:
private void deleteDir(Path dir) { try (Stream<Path> entries = Files.list(dir)) { if (dir.getFileName().toString().length() == 2 && entries.count() == 0) { Files.deleteIfExists(dir); } } catch (DirectoryNotEmptyException ignored) { } catch (IOException e) { LOG.error(e.getMessage(), e); } }
Source:
public static <T extends EntityReference> T cloneReference(@NotNull EntityReference reference, @NotNull Class<T> token) { try { reference = reference.clone(); T ret; if (token != EntityReference.class) { ret = token.getConstructor(EntityReference.class).newInstance(reference.clone()); } else { @SuppressWarnings("unchecked") T castedReference = (T) reference; ret = castedReference; } return ret; } catch (ReflectiveOperationException | SecurityException exc) { throw new IllegalArgumentException("Unsupported entity class: " + token, exc); } }

Target:
public static <T extends EntityReference> T cloneReference(@NotNull EntityReference reference, @NotNull Class<T> token) { try { reference = reference.clone(); T ret; if (token != EntityReference.class) { ret = token.getConstructor(EntityReference.class).newInstance(reference); } else { ret = token.cast(reference); } return ret; } catch (ReflectiveOperationException | SecurityException exc) { throw new IllegalArgumentException("Unsupported entity class: " + token, exc); } }
Source:
protected double getExportResolutionFactor(DiagramEditPart diagramEP, SiriusDiagramImageGenerator gen) { double factor = 1.0; if (this.autoScalingEnabled) { List<?> editParts = diagramEP.getPrimaryEditParts(); org.eclipse.swt.graphics.Rectangle imageRect = gen.calculateImageRectangle(editParts); factor = Math.floor(Math.sqrt(Double.valueOf(getMaximumTotalSize()) / ((imageRect.width) * (imageRect.height))) * 100) / 100; int levelScaling = this.autoScalingLevel; if (factor < 1.0) { if (!allowDownScaling) { factor = 1.0; } else { factor = 1.0 - (1.0 - factor) * levelScaling / 100.; } } else { factor = 1.0 + (factor - 1.0) * levelScaling / 100.; } } return factor; }

Target:
protected double getExportResolutionFactor(DiagramEditPart diagramEP, SiriusDiagramImageGenerator gen) { double factor = 1.0; if (this.autoScalingEnabled) { List<?> editParts = diagramEP.getPrimaryEditParts(); org.eclipse.swt.graphics.Rectangle imageRect = gen.calculateImageRectangle(editParts); factor = Math.floor(Math.sqrt(Double.valueOf(getMaximumTotalSize()) / ((imageRect.width) * (imageRect.height))) * 100) / 100; if (factor < 1.0 && !allowDownScaling) { factor = 1.0; } else { factor = 1.0 + (factor - 1.0) * this.autoScalingLevel / 100.; } } return factor; }
Source:
public Date getOrder() { return new GregorianCalendar(2017, 11, 21, 16, 0, 0).getTime(); }

Target:
public Date getOrder() { return new GregorianCalendar(2017, 10, 21, 16, 0, 0).getTime(); }
Source:
public void newAnswer(@Load Question question, MarkedText description, boolean watching, List<Long> attachmentsIds) { User current = currentUser.getCurrent(); boolean canAnswer = answeredByValidator.validate(question); boolean isUserWithKarma = current.hasKarma(); AnswerInformation information = new AnswerInformation(description, currentUser, "new answer"); Answer answer = new Answer(information, question, current); if (canAnswer) { question.touchedBy(current); answers.save(answer); ReputationEvent reputationEvent = new ReputationEvent(EventType.CREATED_ANSWER, question, current); reputationEvents.save(reputationEvent); if (isUserWithKarma) { current.increaseKarma(reputationEvent.getKarmaReward()); } result.redirectTo(QuestionController.class).showQuestion(question, question.getSluggedTitle()); notificationManager.sendEmailsAndInactivate(new EmailAction(answer, question)); if (watching) { watchers.add(question, new Watcher(current)); } List<Attachment> attachmentsLoaded = attachments.load(attachmentsIds); answer.add(attachmentsLoaded); } else { result.include("answer", answer); answeredByValidator.onErrorRedirectTo(QuestionController.class).showQuestion(question, question.getSluggedTitle()); } }

Target:
public void newAnswer(@Load Question question, MarkedText description, boolean watching, List<Long> attachmentsIds) { User current = currentUser.getCurrent(); boolean canAnswer = answeredByValidator.validate(question); boolean isUserWithKarma = current.hasKarma(); AnswerInformation information = new AnswerInformation(description, currentUser, "new answer"); Answer answer = new Answer(information, question, current); List<Attachment> attachmentsLoaded = attachments.load(attachmentsIds); answer.add(attachmentsLoaded); if (canAnswer) { question.touchedBy(current); answers.save(answer); ReputationEvent reputationEvent = new ReputationEvent(EventType.CREATED_ANSWER, question, current); reputationEvents.save(reputationEvent); if (isUserWithKarma) { current.increaseKarma(reputationEvent.getKarmaReward()); } result.redirectTo(QuestionController.class).showQuestion(question, question.getSluggedTitle()); notificationManager.sendEmailsAndInactivate(new EmailAction(answer, question)); if (watching) { watchers.add(question, new Watcher(current)); } } else { result.include("answer", answer); answeredByValidator.onErrorRedirectTo(QuestionController.class).showQuestion(question, question.getSluggedTitle()); } }
Source:
private Map<String, AttributeValue> toDynamoDBItem(final PillHeartBeat heartBeat) { final Map<String, AttributeValue> key = Maps.newHashMap(); key.put(PILL_ID_ATTRIBUTE_NAME, new AttributeValue().withS(heartBeat.pillId)); key.put(UTC_DATETIME_ATTRIBUTE_NAME, new AttributeValue().withS(heartBeat.createdAtUTC.toString(DATETIME_FORMAT))); final Map<String, AttributeValue> item = Maps.newHashMap(); item.put(BATTERY_LEVEL_ATTRIBUTE_NAME, new AttributeValue().withN(String.valueOf(heartBeat.batteryLevel))); item.put(UPTIME_ATTRIBUTE_NAME, new AttributeValue().withN(String.valueOf(heartBeat.uptimeInSeconds))); item.put(FIRMWARE_VERSION_ATTRIBUTE_NAME, new AttributeValue().withN(String.valueOf(heartBeat.firmwareVersion))); return item; }

Target:
private Map<String, AttributeValue> toDynamoDBItem(final PillHeartBeat heartBeat) { final Map<String, AttributeValue> item = Maps.newHashMap(); item.put(PILL_ID_ATTRIBUTE_NAME, new AttributeValue().withS(heartBeat.pillId)); item.put(UTC_DATETIME_ATTRIBUTE_NAME, new AttributeValue().withS(heartBeat.createdAtUTC.toString(DATETIME_FORMAT))); item.put(BATTERY_LEVEL_ATTRIBUTE_NAME, new AttributeValue().withN(String.valueOf(heartBeat.batteryLevel))); item.put(UPTIME_ATTRIBUTE_NAME, new AttributeValue().withN(String.valueOf(heartBeat.uptimeInSeconds))); item.put(FIRMWARE_VERSION_ATTRIBUTE_NAME, new AttributeValue().withN(String.valueOf(heartBeat.firmwareVersion))); return item; }
Source:
public VersionHolder updateElementRevision(StudyIdentifier studyId, AppConfigElement element) { checkNotNull(studyId); checkNotNull(element); Validate.entityThrowingException(AppConfigElementValidator.INSTANCE, element); AppConfigElement existing = getElementRevision(studyId, element.getId(), element.getRevision()); if (element.isDeleted() && existing.isDeleted()) { throw new EntityNotFoundException(AppConfigElement.class); } if (existing.isPublished()) { throw new EntityPublishedException("App config element cannot be changed, it is published."); } element.setKey(studyId.getIdentifier() + ":" + element.getId()); element.setStudyId(studyId.getIdentifier()); element.setModifiedOn(getDateTime().getMillis()); element.setCreatedOn(existing.getCreatedOn()); element.setPublished(existing.isPublished()); return appConfigElementDao.saveElementRevision(element); }

Target:
public VersionHolder updateElementRevision(StudyIdentifier studyId, AppConfigElement element) { checkNotNull(studyId); checkNotNull(element); Validate.entityThrowingException(AppConfigElementValidator.INSTANCE, element); AppConfigElement existing = getElementRevision(studyId, element.getId(), element.getRevision()); if (element.isDeleted() && existing.isDeleted()) { throw new EntityNotFoundException(AppConfigElement.class); } element.setStudyId(studyId.getIdentifier()); element.setId(element.getId()); element.setModifiedOn(DateTime.now().getMillis()); element.setCreatedOn(existing.getCreatedOn()); return appConfigElementDao.saveElementRevision(element); }
Source:
private List<Node> recursiveTraceFragment(String tenantId, Span parent) { List<Span> spanChildren = getChildren(tenantId, SpanUniqueIdGenerator.toOriginal(parent)); if (spanChildren == null) { return Collections.emptyList(); } List<Node> nodes = new ArrayList<>(); for (Span child: spanChildren) { InteractionNode node = spanToNode(child); nodes.add(node); if (node.getType() == NodeType.Component) { node.setNodes(recursiveTraceFragment(tenantId, child)); } } return nodes; }

Target:
private List<Node> recursiveTraceFragment(String tenantId, Span parent) { List<Span> spanChildren = getChildren(tenantId, parent.getId()); if (spanChildren == null) { return Collections.emptyList(); } List<Node> nodes = new ArrayList<>(); for (Span child: spanChildren) { InteractionNode node = spanToNode(child); if (!parent.clientSpan()) { nodes.add(node); } if (!child.clientSpan()) { node.setNodes(recursiveTraceFragment(tenantId, child)); } } return nodes; }
Source:
protected Provider<AdditionalProperties> createProvider(String name) { Provider<AdditionalProperties> p = mock(Provider.class); when(p.getName()).thenReturn(name); return p; }

Target:
private Provider<AdditionalProperties> createProvider(String name) { Provider<AdditionalProperties> p = mock(Provider.class); when(p.getName()).thenReturn(name); return p; }
Source:
public Integer getScalingFactor() { return scalingFactor; }

Target:
public Double getScalingFactor() { return scalingFactor; }
Source:
protected Set<JWSAlgorithm> getSignatureAlgorithms(JWKSource<SecurityContext> jwkSource) { Set<SignatureAlgorithm> jwkAlgorithms = getDefaultAlgorithms(); try { jwkAlgorithms.addAll(fetchSignatureVerificationAlgorithms(jwkSource)); } catch (Exception ex) { log.error("Error fetching Signature Verification algorithms"); } return convertToJwsAlgorithms(jwkAlgorithms); }

Target:
protected Set<JWSAlgorithm> getSignatureAlgorithms(JWKSource<SecurityContext> jwkSource) { Set<SignatureAlgorithm> jwkAlgorithms = getDefaultAlgorithms(); try { if (signatureAlgorithms.isEmpty()) { jwkAlgorithms.addAll(fetchSignatureVerificationAlgorithms(jwkSource)); } } catch (Exception ex) { log.error("Error fetching Signature Verification algorithms"); } return convertToJwsAlgorithms(jwkAlgorithms); }
Source:
private Mono<CosmosContainerResponse> createContainerInternal( CosmosContainerProperties containerProperties, CosmosContainerRequestOptions options, Context context) { String spanName = "createContainer." + containerProperties.getId(); Mono<CosmosContainerResponse> responseMono = createContainerInternal(containerProperties, options); return this.client.getTracerProvider().traceEnabledCosmosResponsePublisher(responseMono, context, spanName, getId(), getClient().getServiceEndpoint()); }

Target:
private Mono<CosmosContainerResponse> createContainerInternal( CosmosContainerProperties containerProperties, CosmosContainerRequestOptions options, Context context) { String spanName = "createContainer." + containerProperties.getId(); Mono<CosmosContainerResponse> responseMono = getDocClientWrapper() .createCollection(this.getLink(), ModelBridgeInternal.getV2Collection(containerProperties), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosContainerResponse(response)).single(); return this.client.getTracerProvider().traceEnabledCosmosResponsePublisher(responseMono, context, spanName, getId(), getClient().getServiceEndpoint()); }
Source:
public static String getErrorMessage(String filename){ String errorMessage = ""; String noWhitespace = "[\\S]+"; String firstCharacterLetter = "[A-Za-z].*"; String temp = filename.replaceAll("( )+", " ").replace(" ","_"); if(temp.length() > 0){ if(!temp.matches("[A-Za-z][A-Za-z0-9_]*")) { if (!temp.matches(firstCharacterLetter)) { return MESSAGES.firstCharProjectNameError(); } else { return MESSAGES.invalidCharProjectNameError(); } } if (!filename.matches("[A-Za-z][A-Za-z0-9_]*")) { return MESSAGES.whitespaceProjectNameError().concat(". \n '").concat(temp).concat("' will be used if continued."); } else return ""; } return ""; }

Target:
public static String getErrorMessage(String filename){ String errorMessage = ""; String noWhitespace = "[\\S]+"; String firstCharacterLetter = "[A-Za-z].*"; String temp = filename.trim().replaceAll("( )+", " ").replace(" ","_"); if (temp.length() > 0) { if (!temp.matches("[A-Za-z][A-Za-z0-9_]*")) { if (!temp.matches(firstCharacterLetter)) { errorMessage = MESSAGES.firstCharProjectNameError(); } else { errorMessage = MESSAGES.invalidCharProjectNameError(); } } } return errorMessage; }
Source:
public String showInDoubtTransactions() { Set<RecoveryManager.InDoubtTxInfo> info = getRecoveryInfoFromCluster(); if (trace) { log.tracef("Found in doubt transactions: %s", info.size()); } StringBuilder result = new StringBuilder(); for (RecoveryManager.InDoubtTxInfo i : info) { result.append("xid = [").append(i.getXid()).append("], ").append(SEPARATOR) .append("internalId = ").append(i.getInternalId()).append(SEPARATOR); result.append("status = [ "); int status = i.getTxStatus(); if (status == Status.STATUS_PREPARED) { result.append("_PREPARED_"); } else if (status == Status.STATUS_COMMITTED) { result.append("_COMMITTED_"); } else if (status == Status.STATUS_ROLLEDBACK) { result.append("_ROLLEDBACK_"); } result.append(" ]"); result.append('\n'); } return result.toString(); }

Target:
public String showInDoubtTransactions() { Set<RecoveryManager.InDoubtTxInfo> info = getRecoveryInfoFromCluster(); if (trace) { log.tracef("Found in doubt transactions: %s", info.size()); } StringBuilder result = new StringBuilder(); for (RecoveryManager.InDoubtTxInfo i : info) { result.append("xid = [").append(i.getXid()).append("], ").append(SEPARATOR) .append("internalId = ").append(i.getInternalId()).append(SEPARATOR); result.append("status = [ "); int status = i.getStatus(); if (status != -1) result.append(Util.transactionStatusToString(status)); result.append(" ]"); result.append('\n'); } return result.toString(); }
Source:
public HttpResponse openAsHttpResponse(String url, HttpEntity entity, HttpMethod method) throws ClientProtocolException, IOException { this.currentURI = url; HttpResponse response; String[] headerKeys = (String[]) this.headers.keySet().toArray(new String[headers.size()]); String[] headerVals = (String[]) this.headers.values().toArray(new String[headers.size()]); ResponseHandler<String> responseHandler = new BasicResponseHandler(); HttpUriRequest request; switch (method) { case GET: request = new HttpGet(url); break; case POST: request = new HttpPost(url); ((HttpPost) request).setEntity(entity); break; case PUT: request = new HttpPut(url); ((HttpPut) request).setEntity(entity); break; default: request = new HttpGet(url); } if (userAgent != null) { request.addHeader("User-Agent", userAgent); } for (int i = 0; i < headerKeys.length; i++) { request.addHeader(headerKeys[i], headerVals[i]); } HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() { public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if(executionCount >= 5){ return false; } if(exception instanceof NoHttpResponseException){ return true; } else if (exception instanceof ClientProtocolException){ return true; } return false; } }; httpclient.setHttpRequestRetryHandler(retryHandler); response = httpclient.execute(request, mHttpContext); this.currentURI = request.getURI().toString(); return response; }

Target:
public HttpResponse openAsHttpResponse(String url, HttpEntity entity, HttpMethod method) throws ClientProtocolException, IOException { this.currentURI = url; HttpResponse response; String[] headerKeys = (String[]) this.headers.keySet().toArray(new String[headers.size()]); String[] headerVals = (String[]) this.headers.values().toArray(new String[headers.size()]); ResponseHandler<String> responseHandler = new BasicResponseHandler(); HttpUriRequest request; switch (method) { case GET: request = new HttpGet(url); break; case POST: request = new HttpPost(url); ((HttpPost) request).setEntity(entity); break; case PUT: request = new HttpPut(url); ((HttpPut) request).setEntity(entity); break; default: request = new HttpGet(url); } if (userAgent != null) { request.addHeader("User-Agent", userAgent); } for (int i = 0; i < headerKeys.length; i++) { request.addHeader(headerKeys[i], headerVals[i]); } HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() { public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= MAX_RETRIES) { return false; } if (exception instanceof NoHttpResponseException) { return true; } else if (exception instanceof ClientProtocolException) { return true; } return false; } }; httpclient.setHttpRequestRetryHandler(retryHandler); response = httpclient.execute(request, mHttpContext); this.currentURI = request.getURI().toString(); return response; }
Source:
private void configureBottomCard() { BasicKvStore flag = new BasicKvStore(this, "prevTitleDesc"); int flagVal = flag.getInt("flag"); if(flagVal == 0){ prevTitleDecs.setVisibility(View.INVISIBLE); } else { prevTitleDecs.setVisibility(View.VISIBLE); } bottomCardExpandButton.setOnClickListener(v -> presenter.toggleBottomCardState()); bottomCard.setOnClickListener(v -> presenter.toggleBottomCardState()); bottomCardAddDescription.setOnClickListener(v -> addNewDescription()); }

Target:
private void configureBottomCard() { boolean flagVal = directKvStore.getBoolean("flagForSubmit"); if(flagVal){ prevTitleDecs.setVisibility(View.VISIBLE); } else { prevTitleDecs.setVisibility(View.INVISIBLE); } bottomCardExpandButton.setOnClickListener(v -> presenter.toggleBottomCardState()); bottomCard.setOnClickListener(v -> presenter.toggleBottomCardState()); bottomCardAddDescription.setOnClickListener(v -> addNewDescription()); }
Source:
private void performDiscardChanges() { ArrayList<IResource> allFiles = new ArrayList<IResource>(); for (IResource res : getSelectedResources()) { allFiles.addAll(getAllMembers(res)); } for (IResource res : allFiles) { try { discardChange(res); } catch (IOException e1) { MessageDialog.openError(getShell(), UIText.DiscardChangesAction_checkoutErrorTitle, UIText.DiscardChangesAction_checkoutErrorMessage); } catch (CoreException e) { MessageDialog.openError(getShell(), UIText.DiscardChangesAction_refreshErrorTitle, UIText.DiscardChangesAction_refreshErrorMessage); } } }

Target:
private void performDiscardChanges() { ArrayList<IResource> allFiles = new ArrayList<IResource>(); for (IResource res : getSelectedResources()) { allFiles.addAll(getAllMembers(res)); } for (IResource res : allFiles) { try { discardChange(res); } catch (IOException e1) { MessageDialog.openError(getShell(), UIText.DiscardChangesAction_unexpectedErrorTitle, UIText.DiscardChangesAction_unexpectedErrorMessage); }catch (RuntimeException e2) { MessageDialog.openError(getShell(), UIText.DiscardChangesAction_unexpectedErrorTitle, UIText.DiscardChangesAction_unexpectedIndexErrorMessage); } } }
Source:
public void start() throws CacheLoaderException { try { if(!config.autoCreateKeyspace) config.poolProperties.setKeySpace(config.keySpace); dataSource = new DataSource(config.getPoolProperties()); readConsistencyLevel = ConsistencyLevel.valueOf(config.readConsistencyLevel); writeConsistencyLevel = ConsistencyLevel.valueOf(config.writeConsistencyLevel); entryColumnPath = new ColumnPath(config.entryColumnFamily).setColumn(ENTRY_COLUMN_NAME.getBytes(UTF8Charset)); entryColumnParent = new ColumnParent(config.entryColumnFamily); entryKeyPrefix = ENTRY_KEY_PREFIX + (config.isSharedKeyspace() ? cacheName + "_" : ""); expirationColumnParent = new ColumnParent(config.expirationColumnFamily); expirationKey = ByteBufferUtil.bytes(EXPIRATION_KEY + (config.isSharedKeyspace() ? "_" + cacheName : "")); keyMapper = (TwoWayKey2StringMapper) Util.getInstance(config.getKeyMapper()); } catch (Exception e) { throw new ConfigurationException(e); } if(config.autoCreateKeyspace) { log.debug("automatically create keyspace"); createKeySpace(); dataSource.close(); dataSource.setKeySpace(config.keySpace); } log.debug("cleaning up expired entries..."); purgeInternal(); log.debug("started"); super.start(); }

Target:
public void start() throws CacheLoaderException { try { if (!config.autoCreateKeyspace) config.poolProperties.setKeySpace(config.keySpace); dataSource = new DataSource(config.getPoolProperties()); readConsistencyLevel = ConsistencyLevel.valueOf(config.readConsistencyLevel); writeConsistencyLevel = ConsistencyLevel.valueOf(config.writeConsistencyLevel); entryColumnPath = new ColumnPath(config.entryColumnFamily).setColumn(ENTRY_COLUMN_NAME .getBytes(UTF8Charset)); entryColumnParent = new ColumnParent(config.entryColumnFamily); entryKeyPrefix = ENTRY_KEY_PREFIX + (config.isSharedKeyspace() ? cacheName + "_" : ""); expirationColumnParent = new ColumnParent(config.expirationColumnFamily); expirationKey = ByteBufferUtil.bytes(EXPIRATION_KEY + (config.isSharedKeyspace() ? "_" + cacheName : "")); keyMapper = (TwoWayKey2StringMapper) Util.getInstance(config.getKeyMapper()); } catch (Exception e) { throw new ConfigurationException(e); } if (config.autoCreateKeyspace) { log.debug("automatically create keyspace"); try { createKeySpace(); } finally { dataSource.close(); } dataSource.setKeySpace(config.keySpace); } log.debug("cleaning up expired entries..."); purgeInternal(); log.debug("started"); super.start(); }
Source:
private static BkBasicTest.MkSocket createMockSocket() throws IOException { return new BkBasicTest.MkSocket(); }

Target:
private static MkSocket createMockSocket() throws IOException { return new MkSocket( new ByteArrayInputStream( Joiner.on(BkBasicTest.CRLF).join( "GET / HTTP/1.1", "Host:localhost", "Content-Length: 2", "", "hi" ).getBytes() ) ); }