auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void clipForOverlappingReads(final SAMRecord read1, final SAMRecord read2) { if (!(read1.getReadUnmappedFlag() || read2.getReadUnmappedFlag())) { if (read1.getReadNegativeStrandFlag() != read2.getReadNegativeStrandFlag()) { final SAMRecord pos = (read1.getReadNegativeStrandFlag()) ? read2 : read1; final SAMRecord neg = (read1.getReadNegativeStrandFlag()) ? read1 : read2; if (pos.getAlignmentStart() < neg.getAlignmentEnd()) { final int posDiff = pos.getAlignmentEnd() - neg.getAlignmentEnd(); final int negDiff = pos.getAlignmentStart() - neg.getAlignmentStart(); if (posDiff > 0) { CigarUtil.softClip3PrimeEndOfRead(pos, Math.min(pos.getReadLength(), pos.getReadLength() - posDiff + 1)); } if (negDiff > 0) { CigarUtil.softClip3PrimeEndOfRead(neg, Math.min(neg.getReadLength(), neg.getReadLength() - negDiff + 1)); } } } else { } } }

Target:
protected void clipForOverlappingReads(final SAMRecord read1, final SAMRecord read2) { if (!(read1.getReadUnmappedFlag() || read2.getReadUnmappedFlag())) { if (read1.getReadNegativeStrandFlag() != read2.getReadNegativeStrandFlag()) { final SAMRecord pos = (read1.getReadNegativeStrandFlag()) ? read2 : read1; final SAMRecord neg = (read1.getReadNegativeStrandFlag()) ? read1 : read2; if (pos.getAlignmentStart() < neg.getAlignmentEnd()) { final int posDiff = pos.getAlignmentEnd() - neg.getAlignmentEnd(); final int negDiff = pos.getAlignmentStart() - neg.getAlignmentStart(); if (posDiff > 0) { CigarUtil.softClip3PrimeEndOfRead(pos, Math.min(pos.getReadLength(), pos.getReadLength() - posDiff + 1)); removeNmMdAndUqTags(pos); } if (negDiff > 0) { CigarUtil.softClip3PrimeEndOfRead(neg, Math.min(neg.getReadLength(), neg.getReadLength() - negDiff + 1)); removeNmMdAndUqTags(neg); } } } else { } } }
Source:
@Test public void writerBooleanValue() throws Exception { JsonWriter writer = factory.newWriter(); writer.beginObject(); writer.promoteValueToName(); try { writer.value(true); fail(); } catch (IllegalStateException e) { assertThat(e).hasMessage("Boolean cannot be used as a map key in JSON."); } writer.value("true"); assertThat(writer.getPath()).isEqualTo("$.true"); writer.value(1); writer.endObject(); assertThat(writer.getPath()).isEqualTo("$"); assertThat(factory.json()).isEqualTo("{\"true\":1}"); }

Target:
@Test public void writerBooleanValue() throws Exception { JsonWriter writer = factory.newWriter(); writer.beginObject(); writer.promoteValueToName(); try { writer.value(true); fail(); } catch (IllegalStateException e) { assertThat(e).hasMessage("Boolean cannot be used as a map key in JSON at path $."); } writer.value("true"); assertThat(writer.getPath()).isEqualTo("$.true"); writer.value(1); writer.endObject(); assertThat(writer.getPath()).isEqualTo("$"); assertThat(factory.json()).isEqualTo("{\"true\":1}"); }
Source:
public Boolean call() throws Exception { if (!settings.userDataExists()) { throw new TmcCoreException( "Unable to download model solution: missing username/password"); } String courseName = getCourseName(); Path target = exerciseDownloader.createCourseFolder( Paths.get(settings.getTmcMainDirectory()), courseName); return exerciseDownloader.downloadModelSolution(exercise, target); }

Target:
public Boolean call() throws Exception { if (!settings.userDataExists()) { throw new TmcCoreException( "Unable to download model solution: missing username/password"); } String courseName = getCourseName(); Path target = exerciseDownloader.createCourseFolder( settings.getTmcMainDirectory(), courseName); return exerciseDownloader.downloadModelSolution(exercise, target); }
Source:
public void channelActive(ChannelHandlerContext ctx) throws Exception { MqttFixedHeader connectFixedHeader = new MqttFixedHeader(MqttMessageType.CONNECT, false, MqttQoS.AT_MOST_ONCE, false, 0); MqttConnectVariableHeader connectVariableHeader = new MqttConnectVariableHeader(PROTOCOL_NAME_MQTT_3_1_1, PROTOCOL_VERSION_MQTT_3_1_1, true, true, false, 0, false, false, 20); MqttConnectPayload connectPayload = new MqttConnectPayload(clientId, null, null, userName, password); MqttConnectMessage connectMessage = new MqttConnectMessage(connectFixedHeader, connectVariableHeader, connectPayload); ctx.channel().writeAndFlush(connectMessage); System.out.println("Sent CONNECT"); }

Target:
public void channelActive(ChannelHandlerContext ctx) throws Exception { MqttFixedHeader connectFixedHeader = new MqttFixedHeader(MqttMessageType.CONNECT, false, MqttQoS.AT_MOST_ONCE, false, 0); MqttConnectVariableHeader connectVariableHeader = new MqttConnectVariableHeader(PROTOCOL_NAME_MQTT_3_1_1, PROTOCOL_VERSION_MQTT_3_1_1, true, true, false, 0, false, false, 20); MqttConnectPayload connectPayload = new MqttConnectPayload(clientId, null, null, userName, password); MqttConnectMessage connectMessage = new MqttConnectMessage(connectFixedHeader, connectVariableHeader, connectPayload); ctx.writeAndFlush(connectMessage); System.out.println("Sent CONNECT"); }
Source:
public ActivityMetadataBuilder getBuilder(final ActivityDTO dto) { ActivityMetadataBuilder builder = null; switch (dto.getConcept()) { case CERTIFIED_PRODUCT: builder = listingBuilder; break; case DEVELOPER: builder = developerBuilder; break; case PRODUCT: builder = productBuilder; break; case VERSION: builder = versionBuilder; break; case CERTIFICATION_BODY: builder = acbBuilder; break; case TESTING_LAB: builder = atlBuilder; break; case USER: builder = userMaintenanceActivityMetadataBuilder; break; case ANNOUNCEMENT: builder = announcementActivityMetadataBuilder; break; case PENDING_CERTIFIED_PRODUCT: builder = pendingListingActivityMetadataBuilder; break; case CORRECTIVE_ACTION_PLAN: builder = correctActionPlanActivityMetadataBuilder; break; case PENDING_SURVEILLANCE: builder = pendingListingActivityMetadataBuilder; break; default: break; } return builder; }

Target:
public ActivityMetadataBuilder getBuilder(final ActivityDTO dto) { ActivityMetadataBuilder builder = null; switch (dto.getConcept()) { case CERTIFIED_PRODUCT: builder = listingBuilder; break; case DEVELOPER: builder = developerBuilder; break; case PRODUCT: builder = productBuilder; break; case VERSION: builder = versionBuilder; break; case CERTIFICATION_BODY: builder = acbBuilder; break; case TESTING_LAB: builder = atlBuilder; break; case USER: builder = userMaintenanceActivityMetadataBuilder; break; case ANNOUNCEMENT: builder = announcementActivityMetadataBuilder; break; case PENDING_CERTIFIED_PRODUCT: builder = pendingListingActivityMetadataBuilder; break; case CORRECTIVE_ACTION_PLAN: builder = correctActionPlanActivityMetadataBuilder; break; case PENDING_SURVEILLANCE: builder = pendingSurveillanceActivityMetadataBuilder; break; default: break; } return builder; }
Source:
public void addDeviceToUser_addFirstDevice_userHasOneDevice() { String deviceName = "Testing"; OperatingSystem operatingSystem = OperatingSystem.ANDROID; LocalDateTime startTime = TimeUtil.utcNow(); UserDeviceDto deviceDto = new UserDeviceDto(deviceName, operatingSystem, "Unknown"); service.addDeviceToUser(richard, deviceDto); verify(userDeviceRepository, times(1)).save(any(UserDevice.class)); assertThat(deviceAnonymizedRepository.count(), equalTo(1L)); Set<UserDevice> devices = richard.getDevices(); assertThat(devices.size(), equalTo(1)); UserDevice device = devices.iterator().next(); assertDevice(device, startTime, deviceName, operatingSystem, 0); assertVpnAccountCreated(device); }

Target:
public void addDeviceToUser_addFirstDevice_userHasOneDevice() { String deviceName = "Testing"; OperatingSystem operatingSystem = OperatingSystem.ANDROID; LocalDateTime startTime = TimeUtil.utcNow(); UserDeviceDto deviceDto = new UserDeviceDto(deviceName, operatingSystem, SUPPORTED_APP_VERSION); service.addDeviceToUser(richard, deviceDto); verify(userDeviceRepository, times(1)).save(any(UserDevice.class)); assertThat(deviceAnonymizedRepository.count(), equalTo(1L)); Set<UserDevice> devices = richard.getDevices(); assertThat(devices.size(), equalTo(1)); UserDevice device = devices.iterator().next(); assertDevice(device, startTime, deviceName, operatingSystem, 0); assertVpnAccountCreated(device); }
Source:
public void setValueArrayFromString() { Element convert = ElementFactory.make("audioconvert", null); convert.setAsString("mix-matrix", "<<(float)0.25, (float)0.45>,<(float)0.65, (float)0.85>>"); String matrix = convert.getAsString("mix-matrix"); assertTrue(matrix.contains("0.2")); assertTrue(matrix.contains("0.4")); assertTrue(matrix.contains("0.6")); assertTrue(matrix.contains("0.8")); convert.dispose(); }

Target:
public void setValueArrayFromString() { if (!Gst.testVersion(1, 14)) { return; } Element convert = ElementFactory.make("audioconvert", null); convert.setAsString("mix-matrix", "<<(float)0.25, (float)0.45>,<(float)0.65, (float)0.85>>"); String matrix = convert.getAsString("mix-matrix"); assertTrue(matrix.contains("0.2")); assertTrue(matrix.contains("0.4")); assertTrue(matrix.contains("0.6")); assertTrue(matrix.contains("0.8")); convert.dispose(); }
Source:
public void testChunkFillerSleep() throws Exception { router = getNonBlockingRouter(); Thread chunkFillerThread = TestUtils.getThreadByThisName("ChunkFillerThread"); Assert.assertTrue("ChunkFillerThread should have gone to WAITING state as there are no active operations", waitForThreadState(chunkFillerThread, Thread.State.WAITING)); int blobSize = chunkSize * 2; RequestAndResult requestAndResult = new RequestAndResult(blobSize); requestAndResultsList.add(requestAndResult); MockReadableStreamChannel putChannel = new MockReadableStreamChannel(blobSize); FutureResult<String> future = (FutureResult<String>) router .putBlob(requestAndResult.putBlobProperties, requestAndResult.putUserMetadata, putChannel, null); ByteBuffer src = ByteBuffer.wrap(requestAndResult.putContent); int writeSize = blobSize / 2; ByteBuffer buf = ByteBuffer.allocate(writeSize); src.get(buf.array()); putChannel.write(buf); Assert.assertTrue( "ChunkFillerThread should have gone to RUNNABLE state as there is an active operation that is not yet complete", waitForThreadState(chunkFillerThread, Thread.State.RUNNABLE)); buf.rewind(); src.get(buf.array()); putChannel.write(buf); Assert .assertTrue("ChunkFillerThread should have gone to WAITING state as the only active operation is now complete", waitForThreadState(chunkFillerThread, Thread.State.WAITING)); future.await(); requestAndResult.result = future; assertSuccess(); assertCloseCleanup(); }

Target:
public void testChunkFillerSleep() throws Exception { router = getNonBlockingRouter(); Thread chunkFillerThread = TestUtils.getThreadByThisName("ChunkFillerThread"); Assert.assertTrue("ChunkFillerThread should have gone to WAITING state as there are no active operations", waitForThreadState(chunkFillerThread, Thread.State.WAITING)); int blobSize = chunkSize * 2; RequestAndResult requestAndResult = new RequestAndResult(blobSize); requestAndResultsList.add(requestAndResult); MockReadableStreamChannel putChannel = new MockReadableStreamChannel(blobSize); FutureResult<String> future = (FutureResult<String>) router .putBlob(requestAndResult.putBlobProperties, requestAndResult.putUserMetadata, putChannel, null); ByteBuffer src = ByteBuffer.wrap(requestAndResult.putContent); int writeSize = blobSize / 2; ByteBuffer buf = ByteBuffer.allocate(writeSize); src.get(buf.array()); putChannel.write(buf); Assert.assertTrue( "ChunkFillerThread should have gone to RUNNABLE state as there is an active operation that is not yet complete", waitForThreadState(chunkFillerThread, Thread.State.RUNNABLE)); buf.rewind(); src.get(buf.array()); putChannel.write(buf); Assert .assertTrue("ChunkFillerThread should have gone to WAITING state as the only active operation is now complete", waitForThreadState(chunkFillerThread, Thread.State.WAITING)); Assert .assertTrue("Operation should not take too long to complete", future.await(MAX_WAIT_MS, TimeUnit.MILLISECONDS)); requestAndResult.result = future; assertSuccess(); assertCloseCleanup(); }
Source:
public static Slice castFromIpAddressToVarchar(@SqlType(StandardTypes.IPADDRESS) Slice slice) { SqlIpAddress address = new SqlIpAddress(slice.getBytes()); return utf8Slice(address.toString()); }

Target:
public static Slice castFromIpAddressToVarchar(@SqlType(StandardTypes.IPADDRESS) Slice slice) { try { return utf8Slice(InetAddresses.toAddrString(InetAddress.getByAddress(slice.getBytes()))); } catch (UnknownHostException e) { throw new PrestoException(INVALID_CAST_ARGUMENT, "Invalid IP address binary length: " + slice.length(), e); } }
Source:
private void createTimeEventContextMenu() { fEventMenuManager.setRemoveAllWhenShown(true); TimeGraphControl timeGraphControl = fTimeGraphViewer.getTimeGraphControl(); final Menu timeEventMenu = fEventMenuManager.createContextMenu(timeGraphControl); timeGraphControl.addTimeEventMenuListener(new MenuDetectListener() { @Override public void menuDetected(MenuDetectEvent event) { Menu menu = timeEventMenu; if (!isOnFlameGraphEvent(event, timeGraphControl)) { timeGraphControl.setMenu(null); } timeGraphControl.setMenu(menu); } }); timeGraphControl.addTimeGraphEntryMenuListener(new MenuDetectListener() { @Override public void menuDetected(MenuDetectEvent event) { if (!isOnFlameGraphEvent(event, timeGraphControl)) { timeGraphControl.setMenu(null); } } }); fEventMenuManager.addMenuListener(new IMenuListener() { @Override public void menuAboutToShow(IMenuManager manager) { fillTimeEventContextMenu(fEventMenuManager); fEventMenuManager.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); } }); getSite().registerContextMenu(fEventMenuManager, fTimeGraphViewer.getSelectionProvider()); }

Target:
private void createTimeEventContextMenu() { fEventMenuManager.setRemoveAllWhenShown(true); TimeGraphControl timeGraphControl = fTimeGraphViewer.getTimeGraphControl(); final Menu timeEventMenu = fEventMenuManager.createContextMenu(timeGraphControl); timeGraphControl.addTimeEventMenuListener(new MenuDetectListener() { @Override public void menuDetected(MenuDetectEvent event) { Menu menu = timeEventMenu; if (isOnNamespace(event, timeGraphControl) || !(event.data instanceof FlamegraphEvent)) { timeGraphControl.setMenu(null); event.doit = false; return; } timeGraphControl.setMenu(menu); } }); timeGraphControl.addTimeGraphEntryMenuListener(new MenuDetectListener() { @Override public void menuDetected(MenuDetectEvent event) { if (isOnNamespace(event, timeGraphControl)) { timeGraphControl.setMenu(null); event.doit = false; } } }); fEventMenuManager.addMenuListener(new IMenuListener() { @Override public void menuAboutToShow(IMenuManager manager) { fillTimeEventContextMenu(fEventMenuManager); fEventMenuManager.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); } }); getSite().registerContextMenu(fEventMenuManager, fTimeGraphViewer.getSelectionProvider()); }
Source:
private void setVmTemplateIdParameter() { Map<Boolean, VmTemplate> templateMap = getDbFacade().getVmTemplateDAO().getAllForImage(((DiskImage) disk).getImageId()); if (!templateMap.values().isEmpty()) { setVmTemplateId(templateMap.values().iterator().next().getId()); } }

Target:
private void setVmTemplateIdParameter() { Map<Boolean, VmTemplate> templateMap = getDbFacade().getVmTemplateDAO().getAllForImage(((DiskImage) disk).getImageId()); if (!templateMap.isEmpty()) { setVmTemplateId(templateMap.values().iterator().next().getId()); } }
Source:
public <S> SparqlTraversal<S,?> sparql(final String query) { final SparqlTraversalSource clone = this.clone(); clone.getStrategies().addStrategies(SparqlStrategy.instance()); clone.bytecode.addStep(GraphTraversal.Symbols.inject); clone.bytecode.addStep(GraphTraversal.Symbols.constant, query); final SparqlTraversal.Admin<S, S> traversal = new DefaultSparqlTraversal<>(clone); traversal.addStep(new InjectStep<S>(traversal)); return traversal.addStep(new ConstantStep<S,String>(traversal, query)); }

Target:
public <S> SparqlTraversal<S,?> sparql(final String query) { final SparqlTraversalSource clone = this.clone(); clone.getStrategies().addStrategies(SparqlStrategy.instance()); clone.bytecode.addStep(GraphTraversal.Symbols.inject, query); final SparqlTraversal.Admin<S, S> traversal = new DefaultSparqlTraversal<>(clone); return traversal.addStep(new InjectStep<>(traversal, query)); }
Source:
public void testGameRefresh() throws URISyntaxException, IOException { MockApplication.initStatics(); MockPlatform mockPlatform = new MockPlatform(); MockFiles mf = new MockFiles(); Controller mockController = new Controller(mockPlatform, mf, new Group()); File source = new File( "../../engine/desktop/src/test/resources/techdemo") .getCanonicalFile(); mockController.getModel().addLoadListener( new Model.ModelListener<LoadEvent>() { @Override public void modelChanged(LoadEvent event) { Model m = event.getModel(); Index.SearchResult sr; sr = m.search("_g_lang"); assertEquals("single match", 1, sr.getMatches().size()); assertTrue(sr.getMatches().get(0).getObject() instanceof VariableDef); sr = m.search("zebras"); assertEquals("no zebras here", 0, sr.getMatches() .size()); sr = m.search("_g_"); assertEquals("single match", 1, sr.getMatches().size()); assertTrue(sr.getMatches().get(0).getObject() instanceof VariableDef); } }); mockController.action(OpenGame.class, source.getPath()); mockController.getEditorGameAssets().finishLoading(); }

Target:
public void testGameRefresh() throws URISyntaxException, IOException { MockApplication.initStatics(); MockPlatform mockPlatform = new MockPlatform(); MockFiles mf = new MockFiles(); Controller mockController = new Controller(mockPlatform, mf, new Group()); File source = new File( "../../engine/desktop/src/test/resources/techdemo") .getCanonicalFile(); mockController.getModel().addLoadListener( new Model.ModelListener<LoadEvent>() { @Override public void modelChanged(LoadEvent event) { Model m = event.getModel(); Index.SearchResult sr; sr = m.search("lang"); assertEquals("only one language per game", 1, sr .getMatches().size()); assertTrue(sr.getMatches().get(0).getObject() instanceof VariableDef); sr = m.search("zebras"); assertEquals("no zebras here", 0, sr.getMatches() .size()); sr = m.search("logo"); assertEquals("lots of logos", 4, sr.getMatches().size()); sr = m.search("logo2"); assertEquals("single match", 1, sr.getMatches().size()); assertTrue(sr.getMatches().get(0).getObject() instanceof Image); } }); mockController.action(OpenGame.class, source.getPath()); mockController.getEditorGameAssets().finishLoading(); }
Source:
public void clear() throws IOException { for (final String label : this.labelSet()) { this.remove(label); } }

Target:
public void clear() throws IOException { for (final String label : this.labels()) { this.remove(label); } }
Source:
public void initialize(InputSplit inputSplit, TaskAttemptContext context) throws IOException, InterruptedException { if (context instanceof TaskInputOutputContext<?, ?, ?, ?>) { BenchmarkCounter.initCounterFromContext((TaskInputOutputContext<?, ?, ?, ?>) context); } else { LOG.error("Can not initialize counter due to context is not a instance of TaskInputOutputContext, but is " + context.getClass().getCanonicalName()); } ParquetInputSplit parquetSplit; if (inputSplit instanceof ParquetInputSplit) { parquetSplit = (ParquetInputSplit) inputSplit; } else if (inputSplit instanceof FileSplit) { parquetSplit = ParquetInputSplit.from((FileSplit) inputSplit); } else { throw new IllegalArgumentException( "Invalid split (not a FileSplit or ParquetInputSplit): " + inputSplit); } initializeInternalReader(parquetSplit, ContextUtil.getConfiguration(context)); }

Target:
public void initialize(InputSplit inputSplit, TaskAttemptContext context) throws IOException, InterruptedException { if (context instanceof TaskInputOutputContext<?, ?, ?, ?>) { BenchmarkCounter.initCounterFromContext((TaskInputOutputContext<?, ?, ?, ?>) context); } else { LOG.error("Can not initialize counter due to context is not a instance of TaskInputOutputContext, but is " + context.getClass().getCanonicalName()); } initializeInternalReader(toParquetSplit(inputSplit), ContextUtil.getConfiguration(context)); }
Source:
public void testPutHeaders() { PutOptions options = new PutOptions().headers(ImmutableMultimap.of(OBJECT_DELETE_AT, "123456789")); assertEquals(ImmutableList.of("123456789"), options.buildRequestHeaders().get(OBJECT_DELETE_AT)); }

Target:
public void testPutHeaders() { PutOptions options = new PutOptions().headers(ImmutableMultimap.of(OBJECT_DELETE_AT, "123456789")); assertEquals(options.buildRequestHeaders().get(OBJECT_DELETE_AT), ImmutableList.of("123456789")); }
Source:
public void run() { Location dropLocation = this.location.clone(); ItemStack item = this.itemstack.clone(); if (Main.getInstance().getBooleanConfig("spawnRessourcesInChest", true)) { BlockState blockState = dropLocation.getBlock().getState(); if (blockState instanceof Chest) { Chest chest = (Chest) blockState; if (canContainItem(chest.getInventory(), item)) { chest.getInventory().addItem(item); return; } else { dropLocation.setY(dropLocation.getY() + 1); } } } dropItem(dropLocation); }

Target:
public void run() { Location dropLocation = this.location.clone(); ItemStack item = this.itemstack.clone(); if (Main.getInstance().getBooleanConfig("spawn-ressources-in-chest", true)) { BlockState blockState = dropLocation.getBlock().getState(); if (blockState instanceof Chest) { Chest chest = (Chest) blockState; if (canContainItem(chest.getInventory(), item)) { chest.getInventory().addItem(item); return; } else { dropLocation.setY(dropLocation.getY() + 1); } } } dropItem(dropLocation); }
Source:
private Change submitThisChange(RevisionResource rsrc, IdentifiedUser caller, boolean force) throws ResourceConflictException, OrmException, IOException { ReviewDb db = dbProvider.get(); ChangeData cd = changeDataFactory.create(db, rsrc.getControl()); List<SubmitRecord> submitRecords = checkSubmitRule(cd, rsrc.getPatchSet(), force); final Timestamp timestamp = TimeUtil.nowTs(); Change change = rsrc.getChange(); ChangeUpdate update = updateFactory.create(rsrc.getControl(), timestamp); update.submit(submitRecords); db.changes().beginTransaction(change.getId()); try { BatchMetaDataUpdate batch = approve(rsrc, update, caller, timestamp); batch.write(update, new CommitBuilder()); change = submitToDatabase(db, change.getId(), timestamp); db.commit(); } catch (ResourceConflictException e) { throw e; } finally { db.rollback(); } indexer.index(db, change); return change; }

Target:
private Change submitThisChange(RevisionResource rsrc, IdentifiedUser caller, boolean force) throws ResourceConflictException, OrmException, IOException { ReviewDb db = dbProvider.get(); ChangeData cd = changeDataFactory.create(db, rsrc.getControl()); List<SubmitRecord> submitRecords = checkSubmitRule(cd, rsrc.getPatchSet(), force); final Timestamp timestamp = TimeUtil.nowTs(); Change change = rsrc.getChange(); ChangeUpdate update = updateFactory.create(rsrc.getControl(), timestamp); update.submit(submitRecords); db.changes().beginTransaction(change.getId()); try { BatchMetaDataUpdate batch = approve(rsrc, update, caller, timestamp); batch.write(update, new CommitBuilder()); change = submitToDatabase(db, change.getId(), timestamp); db.commit(); } finally { db.rollback(); } indexer.index(db, change); return change; }
Source:
private void walkNetwork() { if (cableBlockEntities.isEmpty()) { return; } TechReborn.LOGGER.debug("Walking the Electric Network to detect for changes in neighbors..."); HashSet<CableBlockEntity> seenNodes = new HashSet<>(); HashSet<CableBlockEntity> visitedNodes = new HashSet<>(); CableBlockEntity firstNode = cableBlockEntities.iterator().next(); TechReborn.LOGGER.debug("First node in the walk: {}", firstNode); seenNodes.addAll(visitCableNode(firstNode, visitedNodes)); HashSet<CableBlockEntity> remainingNodesToVisit = new HashSet<>(seenNodes); while (!remainingNodesToVisit.isEmpty()) { for (CableBlockEntity nodeToVisit : remainingNodesToVisit) { seenNodes.addAll(visitCableNode(nodeToVisit, visitedNodes)); } remainingNodesToVisit.clear(); remainingNodesToVisit.addAll(seenNodes); remainingNodesToVisit.removeAll(visitedNodes); } for (CableBlockEntity nodeConnected : seenNodes) { if (nodeConnected.getElectricNetwork() != this) { TechReborn.LOGGER.debug( "Block network change: -> {}", nodeConnected.getPos().asLong(), nodeConnected.getElectricNetwork(), this); nodeConnected.setElectricNetwork(this); } } TechReborn.LOGGER.debug( "Starting purge of disconnected entities. Have {}, seen {}", cableBlockEntities.size(), seenNodes.size()); cableBlockEntities .stream() .filter(node -> !seenNodes.contains(node)) .collect(Collectors.toList()) .forEach(node -> { if (node != null) { TechReborn.LOGGER.debug( "Block being ejected from the network {}", node, this); node.setElectricNetwork(null); } }); TechReborn.LOGGER.debug("Finished walking network for cable connection changes."); }

Target:
private void walkNetwork() { if (cableBlockEntities.isEmpty()) { return; } TechReborn.LOGGER.debug("Walking the Electric Network to detect for changes in neighbors..."); HashSet<CableBlockEntity> seenNodes = new HashSet<>(); HashSet<CableBlockEntity> visitedNodes = new HashSet<>(); CableBlockEntity firstNode = cableBlockEntities.iterator().next(); TechReborn.LOGGER.debug("First node in the walk: {}", firstNode); seenNodes.addAll(visitCableNode(firstNode, visitedNodes)); HashSet<CableBlockEntity> remainingNodesToVisit = new HashSet<>(seenNodes); while (!remainingNodesToVisit.isEmpty()) { for (CableBlockEntity nodeToVisit : remainingNodesToVisit) { seenNodes.addAll(visitCableNode(nodeToVisit, visitedNodes)); } remainingNodesToVisit.clear(); remainingNodesToVisit.addAll(seenNodes); remainingNodesToVisit.removeAll(visitedNodes); } for (CableBlockEntity nodeConnected : seenNodes) { if (nodeConnected.getElectricNetwork() != this) { TechReborn.LOGGER.debug( "Block network change: -> {}", nodeConnected.getPos().asLong(), nodeConnected.getElectricNetwork(), this); nodeConnected.setElectricNetwork(this); } } TechReborn.LOGGER.debug( "Starting purge of disconnected entities. Have {}, seen {}", cableBlockEntities.size(), seenNodes.size()); cableBlockEntities .stream() .filter(node -> !seenNodes.contains(node) && node != null) .collect(Collectors.toList()) .forEach(node -> { TechReborn.LOGGER.debug( "Block being ejected from the network {}", node, this); node.setElectricNetwork(null); }); TechReborn.LOGGER.debug("Finished walking network for cable connection changes."); }
Source:
public void testCiphersuites(boolean hasException, int serverPort) { try { ByteBuffer byteBuffer = ByteBuffer.wrap(testValue.getBytes(Charset.forName("UTF-8"))); HTTPCarbonMessage msg = new HTTPCarbonMessage( new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "")); msg.setProperty("PORT", serverPort); msg.setProperty("PROTOCOL", scheme); msg.setProperty("HOST", TestUtil.TEST_HOST); msg.setProperty("HTTP_METHOD", "GET"); msg.addMessageBody(byteBuffer); msg.setEndOfMsgAdded(true); CountDownLatch latch = new CountDownLatch(1); SSLConnectorListener listener = new SSLConnectorListener(latch); HttpResponseFuture responseFuture = httpClientConnector.send(msg); responseFuture.setHttpConnectorListener(listener); latch.await(3, TimeUnit.SECONDS); HTTPCarbonMessage response = listener.getHttpResponseMessage(); if (hasException) { assertNotNull(listener.getThrowables()); boolean hasSSLException = false; for (Throwable t : listener.getThrowables()) { if (t.getMessage() != null && t.getMessage().contains("handshake_failure")) { hasSSLException = true; break; } } assertTrue(hasSSLException); } else { assertNotNull(response); String result = new BufferedReader( new InputStreamReader(new HttpMessageDataStreamer(response).getInputStream())).lines() .collect(Collectors.joining("\n")); assertEquals(testValue, result); } } catch (Exception e) { TestUtil.handleException("Exception occurred while running testCiphersuites", e); } }

Target:
public void testCiphersuites(boolean hasException, int serverPort) { try { ByteBuffer byteBuffer = ByteBuffer.wrap(testValue.getBytes(Charset.forName("UTF-8"))); HTTPCarbonMessage msg = new HTTPCarbonMessage( new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "")); msg.setProperty("PORT", serverPort); msg.setProperty("PROTOCOL", scheme); msg.setProperty("HOST", TestUtil.TEST_HOST); msg.setProperty("HTTP_METHOD", "GET"); msg.addMessageBody(byteBuffer); msg.setEndOfMsgAdded(true); CountDownLatch latch = new CountDownLatch(1); SSLConnectorListener listener = new SSLConnectorListener(latch); HttpResponseFuture responseFuture = httpClientConnector.send(msg); responseFuture.setHttpConnectorListener(listener); latch.await(5, TimeUnit.SECONDS); HTTPCarbonMessage response = listener.getHttpResponseMessage(); if (hasException) { assertNotNull(listener.getThrowables()); boolean hasSSLException = false; for (Throwable throwable : listener.getThrowables()) { if (throwable.getMessage() != null && throwable.getMessage().contains("handshake_failure")) { hasSSLException = true; break; } } assertTrue(hasSSLException); } else { assertNotNull(response); String result = new BufferedReader( new InputStreamReader(new HttpMessageDataStreamer(response).getInputStream())).lines() .collect(Collectors.joining("\n")); assertEquals(testValue, result); } } catch (Exception e) { TestUtil.handleException("Exception occurred while running testCiphersuites", e); } }
Source:
public void destroySession(final HttpServletRequest request) { final String logoutMessage = CommonUtils.safeGetParameter(request, this.logoutParameterName, this.safeParameters); logger.trace("Logout request:\n{}", logoutMessage); final String token = XmlUtils.getTextForElement(logoutMessage, "SessionIndex"); if (CommonUtils.isNotBlank(token)) { final HttpSession session = this.sessionMappingStorage.removeSessionByMappingId(token); if (session != null) { String sessionID = session.getId(); logger.debug("Invalidating session for token [{}]", sessionID, token); try { session.invalidate(); request.logout(); } catch (final ServletException e) { logger.debug("Error performing request.logout."); } catch (final IllegalStateException e) { logger.debug("Error invalidating session.", e); } } } }

Target:
public void destroySession(final HttpServletRequest request) { final String logoutMessage = CommonUtils.safeGetParameter(request, this.logoutParameterName, this.safeParameters); logger.trace("Logout request:\n{}", logoutMessage); final String token = XmlUtils.getTextForElement(logoutMessage, "SessionIndex"); if (CommonUtils.isNotBlank(token)) { final HttpSession session = this.sessionMappingStorage.removeSessionByMappingId(token); if (session != null) { String sessionID = session.getId(); logger.debug("Invalidating session for token [{}]", sessionID, token); try { session.invalidate(); } catch (final IllegalStateException e) { logger.debug("Error invalidating session.", e); } try { request.logout(); } catch (final ServletException e) { logger.debug("Error performing request.logout."); } } } }
Source:
protected Sheet createSheet() { Sheet sheet = super.createSheet(); Sheet.Set sheetSet = sheet.get(Sheet.PROPERTIES); if (sheetSet == null) { sheetSet = Sheet.createPropertiesSet(); sheet.put(sheetSet); } final BlackboardArtifact artifact = getArtifact(); BlackboardArtifact.ARTIFACT_TYPE fromID = BlackboardArtifact.ARTIFACT_TYPE.fromID(artifact.getArtifactTypeID()); if (null != fromID && fromID != TSK_CALLLOG) { return sheet; } String phoneNumber = getAttributeDisplayString(artifact, TSK_PHONE_NUMBER_FROM); if(phoneNumber == null || phoneNumber.isEmpty()) { phoneNumber = getAttributeDisplayString(artifact, TSK_PHONE_NUMBER_TO); } long duration = -1; try{ duration = getCallDuration(artifact); } catch(TskCoreException ex) { } sheetSet.put(createNode(TSK_DATETIME_START, artifact)); sheetSet.put(createNode(TSK_DIRECTION, artifact)); sheetSet.put(new NodeProperty<>(TSK_PHONE_NUMBER.getLabel(), TSK_PHONE_NUMBER.getDisplayName(), "", phoneNumber)); if(duration != -1) { sheetSet.put(new NodeProperty<>("duration", "Duration", "", Long.toString(duration))); } return sheet; }

Target:
protected Sheet createSheet() { Sheet sheet = super.createSheet(); Sheet.Set sheetSet = sheet.get(Sheet.PROPERTIES); if (sheetSet == null) { sheetSet = Sheet.createPropertiesSet(); sheet.put(sheetSet); } final BlackboardArtifact artifact = getArtifact(); BlackboardArtifact.ARTIFACT_TYPE fromID = BlackboardArtifact.ARTIFACT_TYPE.fromID(artifact.getArtifactTypeID()); if (null != fromID && fromID != TSK_CALLLOG) { return sheet; } String phoneNumber = getAttributeDisplayString(artifact, TSK_PHONE_NUMBER_FROM); if(phoneNumber == null || phoneNumber.isEmpty()) { phoneNumber = getAttributeDisplayString(artifact, TSK_PHONE_NUMBER_TO); } long duration = -1; try{ duration = getCallDuration(artifact); } catch(TskCoreException ex) { logger.log(Level.WARNING, String.format("Unable to get calllog duration for artifact: %d", artifact.getArtifactID()), ex); } sheetSet.put(createNode(TSK_DATETIME_START, artifact)); sheetSet.put(createNode(TSK_DIRECTION, artifact)); sheetSet.put(new NodeProperty<>(TSK_PHONE_NUMBER.getLabel(), TSK_PHONE_NUMBER.getDisplayName(), "", phoneNumber)); if(duration != -1) { sheetSet.put(new NodeProperty<>("duration", "Duration", "", Long.toString(duration))); } return sheet; }
Source:
@Override protected WORKFLOWAPP getWorkflow(Cluster src, Cluster target) throws FalconException { WORKFLOWAPP workflow = new WORKFLOWAPP(); String wfName = EntityUtil.getWorkflowName(Tag.REPLICATION, Arrays.asList(src.getName()), entity).toString(); String start = REPLICATION_ACTION_NAME; if (shouldPreProcess()) { ACTION action = getPreProcessingAction(false, Tag.REPLICATION); addHDFSServersConfig(action, src, target); addTransition(action, REPLICATION_ACTION_NAME, FAIL_POSTPROCESS_ACTION_NAME); workflow.getDecisionOrForkOrJoin().add(action); start = PREPROCESS_ACTION_NAME; } ACTION replication = unmarshalAction(REPLICATION_ACTION_TEMPLATE); addHDFSServersConfig(replication, src, target); addAdditionalReplicationProperties(replication); enableCounters(replication); if (!Boolean.parseBoolean(ENABLE_POSTPROCESSING)){ addTransition(replication, OK_ACTION_NAME, FAIL_ACTION_NAME); workflow.getDecisionOrForkOrJoin().add(replication); }else { addTransition(replication, SUCCESS_POSTPROCESS_ACTION_NAME, FAIL_POSTPROCESS_ACTION_NAME); workflow.getDecisionOrForkOrJoin().add(replication); ACTION success = getSuccessPostProcessAction(); addHDFSServersConfig(success, src, target); addTransition(success, OK_ACTION_NAME, FAIL_ACTION_NAME); workflow.getDecisionOrForkOrJoin().add(success); ACTION fail = getFailPostProcessAction(); addHDFSServersConfig(fail, src, target); addTransition(fail, FAIL_ACTION_NAME, FAIL_ACTION_NAME); workflow.getDecisionOrForkOrJoin().add(fail); } decorateWorkflow(workflow, wfName, start); return workflow; }

Target:
@Override protected WORKFLOWAPP getWorkflow(Cluster src, Cluster target) throws FalconException { WORKFLOWAPP workflow = new WORKFLOWAPP(); String wfName = EntityUtil.getWorkflowName(Tag.REPLICATION, Arrays.asList(src.getName()), entity).toString(); String start = REPLICATION_ACTION_NAME; if (shouldPreProcess()) { ACTION action = getPreProcessingAction(false, Tag.REPLICATION); addHDFSServersConfig(action, src, target); addTransition(action, REPLICATION_ACTION_NAME, FAIL_POSTPROCESS_ACTION_NAME); workflow.getDecisionOrForkOrJoin().add(action); start = PREPROCESS_ACTION_NAME; } ACTION replication = unmarshalAction(REPLICATION_ACTION_TEMPLATE); addHDFSServersConfig(replication, src, target); addAdditionalReplicationProperties(replication); enableCounters(replication); enableTDE(replication); addPostProcessing(workflow, replication); decorateWorkflow(workflow, wfName, start); return workflow; }
Source:
protected ApiConnection( @JsonProperty("baseUrl") String apiBaseUrl, @JsonProperty("cookies") Map<String, String> cookies, @JsonProperty("username") String username, @JsonProperty("loggedIn") boolean loggedIn) { this.apiBaseUrl = apiBaseUrl; this.username = username; this.cookies = cookies; this.loggedIn = loggedIn; }

Target:
private ApiConnection( @JsonProperty("baseUrl") String apiBaseUrl, @JsonProperty("cookies") Map<String, String> cookies, @JsonProperty("username") String username, @JsonProperty("loggedIn") boolean loggedIn) { this.apiBaseUrl = apiBaseUrl; this.username = username; this.cookies = cookies; this.loggedIn = loggedIn; }
Source:
protected void onPostExecute(String templatesList) { super.onPostExecute(templatesList); if (progressDialog != null && progressDialog.isShowing() && !((Activity) context).isFinishing()) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && !((Activity) context).isDestroyed()) { progressDialog.dismiss(); } else { progressDialog.dismiss(); } } if (Utils.checkForNetworkError(exception)) { showDialog(R.string.error_internet_connection); return; } if (onFetchTemplatesCompleteListener != null) { onFetchTemplatesCompleteListener.onFetchTemplatesComplete(templatesList); } }

Target:
protected void onPostExecute(String templatesList) { super.onPostExecute(templatesList); if (progressDialog != null && progressDialog.isShowing() && !((Activity) context).isFinishing()) { progressDialog.dismiss(); } if (!networkAvailable) { ToastUtil.showError(context, R.string.error_internet_connection); return; } else if (message != null) { ToastUtil.showError(context, message); return; } onFetchTemplatesCompleteListener.onFetchTemplatesComplete(templatesList); }
Source:
public String getAsHtml() throws OseeCoreException { BranchQuery query = orcsApi.getQueryFactory().branchQuery(); ResultSet<BranchReadable> results = query.andUuids(branchId.getId()).getResults(); HtmlWriter writer = new HtmlWriter(uriInfo); return writer.toHtml(results); }

Target:
public String getAsHtml() throws OseeCoreException { BranchQuery query = orcsApi.getQueryFactory().branchQuery(); ResultSet<BranchReadable> results = query.andIds(branchId).getResults(); HtmlWriter writer = new HtmlWriter(uriInfo); return writer.toHtml(results); }
Source:
private void addEntryAddressToEnd(long entryAddress) { if (trace) { log.tracef("Updating LRU contents for new entry 0x%016x", entryAddress); } if (lastAddress == 0) { firstAddress = entryAddress; lastAddress = entryAddress; OffHeapLruNode.setPrevious(entryAddress, 0); } else { OffHeapLruNode.setPrevious(entryAddress, lastAddress); OffHeapLruNode.setNext(lastAddress, entryAddress); lastAddress = entryAddress; } OffHeapLruNode.setNext(entryAddress, 0); }

Target:
private void addEntryAddressToEnd(long entryAddress) { if (trace) { log.tracef("Adding entry 0x%016x to the end of the LRU list", entryAddress); } if (lastAddress == 0) { firstAddress = entryAddress; lastAddress = entryAddress; OffHeapLruNode.setPrevious(entryAddress, 0); } else { OffHeapLruNode.setPrevious(entryAddress, lastAddress); OffHeapLruNode.setNext(lastAddress, entryAddress); lastAddress = entryAddress; } OffHeapLruNode.setNext(entryAddress, 0); }
Source:
private Span serverRequest(Tracing brave, String serviceName, Exchange exchange) { ZipkinState state = exchange.getProperty(ZipkinState.KEY, ZipkinState.class); if (state == null) { state = new ZipkinState(); exchange.setProperty(ZipkinState.KEY, state); } Span span = null; if (ObjectHelper.isEmpty(EXTRACTOR.extract(exchange.getIn()))) { span = brave.tracer().nextSpan(); INJECTOR.inject(span.context(), exchange.getIn()); } else { span = brave.tracer().nextSpan(EXTRACTOR.extract(exchange.getIn())); } span.kind(Span.Kind.SERVER).start(); ZipkinServerRequestAdapter parser = new ZipkinServerRequestAdapter(this, exchange); parser.onRequest(exchange, span.customizer()); state.pushServerSpan(span); if (LOG.isDebugEnabled()) { TraceContext context = span.context(); String traceId = "" + context.traceIdString(); String spanId = "" + context.spanId(); String parentId = context.parentId() != null ? "" + context.parentId() : null; if (parentId != null) { LOG.debug(String.format("serverRequest [service=%s, traceId=%20s, spanId=%20s, parentId=%20s]", serviceName, traceId, spanId, parentId)); } else { LOG.debug(String.format("serverRequest [service=%s, traceId=%20s, spanId=%20s]", serviceName, traceId, spanId)); } } return span; }

Target:
private Span serverRequest(Tracing brave, String serviceName, Exchange exchange) { ZipkinState state = exchange.getProperty(ZipkinState.KEY, ZipkinState.class); if (state == null) { state = new ZipkinState(); exchange.setProperty(ZipkinState.KEY, state); } Span span = null; TraceContextOrSamplingFlags sampleFlag = EXTRACTOR.extract(exchange.getIn()); if (ObjectHelper.isEmpty(sampleFlag)) { span = brave.tracer().nextSpan(); INJECTOR.inject(span.context(), exchange.getIn()); } else { span = brave.tracer().nextSpan(sampleFlag); } span.kind(Span.Kind.SERVER).start(); ZipkinServerRequestAdapter parser = new ZipkinServerRequestAdapter(this, exchange); parser.onRequest(exchange, span.customizer()); state.pushServerSpan(span); if (LOG.isDebugEnabled()) { TraceContext context = span.context(); String traceId = "" + context.traceIdString(); String spanId = "" + context.spanId(); String parentId = context.parentId() != null ? "" + context.parentId() : null; if (parentId != null) { LOG.debug(String.format("serverRequest [service=%s, traceId=%20s, spanId=%20s, parentId=%20s]", serviceName, traceId, spanId, parentId)); } else { LOG.debug(String.format("serverRequest [service=%s, traceId=%20s, spanId=%20s]", serviceName, traceId, spanId)); } } return span; }
Source:
public JSON getRepositories(String path) throws IOException { final List<JSON> repositories = new ArrayList<>(addresses.length); for (String address : addresses) { repositories.add(getJSON(address + path)); } final JSONArray result = new JSONArray(); final List<String> pluginsIDs = new ArrayList<>(); for (JSON json : repositories) { if (!(json instanceof JSONArray)) { throw new RuntimeException("Result is not array"); } for (Object elm : (JSONArray) json) { String id = ((JSONObject) elm).getString("id"); if (!pluginsIDs.contains(id)) { pluginsIDs.add(id); result.add(elm); } else { log.info("Plugin " + id + " will be skipped, because it is duplicated."); } } } return result; }

Target:
protected JSONArray getRepositories(String path) throws IOException { final List<JSON> repositories = new ArrayList<>(addresses.length); for (String address : addresses) { repositories.add(getJSON(address + path)); } final JSONArray result = new JSONArray(); final List<String> pluginsIDs = new ArrayList<>(); for (JSON json : repositories) { if (!(json instanceof JSONArray)) { throw new RuntimeException("Result is not array"); } for (Object elm : (JSONArray) json) { String id = ((JSONObject) elm).getString("id"); if (!pluginsIDs.contains(id)) { pluginsIDs.add(id); result.add(elm); } else { log.info("Plugin " + id + " will be skipped, because it is duplicated."); } } } return result; }
Source:
public final RedirectAction getLogoutRedirectAction(final WebContext context) { if (ajaxRequestResolver.isAjax(context)) { logger.info("AJAX request detected -> returning 401"); cleanRequestedUrl(context); return null; } final String attemptedAuth = (String) context.getSessionAttribute(getName() + ATTEMPTED_AUTHENTICATION_SUFFIX); if (CommonHelper.isNotBlank(attemptedAuth)) { return null; } init(context); return retrieveLogoutRedirectAction(context); }

Target:
public final RedirectAction getLogoutRedirectAction(final WebContext context) { init(context); return retrieveLogoutRedirectAction(context); }
Source:
private void processBundle(Bundle bundle, int state) { boolean isActive = true; boolean isStopping = false; if (state == Bundle.ACTIVE || state == Bundle.STARTING || state == Bundle.INSTALLED || state == Bundle.RESOLVED) { isActive = true; } else if (state == Bundle.STOPPING) { isStopping = true; } if (isActive && hasWebResourceHeader(bundle)) { addBundle(bundle); } else if (isStopping && hasWebResourceHeader(bundle)) { removeBundle(bundle); } }

Target:
private void processBundle(Bundle bundle, int state) { boolean isActive = false; boolean isStopping = false; if (state == Bundle.ACTIVE || state == Bundle.STARTING || state == Bundle.INSTALLED || state == Bundle.RESOLVED) { isActive = true; } else if (state == Bundle.STOPPING) { isStopping = true; } if (isActive && hasWebResourceHeader(bundle)) { addBundle(bundle); } else if (isStopping && hasWebResourceHeader(bundle)) { removeBundle(bundle); } }
Source:
public HtmlMetacardUtility(String htmlTemplate) { try { this.mimeType = new MimeType("text/html"); } catch (MimeTypeParseException e) { LOGGER.warn("Failed to apply mimetype text/html"); } this.htmlTemplate = htmlTemplate; this.templateLoader = new ClassPathTemplateLoader(); this.templateLoader.setPrefix(TEMPLATE_DIRECTORY); this.templateLoader.setSuffix(TEMPLATE_SUFFIX); this.handlebars = new Handlebars(this.templateLoader); this.resolvers = new ValueResolver[] { FieldValueResolver.INSTANCE, MapValueResolver.INSTANCE, JavaBeanValueResolver.INSTANCE }; this.registerHelpers(); try { this.template = this.handlebars.compile(htmlTemplate); } catch (IOException e) { LOGGER.warn("Failed to compile handlebars template {}", HTML_TEMPLATE, e); } }

Target:
public HtmlMetacardUtility(String htmlTemplate) { this.htmlTemplate = htmlTemplate; this.templateLoader = new ClassPathTemplateLoader(); this.templateLoader.setPrefix(TEMPLATE_DIRECTORY); this.templateLoader.setSuffix(TEMPLATE_SUFFIX); this.handlebars = new Handlebars(this.templateLoader); this.resolvers = new ValueResolver[] { FieldValueResolver.INSTANCE, MapValueResolver.INSTANCE, JavaBeanValueResolver.INSTANCE, MethodValueResolver.INSTANCE }; try { this.template = this.handlebars.compile(htmlTemplate); } catch (IOException e) { LOGGER.warn("Failed to compile handlebars template {}", HTML_TEMPLATE, e); } }
Source:
public static KafkaDestination parse(String uri) { Validate.isTrue(uri.startsWith(SCHEME_KAFKA) || uri.startsWith(SCHEME_SECURE_KAFKA), "Invalid scheme in URI: " + uri); try { uri = URIUtil.decode(uri); } catch (Exception e) { throw new DatastreamRuntimeException("Failed to decode Kafka destination URI: " + uri, e); } URI u = URI.create(uri); String scheme = u.getScheme(); String address = u.getAuthority(); String path = u.getPath(); String topicName; int lastSlash = path.lastIndexOf("/"); if (lastSlash > 0) { address += path.substring(0, lastSlash); topicName = path.substring(lastSlash + 1); } else { topicName = path.substring(1); } long portNo = u.getPort(); Validate.notBlank(address, "Missing zkAddress in URI: " + uri); Validate.notBlank(topicName, "Missing topic name in URI: " + uri); Validate.isTrue(portNo != -1, "Missing port number in URI: " + uri); boolean isSecure = scheme.equals(SCHEME_SECURE_KAFKA); return new KafkaDestination(address, topicName, isSecure); }

Target:
public static KafkaDestination parse(String uri) { Validate.isTrue(uri.startsWith(SCHEME_KAFKA) || uri.startsWith(SCHEME_SECURE_KAFKA), "Invalid scheme in URI: " + uri); try { uri = URIUtil.decode(uri); } catch (Exception e) { throw new DatastreamRuntimeException("Failed to decode Kafka destination URI: " + uri, e); } URI u = URI.create(uri); String scheme = u.getScheme(); String zkAddress = u.getAuthority(); String path = u.getPath(); String topicName; int lastSlash = path.lastIndexOf("/"); if (lastSlash > 0) { zkAddress += path.substring(0, lastSlash); topicName = path.substring(lastSlash + 1); } else { topicName = path.substring(1); } long portNo = u.getPort(); Validate.notBlank(zkAddress, "Missing zkAddress in URI: " + uri); Validate.notBlank(topicName, "Missing topic name in URI: " + uri); Validate.isTrue(portNo != -1, "Missing port number in URI: " + uri); boolean isSecure = scheme.equals(SCHEME_SECURE_KAFKA); return new KafkaDestination(zkAddress, topicName, isSecure); }