auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Object lookup(ArquillianResource resource, Annotation... qualifiers) { URL url = (URL) super.doLookup(resource, qualifiers); if (url == null) { URL customURL; String grapheneCustomURL = grapheneConfiguration.get().getUrl(); if (grapheneCustomURL != null) { try { customURL = new URL(grapheneCustomURL); url = customURL; } catch (MalformedURLException ex) { throw new IllegalStateException("Configured custom URL from GrapheneConfiguration should be already a valid URL."); } } } return url; }

Target:
public Object lookup(ArquillianResource resource, Annotation... qualifiers) { URL url = null; if (hasDeployment(testClass.get())) { url = (URL) super.lookup(resource, qualifiers); } else { url = (URL) super.doLookup(resource, qualifiers); } if (url == null) { String grapheneCustomURL = grapheneConfiguration.get().getUrl(); if (grapheneCustomURL != null) { try { url = new URL(grapheneCustomURL); } catch (MalformedURLException ex) { throw new IllegalStateException("Configured custom URL from GrapheneConfiguration should be already a valid URL."); } } } return url; }
Source:
ZipFormatter( Formatters formatters, FormatterUtil formatterUtil, HtmlBuilder html) { this.formatters = formatters; this.util = formatterUtil; this.html = html; }

Target:
ZipFormatter( Formatters formatters, FormatterUtil formatterUtil, HtmlBuilder html) { this.util = formatterUtil; this.html = html; }
Source:
private StudentProfileAttributes getProfileAttributesFrom( String[] submissionParams) { StudentProfileAttributes spa = new StudentProfileAttributes(); if(submissionParams[1] != null){ spa.shortName = submissionParams[1].trim();; } if(submissionParams[3] != null){ spa.email = submissionParams[3].trim();; } if(submissionParams[5] != null){ spa.institute = submissionParams[5].trim();; } if(submissionParams[7] != null){ spa.nationality = submissionParams[7].trim();; } if(submissionParams[9] != null){ spa.gender = submissionParams[9].trim();; } if(submissionParams[11] != null){ spa.moreInfo = submissionParams[11].trim();; } spa.modifiedDate = null; return spa; }

Target:
private StudentProfileAttributes getProfileAttributesFrom( String[] submissionParams) { StudentProfileAttributes spa = new StudentProfileAttributes(); spa.shortName = StringHelper.trimIfNotNull(submissionParams[1]); spa.email = StringHelper.trimIfNotNull(submissionParams[3]); spa.institute = StringHelper.trimIfNotNull(submissionParams[5]); spa.nationality = StringHelper.trimIfNotNull(submissionParams[7]); spa.gender = StringHelper.trimIfNotNull(submissionParams[9]); spa.moreInfo = StringHelper.trimIfNotNull(submissionParams[11]); spa.modifiedDate = null; return spa; }
Source:
public XmlTextAnnotation next() { String data; try { data = LineIO.slurp(currentfile); } catch (FileNotFoundException e1) { System.err.println("The named entity file, \""+this.currentfile+"\", did not exist"); return null; } catch (Throwable e1) { e1.printStackTrace(); return null; } try { XmlTextAnnotation ta = nextAnnotation(data, currentfile); return ta; } catch (AnnotatorException e) { e.printStackTrace(); throw new IllegalStateException(e); } }

Target:
public XmlTextAnnotation next() { String data; try { data = LineIO.slurp(currentfile); } catch (FileNotFoundException e1) { this.badFiles.add(this.currentfile); return null; } catch (Throwable e1) { e1.printStackTrace(); return null; } try { XmlTextAnnotation ta = nextAnnotation(data, currentfile); return ta; } catch (AnnotatorException e) { e.printStackTrace(); throw new IllegalStateException(e); } }
Source:
private ResultSet bindAndExecute(Object[] columnValues, RegularStatement statement) { PreparedStatement preparedStatement; try { preparedStatement = preparedStatementCache.get( statement.getQueryString() ); session.prepare( statement ); } catch (ExecutionException e) { log.failToPrepareCQL( statement.getQueryString(), e.getCause() ); throw new RuntimeException( e.getCause() ); } try { BoundStatement boundStatement = new BoundStatement( preparedStatement ); for ( int i = 0; i < columnValues.length; i++ ) { boundStatement.setObject( i, columnValues[i] ); } return session.execute( boundStatement ); } catch (DriverException e) { log.failToExecuteCQL( statement.getQueryString(), e ); throw e; } }

Target:
private ResultSet bindAndExecute(Object[] columnValues, RegularStatement statement) { PreparedStatement preparedStatement; try { preparedStatement = preparedStatementCache.get( statement.getQueryString() ); session.prepare( statement ); } catch (ExecutionException e) { throw log.failToPrepareCQL( statement.getQueryString(), e.getCause() ); } try { BoundStatement boundStatement = new BoundStatement( preparedStatement ); for ( int i = 0; i < columnValues.length; i++ ) { boundStatement.setObject( i, columnValues[i] ); } return session.execute( boundStatement ); } catch (DriverException e) { throw log.failToExecuteCQL( statement.getQueryString(), e ); } }
Source:
public long commit() { if (currentStoreThread.compareAndSet(null, Thread.currentThread())) { synchronized (this) { try { currentStoreVersion = currentVersion; if (!closed && hasUnsavedChangesInternal()) { if (fileStore == null) { lastStoredVersion = currentVersion; ++currentVersion; setWriteVersion(currentVersion); metaChanged = false; } else { if (fileStore.isReadOnly()) { throw DataUtils.newIllegalStateException( DataUtils.ERROR_WRITING_FAILED, "This store is read-only"); } try { storeNow(); } catch (IllegalStateException e) { panic(e); } catch (Throwable e) { panic(DataUtils.newIllegalStateException(DataUtils.ERROR_INTERNAL, e.toString(), e)); } } } } finally { currentStoreVersion = -1; currentStoreThread.set(null); } } } return currentVersion; }

Target:
public synchronized long commit() { currentStoreThread.set(Thread.currentThread()); store(); return currentVersion; }
Source:
public void testBehaviorWhenReportedSizesSmall() throws Exception { File baseDir = Files.createTempDir(); try { FileSmoosher smoosher = new FileSmoosher(baseDir, 21); final SmooshedWriter writer = smoosher.addWithSmooshedWriter("1", 2); boolean exceptionThrown = false; try { writer.write(ByteBuffer.wrap(Ints.toByteArray(1))); } catch (ISE e) { Assert.assertTrue(e.getMessage().contains("Liar!!!")); exceptionThrown = true; } Assert.assertTrue(exceptionThrown); File[] files = baseDir.listFiles(); Assert.assertEquals(1, files.length); Assert.assertEquals(4, files[0].length()); } finally { for (File file : baseDir.listFiles()) { file.delete(); } } }

Target:
public void testBehaviorWhenReportedSizesSmall() throws Exception { File baseDir = folder.newFolder("base"); try (FileSmoosher smoosher = new FileSmoosher(baseDir, 21)) { boolean exceptionThrown = false; try (final SmooshedWriter writer = smoosher.addWithSmooshedWriter("1", 2)) { writer.write(ByteBuffer.wrap(Ints.toByteArray(1))); } catch (ISE e) { Assert.assertTrue(e.getMessage().contains("Liar!!!")); exceptionThrown = true; } Assert.assertTrue(exceptionThrown); File[] files = baseDir.listFiles(); Assert.assertNotNull(files); Assert.assertEquals(1, files.length); } }
Source:
private synchronized boolean createTable(DynamoDBMapper mapper, Class<?> dtoClass) { if (db == null) { return false; } String tableName; try { ProvisionedThroughput provisionedThroughput = new ProvisionedThroughput(dbConfig.getReadCapacityUnits(), dbConfig.getWriteCapacityUnits()); CreateTableRequest request = mapper.generateCreateTableRequest(dtoClass); request.setProvisionedThroughput(provisionedThroughput); if (request.getGlobalSecondaryIndexes() != null) { for (GlobalSecondaryIndex index : request.getGlobalSecondaryIndexes()) { index.setProvisionedThroughput(provisionedThroughput); } } tableName = request.getTableName(); try { db.getDynamoClient().describeTable(tableName); } catch (ResourceNotFoundException e) { db.getDynamoClient().createTable(request); } catch (AmazonClientException e) { logger.error("Exception when creation table (descibe): {}", e.getMessage()); return false; } return waitForTableToBecomeActive(tableName); } catch (AmazonClientException e) { logger.error("Exception when creation table: {}", e.getMessage()); return false; } }

Target:
private synchronized boolean createTable(DynamoDBMapper mapper, Class<?> dtoClass) { if (db == null) { return false; } String tableName; try { ProvisionedThroughput provisionedThroughput = new ProvisionedThroughput(dbConfig.getReadCapacityUnits(), dbConfig.getWriteCapacityUnits()); CreateTableRequest request = mapper.generateCreateTableRequest(dtoClass); request.setProvisionedThroughput(provisionedThroughput); if (request.getGlobalSecondaryIndexes() != null) { for (GlobalSecondaryIndex index : request.getGlobalSecondaryIndexes()) { index.setProvisionedThroughput(provisionedThroughput); } } tableName = request.getTableName(); try { db.getDynamoClient().describeTable(tableName); } catch (ResourceNotFoundException e) { db.getDynamoClient().createTable(request); } catch (AmazonClientException e) { logger.error("Table creation failed due to error in describeTable operation", e); return false; } return waitForTableToBecomeActive(tableName); } catch (AmazonClientException e) { logger.error("Exception when creating table", e); return false; } }
Source:
public FileDeferredDownloadBehavior(final IModel<File> fileModel, final IModel<String> fileNameModel, boolean addAntiCache) { this( new AbstractReadOnlyModel<LabelValue<String, File>>() { private static final long serialVersionUID = 1L; @Override public LabelValue<String, File> getObject() { return LabelValue.with(fileNameModel.getObject(), fileModel.getObject()); } }, addAntiCache ); Objects.requireNonNull(fileModel); Objects.requireNonNull(fileNameModel); }

Target:
public FileDeferredDownloadBehavior(final IModel<File> fileModel, final IModel<String> fileNameModel, boolean addAntiCache) { this( new AbstractReadOnlyModel<LabelValue<String, File>>() { private static final long serialVersionUID = 1L; @Override public LabelValue<String, File> getObject() { return LabelValue.with(fileNameModel.getObject(), fileModel.getObject()); } @Override public void detach() { super.detach(); Detachables.detach(fileModel, fileNameModel); } }, addAntiCache ); Objects.requireNonNull(fileModel); Objects.requireNonNull(fileNameModel); }
Source:
private void setConfigs(ASTNode node) throws SemanticException { Map<String, String> replConfigs = DDLSemanticAnalyzer.getProps(node); if (null != replConfigs) { for (Map.Entry<String, String> config : replConfigs.entrySet()) { String key = config.getKey(); if (key.equalsIgnoreCase(HIVEQUERYID.varname)) { String queryTag = config.getValue(); if (!StringUtils.isEmpty(queryTag)) { String jobTag = conf.get(MRJobConfig.JOB_TAGS); if (jobTag == null) { jobTag = queryTag; } else { jobTag = jobTag.concat("," + queryTag); } conf.set(MRJobConfig.JOB_TAGS, jobTag); } queryState.setQueryTag(queryTag); } else { conf.set(key, config.getValue()); } } try { db = Hive.get(conf); } catch (HiveException e) { throw new SemanticException(e); } } }

Target:
private void setConfigs(ASTNode node) throws SemanticException { Map<String, String> replConfigs = DDLSemanticAnalyzer.getProps(node); if (null != replConfigs) { for (Map.Entry<String, String> config : replConfigs.entrySet()) { String key = config.getKey(); if (key.equalsIgnoreCase(HIVEQUERYID.varname)) { String queryTag = config.getValue(); if (!StringUtils.isEmpty(queryTag)) { QueryState.setMapReduceJobTag(conf, queryTag); } queryState.setQueryTag(queryTag); } else { conf.set(key, config.getValue()); } } try { db = Hive.get(conf); } catch (HiveException e) { throw new SemanticException(e); } } }
Source:
private StorageConnections mapCollection(List<StorageServerConnections> entities) { StorageConnections collection = new StorageConnections(); for (org.ovirt.engine.core.common.businessentities.StorageServerConnections entity : entities) { Storage connection = map(entity); if (connection != null) { collection.getStorageConnections().add(addLinks(connection)); } } return collection; }

Target:
private StorageConnections mapCollection(List<StorageServerConnections> entities) { StorageConnections collection = new StorageConnections(); for (org.ovirt.engine.core.common.businessentities.StorageServerConnections entity : entities) { Storage connection = map(entity); if (connection != null) { collection.getStorageConnections().add(addLinks(populate(connection,entity))); } } return collection; }
Source:
public void setUp() { postgresDdlTable = new PostgresDdlTable(TEST_TABLE, connectionSupplier, ImmutablePostgresDdlConfig.builder().compactIntervalMillis(10).build()); }

Target:
public void setUp() { postgresDdlTable = new PostgresDdlTable(TEST_TABLE, connectionSupplier, ImmutablePostgresDdlConfig.builder() .compactInterval(HumanReadableDuration.milliseconds(COMPACT_INTERVAL_MILLIS)) .build()); }
Source:
protected JComboBox getPointUomCombo(){ CanvasSE prev = getPreview(); uoms= Uom.values(); String[] values = new String[uoms.length]; for (int i = 0; i < values.length; i++) { values[i] = I18N.tr(uoms[i].toString()); } final JComboBox jcc = new JComboBox(values); ActionListener acl = EventHandler.create(ActionListener.class, prev, "repaint"); ActionListener acl2 = EventHandler.create(ActionListener.class, this, "updateSUComboBox", "source.selectedIndex"); jcc.addActionListener(acl2); jcc.addActionListener(acl); jcc.setSelectedItem(((ConstantFormPoint)getLegend()).getSymbolUom().toString().toUpperCase()); return jcc; }

Target:
protected JComboBox getPointUomCombo(){ CanvasSE prev = getPreview(); uoms= getUomProperties(); String[] values = new String[uoms.length]; for (int i = 0; i < values.length; i++) { values[i] = I18N.tr(uoms[i].toString()); } final JComboBox jcc = new JComboBox(values); ActionListener acl = EventHandler.create(ActionListener.class, prev, "repaint"); ActionListener acl2 = EventHandler.create(ActionListener.class, this, "updateSUComboBox", "source.selectedIndex"); jcc.addActionListener(acl2); jcc.addActionListener(acl); jcc.setSelectedItem(((ConstantFormPoint)getLegend()).getSymbolUom().toString().toUpperCase()); return jcc; }
Source:
private void setup(Predicate<String> validation) { setPrefColumnCount(30); validationSupport.registerValidator(this, (c, newValue) -> { boolean isError = !validation.test(getText()); if (isError) { setStyleForInvalidFilter(); } else { setStyleForValidFilter(); } return ValidationResult.fromErrorIf(this, "Parse error", isError); }); setOnKeyTyped(e -> { boolean isModifierKeyPress = e.isAltDown() || e.isMetaDown() || e.isControlDown(); String key = e.getCharacter(); if (key == null || key.isEmpty() || isModifierKeyPress) { return; } char typed = key.charAt(0); if (typed == '\t' && suggestion.isShowing()) { suggestion.hide(); suggestion.getSelectedContent().ifPresent(this::completeWord); } else { suggestion.loadSuggestions(getMatchingKeywords(getCurrentWord())); suggestion.show(this, Side.BOTTOM, 0, 0); } }); setOnKeyPressed(e -> { if (e.getCode() == KeyCode.TAB) { e.consume(); } }); setOnKeyReleased(e -> { e.consume(); if (e.getCode() == KeyCode.ENTER) handleOnEnter(); if (e.getCode() == KeyCode.ESCAPE) handleOnEscape(); isNavigating = e.getCode() == KeyCode.UP || e.getCode() == KeyCode.DOWN; if (suggestion.isShowing() && !isNavigating) { suggestion.loadSuggestions(getMatchingKeywords(getCurrentWord())); } }); addEventHandler(KeyEvent.KEY_PRESSED, event -> { if (SHOW_DOCS.match(event)) { onShowDocs.run(); } }); }

Target:
private void setup(Predicate<String> validation) { setPrefColumnCount(30); validationSupport.registerValidator(this, (c, newValue) -> { boolean isError = !validation.test(getText()); if (isError) { setStyleForInvalidFilter(); } else { setStyleForValidFilter(); } return ValidationResult.fromErrorIf(this, "Parse error", isError); }); setOnKeyTyped(e -> { boolean isModifierKeyPress = e.isAltDown() || e.isMetaDown() || e.isControlDown(); String key = e.getCharacter(); if (key == null || key.isEmpty() || isModifierKeyPress) { return; } char typed = key.charAt(0); if (typed == '\t' && suggestions.isShowing()) { suggestions.hide(); suggestions.getSelectedContent().ifPresent(this::completeWord); } else { suggestions.loadSuggestions(getMatchingKeywords(getCurrentWord())); if (!suggestions.isShowing()) suggestions.show(this, Side.BOTTOM, 0, 0); } }); setOnKeyPressed(e -> { if (e.getCode() == KeyCode.TAB) { e.consume(); } }); setOnKeyReleased(e -> { e.consume(); if (e.getCode() == KeyCode.ENTER) { handleOnEnter(); } else if (e.getCode() == KeyCode.ESCAPE) { handleOnEscape(); } isNavigating = e.getCode() == KeyCode.UP || e.getCode() == KeyCode.DOWN; if (suggestions.isShowing() && !isNavigating) { suggestions.loadSuggestions(getMatchingKeywords(getCurrentWord())); } }); addEventHandler(KeyEvent.KEY_PRESSED, event -> { if (SHOW_DOCS.match(event)) { onShowDocs.run(); } }); }
Source:
public void testWhenProjectWithParamsThenRebuildProjectExecutesRebuildOfLastBuild() throws Exception { FreeStyleProject project = createFreeStyleProject(); project.scheduleBuild2(0, new Cause.UserIdCause(), new ParametersAction( new StringParameterValue("name", "test"))).get(); HtmlPage rebuildConfigPage = createWebClient().getPage(project, "1/rebuild"); submit(rebuildConfigPage.getFormByName("config")); HtmlPage projectPage = createWebClient().getPage(project); HtmlAnchor rebuildHref = projectPage.getAnchorByText("Rebuild Last"); WebAssert.assertLinkPresentWithText(projectPage, "Rebuild Last"); assertEquals("Rebuild Last should point to the second build", rebuildHref.getHrefAttribute(), "/" + project.getUrl() + "2/rebuild"); }

Target:
public void testWhenProjectWithParamsThenRebuildProjectExecutesRebuildOfLastBuild() throws Exception { FreeStyleProject project = createFreeStyleProject(); project.scheduleBuild2(0, new Cause.UserIdCause(), new ParametersAction( new StringParameterValue("name", "test"))).get(); HtmlPage rebuildConfigPage = createWebClient().getPage(project, "1/rebuild"); submit(rebuildConfigPage.getFormByName("config")); HtmlPage projectPage = createWebClient().getPage(project); WebAssert.assertLinkPresentWithText(projectPage, "Rebuild Last"); HtmlAnchor rebuildHref = projectPage.getAnchorByText("Rebuild Last"); assertEquals("Rebuild Last should point to the second build", rebuildHref.getHrefAttribute(), "/" + project.getUrl() + "2/rebuild"); }
Source:
public T get(int index) { if ((index < 0) || (index >= length())) { throw new IndexOutOfBoundsException("get(" + index + ")"); } else { final T[] leaf = trie.getLeaf(index); final int leafIndex = lastDigit(trie.offset() + index); return leaf[leafIndex]; } }

Target:
public T get(int index) { if ((index < 0) || (index >= length())) { throw new IndexOutOfBoundsException("get(" + index + ")"); } else { return trie.get(index); } }
Source:
public Date getBarcodeDate() { return getReceivedDate(); }

Target:
public Date getBarcodeDate() { return getReceivedDate() == null ? getCreationTime() : getReceivedDate(); }
Source:
public BroadcastEndpoint createBroadcastEndpoint() throws Exception { JGroupsBroadcastEndpoint endpoint = new JGroupsBroadcastEndpoint(JChannelManager.getInstance(), channelName) { @Override public JChannel createChannel() throws Exception { synchronized (JGroupsBroadcastEndpointFactory.class) { JChannel channel = (JChannel) channelFactory.createChannel(channelName); channels.put(channelName, channel); return channel; } } @Override protected synchronized void internalCloseChannel(JChannelWrapper channel) { synchronized (JGroupsBroadcastEndpointFactory.class) { channels.remove(channelName); super.internalCloseChannel(channel); } } }; return endpoint.initChannel(); }

Target:
public BroadcastEndpoint createBroadcastEndpoint() throws Exception { JGroupsBroadcastEndpoint endpoint = new JGroupsBroadcastEndpoint(JChannelManager.getInstance(), channelName) { @Override public JChannel createChannel() throws Exception { JChannel channel = (JChannel) channelFactory.createChannel(channelName); if (channels != null) { channels.put(channelName, channel); } return channel; } @Override protected void internalCloseChannel(JChannelWrapper channel) { if (channels != null) { channels.remove(channelName); } super.internalCloseChannel(channel); } }; return endpoint.initChannel(); }
Source:
public static RadioStation fromJson(String json) throws JSONException { JSONObject jsonStation = new JSONObject(json); RadioStation station = new RadioStation(); station.id = jsonStation.getLong(JSON_ID); station.name = jsonStation.getString(JSON_NAME); station.countryCode = jsonStation.getString(JSON_COUNTRY); station.stream = jsonStation.getString(JSON_STREAM); String bitRateString = jsonStation.getString(JSON_BITRATE); if (bitRateString != null && !bitRateString.isEmpty()) { try { station.bitrate = jsonStation.getLong(JSON_BITRATE); } catch (Throwable t) { } } return station; }

Target:
public static RadioStation fromJson(String json) throws JSONException { JSONObject jsonStation = new JSONObject(json); RadioStation station = new RadioStation(); station.id = jsonStation.getLong(JSON_ID); station.name = jsonStation.getString(JSON_NAME); station.countryCode = jsonStation.getString(JSON_COUNTRY); station.stream = jsonStation.getString(JSON_STREAM); String bitRateString = jsonStation.getString(JSON_BITRATE); if (bitRateString != null && !bitRateString.isEmpty()) { try { station.bitrate = jsonStation.getLong(JSON_BITRATE); } catch (JSONException e) { } } return station; }
Source:
public String toString() { if (isTheDefaultInstance()) { fbo = frameBuffersManager.getFBO(fboName); } return String.format("%21s: %s(%sx%s)", this.getClass().getSimpleName(), fboName, fbo.width(), fbo.height()); }

Target:
public String toString() { return String.format("%21s: %s", this.getClass().getSimpleName(), fboName); }
Source:
public BroadcastExchanger(List<Consumer<PageReference>> buffers, LocalExchangeMemoryManager memoryManager) { this.buffers = ImmutableList.copyOf(requireNonNull(buffers, "buffers is null")); this.memoryManager = requireNonNull(memoryManager, "v is null"); }

Target:
public BroadcastExchanger(List<Consumer<PageReference>> buffers, LocalExchangeMemoryManager memoryManager) { this.buffers = ImmutableList.copyOf(requireNonNull(buffers, "buffers is null")); this.memoryManager = requireNonNull(memoryManager, "memoryManager is null"); }
Source:
private void showNewDialog() { final AbstractDiskModel model = new NewDiskModel() { @Override public void onSave() { if (validate()) { flush(); getDiskModel().setEntity(this); parentModel.getParentListModel().setWindow(null); parentModel.getParentListModel().setWindow(parentModel.getUnitVmModel()); attachCommand.setIsAvailable(false); fillData(); if (getDisk().getDiskStorageType() == DiskStorageType.IMAGE) { ((DiskImage) getDisk()).setActive(true); } } } @Override protected void updateBootableDiskAvailable() { updateBootableFrom(parentModel.getAllCurrentDisks()); } }; VM vm = new VM(); vm.setVdsGroupId(parentModel.getUnitVmModel().getSelectedCluster().getId()); vm.setStoragePoolId(parentModel.getUnitVmModel().getSelectedDataCenter().getId()); vm.setVdsGroupCompatibilityVersion(parentModel.getUnitVmModel().getSelectedCluster().getCompatibilityVersion()); model.setVm(vm); setupModelAsDialog(model, ConstantsManager.getInstance().getConstants().newVirtualDiskTitle(), HelpTag.new_virtual_disk, "new_virtual_disk"); showDialog(model); model.initialize(parentModel.getAllCurrentDisks()); if (getVm() != null) { model.setVm(getVm()); ((NewDiskModel)model).updateSuggestedDiskAliasFromServer(); } else { String currentVmName = parentModel.getUnitVmModel().getName().getEntity(); if (!StringUtils.isEmpty(currentVmName)) { model.getAlias().setEntity(suggestAliasForNewVm(currentVmName)); } } }

Target:
private void showNewDialog() { final AbstractDiskModel model = new NewDiskModel() { @Override public void onSave() { if (validate()) { flush(); getDiskModel().setEntity(this); parentModel.getParentListModel().setWindow(null); parentModel.getParentListModel().setWindow(parentModel.getUnitVmModel()); attachCommand.setIsAvailable(false); fillData(); Disk disk = super.getDisk(); if (disk.getDiskStorageType() == DiskStorageType.IMAGE || disk.getDiskStorageType() == DiskStorageType.CINDER) { ((DiskImage) disk).setActive(true); } } } @Override protected void updateBootableDiskAvailable() { updateBootableFrom(parentModel.getAllCurrentDisks()); } }; VM vm = new VM(); vm.setVdsGroupId(parentModel.getUnitVmModel().getSelectedCluster().getId()); vm.setStoragePoolId(parentModel.getUnitVmModel().getSelectedDataCenter().getId()); vm.setVdsGroupCompatibilityVersion(parentModel.getUnitVmModel().getSelectedCluster().getCompatibilityVersion()); model.setVm(vm); setupModelAsDialog(model, ConstantsManager.getInstance().getConstants().newVirtualDiskTitle(), HelpTag.new_virtual_disk, "new_virtual_disk"); showDialog(model); model.initialize(parentModel.getAllCurrentDisks()); if (getVm() != null) { model.setVm(getVm()); ((NewDiskModel)model).updateSuggestedDiskAliasFromServer(); } else { String currentVmName = parentModel.getUnitVmModel().getName().getEntity(); if (!StringUtils.isEmpty(currentVmName)) { model.getAlias().setEntity(suggestAliasForNewVm(currentVmName)); } } }
Source:
public static float[] removeAllOccurences(final float[] array, final float element) { BitSet foundBits = indexesOf(array, element); return (float[]) removeAll((Object) array, foundBits); }

Target:
public static float[] removeAllOccurences(final float[] array, final float element) { return (float[]) removeAll((Object) array, indexesOf(array, element)); }
Source:
private void printSchema() { SchemaPrinter printer = new SchemaPrinter(); try { Files.write(Paths.get("/Users/danielsilva/Documents/schema.graphqls"), printer.print(schema).getBytes()); } catch (IOException e) { Logger.error(this, "Error printing schema", e); } }

Target:
private void printSchema() { if (Config.getBooleanProperty("PRINT_GRAPHQL_SCHEMA", false)) { SchemaPrinter printer = new SchemaPrinter(); try { File graphqlDirectory = new File(ConfigUtils.getGraphqlPath()); if(!graphqlDirectory.exists()) { graphqlDirectory.mkdirs(); } File schemaFile = new File(graphqlDirectory.getPath() + File.separator + "schema.graphqls"); schemaFile.createNewFile(); Files.write(schemaFile.toPath(), printer.print(schema).getBytes()); } catch (IOException e) { Logger.error(this, "Error printing schema", e); } } }
Source:
private static List<String> toStringList(final Object toCast) { if (toCast instanceof List) { return (List<String>) toCast; } return Collections.singletonList((String) toCast); }

Target:
private static List<String> toStringList(final Object toCast) { if (toCast instanceof List) { return (List<String>) toCast; } return new ArrayList<String>(Arrays.asList((String) toCast)); }
Source:
public void getCardsShouldReturnTheListOfCards() throws Exception { final AtomicReference<List<Card>> bodyRefResponse = new AtomicReference<>(); final AtomicReference<Request> bodyRefRequest = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); User user = Fixtures.loadUser(); BitreserveRestAdapter mockRestDapter = new BitreserveRestAdapter("foobar"); mockRestDapter.setAdapter(new RestAdapter.Builder().setEndpoint(GlobalConfigurations.SERVER_URL).setClient(new Client() { @Override public Response execute(Request request) throws IOException { String responseString = "[ { \"id\": \"FOO\" }, { \"id\": \"BAR\" } ]"; bodyRefRequest.set(request); return new Response("some/url", 200, "reason", new ArrayList<retrofit.client.Header>() { { add(new retrofit.client.Header("foo", "bar")); } }, new TypedByteArray("application/json", responseString.getBytes())); } }).build()); user.setBitreserveRestAdapter(mockRestDapter); user.getCards().then(new PromiseAction<List<Card>>() { @Override public void call(List<Card> cards) { bodyRefResponse.set(cards); latch.countDown(); } }).fail(new PromiseAction<Exception>() { @Override public void call(Exception e) { latch.countDown(); } }); latch.await(); List<Card> cardsResponse = bodyRefResponse.get(); Request request = bodyRefRequest.get(); Assert.assertEquals(request.getMethod(), "GET"); Assert.assertEquals(request.getUrl(), "<LINK_0>"); Assert.assertEquals(cardsResponse.size(), 2); Assert.assertEquals(cardsResponse.get(0).getId(), "FOO"); Assert.assertEquals(cardsResponse.get(1).getId(), "BAR"); }

Target:
public void getCardsShouldReturnTheListOfCards() throws Exception { final AtomicReference<List<Card>> bodyRefResponse = new AtomicReference<>(); final AtomicReference<Request> bodyRefRequest = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); User user = Fixtures.loadUser(); BitreserveRestAdapter mockRestAdapter = new BitreserveRestAdapter("foobar"); mockRestAdapter.setAdapter(new RestAdapter.Builder().setEndpoint(GlobalConfigurations.SERVER_URL).setClient(new Client() { @Override public Response execute(Request request) throws IOException { String responseString = "[ { \"id\": \"FOO\" }, { \"id\": \"BAR\" } ]"; bodyRefRequest.set(request); return new Response("some/url", 200, "reason", new ArrayList<retrofit.client.Header>(), new TypedByteArray("application/json", responseString.getBytes())); } }).build()); user.setBitreserveRestAdapter(mockRestAdapter); user.getCards().then(new PromiseAction<List<Card>>() { @Override public void call(List<Card> cards) { bodyRefResponse.set(cards); latch.countDown(); } }).fail(new PromiseAction<Exception>() { @Override public void call(Exception e) { latch.countDown(); } }); latch.await(); List<Card> cards = bodyRefResponse.get(); Request request = bodyRefRequest.get(); Assert.assertEquals(request.getMethod(), "GET"); Assert.assertEquals(request.getUrl(), "<LINK_0>"); Assert.assertEquals(cards.size(), 2); Assert.assertEquals(cards.get(0).getId(), "FOO"); Assert.assertEquals(cards.get(1).getId(), "BAR"); }
Source:
StoredRevision insertRevision(int projId, Revision revision) throws ResourceConflictException; void insertRevisionArchiveData(int revId, byte[] data) throws ResourceConflictException; StoredWorkflowDefinition insertWorkflowDefinition(int projId, int revId, WorkflowDefinition workflow, ZoneId workflowTimeZone) throws ResourceConflictException; interface ScheduleUpdateAction { public ScheduleTime apply(ScheduleStatus oldStatus, Schedule newSchedule); }

Target:
StoredRevision insertRevision(int projId, Revision revision) throws ResourceConflictException; void insertRevisionArchiveData(int revId, byte[] data) throws ResourceConflictException; StoredWorkflowDefinition insertWorkflowDefinition(int projId, int revId, WorkflowDefinition workflow, ZoneId workflowTimeZone) throws ResourceConflictException; interface ScheduleUpdateAction <T extends Schedule> { ScheduleTime apply(ScheduleStatus oldStatus, T newSchedule); }
Source:
public UnitVmModel flush() { UnitVmModel model = driver.flush(); model.getNicsWithLogicalNetworks().getItemsChangedEvent().removeListener(vnicsChangedListener); profilesInstanceTypeEditor.flush(); priorityEditor.flush(); return model; }

Target:
public UnitVmModel flush() { priorityEditor.flush(); profilesInstanceTypeEditor.flush(); return driver.flush(); }
Source:
public void onBarrierStateChanged(final String version, ZkBarrierForVersionUpgrade.State state) { LOG.info("JobModel version " + version + " obtained consensus successfully!"); metrics.barrierStateChange.inc(); if (ZkBarrierForVersionUpgrade.State.DONE.equals(state)) { metrics.singleBarrierRebalancingTime.update(System.nanoTime() - startTime); debounceTimer.scheduleAfterDebounceTime( barrierAction, 0, () -> onNewJobModelConfirmed(version)); } else { if (ZkBarrierForVersionUpgrade.State.TIMED_OUT.equals(state)) { LOG.info("Barrier for version " + version + " timed out."); } } }

Target:
public void onBarrierStateChanged(final String version, ZkBarrierForVersionUpgrade.State state) { LOG.info("JobModel version " + version + " obtained consensus successfully!"); metrics.barrierStateChange.inc(); metrics.singleBarrierRebalancingTime.update(System.nanoTime() - startTime); if (ZkBarrierForVersionUpgrade.State.DONE.equals(state)) { debounceTimer.scheduleAfterDebounceTime( barrierAction, 0, () -> onNewJobModelConfirmed(version)); } else { if (ZkBarrierForVersionUpgrade.State.TIMED_OUT.equals(state)) { LOG.info("Barrier for version " + version + " timed out."); } } }
Source:
public boolean advancePhase(float minWeight) { boolean changed = false; for (QueryTree child : children) { changed |= child.advancePhase(minWeight); } children.sort(Comparator.comparingDouble(QueryTree::weight)); return changed; }

Target:
public boolean advancePhase(float minWeight) { boolean changed = false; for (QueryTree child : children) { changed |= child.advancePhase(minWeight); } if (changed == false) { return false; } children.sort(Comparator.comparingDouble(QueryTree::weight)); return changed; }
Source:
public String getFirehoseId() { if (config != null) { return serviceName.replaceFirst(config.getFirehoseIdPrefix(), ""); } return null; }

Target:
public String getFirehoseId() { if (config != null) { return serviceName.replaceFirst(String.format("%s:", config.getFirehoseIdPrefix()), ""); } return null; }
Source:
public ListenableFuture<Map<Cell, byte[]>> getAsync(TableReference tableRef, Set<Cell> cells) { Timer.Context timer = getTimer("get").time(); checkGetPreconditions(tableRef); if (Iterables.isEmpty(cells)) { return Futures.immediateFuture(ImmutableMap.of()); } hasReads = true; ImmutableMap.Builder<Cell, byte[]> resultBuilder = ImmutableMap.builder(); SortedMap<Cell, byte[]> writes = writesByTable.get(tableRef); if (writes != null) { for (Cell cell : cells) { if (writes.containsKey(cell)) { resultBuilder.put(cell, writes.get(cell)); } } } Map<Cell, byte[]> writtenLocally = resultBuilder.build(); return Futures.transform( getFromKeyValueServiceAsync(tableRef, Sets.difference(cells, writtenLocally.keySet())), keyValueResult -> { ImmutableMap<Cell, byte[]> result = ImmutableMap.<Cell, byte[]>builder() .putAll(writtenLocally) .putAll(keyValueResult) .build(); long getMillis = TimeUnit.NANOSECONDS.toMillis(timer.stop()); if (perfLogger.isDebugEnabled()) { perfLogger.debug("get({}, cells) found cells (some possibly deleted), took ms", tableRef, cells.size(), result.size(), getMillis); } validatePreCommitRequirementsOnReadIfNecessary(tableRef, getStartTimestamp()); return removeEmptyColumns(result, tableRef); }, MoreExecutors.directExecutor()); }

Target:
public ListenableFuture<Map<Cell, byte[]>> getAsync(TableReference tableRef, Set<Cell> cells) { return getWithLoader("getAsync", tableRef, cells, keyValueService::getAsync); }
Source:
public void add(final T rec) { if (doneAdding) { throw new IllegalStateException("Cannot add after calling doneAdding()"); } if (iterationStarted) { throw new IllegalStateException("Cannot add after calling iterator()"); } if (numRecordsInRam == maxRecordsInRam) { long startMem = 0; if (sampleRecordSize) { Runtime.getRuntime().gc(); startMem = Runtime.getRuntime().freeMemory(); } spillToDisk(); if (sampleRecordSize) { Runtime.getRuntime().gc(); long endMem = Runtime.getRuntime().freeMemory(); long usedBytes = endMem - startMem; log.debug(String.format("%d records in ram required approximately %s memory or %s per record. ", maxRecordsInRam, StringUtil.humanReadableByteCount(usedBytes), StringUtil.humanReadableByteCount(usedBytes / maxRecordsInRam))); } } ramRecords[numRecordsInRam++] = rec; }

Target:
public void add(final T rec) { if (doneAdding) { throw new IllegalStateException("Cannot add after calling doneAdding()"); } if (iterationStarted) { throw new IllegalStateException("Cannot add after calling iterator()"); } if (numRecordsInRam == maxRecordsInRam) { long startMem = 0; if (printRecordSizeSampling) { Runtime.getRuntime().gc(); startMem = Runtime.getRuntime().freeMemory(); } spillToDisk(); if (printRecordSizeSampling) { Runtime.getRuntime().gc(); long endMem = Runtime.getRuntime().freeMemory(); long usedBytes = endMem - startMem; log.debug(String.format("%d records in ram required approximately %s memory or %s per record. ", maxRecordsInRam, StringUtil.humanReadableByteCount(usedBytes), StringUtil.humanReadableByteCount(usedBytes / maxRecordsInRam))); } } ramRecords[numRecordsInRam++] = rec; }
Source:
public void createTopic(String connectionString, int numberOfPartitions, Properties topicConfig) { Validate.notNull(connectionString, "destination should not be null"); Validate.notNull(topicConfig, "topicConfig should not be null"); KafkaDestination kafkaDestination = KafkaDestination.parse(connectionString); String topicName = kafkaDestination.getTopicName(); try { if (!AdminUtils.topicExists(_zkUtils, topicName)) { int replicationFactor = Integer.parseInt(topicConfig.getProperty("replicationFactor", DEFAULT_REPLICATION_FACTOR)); LOG.info( String.format("Creating topic with name %s partitions=%d with properties %s", topicName, numberOfPartitions, topicConfig)); if (!topicConfig.containsKey(TOPIC_RETENTION_MS)) { topicConfig.put(TOPIC_RETENTION_MS, String.valueOf(_retention.toMillis())); } AdminUtils.createTopic(_zkUtils, topicName, numberOfPartitions, replicationFactor, topicConfig, RackAwareMode.Disabled$.MODULE$); } else { LOG.warn(String.format("Topic with name %s already exists", topicName)); } } catch (Throwable e) { LOG.error(String.format("Creating topic %s failed with exception %s ", topicName, e)); throw e; } }

Target:
public void createTopic(String connectionString, int numberOfPartitions, Properties topicConfig) { Validate.notNull(connectionString, "destination should not be null"); Validate.notNull(topicConfig, "topicConfig should not be null"); KafkaDestination kafkaDestination = KafkaDestination.parse(connectionString); String topicName = kafkaDestination.getTopicName(); try { if (!AdminUtils.topicExists(_zkUtils, topicName)) { int replicationFactor = Integer.parseInt(topicConfig.getProperty("replicationFactor", DEFAULT_REPLICATION_FACTOR)); LOG.info("Creating topic with name partitions={} with properties %s", topicName, numberOfPartitions, topicConfig); if (!topicConfig.containsKey(TOPIC_RETENTION_MS)) { topicConfig.put(TOPIC_RETENTION_MS, String.valueOf(_retention.toMillis())); } AdminUtils.createTopic(_zkUtils, topicName, numberOfPartitions, replicationFactor, topicConfig, RackAwareMode.Disabled$.MODULE$); } else { LOG.warn("Topic with name already exists", topicName); } } catch (Throwable e) { LOG.error("Creating topic failed with exception {}", topicName, e); throw e; } }
Source:
public void testLoadDataObjects() { final WorkspaceProject project = mock(WorkspaceProject.class); final Path p1 = mock(Path.class); final String file1 = "file1.java"; when(p1.getFileName()).thenReturn(file1); final Path p2 = mock(Path.class); final String file2 = "file2.java"; when(p2.getFileName()).thenReturn(file2); final List<Path> files = Arrays.asList(p1, p2); when(pathsHelper.getDataObjectsPaths(project)).thenReturn(files); final List<DataObject> dataObjects = service.loadDataObjects(project); assertEquals(2, dataObjects.size()); assertEquals(file1, dataObjects.get(0).getClassType()); assertEquals(file2, dataObjects.get(1).getClassType()); }

Target:
public void testLoadDataObjects() { final WorkspaceProject project = mock(WorkspaceProject.class); final String file1 = "file1.java"; final String file2 = "file2.java"; final List<Path> files = Arrays.asList(getPath(file1), getPath(file2)); when(pathsHelper.getDataObjectsPaths(project)).thenReturn(files); final List<DataObject> dataObjects = service.loadDataObjects(project); assertEquals(2, dataObjects.size()); assertEquals(file1, dataObjects.get(0).getClassType()); assertEquals(file2, dataObjects.get(1).getClassType()); }
Source:
public static void setUp() throws Exception { SpannerOptions options = SpannerOptions.newBuilder().build(); spanner = options.getService(); dbClient = spanner.getDatabaseAdminClient(); dbId = DatabaseId.of(options.getProjectId(), instanceId, databaseId); deleteStaleTestDatabases(instanceId, System.getProperty("spanner.sample.database")); }

Target:
public static void setUp() throws Exception { SpannerOptions options = SpannerOptions.newBuilder().build(); spanner = options.getService(); dbClient = spanner.getDatabaseAdminClient(); dbId = DatabaseId.of(options.getProjectId(), instanceId, databaseId); deleteStaleTestDatabases(instanceId, baseDbId); }
Source:
private String getStatusMessage(Markers markers, Integer[] counts) { String status = MarkerSupportInternalUtilities.EMPTY_STRING; int totalCount = builder.getTotalMarkerCount(markers); int filteredCount = 0; boolean markerLimitsEnabled = generator.isMarkerLimitsEnabled(); int markerLimit = generator.getMarkerLimits(); MarkerSupportItem[] categories = markers.getCategories(); if (categories != null && builder.isShowingHierarchy()) { for (int i = 0; i < categories.length; i++) { int childCount = categories[i].getChildrenCount(); if (markerLimitsEnabled) childCount = Math.min(childCount, markerLimit); filteredCount += childCount; } } else { if(markerLimitsEnabled) filteredCount = markerLimit; else filteredCount = -1; } if (counts[0].intValue() == 0 && counts[1].intValue() == 0) { if (filteredCount < 0 || filteredCount >= totalCount) { status = NLS.bind(MarkerMessages.filter_itemsMessage, new Integer(totalCount)); } else { status = NLS.bind(MarkerMessages.filter_matchedMessage, new Integer(filteredCount), new Integer(totalCount)); } return status; } counts = new Integer[] { counts[0], counts[1], new Integer(counts[2].intValue() + counts[3].intValue()) }; if (filteredCount < 0 || filteredCount >= totalCount) return MessageFormat.format( MarkerMessages.errorsAndWarningsSummaryBreakdown, (Object[]) counts); return NLS .bind( MarkerMessages.problem_filter_matchedMessage, new Object[] { MessageFormat .format( MarkerMessages.errorsAndWarningsSummaryBreakdown, (Object[]) counts), new Integer(filteredCount), new Integer(totalCount) }); }

Target:
private String getStatusMessage(Markers markers, Integer[] counts) { String status = MarkerSupportInternalUtilities.EMPTY_STRING; int totalCount = builder.getTotalMarkerCount(markers); int filteredCount = 0; boolean markerLimitsEnabled = generator.isMarkerLimitsEnabled(); int markerLimit = generator.getMarkerLimits(); MarkerSupportItem[] categories = markers.getCategories(); if (categories != null && builder.isShowingHierarchy()) { for (int i = 0; i < categories.length; i++) { int childCount = categories[i].getChildrenCount(); if (markerLimitsEnabled) childCount = Math.min(childCount, markerLimit); filteredCount += childCount; } } else { if(markerLimitsEnabled) filteredCount = markerLimit; else filteredCount = -1; } if (counts[0].intValue() == 0 && counts[1].intValue() == 0) { if (filteredCount < 0 || filteredCount >= totalCount) { status = NLS.bind(MarkerMessages.filter_itemsMessage, new Integer(totalCount)); } else { status = NLS.bind(MarkerMessages.filter_matchedMessage, new Integer(filteredCount), new Integer(totalCount)); } return status; } counts = new Integer[] { counts[0], counts[1], new Integer(counts[2].intValue() + counts[3].intValue()) }; if (filteredCount < 0 || filteredCount >= totalCount) return MessageFormat.format( MarkerMessages.errorsAndWarningsSummaryBreakdown, counts[0], counts[1], counts[2] + counts[3]); return NLS .bind( MarkerMessages.problem_filter_matchedMessage, new Object[] { MessageFormat .format( MarkerMessages.errorsAndWarningsSummaryBreakdown, counts[0], counts[1], counts[2] + counts[3]), new Integer(filteredCount), new Integer(totalCount) }); }
Source:
public FactoryDto findFactory(String name) throws ApiException, IOException { String queryParamPrefix = "find?name=" + name; HttpJsonResponse request; try { request = requestFactory.fromUrl(factoryApiEndpoint + queryParamPrefix).request(); } catch (NotFoundException e) { return null; } List<FactoryDto> dtos = request.asList(FactoryDto.class); return dtos.isEmpty() ? null : dtos.get(0); }

Target:
public List<FactoryDto> findFactory(String name) throws ApiException, IOException { String queryParamPrefix = "find?name=" + name; HttpJsonResponse request; try { request = requestFactory.fromUrl(factoryApiEndpoint + queryParamPrefix).request(); } catch (NotFoundException e) { return emptyList(); } return request.asList(FactoryDto.class); }
Source:
public void createSetOfLocalizedEnumAttribute() throws Exception { executeTest(SetType.class, AttributeDefinitionBuilder .of("set-of-localized-enum-attribute", LABEL, new SetType(new LocalizedEnumType(LOCALIZED_ENUM_VALUES))) .searchable(false) .build(), attributeDefinitionFromServer -> { final SetType setType = (SetType) attributeDefinitionFromServer.getAttributeType(); final LocalizedEnumType elementType = (LocalizedEnumType) setType.getElementType(); assertThat(elementType.getValues()).isEqualTo(LOCALIZED_ENUM_VALUES); }); }

Target:
public void createSetOfLocalizedEnumAttribute() throws Exception { executeTest(SetType.class, AttributeDefinitionBuilder .of("set-of-localized-enum-attribute", LABEL, SetType.of(LocalizedEnumType.of(LOCALIZED_ENUM_VALUES))) .searchable(false) .build(), attributeDefinitionFromServer -> { final SetType setType = (SetType) attributeDefinitionFromServer.getAttributeType(); final LocalizedEnumType elementType = (LocalizedEnumType) setType.getElementType(); assertThat(elementType.getValues()).isEqualTo(LOCALIZED_ENUM_VALUES); }); }
Source:
private EmailPopulatingBuilder addFormat( final EmailPopulatingBuilder builder, final RenderedReport rendered ) throws IOException { final String mimeType = rendered.getFormat().getMimeType(); final InputStream content = rendered.getBytes(); if (mimeType.equals("text/html")) { return builder.withHTMLText(readString(content)); } return builder.withAttachment("report", readBytes(content), mimeType); }

Target:
private EmailPopulatingBuilder addFormat( final EmailPopulatingBuilder builder, final RenderedReport rendered ) throws IOException { final MediaType mimeType = rendered.getFormat().getMimeType(); final ByteSource content = rendered.getBytes(); if (mimeType.equals(MediaType.HTML_UTF_8)) { return builder.withHTMLText(content.asCharSource(StandardCharsets.UTF_8).read()); } return builder.withAttachment("report", content.read(), mimeType.toString()); }
Source:
String getPropertyKey() { String url = Jenkins.getActiveInstance().getRootUrl(); if (url!=null) return url; LOGGER.log(Level.WARNING, "The instance is not configured using a rootUrl, the key that represents your instance will not be stable"); if(randomId == null){ synchronized (this){ if(randomId == null){ randomId = Secret.fromString("key").getEncryptedValue(); } } } return randomId; }

Target:
String getPropertyKey() { Jenkins j = Jenkins.getActiveInstance(); String url = j.getRootUrl(); if (url!=null) return url; LOGGER.log(Level.WARNING, "The instance is not configured using a rootUrl, the key that represents your instance will not be stable"); return j.getLegacyInstanceId(); }
Source:
public static DimensionType getById(int dimensionId) { final Optional<DimensionType> optDimensionType = DimensionManager.getDimensionType(dimensionId); if (!optDimensionType.isPresent()) { throw new IllegalArgumentException("Invalid dimension id " + dimensionId); } return optDimensionType.get(); }

Target:
public static DimensionType getById(int dimensionId) { return DimensionManager.getDimensionType(dimensionId).orElseThrow(() -> new IllegalArgumentException("Invalid dimension id " + dimensionId)); }
Source:
public Response get() { HealthCheckRegistry checks = this.environment.healthChecks(); SortedMap<String, HealthCheck.Result> results = checks.runHealthChecks(); if (results.entrySet().stream().anyMatch(r -> !r.getValue().isHealthy())) { logger.warn("Health checks failed: {}", results); return Response.serverError().entity(results).build(); } return Response.ok(results).build(); }

Target:
public Response get() { HealthCheckRegistry checks = this.environment.healthChecks(); SortedMap<String, HealthCheck.Result> results = checks.runHealthChecks(); List<String> failing = results.entrySet().stream() .filter(r -> !r.getValue().isHealthy()) .map(Map.Entry::getKey) .collect(toList()); if (!failing.isEmpty()) { logger.warn("Health checks failed: {}", results); String message = "failing health checks: " + Arrays.toString(failing.toArray()); StatusResponse sr = new StatusResponse("critical", message, results); return Response.serverError().entity(sr).build(); } StatusResponse sr = new StatusResponse("ok", "ok", results); return Response.ok(sr).build(); }
Source:
public void close() { if (dataReader != null && dataReader.isRunning()) dataReader.stopReader(); connectionInterface.close(); logger.info("Connection interface closed."); }

Target:
public void close() { if (dataReader != null && dataReader.isRunning()) dataReader.stopReader(); connectionInterface.close(); logger.info(toString() + "Connection interface closed."); }