auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
@Override protected Map<TypeElement, InjectionTarget> findAndParseTargets(RoundEnvironment env) { Map<TypeElement, InjectionTarget> targetClassMap = new LinkedHashMap<>(); Set<TypeMirror> erasedTargetTypes = new LinkedHashSet<>(); parseInjectExtraAnnotatedElements(env, targetClassMap, erasedTargetTypes); for (Map.Entry<TypeElement, InjectionTarget> entry : targetClassMap.entrySet()) { TypeElement typeElement = entry.getKey(); InjectionTarget injectionTarget = entry.getValue(); String parentClassFqcn = findParentFqcn(typeElement, erasedTargetTypes); if (parentClassFqcn != null) { injectionTarget.setParentTarget(parentClassFqcn); } else { findInjectionTargetForSuperTypeWithInjectExtra(typeElement, injectionTarget); } } return targetClassMap; }

Target:
@Override protected Map<TypeElement, InjectionTarget> findAndParseTargets(RoundEnvironment env) { Map<TypeElement, InjectionTarget> targetClassMap = new LinkedHashMap<>(); Set<TypeMirror> erasedTargetTypes = new LinkedHashSet<>(); parseInjectExtraAnnotatedElements(env, targetClassMap, erasedTargetTypes, false); for (Map.Entry<TypeElement, InjectionTarget> entry : targetClassMap.entrySet()) { TypeElement typeElement = entry.getKey(); InjectionTarget injectionTarget = entry.getValue(); String parentClassFqcn = findParentFqcn(typeElement, erasedTargetTypes); if (parentClassFqcn != null) { injectionTarget.setParentTarget(parentClassFqcn); } else { findParentInjectionTarget(typeElement, injectionTarget); } } return targetClassMap; }
Source:
public void invoke(final Object event, boolean isLocalNodePrimaryOwner, final boolean unKeyed) { if (unKeyed || shouldInvoke(event, isLocalNodePrimaryOwner)) { Runnable r = new Runnable() { @Override public void run() { ClassLoader contextClassLoader = null; Transaction transaction = suspendIfNeeded(); if (classLoader != null && classLoader.get() != null) { contextClassLoader = setContextClassLoader(classLoader.get()); } try { if (!unKeyed && converter != null && event instanceof EventImpl) { EventImpl eventImpl = (EventImpl)event; eventImpl.setValue(converter.convert(eventImpl.getKey(), eventImpl.getValue(), eventImpl.getMetadata())); } method.invoke(target, event); } catch (InvocationTargetException exception) { Throwable cause = getRealException(exception); if (sync) { throw getLog().exceptionInvokingListener( cause.getClass().getName(), method, target, cause); } else { getLog().unableToInvokeListenerMethod(method, target, cause); } } catch (IllegalAccessException exception) { getLog().unableToInvokeListenerMethod(method, target, exception); removeListener(target); } finally { if (classLoader != null && classLoader.get() != null) { setContextClassLoader(contextClassLoader); } resumeIfNeeded(transaction); } } }; if (sync) syncProcessor.execute(r); else asyncProcessor.execute(r); } }

Target:
public void invoke(final Object event, boolean isLocalNodePrimaryOwner, final boolean unKeyed) { if (unKeyed || shouldInvoke(event, isLocalNodePrimaryOwner)) { Runnable r = new Runnable() { @Override public void run() { ClassLoader contextClassLoader = null; Transaction transaction = suspendIfNeeded(); if (classLoader != null && classLoader.get() != null) { contextClassLoader = setContextClassLoader(classLoader.get()); } try { if (!unKeyed && converter != null) { if (event instanceof EventImpl) { EventImpl eventImpl = (EventImpl)event; eventImpl.setValue(converter.convert(eventImpl.getKey(), eventImpl.getValue(), eventImpl.getMetadata())); } else { throw new IllegalArgumentException("Provided event should be EventImpl when a converter is" + "being used!"); } } method.invoke(target, event); } catch (InvocationTargetException exception) { Throwable cause = getRealException(exception); if (sync) { throw getLog().exceptionInvokingListener( cause.getClass().getName(), method, target, cause); } else { getLog().unableToInvokeListenerMethod(method, target, cause); } } catch (IllegalAccessException exception) { getLog().unableToInvokeListenerMethod(method, target, exception); removeListener(target); } finally { if (classLoader != null && classLoader.get() != null) { setContextClassLoader(contextClassLoader); } resumeIfNeeded(transaction); } } }; if (sync) syncProcessor.execute(r); else asyncProcessor.execute(r); } }
Source:
public void startServer() { final Semaphore serverTaskInitialized = new Semaphore(0); Thread serverThread = new Thread(new Runnable() { @Override public void run() { try { if (serverTask == null) { serverTask = initializeJava(); } messagesLogFile = new File(serverTask.getOutputDir() + "/" + serverTask.getServerName() + "/logs/messages.log"); if (messagesLogFile.exists()) { messagesLogFile.delete(); } serverTaskInitialized.release(); copyConfigFiles(); serverTask.setClean(clean); serverTask.setOperation("debug"); if (serverStartTimeout < 0) { serverStartTimeout = 30; } serverTask.setTimeout(Long.toString(serverStartTimeout * 1000)); serverTask.execute(); } catch (Exception e) { log.debug("Error starting server", e); } } }); serverThread.start(); try { serverTaskInitialized.acquire(); if (verifyTimeout < 0) { verifyTimeout = 30; } long timeout = verifyTimeout * 1000; long endTime = System.currentTimeMillis() + timeout; String startMessage = serverTask.waitForStringInLog(START_APP_MESSAGE_REGEXP, timeout, messagesLogFile); if (startMessage == null) { stopServer(); throw new MojoExecutionException(MessageFormat .format(messages.getString("error.server.start.verify"), verifyTimeout)); } timeout = endTime - System.currentTimeMillis(); } catch (Exception e) { log.debug("Error waiting for server to start ", e); } }

Target:
public void startServer() { try { if (serverTask == null) { serverTask = initializeJava(); } String logsDirectory = serverTask.getOutputDir() + "/" + serverTask.getServerName() + "/logs"; messagesLogFile = new File(logsDirectory + "/messages.log"); copyConfigFiles(); serverTask.setClean(clean); serverTask.setOperation("debug"); if (serverStartTimeout < 0) { serverStartTimeout = 30; } serverTask.setTimeout(Long.toString(serverStartTimeout * 1000)); WatchService watchService = FileSystems.getDefault().newWatchService(); boolean logsExist = new File(logsDirectory).isDirectory(); if (logsExist) { Paths .get(logsDirectory) .register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY); } Thread serverThread = new Thread(new Runnable() { @Override public void run() { try { serverTask.execute(); } catch (Exception e) { log.debug("Error starting server", e); } } }); serverThread.start(); if (logsExist) { boolean messagesModified = false; WatchKey key; while (!messagesModified && (key = watchService.take()) != null) { for (WatchEvent<?> event : key.pollEvents()) { if (event.context().toString().equals("messages.log")) { messagesModified = true; debug("messages.log has been changed"); } } } } if (verifyTimeout < 0) { verifyTimeout = 30; } long timeout = verifyTimeout * 1000; long endTime = System.currentTimeMillis() + timeout; String startMessage = serverTask.waitForStringInLog(START_APP_MESSAGE_REGEXP, timeout, messagesLogFile); if (startMessage == null) { stopServer(); throw new MojoExecutionException( MessageFormat.format(messages.getString("error.server.start.verify"), verifyTimeout)); } timeout = endTime - System.currentTimeMillis(); } catch (Exception e) { log.debug("Error starting server", e); } }
Source:
public String getName() { return "ATLAS_DUMP_TASK"; }

Target:
public String getName() { return "ATLAS_DUMP"; }
Source:
private void checkConstraints(JsonDoc doc, Path currentValuePath, JsonNode currentValue) { LOGGER.debug("checking field constraints"); FieldCursor cursor = md.getFieldCursor(); Path skip=null; while (cursor.next()) { currentFieldNode = cursor.getCurrentNode(); currentFieldPath = cursor.getCurrentPath(); if(skip==null) { if(currentFieldNode instanceof ResolvedReferenceField) skip=currentFieldNode.getFullPath(); } else { if(!currentFieldPath.prefix(skip.numSegments()).equals(skip)) skip=null; } if(skip==null) { LOGGER.debug("checking field {}", currentFieldPath); Error.push(currentFieldPath.toString()); try { List<FieldConstraint> constraints = null; if (currentFieldNode instanceof Field) { constraints = ((Field) currentFieldNode).getConstraints(); } else if (currentFieldNode instanceof SimpleArrayElement) { constraints = ((SimpleArrayElement) currentFieldNode).getConstraints(); } if (constraints != null && !constraints.isEmpty()) { checkFieldConstraints(doc, constraints, currentValuePath, currentValue); } } catch (Error e) { throw e; } catch (Exception e) { LOGGER.error(e.getMessage(), e); throw Error.get(CrudConstants.ERR_CRUD, e.getMessage()); } finally { Error.pop(); } } } }

Target:
private void checkConstraints(JsonDoc doc, Path currentValuePath, JsonNode currentValue) { LOGGER.debug("checking field constraints"); FieldCursor cursor = md.getFieldCursor(); Path skip=null; while (cursor.next()) { currentFieldNode = cursor.getCurrentNode(); currentFieldPath = cursor.getCurrentPath(); if(skip!=null) { if(!currentFieldPath.prefix(skip.numSegments()).equals(skip)) skip=null; } if(skip==null) { if(currentFieldNode instanceof ResolvedReferenceField) skip=currentFieldNode.getFullPath(); } if(skip==null) { LOGGER.debug("checking field {}", currentFieldPath); Error.push(currentFieldPath.toString()); try { List<FieldConstraint> constraints = null; if (currentFieldNode instanceof Field) { constraints = ((Field) currentFieldNode).getConstraints(); } else if (currentFieldNode instanceof SimpleArrayElement) { constraints = ((SimpleArrayElement) currentFieldNode).getConstraints(); } if (constraints != null && !constraints.isEmpty()) { checkFieldConstraints(doc, constraints, currentValuePath, currentValue); } } catch (Error e) { throw e; } catch (Exception e) { LOGGER.error(e.getMessage(), e); throw Error.get(CrudConstants.ERR_CRUD, e.getMessage()); } finally { Error.pop(); } } } }
Source:
public boolean isEmpty() { return !startPosition.isValid() && !endPosition.isValid(); }

Target:
public boolean isEmpty() { return this == EMPTY_SELECTION; }
Source:
public static void setLogger(Logger logger) { sLogger = logger; }

Target:
public static synchronized void setLogger(Logger logger) { sLogger = logger; }
Source:
public void TestSuppressTransientExceptions() throws IOException { Configuration conf = new HdfsConfiguration(); HdfsStorageFactory.reset(); HdfsStorageFactory.setConfiguration(conf); HopsTransactionalRequestHandler txHandler = new HopsTransactionalRequestHandler(HDFSOperationType.TEST) { @Override public void setUp() throws IOException { throw new RuntimeException("Test"); } @Override public Object performTask() throws IOException { return null; } @Override public void acquireLock(TransactionLocks locks) throws IOException { } }; try { txHandler.handle(); } catch (RuntimeException e) { assert e.getMessage().compareToIgnoreCase("Test") == 0; } txHandler = new HopsTransactionalRequestHandler(HDFSOperationType.TEST) { @Override public void setUp() throws IOException { } @Override public Object performTask() throws IOException { throw new RuntimeException("Test"); } @Override public void acquireLock(TransactionLocks locks) throws IOException { } }; try { txHandler.handle(); } catch (RuntimeException e) { assert e.getMessage().compareToIgnoreCase("Test") == 0; } txHandler = new HopsTransactionalRequestHandler(HDFSOperationType.TEST) { @Override public void setUp() throws IOException { } @Override public Object performTask() throws IOException { return null; } @Override public void acquireLock(TransactionLocks locks) throws IOException { throw new RuntimeException("Test"); } }; try { txHandler.handle(); } catch (RuntimeException e) { assert e.getMessage().compareToIgnoreCase("Test") == 0; } }

Target:
public void TestSuppressTransientExceptions() throws IOException { Configuration conf = new HdfsConfiguration(); HdfsStorageFactory.reset(); HdfsStorageFactory.setConfiguration(conf); HopsTransactionalRequestHandler txHandler = new HopsTransactionalRequestHandler(HDFSOperationType.TEST) { @Override public void setUp() throws IOException { throw new RuntimeException("Test"); } @Override public Object performTask() throws IOException { return null; } @Override public void acquireLock(TransactionLocks locks) throws IOException { } }; try { txHandler.handle(); fail(); } catch (RuntimeException e) { assert e.getMessage().compareToIgnoreCase("Test") == 0; } txHandler = new HopsTransactionalRequestHandler(HDFSOperationType.TEST) { @Override public void setUp() throws IOException { } @Override public Object performTask() throws IOException { throw new RuntimeException("Test"); } @Override public void acquireLock(TransactionLocks locks) throws IOException { } }; try { txHandler.handle(); fail(); } catch (RuntimeException e) { assert e.getMessage().compareToIgnoreCase("Test") == 0; } txHandler = new HopsTransactionalRequestHandler(HDFSOperationType.TEST) { @Override public void setUp() throws IOException { } @Override public Object performTask() throws IOException { return null; } @Override public void acquireLock(TransactionLocks locks) throws IOException { throw new RuntimeException("Test"); } }; try { txHandler.handle(); fail(); } catch (RuntimeException e) { assert e.getMessage().compareToIgnoreCase("Test") == 0; } }
Source:
public TmfEventRequest(Class<? extends ITmfEvent> dataType, TmfTimeRange range, long index, int nbRequested, ExecutionType priority) { synchronized (TmfEventRequest.class) { fRequestId = fRequestNumber++; } fDataType = dataType; fIndex = index; fNbRequested = nbRequested; fExecType = priority; fRange = range; fNbRead = 0; fRequestRunning = false; fRequestCompleted = false; fRequestFailed = false; fRequestCanceled = false; if (TmfCoreTracer.isRequestTraced()) { String type = getClass().getName(); type = type.substring(type.lastIndexOf('.') + 1); @SuppressWarnings("nls") String message = "CREATED " + (getExecType() == ExecutionType.BACKGROUND ? "(BG)" : "(FG)") + " Type=" + type + " Index=" + getIndex() + " NbReq=" + getNbRequested() + " Range=" + getRange() + " DataType=" + getDataType().getSimpleName(); TmfCoreTracer.traceRequest(fRequestId, message); } }

Target:
public TmfEventRequest(Class<? extends ITmfEvent> dataType, TmfTimeRange range, long index, int nbRequested, ExecutionType priority) { this(dataType, range, index, nbRequested, priority, 0); }
Source:
private void mockJobSubjectEntityDao(Guid jobId) { when(jobSubjectEntityDao.getJobSubjectEntityByJobId(eq(jobId))) .thenReturn(JOB_SUBJECT_ENTITIES_MAP); when(jobSubjectEntityDao.getJobIdByEntityId(any(Guid.class))).thenReturn(Collections.<Guid>singletonList(jobId)); }

Target:
private void mockJobSubjectEntityDao(Guid jobId) { when(jobSubjectEntityDao.getJobSubjectEntityByJobId(eq(jobId))) .thenReturn(JOB_SUBJECT_ENTITIES_MAP); when(jobSubjectEntityDao.getJobIdByEntityId(any(Guid.class))).thenReturn(Collections.singletonList(jobId)); }
Source:
protected List<Disk> manualAggregateSnapshots() { List<Disk> Param = new ArrayList<>(); DiskImage diskWithSnaps = diskWithSnapshots; diskWithSnaps.getSnapshots().addAll(snapshotsList); Param.add(diskWithSnapshots); return Param; }

Target:
protected List<DiskImage> manualAggregateSnapshots() { List<DiskImage> diskImageWithAggregatedSnapshots = new ArrayList<>(); DiskImage diskWithSnaps = diskWithSnapshots; diskWithSnaps.getSnapshots().addAll(snapshotsList); diskImageWithAggregatedSnapshots.add(diskWithSnapshots); return diskImageWithAggregatedSnapshots; }
Source:
private void invokeBeforeServerStop() { Arrays.stream(testClass.getMethods()) .filter(field -> field.getAnnotation(BeforeServerStop.class) != null) .forEach(method -> { try { method.invoke(testInstance); } catch (Exception e) { throw new RuntimeException(e); } }); }

Target:
private void invokeBeforeServerStop() { stream(testClass.getMethods()) .filter(field -> field.getAnnotation(BeforeServerStop.class) != null) .forEach(this::invokeTestInstanceMethod); }
Source:
AllProjectsNameOnInitProvider(Section.Factory sections) { String n = sections.get("gerrit", null).get("allProjects"); if (n == null || n.isEmpty()) { n = AllProjectsNameProvider.DEFAULT; } name = n; }

Target:
AllProjectsNameOnInitProvider(Section.Factory sections) { String n = sections.get("gerrit", null).get("allProjects"); name = Objects.firstNonNull( Strings.emptyToNull(n), AllProjectsNameProvider.DEFAULT); }
Source:
public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); if (HttpServer.Method.POST == request.getMethod() || HttpServer.Method.PUT == request.getMethod()) { ZooKeeper zk = ZooKeeperClient.newBuilder() .connectString(conf.getZkServers()) .sessionTimeoutMs(conf.getZkTimeout()) .build(); File[] ledgerDirectories = Bookie.getCurrentDirectories(conf.getLedgerDirs()); File[] journalDirectories = Bookie.getCurrentDirectories(conf.getJournalDirs()); File[] indexDirectories; if (null == conf.getIndexDirs()) { indexDirectories = ledgerDirectories; } else { indexDirectories = Bookie.getCurrentDirectories(conf.getIndexDirs()); } List<File> allLedgerDirs = Lists.newArrayList(); allLedgerDirs.addAll(Arrays.asList(ledgerDirectories)); if (indexDirectories != ledgerDirectories) { allLedgerDirs.addAll(Arrays.asList(indexDirectories)); } try { Bookie.checkEnvironmentWithStorageExpansion(conf, zk, Lists.newArrayList(journalDirectories), allLedgerDirs); } catch (BookieException | IOException e) { LOG.error( "Exception while updating cookie for storage expansion", e); response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Exception while updating cookie for storage expansion"); return response; } if (zk != null) { zk.close(); } String jsonResponse = "Success expand storage"; LOG.debug("output body:" + jsonResponse); response.setBody(jsonResponse); response.setCode(HttpServer.StatusCode.OK); return response; } else { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Not found method. Should be POST/PUT method"); return response; } }

Target:
public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); if (HttpServer.Method.PUT == request.getMethod()) { File[] ledgerDirectories = Bookie.getCurrentDirectories(conf.getLedgerDirs()); File[] journalDirectories = Bookie.getCurrentDirectories(conf.getJournalDirs()); File[] indexDirectories; if (null == conf.getIndexDirs()) { indexDirectories = ledgerDirectories; } else { indexDirectories = Bookie.getCurrentDirectories(conf.getIndexDirs()); } List<File> allLedgerDirs = Lists.newArrayList(); allLedgerDirs.addAll(Arrays.asList(ledgerDirectories)); if (indexDirectories != ledgerDirectories) { allLedgerDirs.addAll(Arrays.asList(indexDirectories)); } try { Bookie.checkEnvironmentWithStorageExpansion(conf, zk, Lists.newArrayList(journalDirectories), allLedgerDirs); } catch (BookieException | IOException e) { LOG.error("Exception occurred while updating cookie for storage expansion", e); response.setCode(HttpServer.StatusCode.INTERNAL_ERROR); response.setBody("Exception while updating cookie for storage expansion"); return response; } String jsonResponse = "Success expand storage"; LOG.debug("output body:" + jsonResponse); response.setBody(jsonResponse); response.setCode(HttpServer.StatusCode.OK); return response; } else { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Not found method. Should be PUT method"); return response; } }
Source:
protected IStateHistoryBackend getBackend() { return fBackend; }

Target:
protected @NonNull IStateHistoryBackend getBackend() { return fPartialBackend; }
Source:
public static String getParameter(String key) { try { return getConfig().getString(key); } catch (NoSuchElementException e) { logger.catching(e); throw new NoSuchElementException("No configuration found in kitodo_config.properties for key " + key + "!"); } }

Target:
public static String getParameter(String key) { try { return getConfig().getString(key); } catch (NoSuchElementException e) { try { FIELD_DETAIL_MESSAGE.set(e, "No configuration found in kitodo_config.properties for key " + key + "!"); } catch (IllegalAccessException e1) { throw new UndeclaredThrowableException(e1); } throw e; } }
Source:
public AndroidSentryClientFactory(Context ctx) { Log.d(TAG, "Construction of Android Sentry from Android Context."); this.ctx = ctx; }

Target:
public AndroidSentryClientFactory(Context ctx) { Log.d(TAG, "Construction of Android Sentry from Android Context."); this.ctx = ctx.getApplicationContext(); if (this.ctx == null) { this.ctx = ctx; } }
Source:
public final void onMessage(final SocketSession conn, final Request req) { if (req.getRequestType() == Request.MessageType.DATA_REQUEST) { DataRequestHandler.handleRequest(req, conn, super.getConnectionToId().get(conn).getKey(), getConnectionManager()); } else if (req.getRequestType() == Request.MessageType.DATA_INSERT) { DataInsertHandler.handleData(req, conn); } else if (req.getRequestType() == Request.MessageType.DATA_UPDATE) { DataUpdateHandler.handleData(req, conn); } else if (req.getRequestType() == Request.MessageType.TIME) { final Request rsp = TimeManager.decodeRequest(req); if (rsp != null) { send(conn, rsp); } } LOG.info("Finished looking at query"); }

Target:
public final void onMessage(final SocketSession conn, final Request req) { if (req.getRequestType() == Request.MessageType.DATA_REQUEST) { DataRequestHandler.handleRequest(req, conn, super.getConnectionToId().get(conn).getKey(), getConnectionManager()); } else if (req.getRequestType() == Request.MessageType.DATA_INSERT) { DataInsertHandler.handleData(req, conn); } else if (req.getRequestType() == Request.MessageType.DATA_UPDATE) { DataUpdateHandler.handleData(req, conn); } else if (req.getRequestType() == Request.MessageType.TIME) { final Request rsp = TimeManager.decodeRequest(req); if (rsp != null) { send(conn, rsp); } } LOG.info("Finished looking at query {}", req); }
Source:
private void printTableScanInfo(TableScanNode node, int indent) { TableHandle table = node.getTable(); if (node.getLayout().isPresent()) { ConnectorTableLayoutHandle layout = node.getLayout().get().getConnectorHandle(); if (!table.getConnectorHandle().toString().equals(layout.toString())) { print(indent + 2, "LAYOUT: %s", layout); } } TupleDomain<ColumnHandle> predicate = node.getLayoutConstraint(); if (predicate.isNone()) { print(indent + 2, ":: NONE"); } else { for (Map.Entry<Symbol, ColumnHandle> assignment : node.getAssignments().entrySet()) { ColumnHandle column = assignment.getValue(); print(indent + 2, "%s := %s", assignment.getKey(), column); printConstraint(indent + 3, column, predicate); } if (!predicate.isAll()) { Set<ColumnHandle> outputs = ImmutableSet.copyOf(node.getAssignments().values()); predicate.getDomains().get() .entrySet().stream() .filter(entry -> !outputs.contains(entry.getKey())) .forEach(entry -> { ColumnHandle column = entry.getKey(); print(indent + 2, "%s", column); printConstraint(indent + 3, column, predicate); }); } } }

Target:
private void printTableScanInfo(TableScanNode node, int indent) { TableHandle table = node.getTable(); if (node.getLayout().isPresent()) { ConnectorTableLayoutHandle layout = node.getLayout().get().getConnectorHandle(); if (!table.getConnectorHandle().toString().equals(layout.toString())) { print(indent + 2, "LAYOUT: %s", layout); } } TupleDomain<ColumnHandle> predicate = node.getCurrentConstraint(); if (predicate.isNone()) { print(indent + 2, ":: NONE"); } else { for (Map.Entry<Symbol, ColumnHandle> assignment : node.getAssignments().entrySet()) { ColumnHandle column = assignment.getValue(); print(indent + 2, "%s := %s", assignment.getKey(), column); printConstraint(indent + 3, column, predicate); } if (!predicate.isAll()) { Set<ColumnHandle> outputs = ImmutableSet.copyOf(node.getAssignments().values()); predicate.getDomains().get() .entrySet().stream() .filter(entry -> !outputs.contains(entry.getKey())) .forEach(entry -> { ColumnHandle column = entry.getKey(); print(indent + 2, "%s", column); printConstraint(indent + 3, column, predicate); }); } } }
Source:
private static Object prioritizeObjectValue(Object value1, Object value2) { boolean value1Null = value1 == null; if (!value1Null && !(value1 instanceof Data)) { return value1; } boolean value2Null = value2 == null; if (!value2Null && !(value2 instanceof Data)) { return value2; } if (!value1Null) { return value1; } if (!value2Null) { return value2; } return null; }

Target:
private static Object prioritizeObjectValue(Object value1, Object value2) { boolean value1NotNull = value1 != null; if (value1NotNull && !(value1 instanceof Data)) { return value1; } boolean value2NotNull = value2 != null; if (value2NotNull && !(value2 instanceof Data)) { return value2; } if (value1NotNull) { return value1; } if (value2NotNull) { return value2; } return null; }
Source:
public DBObject fetch(DBRef dbRef) { return ReflectiveDBRefResolver.fetch(MongoClientVersion.isMongo3Driver() ? mongoDbFactory.getDb() : null, dbRef); }

Target:
public DBObject fetch(DBRef dbRef) { return ReflectiveDBRefResolver.fetch(mongoDbFactory, dbRef); }
Source:
protected void logError( Request request, Throwable error, long latencyNanos, Node node, int maxQueryLength, boolean showValues, int maxValues, int maxValueLength, boolean showStackTraces) { StringBuilder builder = formatter.logBuilder(logPrefix, node); formatter.appendErrorDescription(builder); formatter.appendLatency(latencyNanos, builder); formatter.appendRequest( request, maxQueryLength, showValues, maxValues, maxValueLength, builder); if (showStackTraces) { LOG.error(builder.toString(), error); } else { LOG.error("{} {}", builder.toString(), error.toString()); } }

Target:
protected void logError( Request request, Throwable error, long latencyNanos, Node node, int maxQueryLength, boolean showValues, int maxValues, int maxValueLength, boolean showStackTraces) { StringBuilder builder = formatter.logBuilder(logPrefix, node); formatter.appendErrorDescription(builder); formatter.appendLatency(latencyNanos, builder); formatter.appendRequest( request, maxQueryLength, showValues, maxValues, maxValueLength, builder); if (showStackTraces) { LOG.error(builder.toString(), error); } else { LOG.error("{} [{}]", builder.toString(), error.toString()); } }
Source:
public void checkStoppingByApi() throws Exception { Workspace workspace = workspaceServiceClient.getByName( testWorkspace.getName(), testUser.getName(), testUser.getAuthToken()); assertEquals(workspace.getStatus(), WorkspaceStatus.STOPPED); }

Target:
public void checkStoppingByApi() throws Exception { Workspace workspace = workspaceServiceClient.getByName( testWorkspace.getName(), testUser.getName()); assertEquals(workspace.getStatus(), STOPPED); }
Source:
public void writePacketData(RailcraftOutputStream data) throws IOException { for (StandardTank tank : tanks) { data.writeFluidStack(tank.getFluid()); data.writeInt(tank.getCapacity()); } }

Target:
public void writePacketData(RailcraftOutputStream data) throws IOException { for (StandardTank tank : tanks) { data.writeFluidStack(tank.getFluid()); } }
Source:
public PreparedOperation<PutResult> prepare() { Checks.checkNotNull(mapFunc, "Please specify map function"); return new PreparedPutObject<>( storIOSQLiteDb, putResolver, object, mapFunc ); }

Target:
public PreparedOperation<PutResult> prepare() { checkNotNull(mapFunc, "Please specify map function"); return new PreparedPutObject<>( storIOSQLiteDb, putResolver, object, mapFunc ); }
Source:
public String render(@RequestParam(value = "reportId", required = true) int reportId, WebRequest request, HttpServletResponse response) throws IOException { String message = null; int timesheetId; String temp = request.getParameter("timesheetId"); if (!StringUtils.isEmpty(temp) && StringUtils.isNumeric(temp)) { timesheetId = Integer.parseInt(temp); } else { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The timesheet id ('" + temp + "') must be " + "defined and be numeric."); return null; } JasperReportService jasperService = Context.getService(JasperReportService.class); JasperReport report = jasperService.getJasperReport(reportId); if (report == null) { message = "Could not find report '" + reportId + "'"; return "redirect:" + JasperReportConstants.REPORT_ERROR_PAGE + "?reportId="+reportId+"&message="+message; } report.setName("Cashier Shift Report - " + temp); HashMap<String, Object> params = new HashMap<String, Object>(); params.put("timesheetId", timesheetId); try { ReportGenerator.generate(report, params, false, true); } catch (IOException e) { message = "Error generating cashier shift report for " + "timesheet '" + temp + "'"; return "redirect:" + JasperReportConstants.REPORT_ERROR_PAGE + "?reportId="+reportId+"&message="+message; } return "redirect:" + CashierWebConstants.REPORT_DOWNLOAD_URL + "?reportName=" + report.getName().replaceAll("\\W", "") + ".pdf"; }

Target:
public String render(@RequestParam(value = "reportId", required = true) int reportId, WebRequest request, HttpServletResponse response) throws IOException { String message = null; int timesheetId; String temp = request.getParameter("timesheetId"); if (!StringUtils.isEmpty(temp) && StringUtils.isNumeric(temp)) { timesheetId = Integer.parseInt(temp); } else { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The timesheet id ('" + temp + "') must be " + "defined and be numeric."); return null; } JasperReportService jasperService = Context.getService(JasperReportService.class); JasperReport report = jasperService.getJasperReport(reportId); if (report == null) { message = "No Jasper Report with an ID of" +reportId+ "could be found."; return "redirect:" + JasperReportConstants.REPORT_ERROR_PAGE + "?reportId="+reportId+"&message="+message; } report.setName("Cashier Shift Report - " + temp); HashMap<String, Object> params = new HashMap<String, Object>(); params.put("timesheetId", timesheetId); try { ReportGenerator.generate(report, params, false, true); } catch (IOException e) { message = "Error generating cashier shift report for " + "timesheet " + temp + ". The Following Error Occurred " + ""+e.getMessage()+""; return "redirect:" + JasperReportConstants.REPORT_ERROR_PAGE + "?reportId="+reportId+"&message="+message; } return "redirect:" + CashierWebConstants.REPORT_DOWNLOAD_URL + "?reportName=" + report.getName().replaceAll("\\W", "") + ".pdf"; }
Source:
void onCancelClicked() { new AlertDialog.Builder(getContext()) .setMessage(R.string.compilation_download_cancel_confirm) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { if (callback != null) { callback.onCancel(); } } }) .setNegativeButton(android.R.string.no, null) .show(); }

Target:
void onCancelClicked() { new AlertDialog.Builder(getContext()) .setMessage(R.string.compilation_download_cancel_confirm) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { if (callback != null) { callback.onCancel(); } } }) .setNegativeButton(R.string.no, null) .show(); }
Source:
public boolean haveTriggersFired() { ModelNode causes = get(DEPLOYMENTCONFIG_CAUSES); if (causes == null || causes.getType() != ModelType.LIST) return false; return causes.asList().size() > 0; }

Target:
public boolean haveTriggersFired() { ModelNode causes = get(DEPLOYMENTCONFIG_CAUSES); if (causes.getType() == ModelType.UNDEFINED || causes.getType() != ModelType.LIST) return false; return causes.asList().size() > 0; }
Source:
public void nextPage() { int curPage = model.getPage(); if (curPage == model.getMaxPage()) return; model.setPage(model.getPage() + 1); model.setFetchData(null, model.getCurrentStartCursor(), false); this.fetch(false); }

Target:
public void nextPage() { int curPage = model.getPage(); if (curPage == model.getMaxPage()) return; model.setPage(curPage + 1); model.setFetchData(null, model.getCurrentStartCursor(), false); this.fetch(false); }
Source:
public static void replyError(HttpServletRequest req, HttpServletResponse res, int statusCode, String msg, CacheControl c, @Nullable Throwable err) throws IOException { res.setStatus(statusCode); configureCaching(req, res, null, c); replyText(req, res, msg); if (err != null) { req.setAttribute(RequestUtil.ATTRIBUTE_ERROR_TRACE, err); } }

Target:
public static void replyError(HttpServletRequest req, HttpServletResponse res, int statusCode, String msg, CacheControl c, @Nullable Throwable err) throws IOException { res.setStatus(statusCode); configureCaching(req, res, null, c); replyText(req, res, msg); if (err != null) { RequestUtil.setErrorTraceAttribute(req, err); } }
Source:
public GroupAddRequest(User sender, Group group, User newUser) { super(); mSender = sender; mGroup = group; mUser = newUser; }

Target:
public GroupAddRequest(User sender, Group group, User newUser) { super(); Objects.requireNonNull(sender); Objects.requireNonNull(group); Objects.requireNonNull(newUser); mSender = sender; mGroup = group; mUser = newUser; }
Source:
private List<GlusterBrickEntity> getBricks(Guid volumeId, String dirPrefix, int n) { List<GlusterBrickEntity> bricks = new ArrayList<GlusterBrickEntity>(); GlusterBrickEntity brick; for (Integer i = 0; i < n; i++) { brick = new GlusterBrickEntity(volumeId, new VdsStatic(serverName, "127.0.0.1", "0934390834", 20, new Guid(), serverId, serverName, true, VDSType.oVirtNode, "", "", "", "", "", ""), "/tmp/" + dirPrefix + i.toString(), GlusterStatus.UP); bricks.add(brick); } return bricks; }

Target:
private List<GlusterBrickEntity> getBricks(Guid volumeId, String dirPrefix, int n) { List<GlusterBrickEntity> bricks = new ArrayList<GlusterBrickEntity>(); GlusterBrickEntity brick; for (Integer i = 0; i < n; i++) { brick = new GlusterBrickEntity(volumeId, new VdsStatic(serverName, "127.0.0.1", "0934390834", 20, new Guid(), serverId, serverName, true, VDSType.oVirtNode), "/tmp/" + dirPrefix + i.toString(), GlusterStatus.UP); bricks.add(brick); } return bricks; }
Source:
private void setOperationParams(int putContentSize, long ttlSecs) { putBlobProperties = new BlobProperties(-1, "serviceId", "memberId", "contentType", false, ttlSecs, Utils.getRandomShort(TestUtils.RANDOM), Utils.getRandomShort(TestUtils.RANDOM), testEncryption); putUserMetadata = new byte[10]; random.nextBytes(putUserMetadata); putContent = new byte[putContentSize]; random.nextBytes(putContent); putChannel = new ByteBufferReadableStreamChannel(ByteBuffer.wrap(putContent)); }

Target:
private void setOperationParams(int putContentSize, long ttlSecs) { putBlobProperties = new BlobProperties(-1, "serviceId", "memberId", "contentType", false, ttlSecs, Utils.getRandomShort(TestUtils.RANDOM), Utils.getRandomShort(TestUtils.RANDOM), testEncryption); putUserMetadata = new byte[USER_METADATA_SIZE]; random.nextBytes(putUserMetadata); putContent = new byte[putContentSize]; random.nextBytes(putContent); putChannel = new ByteBufferReadableStreamChannel(ByteBuffer.wrap(putContent)); }
Source:
public void testCheckPropertyAccessDeniedProperty() { String key = "mockDeniedProperty"; System.setProperty("denied.system.properties", "mockDeniedProperty"); carbonSecurityManager = new CarbonSecurityManager(); carbonSecurityManager.checkPropertyAccess(key); }

Target:
public void testCheckPropertyAccessDeniedProperty() { String key = "mockDeniedProperty"; System.setProperty("denied.system.properties", key); carbonSecurityManager = new CarbonSecurityManager(); carbonSecurityManager.checkPropertyAccess(key); }
Source:
private static void checkValidEntityName(String entityName, int maxEntityNameLength, boolean allowSeparator) { if (entityName == null || entityName.isEmpty()) { throw new IllegalArgumentException("Entity name cannot be null."); } String tempName = entityName.replace('\\', '/'); if (tempName.length() > maxEntityNameLength) { throw new IllegalArgumentException("Entity path " + entityName + " exceeds the " + maxEntityNameLength + " character limit"); } if (tempName.startsWith(PATH_DELIMITER) || tempName.endsWith(PATH_DELIMITER)) { throw new IllegalArgumentException("The entity name cannot contain '/' as prefix or suffix."); } if (!allowSeparator && tempName.contains(PATH_DELIMITER)) { throw new IllegalArgumentException("The entity name contains an invalid character '" + PATH_DELIMITER + "'"); } for (char key : ManagementClientConstants.INVALID_ENTITY_PATH_CHARACTERS) { if (entityName.indexOf(key) >= 0) { throw new IllegalArgumentException(entityName + " contains character '" + key + "' which is not allowed" + "because it is reserved in the Uri scheme."); } } }

Target:
private static void checkValidEntityName(String entityName, int maxEntityNameLength, boolean allowSeparator) { if (entityName == null || entityName.isEmpty()) { throw new IllegalArgumentException("Entity name cannot be null"); } String tempName = entityName.replace('\\', '/'); if (tempName.length() > maxEntityNameLength) { throw new IllegalArgumentException("Entity path " + entityName + " exceeds the " + maxEntityNameLength + " character limit"); } if (tempName.startsWith(PATH_DELIMITER) || tempName.endsWith(PATH_DELIMITER)) { throw new IllegalArgumentException("The entity name cannot contain '/' as prefix or suffix."); } if (!allowSeparator && tempName.contains(PATH_DELIMITER)) { throw new IllegalArgumentException("The entity name contains an invalid character '" + PATH_DELIMITER + "'"); } for (char key : ManagementClientConstants.INVALID_ENTITY_PATH_CHARACTERS) { if (entityName.indexOf(key) >= 0) { throw new IllegalArgumentException(entityName + " contains character '" + key + "' which is not allowed" + "because it is reserved in the Uri scheme."); } } }
Source:
private static void updateTimeNotification(String machine, Context context, long timeLeft) { if (notifcationIds == null || self == null) { return; } int id = notifcationIds.get(machine); String countDown; if (timeLeft > 0) { countDown = String.format("%01d minutes left", TimeUnit.MILLISECONDS.toMinutes(timeLeft)); } else { timeLeft = 0; countDown = " is finished!"; } NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); Intent cancelIntent = new Intent(context, NotificationCancelReceiver.class); cancelIntent.putExtra("timeLeft", timeLeft); cancelIntent.putExtra("notificationId", id); cancelIntent.putExtra("machine", machine); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, cancelIntent, PendingIntent.FLAG_UPDATE_CURRENT); android.support.v4.app.NotificationCompat.Builder builder = new NotificationCompat.Builder(context) .setContentTitle(machine) .setContentText(countDown) .setSmallIcon(R.drawable.ic_machine_notification) .setColor(ContextCompat.getColor(context, R.color.Available)) .setGroup(GROUP_KEY_EMAILS) .addAction(R.drawable.ic_action_content_clear, "Cancel", pendingIntent) .setOngoing(true) .setPriority(id); if (timeLeft == 0) { builder.setOngoing(false); } if (timeLeft == 0 || (countDown.equals("5:00"))) { AnalyticsHelper.sendEventHit("Reminders", "Passive", "Timer Finished"); builder.setVibrate(new long[]{1000, 1000, 1000}); } notificationManager.notify(id, builder.build()); }

Target:
private static void updateTimeNotification(String machine, Context context, long timeLeft) { if (notifcationIds == null || self == null) { AnalyticsHelper.sendErrorHit(new NullPointerException("notificationIds or service null"), false); return; } int id = notifcationIds.get(machine); String countDown; if (timeLeft > 0) { countDown = String.format("%01d minutes left", TimeUnit.MILLISECONDS.toMinutes(timeLeft)); } else { timeLeft = 0; countDown = " is finished!"; } NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); Intent cancelIntent = new Intent(context, NotificationCancelReceiver.class); cancelIntent.putExtra("timeLeft", timeLeft); cancelIntent.putExtra("notificationId", id); cancelIntent.putExtra("machine", machine); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, cancelIntent, PendingIntent.FLAG_UPDATE_CURRENT); android.support.v4.app.NotificationCompat.Builder builder = new NotificationCompat.Builder(context) .setContentTitle(machine) .setContentText(countDown) .setSmallIcon(R.drawable.ic_machine_notification) .setColor(ContextCompat.getColor(context, R.color.Available)) .setGroup(GROUP_KEY_EMAILS) .addAction(R.drawable.ic_action_content_clear, "Cancel", pendingIntent) .setOngoing(true) .setPriority(id); if (timeLeft == 0) { builder.setOngoing(false); } if (timeLeft == 0 || (countDown.equals("5:00"))) { AnalyticsHelper.sendEventHit("Reminders", "Passive", "Timer Finished"); builder.setVibrate(new long[]{1000, 1000, 1000}); } notificationManager.notify(id, builder.build()); }
Source:
public Map marshal(java.util.Map<String, java.lang.Object> input) throws Exception { if (input == null) { return null; } else { Map output = new Map(); for (String key : input.keySet()) { java.lang.Object value = input.get(key); if (value instanceof java.util.Map) { java.util.Map<String, java.lang.Object> nestedMap = new HashMap<>(); ((java.util.Map<?, ?>) value).forEach((k, v) -> nestedMap.put(k.toString(), v)); value = marshal(nestedMap); } output.getEntries().add(new MapEntry().withKey(key).withValue(value)); } return output; } }

Target:
public Map marshal(java.util.Map<String, java.lang.Object> input) throws Exception { if (input == null) { return null; } else { Map output = new Map(); for (java.util.Map.Entry<String, java.lang.Object> entry : input.entrySet()) { String key = entry.getKey(); java.lang.Object value = entry.getValue(); if (value instanceof java.util.Map) { java.util.Map<String, java.lang.Object> nestedMap = new HashMap<>(); ((java.util.Map<?, ?>) value).forEach((k, v) -> nestedMap.put(k.toString(), v)); value = marshal(nestedMap); } output.getEntries().add(new MapEntry().withKey(key).withValue(value)); } return output; } }
Source:
protected Properties getProperties(File file, Properties defaultProperties) { Properties properties = new Properties(defaultProperties); copySystemProperty(KEY_LIBRA_DOMAIN, properties); copySystemProperty(KEY_LIBRA_SERVER, properties); copySystemProperty(KEY_RHLOGIN, properties); copySystemProperty(KEY_PASSWORD, properties); copySystemProperty(KEY_CLIENT_ID, properties); copySystemProperty(OPENSHIFT_TIMEOUT, properties); return properties; }

Target:
protected Properties getProperties(File file, Properties defaultProperties) { Properties properties = new Properties(defaultProperties); copySystemProperty(KEY_LIBRA_DOMAIN, properties); copySystemProperty(KEY_LIBRA_SERVER, properties); copySystemProperty(KEY_RHLOGIN, properties); copySystemProperty(KEY_PASSWORD, properties); copySystemProperty(KEY_CLIENT_ID, properties); copySystemProperty(KEY_OPENSHIFT_TIMEOUT, properties); return properties; }
Source:
@Override public String convertToCompilableExpression(String expression, Class<?> objectType, Class<?> returnType) { if (expression.startsWith(".")) { expression = expression.substring(1); } if (expression.isEmpty()) { throw new IllegalArgumentException("The getter expression: \"" + expression + "\" is invalid."); } Pattern entry = Pattern.compile(variablePlaceholderPattern); Matcher matcher = entry.matcher(expression); StringBuffer sb = new StringBuffer(); while (matcher.find()) { if (matcher.groupCount() == 1) { try { matcher.appendReplacement(sb, getObjectJavaExpression(matcher.group(1), objectType)); } catch (NoSuchFieldException e) { throw new RuntimeException("Failed to parse the operand: " + matcher.group(1), e); } } else { throw new RuntimeException("Invalid expression: " + matcher.group()); } } matcher.appendTail(sb); if (sb.toString().equals(expression)) { if (!expression.startsWith("$.")) { expression = "$." + expression; } try { String tempExpr = getObjectJavaExpression(expression, objectType); sb.setLength(0); sb.append(tempExpr.replace("\\$", "$")); } catch (NoSuchFieldException e) { throw new RuntimeException("Failed to create expression.", e); } } return "return ((" + returnType.getName().replace("$", "\\$") + ")" + sb.toString() + ");"; }

Target:
public String convertToCompilableExpression(String expression, Class<?> objectType, Class<?> returnType) { if (expression.startsWith(".")) { expression = expression.substring(1); } if (expression.isEmpty()) { throw new IllegalArgumentException("The getter expression: \"" + expression + "\" is invalid."); } Pattern entry = Pattern.compile(variablePlaceholderPattern); Matcher matcher = entry.matcher(expression); StringBuffer sb = new StringBuffer(); while (matcher.find()) { if (matcher.groupCount() == 1) { matcher.appendReplacement(sb, getObjectJavaExpression(matcher.group(1), objectType)); } else { throw new RuntimeException("Invalid expression: " + matcher.group()); } } matcher.appendTail(sb); if (sb.toString().equals(expression)) { if (!expression.startsWith(this.exprObjPlaceholder + ".")) { expression = this.exprObjPlaceholder + "." + expression; } String tempExpr = getObjectJavaExpression(expression, objectType); sb.setLength(0); sb.append(tempExpr.replace("\\$", "$")); } return "return ((" + returnType.getName().replace("$", "\\$") + ")" + sb.toString() + ");"; }
Source:
private void allocateTimestamp() throws Exception { Stat stat = new Stat(); synchronized (this) { while (!curatorFramework.getState().equals(CuratorFrameworkState.STARTED)) { Thread.sleep(200); } byte[] d = curatorFramework.getData().storingStatIn(stat).forPath(maxTsPath); long newMax = Long.parseLong(new String(d)) + 1000; curatorFramework.setData().withVersion(stat.getVersion()).forPath(maxTsPath, LongUtil.toByteArray(newMax)); maxTs = newMax; } if (!isLeader) { throw new IllegalStateException(); } }

Target:
private void allocateTimestamp() throws Exception { Stat stat = new Stat(); while (!curatorFramework.getState().equals(CuratorFrameworkState.STARTED)) { Thread.sleep(200); } byte[] d = curatorFramework.getData().storingStatIn(stat).forPath(maxTsPath); long newMax = Long.parseLong(new String(d)) + 1000; curatorFramework.setData().withVersion(stat.getVersion()).forPath(maxTsPath, LongUtil.toByteArray(newMax)); maxTs = newMax; if (!isLeader) { throw new IllegalStateException(); } }
Source:
public void setMenuItems(@Nullable List<CarMenuItem> items) { mMenuItems = items; List<CarMenuItem> actionItems = new ArrayList<>(); mOverflowMenuItems = new ArrayList<>(); mActionViews.forEach(this::removeView); mActionViews.clear(); if (mMenuItems != null) { mMenuItems.forEach(item -> { if (item.getDisplayBehavior() == CarMenuItem.DisplayBehavior.NEVER) { mOverflowMenuItems.add(item); } else { actionItems.add(item); } }); } mOverflowButtonView.setVisibility(mOverflowMenuItems.isEmpty() ? GONE : VISIBLE); actionItems.forEach(item -> { View view = item.isCheckable() ? createCheckableAction(item) : createAction(item); MarginLayoutParams marginLayoutParams = new MarginLayoutParams(LayoutParams.WRAP_CONTENT, mActionButtonHeight); view.setLayoutParams(marginLayoutParams); mActionViews.add(view); addView(view); }); requestLayout(); }

Target:
public void setMenuItems(@Nullable List<CarMenuItem> items) { mMenuItems = items; List<CarMenuItem> actionItems = new ArrayList<>(); mOverflowMenuItems.clear(); mActionViews.forEach(this::removeView); mActionViews.clear(); if (mMenuItems != null) { for (CarMenuItem item : mMenuItems) { if (item.getDisplayBehavior() == CarMenuItem.DisplayBehavior.ALWAYS) { actionItems.add(item); } else { mOverflowMenuItems.add(item); } } } mOverflowButtonView.setVisibility(mOverflowMenuItems.isEmpty() ? GONE : VISIBLE); for (CarMenuItem item : actionItems) { View view = item.isCheckable() ? createCheckableAction(item) : createAction(item); MarginLayoutParams marginLayoutParams = new MarginLayoutParams(LayoutParams.WRAP_CONTENT, mActionButtonHeight); view.setLayoutParams(marginLayoutParams); mActionViews.add(view); addView(view); } requestLayout(); }