auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Response applications() { checkAccountApiEnabled(); auth.requireOneOf(AccountRoles.VIEW_APPLICATIONS, AccountRoles.MANAGE_APPLICATIONS); List<String> activeClients = new LinkedList<String>(); List<UserSessionModel> sessions = session.sessions().getUserSessions(realm, user); for (UserSessionModel s : sessions) { activeClients.addAll(s.getAuthenticatedClientSessions().keySet()); } List<ClientRepresentation> apps = new LinkedList<>(); for (ClientModel client : realm.getClients()) { if (client.isBearerOnly()) { continue; } ClientRepresentation clientRep = new ClientRepresentation(); clientRep.setClientId(client.getClientId()); clientRep.setClientName(client.getName()); clientRep.setInternal(true); clientRep.setInUse(activeClients.contains(client.getClientId())); clientRep.setUrl(client.getBaseUrl()); apps.add(clientRep); } for (UserConsentModel consent : session.users().getConsents(realm, user.getId())) { ClientModel client = consent.getClient(); if (!new StorageId(client.getId()).isLocal()) { ClientRepresentation clientRep = new ClientRepresentation(); clientRep.setClientId(client.getClientId()); clientRep.setClientName(client.getName()); clientRep.setInternal(false); clientRep.setInUse(activeClients.contains(client.getClientId())); clientRep.setUrl(client.getBaseUrl()); apps.add(clientRep); } } return Cors.add(request, Response.ok(apps)).auth().allowedOrigins(auth.getToken()).build(); }

Target:
public Response applications() { checkAccountApiEnabled(); auth.requireOneOf(AccountRoles.MANAGE_ACCOUNT, AccountRoles.VIEW_APPLICATIONS); Set<ClientModel> clients = new HashSet<ClientModel>(); List<String> inUseClients = new LinkedList<String>(); List<UserSessionModel> sessions = session.sessions().getUserSessions(realm, user); for(UserSessionModel s : sessions) { for (AuthenticatedClientSessionModel a : s.getAuthenticatedClientSessions().values()) { ClientModel client = a.getClient(); clients.add(client); inUseClients.add(client.getClientId()); } } List<String> offlineClients = new LinkedList<String>(); List<UserSessionModel> offlineSessions = session.sessions().getOfflineUserSessions(realm, user); for(UserSessionModel s : offlineSessions) { for(AuthenticatedClientSessionModel a : s.getAuthenticatedClientSessions().values()) { ClientModel client = a.getClient(); clients.add(client); offlineClients.add(client.getClientId()); } } Map<String, UserConsentModel> consentModels = new HashMap<String, UserConsentModel>(); List<UserConsentModel> consents = session.users().getConsents(realm, user.getId()); for (UserConsentModel consent : consents) { ClientModel client = consent.getClient(); clients.add(client); consentModels.put(client.getClientId(), consent); } List<ClientRepresentation> apps = new LinkedList<ClientRepresentation>(); for (ClientModel client : clients) { if (client.isBearerOnly() || client.getBaseUrl() == null) { continue; } apps.add(modelToRepresentation(client, inUseClients, offlineClients, consentModels)); } return Cors.add(request, Response.ok(apps)).auth().allowedOrigins(auth.getToken()).build(); }
Source:
private static void assertAuditLogWritten() { assertTrue(EXPECTED_AUDIT_LOG_MESSAGE, auditLogWritten); auditLogWritten = false; }

Target:
private void assertAuditLogWritten() { assertTrue(EXPECTED_AUDIT_LOG_MESSAGE, auditLogWritten); auditLogWritten = false; }
Source:
public void scan(HttpMessage msg, NameValuePair originalParam) { isJsonPayload = originalParam.getType() == NameValuePair.TYPE_POST_DATA; super.scan(msg, originalParam); }

Target:
public void scan(HttpMessage msg, NameValuePair originalParam) { isJsonPayload = originalParam.getType() == NameValuePair.TYPE_JSON; super.scan(msg, originalParam); }
Source:
public static String toKey(Role role) { switch (role) { case SUPER_ADMIN: return KEY_SUPER_ADMIN; case ADMIN: return KEY_ADMIN; case EDITOR: return KEY_EDITOR; case AUTHOR: return KEY_AUTHOR; case CONTRIBUTOR: return KEY_CONTRIBUTOR; default: return "unsupported"; } }

Target:
public static String toKey(Role role) { switch (role) { case SUPER_ADMIN: return KEY_SUPER_ADMIN; case ADMIN: return KEY_ADMIN; case EDITOR: return KEY_EDITOR; case AUTHOR: return KEY_AUTHOR; case CONTRIBUTOR: return KEY_CONTRIBUTOR; case UNSUPPORTED: return "unsupported"; } return "unsupported"; }
Source:
public String getBuckName() { @Var RuleType ruleType = this; @Var Boolean insertOkBuckPrefix = false; switch (this) { case KOTLIN_ANDROID_LIBRARY: case ANDROID_LIBRARY: ruleType = ANDROID_LIBRARY; insertOkBuckPrefix = true; break; case KOTLIN_ROBOLECTRIC_TEST: case ROBOLECTRIC_TEST: ruleType = ROBOLECTRIC_TEST; break; case ANDROID_PREBUILT_AAR: insertOkBuckPrefix = true; break; default: break; } String prefix = insertOkBuckPrefix ? "okbuck_" : ""; return prefix + ruleType.name().toLowerCase(); }

Target:
public String getBuckName() { @Var RuleType ruleType = this; @Var Boolean insertOkBuckPrefix = false; switch (this) { case KOTLIN_ANDROID_LIBRARY: case ANDROID_LIBRARY: ruleType = ANDROID_LIBRARY; insertOkBuckPrefix = true; break; case KOTLIN_ROBOLECTRIC_TEST: case ROBOLECTRIC_TEST: ruleType = ROBOLECTRIC_TEST; break; case ANDROID_PREBUILT_AAR: insertOkBuckPrefix = true; break; default: break; } String prefix = insertOkBuckPrefix ? OKBUCK_PREFIX : ""; return prefix + ruleType.name().toLowerCase(); }
Source:
protected Command getDeleteCommand(final GroupRequest request) { if (getHost() instanceof Link) { return new DeleteLinkCommand((Link) getHost().getModel()); } return null; }

Target:
protected Command getDeleteCommand(final GroupRequest request) { if (getHost().getModel() instanceof Link) { return new DeleteLinkCommand((Link) getHost().getModel()); } return null; }
Source:
private void pending() { Callback callback; boolean commit; Throwable failure; synchronized (this) { switch (_state) { case SENDING: { _state = State.PENDING; return; } case SUCCEEDING: { callback = _callback; commit = _commit; failure = null; reset(); break; } case FAILING: { _state = State.FAILED; callback = _callback; commit = _commit; failure = _failure; break; } default: { _state = State.FAILED; _failure = new IllegalStateException("Invalid transport state: " + _state); callback = _callback; commit = _commit; failure = _failure; break; } } } if (failure == null) succeed(callback, commit); else fail(callback, commit, failure); }

Target:
private void pending() { Callback callback; boolean commit; Throwable failure; synchronized (this) { switch (_state) { case SENDING: { _state = State.PENDING; return; } case SUCCEEDING: { callback = _callback; commit = _commit; failure = null; reset(null); break; } case FAILING: { callback = _callback; commit = _commit; failure = _failure; reset(failure); break; } default: { callback = _callback; commit = _commit; failure = new IllegalStateException("Invalid transport state: " + _state); reset(failure); break; } } } if (failure == null) succeed(callback, commit); else fail(callback, commit, failure); }
Source:
public boolean execute(Property inputProperty, Node outputNode, Context context) throws Exception { LOGGER.debug("VdbDynamicSequencer.execute called:outputNode name='{0}', path='{1}'", outputNode.getName(), outputNode.getPath()); final Binary binaryValue = inputProperty.getBinary(); CheckArg.isNotNull(binaryValue, "binary"); outputNode.setPrimaryType(VdbLexicon.Vdb.VIRTUAL_DATABASE); outputNode.addMixin(JcrConstants.MIX_REFERENCEABLE); outputNode.setProperty(VdbLexicon.Vdb.ORIGINAL_FILE, outputNode.getPath()); outputNode.setProperty(JcrConstants.MODE_SHA1, ((org.modeshape.jcr.api.Binary)binaryValue).getHexHash()); InputStream stream = binaryValue.getStream(); VdbManifest manifest = readManifest(stream, outputNode, context); if (manifest == null) { throw new Exception("VdbDynamicSequencer.execute failed. The xml cannot be read."); } return true; }

Target:
public boolean execute(Property inputProperty, Node outputNode, Context context) throws Exception { LOGGER.debug("VdbDynamicSequencer.execute called:outputNode name='{0}', path='{1}'", outputNode.getName(), outputNode.getPath()); final Binary binaryValue = inputProperty.getBinary(); CheckArg.isNotNull(binaryValue, "binary"); InputStream stream = binaryValue.getStream(); VdbManifest manifest = readManifest(binaryValue, stream, outputNode, context); if (manifest == null) { throw new Exception("VdbDynamicSequencer.execute failed. The xml cannot be read."); } return true; }
Source:
public int createSaveProjectToExternalMemoryNotification(Context context, String programName) { if (context == null || programName == null) { return -1; } PendingIntent doesNothingPendingIntent = PendingIntent.getActivity(context, -1, new Intent(), PendingIntent.FLAG_ONE_SHOT); NotificationData data = new NotificationData(doesNothingPendingIntent, R.drawable.ic_stat, programName, context.getString(R.string.notification_save_project_to_external_storage_title_pending), context.getString(R.string.notification_save_project_to_external_storage_title_open), context.getString(R.string.notification_save_project_to_external_storage_pending), context.getString(R.string.notification_save_project_to_external_storage_open, EXTERNAL_STORAGE_ROOT_EXPORT_DIRECTORY), 0, 100, false, false); int id = createNotification(context, data); showOrUpdateNotification(id, 0); return id; }

Target:
public int createSaveProjectToExternalMemoryNotification(Context context, String programName) { if (context == null || programName == null) { return -1; } PendingIntent doesNothingPendingIntent = PendingIntent.getActivity(context, -1, new Intent(), PendingIntent.FLAG_ONE_SHOT); NotificationData data = new NotificationData(doesNothingPendingIntent, R.drawable.ic_stat, programName, context.getString(R.string.notification_save_project_to_external_storage_title_pending), context.getString(R.string.notification_save_project_to_external_storage_title_open), context.getString(R.string.notification_save_project_to_external_storage_pending), context.getString(R.string.notification_save_project_to_external_storage_open, EXTERNAL_STORAGE_ROOT_EXPORT_DIRECTORY), 0, MAX_PERCENT, false, false); int id = createNotification(context, data); showOrUpdateNotification(id, 0); return id; }
Source:
private IVariableBinding[] compressArray(IVariableBinding[] array) { if (array == null) return null; int size= 0; for (IVariableBinding a : array) { if (a != null) { size++; } } if (size == array.length) return array; IVariableBinding[] result= new IVariableBinding[size]; for (int i= 0, r= 0; i < array.length; i++) { if (array[i] != null) result[r++]= array[i]; } return result; }

Target:
private IVariableBinding[] compressArray(IVariableBinding[] array) { if (array == null) return null; int size= 0; for (IVariableBinding binding : array) { if (binding != null) { size++; } } if (size == array.length) return array; IVariableBinding[] result= new IVariableBinding[size]; for (int i= 0, r= 0; i < array.length; i++) { if (array[i] != null) result[r++]= array[i]; } return result; }
Source:
public boolean isAutoincrementIdField() { return autoincrementIdField == null ? AUTO_INCREMENT_ID_FIELD_DEFAULT : autoincrementIdField; }

Target:
public boolean isAutoincrementIdField() { return autoincrementIdField == null ? AUTO_INCREMENT_ID_FIELD_DEFAULT : autoincrementIdField.booleanValue(); }
Source:
public boolean isLoggedIn() { if (!"XWiki.XWikiGuest".equals(getContext().getUser())) { return true; } else { LOGGER.info("User is not logged in"); } return false; }

Target:
public boolean isLoggedIn() { boolean ret = !XWikiRightService.GUEST_USER_FULLNAME.equals(getContext().getUser()); LOGGER.info("isLoggedIn: {}", ret); return ret; }
Source:
private boolean ifExceedQuota(CacheQuota cacheQuota, FileReadRequest request) { DataSize cacheSize = DataSize.succinctBytes(cacheScopeSizeInBytes.getOrDefault(cacheQuota.getIdentifier(), 0L) + request.getLength()); Optional<DataSize> quota = cacheQuota.getQuota(); return quota.isPresent() && (cacheSize.compareTo(quota.get()) > 0); }

Target:
private boolean ifExceedQuota(CacheQuota cacheQuota, FileReadRequest request) { DataSize cacheSize = DataSize.succinctBytes(cacheScopeSizeInBytes.getOrDefault(cacheQuota.getIdentifier(), 0L) + request.getLength()); return cacheQuota.getQuota().map(quota -> cacheSize.compareTo(quota) > 0).orElse(false); }
Source:
protected MessageType getProjectedSchema(FieldProjectionFilter fieldProjectionFilter) { return new ThriftSchemaConverter(null, fieldProjectionFilter) .convert((Class<TBase<?, ?>>)thriftClass); }

Target:
protected MessageType getProjectedSchema(FieldProjectionFilter fieldProjectionFilter) { return new ThriftSchemaConverter(new Configuration(), fieldProjectionFilter) .convert((Class<TBase<?, ?>>)thriftClass); }
Source:
protected SyslogReceivingChannelAdapterSupport createInstance() throws Exception { SyslogReceivingChannelAdapterSupport adapter; if (this.protocol == Protocol.tcp) { adapter = new TcpSyslogReceivingChannelAdapter(); if (this.connectionFactory != null) { Assert.isNull(this.port, "Cannot specify both 'port' and 'connectionFactory'"); ((TcpSyslogReceivingChannelAdapter) adapter).setConnectionFactory(this.connectionFactory); } Assert.isNull(this.udpAdapter, "Cannot specifiy 'udp-attributes' when the protocol is 'tcp'"); } else { adapter = new UdpSyslogReceivingChannelAdapter(); if (this.udpAdapter != null) { Assert.isNull(this.port, "Cannot specify both 'port' and 'udpAdapter'"); ((UdpSyslogReceivingChannelAdapter) adapter).setUdpAdapter(this.udpAdapter); } Assert.isNull(this.connectionFactory, "Cannot specifiy 'connection-factory' unless the protocol is 'tcp'"); } if (this.port != null) { adapter.setPort(this.port); } if (this.outputChannel != null) { adapter.setOutputChannel(this.outputChannel); } adapter.setAutoStartup(this.autoStartup); adapter.setPhase(this.phase); if (this.errorChannel != null) { adapter.setErrorChannel(this.errorChannel); } if (this.sendTimeout != null) { adapter.setSendTimeout(this.sendTimeout); } if (this.converter != null) { adapter.setConverter(this.converter); } if (this.beanName != null) { adapter.setBeanName(this.beanName); } adapter.afterPropertiesSet(); this.adapter = adapter; return adapter; }

Target:
protected SyslogReceivingChannelAdapterSupport createInstance() throws Exception { SyslogReceivingChannelAdapterSupport adapter; if (this.protocol == Protocol.tcp) { adapter = new TcpSyslogReceivingChannelAdapter(); if (this.connectionFactory != null) { Assert.isNull(this.port, "Cannot specify both 'port' and 'connectionFactory'"); ((TcpSyslogReceivingChannelAdapter) adapter).setConnectionFactory(this.connectionFactory); } Assert.isNull(this.udpAdapter, "Cannot specifiy 'udp-attributes' when the protocol is 'tcp'"); } else if(this.protocol == Protocol.udp) { adapter = new UdpSyslogReceivingChannelAdapter(); if (this.udpAdapter != null) { Assert.isNull(this.port, "Cannot specify both 'port' and 'udpAdapter'"); ((UdpSyslogReceivingChannelAdapter) adapter).setUdpAdapter(this.udpAdapter); } Assert.isNull(this.connectionFactory, "Cannot specifiy 'connection-factory' unless the protocol is 'tcp'"); } else { throw new IllegalStateException("Unsupported protocol: " + this.protocol.toString()); } if (this.port != null) { adapter.setPort(this.port); } if (this.outputChannel != null) { adapter.setOutputChannel(this.outputChannel); } adapter.setAutoStartup(this.autoStartup); adapter.setPhase(this.phase); if (this.errorChannel != null) { adapter.setErrorChannel(this.errorChannel); } if (this.sendTimeout != null) { adapter.setSendTimeout(this.sendTimeout); } if (this.converter != null) { adapter.setConverter(this.converter); } if (this.beanName != null) { adapter.setBeanName(this.beanName); } adapter.afterPropertiesSet(); this.adapter = adapter; return adapter; }
Source:
public static Collection<Object[]> data() { Collection<Object[]> params = Lists.newArrayListWithCapacity(4); params.add(new Object[]{true}); params.add(new Object[]{false}); return params; }

Target:
public static Collection<Object[]> data() { Collection<Object[]> params = Lists.newArrayListWithCapacity(2); params.add(new Object[]{true}); params.add(new Object[]{false}); return params; }
Source:
public void onActivityResult(int requestCode, int resultCode, Intent data) { int errorCode = data.getIntExtra(WalletConstants.EXTRA_ERROR_CODE, 0); switch (requestCode) { case AndroidPayHelper.REQUEST_CODE_CHANGE_MASKED_WALLET: if (resultCode == Activity.RESULT_OK && data.hasExtra(WalletConstants.EXTRA_MASKED_WALLET)) { MaskedWallet maskedWallet = data.getParcelableExtra(WalletConstants.EXTRA_MASKED_WALLET); getSampleApplication().setMaskedWallet(maskedWallet); updateCheckoutWithMaskedWallet(maskedWallet); } break; case AndroidPayHelper.REQUEST_CODE_FULL_WALLET: switch (resultCode) { case Activity.RESULT_OK: if (data != null && data.hasExtra(WalletConstants.EXTRA_FULL_WALLET)) { FullWallet fullWallet = data.getParcelableExtra(WalletConstants.EXTRA_FULL_WALLET); completeCheckout(fullWallet); } break; case Activity.RESULT_CANCELED: break; default: handleGoogleWalletError(errorCode); break; } break; case WalletConstants.RESULT_ERROR: handleGoogleWalletError(errorCode); break; default: super.onActivityResult(requestCode, resultCode, data); break; } }

Target:
public void onActivityResult(int requestCode, int resultCode, Intent data) { int errorCode = data.getIntExtra(WalletConstants.EXTRA_ERROR_CODE, 0); switch (requestCode) { case AndroidPayHelper.REQUEST_CODE_CHANGE_MASKED_WALLET: if (resultCode == Activity.RESULT_OK && data.hasExtra(WalletConstants.EXTRA_MASKED_WALLET)) { MaskedWallet maskedWallet = data.getParcelableExtra(WalletConstants.EXTRA_MASKED_WALLET); updateCheckoutWithMaskedWallet(maskedWallet); } break; case AndroidPayHelper.REQUEST_CODE_FULL_WALLET: switch (resultCode) { case Activity.RESULT_OK: if (data != null && data.hasExtra(WalletConstants.EXTRA_FULL_WALLET)) { FullWallet fullWallet = data.getParcelableExtra(WalletConstants.EXTRA_FULL_WALLET); completeCheckout(fullWallet); } break; case Activity.RESULT_CANCELED: break; default: handleGoogleWalletError(errorCode); break; } break; case WalletConstants.RESULT_ERROR: handleGoogleWalletError(errorCode); break; default: super.onActivityResult(requestCode, resultCode, data); break; } }
Source:
protected Set<AgentInfo> getVisibleAsSet() { return getAllLocal() .stream() .filter(agentInfo -> agentInfo.getRegion().equals(getConfig().getRegion())) .collect(toSet()); }

Target:
protected Set<AgentInfo> getVisibleAsSet() { return getAllAttached() .stream() .filter(agentInfo -> agentInfo.getRegion().equals(getConfig().getRegion())) .collect(toSet()); }
Source:
public boolean matches(URL url) { return url.getProtocol().equals("file") && url.toExternalForm().endsWith(".jar"); }

Target:
public boolean matches(URL url) { return url.getProtocol().equals("file") && url.toExternalForm().contains(".jar"); }
Source:
private boolean isFirstBoot() { IPackageManager pm = AppGlobals.getPackageManager(); try { final boolean isFirstBoot = pm.isFirstBoot(); final boolean isUpgrade = pm.isDeviceUpgrading(); return isFirstBoot && !isUpgrade; } catch (RemoteException e) { throw new IllegalStateException("Package manager not available"); } }

Target:
private boolean isFirstBoot() { return Settings.Global.getInt(mResolver, Settings.Global.BOOT_COUNT) == 1; }
Source:
public Completable compressBlock(long startTimeSlice, int pageSize, int maxConcurrency) { return Completable.fromObservable( dataAccess.findAllDataFromBucket(startTimeSlice, pageSize, maxConcurrency) .flatMap(rows -> rows .publish(p -> p.window( p.map(Row::getPartitionKeyToken) .distinctUntilChanged())) .concatMap(o -> { Observable<Row> sharedRows = o.share(); Observable<CompressedPointContainer> compressed = sharedRows.compose(new TempTableCompressTransformer(startTimeSlice)); Observable<Row> keyTake = sharedRows.take(1); return compressed.zipWith(keyTake, (cpc, r) -> { MetricId<?> metricId = new MetricId(r.getString(0), MetricType.fromCode(r.getByte(1)), r.getString(2)); return dataAccess .insertCompressedData(metricId, startTimeSlice, cpc, getTTL(metricId)) .mergeWith(updateMetricExpiration(metricId).map(rs -> null)); }); }), maxConcurrency) .flatMap(rs -> rs) .doOnError(Throwable::printStackTrace) .doOnCompleted(() -> { log.infof("Compress part completed"); dataAccess.dropTempTable(startTimeSlice) .subscribeOn(Schedulers.io()) .subscribe(); }) ); }

Target:
public Completable compressBlock(long startTimeSlice, int pageSize, int maxConcurrency) { return Completable.fromObservable( dataAccess.findAllDataFromBucket(startTimeSlice, pageSize, maxConcurrency) .switchIfEmpty(Observable.empty()) .flatMap(rows -> rows .publish(p -> p.window( p.map(Row::getPartitionKeyToken) .distinctUntilChanged())) .concatMap(o -> { Observable<Row> sharedRows = o.share(); Observable<CompressedPointContainer> compressed = sharedRows.compose(new TempTableCompressTransformer(startTimeSlice)); Observable<Row> keyTake = sharedRows.take(1); return compressed.zipWith(keyTake, (cpc, r) -> { MetricId<?> metricId = new MetricId(r.getString(0), MetricType.fromCode(r.getByte(1)), r.getString(2)); return dataAccess .insertCompressedData(metricId, startTimeSlice, cpc, getTTL(metricId)) .mergeWith(updateMetricExpiration(metricId).map(rs -> null)); }); }), maxConcurrency) .flatMap(rs -> rs) .doOnCompleted(() -> dataAccess.dropTempTable(startTimeSlice) .compose(applyRetryPolicy()) .subscribeOn(Schedulers.io()) .subscribe()) ); }
Source:
public void setSelectableItems(List<SearchBoxRecordWidget<T>> resultDisplayItems) { waitingForResults = false; hasResults = !(resultDisplayItems.size() == 0); this.resultDisplayItems = resultDisplayItems; if (hasResults) { mainPanel.clear(); int count = 0; for (final SearchBoxRecordWidget<T> displayItem : this.resultDisplayItems) { if (count > 0) { SimplePanel recordsSplitter = new SimplePanel(); recordsSplitter.setHeight("1px"); recordsSplitter.setStyleName("itemSplitter"); mainPanel.add(recordsSplitter); System.out.println("Hello"); } mainPanel.add(displayItem); final int itemId = count; displayItem.addMouseOverHandler(new MouseOverHandler() { @Override public void onMouseOver(MouseOverEvent arg0) { if (selectedIndex >= 0) { SearchBoxDropDown.this.resultDisplayItems.get(selectedIndex).setSelectedState(false); } displayItem.setSelectedState(true); selectedIndex = itemId; } }); displayItem.addMouseOutHandler(new MouseOutHandler() { @Override public void onMouseOut(MouseOutEvent arg0) { displayItem.setSelectedState(false); } }); count++; } } else { addInfoMessages(); } }

Target:
public void setSelectableItems(List<SearchBoxRecordWidget<T>> resultDisplayItems) { waitingForResults = false; hasResults = !(resultDisplayItems.size() == 0); this.resultDisplayItems = resultDisplayItems; if (hasResults) { mainPanel.clear(); int count = 0; for (final SearchBoxRecordWidget<T> displayItem : this.resultDisplayItems) { if (count > 0) { SimplePanel recordsSplitter = new SimplePanel(); recordsSplitter.setHeight("1px"); recordsSplitter.setStyleName("itemSplitter"); mainPanel.add(recordsSplitter); } mainPanel.add(displayItem); final int itemId = count; displayItem.addMouseOverHandler(new MouseOverHandler() { @Override public void onMouseOver(MouseOverEvent event) { if (selectedIndex >= 0) { SearchBoxDropDown.this.resultDisplayItems.get(selectedIndex).setSelectedState(false); } displayItem.setSelectedState(true); selectedIndex = itemId; } }); displayItem.addMouseOutHandler(new MouseOutHandler() { @Override public void onMouseOut(MouseOutEvent event) { displayItem.setSelectedState(false); } }); count++; } } else { addInfoMessages(); } }
Source:
public ATCommandResponse sendATCommand(ATCommand command) throws InterfaceNotOpenException, InvalidOperatingModeException, TimeoutException, IOException { if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); if (command == null) throw new NullPointerException("AT command cannot be null."); ATCommandResponse response = null; switch (getOperatingMode()) { case AT: case UNKNOWN: default: throw new InvalidOperatingModeException(); case API: case API_ESCAPE: XBeeAPIPacket packet = new ATCommandPacket(getNextFrameID(), command.getCommand(), command.getParameter()); logger.debug("Sending AT command [{} {}].", command.getCommand(), command.getParameter()); try { ATCommandResponsePacket answerPacket = (ATCommandResponsePacket)sendXBeePacket(packet); response = new ATCommandResponse(command, answerPacket.getCommandData(), answerPacket.getStatus()); logger.debug("AT command response: {}.", response.getResponseString()); } catch (InvalidOperatingModeException e) { logger.error(e.getMessage(), e); } catch (ClassCastException e) { logger.error("Received an invalid packet type after sending an AT command packet." + e); } } return response; }

Target:
public ATCommandResponse sendATCommand(ATCommand command) throws InterfaceNotOpenException, InvalidOperatingModeException, TimeoutException, IOException { if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); if (command == null) throw new NullPointerException("AT command cannot be null."); ATCommandResponse response = null; OperatingMode operatingMode = getOperatingMode(); switch (operatingMode) { case AT: case UNKNOWN: default: throw new InvalidOperatingModeException(operatingMode); case API: case API_ESCAPE: XBeeAPIPacket packet = new ATCommandPacket(getNextFrameID(), command.getCommand(), command.getParameter()); if (command.getParameter() == null) logger.debug(toString() + "Sending AT command '{}'.", command.getCommand()); else logger.debug(toString() + "Sending AT command '{} {}'.", command.getCommand(), HexUtils.prettyHexString(command.getParameter())); try { ATCommandResponsePacket answerPacket = (ATCommandResponsePacket)sendXBeePacket(packet); response = new ATCommandResponse(command, answerPacket.getCommandData(), answerPacket.getStatus()); logger.debug(toString() + "AT command response: {}.", HexUtils.prettyHexString(response.getResponse())); } catch (ClassCastException e) { logger.error("Received an invalid packet type after sending an AT command packet." + e); } } return response; }
Source:
public Map<EtlKey, ExceptionWritable> readErrors(FileSystem fs, Path newExecutionOutput) throws IOException { Map<EtlKey, ExceptionWritable> errors = new HashMap<EtlKey, ExceptionWritable>(); for (FileStatus f : fs.listStatus(newExecutionOutput, new PrefixFilter( EtlMultiOutputFormat.ERRORS_PREFIX))) { SequenceFile.Reader reader = new SequenceFile.Reader(fs, f.getPath(), fs.getConf()); EtlKey key = new EtlKey(); ExceptionWritable value = new ExceptionWritable(); while (reader.next(key, value)) { ExceptionWritable exceptionWritable = new ExceptionWritable(); exceptionWritable.set(value.toString()); errors.put(new EtlKey(key), exceptionWritable); } reader.close(); } return errors; }

Target:
public Map<EtlKey, ExceptionWritable> readErrors(FileSystem fs, Path newExecutionOutput) throws IOException { Map<EtlKey, ExceptionWritable> errors = new HashMap<EtlKey, ExceptionWritable>(); for (FileStatus f : fs.listStatus(newExecutionOutput, new PrefixFilter( EtlMultiOutputFormat.ERRORS_PREFIX))) { SequenceFile.Reader reader = new SequenceFile.Reader(fs, f.getPath(), fs.getConf()); String errorFrom = "\nError from file [" + f.getPath() + "]"; EtlKey key = new EtlKey(); ExceptionWritable value = new ExceptionWritable(); while (reader.next(key, value)) { ExceptionWritable exceptionWritable = new ExceptionWritable(value.toString() + errorFrom); errors.put(new EtlKey(key), exceptionWritable); } reader.close(); } return errors; }
Source:
protected DimensionColumn constructDimension(String dimensionField, Class<?> cls, EntityDictionary entityDictionary) { DimensionColumn dim = super.constructDimension(dimensionField, cls, entityDictionary); JoinTo joinTo = entityDictionary.getAttributeOrRelationAnnotation(cls, JoinTo.class, dimensionField); if (joinTo == null) { String columnName = getColumnName(entityClass, dimensionField); if (dim instanceof TimeDimensionColumn) { return new SQLTimeDimension((TimeDimensionColumn) dim, columnName, getAlias()); } return new SQLDimension(dim, columnName, getAlias()); } Path path = new Path(entityClass, entityDictionary, joinTo.path()); if (dim instanceof TimeDimensionColumn) { return new SQLTimeDimension((TimeDimensionColumn) dim, getJoinColumn(path), getJoinTableAlias(path), path); } return new SQLDimension(dim, getJoinColumn(path), getJoinTableAlias(path), path); }

Target:
protected DimensionColumn constructDimension(String dimensionField, Class<?> cls, EntityDictionary entityDictionary) { DimensionColumn dim = super.constructDimension(dimensionField, cls, entityDictionary); JoinTo joinTo = entityDictionary.getAttributeOrRelationAnnotation(cls, JoinTo.class, dimensionField); if (joinTo == null) { String columnName = getColumnName(entityClass, dimensionField); if (dim instanceof TimeDimensionColumn) { return new SQLTimeDimensionColumn((TimeDimensionColumn) dim, columnName, getAlias()); } return new SQLDimensionColumn(dim, columnName, getAlias()); } Path path = new Path(entityClass, entityDictionary, joinTo.path()); if (dim instanceof TimeDimensionColumn) { return new SQLTimeDimensionColumn((TimeDimensionColumn) dim, getJoinColumn(path), getJoinTableAlias(path), path); } return new SQLDimensionColumn(dim, getJoinColumn(path), getJoinTableAlias(path), path); }
Source:
public ExitCode run() { for (final sun.misc.Signal s : signalsToIntercept) { sun.misc.Signal.handle(s, signal -> handleTerminationSignal()); } log.info("Starting job execution"); try { this.stateMachine.run(); } catch (final Exception e) { log.error("Job state machine execution failed: {}", e.getMessage()); throw e; } final ExecutionContext executionContext = this.stateMachine.getExecutionContext(); final JobStatus finalJobStatus = executionContext.getCurrentJobStatus(); final boolean jobLaunched = executionContext.isJobLaunched(); final FatalTransitionException fatalException = executionContext.getExecutionAbortedFatalException(); if (fatalException != null) { UserConsole.getLogger().error( "Job execution fatal error in state {}: {}", fatalException.getSourceState(), fatalException.getCause().getMessage() ); } final ExitCode exitCode; switch (finalJobStatus) { case SUCCEEDED: log.info("Job executed successfully"); exitCode = ExitCode.SUCCESS; break; case KILLED: log.info("Job killed during execution"); exitCode = ExitCode.EXEC_ABORTED; break; case FAILED: if (jobLaunched) { log.info("Job execution failed"); exitCode = ExitCode.EXEC_FAIL; } else { log.info("Job setup failed"); exitCode = ExitCode.COMMAND_INIT_FAIL; } break; case INVALID: log.info("Job execution initialization failed"); exitCode = ExitCode.INIT_FAIL; break; default: throw new RuntimeException("Unexpected final job status: " + finalJobStatus.name()); } return exitCode; }

Target:
public ExitCode run() { for (final sun.misc.Signal s : signalsToIntercept) { sun.misc.Signal.handle(s, signal -> handleTerminationSignal()); } log.info("Starting job execution"); try { this.stateMachine.run(); } catch (final Exception e) { log.error("Job state machine execution failed: {}", e.getMessage()); throw e; } final ExecutionContext executionContext = this.stateMachine.getExecutionContext(); final JobStatus finalJobStatus = executionContext.getCurrentJobStatus(); final boolean jobLaunched = executionContext.isJobLaunched(); final FatalJobExecutionException fatalException = executionContext.getExecutionAbortedFatalException(); if (fatalException != null) { UserConsole.getLogger().error( "Job execution fatal error in state {}: {}", fatalException.getSourceState(), fatalException.getCause().getMessage() ); } final ExitCode exitCode; switch (finalJobStatus) { case SUCCEEDED: log.info("Job executed successfully"); exitCode = ExitCode.SUCCESS; break; case KILLED: log.info("Job killed during execution"); exitCode = ExitCode.EXEC_ABORTED; break; case FAILED: if (jobLaunched) { log.info("Job execution failed"); exitCode = ExitCode.EXEC_FAIL; } else { log.info("Job setup failed"); exitCode = ExitCode.COMMAND_INIT_FAIL; } break; case INVALID: log.info("Job execution initialization failed"); exitCode = ExitCode.INIT_FAIL; break; default: throw new RuntimeException("Unexpected final job status: " + finalJobStatus.name()); } return exitCode; }
Source:
protected File doInBackground(Uri... uris) { File instanceFile; FormController formController = Collect.getInstance().getFormController(); if (formController != null) { instanceFile = formController.getInstanceFile(); if (instanceFile != null) { String instanceFolder = instanceFile.getParent(); String extension = ContentResolverHelper.getFileExtensionFromUri(formEntryActivity.get(), uris[0]); String destMediaPath = instanceFolder + File.separator + System.currentTimeMillis() + extension; try { File chosenFile = MediaUtils.getFileFromUri(formEntryActivity.get(), uris[0], MediaStore.Images.Media.DATA, formEntryActivity.get().getNetworkStateProvider()); if (chosenFile != null) { final File newFile = new File(destMediaPath); FileUtils.copyFile(chosenFile, newFile); QuestionWidget questionWidget = formEntryActivity.get().getWidgetWaitingForBinaryData(); if (questionWidget instanceof BaseImageWidget) { ImageConverter.execute(newFile.getPath(), questionWidget, formEntryActivity.get()); } return newFile; } else { Timber.e("Could not receive chosen file"); formEntryActivity.get().runOnUiThread(() -> ToastUtils.showShortToastInMiddle(R.string.error_occured)); return null; } } catch (GDriveConnectionException e) { Timber.e("Could not receive chosen file due to connection problem"); formEntryActivity.get().runOnUiThread(() -> ToastUtils.showLongToastInMiddle(R.string.gdrive_connection_exception)); return null; } } } return null; }

Target:
protected File doInBackground(Uri... uris) { File instanceFile; FormController formController = Collect.getInstance().getFormController(); if (formController != null) { instanceFile = formController.getInstanceFile(); if (instanceFile != null) { String instanceFolder = instanceFile.getParent(); String extension = ContentResolverHelper.getFileExtensionFromUri(formEntryActivity.get(), uris[0]); String destMediaPath = instanceFolder + File.separator + System.currentTimeMillis() + extension; try { File chosenFile = MediaUtils.getFileFromUri(formEntryActivity.get(), uris[0], MediaStore.Images.Media.DATA, connectivityProvider.get()); if (chosenFile != null) { final File newFile = new File(destMediaPath); FileUtils.copyFile(chosenFile, newFile); QuestionWidget questionWidget = formEntryActivity.get().getWidgetWaitingForBinaryData(); if (questionWidget instanceof BaseImageWidget) { ImageConverter.execute(newFile.getPath(), questionWidget, formEntryActivity.get()); } return newFile; } else { Timber.e("Could not receive chosen file"); formEntryActivity.get().runOnUiThread(() -> ToastUtils.showShortToastInMiddle(R.string.error_occured)); return null; } } catch (GDriveConnectionException e) { Timber.e("Could not receive chosen file due to connection problem"); formEntryActivity.get().runOnUiThread(() -> ToastUtils.showLongToastInMiddle(R.string.gdrive_connection_exception)); return null; } } } return null; }
Source:
public MotechUser findByUserName(String userName) { if (userName == null) { return null; } MotechUser retrievedUser = dataService.findByUserName(userName.toLowerCase()); if (retrievedUser != null && retrievedUser.getRoles() == null) { return findByUserName(userName); } return retrievedUser; }

Target:
public MotechUser findByUserName(String userName) { MotechUser retrievedUser = null; if (userName != null) { retrievedUser = dataService.findByUserName(userName.toLowerCase()); if (retrievedUser != null && retrievedUser.getRoles() == null) { retrievedUser.setRoles((List<String>) dataService.getDetachedField(retrievedUser, "roles")); } } return retrievedUser; }
Source:
private void validateSingleTableInput(AnalysisJob job) { SourceColumnFinder sourceColumnFinder = new SourceColumnFinder(); sourceColumnFinder.addSources(job); validateSingleTableInput(sourceColumnFinder, job.getTransformerJobs()); validateSingleTableInput(sourceColumnFinder, job.getFilterJobs()); validateSingleTableInput(sourceColumnFinder, job.getAnalyzerJobs()); }

Target:
private void validateSingleTableInput(AnalysisJob job) { final SourceColumnFinder sourceColumnFinder = new SourceColumnFinder(); sourceColumnFinder.addSources(job); validateSingleTableInput(sourceColumnFinder, job.getTransformerJobs()); validateSingleTableInput(sourceColumnFinder, job.getFilterJobs()); validateSingleTableInput(sourceColumnFinder, job.getAnalyzerJobs()); }
Source:
protected Location getLocation(@Nullable Collection<? extends Location> locations) { if (locations==null || locations.isEmpty()) locations = entity().getLocations(); if (locations.isEmpty()) { MachineProvisioningLocation<?> provisioner = entity().getAttribute(SoftwareProcess.PROVISIONING_LOCATION); if (provisioner!=null) locations = Arrays.<Location>asList(provisioner); } if (locations.isEmpty()) { Entity parent = entity().getParent(); if (parent!=null) locations = parent.getLocations(); } if (locations.size() > 1) { Collection<Location> locationsNonProvisioning = LocationFunctions.filter(locations, LocationFunctions.isNotOfType(MachineProvisioningLocation.class)); if (locationsNonProvisioning.size()==1) locations = locationsNonProvisioning; } if (locations.size() != 1 || Iterables.getOnlyElement(locations)==null) throw new IllegalArgumentException("Ambiguous locations detected when starting "+entity()+": "+locations); return Iterables.getOnlyElement(locations); }

Target:
protected Location getLocation(@Nullable Collection<? extends Location> locations) { if (locations==null || locations.isEmpty()) locations = entity().getLocations(); if (locations.isEmpty()) { MachineProvisioningLocation<?> provisioner = entity().getAttribute(SoftwareProcess.PROVISIONING_LOCATION); if (provisioner!=null) locations = Arrays.<Location>asList(provisioner); } locations = Locations.getLocationsCheckingAncestors(locations, entity()); Optional<MachineLocation> ml = Locations.findUniqueMachineLocation(locations); if (ml.isPresent()) return ml.get(); if (locations.size() != 1 || Iterables.getOnlyElement(locations)==null) throw new IllegalArgumentException("Ambiguous locations detected when starting "+entity()+": "+locations); return Iterables.getOnlyElement(locations); }
Source:
public void setAuthorizations(DualListModel<Authorization> authorizations) { try { List<Authorization> assignedAuthorizations = new ArrayList<>(); for (Object object : authorizations.getTarget()) { assignedAuthorizations .add(serviceManager.getAuthorizationService().getById(Integer.parseInt((String) object))); } this.myBenutzergruppe.setAuthorizations(assignedAuthorizations); } catch (DAOException e) { logger.error(e.getMessage()); } }

Target:
public void setAuthorizations(DualListModel<Authorization> authorizations) { authorizations.getTarget().removeIf(Objects::isNull); this.myBenutzergruppe.setAuthorizations(authorizations.getTarget()); }
Source:
protected void testAccessControl() throws Exception { FeedbackSessionAttributes fs = typicalBundle.feedbackSessions.get("session1InCourse1"); String[] submissionParams = new String[]{ Const.ParamsNames.COURSE_ID, fs.getCourseId(), Const.ParamsNames.FEEDBACK_SESSION_NAME, fs.getFeedbackSessionName() }; verifyOnlyInstructorsOfTheSameCourseCanAccess(submissionParams); }

Target:
protected void testAccessControl() throws Exception { FeedbackSessionAttributes fs = typicalBundle.feedbackSessions.get("session1InCourse1"); StudentAttributes studentNotSubmitFeedback = typicalBundle.students.get("student5InCourse1"); String[] submissionParams = new String[]{ Const.ParamsNames.COURSE_ID, fs.getCourseId(), Const.ParamsNames.FEEDBACK_SESSION_NAME, fs.getFeedbackSessionName(), Const.ParamsNames.SUBMISSION_REMIND_USERLIST, studentNotSubmitFeedback.getEmail() }; verifyOnlyInstructorsOfTheSameCourseCanAccess(submissionParams); verifyUnaccessibleWithoutModifySessionPrivilege(submissionParams); }
Source:
private boolean areContextsReady(ServiceReference[] refs) { if (refs != null && refs.length > expectedContexts) { LOGGER.info("Tested bundles contexts:"); for (ServiceReference ref : refs) { LOGGER.info(ref.toString()); } return true; } return false; }

Target:
private boolean areContextsReady(ServiceReference[] refs) { if (refs != null && refs.length >= expectedContexts) { LOGGER.info("Tested bundle contexts: {}", Arrays.toString(refs)); return true; } return false; }
Source:
public VaultEnvironmentRepository(ObjectProvider<HttpServletRequest> request, EnvironmentWatch watch, RestTemplate rest, VaultEnvironmentProperties properties, ConfigTokenProvider tokenProvider) { this.request = request; this.watch = watch; this.backend = properties.getBackend(); this.defaultKey = properties.getDefaultKey(); this.host = properties.getHost(); this.order = properties.getOrder(); this.port = properties.getPort(); this.profileSeparator = properties.getProfileSeparator(); this.scheme = properties.getScheme(); this.namespace = properties.getNamespace(); String baseUrl = String.format("%s://%s:%s", this.scheme, this.host, this.port); this.accessStrategy = VaultKvAccessStrategyFactory.forVersion(rest, baseUrl, properties.getKvVersion()); if (tokenProvider == null) { this.tokenProvider = new HttpRequestConfigTokenProvider(request); } else { this.tokenProvider = tokenProvider; } }

Target:
public VaultEnvironmentRepository(ObjectProvider<HttpServletRequest> request, EnvironmentWatch watch, RestTemplate rest, VaultEnvironmentProperties properties, ConfigTokenProvider tokenProvider) { this.request = request; this.watch = watch; this.tokenProvider = tokenProvider; this.backend = properties.getBackend(); this.defaultKey = properties.getDefaultKey(); this.host = properties.getHost(); this.order = properties.getOrder(); this.port = properties.getPort(); this.profileSeparator = properties.getProfileSeparator(); this.scheme = properties.getScheme(); this.namespace = properties.getNamespace(); String baseUrl = String.format("%s://%s:%s", this.scheme, this.host, this.port); this.accessStrategy = VaultKvAccessStrategyFactory.forVersion(rest, baseUrl, properties.getKvVersion()); }
Source:
int getWidth() { return this.width; }

Target:
public int getWidth() { return this.width; }
Source:
public static void stop(String ifaceName) throws KuraException { try { if (!s_isIntelEdison) { int pid = getPid(ifaceName); if (pid >= 0) { s_logger.info("stopping wpa_suplicant for the interface, pid={}", ifaceName, pid); boolean exists = LinuxProcessUtil.stop(pid); if (!exists) { s_logger.warn("stopping wpa_supplicant for the inetrface, pid={} has failed", ifaceName, pid); } else { exists = LinuxProcessUtil.waitProcess(pid, 500, 5000); } if (exists) { s_logger.info("stopping wpa_supplicant for the interface - killing pid={}", ifaceName, pid); exists = LinuxProcessUtil.kill(pid); if (!exists) { s_logger.warn("stopping wpa_supplicant for the interface - killing pid={} has failed", ifaceName, pid); } else { exists = LinuxProcessUtil.waitProcess(pid, 500, 5000); } } if (exists) { s_logger.warn("Failed to stop hostapd for the interface", ifaceName); } } } else { LinuxProcessUtil.start("systemctl stop hostapd"); } if (ifaceName != null) { LinuxNetworkUtil.disableInterface(ifaceName); Thread.sleep(1000); } } catch (Exception e) { throw KuraException.internalError(e); } }

Target:
public static void stop(String ifaceName) throws KuraException { try { if (!s_isIntelEdison) { LinuxProcessUtil.stopAndKill(getPid(ifaceName)); } else { LinuxProcessUtil.start("systemctl stop hostapd"); } if (ifaceName != null) { LinuxNetworkUtil.disableInterface(ifaceName); Thread.sleep(1000); } } catch (Exception e) { throw KuraException.internalError(e); } }
Source:
public double getTotalHours() { final long ms = getTotalAward().toMillis(); return ((double) ms) / 3600000.0; }

Target:
public double getTotalHours() { return toHours(getTotalAward()); }
Source:
public void selectAll() { press(KeyCode.SHIFT).press(KeyCode.HOME).release(KeyCode.HOME).release(KeyCode.SHIFT); }

Target:
public void selectAll() { pushKeys(new KeyCodeCombination(KeyCode.A, KeyCombination.SHORTCUT_DOWN)); }
Source:
private static String execute( String[] commands, Map<String, String> environmentVariables, boolean log) throws IOException { ProcessBuilder pb = new ProcessBuilder(commands); pb.environment().putAll(environmentVariables); pb.redirectErrorStream(true); Process p = pb.start(); InputStream in = new BufferedInputStream(p.getInputStream()); StringBuilder out = new StringBuilder(); String s; if (log) { LOG.info(String.format("Execute the commnad: %s", String.join(" ", commands))); } try (BufferedReader br = new BufferedReader(new InputStreamReader(in))) { while ((s = br.readLine()) != null) { out.append(s).append("\n"); if (log) { LOG.info(s); } } } try { if (p.waitFor() != 0) { throw new IOException(String.format( "Execute the command:\n%s\nfailed:\n%s", String.join(" ", commands), out)); } } catch (InterruptedException e) { } return out.toString(); }

Target:
private static String execute( String[] commands, Map<String, String> environmentVariables, boolean log) throws IOException { ProcessBuilder pb = new ProcessBuilder(commands); pb.environment().putAll(environmentVariables); pb.redirectErrorStream(true); Process p = pb.start(); InputStream in = new BufferedInputStream(p.getInputStream()); StringBuilder out = new StringBuilder(); String s; if (log) { LOG.info(String.format("Execute command: %s", String.join(" ", commands))); } try (BufferedReader br = new BufferedReader(new InputStreamReader(in))) { while ((s = br.readLine()) != null) { out.append(s).append("\n"); if (log) { LOG.info(s); } } } try { if (p.waitFor() != 0) { throw new IOException(String.format( "Execute the command:\n%s\nfailed:\n%s", String.join(" ", commands), out)); } } catch (InterruptedException e) { } return out.toString(); }
Source:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + scope.hashCode(); result = prime * result + doneAt.hashCode(); return result; }

Target:
public int hashCode() { return Objects.hash(scope, doneAt); }
Source:
public Cohort(String name, String description, Collection patientsOrIds) { this(name, description, (Integer[]) null); if (patientsOrIds != null) { for (Object o : patientsOrIds) { if (o instanceof Patient) { CohortMember cohortMember = new CohortMember(this, (Patient) o, new Date()); members.add(cohortMember); } else if (o instanceof Integer) { CohortMember cohortMember = new CohortMember(this, new Patient((Integer) o), new Date()); members.add(cohortMember); } } } }

Target:
public Cohort(String name, String description, Collection patientsOrIds) { this(name, description, (Integer[]) null); if (patientsOrIds != null) { for (Object o : patientsOrIds) { if (o instanceof Patient) { addMembership(new CohortMembership((Patient) o)); } else if (o instanceof Integer) { addMembership(new CohortMembership(new Patient((Integer) o))); } } } }
Source:
public String doValidation(){ for(int i = 0; i < fields.size(); i++){ if(fields.get(i).errorStyleName != null){ fields.get(i).uiField.removeStyleName(fields.get(i).errorStyleName.toString()); } } for(int i = 0; i < fields.size(); i++){ ValidatorInterface<String> validator = (ValidatorInterface<String>)validatorFactory(fields.get(i).validatorReferenceName); validator.setConfiguration(fields.get(i).config); boolean valid = validator.isValid( ((AdvancedTextbox)fields.get(i).uiField).getValue() ); if(!valid){ if(fields.get(i).errorStyleName != null){ fields.get(i).uiField.addStyleName(fields.get(i).errorStyleName.toString()); } if (fields.get(i).errorMessage != null){ return fields.get(i).errorMessage; } else { return validator.getDefaultValidationMessage(); } } } return null; }

Target:
public String doValidation(){ int fieldSize = fields.size(); for (int i = 0; i < fieldSize; i++){ if (fields.get(i).errorStyleName != null){ fields.get(i).uiField.removeStyleName(fields.get(i).errorStyleName.toString()); } } for (int i = 0; i < fieldSize; i++){ ValidatorInterface<String> validator = (ValidatorInterface<String>)validatorFactory(fields.get(i).validatorReferenceName); validator.setConfiguration(fields.get(i).config); boolean valid = validator.isValid(((AdvancedTextbox)fields.get(i).uiField).getValue()); if (!valid){ if (fields.get(i).errorStyleName != null){ fields.get(i).uiField.addStyleName(fields.get(i).errorStyleName.toString()); } if (fields.get(i).errorMessage != null){ return fields.get(i).errorMessage; } else { return validator.getDefaultValidationMessage(); } } } return null; }