auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void open(NotificationContext context) { LOG.debug("MQTTDeviceNotifier open called with context {}", context); try { this.context = context; mqttClientId = UUID.randomUUID().toString(); configProperties = context.getConfig().getProperties(); callbackOperations = context.getConfig().getDefaultFieldValues(); deviceInstance = ((DeviceNotifierConfig)context.getConfig()).getDeviceMetaData(); mqttBrokerURL = setBrokerUrl(); mqttQoS = setQoS(); mqttTopic = (String) deviceInstance.getProtocol().getProperties().get(MQTTProtocol.MQTT_TOPIC); mqttOptions = getMqttConnectOptions(); connect(); } catch(MqttException ex) { throw new NotifierRuntimeException("Got exception while attempting to connect to MQTT broker", ex); } }

Target:
public void open(NotificationContext context) { LOG.debug("MQTTDeviceNotifier open called with context {}", context); try { this.context = context; mqttClientId = UUID.randomUUID().toString(); configProperties = context.getConfig().getProperties(); callbackOperation = context.getConfig().getDefaultFieldValues(); deviceInstance = ((DeviceNotifierConfig)context.getConfig()).getDeviceInstance(); mqttBrokerURL = setBrokerUrl(); mqttQoS = setQoS(); mqttTopic = (String) deviceInstance.getProtocol().getProperties().get(MQTTProtocol.MQTT_TOPIC); mqttOptions = getMqttConnectOptions(); connect(); } catch(MqttException ex) { throw new NotifierRuntimeException("Got exception while attempting to connect to MQTT broker", ex); } }
Source:
public void visitNode(AstNode expression) { List<AstNode> children = expression.getChildren(); AstNode leftOperand = children.get(0); String operator = children.get(1).getTokenValue(); AstNode rightOperand = children.get(2); if (!EXCLUDED_OPERATOR_TYPES.contains(operator) && CheckUtils.equalNodes(leftOperand, rightOperand) && !isLeftShiftBy1(leftOperand, operator)) { addIssue(rightOperand, "Identical sub-expressions on both sides of operator \"" + operator + "\".") .secondary(leftOperand, "Identical left operand."); } }

Target:
public void visitNode(AstNode expression) { List<AstNode> children = expression.getChildren(); AstNode leftOperand = children.get(0); String operator = children.get(1).getTokenValue(); AstNode rightOperand = children.get(2); if (!EXCLUDED_OPERATOR_TYPES.contains(operator) && CheckUtils.equalNodes(leftOperand, rightOperand) && !isLeftShiftBy1(leftOperand, operator)) { addIssue(rightOperand, "Correct one of the identical sub-expressions on both sides of operator \"" + operator + "\".") .secondary(leftOperand, ""); } }
Source:
private static List<MoveDescription> calculateNonCombatSea( final boolean nonCombat, final GameData data, final PlayerId player) { final Route amphibRoute = getAmphibRoute(player, data); Territory firstSeaZoneOnAmphib = null; Territory lastSeaZoneOnAmphib = null; if (amphibRoute != null) { firstSeaZoneOnAmphib = amphibRoute.getAllTerritories().get(1); lastSeaZoneOnAmphib = amphibRoute.getAllTerritories().get(amphibRoute.numberOfSteps() - 1); } final Predicate<Unit> ownedAndNotMoved = Matches.unitIsOwnedBy(player).and(Matches.unitHasNotMoved()); final var moves = new ArrayList<MoveDescription>(); for (final Territory t : data.getMap()) { if (t.isWater()) { if (t.getUnitCollection().anyMatch(Matches.unitIsLand())) { if (lastSeaZoneOnAmphib != null) { final Route r = getMaxSeaRoute(data, t, lastSeaZoneOnAmphib, player); if (r != null) { final List<Unit> unitsToMove = t.getUnitCollection().getMatches(Matches.unitIsOwnedBy(player)); moves.add(new MoveDescription(unitsToMove, r)); } } } if (nonCombat && t.getUnitCollection().anyMatch(ownedAndNotMoved)) { if (firstSeaZoneOnAmphib != null) { final Route r = getMaxSeaRoute(data, t, firstSeaZoneOnAmphib, player); if (r != null) { moves.add(new MoveDescription(t.getUnitCollection().getMatches(ownedAndNotMoved), r)); } } } } } return moves; }

Target:
private static List<MoveDescription> calculateNonCombatSea( final boolean nonCombat, final GameData data, final PlayerId player) { final Route amphibRoute = getAmphibRoute(player, data); Territory firstSeaZoneOnAmphib = null; Territory lastSeaZoneOnAmphib = null; if (amphibRoute != null) { firstSeaZoneOnAmphib = amphibRoute.getAllTerritories().get(1); lastSeaZoneOnAmphib = amphibRoute.getAllTerritories().get(amphibRoute.numberOfSteps() - 1); } final Predicate<Unit> ownedAndNotMoved = Matches.unitIsOwnedBy(player).and(Matches.unitHasNotMoved()); final var moves = new ArrayList<MoveDescription>(); for (final Territory t : data.getMap()) { if (t.isWater()) { if (t.getUnitCollection().anyMatch(Matches.unitIsLand())) { if (lastSeaZoneOnAmphib != null) { final @Nullable Route r = getMaxSeaRoute(data, t, lastSeaZoneOnAmphib, player); if (r != null) { final List<Unit> unitsToMove = t.getUnitCollection().getMatches(Matches.unitIsOwnedBy(player)); moves.add(new MoveDescription(unitsToMove, r)); } } } if (nonCombat && t.getUnitCollection().anyMatch(ownedAndNotMoved)) { if (firstSeaZoneOnAmphib != null) { final @Nullable Route r = getMaxSeaRoute(data, t, firstSeaZoneOnAmphib, player); if (r != null) { moves.add(new MoveDescription(t.getUnitCollection().getMatches(ownedAndNotMoved), r)); } } } } } return moves; }
Source:
private void startConsumer(MqttMessageConsumer subscriber) { String topic = subscriber.getTopic(); logger.debug("Starting message consumer for broker '{}' on topic '{}'", name, topic); try { client.subscribe(topic, qos); } catch (Exception e) { logger.error(String.format("Error starting consumer for broker '{}' on topic '{}'", name, topic), e); } }

Target:
private void startConsumer(MqttMessageConsumer subscriber) { String topic = subscriber.getTopic(); logger.debug("Starting message consumer for broker '{}' on topic '{}'", name, topic); try { client.subscribe(topic, qos); } catch (Exception e) { logger.error("Error starting consumer", e); } }
Source:
protected void startHttpServer(String path, int port) { try { httpServer = HttpServer.create(new InetSocketAddress(port), 0); httpServer.createContext(path, new HttpHandler() { @Override public void handle(HttpExchange httpExchange) throws IOException { byte[] response = MAPPER.writeValueAsString(metrics).getBytes(); httpExchange.sendResponseHeaders(HTTP_STATUS_OK, response.length); OutputStream os = httpExchange.getResponseBody(); os.write(response); os.close(); LOG.log(Level.INFO, "Received metrics request."); } }); httpServer.start(); } catch (IOException e) { LOG.log(Level.SEVERE, "Could not create HttpServer on port " + port, e); } }

Target:
protected void startHttpServer(String path, int port) { try { httpServer = HttpServer.create(new InetSocketAddress(port), 0); httpServer.createContext(path, new HttpHandler() { @Override public void handle(HttpExchange httpExchange) throws IOException { metricsCache.cleanUp(); byte[] response = MAPPER.writeValueAsString(metricsCache.asMap()) .getBytes(); httpExchange.sendResponseHeaders(HTTP_STATUS_OK, response.length); OutputStream os = httpExchange.getResponseBody(); os.write(response); os.close(); LOG.log(Level.INFO, "Received metrics request."); } }); httpServer.start(); } catch (IOException e) { throw new RuntimeException("Failed to create Http server on port " + port, e); } }
Source:
public SchemaRecordCheckTest() { super( new SchemaRecordCheck( configureSchemaStore(), configureIndexAssessors() ), ConsistencyReport.SchemaConsistencyReport.class, new int[0] ); }

Target:
public SchemaRecordCheckTest() { super( new SchemaRecordCheck( configureSchemaStore(), configureIndexAccessors() ), ConsistencyReport.SchemaConsistencyReport.class, new int[0] ); }
Source:
private <T extends FieldMetadataCreationContext> T create(Class<T> backend) { try { return backend.getDeclaredConstructor( BridgeDefinedField.class, FieldMetadataCreationContext.class ).newInstance( field, this ); } catch (Exception e) { throw new RuntimeException( e ); } }

Target:
private <T extends FieldMetadataCreationContext> T create(Class<T> backend) { try { return backend.getDeclaredConstructor( BridgeDefinedField.class, FieldMetadataCreationContext.class ).newInstance( field, this ); } catch (Exception e) { throw LOG.cannotCreateBridgeDefinedField( backend, e ); } }
Source:
public static CompletableFuture<MessageActionItem> showMessageRequest(LanguageServerWrapper wrapper, ShowMessageRequestParams params) { String options[] = params.getActions().stream().map(MessageActionItem::getTitle).toArray(String[]::new); CompletableFuture<MessageActionItem> future = new CompletableFuture<>(); Display.getDefault().asyncExec(() -> { Shell shell = new Shell(Display.getCurrent()); MessageDialog dialog = new MessageDialog(shell, wrapper.serverDefinition.label, null, params.getMessage(), MessageDialog.INFORMATION, 0, options); MessageActionItem result = new MessageActionItem(); int dialogResult = dialog.open(); if (dialogResult != SWT.DEFAULT) { result.setTitle(options[dialogResult]); future.complete(result); } }); return future; }

Target:
public static CompletableFuture<MessageActionItem> showMessageRequest(LanguageServerWrapper wrapper, ShowMessageRequestParams params) { String options[] = params.getActions().stream().map(MessageActionItem::getTitle).toArray(String[]::new); CompletableFuture<MessageActionItem> future = new CompletableFuture<>(); Display.getDefault().asyncExec(() -> { Shell shell = new Shell(Display.getCurrent()); MessageDialog dialog = new MessageDialog(shell, wrapper.serverDefinition.label, null, params.getMessage(), MessageDialog.INFORMATION, 0, options); MessageActionItem result = new MessageActionItem(); int dialogResult = dialog.open(); if (dialogResult != SWT.DEFAULT) { result.setTitle(options[dialogResult]); } future.complete(result); }); return future; }
Source:
public Set<CfgBlock> blocks() { return ImmutableSet.<CfgBlock>copyOf(blocks); }

Target:
public Set<CfgBlock> blocks() { return Collections.<CfgBlock>unmodifiableSet(blocks); }
Source:
private void onCommitRemoveBricks() { if (getConfirmWindow() == null) { return; } ConfirmationModel model = (ConfirmationModel) getConfirmWindow(); if (model.getProgress() != null) { return; } if (getSelectedItems() == null || getSelectedItems().isEmpty()) { return; } GlusterVolumeEntity volumeEntity = (GlusterVolumeEntity) getEntity(); ArrayList<GlusterBrickEntity> list = new ArrayList<GlusterBrickEntity>(); for (GlusterBrickEntity brick : volumeEntity.getBricks()) { if (brick.getAsyncTask() != null && brick.getAsyncTask().getStatus() == JobExecutionStatus.STARTED) { list.add(brick); } } GlusterVolumeRemoveBricksParameters parameter = new GlusterVolumeRemoveBricksParameters(volumeEntity.getId(), list); model.startProgress(null); Frontend.RunAction(VdcActionType.CommitRemoveGlusterVolumeBricks, parameter, new IFrontendActionAsyncCallback() { @Override public void executed(FrontendActionAsyncResult result) { ConfirmationModel localModel = (ConfirmationModel) result.getState(); localModel.stopProgress(); setConfirmWindow(null); } }, model); }

Target:
private void onCommitRemoveBricks() { if (getConfirmWindow() == null) { return; } ConfirmationModel model = (ConfirmationModel) getConfirmWindow(); if (model.getProgress() != null) { return; } if (getSelectedItems() == null || getSelectedItems().isEmpty()) { return; } GlusterVolumeEntity volumeEntity = (GlusterVolumeEntity) getEntity(); GlusterAsyncTask volumeTask = volumeEntity.getAsyncTask(); ArrayList<GlusterBrickEntity> list = new ArrayList<GlusterBrickEntity>(); for (GlusterBrickEntity brick : volumeEntity.getBricks()) { if (brick.getAsyncTask() != null && brick.getAsyncTask().getTaskId() != null && volumeTask != null && volumeTask.getStatus() == JobExecutionStatus.FINISHED) { list.add(brick); } } GlusterVolumeRemoveBricksParameters parameter = new GlusterVolumeRemoveBricksParameters(volumeEntity.getId(), list); model.startProgress(null); Frontend.RunAction(VdcActionType.CommitRemoveGlusterVolumeBricks, parameter, new IFrontendActionAsyncCallback() { @Override public void executed(FrontendActionAsyncResult result) { ConfirmationModel localModel = (ConfirmationModel) result.getState(); localModel.stopProgress(); setConfirmWindow(null); } }, model); }
Source:
public <T> T lookup(C criteria, F filter) { Objects.requireNonNull(criteria); T service = delegate.lookup(criteria, filter); if (service != null) { return service; } final long waitUntil = System.currentTimeMillis() + this.waitTimeMs; while (service == null && uptimeSupplier.get() < this.gracePeriodInMs || System.currentTimeMillis() < waitUntil) { try { Thread.sleep(this.lookupDelayMs); } catch (InterruptedException e) { LOG.error("Interrupted while waiting for service with search criteria " + criteria + " to become available in the service registry. Aborting."); return null; } service = delegate.lookup(criteria, filter); if (service != null) { return service; } } return null; }

Target:
public <T> T lookup(C criteria, F filter) { Objects.requireNonNull(criteria); T service = delegate.lookup(criteria, filter); if (service != null) { return service; } final long waitUntil = System.currentTimeMillis() + this.waitTimeMs; while (uptimeSupplier.get() < this.gracePeriodInMs || System.currentTimeMillis() < waitUntil) { try { Thread.sleep(this.lookupDelayMs); } catch (InterruptedException e) { LOG.error("Interrupted while waiting for service with search criteria " + criteria + " to become available in the service registry. Aborting."); return null; } service = delegate.lookup(criteria, filter); if (service != null) { return service; } } return null; }
Source:
private Bundle getAuthTokenFromAccountManager(final AuthenticationRequest request, final Bundle requestBundle) throws AuthenticationException { final Account targetAccount = getTargetAccount(request); Bundle bundleResult = null; if (targetAccount != null) { try { final AccountManagerFuture<Bundle> result = mAcctManager.getAuthToken(targetAccount, AuthenticationConstants.Broker.AUTHTOKEN_TYPE, requestBundle, false, null, mHandler); Logger.v(TAG, "Received result from broker"); bundleResult = result.getResult(); } catch (OperationCanceledException e) { Logger.e(TAG, AUTHENTICATOR_CANCELS_REQUEST, "", ADALError.AUTH_FAILED_CANCELLED, e); } catch (AuthenticatorException e) { Logger.e(TAG, AUTHENTICATOR_CANCELS_REQUEST, "", ADALError.BROKER_AUTHENTICATOR_NOT_RESPONDING); if (!StringExtensions.isNullOrBlank(e.getMessage()) && e.getMessage().contains(ADALError.DEVICE_CONNECTION_IS_NOT_AVAILABLE.toString())) { throw new AuthenticationException(ADALError.DEVICE_CONNECTION_IS_NOT_AVAILABLE, e.getMessage()); } } catch (IOException e) { Logger.e(TAG, AUTHENTICATOR_CANCELS_REQUEST, "", ADALError.BROKER_AUTHENTICATOR_IO_EXCEPTION); } Logger.v(TAG, "Returning result from broker"); return bundleResult; } else { Logger.v(TAG, "Target account is not found"); } return null; }

Target:
private Bundle getAuthTokenFromAccountManager(final AuthenticationRequest request, final Bundle requestBundle) throws AuthenticationException { final Account targetAccount = getTargetAccount(request); Bundle bundleResult = null; if (targetAccount != null) { try { final AccountManagerFuture<Bundle> result = mAcctManager.getAuthToken(targetAccount, AuthenticationConstants.Broker.AUTHTOKEN_TYPE, requestBundle, false, null, mHandler); Logger.v(TAG, "Received result from broker"); bundleResult = result.getResult(); } catch (OperationCanceledException e) { Logger.e(TAG, AUTHENTICATOR_CANCELS_REQUEST, "", ADALError.AUTH_FAILED_CANCELLED, e); } catch (AuthenticatorException e) { Logger.e(TAG, AUTHENTICATOR_CANCELS_REQUEST, "", ADALError.BROKER_AUTHENTICATOR_NOT_RESPONDING); } catch (IOException e) { Logger.e(TAG, AUTHENTICATOR_CANCELS_REQUEST, "", ADALError.BROKER_AUTHENTICATOR_IO_EXCEPTION); } Logger.v(TAG, "Returning result from broker"); return bundleResult; } else { Logger.v(TAG, "Target account is not found"); } return null; }
Source:
private static OutputFormat<BaseRow> createEncoderOutputFormat( Encoder<BaseRow> encoder, Path path) { return new OutputFormat<BaseRow>() { private FSDataOutputStream output; @Override public void configure(Configuration parameters) { } @Override public void open(int taskNumber, int numTasks) throws IOException { this.output = path.getFileSystem() .create(path, FileSystem.WriteMode.OVERWRITE); } @Override public void writeRecord(BaseRow record) throws IOException { encoder.encode(record, output); } @Override public void close() throws IOException { this.output.flush(); this.output.close(); } }; }

Target:
private static OutputFormat<BaseRow> createEncoderOutputFormat( Encoder<BaseRow> encoder, Path path) { return new OutputFormat<BaseRow>() { private static final long serialVersionUID = 1L; private transient FSDataOutputStream output; @Override public void configure(Configuration parameters) { } @Override public void open(int taskNumber, int numTasks) throws IOException { this.output = path.getFileSystem() .create(path, FileSystem.WriteMode.OVERWRITE); } @Override public void writeRecord(BaseRow record) throws IOException { encoder.encode(record, output); } @Override public void close() throws IOException { this.output.flush(); this.output.close(); } }; }
Source:
public void testDuplicateClientIdSet() throws Exception { ActiveMQConnectionFactory activeMQConnectionFactory = (ActiveMQConnectionFactory) cf; Connection con = cf.createConnection(); Connection con2 = cf.createConnection(); try { con.setClientID("valid"); con2.setClientID("valid"); fail("Should have failed for duplicate clientId"); } catch (Exception e) { assertEquals(1, duplicateCount.get()); throw e; } finally { activeMQConnectionFactory.close(); } }

Target:
public void testDuplicateClientIdSet() throws Exception { ActiveMQConnectionFactory activeMQConnectionFactory = (ActiveMQConnectionFactory) cf; Connection con = cf.createConnection(); Connection con2 = cf.createConnection(); try { con.setClientID("valid"); con2.setClientID("valid"); fail("Should have failed for duplicate clientId"); } catch (InvalidClientIDException e) { assertEquals(1, duplicateCount.get()); } finally { activeMQConnectionFactory.close(); } }
Source:
public void validate_shouldFailValidationIfVisitDateBeforeBirthDate() { VisitService vs = Context.getVisitService(); Visit visit = new Visit(); visit.setVisitType(vs.getVisitType(1)); visit.setPatient(Context.getPatientService().getPatient(2)); Calendar c = Calendar.getInstance(); c.set(1974, 4, 8); visit.setStartDatetime(c.getTime()); Errors errors = new BindException(visit, "visit"); new VisitValidator().validate(visit, errors); assertTrue(errors.hasFieldErrors("startDatetime")); }

Target:
public void validate_shouldFailValidationIfVisitDateBeforeBirthDate() { Visit visit = new Visit(); Patient patient = new Patient(); calendar.set(1974, 4, 8); patient.setBirthdate(calendar.getTime()); patient.setBirthdateEstimated(false); visit.setPatient(patient); calendar.set(1974, 4, 7); visit.setStartDatetime(calendar.getTime()); Errors errors = new BindException(visit, "visit"); new VisitValidator().validate(visit, errors); assertThat(errors, hasFieldErrors("startDatetime", "Visit.startDateCannotFallBeforeTheBirthDateOfTheSamePatient")); }
Source:
public void startUp() { cacheManager = TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration()); assertEquals(cacheManager.getCache().size(), 0); TestingUtil.registerTranscoders(cacheManager, new ProtostreamBinaryTranscoder()); hotRodServer = HotRodTestingUtil.startHotRodServer(cacheManager, 19711); }

Target:
public void startUp() { cacheManager = TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration()); assertEquals(cacheManager.getCache().size(), 0); hotRodServer = HotRodTestingUtil.startHotRodServer(cacheManager, 19711); }
Source:
private ClientCnxnSocket getClientCnxnSocket() throws IOException { String clientCnxnSocketName = getClientConfig().getProperty(ZKClientConfig.ZOOKEEPER_CLIENT_CNXN_SOCKET); if (clientCnxnSocketName == null) { clientCnxnSocketName = ClientCnxnSocketNIO.class.getName(); } try { Constructor<?> clientCxnConstructor = Class.forName(clientCnxnSocketName).getDeclaredConstructor(ZKClientConfig.class); ClientCnxnSocket clientCxnSocket = (ClientCnxnSocket) clientCxnConstructor.newInstance(getClientConfig()); return clientCxnSocket; } catch (Exception e) { IOException ioe = new IOException("Couldn't instantiate " + clientCnxnSocketName, e); throw ioe; } }

Target:
private ClientCnxnSocket getClientCnxnSocket() throws IOException { String clientCnxnSocketName = getClientConfig().getProperty(ZKClientConfig.ZOOKEEPER_CLIENT_CNXN_SOCKET); if (clientCnxnSocketName == null) { clientCnxnSocketName = ClientCnxnSocketNIO.class.getName(); } try { Constructor<?> clientCxnConstructor = Class.forName(clientCnxnSocketName) .getDeclaredConstructor(ZKClientConfig.class); ClientCnxnSocket clientCxnSocket = (ClientCnxnSocket) clientCxnConstructor.newInstance(getClientConfig()); return clientCxnSocket; } catch (Exception e) { throw new IOException("Couldn't instantiate " + clientCnxnSocketName, e); } }
Source:
public int compare(ItemStack o1, ItemStack o2) { List<DataManipulator<?, ?>> manipulators = Lists.newArrayList(o2.getContainers()); for (final DataManipulator<?, ?> manipulator : o1.getContainers()) { if (manipulators.contains(manipulator)) { manipulators.remove(manipulator); } else if (!isIgnored(manipulators, manipulator)) { return -1; } } return manipulators.size(); }

Target:
public int compare(ItemStack o1, ItemStack o2) { Set<DataManipulator<?, ?>> manipulators = new LinkedHashSet<>(o2.getContainers()); for (final DataManipulator<?, ?> manipulator : o1.getContainers()) { if (manipulators.contains(manipulator)) { manipulators.remove(manipulator); } else if (!isIgnored(manipulators, manipulator)) { return -1; } } return manipulators.size(); }
Source:
public StateTransitionException failed(Throwable t) { if (st.done()) { return null; } st.failed(); if (t == null) { return null; } logger.error("{} failed.", action); if(t instanceof StateTransitionException) { return (StateTransitionException) t; } return new StateTransitionException(t); }

Target:
public StateTransitionException failed(Throwable t) { if (st.done()) { if (t != null) { throw new AssertionError("Throwable cannot be null if Transition is done."); } return null; } st.failed(); if (t == null) { return null; } logger.error("{} failed.", action); if(t instanceof StateTransitionException) { return (StateTransitionException) t; } return new StateTransitionException(t); }
Source:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest)request; HttpServletResponse res = (HttpServletResponse)response; if (FiltersHelper.isAuthenticated(req)) { chain.doFilter(request, response); } else { @SuppressWarnings("unchecked") List<String> schemes = (List<String>) req.getAttribute(FiltersHelper.Constants.REQUEST_SCHEMES_KEY); if (schemes == null) { schemes = Collections.emptyList(); } Set<String> allSchemes = new HashSet<>(schemes); if (additionalSchemes != null) { allSchemes.addAll(additionalSchemes); } for (String scheme: allSchemes) { res.setHeader(FiltersHelper.Constants.HEADER_WWW_AUTHENTICATE, scheme); } if (req.getContextPath().endsWith("/api")) { req.setAttribute(SessionConstants.SSO_AUTHENTICATION_ERR, Boolean.TRUE); req.getRequestDispatcher(String.format(ERROR_URL_FORMAT, req.getAttribute(SessionConstants.SSO_AUTHENTICATION_ERR_MSG))).forward(req, res); } else { res.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } }

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest)request; HttpServletResponse res = (HttpServletResponse)response; if (FiltersHelper.isAuthenticated(req)) { chain.doFilter(request, response); } else { @SuppressWarnings("unchecked") List<String> schemes = (List<String>) req.getAttribute(FiltersHelper.Constants.REQUEST_SCHEMES_KEY); if (schemes == null) { schemes = Collections.emptyList(); } Set<String> allSchemes = new HashSet<>(schemes); if (additionalSchemes != null) { allSchemes.addAll(additionalSchemes); } for (String scheme: allSchemes) { res.setHeader(FiltersHelper.Constants.HEADER_WWW_AUTHENTICATE, scheme); } String errMsg = (String) req.getAttribute(SessionConstants.SSO_AUTHENTICATION_ERR_MSG); if (StringUtils.isEmpty(errMsg)) { res.sendError(HttpServletResponse.SC_UNAUTHORIZED); } else { res.sendError(HttpServletResponse.SC_UNAUTHORIZED, errMsg); } } }
Source:
protected List<EmailWrapper> prepareMailToBeSent() { FeedbackSessionAttributes feedbackObject = FeedbackSessionsLogic.inst() .getFeedbackSession(feedbackSessionName, courseId); log.info("Fetching feedback session object for feedback session name : " + feedbackSessionName + " and course : " + courseId); if (feedbackObject == null) { log.severe("Feedback session object for feedback session name : " + feedbackSessionName + " for course : " + courseId + " could not be fetched"); return null; } return new EmailGenerator().generateFeedbackSessionUnpublishedEmails(feedbackObject); }

Target:
protected List<EmailWrapper> prepareMailToBeSent() { FeedbackSessionAttributes feedbackSession = FeedbackSessionsLogic.inst() .getFeedbackSession(feedbackSessionName, courseId); if (feedbackSession == null) { log.severe("Feedback session object for feedback session name : " + feedbackSessionName + " for course : " + courseId + " could not be fetched while sending unpublished emails"); return null; } return new EmailGenerator().generateFeedbackSessionUnpublishedEmails(feedbackSession); }
Source:
public static Option startRowOpt() { final Option o = new Option(START_ROW_OPT, "begin-row", true, "begin row (NOT) inclusive"); o.setArgName("begin-row"); return o; }

Target:
public static Option startRowOpt() { final Option o = new Option(START_ROW_OPT, "begin-row", true, "begin row (exclusive)"); o.setArgName("begin-row"); return o; }
Source:
public DelegatingResourceDescription getRepresentationDescription(Representation rep) { if (rep instanceof DefaultRepresentation) { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addProperty("display"); description.addProperty("uuid"); description.addProperty("allergyId"); description.addProperty("allergen"); description.addProperty("severity"); description.addProperty("comment"); description.addProperty("reactions"); description.addProperty("patient"); description.addSelfLink(); description.addLink("full", ".?v=" + RestConstants.REPRESENTATION_FULL); return description; } else if (rep instanceof FullRepresentation) { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addProperty("display"); description.addProperty("uuid"); description.addProperty("allergyId"); description.addProperty("allergen"); description.addProperty("severity"); description.addProperty("comment"); description.addProperty("reactions"); description.addProperty("patient"); description.addProperty("voided"); description.addProperty("auditInfo"); description.addSelfLink(); return description; } return null; }

Target:
public DelegatingResourceDescription getRepresentationDescription(Representation rep) { if (rep instanceof DefaultRepresentation) { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addProperty("display"); description.addProperty("uuid"); description.addProperty("allergen", rep); description.addProperty("severity", rep); description.addProperty("comment", rep); description.addProperty("reactions", rep); description.addProperty("patient", rep); description.addSelfLink(); description.addLink("full", ".?v=" + RestConstants.REPRESENTATION_FULL); return description; } else if (rep instanceof FullRepresentation) { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addProperty("display"); description.addProperty("uuid"); description.addProperty("allergen", rep); description.addProperty("severity", rep); description.addProperty("comment", rep); description.addProperty("reactions", rep); description.addProperty("patient", rep); description.addProperty("voided"); description.addProperty("auditInfo"); description.addSelfLink(); return description; } return null; }
Source:
public boolean isMember(User user) { if (user == null || user.getPerson() == null) { return false; } return new ActivePhdProcessesGroup().isMember(user) || (user.getPerson().getStudent() != null && user.getPerson() .getStudent().hasActiveRegistrations()); }

Target:
public boolean isMember(User user) { if (user == null || user.getPerson() == null) { return false; } return (user.getPerson().getStudent() != null && user.getPerson().getStudent().hasActiveRegistrations()) || new ActivePhdProcessesGroup().isMember(user); }
Source:
public boolean act(float delta) { if (firstStart) { firstStart = false; webConnection = webConnectionFactory.getWebConnection(url, this); boolean successfullyAddedConnection = StageActivity.webConnectionHolder.addConnectionToList(webConnection); if (!successfullyAddedConnection) { userVariable.setValue(ERROR_TOO_MANY_REQUESTS); return true; } boolean successfullySentWebRequest = webConnection.sendWebRequest(); if (!successfullySentWebRequest) { StageActivity.webConnectionHolder.removeConnectionFromList(webConnection); userVariable.setValue(ERROR_BAD_REQUEST); return true; } } if (isRequestFinished) { userVariable.setValue(response); StageActivity.webConnectionHolder.removeConnectionFromList(webConnection); return true; } time += delta; if (time >= TIMEOUT_DURATION) { userVariable.setValue(ERROR_TIMEOUT); StageActivity.webConnectionHolder.removeConnectionFromList(webConnection); return true; } return false; }

Target:
public boolean act(float delta) { if (userVariable == null) { return true; } if (requestStatus == NOT_SENT) { requestStatus = WAITING; webConnection = webConnectionFactory.createWebConnection(url, this); if (!StageActivity.stageListener.webConnectionHolder.addConnection(webConnection)) { userVariable.setValue(ERROR_TOO_MANY_REQUESTS); return true; } webConnection.sendWebRequest(); } if (requestStatus == FINISHED) { userVariable.setValue(response); StageActivity.stageListener.webConnectionHolder.removeConnection(webConnection); return true; } return false; }
Source:
public void testRoles() { final String roles = "[role1, role2, role with space]"; final AuthenticationInfo authenticationInfo = new AuthenticationInfo("foo", roles, "bar"); assertEquals(authenticationInfo.getRoles(), new ArrayList<>(Arrays.asList("role1", "role2", "role with space"))); }

Target:
public void testRoles() { final String roles = "[role1, role2, role with space]"; final AuthenticationInfo authenticationInfo = new AuthenticationInfo("foo", roles, "bar"); assertEquals( new ArrayList<>(Arrays.asList("role1", "role2", "role with space")), authenticationInfo.getRoles()); }
Source:
private boolean shouldRequireClientSaslAuth() { String sessionRequireClientSASLAuth = System.getProperty("zookeeper.sessionRequireClientSASLAuth"); if (sessionRequireClientSASLAuth == null) { return false; } else { return sessionRequireClientSASLAuth.equals("true"); } }

Target:
private static boolean shouldRequireClientSaslAuth() { return Boolean.getBoolean(SESSION_REQUIRE_CLIENT_SASL_AUTH); }
Source:
public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (!(getActivity() instanceof PhoneActivity)) { throw new IllegalStateException("Activity must implement PhoneVerificationHandler"); } mVerifier = (PhoneActivity) getActivity(); if (savedInstanceState != null) { return; } Bundle params = getArguments().getBundle(ExtraConstants.PARAMS); List<String> whitelistedCountryCodes = null; List<String> blacklistedCountryCodes = null; String phone = null; String countryIso = null; String nationalNumber = null; if (params != null) { phone = params.getString(ExtraConstants.PHONE); countryIso = params.getString(ExtraConstants.COUNTRY_ISO); nationalNumber = params.getString(ExtraConstants.NATIONAL_NUMBER); } if (!TextUtils.isEmpty(countryIso) && !TextUtils.isEmpty(nationalNumber)) { PhoneNumber phoneNumber = PhoneNumberUtils.getPhoneNumber(countryIso, nationalNumber); setPhoneNumber(phoneNumber); setCountryCode(phoneNumber); } else if (!TextUtils.isEmpty(countryIso)) { setCountryCode(new PhoneNumber( "", countryIso, String.valueOf(PhoneNumberUtils.getCountryCode(countryIso)))); } else if (!TextUtils.isEmpty(phone)) { PhoneNumber phoneNumber = PhoneNumberUtils.getPhoneNumber(phone); setPhoneNumber(phoneNumber); setCountryCode(phoneNumber); } else if (getFlowParams().enableHints) { showPhoneAutoCompleteHint(); } }

Target:
public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (!(getActivity() instanceof PhoneActivity)) { throw new IllegalStateException("Activity must implement PhoneVerificationHandler"); } mVerifier = (PhoneActivity) getActivity(); if (savedInstanceState != null) { return; } Bundle params = getArguments().getBundle(ExtraConstants.PARAMS); String phone = null; String countryIso = null; String nationalNumber = null; if (params != null) { phone = params.getString(ExtraConstants.PHONE); countryIso = params.getString(ExtraConstants.COUNTRY_ISO); nationalNumber = params.getString(ExtraConstants.NATIONAL_NUMBER); } if (!TextUtils.isEmpty(countryIso) && !TextUtils.isEmpty(nationalNumber)) { PhoneNumber phoneNumber = PhoneNumberUtils.getPhoneNumber(countryIso, nationalNumber); setPhoneNumber(phoneNumber); setCountryCode(phoneNumber); } else if (!TextUtils.isEmpty(countryIso)) { setCountryCode(new PhoneNumber( "", countryIso, String.valueOf(PhoneNumberUtils.getCountryCode(countryIso)))); } else if (!TextUtils.isEmpty(phone)) { PhoneNumber phoneNumber = PhoneNumberUtils.getPhoneNumber(phone); setPhoneNumber(phoneNumber); setCountryCode(phoneNumber); } else if (getFlowParams().enableHints) { showPhoneAutoCompleteHint(); } }
Source:
public void shouldFailGettingCreatedCoupaInstance() throws Exception { onRequest() .havingMethodEqualTo("POST") .havingPathEqualTo("/gdc/projects/PROJECT_ID/connectors/coupa/integration/config/settings/instances") .respond() .withStatus(201) .withBody("{\"uri\":\"/coupa/instance/uri/123\"}"); onRequest() .havingMethodEqualTo("GET") .havingPathEqualTo("/coupa/instance/uri/123") .respond() .withStatus(404); connectors.createCoupaInstance(project, new CoupaInstance("i1", "url", "key")); }

Target:
public void shouldFailGettingCreatedCoupaInstance() throws Exception { onRequest() .havingMethodEqualTo("POST") .havingPathEqualTo("/gdc/projects/PROJECT_ID/connectors/coupa/integration/config/settings/instances") .respond() .withStatus(201) .withBody("{\"uri\":\"/gdc/projects/PROJECT_ID/connectors/coupa/integration/config/settings/instances/123\"}"); onRequest() .havingMethodEqualTo("GET") .havingPathEqualTo("/gdc/projects/PROJECT_ID/connectors/coupa/integration/config/settings/instances/123") .respond() .withStatus(404); connectors.createCoupaInstance(project, new CoupaInstance("i1", "url", "key")); }
Source:
public AbstractDifferenceFilter() { super(); setPredicateWhenSelected(); setPredicateWhenUnselected(); }

Target:
public AbstractDifferenceFilter() { super(); }
Source:
private ResponseHandler<Object> getImageResponseHandler(final String filename, final ArchiveCompression compression) throws FileNotFoundException { return new ResponseHandler<Object>() { @Override public Object handleResponse(HttpResponse response) throws IOException { try (InputStream stream = response.getEntity().getContent(); OutputStream out = compression.wrapOutputStream(new FileOutputStream(filename))) { IOUtils.copy(stream, out, 65536); } return null; } }; }

Target:
private ResponseHandler<Object> getImageResponseHandler(final String filename, final ArchiveCompression compression) throws FileNotFoundException { return new ResponseHandler<Object>() { @Override public Object handleResponse(HttpResponse response) throws IOException { try (InputStream stream = response.getEntity().getContent(); OutputStream out = compression.wrapOutputStream(new FileOutputStream(filename))) { IOUtils.copy(stream, out, COPY_BUFFER_SIZE); } return null; } }; }
Source:
private void writeBack() { ArrayList<CacheObject> list = cache.getAllChanged(); Collections.sort(list); for (CacheObject aList : list) { writeBack(aList); } }

Target:
private void writeBack() { ArrayList<CacheObject> list = cache.getAllChanged(); Collections.sort(list); for (CacheObject cacheObject : list) { writeBack(cacheObject); } }
Source:
private void reset() throws Exception { if ( (client.getState() == CuratorFrameworkState.STARTED) && (state.get() == State.STARTED) ) { BackgroundCallback backgroundCallback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { outstanding.decrementAndGet(); if ( (event.getType() == CuratorEventType.GET_CONFIG) && (event.getResultCode() == KeeperException.Code.OK.intValue()) ) { processConfigData(event.getData()); } } }; outstanding.incrementAndGet(); try { client.getConfig().usingWatcher(this).inBackground(backgroundCallback).forEnsemble(); } catch ( Exception e ) { outstanding.decrementAndGet(); throw e; } } }

Target:
private void reset() throws Exception { if ( (client.getState() == CuratorFrameworkState.STARTED) && (state.get() == State.STARTED) ) { BackgroundCallback backgroundCallback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { outstanding.decrementAndGet(); if ( (event.getType() == CuratorEventType.GET_CONFIG) && (event.getResultCode() == KeeperException.Code.OK.intValue()) ) { processConfigData(event.getData()); } } }; outstanding.incrementAndGet(); try { client.getConfig().usingWatcher(this).inBackground(backgroundCallback).forEnsemble(); outstanding.incrementAndGet(); } finally { outstanding.decrementAndGet(); } } }
Source:
void verifyModel() { ModelVerifier verifier = new ModelVerifier(project); verify(project).getSubprojects(); String commandHandlerTypeName = ModelVerifierTestEnv.AnyCommandHandler.class.getName(); String aggregateTypeName = ModelVerifierTestEnv.Int32HandlerAggregate.class.getName(); String procManTypeName = ModelVerifierTestEnv.Int64HandlerProcMan.class.getName(); CommandHandlers spineModel = CommandHandlers.newBuilder() .addCommandHandlingTypes(commandHandlerTypeName) .addCommandHandlingTypes(aggregateTypeName) .addCommandHandlingTypes(procManTypeName) .build(); verifier.verify(spineModel); }

Target:
void verifyModel() { ModelVerifier verifier = new ModelVerifier(project); verify(project).getSubprojects(); String commandHandlerTypeName = AnyCommandHandler.class.getName(); String aggregateTypeName = Int32HandlerAggregate.class.getName(); String procManTypeName = Int64HandlerProcMan.class.getName(); CommandHandlers spineModel = CommandHandlers.newBuilder() .addCommandHandlingTypes(commandHandlerTypeName) .addCommandHandlingTypes(aggregateTypeName) .addCommandHandlingTypes(procManTypeName) .build(); verifier.verify(spineModel); }
Source:
private void initCommentVisibilityStrategy(Button expandAll, Button collapseAll) { CommentVisibilityStrategy commentVisibilityStrategy = CommentVisibilityStrategy.EXPAND_RECENT; if (Gerrit.isSignedIn()) { commentVisibilityStrategy = Gerrit.getUserAccount() .getGeneralPreferences().getCommentVisibilityStrategy(); } long AGE = 7 * 24 * 60 * 60 * 1000L; Timestamp aged = new Timestamp(System.currentTimeMillis() - AGE); int n = getWidgetCount(); for (int i = 0; i < n; i++) { Message msg = (Message) getWidget(i); boolean isRecent; if (i == n - 1) { isRecent = true; } else { isRecent = msg.getMessageInfo().date().after(aged); } boolean isOpen = false; switch (commentVisibilityStrategy) { case COLLAPSE_ALL: break; case EXPAND_ALL: isOpen = true; break; case EXPAND_MOST_RECENT: isOpen = i == n - 1; break; case EXPAND_RECENT: default: isOpen = isRecent; break; } msg.setOpen(isOpen); } if (commentVisibilityStrategy == COLLAPSE_ALL) { expandAll.setVisible(true); collapseAll.setVisible(false); } else if (commentVisibilityStrategy == EXPAND_ALL) { expandAll.setVisible(false); collapseAll.setVisible(true); } }

Target:
private void initCommentVisibilityStrategy(Button expandAll, Button collapseAll) { CommentVisibilityStrategy commentVisibilityStrategy = CommentVisibilityStrategy.EXPAND_RECENT; if (Gerrit.isSignedIn()) { commentVisibilityStrategy = Gerrit.getUserAccount() .getGeneralPreferences().getCommentVisibilityStrategy(); } Timestamp aged = new Timestamp(System.currentTimeMillis() - AGE); int n = getWidgetCount(); for (int i = 0; i < n; i++) { Message msg = (Message) getWidget(i); boolean isRecent = (i == n - 1) ? true : msg.getMessageInfo().date().after(aged); boolean isOpen = false; switch (commentVisibilityStrategy) { case COLLAPSE_ALL: break; case EXPAND_ALL: isOpen = true; break; case EXPAND_MOST_RECENT: isOpen = i == n - 1; break; case EXPAND_RECENT: default: isOpen = isRecent; break; } msg.setOpen(isOpen); } if (commentVisibilityStrategy == COLLAPSE_ALL) { expandAll.setVisible(true); collapseAll.setVisible(false); } else if (commentVisibilityStrategy == EXPAND_ALL) { expandAll.setVisible(false); collapseAll.setVisible(true); } }
Source:
@Override public Object evaluate(DeferredObject[] arguments) throws HiveException { assert (arguments.length == 2); if (arguments[0].get() == null || arguments[1].get() == null) { return null; } Text s = (Text) converters[0].convert(arguments[0].get()); ArrayList<Text> result = new ArrayList<Text>(); int index = 0; Map<Integer, String> privs = privsMap.getPrivilegeMap(); if (constPattern == null) { Text regex = (Text) converters[1].convert(arguments[1].get()); for (String str : s.toString().split(regex.toString(), -1)) { if ("1".equals(str)) { result.add(new Text(privs.get(index))); } index++; } } else { for (String str : constPattern.split(s.toString(), -1)) { if ("1".equals(str)) { result.add(new Text(privs.get(index))); } index++; } } return result; }

Target:
@Override public Object evaluate(DeferredObject[] arguments) throws HiveException { assert (arguments.length == 1); if (arguments[0].get() == null) { return null; } Text s = (Text) converters[0].convert(arguments[0].get()); ArrayList<Text> result = new ArrayList<Text>(); int index = 0; Map<Integer, String> privs = privsMap.getPrivilegeMap(); for (String str : s.toString().split(" ", -1)) { if ("1".equals(str)) { result.add(new Text(privs.get(index))); } index++; } return result; }
Source:
public ServerResponse preProcess(HttpRequest request, ResourceMethod method) throws Failure, WebApplicationException { HttpSession httpSession = null; ServerResponse response = null; boolean successful = false; HttpHeaders headers = request.getHttpHeaders(); boolean preferPersistentAuth = checkPersistentAuthentication(headers); boolean hasAuthorizationHeader = checkAuthorizationHeader(headers); Integer customHttpSessionTtl = getCustomHttpSessionTtl(headers); httpSession = getCurrentSession(false); if (validator != null && httpSession != null && !httpSession.isNew() && !hasAuthorizationHeader) { successful = executeSessionValidation(httpSession, preferPersistentAuth); } else { if (validator != null && httpSession != null && !httpSession.isNew()) { httpSession.invalidate(); httpSession = getCurrentSession(true); } String engineSessionId = SessionUtils.generateEngineSessionId(); successful = executeBasicAuthentication(headers, engineSessionId, preferPersistentAuth); if (successful && httpSession == null) { httpSession = getCurrentSession(true); } if (httpSession != null) { SessionUtils.setEngineSessionId(httpSession, engineSessionId); } if (successful && preferPersistentAuth) { if (httpSession != null && customHttpSessionTtl != null) { httpSession.setMaxInactiveInterval( customHttpSessionTtl.intValue() * SECONDS_IN_MINUTE); } } } if (!successful) { response = challenge(); if (httpSession != null) { httpSession.invalidate(); } } return response; }

Target:
public ServerResponse preProcess(HttpRequest request, ResourceMethod method) throws Failure, WebApplicationException { HttpSession httpSession = null; ServerResponse response = null; boolean successful = false; HttpHeaders headers = request.getHttpHeaders(); boolean preferPersistentAuth = checkPersistentAuthentication(headers); boolean hasAuthorizationHeader = checkAuthorizationHeader(headers); Integer customHttpSessionTtl = getCustomHttpSessionTtl(headers); httpSession = getCurrentSession(false); if (validator != null && httpSession != null && !hasAuthorizationHeader) { successful = executeSessionValidation(httpSession, preferPersistentAuth); } else { if (validator != null && httpSession != null) { httpSession.invalidate(); httpSession = getCurrentSession(true); } String engineSessionId = SessionUtils.generateEngineSessionId(); successful = executeBasicAuthentication(headers, engineSessionId, preferPersistentAuth); if (successful && preferPersistentAuth) { if (httpSession == null) { httpSession = getCurrentSession(true); } if (httpSession != null && customHttpSessionTtl != null) { httpSession.setMaxInactiveInterval( customHttpSessionTtl.intValue() * SECONDS_IN_MINUTE); } } if (successful && httpSession != null) { SessionUtils.setEngineSessionId(httpSession, engineSessionId); } } if (!successful) { response = challenge(); if (httpSession != null) { httpSession.invalidate(); } } return response; }
Source:
public @ResponseBody CertifiedProductSearchDetails getCertifiedProductByChplProductNumberBasic( @PathVariable("year") final String year, @PathVariable("testingLab") final String testingLab, @PathVariable("certBody") final String certBody, @PathVariable("vendorCode") final String vendorCode, @PathVariable("productCode") final String productCode, @PathVariable("versionCode") final String versionCode, @PathVariable("icsCode") final String icsCode, @PathVariable("addlSoftwareCode") final String addlSoftwareCode, @PathVariable("certDateCode") final String certDateCode) throws EntityRetrievalException { String chplProductNumber = chplProductNumberUtil.getChplProductNumber(year, testingLab, certBody, vendorCode, productCode, versionCode, icsCode, addlSoftwareCode, certDateCode); CertifiedProductSearchDetails certifiedProduct = cpdManager.getCertifiedProductDetailsBasicByChplProductNumber(chplProductNumber); certifiedProduct = validateCertifiedProduct(certifiedProduct); removeNonBasicCertifiedProductSearchDetails(certifiedProduct); return certifiedProduct; }

Target:
CertifiedProductSearchBasicDetails getCertifiedProductByChplProductNumberBasic( @PathVariable("year") final String year, @PathVariable("testingLab") final String testingLab, @PathVariable("certBody") final String certBody, @PathVariable("vendorCode") final String vendorCode, @PathVariable("productCode") final String productCode, @PathVariable("versionCode") final String versionCode, @PathVariable("icsCode") final String icsCode, @PathVariable("addlSoftwareCode") final String addlSoftwareCode, @PathVariable("certDateCode") final String certDateCode) throws EntityRetrievalException { String chplProductNumber = chplProductNumberUtil.getChplProductNumber(year, testingLab, certBody, vendorCode, productCode, versionCode, icsCode, addlSoftwareCode, certDateCode); CertifiedProductSearchDetails certifiedProduct = cpdManager.getCertifiedProductDetailsBasicByChplProductNumber(chplProductNumber); return mapCertifiedProductDetailsToBasic.apply(certifiedProduct); }
Source:
synchronized LocalHub getLocalServerComponent() { if (instance == null) { instance = new LocalHub(); instance.setHost(new NetworkUtils().getIpOfLoopBackIp4()); int configHubPort = Integer.parseInt(Config.getConfigProperty(ConfigProperty.SELENIUM_PORT)); int hubPort = PortProber.pollPort(configHubPort) ? configHubPort : PortProber.findFreePort(); instance.setPort(hubPort); LauncherOptions launcherOptions = new LauncherOptionsImpl() .setFileDownloadCheckTimeStampOnInvocation(false).setFileDownloadCleanupOnInvocation(false); instance.setLauncher(new ThreadedLauncher(new String[] { "-role", "hub", "-port", String.valueOf(instance.getPort()), "-host", instance.getHost() }, launcherOptions)); } return instance; }

Target:
synchronized LocalHub getLocalServerComponent() { if (instance == null) { instance = new LocalHub(); instance.setHost(new NetworkUtils().getIpOfLoopBackIp4()); int hubPort = PortProber.findFreePort(); instance.setPort(hubPort); Config.setConfigProperty(ConfigProperty.SELENIUM_PORT, Integer.toString(hubPort)); LauncherOptions launcherOptions = new LauncherOptionsImpl() .setFileDownloadCheckTimeStampOnInvocation(false).setFileDownloadCleanupOnInvocation(false); instance.setLauncher(new ThreadedLauncher(new String[] { "-role", "hub", "-port", String.valueOf(instance.getPort()), "-host", instance.getHost() }, launcherOptions)); } return instance; }