auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private List<XmlClass> createXmlClasses(List<ITestNGMethod> methods, XmlTest srcXmlTest) { List<XmlClass> result = Lists.newArrayList(); Map<Class, Set<ITestNGMethod>> methodsMap = Maps.newHashMap(); for (ITestNGMethod m : methods) { Object instances = m.getInstance(); Class clazz = instances == null ? m.getRealClass() : instances.getClass(); Set<ITestNGMethod> methodList = methodsMap.get(clazz); if (null == methodList) { methodList = new HashSet<>(); methodsMap.put(clazz, methodList); } methodList.add(m); } <START> Map<String, Map<String, String>> classParameters = new HashMap<String,Map<String, String>>(); <END> for (XmlClass c : srcXmlTest.getClasses()) { classParameters.put(c.getName(),c.getLocalParameters()); } int index = 0; for (Map.Entry<Class, Set<ITestNGMethod>> entry : methodsMap.entrySet()) { Class clazz = entry.getKey(); Set<ITestNGMethod> methodList = entry.getValue(); XmlClass xmlClass = new XmlClass(clazz.getName(), index++, false ); List<XmlInclude> methodNames = Lists.newArrayList(methodList.size()); int ind = 0; for (ITestNGMethod m : methodList) { XmlInclude methodName = new XmlInclude( m.getConstructorOrMethod().getName(), m.getFailedInvocationNumbers(), ind++); methodName.setParameters(findMethodLocalParameters(srcXmlTest, m)); methodNames.add(methodName); } xmlClass.setIncludedMethods(methodNames); xmlClass.setParameters(classParameters.get(xmlClass.getName())); result.add(xmlClass); } return result; }</code><technical_language>Style issues + prefer Maps</technical_language>

Target:
private List<XmlClass> createXmlClasses(List<ITestNGMethod> methods, XmlTest srcXmlTest) { List<XmlClass> result = Lists.newArrayList(); Map<Class, Set<ITestNGMethod>> methodsMap = Maps.newHashMap(); for (ITestNGMethod m : methods) { Object instances = m.getInstance(); Class clazz = instances == null ? m.getRealClass() : instances.getClass(); Set<ITestNGMethod> methodList = methodsMap.get(clazz); if (null == methodList) { methodList = Sets.newHashSet(); methodsMap.put(clazz, methodList); } methodList.add(m); } Map<String, Map<String, String>> classParameters = Maps.newHashMap(); for (XmlClass c : srcXmlTest.getClasses()) { classParameters.put(c.getName(),c.getLocalParameters()); } int index = 0; for (Map.Entry<Class, Set<ITestNGMethod>> entry : methodsMap.entrySet()) { Class clazz = entry.getKey(); Set<ITestNGMethod> methodList = entry.getValue(); XmlClass xmlClass = new XmlClass(clazz.getName(), index++, false ); List<XmlInclude> methodNames = Lists.newArrayList(methodList.size()); int ind = 0; for (ITestNGMethod m : methodList) { XmlInclude methodName = new XmlInclude( m.getConstructorOrMethod().getName(), m.getFailedInvocationNumbers(), ind++); methodName.setParameters(findMethodLocalParameters(srcXmlTest, m)); methodNames.add(methodName); } xmlClass.setIncludedMethods(methodNames); xmlClass.setParameters(classParameters.get(xmlClass.getName())); result.add(xmlClass); } return result; }
Source:
<code>public String clearAuditTabMessageId() { this.relatesTo = null; this.messageId = null; <START> if (this.auditRecordList != null && !auditRecordList.isEmpty()) { <END> this.auditRecordList.clear(); } this.auditMessage = ""; this.auditFound = false; return NavigationConstant.AUDIT_SEARCH_PAGE; }</code><technical_language>Checking for null is sufficient here. need check !auditRecordList.isEmpty() clearing list</technical_language>

Target:
public String clearAuditTabMessageId() { this.relatesTo = null; this.messageId = null; if (auditRecordList != null) { this.auditRecordList.clear(); } this.auditMessage = ""; this.auditFound = false; return NavigationConstant.AUDIT_SEARCH_PAGE; }
Source:
<code>public static void testRead() throws Exception { <START> ProgressInputStream stream = new ProgressInputStream(IOUtils.toInputStream("test", (String) null)); <END> assertThat(stream.getProgress()).isEqualTo(0); int bytesRead = 0; while (stream.read() >= 0 && bytesRead < 10000) { bytesRead++; } assertThat(bytesRead).isEqualTo(4); assertThat(stream.getProgress()).isEqualTo(4); IOUtils.closeQuietly(stream); }</code><technical_language>I prefer explicit encoding null is platform default. ASCII a choice null</technical_language>

Target:
public static void testRead() throws Exception { ProgressInputStream stream = new ProgressInputStream(IOUtils.toInputStream("test", "UTF-8")); assertThat(stream.getProgress()).isEqualTo(0); int bytesRead = 0; while (stream.read() >= 0 && bytesRead < 10000) { bytesRead++; } assertThat(bytesRead).isEqualTo(4); assertThat(stream.getProgress()).isEqualTo(4); IOUtils.closeQuietly(stream); }
Source:
<code>private static String getSchedulerVersion() { Properties properties = FileUtils.resolvePropertiesFile(GRADLE_PROPERTIES_PATH); <START> String version = properties.getProperty(VERSION_ATTRIBUTE_NAME); <END> return version == null ? "not found" : version; }</code><technical_language>put a argument default property "not found". be: return properties.getProperty(VERSION_ATTRIBUTE_NAME, "not found");</technical_language>

Target:
private static String getSchedulerVersion() { return FileUtils.resolvePropertiesFile(GRADLE_PROPERTIES_PATH).getProperty(VERSION_ATTRIBUTE_NAME, "not found"); }
Source:
<code>public void removeMember(PerunSession sess, Group group, Member member) throws InternalErrorException, MemberNotExistsException, NotGroupMemberException, PrivilegeException, GroupNotExistsException, WrongAttributeAssignmentException, AttributeNotExistsException, ExternalyManagedException { Utils.checkPerunSession(sess); getGroupsManagerBl().checkGroupExists(sess, group); getPerunBl().getMembersManagerBl().checkMemberExists(sess, member); Attribute attrSynchronizeEnabled = getPerunBl().getAttributesManagerBl().getAttribute(sess, group, GROUPSYNCHROENABLED_ATTRNAME); if (attrSynchronizeEnabled.getValue() != null) { String synchronizeEnabled = (String) attrSynchronizeEnabled.getValue(); if (synchronizeEnabled.equals("true")) { <START> throw new ExternalyManagedException("Removing of member is not allowed. Group is externaly managed."); <END> } } if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, group) && !AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, group)) { throw new PrivilegeException(sess, "removeMember"); } getGroupsManagerBl().removeMember(sess, group, member); }</code><technical_language>Externaly -> Externally in a exception message</technical_language>

Target:
public void removeMember(PerunSession sess, Group group, Member member) throws InternalErrorException, MemberNotExistsException, NotGroupMemberException, PrivilegeException, GroupNotExistsException, WrongAttributeAssignmentException, AttributeNotExistsException, ExternallyManagedException { Utils.checkPerunSession(sess); getGroupsManagerBl().checkGroupExists(sess, group); getPerunBl().getMembersManagerBl().checkMemberExists(sess, member); if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, group) && !AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, group)) { throw new PrivilegeException(sess, "removeMember"); } Attribute attrSynchronizeEnabled = getPerunBl().getAttributesManagerBl().getAttribute(sess, group, GROUPSYNCHROENABLED_ATTRNAME); if (Objects.equals("true", (String) attrSynchronizeEnabled.getValue())) { throw new ExternallyManagedException("Removing of member is not allowed. Group is externally managed."); } getGroupsManagerBl().removeMember(sess, group, member); }
Source:
<code>protected HttpURLConnection setupConnection(URL builtUrl) throws IOException { Log.d(TAG, builtUrl.toString()); HttpURLConnection httpConnection = (HttpURLConnection)builtUrl.openConnection(); if (isPostRequest) { <START> setupConnectionInner(httpConnection); <END> httpConnection.setRequestMethod("POST"); httpConnection.setDoOutput(true); buildPostPayload(httpConnection); } else { setupConnectionInner(httpConnection); httpConnection.setRequestMethod("GET"); } return httpConnection; }</code><technical_language>this line is repeated in else statement, moved if</technical_language>

Target:
protected HttpURLConnection setupConnection(URL builtUrl) throws IOException { Log.d(TAG, builtUrl.toString()); HttpURLConnection httpConnection = (HttpURLConnection)builtUrl.openConnection(); setupConnectionInner(httpConnection); if (isPostRequest) { httpConnection.setRequestMethod("POST"); httpConnection.setDoOutput(true); buildPostPayload(httpConnection); } else { httpConnection.setRequestMethod("GET"); } return httpConnection; }
Source:
<code>public static String[] getStringValuesFromDatabase(Connection dbConnection, String sqlStmt, Object... params) throws UserStoreException { String[] values = new String[0]; try (PreparedStatement prepStmt = dbConnection.prepareStatement(sqlStmt)) { if (params != null && params.length > 0) { for (int i = 0; i < params.length; i++) { Object param = params[i]; if (param == null) { prepStmt.setString(i + 1, null); } else if (param instanceof String) { prepStmt.setString(i + 1, (String) param); } else if (param instanceof Integer) { prepStmt.setInt(i + 1, (Integer) param); } } } try(ResultSet rs = prepStmt.executeQuery() ) { List<String> lst = new ArrayList<String>(); <START> while (rs.next()) { <END> String name = rs.getString(1); lst.add(name); } if (lst.size() > 0) { values = lst.toArray(new String[lst.size()]); } return values; } } catch (SQLException e) { String errorMessage = "Using sql : " + sqlStmt + " " + e.getMessage(); if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } }</code><technical_language>try-with-resource pattern automatically handles ResultSet PreparedStatement objects, Connection, "dbConnection" in this scope, needs closed "DatabaseUtil.closeAllConnections(dbConnection);"</technical_language>

Target:
public static String[] getStringValuesFromDatabase(Connection dbConnection, String sqlStmt, Object... params) throws UserStoreException { String[] values = new String[0]; try (PreparedStatement prepStmt = dbConnection.prepareStatement(sqlStmt)) { if (params != null && params.length > 0) { for (int i = 0; i < params.length; i++) { Object param = params[i]; if (param == null) { prepStmt.setString(i + 1, null); } else if (param instanceof String) { prepStmt.setString(i + 1, (String) param); } else if (param instanceof Integer) { prepStmt.setInt(i + 1, (Integer) param); } } } try(ResultSet rs = prepStmt.executeQuery() ) { List<String> lst = new ArrayList<String>(); while (rs.next()) { String name = rs.getString(1); lst.add(name); } if (lst.size() > 0) { values = lst.toArray(new String[lst.size()]); } return values; } } catch (SQLException e) { String errorMessage = "Using sql : " + sqlStmt + " " + e.getMessage(); if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); }finally { close(dbConnection); } }
Source:
<code>public void returnsCorrectLengthWithStream() throws Exception { final byte[] bytes = new Utf8String("Stream returnsCorrectLength!").asBytes(); MatcherAssert.assertThat( <START> "Stream doesn't provide correct number of bytes", <END> new LengthOf( new Body.Stream(new InputOf(bytes).stream()) ).intValue(), new IsEqual<>(bytes.length) ); }</code><technical_language>@Serranya here. above</technical_language>

Target:
public void returnsCorrectLengthWithStream() throws Exception { final byte[] bytes = new Utf8String("Stream returnsCorrectLength!").asBytes(); MatcherAssert.assertThat( "Body content of Body.Stream doesn't have the correct length", new LengthOf( new Body.Stream(new InputOf(bytes).stream()) ).intValue(), new IsEqual<>(bytes.length) ); }
Source:
<code>public boolean vdsUpEvent(final VDS vds) { HostStoragePoolParametersBase params = new HostStoragePoolParametersBase(vds); boolean isSucceeded = Backend.getInstance().runInternalAction(VdcActionType.InitVdsOnUp, params).getSucceeded(); if (isSucceeded) { ThreadPoolUtil.execute(new Runnable() { @Override public void run() { try { List<VmStatic> vmsToMigrate = DbFacade.getInstance().getVmStaticDao().getAllWithFailbackByVds(vds.getId()); if (!vmsToMigrate.isEmpty()) { CommandContext ctx = new CommandContext(new EngineContext()); ctx.getExecutionContext().setMonitored(true); Backend.getInstance().runInternalMultipleActions(VdcActionType.MigrateVmToServer, new ArrayList<>(createMigrateVmToServerParametersList(vmsToMigrate, vds)), ctx); } } catch (RuntimeException e) { log.error("Failed to initialize Vds on up: {}", e.getMessage()); <START> log.debug("Exception", e); <END> } } }); } return isSucceeded; }</code><technical_language>please log in error</technical_language>

Target:
public boolean vdsUpEvent(final VDS vds) { HostStoragePoolParametersBase params = new HostStoragePoolParametersBase(vds); boolean isSucceeded = Backend.getInstance().runInternalAction(VdcActionType.InitVdsOnUp, params).getSucceeded(); if (isSucceeded) { ThreadPoolUtil.execute(new Runnable() { @Override public void run() { try { List<VmStatic> vmsToMigrate = DbFacade.getInstance().getVmStaticDao().getAllWithFailbackByVds(vds.getId()); if (!vmsToMigrate.isEmpty()) { CommandContext ctx = new CommandContext(new EngineContext()); ctx.getExecutionContext().setMonitored(true); Backend.getInstance().runInternalMultipleActions(VdcActionType.MigrateVmToServer, new ArrayList<>(createMigrateVmToServerParametersList(vmsToMigrate, vds)), ctx); } } catch (RuntimeException e) { log.error("Failed to initialize Vds on up: {}", e.getMessage()); log.error("Exception", e); } } }); } return isSucceeded; }
Source:
<code>private void stop() { notifier.removeListener(cleanupService); cm.removeListener(cleanupService); <START> cleanupService.stop(); <END> shutDownGracefully(); }</code><technical_language>Missing cm.removeListener(this)</technical_language>

Target:
private void stop() { notifier.removeListener(cleanupService); cm.removeListener(cleanupService); cm.removeListener(this); shutDownGracefully(); }
Source:
<code>public void testDescriptionInclusion() throws Exception { <START> final String xml = "src/test/resources/xml/simple-suite-with-method-desc.xml"; <END> SuiteXmlParser parser = new SuiteXmlParser(); TestNGContentHandler handler = new TestNGContentHandler(xml, false); parser.parse(new FileInputStream(xml), handler); List<XmlInclude> includes = handler.getSuite().getTests().get(0).getXmlClasses().get(0).getIncludedMethods(); String desc = includes.get(0).getDescription(); Assert.assertEquals("simple-description", desc); }</code><technical_language>getPathToResource util method</technical_language>

Target:
public void testDescriptionInclusion() throws Exception { final String xml = getPathToResource("xml/simple-suite-with-method-desc.xml"); SuiteXmlParser parser = new SuiteXmlParser(); TestNGContentHandler handler = new TestNGContentHandler(xml, false); parser.parse(new FileInputStream(xml), handler); List<XmlInclude> includes = handler.getSuite().getTests().get(0).getXmlClasses().get(0).getIncludedMethods(); String desc = includes.get(0).getDescription(); Assert.assertEquals("simple-description", desc); }
Source:
<code>public void saveDeposits(final LotDepositRequestDto lotDepositRequestDto, final TransactionStatus transactionStatus) { final WorkbenchUser user = this.securityService.getCurrentlyLoggedInUser(); if (lotDepositRequestDto.getSourceStudy() != null) { <START> this.studyValidator.validate(lotDepositRequestDto.getSourceStudy(), false); <END> } this.lotDepositRequestDtoValidator.validate(lotDepositRequestDto); final LotsSearchDto searchDTO = this.searchRequestDtoResolver.getLotsSearchDto(lotDepositRequestDto.getSelectedLots()); final List<ExtendedLotDto> lotDtos = this.lotService.searchLots(searchDTO, null); this.extendedLotListValidator.validateAllProvidedLotUUIDsExist(lotDtos, lotDepositRequestDto.getSelectedLots().getItemIds()); this.extendedLotListValidator.validateEmptyList(lotDtos); this.extendedLotListValidator.validateEmptyUnits(lotDtos); this.extendedLotListValidator.validateClosedLots(lotDtos); this.lotDepositRequestDtoValidator.validateDepositInstructionsUnits(lotDepositRequestDto, lotDtos); this.transactionService .depositLots(user.getUserid(), lotDtos.stream().map(ExtendedLotDto::getLotId).collect(Collectors.toSet()), lotDepositRequestDto, transactionStatus); }</code><technical_language>making experiment transaction record for study, I study unlocked if study is specified</technical_language>

Target:
public void saveDeposits(final LotDepositRequestDto lotDepositRequestDto, final TransactionStatus transactionStatus) { final WorkbenchUser user = this.securityService.getCurrentlyLoggedInUser(); if (lotDepositRequestDto.getSourceStudyId() != null) { this.studyValidator.validate(lotDepositRequestDto.getSourceStudyId(), true); } this.lotDepositRequestDtoValidator.validate(lotDepositRequestDto); final LotsSearchDto searchDTO = this.searchRequestDtoResolver.getLotsSearchDto(lotDepositRequestDto.getSelectedLots()); final List<ExtendedLotDto> lotDtos = this.lotService.searchLots(searchDTO, null); this.extendedLotListValidator.validateAllProvidedLotUUIDsExist(lotDtos, lotDepositRequestDto.getSelectedLots().getItemIds()); this.extendedLotListValidator.validateEmptyList(lotDtos); this.extendedLotListValidator.validateEmptyUnits(lotDtos); this.extendedLotListValidator.validateClosedLots(lotDtos); this.lotDepositRequestDtoValidator.validateDepositInstructionsUnits(lotDepositRequestDto, lotDtos); this.transactionService .depositLots(user.getUserid(), lotDtos.stream().map(ExtendedLotDto::getLotId).collect(Collectors.toSet()), lotDepositRequestDto, transactionStatus); }
Source:
<code>private CloseableHttpClient buildHttpClient() { try { final SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); <START> sslContext.init(null, null, null); <END> final SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory( sslContext, HostnameVerifier.INSTANCE); return HttpClients.custom() .setSSLSocketFactory(sslSocketFactory) .setDefaultRequestConfig(RequestConfig.custom() .setConnectTimeout(mBuilder.mConnectionTimeoutInMillis) .build()) .setDefaultSocketConfig(SocketConfig.custom() .setSoTimeout(mBuilder.mSocketTimeoutInMillis) .build()) .build(); } catch (final KeyManagementException e) { throw new RuntimeException("Exception while building Apache http client", e); } catch (final NoSuchAlgorithmException e) { throw new RuntimeException("Exception while building Apache http client", e); } }</code><technical_language>initializing SSLContext do in SocketFactory? is, I hostname verification for this client</technical_language>

Target:
private CloseableHttpClient buildHttpClient() { try { final SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(null, new X509ExtendedTrustManager[] { new HostnameVerifyingX509ExtendedTrustManager(true)}, new SecureRandom()); final SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext); return HttpClients.custom() .setSSLSocketFactory(sslSocketFactory) .setDefaultRequestConfig(RequestConfig.custom() .setConnectTimeout(mBuilder.mConnectionTimeoutInMillis) .build()) .setDefaultSocketConfig(SocketConfig.custom() .setSoTimeout(mBuilder.mSocketTimeoutInMillis) .build()) .build(); } catch (final KeyManagementException e) { throw new RuntimeException("Exception while building Apache http client", e); } catch (final NoSuchAlgorithmException e) { throw new RuntimeException("Exception while building Apache http client", e); } }
Source:
<code>public void execute() throws IOException { executeInternal(); <START> } <END></code><technical_language>Is a reason need executeInternal() method, execute() in executeToX methods</technical_language>

Target:
public HttpConnection execute() throws IOException { System.setProperty("http.keepAlive", "false"); connection = (HttpURLConnection) url.openConnection(); for (String key : requestProperties.keySet()) { connection.setRequestProperty(key, requestProperties.get(key)); } connection.setDoInput(true); connection.setRequestMethod(requestMethod); if (contentType != null) { connection.setRequestProperty("Content-type", contentType); } if (url.getUserInfo() != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStream bos = Base64OutputStreamFactory.get(baos); bos.write(url.getUserInfo().getBytes()); bos.flush(); bos.close(); String encodedAuth = baos.toString(); connection.setRequestProperty("Authorization", String.format("Basic %s", encodedAuth)); } if (input != null) { connection.setDoOutput(true); if (inputLength != -1) { connection.setFixedLengthStreamingMode((int)this.inputLength); } else { connection.setChunkedStreamingMode(1024); } connection.setRequestProperty("Expect", "100-continue"); int bufSize = 1024; int nRead = 0; byte[] buf = new byte[bufSize]; InputStream is = input; OutputStream os = connection.getOutputStream(); while((nRead = is.read(buf)) >= 0) { os.write(buf, 0, nRead); } os.flush(); } return this; }
Source:
<code>private MostRecentObserver(T value) { <START> VALUE_UPDATER.lazySet(this, nl.next(value)); <END> }</code><technical_language>I lazySet here. a this definition: <LINK_0> > semantics write is guaranteed re-ordered previous write, reordered subsequent operations (or equivalently, visible other threads) some other volatile write synchronizing action occurs)</technical_language>

Target:
private MostRecentObserver(T value) { this.value = nl.next(value); }
Source:
<code>public void setEnvironment() throws Exception { super.init(userMode); String gatewayUrl; <START> if (gatewayContextWrk.getContextTenant().getDomain().equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { <END> gatewayUrl = gatewayUrlsWrk.getWebAppURLNhttp(); } else { gatewayUrl = gatewayUrlsWrk.getWebAppURLNhttp() + "t/" + gatewayContextWrk.getContextTenant().getDomain() + "/"; } apiEndPointUrl = gatewayUrl + "jaxrs_basic/services/customers/customerservice"; apiProvider = publisherContext.getContextTenant().getContextUser().getUserName(); }</code><technical_language>Swap equals condition</technical_language>

Target:
public void setEnvironment() throws Exception { super.init(userMode); String gatewayUrl; if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(gatewayContextWrk.getContextTenant().getDomain())) { gatewayUrl = gatewayUrlsWrk.getWebAppURLNhttp(); } else { gatewayUrl = gatewayUrlsWrk.getWebAppURLNhttp() + "t/" + gatewayContextWrk.getContextTenant().getDomain() + "/"; } apiEndPointUrl = gatewayUrl + "jaxrs_basic/services/customers/customerservice"; apiProvider = publisherContext.getContextTenant().getContextUser().getUserName(); }
Source:
<code>public Journal getJournal(String journalKey) { Journal journal = hibernateTemplate.execute(session -> { Query query = session.createQuery("" + "FROM Journal j " + <START> "WHERE j.journalKey = :journalKey "); <END> query.setParameter("journalKey", journalKey); return (Journal) query.uniqueResult(); }); if (journal == null) { throw new RestClientException(journalNotFoundMessage(journalKey), HttpStatus.NOT_FOUND); } return journal; }</code><technical_language>Pointless style opinion, I mind writing a query this a single line short enough</technical_language>

Target:
public Journal getJournal(String journalKey) { Journal journal = hibernateTemplate.execute(session -> { Query query = session.createQuery("FROM Journal j WHERE j.journalKey = :journalKey "); query.setParameter("journalKey", journalKey); return (Journal) query.uniqueResult(); }); if (journal == null) { throw new RestClientException(journalNotFoundMessage(journalKey), HttpStatus.NOT_FOUND); } return journal; }
Source:
<code>public void retrieveSubjectToken() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); AwsCredentials awsCredential = (AwsCredentials) AwsCredentials.newBuilder(AWS_CREDENTIAL) .setHttpTransportFactory(transportFactory) .setCredentialSource(buildAwsCredentialSource(transportFactory)) .build(); String subjectToken = awsCredential.retrieveSubjectToken(); JsonParser parser = OAuth2Utils.JSON_FACTORY.createJsonParser(subjectToken); GenericJson json = parser.parseAndClose(GenericJson.class); Map<String, String> headers = (Map<String, String>) json.get("headers"); assertThat(json.get("method")).isEqualTo("POST"); <START> assertThat(json.get("url")).isEqualTo(GET_CALLER_IDENTITY_URL); <END> assertThat(headers.get("host")).isEqualTo(URI.create(GET_CALLER_IDENTITY_URL).getHost()); assertThat(headers.containsKey("x-amz-date")).isTrue(); assertThat(headers.get("x-amz-security-token")).isEqualTo("token"); assertThat(headers.get("x-goog-cloud-target-resource")).isEqualTo(awsCredential.getAudience()); assertThat(headers.get("Authorization")).isNotNull(); }</code><technical_language>assertEquals</technical_language>

Target:
public void retrieveSubjectToken() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); AwsCredentials awsCredential = (AwsCredentials) AwsCredentials.newBuilder(AWS_CREDENTIAL) .setHttpTransportFactory(transportFactory) .setCredentialSource(buildAwsCredentialSource(transportFactory)) .build(); String subjectToken = awsCredential.retrieveSubjectToken(); JsonParser parser = OAuth2Utils.JSON_FACTORY.createJsonParser(subjectToken); GenericJson json = parser.parseAndClose(GenericJson.class); Map<String, String> headers = (Map<String, String>) json.get("headers"); assertEquals("POST", json.get("method")); assertEquals(GET_CALLER_IDENTITY_URL, json.get("url")); assertEquals(URI.create(GET_CALLER_IDENTITY_URL).getHost(), headers.get("host")); assertEquals("token", headers.get("x-amz-security-token")); assertEquals(awsCredential.getAudience(), headers.get("x-goog-cloud-target-resource")); assertTrue(headers.containsKey("x-amz-date")); assertNotNull(headers.get("Authorization")); }
Source:
<code>public void aggregate(ByteBuffer buf, int position) { final int oldPosition = buf.position(); buf.position(position); bufferAdd(buf); <START> buf.position(oldPosition); <END> }</code><technical_language>position adjustment restore wrapped in a try/finally, want buffer left in invalid state if exception is thrown</technical_language>

Target:
public void aggregate(ByteBuffer buf, int position) { final int oldPosition = buf.position(); try { buf.position(position); bufferAdd(buf); } finally { buf.position(oldPosition); } }
Source:
<code>Map<String, RedisPatchSchedule> patchSchedulesAsMap() { <START> if (!load) { load = true; cacheCollection(); } Map<String, RedisPatchSchedule> result = new HashMap<>(); <END> for (Map.Entry<String, RedisPatchScheduleImpl> entry : this.collection().entrySet()) { RedisPatchScheduleImpl patchSchedule = entry.getValue(); result.put(entry.getKey(), patchSchedule); } return Collections.unmodifiableMap(result); }</code><technical_language>put a shared method ensureCollectionLoaded etc</technical_language>

Target:
Map<String, RedisPatchSchedule> patchSchedulesAsMap() { ensureCollectionLoaded(); Map<String, RedisPatchSchedule> result = new HashMap<>(); for (Map.Entry<String, RedisPatchScheduleImpl> entry : this.collection().entrySet()) { RedisPatchScheduleImpl patchSchedule = entry.getValue(); result.put(entry.getKey(), patchSchedule); } return Collections.unmodifiableMap(result); }
Source:
<code>@Override public void updateMvccCandidatesWithCurrentThread(long oldThreadId) { long currentThreadId = Thread.currentThread().getId(); <START> for (IgniteTxEntry igniteTxEntry : txMap.values()) { <END> GridCacheEntryEx cached = igniteTxEntry.cached(); if (cached != null && !cached.obsolete()) { GridCacheMvccCandidate candidate = null; try { candidate = cached.localCandidate(oldThreadId); } catch (GridCacheEntryRemovedException ignore) { assert false; } if (candidate != null) candidate.setThreadId(currentThreadId); } } }</code><technical_language>rename "igniteTxEntry" "entry"</technical_language>

Target:
@Override public void updateMvccCandidatesWithCurrentThread(long oldThreadId) { long curThreadId = Thread.currentThread().getId(); for (IgniteTxEntry entry : txMap.values()) { GridCacheEntryEx cached = entry.cached(); if (cached != null && !cached.obsolete()) { GridCacheMvccCandidate candidate = null; try { candidate = cached.localCandidate(oldThreadId); } catch (GridCacheEntryRemovedException e) { assert false; } if (candidate != null) candidate.threadId(curThreadId); } } }
Source:
<code>public S3BatchSource(S3BatchConfig config) { <START> super(new FileBatchConfig(config.referenceName, config.fileRegex, config.timeTable, config.inputFormatClass, <END> config.fileSystemProperties, config.maxSplitSize, config.ignoreNonExistingFolders, config.recursive, config.path, config.pathField, config.filenameOnly, config.schema)); this.config = config; }</code><technical_language>I able pass config in</technical_language>

Target:
public S3BatchSource(S3BatchConfig config) { super(config); this.config = config; }
Source:
<code>public void run() { super.run(); EObject target; DTreeItemContainer lineContainer; if <START> (getTreeItem() <END> != null) { target = getTreeItem().getTarget(); lineContainer = (DTreeItemContainer) getTreeItem().eContainer(); } else { target = tree.getTarget(); lineContainer = tree; } CompoundCommand compoundCommand = new CompoundCommand(getText()); Command cmd = treeCommandFactory.buildCreateLineCommandFromTool(lineContainer, target, getCreationTool()); compoundCommand.append(cmd); getEditingDomain().getCommandStack().execute(compoundCommand); }</code><technical_language>This method is called times</technical_language>

Target:
public void run() { super.run(); EObject target; DTreeItemContainer lineContainer; DTreeItem dTreeItem = getTreeItem(); if (dTreeItem != null) { target = dTreeItem.getTarget(); lineContainer = (DTreeItemContainer) dTreeItem.eContainer(); } else { target = tree.getTarget(); lineContainer = tree; } Command cmd = treeCommandFactory.buildCreateLineCommandFromTool(lineContainer, target, getCreationTool()); String label = getText(); cmd = new CommandWrapper(label, label, cmd); getEditingDomain().getCommandStack().execute(cmd); }
Source:
<code>public PoissonEventsArrival(double events, TimeUnit perUnit) { <START> _nanosToNextEventMean = perUnit.toNanos(1) / events; <END> }</code><technical_language>events 0</technical_language>

Target:
public PoissonEventsArrival(double events, TimeUnit perUnit) { if (events <= 0) { throw new IllegalArgumentException("events must be a positive number"); } _nanosToNextEventMean = perUnit.toNanos(1) / events; }
Source:
<code>protected <C extends FlagAffectedCommand & TopologyAffectedCommand> CompletableFuture<Void> remoteGet(InvocationContext ctx, C command, Object key, boolean isWrite) { CompletableFuture<Void> cf = super.remoteGet(ctx, command, key, isWrite); if (!ctx.isOriginLocal() || !ctx.isInTxScope()) { return cf; } List<Mutation> mutationsOnKey = getMutationsOnKey((TxInvocationContext) ctx, key); if (mutationsOnKey.isEmpty()) { return cf; } return cf.thenRun(() -> { entryFactory.wrapEntryForWriting(ctx, key, false, true); MVCCEntry cacheEntry = (MVCCEntry) ctx.lookupEntry(key); <START> EntryView.ReadWriteEntryView readWriteEntryView = EntryViews.readWrite(cacheEntry, null, null); <END> for (Mutation mutation : mutationsOnKey) { mutation.apply(readWriteEntryView); cacheEntry.updatePreviousValue(); } }); }</code><technical_language>call command.getKeyDataConversion() here</technical_language>

Target:
protected <C extends FlagAffectedCommand & TopologyAffectedCommand> CompletableFuture<Void> remoteGet(InvocationContext ctx, C command, Object key, boolean isWrite) { CompletableFuture<Void> cf = super.remoteGet(ctx, command, key, isWrite); if (!ctx.isOriginLocal() || !ctx.isInTxScope()) { return cf; } List<Mutation> mutationsOnKey = getMutationsOnKey((TxInvocationContext) ctx, key); if (mutationsOnKey.isEmpty()) { return cf; } return cf.thenRun(() -> { entryFactory.wrapEntryForWriting(ctx, key, false, true); MVCCEntry cacheEntry = (MVCCEntry) ctx.lookupEntry(key); EntryView.ReadWriteEntryView readWriteEntryView = EntryViews.readWrite(cacheEntry, DataConversion.DEFAULT, DataConversion.DEFAULT); for (Mutation mutation : mutationsOnKey) { mutation.apply(readWriteEntryView); cacheEntry.updatePreviousValue(); } }); }
Source:
<code>DefaultChannelHandlerContext(DefaultChannelPipeline pipeline, String name, ChannelHandler handler) { this.name = requireNonNull(name, "name"); this.pipeline = pipeline; <START> this.executionMask = ChannelHandlerMask.mask(handler.getClass()); <END> this.handler = handler; }</code><technical_language>omit classname static * import</technical_language>

Target:
DefaultChannelHandlerContext(DefaultChannelPipeline pipeline, String name, ChannelHandler handler) { this.name = requireNonNull(name, "name"); this.pipeline = pipeline; this.executionMask = mask(handler.getClass()); this.handler = handler; }
Source:
<code>public void start() { this.eventQueue.add(new DiscoveryServiceEvent(DISCOVER_INIT_TOPOLOGY)); this.executorService.submit(this::run); <START> startDiscovery(); <END> }</code><technical_language>purpose of DISCOVER_INIT_TOPOLOGY call startDiscovery there? DISCOVER_INIT_TOPOLOGY is a supported event (processEvent)</technical_language>

Target:
public void start() { this.eventQueue.add(new DiscoveryServiceEvent(DISCOVER_INIT_TOPOLOGY)); this.executorService.submit(this::run); }
Source:
<code>public static boolean isRecoverableException(final Throwable t) { <START> if( <END> t instanceof FailedRequestException || t instanceof Ds3NoMoreRetriesException || t instanceof IOException ) { return true; } return false; }</code><technical_language>This simplified. if/else is necessary</technical_language>

Target:
public static boolean isRecoverableException(final Throwable t) { if(t instanceof IOException) { return true; } return false; }
Source:
<code>public void appendRows(DecodedBlockNode[] decodedBlocks, int fixedWidthRowSize, List<Integer> variableWidthChannels, OutputBuffer outputBuffer) { if (positionCount == 0) { return; } initializeBlockEncodingBuffers(decodedBlocks); for (int i = 0; i < decodedBlocks.length; i++) { <START> blockEncodingBuffers[i].setupDecodedBlocksAndPositions(decodedBlocks[i], positions, positionCount); <END> } calculateRowSizes(fixedWidthRowSize, variableWidthChannels); int offset = 0; do { int positionsFit = calculateNumberRowsFitInBuffers(variableWidthChannels, fixedWidthRowSize, offset); assert positionsFit > 0; assert positionsFit <= positionCount - offset; for (int i = 0; i < channelCount; i++) { blockEncodingBuffers[i].setNextBatch(offset, positionsFit); blockEncodingBuffers[i].copyValues(); } bufferedRowCount += positionsFit; offset += positionsFit; if (bufferFull) { flush(outputBuffer); bufferFull = false; for (int i = 0; i < blockEncodingBuffers.length; i++) { blockEncodingBuffers[i].resetBuffers(); } } } while (offset < positionCount); }</code><technical_language>decodedBlocks.length -> channelCount (for consistency)</technical_language>

Target:
public void appendRows(DecodedBlockNode[] decodedBlocks, int fixedWidthRowSize, List<Integer> variableWidthChannels, OutputBuffer outputBuffer) { checkArgument(decodedBlocks.length == channelCount, "Unexpected number of blocks"); if (positionCount == 0) { return; } if (channelCount == 0) { bufferedRowCount += positionCount; return; } initializeBlockEncodingBuffers(decodedBlocks); for (int i = 0; i < channelCount; i++) { blockEncodingBuffers[i].setupDecodedBlocksAndPositions(decodedBlocks[i], positions, positionCount); } calculateRowSizes(fixedWidthRowSize, variableWidthChannels); int offset = 0; do { int batchSize = calculateNextBatchSize(fixedWidthRowSize, variableWidthChannels, offset); for (int i = 0; i < channelCount; i++) { blockEncodingBuffers[i].setNextBatch(offset, batchSize); blockEncodingBuffers[i].copyValues(); } bufferedRowCount += batchSize; offset += batchSize; if (bufferFull) { flush(outputBuffer); bufferFull = false; } } while (offset < positionCount); }
Source:
<code>public <T> int readFieldNumber(Schema<T> schema) throws IOException { if (offset == limit) { lastTag = 0; return 0; } final int tag; if (currentPacked()) { <START> if (packed_limit < offset) <END> throw ProtobufException.misreportedSize(); return lastTag >>> TAG_TYPE_BITS; } else { tag = readRawVarint32(); packed_limit = 0; } final int fieldNumber = tag >>> TAG_TYPE_BITS; if (fieldNumber == 0) { if (decodeNestedMessageAsGroup && WIRETYPE_TAIL_DELIMITER == (tag & TAG_TYPE_MASK)) { lastTag = 0; return 0; } throw ProtobufException.invalidTag(); } if (decodeNestedMessageAsGroup && WIRETYPE_END_GROUP == (tag & TAG_TYPE_MASK)) { lastTag = 0; return 0; } lastTag = tag; return fieldNumber; }</code><technical_language>camel case - packed_limit -> packedLimit</technical_language>

Target:
public <T> int readFieldNumber(Schema<T> schema) throws IOException { if (offset == limit) { lastTag = 0; return 0; } if (isCurrentFieldPacked()) { if (packedLimit < offset) throw ProtobufException.misreportedSize(); return lastTag >>> TAG_TYPE_BITS; } packedLimit = 0; final int tag = readRawVarint32(); final int fieldNumber = tag >>> TAG_TYPE_BITS; if (fieldNumber == 0) { if (decodeNestedMessageAsGroup && WIRETYPE_TAIL_DELIMITER == (tag & TAG_TYPE_MASK)) { lastTag = 0; return 0; } throw ProtobufException.invalidTag(); } if (decodeNestedMessageAsGroup && WIRETYPE_END_GROUP == (tag & TAG_TYPE_MASK)) { lastTag = 0; return 0; } lastTag = tag; return fieldNumber; }
Source:
<code>public Histogram getTemperatures() { Metadata metadata = new Metadata("temperatures", MetricType.HISTOGRAM, "degrees F"); metadata.setDescription("A histogram of recent New York temperatures."); <START> final int[] RECENT_NEW_YORK_TEMPS = { 46, 45, 50, 46, 45, 27, 30, 48, 55, 54, 45, 41, 45, 43, 46 }; <END> histogram = registry.histogram(metadata); for(int temp : RECENT_NEW_YORK_TEMPS) { histogram.update(temp); } return histogram; }</code><technical_language>RECENT_NEW_YORK_TEMPS a convention of a constant variable. I suggest move out of method add private static match java convention</technical_language>

Target:
public Histogram getTemperatures() { Metadata metadata = new Metadata("temperatures", MetricType.HISTOGRAM, "degrees F"); metadata.setDescription("A histogram of recent New York temperatures."); histogram = registry.histogram(metadata); for(int temp : RECENT_NEW_YORK_TEMPS) { histogram.update(temp); } return histogram; }
Source:
<code>void unpackId(String id) { if (id != null && id.length() > 0) { this.id = id; try { URL url = new URL(id); String[] tokens = url.getPath().split("/"); <START> this.vaultUrl = (tokens.length >= 1 ? tokens[1] : null); <END> this.name = (tokens.length >= 3 ? tokens[2] : null); this.version = (tokens.length >= 4 ? tokens[3] : null); } catch (MalformedURLException e) { e.printStackTrace(); } } }</code><technical_language>tokens.length >= 2 ? ....</technical_language>

Target:
void unpackId(String id) { if (id != null && id.length() > 0) { this.id = id; try { URL url = new URL(id); String[] tokens = url.getPath().split("/"); this.vaultUrl = (tokens.length >= 2 ? tokens[1] : null); this.name = (tokens.length >= 3 ? tokens[2] : null); this.version = (tokens.length >= 4 ? tokens[3] : null); } catch (MalformedURLException e) { throw logger.logExceptionAsError(new IllegalArgumentException("The Azure Key Vault endpoint url is malformed.", e)); } } }
Source:
<code>private void internalClientProviderRemoved(Class<? extends IInternalClientProvider<?, ?>> clazz) { <START> Set<IInternalClientProvider<?, ?>> internalClientProvidersToBeRemoved = new HashSet<IInternalClientProvider<?, ?>>(); <END> for (IInternalClientProvider<?, ?> internalClientProvider : internalClientProviders) { if (internalClientProvider.getClass().isAssignableFrom(clazz)) { internalClientProvidersToBeRemoved.add(internalClientProvider); } } internalClientProviders.remove(internalClientProvidersToBeRemoved); }</code><technical_language>Maintenance of map simpler of list</technical_language>

Target:
private void internalClientProviderRemoved(Class<? extends IInternalClientProvider<?, ?>> clazz) { internalClientProviders.remove(clazz); }
Source:
<code>public void stop() { LOGGER.debug("Shutting down PooledExecutionService"); running = false; scheduledExecutor.shutdownNow(); for (Iterator<Entry<String, ThreadPoolExecutor>> it = pools.entrySet().iterator(); it.hasNext(); ) { Entry<String, ThreadPoolExecutor> e = it.next(); try { destroyPool(e.getKey(), e.getValue()); } finally { it.remove(); } } try { <START> scheduledExecutor.awaitTermination(30, SECONDS); <END> } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }</code><technical_language>this in a similar loop in destroyPool method</technical_language>

Target:
public void stop() { LOGGER.debug("Shutting down PooledExecutionService"); running = false; scheduledExecutor.shutdownNow(); for (Iterator<Entry<String, ThreadPoolExecutor>> it = pools.entrySet().iterator(); it.hasNext(); ) { Entry<String, ThreadPoolExecutor> e = it.next(); try { destroyPool(e.getKey(), e.getValue()); } finally { it.remove(); } } try { if(!scheduledExecutor.awaitTermination(30, SECONDS)) { LOGGER.warn("Timeout while waiting on scheduler to finish"); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
Source:
<code>public void testVersionMergeReplaceStrategy() { ContentMerger contentMerger = new ContentMerger(MergeStrategy.REPLACE, MergeStrategy.KEEP); Item current = new Item(); Item extracted = new Item(); Version version1 = new Version(); version1.setCanonicalUri("<LINK_1>"); current.setVersions(ImmutableSet.of(version1)); Restriction restriction = new Restriction(); restriction.setRestricted(true); Version version2 = new Version(); version2.setCanonicalUri("<LINK_0>"); version2.setRestriction(restriction); extracted.setVersions(ImmutableSet.of(version2)); Item merged = contentMerger.merge(current, extracted); <START> Version mergetVersion = Iterables.getOnlyElement(merged.getVersions()); <END> assertEquals("<LINK_0>", mergetVersion.getCanonicalUri()); assertTrue(mergetVersion.getRestriction().isRestricted()); }</code><technical_language>slight typo here, merget instead of merged. major though..</technical_language>

Target:
public void testVersionMergeReplaceStrategy() { ContentMerger contentMerger = new ContentMerger(MergeStrategy.REPLACE, MergeStrategy.KEEP); Item current = new Item(); Item extracted = new Item(); Version version1 = new Version(); version1.setCanonicalUri("<LINK_1>"); current.setVersions(ImmutableSet.of(version1)); Restriction restriction = new Restriction(); restriction.setRestricted(true); Version version2 = new Version(); version2.setCanonicalUri("<LINK_0>"); version2.setRestriction(restriction); extracted.setVersions(ImmutableSet.of(version2)); Item merged = contentMerger.merge(current, extracted); Version mergedVersion = Iterables.getOnlyElement(merged.getVersions()); assertEquals("<LINK_0>", mergedVersion.getCanonicalUri()); assertTrue(mergedVersion.getRestriction().isRestricted()); }
Source:
<code>public void perform(@Observes PostStartup event) { boolean isDependencies = event.getAddon().getId().toString().contains("org.jboss.windup.ui:windup-ui"); if(isDependencies) { <START> Furnace furnace = FurnaceHolder.getFurnace(); <END> Imported<DependencyResolver> exportedTypes = furnace.getAddonRegistry().getServices(DependencyResolver.class); if(!exportedTypes.isUnsatisfied() && rulesetNeedUpdate(exportedTypes.get())) { System.out.println(""); System.out.println("Your ruleset is obsolete. Consider running windup-update-ruleset or windup-update-distribution command. Press ENTER to continue."); System.out.println(""); } } }</code><technical_language>I @Inject furnace instead of this. are, all, in a Furnace CDI environment this point in system. switch useing @Inject, add Furnace method parameter list for another style of injection</technical_language>

Target:
public void perform(@Observes PostStartup event) { boolean isDependencies = event.getAddon().getId().toString().contains("org.jboss.windup.ui:windup-ui"); if (isDependencies) { Imported<DependencyResolver> exportedTypes = furnace.getAddonRegistry().getServices(DependencyResolver.class); if (!exportedTypes.isUnsatisfied() && rulesetNeedUpdate(exportedTypes.get())) { System.out.println(""); System.out.println("Your ruleset is obsolete. Consider running windup-update-ruleset or windup-update-distribution command. Press ENTER to continue."); System.out.println(""); } } }
Source:
<code>protected MethodMatchers getMethodInvocationMatchers() { return MethodMatchers.or( MethodMatchers.create() .ofTypes( "org.junit.Assert", "org.junit.jupiter.api.Assertions", "junit.framework.Assert", "junit.framework.TestCase") .name(name -> name.startsWith(ASSERT)) .withAnyParameters() .build(), <START> MethodMatchers.create() .ofTypes("org.fest.assertions.Assertions") .names(ASSERT_THAT) .withAnyParameters() .build(), <END> MethodMatchers.create() .ofSubTypes("org.fest.assertions.GenericAssert") .name(name -> name.startsWith(IS)) .withAnyParameters() .build() ); }</code><technical_language>I remove (or extract for use) this matcher, is useful anymore able avoid check line 94</technical_language>

Target:
protected MethodMatchers getMethodInvocationMatchers() { return MethodMatchers.or( MethodMatchers.create() .ofTypes( "org.junit.Assert", "org.junit.jupiter.api.Assertions", "junit.framework.Assert", "junit.framework.TestCase") .name(name -> name.startsWith(ASSERT)) .withAnyParameters() .build(), MethodMatchers.create() .ofSubTypes("org.fest.assertions.GenericAssert") .name(name -> name.startsWith(IS)) .withAnyParameters() .build() ); }
Source:
<code>private TypeSpec(Builder builder) { checkArgument(builder.name != null ^ builder.anonymousTypeArguments != null, "types must have either a name or anonymous type arguments"); boolean isInterface = builder.type == Type.INTERFACE; boolean typeIsAbstract = builder.modifiers.contains(Modifier.ABSTRACT) || isInterface; for (MethodSpec methodSpec : builder.methodSpecs) { checkArgument(typeIsAbstract || !methodSpec.hasModifier(Modifier.ABSTRACT), "non-abstract type %s cannot declare abstract method %s", builder.name, methodSpec.name); checkArgument(!isInterface || methodSpec.hasModifier(Modifier.ABSTRACT), "interface %s cannot declare non-abstract method %s", builder.name, methodSpec.name); <START> checkArgument(!isInterface || methodSpec.hasModifier(Modifier.PUBLIC), <END> "interface %s cannot declare non-public method %s", builder.name, methodSpec.name); } this.annotations = ImmutableList.copyOf(builder.annotations); this.modifiers = ImmutableSet.copyOf(builder.modifiers); this.type = checkNotNull(builder.type); this.name = builder.name; this.supertype = builder.supertype; this.anonymousTypeArguments = builder.anonymousTypeArguments; this.fieldSpecs = ImmutableList.copyOf(builder.fieldSpecs); this.methodSpecs = ImmutableList.copyOf(builder.methodSpecs); }</code><technical_language>Later, is</technical_language>

Target:
private TypeSpec(Builder builder) { checkArgument(builder.name != null ^ builder.anonymousTypeArguments != null, "types must have either a name or anonymous type arguments"); boolean isInterface = builder.type == Type.INTERFACE; boolean typeIsAbstract = builder.modifiers.contains(Modifier.ABSTRACT) || isInterface; for (MethodSpec methodSpec : builder.methodSpecs) { checkArgument(typeIsAbstract || !methodSpec.hasModifier(Modifier.ABSTRACT), "non-abstract type %s cannot declare abstract method %s", builder.name, methodSpec.name); checkArgument(!isInterface || methodSpec.hasModifier(Modifier.ABSTRACT), "interface %s cannot declare non-abstract method %s", builder.name, methodSpec.name); checkArgument(!isInterface || methodSpec.hasModifier(Modifier.PUBLIC), "interface %s cannot declare non-public method %s", builder.name, methodSpec.name); } for (FieldSpec fieldSpec : builder.fieldSpecs) { if (isInterface) { checkArgument(fieldSpec.hasModifier(Modifier.PUBLIC) && fieldSpec.hasModifier(Modifier.STATIC) && fieldSpec.hasModifier(Modifier.FINAL), "interface %s field %s must be public static final", builder.name, fieldSpec.name); } } this.annotations = ImmutableList.copyOf(builder.annotations); this.modifiers = ImmutableSet.copyOf(builder.modifiers); this.type = checkNotNull(builder.type); this.name = builder.name; this.supertype = builder.supertype; this.anonymousTypeArguments = builder.anonymousTypeArguments; this.fieldSpecs = ImmutableList.copyOf(builder.fieldSpecs); this.methodSpecs = ImmutableList.copyOf(builder.methodSpecs); }