auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void trade() { for (String symbol : this.buyOrders.keySet()){ if (this.sellOrders.containsKey(symbol)){ HashMap<Double, ArrayList<Integer>> orderbook=orderBookCreator(symbol); double matchPrice=matchPrice(orderbook); if(matchPrice>0) try{ market.updateStockPrice(symbol, matchPrice);} catch (StockMarketExpection e){}; for (Order sellOrder : this.sellOrders.get(symbol)){ if (sellOrder.getPrice()<=matchPrice){ try { sellOrder.getTrader().tradePerformed(sellOrder, matchPrice); } catch (StockMarketExpection e) { e.printStackTrace(); } this.sellOrders.remove(sellOrder); } } for (Order buyOrder : this.buyOrders.get(symbol)){ if (buyOrder.getPrice()>=matchPrice){ try { buyOrder.getTrader().tradePerformed(buyOrder, matchPrice); } catch (StockMarketExpection e) { e.printStackTrace(); } this.buyOrders.remove(buyOrder); } } } } }

Target:
public void trade() { for (String symbol : this.buyOrders.keySet()){ if (this.sellOrders.containsKey(symbol)){ HashMap<Double, ArrayList<Integer>> orderbook=orderBookCreator(symbol); double matchPrice=matchPrice(orderbook); if(matchPrice>0) try{ market.updateStockPrice(symbol, matchPrice);} catch (StockMarketExpection e){}; for (Order sellOrder : this.sellOrders.get(symbol)){ if (sellOrder.getPrice()<=matchPrice){ try { Trader sellTrader=sellOrder.getTrader(); sellTrader.tradePerformed(sellOrder, matchPrice); } catch (StockMarketExpection e) { e.printStackTrace(); } this.sellOrders.remove(sellOrder); } } for (Order buyOrder : this.buyOrders.get(symbol)){ if (buyOrder.getPrice()>=matchPrice){ try { Trader buyTrader=buyOrder.getTrader(); buyTrader.tradePerformed(buyOrder, matchPrice); } catch (StockMarketExpection e) { e.printStackTrace(); } this.buyOrders.remove(buyOrder); } } } } }
Source:
public void updateRefundTransactionStatus(PaymentGatewayName provider, String refundReference, RefundStatus newRefundStatus) { Optional<RefundTransactionEntity> refundTransaction = refundTransactionDao.findByProviderAndReference(provider, refundReference); String errorMessage = format("Not updating refund transaction status for refundReference [%s] to [%s] charge transaction not found", refundReference, newRefundStatus.getValue() ); updateRefundTransactionStatus(refundTransaction, newRefundStatus, errorMessage); }

Target:
public void updateRefundTransactionStatus(PaymentGatewayName provider, String refundReference, RefundStatus newRefundStatus) { Optional<RefundTransactionEntity> refundTransaction = refundTransactionDao.findByProviderAndReference(provider, refundReference); if (refundTransaction.isPresent()) { updateRefundTransactionStatus(newRefundStatus, refundTransaction.get()); } else { logger.warn(format("Not updating refund transaction status for refundReference [%s] to [%s] refund transaction not found", refundReference, newRefundStatus.getValue() )); } }
Source:
public void checkIfCanBeDeleted(@NonNull final I_MKTG_Channel mktgChannel) { if (!isMarketingChannelsUseEnforced()) { return; } boolean canBeDeleted = true; Set<UserId> usersSet = mktgChannelDao.retrieveUsersHavingChannel(mktgChannel.getMKTG_Channel_ID()); for (UserId userId : usersSet) { if (mktgChannelDao.retrieveMarketingChannelsCountForUser(userId) == 1 && !userDAO.isSystemUser(userId)) { canBeDeleted = false; break; } } if (!canBeDeleted) { throw new AdempiereException(MSG_MUST_HAVE_CHANNEL).markAsUserValidationError(); } }

Target:
public void checkIfCanBeDeleted(@NonNull final I_MKTG_Channel mktgChannel) { boolean canBeDeleted = true; Set<UserId> usersSet = mktgChannelDao.retrieveUsersHavingChannel(mktgChannel.getMKTG_Channel_ID()); for (final UserId userId : usersSet) { if (mktgChannelDao.retrieveMarketingChannelsCountForUser(userId) > 0) { canBeDeleted = false; break; } } if (!canBeDeleted) { throw new AdempiereException(MSG_MUST_HAVE_CHANNEL).markAsUserValidationError(); } }
Source:
public SlackNotificationPayloadContent(SBuildServer server, SRunningBuild sRunningBuild, SFinishedBuild previousBuild, BuildStateEnum buildState) { payloadCommits = new PayloadContentCommits(); populateCommonContent(server, sRunningBuild, previousBuild, buildState); populateMessageAndText(sRunningBuild, buildState); payloadCommits.populateCommits(sRunningBuild); populateArtifacts(sRunningBuild); populateResults(sRunningBuild); }

Target:
public SlackNotificationPayloadContent(SBuildServer server, SRunningBuild sRunningBuild, SFinishedBuild previousBuild, BuildStateEnum buildState) { populateCommonContent(server, sRunningBuild, previousBuild, buildState); populateMessageAndText(sRunningBuild, buildState); payloadCommits.populateCommits(sRunningBuild); populateArtifacts(sRunningBuild); populateResults(sRunningBuild); }
Source:
public DynamicTableSource createDynamicTableSource(Context context) { TableFactoryHelper helper = createTableFactoryHelper(this, context); String hTableName = helper.getOptions().get(TABLE_NAME); Configuration hbaseClientConf = HBaseConfiguration.create(); hbaseClientConf.set(HConstants.ZOOKEEPER_QUORUM, helper.getOptions().get(ZOOKEEPER_QUORUM)); hbaseClientConf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, helper.getOptions().get(ZOOKEEPER_ZNODE_PARENT)); String nullStringLiteral = helper.getOptions().get(NULL_STRING_LITERAL); TableSchema tableSchema = context.getCatalogTable().getSchema(); HBaseTableSchema hbaseSchema = HBaseTableSchema.fromTableSchema(tableSchema); return new HBaseDynamicTableSource( hbaseClientConf, hTableName, hbaseSchema, nullStringLiteral); }

Target:
public DynamicTableSource createDynamicTableSource(Context context) { TableFactoryHelper helper = createTableFactoryHelper(this, context); helper.validate(); String hTableName = helper.getOptions().get(TABLE_NAME); Configuration hbaseClientConf = HBaseConfiguration.create(); hbaseClientConf.set(HConstants.ZOOKEEPER_QUORUM, helper.getOptions().get(ZOOKEEPER_QUORUM)); hbaseClientConf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, helper.getOptions().get(ZOOKEEPER_ZNODE_PARENT)); String nullStringLiteral = helper.getOptions().get(NULL_STRING_LITERAL); TableSchema tableSchema = context.getCatalogTable().getSchema(); HBaseTableSchema hbaseSchema = HBaseTableSchema.fromTableSchema(tableSchema); return new HBaseDynamicTableSource( hbaseClientConf, hTableName, hbaseSchema, nullStringLiteral); }
Source:
public ImmutableMap<String, String> query(Serializer serializer) { if (serializer == null) { serializer = Serializer.defaultSerializer(); } ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<>(); if (scope != null) { builder = builder.put("scope", serializer.serializeToQueryParams(scope)); } if (query != null && !query.isEmpty()) { builder = builder.put("query", query); } if (filters != null && !filters.isEmpty()) { for (Map.Entry<String, String> entry : filters.entrySet()) { builder = builder.put("filters[" + entry.getKey() + "]", entry.getValue()); } } if (order != null) { builder = builder.put("order", serializer.serializeToQueryParams(order)); } if (page > 0) { builder = builder.put("page", page + ""); } if (perPage > 0) { builder = builder.put("per_page", perPage + ""); } return builder.build(); }

Target:
public Map<String, String> query(Serializer serializer) { if (serializer == null) { serializer = Serializer.defaultSerializer(); } Map<String, String> map = new HashMap<>(); if (scope != null) { map.put("scope", serializer.serializeToQueryParams(scope)); } if (query != null && !query.isEmpty()) { map.put("query", query); } if (filters != null && !filters.isEmpty()) { for (Map.Entry<String, String> entry : filters.entrySet()) { map.put("filters[" + entry.getKey() + "]", entry.getValue()); } } if (order != null) { map.put("order", serializer.serializeToQueryParams(order)); } if (page > 0) { map.put("page", String.valueOf(page)); } if (dataPerPage > 0) { map.put("per_page", String.valueOf(dataPerPage)); } return Collections.unmodifiableMap(map); }
Source:
public int getPostsListLength() { wait.forElementNotVisible(By.className(".spinner")); return postList.size(); }

Target:
public int getPostsListLength() { return postList.size(); }
Source:
public static List<Diagnostic> validate(String str) throws IOException, RecognitionException { ByteArrayInputStream input = new ByteArrayInputStream(str.getBytes()); ANTLRInputStream antlrStream = new ANTLRInputStream(input); FilterParserLexer lexer = new FilterParserLexer(antlrStream); ArrayList<RecognitionException> lexerExceptions = new ArrayList<>(); lexer.setErrorListener(e -> { lexerExceptions.add((RecognitionException) e); }); CommonTokenStream tokenStream = new CommonTokenStream(lexer); FilterParserParser parser = new FilterParserParser(tokenStream); ArrayList<RecognitionException> parserExceptions = new ArrayList<>(); parser.setErrorListener(e -> { parserExceptions.add((RecognitionException) e); }); parser.parse(); List<Diagnostic> diagnostics = new ArrayList<>(); lexerExceptions.forEach(e -> { String message = lexer.getErrorMessage(e, lexer.getTokenNames()); int idx = e.index; Position start = new Position(e.line, idx); Position end = new Position(e.line, idx); Range range = new Range(start, end); Diagnostic diagnostic = new Diagnostic(range, message); diagnostics.add(diagnostic); }); return diagnostics; }

Target:
public static List<Diagnostic> validate(String str) throws IOException, RecognitionException { ByteArrayInputStream input = new ByteArrayInputStream(str.getBytes()); ANTLRInputStream antlrStream = new ANTLRInputStream(input); FilterParserLexer lexer = new FilterParserLexer(antlrStream); ArrayList<RecognitionException> lexerExceptions = new ArrayList<>(); lexer.setErrorListener(e -> { lexerExceptions.add((RecognitionException) e); }); CommonTokenStream tokenStream = new CommonTokenStream(lexer); FilterParserParser parser = new FilterParserParser(tokenStream); ArrayList<RecognitionException> parserExceptions = new ArrayList<>(); parser.setErrorListener(e -> { parserExceptions.add((RecognitionException) e); }); parse_return parse = parser.parse(); CommonTree tree = parse.getTree(); List<Diagnostic> diagnostics = new ArrayList<>(); lexerExceptions.forEach(e -> { String message = lexer.getErrorMessage(e, lexer.getTokenNames()); Range range = getRangeFromException(e, str, tree); Diagnostic diagnostic = new Diagnostic(range, message); diagnostics.add(diagnostic); }); parserExceptions.forEach(e -> { String message = parser.getErrorMessage(e, parser.getTokenNames()); Range range = getRangeFromException(e, str, tree); Diagnostic diagnostic = new Diagnostic(range, message); diagnostics.add(diagnostic); }); return preprocessDiagnostics(diagnostics); }
Source:
public static void stringToFile(IContext context, String value, FileDocument destination) throws IOException { stringToFile(context, value, destination, "UTF-8"); }

Target:
public static void stringToFile(IContext context, String value, FileDocument destination) throws IOException { stringToFile(context, value, destination, StandardCharsets.UTF_8); }
Source:
protected Collection<BackingChecker> getCheckers() throws ConfigurationException { if (checkers == null) { checkers = new HashSet<>(); for (String template : configurationGenerator.getTemplateList()) { try { File templateDir = configurationGenerator.getTemplateConf(template).getParentFile(); String classPath = getClasspathForTemplate(template); String checkClass = configurationGenerator.getUserConfig().getProperty(template + ".check.class"); Optional<URLClassLoader> ucl = getClassLoaderForTemplate(templateDir, classPath); if (ucl.isPresent()) { Class<?> klass = Class.forName(checkClass, true, ucl.get()); checkers.add((BackingChecker) klass.newInstance()); } } catch (IOException e) { log.warn("Unable to read check configuration for template : " + template, e); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { throw new ConfigurationException("Unable to check configuration for backing service " + template, e); } } checkers.add(new DBCheck()); } return checkers; }

Target:
protected Collection<BackingChecker> getCheckers() throws ConfigurationException { if (checkers == null) { checkers = new HashSet<>(); for (String template : configurationGenerator.getTemplateList()) { try { File templateDir = configurationGenerator.getTemplateConf(template).getParentFile(); String classPath = getClasspathForTemplate(template); String checkClass = configurationGenerator.getUserConfig().getProperty(template + PARAM_CHECK_SUFFIX); Optional<URLClassLoader> ucl = getClassLoaderForTemplate(templateDir, classPath); if (ucl.isPresent()) { Class<?> klass = Class.forName(checkClass, true, ucl.get()); checkers.add((BackingChecker) klass.newInstance()); } } catch (IOException e) { log.warn("Unable to read check configuration for template : " + template, e); } catch (ReflectiveOperationException | ClassCastException e) { throw new ConfigurationException("Unable to check configuration for backing service " + template, e); } } checkers.add(new DBCheck()); } return checkers; }
Source:
protected Compressor<ByteBuf> buildCompressor() { DriverExecutionProfile defaultProfile = getConfig().getDefaultProfile(); if (!defaultProfile.isDefined(DefaultDriverOption.PROTOCOL_COMPRESSION)) { return Compressor.none(); } String name = defaultProfile.getString(DefaultDriverOption.PROTOCOL_COMPRESSION); switch (name) { case "lz4": return new Lz4Compressor(this); case "snappy": return new SnappyCompressor(this); case "none": return Compressor.none(); default: throw new IllegalArgumentException( String.format( "Unsupported compression algorithm '%s' (from configuration option %s)", name, DefaultDriverOption.PROTOCOL_COMPRESSION.getPath())); } }

Target:
protected Compressor<ByteBuf> buildCompressor() { DriverExecutionProfile defaultProfile = getConfig().getDefaultProfile(); String name = defaultProfile.getString(DefaultDriverOption.PROTOCOL_COMPRESSION, "none"); assert name != null : "should use default value"; switch (name.toLowerCase()) { case "lz4": return new Lz4Compressor(this); case "snappy": return new SnappyCompressor(this); case "none": return Compressor.none(); default: throw new IllegalArgumentException( String.format( "Unsupported compression algorithm '%s' (from configuration option %s)", name, DefaultDriverOption.PROTOCOL_COMPRESSION.getPath())); } }
Source:
private static Date addDates(Date d, int days) { Calendar c = Calendar.getInstance(); c.setTime(d); c.add(Calendar.DAY_OF_MONTH, days); return c.getTime(); }

Target:
private Date addDates(Date d, int days) { Calendar c = Calendar.getInstance(); c.setTime(d); c.add(Calendar.DAY_OF_MONTH, days); return c.getTime(); }
Source:
private static void reportEntityDetailNavigation(String direction, String navMethod, int detailTabCount) { String detailUiState = detailTabCount > 1 ? CCAnalyticsParamValue.DETAIL_WITH_TABS : CCAnalyticsParamValue.DETAIL_NO_TABS; reportEvent(CCAnalyticsEvent.ENTITY_DETAIL_NAVIGATION, new String[]{ CCAnalyticsParam.DIRECTION, CCAnalyticsParam.METHOD, CCAnalyticsParam.UI_STATE}, new String[]{direction, navMethod, detailUiState}); }

Target:
private static void reportEntityDetailNavigation(String direction, String navMethod, int detailTabCount) { String detailUiState = detailTabCount > 1 ? AnalyticsParamValue.DETAIL_WITH_TABS : AnalyticsParamValue.DETAIL_NO_TABS; reportEvent(CCAnalyticsEvent.ENTITY_DETAIL_NAVIGATION, new String[]{ CCAnalyticsParam.DIRECTION, CCAnalyticsParam.METHOD, CCAnalyticsParam.UI_STATE}, new String[]{direction, navMethod, detailUiState}); }
Source:
private static boolean needsQuote(String s) { char c = s.charAt(0); if (!(c >= 97 && c <= 122)) return true; for (int i = 1; i < s.length(); i++) { c = s.charAt(i); if (!( (c >= 48 && c <= 57) || (c == 95) || (c >= 97 && c <= 122) )) { return true; } } return isReservedCqlKeyword(s); }

Target:
private static boolean needsQuote(String s) { assert s != null && !s.isEmpty(); char c = s.charAt(0); if (!(c >= 97 && c <= 122)) return true; for (int i = 1; i < s.length(); i++) { c = s.charAt(i); if (!( (c >= 48 && c <= 57) || (c == 95) || (c >= 97 && c <= 122) )) { return true; } } return isReservedCqlKeyword(s); }
Source:
public void testAsyncRollback() throws Exception { Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); MessageConsumer messageConsumer = session.createConsumer(queue); messageConsumer.setMessageListener(new MessageListener() { @Override @Transactional public void onMessage(Message message) { try { System.out.println("RECEIVED"); TransactionManager.transactionManager().getTransaction().enlistResource(xaResourceMock); messageConsumer.setMessageListener(null); } catch (Exception e) { System.out.println("PROBLEM " + e.getMessage()); throw new RuntimeException(e); } System.out.println("EXCEPTION"); throw new RuntimeException("Fail - should imply a rollback"); } }); sendMessage(); verify(xaResourceMock, timeout(1_000L).times(1)).rollback(any(Xid.class)); }

Target:
public void testAsyncRollback() throws Exception { Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); MessageConsumer messageConsumer = session.createConsumer(queue); messageConsumer.setMessageListener(new MessageListener() { @Override @Transactional public void onMessage(Message message) { try { TransactionManager.transactionManager().getTransaction().enlistResource(xaResourceMock); messageConsumer.setMessageListener(null); } catch (Exception e) { throw new RuntimeException(e); } throw new RuntimeException("Fail - should imply a rollback"); } }); sendMessage(); verify(xaResourceMock, timeout(1_000L).times(1)).rollback(any(Xid.class)); Message receivedMessage = messageConsumer.receiveNoWait(); assertNotNull(receivedMessage); }
Source:
public void testExtractLoggingOutputs() throws Exception { StringBuilder input = new StringBuilder(); List<String> expectedOutput = new ArrayList<>(); for (int i = 0; i < 5; ++i) { String line = "BashJavaUtils output line " + i; if (i % 2 == 0) { expectedOutput.add(line); } else { line = BashJavaUtils.EXECUTION_PREFIX + line; } input.append(line + "\n"); } String[] commands = {RUN_EXTRACT_LOGGING_OUTPUTS_SCRIPT, input.toString()}; List<String> actualOutput = Arrays.asList(executeScript(commands).split(System.lineSeparator())); assertEquals(expectedOutput, actualOutput); }

Target:
public void testExtractLoggingOutputs() throws Exception { StringBuilder input = new StringBuilder(); List<String> expectedOutput = new ArrayList<>(); for (int i = 0; i < 5; ++i) { String line = "BashJavaUtils output line " + i + " `~!@#$%^&*()-_=+;:,.'\"\\\t/?"; if (i % 2 == 0) { expectedOutput.add(line); } else { line = BashJavaUtils.EXECUTION_PREFIX + line; } input.append(line + "\n"); } String[] commands = {RUN_EXTRACT_LOGGING_OUTPUTS_SCRIPT, input.toString()}; List<String> actualOutput = Arrays.asList(executeScript(commands).split(System.lineSeparator())); assertThat(actualOutput, is(expectedOutput)); }
Source:
public static void setMetrics(Configuration config) { LOG.info("Initializing HttpFSServerMetrics"); HttpFSServerWebApp.metrics = HttpFSServerMetrics.create(config, "HttpFSServer"); JvmPauseMonitor pauseMonitor = new JvmPauseMonitor(); pauseMonitor.init(config); pauseMonitor.start(); HttpFSServerWebApp.metrics.getJvmMetrics().setPauseMonitor(pauseMonitor); FSOperations.setBufferSize(config); DefaultMetricsSystem.initialize("HttpFSServer"); }

Target:
private static void setMetrics(Configuration config) { LOG.info("Initializing HttpFSServerMetrics"); metrics = HttpFSServerMetrics.create(config, "HttpFSServer"); JvmPauseMonitor pauseMonitor = new JvmPauseMonitor(); pauseMonitor.init(config); pauseMonitor.start(); metrics.getJvmMetrics().setPauseMonitor(pauseMonitor); FSOperations.setBufferSize(config); DefaultMetricsSystem.initialize("HttpFSServer"); }
Source:
public synchronized void unsubscribe(@Nonnull StreamListener streamListener) { SubscriptionThread st = subscriptions.remove(streamListener); if (st == null) { log.warn("StreamManager::unsubscribe has no context for "+streamListener.toString()); return; } st.setShutdown(true); st.interrupt(); log.info("Unsubscribed StreamListener {}", streamListener.toString()); }

Target:
public void unsubscribe(@Nonnull StreamListener streamListener) { StreamSubscriber streamSubscriber = unsubscribeInternal(streamListener); if (streamSubscriber != null) { streamSubscriber.getScheduledFuture().cancel(false); } }
Source:
public void testErrorDuringInitialization() throws Exception { dispatcher = createAndStartDispatcher(heartbeatServices, haServices, new ExpectedJobIdJobManagerRunnerFactory(TEST_JOB_ID, createdJobManagerRunnerLatch)); jobMasterLeaderElectionService.isLeader(UUID.randomUUID()); DispatcherGateway dispatcherGateway = dispatcher.getSelfGateway(DispatcherGateway.class); final FailingInitializationJobVertex failingInitializationJobVertex = new FailingInitializationJobVertex( "testVertex"); failingInitializationJobVertex.setInvokableClass(NoOpInvokable.class); JobGraph blockingJobGraph = new JobGraph(TEST_JOB_ID, "failingTestJob", failingInitializationJobVertex); dispatcherGateway.submitJob(blockingJobGraph, TIMEOUT).get(); JobStatus status; do { CompletableFuture<JobStatus> statusFuture = dispatcherGateway.requestJobStatus(blockingJobGraph.getJobID(), TIMEOUT); status = statusFuture.get(); Thread.sleep(50); Assert.assertThat(status, either(is(JobStatus.INITIALIZING)).or(is(JobStatus.FAILED))); } while (status != JobStatus.FAILED); ArchivedExecutionGraph execGraph = dispatcherGateway.requestJob(jobGraph.getJobID(), TIMEOUT).get(); Assert.assertNotNull(execGraph.getFailureInfo()); Assert.assertTrue(execGraph.getFailureInfo().getExceptionAsString().contains("Artificial test failure")); closeDispatcherAfterInitializationError(); }

Target:
public void testErrorDuringInitialization() throws Exception { dispatcher = createAndStartDispatcher(heartbeatServices, haServices, new ExpectedJobIdJobManagerRunnerFactory(TEST_JOB_ID, createdJobManagerRunnerLatch)); DispatcherGateway dispatcherGateway = dispatcher.getSelfGateway(DispatcherGateway.class); final FailingInitializationJobVertex failingInitializationJobVertex = new FailingInitializationJobVertex("testVertex"); failingInitializationJobVertex.setInvokableClass(NoOpInvokable.class); JobGraph blockingJobGraph = new JobGraph(TEST_JOB_ID, "failingTestJob", failingInitializationJobVertex); dispatcherGateway.submitJob(blockingJobGraph, TIMEOUT).get(); dispatcherGateway.requestJobResult(TEST_JOB_ID, TIMEOUT).get(); ArchivedExecutionGraph execGraph = dispatcherGateway.requestJob(jobGraph.getJobID(), TIMEOUT).get(); Assert.assertNotNull(execGraph.getFailureInfo()); Throwable throwable = execGraph.getFailureInfo().getException().deserializeError(ClassLoader.getSystemClassLoader()); assertTrue(throwable instanceof JobInitializationException); }
Source:
@Test public void testTrimLeft() throws Exception { Connection conn = DriverManager.getConnection(getUrl()); String val = "ABCD"; byte[] b = val.getBytes(); byte[] vb = val.getBytes(); String tableName = initTable(conn, b, 4, vb); ResultSet rs = conn.createStatement().executeQuery("SELECT TRIMB(b,cast('AB' as VARBINARY)),TRIMB(vb,cast('A' as VARBINARY)) FROM " + tableName + " WHERE TRIMB(b,cast('AB' as VARBINARY))='CD' and TRIMB(vb,cast('A' as VARBINARY))='BCD'"); assertTrue(rs.next()); assertEquals("CD", new String(rs.getBytes(1))); assertEquals("BCD", new String(rs.getBytes(2))); assertFalse(rs.next()); }

Target:
@Test public void testTrimLeft() throws Exception { Connection conn = DriverManager.getConnection(getUrl()); String val = "ABCD"; byte[] b = val.getBytes(); byte[] vb = val.getBytes(); String tableName = initTable(conn, b, 4, vb); ResultSet rs = conn.createStatement().executeQuery( "SELECT TRIMB(b,cast('AB' as VARBINARY)),TRIMB(vb,cast('A' as VARBINARY))" + " FROM " + tableName + " WHERE TRIMB(b,cast('AB' as VARBINARY))='CD' and TRIMB(vb,cast" + "('A' as VARBINARY))='BCD'"); assertTrue(rs.next()); assertEquals("CD", new String(rs.getBytes(1))); assertEquals("BCD", new String(rs.getBytes(2))); assertFalse(rs.next()); }
Source:
public void testInvalidRefreshToken(String opHost, String redirectUrl) throws Exception { final DevelopersApi client = Tester.api(); final RegisterSiteResponse site = RegisterSiteTest.registerSite(client, opHost, redirectUrl); final String authorizationStr = Tester.getAuthorization(site); final String invalidCode = CoreUtils.secureRandomString(); final GetAccessTokenByRefreshTokenParams params = new GetAccessTokenByRefreshTokenParams(); params.setOxdId(site.getOxdId()); params.setRefreshToken(invalidCode); try { client.getAccessTokenByRefreshToken(authorizationStr, params); } catch (ApiException ex) { assertEquals(401, ex.getCode()); } }

Target:
public void testInvalidRefreshToken(String opHost, String redirectUrl) throws Exception { final DevelopersApi client = Tester.api(); final RegisterSiteResponse site = RegisterSiteTest.registerSite(client, opHost, redirectUrl); final String authorizationStr = Tester.getAuthorization(site); final String invalidCode = CoreUtils.secureRandomString(); final GetAccessTokenByRefreshTokenParams params = new GetAccessTokenByRefreshTokenParams(); params.setOxdId(site.getOxdId()); params.setRefreshToken(invalidCode); try { client.getAccessTokenByRefreshToken(authorizationStr, params); fail("Test should throw an exception"); } catch (ApiException ex) { assertEquals(401, ex.getCode()); } }
Source:
public void checkSpecificAccessControl() { if (!userInfo.isInstructor) { throw new UnauthorizedAccessException("Instructor privilege is required to access this resource."); } String idOfCourseToDelete = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); gateKeeper.verifyAccessible(logic.getInstructorForGoogleId(idOfCourseToDelete, userInfo.id), logic.getCourse(idOfCourseToDelete), Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_COURSE); }

Target:
public void checkSpecificAccessControl() { if (!userInfo.isInstructor) { throw new UnauthorizedAccessException("Instructor privilege is required to access this resource."); } String idOfCourseToBin = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); gateKeeper.verifyAccessible(logic.getInstructorForGoogleId(idOfCourseToBin, userInfo.id), logic.getCourse(idOfCourseToBin), Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_COURSE); }
Source:
public ImmutableSet<EventClass> externalEventClasses() { return ImmutableSet.of(); }

Target:
public ImmutableSet<EventClass> externalEventClasses() { return EventClass.emptySet(); }
Source:
public int callJavaUserDefinedAggregateCombine() { m_udfBuffer.clear(); m_udfBuffer.getInt(); int functionId = m_udfBuffer.getInt(); UserDefinedAggregateFunctionRunner udafRunner = m_functionManager.getAggregateFunctionRunnerById(functionId); Throwable throwable = null; Object worker_object = null; try { assert(udafRunner != null); byte[] worker_byte_array = UserDefinedAggregateFunctionRunner.readVarbinary(m_udfBuffer); ByteArrayInputStream bis = new ByteArrayInputStream(worker_byte_array); ObjectInput in = null; try { in = new udfObjectInputStream(bis); worker_object = in.readObject(); } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { } } udafRunner.combine(worker_object); m_udfBuffer.clear(); return 0; } catch (InvocationTargetException ex1) { throwable = ex1.getCause(); } catch (Throwable ex2) { throwable = ex2; ex2.printStackTrace(); } try { assert(throwable != null); byte[] errorMsg = throwable.toString().getBytes(Constants.UTF8ENCODING); if (errorMsg.length + 4 > m_udfBuffer.capacity()) { resizeUDFBuffer(errorMsg.length + 4); } m_udfBuffer.clear(); SerializationHelper.writeVarbinary(errorMsg, m_udfBuffer); } catch (IOException e) { throw new RuntimeException(e); } return -1; }

Target:
public int callJavaUserDefinedAggregateCombine() { UserDefinedAggregateFunctionRunner udafRunner = getUdafRunner(); int udafIndex = m_udfBuffer.getInt(); Object workerObject = null; try { assert(udafRunner != null); byte[] workerByteArray = UserDefinedAggregateFunctionRunner.readVarbinary(m_udfBuffer); ByteArrayInputStream bis = new ByteArrayInputStream(workerByteArray); ObjectInput in = new UDAFObjectInputStream(bis); try { workerObject = in.readObject(); } finally { try { in.close(); } catch (IOException ex) { } } udafRunner.combine(workerObject, udafIndex); m_udfBuffer.clear(); return 0; } catch (InvocationTargetException ex1) { handleUDAFError(ex1.getCause()); } catch (Throwable ex2) { handleUDAFError(ex2); } return -1; }
Source:
public static File toFile(final Archive<?> archive, final boolean exploded) { try { File root = File.createTempFile("arquillian", archive.getName()); root.delete(); root.mkdirs(); File deployment = new File(root, archive.getName()); deployment.deleteOnExit(); archive.as(ZipExporter.class).exportTo(deployment, true); return exploded ? Unzipper.unzip(deployment, new File(new File(root, "exploded"), archive.getName())) : deployment; } catch (Exception e) { throw new RuntimeException("Could not export deployment to temp", e); } }

Target:
public static File toFile(final Archive<?> archive, final boolean exploded) { try { File root = File.createTempFile("arquillian", archive.getName()); root.delete(); root.mkdirs(); File deployment = new File(root, archive.getName()); deployment.deleteOnExit(); if (exploded) { return archive.as(ExplodedExporter.class).exportExploded(root, archive.getName()); } else { archive.as(ZipExporter.class).exportTo(deployment, true); return deployment; } } catch (Exception e) { throw new RuntimeException("Could not export deployment to temp", e); } }
Source:
public void run() { final long startTime = System.nanoTime(); final long currentTime = System.currentTimeMillis(); long timeSpent = (startTime - lastPoll) / 1000; if (timeSpent == 0) { timeSpent = 1; } if (history.size() > 10) { history.remove(); } double tps = tickInterval * 1000000.0 / timeSpent; if (tps <= 21) { history.add(tps); } lastPoll = startTime; int count = 0; for (Player player : ess.getOnlinePlayers()) { count++; if (skip1 > 0) { skip1--; continue; } if (count % 10 == 0) { if (System.nanoTime() - startTime > maxTime / 2) { skip1 = count - 1; break; } } try { final User user = ess.getUser(player); onlineUsers.add(user.getBase().getUniqueId()); user.setLastOnlineActivity(currentTime); user.checkActivity(); } catch (Exception e) { ess.getLogger().log(Level.WARNING, "EssentialsTimer Error:", e); } } count = 0; final Iterator<UUID> iterator = onlineUsers.iterator(); while (iterator.hasNext()) { count++; if (skip2 > 0) { skip2--; continue; } if (count % 10 == 0) { if (System.nanoTime() - startTime > maxTime) { skip2 = count - 1; break; } } final User user = ess.getUser(iterator.next()); if (user == null) { iterator.remove(); continue; } if (user.getLastOnlineActivity() < currentTime && user.getLastOnlineActivity() > user.getLastLogout()) { if (!user.isHidden()) { user.setLastLogout(user.getLastOnlineActivity()); } iterator.remove(); continue; } user.checkMuteTimeout(currentTime); user.checkIgnoreTimeouts(currentTime); user.checkJailTimeout(currentTime); user.resetInvulnerabilityAfterTeleport(); } }

Target:
public void run() { final long startTime = System.nanoTime(); final long currentTime = System.currentTimeMillis(); long timeSpent = (startTime - lastPoll) / 1000; if (timeSpent == 0) { timeSpent = 1; } if (history.size() > 10) { history.remove(); } double tps = tickInterval * 1000000.0 / timeSpent; if (tps <= 21) { history.add(tps); } lastPoll = startTime; int count = 0; for (Player player : ess.getOnlinePlayers()) { count++; if (skip1 > 0) { skip1--; continue; } if (count % 10 == 0) { if (System.nanoTime() - startTime > maxTime / 2) { skip1 = count - 1; break; } } try { final User user = ess.getUser(player); onlineUsers.add(user.getBase().getUniqueId()); user.setLastOnlineActivity(currentTime); user.checkActivity(); } catch (Exception e) { ess.getLogger().log(Level.WARNING, "EssentialsTimer Error:", e); } } count = 0; final Iterator<UUID> iterator = onlineUsers.iterator(); while (iterator.hasNext()) { count++; if (skip2 > 0) { skip2--; continue; } if (count % 10 == 0) { if (System.nanoTime() - startTime > maxTime) { skip2 = count - 1; break; } } final User user = ess.getUser(iterator.next()); if (user == null) { iterator.remove(); continue; } if (user.getLastOnlineActivity() < currentTime && user.getLastOnlineActivity() > user.getLastLogout()) { if (!user.isHidden()) { user.setLastLogout(user.getLastOnlineActivity()); } iterator.remove(); continue; } user.checkMuteTimeout(currentTime); user.checkJailTimeout(currentTime); user.resetInvulnerabilityAfterTeleport(); } }
Source:
public void setId() { EntityDictionary dictionary = this.requestScope.getDictionary(); String idFieldName = dictionary.getIdFieldName(this.entityClass); if(!getId().isPresent()) { String uuid = UUID.randomUUID().toString() .replaceAll("[^0-9]", "") .substring(0, 3); this.data.put(idFieldName, uuid); this.attributes.add(new Attribute(idFieldName, uuid)); } }

Target:
public void setId() { if(!getId().isPresent()) { EntityDictionary dictionary = this.requestScope.getDictionary(); String idFieldName = dictionary.getIdFieldName(this.entityClass); String uuid = UUID.randomUUID().toString() .replaceAll("[^0-9]", "") .substring(0, 3); this.attributes.add(new Attribute(idFieldName, uuid)); } }
Source:
public UiAction.Description getDescription(RevisionResource resource) { return new UiAction.Description() .setLabel("Cherry Pick") .setTitle("Cherry pick change to a different branch") .setVisible(resource.getControl().getProjectControl().canUpload() && resource.getPatchSet().getId().equals( resource.getChange().currentPatchSetId())); }

Target:
public UiAction.Description getDescription(RevisionResource resource) { return new UiAction.Description() .setLabel("Cherry Pick") .setTitle("Cherry pick change to a different branch") .setVisible(resource.getControl().getProjectControl().canUpload() && resource.isCurrent()); }
Source:
public AsyncDolphinConfiguration build() { if (trainerClass == null) { throw new RuntimeException("Trainer class is required."); } if (updaterClass == null) { throw new RuntimeException("Updater class is required."); } return new AsyncDolphinConfiguration(trainerClass, memoryStoreInitializer, updaterClass, keyCodecClass, preValueCodecClass, valueCodecClass, parameterClassList, workerSerializerClass, serverSerializerClass, workerConfiguration, serverConfiguration); }

Target:
public AsyncDolphinConfiguration build() { BuilderUtils.notNull(trainerClass); BuilderUtils.notNull(memoryStoreInitializer); BuilderUtils.notNull(updaterClass); return new AsyncDolphinConfiguration(trainerClass, memoryStoreInitializer, updaterClass, keyCodecClass, preValueCodecClass, valueCodecClass, parameterClassList, workerSerializerClass, serverSerializerClass, workerConfiguration, serverConfiguration); }
Source:
public List<Suggestion> getSuggestedNames(String queryString, int maxResults) throws GeoEntryQueryException { Map<String, Serializable> suggestProps = new HashMap<>(); suggestProps.put(SUGGESTION_QUERY_KEY, queryString); suggestProps.put(SUGGESTION_CONTEXT_KEY, GAZETTEER_METACARD_TAG); suggestProps.put(SUGGESTION_DICT_KEY, SUGGEST_PLACE_KEY); SortBy[] sortbys = { new SortByImpl(GeoCodingConstants.GAZETTEER_SORT_VALUE, SortOrder.ASCENDING) }; suggestProps.put(ADDITIONAL_SORT_BYS, sortbys); Query suggestionQuery = new QueryImpl(filterBuilder.attribute(Core.TITLE).text(queryString)); QueryRequest suggestionRequest = new QueryRequestImpl(suggestionQuery, suggestProps); try { QueryResponse suggestionResponse = catalogFramework.query(suggestionRequest); if (suggestionResponse.getPropertyValue(SUGGESTION_RESULT_KEY) instanceof List) { List<Map.Entry<String, String>> suggestions = (List<Map.Entry<String, String>>) suggestionResponse.getPropertyValue(SUGGESTION_RESULT_KEY); return suggestions .stream() .map(suggestion -> new SuggestionImpl(suggestion.getKey(), suggestion.getValue())) .limit(maxResults) .collect(Collectors.toList()); } } catch (SourceUnavailableException | FederationException | UnsupportedQueryException e) { throw new GeoEntryQueryException("Failed to execute suggestion query", e); } return Collections.emptyList(); }

Target:
public List<Suggestion> getSuggestedNames(String queryString, int maxResults) throws GeoEntryQueryException { Map<String, Serializable> suggestProps = new HashMap<>(); suggestProps.put(SUGGESTION_QUERY_KEY, queryString); suggestProps.put(SUGGESTION_CONTEXT_KEY, GAZETTEER_METACARD_TAG); suggestProps.put(SUGGESTION_DICT_KEY, SUGGEST_PLACE_KEY); Query suggestionQuery = new QueryImpl(filterBuilder.attribute(Core.TITLE).text(queryString)); QueryRequest suggestionRequest = new QueryRequestImpl(suggestionQuery, suggestProps); try { QueryResponse suggestionResponse = catalogFramework.query(suggestionRequest); if (suggestionResponse.getPropertyValue(SUGGESTION_RESULT_KEY) instanceof List) { List<Map.Entry<String, String>> suggestions = (List<Map.Entry<String, String>>) suggestionResponse.getPropertyValue(SUGGESTION_RESULT_KEY); return suggestions .stream() .map(suggestion -> new SuggestionImpl(suggestion.getKey(), suggestion.getValue())) .limit(maxResults) .collect(Collectors.toList()); } } catch (SourceUnavailableException | FederationException | UnsupportedQueryException e) { throw new GeoEntryQueryException("Failed to execute suggestion query", e); } return Collections.emptyList(); }
Source:
public void insert(final Task task, final TaskStatus status) { Preconditions.checkNotNull(task, "task"); Preconditions.checkNotNull(status, "status"); Preconditions.checkArgument( task.getId().equals(status.getId()), "Task/Status ID mismatch[%s/%s]", task.getId(), status.getId() ); log.info("Inserting task %s with status: %s", task.getId(), status); try { dbi.withHandle( new HandleCallback<Void>() { @Override public Void withHandle(Handle handle) throws Exception { handle.createStatement( String.format( "INSERT INTO %s (id, created_date, datasource, payload, active, status_payload) VALUES (:id, :created_date, :datasource, :payload, :active, :status_payload)", dbConnectorConfig.getTaskTable() ) ) .bind("id", task.getId()) .bind("created_date", new DateTime().toString()) .bind("datasource", task.getDataSource()) .bind("payload", jsonMapper.writeValueAsString(task)) .bind("active", status.isRunnable() ? 1 : 0) .bind("status_payload", jsonMapper.writeValueAsString(status)) .execute(); return null; } } ); } catch (StatementException e) { if(getTask(task.getId()).isPresent()) { throw new TaskExistsException(task.getId(), e); } else { throw e; } } }

Target:
public void insert(final Task task, final TaskStatus status) { Preconditions.checkNotNull(task, "task"); Preconditions.checkNotNull(status, "status"); Preconditions.checkArgument( task.getId().equals(status.getId()), "Task/Status ID mismatch[%s/%s]", task.getId(), status.getId() ); log.info("Inserting task %s with status: %s", task.getId(), status); try { dbi.withHandle( new HandleCallback<Void>() { @Override public Void withHandle(Handle handle) throws Exception { handle.createStatement( String.format( "INSERT INTO %s (id, created_date, datasource, payload, active, status_payload) VALUES (:id, :created_date, :datasource, :payload, :active, :status_payload)", dbConnectorConfig.getTaskTable() ) ) .bind("id", task.getId()) .bind("created_date", new DateTime().toString()) .bind("datasource", task.getDataSource()) .bind("payload", jsonMapper.writeValueAsBytes(task)) .bind("active", status.isRunnable() ? 1 : 0) .bind("status_payload", jsonMapper.writeValueAsBytes(status)) .execute(); return null; } } ); } catch (StatementException e) { if(getTask(task.getId()).isPresent()) { throw new TaskExistsException(task.getId(), e); } else { throw e; } } }
Source:
protected void uploadFiles(TopicPartition topicPartition) throws Exception { long committedOffsetCount = mOffsetTracker.getTrueCommittedOffsetCount(topicPartition); long lastSeenOffset = mOffsetTracker.getLastSeenOffset(topicPartition); String stripped = StringUtils.strip(mConfig.getZookeeperPath(), "/"); final String lockPath = Joiner.on("/").skipNulls().join( "", stripped.isEmpty() ? null : stripped, "secor", "locks", topicPartition.getTopic(), topicPartition.getPartition()); mZookeeperConnector.lock(lockPath); try { long zookeeperCommittedOffsetCount = mZookeeperConnector.getCommittedOffsetCount( topicPartition); if (zookeeperCommittedOffsetCount == committedOffsetCount) { LOG.info("uploading topic partition {}", topicPartition.getTopic(), topicPartition.getPartition()); mFileRegistry.deleteWriters(topicPartition); Collection<LogFilePath> paths = mFileRegistry.getPaths(topicPartition); List<Handle<?>> uploadHandles = new ArrayList<Handle<?>>(); for (LogFilePath path : paths) { uploadHandles.add(mUploadManager.upload(path)); } for (Handle<?> uploadHandle : uploadHandles) { uploadHandle.get(); } mFileRegistry.deleteTopicPartition(topicPartition); mZookeeperConnector.setCommittedOffsetCount(topicPartition, lastSeenOffset + 1); mOffsetTracker.setCommittedOffsetCount(topicPartition, lastSeenOffset + 1); if (mConfig.getOffsetsStorage().equals("kafka")) { mMessageReader.commit(); } mMetricCollector.increment("uploader.file_uploads.count", paths.size(), topicPartition.getTopic()); } } finally { mZookeeperConnector.unlock(lockPath); } }

Target:
protected void uploadFiles(TopicPartition topicPartition) throws Exception { long committedOffsetCount = mOffsetTracker.getTrueCommittedOffsetCount(topicPartition); long lastSeenOffset = mOffsetTracker.getLastSeenOffset(topicPartition); String stripped = StringUtils.strip(mConfig.getZookeeperPath(), "/"); final String lockPath = Joiner.on("/").skipNulls().join( "", stripped.isEmpty() ? null : stripped, "secor", "locks", topicPartition.getTopic(), topicPartition.getPartition()); mZookeeperConnector.lock(lockPath); try { long zookeeperCommittedOffsetCount = mZookeeperConnector.getCommittedOffsetCount( topicPartition); if (zookeeperCommittedOffsetCount == committedOffsetCount) { LOG.info("uploading topic partition {}", topicPartition.getTopic(), topicPartition.getPartition()); mFileRegistry.deleteWriters(topicPartition); Collection<LogFilePath> paths = mFileRegistry.getPaths(topicPartition); List<Handle<?>> uploadHandles = new ArrayList<Handle<?>>(); for (LogFilePath path : paths) { uploadHandles.add(mUploadManager.upload(path)); } for (Handle<?> uploadHandle : uploadHandles) { uploadHandle.get(); } mFileRegistry.deleteTopicPartition(topicPartition); mZookeeperConnector.setCommittedOffsetCount(topicPartition, lastSeenOffset + 1); mOffsetTracker.setCommittedOffsetCount(topicPartition, lastSeenOffset + 1); if (isOffsetsStorageKafka) { mMessageReader.commit(); } mMetricCollector.increment("uploader.file_uploads.count", paths.size(), topicPartition.getTopic()); } } finally { mZookeeperConnector.unlock(lockPath); } }
Source:
public static void redefineProperty(String name, String value, ModelControllerClient client) { ModelNode modelNode = createOpNode("system-property=" + name, WRITE_ATTRIBUTE_OPERATION); modelNode.get(NAME).set(VALUE); modelNode.get(VALUE).set(value); modelNode.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true); ModelNode result = executeOp(modelNode, client); log.debugf("Redefine property %s to value %s. Result: %s.", name, value, result); }

Target:
public static void redefineProperty(String name, String value, ModelControllerClient client) { ModelNode modelNode = createOpNode("system-property=" + name, WRITE_ATTRIBUTE_OPERATION); modelNode.get(NAME).set(VALUE); modelNode.get(VALUE).set(value); ModelNode result = executeOp(modelNode, client); log.debugf("Redefine property %s to value %s. Result: %s.", name, value, result); }
Source:
public void testTableSink() { final DataType consumedDataType = SINK_SCHEMA.toPhysicalRowDataType(); SinkFormat<SerializationSchema<RowData>> sinkFormat = new TestFormatFactory.SinkFormatMock(","); ObjectIdentifier objectIdentifier = ObjectIdentifier.of( "default", "default", "sinkTable"); final CatalogTable sinkTable = createKafkaSinkCatalogTable(); final DynamicTableSink actualSink = FactoryUtil.createTableSink( null, objectIdentifier, sinkTable, new Configuration(), Thread.currentThread().getContextClassLoader()); assertThat(actualSink, instanceOf(getExpectedSinkClass())); assertThat(actualSink, instanceOf(KafkaSinkBase.class)); final KafkaSinkBase kafkaSink = (KafkaSinkBase) actualSink; assertEquals(consumedDataType, kafkaSink.consumedDataType); assertEquals(TOPIC, kafkaSink.topic); assertEquals(KAFKA_PROPERTIES, kafkaSink.properties); assertThat(kafkaSink.partitioner.isPresent(), is(true)); assertThat(kafkaSink.partitioner.get(), instanceOf(FlinkFixedPartitioner.class)); final KafkaSinkBase actualKafkaSink = (KafkaSinkBase) actualSink; assertEquals(sinkFormat, actualKafkaSink.sinkFormat); DynamicTableSink.SinkRuntimeProvider provider = actualKafkaSink.getSinkRuntimeProvider(new SinkRuntimeProviderContext(false)); assertThat(provider, instanceOf(SinkFunctionProvider.class)); final SinkFunctionProvider sinkFunctionProvider = (SinkFunctionProvider) provider; final SinkFunction<RowData> sinkFunction = sinkFunctionProvider.createSinkFunction(); assertThat(sinkFunction, instanceOf(getExpectedProducerClass())); }

Target:
public void testTableSink() { final DataType consumedDataType = SINK_SCHEMA.toPhysicalRowDataType(); SinkFormat<SerializationSchema<RowData>> sinkFormat = new TestFormatFactory.SinkFormatMock(","); ObjectIdentifier objectIdentifier = ObjectIdentifier.of( "default", "default", "sinkTable"); final CatalogTable sinkTable = createKafkaSinkCatalogTable(); final DynamicTableSink actualSink = FactoryUtil.createTableSink( null, objectIdentifier, sinkTable, new Configuration(), Thread.currentThread().getContextClassLoader()); final DynamicTableSink expectedSink = getExpectedSink( consumedDataType, TOPIC, KAFKA_PROPERTIES, Optional.of(new FlinkFixedPartitioner<>()), sinkFormat); assertEquals(expectedSink, actualSink); final KafkaSinkBase actualKafkaSink = (KafkaSinkBase) actualSink; assertEquals(sinkFormat, actualKafkaSink.sinkFormat); DynamicTableSink.SinkRuntimeProvider provider = actualKafkaSink.getSinkRuntimeProvider(new SinkRuntimeProviderContext(false)); assertThat(provider, instanceOf(SinkFunctionProvider.class)); final SinkFunctionProvider sinkFunctionProvider = (SinkFunctionProvider) provider; final SinkFunction<RowData> sinkFunction = sinkFunctionProvider.createSinkFunction(); assertThat(sinkFunction, instanceOf(getExpectedProducerClass())); }
Source:
private static ImmutableSet<Flavor> getValidFlavors(Flavored flavored, BuildTarget target) { return target.getFlavors().stream() .filter(flavor -> flavored.hasFlavors(ImmutableSet.of(flavor))) .collect(collectingAndThen(toList(), ImmutableSet::copyOf)); }

Target:
private static ImmutableSet<Flavor> getValidFlavors(Flavored flavored, BuildTarget target) { return target .getFlavors() .stream() .filter(flavor -> flavored.hasFlavors(ImmutableSet.of(flavor))) .collect(ImmutableSet.toImmutableSet()); }
Source:
private void flushEventFile(File eventFile) { try { EventPayload payload = new EventPayload(config.getApiKey(), eventFile); DeliveryParams deliveryParams = config.getErrorApiDeliveryParams(); DeliveryStatus deliveryStatus = config.getDelivery().deliver(payload, deliveryParams); switch (deliveryStatus) { case DELIVERED: deleteStoredFiles(Collections.singleton(eventFile)); logger.i("Deleting sent error file " + eventFile.getName()); break; case UNDELIVERED: cancelQueuedFiles(Collections.singleton(eventFile)); logger.w("Could not send previously saved error(s)" + " to Bugsnag, will try again later"); break; case FAILURE: Exception exc = new RuntimeException("Failed to deliver eventPayload"); handleEventFlushFailure(exc, eventFile); break; default: break; } } catch (Exception exception) { handleEventFlushFailure(exception, eventFile); } }

Target:
private void flushEventFile(File eventFile) { try { EventPayload payload = new EventPayload(config.getApiKey(), eventFile); DeliveryParams deliveryParams = config.getErrorApiDeliveryParams(); DeliveryStatus deliveryStatus = config.getDelivery().deliver(payload, deliveryParams); switch (deliveryStatus) { case DELIVERED: deleteStoredFiles(Collections.singleton(eventFile)); logger.i("Deleting sent error file " + eventFile.getName()); break; case UNDELIVERED: cancelQueuedFiles(Collections.singleton(eventFile)); logger.w("Could not send previously saved error(s)" + " to Bugsnag, will try again later"); break; case FAILURE: Exception exc = new RuntimeException("Failed to deliver event payload"); handleEventFlushFailure(exc, eventFile); break; default: break; } } catch (Exception exception) { handleEventFlushFailure(exception, eventFile); } }