auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void updateSSH(SSH ssh) throws DAOException { try { PreparedStatement ps = connection.prepareStatement("UPDATE " + "VIPSSHAccounts " + "SET sshUser=?, sshHost=?,transfertType=?, sshDir=?, sshPort=?, auth_failed='0' " + "WHERE email=? AND LFCDir=?"); ps.setString(1, ssh.getUser()); ps.setString(2, ssh.getHost()); ps.setString(3, ssh.getTransfertType()); ps.setString(4, ssh.getDirectory()); ps.setString(5, ssh.getPort()); ps.setString(6, ssh.getEmail()); try { ps.setString(7, DataManagerBusiness.generateLFCDir(ssh.getName(),ssh.getEmail())); } catch (DataManagerException ex) { logger.error(ex); throw new DAOException(ex); } catch (BusinessException ex) { throw new DAOException(ex); } ps.executeUpdate(); ps.close(); } catch (SQLException ex) { logger.error(ex); throw new DAOException(ex); } }

Target:
public void updateSSH(SSH ssh) throws DAOException { try { PreparedStatement ps = connection.prepareStatement("UPDATE " + "VIPSSHAccounts " + "SET sshUser=?, sshHost=?, transfertType=?, sshDir=?, sshPort=?, auth_failed='0', numberSynchronizationFailed=?, deleteFilesFromSource=? " + "WHERE email=? AND LFCDir=?"); ps.setString(1, ssh.getUser()); ps.setString(2, ssh.getHost()); ps.setString(3, ssh.getTransfertType().toString()); ps.setString(4, ssh.getDirectory()); ps.setInt(5, ssh.getPort()); ps.setLong(6, ssh.getNumberSynchronizationFailes()); ps.setBoolean(7, ssh.isDeleteFilesFromSource()); ps.setString(8, ssh.getEmail()); try { ps.setString(9, DataManagerBusiness.generateLFCDir(ssh.getName(), ssh.getEmail())); } catch (DataManagerException ex) { logger.error(ex); throw new DAOException(ex); } catch (BusinessException ex) { throw new DAOException(ex); } ps.executeUpdate(); ps.close(); } catch (SQLException ex) { logger.error(ex); throw new DAOException(ex); } }
Source:
public String getNumericFunctions() throws SQLException { checkClosed(); return "ABS,BITAND,BITNOT,BITOR,BIT_SHIFT_LEFT,BIT_SHIFT_RIGHT,BITXOR,CEILING,COS,COT,CSC,DEGREES,EXP,FLOOR,LN,LOG,LOG10,PI,POWER,RADIANS,ROUND,SEC,SIN,SQRT,TAN, GET_UNIQUE_ID"; }

Target:
public String getNumericFunctions() throws SQLException { checkClosed(); return "ABS,BITAND,BITNOT,BITOR,BIT_SHIFT_LEFT,BIT_SHIFT_RIGHT,BITXOR,CEILING,COS,COT,CSC,DEGREES,EXP,FLOOR,GET_UNIQUE_ID,LN,LOG,LOG10,PI,POWER,RADIANS,ROUND,SEC,SIN,SQRT,TAN"; }
Source:
public Set<OrderGroup> getOrderGroups() { if (orderGroups == null) { orderGroups = new LinkedHashSet<OrderGroup>(); } return orderGroups; }

Target:
public List<OrderGroup> getOrderGroups() { Map<String, OrderGroup> orderGroups = new HashMap<String, OrderGroup>(); for (Order order : orders) { if (order.getOrderGroup() != null) { if (null == orderGroups.get(order.getOrderGroup().getUuid())) { orderGroups.put(order.getOrderGroup().getUuid(), order.getOrderGroup()); } order.getOrderGroup().addOrder(order, null); } } List<OrderGroup> orderGroupList = new ArrayList<OrderGroup>(); orderGroupList.addAll(orderGroups.values()); return orderGroupList; }
Source:
public static CepAction doNothingAction() { List<Object> list = new ArrayList<>(); list.add("dummy"); return new CepAction(CepActionType.DO_NOTHING, null, list); }

Target:
public static CepAction doNothingAction() { final List<Object> list = new ArrayList<>(); list.add("dummy"); return new CepAction(CepActionType.DO_NOTHING, null, list); }
Source:
private Map<IMember, Set<IMember>> getMatchingMembersMapping(final IType initial) throws JavaModelException { final Map<IMember, Set<IMember>> result= new HashMap<>(); final IMember[] members= getCreatedDestinationMembers(); for (int i= 0; i < members.length; i++) { final IMember member= members[i]; if (member instanceof IMethod) { final IMethod method= (IMethod) member; final IMethod found= MemberCheckUtil.findMethod(method, initial.getMethods()); if (found != null) addMatchingMember(result, method, found); } else if (member instanceof IField) { final IField field= (IField) member; final IField found= initial.getField(field.getElementName()); if (found.exists()) { if(field.getTypeSignature().equals(found.getTypeSignature())) { addMatchingMember(result, field, found); } } } else if (member instanceof IType) { final IType type= (IType) member; final IType found= initial.getType(type.getElementName()); if (found.exists()) addMatchingMember(result, type, found); } else Assert.isTrue(false); } return result; }

Target:
private Map<IMember, Set<IMember>> getMatchingMembersMapping(final IType initial) throws JavaModelException { final Map<IMember, Set<IMember>> result= new HashMap<>(); final IMember[] members= getCreatedDestinationMembers(); for (int i= 0; i < members.length; i++) { final IMember member= members[i]; if (member instanceof IMethod) { final IMethod method= (IMethod) member; final IMethod found= MemberCheckUtil.findMethod(method, initial.getMethods()); if (found != null) addMatchingMember(result, method, found); } else if (member instanceof IField) { final IField field= (IField) member; final IField found= initial.getField(field.getElementName()); if (found.exists() && field.getTypeSignature().equals(found.getTypeSignature())) { addMatchingMember(result, field, found); } } else if (member instanceof IType) { final IType type= (IType) member; final IType found= initial.getType(type.getElementName()); if (found.exists()) addMatchingMember(result, type, found); } else Assert.isTrue(false); } return result; }
Source:
public String[] getStepDescriptions() { List<String> result= new ArrayList<>(); if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_IMPORTS)) result.add(MultiFixMessages.UnusedCodeMultiFix_RemoveUnusedImport_description); if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS) && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_METHODS)) result.add(MultiFixMessages.UnusedCodeMultiFix_RemoveUnusedMethod_description); if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS) && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_CONSTRUCTORS)) result.add(MultiFixMessages.UnusedCodeMultiFix_RemoveUnusedConstructor_description); if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS) && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_TYPES)) result.add(MultiFixMessages.UnusedCodeMultiFix_RemoveUnusedType_description); if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS) && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_FELDS)) result.add(MultiFixMessages.UnusedCodeMultiFix_RemoveUnusedField_description); if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_LOCAL_VARIABLES)) result.add(MultiFixMessages.UnusedCodeMultiFix_RemoveUnusedVariable_description); return result.toArray(new String[result.size()]); }

Target:
public String[] getStepDescriptions() { List<String> result= new ArrayList<>(); if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_IMPORTS)) result.add(MultiFixMessages.UnusedCodeMultiFix_RemoveUnusedImport_description); if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS) && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_METHODS)) result.add(MultiFixMessages.UnusedCodeMultiFix_RemoveUnusedMethod_description); if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS) && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_CONSTRUCTORS)) result.add(MultiFixMessages.UnusedCodeMultiFix_RemoveUnusedConstructor_description); if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS) && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_TYPES)) result.add(MultiFixMessages.UnusedCodeMultiFix_RemoveUnusedType_description); if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS) && isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_FELDS)) result.add(MultiFixMessages.UnusedCodeMultiFix_RemoveUnusedField_description); if (isEnabled(CleanUpConstants.REMOVE_UNUSED_CODE_LOCAL_VARIABLES)) result.add(MultiFixMessages.UnusedCodeMultiFix_RemoveUnusedVariable_description); return result.toArray(new String[0]); }
Source:
SystemProperties(final Map<String, Object> map) { super(map); this.offset = getSystemProperty(OFFSET_ANNOTATION_NAME.getValue()); this.partitionKey = getSystemProperty(PARTITION_KEY_ANNOTATION_NAME.getValue()); final Date enqueuedTimeValue = getSystemProperty(ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue()); this.enqueuedTime = enqueuedTimeValue != null ? enqueuedTimeValue.toInstant() : null; final Long sequenceNumber = getSystemProperty(SEQUENCE_NUMBER_ANNOTATION_NAME.getValue()); if (sequenceNumber == null) { throw new IllegalStateException(String.format(Locale.US, "sequenceNumber: %s should always be in map.", SEQUENCE_NUMBER_ANNOTATION_NAME.getValue())); } this.sequenceNumber = sequenceNumber; remove(OFFSET_ANNOTATION_NAME.getValue()); remove(PARTITION_KEY_ANNOTATION_NAME.getValue()); remove(ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue()); remove(SEQUENCE_NUMBER_ANNOTATION_NAME.getValue()); }

Target:
SystemProperties(final Map<String, Object> map) { super(map); this.partitionKey = removeSystemProperty(PARTITION_KEY_ANNOTATION_NAME.getValue()); final String offset = removeSystemProperty(OFFSET_ANNOTATION_NAME.getValue()); if (offset == null) { throw new IllegalStateException(String.format(Locale.US, "offset: %s should always be in map.", OFFSET_ANNOTATION_NAME.getValue())); } this.offset = Long.valueOf(offset); final Date enqueuedTimeValue = removeSystemProperty(ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue()); if (enqueuedTimeValue == null) { throw new IllegalStateException(String.format(Locale.US, "enqueuedTime: %s should always be in map.", ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue())); } this.enqueuedTime = enqueuedTimeValue.toInstant(); final Long sequenceNumber = removeSystemProperty(SEQUENCE_NUMBER_ANNOTATION_NAME.getValue()); if (sequenceNumber == null) { throw new IllegalStateException(String.format(Locale.US, "sequenceNumber: %s should always be in map.", SEQUENCE_NUMBER_ANNOTATION_NAME.getValue())); } this.sequenceNumber = sequenceNumber; }
Source:
public void testContigNotFoundInRef() throws IOException { final File CRAMFile = new File("testdata/htsjdk/samtools/cram/test.cram"); final File refFile = new File("testdata/htsjdk/samtools/cram/test.fa"); final ReferenceSource refSource = new ReferenceSource(refFile); final CRAMIterator iterator = new CRAMIterator(new FileInputStream(CRAMFile), refSource); try { while (iterator.hasNext()) { iterator.next(); } } catch (RuntimeEOFException e) { Assert.assertEquals(e.getCause().getClass(), CRAMException.class); } }

Target:
public void testContigNotFoundInRef() throws IOException { boolean sawException = false; final File CRAMFile = new File("testdata/htsjdk/samtools/cram/CRAMException/testContigNotInRef.cram"); final File refFile = new File("testdata/htsjdk/samtools/cram/CRAMException/testContigNotInRef.fa"); final ReferenceSource refSource = new ReferenceSource(refFile); final CRAMIterator iterator = new CRAMIterator(new FileInputStream(CRAMFile), refSource); try { while (iterator.hasNext()) { iterator.next(); } } catch (RuntimeEOFException e) { Assert.assertEquals(e.getCause().getClass(), CRAMException.class); sawException = true; } if (!sawException) {Assert.fail("Expected an exception to occur, none found");} }
Source:
@NotNull @Override public Iterator<R> iterator(Map<String, Object> filter) { if (filter == null) filter = Collections.emptyMap(); Iterator<D> dataIter = dataSupplier.apply(filter).iterator(); return new Iterator<R>() { @Override public boolean hasNext() { return dataIter.hasNext(); } @Override public R next() { return rowFunc.apply(dataIter.next()); } }; }

Target:
@NotNull @Override public Iterator<R> iterator(Map<String, Object> filter) { if (filter == null) filter = Collections.emptyMap(); return F.iterator(dataSupplier.apply(filter), rowFunc::apply, true); }
Source:
public static <T> Flowable<T> fromStream(@NonNull Stream<T> stream) { ObjectHelper.requireNonNull(stream, "stream is null"); return RxJavaPlugins.onAssembly(new FlowableFromStream<>(stream)); }

Target:
public static <T> Flowable<@NonNull T> fromStream(@NonNull Stream<T> stream) { ObjectHelper.requireNonNull(stream, "stream is null"); return RxJavaPlugins.onAssembly(new FlowableFromStream<>(stream)); }
Source:
private void assertInvalidGeometryCollectionUnion(String validWkt) { assertInvalidFunction(format("ST_ASText(ST_Union(ST_GeometryFromText('%s'), ST_GeometryFromText('%s')))", validWkt, "GEOMETRYCOLLECTION(POINT(2 3))"), "ST_Union only applies to POINT or MULTI_POINT or LINE_STRING or MULTI_LINE_STRING or POLYGON or MULTI_POLYGON. Input type is: GEOMETRY_COLLECTION"); assertInvalidFunction(format("ST_ASText(ST_Union(ST_GeometryFromText('%s'), ST_GeometryFromText('%s')))", "GEOMETRYCOLLECTION(POINT(2 3))", validWkt), "ST_Union only applies to POINT or MULTI_POINT or LINE_STRING or MULTI_LINE_STRING or POLYGON or MULTI_POLYGON. Input type is: GEOMETRY_COLLECTION"); }

Target:
private void assertInvalidGeometryCollectionUnion(String validWkt) { assertInvalidFunction(format("ST_Union(ST_GeometryFromText('%s'), ST_GeometryFromText('GEOMETRYCOLLECTION (POINT(2 3))'))", validWkt), "ST_Union only applies to POINT or MULTI_POINT or LINE_STRING or MULTI_LINE_STRING or POLYGON or MULTI_POLYGON. Input type is: GEOMETRY_COLLECTION"); assertInvalidFunction(format("ST_Union(ST_GeometryFromText('GEOMETRYCOLLECTION (POINT(2 3))'), ST_GeometryFromText('%s'))", validWkt), "ST_Union only applies to POINT or MULTI_POINT or LINE_STRING or MULTI_LINE_STRING or POLYGON or MULTI_POLYGON. Input type is: GEOMETRY_COLLECTION"); }
Source:
private void scanQrCode() { Intent scanQrCode = new Intent(getActivity(), ImportKeysProxyActivity.class); scanQrCode.setAction(ImportKeysProxyActivity.ACTION_SCAN_IMPORT); scanQrCode.putExtra(ImportKeysProxyActivity.EXTRA_IS_INTERNAL, true); startActivityForResult(scanQrCode, REQUEST_ACTION); }

Target:
private void scanQrCode() { Intent scanQrCode = new Intent(getActivity(), ImportKeysProxyActivity.class); scanQrCode.setAction(ImportKeysProxyActivity.ACTION_SCAN_IMPORT); startActivityForResult(scanQrCode, REQUEST_ACTION); }
Source:
private void setValueForTextInput(Driver driver, WebElement element, String text) { if (text == null || text.isEmpty()) { element.clear(); } else if (driver.config().fastSetValue()) { String error = setValueByJs(driver, element, text); if (error != null) throw new InvalidStateException(driver, error); else { events.fireEvent(driver, element, "keydown", "keypress", "input", "keyup"); } } else { element.clear(); element.sendKeys(text); } }

Target:
private void setValueForTextInput(Driver driver, WebElement element, String text) { if (text == null || text.isEmpty()) { element.clear(); } else if (driver.config().fastSetValue()) { String error = setValueByJs(driver, element, text); if (error != null) throw new InvalidStateException(driver, error); else { events.fireEvent(driver, element, "keydown", "keypress", "input", "keyup", "change"); } } else { element.clear(); element.sendKeys(text); } }
Source:
public ElasticsearchColumnMetadata(String name, Type type, String jsonPath, String jsonType, boolean isList, int ordinalPosition) { super(name, type); this.jsonPath = jsonPath; this.jsonType = jsonType; this.isList = isList; this.ordinalPosition = ordinalPosition; }

Target:
public ElasticsearchColumnMetadata(String name, Type type, String jsonPath, String jsonType, boolean isList, int ordinalPosition) { super(name, type); this.jsonPath = requireNonNull(jsonPath, "jsonPath is null"); this.jsonType = requireNonNull(jsonType, "jsonType is null"); this.isList = isList; this.ordinalPosition = ordinalPosition; }
Source:
public static DigestSource pbkDf2() { return (value, salt) -> { if (salt == null || salt.length == 0) { throw new IllegalArgumentException("Cannot use pbkDf2 with empty or null salt."); } try { KeySpec spec = new PBEKeySpec(value.toCharArray(), salt, 65536, 256); SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); final byte[] bytes = factory.generateSecret(spec).getEncoded(); return EncodingUtils.BASE64_ENCODER.apply(bytes); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { throw new IllegalStateException("Unable digest value.", e); } }; }

Target:
public static DigestSource pbkDf2() { return (value, salt) -> { if (salt == null || salt.length == 0) { throw new IllegalArgumentException("Cannot use pbkDf2 with empty or null salt."); } try { KeySpec spec = new PBEKeySpec(value.toCharArray(), salt, 65536, 256); SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); final byte[] bytes = factory.generateSecret(spec).getEncoded(); return EncodingUtils.BASE64_ENCODER.apply(bytes); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { throw new IllegalStateException("Unable to digest value.", e); } }; }
Source:
private static String canonicalize(String s) { return s.toLowerCase(Locale.US); }

Target:
private static String canonicalize(String s) { return s.toLowerCase(Locale.ROOT); }
Source:
protected void setActionMessageParameters() { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__HOT_PLUG); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__VM_DISK); if (getDiskAlias() != null) { addCanDoActionMessage(String.format("$%1$s %2$s", "diskAliases", getDiskAlias())); } }

Target:
protected void setActionMessageParameters() { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__HOT_PLUG); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__VM_DISK); if (getDisk() != null) { addCanDoActionMessage(String.format("$%1$s %2$s", "diskAliases", getDiskAlias())); } }
Source:
public StorageDomain mapRow(final ResultSet rs, final int rowNum) throws SQLException { final StorageDomain entity = new StorageDomain(); entity.setId(getGuidDefaultEmpty(rs, "id")); entity.setStorage(rs.getString("storage")); entity.setStorageName(rs.getString("storage_name")); entity.setDescription(rs.getString("storage_description")); entity.setStoragePoolId(getGuid(rs, "storage_pool_id")); entity.setComment(rs.getString("storage_comment")); entity.setStorageType(StorageType.forValue(rs.getInt("storage_type"))); entity.setStoragePoolName(rs.getString("storage_pool_name")); entity.setStorageDomainType(StorageDomainType.forValue(rs.getInt("storage_domain_type"))); entity.setStorageFormat(StorageFormatType.forValue(rs.getString("storage_domain_format_type"))); entity.setAvailableDiskSize((Integer) rs.getObject("available_disk_size")); entity.setUsedDiskSize((Integer) rs.getObject("used_disk_size")); entity.setCommittedDiskSize(rs.getInt("actual_images_size")); entity.setCommittedDiskSize(rs.getInt("commited_disk_size")); entity.setStatus(StorageDomainStatus.forValue(rs.getInt("status"))); entity.setStorageDomainSharedStatus( StorageDomainSharedStatus.forValue(rs.getInt("storage_domain_shared_status"))); entity.setAutoRecoverable(rs.getBoolean("recoverable")); entity.setLastTimeUsedAsMaster(rs.getLong("last_time_used_as_master")); return entity; }

Target:
public StorageDomain mapRow(final ResultSet rs, final int rowNum) throws SQLException { final StorageDomain entity = new StorageDomain(); entity.setId(getGuidDefaultEmpty(rs, "id")); entity.setStorage(rs.getString("storage")); entity.setStorageName(rs.getString("storage_name")); entity.setDescription(rs.getString("storage_description")); entity.setStoragePoolId(getGuid(rs, "storage_pool_id")); entity.setComment(rs.getString("storage_comment")); entity.setStorageType(StorageType.forValue(rs.getInt("storage_type"))); entity.setStoragePoolName(rs.getString("storage_pool_name")); entity.setStorageDomainType(StorageDomainType.forValue(rs.getInt("storage_domain_type"))); entity.setStorageFormat(StorageFormatType.forValue(rs.getString("storage_domain_format_type"))); entity.setAvailableDiskSize((Integer) rs.getObject("available_disk_size")); entity.setUsedDiskSize((Integer) rs.getObject("used_disk_size")); entity.setActualImagesSize(rs.getInt("actual_images_size")); entity.setCommittedDiskSize(rs.getInt("commited_disk_size")); entity.setStatus(StorageDomainStatus.forValue(rs.getInt("status"))); entity.setStorageDomainSharedStatus( StorageDomainSharedStatus.forValue(rs.getInt("storage_domain_shared_status"))); entity.setAutoRecoverable(rs.getBoolean("recoverable")); entity.setLastTimeUsedAsMaster(rs.getLong("last_time_used_as_master")); return entity; }
Source:
public static Enumeration listRoots() { return new Vector().elements(); }

Target:
public static Enumeration listRoots() { System.out.println("FileSystemRegistry::listRoots() not implemented."); return new Vector().elements(); }
Source:
public static void main(String[] args) { SearchIndexAsyncClient searchClient = new SearchIndexClientBuilder() .endpoint(ENDPOINT) .credential(new SearchApiKeyCredential(API_KEY)) .indexName(INDEX_NAME) .buildAsyncClient(); ObjectMapper objectMapper = new ObjectMapper(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); df.setTimeZone(TimeZone.getDefault()); objectMapper.setDateFormat(df); objectMapper.registerModule(new JavaTimeModule()); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); SearchPagedFlux results = searchClient.search("searchText"); results .subscribe(item -> { Document document = new Document(item.getDocument()); Hotel hotel = objectMapper.convertValue(document, Hotel.class); System.out.println("Hotel " + hotel.getHotelId()); }); results.blockLast(); }

Target:
public static void main(String[] args) { SearchIndexAsyncClient searchClient = new SearchIndexClientBuilder() .endpoint(ENDPOINT) .credential(new SearchApiKeyCredential(API_KEY)) .indexName(INDEX_NAME) .buildAsyncClient(); ObjectMapper objectMapper = new ObjectMapper(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); df.setTimeZone(TimeZone.getDefault()); objectMapper.setDateFormat(df); objectMapper.registerModule(new JavaTimeModule()); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); SearchPagedFlux results = searchClient.search("searchText"); results .subscribe(item -> { SearchDocument searchDocument = item.getDocument(); Hotel hotel = objectMapper.convertValue(searchDocument, Hotel.class); System.out.println("Hotel " + hotel.getHotelId()); }); results.blockLast(); }
Source:
public void loadTrace(ITmfTrace trace) { cancelUpdate(); clearStyles(); super.loadTrace(trace); initializeDataProvider(); }

Target:
public void loadTrace(ITmfTrace trace) { clearStyles(); super.loadTrace(trace); initializeDataProvider(); }
Source:
public static Correlation copyFrom(ICorrelation source) { if (source == null) { return null; } Correlation correlation = new Correlation(); correlation.setState(source.getState()); correlation.setPath(source.getPath()); correlation.getCueiCollection().addAll(MutableCollections.copyListFromNullable(source.getCueiCollection())); correlation.setCmin(source.getCmin()); correlation.setCmax(source.getCmax()); correlation.setCtime(source.getCtime()); return correlation; }

Target:
public static Correlation copyFrom(ICorrelation source) { if (source == null) { return null; } Correlation correlation = new Correlation(); correlation.setState(source.getState()); correlation.setPath(source.getPath()); correlation.getCueiCollection().addAll(source.getCueiCollection()); correlation.setCmin(source.getCmin()); correlation.setCmax(source.getCmax()); correlation.setCtime(source.getCtime()); return correlation; }
Source:
public void reportMeterWithDisabledAttributes() throws Exception { Set<MetricAttribute> disabledMetricAttributes = EnumSet.of(MetricAttribute.M15_RATE, MetricAttribute.M5_RATE, MetricAttribute.COUNT); final ConsoleReporter customReporter = ConsoleReporter.forRegistry(registry) .outputTo(output) .formattedFor(Locale.US) .withClock(clock) .formattedFor(TimeZone.getTimeZone("PST")) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .filter(MetricFilter.ALL) .disabledMetricAttributes(disabledMetricAttributes) .build(); final Meter meter = mock(Meter.class); when(meter.getCount()).thenReturn(1L); when(meter.getMeanRate()).thenReturn(2.0); when(meter.getOneMinuteRate()).thenReturn(3.0); when(meter.getFiveMinuteRate()).thenReturn(4.0); when(meter.getFifteenMinuteRate()).thenReturn(5.0); customReporter.report(this.<Gauge>map(), this.<Counter>map(), this.<Histogram>map(), map("test.meter", meter), this.<Timer>map()); assertThat(consoleOutput()) .isEqualTo(lines( "3/17/13 6:04:36 PM =============================================================", "", "-- Meters ----------------------------------------------------------------------", "test.meter", " mean rate = 2.00 events/second", " 1-minute rate = 3.00 events/second", "", "" )); }

Target:
public void reportMeterWithDisabledAttributes() throws Exception { Set<MetricAttribute> disabledMetricAttributes = EnumSet.of(MetricAttribute.M15_RATE, MetricAttribute.M5_RATE, MetricAttribute.COUNT); final ConsoleReporter customReporter = ConsoleReporter.forRegistry(registry) .outputTo(output) .formattedFor(locale) .withClock(clock) .formattedFor(timeZone) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .filter(MetricFilter.ALL) .disabledMetricAttributes(disabledMetricAttributes) .build(); final Meter meter = mock(Meter.class); when(meter.getCount()).thenReturn(1L); when(meter.getMeanRate()).thenReturn(2.0); when(meter.getOneMinuteRate()).thenReturn(3.0); when(meter.getFiveMinuteRate()).thenReturn(4.0); when(meter.getFifteenMinuteRate()).thenReturn(5.0); customReporter.report(this.<Gauge>map(), this.<Counter>map(), this.<Histogram>map(), map("test.meter", meter), this.<Timer>map()); assertThat(consoleOutput()) .isEqualTo(lines( "3/17/13 6:04:36 PM =============================================================", "", "-- Meters ----------------------------------------------------------------------", "test.meter", " mean rate = 2.00 events/second", " 1-minute rate = 3.00 events/second", "", "" )); }
Source:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.account_setup_basics); mEmailView = (EditText)findViewById(R.id.account_email); mPasswordView = (EditText)findViewById(R.id.account_password); mNextButton = (Button)findViewById(R.id.next); mManualSetupButton = (Button)findViewById(R.id.manual_setup); mShowPassword = (CheckBox) findViewById(R.id.show_password); mShowPassword.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { mPasswordView.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD); } else { mPasswordView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); } } }); mNextButton.setOnClickListener(this); mManualSetupButton.setOnClickListener(this); mEmailView.addTextChangedListener(this); mPasswordView.addTextChangedListener(this); }

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.account_setup_basics); mEmailView = (EditText) findViewById(R.id.account_email); mPasswordView = (EditText) findViewById(R.id.account_password); mNextButton = (Button) findViewById(R.id.next); mManualSetupButton = (Button) findViewById(R.id.manual_setup); CheckBox showPassword = (CheckBox) findViewById(R.id.show_password); showPassword.setOnCheckedChangeListener (new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { mPasswordView .setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD); } else { mPasswordView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); } } }); mNextButton.setOnClickListener(this); mManualSetupButton.setOnClickListener(this); mEmailView.addTextChangedListener(this); mPasswordView.addTextChangedListener(this); }
Source:
public void createPartControl(Composite parent) { GridLayout topLayout = new GridLayout(); GridData data = new GridData(); topLayout.numColumns = 1; topLayout.verticalSpacing = 10; parent.setLayout(topLayout); parent.setLayoutData(data); parent.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_WHITE)); fText = new Text(parent,SWT.READ_ONLY|SWT.WRAP); data = new GridData(GridData.FILL_HORIZONTAL); data.grabExcessHorizontalSpace = true; fText.setLayoutData(data); fText.setForeground(new Color(fText.getDisplay(), 0, 0, 0)); fText.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_WHITE)); if (getEditorInput() != null) { setInput(getEditorInput()); } createButtons(parent); Dialog.applyDialogFont(parent); PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, IDebugHelpContextIds.NO_SOURCE_EDITOR); PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, ICDebugHelpContextIds.SOURCE_NOT_FOUND); }

Target:
public void createPartControl(Composite parent) { GridLayout topLayout = new GridLayout(); GridData data = new GridData(); topLayout.numColumns = 1; topLayout.verticalSpacing = 10; parent.setLayout(topLayout); parent.setLayoutData(data); parent.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_WHITE)); fText = new Text(parent, SWT.READ_ONLY | SWT.WRAP); data = new GridData(GridData.FILL_HORIZONTAL); data.grabExcessHorizontalSpace = true; fText.setLayoutData(data); fText.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_BLACK)); fText.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_WHITE)); if (getEditorInput() != null) { setInput(getEditorInput()); } createButtons(parent); Dialog.applyDialogFont(parent); PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, ICDebugHelpContextIds.SOURCE_NOT_FOUND); }
Source:
public OzoneFileStatus getFileStatus(OmKeyArgs args) throws IOException { Preconditions.checkNotNull(args, "Key args can not be null"); String volumeName = args.getVolumeName(); String bucketName = args.getBucketName(); String keyName = args.getKeyName(); try { metadataManager.getLock().acquireBucketLock(volumeName, bucketName); if (keyName.length() == 0) { validateBucket(volumeName, bucketName); return new OzoneFileStatus(OZONE_URI_DELIMITER); } String fileKeyBytes = metadataManager.getOzoneKey( volumeName, bucketName, keyName); OmKeyInfo fileKeyInfo = metadataManager.getKeyTable().get(fileKeyBytes); if (fileKeyInfo != null) { return new OzoneFileStatus(fileKeyInfo, scmBlockSize, false); } String dirKey = OzoneFSUtils.addTrailingSlashIfNeeded(keyName); String dirKeyBytes = metadataManager.getOzoneKey( volumeName, bucketName, dirKey); OmKeyInfo dirKeyInfo = metadataManager.getKeyTable().get(dirKeyBytes); if (dirKeyInfo != null) { return new OzoneFileStatus(dirKeyInfo, scmBlockSize, true); } List<OmKeyInfo> keys = metadataManager.listKeys(volumeName, bucketName, null, dirKey, 1); if (keys.iterator().hasNext()) { return new OzoneFileStatus(keyName); } LOG.debug("Unable to get file status for the key: volume:" + volumeName + " bucket:" + bucketName + " key:" + keyName + " with error no " + "such file exists:"); throw new OMException("Unable to get file status: volume: " + volumeName + " bucket: " + bucketName + " key: " + keyName, ResultCodes.FILE_NOT_FOUND); } finally { metadataManager.getLock().releaseBucketLock(volumeName, bucketName); } }

Target:
public OzoneFileStatus getFileStatus(OmKeyArgs args) throws IOException { Preconditions.checkNotNull(args, "Key args can not be null"); String volumeName = args.getVolumeName(); String bucketName = args.getBucketName(); String keyName = args.getKeyName(); metadataManager.getLock().acquireBucketLock(volumeName, bucketName); try { if (keyName.length() == 0) { validateBucket(volumeName, bucketName); return new OzoneFileStatus(OZONE_URI_DELIMITER); } String fileKeyBytes = metadataManager.getOzoneKey( volumeName, bucketName, keyName); OmKeyInfo fileKeyInfo = metadataManager.getKeyTable().get(fileKeyBytes); if (fileKeyInfo != null) { return new OzoneFileStatus(fileKeyInfo, scmBlockSize, false); } String dirKey = OzoneFSUtils.addTrailingSlashIfNeeded(keyName); String dirKeyBytes = metadataManager.getOzoneKey( volumeName, bucketName, dirKey); OmKeyInfo dirKeyInfo = metadataManager.getKeyTable().get(dirKeyBytes); if (dirKeyInfo != null) { return new OzoneFileStatus(dirKeyInfo, scmBlockSize, true); } List<OmKeyInfo> keys = metadataManager.listKeys(volumeName, bucketName, null, dirKey, 1); if (keys.iterator().hasNext()) { return new OzoneFileStatus(keyName); } LOG.debug("Unable to get file status for the key: volume:" + volumeName + " bucket:" + bucketName + " key:" + keyName + " with error no " + "such file exists:"); throw new OMException("Unable to get file status: volume: " + volumeName + " bucket: " + bucketName + " key: " + keyName, ResultCodes.FILE_NOT_FOUND); } finally { metadataManager.getLock().releaseBucketLock(volumeName, bucketName); } }
Source:
protected void initFile(String id) throws FormatException, IOException { super.initFile(id); xmlId = id; store = makeFilterMetadata(); in = new RandomAccessInputStream(xmlId); in.setEncoding("ASCII"); DefaultHandler handler = new BDVXMLHandler(); try { RandomAccessInputStream s = new RandomAccessInputStream(id); XMLTools.parseXML(s, handler); s.close(); } catch (IOException e) { throw new FormatException("Malformed XML", e); } store.setXMLAnnotationValue(bdvxml, 0); String xml_id = MetadataTools.createLSID("XMLAnnotation", 0); store.setXMLAnnotationID(xml_id, 0); initializeJHDFService(h5Id); parseStructure(); if (seriesCount <= 2 && getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) { parseROIs(0); } }

Target:
protected void initFile(String id) throws FormatException, IOException { super.initFile(id); if (checkSuffix(id, "h5")) { id = fetchXMLId(); } store = makeFilterMetadata(); in = new RandomAccessInputStream(id); in.setEncoding("ASCII"); DefaultHandler handler = new BDVXMLHandler(); try (RandomAccessInputStream s = new RandomAccessInputStream(id)) { XMLTools.parseXML(s, handler); } catch (IOException e) { throw new FormatException("Malformed XML", e); } if (StringUtils.isEmpty(h5Id)) { throw new FormatException("Could not find H5 file location in XML"); } store.setXMLAnnotationValue(bdvxml, 0); String xml_id = MetadataTools.createLSID("XMLAnnotation", 0); store.setXMLAnnotationID(xml_id, 0); initializeJHDFService(h5Id); parseStructure(); if (seriesCount <= 2 && getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) { parseROIs(0); } }
Source:
public boolean isExpired() { if (getTimeToLiveInMs() != Utils.Infinite_TTL && SystemTime.getInstance().milliseconds() > getTimeToLiveInMs()) { return true; } return false; }

Target:
public boolean isExpired() { if (getTimeToLiveInMs() != Utils.Infinite_Time && SystemTime.getInstance().milliseconds() > getTimeToLiveInMs()) { return true; } return false; }
Source:
public String getQueryKeywordsForInfo() { char delimiter = ','; StringBuffer keywords = new StringBuffer(); if (q != null && q.isInfoInQuery) { for (String keyword : q.infoValues) { keywords.append(keyword).append(delimiter); } if (keywords.length() > 0) { keywords.deleteCharAt(keywords.length() - 1); } } return keywords.toString(); }

Target:
public String getQueryKeywordsForInfo() { if (q == null || !q.isInfoInQuery) { return ""; } char delimiter = ','; StringBuffer keywords = new StringBuffer(); for (String keyword : q.infoValues) { keywords.append(keyword).append(delimiter); } if (keywords.length() > 0) { keywords.deleteCharAt(keywords.length() - 1); } return keywords.toString(); }
Source:
protected SslContextFactory getSSLContext( Map args) { try { String privateKeyPassword; privateKeyPassword = Option.HTTPS_PRIVATE_KEY_PASSWORD.get(args, keystorePassword); KeyManagerFactory kmf = KeyManagerFactory.getInstance( Option.HTTPS_KEY_MANAGER_TYPE.get( args)); kmf.init(keystore, keystorePassword.toCharArray()); Logger.log(Logger.FULL_DEBUG, SSL_RESOURCES, "HttpsListener.KeyCount", keystore.size() + ""); for ( Enumeration e = keystore.aliases(); e.hasMoreElements();) { String alias = (String) e.nextElement(); Logger.log(Logger.FULL_DEBUG, SSL_RESOURCES, "HttpsListener.KeyFound", alias, keystore.getCertificate(alias) + ""); } SslContextFactory.Server ssl = new SslContextFactory.Server(); ssl.setKeyStore(keystore); ssl.setKeyStorePassword(keystorePassword); ssl.setKeyManagerPassword(privateKeyPassword); ssl.setKeyManagerFactoryAlgorithm(Option.HTTPS_KEY_MANAGER_TYPE.get(args)); ssl.setCertAlias(Option.HTTPS_CERTIFICATE_ALIAS.get(args)); ssl.setExcludeProtocols("SSLv3", "SSLv2", "SSLv2Hello"); String excludeCiphers = Option.HTTPS_EXCLUDE_CIPHER_SUITES.get(args); if(excludeCiphers!=null&&excludeCiphers.length()>0) { String[] cipherSuites = excludeCiphers.split(","); ssl.setExcludeCipherSuites(cipherSuites); } Logger.log( Logger.INFO, SSL_RESOURCES, "HttpsListener.ExcludeCiphers", Arrays.asList(ssl.getExcludeCipherSuites())); ssl.setNeedClientAuth(Option.HTTPS_VERIFY_CLIENT.get(args)); return ssl; } catch (Exception err) { throw new WinstoneException(SSL_RESOURCES .getString("HttpsListener.ErrorGettingContext"), err); } }

Target:
protected SslContextFactory getSSLContext( Map args) { try { String privateKeyPassword; privateKeyPassword = Option.HTTPS_PRIVATE_KEY_PASSWORD.get(args, keystorePassword); KeyManagerFactory kmf = KeyManagerFactory.getInstance( Option.HTTPS_KEY_MANAGER_TYPE.get( args)); kmf.init(keystore, keystorePassword.toCharArray()); Logger.log(Logger.FULL_DEBUG, SSL_RESOURCES, "HttpsListener.KeyCount", keystore.size() + ""); for ( Enumeration e = keystore.aliases(); e.hasMoreElements();) { String alias = (String) e.nextElement(); Logger.log(Logger.FULL_DEBUG, SSL_RESOURCES, "HttpsListener.KeyFound", alias, keystore.getCertificate(alias) + ""); } SslContextFactory ssl = new SslContextFactory.Server(); ssl.setKeyStore(keystore); ssl.setKeyStorePassword(keystorePassword); ssl.setKeyManagerPassword(privateKeyPassword); ssl.setKeyManagerFactoryAlgorithm(Option.HTTPS_KEY_MANAGER_TYPE.get(args)); ssl.setCertAlias(Option.HTTPS_CERTIFICATE_ALIAS.get(args)); ssl.setExcludeProtocols("SSLv3", "SSLv2", "SSLv2Hello"); String excludeCiphers = Option.HTTPS_EXCLUDE_CIPHER_SUITES.get(args); if(excludeCiphers!=null&&excludeCiphers.length()>0) { String[] cipherSuites = excludeCiphers.split(","); ssl.setExcludeCipherSuites(cipherSuites); } Logger.log( Logger.INFO, SSL_RESOURCES, "HttpsListener.ExcludeCiphers", Arrays.asList(ssl.getExcludeCipherSuites())); ssl.setNeedClientAuth(Option.HTTPS_VERIFY_CLIENT.get(args)); return ssl; } catch (Exception err) { throw new WinstoneException(SSL_RESOURCES .getString("HttpsListener.ErrorGettingContext"), err); } }
Source:
public void setUp() { MockitoAnnotations.initMocks(this); mContext = spy(RuntimeEnvironment.application); mLifecycleOwner = () -> mLifecycle; mLifecycle = new Lifecycle(mLifecycleOwner); when(mContext.getSystemService(Context.TELEPHONY_SERVICE)).thenReturn(mTelephonyManager); when(mContext.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE)) .thenReturn(mSubscriptionManager); List<SubscriptionInfo> list = new ArrayList<SubscriptionInfo>(); list.add(new SubscriptionInfo(subid_1, "", 0, "", "", 0, 0, "", 0, null, "0", "0", "", false, null, null)); list.add(new SubscriptionInfo(subid_2, "", 1, "", "", 0, 0, "", 0, null, "0", "0", "", false, null, null)); when(mSubscriptionManager.getActiveSubscriptionInfoList()).thenReturn(list); when(mTelephonyManager.getNetworkOperatorName(eq(SUBID_1))).thenReturn(TEST_CARRIER_NAME1); when(mTelephonyManager.getNetworkOperatorName(eq(SUBID_2))).thenReturn(TEST_CARRIER_NAME2); }

Target:
public void setUp() { MockitoAnnotations.initMocks(this); mContext = spy(RuntimeEnvironment.application); mLifecycleOwner = () -> mLifecycle; mLifecycle = new Lifecycle(mLifecycleOwner); when(mContext.getSystemService(Context.TELEPHONY_SERVICE)).thenReturn(mTelephonyManager); when(mContext.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE)) .thenReturn(mSubscriptionManager); List<SubscriptionInfo> list = new ArrayList<SubscriptionInfo>(); list.add(new SubscriptionInfo(SUBID_1, "", 0, "", "", 0, 0, "", 0, null, "0", "0", "", false, null, null)); list.add(new SubscriptionInfo(SUBID_2, "", 1, "", "", 0, 0, "", 0, null, "0", "0", "", false, null, null)); when(mSubscriptionManager.getActiveSubscriptionInfoList()).thenReturn(list); when(mTelephonyManager.getNetworkOperatorName(eq(SUBID_1))).thenReturn(TEST_CARRIER_NAME1); when(mTelephonyManager.getNetworkOperatorName(eq(SUBID_2))).thenReturn(TEST_CARRIER_NAME2); }
Source:
private void copyDiskDevicesFromTemplate() { Guid templateId = getParameters().getVmStaticData().getVmtGuid(); List<VmDevice> disks = DbFacade.getInstance().getVmDeviceDao().getVmDeviceByVmIdAndType(templateId, VmDeviceGeneralType.DISK); VmDeviceUtils.copyVmDevices( templateId, getVmId(), getVm(), getVm().getStaticData(), true, disks, getSrcDeviceIdToTargetDeviceIdMapping(), false, false, false, false, false ); }

Target:
private void copyDiskDevicesFromTemplate() { List<VmDevice> disks = DbFacade.getInstance().getVmDeviceDao().getVmDeviceByVmIdAndType(getVmTemplateId(), VmDeviceGeneralType.DISK); VmDeviceUtils.copyVmDevices( getVmTemplateId(), getVmId(), getVm(), getVm().getStaticData(), true, disks, getSrcDeviceIdToTargetDeviceIdMapping(), false, false, false, false, false ); }
Source:
static int compare(Row row, String aggregationName, Number value) { Object metricValueObj = row.getRaw(aggregationName); if (metricValueObj != null) { if (metricValueObj instanceof Long) { long l = ((Long) metricValueObj).longValue(); return Longs.compare(l, value.longValue()); } else if (metricValueObj instanceof String) { String metricValueStr = (String) metricValueObj; if (!metricValueStr.contains(".")) { long l = row.getLongMetric(aggregationName); return Longs.compare(l, value.longValue()); } } } float f = row.getFloatMetric(aggregationName); return Floats.compare(f, value.floatValue()); }

Target:
static int compare(Row row, String aggregationName, Number value) { Object metricValueObj = row.getRaw(aggregationName); if (metricValueObj != null) { if (metricValueObj instanceof Long) { long l = ((Long) metricValueObj).longValue(); return Longs.compare(l, value.longValue()); } else if (metricValueObj instanceof String) { String metricValueStr = (String) metricValueObj; if (LONG_PAT.matcher(metricValueStr).matches()) { long l = row.getLongMetric(aggregationName); return Longs.compare(l, value.longValue()); } } } float f = row.getFloatMetric(aggregationName); return Floats.compare(f, value.floatValue()); }
Source:
public void testStressLargeNumberOfLiveInstances() throws Exception { int concurrencyLevel = 100; String testCluster = "testStressUniqueInstanceNames"; ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool(); ZkClient zkClient = new ZkClient(_zkConnectionString); long duration = WAIT_DURATION_FOR_ZK_MS * 5; for (int i = 0; i < concurrencyLevel; i++) { Runnable task = () -> { try { Coordinator instance = createCoordinator(_zkConnectionString, testCluster); instance.start(); Thread.sleep(duration); instance.stop(); } catch (Exception ex) { LOG.error("Failed to launch coordinator", ex); Assert.fail(); } }; executor.execute(task); } Thread.sleep(duration); List<String> instances = zkClient.getChildren(KeyBuilder.liveInstances(testCluster)); List<String> sortedList = new ArrayList<>(instances); Collections.sort(sortedList); LOG.info(String.format("Live instances %s", sortedList)); Assert.assertEquals(instances.size(), concurrencyLevel, String.format("Live instances %s", sortedList)); zkClient.close(); }

Target:
public void testStressLargeNumberOfLiveInstances() throws Exception { int concurrencyLevel = 100; String testCluster = "testStressUniqueInstanceNames"; ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool(); ZkClient zkClient = new ZkClient(_zkConnectionString); long duration = Duration.ofSeconds(10).toMillis(); for (int i = 0; i < concurrencyLevel; i++) { Runnable task = () -> { try { Coordinator instance = createCoordinator(_zkConnectionString, testCluster); instance.start(); Thread.sleep(duration); instance.stop(); } catch (Exception ex) { LOG.error("Failed to launch coordinator", ex); Assert.fail(); } }; executor.execute(task); } Thread.sleep(duration); List<String> instances = zkClient.getChildren(KeyBuilder.liveInstances(testCluster)); List<String> sortedList = new ArrayList<>(instances); Collections.sort(sortedList); LOG.info(String.format("Live instances %s", sortedList)); Assert.assertEquals(instances.size(), concurrencyLevel, String.format("Live instances %s", sortedList)); zkClient.close(); }
Source:
public void testRangeRequestStitchDifferentSizedBlobsSegments() throws Exception { if (metadataContentVersion > 2) { for (int i = 0; i < NUM_STITCHED_CHUNKS; i++) { testGetSuccessStitch(chunkSize * 6 + 11, new GetBlobOptionsBuilder().blobSegment(i) .range(ByteRanges.fromOffsetRange(0, chunkSize / NUM_STITCHED_CHUNKS)) .build()); testGetSuccessStitch(chunkSize * 6 + 11, new GetBlobOptionsBuilder().blobSegment(i) .range(ByteRanges.fromOffsetRange(chunkSize / NUM_STITCHED_CHUNKS / 2, chunkSize / NUM_STITCHED_CHUNKS)) .build()); testGetSuccessStitch(chunkSize * 6 + 11, new GetBlobOptionsBuilder().blobSegment(i) .range(ByteRanges.fromOffsetRange(5, chunkSize / NUM_STITCHED_CHUNKS - 5)) .build()); testGetSuccessStitch(chunkSize * 6 + 11, new GetBlobOptionsBuilder().blobSegment(i).range(ByteRanges.fromOffsetRange(0, 0)).build()); } } else { router = getNonBlockingRouter(); router.close(); } }

Target:
public void testRangeRequestStitchDifferentSizedBlobsSegments() throws Exception { if (metadataContentVersion > MessageFormatRecord.Metadata_Content_Version_V2) { for (int i = 0; i < NUM_STITCHED_CHUNKS; i++) { testGetSuccessStitch(LARGE_BLOB_SIZE, new GetBlobOptionsBuilder().blobSegment(i) .range(ByteRanges.fromOffsetRange(0, CHUNK_SIZE / NUM_STITCHED_CHUNKS)) .build()); testGetSuccessStitch(LARGE_BLOB_SIZE, new GetBlobOptionsBuilder().blobSegment(i) .range(ByteRanges.fromOffsetRange(CHUNK_SIZE / NUM_STITCHED_CHUNKS / 2, CHUNK_SIZE / NUM_STITCHED_CHUNKS)) .build()); testGetSuccessStitch(LARGE_BLOB_SIZE, new GetBlobOptionsBuilder().blobSegment(i) .range(ByteRanges.fromOffsetRange(5, CHUNK_SIZE / NUM_STITCHED_CHUNKS - 5)) .build()); testGetSuccessStitch(LARGE_BLOB_SIZE, new GetBlobOptionsBuilder().blobSegment(i).range(ByteRanges.fromOffsetRange(0, 0)).build()); } } else { router = getNonBlockingRouter(); router.close(); } }
Source:
public void initialize() { for (SensorMotor motor : motors) { if (motor instanceof VelocitySensorMotor) { ((VelocitySensorMotor) motor).set(speed); } } }

Target:
public void initialize() { for (SensorMotor motor : motors) { if (motor instanceof VelocitySensorMotor) { ((VelocitySensorMotor) motor).set(speed); } else if (motor instanceof PositionSensorMotor) { ((PositionSensorMotor) motor).setPosition(position); } } }
Source:
public List<Project> getProjectsByFilter(final int pageNumber,final int pageSize, final Map<ProgramFilters, Object> filters) throws MiddlewareException { try { Criteria criteria = this.getSession().createCriteria(Project.class); for (Map.Entry<ProgramFilters, Object> entry : filters.entrySet()) { ProgramFilters filter = entry.getKey(); Object value = entry.getValue(); criteria.add(Restrictions.eq(filter.getStatement(), value)); } int start = pageSize * (pageNumber - 1); int numOfRows = pageSize; criteria.setFirstResult(start); criteria.setMaxResults(numOfRows); return criteria.list(); } catch (HibernateException e) { throw new MiddlewareException( "Error in getProjectsByFilter(start=" + pageNumber + ", numOfRows=" + pageSize + "): " + e.getMessage(), e); } }

Target:
public List<Project> getProjectsByFilter(final int pageNumber,final int pageSize, final Map<ProgramFilters, Object> filters) throws MiddlewareException { try { final Criteria criteria = this.getSession().createCriteria(Project.class); for (Map.Entry<ProgramFilters, Object> entry : filters.entrySet()) { final ProgramFilters filter = entry.getKey(); final Object value = entry.getValue(); criteria.add(Restrictions.eq(filter.getStatement(), value)); } final int start = pageSize * (pageNumber - 1); final int numOfRows = pageSize; criteria.setFirstResult(start); criteria.setMaxResults(numOfRows); return criteria.list(); } catch (HibernateException e) { throw new MiddlewareException( "Error in getProjectsByFilter(start=" + pageNumber + ", numOfRows=" + pageSize + "): " + e.getMessage(), e); } }