auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public IStatus validate(final Object value) { final String content = inputExpression.getContent(); final WebPageRepositoryStore repositoryStore = repositoryAccessor.getRepositoryStore(WebPageRepositoryStore.class); final String errorMessage = ProcessPackage.Literals.RECAP_FLOW__OVERVIEW_FORM_MAPPING.equals(feature) ? Messages.bind(Messages.pageDoesntExists, String.format("%s (%s)", inputExpression.getName(), content)) : Messages.bind(Messages.formDoesntExists, String.format("%s (%s)", inputExpression.getName(), content)); return repositoryStore.getChild(content) == null ? ValidationStatus.error(errorMessage) : ValidationStatus.ok(); }

Target:
public IStatus validate(final Object value) { final String content = inputExpression.getContent(); final WebPageRepositoryStore repositoryStore = repositoryAccessor.getRepositoryStore(WebPageRepositoryStore.class); String errorMessage = null; if (ProcessPackage.Literals.RECAP_FLOW__OVERVIEW_FORM_MAPPING.equals(feature)) { errorMessage = Messages.bind(Messages.pageDoesntExist, content); } else { errorMessage = Messages.bind(Messages.formDoesntExist, content); } return repositoryStore.getChild(content) == null ? ValidationStatus.error(errorMessage) : ValidationStatus.ok(); }
Source:
private List<LdapUserResponse> applyUserFilter(List<LdapUserResponse> ldapResponses) { if(s_logger.isTraceEnabled()) { s_logger.trace(String.format("applying filter: %s or %s.", this.getListTypeString(), this.getUserFilter())); } Method filterMethod = getFilterMethod(); List<LdapUserResponse> responseList = ldapResponses; if (filterMethod != null) { if(s_logger.isTraceEnabled()) { s_logger.trace("applying filter: " + filterMethod.getName()); } try { responseList = (List<LdapUserResponse>)filterMethod.invoke(this, ldapResponses); } catch (IllegalAccessException | InvocationTargetException e) { throw new CloudRuntimeException("we're damned, the earth is screwed. we will now return to our maker",e); } } return responseList; }

Target:
private List<LdapUserResponse> applyUserFilter(List<LdapUserResponse> ldapResponses) { if(s_logger.isTraceEnabled()) { s_logger.trace(String.format("applying filter: %s or %s.", this.getListTypeString(), this.getUserFilter())); } List<LdapUserResponse> responseList = getUserFilter().filter(this,ldapResponses); return responseList; }
Source:
public ChassisTurnAbsolute(Chassis chassis, double finalAngle, IMU imu, CommandBase fallbackCommand, MotionController motionController) { super(chassis, finalAngle, imu, fallbackCommand, motionController); }

Target:
public ChassisTurnAbsolute(Chassis chassis, double finalAngle, IMU imu, CommandBase fallbackCommand, MotionController motionController) { super("Chassis Turn Absolute", chassis, finalAngle, imu, fallbackCommand, motionController); }
Source:
private Task<String> tryAcquire(String lockNode, long deadline) { return _zkClient.getChildren(_lockPath) .flatMap(children -> { children = children.stream().map(child -> ZKUtil.noramlizeZKPath(_lockPath, child)) .collect(Collectors.toList()); String node = ZKUtil.findNodeWithNextLowestSN(children, lockNode); if (node.equals(lockNode)) { return PlanLocal.put(getPlanLocalKey(), new LockInternal(lockNode)).map(unused -> lockNode); } else { Task<Void> wait = Task.async(context -> { AtomicBoolean committed = new AtomicBoolean(false); SettablePromise<Void> promise = Promises.settable(); Task<Optional<Stat>> exists = _zkClient.exists(node).withWatcher(watchEvent -> { if (committed.compareAndSet(false, true)) { promise.done(null); } }).andThen(stat -> { if (!stat.isPresent() && committed.compareAndSet(false, true)) { promise.done(null); } }); context.run(exists); return promise; }); return wait.flatMap(unused -> tryAcquire(lockNode, deadline)); } }) .recoverWith(e -> retry(e, deadline, tryAcquire(lockNode, deadline))); }

Target:
private Task<String> tryAcquire(String lockNode, long deadline) { return _zkClient.getChildren(_lockPath) .flatMap(children -> { children = children.stream().map(child -> ZKUtil.normalizeZKPath(_lockPath, child)) .collect(Collectors.toList()); String node = ZKUtil.findNodeWithNextLowestSN(children, lockNode); if (node.equals(lockNode)) { return PlanLocal.put(getPlanLocalKey(), new LockInternal(lockNode)).map(unused -> lockNode); } else { Task<Void> wait = Task.async(context -> { AtomicBoolean committed = new AtomicBoolean(false); SettablePromise<Void> promise = Promises.settable(); Task<Optional<Stat>> exists = _zkClient.exists(node).withWatcher(watchEvent -> { if (committed.compareAndSet(false, true)) { promise.done(null); } }).andThen(stat -> { if (!stat.isPresent() && committed.compareAndSet(false, true)) { promise.done(null); } }); context.run(exists); return promise; }); return wait.flatMap(unused -> tryAcquire(lockNode, deadline)); } }) .recoverWith(e -> retry(e, deadline, tryAcquire(lockNode, deadline))); }
Source:
public void onMatch(RelOptRuleCall call) { final Project project = call.rel(0); VbuilderPAP vb = buildProcessor(call); RelNode newProject = vb.processProject(project); if (newProject instanceof Project && ((Project) newProject).getChildExps().equals(project.getChildExps())) { return; } else { call.transformTo(newProject); } }

Target:
public void onMatch(RelOptRuleCall call) { final Project project = call.rel(0); VbuilderPAP vb = buildProcessor(call); RelNode newProject = vb.processProject(project); if (newProject == project) { return; } else { call.transformTo(newProject); } }
Source:
private Map<String, DbParameterAccessor> readIntoParams( String[] queryParameters, String query) throws SQLException { try (PreparedStatement dc = currentConnection.prepareStatement(query)) { for (int i = 0; i < queryParameters.length; i++) { dc.setString(i + 1, NameNormaliserPostgres.normaliseName(queryParameters[i])); } ResultSet rs = dc.executeQuery(); Map<String, DbParameterAccessor> allParams = new HashMap<String, DbParameterAccessor>(); int position = 0; while (rs.next()) { String paramName = rs.getString(1); if (paramName == null) paramName = ""; String dataType = rs.getString(2); DbParameterAccessor dbp = createDbParameterAccessor( '"'+paramName+'"', Direction.INPUT, getSqlType(dataType), getJavaClass(dataType), position++); allParams.put(NameNormaliser.normaliseName(paramName), dbp); } rs.close(); return allParams; } }

Target:
private Map<String, DbParameterAccessor> readIntoParams( String[] queryParameters, String query) throws SQLException { try (PreparedStatement dc = currentConnection.prepareStatement(query)) { for (int i = 0; i < queryParameters.length; i++) { dc.setString(i + 1, NameNormaliserPostgres.normaliseName(queryParameters[i])); } ResultSet rs = dc.executeQuery(); Map<String, DbParameterAccessor> allParams = new HashMap<String, DbParameterAccessor>(); int position = 0; while (rs.next()) { String paramName = rs.getString(1); if (paramName == null) paramName = ""; paramName = paramName.replace("\"","\"\""); String dataType = rs.getString(2); DbParameterAccessor dbp = createDbParameterAccessor( '"' + paramName + '"', Direction.INPUT, getSqlType(dataType), getJavaClass(dataType), position++); allParams.put(NameNormaliser.normaliseName(paramName), dbp); } rs.close(); return allParams; } }
Source:
public void equality() throws Exception { NotFilter filter = NotFilter.newBuilder() .setFilter(new UTQueryFilter("host", "web01|web02")) .build(); NotFilter filter2 = NotFilter.newBuilder() .setFilter(new UTQueryFilter("host", "web01|web02")) .build(); NotFilter filter3 = NotFilter.newBuilder() .setFilter(new UTQueryFilter("hostname", "web01|web02")) .build(); assertTrue(filter.equals(filter2)); assertTrue(!filter.equals(filter3)); assertEquals(filter.hashCode(), filter2.hashCode()); assertNotEquals(filter.hashCode(), filter3.hashCode()); filter3 = NotFilter.newBuilder() .setFilter(new UTQueryFilter("host", "web01")) .build(); assertTrue(!filter.equals(filter3)); assertNotEquals(filter.hashCode(), filter3.hashCode()); }

Target:
public void equality() throws Exception { NotFilter filter = NotFilter.newBuilder() .setFilter(new UTQueryFilter("host", "web01|web02")) .build(); NotFilter filter2 = NotFilter.newBuilder() .setFilter(new UTQueryFilter("host", "web01|web02")) .build(); NotFilter filter3 = NotFilter.newBuilder() .setFilter(new UTQueryFilter("hostname", "web01|web02")) .build(); assertTrue(filter.equals(filter2)); assertTrue(!filter.equals(filter3)); assertEquals(filter.hashCode(), filter2.hashCode()); assertNotEquals(filter.hashCode(), filter3.hashCode()); filter3 = NotFilter.newBuilder() .setFilter(new UTQueryFilter("host", "web01")) .build(); assertTrue(!filter.equals(filter3)); assertNotEquals(filter.hashCode(), filter3.hashCode()); assertNotEquals(filter, filter.getFilter()); }
Source:
public void testFilterEmptySketch() { DoubleSummaryFactory factory = new DoubleSummaryFactory(DoubleSummary.Mode.Sum); Sketch<DoubleSummary> sketch = Sketches.createEmptySketch(); Filter<DoubleSummary> filter = new Filter<>(o -> true, factory); Sketch<DoubleSummary> filteredSketch = filter.filter(sketch); Assert.assertEquals(filteredSketch.getEstimate(), 0.0d); Assert.assertEquals(filteredSketch.getThetaLong(), sketch.getThetaLong()); }

Target:
public void testFilterEmptySketch() { Sketch<DoubleSummary> sketch = Sketches.createEmptySketch(); Filter<DoubleSummary> filter = new Filter<>(o -> true); Sketch<DoubleSummary> filteredSketch = filter.filter(sketch); Assert.assertEquals(filteredSketch.getEstimate(), 0.0d); Assert.assertEquals(filteredSketch.getThetaLong(), sketch.getThetaLong()); Assert.assertTrue(filteredSketch.isEmpty()); }
Source:
public void verifyMonetizationModuleSlot() { List<WebElement> listWebElements = driver.findElements(MonetizationModuleList); for (WebElement elem : listWebElements) { String slotName = elem.getAttribute("data-mon-slot"); switch (slotName) { case "above_title": verifyMonetizationModuleShownAboveTitle(); break; case "below_title": verifyMonetizationModuleShownBelowTitle(); break; case "in_content": verifyMonetizationModuleShownInContent(); break; case "below_category": verifyMonetizationModuleShownBelowCategory(); break; case "above_footer": verifyMonetizationModuleShownAboveFooter(); break; } } }

Target:
public void verifyMonetizationModuleSlot() { List<WebElement> listWebElements = driver.findElements(MonetizationModuleListBy); for (WebElement elem : listWebElements) { String slotName = elem.getAttribute(attributeNameSlot); switch (slotName) { case "above_title": verifyMonetizationModuleShownAboveTitle(); break; case "below_title": verifyMonetizationModuleShownBelowTitle(); break; case "in_content": verifyMonetizationModuleShownInContent(); break; case "below_category": verifyMonetizationModuleShownBelowCategory(); break; case "above_footer": verifyMonetizationModuleShownAboveFooter(); break; default: PageObjectLogging.log("verifyMonetizationModuleSlot", "Invalid slot name (Name: " + slotName + ")", true); break; } } }
Source:
public void onResume() { super.onResume(); int productCount = sp.getInt("productCount", 0); apiClient.getTotalProductCount(getString(R.string.app_name) + " " + Utils.getUserAgent("OTHERS")) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new SingleObserver<Search>() { @Override public void onSubscribe(Disposable d) { disposable=d; if(isAdded()) { updateTextHome(productCount); } } @Override public void onSuccess(Search search) { if(isAdded()) { int totalProductCount = productCount; try { totalProductCount = Integer.parseInt(search.getCount()); } catch (NumberFormatException e) { Log.w(HomeFragment.class.getSimpleName(), "can parse " + search.getCount() + " as int", e); } updateTextHome(totalProductCount); SharedPreferences.Editor editor = sp.edit(); editor.putInt("productCount", totalProductCount); editor.apply(); } } @Override public void onError(Throwable e) { if(isAdded()) { updateTextHome(productCount); } } }); getTagline(); if (getActivity() instanceof AppCompatActivity) { ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar(); if (actionBar != null) { actionBar.setTitle(""); } } }

Target:
public void onResume() { super.onResume(); int productCount = sp.getInt("productCount", 0); apiClient.getTotalProductCount(Utils.getUserAgent()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new SingleObserver<Search>() { @Override public void onSubscribe(Disposable d) { disposable=d; if(isAdded()) { updateTextHome(productCount); } } @Override public void onSuccess(Search search) { if(isAdded()) { int totalProductCount = productCount; try { totalProductCount = Integer.parseInt(search.getCount()); } catch (NumberFormatException e) { Log.w(HomeFragment.class.getSimpleName(), "can parse " + search.getCount() + " as int", e); } updateTextHome(totalProductCount); SharedPreferences.Editor editor = sp.edit(); editor.putInt("productCount", totalProductCount); editor.apply(); } } @Override public void onError(Throwable e) { if(isAdded()) { updateTextHome(productCount); } } }); getTagline(); if (getActivity() instanceof AppCompatActivity) { ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar(); if (actionBar != null) { actionBar.setTitle(""); } } }
Source:
public Object getPayload() { InputStream inputStream; try { inputStream = inputStream(); } catch (IOException e1) { throw new UncheckedIOException(new SoftEndOfStreamException("Socket closed when getting input stream", e1)); } try { return getDeserializer() .deserialize(inputStream); } catch (IOException e) { throw new UncheckedIOException(e); } }

Target:
public Object getPayload() { InputStream inputStream; try { inputStream = inputStream(); } catch (IOException e1) { throw new SoftEndOfStreamException("Socket closed when getting input stream", e1); } try { return getDeserializer() .deserialize(inputStream); } catch (IOException e) { throw new UncheckedIOException(e); } }
Source:
public RGBValues createRGBValues() { return new RGBValues(209, 209, 209); }

Target:
public RGBValues createRGBValues() { return new RGBValues(0, 0, 0); }
Source:
public CompletionStage<RestResponse> synchronizeData(Integer readBatch, Integer threads) { Request.Builder builder = new Request.Builder(); StringBuilder sb = new StringBuilder(cacheUrl + "?action=sync-data"); if (readBatch != null) { sb.append("&read-batch=" + readBatch); } if (threads != null) { sb.append("&threads=" + threads); } builder.url(sb.toString()).get(); return client.execute(builder); }

Target:
public CompletionStage<RestResponse> synchronizeData(Integer readBatch, Integer threads) { Request.Builder builder = new Request.Builder(); StringBuilder sb = new StringBuilder(cacheUrl + "?action=sync-data"); if (readBatch != null) { sb.append("&read-batch=").append(readBatch); } if (threads != null) { sb.append("&threads=").append(threads); } builder.url(sb.toString()).get(); return client.execute(builder); }
Source:
private Task createTaskForEventsWithName(List<EventBase> events, String taskName) { final Task overallTask; if (!events.isEmpty()) { Collections.sort(events); overallTask = new Task(taskName, events.get(0).getTimestamp(), addDeltaTo(events.get(events.size() - 1).getTimestamp())); for (EventBase event : events) { overallTask.addSubtask( new Task(event.toString(), event.getTimestamp(), addDeltaTo(event.getTimestamp()))); } } else { overallTask = new Task(taskName, new Date(), addDeltaTo(new Date())); } return overallTask; }

Target:
private Task createTaskForEventsWithName(List<EventBase> events, String taskName) { Task overallTask; if (!events.isEmpty()) { Collections.sort(events); overallTask = new Task(taskName, events.get(0).getTimestamp(), addDeltaTo(events.get(events.size() - 1).getTimestamp())); for (EventBase event : events) { overallTask.addSubtask( new Task(event.toString(), event.getTimestamp(), addDeltaTo(event.getTimestamp()))); } } else { overallTask = new Task(taskName, new Date(), addDeltaTo(new Date())); } return overallTask; }
Source:
private ParseTree parseAssignment(Expression expressionIn, boolean mayHaveColonType) { if (peek(TokenType.YIELD) && inGeneratorContext()) { return parseYield(expressionIn); } SourcePosition start = getTreeStartLocation(); GenericTypeListTree generics = maybeParseGenericTypes(); ParseTree left = parseConditional(expressionIn); ParseTree returnType = null; if (peek(TokenType.COLON) && mayHaveColonType) { returnType = parseTypeAnnotation(); } if (peek(TokenType.ARROW)) { FormalParameterListTree params = transformArrowFunctionParameters(start, left); if (peek(TokenType.COLON)) { parseTypeAnnotation(); } return parseArrowFunctionTail(start, generics, params, returnType, expressionIn); } if (left.type == ParseTreeType.FORMAL_PARAMETER_LIST) { reportError("invalid paren expression"); } if (peekAssignmentOperator()) { left = transformLeftHandSideExpression(left); if (!left.isValidAssignmentTarget()) { reportError("invalid assignment target"); } Token operator = nextToken(); ParseTree right = parseAssignment(expressionIn, mayHaveColonType); return new BinaryOperatorTree(getTreeLocation(start), left, operator, right); } return left; }

Target:
private ParseTree parseAssignment(Expression expressionIn, boolean mayHaveColonType) { if (peek(TokenType.YIELD) && inGeneratorContext()) { return parseYield(expressionIn); } SourcePosition start = getTreeStartLocation(); GenericTypeListTree generics = maybeParseGenericTypes(); ParseTree left = parseConditional(expressionIn); ParseTree returnType = null; if (peek(TokenType.COLON) && mayHaveColonType) { colonTypeTokens.add(peekToken()); returnType = parseTypeAnnotation(); } if (peek(TokenType.ARROW)) { FormalParameterListTree params = transformArrowFunctionParameters(start, left); colonTypeTokens.clear(); if (peek(TokenType.COLON)) { parseTypeAnnotation(); } return parseArrowFunctionTail(start, generics, params, returnType, expressionIn); } if (generics != null) { reportError("invalid location for generics"); } if (left.type == ParseTreeType.FORMAL_PARAMETER_LIST) { reportError("invalid paren expression"); } if (peekAssignmentOperator()) { left = transformLeftHandSideExpression(left); if (!left.isValidAssignmentTarget()) { reportError("invalid assignment target"); } Token operator = nextToken(); ParseTree right = parseAssignment(expressionIn, mayHaveColonType); return new BinaryOperatorTree(getTreeLocation(start), left, operator, right); } if (peek(TokenType.CLOSE_PAREN)) { if (!peek(1, TokenType.ARROW) && !peek(1, TokenType.COLON)) { reportInvalidColonTypes(); } } else if (!peek(TokenType.COMMA)) { reportInvalidColonTypes(); } return left; }
Source:
public String name() { return "db"; }

Target:
protected String name() { return "db"; }
Source:
public void stopServer() throws CommandFailedException, IOException { offlineClient.apply(CONFIGURATION_BACKUP.restore()); controller.stop(ManualTests.ARQUILLIAN_CONTAINER); }

Target:
public void stopServer() throws CommandFailedException, IOException { controller.stop(ManualTests.ARQUILLIAN_CONTAINER); offlineClient.apply(CONFIGURATION_BACKUP.restore()); }
Source:
public static boolean checkSpaces(String s) { boolean isPrevNum = false; boolean isPrevSpace = false; for (int i = 0; i < s.length(); ++i) { char c = s.charAt(i); if ((isPrevNum) && (isPrevSpace) && (Character.isDigit(c))) { return false; } else { if ((isPrevNum) && ((c == ' ') || (c == ' '))) { isPrevSpace = true; } else { if ((!isPrevNum) && (Character.isDigit(c))) { isPrevNum = true; isPrevSpace = false; } else { if ((c != ' ') && (c != ' ')) { isPrevSpace = false; } } } } if ((!Character.isDigit(c)) && (c != ' ') && (c != ' ')) { isPrevNum = false; } } return true; }

Target:
public static boolean checkSpaces(String s) { boolean isPrevNum = false; boolean isPrevSpace = false; for (int i = 0; i < s.length(); ++i) { char c = s.charAt(i); if ((isPrevNum) && (isPrevSpace) && (Character.isDigit(c))) { return false; } else { if ((isPrevNum) && (Character.isWhitespace(c))) { isPrevSpace = true; } else { if ((!isPrevNum) && (Character.isDigit(c))) { isPrevNum = true; isPrevSpace = false; } else { if (!Character.isWhitespace(c)) { isPrevSpace = false; } } } } if ((!Character.isDigit(c)) && (!Character.isWhitespace(c))) { isPrevNum = false; } } return true; }
Source:
public abstract void checkApiRateLimit(@NonNull TaskListener listener, GitHub github) throws IOException, InterruptedException; private static void waitUntilRateLimit(@NonNull TaskListener listener, GitHub github, GHRateLimit rateLimit, long expiration) throws InterruptedException, IOException { long nextNotify = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(3); while (expiration > System.currentTimeMillis()) { if (Thread.interrupted()) { throw new InterruptedException(); } long sleep = Math.min(expiration, nextNotify) - System.currentTimeMillis(); if (sleep > 0) { Thread.sleep(sleep); } nextNotify += TimeUnit.SECONDS.toMillis(180); long now = System.currentTimeMillis(); if (now < expiration) { GHRateLimit current = github.getRateLimit(); if (current.remaining > rateLimit.remaining || current.getResetDate().getTime() > rateLimit.getResetDate().getTime()) { listener.getLogger().println(GitHubConsoleNote.create(now, "GitHub API Usage: The quota may have been refreshed earlier than expected, rechecking..." )); break; } listener.getLogger().println(GitHubConsoleNote.create(now, String.format( "GitHub API Usage: Still sleeping, now only %s remaining.", Util.getTimeSpanString(expiration - now) ))); } } }

Target:
public abstract void checkApiRateLimit(@NonNull TaskListener listener, GitHub github) throws IOException, InterruptedException; static int calculateBuffer(int limit) { return Math.max(15, limit / 20); }
Source:
public void handleException(HttpServletRequest httpRequest, HttpServletResponse httpResponse, Exception e) throws IOException { SecurityContext context = SecurityContextHolder.getContext(); String message = "There was an error authenticating you. Please check the server logs, or contact your the go administrator."; httpRequest.getSession().setAttribute(AbstractProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY, new RuntimeException(message)); httpRequest.setAttribute(SessionDenialAwareAuthenticationProcessingFilterEntryPoint.SESSION_DENIED, true); context.setAuthentication(null); httpResponse.sendRedirect("/go/auth/login?login_error=1"); LOG.error(e.getMessage()); LOG.trace(e.getMessage(), e); }

Target:
public void handleException(HttpServletRequest httpRequest, HttpServletResponse httpResponse, Exception e) throws IOException { String message = "There was an error authenticating you. Please check the server logs, or contact your the go administrator."; if (hasAccept(httpRequest, "text/html") || hasAccept(httpRequest, "application/xhtml")) { SecurityContext context = SecurityContextHolder.getContext(); httpRequest.getSession().setAttribute(AbstractProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY, new RuntimeException(message)); httpRequest.setAttribute(SessionDenialAwareAuthenticationProcessingFilterEntryPoint.SESSION_DENIED, true); context.setAuthentication(null); httpResponse.sendRedirect("/go/auth/login?login_error=1"); LOG.error(e.getMessage()); LOG.trace(e.getMessage(), e); return; } if (hasAccept(httpRequest, "application/vnd.go.cd.v1+json") || hasAccept(httpRequest, "application/json")) { String msg = String.format("{\n \"message\": \"%s\"\n}\n", message); generateResponse(httpResponse, "application/vnd.go.cd.v1+json; charset=utf-8", msg); return; } if (hasAccept(httpRequest, "application/xml")) { String msg = String.format("<message>%s</message>\n", message); generateResponse(httpResponse, "application/xml; charset=utf-8", msg); return; } httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); }
Source:
private Lane getLaneNodeById(Diagram<Graph, Metadata> diagram, String id) { Node<? extends Definition, ?> node = getNodebyId(diagram, id); return Lane.class.cast(node.getContent().getDefinition()); }

Target:
private Lane getLaneNodeById(Diagram<Graph, Metadata> diagram, String id) { Node<? extends Definition, ?> node = getNodebyId(diagram, id); return (Lane) node.getContent().getDefinition(); }
Source:
private void registerWithZooKeeper(CuratorFramework client) { try { String jvmName = containerMetadata.getJvmName(); String tokens[] = jvmName.split("@"); StringBuilder builder = new StringBuilder() .append("pid=").append(tokens[0]) .append(System.lineSeparator()) .append("host=").append(tokens[1]); client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath( Paths.CONTAINERS + "/" + containerMetadata.getId(), builder.toString().getBytes("UTF-8")); logger.info("Started container " + containerMetadata.getId() + " with attributes: " + builder); } catch (Exception e) { throw new RuntimeException(e); } }

Target:
private void registerWithZooKeeper(CuratorFramework client) { try { String jvmName = containerMetadata.getJvmName(); String tokens[] = jvmName.split("@"); StringBuilder builder = new StringBuilder() .append("pid=").append(tokens[0]) .append(System.getProperty("line.separator")) .append("host=").append(tokens[1]); client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath( Paths.CONTAINERS + "/" + containerMetadata.getId(), builder.toString().getBytes("UTF-8")); logger.info("Started container " + containerMetadata.getId() + " with attributes: " + builder); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
private void assertWarnings(@Language("SQL") String sql, Map<String, String> sessionProperties, List<WarningCode> expectedWarnings) throws Exception { Session.SessionBuilder sessionBuilder = testSessionBuilder() .setSystemProperty("task_concurrency", "1"); sessionProperties.forEach(sessionBuilder::setSystemProperty); queryRunner.execute(sessionBuilder.build(), sql); generatedEvents.waitForEvents(10); assertEquals(generatedEvents.getQueryCompletedEvents().size(), 1, String.join("\n", generatedEvents.getQueryCompletedEvents().stream() .map(event -> String.format("%s: %s", event.getMetadata().getQueryId(), event.getMetadata().getQuery())) .collect(toImmutableList()))); Set<WarningCode> warnings = generatedEvents.getQueryCompletedEvents() .stream() .flatMap(event -> event.getWarnings().stream()) .map(PrestoWarning::getCode) .collect(toImmutableSet()); for (WarningCode warningCode : expectedWarnings) { if (!warnings.contains(warningCode)) { fail("Expected warning: " + warningCode); } } }

Target:
private void assertWarnings(@Language("SQL") String sql, Map<String, String> sessionProperties, List<WarningCode> expectedWarnings) throws InterruptedException { SessionBuilder sessionBuilder = testSessionBuilder() .setSystemProperty("task_concurrency", "1"); sessionProperties.forEach(sessionBuilder::setSystemProperty); queryRunner.execute(sessionBuilder.build(), sql); generatedEvents.waitForEvents(10); Set<WarningCode> warnings = getOnlyElement(generatedEvents.getQueryCompletedEvents()) .getWarnings() .stream() .map(PrestoWarning::getWarningCode) .collect(toImmutableSet()); for (WarningCode warningCode : expectedWarnings) { if (!warnings.contains(warningCode)) { fail("Expected warning: " + warningCode); } } }
Source:
private void persistRadioStation(RadioStation station) { persistString(station.stream); Settings settings = new Settings(getContext()); settings.setRadioStation(station); }

Target:
private void persistRadioStation(RadioStation station) { persistString(station.stream); try { String json = station.toJson(); SharedPreferences prefs = getSharedPreferences(); SharedPreferences.Editor prefEditor = prefs.edit(); prefEditor.putString(jsonKey(), json); prefEditor.commit(); } catch (JSONException e) { Log.e(TAG, "error converting station to json", e); } }
Source:
private Map<String, DashboardInfo> allDashboardsFor(ProjectState projectState) { final Project.NameKey projectName = projectState.getProject().getNameKey(); Project.NameKey parent; Map<String, DashboardInfo> dashboards = Maps.newTreeMap(); Set<Project.NameKey> seen = new HashSet<Project.NameKey>(); seen.add(projectName); do { dashboards = addProjectDashboards(projectState, dashboards); parent = projectState.getProject().getParent(); if (parent == null || !seen.add(parent)) { break; } projectState = projectCache.get(parent); } while (projectState != null); projectState = projectCache.getAllProjects(); parent = projectState.getProject().getNameKey(); if (seen.add(parent)) { dashboards = addProjectDashboards(projectState, dashboards); } for (String id : dashboards.keySet()) { DashboardInfo info = dashboards.get(id); info.parameters = info.parameters.replaceAll("[$][{]project[}]", projectName.get()); } return dashboards; }

Target:
private Map<String, DashboardInfo> allDashboardsFor(ProjectState projectState) { final Project.NameKey projectName = projectState.getProject().getNameKey(); Project.NameKey parent; Map<String, DashboardInfo> dashboards = Maps.newTreeMap(); Set<Project.NameKey> seen = new HashSet<Project.NameKey>(); seen.add(projectName); do { dashboards = addProjectDashboards(projectState, dashboards); parent = projectState.getProject().getParent(); if (parent == null || !seen.add(parent)) { break; } projectState = projectCache.get(parent); } while (projectState != null); projectState = projectCache.getAllProjects(); parent = projectState.getProject().getNameKey(); if (seen.add(parent)) { dashboards = addProjectDashboards(projectState, dashboards); } for (String id : dashboards.keySet()) { replaceTokens(dashboards.get(id), projectName.get()); } return dashboards; }
Source:
public JSONObject listWatchOverview(HttpSession session, JSONObject json) { final Long overviewId = json.getLong("overviewId"); final StringBuilder sb = new StringBuilder(); final JSONObject j = new JSONObject(); try { final ProjectOverview overview = requestManager.getProjectOverviewById(overviewId); sb.append("<ul class='bullets' style='margin-left: -30px;'>"); for (final User theUser : overview.getProject().getWatchers()) { sb.append("<li>"); sb.append(theUser.getFullName()); sb.append("</li>"); } sb.append("</ul>"); j.put("watchers", sb.toString()); return j; } catch (final IOException e) { log.error("list watch overview", e); } return JSONUtils.SimpleJSONError("Unable to list watchers"); }

Target:
public JSONObject listWatchOverview(HttpSession session, JSONObject json) { final Long overviewId = json.getLong("overviewId"); final StringBuilder sb = new StringBuilder(); final JSONObject j = new JSONObject(); try { final ProjectOverview overview = requestManager.getProjectOverviewById(overviewId); sb.append("<ul class='bullets' style='margin-left: -30px;'>"); for (final User theUser : overview.getWatchers()) { sb.append("<li>"); sb.append(theUser.getFullName()); sb.append("</li>"); } sb.append("</ul>"); j.put("watchers", sb.toString()); return j; } catch (final IOException e) { log.error("list watch overview", e); } return JSONUtils.SimpleJSONError("Unable to list watchers"); }
Source:
public Invocations getInvocations() { return new Invocations.Builder() .invocation().methods(GET).path("/v2/server/").handleWith(this::info) .invocation().methods(GET).path("/v2/server/config").handleWith(this::config) .invocation().methods(GET).path("/v2/server/env").handleWith(this::env) .invocation().methods(GET).path("/v2/server/memory").handleWith(this::memory) .invocation().methods(GET).path("/v2/server/stop").handleWith(this::stop) .invocation().methods(GET).path("/v2/server/stop-cluster").handleWith(this::stopCluster) .invocation().methods(GET).path("/v2/server/threads").handleWith(this::threads) .invocation().methods(GET).path("/v2/server/cache-managers").handleWith(this::cacheManagers) .invocation().methods(GET).path("/v2/server/ignored-caches/{cache-manager}").handleWith(this::listIgnored) .invocation().methods(POST, DELETE).path("/v2/server/ignored-caches/{cache-manager}/{cache}").handleWith(this::doIgnoreOp) .create(); }

Target:
public Invocations getInvocations() { return new Invocations.Builder() .invocation().methods(GET).path("/v2/server/").handleWith(this::info) .invocation().methods(GET).path("/v2/server/config").handleWith(this::config) .invocation().methods(GET).path("/v2/server/env").handleWith(this::env) .invocation().methods(GET).path("/v2/server/memory").handleWith(this::memory) .invocation().methods(GET).path("/v2/server/stop").handleWith(this::stop) .invocation().methods(GET).path("/v2/server/threads").handleWith(this::threads) .invocation().methods(GET).path("/v2/server/cache-managers").handleWith(this::cacheManagers) .invocation().methods(GET).path("/v2/server/ignored-caches/{cache-manager}").handleWith(this::listIgnored) .invocation().methods(POST, DELETE).path("/v2/server/ignored-caches/{cache-manager}/{cache}").handleWith(this::doIgnoreOp) .create(); }
Source:
private void removeDirectMember(PerunSession sess, Group group, Member member) throws InternalErrorException, NotGroupMemberException, GroupNotExistsException, WrongAttributeValueException, WrongReferenceAttributeValueException { member.setSourceGroupId(group.getId()); getGroupsManagerImpl().removeMember(sess, group, member); if (this.getGroupsManagerImpl().isGroupMember(sess, group, member)) { getPerunBl().getAuditer().log(sess, "{} was removed from {}.", member, group); return; } else { notifyMemberRemovalFromGroup(sess, group, member); try { getPerunBl().getAttributesManagerBl().removeAllAttributes(sess, member, group); } catch (WrongAttributeAssignmentException ex) { throw new InternalErrorException(ex); } getPerunBl().getAuditer().log(sess, "{} was removed from totally.", member, group); } List<Integer> relations = groupsManagerImpl.getResultGroupsIds(sess, group.getId()); for (Integer groupId : relations) { removeRelationMembers(sess, groupsManagerImpl.getGroupById(sess, groupId), Collections.singletonList(member), group.getId()); } recalculateMemberGroupStatusRecursively(sess, member, group); }

Target:
private void removeDirectMember(PerunSession sess, Group group, Member member) throws InternalErrorException, NotGroupMemberException, GroupNotExistsException, WrongAttributeValueException, WrongReferenceAttributeValueException { member.setSourceGroupId(group.getId()); getGroupsManagerImpl().removeMember(sess, group, member); if (this.getGroupsManagerImpl().isGroupMember(sess, group, member)) { getPerunBl().getAuditer().log(sess, "{} was removed from {}.", member, group); return; } else { notifyMemberRemovalFromGroup(sess, group, member); try { getPerunBl().getAttributesManagerBl().removeAllAttributes(sess, member, group); } catch (WrongAttributeAssignmentException ex) { throw new InternalErrorException(ex); } getPerunBl().getAuditer().log(sess, "{} was removed from totally.", member, group); } List<Integer> relations = groupsManagerImpl.getResultGroupsIds(sess, group.getId()); for (Integer groupId : relations) { removeRelationMembers(sess, groupsManagerImpl.getGroupById(sess, groupId), Collections.singletonList(member), group.getId()); } if (!VosManager.MEMBERS_GROUP.equals(group.getName())) { recalculateMemberGroupStatusRecursively(sess, member, group); } }
Source:
public synchronized void register(String streamName) { LOG.info("Trying to register {}.", streamName); if (isStarted) { String msg = "Cannot register once the producer is started."; LOG.error(msg); throw new SamzaException(msg); } EventHubClientWrapper ehClient = eventHubClientWrapperFactory .getEventHubClientWrapper(config.getStreamNamespace(streamName), config.getStreamEntityPath(streamName), config.getStreamSasKeyName(streamName), config.getStreamSasToken(streamName), config); ehClient.init(); eventHubClients.put(streamName, ehClient); streamPartitionSenders.put(streamName, new HashMap<>()); }

Target:
public synchronized void register(String streamName) { LOG.debug("Trying to register {}.", streamName); if (isStarted) { String msg = "Cannot register once the producer is started."; throw new SamzaException(msg); } if (eventHubClients.containsKey(streamName)) { LOG.warn("Already registered stream {}.", streamName); return; } EventHubClientManager ehClient = eventHubClientManagerFactory.getEventHubClientManager(systemName, streamName, config); ehClient.init(); eventHubClients.put(streamName, ehClient); }
Source:
public Cursor searchItems(long feedID, String searchQuery) { String[] queryWords = prepareSearchQuery(searchQuery); String queryFeedId; if (feedID != 0) { queryFeedId = KEY_FEED + " = " + feedID; } else { queryFeedId = "1 = 1"; } String queryStart = SELECT_FEED_ITEMS_AND_MEDIA_WITH_DESCRIPTION + " WHERE " + queryFeedId + " AND ("; StringBuilder sb = new StringBuilder(queryStart); for (int i = 0; i < queryWords.length; i++) { sb .append(KEY_DESCRIPTION + " LIKE '%").append(queryWords[i]) .append("%' OR ") .append(KEY_CONTENT_ENCODED).append(" LIKE '%").append(queryWords[i]) .append("%' OR ") .append(KEY_TITLE).append(" LIKE '%").append(queryWords[i]) .append("%' "); if (i != queryWords.length - 1) { sb.append("OR "); } } sb.append(") ORDER BY " + KEY_PUBDATE + " DESC LIMIT 300"); return db.rawQuery(sb.toString(), null); }

Target:
public Cursor searchItems(long feedID, String searchQuery) { String[] queryWords = prepareSearchQuery(searchQuery); String queryFeedId; if (feedID != 0) { queryFeedId = KEY_FEED + " = " + feedID; } else { queryFeedId = "1 = 1"; } String queryStart = SELECT_FEED_ITEMS_AND_MEDIA_WITH_DESCRIPTION + " WHERE " + queryFeedId + " AND ("; StringBuilder sb = new StringBuilder(queryStart); for (int i = 0; i < queryWords.length; i++) { sb .append("(") .append(KEY_DESCRIPTION + " LIKE '%").append(queryWords[i]) .append("%' OR ") .append(KEY_CONTENT_ENCODED).append(" LIKE '%").append(queryWords[i]) .append("%' OR ") .append(KEY_TITLE).append(" LIKE '%").append(queryWords[i]) .append("%') "); if (i != queryWords.length - 1) { sb.append("AND "); } } sb.append(") ORDER BY " + KEY_PUBDATE + " DESC LIMIT 300"); return db.rawQuery(sb.toString(), null); }
Source:
private String getSolverConfigResource(final Path resourcePath, final KieModule kieWorkbenchModule) { final Path convertedResourcePath = Paths.convert(Paths.convert(resourcePath)); final Path convertedModuleRootPath = Paths.convert(Paths.convert(kieWorkbenchModule.getRootPath())); final String result = convertedResourcePath.toURI().substring(getUriLength(convertedModuleRootPath) + "/src/main/resources/".length()); return result; }

Target:
private String getSolverConfigResource(final Path resourcePath, final KieModule kieWorkbenchModule) { return PathUtil.removePrefix(resourcePath, kieWorkbenchModule.getRootPath()).substring("src/main/resources/".length()); }
Source:
public DsfGdbAdaptor(GdbTrace trace, String gdbExec, String traceFile, String tracedExecutable) { this.fGdbTrace = trace; this.gdb72Executable = gdbExec; this.fTraceFilePath = traceFile; this.fTraceFile = traceFile.substring(traceFile.lastIndexOf(IPath.SEPARATOR) + 1); this.tracedExecutable = tracedExecutable; try { launchDGBPostMortemTrace(); } catch (CoreException e) { GdbTraceCorePlugin.logError(CORE_EXCEPTION, e); } }

Target:
public DsfGdbAdaptor(GdbTrace trace, String gdbExec, String traceFile, String tracedExecutable) { this.fGdbTrace = trace; this.gdb72Executable = gdbExec; this.fTraceFilePath = traceFile; this.fTraceFile = traceFile.substring(traceFile.lastIndexOf(IPath.SEPARATOR) + 1); this.tracedExecutable = tracedExecutable; try { launchDGBPostMortemTrace(); } catch (CoreException e) { GdbTraceCorePlugin.logError(e.getMessage(), e); } }
Source:
private static Map<Identifier, VariableReferenceExpression> buildIdentifierToVariableMap(FunctionMetadata functionMetadata, Expression sqlFunction, SqlFunctionProperties sqlFunctionProperties, Metadata metadata, PlanVariableAllocator variableAllocator) { Map<String, Type> argumentTypes = getFunctionArgumentTypes(functionMetadata, metadata); Map<NodeRef<Expression>, Type> expressionTypes = getSqlFunctionExpressionTypes(metadata, sqlFunctionProperties, sqlFunction, argumentTypes); Map<Identifier, VariableReferenceExpression> variables = new LinkedHashMap(); for (Map.Entry<NodeRef<Expression>, Type> entry : expressionTypes.entrySet()) { Expression node = entry.getKey().getNode(); if (node instanceof LambdaArgumentDeclaration) { LambdaArgumentDeclaration lambdaArgumentDeclaration = (LambdaArgumentDeclaration) node; if (!variables.containsKey(lambdaArgumentDeclaration.getName())) { variables.put(lambdaArgumentDeclaration.getName(), variableAllocator.newVariable(lambdaArgumentDeclaration.getName(), entry.getValue())); } } else if (node instanceof Identifier && argumentTypes.containsKey(((Identifier) node).getValue())) { if (!variables.containsKey(node)) { variables.put((Identifier) node, variableAllocator.newVariable(node, entry.getValue())); } } } return variables; }

Target:
private static Map<Identifier, VariableReferenceExpression> buildIdentifierToVariableMap(FunctionMetadata functionMetadata, Expression sqlFunction, SqlFunctionProperties sqlFunctionProperties, Metadata metadata, PlanVariableAllocator variableAllocator) { Map<String, Type> argumentTypes = getFunctionArgumentTypes(functionMetadata, metadata); Map<NodeRef<Expression>, Type> expressionTypes = getSqlFunctionExpressionTypes(metadata, sqlFunctionProperties, sqlFunction, argumentTypes); Map<Identifier, VariableReferenceExpression> variables = new LinkedHashMap<>(); for (Map.Entry<NodeRef<Expression>, Type> entry : expressionTypes.entrySet()) { Expression node = entry.getKey().getNode(); if (node instanceof LambdaArgumentDeclaration) { LambdaArgumentDeclaration lambdaArgumentDeclaration = (LambdaArgumentDeclaration) node; if (!variables.containsKey(lambdaArgumentDeclaration.getName())) { variables.put(lambdaArgumentDeclaration.getName(), variableAllocator.newVariable(lambdaArgumentDeclaration.getName(), entry.getValue())); } } else if (node instanceof Identifier && argumentTypes.containsKey(((Identifier) node).getValue())) { if (!variables.containsKey(node)) { variables.put((Identifier) node, variableAllocator.newVariable(node, entry.getValue())); } } } return variables; }
Source:
public void mergeValue(StructuredRecord record) { if (record.get(fieldName) != null) { String value = Objects .requireNonNull(record.get(fieldName)).toString(); if (firstString) { concatString = value; firstString = false; return; } concatString = String.format("%s, %s", concatString, value); } }

Target:
public void mergeValue(StructuredRecord record) { if (record.get(fieldName) != null) { String value = record.get(fieldName); if (firstString) { concatString = value; firstString = false; return; } concatString = String.format("%s, %s", concatString, value); } }
Source:
private void ensureCapacity(final IsaacEventPageDTO event, final List<RegisteredUserDTO> users) throws SegueDatabaseException, EventIsFullException { final boolean isStudentEvent = event.getTags().contains("student"); Long numberOfPlaces = getPlacesAvailable(event); if (numberOfPlaces != null) { long numberOfRequests = users.stream().filter(user -> !isStudentEvent || !Role.TEACHER.equals(user.getRole())).count(); if (numberOfPlaces - numberOfRequests < 0) { throw new EventIsFullException(String.format("Unable to book batch (%s) onto event (%s) as there are " + "not enough places available", users, event.getId())); } } }

Target:
private void ensureCapacity(final IsaacEventPageDTO event, final List<RegisteredUserDTO> users) throws SegueDatabaseException, EventIsFullException { final boolean isStudentEvent = event.getTags().contains("student"); Long numberOfPlaces = getPlacesAvailable(event); if (numberOfPlaces != null) { long numberOfRequests = users.stream() .filter(user -> !isStudentEvent || !Role.TEACHER.equals(user.getRole())) .count(); if (numberOfPlaces - numberOfRequests < 0) { throw new EventIsFullException( String.format("Unable to book %s (%s) onto event (%s) as there are not enough places available", users.size() > 1 ? "batch" : "user", users, event.getId())); } } }
Source:
SuggestReviewers(AccountVisibility av, AccountInfo.Loader.Factory accountLoaderFactory, AccountControl.Factory accountControlFactory, AccountCache accountCache, GroupMembers.Factory groupMembersFactory, IdentifiedUser.GenericFactory identifiedUserFactory, Provider<CurrentUser> currentUser, Provider<ReviewDb> dbProvider, @GerritServerConfig Config cfg, GroupBackend groupBackend) { this.accountLoaderFactory = accountLoaderFactory; this.accountControlFactory = accountControlFactory; this.accountCache = accountCache; this.groupMembersFactory = groupMembersFactory; this.dbProvider = dbProvider; this.identifiedUserFactory = identifiedUserFactory; this.currentUser = currentUser; this.groupBackend = groupBackend; this.cfg = cfg; String suggest = cfg.getString("suggest", null, "accounts"); if ("OFF".equalsIgnoreCase(suggest) || "false".equalsIgnoreCase(suggest)) { this.suggestAccounts = false; } else { this.useFullTextSearch = cfg.getBoolean("suggest", "fulltextsearch", false); this.suggestAccounts = (av != AccountVisibility.NONE); } this.suggestFrom = cfg.getInt("suggest", null, "from", 0); this.maxAllowed = cfg.getInt("addreviewer", "maxAllowed", PostReviewers.DEFAULT_MAX_REVIEWERS); }

Target:
SuggestReviewers(AccountVisibility av, AccountInfo.Loader.Factory accountLoaderFactory, AccountControl.Factory accountControlFactory, AccountCache accountCache, GroupMembers.Factory groupMembersFactory, IdentifiedUser.GenericFactory identifiedUserFactory, Provider<CurrentUser> currentUser, Provider<ReviewDb> dbProvider, @GerritServerConfig Config cfg, GroupBackend groupBackend) { this.accountLoaderFactory = accountLoaderFactory; this.accountControlFactory = accountControlFactory; this.accountCache = accountCache; this.groupMembersFactory = groupMembersFactory; this.dbProvider = dbProvider; this.identifiedUserFactory = identifiedUserFactory; this.currentUser = currentUser; this.groupBackend = groupBackend; this.maxSuggestedReviewers = cfg.getInt("suggest", "maxsuggestedreviewers", DEFAULT_MAX_SUGGESTED); this.fullTextMaxMatches = cfg.getInt("suggest", "fulltextsearchmaxmatches", DEFAULT_MAX_MATCHES); String suggest = cfg.getString("suggest", null, "accounts"); if ("OFF".equalsIgnoreCase(suggest) || "false".equalsIgnoreCase(suggest)) { this.suggestAccounts = false; } else { this.useFullTextSearch = cfg.getBoolean("suggest", "fulltextsearch", false); this.suggestAccounts = (av != AccountVisibility.NONE); } this.suggestFrom = cfg.getInt("suggest", null, "from", 0); this.maxAllowed = cfg.getInt("addreviewer", "maxAllowed", PostReviewers.DEFAULT_MAX_REVIEWERS); }
Source:
public void testFailJoiningNodeBecauseNeedConfigUpdateOnActiveGrid() throws Exception { prepareTestGrid(); IgniteEx ig = startGrid(1); ig.cluster().state(ClusterState.ACTIVE); try { startGrid(0); fail("Node should start with fail"); } catch (Exception e) { assertThat(X.cause(e, IgniteSpiException.class).getMessage(), containsString("Failed to join node to the active cluster")); } }

Target:
public void testFailJoiningNodeBecauseNeedConfigUpdateOnActiveGrid() throws Exception { prepareTestGrid(); IgniteEx ig = startGrid(1); ig.cluster().state(ClusterState.ACTIVE); try { startGrid(0); fail("Node should start with fail"); } catch (Exception e) { assertThat(X.cause(e, IgniteSpiException.class).getMessage(), containsString("the config of the cache 'poi' has to be merged which is impossible on active grid")); } }
Source:
public void initialize(Map<String, Param> params) throws TikaConfigException { AnnotationUtils.assignFieldParams(recogniser, params); recogniser.initialize(params); LOG.info("Recogniser = {}", recogniser.getClass().getName()); LOG.info("Recogniser Available = {}", recogniser.isAvailable()); if (recogniser instanceof TensorflowRESTRecogniser || recogniser instanceof TensorflowImageRecParser) { LOG.info("minConfidence = {}, topN={}", minConfidence, topN); } else if (recogniser instanceof TensorflowRESTCaptioner) { LOG.info("captions = {}, maxCaptionLength={}", captions, maxCaptionLength); } }

Target:
public void initialize(Map<String, Param> params) throws TikaConfigException { AnnotationUtils.assignFieldParams(recogniser, params); recogniser.initialize(params); LOG.info("Recogniser = {}", recogniser.getClass().getName()); LOG.info("Recogniser Available = {}", recogniser.isAvailable()); LOG.info("minConfidence = {}, topN={}", minConfidence, topN); }