auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void onError(Throwable throwable) { log.error("onError for CorfuReplicationDiscoveryServeiceLisener"); }

Target:
public void onError(Throwable throwable) { log.error("onError with a throwable {}", throwable); }
Source:
public static boolean hasConstexprStaticIntegralValueField(ICPPClassType type, long expectedValue) { return Arrays.stream(ClassTypeHelper.getFields(type)).filter(IS_STATIC_VARIABLE).filter(IS_NAMED_VALUE) .filter(HAS_INTEGRAL_TYPE).filter(IS_CONSTEXPR_FIELD).filter(field -> { return field.getInitialValue().numberValue().longValue() == expectedValue; }).findFirst().isPresent(); }

Target:
public static boolean hasConstexprStaticIntegralValueField(ICPPClassType type, long expectedValue) { return Arrays.stream(ClassTypeHelper.getFields(type)).filter(IS_STATIC_VARIABLE).filter(IS_NAMED_VALUE) .filter(HAS_INTEGRAL_TYPE).filter(HAS_CONST_TYPE).filter(field -> { return variableHasInitialNumberValue(field, expectedValue); }).findFirst().isPresent(); }
Source:
public URL getEntryUrlOrNull(String entryName) { if (jarFile.findEntry(entryName) != null) { try { return new URL("jar", null, -1, fileUri + "!/" + entryName, this); } catch (MalformedURLException e) { throw new RuntimeException("Unexpectedly invalid entry name", e); } } return null; }

Target:
public URL getEntryUrlOrNull(String entryName) { if (jarFile.findEntry(entryName) != null) { try { return new URL("jar", null, -1, fileUri + "!/" + entryName, this); } catch (MalformedURLException e) { throw new RuntimeException("Invalid entry name", e); } } return null; }
Source:
@Test public void testExchange() { final FrameworkConfig config = RelBuilderTest.config().build(); final RelBuilder builder = RelBuilder.create(config); final RelNode rel = builder .scan("EMP") .exchange(RelDistributions.hash(ImmutableList.of(0, 1))) .build(); String relJson = RelOptUtil.dumpPlan("", rel, SqlExplainFormat.JSON, SqlExplainLevel.EXPPLAN_ATTRIBUTES); String s = deserializeAndDumpToTextFormat(getSchema(rel), relJson); final String expected = "" + "LogicalExchange(distribution=[hash[0, 1]])\n" + " LogicalTableScan(table=[[scott, EMP]])\n"; assertThat(s, isLinux(expected)); }

Target:
@Test public void testExchange() { final FrameworkConfig config = RelBuilderTest.config().build(); final RelBuilder builder = RelBuilder.create(config); final RelNode rel = builder .scan("EMP") .exchange(RelDistributions.hash(ImmutableList.of(0, 1))) .build(); final String relJson = RelOptUtil.dumpPlan("", rel, SqlExplainFormat.JSON, SqlExplainLevel.EXPPLAN_ATTRIBUTES); String s = deserializeAndDumpToTextFormat(getSchema(rel), relJson); final String expected = "" + "LogicalExchange(distribution=[hash[0, 1]])\n" + " LogicalTableScan(table=[[scott, EMP]])\n"; assertThat(s, isLinux(expected)); }
Source:
public void initialize() { logger.debug("Initializing thing {}", getThing().getUID()); config = getConfigAs(LIRCRemoteConfiguration.class); remoteName = config.getRemote(); if (remoteName == null) { logger.error("Remote name is not set in {}", getThing().getUID()); return; } initializeBridge((getBridge() == null) ? null : getBridge().getHandler(), (getBridge() == null) ? null : getBridge().getStatus()); }

Target:
public void initialize() { logger.debug("Initializing thing {}", getThing().getUID()); config = getConfigAs(LIRCRemoteConfiguration.class); remoteName = config.getRemote(); if (remoteName == null) { logger.error("Remote name is not set in {}", getThing().getUID()); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Remote name is not set"); } else { bridgeHandler = (LIRCBridgeHandler) getBridge().getHandler(); bridgeHandler.registerMessageListener(this); if (getBridge().getStatus() == ThingStatus.ONLINE) { updateStatus(ThingStatus.ONLINE); } else { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE); } } }
Source:
public TextAnalyticsClientBuilder() { policies = new ArrayList<>(); httpLogOptions = new HttpLogOptions(); Map<String, String> properties = CoreUtils.getProperties(TEXT_ANALYTICS_PROPERTIES); clientName = properties.getOrDefault(NAME, "UnknownName"); clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); headers = new HttpHeaders() .put(ECHO_REQUEST_ID_HEADER, "true") .put(CONTENT_TYPE_HEADER, CONTENT_TYPE_HEADER_VALUE) .put(ACCEPT_HEADER, ACCEPT_HEADER_VALUE); }

Target:
public TextAnalyticsClientBuilder() { policies = new ArrayList<>(); httpLogOptions = new HttpLogOptions(); Map<String, String> properties = CoreUtils.getProperties(TEXT_ANALYTICS_PROPERTIES); clientName = properties.getOrDefault(NAME, "UnknownName"); clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); headers = new HttpHeaders() .put(ECHO_REQUEST_ID_HEADER, "true") .put(CONTENT_TYPE_HEADER, CONTENT_TYPE_HEADER_VALUE) .put(ACCEPT_HEADER, CONTENT_TYPE_HEADER_VALUE); }
Source:
public void testDeployServerReturnsUnexpectedError() throws InterruptedException { server.enqueue(responseUnexpectedError()); NetworkInfo networkInfo = NetworkInfo .create("networkDomainId", NIC.builder().vlanId("vlanId").build(), Lists.<NIC>newArrayList()); try { serverApi().deployServer(ServerApiMockTest.class.getSimpleName(), "imageId", true, networkInfo, "administratorPassword"); failBecauseExceptionWasNotThrown(ResourceNotFoundException.class); } catch (HttpResponseException e) { assertNotNull(e); assertSent(POST, "/caas/2.4/6ac1e746-b1ea-4da5-a24e-caf1a978789d/server/deployServer"); } }

Target:
public void testDeployServerReturnsUnexpectedError() throws InterruptedException { server.enqueue(responseUnexpectedError()); NetworkInfo networkInfo = NetworkInfo .create("networkDomainId", NIC.builder().vlanId("vlanId").build(), Lists.<NIC>newArrayList()); try { serverApi().deployServer(ServerApiMockTest.class.getSimpleName(), "imageId", true, networkInfo, "administratorPassword"); failBecauseExceptionWasNotThrown(HttpResponseException.class); } catch (HttpResponseException e) { assertNotNull(e); assertSent(POST, "/caas/2.4/6ac1e746-b1ea-4da5-a24e-caf1a978789d/server/deployServer"); } }
Source:
private Employment getEmployment(boolean full) throws JAXBException { JAXBContext context = JAXBContext.newInstance(new Class[] { Employment.class }); Unmarshaller unmarshaller = context.createUnmarshaller(); String name = "/record_2.0/samples/read_samples/employment-2.0.xml"; if(full) { name = "/record_2.0/samples/read_samples } InputStream inputStream = getClass().getResourceAsStream(name); return (Employment) unmarshaller.unmarshal(inputStream); }

Target:
private Employment getEmployment(boolean full) throws JAXBException { JAXBContext context = JAXBContext.newInstance(new Class[] { Employment.class }); Unmarshaller unmarshaller = context.createUnmarshaller(); String name = "/record_2.0/samples/read_samples/employment-2.0.xml"; if(full) { name = "/record_2.0/samples/read_samples/employment-full-2.0.xml"; } InputStream inputStream = getClass().getResourceAsStream(name); return (Employment) unmarshaller.unmarshal(inputStream); }
Source:
public PluginInfoWrapper getPluginInfo(String plugname) { for (PluginInfoWrapper pluginInfoWrapper : pluginWrappers) { if (pluginInfoWrapper.getPluginClassName().equals(plugname) || pluginInfoWrapper.getFilename().equals(plugname)) { return pluginInfoWrapper; } } return null; }

Target:
public PluginInfoWrapper getPluginInfo(String plugname) { for (PluginInfoWrapper pluginInfoWrapper : loadedPlugins.getLoadedPlugins()) { if (pluginInfoWrapper.getPluginClassName().equals(plugname) || pluginInfoWrapper.getFilename().equals(plugname)) { return pluginInfoWrapper; } } return null; }
Source:
protected X509Certificate loadCACertificate(String path) { try ( InputStream inStream = new FileInputStream(path); ) { X509Certificate cert = (X509Certificate) this.certFactory.generateCertificate(inStream); inStream.close(); return cert; } catch (Exception e) { throw new RuntimeException(e); } }

Target:
protected X509Certificate loadCACertificate(String path) { try ( InputStream inStream = new FileInputStream(path); ) { return (X509Certificate) this.certFactory.generateCertificate(inStream); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
public static File getRemovableStorageAppDir(@NonNull Context context) { int currentapiVersion = android.os.Build.VERSION.SDK_INT; if (currentapiVersion >= Build.VERSION_CODES.LOLLIPOP) { File[] fileList = context.getExternalFilesDirs("Android"); for (File extFile : fileList){ if (extFile != null && Environment.isExternalStorageRemovable(extFile)){ return extFile; } } } return null; }

Target:
public static File getRemovableStorageAppDir(@NonNull Context context) { int currentapiVersion = android.os.Build.VERSION.SDK_INT; if (currentapiVersion >= Build.VERSION_CODES.LOLLIPOP) { File[] fileList = context.getExternalFilesDirs(null); for (File extFile : fileList){ if (extFile != null && Environment.isExternalStorageRemovable(extFile)){ return extFile; } } } return null; }
Source:
private void loadBackdrop() { getSharedPreferences(); if (!name.equals(Preferences.DEF_VALUE)) tvName.setText(name); if (!email.equals(Preferences.DEF_VALUE)) tvEmail.setText(email); if (!profilePicUrl.equals(Preferences.DEF_VALUE)) Glide.with(this).load(profilePicUrl).into(ivProfilePic); if (!coverPicUrl.equals(Preferences.DEF_VALUE)) Picasso.with(this).load(coverPicUrl).resize(DeviceDimensionsHelper.getDisplayWidth(this), 0).into(ivCoverPic); }

Target:
private void loadBackdrop() { getSharedPreferences(); if (!Preferences.DEF_VALUE.equals(name)) tvName.setText(name); if (!Preferences.DEF_VALUE.equals(email)) tvEmail.setText(email); if (!Preferences.DEF_VALUE.equals(profilePicUrl)) Glide.with(this).load(profilePicUrl).into(ivProfilePic); if (!Preferences.DEF_VALUE.equals(coverPicUrl)) Picasso.with(this).load(coverPicUrl).resize(DeviceDimensionsHelper.getDisplayWidth(this), 0).into(ivCoverPic); }
Source:
void markContainersInactive(Set<Container> inactiveContainerCandidateSet) throws InterruptedException { if (inactiveContainerCandidateSet != null) { boolean success = false; Exception updateException = null; int retry = 0; while (!success && retry < config.maxRetryCountOnUpdateFailure) { Map<Short, Account> accountToUpdateMap = new HashMap<>(); inactiveContainerCandidateSet.forEach(container -> { short accountId = container.getParentAccountId(); Account accountToEdit = accountToUpdateMap.computeIfAbsent(accountId, this::getAccountById); Container containerToEdit = accountToEdit.getContainerById(container.getId()); Container editedContainer = new ContainerBuilder(containerToEdit).setStatus(Container.ContainerStatus.INACTIVE).build(); accountToUpdateMap.put(accountId, new AccountBuilder(accountToEdit).addOrUpdateContainer(editedContainer).build()); }); try { updateAccounts(accountToUpdateMap.values()); success = true; } catch (AccountServiceException ase) { updateException = ase; retry++; Thread.sleep(config.retryDelayMs); } } if (updateException != null) { logger.error("Failed to mark containers INACTIVE in set : after retries", inactiveContainerCandidateSet, config.maxRetryCountOnUpdateFailure, updateException); accountServiceMetrics.accountUpdatesToZkErrorCount.inc(); } } }

Target:
void markContainersInactive(Set<Container> inactiveContainerCandidateSet) throws InterruptedException { if (inactiveContainerCandidateSet != null) { Exception updateException = null; int retry = 0; Map<Short, Account> accountToUpdateMap = new HashMap<>(); inactiveContainerCandidateSet.forEach(container -> { short accountId = container.getParentAccountId(); Account accountToEdit = accountToUpdateMap.computeIfAbsent(accountId, this::getAccountById); Container containerToEdit = accountToEdit.getContainerById(container.getId()); Container editedContainer = new ContainerBuilder(containerToEdit).setStatus(Container.ContainerStatus.INACTIVE).build(); accountToUpdateMap.put(accountId, new AccountBuilder(accountToEdit).addOrUpdateContainer(editedContainer).build()); }); do { try { updateAccounts(accountToUpdateMap.values()); updateException = null; } catch (AccountServiceException ase) { updateException = ase; retry++; Thread.sleep(config.retryDelayMs); } } while (updateException != null && retry < config.maxRetryCountOnUpdateFailure); if (updateException != null) { logger.error("Failed to mark containers INACTIVE in set : after retries", inactiveContainerCandidateSet, config.maxRetryCountOnUpdateFailure, updateException); accountServiceMetrics.accountUpdatesToStoreErrorCount.inc(); } } }
Source:
private void expandPoolIfNecessary(int channelCount) { if (!asyncExpantionExceptionOccurred.get()) { try { this.channelPool.ensureCapacity(channelCount); } catch (IOException e) { LOG.info("Could not expand the channel pool.", e); asyncExpantionExceptionOccurred.set(true); } } }

Target:
private void expandPoolIfNecessary(int channelCount) { try { this.channelPool.ensureChannelCount(channelCount); } catch (IOException e) { LOG.info("Could not expand the channel pool.", e); } }
Source:
private List<PageTitle> getExpectedResults() { List<PageTitle> result = new ArrayList<>(); result.add(new PageTitle(null, "Sciëntologie", new WikiSite("af.wikipedia.org"))); result.add(new PageTitle(null, "سينتولوجيا", new WikiSite("ar.wikipedia.org"))); result.add(new PageTitle(null, "سيينتولوجيا", new WikiSite("arz.wikipedia.org"))); return result; }

Target:
private List<PageTitle> getExpectedResults() { List<PageTitle> result = new ArrayList<>(); result.add(new PageTitle("Sciëntologie", WikiSite.forLanguageCode("af"))); result.add(new PageTitle("سينتولوجيا", WikiSite.forLanguageCode("ar"))); result.add(new PageTitle("سيينتولوجيا", WikiSite.forLanguageCode("arz"))); return result; }
Source:
public B readEnvironment(SystemReader sr) { if (getGitDir() == null) { String val = sr.getenv(GIT_DIR_KEY); if (val != null) setGitDir(new File(val)); } if (getGitCommonDir() == null) { String val = sr.getenv(GIT_COMMON_DIR_KEY); if (val != null) setGitCommonDir(new File(val)); } if (getObjectDirectory() == null) { String val = sr.getenv(GIT_OBJECT_DIRECTORY_KEY); if (val != null) setObjectDirectory(new File(val)); } if (getAlternateObjectDirectories() == null) { String val = sr.getenv(GIT_ALTERNATE_OBJECT_DIRECTORIES_KEY); if (val != null) { for (String path : val.split(File.pathSeparator)) addAlternateObjectDirectory(new File(path)); } } if (getWorkTree() == null) { String val = sr.getenv(GIT_WORK_TREE_KEY); if (val != null) setWorkTree(new File(val)); } if (getIndexFile() == null) { String val = sr.getenv(GIT_INDEX_FILE_KEY); if (val != null) setIndexFile(new File(val)); } if (ceilingDirectories == null) { String val = sr.getenv(GIT_CEILING_DIRECTORIES_KEY); if (val != null) { for (String path : val.split(File.pathSeparator)) addCeilingDirectory(new File(path)); } } return self(); }

Target:
public B readEnvironment(SystemReader sr) { if (getGitDir() == null) { String val = sr.getenv(GIT_DIR_KEY); if (val != null) setGitDir(new File(val)); } if (getGitCommonDir() == null) { String val = sr.getenv(GIT_COMMON_DIR_KEY); if (val != null) { setGitCommonDir(new File(val)); } } if (getObjectDirectory() == null) { String val = sr.getenv(GIT_OBJECT_DIRECTORY_KEY); if (val != null) setObjectDirectory(new File(val)); } if (getAlternateObjectDirectories() == null) { String val = sr.getenv(GIT_ALTERNATE_OBJECT_DIRECTORIES_KEY); if (val != null) { for (String path : val.split(File.pathSeparator)) addAlternateObjectDirectory(new File(path)); } } if (getWorkTree() == null) { String val = sr.getenv(GIT_WORK_TREE_KEY); if (val != null) setWorkTree(new File(val)); } if (getIndexFile() == null) { String val = sr.getenv(GIT_INDEX_FILE_KEY); if (val != null) setIndexFile(new File(val)); } if (ceilingDirectories == null) { String val = sr.getenv(GIT_CEILING_DIRECTORIES_KEY); if (val != null) { for (String path : val.split(File.pathSeparator)) addCeilingDirectory(new File(path)); } } return self(); }
Source:
public List<Diagnosis> getUniqueDiagnoses(Patient patient, Date fromDate) { List<Diagnosis> diagnoses = getDiagnoses(patient, fromDate); Set<CodedOrFreeText> uniqueDiagnoses = new HashSet<CodedOrFreeText>(); Iterator<Diagnosis> it = diagnoses.iterator(); while (it.hasNext()) { Diagnosis diagnosis = it.next(); if (!uniqueDiagnoses.add(diagnosis.getDiagnosis())) { it.remove(); } } return diagnoses; }

Target:
public List<Diagnosis> getUniqueDiagnoses(Patient patient, Date fromDate) { Set<Diagnosis> uniqueDiagnoses = new HashSet<Diagnosis>(); uniqueDiagnoses.addAll(getDiagnoses(patient, fromDate)); return new ArrayList(uniqueDiagnoses); }
Source:
public void testMetaDataRemoval() { BugsnagAppender.addThreadMetaData("thread", "some key", "some thread value"); BugsnagAppender.addThreadMetaData("report", "some key", "some report value"); LOGGER.warn("Test exception", new RuntimeException("test")); BugsnagAppender.clearThreadMetaData(); LOGGER.warn("Test exception", new RuntimeException("test")); assertEquals(2, delivery.getNotifications().size()); Notification notification = delivery.getNotifications().get(0); Report report = notification.getEvents().get(0); assertTrue(report.getMetaData().containsKey("report")); assertTrue(report.getMetaData().containsKey("thread")); assertEquals("some report value", getMetaDataMap(notification, "report").get("some key")); assertEquals("some thread value", getMetaDataMap(notification, "thread").get("some key")); notification = delivery.getNotifications().get(1); report = notification.getEvents().get(0); assertFalse(report.getMetaData().containsKey("report")); assertFalse(report.getMetaData().containsKey("thread")); }

Target:
public void testMetaDataRemoval() { Bugsnag.addThreadMetaData("thread", "some key", "some thread value"); LOGGER.warn(new BugsnagMarker(new Callback() { @Override public void beforeNotify(Report report) { report.addToTab("report", "some key", "some report value"); } }), "Test exception", new RuntimeException("test")); LOGGER.warn("Test exception", new RuntimeException("test")); Bugsnag.clearThreadMetaData(); LOGGER.warn("Test exception", new RuntimeException("test")); assertEquals(3, delivery.getNotifications().size()); Notification notification = delivery.getNotifications().get(0); Report report = notification.getEvents().get(0); assertTrue(report.getMetaData().containsKey("report")); assertTrue(report.getMetaData().containsKey("thread")); assertEquals("some report value", getMetaDataMap(notification, "report").get("some key")); assertEquals("some thread value", getMetaDataMap(notification, "thread").get("some key")); notification = delivery.getNotifications().get(1); report = notification.getEvents().get(0); assertFalse(report.getMetaData().containsKey("report")); assertTrue(report.getMetaData().containsKey("thread")); assertEquals("some thread value", getMetaDataMap(notification, "thread").get("some key")); notification = delivery.getNotifications().get(2); report = notification.getEvents().get(0); assertFalse(report.getMetaData().containsKey("report")); assertFalse(report.getMetaData().containsKey("thread")); }
Source:
public void init() { dataSourceSync(); if (refreshRate > 0) { refreshTimer.schedule(new TimerTask() { @Override public void run() { dataSourceSync(); } }, refreshRate, refreshRate); } }

Target:
public void init() { dataSourceSync(); if (refreshRate > 0) { refreshTimer.schedule(new TimerTask() { @Override public void run() { try { dataSourceSync(); } catch (Exception ex) { LOG.error("An error occurred while synchronizing the datasource: {}", ex.getMessage(), ex); } } }, refreshRate, refreshRate); } }
Source:
public void delete(File file) throws IOException { if (file != null && file.exists() && !file.delete()) { log.warn("Failed to delete file/directory at path: " + file.getAbsolutePath()); } }

Target:
private void delete(File file) throws IOException { if (file != null && file.exists() && !file.delete()) { log.warn("Failed to delete file/directory at path: " + file.getAbsolutePath()); } }
Source:
private AbstractFile getOrMakeFolder(SleuthkitCase skCase, FsContent dataSource, String path) throws TskCoreException { String parentPath = getParentPath(path); String folderName = getFileName(path); List<AbstractFile> files = null; if(parentPath != null) { if(!parentPath.equals("/")) { parentPath = parentPath + "/"; } files = skCase.findAllFilesWhere(String.format("fs_obj_id=%s AND parent_path='%s' AND name='%s'", dataSource.getFileSystemId(), parentPath, folderName != null ? folderName : "")); } else { files = skCase.findAllFilesWhere(String.format("fs_obj_id=%s AND parent_path='/' AND name=''", dataSource.getFileSystemId())); } if(files == null || files.isEmpty()) { AbstractFile parent = getOrMakeFolder(skCase, dataSource, parentPath); return skCase.addVirtualDirectory(parent.getId(), folderName); } else { return files.get(0); } }

Target:
private AbstractFile getOrMakeFolder(SleuthkitCase skCase, FsContent dataSource, String path) throws TskCoreException { String parentPath = getParentPath(path); String folderName = getFileName(path); List<AbstractFile> files = null; if (parentPath != null) { if (!parentPath.equals("/")) { parentPath = parentPath + "/"; } files = skCase.findAllFilesWhere(String.format("fs_obj_id=%s AND parent_path='%s' AND name='%s'", dataSource.getFileSystemId(), SleuthkitCase.escapeSingleQuotes(parentPath), folderName != null ? SleuthkitCase.escapeSingleQuotes(folderName) : "")); } else { files = skCase.findAllFilesWhere(String.format("fs_obj_id=%s AND parent_path='/' AND name=''", dataSource.getFileSystemId())); } if (files == null || files.isEmpty()) { AbstractFile parent = getOrMakeFolder(skCase, dataSource, parentPath); return skCase.addVirtualDirectory(parent.getId(), folderName); } else { return files.get(0); } }
Source:
public void testCreateFromXMLFunctionExtension5() throws InterruptedException { log.info("CreateFromXMLFunctionExtension TestCase 4"); SiddhiManager siddhiManager = new SiddhiManager(); siddhiManager.setExtension("str:concat", ConcatFunctionExtension.class); String inStreamDefinition = "\ndefine stream inputStream (longAttr long, doubleAttr double, booleanAttr bool, strAttr string);"; String query = ("@info(name = 'query1') from inputStream select " + "longAttr, doubleAttr, booleanAttr, strAttr as hashMap insert into outputStream;" + "from outputStream " + "select map:toXML(hashMap, 'sensor') as xmlString " + "insert into outputStream2"); ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inStreamDefinition + query); InputHandler inputHandler = executionPlanRuntime.getInputHandler("inputStream"); executionPlanRuntime.start(); inputHandler.send(new Object[]{25, 100.1, true, "Event1"}); inputHandler.send(new Object[]{35, 100.11, false, "Event2"}); inputHandler.send(new Object[]{45, 100.13456, true, "Event3"}); executionPlanRuntime.shutdown(); }

Target:
public void testCreateFromXMLFunctionExtension5() throws InterruptedException { log.info("CreateFromXMLFunctionExtension TestCase with test Object[] data should be string format"); SiddhiManager siddhiManager = new SiddhiManager(); siddhiManager.setExtension("str:concat", ConcatFunctionExtension.class); String inStreamDefinition = "\ndefine stream inputStream (longAttr long, doubleAttr double, booleanAttr bool," + " strAttr string);"; String query = ("@info(name = 'query1') from inputStream select " + "longAttr, doubleAttr, booleanAttr, strAttr as hashMap insert into outputStream;" + "from outputStream " + "select map:toXML(hashMap, 'sensor') as xmlString " + "insert into outputStream2"); ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inStreamDefinition + query); InputHandler inputHandler = executionPlanRuntime.getInputHandler("inputStream"); executionPlanRuntime.start(); inputHandler.send(new Object[]{25, 100.1}); executionPlanRuntime.shutdown(); }
Source:
public List<PermissionSubject> getPermissionCheckSubjects() { if (permsList == null && disk != null) { permsList = new ArrayList<PermissionSubject>(); permsList.add(new PermissionSubject(disk.getimage_group_id(), VdcObjectType.Disk, ActionGroup.DELETE_DISK)); if (disk.getvm_guid() != null) { if (disk.getVmEntityType() == VmEntityType.VM) { permsList.add(new PermissionSubject(disk.getvm_guid(), VdcObjectType.VM, ActionGroup.CONFIGURE_VM_STORAGE)); } if (disk.getVmEntityType() == VmEntityType.TEMPLATE) { permsList.add(new PermissionSubject(disk.getvm_guid(), VdcObjectType.VmTemplate, ActionGroup.DELETE_TEMPLATE)); } } } return permsList; }

Target:
public List<PermissionSubject> getPermissionCheckSubjects() { if (permsList == null && disk != null) { permsList = new ArrayList<PermissionSubject>(); permsList.add(new PermissionSubject(disk.getimage_group_id(), VdcObjectType.Disk, ActionGroup.DELETE_DISK)); } return permsList; }
Source:
public Deserializer getDeserializer() { return (buffer, builder, columnConfig) -> { byte versionFromBuffer = buffer.get(); if (VERSION_ONE == versionFromBuffer) { int offset = buffer.getInt(); int initialPos = buffer.position(); final CompressedDoublesIndexedSupplier column = CompressedDoublesIndexedSupplier.fromByteBuffer( buffer, byteOrder, builder.getFileMapper() ); buffer.position(initialPos + offset); final ImmutableBitmap bitmap; if (buffer.hasRemaining()) { int bitmapSize = buffer.getInt(); bitmap = bitmapSerdeFactory.getObjectStrategy().fromByteBuffer(buffer, bitmapSize); builder.setNullValueBitmap(Suppliers.ofInstance(bitmap)); } else { bitmap = bitmapSerdeFactory.getBitmapFactory().makeEmptyImmutableBitmap(); } builder.setType(ValueType.DOUBLE) .setHasMultipleValues(false) .setGenericColumn(new DoubleGenericColumnSupplier(column, bitmap)); } else { throw new IAE("Unknown version[%d]", (int) versionFromBuffer); } }; }

Target:
public Deserializer getDeserializer() { return (buffer, builder, columnConfig) -> { int offset = buffer.getInt(); int initialPos = buffer.position(); final Supplier<ColumnarDoubles> column = CompressedColumnarDoublesSuppliers.fromByteBuffer( buffer, byteOrder ); buffer.position(initialPos + offset); final ImmutableBitmap bitmap; if (buffer.hasRemaining()) { bitmap = bitmapSerdeFactory.getObjectStrategy().fromByteBufferWithSize(buffer); } else { bitmap = bitmapSerdeFactory.getBitmapFactory().makeEmptyImmutableBitmap(); } builder.setType(ValueType.DOUBLE) .setHasMultipleValues(false) .setGenericColumn(new DoubleGenericColumnSupplier(column, bitmap)); }; }
Source:
public Set<String> getContentTypes() { return new TreeSet<String>(contentTypeToBodyParserMap.keySet()); }

Target:
public Set<String> getContentTypes() { return ImmutableSet.copyOf(contentTypeToBodyParserMap.keySet()); }
Source:
protected boolean isUserCanBeAuthenticated() { boolean authenticated = authenticateWithLdap(); if (authenticated) { if (!checkUserAndGroupsAuthorization(ldapUser.getUserId(), ldapUser.getGroupIds(), getActionType().getActionGroup(), MultiLevelAdministrationHandler.BOTTOM_OBJECT_ID, VdcObjectType.Bottom)) { addCanDoActionMessage(VdcBllMessages.USER_NOT_AUTHORIZED_TO_PERFORM_ACTION); return false; } VdcUser currentUser = new VdcUser(ldapUser); boolean isAdmin = MultiLevelAdministrationHandler.isAdminUser(currentUser); log.debugFormat("Checking if user {0} is an admin, result {1}", currentUser.getUserName(), isAdmin); currentUser.setAdmin(isAdmin); setCurrentUser(currentUser); } return authenticated; }

Target:
protected boolean isUserCanBeAuthenticated() { boolean authenticated = performUserAuthentication(); if (authenticated) { if (!checkUserAndGroupsAuthorization(ldapUser.getUserId(), ldapUser.getGroupIds(), getActionType().getActionGroup(), MultiLevelAdministrationHandler.BOTTOM_OBJECT_ID, VdcObjectType.Bottom)) { addCanDoActionMessage(VdcBllMessages.USER_NOT_AUTHORIZED_TO_PERFORM_ACTION); return false; } VdcUser currentUser = new VdcUser(ldapUser); retrieveUserAdminStatus(currentUser); setCurrentUser(currentUser); } return authenticated; }
Source:
public VertexRef getTarget() { return Optional.ofNullable(getPropertyValue(PROPERTY_TARGET)).map(VertexRef::new).orElse(null); }

Target:
public VertexRefEntity getTarget() { return target; }
Source:
void onAnnounce(Message announcementMessage) { LOG.debug(String.format("Handling announcement message %s...", announcementMessage)); boolean successfullyAggregated = aggregateInfo(masterAggregatorStats, announcementMessage); if(successfullyAggregated) { LOG.debug(String.format("Calling registered handler for for aggregated statistics %s...", masterAggregatorStats)); handler.call(masterAggregatorStats); LOG.debug(String.format("Announcement message processed")); } else { LOG.error("Message will be skipped in statistics computation.", announcementMessage); } }

Target:
void onAnnounce(Message announcementMessage) { LOG.debug(String.format("Handling announcement message %s...", announcementMessage)); boolean successfullyAggregated = aggregateInfo(masterAggregatorStats, announcementMessage); if (successfullyAggregated) { LOG.debug(String.format("Calling registered handler for announcement statistics %s...", masterAggregatorStats)); handler.call(masterAggregatorStats); LOG.debug(String.format("Announcement message processed")); } }
Source:
public Map<String, ByteBuffer> unTar() throws IOException { Map<String, ByteBuffer> fileContent = new HashMap<>(); TarArchiveEntry tarEntry = null; tarEntry = tarInputStream.getNextTarEntry(); while (tarEntry != null) { byte[] content = new byte[(int) tarEntry.getSize()]; try (InputStream is = new FileInputStream(tarEntry.getFile());) { if (is.read(content) == -1) { log.errorFormat("File {0} could not be read ", tarEntry.getFile()); } } fileContent.put(tarEntry.getName(), ByteBuffer.wrap(content)); tarEntry = tarInputStream.getNextTarEntry(); } return fileContent; }

Target:
public Map<String, ByteBuffer> unTar() throws IOException { Map<String, ByteBuffer> fileContent = new HashMap<>(); TarArchiveEntry tarEntry = null; tarEntry = tarInputStream.getNextTarEntry(); while (tarEntry != null) { byte[] content = new byte[(int) tarEntry.getSize()]; try (InputStream is = new FileInputStream(tarEntry.getFile());) { if (is.read(content) == -1) { log.errorFormat("File {0} could not be read ", tarEntry.getFile()); continue; } } fileContent.put(tarEntry.getName(), ByteBuffer.wrap(content)); tarEntry = tarInputStream.getNextTarEntry(); } return fileContent; }
Source:
private String modifybasename(String name) { if(name.equalsIgnoreCase("children")) return "child"; if(name.length()>2 && name.endsWith("s")) return name.substring(0,name.length()-1); return FOR_LOOP_ELEMENT_IDENTIFIER; }

Target:
private String modifybasename(String name) { if(name.equalsIgnoreCase("children")) return "child"; if(name.endsWith("Entries")) { String firstpart=name.substring(0,name.length()-7); return firstpart+"Entry"; } if(name.length()>2 && name.endsWith("s")) return name.substring(0,name.length()-1); return FOR_LOOP_ELEMENT_IDENTIFIER; }
Source:
public AmqpTransaction(ByteBuffer transactionId) { this.transactionId = transactionId; }

Target:
public AmqpTransaction(ByteBuffer transactionId) { this.transactionId = Objects.requireNonNull(transactionId, "'transactionId' cannot be null."); }
Source:
public static void main(String[] args) throws InterruptedException { MesosCluster cluster = new MesosCluster( MesosClusterConfig.builder() .mesosImageTag(MESOS_IMAGE_TAG) .slaveResources(new String[]{"ports(*):[4000-4000,5000-5000]", "ports(*):[4001-4001,5001-5001]", "ports(*):[4002-4002,5002-5002]"}) .build() ); final AtomicReference<ElasticsearchSchedulerContainer> schedulerReference = new AtomicReference<>(null); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { if (schedulerReference.get() != null) { schedulerReference.get().remove(); } cluster.stop(); new DockerUtil(cluster.getConfig().dockerClient).killAllExecutors(); } }); cluster.start(); LOGGER.info("Starting scheduler"); ElasticsearchSchedulerContainer scheduler = new ElasticsearchSchedulerContainer(cluster.getConfig().dockerClient, cluster.getZkContainer().getIpAddress(), cluster); schedulerReference.set(scheduler); scheduler.start(); seedData(cluster, scheduler); LOGGER.info("Scheduler started at http://" + scheduler.getIpAddress() + ":" + TEST_CONFIG.getSchedulerGuiPort()); LOGGER.info("Type CTRL-C to quit"); while (true) { Thread.sleep(1000); } }

Target:
public static void main(String[] args) throws InterruptedException { MesosCluster cluster = new MesosCluster( MesosClusterConfig.builder() .mesosImageTag(MESOS_IMAGE_TAG) .slaveResources(TEST_CONFIG.getPortRanges()) .build() ); final AtomicReference<ElasticsearchSchedulerContainer> schedulerReference = new AtomicReference<>(null); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { if (schedulerReference.get() != null) { schedulerReference.get().remove(); } cluster.stop(); new DockerUtil(cluster.getConfig().dockerClient).killAllExecutors(); } }); cluster.start(); LOGGER.info("Starting scheduler"); ElasticsearchSchedulerContainer scheduler = new ElasticsearchSchedulerContainer(cluster.getConfig().dockerClient, cluster.getZkContainer().getIpAddress(), cluster); schedulerReference.set(scheduler); scheduler.start(); seedData(cluster, scheduler); LOGGER.info("Scheduler started at http://" + scheduler.getIpAddress() + ":" + TEST_CONFIG.getSchedulerGuiPort()); LOGGER.info("Type CTRL-C to quit"); while (true) { Thread.sleep(1000); } }
Source:
public static Step addStep(ExecutionContext context, StepEnum stepName, String description, boolean isExternal) { if (context == null) { return null; } Step step = null; if (context.isMonitored()) { if (description == null) { description = ExecutionMessageDirector.getInstance().getStepMessage(stepName); } try { Job job = context.getJob(); if (context.getExecutionMethod() == ExecutionMethod.AsJob && job != null) { JobRepositoryFactory.getJobRepository().loadJobSteps(job); step = job.addStep(stepName, description); try { step.setExternal(isExternal); JobRepositoryFactory.getJobRepository().saveStep(step); } catch (Exception e) { log.errorFormat("Failed to save new step {0} for job {1}, {2}.", stepName.name(), job.getId(), job.getActionType().name(), e); job.getSteps().remove(step); step = null; } } else { Step contextStep = context.getStep(); if (context.getExecutionMethod() == ExecutionMethod.AsStep && contextStep != null) { JobRepositoryFactory.getJobRepository().loadParentStepSteps(contextStep); step = addSubStep(contextStep, stepName, description); step.setExternal(isExternal); } } } catch (Exception e) { log.error(e); } } return step; }

Target:
public static Step addStep(ExecutionContext context, StepEnum stepName, String description, boolean isExternal) { if (context == null) { return null; } Step step = null; if (context.isMonitored()) { if (description == null) { description = ExecutionMessageDirector.getInstance().getStepMessage(stepName); } try { Job job = context.getJob(); if (context.getExecutionMethod() == ExecutionMethod.AsJob && job != null) { step = job.addStep(stepName, description); try { step.setExternal(isExternal); JobRepositoryFactory.getJobRepository().saveStep(step); } catch (Exception e) { log.errorFormat("Failed to save new step {0} for job {1}, {2}.", stepName.name(), job.getId(), job.getActionType().name(), e); job.getSteps().remove(step); step = null; } } else { Step contextStep = context.getStep(); if (context.getExecutionMethod() == ExecutionMethod.AsStep && contextStep != null) { step = addSubStep(contextStep, stepName, description); step.setExternal(isExternal); } } } catch (Exception e) { log.error(e); } } return step; }
Source:
public static synchronized Properties getProperties() { if (properties == null) { File propFile = getPropertiesFile(getBasedir().getAbsoluteFile(), BUILD_PROPS_SEARCH_PARENT_DIR_LIMIT); Validate.isTrue(propFile.exists(), "Couldn't find build.properties at '%s'!", propFile.getAbsolutePath()); properties = new Properties(); FileInputStream fis = null; try { fis = new FileInputStream(propFile); properties.load(fis); } catch (FileNotFoundException e) { throw new IllegalStateException("Properties file not found. At this point, this is impossible.", e); } catch (IOException e) { throw new IllegalStateException("Properties file cannot be read!", e); } finally { if (fis != null) { try { fis.close(); } catch (IOException ex) { LOGGER.warn("Failed to close input stream", ex); } } } } return (Properties) properties.clone(); }

Target:
public static synchronized Properties getProperties() { return (properties==null) ? createProperties() : (Properties) properties.clone(); }
Source:
protected String getRFC822EmailAddress(final Collection<List<?>> subjectAltNames) { try { if (subjectAltNames == null) { return null; } Optional<List<?>> email = subjectAltNames.stream().filter(s -> ((Integer) s.get(0)) == RFC822_SAN_TYPE).findFirst(); if (email.isPresent()) { return (String) email.get().get(1); } } catch (final ArrayIndexOutOfBoundsException e) { LOGGER.error("Subject Alternative Name List does not contain at least two required elements. Returning null principal id..."); } return null; }

Target:
protected String getRFC822EmailAddress(final Collection<List<?>> subjectAltNames) { if (subjectAltNames == null) { return null; } Optional<List<?>> email = subjectAltNames .stream() .filter(s -> s.size() == 2 && ((Integer) s.get(0)) == SAN_RFC822_EMAIL_TYPE) .findFirst(); if (email.isPresent()) { return (String) email.get().get(1); } return null; }
Source:
public SimplifyExpressions(Metadata metadata, SqlParser sqlParser) { super((expression, context) -> rewrite(expression, context, metadata, sqlParser)); }

Target:
public SimplifyExpressions(Metadata metadata, SqlParser sqlParser) { this.metadata = metadata; this.sqlParser = sqlParser; }
Source:
private void validateDeploymentProperties(D definition, Map<String, String> properties) { List<ModuleDescriptor> modules = parser.parse(definition.getName(), definition.getDefinition(), definitionKind); Set<String> moduleLabels = new HashSet<String>(modules.size()); for (ModuleDescriptor md : modules) { moduleLabels.add(md.getModuleLabel()); } DeploymentPropertiesUtility.validateDeploymentProperties(properties, moduleLabels); }

Target:
private void validateDeploymentProperties(D definition, Map<String, String> properties) { List<ModuleDescriptor> modules = parser.parse(definition.getName(), definition.getDefinition(), definitionKind); Set<String> moduleLabels = new HashSet<String>(modules.size()); for (ModuleDescriptor md : modules) { moduleLabels.add(md.getModuleLabel()); } for (Map.Entry<String, String> pair : properties.entrySet()) { Matcher matcher = DEPLOYMENT_PROPERTY_PATTERN.matcher(pair.getKey()); Assert.isTrue(matcher.matches(), String.format("'%s' does not match '%s'", pair.getKey(), DEPLOYMENT_PROPERTY_PATTERN)); String moduleName = matcher.group(1); Assert.isTrue(moduleLabels.contains(moduleName), String.format("'%s' refers to a module that is not in the list: %s", pair.getKey(), moduleLabels)); } }
Source:
public String toString() { return Objects.toStringHelper(this) .add("World:", this.worldObj) .add("Position: ", this.xPosition + this.zPosition) .toString(); }

Target:
public String toString() { return Objects.toStringHelper(this) .add("World", this.worldObj) .add("Position", this.xPosition + this.zPosition) .toString(); }
Source:
private SharedRealm getSharedRealm() { RealmConfiguration config; config = configFactory.createConfiguration(); return getSharedRealm(config); }

Target:
private SharedRealm getSharedRealm() { RealmConfiguration config = configFactory.createConfiguration(); return getSharedRealm(config); }
Source:
public final HttpResponse invoke(Q query, String endpoint) throws InvocationException { Preconditions.checkNotNull(query); Preconditions.checkNotNull(endpoint); httpClient.setParams(getHttpClientParams(query)); HttpRequestBase method; HttpEntity response = null; try { method = getHttpMethod(query, endpoint); org.apache.http.HttpResponse httpResponse = httpClient.execute(method); response = httpResponse.getEntity(); return HttpResponse.create(httpResponse.getStatusLine().getStatusCode(), EntityUtils.toString(response)); } catch (URISyntaxException e) { log.debug("Error during invocation", e); throw new InvocationException("InvocationException : ", e); } catch (ClientProtocolException e) { log.debug("Error during invocation", e); throw new InvocationException("InvocationException : ", e); } catch (IOException e) { log.debug("Error during invocation", e); throw new InvocationException("InvocationException : ", e); } finally { try { if (response != null) EntityUtils.consume(response); } catch (Throwable e) { log.error("Cannot release connection", e); } } }

Target:
public final HttpResponse invoke(Q query, String endpoint) throws InvocationException { Preconditions.checkNotNull(query); Preconditions.checkNotNull(endpoint); httpClient.setParams(getHttpClientParams(query)); HttpRequestBase method = null; HttpEntity response = null; try { method = getHttpMethod(query, endpoint); org.apache.http.HttpResponse httpResponse = httpClient.execute(method); response = httpResponse.getEntity(); return HttpResponse.create(httpResponse.getStatusLine().getStatusCode(), EntityUtils.toString(response)); } catch (Exception e) { if (method != null) { log.debug("Error during invocation with URL: " + method.getURI() + ", endpoint: " + endpoint + ", query: " + query, e); } else { log.debug("Error during invocation with: endpoint: " + endpoint + ", query: " + query, e); } throw new InvocationException("InvocationException : ", e); } finally { EntityUtils.consumeQuietly(response); } }
Source:
public <T> T doPost(final String uri, final Object body, final Multimap<String, String> options, final Class<T> clazz) throws KillBillClientException { return doPost(uri, body, options, this.httpTimeOut, clazz); }

Target:
public <T> T doPost(final String uri, final Object body, final Multimap<String, String> options, final Class<T> clazz) throws KillBillClientException { return doPost(uri, body, options, requestTimeoutSec, clazz); }
Source:
private static AuditListener createListener(String format, String outputLocation) throws IOException { final OutputStream out; final AutomaticBean.OutputStreamOptions closeOutputStream; if (outputLocation == null) { out = System.out; closeOutputStream = AutomaticBean.OutputStreamOptions.NONE; } else { out = Files.newOutputStream(Paths.get(outputLocation)); closeOutputStream = AutomaticBean.OutputStreamOptions.CLOSE; } final AuditListener listener; if (XML_FORMAT_NAME.equals(format)) { listener = new XMLLogger(out, closeOutputStream); } else if (PLAIN_FORMAT_NAME.equals(format)) { listener = new DefaultLogger(out, closeOutputStream, out, AutomaticBean.OutputStreamOptions.NONE); } else { if (closeOutputStream == AutomaticBean.OutputStreamOptions.CLOSE) { CommonUtils.close(out); } final LocalizedMessage outputFormatExceptionMessage = new LocalizedMessage(0, Definitions.CHECKSTYLE_BUNDLE, CREATE_LISTENER_EXCEPTION, new String[] {format, PLAIN_FORMAT_NAME, XML_FORMAT_NAME}, null, Main.class, null); throw new IllegalStateException(outputFormatExceptionMessage.getMessage()); } return listener; }

Target:
private static AuditListener createListener(String format, String outputLocation) throws IOException { final AuditListener listener; if (XML_FORMAT_NAME.equals(format)) { final OutputStream out = getOutputStream(outputLocation); final AutomaticBean.OutputStreamOptions closeOutputStreamOption = getOutputStreamOptions(outputLocation); listener = new XMLLogger(out, closeOutputStreamOption); } else if (PLAIN_FORMAT_NAME.equals(format)) { final OutputStream out = getOutputStream(outputLocation); final AutomaticBean.OutputStreamOptions closeOutputStreamOption = getOutputStreamOptions(outputLocation); listener = new DefaultLogger(out, closeOutputStreamOption); } else { final LocalizedMessage outputFormatExceptionMessage = new LocalizedMessage(0, Definitions.CHECKSTYLE_BUNDLE, CREATE_LISTENER_EXCEPTION, new String[] {format, PLAIN_FORMAT_NAME, XML_FORMAT_NAME}, null, Main.class, null); throw new IllegalStateException(outputFormatExceptionMessage.getMessage()); } return listener; }
Source:
private byte[] findBasesByMD5(final String md5) throws IOException { final String url = String.format(Defaults.EBI_REFERENCE_SERVICE_URL_MASK, md5); for (int i = 0; i < downloadTriesBeforeFailing; i++) { try (final InputStream is = new URL(url).openStream()) { if (is == null) return null; log.debug("Downloading reference sequence: " + url); final byte[] data = InputStreamUtils.readFully(is); log.debug("Downloaded " + data.length + " bytes for md5 " + md5); is.close(); final String downloadedMD5 = SequenceUtil.calculateMD5String(data); if (md5.equals(downloadedMD5)) { return data; } else { final String message = String .format("Downloaded sequence is corrupt: requested md5=%s, received md5=%s", md5, downloadedMD5); log.error(message); } } catch (final NoSuchAlgorithmException e) { throw new RuntimeException(e); } } throw new RuntimeException("Giving up on downloading sequence for md5 " + md5); }

Target:
private byte[] findBasesByMD5(final String md5) { final String url = String.format(Defaults.EBI_REFERENCE_SERVICE_URL_MASK, md5); for (int i = 0; i < downloadTriesBeforeFailing; i++) { try (final InputStream is = new URL(url).openStream()) { if (is == null) return null; log.info("Downloading reference sequence: " + url); final byte[] data = InputStreamUtils.readFully(is); log.info("Downloaded " + data.length + " bytes for md5 " + md5); final String downloadedMD5 = SequenceUtil.calculateMD5String(data); if (md5.equals(downloadedMD5)) { return data; } else { final String message = String .format("Downloaded sequence is corrupt: requested md5=%s, received md5=%s", md5, downloadedMD5); log.error(message); } } catch (final NoSuchAlgorithmException | IOException e) { throw new RuntimeException(e); } } throw new GaveUpException("Giving up on downloading sequence for md5 " + md5); }
Source:
protected void doExecute() { if (representationDescriptor != null) { representationDescriptor.setName(newName); representationDescriptor.setName(newName); } }

Target:
protected void doExecute() { if (representationDescriptor != null) { representationDescriptor.setName(newName); } }
Source:
public static String insertId(String message, ObjectId changeId) { if (message.indexOf("\nChange-Id:") > 0) return message; message = message.replaceAll("(.*\n)\n*([a-zA-Z0-9-]+:.*)$", "$1\nChange-Id: I" + ObjectId.toString(changeId) + "\n$2"); if (message.indexOf("\nChange-Id:") > 0) return message; return message + "\nChange-Id: I" + ObjectId.toString(changeId) + "\n"; }

Target:
public static String insertId(String message, ObjectId changeId) { if (message.indexOf("\nChange-Id:") > 0) return message; String[] lines = message.split("\n"); int lastPattern = -1; int firstPattern = -1; for (int i = lines.length - 1; i > 0; --i) { if (issuePattern.matcher(lines[i]).matches()) { firstPattern = i; lastPattern = i; continue; } if (footerPattern.matcher(lines[i]).matches()) { lastPattern = i; continue; } if (lines[i].trim().length() == 0) { lines[i] = ""; break; } lastPattern = lines.length; break; } if (lastPattern == -1) lastPattern = lines.length; if (firstPattern == -1) firstPattern = lastPattern - 1; if (firstPattern > lastPattern) firstPattern = lastPattern - 1; StringBuilder ret = new StringBuilder(); int i = 0; for (; i <= firstPattern; ++i) { if (lines[i].length() != 0 || i > 0 && lines[i-1].length() != 0) { ret.append(lines[i]); ret.append("\n"); } } if (i == lines.length && lastPattern == lines.length) ret.append("\n"); ret.append("Change-Id: I"); ret.append(ObjectId.toString(changeId)); ret.append("\n"); for (; i < lines.length; ++i) { ret.append(lines[i]); ret.append("\n"); } return ret.toString(); }