auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public List<HasMetadata> parse(InternalRecipe recipe) throws ValidationException, InfrastructureException { String content = recipe.getContent(); String contentType = recipe.getContentType(); checkNotNull(contentType, "Recipe content type must not be null"); switch (contentType) { case "application/x-yaml": case "text/yaml": case "text/x-yaml": break; default: throw new ValidationException( "Provided environment recipe content type '" + contentType + "' is unsupported. Supported values are: " + "application/x-yaml, text/yaml, text/x-yaml"); } return parse(content); }

Target:
public List<HasMetadata> parse(InternalRecipe recipe) throws ValidationException, InfrastructureException { String content = recipe.getContent(); String contentType = recipe.getContentType(); checkNotNull(contentType, "Recipe content type must not be null"); if (!SUPPORTED_CONTENT_TYPES.contains(contentType)) { throw new ValidationException( format( "Provided environment recipe content type '%s' is unsupported. Supported values are: %s", contentType, String.join(", ", SUPPORTED_CONTENT_TYPES))); } return parse(content); }
Source:
public final void show() { Gdx.input.setInputProcessor(cStage); TextButton.TextButtonStyle style = new TextButton.TextButtonStyle(); style.font = new BitmapFont(); cButtonResetInterval = new TextButton("Reset interval", style); cButtonResetStroll = new TextButton("Reset stroll", style); cButtonBack = new TextButton("Back", style); int width = Gdx.graphics.getWidth(); int height = Gdx.graphics.getHeight(); cButtonResetInterval.setPosition(width / 2f - cButtonResetInterval.getWidth() / 2f, height / 2f + 10); cButtonResetStroll.setPosition(width / 2f - cButtonResetStroll.getWidth() / 2f, height / 2f - 10); cButtonBack.setPosition(width / 2f - cButtonBack.getWidth() / 2f, 20); cButtonResetInterval.addListener(new ChangeListener() { @Override public void changed(final ChangeEvent event, final Actor actor) { TimeKeeper.getInstance().getTimer("INTERVAL").reset(); } }); cButtonResetStroll.addListener(new ChangeListener() { @Override public void changed(final ChangeEvent event, final Actor actor) { TimeKeeper.getInstance().getTimer("STROLL").reset(); } }); cButtonBack.addListener(new ChangeListener() { @Override public void changed(final ChangeEvent event, final Actor actor) { ((Game) Gdx.app.getApplicationListener()).setScreen(new MainMenu()); Gdx.app.debug("Button", "MainMenu"); } }); cStage.addActor(cButtonResetInterval); cStage.addActor(cButtonResetStroll); cStage.addActor(cButtonBack); }

Target:
public final void show() { cStage = new Stage(); Gdx.input.setInputProcessor(cStage); TextButton.TextButtonStyle style = new TextButton.TextButtonStyle(); style.font = new BitmapFont(); cButtonResetInterval = new TextButton("Reset interval", style); cButtonResetStroll = new TextButton("Reset stroll", style); cButtonBack = new TextButton("Back", style); int width = Gdx.graphics.getWidth(); int height = Gdx.graphics.getHeight(); final int offset = 10; cButtonResetInterval.setPosition(width / 2f - cButtonResetInterval.getWidth() / 2f, height / 2f + offset); cButtonResetStroll.setPosition(width / 2f - cButtonResetStroll.getWidth() / 2f, height / 2f - offset); cButtonBack.setPosition(width / 2f - cButtonBack.getWidth() / 2f, 2 * offset); cButtonResetInterval.addListener(new ChangeListener() { @Override public void changed(final ChangeEvent event, final Actor actor) { TimeKeeper.getInstance().getTimer("INTERVAL").reset(); } }); cButtonResetStroll.addListener(new ChangeListener() { @Override public void changed(final ChangeEvent event, final Actor actor) { TimeKeeper.getInstance().getTimer("STROLL").reset(); } }); cButtonBack.addListener(new ChangeListener() { @Override public void changed(final ChangeEvent event, final Actor actor) { ((Game) Gdx.app.getApplicationListener()).setScreen(new MainMenu()); Gdx.app.debug("Button", "MainMenu"); } }); cStage.addActor(cButtonResetInterval); cStage.addActor(cButtonResetStroll); cStage.addActor(cButtonBack); }
Source:
public void testWithNoArgs() { String[] args = {}; exit.expectSystemExitWithStatus(0); exit.checkAssertionAfterwards( new Assertion() { @Override public void checkAssertion() throws Exception { Mockito.verifyZeroInteractions(executor); assertTrue("Error output should be clean, but it was " + mio.getSysErr().toString(), mio.getSysErr().isEmpty()); assertContains(helpText, mio.getSysOut()); } }); Main.main(args); }

Target:
public void testWithNoArgs() { String[] args = {}; exit.expectSystemExitWithStatus(0); exit.checkAssertionAfterwards( new Assertion() { @Override public void checkAssertion() throws Exception { Mockito.verifyZeroInteractions(executor); assertTrue("Error output should be clean, but it was " + mio.getSysErr(), mio.getSysErr().isEmpty()); assertContains(helpText, mio.getSysOut()); } }); Main.main(args); }
Source:
public Set<Integer> getSegments() { synchronized (segments) { Set<Integer> segmentsCopy = new HashSet<Integer>(segments); segmentsCopy.addAll(segments); return segmentsCopy; } }

Target:
public Set<Integer> getSegments() { synchronized (segments) { return new HashSet<Integer>(segments); } }
Source:
public ArrayList<Property> getWorkpieceProperties() { if (Objects.isNull(workpieceProperties)) { return new ArrayList<>(); } return workpieceProperties; }

Target:
public ArrayList<Property> getWorkpieceProperties() { if (Objects.isNull(workpieceProperties)) { workpieceProperties = new ArrayList<>(); } return workpieceProperties; }
Source:
private void createAndSaveNewDraft(String subject, List<String> addressReceiver, List<String> groupReceiver, String content) { AdminEmailAttributes newDraft = AdminEmailAttributes .builder(subject, addressReceiver, groupReceiver, new Text(content)) .withSendDate(null) .build(); try { logic.createAdminEmail(newDraft); } catch (InvalidParametersException e) { isError = true; setStatusForException(e, e.getMessage()); } }

Target:
private void createAndSaveNewDraft(String subject, List<String> addressReceiver, List<String> groupReceiver, String content) { AdminEmailAttributes newDraft = AdminEmailAttributes .builder(subject, addressReceiver, groupReceiver, new Text(content)) .build(); try { logic.createAdminEmail(newDraft); } catch (InvalidParametersException e) { isError = true; setStatusForException(e, e.getMessage()); } }
Source:
private static Asset persistenceXml() { String persistenceXml = Descriptors.create( PersistenceDescriptor.class ) .version( "2.0" ) .createPersistenceUnit() .name( "primary" ) .jtaDataSource( "java:jboss/datasources/ExampleDS" ) .getOrCreateProperties() .createProperty() .name( "hibernate.hbm2ddl.auto" ) .value( "create-drop" ) .up() .createProperty() .name( "hibernate.search.default.lucene_version" ) .value( "LUCENE_CURRENT" ) .up() .createProperty() .name( "hibernate.search.default.directory_provider" ) .value( "infinispan" ) .up() .createProperty() .name( "hibernate.search.infinispan.configuration_resourcename" ) .value( "user-provided-infinispan.xml" ) .up() .up() .up() .exportAsString(); return new StringAsset( persistenceXml ); }

Target:
private static Asset persistenceXml() { String persistenceXml = Descriptors.create( PersistenceDescriptor.class ) .version( "2.0" ) .createPersistenceUnit() .name( "primary" ) .jtaDataSource( "java:jboss/datasources/ExampleDS" ) .getOrCreateProperties() .createProperty() .name( "hibernate.hbm2ddl.auto" ) .value( "create-drop" ) .up() .createProperty() .name( "hibernate.search.default.lucene_version" ) .value( "LUCENE_CURRENT" ) .up() .createProperty() .name( "hibernate.search.default.directory_provider" ) .value( "infinispan" ) .up() .createProperty() .name( "hibernate.search.default.exclusive_index_use" ) .value( "false" ) .up() .createProperty() .name( "hibernate.search.infinispan.configuration_resourcename" ) .value( "user-provided-infinispan.xml" ) .up() .up() .up() .exportAsString(); return new StringAsset( persistenceXml ); }
Source:
private void markSweepTaskStore(File taskStoreDir) throws IOException { String taskStorePath = taskStoreDir.getAbsolutePath(); File offsetFile = new File(taskStoreDir, OFFSET_FILE_NAME); if (!offsetFile.exists()) { LOG.info("Deleting the task store : {}, since it has no offset file.", taskStorePath); FileUtils.deleteDirectory(taskStoreDir); localStoreMonitorMetrics.diskSpaceFreedInBytes.inc(taskStoreDir.getTotalSpace()); localStoreMonitorMetrics.noOfDeletedTaskPartitionStores.inc(); } else if ((CLOCK.currentTimeMillis() - offsetFile.lastModified()) >= config.getOffsetFileTTL()) { LOG.info("Deleting the offset file from the store : {}, since the last modified timestamp : " + "of the offset file is older than config file ttl : {}.", taskStorePath, offsetFile.lastModified(), config.getOffsetFileTTL()); offsetFile.delete(); } }

Target:
private void markSweepTaskStore(File taskStoreDir) throws IOException { String taskStorePath = taskStoreDir.getAbsolutePath(); File offsetFile = new File(taskStoreDir, OFFSET_FILE_NAME); if (!offsetFile.exists()) { LOG.info("Deleting the task store : {}, since it has no offset file.", taskStorePath); long taskStoreSizeInBytes = taskStoreDir.getTotalSpace(); FileUtils.deleteDirectory(taskStoreDir); localStoreMonitorMetrics.diskSpaceFreedInBytes.inc(taskStoreSizeInBytes); localStoreMonitorMetrics.noOfDeletedTaskPartitionStores.inc(); } else if ((CLOCK.currentTimeMillis() - offsetFile.lastModified()) >= config.getOffsetFileTTL()) { LOG.info("Deleting the offset file from the store : {}, since the last modified timestamp : " + "of the offset file is older than config file ttl : {}.", taskStorePath, offsetFile.lastModified(), config.getOffsetFileTTL()); offsetFile.delete(); } }
Source:
private static HandlerDecorator buildDecorator(Class<? extends HandlerDecorator> decoratorClass) { HandlerDecorator decorator; try { decorator = decoratorClass.getConstructor().newInstance(); } catch (ReflectiveOperationException e) { throw new IllegalStateException("Decorator class " + decoratorClass + "cannot be instantiated", e); } return decorator; }

Target:
private static HandlerDecorator buildDecorator(Class<? extends HandlerDecorator> decoratorClass) { try { return decoratorClass.getConstructor().newInstance(); } catch (ReflectiveOperationException e) { throw new IllegalStateException("Decorator class " + decoratorClass + "cannot be instantiated", e); } }
Source:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; String runas = req.getHeader(RUN_AS); if (runas != null) { if (!enabled) { RestApiServlet.replyError(req, res, SC_FORBIDDEN, RUN_AS + " disabled by auth.enableRunAs = false", null); return; } CurrentUser self = session.get().getCurrentUser(); if (!self.getCapabilities().canRunAs()) { RestApiServlet.replyError(req, res, SC_FORBIDDEN, "not permitted to use " + RUN_AS, null); return; } Account target; try { target = accountResolver.find(runas); } catch (OrmException e) { log.warn("cannot resolve account for " + RUN_AS, e); RestApiServlet.replyError(req, res, SC_INTERNAL_SERVER_ERROR, "cannot resolve " + RUN_AS, e); return; } if (target == null) { RestApiServlet.replyError(req, res, SC_FORBIDDEN, "no account matches " + RUN_AS, null); return; } session.get().setUserAccountId(target.getId()); } chain.doFilter(req, res); }

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; String runas = req.getHeader(RUN_AS); if (runas != null) { if (!enabled) { RestApiServlet.replyError(req, res, SC_FORBIDDEN, RUN_AS + " disabled by auth.enableRunAs = false"); return; } CurrentUser self = session.get().getCurrentUser(); if (!self.getCapabilities().canRunAs()) { RestApiServlet.replyError(req, res, SC_FORBIDDEN, "not permitted to use " + RUN_AS); return; } Account target; try { target = accountResolver.find(runas); } catch (OrmException e) { log.warn("cannot resolve account for " + RUN_AS, e); RestApiServlet.replyError(req, res, SC_INTERNAL_SERVER_ERROR, "cannot resolve " + RUN_AS, e); return; } if (target == null) { RestApiServlet.replyError(req, res, SC_FORBIDDEN, "no account matches " + RUN_AS); return; } session.get().setUserAccountId(target.getId()); } chain.doFilter(req, res); }
Source:
public ChannelOutput receive() throws IOException { channelPromise.awaitUninterruptibly(3, TimeUnit.SECONDS); DataInputStream dataInputStream = new NettyByteBufDataInputStream(responseByteBuf); return new ChannelOutput(dataInputStream, dataInputStream.readLong()); }

Target:
public ChannelOutput receive() throws IOException { ByteBuf responseByteBuf; try { responseByteBuf = responsePromise.get(3, TimeUnit.SECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { throw new IOException("No response received in 3 seconds."); } DataInputStream dataInputStream = new NettyByteBufDataInputStream(responseByteBuf); return new ChannelOutput(dataInputStream, dataInputStream.readLong()); }
Source:
public void testToFlowElement_case() throws Exception { final BaseReusableSubprocess definition = new ReusableSubprocess(); definition.getExecutionSet().setIsCase(new IsCase(true)); final View<BaseReusableSubprocess> view = new ViewImpl<>(definition, Bounds.create()); final Node<View<BaseReusableSubprocess>, ?> node = new NodeImpl<>(java.util.UUID.randomUUID().toString()); node.setContent(view); final PropertyWriter propertyWriter = tested.toFlowElement(node); assertTrue(CallActivityPropertyWriter.class.isInstance(propertyWriter)); assertTrue(CustomElement.isCase.of(propertyWriter.getFlowElement()).get()); }

Target:
public void testToFlowElement_case() { final BaseReusableSubprocess definition = new ReusableSubprocess(); definition.getExecutionSet().setIsCase(new IsCase(true)); final View<BaseReusableSubprocess> view = new ViewImpl<>(definition, Bounds.create()); final Node<View<BaseReusableSubprocess>, ?> node = new NodeImpl<>(java.util.UUID.randomUUID().toString()); node.setContent(view); final PropertyWriter propertyWriter = tested.toFlowElement(node); assertTrue(CallActivityPropertyWriter.class.isInstance(propertyWriter)); assertTrue(CustomElement.isCase.of(propertyWriter.getFlowElement()).get()); }
Source:
public void doSystemCancel_chargeStatusDuringAuthorisation_needsCancellationWithProvider(String chargeStatus) throws Exception { var status = ChargeStatus.fromString(chargeStatus); String externalChargeId = "external-charge-id"; Long gatewayAccountId = nextLong(); ChargeEntity chargeEntity = aValidChargeEntity() .withExternalId(externalChargeId) .withTransactionId("transaction-id") .withStatus(status) .build(); WorldpayCancelResponse worldpayResponse = mock(WorldpayCancelResponse.class); when(worldpayResponse.cancelStatus()).thenReturn(BaseCancelResponse.CancelStatus.CANCELLED); GatewayResponse.GatewayResponseBuilder<WorldpayCancelResponse> gatewayResponseBuilder = responseBuilder(); GatewayResponse cancelResponse = gatewayResponseBuilder.withResponse(worldpayResponse).build(); when(mockQueryService.isTerminableWithGateway(chargeEntity)).thenReturn(true); when(mockChargeDao.findByExternalIdAndGatewayAccount(externalChargeId, gatewayAccountId)).thenReturn(Optional.of(chargeEntity)); when(mockPaymentProviders.byName(chargeEntity.getPaymentGatewayName())).thenReturn(mockPaymentProvider); when(mockPaymentProvider.cancel(argThat(aCancelGatewayRequestMatching(chargeEntity)))).thenReturn(cancelResponse); chargeCancelService.doSystemCancel(externalChargeId, gatewayAccountId); verify(mockPaymentProvider).cancel(argThat(aCancelGatewayRequestMatching(chargeEntity))); verify(chargeService).transitionChargeState(externalChargeId, SYSTEM_CANCELLED); verifyNoMoreInteractions(ignoreStubs(mockChargeDao)); }

Target:
public void doSystemCancel_chargeStatusDuringAuthorisation_needsCancellationWithProvider(String chargeStatus) throws Exception { var status = ChargeStatus.fromString(chargeStatus); String externalChargeId = "external-charge-id"; Long gatewayAccountId = nextLong(); ChargeEntity chargeEntity = aValidChargeEntity() .withExternalId(externalChargeId) .withTransactionId("transaction-id") .withStatus(status) .build(); WorldpayCancelResponse worldpayResponse = new WorldpayCancelResponse(); GatewayResponse.GatewayResponseBuilder<WorldpayCancelResponse> gatewayResponseBuilder = responseBuilder(); GatewayResponse cancelResponse = gatewayResponseBuilder.withResponse(worldpayResponse).build(); when(mockQueryService.isTerminableWithGateway(chargeEntity)).thenReturn(true); when(mockChargeDao.findByExternalIdAndGatewayAccount(externalChargeId, gatewayAccountId)).thenReturn(Optional.of(chargeEntity)); when(mockPaymentProviders.byName(chargeEntity.getPaymentGatewayName())).thenReturn(mockPaymentProvider); when(mockPaymentProvider.cancel(argThat(aCancelGatewayRequestMatching(chargeEntity)))).thenReturn(cancelResponse); chargeCancelService.doSystemCancel(externalChargeId, gatewayAccountId); verify(mockPaymentProvider).cancel(argThat(aCancelGatewayRequestMatching(chargeEntity))); verify(chargeService).transitionChargeState(externalChargeId, SYSTEM_CANCELLED); }
Source:
protected boolean applyUpdateToRuntime(final OperationContext context, final ModelNode operation, final String attributeName, final ModelNode resolvedValue, final ModelNode currentValue, final HandbackHolder<Void> handbackHolder) throws OperationFailedException { int timeout = resolvedValue.asInt(); if (timeout == 0) { ModelNode model = context.readResource(PathAddress.EMPTY_ADDRESS).getModel(); timeout = MAXIMUM_TIMEOUT.resolveModelAttribute(context, model).asInt(); TransactionLogger.ROOT_LOGGER.timeoutValueIsSetToMaximum(timeout); } arjPropertyManager.getCoordinatorEnvironmentBean().setDefaultTimeout(timeout); TxControl.setDefaultTimeout(timeout); ContextTransactionManager.setGlobalDefaultTransactionTimeout(timeout); return false; }

Target:
protected boolean applyUpdateToRuntime(final OperationContext context, final ModelNode operation, final String attributeName, final ModelNode resolvedValue, final ModelNode currentValue, final HandbackHolder<Void> handbackHolder) throws OperationFailedException { int timeout = resolvedValue.asInt(); arjPropertyManager.getCoordinatorEnvironmentBean().setDefaultTimeout(timeout); TxControl.setDefaultTimeout(timeout); if (timeout == 0) { ModelNode model = context.readResource(PathAddress.EMPTY_ADDRESS).getModel(); timeout = MAXIMUM_TIMEOUT.resolveModelAttribute(context, model).asInt(); TransactionLogger.ROOT_LOGGER.timeoutValueIsSetToMaximum(timeout); } ContextTransactionManager.setGlobalDefaultTransactionTimeout(timeout); return false; }
Source:
public <T> T execute(SessionCallback<F, T> callback) { Session<F> session = null; if (this.activeTemplateCallbacks.get() > 0) { session = this.contextSessions.get(); } try { if (session == null) { session = this.sessionFactory.getSession(); } Assert.notNull(session, "failed to acquire a Session"); return callback.doInSession(session); } catch (Exception e) { if (session instanceof CachingSessionFactory<?>.CachedSession) { ((CachingSessionFactory.CachedSession) session).dirty(); } if (e instanceof MessagingException) { throw (MessagingException) e; } throw new MessagingException("Failed to execute on session", e); } finally { if (this.activeTemplateCallbacks.get() == 0 && session != null) { try { session.close(); } catch (Exception ignored) { if (this.logger.isDebugEnabled()) { this.logger.debug("failed to close Session", ignored); } } } } }

Target:
public <T> T execute(SessionCallback<F, T> callback) { Session<F> session = null; boolean invokeScope = false; if (this.activeTemplateCallbacks.get() > 0) { session = this.contextSessions.get(); } try { if (session == null) { session = this.sessionFactory.getSession(); } else { invokeScope = true; } return callback.doInSession(session); } catch (Exception e) { if (session instanceof CachingSessionFactory<?>.CachedSession) { ((CachingSessionFactory.CachedSession) session).dirty(); } if (e instanceof MessagingException) { throw (MessagingException) e; } throw new MessagingException("Failed to execute on session", e); } finally { if (!invokeScope) { try { session.close(); } catch (Exception ignored) { if (this.logger.isDebugEnabled()) { this.logger.debug("failed to close Session", ignored); } } } } }
Source:
public Map<String, String> getPrimeVaccinationDateAndDateRange(String subjectId) { LocalDate primeVacDate = null; LocalDate earliestDate = null; LocalDate latestDate = null; if (!StringUtils.isBlank(subjectId)) { LocalDate screeningDate = visitDataService.findVisitBySubjectIdAndType(subjectId, VisitType.SCREENING) .getDate(); primeVacDate = getPrimeVaccinationDate(subjectId); if (screeningDate != null) { if (isFemaleChildBearingAge(subjectId)) { earliestDate = screeningDate.plusDays(14); } else { earliestDate = screeningDate.plusDays(1); } latestDate = screeningDate.plusDays(28); } } Map<String, String> dates = new HashMap<>(); dates.put("primeVacDate", primeVacDate != null ? primeVacDate.toString() : ""); dates.put("earliestDate", earliestDate != null ? earliestDate.toString() : ""); dates.put("latestDate", latestDate != null ? latestDate.toString() : ""); return dates; }

Target:
public Map<String, String> getPrimeVaccinationDateAndDateRange(String subjectId) { Subject subject = subjectDataService.findSubjectBySubjectId(subjectId); LocalDate primeVacDate = null; LocalDate earliestDate = null; LocalDate latestDate = null; if (subject != null) { VisitBookingDetails details = getPrimerVaccinationDetails(subject); if (subject.getPrimerVaccinationDate() != null) { primeVacDate = subject.getPrimerVaccinationDate(); } else { primeVacDate = details.getBookingActualDate(); } LocalDate screeningDate = getScreeningDate(subject); if (screeningDate != null) { if (!isFemaleChildBearingAge(details)) { earliestDate = screeningDate.plusDays(ONE_DAY); } else { earliestDate = screeningDate.plusDays(TWO_WEEKS); } latestDate = screeningDate.plusDays(FOUR_WEEKS); } } Map<String, String> dates = new HashMap<>(); dates.put("primeVacDate", primeVacDate != null ? primeVacDate.toString(BookingAppConstants.SIMPLE_DATE_FORMAT) : ""); dates.put("earliestDate", earliestDate != null ? earliestDate.toString(BookingAppConstants.SIMPLE_DATE_FORMAT) : ""); dates.put("latestDate", latestDate != null ? latestDate.toString(BookingAppConstants.SIMPLE_DATE_FORMAT) : ""); return dates; }
Source:
private boolean testTranslationSetup() { testResultValueLabel.setText(""); MediaType mediaType = MediaType.parse("application/json"); JsonArray jsonArray = new JsonArray(); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("Text", testUntranslatedTextField.getText()); jsonArray.add(jsonObject); String bodyString = jsonArray.toString(); RequestBody body = RequestBody.create(mediaType, bodyString); Request request = new Request.Builder() .url(BingTranslator.getTranlatorUrl(targetLanguageCode)).post(body) .addHeader("Ocp-Apim-Subscription-Key", authenticationKeyField.getText()) .addHeader("Content-type", "application/json").build(); try { Response response = new OkHttpClient().newCall(request).execute(); JsonParser parser = new JsonParser(); JsonArray responses = parser.parse(response.body().string()).getAsJsonArray(); JsonObject response0 = responses.get(0).getAsJsonObject(); JsonArray translations = response0.getAsJsonArray("translations"); JsonObject translation0 = translations.get(0).getAsJsonObject(); testResultValueLabel.setText(translation0.get("text").getAsString()); return true; } catch (IOException | IllegalStateException | ClassCastException | NullPointerException | IndexOutOfBoundsException e) { return false; } }

Target:
private boolean testTranslationSetup() { testResultValueLabel.setText(""); MediaType mediaType = MediaType.parse("application/json"); JsonArray jsonArray = new JsonArray(); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("Text", testUntranslatedTextField.getText()); jsonArray.add(jsonObject); String bodyString = jsonArray.toString(); RequestBody body = RequestBody.create(mediaType, bodyString); Request request = new Request.Builder() .url(BingTranslator.getTranlatorUrl(targetLanguageCode)).post(body) .addHeader("Ocp-Apim-Subscription-Key", authenticationKeyField.getText()) .addHeader("Content-type", "application/json").build(); try { Response response = new OkHttpClient().newCall(request).execute(); JsonParser parser = new JsonParser(); JsonArray responses = parser.parse(response.body().string()).getAsJsonArray(); JsonObject response0 = responses.get(0).getAsJsonObject(); JsonArray translations = response0.getAsJsonArray("translations"); JsonObject translation0 = translations.get(0).getAsJsonObject(); testResultValueLabel.setText(translation0.get("text").getAsString()); return true; } catch (IOException | IllegalStateException | ClassCastException | NullPointerException | IndexOutOfBoundsException e) { logger.log(Level.WARNING, "Test of Bing Translator failed due to exception", e); return false; } }
Source:
static void initializeServer(Injector injector, Lifecycle lifecycle, final Server server) { JettyServerInitializer initializer = injector.getInstance(JettyServerInitializer.class); try { initializer.initialize(server, injector); } catch (ConfigurationException e) { throw new ProvisionException(Iterables.getFirst(e.getErrorMessages(), null).getMessage()); } lifecycle.addHandler( new Lifecycle.Handler() { @Override public void start() throws Exception { server.start(); } @Override public void stop() { if (activeConnections.get() != 0) { long graceFullShutDownTime = (int)server.getAttribute(GRACEFUL_SHUTDOWN_TIME); log.info("Waiting for [%s] milliseconds for active requests to be zero, current active requests=[%s]", graceFullShutDownTime, activeConnections.get()); try { Thread.sleep(graceFullShutDownTime); } catch (InterruptedException e) { log.error("Sleep has been interrupted, while waiting for active requests to be zero"); } } log.info("Stopping Jetty Server with active requests=[%s]", activeConnections.get()); try { server.stop(); } catch (Exception e) { log.warn(e, "Unable to stop Jetty server."); } } } ); }

Target:
static void initializeServer(Injector injector, Lifecycle lifecycle, final Server server) { JettyServerInitializer initializer = injector.getInstance(JettyServerInitializer.class); try { initializer.initialize(server, injector); } catch (ConfigurationException e) { throw new ProvisionException(Iterables.getFirst(e.getErrorMessages(), null).getMessage()); } lifecycle.addHandler( new Lifecycle.Handler() { @Override public void start() throws Exception { server.start(); } private Handler getStatisticsHandler() { for (Handler handler : server.getHandlers()) { if (handler.getClass().equals(StatisticsHandler.class)) { return handler; } } return null; } @Override public void stop() { StatisticsHandler statisticsHandler = (StatisticsHandler) getStatisticsHandler(); if (statisticsHandler != null) { long startTime = System.currentTimeMillis(); long gracefulShutDownTimeout = (long) server.getAttribute(GRACEFUL_SHUTDOWN_TIMEOUT); if (statisticsHandler.getRequestsActive() > 0) { log.info("Waiting for upto [%s] milliseconds for active requests to be zero, current active requests=[%s]", gracefulShutDownTimeout, statisticsHandler.getRequestsActive()); } while (statisticsHandler.getRequestsActive() > 0 && System.currentTimeMillis() - startTime < gracefulShutDownTimeout) { try { Thread.sleep(500); } catch (InterruptedException e) { log.error("Sleep has been interrupted, while waiting for active requests to be zero"); stopImmediately(); Thread.currentThread().interrupt(); return; } } log.info("Stopping Jetty Server with active requests=[%s]", statisticsHandler.getRequestsActive()); } stopImmediately(); } private void stopImmediately() { try { server.stop(); } catch (Exception e) { log.warn(e, "Unable to stop Jetty server."); } } } ); }
Source:
public void add( final Trans value ) { List<Trans> internalList = new ArrayList<>(); internalList.addAll( internal ); for ( Trans t : internalList ) { if ( t.getTransMeta().equals( value.getTransMeta() ) ) { return; } } super.add( value ); }

Target:
public void add( final Trans value ) { for ( Trans t : internal ) { if ( t.getTransMeta().equals( value.getTransMeta() ) ) { return; } } super.add( value ); }
Source:
private CHProfile select(HintsMap weightingMap, Boolean edgeBased, Integer uTurnCosts) throws CHProfileSelectionException { this.weightingMap = weightingMap; findCHProfilesMatchingWeighting(); if (!foundCHProfilesMatchingWeighting()) { throw new CHProfileSelectionException("Cannot find CH profile for weighting map " + weightingMap + " in entries: " + entriesStrs + "."); } if (edgeBased != null && uTurnCosts != null) { return selectUsingEdgeBasedAndUTurnCosts(edgeBased, uTurnCosts); } else if (edgeBased != null) { return selectUsingEdgeBased(edgeBased); } else if (uTurnCosts != null) { return selectUsingUTurnCosts(uTurnCosts); } else { return selectUsingWeightingOnly(); } }

Target:
private CHProfile select(HintsMap weightingMap, Boolean edgeBased, Integer uTurnCosts) { this.weightingMap = weightingMap; findCHProfilesMatchingWeighting(); if (!foundCHProfilesMatchingWeighting()) { throw new CHProfileSelectionException("Cannot find CH profile for weighting map " + weightingMap + " in entries: " + entriesStrs + "."); } if (edgeBased != null && uTurnCosts != null) { return selectUsingEdgeBasedAndUTurnCosts(edgeBased, uTurnCosts); } else if (edgeBased != null) { return selectUsingEdgeBased(edgeBased); } else if (uTurnCosts != null) { return selectUsingUTurnCosts(uTurnCosts); } else { return selectUsingWeightingOnly(); } }
Source:
protected String[] customCommandLineValidation() { IOUtil.assertFileIsReadable(INPUT); if (!isBamOrSamFile(INPUT) && IGNORE_READ_GROUPS) { return new String[]{"The parameter IGNORE_READ_GROUPS can only be used with BAM/SAM inputs."}; } return super.customCommandLineValidation(); }

Target:
protected String[] customCommandLineValidation() { IOUtil.assertFileIsReadable(INPUT); boolean isBamOrSamFile = isBamOrSamFile(INPUT); if (!isBamOrSamFile && IGNORE_READ_GROUPS) { return new String[]{"The parameter IGNORE_READ_GROUPS can only be used with BAM/SAM inputs."}; } if (isBamOrSamFile && OBSERVED_SAMPLE_ALIAS != null) { return new String[]{"The parameter OBSERVED_SAMPLE_ALIAS can only be used with a VCF input."}; } return super.customCommandLineValidation(); }
Source:
public EntryChangeViewModel(BibEntry entry, BibEntry newEntry, BibDatabaseContext database) { super(); this.firstEntry = entry; this.secondEntry = newEntry; name = entry.getCiteKeyOptional() .map(key -> Localization.lang("Modified entry") + ": '" + key + '\'') .orElse(Localization.lang("Modified entry")); mergePanel = new MergeEntries(firstEntry, secondEntry, database.getMode()); }

Target:
public EntryChangeViewModel(BibEntry entry, BibEntry newEntry, BibDatabaseContext database) { super(); this.oldEntry = entry; this.newEntry = newEntry; this.database = database; name = entry.getCiteKeyOptional() .map(key -> Localization.lang("Modified entry") + ": '" + key + '\'') .orElse(Localization.lang("Modified entry")); }
Source:
public static ByteBuffer serializeState(final Object obj) throws IOException { try(ByteArrayOutputStream b = new ByteArrayOutputStream()){ try(ObjectOutputStream o = new ObjectOutputStream(b)){ o.writeObject(obj); o.flush(); } return ByteBuffer.wrap(b.toByteArray()); } }

Target:
private static ByteBuffer serializeState(final Object obj) throws RuntimeException { try { try (final ByteArrayOutputStream b = new ByteArrayOutputStream()) { try (final ObjectOutputStream o = new ObjectOutputStream(b)) { o.writeObject(obj); o.flush(); } return ByteBuffer.wrap(b.toByteArray()); } } catch (final IOException e) { LOG.log(Level.SEVERE, "An exception occured while serializing the state."); e.printStackTrace(); throw new RuntimeException("Error while serializing the operator state."); } }
Source:
private String waitForCid(CommandBuilder docker, Process p) throws InterruptedException, IOException { for (int i = 0; i < 10; i++) { Thread.sleep(500); String output = IOUtils.toString(p.getInputStream()); try { if (p.exitValue() != 0) { throw new IOException("docker died unexpectedly: " + docker + "\n" + output); } } catch (IllegalThreadStateException e) { } if (output != null && output.length() != 0) { return output.trim(); } } throw new IOException("docker didn't leave CID file yet still running. Huh?: "+docker+"\n"+IOUtils.toString(p.getInputStream())); }

Target:
private String waitForCid(CommandBuilder docker, Process p) throws InterruptedException, IOException { String output = IOUtils.toString(p.getInputStream()); if (p.waitFor() != 0) { throw new IOException("docker died unexpectedly with return code " + p.exitValue() + " : " + docker + "\n" + output); } if (output != null && output.length() != 0) { return output.trim(); } throw new IOException("docker didn't output a container id or have a non-zero exit status. Huh?: "+docker); }
Source:
public void buildsTextFromIntArray() throws Exception { final Object[][] pairs = new Object[][] { new Object[] {new int[0], EMPTY_ARRAY}, new Object[] {new int[] {1}, "[1]"}, new Object[] {new int[] {1, 2, 3}, "[1, 2, 3]"}, }; for (final Object[] pair : pairs) { MatcherAssert.assertThat( Mnemos.toText(pair[0], false, false), Matchers.equalTo(pair[1].toString()) ); } }

Target:
public void buildsTextFromIntArray() throws Exception { final Object[][] pairs = new Object[][] { new Object[] {new int[0], MnemosTest.EMPTY_ARRAY}, new Object[] {new int[] {1}, "[1]"}, new Object[] {new int[] {1, 2, 3}, "[1, 2, 3]"}, }; this.validateText(pairs); }
Source:
public Content findContent(Context context, CachingOptions cachingOptions, String url) throws InvalidContextException, StoreException { if (context.getStoreAdapter().exists(context, cachingOptions, url)) { return context.getStoreAdapter().findContent(context, cachingOptions, url); } else { String blobUrl = blobUrlResolver.getBlobUrl(url); if(context.getStoreAdapter().exists(context, cachingOptions, blobUrl)) { Content content = context.getStoreAdapter().findContent(context, cachingOptions, blobUrl); try(InputStream is = content.getInputStream()) { Blob blob = mapper.readValue(is, Blob.class); Function<String, InputStream> configGetter = path -> { try { return findContent(context, cachingOptions, path).getInputStream(); } catch (Exception e) { return null; } }; BlobStore store = blobStoreResolver.getById(configGetter, blob.getStoreId()); return new ResourceBasedContent(store.getResource(blob)); } catch (IOException e) { throw new StoreException("Error reading blob file at " + blobUrl, e); } } } return null; }

Target:
public Content findContent(Context context, CachingOptions cachingOptions, String url) throws InvalidContextException, StoreException { if (context.getStoreAdapter().exists(context, cachingOptions, url)) { return context.getStoreAdapter().findContent(context, cachingOptions, url); } else { String blobUrl = blobUrlResolver.getBlobUrl(url); if (context.getStoreAdapter().exists(context, cachingOptions, blobUrl)) { Content content = context.getStoreAdapter().findContent(context, cachingOptions, blobUrl); try (InputStream is = content.getInputStream()) { Blob blob = mapper.readValue(is, Blob.class); Function<String, InputStream> configGetter = path -> { try { return findContent(context, cachingOptions, path).getInputStream(); } catch (Exception e) { return null; } }; BlobStore store = blobStoreResolver.getById(configGetter, blob.getStoreId()); return new ResourceBasedContent(store.getResource(blob)); } catch (IOException | ConfigurationException e) { throw new StoreException("Error reading blob file at " + blobUrl, e); } } } return null; }
Source:
public Object visit(PropertyIsEqualTo filter, Object extraData) { Optional<FilterFunction_pgNearest> nearestOpt = getNearestFilter(filter); if (nearestOpt.isPresent()) { return visit(nearestOpt.get(), extraData); } else { return super.visit(filter, extraData); } }

Target:
public Object visit(PropertyIsEqualTo filter, Object extraData) { helper.out = out; FilterFunction_pgNearest nearest = helper.getNearestFilter(filter); if (nearest != null) { return helper.visit( nearest, extraData, new FilterToSqlHelper.NearestHelperContext( pgDialect, (a, b) -> { try { pgDialect.encodeGeometryValue( a, helper.getFeatureTypeGeometryDimension(), helper.getFeatureTypeGeometrySRID(), b); } catch (IOException e) { throw new RuntimeException(e); } })); } else { return super.visit(filter, extraData); } }
Source:
public void resilientToRepeatedRedirects() { server.stubFor(TIMESTAMP_MAPPING.willReturn(aResponse() .withStatus(308) .withHeader("Location", getUriForPort(serverPort)))); Instant start = Instant.now(); ExecutorService ex = PTExecutors.newSingleThreadExecutor(true); ex.submit(this::scheduleServerRecoveryAfterFiveSeconds); assertThatCode(this::makeTimestampsRequest).doesNotThrowAnyException(); assertThat(Instant.now()) .as("should recover in a second after things are good again") .isBefore(start.plus(Duration.ofSeconds(11))); ex.shutdown(); }

Target:
public void resilientToRepeatedRedirects() { server.stubFor(TIMESTAMP_MAPPING.willReturn(aResponse() .withStatus(308) .withHeader(HttpHeaders.LOCATION, getUriForPort(serverPort)))); Instant start = Instant.now(); ExecutorService ex = PTExecutors.newSingleThreadExecutor(true); ex.submit(this::scheduleServerRecoveryAfterFiveSeconds); assertThatCode(this::makeTimestampsRequest).doesNotThrowAnyException(); assertThat(Instant.now()) .as("should recover in a second after things are good again") .isBefore(start.plus(Duration.ofSeconds(6))); ex.shutdown(); }
Source:
public static String removeCDATAFromPayload(String inputPayload) { if (inputPayload.startsWith("<![CDATA[")) { inputPayload = inputPayload.substring(9); int i = inputPayload.indexOf("]]>"); if (i == -1) throw new IllegalStateException("argument starts with <![CDATA[ but cannot find pairing ]]>"); inputPayload = inputPayload.substring(0, i); } return inputPayload; }

Target:
public static String removeCDATAFromPayload(String inputPayload) { if (inputPayload.startsWith("<![CDATA[")) { inputPayload = inputPayload.substring(9); int i = inputPayload.lastIndexOf("]]>"); if (i == -1) throw new IllegalStateException("argument starts with <![CDATA[ but cannot find pairing ]]>"); inputPayload = inputPayload.substring(0, i); } return inputPayload; }
Source:
public boolean doWorkunitAction(String wuid, ECLWUActions action) throws ArrayOfEspException, RemoteException, Exception { WUAction wa = new WUAction(); wa.setWUActionType(action); wa.setWuids(new String[] { wuid }); WUActionResponse war = this.getSoapProxy().getWsWorkunitsServiceSoap().WUAction(wa); if (war == null || war.getActionResults() == null || war.getActionResults().length == 0 || war.getActionResults()[0].getResult() == null || !war.getActionResults()[0].getResult().equals("Success")) { org.hpccsystems.ws.client.gen.wsworkunits.v1_56.WUAction fwa = new org.hpccsystems.ws.client.gen.wsworkunits.v1_56.WUAction(); fwa.setActionType(action.getValue()); fwa.setWuids(new String[] { wuid }); org.hpccsystems.ws.client.gen.wsworkunits.v1_56.WUActionResponse fwar = this.fallBackWorkunitsServiceSoapProxy.getWsWorkunitsServiceSoap().WUAction(fwa); if (fwar == null || fwar.getActionResults() == null || fwar.getActionResults().length == 0 || fwar.getActionResults()[0].getResult() == null || !fwar.getActionResults()[0].getResult().equals("Success")) { throw new Exception("Unable to perform " + action.getValue() + " on " + wuid); } } return true; }

Target:
public boolean doWorkunitAction(String wuid, ECLWUActions action) throws ArrayOfEspException, RemoteException, Exception { WUAction wa = new WUAction(); wa.setWUActionType(action); wa.setWuids(new String[] { wuid }); WUActionResponse war = this.getSoapProxy().getWsWorkunitsServiceSoap().WUAction(wa); if (war == null || war.getActionResults() == null || war.getActionResults().length == 0 || war.getActionResults()[0].getResult() == null || !war.getActionResults()[0].getResult().equals("Success")) { org.hpccsystems.ws.client.gen.wsworkunits.v1_56.WUAction fwa = new org.hpccsystems.ws.client.gen.wsworkunits.v1_56.WUAction(); fwa.setActionType(action.getValue()); fwa.setWuids(new String[] { wuid }); org.hpccsystems.ws.client.gen.wsworkunits.v1_56.WUActionResponse fwar = this.fallBackWorkunitsServiceSoapProxy.getWsWorkunitsServiceSoap().WUAction(fwa); if (fwar == null || fwar.getActionResults() == null || fwar.getActionResults().length == 0 || fwar.getActionResults()[0].getResult() == null || !fwar.getActionResults()[0].getResult().equals("Success")) { String failreason = "unknown action result"; if (fwar != null && fwar.getActionResults() != null && fwar.getActionResults()[0].getResult() != null) failreason = fwar.getActionResults()[0].getResult(); throw new Exception("Unable to perform " + action.getValue() + " on " + wuid + " :: " + failreason); } } return true; }
Source:
private Stage toStage(Map stage) { return Stage.newBuilder() .setType(stage.get("type").toString()) .setStatus(Status.valueOf(stage.get("status").toString().toUpperCase())) .build(); }

Target:
private Stage toStage(Map stage) { return Stage.newBuilder() .setType(stage.getOrDefault("type", "unknown").toString()) .setStatus(Status.valueOf(stage.getOrDefault("status", "UNKNOWN").toString().toUpperCase())) .build(); }
Source:
public void testBuildHistory() { int historySize = 8; MissionControlView view = jenkins.views.create(MissionControlView.class, "mission-control-sample-view"); view.configure(); view.setHideBuildHistory(false); view.setHistorySize(historySize); view.save(); String strSimpleJob = "simple-job"; String strFailedJob = "simple-failed-job"; FreeStyleJob job = jenkins.jobs.create(FreeStyleJob.class, strSimpleJob); for (int i = 0; i < historySize + 2; ++i) { job.startBuild().waitUntilFinished(); } job = jenkins.jobs.create(FreeStyleJob.class, strFailedJob); job.configure(); job.addShellStep("sh <"); job.save(); job.startBuild().waitUntilFinished(); view.open(); WebElement buildHistory = driver.findElement(By.id("jenkinsBuildHistory")); Assert.assertEquals(0, buildHistory.findElements(By.xpath(". view.reloadConfiguration(); view.open(); buildHistory = driver.findElement(By.id("jenkinsBuildHistory")); Assert.assertEquals(historySize, buildHistory.findElements(By.xpath(". WebElement failedBuild = buildHistory.findElement(By.xpath(". assertThat(failedBuild.getAttribute("class"), containsString("danger")); for (WebElement successfulBuild : buildHistory.findElements(By.xpath(". assertThat(successfulBuild.getAttribute("class"), containsString("")); } }

Target:
public void testBuildHistory() { int historySize = 8; MissionControlView view = jenkins.views.create(MissionControlView.class, "mission-control-sample-view"); view.configure(); view.setHideBuildHistory(false); view.setHistorySize(historySize); view.save(); String strSimpleJob = "simple-job"; String strFailedJob = "simple-failed-job"; FreeStyleJob job = jenkins.jobs.create(FreeStyleJob.class, strSimpleJob); for (int i = 0; i < historySize; ++i) { job.startBuild().waitUntilFinished(); } job = jenkins.jobs.create(FreeStyleJob.class, strFailedJob); job.configure(); job.addShellStep("sh <"); job.save(); job.startBuild().waitUntilFinished(); view.open(); assertThat(view.getBuildHistoryArea().getBuildHistorySize(), is(0)); view.reloadConfiguration(); view.open(); assertThat(view.getBuildHistoryArea().getBuildHistorySize(), is(historySize)); assertThat(view.getBuildHistoryArea().getFailedBuildsOfJob(strFailedJob), hasSize(1)); assertThat(view.getBuildHistoryArea().getSuccessfulBuildsOfJob(strSimpleJob), hasSize(historySize - 1)); }
Source:
private KafkaSupervisor getSupervisor( int replicas, int taskCount, boolean useEarliestOffset, String duration, Period lateMessageRejectionPeriod ) { KafkaSupervisorIOConfig kafkaSupervisorIOConfig = new KafkaSupervisorIOConfig( KAFKA_TOPIC, replicas, taskCount, new Period(duration), ImmutableMap.of("myCustomKey", "myCustomValue", "bootstrap.servers", kafkaHost), new Period("P1D"), new Period("PT30S"), useEarliestOffset, new Period("PT30M"), lateMessageRejectionPeriod ); KafkaIndexTaskClientFactory taskClientFactory = new KafkaIndexTaskClientFactory(null, null) { @Override public KafkaIndexTaskClient build( TaskInfoProvider taskInfoProvider, String dataSource, int numThreads, Duration httpTimeout, long numRetries ) { Assert.assertEquals(TEST_CHAT_THREADS, numThreads); Assert.assertEquals(TEST_HTTP_TIMEOUT.toStandardDuration(), httpTimeout); Assert.assertEquals(TEST_CHAT_RETRIES, numRetries); return taskClient; } }; return new TestableKafkaSupervisor( taskStorage, taskMaster, indexerMetadataStorageCoordinator, taskClientFactory, objectMapper, new KafkaSupervisorSpec( dataSchema, tuningConfig, kafkaSupervisorIOConfig, null, taskStorage, taskMaster, indexerMetadataStorageCoordinator, taskClientFactory, objectMapper, new NoopServiceEmitter() ) ); }

Target:
private KafkaSupervisor getSupervisor( int replicas, int taskCount, boolean useEarliestOffset, String duration, Period lateMessageRejectionPeriod ) { KafkaSupervisorIOConfig kafkaSupervisorIOConfig = new KafkaSupervisorIOConfig( KAFKA_TOPIC, replicas, taskCount, new Period(duration), ImmutableMap.of("myCustomKey", "myCustomValue", "bootstrap.servers", kafkaHost), new Period("P1D"), new Period("PT30S"), useEarliestOffset, new Period("PT30M"), lateMessageRejectionPeriod ); KafkaIndexTaskClientFactory taskClientFactory = new KafkaIndexTaskClientFactory(null, null) { @Override public KafkaIndexTaskClient build( TaskInfoProvider taskInfoProvider, String dataSource, int numThreads, Duration httpTimeout, long numRetries ) { Assert.assertEquals(TEST_CHAT_THREADS, numThreads); Assert.assertEquals(TEST_HTTP_TIMEOUT.toStandardDuration(), httpTimeout); Assert.assertEquals(TEST_CHAT_RETRIES, numRetries); return taskClient; } }; return new TestableKafkaSupervisor( taskStorage, taskMaster, indexerMetadataStorageCoordinator, taskClientFactory, objectMapper, new KafkaSupervisorSpec( dataSchema, tuningConfig, kafkaSupervisorIOConfig, null, taskStorage, taskMaster, indexerMetadataStorageCoordinator, taskClientFactory, objectMapper, new NoopServiceEmitter(), new DruidMonitorSchedulerConfig() ) ); }
Source:
public boolean isArray(Schema<?> schema) { return schema instanceof ArraySchema; }

Target:
private static boolean isArray(Schema<?> schema) { return schema instanceof ArraySchema; }
Source:
public Socket connect(HostAndPort addr, int timeout, ConnectionWatcher optionalWatcher, boolean allowClientSocketFactory, int socketBufferSize, boolean useSSL, TcpSocketFactory socketFactory) throws IOException { if (useSSL) { throw new IllegalArgumentException(); } Socket socket = null; if (allowClientSocketFactory) { socket = createCustomClientSocket(addr); } if (socket == null) { socket = socketFactory.createSocket(); socket.setKeepAlive(ENABLE_TCP_KEEP_ALIVE); if (socketBufferSize != -1) { socket.setReceiveBufferSize(socketBufferSize); } if (optionalWatcher != null) { optionalWatcher.beforeConnect(socket); } InetSocketAddress inetSocketAddress = addr.getSocketInetAddress(); try { socket.connect(inetSocketAddress, Math.max(timeout, 0)); } catch (ConnectException connectException) { LogService.getLogger().info("Failed to connect to " + inetSocketAddress); throw connectException; } finally { if (optionalWatcher != null) { optionalWatcher.afterConnect(socket); } } } return socket; }

Target:
public Socket connect(HostAndPort addr, int timeout, ConnectionWatcher optionalWatcher, boolean allowClientSocketFactory, int socketBufferSize, boolean useSSL, TcpSocketFactory socketFactory) throws IOException { if (useSSL) { throw new IllegalArgumentException(); } Socket socket = null; if (allowClientSocketFactory) { socket = createCustomClientSocket(addr); } if (socket == null) { socket = socketFactory.createSocket(); socket.setKeepAlive(ENABLE_TCP_KEEP_ALIVE); if (socketBufferSize != -1) { socket.setReceiveBufferSize(socketBufferSize); } if (optionalWatcher != null) { optionalWatcher.beforeConnect(socket); } InetSocketAddress inetSocketAddress = addr.getSocketInetAddress(); try { socket.connect(inetSocketAddress, Math.max(timeout, 0)); } catch (ConnectException connectException) { logger.info("Failed to connect to " + inetSocketAddress); throw connectException; } finally { if (optionalWatcher != null) { optionalWatcher.afterConnect(socket); } } } return socket; }