auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
for (int i = 0; i < STATE_TABLE.length; i++) { State state = State.values()[i]; float heightFactor = 1.0f; if (state.equals(State.NETWORK_ARROW)) { networkArrowIndex = i; heightFactor = 0.1f; } else if (state.equals(State.UNKNOWN_ARROW)) { unknownNetworkIndex = i; heightFactor = 0.1f; } RGB stateColor = state.rgb; String stateType = state.equals(State.NETWORK_ARROW) || state.equals(State.UNKNOWN_ARROW) ? ITimeEventStyleStrings.linkType() : ITimeEventStyleStrings.stateType(); ImmutableMap<String, Object> styleMap = ImmutableMap.of( StyleProperties.BACKGROUND_COLOR, X11ColorUtils.toHexColor(stateColor.red, stateColor.green, stateColor.blue), StyleProperties.STYLE_NAME, String.valueOf(state.toString()), StyleProperties.HEIGHT, heightFactor, ITimeEventStyleStrings.itemTypeProperty(), stateType); STATE_TABLE[i] = new StateItem(styleMap); }

Target:
for (int i = 0; i < STATE_TABLE.length; i++) { State state = State.values()[i]; float heightFactor = 1.0f; if (state.equals(State.NETWORK_ARROW)) { networkArrowIndex = i; heightFactor = 0.1f; } else if (state.equals(State.UNKNOWN_ARROW)) { unknownNetworkIndex = i; heightFactor = 0.1f; } RGB stateColor = state.rgb; String stateType = state.equals(State.NETWORK_ARROW) || state.equals(State.UNKNOWN_ARROW) ? ITimeEventStyleStrings.linkType() : ITimeEventStyleStrings.stateType(); ImmutableMap<String, Object> styleMap = ImmutableMap.of( StyleProperties.BACKGROUND_COLOR, ColorUtils.toHexColor(stateColor.red, stateColor.green, stateColor.blue), StyleProperties.STYLE_NAME, String.valueOf(state.toString()), StyleProperties.HEIGHT, heightFactor, ITimeEventStyleStrings.itemTypeProperty(), stateType); STATE_TABLE[i] = new StateItem(styleMap); }
Source:
private void readAmount(int numChars) throws IOException { int bytesRead = is.read(buffer, end, Math.min(numChars, buffer.length - end)); if (bytesRead < 0) { throw new IOException(String.format("Reached end of stream.")); } end = end + bytesRead; }

Target:
private void readAmount(int numChars) throws IOException { int bytesRead = reader.read(buffer, end, Math.min(numChars, buffer.length - end)); if (bytesRead < 0) { throw new IOException("Reached end of stream."); } end = end + bytesRead; }
Source:
protected boolean useDirectReplyTo() { if (this.useTemporaryReplyQueues) { if (this.replyAddress != null) { logger.warn("'useTemporaryReplyQueues' is ignored when a 'replyAddress' is provided"); } else { return false; } } if (this.replyAddress == null || Address.AMQ_RABBITMQ_REPLY_TO.equals(this.replyAddress)) { try { return execute(channel -> { channel.queueDeclarePassive(Address.AMQ_RABBITMQ_REPLY_TO); return true; }); } catch (AmqpConnectException | AmqpIOException ex) { Throwable cause = ex; while (cause != null && !(cause instanceof ShutdownSignalException)) { cause = cause.getCause(); } if (cause instanceof ShutdownSignalException) { if (RabbitUtils.isPassiveDeclarationChannelClose((ShutdownSignalException) cause)) { if (logger.isDebugEnabled()) { logger.warn("Broker does not support fast replies via 'amq.rabbitmq.reply-to', temporary " + "queues will be used:" + ex.getMessage() + "."); } this.replyAddress = null; return false; } } if (logger.isDebugEnabled()) { logger.debug("IO error, deferring directReplyTo detection"); } throw ex; } } return false; }

Target:
protected boolean useDirectReplyTo() { if (this.useTemporaryReplyQueues) { if (this.replyAddress != null) { logger.warn("'useTemporaryReplyQueues' is ignored when a 'replyAddress' is provided"); } else { return false; } } if (this.replyAddress == null || Address.AMQ_RABBITMQ_REPLY_TO.equals(this.replyAddress)) { try { return execute(channel -> { channel.queueDeclarePassive(Address.AMQ_RABBITMQ_REPLY_TO); return true; }); } catch (AmqpConnectException | AmqpIOException ex) { Throwable cause = ex; while (cause != null && !(cause instanceof ShutdownSignalException)) { cause = cause.getCause(); } if (cause instanceof ShutdownSignalException) { if (RabbitUtils.isPassiveDeclarationChannelClose((ShutdownSignalException) cause)) { if (logger.isWarnEnabled()) { logger.warn("Broker does not support fast replies via 'amq.rabbitmq.reply-to', temporary " + "queues will be used: " + cause.getMessage() + "."); } this.replyAddress = null; return false; } } if (logger.isDebugEnabled()) { logger.debug("IO error, deferring directReplyTo detection: " + ex.toString()); } throw ex; } } return false; }
Source:
protected void handleMessage(ClientConnection conn, ContextImpl context, ChannelHandlerContext chctx, Object msg) throws Exception { if (msg instanceof HttpObject) { HttpObject obj = (HttpObject) msg; DecoderResult result = obj.decoderResult(); if (result.isFailure()) { conn.handleException(result.cause()); conn.close(); return; } if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) obj; conn.handleResponse(response); return; } if (msg instanceof HttpContent) { HttpContent chunk = (HttpContent) obj; if (chunk.content().isReadable()) { Buffer buff = Buffer.buffer(chunk.content().slice()); conn.handleResponseChunk(buff); } if (chunk instanceof LastHttpContent) { conn.handleResponseEnd((LastHttpContent) chunk); } return; } } else if (msg instanceof WebSocketFrameInternal) { WebSocketFrameInternal frame = (WebSocketFrameInternal) msg; switch (frame.type()) { case BINARY: case CONTINUATION: case TEXT: case PONG: conn.handleWsFrame(frame); break; case PING: WebSocketFrameImpl pong = new WebSocketFrameImpl(FrameType.PONG, frame.getBinaryData()); conn.reportBytesWritten(pong.binaryData().length()); conn.writeToChannel(pong); break; case CLOSE: if (!closeFrameSent) { chctx.writeAndFlush(frame).addListener(ChannelFutureListener.CLOSE); closeFrameSent = true; } break; default: throw new IllegalStateException("Invalid type: " + frame.type()); } return; } throw new IllegalStateException("Invalid object " + msg); }

Target:
protected void handleMessage(ClientConnection conn, ContextImpl context, ChannelHandlerContext chctx, Object msg) throws Exception { if (msg instanceof HttpObject) { HttpObject obj = (HttpObject) msg; DecoderResult result = obj.decoderResult(); if (result.isFailure()) { conn.handleException(result.cause()); conn.close(); return; } if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) obj; conn.handleResponse(response); return; } if (msg instanceof HttpContent) { HttpContent chunk = (HttpContent) obj; if (chunk.content().isReadable()) { Buffer buff = Buffer.buffer(chunk.content().slice()); conn.handleResponseChunk(buff); } if (chunk instanceof LastHttpContent) { conn.handleResponseEnd((LastHttpContent) chunk); } return; } } else if (msg instanceof WebSocketFrameInternal) { WebSocketFrameInternal frame = (WebSocketFrameInternal) msg; switch (frame.type()) { case BINARY: case CONTINUATION: case TEXT: case PONG: conn.handleWsFrame(frame); break; case PING: chctx.writeAndFlush(new PongWebSocketFrame(frame.getBinaryData().copy())); break; case CLOSE: if (!closeFrameSent) { chctx.writeAndFlush(frame).addListener(ChannelFutureListener.CLOSE); closeFrameSent = true; } break; default: throw new IllegalStateException("Invalid type: " + frame.type()); } return; } throw new IllegalStateException("Invalid object " + msg); }
Source:
public String toValue(String string, INode node) throws ValueConverterException { String result = ""; if (string.split(".").length > 0) { for (String str : string.split(".")) { String partResult = idValueConverter.toValue(str, node); result = reassembleString(string, result, str, partResult); } } else { result = idValueConverter.toValue(string, node); } return result; }

Target:
public String toValue(String string, INode node) throws ValueConverterException { QualifiedName name = converter.toQualifiedName(string); QualifiedName result = QualifiedName.EMPTY; for(String str : name.getSegments()){ result = result.append(idValueConverter.toValue(str, node)); } return result.toString(); }
Source:
public CompletableFuture<Map<K, V>> getAllAsync(List<K> keys) { readMetrics.numGetAlls.inc(); Map<K, V> getAllResult = new HashMap<>(cache.getAll(keys)); List<K> missingKeys = lookupCache(keys, getAllResult); if (missingKeys.isEmpty()) { return CompletableFuture.completedFuture(getAllResult); } long startNs = System.nanoTime(); return rdTable.getAllAsync(missingKeys).handle((records, e) -> { if (e != null) { throw new SamzaException("Failed to get records for " + keys, e); } else { if (records != null) { cache.putAll(records.entrySet().stream() .map(r -> new Entry<>(r.getKey(), r.getValue())) .collect(Collectors.toList())); getAllResult.putAll(records); } readMetrics.getAllNs.update(System.nanoTime() - startNs); return getAllResult; } }); }

Target:
public CompletableFuture<Map<K, V>> getAllAsync(List<K> keys) { readMetrics.numGetAlls.inc(); Map<K, V> getAllResult = new HashMap<>(); List<K> missingKeys = lookupCache(keys, getAllResult); if (missingKeys.isEmpty()) { return CompletableFuture.completedFuture(getAllResult); } long startNs = System.nanoTime(); return rdTable.getAllAsync(missingKeys).handle((records, e) -> { if (e != null) { throw new SamzaException("Failed to get records for " + keys, e); } else { if (records != null) { cache.putAll(records.entrySet().stream() .map(r -> new Entry<>(r.getKey(), r.getValue())) .collect(Collectors.toList())); getAllResult.putAll(records); } readMetrics.getAllNs.update(System.nanoTime() - startNs); return getAllResult; } }); }
Source:
protected InputStream getInputStream(Path path) throws IOException { InputStream stream = null; for (; ; ) { try { stream = createFileInputStream(path); } catch (FileNotFoundException e) { if (e.getMessage().endsWith("(Interrupted system call)")) { continue; } else { throw e; } } catch (AccessDeniedException e) { throw new IOException(e.getMessage() + " (Permission denied)", e); } break; } byte[] buf = new byte[1]; int buflen = 0; try { buflen = stream.read(buf, 0, 1); } catch (IOException e) { if (e.getMessage().equals("Is a directory")) { throw new IOException(path.toString() + " (Is a directory)", e); } throw e; } return new SequenceInputStream(new ByteArrayInputStream(buf, 0, buflen), stream); }

Target:
protected InputStream getInputStream(Path path) throws IOException { for (; ; ) { try { return createMaybeProfiledInputStream(path); } catch (FileNotFoundException e) { if (e.getMessage().endsWith("(Interrupted system call)")) { continue; } else { throw e; } } } }
Source:
public static void getAdditionalDeviceImageList(AsyncQuery<List<String>> aQuery, Guid storagePoolId, int osId, Version clusterVersion) { AsyncDataProvider.isFloppySupported(new AsyncQuery<>(isFloppySupported -> { if (isFloppySupported) { getIrsImageList(aQuery, storagePoolId, false, ImageFileType.Floppy, new RepoImageToImageFileNameAsyncConverter()); } }), osId, clusterVersion); }

Target:
public static void getAdditionalDeviceImageList(AsyncQuery<List<String>> aQuery, Guid storagePoolId, int osId, Version clusterVersion) { getIrsImageList(aQuery, storagePoolId, false, ImageFileType.Floppy, new RepoImageToImageFileNameAsyncConverter()); }
Source:
private void ensureSize(int index) { List<@Nullable IEventDeclaration> list = fEvents; if (list instanceof ArrayList) { if (index > 50000) { fEvents = new SparseList(fEvents); } ((ArrayList<@Nullable IEventDeclaration>) list).ensureCapacity(index); while (list.size() <= index) { list.add(null); } } }

Target:
private void ensureSize(int index) { List<@Nullable IEventDeclaration> list = fEvents; if (list instanceof ArrayList) { if (index > 50000) { fEvents = new SparseList(fEvents); return; } ((ArrayList<@Nullable IEventDeclaration>) list).ensureCapacity(index); while (list.size() <= index) { list.add(null); } } }
Source:
public void testSubmit() throws Exception { Service service = connect(); String indexName = temporaryName(); Integer tcpPort = 10000; while (service.getInputs().containsKey(tcpPort.toString())) { tcpPort += 1; } Index index = null; TcpInput input = null; try { index = service.getIndexes().create(indexName); Args args = new Args(); args.add("index", indexName); input = service.getInputs().create(tcpPort.toString(), InputKind.Tcp, args); int nEvents = index.getTotalEventCount(); input.submit(getTimestamp() + " Boris the mad baboon!\r\n"); int nTries = 50; while (nTries > 0) { index.refresh(); if (index.getTotalEventCount() == nEvents + 1) { break; } else { nTries -= 1; Thread.sleep(1000); } } if (nTries == 0) { SplunkTestCase.fail("Timed out before new events were found in index."); } } finally { if (index != null && service.versionCompare("5.0") >= 0) { index.remove(); } if (input != null) { input.remove(); } } }

Target:
public void testSubmit() throws Exception { Service service = connect(); String indexName = temporaryName(); int tcpPort = findNextUnusedTcpPort(service, 10000); Index index = null; TcpInput input = null; try { index = service.getIndexes().create(indexName); Args args = new Args(); args.add("index", indexName); input = service.getInputs().create(String.valueOf(tcpPort), InputKind.Tcp, args); int nEvents = index.getTotalEventCount(); input.submit(createTimestamp() + " Boris the mad baboon!\r\n"); int nTries = 50; while (nTries > 0) { index.refresh(); if (index.getTotalEventCount() == nEvents + 1) { break; } else { nTries -= 1; Thread.sleep(1000); } } if (nTries == 0) { SplunkTestCase.fail("Timed out before new events were found in index."); } } finally { if (index != null && service.versionCompare("5.0") >= 0) { index.remove(); } if (input != null) { input.remove(); } } }
Source:
public void visitNode(Tree tree) { VariableTree varTree = (VariableTree) tree; int varLineCurrent = varTree.endToken().line(); if (varLineCurrent == varLineLast) { varsOnSameLine.add(varTree.symbol().name()); } else { if (!varsOnSameLine.isEmpty()) { addIssue(varLineLast, String.format("Declare \"%s\" on a separate line.", StringUtils.join(varsOnSameLine, "\", \""))); } varLineLast = varLineCurrent; varsOnSameLine.clear(); } }

Target:
public void visitNode(Tree tree) { if (tree instanceof ClassTree) { for (Tree member : ((ClassTree) tree).members()) { if (member.is(Tree.Kind.VARIABLE)) { checkVariable((VariableTree) member); } } } if (tree instanceof BlockTree) { for (StatementTree statment : ((BlockTree) tree).body()) { if (statment.is(Tree.Kind.VARIABLE)) { checkVariable((VariableTree) statment); } } } }
Source:
public Vote[] getPredictionVotes() { Attribute classAttribute = this.lastSeenInstance.dataset().classAttribute(); double trueValue = this.lastSeenInstance.classValue(); List<String> classAttributeValues = classAttribute.getAttributeValues(); int trueNominalIndex = (int) trueValue; String trueNominalValue = classAttributeValues.get(trueNominalIndex); Vote[] votes = new Vote[classAttributeValues.size() + 3]; votes[0] = new Vote("instance number", this.instanceIdentifier); votes[1] = new Vote("true class value", trueNominalValue); votes[2] = new Vote("predicted class value", classAttributeValues.get(Utils.maxIndex(classVotes))); for (int i = 0; i < classAttributeValues.size(); i++) { if (i < classVotes.length) { votes[3 + i] = new Vote("votes_" + classAttributeValues.get(i), classVotes[i], 10); } else { votes[3 + i] = new Vote("votes_" + classAttributeValues.get(i), 0); } } return votes; }

Target:
public Vote[] getPredictionVotes() { Attribute classAttribute = this.lastSeenInstance.dataset().classAttribute(); double trueValue = this.lastSeenInstance.classValue(); List<String> classAttributeValues = classAttribute.getAttributeValues(); int trueNominalIndex = (int) trueValue; String trueNominalValue = classAttributeValues.get(trueNominalIndex); if (votes == null) { this.votes = new Vote[classAttributeValues.size() + 3]; votes[0] = new Vote("instance number"); votes[1] = new Vote("true class value"); votes[2] = new Vote("predicted class value"); for (int i = 0; i < classAttributeValues.size(); i++) { votes[3 + i] = new Vote("votes_" + classAttributeValues.get(i)); } } votes[0].setValue(this.instanceIdentifier); votes[1].setValue(trueNominalValue); votes[2].setValue(classAttributeValues.get(Utils.maxIndex(classVotes))); for (int i = 0; i < classAttributeValues.size(); i++) { if (i < classVotes.length) { votes[3 + i].setValue(classVotes[i], this.DECIMAL_PLACES); } else { votes[3 + i].setValue(this.NO_VOTE_FOR_CLASS, 0); } } return votes; }
Source:
private CommandResponse executeSimpleCommandWithResponse(String command, boolean sensitive) throws IOException, MessagingException { List<String> results = new ArrayList<String>(); if (command != null) { writeLine(command, sensitive); } String line = readCommandResponseLine(results); int length = line.length(); if (length < 1) { throw new MessagingException("SMTP response is 0 length"); } int replyCode = -1; String message = line; if (length >= 3) { try { replyCode = Integer.parseInt(line.substring(0, 3)); } catch (NumberFormatException e) { } if (length > 4) { message = line.substring(4); } else { message = ""; } } char c = line.charAt(0); if ((c == '4') || (c == '5')) { throw new NegativeSmtpReplyException(replyCode, message); } return new CommandResponse(replyCode, message); }

Target:
private CommandResponse executeSimpleCommandWithResponse(String command, boolean sensitive) throws IOException, MessagingException { List<String> results = new ArrayList<>(); if (command != null) { writeLine(command, sensitive); } String line = readCommandResponseLine(results); int length = line.length(); if (length < 1) { throw new MessagingException("SMTP response is 0 length"); } int replyCode = -1; String message = line; if (length >= 3) { try { replyCode = Integer.parseInt(line.substring(0, 3)); } catch (NumberFormatException e) { } if (length > 4) { message = line.substring(4); } else { message = ""; } } char c = line.charAt(0); if ((c == '4') || (c == '5')) { throw new NegativeSmtpReplyException(replyCode, message); } return new CommandResponse(replyCode, message); }
Source:
public void testServerEnvElements() throws Exception { File in = new File(CONFIG_XML); FileInputStream input = new FileInputStream(in); DocumentBuilderFactory inputBuilderFactory = DocumentBuilderFactory.newInstance(); inputBuilderFactory.setIgnoringComments(true); inputBuilderFactory.setCoalescing(true); inputBuilderFactory.setIgnoringElementContentWhitespace(true); inputBuilderFactory.setValidating(false); DocumentBuilder inputBuilder = inputBuilderFactory.newDocumentBuilder(); Document inputDoc = inputBuilder.parse(input); XPath xPath = XPathFactory.newInstance().newXPath(); String expression = "/liberty-plugin-config/serverEnv/text()"; String nodeValue = (String) xPath.compile(expression).evaluate(inputDoc, XPathConstants.STRING); File f1 = new File(SOURCE_SERVER_ENV); File f2 = new File(nodeValue); Assert.assertEquals("serverEnv value", f1.getAbsolutePath(), f2.getAbsolutePath()); Assert.assertEquals("verify target server server.env", FileUtils.fileRead(f2), FileUtils.fileRead(TARGET_SERVER_ENV)); }

Target:
public void testServerEnvElements() throws Exception { File in = new File(CONFIG_XML); FileInputStream input = new FileInputStream(in); DocumentBuilderFactory inputBuilderFactory = DocumentBuilderFactory.newInstance(); inputBuilderFactory.setIgnoringComments(true); inputBuilderFactory.setCoalescing(true); inputBuilderFactory.setIgnoringElementContentWhitespace(true); inputBuilderFactory.setValidating(false); DocumentBuilder inputBuilder = inputBuilderFactory.newDocumentBuilder(); Document inputDoc = inputBuilder.parse(input); XPath xPath = XPathFactory.newInstance().newXPath(); String expression = "/liberty-plugin-config/serverEnv/text()"; String nodeValue = (String) xPath.compile(expression).evaluate(inputDoc, XPathConstants.STRING); File f1 = new File(SOURCE_SERVER_ENV); File f2 = new File(nodeValue); assertEquals("serverEnv value", f1.getAbsolutePath(), f2.getAbsolutePath()); assertEquals("verify target server server.env", FileUtils.fileRead(f2), FileUtils.fileRead(TARGET_SERVER_ENV)); }
Source:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (extras != null) { mAppWidgetId = extras.getInt( AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); } setResult(RESULT_CANCELED, new Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId)); if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) { finish(); return; } if (!AccountHelper.isSignedIn()) { ToastUtils.showToast(getBaseContext(), R.string.stats_widget_error_no_account, ToastUtils.Duration.LONG); finish(); return; } List<Map<String, Object>> accounts = WordPress.wpDB.getBlogsBy("isHidden = 0", null); if (accounts.size() == 0) { ToastUtils.showToast(getBaseContext(), R.string.stats_widget_error_no_visible_blog, ToastUtils.Duration.LONG); finish(); return; } if (accounts.size() == 1) { Map<String, Object> account = accounts.get(0); Integer localID = (Integer) account.get("id"); addWidgetToScreenAndFinish(localID); return; } setContentView(R.layout.site_picker_activity); final boolean isInSearchMode = false; String lastSearch = ""; setNewAdapter(lastSearch, isInSearchMode); setupActionBar(); setupRecycleView(); }

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (extras != null) { mAppWidgetId = extras.getInt( AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); } setResult(RESULT_CANCELED, new Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId)); if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) { finish(); return; } if (!AccountHelper.isSignedIn()) { ToastUtils.showToast(getBaseContext(), R.string.stats_widget_error_no_account, ToastUtils.Duration.LONG); finish(); return; } List<Map<String, Object>> accounts = WordPress.wpDB.getBlogsBy("isHidden = 0", null); if (accounts.size() == 0) { ToastUtils.showToast(getBaseContext(), R.string.stats_widget_error_no_visible_blog, ToastUtils.Duration.LONG); finish(); return; } if (accounts.size() == 1) { Map<String, Object> account = accounts.get(0); Integer localID = (Integer) account.get("id"); addWidgetToScreenAndFinish(localID); return; } setContentView(R.layout.stats_widget_config_activity); setNewAdapter(); setupActionBar(); setupRecycleView(); }
Source:
public BlobAsyncClient buildBlobAsyncClient() { Objects.requireNonNull(containerName); Objects.requireNonNull(blobName); HttpPipeline pipeline = super.getPipeline(); if (pipeline == null) { pipeline = super.buildPipeline(); } return new BlobAsyncClient(new AzureBlobStorageBuilder() .url(String.format("%s/%s/%s", endpoint, containerName, blobName)) .pipeline(pipeline) .build(), snapshot, cpk); }

Target:
public BlobAsyncClient buildBlobAsyncClient() { Objects.requireNonNull(containerName, "'containerName' cannot be null."); Objects.requireNonNull(blobName, "'blobName' cannot be null."); HttpPipeline pipeline = super.getPipeline(); if (pipeline == null) { pipeline = super.buildPipeline(); } return new BlobAsyncClient(new AzureBlobStorageBuilder() .url(String.format("%s/%s/%s", endpoint, containerName, blobName)) .pipeline(pipeline) .build(), snapshot, customerProvidedKey); }
Source:
private Map<String, IPath> importAsBinary(IProject project, IPluginModelBase model, IProgressMonitor monitor) throws CoreException { try { SubMonitor subMonitor = SubMonitor.convert(monitor, "", 4); File srcFile = new File(model.getInstallLocation()); if (isJARd(model)) { PluginImportHelper.copyArchive(srcFile, project.getFile(srcFile.getName()), subMonitor.newChild(1)); } else { PluginImportHelper.importContent(new File(model.getInstallLocation()), project.getFullPath(), FileSystemStructureProvider.INSTANCE, null, subMonitor.newChild(1)); } Map<String, IPath> sourceMap = importSourceArchives(project, model, IMPORT_BINARY, subMonitor.newChild(1)); importAdditionalSourceFiles(project, model, subMonitor.newChild(1)); importRequiredPluginFiles(project, model, subMonitor.newChild(1)); modifyBundleClasspathHeader(project, model); RepositoryProvider.map(project, PDECore.BINARY_REPOSITORY_PROVIDER); project.setPersistentProperty(PDECore.EXTERNAL_PROJECT_PROPERTY, PDECore.BINARY_PROJECT_VALUE); return sourceMap; } finally { monitor.done(); } }

Target:
private Map<String, IPath> importAsBinary(IProject project, IPluginModelBase model, IProgressMonitor monitor) throws CoreException { SubMonitor subMonitor = SubMonitor.convert(monitor, 4); File srcFile = new File(model.getInstallLocation()); if (isJARd(model)) { PluginImportHelper.copyArchive(srcFile, project.getFile(srcFile.getName()), subMonitor.newChild(1)); } else { PluginImportHelper.importContent(new File(model.getInstallLocation()), project.getFullPath(), FileSystemStructureProvider.INSTANCE, null, subMonitor.newChild(1)); } Map<String, IPath> sourceMap = importSourceArchives(project, model, IMPORT_BINARY, subMonitor.newChild(1)); importAdditionalSourceFiles(project, model, subMonitor.newChild(1)); importRequiredPluginFiles(project, model, subMonitor.newChild(1)); modifyBundleClasspathHeader(project, model); RepositoryProvider.map(project, PDECore.BINARY_REPOSITORY_PROVIDER); project.setPersistentProperty(PDECore.EXTERNAL_PROJECT_PROPERTY, PDECore.BINARY_PROJECT_VALUE); return sourceMap; }
Source:
public Issue getIssue(final PullRequest pullRequest) throws NotFoundException, MalformedURLException { Objects.requireNonNull(pullRequest, "url cannot be null"); checkIssueTrackerExists(); final String body = pullRequest.getBody(); final String[] url = extractURLs(body, ISSUE, false); if (url == null || url.length == 0 || url[0] == null) return null; else return getIssue(new URL(url[0])); }

Target:
public Issue getIssue(final PullRequest pullRequest) throws NotFoundException, MalformedURLException { Objects.requireNonNull(pullRequest, "pull request cannot be null"); checkIssueTrackerExists(); final String body = pullRequest.getBody(); final String[] url = extractURLs(body, ISSUE, false); if (url == null || url.length == 0 || url[0] == null) return null; else return getIssue(new URL(url[0])); }
Source:
EWAHCompressedBitmap getBitmap() { Object r = bitmapContainer; if (r instanceof EWAHCompressedBitmap) return (EWAHCompressedBitmap) r; XorCompressedBitmap xb = (XorCompressedBitmap) r; EWAHCompressedBitmap out = xb.bitmap; while (true) { r = xb.xorBitmap.bitmapContainer; if (r instanceof EWAHCompressedBitmap) { bitmapContainer = out = out.xor((EWAHCompressedBitmap) r); return out; } xb = (XorCompressedBitmap) r; out = out.xor(xb.bitmap); } }

Target:
EWAHCompressedBitmap getBitmap() { Object r = bitmapContainer; if (r instanceof EWAHCompressedBitmap) return (EWAHCompressedBitmap) r; XorCompressedBitmap xb = (XorCompressedBitmap) r; EWAHCompressedBitmap out = xb.bitmap; for (;;) { r = xb.xorBitmap.bitmapContainer; if (r instanceof EWAHCompressedBitmap) { out = out.xor((EWAHCompressedBitmap) r); bitmapContainer = out; return out; } xb = (XorCompressedBitmap) r; out = out.xor(xb.bitmap); } }
Source:
private RbAclAccessRolesProvider getAccessRolesProvider() { return accessRolesProvider; }

Target:
private AccessRolesProvider getAccessRolesProvider() { return accessRolesProvider; }
Source:
public void handleLightStatus(StateResponse packet) { DecimalType hue = new DecimalType(packet.getHue() * 360 / 65535.0f); PercentType saturation = new PercentType(Math.round((packet.getSaturation() / 65535.0f) * 100)); PercentType brightness = new PercentType(Math.round((packet.getBrightness() / 65535.0f) * 100)); DecimalType temperature = new DecimalType(packet.getKelvin()); currentColorState = new HSBType(hue, saturation, brightness); currentPowerState = packet.getPower(); currentTempState = temperature; if (currentPowerState == PowerState.OFF) { updateState(CHANNEL_COLOR, OnOffType.OFF); } else if (currentColorState != null) { updateState(CHANNEL_COLOR, currentColorState); } else { updateState(CHANNEL_COLOR, OnOffType.ON); } updateState(CHANNEL_TEMPERATURE, temperature); updateStatus(ThingStatus.ONLINE); }

Target:
public void handleLightStatus(StateResponse packet) { DecimalType hue = new DecimalType(packet.getHue() * 360 / 65535.0f); PercentType saturation = new PercentType(Math.round((packet.getSaturation() / 65535.0f) * 100)); PercentType brightness = new PercentType(Math.round((packet.getBrightness() / 65535.0f) * 100)); PercentType temperature = new PercentType(toPercent(packet.getKelvin())); currentColorState = new HSBType(hue, saturation, brightness); currentPowerState = packet.getPower(); currentTempState = temperature; if (currentPowerState == PowerState.OFF) { updateState(CHANNEL_COLOR, new HSBType(hue, saturation, PercentType.ZERO)); updateState(CHANNEL_BRIGHTNESS, PercentType.ZERO); } else if (currentColorState != null) { updateState(CHANNEL_COLOR, currentColorState); updateState(CHANNEL_BRIGHTNESS, currentColorState.getBrightness()); } else { updateState(CHANNEL_COLOR, new HSBType(hue, saturation, PercentType.HUNDRED)); updateState(CHANNEL_BRIGHTNESS, PercentType.HUNDRED); } updateState(CHANNEL_TEMPERATURE, temperature); updateStatus(ThingStatus.ONLINE); }
Source:
private void checkAccess(Run<?, ?> run, KubernetesCloud kubernetesCloud) throws AbortException { if(kubernetesCloud.isUsageRestricted()) { Job<?, ?> job = run.getParent(); LOGGER.info("Job:" + job); LOGGER.info("JobStr: " + ReflectionToStringBuilder.toString(job)); ItemGroup<?> parent = job.getParent(); Set<String> allowedClouds = new HashSet<>(); if(parent instanceof Folder) { Folder folder = (Folder) parent; LOGGER.info("Job in Folder: " + folder.getName()); collectAllowedClouds(allowedClouds, folder); } else { LOGGER.info("Job not associated with Folder"); } if(! allowedClouds.contains(kubernetesCloud.name)) { throw new AbortException(String.format("Not authorized to use Kubernetes cloud: %s", step.getCloud())); } LOGGER.fine("Verification succeeded for cloud: " + step.getCloud()); } }

Target:
private void checkAccess(Run<?, ?> run, KubernetesCloud kubernetesCloud) throws AbortException { Job<?, ?> job = run.getParent(); ItemGroup<?> parent = job.getParent(); Set<String> allowedClouds = new HashSet<>(); KubernetesFolderProperty.collectAllowedClouds(allowedClouds, parent); if (!allowedClouds.contains(kubernetesCloud.name)) { throw new AbortException(String.format("Not authorized to use Kubernetes cloud: %s", step.getCloud())); } }
Source:
public void testAddIncompleteParameters() throws Exception { Cluster model = new Cluster(); model.setName(NAMES[0]); setUriInfo(setUpBasicUriExpectations()); control.replay(); try { collection.add(model); fail("expected WebApplicationException on incomplete parameters"); } catch (WebApplicationException wae) { verifyIncompleteException(wae, "Cluster", "add", "dataCenter.name|id"); } }

Target:
public void testAddIncompleteParameters() throws Exception { Cluster model = new Cluster(); setUriInfo(setUpBasicUriExpectations()); control.replay(); try { collection.add(model); fail("expected WebApplicationException on incomplete parameters"); } catch (WebApplicationException wae) { verifyIncompleteException(wae, "Cluster", "add", "name"); } }
Source:
public Image changeDpi(URI sourceUri, int dpi) throws IOException { if (!new File(sourceUri).exists()) { throw new FileNotFoundException("sourceUri must exist: " + sourceUri.getRawPath()); } if (dpi <= 0) { throw new IllegalArgumentException("dpi must be > 0, but was " + Integer.toString(dpi)); } File tempFile = File.createTempFile("dpiChangedImage-", RAW_IMAGE_FORMAT, TMPDIR); try { tempFile.deleteOnExit(); URI imageUri = tempFile.toURI(); ImageConverter imageConverter = new ImageConverter(sourceUri); imageConverter.addResult(imageUri).resizeToDpi(dpi); logger.info("Resizing as to DPI", sourceUri, tempFile, dpi); imageConverter.run(); logger.trace("Loading {}", tempFile); Image buffer = ImageIO.read(tempFile); logger.trace("{} successfully loaded", tempFile); return buffer; } finally { logger.debug("Deleting {}", tempFile); tempFile.delete(); logger.trace("Successfully deleted {}", tempFile); } }

Target:
public Image changeDpi(URI sourceUri, int dpi) throws IOException { if (!new File(sourceUri).exists()) { throw new FileNotFoundException("sourceUri must exist: " + sourceUri.getRawPath()); } if (dpi <= 0) { throw new IllegalArgumentException("dpi must be > 0, but was " + Integer.toString(dpi)); } return summarize("dpiChangedImage-", RAW_IMAGE_FORMAT, sourceUri, λ -> λ.resizeToDpi(dpi), "Resizing as to DPI", dpi); }
Source:
public void testInt3166GroovyScriptExecutingMessageProcessorPerformance() throws Exception { final Message<?> message = new GenericMessage<Object>("test"); ScriptSource scriptSource = new StaticScriptSource("Thread.sleep(100)", Script.class.getName()); final MessageProcessor<Object> processor = new GroovyScriptExecutingMessageProcessor(scriptSource); StopWatch stopWatch = new StopWatch(); stopWatch.start(); ExecutorService executor = Executors.newFixedThreadPool(10); for (int i = 0; i < 10; i++) { executor.execute(new Runnable() { @Override public void run() { processor.processMessage(message); } }); } executor.shutdown(); assertTrue(executor.awaitTermination(2, TimeUnit.SECONDS)); stopWatch.stop(); assertThat(stopWatch.getTotalTimeMillis(), Matchers.lessThan(1000L)); }

Target:
public void testInt3166GroovyScriptExecutingMessageProcessorPerformance() throws Exception { final Message<?> message = new GenericMessage<Object>("test"); final AtomicInteger var1 = new AtomicInteger(); final AtomicInteger var2 = new AtomicInteger(); String script = "var1.incrementAndGet(); Thread.sleep(100); var2.set(Math.max(var1.get(), var2.get())); var1.decrementAndGet()"; ScriptSource scriptSource = new StaticScriptSource(script, Script.class.getName()); final MessageProcessor<Object> processor = new GroovyScriptExecutingMessageProcessor(scriptSource, new ScriptVariableGenerator() { @Override public Map<String, Object> generateScriptVariables(Message<?> message) { Map<String, Object> variables = new HashMap<String, Object>(2); variables.put("var1", var1); variables.put("var2", var2); return variables; } }); ExecutorService executor = Executors.newFixedThreadPool(10); for (int i = 0; i < 10; i++) { executor.execute(new Runnable() { @Override public void run() { processor.processMessage(message); } }); } executor.shutdown(); assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS)); assertTrue(var2.get() > 1); }
Source:
public MetricData getDatapointsForRange(Locator locator, Range range, Granularity gran) { RollupType rollupType = null; String rollupTypeStr = metaCache.safeGet(locator, rollupTypeCacheKey); if ( rollupTypeStr != null ) { rollupType = RollupType.fromString(rollupTypeStr); } if ( rollupType == null ) { rollupType = RollupType.BF_BASIC; } return getNumericMetricDataForRange(locator, range, gran, rollupType); }

Target:
public MetricData getDatapointsForRange(Locator locator, Range range, Granularity gran) { RollupType rollupType = RollupType.BF_BASIC; String rollupTypeStr = metaCache.safeGet(locator, rollupTypeCacheKey); if ( rollupTypeStr != null ) { rollupType = RollupType.fromString(rollupTypeStr); } return getNumericMetricDataForRange(locator, range, gran, rollupType); }
Source:
protected void testWithNbFiles(int nbDocs) throws IOException, OperationException, InterruptedException { DocumentModelList docs = new DocumentModelListImpl(); for (int i = 0; i < nbDocs; i++) { DocumentModel doc = session.createDocumentModel("/", "TestFile" + i, "File"); doc.setProperty("dublincore", "title", "TestTitle" + i); Blob blob1 = Blobs.createBlob("test" + i); String blobFilename = "test" + i + ".txt"; blob1.setFilename(blobFilename); BlobHolder bh1 = doc.getAdapter(BlobHolder.class); bh1.setBlob(blob1); doc = session.createDocument(doc); session.save(); docs.add(doc); } TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); OperationChain chain = new OperationChain("test-chain"); chain.add(BulkDownload.ID); OperationContext ctx = new OperationContext(session); ctx.setInput(docs); Blob resultBlob = (Blob) automationService.run(ctx, BulkDownload.ID); assertNotNull(resultBlob); awaitZipWorks(); if (resultBlob instanceof AsyncBlob) { TransientStoreService tss = Framework.getService(TransientStoreService.class); TransientStore ts = tss.getStore(DownloadService.TRANSIENT_STORE_STORE_NAME); List<Blob> blobs = ts.getBlobs(((AsyncBlob) resultBlob).getKey()); assertNotNull(blobs); assertEquals(1, blobs.size()); resultBlob = blobs.get(0); assertTrue(resultBlob instanceof FileBlob); } assertTrue(resultBlob.getLength() > 0); assertEquals("application/zip", resultBlob.getMimeType()); try (CloseableFile source = resultBlob.getCloseableFile()) { try (ZipFile zip = new ZipFile(source.getFile())) { assertEquals(nbDocs, zip.size()); } } }

Target:
protected void testWithNbFiles(int nbDocs) throws IOException, OperationException, InterruptedException { DocumentModelList docs = new DocumentModelListImpl(); for (int i = 0; i < nbDocs; i++) { DocumentModel doc = session.createDocumentModel("/", "TestFile" + i, "File"); doc.setProperty("dublincore", "title", "TestTitle" + i); Blob blob1 = Blobs.createBlob("test" + i); String blobFilename = "test" + i + ".txt"; blob1.setFilename(blobFilename); BlobHolder bh1 = doc.getAdapter(BlobHolder.class); bh1.setBlob(blob1); doc = session.createDocument(doc); session.save(); docs.add(doc); } coreFeature.waitForAsyncCompletion(); OperationChain chain = new OperationChain("test-chain"); chain.add(BulkDownload.ID); OperationContext ctx = new OperationContext(session); ctx.setInput(docs); Blob resultBlob = (Blob) automationService.run(ctx, BulkDownload.ID); assertNotNull(resultBlob); coreFeature.waitForAsyncCompletion(); if (resultBlob instanceof AsyncBlob) { TransientStoreService tss = Framework.getService(TransientStoreService.class); TransientStore ts = tss.getStore(DownloadService.TRANSIENT_STORE_STORE_NAME); List<Blob> blobs = ts.getBlobs(((AsyncBlob) resultBlob).getKey()); assertNotNull(blobs); assertEquals(1, blobs.size()); resultBlob = blobs.get(0); assertTrue(resultBlob instanceof FileBlob); } assertTrue(resultBlob.getLength() > 0); assertEquals("application/zip", resultBlob.getMimeType()); try (CloseableFile source = resultBlob.getCloseableFile()) { try (ZipFile zip = new ZipFile(source.getFile())) { assertEquals(nbDocs, zip.size()); } } }
Source:
private int compareOrdered(final NakadiCursor c1, final NakadiCursor c2) { if (!c2.isInitial()) { return -1; } Iterator<Timeline> timelineIterator = null; NakadiCursor first = c1; if (first.getTimeline().getLatestPosition() == null) { timelineIterator = createTimelinesIterator(first.getEventType(), first.getTimeline().getOrder()); first = NakadiCursor.of(timelineIterator.next(), first.getPartition(), first.getOffset()); } while (first.getTimeline().getOrder() != c2.getTimeline().getOrder()) { final boolean isFirstAtEndOfTimeline = first.isLast(); if (!isFirstAtEndOfTimeline) { return -1; } if (null == timelineIterator) { timelineIterator = createTimelinesIterator(first.getEventType(), first.getTimeline().getOrder() + 1); } final Timeline nextTimeline = timelineIterator.next(); final String initialOffset = StaticStorageWorkerFactory.get(nextTimeline).getBeforeFirstOffset(); first = NakadiCursor.of(nextTimeline, first.getPartition(), initialOffset); } return first.getOffset().compareTo(c2.getOffset()); }

Target:
private int compareOrdered(final NakadiCursor c1, final NakadiCursor c2) { if (!c2.isInitial()) { return -1; } Iterator<Timeline> timelineIterator = null; NakadiCursor first = c1; if (first.getTimeline().getLatestPosition() == null) { timelineIterator = createTimelinesIterator(first.getEventType(), first.getTimeline().getOrder()); first = NakadiCursor.of(timelineIterator.next(), first.getPartition(), first.getOffset()); } while (first.getTimeline().getOrder() != c2.getTimeline().getOrder()) { if (!first.isLast()) { return -1; } if (null == timelineIterator) { timelineIterator = createTimelinesIterator(first.getEventType(), first.getTimeline().getOrder() + 1); } final Timeline nextTimeline = timelineIterator.next(); final String initialOffset = StaticStorageWorkerFactory.get(nextTimeline).getBeforeFirstOffset(); first = NakadiCursor.of(nextTimeline, first.getPartition(), initialOffset); } return first.getOffset().compareTo(c2.getOffset()); }
Source:
public List<AttributeStatement> createEvidenceStatements(final List accessConstentValues, final List evidenceInstanceAccessConsentValues) { List<AttributeStatement> statements; if (CollectionUtils.isEmpty(accessConstentValues)) { LOG.debug("No Access Consent found for Evidence"); } if (CollectionUtils.isEmpty(evidenceInstanceAccessConsentValues)) { LOG.debug("No Instance Access Consent found for Evidence"); } statements = OpenSAML2ComponentBuilder.getInstance().createEvidenceStatements(accessConstentValues, evidenceInstanceAccessConsentValues, NHIN_NS); LOG.trace("SamlCallbackHandler.createEvidenceStatements() -- End"); return statements; }

Target:
public List<AttributeStatement> createEvidenceStatements(final List accessConstentValues, final List evidenceInstanceAccessConsentValues) { List<AttributeStatement> statements; statements = OpenSAML2ComponentBuilder.getInstance().createEvidenceStatements(accessConstentValues, evidenceInstanceAccessConsentValues, NHIN_NS); LOG.trace("SamlCallbackHandler.createEvidenceStatements() -- End"); return statements; }
Source:
public void andWaitForSuccess() { task.getUnchecked(); }

Target:
public T andWaitForSuccess() { return task.getUnchecked(); }
Source:
public void restoreDefaults(Organization organization) { final Organization persistedOrg = organizationRepo.findOne(organization.getId()); Organization parentOrg = organizationRepo.findOne(organization.getParentOrganization().getId()); persistedOrg.getAggregateWorkflowSteps().clear(); parentOrg.getAggregateWorkflowSteps().forEach(ws -> { persistedOrg.addAggregateWorkflowStep(ws); }); organizationRepo.save(persistedOrg); }

Target:
public Organization restoreDefaults(Organization organization) { Organization persistedOrg = organizationRepo.findOne(organization.getId()); Organization parentOrg = organizationRepo.findOne(organization.getParentOrganization().getId()); persistedOrg.clearAggregatedWorkflowStepsFromHiarchy(); parentOrg.getAggregateWorkflowSteps().forEach(ws -> { persistedOrg.addAggregateWorkflowStep(ws); }); return organizationRepo.save(persistedOrg); }
Source:
public int run(String[] arg0) throws Exception { final int port = getConf().getInt(TRACE_SERVER_HTTP_PORT_KEY, DEFAULT_HTTP_PORT); BasicConfigurator.configure(); final String home = getConf().get(TRACE_SERVER_HTTP_JETTY_HOME_KEY, DEFAULT_HTTP_HOME); Server server = new Server(port); ProtectionDomain domain = Main.class.getProtectionDomain(); URL location = domain.getCodeSource().getLocation(); WebAppContext webapp = new WebAppContext(); webapp.setContextPath("/"); if (home.length() != 0) { webapp.setTempDirectory(new File(home)); } String warPath = location.toString().split("target")[0] + "build/trace-webapp-demo.war"; webapp.setWar(warPath); server.setHandler(webapp); server.start(); server.join(); return 0; }

Target:
public int run(String[] arg0) throws Exception { final int port = getConf().getInt(TRACE_SERVER_HTTP_PORT_KEY, DEFAULT_HTTP_PORT); BasicConfigurator.configure(); final String home = getConf().get(TRACE_SERVER_HTTP_JETTY_HOME_KEY, DEFAULT_HTTP_HOME); ProtectionDomain domain = Main.class.getProtectionDomain(); URL location = domain.getCodeSource().getLocation(); String webappDirLocation = location.toString().split("target")[0] +"src/main/webapp"; Server server = new Server(port); WebAppContext root = new WebAppContext(); root.setContextPath(home); root.setDescriptor(webappDirLocation + "/WEB-INF/web.xml"); root.setResourceBase(webappDirLocation); root.setParentLoaderPriority(true); server.setHandler(root); server.start(); server.join(); return 0; }
Source:
public PendingIntent createPendingIntent(Context context, int pendingIntentId, Intent intent) { return PendingIntent.getService(context, 0, intent, 0); }

Target:
public PendingIntent createPendingIntent(Context context, int pendingIntentId, Intent intent) { return PendingIntent.getService(context, pendingIntentId, intent, 0); }
Source:
public static ByteRange fromStartOffset(long startOffset) throws InvalidByteRangeException { if (startOffset < 0) { throw new InvalidByteRangeException(startOffset, UNDEFINED_OFFSET); } return new ByteRange(startOffset, UNDEFINED_OFFSET, ByteRangeType.FROM_START_OFFSET); }

Target:
public static ByteRange fromStartOffset(long startOffset) { if (startOffset < 0) { throw new IllegalArgumentException("Invalid range offsets provided for ByteRange; startOffset=" + startOffset); } return new ByteRange(startOffset, UNDEFINED_OFFSET, ByteRangeType.FROM_START_OFFSET); }
Source:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) { FailureCollector collector = pipelineConfigurer.getStageConfigurer().getFailureCollector(); config.validate(collector); collector.getOrThrowException(); if (config.containsMacro(NAME_FORMAT)) { for (FileFormat f: FileFormat.values()) { try { pipelineConfigurer.usePlugin(ValidatingInputFormat.PLUGIN_TYPE, f.name().toLowerCase(), f.name().toLowerCase(), config.getRawProperties()); } catch (InvalidPluginConfigException e) { LOG.warn("Failed to register format '{}', which means it cannot be used when the pipeline is run." + "Missing properties: {}, invalid properties: {}", f.name(), e.getMissingProperties(), e.getInvalidProperties()); } } return; } FileFormat fileFormat = config.getFormat(); Schema schema = null; ValidatingInputFormat validatingInputFormat = pipelineConfigurer.usePlugin(ValidatingInputFormat.PLUGIN_TYPE, fileFormat.name().toLowerCase(), fileFormat.name().toLowerCase(), config.getRawProperties()); FormatContext context = new FormatContext(collector, null); validateInputFormatProvider(context, fileFormat, validatingInputFormat); if (validatingInputFormat != null) { schema = validatingInputFormat.getSchema(context); } validatePathField(collector, schema); pipelineConfigurer.getStageConfigurer().setOutputSchema(schema); }

Target:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) { FailureCollector collector = pipelineConfigurer.getStageConfigurer().getFailureCollector(); config.validate(collector); collector.getOrThrowException(); if (config.containsMacro(NAME_FORMAT)) { for (FileFormat f: FileFormat.values()) { try { pipelineConfigurer.usePlugin(ValidatingInputFormat.PLUGIN_TYPE, f.name().toLowerCase(), f.name().toLowerCase(), config.getRawProperties()); } catch (InvalidPluginConfigException e) { LOG.warn("Failed to register format '{}', which means it cannot be used when the pipeline is run. " + "Missing properties: {}, invalid properties: {}", f.name(), e.getMissingProperties(), e.getInvalidProperties().stream().map(InvalidPluginProperty::getName).collect(Collectors.toList())); } } return; } FileFormat fileFormat = config.getFormat(); Schema schema = null; ValidatingInputFormat validatingInputFormat = pipelineConfigurer.usePlugin(ValidatingInputFormat.PLUGIN_TYPE, fileFormat.name().toLowerCase(), fileFormat.name().toLowerCase(), config.getRawProperties()); FormatContext context = new FormatContext(collector, null); validateInputFormatProvider(context, fileFormat, validatingInputFormat); if (validatingInputFormat != null) { schema = validatingInputFormat.getSchema(context); } validatePathField(collector, schema); pipelineConfigurer.getStageConfigurer().setOutputSchema(schema); }
Source:
private static List<String> loadFromResources(String fileName) { try { Path resource = Paths.get(LicenseChecker.class.getResource("/" + fileName).toURI()); List<String> result = Files .readAllLines(resource) .stream() .filter(line -> !line.startsWith("#") && !line.isEmpty()) .collect(Collectors.toList()); LOG.debug("Loaded items from resource {}", result.size(), fileName); return result; } catch (Throwable e) { LOG.warn("Error while loading resource", e); } return Collections.emptyList(); }

Target:
private static List<String> loadFromResources(String fileName) { try { Path resource = Paths.get(LicenseChecker.class.getResource("/" + fileName).toURI()); List<String> result = Files .readAllLines(resource) .stream() .filter(line -> !line.startsWith("#") && !line.isEmpty()) .collect(Collectors.toList()); LOG.debug("Loaded items from resource {}", result.size(), fileName); return result; } catch (Throwable e) { throw new RuntimeException("Error while loading resource", e); } }