auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public List<ApiClusterTemplateConfig> getRoleConfigs(String roleType, HostgroupView hostGroupView, TemplatePreparationObject source) { Integer volumeCount = Objects.nonNull(hostGroupView) ? hostGroupView.getVolumeCount() : 0; switch (roleType) { case HdfsRoles.DATANODE: return List.of( config("dfs_data_dir_list", buildVolumePathStringZeroVolumeHandled(volumeCount, "datanode")) ); case HdfsRoles.NAMENODE: return List.of( config("dfs_name_dir_list", buildVolumePathStringZeroVolumeHandled(volumeCount, "namenode")) ); case HdfsRoles.SECONDARYNAMENODE: return List.of( config("fs_checkpoint_dir_list", buildVolumePathStringZeroVolumeHandled(volumeCount, "namesecondary")) ); case HdfsRoles.JOURNALNODE: return List.of( config("dfs_journalnode_edits_dir", buildVolumePathStringZeroVolumeHandled(volumeCount, "journalnode")) ); default: return List.of(); } }

Target:
public List<ApiClusterTemplateConfig> getRoleConfigs(String roleType, HostgroupView hostGroupView, TemplatePreparationObject source) { Integer volumeCount = Objects.nonNull(hostGroupView) ? hostGroupView.getVolumeCount() : 0; switch (roleType) { case HdfsRoles.DATANODE: return List.of( config("dfs_data_dir_list", buildVolumePathStringZeroVolumeHandled(volumeCount, "datanode")) ); case HdfsRoles.NAMENODE: return List.of( config("dfs_name_dir_list", buildVolumePathStringZeroVolumeHandled(volumeCount, "namenode")) ); case HdfsRoles.SECONDARYNAMENODE: return List.of( config("fs_checkpoint_dir_list", buildVolumePathStringZeroVolumeHandled(volumeCount, "namesecondary")) ); case HdfsRoles.JOURNALNODE: return List.of( config("dfs_journalnode_edits_dir", buildSingleVolumePath(volumeCount, "journalnode")) ); default: return List.of(); } }
Source:
protected Builder() { super(DockerApi.class); id("docker") .name("Docker API") .defaultIdentity("root") .identityName("user") .defaultCredential("password") .credentialName("Password") .documentation(URI.create("<LINK_0>")) .version("1.8") .defaultEndpoint("http://localhost:4243") .defaultProperties(DockerApiMetadata.defaultProperties()) .view(typeToken(ComputeServiceContext.class)) .defaultModules(ImmutableSet.<Class<? extends Module>>of( DockerHttpApiModule.class, DockerParserModule.class, DockerComputeServiceContextModule.class)); }

Target:
protected Builder() { super(DockerApi.class); id("docker") .name("Docker API") .identityName("user") .credentialName("password") .documentation(URI.create("<LINK_1>")) .version("1.12") .defaultEndpoint("<LINK_2>") .defaultProperties(DockerApiMetadata.defaultProperties()) .view(typeToken(ComputeServiceContext.class)) .defaultModules(ImmutableSet.<Class<? extends Module>>of( DockerHttpApiModule.class, DockerParserModule.class, DockerComputeServiceContextModule.class)); }
Source:
public boolean onStartJob(JobParameters jobParameters) { String file = jobParameters.getExtras().getString(FileUploader.KEY_FILE); String account = jobParameters.getExtras().getString(FileUploader.KEY_ACCOUNT); UploadsStorageManager uploadsStorageManager = new UploadsStorageManager(getContentResolver()); OCUpload ocUpload = uploadsStorageManager.getLastUploadFor(new OCFile(file), account); FileUploader.UploadRequester uploadRequester = new FileUploader.UploadRequester(); uploadRequester.retry(this, ocUpload); return true; }

Target:
public boolean onStartJob(JobParameters jobParameters) { UploadsStorageManager uploadsStorageManager = new UploadsStorageManager(getContentResolver()); String fileRemotePath = jobParameters.getExtras().getString(Extras.EXTRA_REMOTE_PATH); String accountName = jobParameters.getExtras().getString(Extras.EXTRA_ACCOUNT_NAME); Log_OC.d(TAG, String.format("Retrying upload of %1s in %2s", fileRemotePath, accountName)); OCUpload ocUpload = uploadsStorageManager.getLastUploadFor(new OCFile(fileRemotePath), accountName); if (ocUpload != null) { TransferRequester requester = new TransferRequester(); requester.retry(this, ocUpload); } else { Log_OC.w( TAG, String.format( "No upload found in database for %1s in %2s", fileRemotePath, accountName ) ); } jobFinished(jobParameters, false); return true; }
Source:
public void enableVerboseLogging(int verbose) { enforceAccessPermission(); mLog.trace("enableVerboseLogging uid=%").c(Binder.getCallingUid()).flush(); mFacade.setIntegerSetting( mContext, Settings.Global.WIFI_VERBOSE_LOGGING_ENABLED, verbose); enableVerboseLoggingInternal(verbose); }

Target:
public void enableVerboseLogging(int verbose) { enforceAccessPermission(); mLog.trace("enableVerboseLogging uid=% verbose=%") .c(Binder.getCallingUid()) .c(verbose).flush(); mFacade.setIntegerSetting( mContext, Settings.Global.WIFI_VERBOSE_LOGGING_ENABLED, verbose); enableVerboseLoggingInternal(verbose); }
Source:
public static void warnMemorySizeLegal(VmBase vm, Version clusterVersion) { if (! VmValidationUtils.isMemorySizeLegal(vm.getOsId(), vm.getMemSizeMb(), clusterVersion)) { AuditLogableBase logable = new AuditLogableBase(); logable.addCustomValue("VmName", vm.getName()); logable.addCustomValue("VmMemInMb", String.valueOf(vm.getMemSizeMb())); logable.addCustomValue("VmMinMemInMb", String.valueOf(VmValidationUtils.getMinMemorySizeInMb(vm.getOsId(), clusterVersion))); logable.addCustomValue("VmMaxMemInMb", String.valueOf(VmValidationUtils.getMaxMemorySizeInMb(vm.getOsId(), clusterVersion))); AuditLogDirector.log(logable, AuditLogType.VM_MEMORY_NOT_IN_RECOMMENDED_RANGE); } }

Target:
public static void warnMemorySizeLegal(VmBase vm, Version clusterVersion) { if (! VmValidationUtils.isMemorySizeLegal(vm.getOsId(), vm.getMemSizeMb(), clusterVersion)) { AuditLogableBase logable = new AuditLogableBase(); logable.setVmId(vm.getId()); logable.addCustomValue("VmName", vm.getName()); logable.addCustomValue("VmMemInMb", String.valueOf(vm.getMemSizeMb())); logable.addCustomValue("VmMinMemInMb", String.valueOf(VmValidationUtils.getMinMemorySizeInMb(vm.getOsId(), clusterVersion))); logable.addCustomValue("VmMaxMemInMb", String.valueOf(VmValidationUtils.getMaxMemorySizeInMb(vm.getOsId(), clusterVersion))); AuditLogDirector.log(logable, AuditLogType.VM_MEMORY_NOT_IN_RECOMMENDED_RANGE); } }
Source:
private String getColor(TimeEvent event) { List<@NonNull RGBAColor> list = getPalette().get(); int colorInt = list.get((int) Math.floorMod((event.getValue() & ((1L << Integer.SIZE) - 1)), list.size())).toInt(); return X11ColorUtils.toHexColor(colorInt >> 24, colorInt >> 16, colorInt >> 8); }

Target:
private String getColor(TimeEvent event) { List<@NonNull RGBAColor> list = getPalette().get(); int colorInt = list.get((int) Math.floorMod((event.getValue() & ((1L << Integer.SIZE) - 1)), list.size())).toInt(); return ColorUtils.toHexColor(colorInt >> 24, colorInt >> 16, colorInt >> 8); }
Source:
protected void executeCommand() { executeInNewTransaction(new TransactionMethod<Void>() { public Void runInTransaction() { setStorageDomainStatus(StorageDomainStatus.Locked, getCompensationContext()); getCompensationContext().stateChanged(); return null; } }); setSucceeded(false); List<String> lunsToRefresh = getParameters().getLunIds(); Map<String, List<VDS>> lunToFailedVDS = refreshLunSizeAllVds(lunsToRefresh); if (!lunToFailedVDS.isEmpty()) { ArrayList<String> failedVds = new ArrayList<>(); for (Map.Entry<String, List<VDS>> entry : lunToFailedVDS.entrySet()) { String lunId = entry.getKey(); List<VDS> vdsList = entry.getValue(); log.error("Failed to refresh device " + lunId + " Not all VDS are seeing the same size " + "VDS :" + vdsList); String vdsListString = StringUtils.join(getVdsNameList(vdsList), ", "); failedVds.add("LUN :" + lunId + "VDS: " + vdsListString); } changeStorageDomainToActive(); throw new VdcBLLException(VdcBllErrors.REFRESH_LUN_ERROR, "Failed to refresh LUNs. Not all VDS are seeing the same size " + failedVds); } resizePVs(lunsToRefresh); updateStorageDomainData(); refreshPVAllVds(lunsToRefresh); changeStorageDomainToActive(); setSucceeded(true); }

Target:
protected void executeCommand() { executeInNewTransaction(new TransactionMethod<Void>() { public Void runInTransaction() { setStorageDomainStatus(StorageDomainStatus.Locked, getCompensationContext()); getCompensationContext().stateChanged(); return null; } }); List<String> lunsToRefresh = getParameters().getLunIds(); Map<String, List<Pair<VDS, Integer>>> lunToVds = getDeviceListAllVds(lunsToRefresh); Map<String, List<VDS>> lunToFailedVDS = getFailedLuns(lunToVds); if (!lunToFailedVDS.isEmpty()) { List<String> failedVds = new ArrayList<>(); for (Map.Entry<String, List<VDS>> entry : lunToFailedVDS.entrySet()) { String lunId = entry.getKey(); List<VDS> vdsList = entry.getValue(); log.error("Failed to refresh device " + lunId + " Not all VDS are seeing the same size " + "VDS :" + vdsList); String vdsListString = StringUtils.join(getVdsNameList(vdsList), ", "); failedVds.add("LUN : " + lunId + "VDS: " + vdsListString); } throw new VdcBLLException(VdcBllErrors.REFRESH_LUN_ERROR, "Failed to refresh LUNs. Not all VDS are seeing the same size: " + failedVds); } resizePVs(lunsToRefresh); updateStorageDomainData(); changeStorageDomainToActive(); setSucceeded(true); }
Source:
protected @Nullable String getProcessName(@NonNull ITmfEvent event) { return getTrace().getExecAspect().resolve(event); }

Target:
protected @Nullable String getProcessName(@NonNull ITmfEvent event) { return fExecAspect.resolve(event); }
Source:
public void send(final OutgoingT message) { final String json = gson.toJson(message); CompletableFutureUtils.logExceptionWhenComplete( CompletableFuture.runAsync(() -> client.sendMessage(json), threadPool), "Failed to send message to server"); }

Target:
public void send(final OutgoingT message) { CompletableFutureUtils.logExceptionWhenComplete( CompletableFuture.runAsync(() -> client.sendMessage(gson.toJson(message)), threadPool), e -> log.log(Level.WARNING, "Failed to send message to server", e)); }
Source:
private Mono<Void> createContainerIfNotExistsAsync(final StorageAccount storageAccount, final String containerName) { return getBlobClientAsync(storageAccount) .flatMap(blobServiceAsyncClient -> blobServiceAsyncClient .getBlobContainerAsyncClient(containerName) .exists() .flatMap(aBoolean -> { if (aBoolean) { return Mono.empty(); } return blobServiceAsyncClient.getBlobContainerAsyncClient(containerName).create(); })); }

Target:
private Mono<Indexable> createContainerIfNotExistsAsync(final StorageAccount storageAccount, final String containerName) { return storageManager.blobContainers() .getAsync(storageAccount.resourceGroupName(), storageAccount.name(), containerName) .cast(Indexable.class) .onErrorResume(throwable -> storageManager.blobContainers() .defineContainer(containerName) .withExistingBlobService(storageAccount.resourceGroupName(), storageAccount.name()) .withPublicAccess(PublicAccess.CONTAINER) .createAsync() .last()); }
Source:
void wrapUp(GitHub root) { super.wrapUp(root); if (installation == null) throw new IllegalStateException( "Expected check_suite payload, but got something else. Maybe we've got another type of event?"); else installation.wrapUp(root); if (repositories != null && !repositories.isEmpty()) { try { for (GHRepository singleRepo : repositories) { singleRepo.wrap(root); singleRepo.refresh(); } } catch (IOException e) { throw new GHException("Failed to refresh repositories", e); } } }

Target:
void wrapUp(GitHub root) { super.wrapUp(root); if (installation == null) throw new IllegalStateException( "Expected check_suite payload, but got something else. Maybe we've got another type of event?"); else installation.wrapUp(root); if (repositories != null && !repositories.isEmpty()) { try { for (GHRepository singleRepo : repositories) { singleRepo.wrap(root); singleRepo.populate(); } } catch (IOException e) { throw new GHException("Failed to refresh repositories", e); } } }
Source:
protected void login( HttpServletRequest request, HttpServletResponse response, SsoSession ssoSession) throws Exception { log.debug("Entered login queryString: {}", request.getQueryString()); String redirectUrl; String scope = SsoUtils.getScopeRequestParameter(request, ""); if (SsoUtils.isUserAuthenticated(request)) { log.debug("User is authenticated redirecting to interactive-redirect-to-module"); redirectUrl = request.getContextPath() + SsoConstants.INTERACTIVE_REDIRECT_TO_MODULE_URI; } else if (SsoUtils.scopeAsList(scope).contains("ovirt-ext=auth:identity")) { redirectUrl = new URLBuilder(SsoUtils.getRedirectUrl(request)) .addParameter(SsoConstants.ERROR, SsoConstants.ERR_OVIRT_CODE_NOT_AUTHENTICATED) .addParameter(SsoConstants.ERROR_DESCRIPTION, SsoConstants.ERR_CODE_NOT_AUTHENTICATED_MSG).build(); } else { ssoSession.setAuthStack(getAuthSeq(ssoSession)); if (ssoSession.getAuthStack().isEmpty()) { throw new OAuthException(SsoConstants.ERR_CODE_ACCESS_DENIED, ssoContext.getLocalizationUtils().localize( SsoConstants.APP_ERROR_NO_VALID_AUTHENTICATION_MECHANISM_FOUND, (Locale) request.getAttribute(SsoConstants.LOCALE))); } redirectUrl = request.getContextPath() + SsoConstants.INTERACTIVE_LOGIN_NEXT_AUTH_URI; } log.debug("Redirecting to url: {}", redirectUrl); response.sendRedirect(redirectUrl); }

Target:
protected void login( HttpServletRequest request, HttpServletResponse response, SsoSession ssoSession) throws Exception { log.debug("Entered login queryString: {}", request.getQueryString()); String redirectUrl; if (SsoUtils.isUserAuthenticated(request)) { log.debug("User is authenticated redirecting to interactive-redirect-to-module"); redirectUrl = request.getContextPath() + SsoConstants.INTERACTIVE_REDIRECT_TO_MODULE_URI; } else if (SsoUtils.scopeAsList(SsoUtils.getScopeRequestParameter(request, "")) .contains("ovirt-ext=auth:identity")) { redirectUrl = new URLBuilder(SsoUtils.getRedirectUrl(request)) .addParameter(SsoConstants.ERROR, SsoConstants.ERR_OVIRT_CODE_NOT_AUTHENTICATED) .addParameter(SsoConstants.ERROR_DESCRIPTION, SsoConstants.ERR_CODE_NOT_AUTHENTICATED_MSG).build(); } else { ssoSession.setAuthStack(getAuthSeq(ssoSession)); if (ssoSession.getAuthStack().isEmpty()) { throw new OAuthException(SsoConstants.ERR_CODE_ACCESS_DENIED, ssoContext.getLocalizationUtils().localize( SsoConstants.APP_ERROR_NO_VALID_AUTHENTICATION_MECHANISM_FOUND, (Locale) request.getAttribute(SsoConstants.LOCALE))); } redirectUrl = request.getContextPath() + SsoConstants.INTERACTIVE_LOGIN_NEXT_AUTH_URI; } log.debug("Redirecting to url: {}", redirectUrl); response.sendRedirect(redirectUrl); }
Source:
private void renderLatexLineWidget(final Range range, final String text, final MathJaxTypesetCallback callback) { endRender(); final int row = range.getEnd().getRow(); LineWidget widget = docDisplay_.getLineWidgetForRow(row); if (widget == null) { if (pendingLineWidgets_.contains(row)) return; pendingLineWidgets_.add(row); createMathJaxLineWidget(row, range.getStart().getRow() == range.getEnd().getRow(), new CommandWithArg<LineWidget>() { @Override public void execute(LineWidget w) { pendingLineWidgets_.remove(row); renderLatexLineWidget(w, range, text, callback); } }); } else { pendingLineWidgets_.remove(row); renderLatexLineWidget(widget, range, text, callback); } }

Target:
private void renderLatexLineWidget(final Range range, final String text, final MathJaxTypesetCallback callback) { endRender(); final int row = range.getEnd().getRow(); LineWidget widget = docDisplay_.getLineWidgetForRow(row); if (widget == null) { for (Map.Entry<ChunkOutputWidget, PinnedLineWidget> entry : cowToPlwMap_.entrySet()) if (entry.getValue().getRow() == row) return; createMathJaxLineWidget(row, range.getStart().getRow() == range.getEnd().getRow(), new CommandWithArg<LineWidget>() { @Override public void execute(LineWidget w) { renderLatexLineWidget(w, range, text, callback); } }); } else { renderLatexLineWidget(widget, range, text, callback); } }
Source:
public void shouldEnrollPatientInDSDMProgramWhenDSDMIsSelectedOnNewForm() throws Exception { Patient patient = new Patient(1393); ProgramWorkflowService service = Context.getService(ProgramWorkflowService.class); HtmlForm htmlForm1 = new HtmlForm(); htmlForm1.setXmlData(xml); Form form1 = new Form(8); form1.setEncounterType(new EncounterType(15)); htmlForm1.setForm(form1); FormEntrySession session1 = new FormEntrySession(patient, null, FormEntryContext.Mode.ENTER, htmlForm1, new MockHttpSession()); session1.getHtmlToDisplay(); session1.prepareForSubmit(); HttpServletRequest request = mock(MockHttpServletRequest.class); when(request.getParameter("w1")).thenReturn("2017-04-01"); when(request.getParameter("w8")).thenReturn("165139"); session1.getSubmissionController().handleFormSubmission(session1, request); session1.applyActions(); List<PatientProgram> patientProgramList = getPatientPrograms(patient, null,null,null,false); Assert.assertEquals(service.getProgramByName("FTR"), patientProgramList.get(1).getProgram()); Assert.assertEquals(service.getProgramByName("FBIM"), patientProgramList.get(0).getProgram()); Assert.assertEquals(patientProgramList.get(1).getDateEnrolled(), patientProgramList.get(0).getDateCompleted()); }

Target:
public void shouldEnrollPatientInDSDMProgramWhenDSDMIsSelectedOnNewForm() throws Exception { Patient patient = new Patient(1393); ProgramWorkflowService service = Context.getService(ProgramWorkflowService.class); HtmlForm htmlForm1 = new HtmlForm(); htmlForm1.setXmlData(xml); Form form1 = new Form(8); form1.setEncounterType(new EncounterType(15)); htmlForm1.setForm(form1); FormEntrySession session1 = new FormEntrySession(patient, null, FormEntryContext.Mode.ENTER, htmlForm1, new MockHttpSession()); session1.getHtmlToDisplay(); session1.prepareForSubmit(); HttpServletRequest request = mock(MockHttpServletRequest.class); when(request.getParameter("w1")).thenReturn("2017-04-01"); when(request.getParameter("w8")).thenReturn("165139"); session1.getSubmissionController().handleFormSubmission(session1, request); session1.applyActions(); List<PatientProgram> patientProgramList = getPatientPrograms(patient, null,null,null,false); Assert.assertEquals(service.getProgramByName("FTR"), patientProgramList.get(1).getProgram()); Assert.assertEquals(service.getProgramByName("FBIM"), patientProgramList.get(0).getProgram()); Assert.assertEquals(session1.getEncounter().getEncounterDatetime(), patientProgramList.get(1).getDateEnrolled()); Assert.assertEquals(patientProgramList.get(1).getDateEnrolled(), patientProgramList.get(0).getDateCompleted()); }
Source:
public static MongoQueryRunner createMongoQueryRunner(Iterable<TpchTable<?>> tables) throws Exception { MongoQueryRunner queryRunner = null; try { queryRunner = new MongoQueryRunner(createSession(), 3); queryRunner.installPlugin(new TpchPlugin()); queryRunner.createCatalog("tpch", "tpch"); Map<String, String> properties = ImmutableMap.of( "mongodb.seeds", queryRunner.getAddress().getHostString() + ":" + queryRunner.getAddress().getPort(), "mongodb.socket-keep-alive", "true", "mongodb.read-preference", "SECONDARY", "mongodb.read-preference-tags", "dc:east,use:reporting&use:reporting"); queryRunner.installPlugin(new MongoPlugin()); queryRunner.createCatalog("mongodb", "mongodb", properties); copyTpchTables(queryRunner, "tpch", TINY_SCHEMA_NAME, createSession(), tables); return queryRunner; } catch (Throwable e) { closeAllSuppress(e, queryRunner); throw e; } }

Target:
public static MongoQueryRunner createMongoQueryRunner(Iterable<TpchTable<?>> tables) throws Exception { MongoQueryRunner queryRunner = null; try { queryRunner = new MongoQueryRunner(createSession(), 3); queryRunner.installPlugin(new TpchPlugin()); queryRunner.createCatalog("tpch", "tpch"); Map<String, String> properties = ImmutableMap.of( "mongodb.seeds", queryRunner.getAddress().getHostString() + ":" + queryRunner.getAddress().getPort(), "mongodb.socket-keep-alive", "true"); queryRunner.installPlugin(new MongoPlugin()); queryRunner.createCatalog("mongodb", "mongodb", properties); copyTpchTables(queryRunner, "tpch", TINY_SCHEMA_NAME, createSession(), tables); return queryRunner; } catch (Throwable e) { closeAllSuppress(e, queryRunner); throw e; } }
Source:
public void addEntity(Query query, String alias, Class<?> type) { if (query instanceof NativeQuery) { query.unwrap(NativeQuery.class).addEntity(alias, type); } else { throw new IllegalArgumentException(String.format("invalid Query type `%s` in HibernateHandler", query.getClass())); } }

Target:
public void addEntity(Query query, String alias, Class<?> type) { query.unwrap(NativeQuery.class).addEntity(alias, type); }
Source:
private void checkNumColumns(String location, int[] baseColumnMap, Dataset<Row> table) throws StandardException { if( baseColumnMap.length > table.schema().fields().length) { throw StandardException.newException(SQLState.INCONSISTENT_NUMBER_OF_ATTRIBUTE, baseColumnMap.length, table.schema().fields().length, location, ExternalTableUtils.getSuggestedSchema(table.schema())); } }

Target:
private static void checkNumColumns(String location, int[] baseColumnMap, Dataset<Row> table) throws StandardException { if( baseColumnMap.length > table.schema().fields().length) { throw StandardException.newException(SQLState.INCONSISTENT_NUMBER_OF_ATTRIBUTE, baseColumnMap.length, table.schema().fields().length, location, ExternalTableUtils.getSuggestedSchema(table.schema())); } }
Source:
public Map<DiskImage, DiskImage> mapChainToNewIDs(Guid sourceImageGroupID, Guid newImageGroupID, Guid targetStorageDomainID) { List<DiskImage> oldChain = diskImageDao.getAllSnapshotsForImageGroup(sourceImageGroupID); Map<DiskImage, DiskImage> oldToNewChain = new HashMap<>(oldChain.size()); Guid nextParentId = Guid.Empty; sortImageList(oldChain); for (DiskImage diskImage : oldChain) { DiskImage newImage = DiskImage.copyOf(diskImage); newImage.setParentId(nextParentId); newImage.setId(newImageGroupID); newImage.setStorageIds(Collections.singletonList(targetStorageDomainID)); nextParentId = Guid.newGuid(); newImage.setImageId(nextParentId); newImage.setVmSnapshotId(null); oldToNewChain.put(diskImage, newImage); } log.info("New image group {}", newImageGroupID); log.info("mapped old chain to new chain {}", ImagesHandler.getDiskImageIds(oldChain), oldToNewChain); return oldToNewChain; }

Target:
public Map<DiskImage, DiskImage> mapChainToNewIDs(Guid sourceImageGroupID, Guid newImageGroupID, Guid targetStorageDomainID) { List<DiskImage> oldChain = diskImageDao.getAllSnapshotsForImageGroup(sourceImageGroupID); Map<DiskImage, DiskImage> oldToNewChain = new HashMap<>(oldChain.size()); Guid nextParentId = Guid.Empty; sortImageList(oldChain); for (DiskImage diskImage : oldChain) { DiskImage newImage = DiskImage.copyOf(diskImage); newImage.setParentId(nextParentId); newImage.setId(newImageGroupID); newImage.setStorageIds(List.of(targetStorageDomainID)); nextParentId = Guid.newGuid(); newImage.setImageId(nextParentId); newImage.setVmSnapshotId(null); oldToNewChain.put(diskImage, newImage); } log.info("New image group {}", newImageGroupID); log.info("mapped old chain to new chain {}", ImagesHandler.getDiskImageIds(oldChain), oldToNewChain); return oldToNewChain; }
Source:
private String toJavaSymbol(String s) { String javaSymbol = s.replaceAll("[^A-Z-a-z0-9_]", ""); if (!isAlphabetic(javaSymbol.charAt(0))) { javaSymbol = "_" + javaSymbol; } return javaSymbol; }

Target:
private String toJavaSymbol(String s) { String javaSymbol = s.replaceAll("[^A-Za-z0-9_]", "_"); if (!isAlphabetic(javaSymbol.charAt(0))) { javaSymbol = "_" + javaSymbol; } return javaSymbol; }
Source:
public Or buildInPredicate(final int nodeExpression) throws CQLException { List<Expression> exprList = new LinkedList<Expression>(); while (!getResultStack().empty()) { Result result = getResultStack().peek(); int node = result.getNodeType(); if (node != nodeExpression) { break; } getResultStack().popResult(); Expression expr = (Expression) getResultStack().popExpression(); exprList.add(expr); } assert exprList.size() >= 1 : "must have one or more expressions"; final Expression leftHandExpr = getResultStack().popExpression(); List<Filter> filterList = new LinkedList<Filter>(); for (Expression expression : exprList) { PropertyIsEqualTo eq = getFilterFactory().equals(leftHandExpr, expression); filterList.add(0,eq); } Or orFilter = getFilterFactory().or(filterList); return orFilter; }

Target:
public Or buildInPredicate(final int nodeExpression) throws CQLException { List<Expression> exprList = new LinkedList<Expression>(); while (!getResultStack().empty()) { Result result = getResultStack().peek(); int node = result.getNodeType(); if (node != nodeExpression) { break; } getResultStack().popResult(); Expression expr = (Expression) getResultStack().popExpression(); exprList.add(expr); } assert exprList.size() >= 1 : "must have one or more expressions"; final Expression leftHandExpr = getResultStack().popExpression(); List<Filter> filterList = new LinkedList<Filter>(); for (Expression expression : exprList) { PropertyIsEqualTo eq = getFilterFactory().equals(leftHandExpr, expression); filterList.add(eq); } Collections.reverse(filterList); Or orFilter = getFilterFactory().or(filterList); return orFilter; }
Source:
private boolean indexExists(final File vcf) { return !Tribble.indexFile(vcf).exists() && !Tribble.tabixIndexFile(vcf).exists(); }

Target:
private boolean indexExists(final File vcf) { return Tribble.indexFile(vcf).exists() || Tribble.tabixIndexFile(vcf).exists(); }
Source:
private <T> T getLiteralValue(int childIndex, Class<T> type) { Expression expression = getChildren().get(childIndex); if (LOG.isDebugEnabled()) { LOG.debug("child: " + childIndex + ", expression: " + expression); } if (!(expression instanceof LiteralExpression)) { throw new ExpressionEvaluationException(expression); } return type.cast(((LiteralExpression) expression).getValue()); }

Target:
private <T> T getLiteralValue(int childIndex, Class<T> type) { Expression expression = getChildren().get(childIndex); if (LOG.isDebugEnabled()) { LOG.debug("child: " + childIndex + ", expression: " + expression); } return type.cast(((LiteralExpression) expression).getValue()); }
Source:
public void calcAutoCompleteSettings(String field, Map<String, Object> attributes) { if (attributes.containsKey("autoCompleteUrl")) { super.calcAutoCompleteSettings(field, attributes); return; } super.calcAutoCompleteSettings(field, attributes); if (attributes.containsKey("autoCompleteUrl")) { try { JellyContext jelly = Functions.getCurrentJellyContext(); Object it = jelly.findVariable("it"); if (it instanceof CredentialsStore) { ModelObject context = ((CredentialsStore) it).getContext(); for (CredentialsSelectHelper.ContextResolver r : ExtensionList .lookup(CredentialsSelectHelper.ContextResolver.class)) { String token = r.getToken(context); if (token != null) { String fillUrl = (String) attributes.get("autoCompleteUrl"); if (fillUrl.indexOf('?') != -1) { fillUrl = fillUrl + '&'; } else { fillUrl = fillUrl + '?'; } attributes.put("autoCompleteUrl", fillUrl + "$provider=" + r.getClass().getName() + "&" + "$token=" + URLEncoder.encode(token, "UTF-8")); } } } } catch (AssertionError e) { } catch (UnsupportedEncodingException e) { } } }

Target:
public void calcAutoCompleteSettings(String field, Map<String, Object> attributes) { if (attributes.containsKey("autoCompleteUrl")) { super.calcAutoCompleteSettings(field, attributes); return; } super.calcAutoCompleteSettings(field, attributes); if (attributes.containsKey("autoCompleteUrl")) { try { JellyContext jelly = Functions.getCurrentJellyContext(); Object it = jelly.findVariable("it"); if (it instanceof CredentialsStore) { ModelObject context = ((CredentialsStore) it).getContext(); for (CredentialsSelectHelper.ContextResolver r : ExtensionList .lookup(CredentialsSelectHelper.ContextResolver.class)) { String token = r.getToken(context); if (token != null) { String autoCompleteUrl = (String) attributes.get("autoCompleteUrl"); if (autoCompleteUrl != null) { if (autoCompleteUrl.indexOf('?') != -1) { autoCompleteUrl = autoCompleteUrl + '&'; } else { autoCompleteUrl = autoCompleteUrl + '?'; } attributes.put("autoCompleteUrl", autoCompleteUrl + "$provider=" + URLEncoder.encode(r.getClass().getName(), "UTF-8") + "&$token=" + URLEncoder.encode(token, "UTF-8")); } } } } } catch (AssertionError e) { } catch (UnsupportedEncodingException e) { } } }
Source:
public static void Init() { mUpdateVmsStatic = new ObjectIdentityChecker(VmHandler.class, Arrays.asList(new String[] { "VM", "VmStatic", "VmDynamic" }), VMStatus.class); mUpdateVmsStatic.AddPermittedFields(new String[] { "vm_name", "description", "domain", "os", "osType", "creation_date", "num_of_monitors", "allowConsoleReconnect", "usb_policy", "is_auto_suspend", "auto_startup", "dedicated_vm_for_vds", "default_display_type", "priority", "default_boot_sequence", "initrd_url", "kernel_url", "kernel_params", "migrationSupport", "minAllocatedMem", "quotaId", "quotaName", "quotaEnforcementType", "cpuPinning", "vmPayload", "balloonEnabled", "smartcardEnabled", "images", "interfaces" }); mUpdateVmsStatic.AddFields( Arrays.asList(new Enum<?>[] { VMStatus.Down }), Arrays.asList(new String[] { "vds_group_id", "time_zone", "is_stateless", "nice_level", "mem_size_mb", "num_of_sockets", "cpu_per_socket", "iso_path", "userDefinedProperties", "predefinedProperties", "customProperties" })); }

Target:
public static void Init() { mUpdateVmsStatic = new ObjectIdentityChecker(VmHandler.class, Arrays.asList(new String[] { "VM", "VmStatic", "VmDynamic" }), VMStatus.class); mUpdateVmsStatic.AddPermittedFields(new String[] { "vmName", "description", "domain", "os", "osType", "creationDate", "numOfMonitors", "allowConsoleReconnect", "usbPolicy", "autoSuspend", "autoStartup", "dedicatedVmForVds", "defaultDisplayType", "priority", "defaultBootSequence", "initrdUrl", "kernelUrl", "kernelParams", "migrationSupport", "minAllocatedMem", "quotaId", "quotaName", "quotaEnforcementType", "cpuPinning", "vmPayload", "balloonEnabled", "smartcardEnabled", "images", "interfaces" }); mUpdateVmsStatic.AddFields( Arrays.asList(new Enum<?>[] { VMStatus.Down }), Arrays.asList(new String[] { "vds_group_id", "time_zone", "is_stateless", "nice_level", "mem_size_mb", "num_of_sockets", "cpu_per_socket", "iso_path", "userDefinedProperties", "predefinedProperties", "customProperties" })); }
Source:
protected ICommand getAfterMoveCommand(final MoveRequest request) { ICommand moveCommand = super.getAfterMoveCommand(request); Set<View> viewsToDestroy = new HashSet<View>(); Object parameter = request.getParameter(TYPE_MOVING); if ((parameter == null) || (!parameter.equals(TYPE_MOVING_DIAGRAM))) { @SuppressWarnings("unchecked") Iterator<EObject> it = request.getElementsToMove().keySet().iterator(); while (it.hasNext()) { EObject eObject = it.next(); viewsToDestroy.addAll(getMemberViewsToDestroy(eObject)); } Iterator<View> viewToDestroyIterator = viewsToDestroy.iterator(); while (viewToDestroyIterator.hasNext()) { View view = viewToDestroyIterator.next(); DeleteCommand destroyViewsCommand = new DeleteCommand(request.getEditingDomain(), view); moveCommand = CompositeCommand.compose(moveCommand, destroyViewsCommand); } } return moveCommand; }

Target:
protected ICommand getAfterMoveCommand(final MoveRequest request) { ICommand moveCommand = super.getAfterMoveCommand(request); Set<View> viewsToDestroy = new HashSet<View>(); Object parameter = request.getParameter(DefaultCreationEditPolicy.TYPE_MOVING); if ((null == parameter) || (!DefaultCreationEditPolicy.TYPE_MOVING_DIAGRAM.equals(parameter))) { @SuppressWarnings("unchecked") Iterator<EObject> it = request.getElementsToMove().keySet().iterator(); while (it.hasNext()) { EObject eObject = it.next(); viewsToDestroy.addAll(getMemberViewsToDestroy(eObject)); } Iterator<View> viewToDestroyIterator = viewsToDestroy.iterator(); while (viewToDestroyIterator.hasNext()) { View view = viewToDestroyIterator.next(); DeleteCommand destroyViewsCommand = new DeleteCommand(request.getEditingDomain(), view); moveCommand = CompositeCommand.compose(moveCommand, destroyViewsCommand); } } return moveCommand; }
Source:
public static ParameterSet fromByteBuffer(ByteBuffer buffer) throws IOException { int startPos = buffer.position(); short count = buffer.getShort(); if (count < 0) { throw new RuntimeException("ParameterSet exceeds the length limitation " + Short.MAX_VALUE); } Object[] params = new Object[count]; byte[][] encodedStrings = null; byte[][][] encodedStringArrays = null; for (int i = 0; i < count; ++i) { OneParamInfo opi = readOneParameter(buffer); params[i] = opi.value; if (opi.encodedString != null) { if (encodedStrings == null) { encodedStrings = new byte[count][]; } encodedStrings[i] = opi.encodedString; } if (opi.encodedStringArray != null) { if (encodedStringArrays == null) { encodedStringArrays = new byte[count][][]; } encodedStringArrays[i] = opi.encodedStringArray; } } int size = buffer.position() - startPos; return new ParameterSet(params, size, encodedStrings, encodedStringArrays); }

Target:
public static ParameterSet fromByteBuffer(ByteBuffer buffer) throws IOException { int startPos = buffer.position(); short count = buffer.getShort(); if (count < 0) { throw new IllegalArgumentException("Invalid parameter length " + count + " for ParameterSet." ); } Object[] params = new Object[count]; byte[][] encodedStrings = null; byte[][][] encodedStringArrays = null; for (int i = 0; i < count; ++i) { OneParamInfo opi = readOneParameter(buffer); params[i] = opi.value; if (opi.encodedString != null) { if (encodedStrings == null) { encodedStrings = new byte[count][]; } encodedStrings[i] = opi.encodedString; } if (opi.encodedStringArray != null) { if (encodedStringArrays == null) { encodedStringArrays = new byte[count][][]; } encodedStringArrays[i] = opi.encodedStringArray; } } int size = buffer.position() - startPos; return new ParameterSet(params, size, encodedStrings, encodedStringArrays); }
Source:
private List<String> recursiveFolderUpload(ChannelSftp channelSftp, String sourcePath, String destinationPath) throws SftpException, FileNotFoundException { List<String> filesRelativePathName = new ArrayList<>(); File sourceFile = new File(sourcePath); if (sourceFile.isFile()) { channelSftp.cd(destinationPath); getOut().println("Uploading " + sourcePath); channelSftp.put(new FileInputStream(sourceFile), sourceFile.getName(), ChannelSftp.OVERWRITE); getOut().println("File uploaded successfully to " + Paths.get(destinationPath, sourceFile.getName()).toString()); filesRelativePathName.add(Paths.get(destinationPath, sourceFile.getName()).toString()); } else { String remoteFilePath = Paths.get(destinationPath, sourceFile.getName()).toString(); File[] files = sourceFile.listFiles(); if (files != null && !sourceFile.getName().startsWith(".")) { channelSftp.cd(destinationPath); if (!remoteDirExists(channelSftp, remoteFilePath)) { channelSftp.mkdir(sourceFile.getName()); } for (File f : files) { filesRelativePathName.addAll(recursiveFolderUpload(channelSftp, f.getAbsolutePath(), remoteFilePath)); } } } return filesRelativePathName; }

Target:
private List<String> recursiveFolderUpload(ChannelSftp channelSftp, String sourcePath, String destinationPath) throws SftpException, FileNotFoundException { List<String> filesRelativePathName = new ArrayList<>(); File sourceFile = new File(sourcePath); String remoteFilePath = Paths.get(destinationPath, sourceFile.getName()).toString(); if (sourceFile.isFile()) { getOut().println("Uploading " + sourcePath); channelSftp.put(new FileInputStream(sourceFile), remoteFilePath, ChannelSftp.OVERWRITE); getOut().println("File uploaded successfully to " + remoteFilePath); filesRelativePathName.add(remoteFilePath); } else { File[] files = sourceFile.listFiles(); if (!sourceFile.isHidden()) { if (!remoteDirExists(channelSftp, remoteFilePath)) { channelSftp.mkdir(remoteFilePath); } for (File f : files) { filesRelativePathName.addAll(recursiveFolderUpload(channelSftp, f.getAbsolutePath(), remoteFilePath)); } } } return filesRelativePathName; }
Source:
public OperationContext(String clientId) { this.clientId = clientId; this.correlationId = new Random().nextInt(); }

Target:
public OperationContext(String clientId) { this.clientId = clientId; this.correlationId = currentCount.incrementAndGet(); }
Source:
private void transferKarma( GenericMessageEvent event, Matcher transferMatcher ) { if ( !( event instanceof MessageEvent ) || !( (MessageEvent) event ).getChannel().getName().equals( Vilebot.getConfig().get( "ircChannel1" ) ) ) { event.respondWith( "You must be in " + Vilebot.getConfig().get( "ircChannel1" ) + " to make or accept wagers." ); return; } synchronized ( currentTransferMutex ) { if ( currentTransaction == null ) { String sender = BaseNick.toBaseNick( event.getUser().getNick() ); String receiver = BaseNick.toBaseNick( transferMatcher.group( 1 ) ); if ( sender.equals( receiver ) ) { event.respondWith( "Really? What's the point of transferring karma to yourself?" ); return; } int transferAmount = Integer.parseInt( transferMatcher.group( 2 ) ); Integer senderKarma = KarmaDB.getNounKarma( sender ); senderKarma = senderKarma == null ? 0 : senderKarma; if ( !validAmount( transferAmount, senderKarma ) ) { event.respondWith( transferAmount + " isn't a valid amount." + " Transfer amount must be greater than 0, and you must have at least as much karma" + " as the amount you want to transfer." ); } else { startTransaction( event, sender, receiver, transferAmount ); } } else { String sender = currentTransaction.getSender(); String receiver = currentTransaction.getReceiver(); int amount = currentTransaction.getTransferAmount(); event.respondWith( "A transfer is already active. " + sender + " wants to transfer " + amount + " karma to " + receiver + ". " + receiver + ", please !accept or !reject this transfer." + " You have 30 seconds to respond." ); } } }

Target:
private void transferKarma( GenericMessageEvent event, Matcher transferMatcher ) { if ( !( event instanceof MessageEvent ) || !( (MessageEvent) event ).getChannel().getName().equals( Vilebot.getConfig().get( "ircChannel1" ) ) ) { event.respondWith( "You must be in " + Vilebot.getConfig().get( "ircChannel1" ) + " to transfer karma." ); return; } synchronized ( currentTransferMutex ) { if ( currentTransaction == null ) { String sender = BaseNick.toBaseNick( event.getUser().getNick() ); String receiver = BaseNick.toBaseNick( transferMatcher.group( 1 ) ); if ( sender.equals( receiver ) ) { event.respondWith( "Really? What's the point of transferring karma to yourself?" ); return; } int transferAmount = Integer.parseInt( transferMatcher.group( 2 ) ); Integer senderKarma = KarmaDB.getNounKarma( sender ); senderKarma = senderKarma == null ? 0 : senderKarma; if ( !validAmount( transferAmount, senderKarma ) ) { event.respondWith( transferAmount + " isn't a valid amount." + " Transfer amount must be greater than 0, and you must have at least as much karma" + " as the amount you want to transfer." ); } else { startTransaction( event, sender, receiver, transferAmount ); } } else { String sender = currentTransaction.getSender(); String receiver = currentTransaction.getReceiver(); int amount = currentTransaction.getTransferAmount(); event.respondWith( "A transfer is already active. " + sender + " wants to transfer " + amount + " karma to " + receiver + ". " + receiver + ", please !accept or !reject this transfer." + " You have 30 seconds to respond." ); } } }
Source:
public AndroidByteBuddyMockMaker() { if (Platform.isAndroid() || Boolean.getBoolean("org.mockito.mock.android")) { delegate = new SubclassByteBuddyMockMaker(new AndroidLoadingStrategy()); } else { System.err.println(join( "IMPORTANT NOTE FROM MOCKITO:", "", "You included the 'mockito-android' dependency in a non-Android environment.", "The Android mock maker was disabled. You should only include the latter in your 'androidTestCompile' configuration", "If disabling was a mistake, you can set the 'org.mockito.mock.android' property to 'true' to override this behavior." )); delegate = new SubclassByteBuddyMockMaker(); } }

Target:
public AndroidByteBuddyMockMaker() { if (Platform.isAndroid() || Platform.isAndroidMockMakerRequired()) { delegate = new SubclassByteBuddyMockMaker(new AndroidLoadingStrategy()); } else { new ConsoleMockitoLogger().log(join( "IMPORTANT NOTE FROM MOCKITO:", "", "You included the 'mockito-android' dependency in a non-Android environment.", "The Android mock maker was disabled. You should only include the latter in your 'androidTestCompile' configuration", "If disabling was a mistake, you can set the 'org.mockito.mock.android' property to 'true' to override this detection.", "", "Visit <LINK_0> for more information" )); delegate = new SubclassByteBuddyMockMaker(); } }
Source:
public void setup() throws InjectionException { final Configuration configuration = Tang.Factory.getTang().newConfigurationBuilder() .bindNamedParameter(ServerId.class, "ServerId") .build(); final Injector injector = Tang.Factory.getTang().newInjector(configuration); mockSender = mock(WorkerMsgSender.class); injector.bindVolatileInstance(WorkerMsgSender.class, mockSender); injector.bindVolatileInstance(ParameterUpdater.class, mock(ParameterUpdater.class)); injector.bindVolatileInstance(ServerResolver.class, mock(ServerResolver.class)); injector.bindVolatileParameter(PSParameters.KeyCodecName.class, new IntegerCodec()); injector.bindVolatileParameter(WorkerQueueSize.class, 2500); injector.bindVolatileParameter(ParameterWorkerNumThreads.class, 2); doAnswer(invocationOnMock -> { final EncodedKey<Integer> encodedKey = (EncodedKey) invocationOnMock.getArguments()[1]; handler.processReply(encodedKey.getKey(), encodedKey.getKey()); return null; }).when(mockSender).sendPullMsg(anyString(), anyObject()); worker = injector.getInstance(ParameterWorkerImpl.class); handler = injector.getInstance(AsyncWorkerHandlerImpl.class); }

Target:
public void setup() throws InjectionException, NetworkException { final Configuration configuration = Tang.Factory.getTang().newConfigurationBuilder() .bindNamedParameter(ServerId.class, "ServerId") .build(); final Injector injector = Tang.Factory.getTang().newInjector(configuration); mockSender = mock(WorkerMsgSender.class); injector.bindVolatileInstance(WorkerMsgSender.class, mockSender); injector.bindVolatileInstance(ParameterUpdater.class, mock(ParameterUpdater.class)); injector.bindVolatileInstance(ServerResolver.class, mock(ServerResolver.class)); injector.bindVolatileParameter(PSParameters.KeyCodecName.class, new IntegerCodec()); injector.bindVolatileParameter(WorkerQueueSize.class, WORKER_QUEUE_SIZE); injector.bindVolatileParameter(ParameterWorkerNumThreads.class, WORKER_NUM_THREADS); doAnswer(invocationOnMock -> { final EncodedKey<Integer> encodedKey = (EncodedKey) invocationOnMock.getArguments()[1]; handler.processReply(encodedKey.getKey(), encodedKey.getKey()); return null; }).when(mockSender).sendPullMsg(anyString(), anyObject()); worker = injector.getInstance(ParameterWorkerImpl.class); handler = injector.getInstance(AsyncWorkerHandlerImpl.class); }
Source:
public String toString() { return "SenderId{" + "id=" + id + '}'; }

Target:
public String toString() { return "SenderId{" + id + "}"; }
Source:
private static long doubleToSortableLong(double value) { long bits = Double.doubleToLongBits(value); return bits ^ (bits >> 63) & Long.MAX_VALUE; }

Target:
private static long doubleToSortableLong(double value) { long bits = Double.doubleToLongBits(value); return bits ^ ((bits >> 63) & Long.MAX_VALUE); }
Source:
private void requestLocationUpdates(){ if(locationListener == null) { locationListener = new LocationListener() { @Override public void onLocationChanged(android.location.Location location) { double latitude = location.getLatitude(); double longitude = location.getLongitude(); Log.e(getClass().getSimpleName(), "New Latitude: " + latitude + "New Longitude: " + longitude); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { Log.e(getClass().getSimpleName(), "GPS location enabled"); } @Override public void onProviderEnabled(String provider) { Log.e(getClass().getSimpleName(), "GPS location enabled"); } @Override public void onProviderDisabled(String provider) { Log.e(getClass().getSimpleName(), "GPS location disabled"); } }; } locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); }

Target:
private void requestLocationUpdates(){ if(locationListener == null) { locationListener = new LocationListener() { @Override public void onLocationChanged(android.location.Location location) @Override public void onStatusChanged(String provider, int status, Bundle extras) @Override public void onProviderEnabled(String provider) @Override public void onProviderDisabled(String provider) }; } locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); }
Source:
private void checkField(final PendingCertifiedProductDTO listing, final Object field, final String errorField, String type) { if (type.equals(ERROR)) { if (field instanceof Long) { Long fieldCasted = (Long) field; if (fieldCasted.toString().length() > getMaxLength("maxLength." + errorField)) { listing.getErrorMessages().add(msgUtil.getMessage("listing." + errorField + ".maxlength", String.valueOf(getMaxLength("maxLength." + errorField)), fieldCasted)); } } else if (field instanceof String) { String fieldCasted = (String) field; if (fieldCasted.length() > getMaxLength("maxLength." + errorField)) { listing.getErrorMessages().add(msgUtil.getMessage("listing." + errorField + ".maxlength", String.valueOf(getMaxLength("maxLength." + errorField)), fieldCasted)); } } } else { if (field instanceof Long) { Long fieldCasted = (Long) field; if (fieldCasted.toString().length() > getMaxLength("maxLength." + errorField)) { listing.getWarningMessages().add(msgUtil.getMessage("listing." + errorField + ".maxlength", String.valueOf(getMaxLength("maxLength." + errorField)), fieldCasted)); } } else if (field instanceof String) { String fieldCasted = (String) field; if (fieldCasted.length() > getMaxLength("maxLength." + errorField)) { listing.getWarningMessages().add(msgUtil.getMessage("listing." + errorField + ".maxlength", String.valueOf(getMaxLength("maxLength." + errorField)), fieldCasted)); } } } }

Target:
private void checkField(final PendingCertifiedProductDTO listing, final Object field, final String errorField, String type) { String message = null; if (field instanceof Long) { Long fieldCasted = (Long) field; if (fieldCasted.toString().length() > getMaxLength("maxLength." + errorField)) { message = msgUtil.getMessage("listing." + errorField + ".maxlength", String.valueOf(getMaxLength("maxLength." + errorField)), fieldCasted); } } else if (field instanceof String) { String fieldCasted = (String) field; if (fieldCasted.length() > getMaxLength("maxLength." + errorField)) { message = msgUtil.getMessage("listing." + errorField + ".maxlength", String.valueOf(getMaxLength("maxLength." + errorField)), fieldCasted); } } if (type.equals(ERROR)) { listing.getErrorMessages().add(message); } else { listing.getWarningMessages().add(message); } }