auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void partOpened(IWorkbenchPart part) { IDragAndDropService dndService = part.getSite() .getService(IDragAndDropService.class); if (dndService == null) { return; } if (part instanceof BndEditor) { part = ((BndEditor) part).getSourcePage(); } Control control = part.getAdapter(Control.class); if ((control == null) || !(control instanceof StyledText)) { return; } IPath file = null; if (part instanceof EditorPart) { EditorPart editorPart = (EditorPart) part; IEditorInput editorInput = editorPart.getEditorInput(); if (editorInput instanceof IFileEditorInput) { IFileEditorInput input = (IFileEditorInput) editorInput; file = input.getFile() .getFullPath(); } else if (editorInput instanceof IStorageEditorInput) { IStorageEditorInput input = (IStorageEditorInput) editorInput; try { file = input.getStorage() .getFullPath(); } catch (CoreException e) { throw Exceptions.duck(e); } } } if (file != null) { String fileName = file.lastSegment(); String fileExtension = file.getFileExtension(); if ("pom.xml".equals(fileName)) { dndService.addMergedDropTarget(control, DROP_COPY, transfers, new MavenDropTargetListener((StyledText) control)); } else if ("gradle".equalsIgnoreCase(fileExtension)) { dndService.addMergedDropTarget(control, DROP_COPY, transfers, new GradleDropTargetListener((StyledText) control)); } else if ("bnd".equalsIgnoreCase(fileExtension) || "bndrun".equalsIgnoreCase(fileExtension)) { dndService.addMergedDropTarget(control, DROP_COPY, transfers, new BndDropTargetListener((StyledText) control)); } } }

Target:
public void partOpened(IWorkbenchPart part) { IDragAndDropService dndService = part.getSite() .getService(IDragAndDropService.class); if (dndService == null) { return; } Control control = part.getAdapter(Control.class); if ((control == null) || !(control instanceof StyledText)) { return; } IPath file = null; if (part instanceof EditorPart) { EditorPart editorPart = (EditorPart) part; IEditorInput editorInput = editorPart.getEditorInput(); if (editorInput instanceof IFileEditorInput) { IFileEditorInput input = (IFileEditorInput) editorInput; file = input.getFile() .getFullPath(); } else if (editorInput instanceof IStorageEditorInput) { IStorageEditorInput input = (IStorageEditorInput) editorInput; try { file = input.getStorage() .getFullPath(); } catch (CoreException e) { throw Exceptions.duck(e); } } } if (file != null) { String fileName = file.lastSegment(); String fileExtension = file.getFileExtension(); if ("pom.xml".equals(fileName)) { dndService.addMergedDropTarget(control, DROP_COPY, transfers, new MavenDropTargetListener((StyledText) control)); } else if ("gradle".equalsIgnoreCase(fileExtension)) { dndService.addMergedDropTarget(control, DROP_COPY, transfers, new GradleDropTargetListener((StyledText) control)); } else if ("bnd".equalsIgnoreCase(fileExtension) || "bndrun".equalsIgnoreCase(fileExtension)) { dndService.addMergedDropTarget(control, DROP_COPY, transfers, new BndDropTargetListener((StyledText) control)); } } }
Source:
public CleanerThread() { this.setName("Reportal-Cleaner-Thread"); CLEAN_INTERVAL_MS = props.getInt("reportal.clean.interval.ms", 24 * 60 * 60 * 1000); OUTPUT_DIR_RETENTION_MS = props.getInt("reportal.output.dir.retention.ms", 7 * 24 * 60 * 60 * 1000); MAIL_TEMP_DIR_RETENTION_MS = props.getInt("reportal.mail.temp.dir.retention.ms", 1 * 24 * 60 * 60 * 1000); }

Target:
public CleanerThread() { this.setName("Reportal-Cleaner-Thread"); CLEAN_INTERVAL_MS = props.getLong("reportal.clean.interval.ms", DEFAULT_CLEAN_INTERVAL_MS); OUTPUT_DIR_RETENTION_MS = props.getLong("reportal.output.dir.retention.ms", DEFAULT_OUTPUT_DIR_RETENTION_MS); MAIL_TEMP_DIR_RETENTION_MS = props.getLong("reportal.mail.temp.dir.retention.ms", DEFAULT_MAIL_TEMP_DIR_RETENTION_MS); }
Source:
public static ClientSelector labelSelector(final String labelMask) { return new ClientSelector() { @Override public boolean select(Client client) { return client.getAttributes().values().iterator().next().matches(labelMask); } @Override public String toString() { return "ClientSelector{labelMask:" + labelMask + " }"; } }; }

Target:
public static ClientSelector labelSelector(final String labelMask) { return new ClientSelector() { @Override public boolean select(Client client) { Set<String> labels = client.getLabels(); for (String label : labels) { if (label.matches(labelMask)) { return true; } } return false; } @Override public String toString() { return "ClientSelector{labelMask:" + labelMask + " }"; } }; }
Source:
private void setNeedsMoreUsersIfAppropriate(final Page page, final Project project, final Session session) { boolean hasEnoughUsersGroups = project.getUsersWithPermission(Type.ADMIN).size() > 1 || project.getGroupsWithPermission(Type.ADMIN).size() > 0 || !hasPermission(session.getUser(), Type.ADMIN) || !this.forceMultipleUsers; page.add("hasEnoughUsersGroups", hasEnoughUsersGroups); }

Target:
private void setNeedsMoreUsersIfAppropriate(final Page page, final Project project, final Session session) { boolean hasEnoughUsersGroups = !this.forceMultipleUsers || project.getUsersWithPermission(Type.ADMIN).size() > 1 || project.getGroupsWithPermission(Type.ADMIN).size() > 0 || !hasPermission(session.getUser(), Type.ADMIN); page.add("hasEnoughUsersGroups", hasEnoughUsersGroups); }
Source:
private void broadcastUDPForCoapDeviceDiscover() { logger.debug(TAG + ": Broadcasting udp"); DatagramSocket mClientSock; try { mClientSock = new DatagramSocket(); InetAddress hostAddress = InetAddress.getByName("255.255.255.255"); logger.info(hostAddress.getHostAddress()); logger.info(hostAddress.getHostName()); logger.info(hostAddress.getCanonicalHostName()); logger.debug(hostAddress.getHostAddress()); logger.debug(hostAddress.getHostName()); logger.debug(hostAddress.getCanonicalHostName()); String mMsg = "mchp_coap"; DatagramPacket out = new DatagramPacket(mMsg.getBytes(), mMsg.length(), hostAddress, 65525); mClientSock.send(out); mClientSock.setSoTimeout(5000); while (true) { try { byte[] buf = new byte[1000]; DatagramPacket in = new DatagramPacket(buf, buf.length); mClientSock.receive(in); String payload = new String(in.getData()); logger.debug(TAG + ": Get reply from bcast from:" + in.getAddress().getHostAddress()); if (payload.substring(0, 9).equals("mchp_coap")) { discoverCoAP(in.getAddress()); } } catch (SocketTimeoutException e) { mClientSock.close(); break; } } } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }

Target:
private void broadcastUDPForCoapDeviceDiscover() { logger.debug(TAG + ": Broadcasting udp"); DatagramSocket mClientSock; try { mClientSock = new DatagramSocket(); InetAddress hostAddress = InetAddress.getByName("255.255.255.255"); logger.debug("address: {}, name: {}, canonicalName: {}", hostAddress.getHostAddress(), hostAddress.getHostName(), hostAddress.getCanonicalHostName()); DatagramPacket out = new DatagramPacket(serverIdentifier.getBytes(), serverIdentifier.length(), hostAddress, 65525); mClientSock.send(out); mClientSock.setSoTimeout(5000); while (true) { try { byte[] buf = new byte[1000]; DatagramPacket in = new DatagramPacket(buf, buf.length); mClientSock.receive(in); String payload = new String(in.getData()); logger.debug(TAG + ": Get reply from bcast from:" + in.getAddress().getHostAddress()); if (payload.substring(0, 9).equals(serverIdentifier)) { discoverCoAP(in.getAddress()); } } catch (SocketTimeoutException e) { mClientSock.close(); break; } } } catch (SocketException e) { logger.debug("UDP error on the socket", e); } catch (IOException e) { logger.debug("IO error on the socket", e); } }
Source:
public void endWindow() { if (windowId <= windowDataManager.getLargestCompletedWindow()) { return; } if (!partialWindowTuples.isEmpty() && windowId > windowDataManager.getLargestCompletedWindow()) { throw new RuntimeException("Violates Exactly once. Not all the tuples received after operator reset."); } getProducer().flush(); try { this.windowDataManager.save(getPartitionsAndOffsets(true), windowId); } catch (IOException | InterruptedException | ExecutionException e) { throw new RuntimeException(e); } }

Target:
public void endWindow() { if (windowId <= windowDataManager.getLargestCompletedWindow()) { return; } if (!partialWindowTuples.isEmpty()) { throw new RuntimeException("Violates Exactly once. Not all the tuples received after operator reset."); } getProducer().flush(); try { this.windowDataManager.save(getPartitionsAndOffsets(true), windowId); } catch (IOException | InterruptedException | ExecutionException e) { throw new RuntimeException(e); } }
Source:
public void testResolveTipSha1() throws IOException { ObjectId masterId = db.resolve("refs/heads/master"); Set<Ref> resolved = db.getRefDatabase().resolveTipSha1(masterId); assertEquals(resolved.size(), 2); checkContainsRef(resolved, db.exactRef("refs/heads/master")); checkContainsRef(resolved, db.exactRef("HEAD")); assertEquals(db.getRefDatabase() .resolveTipSha1(ObjectId.zeroId()).size(), 0); }

Target:
public void testResolveTipSha1() throws IOException { ObjectId masterId = db.resolve("refs/heads/master"); Set<Ref> resolved = db.getRefDatabase().resolveTipSha1(masterId); assertEquals(2, resolved.size()); checkContainsRef(resolved, db.exactRef("refs/heads/master")); checkContainsRef(resolved, db.exactRef("HEAD")); assertEquals(db.getRefDatabase() .resolveTipSha1(ObjectId.zeroId()).size(), 0); }
Source:
protected boolean set(Entity entity, Boolean value) { if (!entity.worldObj.isRemote) { if (value) { ((WorldServer) entity.worldObj).getEntityTracker().untrackEntity(entity); } else { ((WorldServer) entity.worldObj).getEntityTracker().trackEntity(entity); } ((WorldServer) entity.worldObj).getEntityTracker().updateTrackedEntities(); entity.setInvisible(value); return true; } else { return false; } }

Target:
protected boolean set(Entity entity, Boolean value) { if (!entity.worldObj.isRemote) { EntityTracker entityTracker = ((WorldServer) entity.worldObj).getEntityTracker(); if (value) { entityTracker.untrackEntity(entity); } else { if (!entityTracker.trackedEntityHashTable.containsItem(entity.getEntityId())) { entityTracker.trackEntity(entity); } } entityTracker.updateTrackedEntities(); entity.setInvisible(value); return true; } else { return false; } }
Source:
public boolean onScale(ScaleGestureDetector detector) { mScaleFactor *= detector.getScaleFactor(); mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f)); Iterator<Paint> iter = mTextStyle.iterator(); while (iter.hasNext()) { iter.next().setTextSize(DEFAULT_TEXT_SIZE * mScaleFactor); } invalidate(); return true; }

Target:
public boolean onScale(ScaleGestureDetector detector) { mScaleFactor *= detector.getScaleFactor(); mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f)); for (Paint p : mTextStyle) { p.setTextSize(DEFAULT_TEXT_SIZE * mScaleFactor); } invalidate(); return true; }
Source:
public void testListMultipartUploads() throws Exception { String uploadId = api.initiateMultipartUpload(VAULT_NAME1, 8); try { PaginatedMultipartUploadCollection uploads = api.listMultipartUploads(VAULT_NAME1); ImmutableList.Builder<String> list = ImmutableList.<String>builder(); for(MultipartUploadMetadata upload : uploads) { list.add(upload.getMultipartUploadId()); } assertTrue(list.build().contains(uploadId)); assertTrue(api.abortMultipartUpload(VAULT_NAME1, uploadId)); } finally { api.abortMultipartUpload(VAULT_NAME1, uploadId); } }

Target:
public void testListMultipartUploads() throws Exception { long partSizeInMb = 1; String uploadId = api.initiateMultipartUpload(VAULT_NAME1, partSizeInMb); try { assertNotNull(api.uploadPart(VAULT_NAME1, uploadId, ContentRange.fromPartNumber(0, partSizeInMb), buildPayload(partSizeInMb * MiB))); PaginatedMultipartUploadCollection uploads = api.listMultipartUploads(VAULT_NAME1); ImmutableList.Builder<String> list = ImmutableList.builder(); for (MultipartUploadMetadata upload : uploads) { list.add(upload.getMultipartUploadId()); } assertTrue(list.build().contains(uploadId)); assertTrue(api.abortMultipartUpload(VAULT_NAME1, uploadId)); } finally { api.abortMultipartUpload(VAULT_NAME1, uploadId); } }
Source:
private String endOfMonthManipulation(String value) { DateTime dateTime = new DateTime(value); return dateTime.dayOfMonth().withMaximumValue().toString(); }

Target:
private String endOfMonthManipulation(String value) { DateTime dateTime = new DateTime(value); return dateTime.dayOfMonth().withMaximumValue().withTime(23, 59, 59, 999).toString(); }
Source:
public ListenableFuture<PaymentIncrementAck> incrementPayment(Coin size, @Nullable ByteString info, @Nullable KeyParameter userKey) throws ValueOutOfRangeException, IllegalStateException { lock.lock(); try { if (state() == null || !connectionOpen || step != InitStep.CHANNEL_OPEN) throw new IllegalStateException("Channel is not fully initialized/has already been closed"); if (increasePaymentFuture != null) throw new IllegalStateException("Already incrementing paying, wait for previous payment to complete."); if (wallet.isEncrypted() && (userKey == null || userKey.getKey().length == 0) ) throw new IllegalArgumentException("Must supply a key parameter when the wallet is encrypted."); PaymentChannelClientState.IncrementedPayment payment = state().incrementPaymentBy(size, userKey); Protos.UpdatePayment.Builder updatePaymentBuilder = Protos.UpdatePayment.newBuilder() .setSignature(ByteString.copyFrom(payment.signature.encodeToBitcoin())) .setClientChangeValue(state.getValueRefunded().value); if (info != null) updatePaymentBuilder.setInfo(info); increasePaymentFuture = SettableFuture.create(); increasePaymentFuture.addListener(new Runnable() { @Override public void run() { lock.lock(); increasePaymentFuture = null; lock.unlock(); } }, MoreExecutors.sameThreadExecutor()); conn.sendToServer(Protos.TwoWayChannelMessage.newBuilder() .setUpdatePayment(updatePaymentBuilder) .setType(Protos.TwoWayChannelMessage.MessageType.UPDATE_PAYMENT) .build()); lastPaymentActualAmount = payment.amount; return increasePaymentFuture; } finally { lock.unlock(); } }

Target:
public ListenableFuture<PaymentIncrementAck> incrementPayment(Coin size, @Nullable ByteString info, @Nullable KeyParameter userKey) throws ValueOutOfRangeException, IllegalStateException, ECKey.KeyIsEncryptedException { lock.lock(); try { if (state() == null || !connectionOpen || step != InitStep.CHANNEL_OPEN) throw new IllegalStateException("Channel is not fully initialized/has already been closed"); if (increasePaymentFuture != null) throw new IllegalStateException("Already incrementing paying, wait for previous payment to complete."); if (wallet.isEncrypted() && userKey == null) throw new ECKey.KeyIsEncryptedException(); PaymentChannelClientState.IncrementedPayment payment = state().incrementPaymentBy(size, userKey); Protos.UpdatePayment.Builder updatePaymentBuilder = Protos.UpdatePayment.newBuilder() .setSignature(ByteString.copyFrom(payment.signature.encodeToBitcoin())) .setClientChangeValue(state.getValueRefunded().value); if (info != null) updatePaymentBuilder.setInfo(info); increasePaymentFuture = SettableFuture.create(); increasePaymentFuture.addListener(new Runnable() { @Override public void run() { lock.lock(); increasePaymentFuture = null; lock.unlock(); } }, MoreExecutors.sameThreadExecutor()); conn.sendToServer(Protos.TwoWayChannelMessage.newBuilder() .setUpdatePayment(updatePaymentBuilder) .setType(Protos.TwoWayChannelMessage.MessageType.UPDATE_PAYMENT) .build()); lastPaymentActualAmount = payment.amount; return increasePaymentFuture; } finally { lock.unlock(); } }
Source:
protected void onShowErrata() { logger.info(this.getClass().toString() + " onShowErrata"); if (getWindow() != null) { return; } this.setTitle("Errata for VM xxxx"); setWindow(this); initCommands(this); }

Target:
protected void onShowErrata() { if (getWindow() != null) { return; } VmErrataCountModel transferObj = new VmErrataCountModel(); transferObj.setTitle(messages.errataForVm(getName())); transferObj.setGuid(getGuid()); transferObj.setName(getName()); setWindow(transferObj); initCommands(transferObj); }
Source:
public String toString() { String data = ""; try { String.valueOf(atts.get("dn").get(0)); } catch (NamingException e) { } return data; }

Target:
public String toString() { try { return getDN(); } catch (NamingException e) { return ""; } }
Source:
public abstract void setSentDate(Date sentDate, boolean hideTimeZone) throws MessagingException; public abstract Address[] getRecipients(RecipientType type) throws MessagingException; public abstract Address[] getListPost(); public abstract void setRecipients(RecipientType type, Address[] addresses) throws MessagingException; public void setRecipient(RecipientType type, Address address) throws MessagingException { setRecipients(type, new Address[] { address }); }

Target:
public abstract void setSentDate(Date sentDate, boolean hideTimeZone) throws MessagingException; public abstract Address[] getRecipients(RecipientType type) throws MessagingException; public abstract void setRecipients(RecipientType type, Address[] addresses) throws MessagingException; public void setRecipient(RecipientType type, Address address) throws MessagingException { setRecipients(type, new Address[] { address }); }
Source:
protected void build(Controller controller) { Skin skin = controller.getApplicationAssets().getSkin(); I18N i18n = controller.getApplicationAssets().getI18N(); this.duration = new TextField(DEFAULT_DURATION, skin) { @Override public float getPrefWidth() { return IMAGE_WIDTH; } }; duration.setMaxLength(MAX_DURATION_LENGTH); duration.setRightAligned(true); IconButton dup = new IconButton("close", skin); dup.setTooltip(i18n.m("frames.duplicate")); IconButton delete = new IconButton("close", skin); dup.setTooltip(i18n.m("frames.delete")); top = new Table(); top.setVisible(false); top.add(dup).left(); top.add(delete).expandX().right(); getImage().setScaling(Scaling.fit); topCell = add(top).expandX().fillX().ignore(); row(); add(widget).height(IMAGE_HEIGHT).width(IMAGE_WIDTH); row(); add(duration); }

Target:
protected void build(Controller controller) { Skin skin = controller.getApplicationAssets().getSkin(); I18N i18n = controller.getApplicationAssets().getI18N(); this.duration = new TextField(DEFAULT_DURATION, skin) { @Override public float getPrefWidth() { return IMAGE_WIDTH; } }; duration.setMaxLength(MAX_DURATION_LENGTH); duration.setRightAligned(true); IconButton dup = new IconButton("close", skin); dup.setTooltip(i18n.m("frames.duplicate")); IconButton delete = new IconButton("close", skin); delete.setTooltip(i18n.m("frames.delete")); top = new Table(); top.setVisible(false); top.add(dup).left(); top.add(delete).expandX().right(); getImage().setScaling(Scaling.fit); topCell = add(top).expandX().fillX().ignore(); row(); add(widget).height(IMAGE_HEIGHT).width(IMAGE_WIDTH); row(); add(duration); }
Source:
private static boolean isLeafDirectory(DirectoryNode node) { Directory dir = node.getLookup().lookup(Directory.class); boolean ret = true; try { for (Content c : dir.getChildren()) { if (c instanceof Directory && (!((Directory) c).getName().equals(".") && !((Directory) c).getName().equals(".."))) { ret = false; break; } else if (0 < Case.getCurrentCase().getSleuthkitCase().getVisibleContentChildrenCount(c)) { ret = false; break; } } } catch (TskException ex) { Logger.getLogger(DirectoryTreeFilterChildren.class.getName()) .log(Level.WARNING, "Error getting directory children", ex); return false; } return ret; }

Target:
private static boolean isLeafDirectory(DirectoryNode node) { Directory dir = node.getLookup().lookup(Directory.class); boolean ret = true; try { for (Content c : dir.getChildren()) { if (c instanceof Directory && (!((Directory) c).getName().equals(".") && !((Directory) c).getName().equals(".."))) { ret = false; break; } else if(AbstractContentNode.contentHasVisibleContentChildren(c)){ ret = false; break; } } } catch (TskException ex) { Logger.getLogger(DirectoryTreeFilterChildren.class.getName()) .log(Level.WARNING, "Error getting directory children", ex); return false; } return ret; }
Source:
public void testCatalogMethodImpl() throws Throwable { try { testResult(checkNotNull(this.method.invoke(this.catalogType), "return value")); } catch (InvocationTargetException e) { if (e.getCause() != null) { throw e.getCause(); } throw e; } }

Target:
public void testCatalogMethodImpl() throws Throwable { if (!last.equals(this.catalogKey)) { last = this.catalogKey; testKeyAndName(this.catalogType); if (this.catalogType instanceof Translatable) { testTranslation((Translatable) this.catalogType); } } try { testResult(checkNotNull(this.method.invoke(this.catalogType), "return value")); } catch (InvocationTargetException e) { if (e.getCause() != null) { throw e.getCause(); } throw e; } }
Source:
public void testDropViewKeepsHTable() throws Exception { HBaseAdmin admin = driver.getConnectionQueryServices(getUrl(), TEST_PROPERTIES).getAdmin(); String hbaseNativeViewName = generateRandomString(); byte[] hbaseNativeBytes = SchemaUtil.getTableNameAsBytes(HBASE_NATIVE_SCHEMA_NAME, hbaseNativeViewName); try { try { admin.disableTable(hbaseNativeBytes); admin.deleteTable(hbaseNativeBytes); } catch (org.apache.hadoop.hbase.TableNotFoundException e) { } @SuppressWarnings("deprecation") HTableDescriptor descriptor = new HTableDescriptor(hbaseNativeBytes); HColumnDescriptor columnDescriptor = new HColumnDescriptor(FAMILY_NAME); columnDescriptor.setKeepDeletedCells(true); descriptor.addFamily(columnDescriptor); admin.createTable(descriptor); } finally { admin.close(); } Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); conn.createStatement().execute("create view " + hbaseNativeViewName+ " (uint_key unsigned_int not null," + " ulong_key unsigned_long not null," + " string_key varchar not null,\n" + " \"1\".uint_col unsigned_int," + " \"1\".ulong_col unsigned_long" + " CONSTRAINT pk PRIMARY KEY (uint_key, ulong_key, string_key))\n" + HColumnDescriptor.DATA_BLOCK_ENCODING + "='" + DataBlockEncoding.NONE + "'"); conn.createStatement().execute("drop view " + hbaseNativeViewName); admin = driver.getConnectionQueryServices(getUrl(), PropertiesUtil.deepCopy(TEST_PROPERTIES)).getAdmin(); try { try { admin.disableTable(hbaseNativeBytes); admin.deleteTable(hbaseNativeBytes); } catch (org.apache.hadoop.hbase.TableNotFoundException e) { fail(); } } finally { admin.close(); } }

Target:
public void testDropViewKeepsHTable() throws Exception { HBaseAdmin admin = driver.getConnectionQueryServices(getUrl(), TEST_PROPERTIES).getAdmin(); String hbaseNativeViewName = generateRandomString(); byte[] hbaseNativeBytes = SchemaUtil.getTableNameAsBytes(HBASE_NATIVE_SCHEMA_NAME, hbaseNativeViewName); try { @SuppressWarnings("deprecation") HTableDescriptor descriptor = new HTableDescriptor(hbaseNativeBytes); HColumnDescriptor columnDescriptor = new HColumnDescriptor(FAMILY_NAME); columnDescriptor.setKeepDeletedCells(true); descriptor.addFamily(columnDescriptor); admin.createTable(descriptor); } finally { admin.close(); } Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); conn.createStatement().execute("create view " + hbaseNativeViewName+ " (uint_key unsigned_int not null," + " ulong_key unsigned_long not null," + " string_key varchar not null,\n" + " \"1\".uint_col unsigned_int," + " \"1\".ulong_col unsigned_long" + " CONSTRAINT pk PRIMARY KEY (uint_key, ulong_key, string_key))\n" + HColumnDescriptor.DATA_BLOCK_ENCODING + "='" + DataBlockEncoding.NONE + "'"); conn.createStatement().execute("drop view " + hbaseNativeViewName); }
Source:
public void testFsActionNONE() throws Exception { Assume.assumeTrue(FS_AZURE_ENABLE_CHECK_ACCESS + " is false", isCheckAccessEnabled); Path testFilePath = setupTestDirectoryAndUserAccess("/test2.txt", FsAction.NONE); assertFalse(isAccessible(testFilePath, FsAction.EXECUTE)); assertFalse(isAccessible(testFilePath, FsAction.READ)); assertFalse(isAccessible(testFilePath, FsAction.WRITE)); assertFalse(isAccessible(testFilePath, FsAction.READ_EXECUTE)); assertFalse(isAccessible(testFilePath, FsAction.WRITE_EXECUTE)); assertFalse(isAccessible(testFilePath, FsAction.READ_WRITE)); assertFalse(isAccessible(testFilePath, FsAction.ALL)); }

Target:
public void testFsActionNONE() throws Exception { assumeHNSAndCheckAccessEnabled(); Path testFilePath = setupTestDirectoryAndUserAccess("/test2.txt", FsAction.NONE); assertInaccessible(testFilePath, FsAction.EXECUTE); assertInaccessible(testFilePath, FsAction.READ); assertInaccessible(testFilePath, FsAction.WRITE); assertInaccessible(testFilePath, FsAction.READ_EXECUTE); assertInaccessible(testFilePath, FsAction.WRITE_EXECUTE); assertInaccessible(testFilePath, FsAction.READ_WRITE); assertInaccessible(testFilePath, FsAction.ALL); }
Source:
private void createConfigGroup(final Composite parent) { final Group g = createGroup(parent, UIText.CloneDestinationPage_groupConfiguration); newLabel(g, UIText.CloneDestinationPage_promptRemoteName + ":"); remoteText = new Text(g, SWT.BORDER); remoteText.setText(Constants.DEFAULT_REMOTE_NAME); remoteText.setLayoutData(createFieldGridData()); remoteText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { checkPage(); } }); setRemoteWebAddr = new Button(g, SWT.CHECK); setRemoteWebAddr.setText("Remote Web Login Address"); GridDataFactory.swtDefaults().span(2, 1).applyTo(setRemoteWebAddr); setRemoteWebAddr.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { remoteText.setText(uri); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); }

Target:
private void createConfigGroup(final Composite parent) { final Group g = createGroup(parent, UIText.CloneDestinationPage_groupConfiguration); newLabel(g, UIText.CloneDestinationPage_promptRemoteName + ":"); remoteText = new Combo(g, SWT.NONE); remoteText.setLayoutData(createFieldGridData()); }
Source:
private static void prepareResponseBuilderForPartialRequestWithMultipleRanges(HttpServletResponse response) { response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY); response.setHeader(HttpHeaders.PRAGMA, "no-cache"); response.setStatus(PARTIAL_CONTENT.value()); }

Target:
private static void prepareResponseBuilderForPartialRequestWithMultipleRanges(HttpServletResponse response) { response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY); response.setStatus(PARTIAL_CONTENT.value()); }
Source:
private HealthDetailsFreeIpaResponse updateResponse(Stack stack, HealthDetailsFreeIpaResponse response) { response.setEnvironmentCrn(stack.getEnvironmentCrn()); response.setCrn(stack.getResourceCrn()); response.setName(stack.getName()); Set<String> notTermiatedStackInstanceIds = stack.getAllInstanceMetaDataList().stream() .filter(not(InstanceMetaData::isTerminated)) .map(InstanceMetaData::getInstanceId) .filter(Objects::nonNull) .collect(Collectors.toSet()); List<InstanceStatus> nonTerminatedStatuses = response.getNodeHealthDetails().stream() .filter(nodeHealthDetails -> notTermiatedStackInstanceIds.contains(nodeHealthDetails.getInstanceId())) .map(NodeHealthDetails::getStatus) .collect(Collectors.toList()); if (!nonTerminatedStatuses.isEmpty() && areAllStatusTheSame(nonTerminatedStatuses) && !hasMissingStatus(nonTerminatedStatuses, notTermiatedStackInstanceIds)) { response.setStatus(toStatus(nonTerminatedStatuses.get(0))); } else { response.setStatus(Status.UNHEALTHY); } updateResponseWithInstanceIds(response, stack); return response; }

Target:
private HealthDetailsFreeIpaResponse updateResponse(Stack stack, HealthDetailsFreeIpaResponse response) { response.setEnvironmentCrn(stack.getEnvironmentCrn()); response.setCrn(stack.getResourceCrn()); response.setName(stack.getName()); Set<String> notTermiatedStackInstanceIds = stack.getAllInstanceMetaDataList().stream() .filter(not(InstanceMetaData::isTerminated)) .map(InstanceMetaData::getInstanceId) .filter(Objects::nonNull) .collect(Collectors.toSet()); List<InstanceStatus> nonTerminatedStatuses = response.getNodeHealthDetails().stream() .filter(nodeHealthDetails -> notTermiatedStackInstanceIds.contains(nodeHealthDetails.getInstanceId())) .map(NodeHealthDetails::getStatus) .collect(Collectors.toList()); if (nonTerminatedStatuses.isEmpty()) { LOGGER.debug("FreeIPA is unhealthy because all instances are terminated"); response.setStatus(Status.UNHEALTHY); } else if (!areAllStatusTheSame(nonTerminatedStatuses)) { LOGGER.debug("There are different health statuses for FreeIPA so the the overall health is unhealthy"); response.setStatus(Status.UNHEALTHY); } else if (hasMissingStatus(nonTerminatedStatuses, notTermiatedStackInstanceIds)) { LOGGER.debug("There are missing health checks for some instances of FreeIPA so the overall health is unhealthy"); response.setStatus(Status.UNHEALTHY); } else { response.setStatus(toStatus(nonTerminatedStatuses.get(0))); } updateResponseWithInstanceIds(response, stack); return response; }
Source:
public H3IndexFilterOperator(Predicate predicate, IndexSegment indexSegment, int numDocs) { FunctionContext function = predicate.getLhs().getFunction(); String columnName; if (function.getArguments().get(0).getType() == ExpressionContext.Type.IDENTIFIER) { columnName = function.getArguments().get(0).getIdentifier(); byte[] bytes = BytesUtils.toBytes(function.getArguments().get(1).getLiteral()); _geometry = GeometrySerializer.deserialize(bytes); } else if (function.getArguments().get(1).getType() == ExpressionContext.Type.IDENTIFIER) { columnName = function.getArguments().get(1).getIdentifier(); byte[] bytes = BytesUtils.toBytes(function.getArguments().get(0).getLiteral()); _geometry = GeometrySerializer.deserialize(bytes); } else { throw new RuntimeException("Expecting one of the arguments of ST_DISTANCE to be an identifier"); } DataSource dataSource = indexSegment.getDataSource(columnName); _h3IndexReader = dataSource.getH3Index(); switch (predicate.getType()) { case EQ: break; case NOT_EQ: break; case IN: break; case NOT_IN: break; case RANGE: RangePredicate rangePredicate = (RangePredicate) predicate; _distance = Double.parseDouble(rangePredicate.getUpperBound()); break; case REGEXP_LIKE: break; case TEXT_MATCH: break; case IS_NULL: break; case IS_NOT_NULL: break; } _numDocs = numDocs; try { _h3Core = H3Core.newInstance(); } catch (IOException e) { throw new RuntimeException("Unable to instantiate H3", e); } }

Target:
public H3IndexFilterOperator(Predicate predicate, IndexSegment indexSegment, int numDocs) { _predicate = predicate; _segment = indexSegment; FunctionContext function = predicate.getLhs().getFunction(); String columnName; if (function.getArguments().get(0).getType() == ExpressionContext.Type.IDENTIFIER) { columnName = function.getArguments().get(0).getIdentifier(); byte[] bytes = BytesUtils.toBytes(function.getArguments().get(1).getLiteral()); _geometry = GeometrySerializer.deserialize(bytes); } else if (function.getArguments().get(1).getType() == ExpressionContext.Type.IDENTIFIER) { columnName = function.getArguments().get(1).getIdentifier(); byte[] bytes = BytesUtils.toBytes(function.getArguments().get(0).getLiteral()); _geometry = GeometrySerializer.deserialize(bytes); } else { throw new RuntimeException("Expecting one of the arguments of ST_DISTANCE to be an identifier"); } _dataSource = indexSegment.getDataSource(columnName); _h3IndexReader = _dataSource.getH3Index(); _resolution = _h3IndexReader.getH3IndexResolution(); switch (predicate.getType()) { case RANGE: RangePredicate rangePredicate = (RangePredicate) predicate; _distance = Double.parseDouble(rangePredicate.getUpperBound()); break; default: throw new RuntimeException(String.format("H3 index does not support predicate type %s", predicate.getType())); } _numDocs = numDocs; try { _h3Core = H3Core.newInstance(); } catch (IOException e) { throw new RuntimeException("Unable to instantiate H3 instance", e); } }
Source:
protected final Properties[] extractConsumerProducerProperties(Module module) { Properties consumerProperties = new Properties(); Properties producerProperties = new Properties(); String consumerKeyPrefix = "consumer."; String producerKeyPrefix = "producer."; String partitionPrefix = "partition."; if (module.getDeploymentProperties() != null) { for (Map.Entry<String, String> entry : module.getDeploymentProperties().entrySet()) { String key = entry.getKey(); if (key.startsWith(consumerKeyPrefix)) { consumerProperties.put(key.substring(consumerKeyPrefix.length()), entry.getValue()); } else if (key.startsWith(producerKeyPrefix)) { producerProperties.put(key.substring(producerKeyPrefix.length()), entry.getValue()); } else if (key.startsWith(partitionPrefix)) { consumerProperties.put(key, entry.getValue()); producerProperties.put(key, entry.getValue()); } } } return new Properties[] { consumerProperties, producerProperties }; }

Target:
protected final Properties[] extractConsumerProducerProperties(Module module) { Properties consumerProperties = new Properties(); Properties producerProperties = new Properties(); String consumerKeyPrefix = "consumer."; String producerKeyPrefix = "producer."; if (module.getDeploymentProperties() != null) { for (Map.Entry<String, String> entry : module.getDeploymentProperties().entrySet()) { if (entry.getKey().startsWith(consumerKeyPrefix)) { consumerProperties.put(entry.getKey().substring(consumerKeyPrefix.length()), entry.getValue()); } else if (entry.getKey().startsWith(producerKeyPrefix)) { producerProperties.put(entry.getKey().substring(producerKeyPrefix.length()), entry.getValue()); } } } return new Properties[] { consumerProperties, producerProperties }; }
Source:
public void setStatus(final TaskStatus status) { Preconditions.checkNotNull(status, "status"); log.info("Updating task %s to status: %s", status.getId(), status); int updated = dbi.withHandle( new HandleCallback<Integer>() { @Override public Integer withHandle(Handle handle) throws Exception { return handle.createStatement( String.format( "UPDATE %s SET active = :active, status_payload = :status_payload WHERE id = :id AND active = 1", dbConnectorConfig.getTaskTable() ) ) .bind("id", status.getId()) .bind("active", status.isRunnable() ? 1 : 0) .bind("status_payload", jsonMapper.writeValueAsString(status)) .execute(); } } ); if(updated != 1) { throw new IllegalStateException(String.format("Active task not found: %s", status.getId())); } }

Target:
public void setStatus(final TaskStatus status) { Preconditions.checkNotNull(status, "status"); log.info("Updating task %s to status: %s", status.getId(), status); int updated = dbi.withHandle( new HandleCallback<Integer>() { @Override public Integer withHandle(Handle handle) throws Exception { return handle.createStatement( String.format( "UPDATE %s SET active = :active, status_payload = :status_payload WHERE id = :id AND active = 1", dbConnectorConfig.getTaskTable() ) ) .bind("id", status.getId()) .bind("active", status.isRunnable() ? 1 : 0) .bind("status_payload", jsonMapper.writeValueAsBytes(status)) .execute(); } } ); if(updated != 1) { throw new IllegalStateException(String.format("Active task not found: %s", status.getId())); } }
Source:
private JsonNode evalValue(ObjectNode local, String code) throws TemplateException { Config scopedParams = params.deepCopy(); for (Map.Entry<String, JsonNode> pair : ImmutableList.copyOf(local.fields())) { scopedParams.set(pair.getKey(), pair.getValue()); } String resultText = null; if (requireInvokedTemplate(code)) { resultText = invokeTemplate(lazyGetTemplateInvocable(), code, scopedParams); } else { resultText = code; } if (resultText == null) { return jsonMapper.getNodeFactory().nullNode(); } else { return jsonMapper.getNodeFactory().textNode(resultText); } }

Target:
private JsonNode evalValue(ObjectNode local, String code) throws TemplateException { Config scopedParams = params.deepCopy(); for (Map.Entry<String, JsonNode> pair : ImmutableList.copyOf(local.fields())) { scopedParams.set(pair.getKey(), pair.getValue()); } String resultText = null; if (isInvokeTemplateRequired(code)) { resultText = invokeTemplate(lazyGetTemplateInvocable(), code, scopedParams); } else { resultText = code; } if (resultText == null) { return jsonMapper.getNodeFactory().nullNode(); } else { return jsonMapper.getNodeFactory().textNode(resultText); } }
Source:
public int compareTo(Object o) { AbstractMetadataInputSplit other = (AbstractMetadataInputSplit) o; long myLength = getTotalSize(); long otherLength = other.getTotalSize(); if (myLength < otherLength) { return -1; } else if (myLength == otherLength) { return 0; } else { return 1; } }

Target:
public int compareTo(Object o) { return Long.compare(getTotalBytes(), ((AbstractMetadataInputSplit) o).getTotalBytes()); }
Source:
public Set<NameKey> getWatchedProjects() { if (watchedProjects == null) { if (dbProvider == null) { throw new OutOfScopeException("Not in request scoped user"); } final Set<Project.NameKey> h = new HashSet<Project.NameKey>(); try { for (AccountProjectWatch projectWatch : dbProvider.get().accountProjectWatches().byAccount(getAccountId()).toList()) { h.add(projectWatch.getProjectNameKey()); } } catch (ProvisionException e) { log.warn("Cannot query project watches of a user", e); } catch (OrmException e) { log.warn("Cannot query project watches of a user", e); } watchedProjects = Collections.unmodifiableSet(h); } return watchedProjects; }

Target:
public Set<Project.NameKey> getWatchedProjects() { if (watchedProjects == null) { if (dbProvider == null) { throw new OutOfScopeException("Not in request scoped user"); } final Set<Project.NameKey> h = new HashSet<Project.NameKey>(); try { for (AccountProjectWatch projectWatch : dbProvider.get() .accountProjectWatches().byAccount(getAccountId())) { h.add(projectWatch.getProjectNameKey()); } } catch (OrmException e) { log.warn("Cannot query project watches of a user", e); } watchedProjects = Collections.unmodifiableSet(h); } return watchedProjects; }
Source:
public Encounter deserialize(final JsonElement src, final Type typeOfT, final JsonDeserializationContext context) { final JsonObject jsonEncounter = src.getAsJsonObject(); final JsonElement jsonProvider = jsonEncounter.get("provider"); Person provider; provider = (Person) JsonUtils.readJson(jsonProvider.toString(), Person.class); List<Person> encounterProviders = new ArrayList<>(); encounterProviders.add(provider); Encounter encounter; encounter = (Encounter) JsonUtils.readJson(src.toString(), Encounter.class); encounter.setEncounterProviders(encounterProviders); return encounter; }

Target:
public Encounter deserialize(final JsonElement src, final Type typeOfT, final JsonDeserializationContext context) { final JsonObject jsonEncounter = src.getAsJsonObject(); final JsonElement jsonProvider = jsonEncounter.get("provider"); Person provider = (Person) JsonUtils.readJson(jsonProvider.toString(), Person.class); Encounter encounter = (Encounter) JsonUtils.readJson(src.toString(), Encounter.class); encounter.setEncounterProviders(Collections.singletonList(provider)); return encounter; }
Source:
public Response deleteFields(@PathParam("typeId") final String typeId, final String[] fieldsID, @Context final HttpServletRequest req) throws DotDataException, DotSecurityException { final InitDataObject initData = this.webResource.init(null, false, req, false, null); final User user = initData.getUser(); Response response = null; try { final List<String> deletedIds = new ArrayList<>(); for (final String fieldId : fieldsID) { try { Field field = fieldAPI.find(fieldId); fieldAPI.delete(field, user); deletedIds.add(fieldId); } catch (NotFoundInDbException e) { continue; } } final List<Field> contentTypeFields = fieldAPI.byContentTypeId(typeId); response = Response.ok(new ResponseEntityView(imap("deletedIds", deletedIds, "fields", new JsonFieldTransformer(contentTypeFields).mapList()))).build(); }catch (Exception e) { response = ExceptionMapperUtil.createResponse(e, Response.Status.INTERNAL_SERVER_ERROR); } return response; }

Target:
public Response deleteFields(@PathParam("typeId") final String typeId, final String[] fieldsID, @Context final HttpServletRequest req) throws DotDataException, DotSecurityException { final InitDataObject initData = this.webResource.init(null, false, req, false, null); final User user = initData.getUser(); Response response = null; try { final List<String> deletedIds = new ArrayList<>(); for (final String fieldId : fieldsID) { try { final Field field = fieldAPI.find(fieldId); fieldAPI.delete(field, user); deletedIds.add(fieldId); } catch (NotFoundInDbException e) { continue; } } final List<Field> contentTypeFields = fieldAPI.byContentTypeId(typeId); response = Response.ok(new ResponseEntityView(imap("deletedIds", deletedIds, "fields", new JsonFieldTransformer(contentTypeFields).mapList()))).build(); }catch (Exception e) { response = ExceptionMapperUtil.createResponse(e, Response.Status.INTERNAL_SERVER_ERROR); } return response; }
Source:
public void tearDown() { CtfTmfTestTrace.KERNEL.dispose(); }

Target:
public void tearDown() { fTrace.dispose(); }
Source:
public static ByteBuffer serializeRecord( DataOutputSerializer serializer, IOReadableWritable record) throws IOException { serializer.clear(); serializer.skipBytesToWrite(4); record.write(serializer); int len = serializer.length() - 4; serializer.setPosition(0); serializer.writeInt(len); serializer.skipBytesToWrite(len); return serializer.wrapAsByteBuffer(); }

Target:
public static ByteBuffer serializeRecord( DataOutputSerializer serializer, IOReadableWritable record) throws IOException { serializer.setPositionUnsafe(4); record.write(serializer); serializer.writeIntUnsafe(serializer.length() - 4, 0); return serializer.wrapAsByteBuffer(); }
Source:
public Object [][] substructureToReadStructureData() { return new Object[][] { {new ReadStructure("10T10T").templates, "10T10T" }, {new ReadStructure("10T4M10T").templates, "10T10T" }, {new ReadStructure("10T8B10T").nonSkips, "10T8B10T"}, {new ReadStructure("10T8B5M10T").nonSkips, "10T8B5M10T"}, {new ReadStructure("8S10T8B8S10T").nonSkips, "10T8B10T"}, {new ReadStructure("10T8S8S10T").skips, "8S8S" }, {new ReadStructure("10T8S8S3M10T").skips, "8S8S" }, {new ReadStructure("10T8S8M10T").molecularBarcode, "8M" }, {new ReadStructure("8B").sampleBarcodes, "8B" } }; }

Target:
public Object [][] substructureToReadStructureData() { return new Object[][] { {new ReadStructure("10T10T"). templates, "10T10T" }, {new ReadStructure("10T4M10T").templates, "10T10T" }, {new ReadStructure("10T8B10T"). nonSkips, "10T8B10T" }, {new ReadStructure("10T8B5M10T"). nonSkips, "10T8B5M10T"}, {new ReadStructure("8S10T8B8S10T").nonSkips, "10T8B10T" }, {new ReadStructure("10T8S8S10T"). skips, "8S8S" }, {new ReadStructure("10T8S8S3M10T").skips, "8S8S" }, {new ReadStructure("8B").sampleBarcodes, "8B" }, {new ReadStructure("10T8S8M10T").molecularBarcode, "8M" } }; }
Source:
protected void markStartTime() { callbackTracker.markOperationStart(); }

Target:
void markStartTime() { callbackTracker.markOperationStart(); }
Source:
private Expression<?> createExpressionAndPotentionallyAddLeftJoinForReferencedAssociation(Order order, JPQLQuery query) { Assert.notNull(order, "Order must not be null!"); Assert.notNull(query, "JPQLQuery must not be null!"); if (!order.getProperty().contains(".")) { return order.isIgnoreCase() ? builder.getString(order.getProperty()).lower() : builder.get(order.getProperty()); } EntityType<?> entitytype = em.getMetamodel().entity(builder.getType()); Set<Attribute<?, ?>> combinedAttributes = new LinkedHashSet<Attribute<?, ?>>(); combinedAttributes.addAll(entitytype.getSingularAttributes()); combinedAttributes.addAll(entitytype.getPluralAttributes()); for (Attribute<?, ?> attribute : combinedAttributes) { String attributePrefix = attribute.getName() + "."; if (order.getProperty().startsWith(attributePrefix)) { EntityPathBase<?> associationPathRoot = new EntityPathBase<Object>(attribute.getJavaType(), attribute.getName()); query.leftJoin((EntityPath) builder.get(attribute.getName()), associationPathRoot); PathBuilder<Object> attributePathBuilder = new PathBuilder<Object>(attribute.getJavaType(), associationPathRoot.getMetadata()); String nestedAttributePath = order.getProperty().substring(attributePrefix.length()); return order.isIgnoreCase() ? attributePathBuilder.getString(nestedAttributePath).lower() : attributePathBuilder.get(nestedAttributePath); } } throw new IllegalArgumentException( String.format("Could not create property expression for %s", order.getProperty())); }

Target:
private Expression<?> createExpressionAndPotentionallyAddLeftJoinForReferencedAssociation(Order order, JPQLQuery query) { Assert.notNull(order, "Order must not be null!"); Assert.notNull(query, "JPQLQuery must not be null!"); if (!order.getProperty().contains(".")) { return order.isIgnoreCase() ? builder.getString(order.getProperty()).lower() : builder.get(order.getProperty()); } EntityType<?> entitytype = em.getMetamodel().entity(builder.getType()); Set<Attribute<?, ?>> combinedAttributes = new LinkedHashSet<Attribute<?, ?>>(); combinedAttributes.addAll(entitytype.getSingularAttributes()); combinedAttributes.addAll(entitytype.getPluralAttributes()); for (Attribute<?, ?> attribute : combinedAttributes) { if (order.getProperty().startsWith(attribute.getName() + ".")) { switch (attribute.getPersistentAttributeType()) { case EMBEDDED: return builder.get(order.getProperty()); default: return createLeftJoinForAttributeInOrderBy(attribute, order, query); } } } throw new IllegalArgumentException( String.format("Could not create property expression for %s", order.getProperty())); }
Source:
public void onChannelReadEvent(AbstractNioChannel channel, Object readObject, SelectionKey key) { if (channel.getHandler() != null) { channel.getHandler().handleChannelRead(channel, readObject, key); } }

Target:
public void onChannelReadEvent(AbstractNioChannel channel, Object readObject, SelectionKey key) { channel.getHandler().handleChannelRead(channel, readObject, key); }
Source:
public final void init(Map<String, Object> conf, SinkContext context) { String path = (String) conf.get(KEY_PATH); String portFile = (String) conf.get(KEY_PORT_FILE); cacheMaxSize = TypeUtils.getLong(conf.getOrDefault(KEY_METRICS_CACHE_MAX_SIZE, DEFAULT_MAX_CACHE_SIZE)); cacheTtlSeconds = TypeUtils.getLong(conf.getOrDefault(KEY_METRICS_CACHE_TTL_SEC, DEFAULT_CACHE_TTL_SECONDS)); topologyName = context.getTopologyName(); initialize(conf, context); int port = TypeUtils.getInteger(conf.getOrDefault(KEY_PORT, 0)); if (port == 0) { if (!Strings.isNullOrEmpty(portFile)) { try { port = TypeUtils.getInteger(Files.lines(Paths.get(portFile)).findFirst() .get().trim()); } catch (IOException | SecurityException | IllegalArgumentException e) { throw new IllegalArgumentException("Could not parse " + KEY_PORT_FILE + " " + portFile + " Make sure the file is readable," + " only contains the port on which the service should run" + " and is UTF8 encoded", e); } } else { throw new IllegalArgumentException("Neither 'port' nor 'port_file' " + "were specified in config for metrics sink " + context.getSinkId()); } } startHttpServer(path, port); }

Target:
public final void init(Map<String, Object> conf, SinkContext context) { String path = (String) conf.get(KEY_PATH); String portFile = (String) conf.get(KEY_PORT_FILE); cacheMaxSize = TypeUtils.getLong(conf.getOrDefault(KEY_METRICS_CACHE_MAX_SIZE, DEFAULT_MAX_CACHE_SIZE)); cacheTtlSeconds = TypeUtils.getLong(conf.getOrDefault(KEY_METRICS_CACHE_TTL_SEC, DEFAULT_CACHE_TTL_SECONDS)); topologyName = context.getTopologyName(); initialize(conf, context); int port = TypeUtils.getInteger(conf.getOrDefault(KEY_PORT, 0)); if (port == 0) { if (!Strings.isNullOrEmpty(portFile)) { try (Stream<String> lines = Files.lines(Paths.get(portFile))) { port = TypeUtils.getInteger(lines.findFirst().get().trim()); } catch (IOException | SecurityException | IllegalArgumentException e) { throw new IllegalArgumentException("Could not parse " + KEY_PORT_FILE + " " + portFile + " Make sure the file is readable," + " only contains the port on which the service should run" + " and is UTF8 encoded", e); } } else { throw new IllegalArgumentException("Neither 'port' nor 'port_file' " + "were specified in config for metrics sink " + context.getSinkId()); } } startHttpServer(path, port); }