auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Long findModelIdByName(String modelName, int numFields) { SharedPreferences modelsDb = mContext.getSharedPreferences(MODEL_REF_DB, Context.MODE_PRIVATE); long prefsModelId = modelsDb.getLong(modelName, -1L); Map<Long, String> modelList = getModelList(numFields); long bestModelIdSoFar = -1L; for (Map.Entry<Long, String> entry : modelList.entrySet()) { if (entry.getValue().equals(modelName)) { long id = entry.getKey(); if (id == prefsModelId) { return id; } if (bestModelIdSoFar == -1L) { bestModelIdSoFar = id; } } } if (bestModelIdSoFar != -1L) { return bestModelIdSoFar; } if (prefsModelId != -1L && getModelName(prefsModelId) != null && getFieldList(prefsModelId).length >= numFields) { return prefsModelId; } return null; }

Target:
public Long findModelIdByName(String modelName, int numFields) { SharedPreferences modelsDb = mContext.getSharedPreferences(MODEL_REF_DB, Context.MODE_PRIVATE); long prefsModelId = modelsDb.getLong(modelName, -1L); if (prefsModelId != -1L && getModelName(prefsModelId) != null && getFieldList(prefsModelId).length >= numFields) { return prefsModelId; } Map<Long, String> modelList = getModelList(numFields); for (Map.Entry<Long, String> entry : modelList.entrySet()) { if (entry.getValue().equals(modelName)) { return entry.getKey(); } } return null; }
Source:
static void ensureHasTypes(Biome biome) { if (!hasAnyType(biome)) { FMLLog.warning("No types have been added to Biome %s, types will be assigned on a best-effort guess."); makeBestGuess(biome); } }

Target:
static void ensureHasTypes(Biome biome) { if (!hasAnyType(biome)) { FMLLog.warning("No types have been added to Biome %s, types will be assigned on a best-effort guess.", biome.getRegistryName()); makeBestGuess(biome); } }
Source:
public void compact(Integer key, String value, byte[] data, int offset, int len) { Assert.assertEquals(4 + value.length(), len); copyIntToArray(key, data, offset); byte[] src = value.getBytes(); Assert.assertEquals(value.length(), src.length); System.arraycopy(src, 0, data, offset + 4, src.length); }

Target:
public void compact(Integer key, String value, byte[] data, int offset, int len) { Assert.assertEquals(4 + value.length(), len); copyIntToArray(key, data, offset); byte[] src = value.getBytes(); Assert.assertEquals(value.length(), src.length); }
Source:
protected List<String> transformM2toM1( final String path, final List<String> extraFolders ) { final Gav gav = getM2GavCalculator().pathToGav( path ); if ( gav == null ) { return null; } final ArrayList<String> exts = new ArrayList<String>(); exts.add( gav.getExtension() + "s" ); if ( extraFolders != null && !extraFolders.isEmpty() ) { exts.addAll( extraFolders ); } final ArrayList<String> result = new ArrayList<String>( exts.size() ); for ( String ext : exts ) { StringBuilder sb = new StringBuilder( RepositoryItemUid.PATH_ROOT ); sb.append( gav.getGroupId() ); sb.append( RepositoryItemUid.PATH_SEPARATOR ); sb.append( ext ); sb.append( RepositoryItemUid.PATH_SEPARATOR ); sb.append( gav.getName() ); result.add( sb.toString() ); } return result; }

Target:
protected List<String> transformM2toM1( final String path, final List<String> extraFolders ) { final Gav gav = getM2GavCalculator().pathToGav( path ); if ( gav == null ) { return null; } final List<String> exts = Lists.newArrayList(); exts.add( gav.getExtension() + "s" ); if ( extraFolders != null && !extraFolders.isEmpty() ) { exts.addAll( extraFolders ); } final List<String> result = Lists.newArrayListWithCapacity( exts.size() ); for ( String ext : exts ) { StringBuilder sb = new StringBuilder( RepositoryItemUid.PATH_ROOT ); sb.append( gav.getGroupId() ); sb.append( RepositoryItemUid.PATH_SEPARATOR ); sb.append( ext ); sb.append( RepositoryItemUid.PATH_SEPARATOR ); sb.append( gav.getName() ); result.add( sb.toString() ); } return result; }
Source:
public IStatus validateDrop(Object target, int operation, TransferData transferType) { if (operation != DND.DROP_MOVE) { return Status.CANCEL_STATUS; } IWorkingSet targetWorkingSet = null; if (target instanceof IAdaptable) { targetWorkingSet = (IWorkingSet) ((IAdaptable)target).getAdapter(IWorkingSet.class); } if (targetWorkingSet == null) { return Status.CANCEL_STATUS; } Set<IProject> toMove = new HashSet<IProject>(); if (LocalSelectionTransfer.getTransfer().isSupportedType(transferType)) { ISelection sel = LocalSelectionTransfer.getTransfer().getSelection(); if (!sel.isEmpty() && sel instanceof IStructuredSelection) { for (Object item : ((IStructuredSelection)sel).toArray()) { if (item instanceof IAdaptable) { IProject project = null; if (item instanceof IAdaptable) { project = (IProject) ((IAdaptable)item).getAdapter(IProject.class); } if (project != null && !workingSetContains(targetWorkingSet, project)) { toMove.add(project); } } } } } if (toMove.isEmpty()) { return Status.CANCEL_STATUS; } return Status.OK_STATUS; }

Target:
public IStatus validateDrop(Object target, int operation, TransferData transferType) { if (operation != DND.DROP_MOVE) { return Status.CANCEL_STATUS; } IWorkingSet targetWorkingSet = null; if (target instanceof IAdaptable) { targetWorkingSet = ((IAdaptable) target).getAdapter(IWorkingSet.class); } if (targetWorkingSet == null) { return Status.CANCEL_STATUS; } if (!LocalSelectionTransfer.getTransfer().isSupportedType(transferType)) { return Status.CANCEL_STATUS; } ISelection sel = LocalSelectionTransfer.getTransfer().getSelection(); if (!sel.isEmpty() && sel instanceof IStructuredSelection) { for (Object item : ((IStructuredSelection) sel).toArray()) { if (item instanceof IAdaptable) { IProject project = ((IAdaptable) item).getAdapter(IProject.class); if (project != null && !workingSetContains(targetWorkingSet, project)) { return Status.OK_STATUS; } } } } return Status.CANCEL_STATUS; }
Source:
public void service(HttpRequest request, HttpResponse response) throws Exception { BufferedWriter w = response.getWriter(); try { DatabaseClient client = getClient(); try (ResultSet rs = client .singleUse() .executeQuery(Statement.of("SELECT SingerId, AlbumId, AlbumTitle FROM Albums"))) { w.write("Albums:\n"); while (rs.next()) { w.write( String.format( "%d %d %s\n", rs.getLong("SingerId"), rs.getLong("AlbumId"), rs.getString("AlbumTitle"))); } } catch (SpannerException e) { w.write(String.format("Error querying database: %s\n", e.getMessage())); response.setStatusCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, e.getMessage()); } } catch (Throwable t) { LOGGER.log(Level.SEVERE, "Spanner example failed", t); w.write(String.format("Error setting up Spanner: %s\n", t.getMessage())); response.setStatusCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, t.getMessage()); } }

Target:
public void service(HttpRequest request, HttpResponse response) throws Exception { BufferedWriter writer = response.getWriter(); try { DatabaseClient client = getClient(); try (ResultSet rs = client .singleUse() .executeQuery(Statement.of("SELECT SingerId, AlbumId, AlbumTitle FROM Albums"))) { writer.write("Albums:\n"); while (rs.next()) { writer.write( String.format( "%d %d %s\n", rs.getLong("SingerId"), rs.getLong("AlbumId"), rs.getString("AlbumTitle"))); } } catch (SpannerException e) { writer.write(String.format("Error querying database: %s\n", e.getMessage())); response.setStatusCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, e.getMessage()); } } catch (Throwable t) { LOGGER.log(Level.SEVERE, "Spanner example failed", t); writer.write(String.format("Error setting up Spanner: %s\n", t.getMessage())); response.setStatusCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, t.getMessage()); } }
Source:
private static DetailedLibraryDto asDetailedLibraryDto(DetailedLibrary from) { DetailedLibraryDto dto = new DetailedLibraryDto(); if (from.getLibraryDesign() != null) { dto.setLibraryDesignId(from.getLibraryDesign().getId()); } dto.setLibraryDesignCodeId(from.getLibraryDesignCode().getId()); dto.setPreMigrationId(from.getPreMigrationId()); dto.setArchived(from.getArchived()); dto.setNonStandardAlias(from.hasNonStandardAlias()); if (from.getGroupId() != null) { dto.setGroupId(from.getGroupId()); dto.setEffectiveGroupId(from.getGroupId()); dto.setEffectiveGroupIdSample(from.getAlias()); } else { Optional<DetailedSample> effective = ((DetailedSample) from.getSample()).getEffectiveGroupIdSample(); effective.ifPresent(upstream -> { dto.setEffectiveGroupId(upstream.getGroupId()); dto.setEffectiveGroupIdSample(upstream.getAlias()); }); } if (from.getGroupDescription() != null) { dto.setGroupDescription(from.getGroupDescription()); } if (from.getSample() != null) { dto.setIdentityConsentLevel(getIdentityConsentLevelString((DetailedSample) from.getSample())); if (isDetailedSample(from.getSample())) { DetailedSample detailed = (DetailedSample) from.getSample(); if (detailed.getSubproject() != null) { dto.setSubprojectAlias(detailed.getSubproject().getAlias()); dto.setSubprojectPriority(detailed.getSubproject().getPriority()); } } } return dto; }

Target:
private static DetailedLibraryDto asDetailedLibraryDto(DetailedLibrary from) { DetailedLibraryDto dto = new DetailedLibraryDto(); if (from.getLibraryDesign() != null) { dto.setLibraryDesignId(from.getLibraryDesign().getId()); } dto.setLibraryDesignCodeId(from.getLibraryDesignCode().getId()); dto.setPreMigrationId(from.getPreMigrationId()); dto.setArchived(from.getArchived()); dto.setNonStandardAlias(from.hasNonStandardAlias()); if (from.getGroupId() != null) { dto.setGroupId(from.getGroupId()); dto.setEffectiveGroupId(from.getGroupId()); dto.setEffectiveGroupIdSample(from.getAlias()); } else { Optional<DetailedSample> effective = ((DetailedSample) from.getSample()).getEffectiveGroupIdSample(); effective.ifPresent(upstream -> { dto.setEffectiveGroupId(upstream.getGroupId()); dto.setEffectiveGroupIdSample(upstream.getAlias()); }); } if (from.getGroupDescription() != null) { dto.setGroupDescription(from.getGroupDescription()); } if (from.getSample() != null) { dto.setIdentityConsentLevel(getIdentityConsentLevelString((DetailedSample) from.getSample())); DetailedSample detailed = (DetailedSample) from.getSample(); if (detailed.getSubproject() != null) { dto.setSubprojectAlias(detailed.getSubproject().getAlias()); dto.setSubprojectPriority(detailed.getSubproject().getPriority()); } } return dto; }
Source:
public static TreeWalk forPath(final Repository db, final String path, final AnyObjectId... trees) throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException { ObjectReader reader = db.newObjectReader(); try { return forPath(reader, path, trees); } finally { reader.close(); } }

Target:
public static TreeWalk forPath(final Repository db, final String path, final AnyObjectId... trees) throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException { try (ObjectReader reader = db.newObjectReader()) { return forPath(reader, path, trees); } }
Source:
public void setConceptsInDbText(String text) { if(text.equals("0")){ downloadConceptsButton.setEnabled(false); Toast.makeText(getActivity(), "There are no concepts in DB!", Toast.LENGTH_LONG).show(); } conceptsInDbTextView.setText(text); }

Target:
public void setConceptsInDbText(String text) { if(text.equals("0")){ downloadConceptsButton.setEnabled(false); ToastUtil.showLongToast(getActivity(), ToastUtil.ToastType.WARNING, R.string.settings_no_concepts_toast); } conceptsInDbTextView.setText(text); }
Source:
public static String encryptPassword(String plainPassword, String algorithm) { if (plainPassword == null) { throw new IllegalArgumentException(); } if (algorithm != null) { if (algorithm.equals(ALGORITHM_COMMON_V3)) { try { return CryptoMigrationUtil.encrypt(plainPassword); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } } else if (algorithm.equals(ALGORITHM_COMMON) || algorithm.equals(ALGORITHM_COMMON_V2)) { return null; } } return encryptPasswordBase64(plainPassword); }

Target:
public static String encryptPassword(String plainPassword, String algorithm) { if (plainPassword == null) { throw new IllegalArgumentException(); } if (algorithm != null) { if (algorithm.equals(ALGORITHM_COMMON_V3)) { try { return StudioEncryption.getStudioEncryption(StudioEncryption.EncryptionKeyName.SYSTEM) .encrypt(plainPassword); } catch (Exception e) { LOGGER.error(e.getMessage(), e); return null; } } else if (algorithm.equals(ALGORITHM_COMMON) || algorithm.equals(ALGORITHM_COMMON_V2)) { return null; } } return encryptPasswordBase64(plainPassword); }
Source:
public LoggingHandler(Level level) { setLevel(level); }

Target:
public LoggingHandler(Level level) { doSetLevel(level); }
Source:
public Response toResponse(WebApplicationException e) { return status(e.getResponse().getStatus()).entity(e.getMessage()).build(); }

Target:
public Response toResponse(WebApplicationException e) { return status(e.getResponse().getStatus()).entity(new ErrorResponse(e.getMessage())).build(); }
Source:
private LineString getBuildingFeatureOutline(@NonNull Style style) { final PointF pixel = mapboxMap.getProjection().toScreenLocation(new LatLng( mapboxMap.getCameraPosition().target.getLatitude(), mapboxMap.getCameraPosition().target.getLongitude() )); List<Point> pointList = new ArrayList<>(); if (style.getLayer("building") != null) { List<Feature> features = mapboxMap.queryRenderedFeatures(pixel, "building"); if (features.size() > 0) { Feature buildingFeature = features.get(0); if (buildingFeature.geometry() instanceof Polygon) { for (int i = 0; i < ((Polygon) buildingFeature.geometry()).coordinates().size(); i++) { for (int j = 0; j < ((Polygon) buildingFeature.geometry()).coordinates().get(i).size(); j++) { pointList.add(Point.fromLngLat( ((Polygon) buildingFeature.geometry()).coordinates().get(i).get(j).longitude(), ((Polygon) buildingFeature.geometry()).coordinates().get(i).get(j).latitude() )); } } } } } return LineString.fromLngLats(pointList); }

Target:
private LineString getBuildingFeatureOutline(@NonNull Style style) { final PointF pixel = mapboxMap.getProjection().toScreenLocation(new LatLng( mapboxMap.getCameraPosition().target.getLatitude(), mapboxMap.getCameraPosition().target.getLongitude() )); List<Point> pointList = new ArrayList<>(); if (style.getLayer("building") != null) { List<Feature> features = mapboxMap.queryRenderedFeatures(pixel, "building"); if (features.size() > 0) { if (features.get(0).geometry() instanceof Polygon) { Polygon buildingFeature = (Polygon) features.get(0).geometry(); for (int i = 0; i < buildingFeature.coordinates().size(); i++) { for (int j = 0; j < buildingFeature.coordinates().get(i).size(); j++) { pointList.add(Point.fromLngLat( buildingFeature.coordinates().get(i).get(j).longitude(), buildingFeature.coordinates().get(i).get(j).latitude() )); } } } } } else { Toast.makeText(this, R.string.building_layer_not_present, Toast.LENGTH_SHORT).show(); } return LineString.fromLngLats(pointList); }
Source:
public void testDoNotUpgradePropSet() throws Exception { String tableName = "HBASE_SYNTH_TEST"; startMiniClusterWithToggleNamespaceMapping(Boolean.FALSE.toString()); Properties propsDoNotUpgradePropSet = new Properties(); Connection con1 = DriverManager.getConnection(getJdbcUrl(),propsDoNotUpgradePropSet); String ddl = "CREATE TABLE "+ tableName +" (PK1 VARCHAR not null, PK2 VARCHAR not null, " + "COL1 varchar, COL2 varchar " + "CONSTRAINT pk PRIMARY KEY(PK1,PK2))"; con1.createStatement().execute(ddl); con1.createStatement().execute("UPSERT INTO " + tableName + " values ('pk1','pk2','c1','c2')"); con1.commit(); testUtil.getMiniHBaseCluster().getMaster().stopMaster(); UpgradeUtil.doNotUpgradeOnFirstConnection(propsDoNotUpgradePropSet); Connection con2 = DriverManager.getConnection(getJdbcUrl(),propsDoNotUpgradePropSet); ResultSet rs = con2.createStatement().executeQuery("select * from " + tableName); assertTrue(rs.next()); assertEquals("pk1", rs.getString(1)); assertEquals("pk2", rs.getString(2)); assertFalse(rs.next()); con1.close(); con2.close(); }

Target:
public void testDoNotUpgradePropSet() throws Exception { String tableName = "HBASE_SYNTH_TEST"; startMiniClusterWithToggleNamespaceMapping(Boolean.FALSE.toString()); Properties propsDoNotUpgradePropSet = new Properties(); try (Connection con1 = DriverManager.getConnection(getJdbcUrl(), propsDoNotUpgradePropSet)) { String ddl = "CREATE TABLE " + tableName + " (PK1 VARCHAR not null, " + "PK2 VARCHAR not null, COL1 varchar, COL2 varchar " + "CONSTRAINT pk PRIMARY KEY(PK1,PK2))"; con1.createStatement().execute(ddl); con1.createStatement().execute( "UPSERT INTO " + tableName + " values ('pk1','pk2','c1','c2')"); con1.commit(); testUtil.getMiniHBaseCluster().getMaster().stopMaster(); UpgradeUtil.doNotUpgradeOnFirstConnection(propsDoNotUpgradePropSet); try (Connection con2 = DriverManager.getConnection(getJdbcUrl(), propsDoNotUpgradePropSet)) { ResultSet rs = con2.createStatement().executeQuery("select * from " + tableName); assertTrue(rs.next()); assertEquals("pk1", rs.getString(1)); assertEquals("pk2", rs.getString(2)); assertFalse(rs.next()); } } finally { testUtil.getMiniHBaseCluster().startMaster(); } }
Source:
public ServiceBusManagementClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; }

Target:
public ServiceBusAdministrationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; }
Source:
File writeBam(final SAMRecordSetBuilder builder, final File f) { final SAMFileWriter out = new SAMFileWriterFactory().makeSAMOrBAMWriter(builder.getHeader(), false, f); builder.forEach(out::addAlignment); out.close(); return f; }

Target:
File writeBam(final SAMRecordSetBuilder builder, final File f) { try (final SAMFileWriter out = new SAMFileWriterFactory().makeSAMOrBAMWriter(builder.getHeader(), false, f)) { builder.forEach(out::addAlignment); } return f; }
Source:
public void printText(String text) { view.print(text, false); Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { @Override public void execute() { view.scrollBottom(); } }); }

Target:
public void printText(String text) { view.print(text, false); view.scrollBottom(); }
Source:
public synchronized ClassSpec getClassSpec(final String fileName) throws IOException { final JarEntry entry = getJarEntry(fileName); if (entry == null) { return null; } final ClassSpec spec = new ClassSpec(); final long size = entry.getSize(); if (size == -1) { spec.setBytes(getClassBytes(entry)); CodeSource codeSource = createCodeSource(entry); spec.setCodeSource(codeSource); return spec; } else if (size <= (long) Integer.MAX_VALUE) { spec.setBytes(getClassBytes(entry, (int) size)); CodeSource codeSource = createCodeSource(entry); spec.setCodeSource(codeSource); return spec; } else { throw new IOException("Resource is too large to be a valid class file"); } }

Target:
public synchronized ClassSpec getClassSpec(final String fileName) throws IOException { final JarEntry entry = getJarEntry(fileName); if (entry == null) { return null; } final ClassSpec spec = new ClassSpec(); final long size = entry.getSize(); if (size == -1) { spec.setBytes(getClassBytes(entry)); spec.setCodeSource(createCodeSource(entry)); } else if (size <= (long) Integer.MAX_VALUE) { spec.setBytes(getClassBytes(entry, (int) size)); spec.setCodeSource(createCodeSource(entry)); } else { throw new IOException("Resource is too large to be a valid class file"); } return spec; }
Source:
public void processConnectionEvent(Message message, int state) { stateLogD("processConnectionEvent, state=" + state); switch (state) { case HeadsetHalConstants.CONNECTION_STATE_DISCONNECTED: stateLogW("ignore DISCONNECTED event"); break; case HeadsetHalConstants.CONNECTION_STATE_CONNECTED: case HeadsetHalConstants.CONNECTION_STATE_CONNECTING: if (mHeadsetService.okToAcceptConnection(mDevice)) { stateLogI("accept incoming connection"); transitionTo(mConnecting); } else { stateLogI("rejected incoming HF, priority=" + mHeadsetService.getConnectionPolicy(mDevice) + " bondState=" + mAdapterService.getBondState(mDevice)); if (!mNativeInterface.disconnectHfp(mDevice)) { stateLogE("failed to disconnect"); } broadcastConnectionState(mDevice, BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_DISCONNECTED); } break; case HeadsetHalConstants.CONNECTION_STATE_DISCONNECTING: stateLogW("Ignore DISCONNECTING event"); break; default: stateLogE("Incorrect state: " + state); break; } }

Target:
public void processConnectionEvent(Message message, int state) { stateLogD("processConnectionEvent, state=" + state); switch (state) { case HeadsetHalConstants.CONNECTION_STATE_DISCONNECTED: stateLogW("ignore DISCONNECTED event"); break; case HeadsetHalConstants.CONNECTION_STATE_CONNECTED: case HeadsetHalConstants.CONNECTION_STATE_CONNECTING: if (mHeadsetService.okToAcceptConnection(mDevice)) { stateLogI("accept incoming connection"); transitionTo(mConnecting); } else { stateLogI("rejected incoming HF, connectionPolicy=" + mHeadsetService.getConnectionPolicy(mDevice) + " bondState=" + mAdapterService.getBondState(mDevice)); if (!mNativeInterface.disconnectHfp(mDevice)) { stateLogE("failed to disconnect"); } broadcastConnectionState(mDevice, BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_DISCONNECTED); } break; case HeadsetHalConstants.CONNECTION_STATE_DISCONNECTING: stateLogW("Ignore DISCONNECTING event"); break; default: stateLogE("Incorrect state: " + state); break; } }
Source:
@Override public List<Pair<RelTraitSet, List<RelTraitSet>>> deriveCollation(RelTraitSet nodeTraits, List<RelTraitSet> inputTraits) { RelTraitSet left = inputTraits.get(0), right = inputTraits.get(1); RelCollation leftCollation = TraitUtils.collation(left), rightCollation = TraitUtils.collation(right); if (!isPrefix(rightCollation.getKeys(), joinInfo.rightKeys)) return ImmutableList.of(); if (variablesSet.size() == 1) nodeTraits.replace(leftCollation); else nodeTraits.replace(RelCollations.EMPTY); return ImmutableList.of( Pair.of( nodeTraits.replace(leftCollation), ImmutableList.of( left, right.replace(rightCollation) ) ) ); }

Target:
@Override public List<Pair<RelTraitSet, List<RelTraitSet>>> deriveCollation( RelTraitSet nodeTraits, List<RelTraitSet> inputTraits ) { RelTraitSet left = inputTraits.get(0), right = inputTraits.get(1); RelCollation leftCollation = TraitUtils.collation(left), rightCollation = TraitUtils.collation(right); List<Integer> newRightCollationFields = maxPrefix(rightCollation.getKeys(), joinInfo.leftKeys); if (F.isEmpty(newRightCollationFields)) return ImmutableList.of(); if (variablesSet.size() == 1) nodeTraits.replace(leftCollation); else nodeTraits.replace(RelCollations.EMPTY); return ImmutableList.of( Pair.of( nodeTraits.replace(leftCollation), ImmutableList.of( left, right ) ) ); }
Source:
static DurationValue durationBetween( Temporal from, Temporal to ) { long months = 0; long days = 0; if ( from.isSupported( EPOCH_DAY ) && to.isSupported( EPOCH_DAY ) ) { LocalDate fromDate; LocalDate toDate; try { fromDate = LocalDate.from( from ); toDate = LocalDate.from( to ); } catch ( DateTimeException e ) { throw new InvalidTemporalArgumentException( e.getMessage(), e ); } Period period = Period.between( fromDate, toDate ); months = period.getYears() * 12L + period.getMonths(); days = period.getDays(); if ( months != 0 || days != 0 ) { try { from = from.plus( period ); } catch ( DateTimeException | ArithmeticException e ) { throw new TemporalArithmeticException( e.getMessage(), e ); } } } long nanos = assertValidUntil( from, to, NANOS ); return newDuration( months, days, nanos / NANOS_PER_SECOND, (int) (nanos % NANOS_PER_SECOND) ); }

Target:
static DurationValue durationBetween( Temporal from, Temporal to ) { long months = 0; long days = 0; if ( from.isSupported( EPOCH_DAY ) && to.isSupported( EPOCH_DAY ) ) { LocalDate fromDate; LocalDate toDate; try { fromDate = LocalDate.from( from ); toDate = LocalDate.from( to ); } catch ( DateTimeException e ) { throw new InvalidValuesArgumentException( e.getMessage(), e ); } Period period = Period.between( fromDate, toDate ); months = period.getYears() * 12L + period.getMonths(); days = period.getDays(); if ( months != 0 || days != 0 ) { try { from = from.plus( period ); } catch ( DateTimeException | ArithmeticException e ) { throw new TemporalArithmeticException( e.getMessage(), e ); } } } long nanos = assertValidUntil( from, to, NANOS ); return newDuration( months, days, nanos / NANOS_PER_SECOND, (int) (nanos % NANOS_PER_SECOND) ); }
Source:
@Test public void headWithSiblings() throws Exception { final String bucket = UUID.randomUUID().toString(); final String key = "k"; final String value = "v"; final String value2 = "v2"; IRiakObject o = RiakObjectBuilder.newBuilder(bucket, key).withValue(value).build(); IRiakObject o2 = RiakObjectBuilder.newBuilder(bucket, key).withValue(value2).build(); client.updateBucket(bucket, new BucketPropertiesBuilder().allowSiblings(true).build()); Thread.sleep(500); client.store(o); client.store(o2); RiakResponse r = client.fetch(bucket, key); assertNotNull(r); assertTrue(r.hasValue()); assertTrue(r.hasSiblings()); assertEquals(2, r.getRiakObjects().length); RiakResponse headResponse = client.head(bucket, key, null); assertNotNull(headResponse); assertTrue(headResponse.hasValue()); assertTrue(headResponse.hasSiblings()); for (IRiakObject iro : headResponse.getRiakObjects()) { if (client.getTransport() != Transport.HTTP) { assertEmptyString(iro.getValueAsString()); } } }

Target:
@Test public void headWithSiblings() throws Exception { final String bucket = UUID.randomUUID().toString(); final String key = "k"; final String value = "v"; final String value2 = "v2"; IRiakObject o = RiakObjectBuilder.newBuilder(bucket, key).withValue(value).build(); IRiakObject o2 = RiakObjectBuilder.newBuilder(bucket, key).withValue(value2).build(); client.updateBucket(bucket, new BucketPropertiesBuilder().allowSiblings(true).build()); Thread.sleep(500); client.store(o); client.store(o2); RiakResponse r = client.fetch(bucket, key); assertNotNull(r); assertTrue(r.hasValue()); assertTrue(r.hasSiblings()); assertEquals(2, r.getRiakObjects().length); RiakResponse headResponse = client.head(bucket, key, null); assertNotNull(headResponse); assertTrue(headResponse.hasValue()); assertTrue(headResponse.hasSiblings()); for (IRiakObject iro : headResponse.getRiakObjects()) { assertNotEmptyString(iro.getValueAsString()); } }
Source:
private int createNotification(Context context, NotificationData data) { initNotificationManager(context); PendingIntent doesNothingPendingIntent = PendingIntent.getActivity(context, -1, new Intent(), PendingIntent.FLAG_ONE_SHOT); Notification.Builder notificationBuilder; if (android.os.Build.VERSION.SDK_INT < 26) { notificationBuilder = new Notification.Builder(context); } else { notificationBuilder = new Notification.Builder(context, CHANNEL_ID); } notificationBuilder.setContentTitle(data.getNotificationTitleWorking()) .setContentText(data.getNotificationTextWorking()).setSmallIcon(data.getNotificationIcon()) .setOngoing(true).setContentIntent(doesNothingPendingIntent); data.setNotificationBuilder(notificationBuilder); notificationDataMap.put(notificationId, data); return notificationId++; }

Target:
private int createNotification(Context context, NotificationData data) { initNotificationManager(context); PendingIntent doesNothingPendingIntent = PendingIntent.getActivity(context, -1, new Intent(), PendingIntent.FLAG_ONE_SHOT); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, CHANNEL_ID); notificationBuilder.setContentTitle(data.getNotificationTitleWorking()) .setContentText(data.getNotificationTextWorking()) .setSmallIcon(data.getNotificationIcon()) .setOngoing(true) .setContentIntent(doesNothingPendingIntent); data.setNotificationBuilder(notificationBuilder); notificationDataMap.put(notificationId, data); return notificationId++; }
Source:
public boolean isCounting() { assert startTime != -1; return System.currentTimeMillis() - startTime <= duration.toMillis(); }

Target:
public boolean isCounting() { assert startTime != null; Duration elapsed = Duration.between(startTime, Instant.now()); return elapsed.compareTo(duration) <= 0; }
Source:
public void makeDiscoverablePatchForbiddenTest() throws Exception { context.turnOffAuthorisationSystem(); parentCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity) .withName("Sub Community") .build(); Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build(); Item item = ItemBuilder.createItem(context, col1) .withTitle("Public item 1") .withIssueDate("2017-10-17") .withAuthor("Smith, Donald").withAuthor("Doe, John") .withSubject("ExtraEntry") .makeUnDiscoverable() .build(); String token = getAuthToken(eperson.getEmail(), password); String tokenAdmin = getAuthToken(admin.getEmail(), password); List<Operation> ops = new ArrayList<Operation>(); ReplaceOperation replaceOperation = new ReplaceOperation("/discoverable", "true"); ops.add(replaceOperation); String patchBody = getPatchContent(ops); getClient(token).perform(patch("/api/core/items/" + item.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isForbidden()); getClient(tokenAdmin).perform(get("/api/core/items/" + item.getID())) .andExpect(status().isOk()) .andExpect(jsonPath("$.uuid", Matchers.is(item.getID().toString()))) .andExpect(jsonPath("$.discoverable", Matchers.is(false))); }

Target:
public void makeDiscoverablePatchForbiddenTest() throws Exception { context.turnOffAuthorisationSystem(); parentCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity) .withName("Sub Community") .build(); Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build(); Item item = ItemBuilder.createItem(context, col1) .withTitle("Public item 1") .withIssueDate("2017-10-17") .withAuthor("Smith, Donald").withAuthor("Doe, John") .withSubject("ExtraEntry") .makeUnDiscoverable() .build(); String token = getAuthToken(eperson.getEmail(), password); String tokenAdmin = getAuthToken(admin.getEmail(), password); List<Operation> ops = new ArrayList<Operation>(); ReplaceOperation replaceOperation = new ReplaceOperation("/discoverable", true); ops.add(replaceOperation); String patchBody = getPatchContent(ops); getClient(token).perform(patch("/api/core/items/" + item.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isForbidden()); getClient(tokenAdmin).perform(get("/api/core/items/" + item.getID())) .andExpect(status().isOk()) .andExpect(jsonPath("$.uuid", Matchers.is(item.getID().toString()))) .andExpect(jsonPath("$.discoverable", Matchers.is(false))); }
Source:
public ConfigurationScopeAwareProvider(Configuration configuration) { this.configuration = requireNonNull(configuration); }

Target:
public ConfigurationScopeAwareProvider(Configuration configuration) { this.configuration = Assert.nonNull(configuration, () -> "configuration may not be null"); }
Source:
private void openButtonAction(ActionEvent e) { progressDialog = new ProgressDialog(root, graphLoadService); Optional<ButtonType> result = new OpenDialog(root, Alert.AlertType.NONE, graphLoadService, newickLoadService).showAndWait(); if (result.get().getButtonData() == ButtonBar.ButtonData.OK_DONE) { restart(); } else { reset(); } }

Target:
private void openButtonAction(ActionEvent e) { progressDialog = new ProgressDialog(root, graphLoadService); Optional<ButtonType> result = new OpenDialog(root, graphLoadService, newickLoadService) .showAndWait(); if (result.get().getButtonData() == ButtonBar.ButtonData.OK_DONE) { restart(); } else { reset(); } }
Source:
public Array<Actor> getExtras() { final Array<Actor> actors = new Array<Actor>(false, 2); actors.add(this.paint); actors.add(this.eraser); return actors; }

Target:
public Array<Actor> getExtras() { Array<Actor> actors = new Array<Actor>(false, 2); actors.add(this.paint); actors.add(this.eraser); return actors; }
Source:
public void testResolvingNonNativeNullHandlingOrderIsUnsupported() { KeyValueQuery<String> keyValueQuery = new KeyValueQuery<String>("^pg~]=P"); Sort.Order[] sortOrderArray = new Sort.Order[7]; Sort.Order sortOrderA = Sort.Order.asc("^pg~]=P"); sortOrderArray[0] = sortOrderA; Sort.Order sortOrderB = sortOrderA.nullsLast(); sortOrderArray[1] = sortOrderB; Sort sort = Sort.by(sortOrderArray); keyValueQuery.setSort(sort); HazelcastSortAccessor hazelcastSortAccessor = new HazelcastSortAccessor(); hazelcastSortAccessor.resolve(keyValueQuery); fail("Should have thrown UnsupportedOperationException"); }

Target:
public void testResolvingNonNativeNullHandlingOrderIsUnsupported() { KeyValueQuery<String> keyValueQuery = new KeyValueQuery<>("^pg~]=P"); Sort.Order sortOrder1 = Sort.Order.asc("^pg~]=P"); Sort.Order sortOrder2 = sortOrder1.nullsLast(); keyValueQuery.setSort(Sort.by(sortOrder1, sortOrder2)); HazelcastSortAccessor hazelcastSortAccessor = new HazelcastSortAccessor(); hazelcastSortAccessor.resolve(keyValueQuery); }
Source:
public DataSize getUserMemoryReservation() { return succinctBytes(0); }

Target:
public DataSize getUserMemoryReservation() { return new DataSize(0, BYTE); }
Source:
public boolean removeAll(Collection<?> c) { for (XWikiAttachment x : (Collection<? extends XWikiAttachment>) c) { if (this.list.contains(x)) remove(x); } return true; }

Target:
public boolean removeAll(Collection<?> c) { boolean changed = false; for (XWikiAttachment x : (Collection<? extends XWikiAttachment>) c) { if (map.get(x.getFilename()) == x) { map.remove(x.getFilename()); changed = true; } } if (changed) { updatedMap(); } return changed; }
Source:
protected List<T> fromString(String s) { final String escapedString = escaper.escape(s); final String[] elements = escapedString.split(elementDelimiterPattern); final List<T> result = newArrayList(); for (String element : elements) { checkElement(element); final T convertedValue = Stringifiers.convert(unquote(element), listGenericClass); result.add(convertedValue); } return result; }

Target:
protected List<T> fromString(String s) { final String escapedString = escaper.escape(s); final List<String> items = newArrayList(splitter.split(escapedString)); final Converter<String, String> quoteConverter = ItemQuoter.converter(); final List<T> result = newArrayList(); for (String item : items) { final T convertedItem = quoteConverter.reverse() .andThen(elementStringifier.reverse()) .convert(item); result.add(convertedItem); } return result; }
Source:
public void visit( TypeDefinitionLink n ) { TypeDefinition linkedType = null; if( n.linkedTypeName().equals( TypeDefinitionUndefined.UNDEFINED_KEYWORD ) ) { linkedType = TypeDefinitionUndefined.getInstance(); } else { Optional< SymbolInfo > targetSymbolInfo = getSymbol( n.context(), n.linkedTypeName() ); if( !targetSymbolInfo.isPresent() ) { error( buildSymbolNotFoundError( n, n.id() ) ); return; } if( !(targetSymbolInfo.get().node() instanceof TypeDefinition) ) { error( buildSymbolTypeMismatchError( n, n.id(), "TypeDefinition", targetSymbolInfo.get().node().getClass().getSimpleName() ) ); return; } linkedType = (TypeDefinition) targetSymbolInfo.get().node(); while( linkedType instanceof TypeDefinitionLink ) { linkedType = ((TypeDefinitionLink) linkedType).linkedType(); } if( linkedType.equals( n ) ) { error( buildSymbolNotFoundError( n, n.id() ) ); return; } } n.setLinkedType( linkedType ); }

Target:
public void visit( TypeDefinitionLink n ) { TypeDefinition linkedType = null; if( n.linkedTypeName().equals( TypeDefinitionUndefined.UNDEFINED_KEYWORD ) ) { linkedType = TypeDefinitionUndefined.getInstance(); } else { Optional< SymbolInfo > targetSymbolInfo = getSymbol( n.context(), n.linkedTypeName() ); if( !targetSymbolInfo.isPresent() ) { error( buildSymbolNotFoundError( n, n.id() ) ); return; } if( !(targetSymbolInfo.get().node() instanceof TypeDefinition) ) { error( buildSymbolTypeMismatchError( n, n.id(), "TypeDefinition", targetSymbolInfo.get().node().getClass().getSimpleName() ) ); return; } linkedType = (TypeDefinition) targetSymbolInfo.get().node(); int linkCounter = 0; while( linkedType instanceof TypeDefinitionLink ) { if( linkCounter == 100 ) { error( buildTypeLinkOutOfBoundError( n ) ); return; } linkedType = ((TypeDefinitionLink) linkedType).linkedType(); linkCounter++; } if( linkedType.equals( n ) ) { error( buildSymbolNotFoundError( n, n.id() ) ); return; } } n.setLinkedType( linkedType ); }
Source:
public static boolean isSkipCommitNetworkChangesSupported(VDS vds) { return Version.v4_3.lessOrEquals(vds.getSupportedClusterVersionsSet()) && Version.v4_4.lessOrEquals(Version.ALL); }

Target:
public static boolean isSkipCommitNetworkChangesSupported(VDS vds) { return vds != null && Version.v4_3.lessOrEquals(vds.getSupportedClusterVersionsSet()); }
Source:
protected boolean canDoAction() { if (!isVmExist() || !acquireLockInternal()) { return false; } VM vm = getVm(); if (vm != null) { if (!canRunActionOnNonManagedVm()) { return false; } updateDisksFromDb(); if (!isDiskCanBeAddedToVm(getParameters().getDiskInfo(), vm) || !isDiskPassPciAndIdeLimit(getParameters().getDiskInfo())) { return false; } } else { if (getParameters().getPlugDiskToVm()) { return failCanDoAction(VdcBllMessages.CANNOT_ADD_FLOATING_DISK_WITH_PLUG_VM_SET); } } if (DiskStorageType.IMAGE == getParameters().getDiskInfo().getDiskStorageType()) { return checkIfImageDiskCanBeAdded(vm); } if (DiskStorageType.LUN == getParameters().getDiskInfo().getDiskStorageType()) { return checkIfLunDiskCanBeAdded(); } return true; }

Target:
protected boolean canDoAction() { if (!isVmExist() || !acquireLockInternal()) { return false; } VM vm = getVm(); if (vm != null) { if (!canRunActionOnNonManagedVm()) { return false; } updateDisksFromDb(); if (!isDiskCanBeAddedToVm(getParameters().getDiskInfo(), vm) || !isDiskPassPciAndIdeLimit(getParameters().getDiskInfo())) { return false; } } else if (Boolean.TRUE.equals(getParameters().getPlugDiskToVm())) { return failCanDoAction(VdcBllMessages.CANNOT_ADD_FLOATING_DISK_WITH_PLUG_VM_SET); } if (DiskStorageType.IMAGE == getParameters().getDiskInfo().getDiskStorageType()) { return checkIfImageDiskCanBeAdded(vm); } if (DiskStorageType.LUN == getParameters().getDiskInfo().getDiskStorageType()) { return checkIfLunDiskCanBeAdded(); } return true; }
Source:
public void onError(Throwable e) { Log.e(TAG, e.getMessage()); loginError.setValue(e); if (url.get() != null && url.get().contains("https")) testConnection(true, URLHelper.INSTANCE.getUrlWithMethod(url.get(), "http")); else if (url.get().contains("http")) url.set(url.get().replaceAll("http://", "")); }

Target:
public void onError(Throwable e) { Log.e(TAG, e.getMessage()); loginError.setValue(e); if (testedUrl != null && testedUrl.contains("https")) testConnection(true, URLHelper.INSTANCE.getUrlWithMethod(url.get(), "http")); }
Source:
public void updateConnection(@QueryParam("token") String authToken, @PathParam("connectionID") String connectionID, APIConnection connection) throws GuacamoleException { UserContext userContext = authenticationService.getUserContext(authToken); if (connection == null) throw new GuacamoleClientException("Connection JSON must be submitted when updating connections."); ConnectionGroup rootGroup = userContext.getRootConnectionGroup(); Directory<String, Connection> connectionDirectory = rootGroup.getConnectionDirectory(); Connection existingConnection = connectionDirectory.get(connectionID); if (existingConnection == null) throw new GuacamoleResourceNotFoundException("No such connection: \"" + connectionID + "\""); Connection wrappedConnection = new APIConnectionWrapper(connection); existingConnection.setConfiguration(wrappedConnection.getConfiguration()); existingConnection.setName(wrappedConnection.getName()); connectionDirectory.update(existingConnection); }

Target:
public void updateConnection(@QueryParam("token") String authToken, @PathParam("connectionID") String connectionID, APIConnection connection) throws GuacamoleException { UserContext userContext = authenticationService.getUserContext(authToken); if (connection == null) throw new GuacamoleClientException("Connection JSON must be submitted when updating connections."); ConnectionGroup rootGroup = userContext.getRootConnectionGroup(); Directory<String, Connection> connectionDirectory = rootGroup.getConnectionDirectory(); Connection existingConnection = connectionDirectory.get(connectionID); if (existingConnection == null) throw new GuacamoleResourceNotFoundException("No such connection: \"" + connectionID + "\""); GuacamoleConfiguration config = new GuacamoleConfiguration(); config.setProtocol(connection.getProtocol()); config.setParameters(connection.getParameters()); existingConnection.setConfiguration(config); existingConnection.setName(connection.getName()); connectionDirectory.update(existingConnection); }
Source:
public Checkpoint(String checkpoint) { checkNotNull(checkpoint, "checkpoint may not be null"); logger.info("Checkpoint: '" + checkpoint + "'"); Object[] objs; try { if (checkpoint.indexOf(';') < 0) { objs = SHORT_FORMAT.parse(checkpoint); } else { objs = FULL_FORMAT.parse(checkpoint); } } catch (ParseException e) { throw new IllegalArgumentException( "Invalid Checkpoint: " + checkpoint, e); } switch (objs.length) { case 3: timestamp = (Date) objs[1]; guid = new Id((String) objs[2]); case 1: type = (String) objs[0]; break; default: throw new IllegalArgumentException( "Invalid Checkpoint: " + checkpoint); } }

Target:
public Checkpoint(String checkpoint) { checkNotNull(checkpoint, "checkpoint may not be null"); logger.info("Checkpoint: '" + checkpoint + "'"); try { if (checkpoint.indexOf(';') < 0) { Object[] objs = SHORT_FORMAT.parse(checkpoint); type = (String) objs[0]; timestamp = null; guid = null; } else { Object[] objs = FULL_FORMAT.parse(checkpoint); type = (String) objs[0]; timestamp = (String) objs[1]; guid = (String) objs[2]; } } catch (ParseException e) { throw new IllegalArgumentException( "Invalid Checkpoint: " + checkpoint, e); } }
Source:
private LeaderLatch createNewLeaderLatch() { final LeaderLatch newLeaderLatch = new LeaderLatch( curator, latchPath, self.getHostAndPortToUse() ); newLeaderLatch.addListener( new LeaderLatchListener() { @Override public void isLeader() { try { if (leader) { log.warn("I'm being asked to become leader. But I am already the leader. Ignored event."); return; } leader = true; term++; listener.becomeLeader(); } catch (Exception ex) { log.makeAlert(ex, "listener becomeLeader() failed. Unable to become leader").emit(); final LeaderLatch oldLatch = createNewLeaderLatch(); CloseQuietly.close(oldLatch); leader = false; try { Thread.sleep(1000); leaderLatch.get().start(); } catch (Exception e) { log.makeAlert(e, "I am a zombie").emit(); } } } @Override public void notLeader() { try { if (!leader) { log.warn("I'm being asked to stop being leader. But I am not the leader. Ignored event."); return; } leader = false; listener.stopBeingLeader(); } catch (Exception ex) { log.makeAlert(ex, "listener.stopBeingLeader() failed. Unable to stopBeingLeader").emit(); } } }, Execs.singleThreaded(StringUtils.format("LeaderSelector[%s]", latchPath)) ); return leaderLatch.getAndSet(newLeaderLatch); }

Target:
private LeaderLatch createNewLeaderLatch() { final LeaderLatch newLeaderLatch = new LeaderLatch( curator, latchPath, self.getHostAndPortToUse() ); newLeaderLatch.addListener( new LeaderLatchListener() { @Override public void isLeader() { try { if (leader) { log.warn("I'm being asked to become leader. But I am already the leader. Ignored event."); return; } leader = true; term++; listener.becomeLeader(); } catch (Exception ex) { log.makeAlert(ex, "listener becomeLeader() failed. Unable to become leader").emit(); final LeaderLatch oldLatch = createNewLeaderLatch(); CloseQuietly.close(oldLatch); leader = false; try { Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 5000)); leaderLatch.get().start(); } catch (Exception e) { log.makeAlert(e, "I am a zombie").emit(); } } } @Override public void notLeader() { try { if (!leader) { log.warn("I'm being asked to stop being leader. But I am not the leader. Ignored event."); return; } leader = false; listener.stopBeingLeader(); } catch (Exception ex) { log.makeAlert(ex, "listener.stopBeingLeader() failed. Unable to stopBeingLeader").emit(); } } }, listenerExecutor ); return leaderLatch.getAndSet(newLeaderLatch); }
Source:
public String getZoneGroupName(int zoneID, short groupID) { if (zoneGroupIdNameMap == null) { return null; } if (zoneGroupIdNameMap.get(zoneID) != null) { if (zoneGroupIdNameMap.get(zoneID).groupIdNames != null) { if (zoneGroupIdNameMap.get(zoneID).groupIdNames.get(groupID) != null) { return zoneGroupIdNameMap.get(zoneID).groupIdNames.get(groupID); } } } return null; }

Target:
public String getZoneGroupName(int zoneID, short groupID) { if (zoneGroupIdNameMap == null) { return null; } final ZoneGroupsNameAndIDMap tmp = zoneGroupIdNameMap.get(zoneID); return tmp != null ? tmp.getGroupName(groupID) : null; }
Source:
public RemoveMembersFromConsumerGroupOptions(Collection<MemberToRemove> members) { this.members = new HashSet<>(members); }

Target:
public RemoveMembersFromConsumerGroupOptions(Collection<MemberToRemove> members) { if (members.isEmpty()) { throw new IllegalArgumentException("Invalid empty members has been provided"); } this.members = new HashSet<>(members); }
Source:
public static byte[] getChecksum(String algorithm, File file) throws NoSuchAlgorithmException, IOException { HashFunction hashFunction = null; switch (algorithm) { case MD5: hashFunction = Hashing.md5(); break; case SHA1: hashFunction = Hashing.sha1(); break; case SHA256: hashFunction = Hashing.sha256(); break; default: throw new NoSuchAlgorithmException(algorithm); } HashCode hash = Files.asByteSource(file).hash(hashFunction); return hash.asBytes(); }

Target:
public static byte[] getChecksum(String algorithm, File file) throws NoSuchAlgorithmException, IOException { HashFunction hashFunction = null; switch (algorithm.toUpperCase()) { case MD5: hashFunction = Hashing.md5(); break; case SHA1: hashFunction = Hashing.sha1(); break; case SHA256: hashFunction = Hashing.sha256(); break; default: throw new NoSuchAlgorithmException(algorithm); } HashCode hash = Files.asByteSource(file).hash(hashFunction); return hash.asBytes(); }
Source:
private File getRecordFile(String testName) { URL folderUrl = InterceptorManager.class.getClassLoader().getResource("."); File folderFile = new File(folderUrl.getPath() + RECORD_FOLDER); if (!folderFile.exists()) { if (folderFile.mkdir()) { logger.verbose("Created directory: {}", folderFile.getPath()); } } String filePath = folderFile.getPath() + "/" + testName + ".json"; if (Files.notExists(Paths.get(filePath))) { throw logger.logExceptionAsError(new RuntimeException(String.format( "Missing playback file. File path: %s. ", filePath))); } logger.info("==> Playback file path: " + filePath); return new File(filePath); }

Target:
private File getRecordFile(String testName) { URL folderUrl = InterceptorManager.class.getClassLoader().getResource("."); File folderFile = new File(folderUrl.getPath() + RECORD_FOLDER); if (!folderFile.exists()) { if (folderFile.mkdir()) { logger.verbose("Created directory: {}", folderFile.getPath()); } } File playbackFile = new File(folderFile, testName + ".json"); if (!playbackFile.exists()) { throw logger.logExceptionAsError(new RuntimeException(String.format( "Missing playback file. File path: %s. ", playbackFile))); } logger.info("==> Playback file path: " + playbackFile); return playbackFile; }