auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean rollingRestartVpc(final Vpc vpc, final ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException, InsufficientCapacityException { s_logger.debug("Performing rolling restart of routers of VPC " + vpc); _ntwkMgr.destroyExpendableRouters(_routerDao.listByVpcId(vpc.getId()), context); final DeployDestination dest = new DeployDestination(_dcDao.findById(vpc.getZoneId()), null, null, null); final List<DomainRouterVO> oldRouters = _routerDao.listByVpcId(vpc.getId()); if (oldRouters.size() > 0) { vpc.setRollingRestart(true); } startVpc(vpc, dest, context); if (oldRouters.size() > 0) { vpc.setRollingRestart(false); } if (vpc.isRedundant() || (oldRouters.size() == 1 && oldRouters.get(0).getIsRedundantRouter())) { try { Thread.sleep(10000L); } catch (final InterruptedException ignored) { } } for (final DomainRouterVO oldRouter : oldRouters) { _routerService.destroyRouter(oldRouter.getId(), context.getAccount(), context.getCaller().getId()); } if (!startVpc(vpc, dest, context)) { s_logger.debug("Failed to re-program VPC router or deploy a new backup router for VPC" + vpc); return false; } return _ntwkMgr.validateNewRouters(_routerDao.listByVpcId(vpc.getId())); }

Target:
private boolean rollingRestartVpc(final Vpc vpc, final ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException, InsufficientCapacityException { s_logger.debug("Performing rolling restart of routers of VPC " + vpc); _ntwkMgr.destroyExpendableRouters(_routerDao.listByVpcId(vpc.getId()), context); final DeployDestination dest = new DeployDestination(_dcDao.findById(vpc.getZoneId()), null, null, null); final List<DomainRouterVO> oldRouters = _routerDao.listByVpcId(vpc.getId()); if (oldRouters.size() > 0) { vpc.setRollingRestart(true); } startVpc(vpc, dest, context); if (oldRouters.size() > 0) { vpc.setRollingRestart(false); } if (vpc.isRedundant() || (oldRouters.size() == 1 && oldRouters.get(0).getIsRedundantRouter())) { try { Thread.sleep(NetworkOrchestrationService.RVRHandoverTime); } catch (final InterruptedException ignored) { } } for (final DomainRouterVO oldRouter : oldRouters) { _routerService.destroyRouter(oldRouter.getId(), context.getAccount(), context.getCaller().getId()); } if (!startVpc(vpc, dest, context)) { s_logger.debug("Failed to re-program VPC router or deploy a new backup router for VPC" + vpc); return false; } return _ntwkMgr.areRoutersRunning(_routerDao.listByVpcId(vpc.getId())); }
Source:
protected SQLServerOutputConnector getConnector(PluginTask task, boolean retryableMetadataOperation) { SQLServerPluginTask sqlServerTask = (SQLServerPluginTask) task; Driver driver; boolean useJtdsDriver = false; if (sqlServerTask.getDriverPath().isPresent()) { loadDriverJar(sqlServerTask.getDriverPath().get()); try { driver = (Driver) Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance(); } catch(Exception e) { throw new ConfigException("Driver set at field 'driver_path' doesn't include Microsoft SQLServerDriver", e); } } else { try { driver = (Driver) Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance(); } catch(Exception e) { logger.info("Using jTDS Driver"); driver = new net.sourceforge.jtds.jdbc.Driver(); useJtdsDriver = true; } } UrlAndProperties urlProps = getUrlAndProperties(sqlServerTask, useJtdsDriver); logger.info("Connecting to options {}", urlProps.getUrl(), urlProps.getProps()); return new SQLServerOutputConnector(driver, urlProps.getUrl(), urlProps.getProps(), null); }

Target:
protected SQLServerOutputConnector getConnector(PluginTask task, boolean retryableMetadataOperation) { SQLServerPluginTask sqlServerTask = (SQLServerPluginTask) task; boolean useJtdsDriver = false; if (sqlServerTask.getDriverPath().isPresent()) { loadDriverJar(sqlServerTask.getDriverPath().get()); try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch(Exception e) { throw new ConfigException("Driver set at field 'driver_path' doesn't include Microsoft SQLServerDriver", e); } } else { try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch(Exception e) { logger.info("Using jTDS Driver"); try { Class.forName("net.sourceforge.jtds.jdbc.Driver"); } catch(Exception e2) { throw new ConfigException("'driver_path' doesn't set and can't found jTDS driver", e2); } useJtdsDriver = true; } } UrlAndProperties urlProps = getUrlAndProperties(sqlServerTask, useJtdsDriver); logger.info("Connecting to options {}", urlProps.getUrl(), getPropsWithMaskedSecret(urlProps)); return new SQLServerOutputConnector(urlProps.getUrl(), urlProps.getProps(), null); }
Source:
protected void checkFile(@NotNull GoFile file, @NotNull ProblemsHolder problemsHolder) { super.checkFile(file, problemsHolder); if (((ScratchFileType)ScratchFileType.INSTANCE).isMyFileType(file.getVirtualFile())) return; GoPackageClause packageClause = file.getPackage(); if (packageClause != null) { String packageName = file.getPackageName(); if (packageName == null || packageName.equals(GoConstants.DOCUMENTATION)) return; PsiDirectory dir = file.getContainingDirectory(); Collection<String> packages = GoPackageUtil.getAllPackagesInDirectory(dir, null, true); packages.remove(GoConstants.DOCUMENTATION); if (packages.size() > 1) { Collection<LocalQuickFix> fixes = ContainerUtil.newArrayList(); if (problemsHolder.isOnTheFly()) { fixes.add(new GoMultiplePackagesQuickFix(packageClause, packageName, packages, true)); } else { for (String name : packages) { fixes.add(new GoMultiplePackagesQuickFix(packageClause, name, packages, false)); } } problemsHolder.registerProblem(packageClause, "Multiple packages in directory", fixes.toArray(new LocalQuickFix[fixes.size()])); } } }

Target:
protected void checkFile(@NotNull GoFile file, @NotNull ProblemsHolder problemsHolder) { if (((ScratchFileType)ScratchFileType.INSTANCE).isMyFileType(file.getVirtualFile())) return; GoPackageClause packageClause = file.getPackage(); if (packageClause != null) { String packageName = file.getPackageName(); if (packageName == null || packageName.equals(GoConstants.DOCUMENTATION)) return; PsiDirectory dir = file.getContainingDirectory(); Collection<String> packages = GoPackageUtil.getAllPackagesInDirectory(dir, null, true); packages.remove(GoConstants.DOCUMENTATION); if (packages.size() > 1) { Collection<LocalQuickFix> fixes = ContainerUtil.newArrayList(); if (problemsHolder.isOnTheFly()) { fixes.add(new GoMultiplePackagesQuickFix(packageClause, packageName, packages, true)); } else { for (String name : packages) { fixes.add(new GoMultiplePackagesQuickFix(packageClause, name, packages, false)); } } problemsHolder.registerProblem(packageClause, "Multiple packages in directory", fixes.toArray(new LocalQuickFix[fixes.size()])); } } }
Source:
public Set<CoordinatorStreamMessage> getBoostrappedStream() { log.info("Returning the bootstrapped data from the stream"); bootstrap(); return bootstrappedStreamSet; }

Target:
public Set<CoordinatorStreamMessage> getBoostrappedStream() { log.info("Returning the bootstrapped data from the stream"); if (!isBootstrapped) bootstrap(); return bootstrappedStreamSet; }
Source:
protected String dotOutputFileName(UnderlyingAST ast) { StringBuilder srcLoc = new StringBuilder(); StringBuilder outFile = new StringBuilder(outDir); outFile.append("/"); if (ast.getKind() == UnderlyingAST.Kind.ARBITRARY_CODE) { CFGStatement cfgStatement = (CFGStatement) ast; String clsName = cfgStatement.getClassTree().getSimpleName().toString(); outFile.append(clsName); outFile.append("-initializer-"); outFile.append(ast.hashCode()); srcLoc.append("<"); srcLoc.append(clsName); srcLoc.append("::initializer::"); srcLoc.append(((JCTree) cfgStatement.getCode()).pos); srcLoc.append(">"); } else if (ast.getKind() == UnderlyingAST.Kind.METHOD) { CFGMethod cfgMethod = (CFGMethod) ast; String clsName = cfgMethod.getClassTree().getSimpleName().toString(); String methodName = cfgMethod.getMethod().getName().toString(); outFile.append(clsName); outFile.append("-"); outFile.append(methodName); srcLoc.append("<"); srcLoc.append(clsName); srcLoc.append("::"); srcLoc.append(methodName); srcLoc.append("("); srcLoc.append(cfgMethod.getMethod().getParameters()); srcLoc.append(")::"); srcLoc.append(((JCTree) cfgMethod.getMethod()).pos); srcLoc.append(">"); } else { throw new BugInCF("Unexpected AST kind: " + ast.getKind() + " value: " + ast); } if (!checkerName.isEmpty()) { outFile.append('-'); outFile.append(checkerName); } outFile.append(".dot"); String outFileName = outFile.toString().replace("<", "_").replace(">", ""); generated.put(srcLoc.toString(), outFileName); return outFileName; }

Target:
protected String dotOutputFileName(UnderlyingAST ast) { StringBuilder srcLoc = new StringBuilder(); StringBuilder outFile = new StringBuilder(outDir); outFile.append("/"); if (ast.getKind() == UnderlyingAST.Kind.ARBITRARY_CODE) { CFGStatement cfgStatement = (CFGStatement) ast; String clsName = cfgStatement.getClassTree().getSimpleName().toString(); outFile.append(clsName); outFile.append("-initializer-"); outFile.append(ast.hashCode()); srcLoc.append("<"); srcLoc.append(clsName); srcLoc.append("::initializer::"); srcLoc.append(((JCTree) cfgStatement.getCode()).pos); srcLoc.append(">"); } else if (ast.getKind() == UnderlyingAST.Kind.METHOD) { CFGMethod cfgMethod = (CFGMethod) ast; String clsName = cfgMethod.getClassTree().getSimpleName().toString(); String methodName = cfgMethod.getMethod().getName().toString(); outFile.append(clsName); outFile.append("-"); outFile.append(methodName); srcLoc.append("<"); srcLoc.append(clsName); srcLoc.append("::"); srcLoc.append(methodName); srcLoc.append("("); srcLoc.append(cfgMethod.getMethod().getParameters()); srcLoc.append(")::"); srcLoc.append(((JCTree) cfgMethod.getMethod()).pos); srcLoc.append(">"); } else { throw new BugInCF("Unexpected AST kind: " + ast.getKind() + " value: " + ast); } if (checkerName != null && !checkerName.isEmpty()) { outFile.append('-'); outFile.append(checkerName); } outFile.append(".dot"); String outFileName = outFile.toString().replace("<", "_").replace(">", ""); generated.put(srcLoc.toString(), outFileName); return outFileName; }
Source:
public void registerBundle(String bundleUrl) { try { String nv = urlToBundleIdentifier.get(bundleUrl); if (nv!=null) { if (Osgis.bundleFinder(framework).id(nv).requiringFromUrl(bundleUrl).find().isPresent()) { log.trace("Bundle from "+bundleUrl+" already installed as "+nv+"; not re-registering"); return; } else { log.debug("Bundle "+nv+" from "+bundleUrl+" is known in map but not installed; perhaps in the process of installing?"); } } Bundle b = Osgis.install(framework, bundleUrl); nv = b.getSymbolicName()+":"+b.getVersion().toString(); List<Bundle> matches = Osgis.bundleFinder(framework).id(nv).findAll(); if (matches.isEmpty()) { log.error("OSGi not find bundle "+nv+" in search after installing it from "+bundleUrl); } else if (matches.size()==1) { log.debug("Bundle from "+bundleUrl+" successfully installed as " + nv + " ("+b+")"); } else { log.warn("OSGi has multiple bundles matching "+nv+", when just installed from "+bundleUrl+": "+matches+"; " + "brooklyn will prefer the URL-based bundle for top-level references but any dependencies or " + "import-packages will be at the mercy of OSGi. " + "It is recommended to use distinct versions for different bundles, and the same URL for the same bundles."); } urlToBundleIdentifier.put(bundleUrl, nv); } catch (BundleException e) { log.debug("Bundle from "+bundleUrl+" failed to install (rethrowing): "+e); throw Throwables.propagate(e); } }

Target:
public void registerBundle(String bundleUrl) { try { String nv = urlToBundleIdentifier.get(bundleUrl); if (nv!=null) { if (Osgis.bundleFinder(framework).id(nv).requiringFromUrl(bundleUrl).find().isPresent()) { log.trace("Bundle from "+bundleUrl+" already installed as "+nv+"; not re-registering"); return; } else { log.debug("Bundle "+nv+" from "+bundleUrl+" is known in map but not installed; perhaps in the process of installing?"); } } Bundle b = Osgis.install(framework, bundleUrl); nv = b.getSymbolicName()+":"+b.getVersion().toString(); List<Bundle> matches = Osgis.bundleFinder(framework).id(nv).findAll(); if (matches.isEmpty()) { log.error("OSGi could not find bundle "+nv+" in search after installing it from "+bundleUrl); } else if (matches.size()==1) { log.debug("Bundle from "+bundleUrl+" successfully installed as " + nv + " ("+b+")"); } else { log.warn("OSGi has multiple bundles matching "+nv+", when just installed from "+bundleUrl+": "+matches+"; " + "brooklyn will prefer the URL-based bundle for top-level references but any dependencies or " + "import-packages will be at the mercy of OSGi. " + "It is recommended to use distinct versions for different bundles, and the same URL for the same bundles."); } urlToBundleIdentifier.put(bundleUrl, nv); } catch (BundleException e) { log.debug("Bundle from "+bundleUrl+" failed to install (rethrowing): "+e); throw Throwables.propagate(e); } }
Source:
public int center(Region region, Pattern pattern) throws MaxChangedBlocksException { checkNotNull(region); checkNotNull(pattern); Vector center = region.getCenter(); Vector vec1 = new Vector((int) center.getX(), (int) center.getY(), (int) center.getZ()); Vector vec2 = center.toBlockVector(); boolean condX = (region.getWidth() % 2) == 0; boolean condZ = (region.getLength() % 2) == 0; Vector vec3 = new Vector(vec2.getX() + (condX ? 0.5*Math.signum(vec2.getX()) : 0), vec2.getY(), vec2.getZ() + (condZ ? 0.5*Math.signum(vec2.getZ()) : 0)); Region centerRegion = new CuboidRegion( getWorld(), vec1, vec3); return setBlocks(centerRegion, pattern); }

Target:
public int center(Region region, Pattern pattern) throws MaxChangedBlocksException { checkNotNull(region); checkNotNull(pattern); Vector center = region.getCenter(); Vector vec2 = center.toBlockVector(); Region centerRegion = new CuboidRegion( getWorld(), new Vector((int) center.getX(), (int) center.getY(), (int) center.getZ()), new Vector(MathUtils.round(vec2.getX()), vec2.getY(), MathUtils.round(vec2.getZ()))); return setBlocks(centerRegion, pattern); }
Source:
public void okPressed(Kontakt k) { for (int i = 0; i < fieldDefinitions.length; i++) { String value = values[i].getText(); if ((savedValues == null && !value.isEmpty()) || (savedValues[i] != null && !savedValues[i].equals(value))) { k.setInfoElement(fields[i], value); String xid = xids.get(fields[i]); if (xid != null) { logger.debug("okPressed: Updating field {}: key value -> {}", i, fields[i], xid, savedValues[i], value); k.addXid(xid, value, true); } } } }

Target:
public void okPressed(Kontakt k) { for (int i = 0; i < fieldDefinitions.length; i++) { String value = values[i].getText(); if ((savedValues == null && !value.isEmpty()) || (savedValues[i] != null && !savedValues[i].equals(value))) { k.setInfoElement(fields[i], value); String xid = xids.get(fields[i]); if (xid != null) { k.addXid(xid, value, true); } } } }
Source:
public int getLinePixel(int lineIndex) { checkWidget(); int lineCount = content.getLineCount(); lineIndex = Math.max(0, Math.min(lineCount, lineIndex)); if (isFixedLineHeight()) { int lineHeight = renderer.getLineHeight(); return lineIndex * lineHeight - getVerticalScrollOffset() + topMargin; } if (lineIndex == topIndex) return topIndexY + topMargin; int height = topIndexY; if (lineIndex > topIndex) { for (int i = topIndex; i < lineIndex; i++) { height += renderer.getCachedLineHeight(i); } } else { for (int i = topIndex - 1; i >= lineIndex; i--) { height -= renderer.getCachedLineHeight(i); } } return height + topMargin; }

Target:
public int getLinePixel(int lineIndex) { checkWidget(); int lineCount = content.getLineCount(); lineIndex = Math.max(0, Math.min(lineCount, lineIndex)); if (isFixedLineHeight()) { int lineHeight = renderer.getLineHeight(); return lineIndex * lineHeight - getVerticalScrollOffset() + topMargin; } if (lineIndex == topIndex) return topIndexY + topMargin; int height = topIndexY; if (lineIndex > topIndex) { for (int i = topIndex; i < lineIndex; i++) { height += renderer.getLineHeight(i); } } else { for (int i = topIndex - 1; i >= lineIndex; i--) { height -= renderer.getLineHeight(i); } } return height + topMargin; }
Source:
private String renderGibibyteSize(long size) { long sizeInGB = (unit == SizeUnit.GiB) ? size : SizeConverter.convert(size, unit, SizeUnit.GiB).longValue(); return messages.gibibytes(sizeInGB >= 1 ? String.valueOf(sizeInGB) : "< 1"); }

Target:
private String renderGibibyteSize(long size) { long sizeInGiB = (unit == SizeUnit.GiB) ? size : SizeConverter.convert(size, unit, SizeUnit.GiB).longValue(); return messages.gibibytes(sizeInGiB >= 1 ? String.valueOf(sizeInGiB) : "< 1"); }
Source:
public static String resolveWildCardForJarSpec(String workingDirectory, String unresolvedJarSpec, Logger log) { log.debug("resolveWildCardForJarSpec: unresolved jar specification: " + unresolvedJarSpec); if (unresolvedJarSpec == null || unresolvedJarSpec.isEmpty()) return null; StringBuilder resolvedJarSpec = new StringBuilder(); String[] unresolvedJarSpecList = unresolvedJarSpec.split(","); for (String s : unresolvedJarSpecList) { if (s.endsWith("*")) { String fileName = String.format("%s/%s", workingDirectory, s.substring(0, s.length() - 2)); String[] jarList = new File(fileName).list(jarFilter); for (String ls : jarList) { String lsFilename = fileName + "/" + ls + ","; resolvedJarSpec.append(lsFilename); } } else { resolvedJarSpec.append(s + ","); } } log.debug("resolveWildCardForJarSpec: resolvedJarSpec: " + resolvedJarSpec); int lastCharIndex = resolvedJarSpec.length() - 1; if (lastCharIndex >= 0 && resolvedJarSpec.charAt(lastCharIndex) == ',') { resolvedJarSpec.deleteCharAt(lastCharIndex); } return resolvedJarSpec.toString(); }

Target:
public static String resolveWildCardForJarSpec(String workingDirectory, String unresolvedJarSpec, Logger log) { log.debug("resolveWildCardForJarSpec: unresolved jar specification: " + unresolvedJarSpec); log.debug("working directory: " + workingDirectory); if (unresolvedJarSpec == null || unresolvedJarSpec.isEmpty()) return ""; StringBuilder resolvedJarSpec = new StringBuilder(); String[] unresolvedJarSpecList = unresolvedJarSpec.split(","); for (String s : unresolvedJarSpecList) { if (s.endsWith("*")) { String dirName = String.format("%s/%s", workingDirectory, s.substring(0, s.length() - 2)); File[] jars = null; try { jars = getFilesInFolderByRegex(new File(dirName), ".*jar"); } catch (FileNotFoundException fnfe) { log.warn("folder does not exist: " + dirName); continue; } for (File jar : jars) { resolvedJarSpec.append(jar.toString()).append(","); } } else { resolvedJarSpec.append(s).append(","); } } log.debug("resolveWildCardForJarSpec: resolvedJarSpec: " + resolvedJarSpec); int lastCharIndex = resolvedJarSpec.length() - 1; if (lastCharIndex >= 0 && resolvedJarSpec.charAt(lastCharIndex) == ',') { resolvedJarSpec.deleteCharAt(lastCharIndex); } return resolvedJarSpec.toString(); }
Source:
public static Parameter[] filter(final Parameter[] parameters, final Set<InjectableParameter> filters) { if (filters != null && !filters.isEmpty()) { boolean firstMethodFiltered = false; final List<Parameter> filterList = new ArrayList<>(parameters.length); for (final Parameter parameter : parameters) { boolean omit = false; for (final InjectableParameter injectableParameter : filters) { if (injectableParameter == null) { continue; } omit = canInject(parameter, injectableParameter); switch (injectableParameter) { case CURRENT_TEST_METHOD: if (omit && !firstMethodFiltered) { firstMethodFiltered = true; } else { omit = false; } break; default: break; } if (omit) { break; } } if (!omit) { filterList.add(parameter); } } final Parameter[] filteredArray = new Parameter[filterList.size()]; return filterList.toArray(filteredArray); } else { return parameters; } }

Target:
public static Parameter[] filter(final Parameter[] parameters, final Set<InjectableParameter> filters) { if (filters != null && !filters.isEmpty()) { boolean firstMethodFiltered = false; final List<Parameter> filterList = new ArrayList<>(parameters.length); for (final Parameter parameter : parameters) { boolean omit = false; for (final InjectableParameter injectableParameter : filters) { omit = canInject(parameter, injectableParameter); switch (injectableParameter) { case CURRENT_TEST_METHOD: if (omit && !firstMethodFiltered) { firstMethodFiltered = true; } else { omit = false; } break; default: break; } if (omit) { break; } } if (!omit) { filterList.add(parameter); } } final Parameter[] filteredArray = new Parameter[filterList.size()]; return filterList.toArray(filteredArray); } else { return parameters; } }
Source:
public void reconnect(final long hostId) throws CloudRuntimeException, AgentUnavailableException{ HostVO host; host = _hostDao.findById(hostId); if (host == null || host.getRemoved() != null) { throw new CloudRuntimeException("Unable to find host " + hostId); } if (host.getStatus() == Status.Disconnected) { throw new CloudRuntimeException("Host is already disconnected, no work to be done"); } if (host.getStatus() != Status.Up && host.getStatus() != Status.Alert && host.getStatus() != Status.Rebalancing) { throw new CloudRuntimeException("Unable to disconnect host because it is not in the correct state: host=" + hostId + "; Status=" + host.getStatus()); } final AgentAttache attache = findAttache(hostId); if (attache == null) { throw new CloudRuntimeException("Unable to disconnect host because it is not connected to this server: " + hostId); } disconnectWithoutInvestigation(attache, Event.ShutdownRequested); }

Target:
public void reconnect(final long hostId) throws AgentUnavailableException { HostVO host = _hostDao.findById(hostId); if (host == null) { throw new CloudRuntimeException("Unable to find host: " + hostId); } if (host.getRemoved() != null) { throw new CloudRuntimeException("Host has already been removed: " + hostId); } if (host.getStatus() == Status.Disconnected) { s_logger.debug("Host is already disconnected, no work to be done: " + hostId); return; } if (host.getStatus() != Status.Up && host.getStatus() != Status.Alert && host.getStatus() != Status.Rebalancing) { throw new CloudRuntimeException("Unable to disconnect host because it is not in the correct state: host=" + hostId + "; Status=" + host.getStatus()); } AgentAttache attache = findAttache(hostId); if (attache == null) { throw new CloudRuntimeException("Unable to disconnect host because it is not connected to this server: " + hostId); } disconnectWithoutInvestigation(attache, Event.ShutdownRequested); }
Source:
public void afterDatastoreRef() { S3DatasetDefinition definition = new S3DatasetDefinition(); RuntimeInfo runtimeInfo = definition.getRuntimeInfo(this); try (SandboxedInstance sandboxedInstance = RuntimeUtil.createRuntimeClass(runtimeInfo, getClass().getClassLoader())) { IS3DatasetRuntime runtime = (IS3DatasetRuntime) sandboxedInstance.getInstance(); runtime.initialize(null, this); this.bucket.setPossibleValues(new ArrayList<String>(runtime.listBuckets())); } catch (Exception e) { TalendRuntimeException.build(ComponentsErrorCode.IO_EXCEPTION, e).throwIt(); } }

Target:
public void afterDatastoreRef() { if(!this.bucket.getPossibleValues().isEmpty()) { return; } S3DatasetDefinition definition = new S3DatasetDefinition(); RuntimeInfo runtimeInfo = definition.getRuntimeInfo(this); try (SandboxedInstance sandboxedInstance = RuntimeUtil.createRuntimeClass(runtimeInfo, getClass().getClassLoader())) { IS3DatasetRuntime runtime = (IS3DatasetRuntime) sandboxedInstance.getInstance(); runtime.initialize(null, this); this.bucket.setPossibleValues(new ArrayList<String>(runtime.listBuckets())); } catch (Exception e) { LOGGER.warn(e.getClass() + " : " + e.getMessage()); } }
Source:
public static String getPermString(int perms) { StringBuilder p = new StringBuilder(); if ((perms & ZooDefs.Perms.CREATE) != 0) { p.append('c'); } if ((perms & ZooDefs.Perms.DELETE) != 0) { p.append('d'); } if ((perms & ZooDefs.Perms.READ) != 0) { p.append('r'); } if ((perms & ZooDefs.Perms.WRITE) != 0) { p.append('w'); } if ((perms & ZooDefs.Perms.ADMIN) != 0) { p.append('a'); } return p.toString(); }

Target:
public static String getPermString(int perms) { String permString = permCache.get(perms); if (permString != null) { return permString; } permString = constructPermString(perms); if (!permString.isEmpty()) { permCache.put(perms, permString); } return permString; }
Source:
public static JobContextImpl fromConfigWithDefaults(Config config) { JobConfig jobConfig = new JobConfig(config); String jobName = jobConfig.getName().orElseThrow(() -> new IllegalArgumentException("Job name is not defined in configuration")); String jobId = jobConfig.getJobId(); return new JobContextImpl(config, jobName, jobId); }

Target:
public static JobContextImpl fromConfigWithDefaults(Config config) { JobConfig jobConfig = new JobConfig(config); String jobName = jobConfig.getName() .orElseThrow(() -> new IllegalArgumentException(String.format("Config %s is missing", JobConfig.JOB_NAME))); String jobId = jobConfig.getJobId(); return new JobContextImpl(config, jobName, jobId); }
Source:
public OutputStream newOutputStream(int index) throws IOException { synchronized (DiskLruCache.this) { if (index >= valueCount || index < 0) { throw new IllegalArgumentException("Expected index " + index + " to " + "be greater than 0 and less than the maximum value count " + "of " + valueCount); } if (entry.currentEditor != this) { throw new IllegalStateException(); } if (!entry.readable) { written[index] = true; } File dirtyFile = entry.getDirtyFile(index); FileOutputStream outputStream; try { outputStream = new FileOutputStream(dirtyFile); } catch (FileNotFoundException e) { directory.mkdirs(); try { outputStream = new FileOutputStream(dirtyFile); } catch (FileNotFoundException e2) { return NULL_OUTPUT_STREAM; } } return new FaultHidingOutputStream(outputStream); } }

Target:
public OutputStream newOutputStream(int index) throws IOException { if (index < 0 || index >= valueCount) { throw new IllegalArgumentException("Expected index " + index + " to " + "be greater than 0 and less than the maximum value count " + "of " + valueCount); } synchronized (DiskLruCache.this) { if (entry.currentEditor != this) { throw new IllegalStateException(); } if (!entry.readable) { written[index] = true; } File dirtyFile = entry.getDirtyFile(index); FileOutputStream outputStream; try { outputStream = new FileOutputStream(dirtyFile); } catch (FileNotFoundException e) { directory.mkdirs(); try { outputStream = new FileOutputStream(dirtyFile); } catch (FileNotFoundException e2) { return NULL_OUTPUT_STREAM; } } return new FaultHidingOutputStream(outputStream); } }
Source:
public void testSelectQueryTypes() throws SQLException, IOException { Properties properties = new Properties(); properties.setProperty("common.max_count", "1000"); properties.setProperty("common.max_retry", "3"); properties.setProperty("default.driver", "org.h2.Driver"); properties.setProperty("default.url", getJdbcConnection()); properties.setProperty("default.user", ""); properties.setProperty("default.password", ""); JDBCInterpreter t = new JDBCInterpreter(properties); t.open(); String sqlQuery = "select * from test_table"; InterpreterResult interpreterResult = t.interpret(sqlQuery, interpreterContext); assertEquals(InterpreterResult.Code.SUCCESS, interpreterResult.code()); assertEquals(Collections.nCopies(2, ColumnDef.TYPE.STRING), interpreterResult.message().get(0).getColumnTypes()); }

Target:
public void testSelectQueryTypes() throws SQLException, IOException { Properties properties = new Properties(); properties.setProperty("common.max_count", "1000"); properties.setProperty("common.max_retry", "3"); properties.setProperty("default.driver", "org.h2.Driver"); properties.setProperty("default.url", getJdbcConnection()); properties.setProperty("default.user", ""); properties.setProperty("default.password", ""); JDBCInterpreter t = new JDBCInterpreter(properties); try { t.open(); String sqlQuery = "select * from test_table"; InterpreterResult interpreterResult = t.interpret(sqlQuery, interpreterContext); assertEquals(InterpreterResult.Code.SUCCESS, interpreterResult.code()); assertEquals(Collections.nCopies(2, ColumnDef.TYPE.STRING), interpreterResult.message().get(0).getColumnTypes()); } finally { t.close(); } }
Source:
protected void postRunnable(Runnable runnable) { if (runnable != null) { if (getUseSynchronousMode() || handler == null) { runnable.run(); } else { assert handler != null; handler.post(runnable); } } }

Target:
protected void postRunnable(Runnable runnable) { if (runnable != null) { if (getUseSynchronousMode() || handler == null) { runnable.run(); } else { AssertUtils.asserts(handler != null, "handler should not be null!"); handler.post(runnable); } } }
Source:
public void applyCredentialsFilter(OkHttpClient.Builder clientBuilder) { clientBuilder.addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); HttpUrl url = chain.request().url(); Map<String, String> challengeMap = cache.getCachedChallenge(url); Response response; Pair<Request, HttpMessageSecurity> authenticatedRequestPair; if (challengeMap != null) { authenticatedRequestPair = buildAuthenticatedRequest(originalRequest, challengeMap); } else { response = chain.proceed(buildEmptyRequest(originalRequest)); if (response.code() != 401) { return response; } authenticatedRequestPair = buildAuthenticatedRequest(originalRequest, response); response.close(); } response = chain.proceed(authenticatedRequestPair.getLeft()); if (response.code() == 200) { return authenticatedRequestPair.getRight().unprotectResponse(response); } else { return response; } } }); }

Target:
public void applyCredentialsFilter(OkHttpClient.Builder clientBuilder) { clientBuilder.addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); HttpUrl url = chain.request().url(); Map<String, String> challengeMap = cache.getCachedChallenge(url); Response response; Pair<Request, HttpMessageSecurity> authenticatedRequestPair; if (challengeMap != null) { authenticatedRequestPair = buildAuthenticatedRequest(originalRequest, challengeMap); } else { response = chain.proceed(buildEmptyRequest(originalRequest)); if (response.code() != 401) { return response; } try { authenticatedRequestPair = buildAuthenticatedRequest(originalRequest, response); } finally { response.close(); } } response = chain.proceed(authenticatedRequestPair.getLeft()); if (response.code() == 200) { return authenticatedRequestPair.getRight().unprotectResponse(response); } else { return response; } } }); }
Source:
public List<Long> findPermissionsInDatabaseButStaleInOrMissingFromSolr() { List<Long> indexingRequired = new ArrayList<>(); long rootDvId = dataverseService.findRootDataverse().getId(); for (DvObject dvObject : dvObjectService.findAll()) { Timestamp permissionModificationTime = dvObject.getPermissionModificationTime(); Timestamp permissionIndexTime = dvObject.getPermissionIndexTime(); if (permissionIndexTime == null) { if (dvObject.getId() != rootDvId && !dvObject.isInstanceofDataFile()) { indexingRequired.add(dvObject.getId()); } } else if (permissionModificationTime == null) { logger.info("no permission modification time for dvobject id " + dvObject.getId()); } else if (permissionIndexTime.before(permissionModificationTime)) { indexingRequired.add(dvObject.getId()); } } return indexingRequired; }

Target:
public List<Long> findPermissionsInDatabaseButStaleInOrMissingFromSolr() { List<Long> indexingRequired = new ArrayList<>(); long rootDvId = dataverseService.findRootDataverse().getId(); List<Long> missingDataversePermissionIds = dataverseService.findIdStalePermission(); List<Long> missingDatasetPermissionIds = datasetService.findIdStalePermission(); for (Long id : missingDataversePermissionIds) { if (!id.equals(rootDvId)) { indexingRequired.add(id); } } indexingRequired.addAll(missingDatasetPermissionIds); return indexingRequired; }
Source:
public BinaryObject replaceOriginalFile(InputStream contentStream, String filename, String mimetype, String sha1Checksum, String md5Checksum) { String objectPath = constructOriginalFilePath(); Model fileModel = ModelFactory.createDefaultModel(); Resource resc = fileModel.createResource(objectPath); resc.addProperty(RDF.type, PcdmUse.OriginalFile); return repoObjFactory.updateBinary(fileSetUri, ORIGINAL_FILE, contentStream, filename, mimetype, sha1Checksum, md5Checksum, fileModel); }

Target:
public BinaryObject replaceOriginalFile(InputStream contentStream, String filename, String mimetype, String sha1Checksum, String md5Checksum) { return repoObjFactory.updateBinary(fileSetUri, ORIGINAL_FILE, contentStream, filename, mimetype, sha1Checksum, md5Checksum, null); }
Source:
@Override public void readOnly(boolean readOnly) throws IgniteException { checkReadOnlyModeSupports(); guard(); try { ctx.state().changeGlobalState(readOnly).get(); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } }

Target:
@Override public void readOnly(boolean readOnly) throws IgniteException { guard(); try { verifyReadOnlyModeSupport(); ctx.state().changeGlobalState(readOnly).get(); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } }
Source:
private boolean monitorTellsToContinue(@Nullable DeliveryStage stage) { if(stage == null) { return true; } if(monitor.shouldStopAfter(stage)) { throw new DeliveryStoppedByMonitorException(); } return true; }

Target:
private boolean monitorTellsToContinue(@Nullable DeliveryStage stage) { if (stage == null) { return true; } return monitor.shouldContinueAfter(stage); }
Source:
private void init(SourceManager sourceManager) { try { DataManager dm = (DataManager) Services.getService(DataManager.class); DataSourceFactory dsf = dm.getDataSourceFactory(); String crsName = "Unknown"; int epsgCode = -1; final int validType = SourceManager.VECTORIAL | SourceManager.RASTER | SourceManager.WMS | SourceManager.SYSTEM_TABLE; for (String sourceName : sourceNames) { int type = sourceManager.getSource(sourceName).getType(); if ((validType & type) == 0) { DataBaseRow row = new DataBaseRow(sourceName, sourceName, "public", "gid", "the_geom", crsName, epsgCode, Boolean.TRUE); data.add(row); } else if ((type & SourceManager.VECTORIAL) == SourceManager.VECTORIAL) { DataSource ds = dsf.getDataSource(sourceName); ds.open(); String geomField = ds.getFieldName(ds.getSpatialFieldIndex()); CoordinateReferenceSystem crs = ds.getCRS(); if (crs != null) { crsName = crs.getName(); epsgCode = crs.getEPSGCode(); } ds.close(); DataBaseRow row = new DataBaseRow(sourceName, sourceName, "public", "gid", geomField, crsName, epsgCode, Boolean.TRUE); row.setSpatial(true); data.add(row); } } } catch (NoSuchTableException ex) { LOGGER.error(I18N.tr("This table does not exist."), ex); } catch (DataSourceCreationException ex) { LOGGER.error(I18N.tr("The required DataSource could not be created."), ex); } catch (DriverException e) { LOGGER.error(I18N.tr("Cannot connect to the database."), e); } }

Target:
private void init(SourceManager sourceManager) { try { DataManager dm = Services.getService(DataManager.class); DataSourceFactory dsf = dm.getDataSourceFactory(); String crsName = "Unknown"; int epsgCode = -1; final int validType = SourceManager.VECTORIAL | SourceManager.RASTER | SourceManager.WMS | SourceManager.SYSTEM_TABLE; for (String sourceName : sourceNames) { int type = sourceManager.getSource(sourceName).getType(); if ((validType & type) == 0) { DataBaseRow row = new DataBaseRow(sourceName, sourceName, "public", "gid", "the_geom", crsName, epsgCode, Boolean.TRUE); data.add(row); } else if ((type & SourceManager.VECTORIAL) == SourceManager.VECTORIAL) { DataSource ds = dsf.getDataSource(sourceName); ds.open(); String geomField = ds.getFieldName(ds.getSpatialFieldIndex()); CoordinateReferenceSystem crs = ds.getCRS(); if (crs != null) { crsName = crs.getName(); epsgCode = crs.getEPSGCode(); } ds.close(); DataBaseRow row = new DataBaseRow(sourceName, sourceName, "public", "gid", geomField, crsName, epsgCode, Boolean.TRUE); row.setSpatial(true); data.add(row); } } } catch (NoSuchTableException ex) { LOGGER.error(I18N.tr("This table does not exist."), ex); } catch (DataSourceCreationException ex) { LOGGER.error(I18N.tr("The required DataSource could not be created."), ex); } catch (DriverException e) { LOGGER.error(I18N.tr("Cannot connect to the database."), e); } }
Source:
private UniqueIDType createTerrestrialProgrammeCridIdentifier(Broadcast broadcast) { UniqueIDType otherId = new UniqueIDType(); otherId.setAuthority(BROADCAST_AUTHORITY); Optional<Alias> alias = aliasWithNamespace(broadcast.getAliases(), TERRESTRIAL_PROGRAMME_CRID_NS); if (alias.isPresent()) { otherId.setValue(alias.get().getValue()); } return otherId; }

Target:
private UniqueIDType createTerrestrialProgrammeCridIdentifier(Broadcast broadcast) { UniqueIDType otherId = new UniqueIDType(); otherId.setAuthority(BROADCAST_AUTHORITY); Optional<Alias> alias = aliasWithNamespace(broadcast.getAliases(), TERRESTRIAL_PROGRAMME_CRID_NS); if (!alias.isPresent()) { throw new RuntimeException("Terrestrial Programme Crid Identifier not present for broadcast " + broadcast.getCanonicalUri()); } otherId.setValue(alias.get().getValue()); return otherId; }
Source:
public void testTraceSet() { openTrace(trace1); openTrace(trace2); selectTrace(trace2); ITmfTrace[] expected = new ITmfTrace[] { trace2 }; Collection<ITmfTrace> actual = tm.getActiveTraceSet(); assertEquals(1, actual.size()); assertArrayEquals(expected, actual.toArray(new ITmfTrace[1])); }

Target:
public void testTraceSet() { openTrace(trace1); openTrace(trace2); selectTrace(trace2); Collection<ITmfTrace> expected = Collections.singleton(trace2); Collection<ITmfTrace> actual = tm.getActiveTraceSet(); assertEquals(1, actual.size()); assertEquals(expected, actual); }
Source:
public void close() { log.trace("txid: close()", txid); if (summaryLog.isTraceEnabled()) { TxStats stats = tx.getStats(); String className = "N/A"; if (clazz != null) className = clazz.getSimpleName(); summaryLog.trace("txid: thread : time: #read:TODO #ret: #set: #collisions: waitTime: %s committed: class: {}", txid, Thread .currentThread().getId(), stats.getTime(), stats.getEntriesReturned(), stats.getEntriesSet(), stats.getCollisions(), stats.getLockWaitTime(), committed, className); } tx.close(); }

Target:
public void close() { log.trace("txid: close()", txid); if (summaryLog.isTraceEnabled()) { TxStats stats = tx.getStats(); String className = "N/A"; if (clazz != null) className = clazz.getSimpleName(); summaryLog.trace("txid: thread : time: #ret: #set: #collisions: waitTime: %s committed: class: {}", txid, Thread .currentThread().getId(), stats.getTime(), stats.getEntriesReturned(), stats.getEntriesSet(), stats.getCollisions(), stats.getLockWaitTime(), committed, className); } tx.close(); }
Source:
public void onBlockImpl(BlockSummary blockSummary) { try { logger.debug("onBlock: " + blockSummary.getBlock().getShortDescr()); if (bestBlock != null && blockSummary.getBlock().getNumber() < bestBlock.getNumber() - 16) { logger.debug("Ignoring block as too old: " + blockSummary.getBlock().getShortDescr()); return; } if (contractAddressFilter.matchBloom(new Bloom(blockSummary.getBlock().getLogBloom()))) { for (int i = 0; i < blockSummary.getReceipts().size(); i++) { TransactionReceipt receipt = blockSummary.getReceipts().get(i); if (contractAddressFilter.matchBloom(receipt.getBloomFilter())) { if (!pendings.containsKey(new ByteArrayWrapper(receipt.getTransaction().getHash()))) { ENDING state pendingState.trackTransaction(receipt.getTransaction()); } } } } if (blockSummary.getTotalDifficulty().compareTo(lastTotDiff) > 0) { lastTotDiff = blockSummary.getTotalDifficulty(); bestBlock = blockSummary.getBlock(); newBestBlock(blockSummary.getBlock()); } } catch (Exception e) { logger.error("Unexpected error while processing onBlock", e); } }

Target:
public void onBlockImpl(BlockSummary blockSummary) { if (!initialized) throw new RuntimeException("Event listener should be initialized"); try { logger.debug("onBlock: " + blockSummary.getBlock().getShortDescr()); if (bestBlock != null && blockSummary.getBlock().getNumber() < bestBlock.getNumber() - MAX_IN_REQUEST) { logger.debug("Ignoring block as too old: " + blockSummary.getBlock().getShortDescr()); return; } if (logFilter.matchBloom(new Bloom(blockSummary.getBlock().getLogBloom()))) { for (int i = 0; i < blockSummary.getReceipts().size(); i++) { TransactionReceipt receipt = blockSummary.getReceipts().get(i); if (logFilter.matchBloom(receipt.getBloomFilter())) { if (!pendings.containsKey(receipt.getTransaction().getHash())) { ENDING state pendingState.trackTransaction(receipt.getTransaction()); } } } } if (blockSummary.betterThan(lastTotDiff)) { lastTotDiff = blockSummary.getTotalDifficulty(); bestBlock = blockSummary.getBlock(); newBestBlock(blockSummary.getBlock()); } } catch (Exception e) { logger.error("Unexpected error while processing onBlock", e); } }
Source:
public void logAndThrowRestLiServiceException(HttpStatus status, String msg, Exception e) { String id = UUID.randomUUID().toString(); id = id.substring(0, Math.min(6, id.length())); String cause = e == null ? "None" : e.getMessage(); if (status.getCode() > 500) { _logger.error("[{}] {}", id, msg, e); } else { _logger.warn("[{}] {}, cause={}", id, msg, cause); } throw new RestLiServiceException(status, String.format("msg=%s; cause=%s; instance=%s; id=%s;", msg, cause, _instance, id)); }

Target:
public void logAndThrowRestLiServiceException(HttpStatus status, String msg, Exception e) { String id = UUID.randomUUID().toString(); id = id.substring(0, Math.min(6, id.length())); String cause = e == null ? "None" : e.getMessage(); if (status.getCode() >= HttpStatus.S_500_INTERNAL_SERVER_ERROR.getCode()) { _logger.error("[{}] {}", id, msg, e); } else { _logger.warn("[{}] {}, cause={}", id, msg, cause); } throw new RestLiServiceException(status, String.format("msg=%s; cause=%s; instance=%s; id=%s;", msg, cause, _instance, id)); }
Source:
public void refreshItems() { if (getDataManager() != null) { try { clearItems(); for (Identifiable item : getDataManager().getObjects(getBaseClass())) { putItem(item.getId(), item); driversByUniqueId.put(((Driver) item).getUniqueId(), (Driver) item); } } catch (SQLException error) { Log.warning(error); } } refreshUserItems(); }

Target:
public void refreshItems() { if (getDataManager() != null) { try { clearItems(); for (BaseModel item : getDataManager().getObjects(getBaseClass())) { putItem(item.getId(), item); driversByUniqueId.put(((Driver) item).getUniqueId(), (Driver) item); } } catch (SQLException error) { Log.warning(error); } } refreshUserItems(); }
Source:
public synchronized List<IDockerImage> getImages(final boolean force) { synchronized (imageLock) { List<IDockerImage> latestImages = this.images; if (this.state == EnumDockerConnectionState.CLOSED) { return Collections.emptyList(); } else if (this.state == EnumDockerConnectionState.UNKNOWN) { try { open(true); latestImages = getImages(force); } catch (DockerException e) { Activator.log(e); } } else if (!isImagesLoaded() || force) { try { latestImages = listImages(); } catch (DockerException e) { this.images = Collections.emptyList(); Activator.log(e); } } return latestImages; } }

Target:
public List<IDockerImage> getImages(final boolean force) { List<IDockerImage> latestImages; synchronized (imageLock) { latestImages = this.images; } if (this.state == EnumDockerConnectionState.CLOSED) { return Collections.emptyList(); } else if (this.state == EnumDockerConnectionState.UNKNOWN) { try { open(true); latestImages = getImages(force); } catch (DockerException e) { Activator.log(e); } } else if (!isImagesLoaded() || force) { try { latestImages = listImages(); } catch (DockerException e) { synchronized (imageLock) { this.images = Collections.emptyList(); } Activator.log(e); } } return latestImages; }
Source:
public final Instance runOnDemand() throws IOException { Instance instance = null; final AmazonEC2Client client = new AmazonEC2Client( this.credentials ); client.setEndpoint(this.region); final RunInstancesRequest request = this.createRequest(); final List<Instance> instances = client.runInstances( request ).getReservation().getInstances(); if ((instances != null) && !instances.isEmpty()) { instance = instances.get(0); } InstanceState state = instance.getState(); if (state.getCode() < 16) { final DescribeInstanceStatusRequest statusreq = new DescribeInstanceStatusRequest(); statusreq.withInstanceIds(instance.getInstanceId()); while (state.getCode() < 16) { try { TimeUnit.SECONDS.sleep(Tv.FIFTEEN); } catch (final InterruptedException ex) { continue; } final DescribeInstanceStatusResult instanceStatus = client .describeInstanceStatus(statusreq); state = instanceStatus.getInstanceStatuses().get(0) .getInstanceState(); } } return instance; }

Target:
public final Instance runOnDemand() throws IOException { final AmazonEC2Client client = new AmazonEC2Client( this.credentials ); client.setEndpoint(this.region); final List<Instance> instances = client.runInstances( new RunInstancesRequest() .withKeyName(this.keyname) .withMinCount(1) .withMaxCount(1) .withInstanceType(this.type) ).getReservation().getInstances(); if (instances.isEmpty()) { throw new IllegalStateException( "No Instance was available in the RunInstanceRequest reply!" ); } final Instance instance = instances.get(0); InstanceState state = instance.getState(); if (state.getCode() < RUNNING_STATE) { final DescribeInstanceStatusRequest req = new DescribeInstanceStatusRequest(); req.withInstanceIds(instance.getInstanceId()); while (state.getCode() < RUNNING_STATE) { try { TimeUnit.SECONDS.sleep(Tv.FIFTEEN); } catch (final InterruptedException ex) { throw new IllegalArgumentException(ex); } final DescribeInstanceStatusResult instanceStatus = client .describeInstanceStatus(req); state = instanceStatus.getInstanceStatuses().get(0) .getInstanceState(); } } return instance; }
Source:
void testBinary() { ToCloudEventTransformer transformer = new ToCloudEventTransformer(SOURCE, ToCloudEventTransformer.Result.BINARY); transformer.setSubjectExpression(new LiteralExpression("some_subject")); GenericMessage<String> message = new GenericMessage<>("test"); Message<?> result = transformer.transform(message); assertThat(result.getHeaders()) .containsEntry("ce_type", String.class.getName()) .containsEntry("ce_source", SOURCE.toString()) .containsEntry("ce_id", message.getHeaders().getId().toString()) .containsEntry("ce_subject", "some_subject") .containsKeys("ce_time", "ce_specversion") .doesNotContainKeys("ce_datacontenttype", MessageHeaders.CONTENT_TYPE, "ce_content_type"); assertThat(result.getPayload()) .isInstanceOf(byte[].class) .isEqualTo("\"test\"".getBytes()); }

Target:
void testBinary() { ToCloudEventTransformer transformer = new ToCloudEventTransformer(SOURCE, ToCloudEventTransformer.Result.BINARY); transformer.setSubjectExpression(new LiteralExpression("some_subject")); Message<String> message = MessageBuilder.withPayload("test") .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN) .build(); Message<?> result = transformer.transform(message); assertThat(result.getHeaders()) .containsEntry(CloudEventHeaders.TYPE, String.class.getName()) .containsEntry(CloudEventHeaders.SOURCE, SOURCE.toString()) .containsEntry(CloudEventHeaders.ID, message.getHeaders().getId().toString()) .containsEntry(CloudEventHeaders.SUBJECT, "some_subject") .containsEntry(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN_VALUE) .containsKeys(CloudEventHeaders.TIME, CloudEventHeaders.SPEC_VERSION) .doesNotContainKeys( CloudEventHeaders.DATA_CONTENT_TYPE, "ce_content_type"); assertThat(result.getPayload()) .isInstanceOf(byte[].class) .isEqualTo("test".getBytes()); }
Source:
public String getFeedbackSessionName() { if (displayableFsName == null) { displayableFsName = sanitizeForHtml(bundle.feedbackSession.feedbackSessionName); } return displayableFsName; }

Target:
public String getFeedbackSessionName() { return displayableFsName; }