auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void closeAndCheckForSuspects() { if (!isLaunched()) { return; } List<File> suspectFiles = getDunitSuspectFiles(); if (suspectFiles.isEmpty()) { throw new IllegalStateException("No dunit suspect log files found in '" + getDunitSuspectsDir().getAbsolutePath() + "' - perhaps a rule that is cleaning up before suspect processing has already run."); } boolean ok = true; for (File suspect : suspectFiles) { ok &= checkSuspectFile(suspect); } if (!ok) { Assert.fail("Suspicious messages or exceptions were generated during this run.\n" + "Fix the problems or use IgnoredException.addIgnoredException to ignore."); } }

Target:
public static void closeAndCheckForSuspects() { if (!isLaunched()) { return; } List<File> suspectFiles = getDunitSuspectFiles(); if (suspectFiles.isEmpty()) { throw new IllegalStateException("No dunit suspect log files found in '" + getDunitSuspectsDir().getAbsolutePath() + "' - perhaps a rule that is cleaning up before suspect processing has already run."); } StringBuilder suspectStringCollector = new StringBuilder(); for (File suspect : suspectFiles) { checkSuspectFile(suspect, suspectStringCollector); } if (suspectStringCollector.length() != 0) { System.err.println("Suspicious strings were written to the log during this run.\n" + "Fix the strings or use IgnoredException.addIgnoredException to ignore.\n" + suspectStringCollector); Assert.fail("Suspicious strings were written to the log during this run.\n" + "Fix the strings or use IgnoredException.addIgnoredException to ignore.\n" + suspectStringCollector); } }
Source:
public void writeToChannel(WritableByteChannel channel, FileSmoosher smoosher) throws IOException { if (!requireMultipleFiles) { try (ReadableByteChannel from = Channels.newChannel(combineStreams().getInput())) { ByteStreams.copy(from, channel); return; } } if (smoosher == null) { throw new IAE("version 2 GenericIndexedWriter requires FileSmoosher."); } File f = ioPeon.getFile(makeFilename("headerLong")); Preconditions.checkNotNull(f, "header file missing."); int bagSizePower = bagSizePower(); OutputStream metaOut = Channels.newOutputStream(channel); metaOut.write(0x2); metaOut.write(objectsSorted ? 0x1 : 0x0); metaOut.write(Ints.toByteArray(bagSizePower)); metaOut.write(Ints.toByteArray(Ints.saturatedCast(numWritten))); metaOut.write(Ints.toByteArray(fileNameByteArray.length)); metaOut.write(fileNameByteArray); try (RandomAccessFile headerFile = new RandomAccessFile(f, "r")) { long previousValuePosition = 0; int bagSize = 1 << bagSizePower; int filesRequired = (int) Math.ceil((float) numWritten / bagSize); try (InputStream is = new FileInputStream(ioPeon.getFile(makeFilename("values")))) { int counter = -1; byte[] buffer = new byte[1 << 16]; for (int i = 0; i < filesRequired; i++) { if (i != filesRequired - 1) { headerFile.seek((bagSize + counter) * Longs.BYTES); counter = counter + bagSize; } else { headerFile.seek((numWritten - 1) * Longs.BYTES); } long valuePosition = headerFile.readLong(); long numBytesToPutInFile = valuePosition - previousValuePosition; try (SmooshedWriter smooshChannel = smoosher .addWithSmooshedWriter(generateValueFileName(filenameBase, i), numBytesToPutInFile)) { writeBytesIntoSmooshedChannel(numBytesToPutInFile, buffer, smooshChannel, is); previousValuePosition = valuePosition; } } } writeHeader(smoosher, headerFile, bagSizePower); } }

Target:
public void writeToChannel(WritableByteChannel channel, FileSmoosher smoosher) throws IOException { if (!requireMultipleFiles) { writeToChannelVersionOne(channel); } else { writeToChannelVersionTwo(channel, smoosher); } }
Source:
public CodecRegistry(ClassLoader cl) { codecs = new HashMap<String, Codec>(); Iterator<Codec> it = ServiceFinder.load(Codec.class).iterator(); for(;;) { try { Codec codec = it.next(); String name = codec.getName(); if (codecs.containsKey(name)) { log.duplicateCodec(codec.getClass().getName(), codecs.get(name).getClass().getName()); } else { codecs.put(name, codec); } } catch (ServiceConfigurationError e) { log.loadingCodecFailed(e); } catch (NoSuchElementException e) { break; } } }

Target:
public CodecRegistry(ClassLoader cl) { codecs = new HashMap<String, Codec>(); Iterator<Codec> it = ServiceFinder.load(Codec.class, cl).iterator(); for(;;) { try { Codec codec = it.next(); String name = codec.getName(); if (codecs.containsKey(name)) { log.duplicateCodec(codec.getClass().getName(), codecs.get(name).getClass().getName()); } else { codecs.put(name, codec); } } catch (ServiceConfigurationError e) { log.loadingCodecFailed(e); } catch (NoSuchElementException e) { break; } } }
Source:
public void rollback_DELETED_FILES() throws IOException { ContentFileTransactionContext context = new ContentFileTransactionContext(contentDir, deletedTmpDir); File file1 = new File(deletedTmpDir, "file1.txt"); File file2 = new File(deletedTmpDir, "file2.txt"); file1.createNewFile(); file2.createNewFile(); contentFileCommitRollbackService.rollback(context); assertTrue(new File(contentDir, "file1.txt").exists()); assertTrue(new File(contentDir, "file2.txt").exists()); assertFalse(file1.exists()); assertFalse(file2.exists()); assertFalse(deletedTmpDir.exists()); }

Target:
public void rollback_DELETED_FILES() throws IOException { ContentFileTransactionContext context = new ContentFileTransactionContext(contentDir, deletedTmpDir); File file1 = createFile(deletedTmpDir, "file1.txt", "content1"); File file2 = createFile(deletedTmpDir, "file2.txt", "content2"); contentFileCommitRollbackService.rollback(context); assertFile(new File(contentDir, "file1.txt"), "content1"); assertFile(new File(contentDir, "file2.txt"), "content2"); assertFalse(file1.exists()); assertFalse(file2.exists()); assertFalse(deletedTmpDir.exists()); }
Source:
protected void paint(Graphics g) { g.setColor(0x00FFFFFF); g.fillRect(0, 0, getWidth() - 1, getHeight() - 1); g.setColor(0x00FF0000); g.setStrokeStyle(Graphics.SOLID); g.drawString("Red top left", 0, 0, Graphics.TOP | Graphics.LEFT); System.out.println("PAINTED"); }

Target:
protected void paint(Graphics g) { g.setColor(0x00FFFFFF); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(0x00FF0000); g.setStrokeStyle(Graphics.SOLID); g.drawString("Red top left", 0, 0, Graphics.TOP | Graphics.LEFT); System.out.println("PAINTED"); }
Source:
public PagedFlux<PathItem> listPaths() { try { return this.listPaths(false, false, null); } catch (RuntimeException ex) { return pagedFluxError(logger, ex); } }

Target:
public PagedFlux<PathItem> listPaths() { return this.listPaths(false, false, null); }
Source:
public void handleModifyEvent(CatalogModifyEvent event) throws CatalogException { if (LOGGER.isLoggable(java.util.logging.Level.FINE)) { LOGGER.fine("Incoming message event of type " + event.getClass().getSimpleName() + " from Catalog"); } if (!isEnabled()) { if (LOGGER.isLoggable(java.util.logging.Level.FINE)) { LOGGER.fine("skipping incoming event: context is not initted"); } return; } Properties options = getProperties(); try { GeoServerResourceLoader loader = GeoServerExtensions.bean(GeoServerResourceLoader.class); final CatalogInfo info = event.getSource(); if (info instanceof StyleInfo) { final String canonicalStyleFileName = File.separator + "styles" + File.separator + ((StyleInfo) info).getFilename(); Resource styleFile = loader.get(canonicalStyleFileName); if ( !Resources.exists(styleFile) ) { final String workspace = ((StyleInfo) info).getWorkspace().getName(); final String styleFileName = File.separator + "workspaces" + File.separator + workspace + File.separator + "styles" + File.separator + ((StyleInfo) info).getFilename(); styleFile = loader.get(styleFileName); } jmsPublisher.publish(getTopic(), getJmsTemplate(), options, new DocumentFile( styleFile)); } jmsPublisher.publish(getTopic(), getJmsTemplate(), options, event); } catch (Exception e) { if (LOGGER.isLoggable(java.util.logging.Level.SEVERE)) { LOGGER.severe(e.getLocalizedMessage()); } final CatalogException ex = new CatalogException(e); throw ex; } }

Target:
public void handleModifyEvent(CatalogModifyEvent event) throws CatalogException { if (LOGGER.isLoggable(java.util.logging.Level.FINE)) { LOGGER.fine("Incoming message event of type " + event.getClass().getSimpleName() + " from Catalog"); } if (!isEnabled()) { if (LOGGER.isLoggable(java.util.logging.Level.FINE)) { LOGGER.fine("skipping incoming event: context is not initted"); } return; } Properties options = getProperties(); try { GeoServerResourceLoader loader = GeoServerExtensions.bean(GeoServerResourceLoader.class); final CatalogInfo info = event.getSource(); if (info instanceof StyleInfo) { Resource styleFile = loader.get("styles").get(((StyleInfo) info).getFilename()); if (!Resources.exists(styleFile)) { final String workspace = ((StyleInfo) info).getWorkspace().getName(); styleFile = loader.get(Paths.path("workspaces", workspace, "styles", ((StyleInfo) info).getFilename())); } jmsPublisher.publish(getTopic(), getJmsTemplate(), options, new DocumentFile(styleFile)); } jmsPublisher.publish(getTopic(), getJmsTemplate(), options, event); } catch (Exception e) { if (LOGGER.isLoggable(java.util.logging.Level.SEVERE)) { LOGGER.severe(e.getLocalizedMessage()); } final CatalogException ex = new CatalogException(e); throw ex; } }
Source:
public long getTimelineWaitTimeoutMs() { return 1000; }

Target:
public long getTimelineWaitTimeoutMs() { return timelineWaitTimeoutMs; }
Source:
public GlusterTasksListReturnForXmlRpc(Map<String, Object> innerMap) { super(innerMap); if (mStatus.mCode != 0) { return; } Map<String, Object> tasksMap = (Map<String, Object>) innerMap.get(TASKS_LIST); if (tasksMap != null) { Iterator<Entry<String, Object>> iter=tasksMap.entrySet().iterator(); while (iter.hasNext()) { Entry<String, Object> entry=iter.next(); tasks.add(getTask(entry.getKey(),(Map<String, Object>)entry.getValue())); } } }

Target:
public GlusterTasksListReturnForXmlRpc(Map<String, Object> innerMap) { super(innerMap); if (mStatus.mCode != 0) { return; } Map<String, Object> tasksMap = (Map<String, Object>) innerMap.get(TASKS_LIST); if (tasksMap != null) { for (Entry<String, Object> entry: tasksMap.entrySet()) { tasks.add(getTask(entry.getKey(),(Map<String, Object>)entry.getValue())); } } }
Source:
protected void executeCommand() { GlusterVolumeEntity volume = getGlusterVolume(); VDSReturnValue returnValue = runVdsCommand(VDSCommandType.CommitRemoveGlusterVolumeBricks, new GlusterVolumeRemoveBricksVDSParameters(getUpServer().getId(), volume.getName(), getParameters().getBricks())); setSucceeded(returnValue.getSucceeded()); if (!getSucceeded()) { handleVdsError(AuditLogType.GLUSTER_VOLUME_REMOVE_BRICKS_COMMIT_FAILED, returnValue.getVdsError() .getMessage()); return; } endStepJobCommitted(); releaseVolumeLock(); getDbUtils().removeBricksFromVolumeInDb(volume, getParameters().getBricks(), getParameters().getReplicaCount()); getReturnValue().setActionReturnValue(returnValue.getReturnValue()); }

Target:
protected void executeCommand() { GlusterVolumeEntity volume = getGlusterVolume(); VDSReturnValue returnValue = runVdsCommand(VDSCommandType.CommitRemoveGlusterVolumeBricks, new GlusterVolumeRemoveBricksVDSParameters(getUpServer().getId(), volume.getName(), getParameters().getBricks())); setSucceeded(returnValue.getSucceeded()); if (!getSucceeded()) { handleVdsError(AuditLogType.GLUSTER_VOLUME_REMOVE_BRICKS_COMMIT_FAILED, returnValue.getVdsError() .getMessage()); return; } endStepJobCommitted(); getDbUtils().removeBricksFromVolumeInDb(volume, getParameters().getBricks(), getParameters().getReplicaCount()); releaseVolumeLock(); getGlusterVolumeDao().updateVolumeTask(volume.getId(), null); getReturnValue().setActionReturnValue(returnValue.getReturnValue()); }
Source:
public void run() { super.run(); EObject target; DTable columnContainer; if (getColumn() != null) { target = getColumn().getTarget(); columnContainer = (DTable) getColumn().eContainer(); } else { target = table.getTarget(); columnContainer = table; } CompoundCommand compoundCommand = new CompoundCommand(getText()); Command cmd = tableCommandFactory.buildCreateColumnCommandFromTool(columnContainer, target, getCreateTool()); compoundCommand.append(cmd); getEditingDomain().getCommandStack().execute(compoundCommand); }

Target:
public void run() { super.run(); EObject target; DTable columnContainer; DTargetColumn dTargetColumn = getColumn(); if (dTargetColumn != null) { target = dTargetColumn.getTarget(); columnContainer = (DTable) dTargetColumn.eContainer(); } else { target = table.getTarget(); columnContainer = table; } Command cmd = tableCommandFactory.buildCreateColumnCommandFromTool(columnContainer, target, getCreateTool()); String label = getText(); cmd = new CommandWrapper(label, label, cmd); getEditingDomain().getCommandStack().execute(cmd); }
Source:
private Widget getRadioGroupPanel() { buttonToType = new LinkedHashMap<>(); RadioButton allButton = new RadioButton("diskContentTypeView"); buttonToType.put(allButton, null); allButton.setText(constants.allDisksLabel()); for (DiskContentType contentType : DiskContentType.values()) { RadioButton button = new RadioButton("diskContentTypeView"); buttonToType.put(button, contentType); } FlowPanel buttonsPanel = new FlowPanel(); buttonsPanel.getElement().getStyle().setProperty("marginLeft", "auto"); buttonsPanel.getElement().getStyle().setProperty("marginRight", "auto"); for (RadioButton button : buttonToType.keySet()) { button.getElement().getStyle().setMarginRight(20, Style.Unit.PX); buttonsPanel.add(button); } setDiskContentType(null); localize(); return buttonsPanel; }

Target:
private Widget getRadioGroupPanel() { buttonToType = new LinkedHashMap<>(); RadioButton allButton = new RadioButton(BUTTON_GROUP_NAME); buttonToType.put(allButton, null); allButton.setText(constants.allDisksLabel()); for (DiskContentType contentType : DiskContentType.values()) { RadioButton button = new RadioButton(BUTTON_GROUP_NAME); buttonToType.put(button, contentType); } ButtonGroup buttonGroup = new ButtonGroup(); buttonGroup.setDataToggle(Toggle.BUTTONS); buttonToType.entrySet().forEach(e -> { buttonGroup.add(e.getKey()); e.getKey().addClickHandler(event -> fireChangeHandlers(e.getValue())); }); setDiskContentType(null); localize(); buttonGroup.addStyleName("disk-type-buttons-group"); return buttonGroup; }
Source:
public boolean onDeleteAccount(PaymentAccount paymentAccount) { try { paymentAccountManager.removePaymentAccount(paymentAccount.getId()); return false; } catch(PaymentAccountInUseException e) { return true; } }

Target:
public boolean onDeleteAccount(PaymentAccount paymentAccount) { return paymentAccountManager.removePaymentAccount(paymentAccount); }
Source:
public void shutdownFramework() { Status driverStatus = driverManager.getDriverStatus(); if (Status.DRIVER_RUNNING != driverStatus) { LOGGER.warn("Driver is not running. Status: " + driverStatus); } else { driverStatus = driverManager.stopDriver(false); LOGGER.info("Myriad driver was shutdown with status " + driverStatus); } try { myriadWebServer.stop(); LOGGER.info("Myriad webserver was shutdown successfully"); } catch (Exception e) { LOGGER.info("Failed to shutdown Myriad webserver: " + e.getMessage()); } try { myriadStateStore.removeMyriadState(); LOGGER.info("Myriad State store was removed successfully."); } catch (Exception e) { LOGGER.info("Failed to remove Myriad state store: " + e.getMessage()); } }

Target:
public void shutdownFramework() { LOGGER.info("Received request to shutdown Myriad Framework.."); Status driverStatus = driverManager.getDriverStatus(); if (Status.DRIVER_RUNNING != driverStatus) { LOGGER.warn("Driver is not running. Status: " + driverStatus); } else { driverStatus = driverManager.stopDriver(false); LOGGER.info("Myriad driver was shutdown with status " + driverStatus); } try { myriadWebServer.stop(); LOGGER.info("Myriad webserver was shutdown successfully"); } catch (Exception e) { LOGGER.info("Failed to shutdown Myriad webserver: " + e.getMessage()); } try { myriadStateStore.removeMyriadState(); LOGGER.info("Myriad State store was removed successfully."); } catch (Exception e) { LOGGER.info("Failed to remove Myriad state store: " + e.getMessage()); } }
Source:
public static PublicKey loadPublicKey(String publicKey) throws GeneralSecurityException { Matcher matcher = PUBLIC_KEY_PATTERN.matcher(publicKey); if (!matcher.find()) { throw new KeyStoreException("found no public key"); } String data = matcher.group(1); byte[] encodedKey = base64Decode(data); X509EncodedKeySpec encodedKeySpec = new X509EncodedKeySpec(encodedKey); try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePublic(encodedKeySpec); } catch (InvalidKeySpecException ignore) { } try { KeyFactory keyFactory = KeyFactory.getInstance("EC"); return keyFactory.generatePublic(encodedKeySpec); } catch (InvalidKeySpecException ignore) { } KeyFactory keyFactory = KeyFactory.getInstance("DSA"); return keyFactory.generatePublic(encodedKeySpec); }

Target:
public static PublicKey loadPublicKey(String publicKey) throws GeneralSecurityException { Matcher matcher = PUBLIC_KEY_PATTERN.matcher(publicKey); if (!matcher.find()) { throw new KeyStoreException("did not find a public key"); } String data = matcher.group(1); byte[] encodedKey = base64Decode(data); X509EncodedKeySpec encodedKeySpec = new X509EncodedKeySpec(encodedKey); try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePublic(encodedKeySpec); } catch (InvalidKeySpecException ignore) { } try { KeyFactory keyFactory = KeyFactory.getInstance("EC"); return keyFactory.generatePublic(encodedKeySpec); } catch (InvalidKeySpecException ignore) { } KeyFactory keyFactory = KeyFactory.getInstance("DSA"); return keyFactory.generatePublic(encodedKeySpec); }
Source:
public void workingDirectoryDelete() throws Exception { deleteTrashFile(PATH); assertFalse(committedFile.exists()); RevCommit stashed = git.stashCreate().call(); assertNotNull(stashed); assertEquals("content", read(committedFile)); recorder.assertEvent(new String[] { PATH }, new String[0]); ObjectId unstashed = git.stashApply().call(); assertEquals(stashed, unstashed); assertFalse(committedFile.exists()); recorder.assertEvent(new String[0], new String[] { PATH }); Status status = git.status().call(); assertTrue(status.getAdded().isEmpty()); assertTrue(status.getChanged().isEmpty()); assertTrue(status.getConflicting().isEmpty()); assertTrue(status.getModified().isEmpty()); assertTrue(status.getUntracked().isEmpty()); assertTrue(status.getRemoved().isEmpty()); assertEquals(1, status.getMissing().size()); assertTrue(status.getMissing().contains(PATH)); }

Target:
public void workingDirectoryDelete() throws Exception { deleteTrashFile(PATH); assertFalse(committedFile.exists()); RevCommit stashed = git.stashCreate().call(); assertNotNull(stashed); assertEquals("content", read(committedFile)); recorder.assertEvent(new String[] { PATH }, ChangeRecorder.EMPTY); ObjectId unstashed = git.stashApply().call(); assertEquals(stashed, unstashed); assertFalse(committedFile.exists()); recorder.assertEvent(ChangeRecorder.EMPTY, new String[] { PATH }); Status status = git.status().call(); assertTrue(status.getAdded().isEmpty()); assertTrue(status.getChanged().isEmpty()); assertTrue(status.getConflicting().isEmpty()); assertTrue(status.getModified().isEmpty()); assertTrue(status.getUntracked().isEmpty()); assertTrue(status.getRemoved().isEmpty()); assertEquals(1, status.getMissing().size()); assertTrue(status.getMissing().contains(PATH)); }
Source:
public GenericUrl(String encodedUrl, boolean verbatim) { this(parseURL(encodedUrl), true); }

Target:
public GenericUrl(String encodedUrl, boolean verbatim) { this(parseURL(encodedUrl), verbatim); }
Source:
private void processInheritedPermissions(DocId docId, ActiveMarkingList activeMarkings, Permissions.Acl permissions, Response response) { String fragment = null; Iterator<?> iterator = (activeMarkings == null) ? Collections.emptyIterator() : activeMarkings.iterator(); while (iterator.hasNext()) { ActiveMarking activeMarking = (ActiveMarking) iterator.next(); Marking marking = activeMarking.get_Marking(); Permissions.Acl markingPerms = new Permissions(marking.get_Permissions()).getAcl(); Acl markingAcl = createAcl(docId, fragment, Acl.InheritanceType.AND_BOTH_PERMIT, markingPerms.getAllowUsers(), markingPerms.getDenyUsers(), markingPerms.getAllowGroups(), markingPerms.getDenyGroups()); fragment = SEC_MARKING_POSTFIX + percentEscape(marking.get_Id().toString()); logger.log(Level.FINEST, "Create ACL for active marking {0} {1}#{2}: {3}", new Object[] {activeMarking.get_PropertyDisplayName(), docId, fragment, markingAcl}); response.putNamedResource(fragment, markingAcl); } Acl folderAcl = createAcl(docId, permissions, PermissionSource.SOURCE_PARENT, fragment); fragment = SEC_FOLDER_POSTFIX; logger.log(Level.FINEST, "Create ACL for folder {0}#{1}: {2}", new Object[] {docId, fragment, folderAcl}); response.putNamedResource(fragment, folderAcl); Acl secAcl = createAcl(docId, permissions, PermissionSource.SOURCE_TEMPLATE, fragment); fragment = SEC_POLICY_POSTFIX; logger.log(Level.FINEST, "Create ACL for security template {0}#{1}: {2}", new Object[] {docId, fragment, secAcl}); response.putNamedResource(fragment, secAcl); }

Target:
private void processInheritedPermissions(DocId docId, ActiveMarkingList activeMarkings, Permissions.Acl permissions, Response response) { String fragment = null; Iterator<?> iterator = activeMarkings.iterator(); while (iterator.hasNext()) { ActiveMarking activeMarking = (ActiveMarking) iterator.next(); Marking marking = activeMarking.get_Marking(); Permissions.Acl markingPerms = new Permissions(marking.get_Permissions()).getAcl(); Acl markingAcl = createAcl(docId, fragment, Acl.InheritanceType.AND_BOTH_PERMIT, markingPerms.getAllowUsers(), markingPerms.getDenyUsers(), markingPerms.getAllowGroups(), markingPerms.getDenyGroups()); fragment = SEC_MARKING_POSTFIX + percentEscape(marking.get_Id().toString()); logger.log(Level.FINEST, "Create ACL for active marking {0} {1}#{2}: {3}", new Object[] {activeMarking.get_PropertyDisplayName(), docId, fragment, markingAcl}); response.putNamedResource(fragment, markingAcl); } Acl folderAcl = createAcl(docId, permissions, PermissionSource.SOURCE_PARENT, fragment); fragment = SEC_FOLDER_POSTFIX; logger.log(Level.FINEST, "Create ACL for folder {0}#{1}: {2}", new Object[] {docId, fragment, folderAcl}); response.putNamedResource(fragment, folderAcl); Acl secAcl = createAcl(docId, permissions, PermissionSource.SOURCE_TEMPLATE, fragment); fragment = SEC_POLICY_POSTFIX; logger.log(Level.FINEST, "Create ACL for security template {0}#{1}: {2}", new Object[] {docId, fragment, secAcl}); response.putNamedResource(fragment, secAcl); }
Source:
public PipelineConfig pipelineConfigNamed(final String name) { return getCurrentConfig().pipelineConfigByName(new CaseInsensitiveString(name)); }

Target:
public PipelineConfig pipelineConfigNamed(final String name) { return pipelineConfigNamed(new CaseInsensitiveString(name)); }
Source:
public org.neo4j.internal.kernel.api.Session beginSession( SecurityContext securityContext ) { return new KernelSession( engine, kernel, securityContext ); }

Target:
public KernelSession beginSession( SecurityContext securityContext ) { return new KernelSession( engine, kernel, securityContext ); }
Source:
public boolean isPositive() { return compareTo(ZERO) > 0; }

Target:
public boolean isPositive() { return signum() == 1; }
Source:
private void setLoginTimeout(final DataSource dataSource, final long connectionTimeout) { if (connectionTimeout != Integer.MAX_VALUE) { try { dataSource.setLoginTimeout((int) TimeUnit.MILLISECONDS.toSeconds(Math.max(1000L, connectionTimeout))); } catch (SQLException e) { LOGGER.warn("{} - Unable to set DataSource login timeout", poolName, e); } catch (UnsupportedOperationException e) { LOGGER.warn("{} - Unable to set DataSource login timeout", poolName, e); } } }

Target:
private void setLoginTimeout(final DataSource dataSource, final long connectionTimeout) { if (connectionTimeout != Integer.MAX_VALUE) { try { dataSource.setLoginTimeout((int) TimeUnit.MILLISECONDS.toSeconds(Math.max(1000L, connectionTimeout))); } catch (SQLException | UnsupportedOperationException e) { LOGGER.warn("{} - Unable to set DataSource login timeout", poolName, e); } } }
Source:
private TestRunner() { this.configs = new HashMap<>(); this.inMemoryScope = RandomStringUtils.random(10, true, true); configs.put(JobConfig.JOB_NAME(), JOB_NAME); configs.put(JobConfig.PROCESSOR_ID(), "1"); configs.put(JobCoordinatorConfig.JOB_COORDINATION_UTILS_FACTORY, PassthroughCoordinationUtilsFactory.class.getName()); configs.put(JobCoordinatorConfig.JOB_COORDINATOR_FACTORY, PassthroughJobCoordinatorFactory.class.getName()); configs.put(TaskConfig.GROUPER_FACTORY(), SingleContainerGrouperFactory.class.getName()); configs.put(JobConfig.JOB_DEFAULT_SYSTEM(), JOB_DEFAULT_SYSTEM); addConfig(ClusterManagerConfig.CLUSTER_MANAGER_HOST_AFFINITY_ENABLED, Boolean.FALSE.toString()); putIfAbsentConfig(new InMemorySystemDescriptor(JOB_DEFAULT_SYSTEM).toConfig()); }

Target:
private TestRunner() { this.configs = new HashMap<>(); this.inMemoryScope = RandomStringUtils.random(10, true, true); configs.put(JobConfig.JOB_NAME(), JOB_NAME); configs.put(JobConfig.PROCESSOR_ID(), "1"); configs.put(JobCoordinatorConfig.JOB_COORDINATION_UTILS_FACTORY, PassthroughCoordinationUtilsFactory.class.getName()); configs.put(JobCoordinatorConfig.JOB_COORDINATOR_FACTORY, PassthroughJobCoordinatorFactory.class.getName()); configs.put(TaskConfig.GROUPER_FACTORY(), SingleContainerGrouperFactory.class.getName()); addConfig(JobConfig.JOB_DEFAULT_SYSTEM(), JOB_DEFAULT_SYSTEM); addConfig(ClusterManagerConfig.CLUSTER_MANAGER_HOST_AFFINITY_ENABLED, Boolean.FALSE.toString()); addConfig(InMemorySystemConfig.INMEMORY_SCOPE, inMemoryScope); addConfig(new InMemorySystemDescriptor(JOB_DEFAULT_SYSTEM).withInMemoryScope(inMemoryScope).toConfig()); }
Source:
public void request(final long requested) { if (requested < 0) { throw new IllegalArgumentException("Requested items can not be negative."); } if (requested == 0) { return; } boolean requestToAlternate = false; synchronized (this) { if (null == altProducer) { long r = this.missedRequested; long u = r + requested; if (u < 0) { u = Long.MAX_VALUE; } this.missedRequested = u; } else { requestToAlternate = true; } } if (requestToAlternate) { altProducer.request(requested); } }

Target:
public void request(final long requested) { if (requested < 0) { throw new IllegalArgumentException("Requested items can not be negative."); } if (requested == 0) { return; } boolean requestToAlternate = false; Producer _altProducer; synchronized (this) { if (null == altProducer) { long r = this.missedRequested; long u = r + requested; if (u < 0) { u = Long.MAX_VALUE; } this.missedRequested = u; } else { requestToAlternate = true; } _altProducer = altProducer; } if (requestToAlternate) { _altProducer.request(requested); } }
Source:
public void visibleGroups(final AsyncCallback<List<AccountGroup>> callback) { run(callback, new Action<List<AccountGroup>>() { public List<AccountGroup> run(ReviewDb db) throws OrmException { final IdentifiedUser user = identifiedUser.get(); final List<AccountGroup> result; if (user.isAdministrator()) { result = db.accountGroups().all().toList(); } else { final HashSet<AccountGroup.Id> seen = new HashSet<AccountGroup.Id>(); result = new ArrayList<AccountGroup>(); for (final AccountGroup.Id myGroup : user.getEffectiveGroups()) { for (AccountGroup group : db.accountGroups().ownedByGroup(myGroup)) { final AccountGroup.Id id = group.getId(); if (!seen.add(id)) { continue; } try { GroupControl c = groupControlFactory.controlFor(id); if (c.isOwner()) { result.add(c.getAccountGroup()); } } catch (NoSuchGroupException e) { continue; } } } } for(final AccountGroup group : db.accountGroups().all().toList()) { if (group.isVisibleToAll() && !result.contains(group)) { result.add(group); } } Collections.sort(result, new Comparator<AccountGroup>() { public int compare(final AccountGroup a, final AccountGroup b) { return a.getName().compareTo(b.getName()); } }); return result; } }); }

Target:
public void visibleGroups(final AsyncCallback<List<AccountGroup>> callback) { run(callback, new Action<List<AccountGroup>>() { public List<AccountGroup> run(ReviewDb db) throws OrmException { final IdentifiedUser user = identifiedUser.get(); final List<AccountGroup> result; if (user.isAdministrator()) { result = db.accountGroups().all().toList(); } else { result = new ArrayList<AccountGroup>(); for(final AccountGroup group : db.accountGroups().all().toList()) { final GroupControl c = groupControlFactory.controlFor(group); if (c.isVisible()) { result.add(c.getAccountGroup()); } } } Collections.sort(result, new Comparator<AccountGroup>() { public int compare(final AccountGroup a, final AccountGroup b) { return a.getName().compareTo(b.getName()); } }); return result; } }); }
Source:
@Override public void processOutStream(int type, BinaryRawWriterEx writer) throws IgniteCheckedException { switch (type) { case OP_GET_IGNITE_CONFIGURATION: { PlatformConfigurationUtils.writeIgniteConfiguration(writer, ignite().configuration(), CURRENT_VER); return; } case OP_GET_CACHE_NAMES: { Collection<String> names = ignite().cacheNames(); writer.writeInt(names.size()); for (String name : names) writer.writeString(name); return; } case OP_GET_BASELINE_TOPOLOGY: { Collection<BaselineNode> blt = ignite().cluster().currentBaselineTopology(); writer.writeInt(blt.size()); for (BaselineNode n : blt) { writer.writeObjectDetached(n.consistentId()); PlatformUtils.writeNodeAttributes(writer, n.attributes()); } return; } case OP_NODE_VERSION: { IgniteProductVersion productVersion = ignite().cluster().node().version(); writer.writeByte(productVersion.major()); writer.writeByte(productVersion.minor()); writer.writeByte(productVersion.maintenance()); writer.writeLong(productVersion.revisionTimestamp()); writer.writeByteArray(productVersion.revisionHash()); return; } } PlatformAbstractTarget.throwUnsupported(type); }

Target:
@Override public void processOutStream(int type, BinaryRawWriterEx writer) throws IgniteCheckedException { switch (type) { case OP_GET_IGNITE_CONFIGURATION: { PlatformConfigurationUtils.writeIgniteConfiguration(writer, ignite().configuration(), CURRENT_VER); return; } case OP_GET_CACHE_NAMES: { Collection<String> names = ignite().cacheNames(); writer.writeInt(names.size()); for (String name : names) writer.writeString(name); return; } case OP_GET_BASELINE_TOPOLOGY: { Collection<BaselineNode> blt = ignite().cluster().currentBaselineTopology(); writer.writeInt(blt.size()); for (BaselineNode n : blt) { writer.writeObjectDetached(n.consistentId()); PlatformUtils.writeNodeAttributes(writer, n.attributes()); } return; } case OP_NODE_VERSION: { IgniteProductVersion productVersion = ignite().cluster().node().version(); PlatformUtils.writeNodeVersion(writer, productVersion); return; } } PlatformAbstractTarget.throwUnsupported(type); }
Source:
public Bitstream setLogo(Context context, Community community, MultipartFile uploadfile) throws IOException, AuthorizeException, SQLException { if (community.getLogo() != null) { throw new UnprocessableEntityException( "The community with the given uuid already has a logo: " + community.getID()); } Bitstream bitstream = cs.setLogo(context, community, uploadfile.getInputStream()); cs.update(context, community); bitstreamService.update(context, bitstream); return bitstream; }

Target:
public BitstreamRest setLogo(Context context, Community community, MultipartFile uploadfile) throws IOException, AuthorizeException, SQLException { if (community.getLogo() != null) { throw new UnprocessableEntityException( "The community with the given uuid already has a logo: " + community.getID()); } Bitstream bitstream = cs.setLogo(context, community, uploadfile.getInputStream()); cs.update(context, community); bitstreamService.update(context, bitstream); return bitstreamConverter.fromModel(context.reloadEntity(bitstream)); }
Source:
void validate() { try { stopAllExpired(); checkActivityRecordValidity(); } catch (ServerException e) { LOG.error(e.getLocalizedMessage(), e); } }

Target:
void validate() { try { stopAllExpired(); } catch (ServerException e) { LOG.error(e.getLocalizedMessage(), e); } try { checkActivityRecordValidity(); } catch (ServerException e) { LOG.error(e.getLocalizedMessage(), e); } }
Source:
public void writeTo(StreamOutput out) throws IOException { windowDefinition.writeTo(out); Symbols.toStream(standaloneWithInputs, out); out.writeVInt(windowFunctionContexts.size()); for (var windowFunctionContext : windowFunctionContexts) { Symbols.toStream(windowFunctionContext.function(), out); if (out.getVersion().onOrAfter(Version.V_4_1_0)) { Symbols.toStream(windowFunctionContext.filter(), out); } Symbols.toStream(windowFunctionContext.inputs(), out); } }

Target:
public void writeTo(StreamOutput out) throws IOException { windowDefinition.writeTo(out); Symbols.toStream(standaloneWithInputs, out); out.writeVInt(windowFunctionContexts.size()); boolean onOrAfter4_1_0 = out.getVersion().onOrAfter(Version.V_4_1_0); for (var windowFunctionContext : windowFunctionContexts) { Symbols.toStream(windowFunctionContext.function(), out); if (onOrAfter4_1_0) { Symbols.toStream(windowFunctionContext.filter(), out); } Symbols.toStream(windowFunctionContext.inputs(), out); } }
Source:
protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); boolean handled = mIabHelper.handleActivityResult(requestCode, resultCode, data); }

Target:
protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); mIabHelper.handleActivityResult(requestCode, resultCode, data); }
Source:
private String getPassFromFile(String passFile) throws IOException { FileReader input = new FileReader(passFile); BufferedReader br = new BufferedReader(input); return br.readLine(); }

Target:
private String getPassFromFile(String passFile) throws IOException { FileReader input = new FileReader(passFile); BufferedReader br = new BufferedReader(input); String pass = br.readLine(); try { input.close(); br.close(); } catch (Exception e) { } return pass; }
Source:
public String getAll(final User user, @RequestParam(value = "region", required = false) final String region, ModelMap model) { final Collection<? extends GrantedAuthority> authorities = getCurrentAuthorities(); List<AgentInfo> agents = agentManagerService.getAllVisible(); Collection<AgentInfo> filterAgentByCluster = Collections2.filter(agents, new Predicate<AgentInfo>() { @Override public boolean apply(AgentInfo agentInfo) { return filterAgentByCluster(region, agentInfo.getRegion()); } }); Collection<AgentInfo> filterAgentByUserAuthorityAndId = Collections2.filter(filterAgentByCluster, new Predicate<AgentInfo>() { @Override public boolean apply(AgentInfo agentInfo) { return filterAgentByUserAuthorityAndId(authorities, user.getUserId(), region, agentInfo.getRegion()); } }); model.addAttribute("agents", filterAgentByUserAuthorityAndId); model.addAttribute("region", region); model.addAttribute("regions", regionService.getAllVisibleRegionNames()); File agentPackage = null; if (isClustered()) { if (StringUtils.isNotBlank(region)) { final RegionInfo regionInfo = regionService.getOne(region); agentPackage = agentPackageService.createAgentPackage(region, regionInfo.getIp(), regionInfo.getControllerPort(), null); } } else { agentPackage = agentPackageService.createAgentPackage("", "", getConfig().getControllerPort(), null); } if (agentPackage != null) { model.addAttribute("downloadLink", "/agent/download/" + agentPackage.getName()); } return "agent/list"; }

Target:
public String getAll(final User user, @RequestParam(value = "region", required = false) final String region, ModelMap model) { final Collection<? extends GrantedAuthority> authorities = getCurrentAuthorities(); Collection<AgentInfo> agents = agentManagerService.getAllVisible(); agents = filter(agents, new Predicate<AgentInfo>() { @Override public boolean apply(AgentInfo agentInfo) { return filterAgentByCluster(region, agentInfo.getRegion()); } }); agents = filter(agents, new Predicate<AgentInfo>() { @Override public boolean apply(AgentInfo agentInfo) { return filterAgentByUserAuthorityAndId(authorities, user.getUserId(), region, agentInfo.getRegion()); } }); model.addAttribute("agents", agents); model.addAttribute("region", region); model.addAttribute("regions", regionService.getAllVisibleRegionNames()); File agentPackage = null; if (isClustered()) { if (StringUtils.isNotBlank(region)) { final RegionInfo regionInfo = regionService.getOne(region); agentPackage = agentPackageService.createAgentPackage(region, regionInfo.getIp(), regionInfo.getControllerPort(), null); } } else { agentPackage = agentPackageService.createAgentPackage("", "", getConfig().getControllerPort(), null); } if (agentPackage != null) { model.addAttribute("downloadLink", "/agent/download/" + agentPackage.getName()); } return "agent/list"; }
Source:
private int computeSizeOnDisk(Object stateValue, long nodeStart) { int minSize = HTVarInt.getEncodedLengthLong(fStart - nodeStart) + HTVarInt.getEncodedLengthLong(fDuration) + Integer.BYTES + Byte.BYTES; if (stateValue == null) { return minSize; } else if (stateValue instanceof Integer) { return (minSize + Integer.BYTES); } else if (stateValue instanceof Long) { return (minSize + Long.BYTES); } else if (stateValue instanceof Double) { return (minSize + Double.BYTES); } else if (stateValue instanceof CustomStateValue) { return (minSize + Short.BYTES + ((CustomStateValue) stateValue).getSerializedSize()); } String str = null; if (stateValue instanceof String) { str = (String) stateValue; } else { str = stateValue.toString(); } if (str == null) { throw new IllegalStateException(); } int strLength = str.getBytes(CHARSET).length; if (strLength > Short.MAX_VALUE) { throw new IllegalArgumentException("String is too long to be stored in state system: " + str); } return (minSize + strLength + 3); }

Target:
private int computeSizeOnDisk(Object stateValue, long nodeStart) { int minSize = HTVarInt.getEncodedLengthLong(fStart - nodeStart) + HTVarInt.getEncodedLengthLong(fDuration) + Integer.BYTES + Byte.BYTES; if (stateValue == null) { return minSize; } else if (stateValue instanceof Integer) { return (minSize + Integer.BYTES); } else if (stateValue instanceof Long) { return (minSize + Long.BYTES); } else if (stateValue instanceof Double) { return (minSize + Double.BYTES); } else if (stateValue instanceof CustomStateValue) { return (minSize + Short.BYTES + ((CustomStateValue) stateValue).getSerializedSize()); } String str = String.valueOf(stateValue); int strLength = str.getBytes(CHARSET).length; if (strLength > Short.MAX_VALUE) { throw new IllegalArgumentException("String is too long to be stored in state system: " + str); } return (minSize + strLength + 3); }
Source:
protected void createSwarmSlave(Candidate target) throws IOException, InterruptedException, RetryException { HttpClient client = createHttpClient(new URL(target.url)); String labelStr = StringUtils.join(options.labels, ' '); String toolLocationsStr = StringUtils.join(options.toolLocations, ' '); PostMethod post = new PostMethod(target.url + "/plugin/swarm/createSlave?name=" + options.name + "&executors=" + options.executors + param("remoteFsRoot", options.remoteFsRoot.getAbsolutePath()) + param("description", options.description) + param("labels", labelStr) + param("toolLocations", toolLocationsStr) + "&secret=" + target.secret + param("mode", options.mode.toUpperCase()) + param("hash", hash) ); post.setDoAuthentication(true); Crumb csrfCrumb = getCsrfCrumb(client, target); if (csrfCrumb != null) { post.addRequestHeader(csrfCrumb.crumbRequestField, csrfCrumb.crumb); } int responseCode = client.executeMethod(post); if (responseCode != 200) { throw new RetryException( "Failed to create a slave on Jenkins CODE: " + responseCode); } String name = post.getResponseBodyAsString(); if (name == null) { this.name = options.name; return; } name = name.trim(); if (name.isEmpty()) { return; } this.name = name; }

Target:
protected void createSwarmSlave(Candidate target) throws IOException, InterruptedException, RetryException { HttpClient client = createHttpClient(new URL(target.url)); String labelStr = StringUtils.join(options.labels, ' '); String toolLocationsStr = StringUtils.join(options.toolLocations, ' '); PostMethod post = new PostMethod(target.url + "/plugin/swarm/createSlave?name=" + options.name + "&executors=" + options.executors + param("remoteFsRoot", options.remoteFsRoot.getAbsolutePath()) + param("description", options.description) + param("labels", labelStr) + param("toolLocations", toolLocationsStr) + "&secret=" + target.secret + param("mode", options.mode.toUpperCase(Locale.ENGLISH)) + param("hash", hash) ); post.setDoAuthentication(true); Crumb csrfCrumb = getCsrfCrumb(client, target); if (csrfCrumb != null) { post.addRequestHeader(csrfCrumb.crumbRequestField, csrfCrumb.crumb); } int responseCode = client.executeMethod(post); if (responseCode != 200) { throw new RetryException(String.format("Failed to create a slave on Jenkins CODE: %s%n%s",responseCode, post.getResponseBodyAsString()) ); } Properties props = new Properties(); InputStream stream = post.getResponseBodyAsStream(); if (stream != null) { try { props.load(stream); } finally { stream.close(); } } String name = props.getProperty("name"); if (name == null) { this.name = options.name; return; } name = name.trim(); if (name.isEmpty()) { this.name = options.name; return; } this.name = name; }
Source:
private void newRowConsumer(TelemetryTask telemetryRow) { final TableWriter.Row row = writer.newRow(); row.putDate(0, telemetryRow.ts); row.putShort(1, telemetryRow.event); row.append(); }

Target:
private void newRowConsumer(TelemetryTask telemetryRow) { final TableWriter.Row row = writer.newRow(); row.putDate(0, telemetryRow.ts); row.putShort(1, telemetryRow.event); row.putShort(2, telemetryRow.origin); row.append(); }
Source:
public MarshalledEntry load(Object key) throws PersistenceException { V value = loadKey(key); if (value != null) { Duration expiry = Expiration.getExpiry(expiryPolicy, Expiration.Operation.CREATION); long now = ctx.getTimeService().wallClockTime(); if (expiry.isEternal()) { return ctx.getMarshalledEntryFactory().newMarshalledEntry(value, value, null); } else { long created = now; long exp = now + expiry.getTimeUnit().toMillis(expiry.getDurationAmount()); JCacheInternalMetadata meta = new JCacheInternalMetadata(created, exp); return ctx.getMarshalledEntryFactory().newMarshalledEntry(value, value, meta); } } return null; }

Target:
public MarshalledEntry load(Object key) throws PersistenceException { V value = loadKey(key); if (value != null) { Duration expiry = Expiration.getExpiry(expiryPolicy, Expiration.Operation.CREATION); long now = ctx.getTimeService().wallClockTime(); if (expiry == null || expiry.isEternal()) { return ctx.getMarshalledEntryFactory().newMarshalledEntry(value, value, null); } else { long exp = now + expiry.getTimeUnit().toMillis(expiry.getDurationAmount()); JCacheInternalMetadata meta = new JCacheInternalMetadata(now, exp); return ctx.getMarshalledEntryFactory().newMarshalledEntry(value, value, meta); } } return null; }
Source:
private void blockingCheckAndRethrow() { if (this.currentTask != null) { this.checkAndRethrow(); } }

Target:
private void blockingCheckAndRethrow() { if (this.currentTask != null) checkAndRethrow(); }
Source:
public void theSetActivityCalendarRequestIsReceived() throws Throwable { PROPERTIES_MAP.put(DEVICE_IDENTIFICATION_G_LABEL, this.deviceId.getDeviceIdG()); PROPERTIES_MAP.put(ORGANISATION_IDENTIFICATION_LABEL, this.organisationId.getOrganisationId()); this.RequestRunner(PROPERTIES_MAP, TEST_CASE_NAME_REQUEST, TEST_CASE_XML, TEST_SUITE_XML); }

Target:
public void theSetActivityCalendarRequestIsReceived() throws Throwable { PROPERTIES_MAP.put(DEVICE_IDENTIFICATION_E_LABEL, this.deviceId.getDeviceIdE()); PROPERTIES_MAP.put(ORGANISATION_IDENTIFICATION_LABEL, this.organisationId.getOrganisationId()); this.RequestRunner(PROPERTIES_MAP, TEST_CASE_NAME_REQUEST, TEST_CASE_XML, TEST_SUITE_XML); }
Source:
public void comparesIndexSettingsAndReturnsEquality() { Index index = new Index(fieldNames, indexName, IndexType.TEXT); Index index2 = new Index(fieldNames, indexName, IndexType.TEXT, new Tokenizer("simple")); assertThat(index.equals(index2), is(true)); }

Target:
public void comparesIndexSettingsAndReturnsEquality() { Index index = new Index(fieldNames, indexName, IndexType.TEXT); Index index2 = new Index(fieldNames, indexName, IndexType.TEXT, Tokenizer.DEFAULT); assertThat(index.equals(index2), is(true)); }
Source:
public Optional<SubjectReference> bridge$resolveReferenceOptional() { if (this.impl$subjectReference == null) { new SubjectSettingCallback(this).test(SpongeCommon.getGame().getServiceProvider().permissionService()); } return Optional.ofNullable(this.impl$subjectReference); }

Target:
public Optional<SubjectReference> bridge$resolveReferenceOptional() { if (this.impl$subjectReference == null) { SubjectHelper.applySubject(this); } return Optional.ofNullable(this.impl$subjectReference); }
Source:
public Pod deploy(Pod pod) throws InfrastructureException { putLabel(pod, CHE_WORKSPACE_ID_LABEL, workspaceId); ObjectMeta metadata = pod.getMetadata(); PodSpec podSpec = pod.getSpec(); podSpec.setRestartPolicy("Always"); Watch toCloseOnException = null; try { final CompletableFuture<Pod> createFuture = new CompletableFuture<>(); final Watch createWatch = clientFactory .create(workspaceId) .pods() .inNamespace(namespace) .watch(new CreateWatcher(createFuture, workspaceId)); toCloseOnException = createWatch; Deployment deployment = clientFactory .create(workspaceId) .extensions() .deployments() .inNamespace(namespace) .createNew() .withMetadata(metadata) .withNewSpec() .withReplicas(1) .withNewTemplate() .withMetadata(metadata) .withSpec(podSpec) .endTemplate() .endSpec() .done(); return createFuture.get(POD_CREATION_TIMEOUT_MIN, TimeUnit.MINUTES); } catch (KubernetesClientException e) { throw new KubernetesInfrastructureException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new InfrastructureException( "Interrupted while waiting for Pod creation. " + e.getMessage()); } catch (ExecutionException e) { throw new InfrastructureException( "Error occured while waiting for Pod creation. " + e.getMessage()); } catch (TimeoutException e) { throw new InfrastructureException("Pod creation timeout exceeded " + e.getMessage()); } finally { if (toCloseOnException != null) { toCloseOnException.close(); } } }

Target:
public Pod deploy(Pod pod) throws InfrastructureException { putLabel(pod, CHE_WORKSPACE_ID_LABEL, workspaceId); ObjectMeta metadata = pod.getMetadata(); String originalName = metadata.getName(); putLabel(pod, CHE_DEPLOYMENT_NAME_LABEL, originalName); PodSpec podSpec = pod.getSpec(); podSpec.setRestartPolicy("Always"); final CompletableFuture<Pod> createFuture = new CompletableFuture<>(); final Watch createWatch = clientFactory .create(workspaceId) .pods() .inNamespace(namespace) .watch(new CreateWatcher(createFuture, workspaceId, originalName)); try { clientFactory .create(workspaceId) .extensions() .deployments() .inNamespace(namespace) .createNew() .withMetadata(metadata) .withNewSpec() .withReplicas(1) .withNewTemplate() .withMetadata(metadata) .withSpec(podSpec) .endTemplate() .endSpec() .done(); return createFuture.get(POD_CREATION_TIMEOUT_MIN, TimeUnit.MINUTES); } catch (KubernetesClientException e) { throw new KubernetesInfrastructureException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new InfrastructureException( String.format( "Interrupted while waiting for Pod creation. -id: %s -message: %s", metadata.getName(), e.getMessage())); } catch (ExecutionException e) { throw new InfrastructureException( String.format( "Error occured while waiting for Pod creation. -id: %s -message: %s", metadata.getName(), e.getCause().getMessage())); } catch (TimeoutException e) { throw new InfrastructureException( String.format( "Pod creation timeout exceeded. -id: %s -message: %s", metadata.getName(), e.getMessage())); } finally { createWatch.close(); } }