auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void removeAccount(Account account) { notNull(account, "account"); try { restTemplate.delete(account.getUri()); } catch (GoodDataException | RestClientException e) { throw new GoodDataException("Unable to create account", e); } }

Target:
public void removeAccount(Account account) { notNull(account, "account"); try { restTemplate.delete(account.getUri()); } catch (GoodDataRestException e) { if (HttpStatus.NOT_FOUND.value() == e.getStatusCode()) { throw new AccountNotFoundException(account.getUri(), e); } else { throw e; } } catch (GoodDataException e) { throw new GoodDataException("Unable to remove account", e); } }
Source:
void start() throws Exception { advertisedGcTimetamp = LongUtil.fromByteArray(curator.getData().forPath(ZookeeperPath.ORACLE_GC_TIMESTAMP)); TimerTask tt = new TimerTask() { @Override public void run() { try { updateGcTimestamp(); } catch (Exception e) { log.warn("Failed to update GC timestamp.", e); } } }; TimerTask logTask = new TimerTask() { @Override public void run() { log.warn("Loging the current timestamp: ", currentTs); } }; timer = new Timer("Oracle gc update timer", true); long updatePeriod = env.getConfiguration().getLong(FluoConfigurationImpl.ZK_UPDATE_PERIOD_PROP, FluoConfigurationImpl.ZK_UPDATE_PERIOD_MS_DEFAULT); long nextPeriod = 5 * 60 * 1000L; timer.schedule(tt, updatePeriod, updatePeriod); timer.schedule(logTask, nextPeriod, nextPeriod); }

Target:
void start() throws Exception { advertisedGcTimetamp = LongUtil.fromByteArray(curator.getData().forPath(ZookeeperPath.ORACLE_GC_TIMESTAMP)); TimerTask tt = new TimerTask() { @Override public void run() { try { updateGcTimestamp(); } catch (Exception e) { log.warn("Failed to update GC timestamp.", e); } } }; TimerTask logTask = new TimerTask() { @Override public void run() { log.info("Current timestamp: {}", currentTs); } }; timer = new Timer("Oracle gc update timer", true); long updatePeriod = env.getConfiguration().getLong(FluoConfigurationImpl.ZK_UPDATE_PERIOD_PROP, FluoConfigurationImpl.ZK_UPDATE_PERIOD_MS_DEFAULT); long nextPeriod = 5 * 60 * 1000L; timer.schedule(tt, updatePeriod, updatePeriod); timer.schedule(logTask, 0L, nextPeriod); }
Source:
static public void resetLevel() { level.remove(); }

Target:
static void resetLevel() { level.remove(); }
Source:
public BlockRegion intersection(BlockRegion other, BlockRegion dest) { dest.minX = Math.max(minX, other.minX); dest.minY = Math.max(minY, other.minY); dest.minZ = Math.max(minZ, other.minZ); dest.maxX = Math.min(maxX, other.maxX); dest.maxY = Math.min(maxY, other.maxY); dest.maxZ = Math.min(maxZ, other.maxZ); return dest; }

Target:
public BlockRegion intersection(BlockRegion other, BlockRegion dest) { this.aabb.intersection(other.aabb, dest.aabb); return dest; }
Source:
public Guid getEntityGuid(Object entity) { if (entity instanceof BusinessEntity) { Object id = ((BusinessEntity<?>) entity).getId(); if (id instanceof Guid) { return (Guid) id; } } if (entity instanceof VmPool) { return ((VmPool) entity).getVmPoolId(); } else if (entity instanceof DbUser) { return ((DbUser) entity).getId(); } else if (entity instanceof DbGroup) { return ((DbGroup) entity).getId(); } else if (entity instanceof Job) { return ((Job) entity).getId(); } else { return Guid.Empty; } }

Target:
public Guid getEntityGuid(Object entity) { if (entity instanceof BusinessEntity) { Object id = ((BusinessEntity<?>) entity).getId(); if (id instanceof Guid) { return (Guid) id; } } if (entity instanceof VmPool) { return ((VmPool) entity).getVmPoolId(); } else if (entity instanceof DbUser) { return ((DbUser) entity).getId(); } else if (entity instanceof DbGroup) { return ((DbGroup) entity).getId(); } else { return Guid.Empty; } }
Source:
public DataSet<V> join(OperationContext context, DataSet<V> rightDataSet, JoinType joinType, boolean isBroadcast) { try { JoinOperation op = (JoinOperation) context.getOperation(); Dataset<Row> leftDF = SpliceSpark.getSession().createDataFrame( rdd.map(new LocatedRowToRowFunction()), context.getOperation().getLeftOperation().getExecRowDefinition().schema()); Dataset<Row> rightDF = SpliceSpark.getSession().createDataFrame( ((SparkDataSet)rightDataSet).rdd.map(new LocatedRowToRowFunction()), context.getOperation().getRightOperation().getExecRowDefinition().schema()); if (isBroadcast) { rightDF = broadcast(rightDF); } Column expr = null; int[] rightJoinKeys = ((JoinOperation)context.getOperation()).getRightHashKeys(); int[] leftJoinKeys = ((JoinOperation)context.getOperation()).getLeftHashKeys(); assert rightJoinKeys!=null && leftJoinKeys!=null && rightJoinKeys.length == leftJoinKeys.length:"Join Keys Have Issues"; for (int i = 0; i< rightJoinKeys.length;i++) { Column joinEquality = (leftDF.col(ValueRow.getNamedColumn(leftJoinKeys[i])) .equalTo(rightDF.col(ValueRow.getNamedColumn(rightJoinKeys[i])))); expr = i!=0?expr.and(joinEquality):joinEquality; } DataSet joinedSet; if (op.wasRightOuterJoin) joinedSet = new SparkDataSet(rightDF.join(leftDF,expr,"rightouter").rdd().toJavaRDD().map( new RowToLocatedRowFunction(context))); else joinedSet = new SparkDataSet(leftDF.join(rightDF,expr,joinType.strategy()).rdd().toJavaRDD().map( new RowToLocatedRowFunction(context))); return joinedSet; } catch (Exception e) { throw new RuntimeException(e); } }

Target:
public DataSet<V> join(OperationContext context, DataSet<V> rightDataSet, JoinType joinType, boolean isBroadcast) { try { JoinOperation op = (JoinOperation) context.getOperation(); Dataset<Row> leftDF = SpliceSpark.getSession().createDataFrame( rdd.map(new LocatedRowToRowFunction()), context.getOperation().getLeftOperation().getExecRowDefinition().schema()); Dataset<Row> rightDF = SpliceSpark.getSession().createDataFrame( ((SparkDataSet)rightDataSet).rdd.map(new LocatedRowToRowFunction()), context.getOperation().getRightOperation().getExecRowDefinition().schema()); if (isBroadcast) { rightDF = broadcast(rightDF); } Column expr = null; int[] rightJoinKeys = ((JoinOperation)context.getOperation()).getRightHashKeys(); int[] leftJoinKeys = ((JoinOperation)context.getOperation()).getLeftHashKeys(); assert rightJoinKeys!=null && leftJoinKeys!=null && rightJoinKeys.length == leftJoinKeys.length:"Join Keys Have Issues"; for (int i = 0; i< rightJoinKeys.length;i++) { Column joinEquality = (leftDF.col(ValueRow.getNamedColumn(leftJoinKeys[i])) .equalTo(rightDF.col(ValueRow.getNamedColumn(rightJoinKeys[i])))); expr = i!=0?expr.and(joinEquality):joinEquality; } DataSet joinedSet; if (op.wasRightOuterJoin) joinedSet = new SparkDataSet(rightDF.join(leftDF,expr,joinType.RIGHTOUTER.strategy()).rdd().toJavaRDD().map( new RowToLocatedRowFunction(context))); else joinedSet = new SparkDataSet(leftDF.join(rightDF,expr,joinType.strategy()).rdd().toJavaRDD().map( new RowToLocatedRowFunction(context))); return joinedSet; } catch (Exception e) { throw new RuntimeException(e); } }
Source:
public List<PatientProgram> getPatientProgramByAttributeNameAndValue(String attributeName, String attributeValue) { FlushMode flushMode = sessionFactory.getCurrentSession().getFlushMode(); sessionFactory.getCurrentSession().setFlushMode(FlushMode.MANUAL); Query query; try { query = sessionFactory.getCurrentSession().createQuery( "SELECT bpp FROM BahmniPatientProgram bpp " + "INNER JOIN bpp.attributes attr " + "INNER JOIN attr.attributeType attr_type " + "WHERE attr.valueReference = :attributeValue " + "AND attr_type.name = :attributeName " + "AND bpp.voided = 0") .setParameter("attributeName", attributeName) .setParameter("attributeValue", attributeValue); return query.list(); } finally { sessionFactory.getCurrentSession().setFlushMode(flushMode); } }

Target:
public List<PatientProgram> getPatientProgramByAttributeNameAndValue(String attributeName, String attributeValue) { FlushMode flushMode = sessionFactory.getCurrentSession().getFlushMode(); sessionFactory.getCurrentSession().setFlushMode(FlushMode.MANUAL); Query query; try { query = sessionFactory.getCurrentSession().createQuery( "SELECT pp FROM patient_program pp " + "INNER JOIN pp.attributes attr " + "INNER JOIN attr.attributeType attr_type " + "WHERE attr.valueReference = :attributeValue " + "AND attr_type.name = :attributeName " + "AND pp.voided = 0") .setParameter("attributeName", attributeName) .setParameter("attributeValue", attributeValue); return query.list(); } finally { sessionFactory.getCurrentSession().setFlushMode(flushMode); } }
Source:
public List<Tree.Kind> nodesToVisit() { return ImmutableList.of(Tree.Kind.ANNOTATION); }

Target:
public List<Tree.Kind> nodesToVisit() { return Collections.singletonList(Tree.Kind.ANNOTATION); }
Source:
public void getUserMetadata(User user) { try { GHMyself myself = github.getMyself(); User.Profile profile = new User.Profile(); profile.name = myself.getName(); profile.email = myself.getEmail(); profile.avatarURL = myself.getAvatarUrl(); profile.bio = myself.getBlog(); profile.location = myself.getLocation(); profile.company = myself.getCompany(); profile.username = myself.getLogin(); Map<String, User.Profile> userProfile = user.getUserProfiles(); userProfile.put(TokenType.GITHUB_COM.toString(), profile); user.setAvatarUrl(myself.getAvatarUrl()); } catch (IOException ex) { LOG.info("Could not find user information for user " + user.getUsername()); } }

Target:
public void getUserMetadata(User user) { try { GHMyself myself = github.getMyself(); User.Profile profile = new User.Profile(); profile.name = myself.getName(); profile.email = myself.getEmail(); profile.avatarURL = myself.getAvatarUrl(); profile.bio = myself.getBlog(); profile.location = myself.getLocation(); profile.company = myself.getCompany(); profile.username = myself.getLogin(); Map<String, User.Profile> userProfile = user.getUserProfiles(); userProfile.put(TokenType.GITHUB_COM.toString(), profile); user.setAvatarUrl(myself.getAvatarUrl()); } catch (IOException ex) { LOG.info("Could not find user information for user " + user.getUsername(), ex); } }
Source:
public static GiraphMasterScenarioWrapper readMasterScenarioFromTrace(String jobId, long superstepNo, DebugTrace debugTrace) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException { if (!EnumSet.of(DebugTrace.MASTER_ALL, DebugTrace.MASTER_EXCEPTION, DebugTrace.MASTER_REGULAR).contains(debugTrace)) { throw new IllegalArgumentException( "DebugTrace type is invalid. Use REGULAR, EXCEPTION or ALL_VERTICES"); } FileSystem fs = ServerUtils.getFileSystem(); GiraphMasterScenarioWrapper giraphScenarioWrapper = new GiraphMasterScenarioWrapper(); if (debugTrace == DebugTrace.MASTER_REGULAR || debugTrace == DebugTrace.MASTER_ALL) { String traceFilePath = ServerUtils.getTraceFilePath(jobId, superstepNo, DebugTrace.MASTER_REGULAR, null ); try { giraphScenarioWrapper.loadFromHDFS(fs, traceFilePath); return giraphScenarioWrapper; } catch(FileNotFoundException e) { if ( debugTrace == DebugTrace.MASTER_ALL) { Debug.println("readMasterScenarioFromTrace", "Regular file not found. Ignoring."); } else { throw e; } } } String traceFilePath = ServerUtils.getTraceFilePath(jobId, superstepNo, DebugTrace.MASTER_EXCEPTION, null ); giraphScenarioWrapper.loadFromHDFS(fs, traceFilePath); return giraphScenarioWrapper; }

Target:
public static GiraphMasterScenarioWrapper readMasterScenarioFromTrace(String jobId, long superstepNo, DebugTrace debugTrace) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException { if (!EnumSet.of(DebugTrace.MASTER_ALL, DebugTrace.MASTER_EXCEPTION, DebugTrace.MASTER_REGULAR).contains(debugTrace)) { throw new IllegalArgumentException( "DebugTrace type is invalid. Use REGULAR, EXCEPTION or ALL_VERTICES"); } FileSystem fs = ServerUtils.getFileSystem(); GiraphMasterScenarioWrapper giraphScenarioWrapper = new GiraphMasterScenarioWrapper(); if (debugTrace == DebugTrace.MASTER_REGULAR || debugTrace == DebugTrace.MASTER_ALL) { String traceFilePath = ServerUtils.getMasterTraceFilePath(jobId, superstepNo, DebugTrace.MASTER_REGULAR); try { giraphScenarioWrapper.loadFromHDFS(fs, traceFilePath); return giraphScenarioWrapper; } catch(FileNotFoundException e) { if ( debugTrace == DebugTrace.MASTER_ALL) { Debug.println("readMasterScenarioFromTrace", "Regular file not found. Ignoring."); } else { throw e; } } } String traceFilePath = ServerUtils.getMasterTraceFilePath(jobId, superstepNo, DebugTrace.MASTER_EXCEPTION); giraphScenarioWrapper.loadFromHDFS(fs, traceFilePath); return giraphScenarioWrapper; }
Source:
public Iterable<Directive> process(final XML xml) throws IOException { final Shell shell = new TalkShells(xml).get(); final String dir = xml.xpath("/talk/daemon/dir/text()").get(0); final int exit = new Script("end.sh").exec(xml); final Directives dirs = new Directives(); if (exit == 0) { Logger.info( this, "the daemon is still running in %s (%s)", dir, xml.xpath("/talk/@name").get(0) ); } else { final XML node = xml.node("/p/entry[@key='assets']/entry"); boolean deprecate = false; if(EndsDaemon.IMAGE.equals(node.xpath(" deprecate=true; } dirs.append(this.end(shell, dir,deprecate)); } return dirs; }

Target:
public Iterable<Directive> process(final XML xml) throws IOException { final Shell shell = new TalkShells(xml).get(); final String dir = xml.xpath("/talk/daemon/dir/text()").get(0); final int exit = new Script("end.sh").exec(xml); final Directives dirs = new Directives(); if (exit == 0) { Logger.info( this, "the daemon is still running in %s (%s)", dir, xml.xpath("/talk/@name").get(0) ); } else { dirs.append(this.end(shell, dir)); } return dirs; }
Source:
private void loadNormalizationIds(final File bpmFile) { IlluminaBPMFile illuminaBPMFile; try (final DataInputStream inputStream = new DataInputStream(new FileInputStream(bpmFile))) { illuminaBPMFile = new IlluminaBPMFile(inputStream); allNormalizationIds = illuminaBPMFile.getAllNormalizationIds(); uniqueNormalizationIds = illuminaBPMFile.getUniqueNormalizationIds(); } catch (IOException e) { throw new PicardException("Error reading bpm file '" + bpmFile.getAbsolutePath() + "'", e); } }

Target:
private void loadNormalizationIds(final File bpmFile) { try (IlluminaBPMFile illuminaBPMFile = new IlluminaBPMFile(bpmFile)) { allNormalizationIds = illuminaBPMFile.getAllNormalizationIds(); uniqueNormalizationIds = illuminaBPMFile.getUniqueNormalizationIds(); } catch (IOException e) { throw new PicardException("Error reading bpm file '" + bpmFile.getAbsolutePath() + "'", e); } }
Source:
public ListFactoryBean ldapPasswordSynchronizationAuthenticationPostProcessorListFactoryBean() { val bean = new ListFactoryBean() { @Override protected void destroyInstance(final List list) { list.forEach(Unchecked.consumer(postProcessor -> { ((DisposableBean) postProcessor).destroy(); })); } }; bean.setSourceList(new ArrayList()); return bean; }

Target:
public ListFactoryBean ldapPasswordSynchronizationAuthenticationPostProcessorListFactoryBean() { val bean = new ListFactoryBean() { @Override protected void destroyInstance(final List list) { list.forEach(Unchecked.consumer(postProcessor -> ((DisposableBean) postProcessor).destroy() )); } }; bean.setSourceList(new ArrayList<>()); return bean; }
Source:
private void startTracingContainersStartup(Pod pod) { for (Container container : pod.getSpec().getContainers()) { String machineName = Names.machineName(pod, container); machineStartupTraces.put( machineName, tracer .buildSpan("container-create") .asChildOf(tracer.activeSpan()) .withTag(CheTags.MACHINE_NAME.getKey(), machineName) .start()); } }

Target:
private void startTracingContainersStartup(Pod pod) { if (tracer == null) { return; } for (Container container : pod.getSpec().getContainers()) { String machineName = Names.machineName(pod, container); machineStartupTraces.put( machineName, tracer .buildSpan("machine.create") .asChildOf(tracer.activeSpan()) .withTag(TracingTags.MACHINE_NAME.getKey(), machineName) .start()); } }
Source:
public Post() { this.postContent = randomAlphanumeric(100); }

Target:
public Post()
Source:
public DownloadTracker(Tracker tracker, TrackMe baseTrackMe) { mTracker = tracker; mBaseTrackMe = baseTrackMe; Piwik piwik = tracker.getPiwik(); mPreferences = piwik.getSharedPreferences(); mContext = piwik.getContext(); mPackageName = mContext.getPackageName(); mPackMan = mContext.getPackageManager(); try { PackageInfo pkgInfo = mPackMan.getPackageInfo(mContext.getPackageName(), 0); mVersion = Integer.toString(pkgInfo.versionCode); mName = pkgInfo.packageName; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } }

Target:
public DownloadTracker(Tracker tracker, TrackMe baseTrackMe) { mTracker = tracker; mBaseTrackMe = baseTrackMe; Piwik piwik = tracker.getPiwik(); mPreferences = piwik.getSharedPreferences(); mContext = piwik.getContext(); mPackageName = mContext.getPackageName(); mPackMan = mContext.getPackageManager(); try { mPkgInfo = mPackMan.getPackageInfo(mPackageName, 0); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } }
Source:
protected void decorateRequired() { if (decoration != null) { throw new IllegalStateException(); } decoration = new ControlDecoration(getLabelControl(), SWT.TOP | SWT.RIGHT); decoration.setDescriptionText(Messages.AbstractAttributeEditor_AttributeIsRequired); decoration.setMarginWidth(0); Image image = FieldDecorationRegistry.getDefault() .getFieldDecoration(FieldDecorationRegistry.DEC_ERROR) .getImage(); decoration.setImage(image); getLabelControl().addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { if (decoration != null) { decoration.dispose(); decoration = null; } } }); }

Target:
protected void decorateRequired() { if (decoration == null) { decoration = new ControlDecoration(getLabelControl(), SWT.TOP | SWT.RIGHT); decoration.setDescriptionText(Messages.AbstractAttributeEditor_AttributeIsRequired); decoration.setMarginWidth(0); Image image = FieldDecorationRegistry.getDefault() .getFieldDecoration(FieldDecorationRegistry.DEC_ERROR) .getImage(); decoration.setImage(image); getLabelControl().addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { if (decoration != null) { decoration.dispose(); decoration = null; } } }); } }
Source:
public boolean validate() { if(getChoiceGroupNone().getEntity() && !getChoiceGroupTotal().getEntity() && !getChoiceGroupReadWrite().getEntity() ) { return true; } validateValue(getTotal(), (Integer) AsyncDataProvider.getInstance().getConfigValuePreConverted(maxTotal)); validateValue(getRead(), (Integer) AsyncDataProvider.getInstance().getConfigValuePreConverted(maxRead)); validateValue(getWrite(), (Integer) AsyncDataProvider.getInstance().getConfigValuePreConverted(maxWrite)); if (getTotal().getEntity() != null && (getRead().getEntity() != null || getWrite().getEntity() != null)) { setErrorMsg(getTotal()); setErrorMsg(getRead()); setErrorMsg(getWrite()); } setIsValid(getTotal().getIsValid() && getRead().getIsValid() && getWrite().getIsValid()); return getIsValid(); }

Target:
public boolean validate() { if(getChoiceGroupNone().getEntity()) { return true; } validateValue(getTotal(), (Integer) AsyncDataProvider.getInstance().getConfigValuePreConverted(maxTotal)); validateValue(getRead(), (Integer) AsyncDataProvider.getInstance().getConfigValuePreConverted(maxRead)); validateValue(getWrite(), (Integer) AsyncDataProvider.getInstance().getConfigValuePreConverted(maxWrite)); if (getTotal().getEntity() != null && (getRead().getEntity() != null || getWrite().getEntity() != null)) { setErrorMsg(getTotal()); setErrorMsg(getRead()); setErrorMsg(getWrite()); } setIsValid(getTotal().getIsValid() && getRead().getIsValid() && getWrite().getIsValid()); return getIsValid(); }
Source:
public final void invoke() throws Exception { try { beforeInvoke(); if (canceled) { throw new CancelTaskException(); } runMailboxLoop(); if (canceled) { throw new CancelTaskException(); } afterInvoke(); } catch (Exception invokeException) { LOG.error("Invoke Error", invokeException); try { cleanUpInvoke(); } catch (Throwable cleanUpException) { throw (Exception) ExceptionUtils.firstOrSuppressed(cleanUpException, invokeException); } throw invokeException; } cleanUpInvoke(); }

Target:
public final void invoke() throws Exception { try { beforeInvoke(); if (canceled) { throw new CancelTaskException(); } runMailboxLoop(); if (canceled) { throw new CancelTaskException(); } afterInvoke(); } catch (Exception invokeException) { try { cleanUpInvoke(); } catch (Throwable cleanUpException) { Throwable throwable = ExceptionUtils.firstOrSuppressed(cleanUpException, invokeException); throw (throwable instanceof Exception ? (Exception) throwable : new Exception(throwable)); } throw invokeException; } cleanUpInvoke(); }
Source:
private void doHandle(Request request, HttpServletResponse httpServletResponse) throws IOException { String queries = request.getUri().getQuery(); if (s_logger.isTraceEnabled()) s_logger.trace("Handle WebSocket Console request " + queries); String[] content = new String[]{"<html>", "<head>", "<script type=\"text/javascript\" language=\"javascript\" src=\"/resource/js/jquery.js\"></script>", "<script> \n" + " $(function(){\n" + " $(\"#vncpage\").load(\"/resource/noVNC/novnc.html\"); \n" + " });\n" + " </script>", " <body> \n" + " <div id=\"vncpage\"></div>\n" + " </body> ", "</head>", "</html>"}; StringBuffer sb = new StringBuffer(); for (int i = 0; i < content.length; i++) sb.append(content[i]); sendResponse(httpServletResponse, "text/html", sb.toString()); }

Target:
private void doHandle(Request request, HttpServletResponse httpServletResponse) throws IOException { String queries = request.getHttpURI().getQuery(); if (s_logger.isTraceEnabled()) { s_logger.trace("Handle WebSocket Console request " + queries); } if (queries != null) { Map<String, String> queryMap = ConsoleProxyHttpHandlerHelper.getQueryMap(queries); String host = queryMap.get("host"); String portStr = queryMap.get("port"); String tag = queryMap.get("tag"); ConsoleProxyClientParam param = new ConsoleProxyClientParam(); param.setClientHostAddress(host); param.setClientHostPort(NumbersUtil.parseInt(portStr, 80)); param.setClientTag(tag); ConsoleProxy.removeViewer(param); } sendResponse(httpServletResponse, "text/html", getFile("noVNC/start.html")); }
Source:
public void onWritePossible() throws IOException { while (output.isReady()) { if (writeComplete()) { asyncContext.complete(); return; } if (page == null) { page = serializedPages.poll(); int bufferPosition = 0; slice.setInt(bufferPosition, page.getPositionCount()); bufferPosition += SIZE_OF_INT; slice.setByte(bufferPosition, page.getPageCodecMarkers()); bufferPosition += SIZE_OF_BYTE; slice.setInt(bufferPosition, page.getUncompressedSizeInBytes()); bufferPosition += SIZE_OF_INT; slice.setInt(bufferPosition, page.getSizeInBytes()); bufferPosition += SIZE_OF_INT; output.write(buffer, 0, bufferPosition); } else { Object base = page.getSlice().getBase(); if (base instanceof byte[]) { output.write((byte[]) base, (int) ((page.getSlice().getAddress() - ARRAY_BYTE_BASE_OFFSET)), page.getSizeInBytes()); } else { output.write(page.getSlice().getBytes(), 0, page.getSizeInBytes()); } page = null; } } }

Target:
public void onWritePossible() throws IOException { while (output.isReady()) { if (writeComplete()) { asyncContext.complete(); return; } if (page == null) { page = serializedPages.poll(); int bufferPosition = 0; slice.setInt(bufferPosition, page.getPositionCount()); bufferPosition += SIZE_OF_INT; slice.setByte(bufferPosition, page.getPageCodecMarkers()); bufferPosition += SIZE_OF_BYTE; slice.setInt(bufferPosition, page.getUncompressedSizeInBytes()); bufferPosition += SIZE_OF_INT; slice.setInt(bufferPosition, page.getSizeInBytes()); bufferPosition += SIZE_OF_INT; output.write(slice.byteArray(), 0, bufferPosition); } else { Object base = page.getSlice().getBase(); checkArgument(base instanceof byte[], "serialization type only supports byte[]"); output.write((byte[]) base, (int) ((page.getSlice().getAddress() - ARRAY_BYTE_BASE_OFFSET)), page.getSizeInBytes()); page = null; } } }
Source:
void completePlayerSetup(boolean asked) { skinLayout = (OoyalaSkinLayout) findViewById(R.id.ooyalaPlayer); PlayerDomain domain1 = new PlayerDomain(domain); Options options = new Options.Builder().setShowPromoImage(false).setUseExoPlayer(true).build(); player = new OoyalaPlayer(pcode, domain1, options); SkinOptions skinOptions = new SkinOptions.Builder().build(); controller = new OoyalaSkinLayoutController(getApplication(), skinLayout, player, skinOptions); controller.addObserver(this); player.addObserver(this); OoyalaIMAManager imaManager = new OoyalaIMAManager(player, skinLayout); imaManager.setAdUrlOverride("<LINK_0>[referrer_url]&description_url=[description_url]&correlator=[timestamp]"); if (player.setEmbedCode(embedCode)) { } }

Target:
void completePlayerSetup(boolean asked) { skinLayout = (OoyalaSkinLayout) findViewById(R.id.ooyalaPlayer); PlayerDomain playerDomain = new PlayerDomain(domain); Options options = new Options.Builder().setShowPromoImage(false).setUseExoPlayer(true).build(); player = new OoyalaPlayer(pcode, playerDomain, options); SkinOptions skinOptions = new SkinOptions.Builder().build(); playerLayoutController = new OoyalaSkinLayoutController(getApplication(), skinLayout, player, skinOptions); playerLayoutController.addObserver(this); player.addObserver(this); OoyalaIMAManager imaManager = new OoyalaIMAManager(player, skinLayout); imaManager.setAdUrlOverride("<LINK_0>[referrer_url]&description_url=[description_url]&correlator=[timestamp]"); if (player.setEmbedCode(embedCode)) { } }
Source:
private String readFile(File directory, String fileName) throws IOException { byte[] content = IO.readFully(new File(directory, fileName)); return RawParseUtils.decode(content, 0, RawParseUtils .nextLF(content, 0) - 1); }

Target:
private String readFile(File directory, String fileName) throws IOException { byte[] content = IO.readFully(new File(directory, fileName)); int end = content.length; while (0 < end && content[end - 1] == '\n') end--; return RawParseUtils.decode(content, 0, end); }
Source:
protected static Strategy parseLocator(FindByCoordinates findByCoordinates, String locator) { String prefix = null; String criteria = locator; if (!locator.startsWith(" String[] locatorParts = locator.split("[=:]", 2); if (locatorParts.length == 2) { if (locator.charAt(locatorParts[0].length()) == "=".charAt(0)) { System.out.println( "*WARN* '=' is deprecated as locator strategy separator. ':' should be used instead"); } prefix = locatorParts[0].trim().toUpperCase(); criteria = locatorParts[1].trim(); } } Strategy strategy = StrategyEnum.DEFAULT; if (prefix != null) { try { strategy = StrategyEnum.valueOf(prefix); } catch (IllegalArgumentException e) { CustomStrategy customStrategy = registeredLocationStrategies.get(prefix); if (customStrategy != null) { strategy = customStrategy; } } } findByCoordinates.criteria = criteria; return strategy; }

Target:
protected static Strategy parseLocator(FindByCoordinates findByCoordinates, String locator) { String prefix = null; String criteria = locator; if (!locator.startsWith(" String[] locatorParts = locator.split("[=:]", 2); if (locatorParts.length == 2) { if (locator.charAt(locatorParts[0].length()) == '=') { System.out.println( "*WARN* '=' is deprecated as locator strategy separator. ':' should be used instead"); } prefix = locatorParts[0].trim().toUpperCase(); criteria = locatorParts[1].trim(); } } Strategy strategy = StrategyEnum.DEFAULT; if (prefix != null) { try { strategy = StrategyEnum.valueOf(prefix); } catch (IllegalArgumentException e) { CustomStrategy customStrategy = registeredLocationStrategies.get(prefix); if (customStrategy != null) { strategy = customStrategy; } } } findByCoordinates.criteria = criteria; return strategy; }
Source:
private void fetchPinotData() { long startTimeNanos = System.nanoTime(); try { Map<ServerInstance, DataTable> dataTableMap = queryPinot(session, split); dataTableMap.values().stream() .filter(table -> table != null && table.getNumberOfRows() > 0) .forEach(dataTable -> { checkExceptions(dataTable, split, this.pinotConfig.isRetryPinotException()); int estimatedTableSizeInBytes = IntStream.rangeClosed(0, dataTable.getDataSchema().size() - 1) .map(i -> getEstimatedColumnSizeInBytes(dataTable.getDataSchema().getColumnDataType(i)) * dataTable.getNumberOfRows()) .reduce(0, Integer::sum); dataTableList.add(new PinotDataTableWithSize(dataTable, estimatedTableSizeInBytes)); estimatedMemoryUsageInBytes += estimatedTableSizeInBytes; }); isPinotDataFetched = true; } finally { readTimeNanos += System.nanoTime() - startTimeNanos; } }

Target:
private void fetchPinotData() { long startTimeNanos = System.nanoTime(); try { Map<ServerInstance, DataTable> dataTableMap = queryPinot(session, split); dataTableMap.values().stream() .filter(table -> table != null && table.getNumberOfRows() > 0) .forEach(dataTable -> { checkExceptions(dataTable, split, PinotSessionProperties.isMarkDataFetchExceptionsAsRetriable(session)); int estimatedTableSizeInBytes = IntStream.rangeClosed(0, dataTable.getDataSchema().size() - 1) .map(i -> getEstimatedColumnSizeInBytes(dataTable.getDataSchema().getColumnDataType(i)) * dataTable.getNumberOfRows()) .reduce(0, Integer::sum); dataTableList.add(new PinotDataTableWithSize(dataTable, estimatedTableSizeInBytes)); estimatedMemoryUsageInBytes += estimatedTableSizeInBytes; }); isPinotDataFetched = true; } finally { readTimeNanos += System.nanoTime() - startTimeNanos; } }
Source:
private void initThreadsPerCore() { EnableableFormLabel label = new EnableableFormLabel(); label.setText(constants.threadsPerCore()); threadsPerCoreEditor = new ListModelListBoxOnlyEditor<>(IntegerRenderer.instance(), new ModeSwitchingVisibilityRenderer()); threadsPerCoreEditorWithInfoIcon = new EntityModelDetachableWidgetWithInfo(label, threadsPerCoreEditor); threadsPerCoreEditorWithInfoIcon.setExplanation(templates.italicText(messages.threadsPerCoreInfo())); }

Target:
private void initThreadsPerCore() { EnableableFormLabel label = new EnableableFormLabel(); label.setText(constants.threadsPerCore()); threadsPerCoreEditor = new ListModelListBoxOnlyEditor<>(IntegerRenderer.instance(), new ModeSwitchingVisibilityRenderer()); threadsPerCoreEditorWithInfoIcon = new EntityModelDetachableWidgetWithInfo(label, threadsPerCoreEditor); threadsPerCoreEditorWithInfoIcon.setExplanation(multiLineItalicSafeHtml(messages.threadsPerCoreInfo())); }
Source:
public void testDecode() throws Exception { OpenGtsProtocolDecoder decoder = new OpenGtsProtocolDecoder(new OpenGtsProtocol()); verifyNull(decoder, request( "/?bat=0")); verifyPosition(decoder, request( "/?id=123456789012345&dev=dev_name&acct=account&batt=0&code=0xF020&alt=160.5&gprmc=$GPRMC,191555,A,5025.46624,N,3030.39937,E,0.000000,0.000000,200218,,*2F")); }

Target:
public void testDecode() throws Exception { OpenGtsProtocolDecoder decoder = new OpenGtsProtocolDecoder(new OpenGtsProtocol()); verifyPosition(decoder, request( "/?id=123456789012345&dev=dev_name&acct=account&batt=0&code=0xF020&alt=160.5&gprmc=$GPRMC,191555,A,5025.46624,N,3030.39937,E,0.000000,0.000000,200218,,*2F")); }
Source:
protected void checkPaymentDetailPropertyMaxLength(PaymentDetail paymentDetail, MessageMap errorMap) { for (String propertyName : paymentDetailPropertiesToCheckMaxLength) { String propertyValue = (String) ObjectUtils.getPropertyValue(paymentDetail, propertyName); if (StringUtils.isNotEmpty(propertyValue)) { Integer maxLength = dataDictionaryService.getAttributeMaxLength(PaymentDetail.class, propertyName); if ((maxLength != null) && (maxLength < propertyValue.length())) { String errorLabel = dataDictionaryService.getAttributeErrorLabel(PaymentDetail.class, propertyName); errorLabel += " with the value '" + propertyValue + "'"; errorMap.putError(KFSConstants.GLOBAL_ERRORS, RiceKeyConstants.ERROR_MAX_LENGTH, errorLabel, maxLength.toString()); } } } if (LOG.isDebugEnabled()) { LOG.debug("After checkPaymentDetailPropertyMaxLength: " + printErrorMap(errorMap)); } }

Target:
protected void checkPaymentDetailPropertyMaxLength(PaymentDetail paymentDetail, MessageMap errorMap) { for (String propertyName : paymentDetailPropertiesToCheckMaxLength) { String propertyValue = (String) ObjectUtils.getPropertyValue(paymentDetail, propertyName); if (StringUtils.isNotEmpty(propertyValue)) { Integer maxLength = dataDictionaryService.getAttributeMaxLength(PaymentDetail.class, propertyName); if (maxLength == null) { LOG.warn("checkPaymentDetailPropertyMaxLength, PaymentDetail field '" + propertyName + "' does not have a max length specified in the data dictionary"); } else if (maxLength < propertyValue.length()) { String errorLabel = dataDictionaryService.getAttributeErrorLabel(PaymentDetail.class, propertyName); errorLabel += " with the value '" + propertyValue + "'"; errorMap.putError(KFSConstants.GLOBAL_ERRORS, RiceKeyConstants.ERROR_MAX_LENGTH, errorLabel, maxLength.toString()); } } } if (LOG.isDebugEnabled()) { LOG.debug("After checkPaymentDetailPropertyMaxLength: " + printErrorMap(errorMap)); } }
Source:
public boolean handhshake(String host, int port) throws URISyntaxException, InterruptedException { URI uri = new URI(url); EventLoopGroup group = new NioEventLoopGroup(); Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .handler(new WebSocketClientInitializer()); channel = b.connect(host, port).sync().channel(); WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory. newHandshaker(uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders()); boolean isDone = handshaker.handshake(channel).sync().isSuccess(); return isDone; }

Target:
public boolean handhshake(String host, int port) throws InterruptedException, URISyntaxException { URI uri = new URI(url); EventLoopGroup group = new NioEventLoopGroup(); Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .handler(new WebSocketClientInitializer()); channel = b.connect(host, port).sync().channel(); WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory. newHandshaker(uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders()); boolean isDone = handshaker.handshake(channel).sync().isSuccess(); return isDone; }
Source:
protected Set<String> getFieldsToLoad() { return Stream.of( getIdField(), getTermVectorField(), StatusField.FOLLOWERS_COUNT.name, StatusField.FRIENDS_COUNT.name, StatusField.IN_REPLY_TO_STATUS_ID.name).collect(Collectors.toCollection(HashSet::new)); }

Target:
protected Set<String> getFieldsToLoad() { return new HashSet<>(Arrays.asList( getIdField(), getTermVectorField(), StatusField.FOLLOWERS_COUNT.name, StatusField.FRIENDS_COUNT.name, StatusField.IN_REPLY_TO_STATUS_ID.name) ); }
Source:
public void testCharTrailingSpace() throws Exception { execute("CREATE TABLE tpch.char_trailing_space (x char(10))"); assertUpdate("INSERT INTO char_trailing_space VALUES ('test')", 1); assertQuery("SELECT * FROM char_trailing_space WHERE x = char 'test'", "VALUES 'test'"); assertQuery("SELECT * FROM char_trailing_space WHERE x = char 'test '", "VALUES 'test'"); assertQuery("SELECT * FROM char_trailing_space WHERE x = char 'test '", "VALUES 'test'"); assertEquals(getQueryRunner().execute("SELECT * FROM char_trailing_space WHERE x = char ' test'").getRowCount(), 0); assertUpdate("DROP TABLE char_trailing_space"); }

Target:
public void testCharTrailingSpace() throws Exception { execute("CREATE TABLE tpch.char_trailing_space (x char(10))"); assertUpdate("INSERT INTO char_trailing_space VALUES ('test')", 1); assertQuery("SELECT * FROM char_trailing_space WHERE x = char 'test'", "VALUES 'test'"); assertQuery("SELECT * FROM char_trailing_space WHERE x = char 'test '", "VALUES 'test'"); assertQuery("SELECT * FROM char_trailing_space WHERE x = char 'test '", "VALUES 'test'"); assertEquals(getQueryRunner().execute("SELECT * FROM char_trailing_space WHERE x = char ' test'").getRowCount(), 0); Map<String, String> properties = ImmutableMap.of("deprecated.legacy-char-to-varchar-coercion", "true"); Map<String, String> connectorProperties = ImmutableMap.of("connection-url", mysqlServer.getJdbcUrl()); try (QueryRunner queryRunner = new DistributedQueryRunner(getSession(), 3, properties);) { queryRunner.installPlugin(new MySqlPlugin()); queryRunner.createCatalog("mysql", "mysql", connectorProperties); assertEquals(queryRunner.execute("SELECT * FROM char_trailing_space WHERE x = char 'test'").getRowCount(), 0); assertEquals(queryRunner.execute("SELECT * FROM char_trailing_space WHERE x = char 'test '").getRowCount(), 0); assertEquals(queryRunner.execute("SELECT * FROM char_trailing_space WHERE x = char 'test '").getRowCount(), 0); MaterializedResult result = queryRunner.execute("SELECT * FROM char_trailing_space WHERE x = char 'test '"); assertEquals(result.getRowCount(), 1); assertEquals(result.getMaterializedRows().get(0).getField(0), "test "); } assertUpdate("DROP TABLE char_trailing_space"); }
Source:
public Map<String, List<String>> getInfrasToPoliciesMapping() { Map<String, List<String>> mapping = new HashMap<>(); String fileName = null; try { fileName = PAResourceManagerProperties.RM_NODESOURCE_INFRA_POLICY_MAPPING.getValueAsString(); if (!(new File(fileName).isAbsolute())) { fileName = PAResourceManagerProperties.RM_HOME.getValueAsString() + File.separator + fileName; } try (FileReader fr = new FileReader(fileName); BufferedReader br = new BufferedReader(fr)) { String line = br.readLine(); while (line != null) { final String[] split = line.split(","); if (split.length > 1) { List<String> strings = Arrays.asList(split); String infra = strings.get(0).trim(); List<String> policies = strings.subList(1, strings.size()) .stream() .map(String::trim) .collect(Collectors.toList()); mapping.put(infra, policies); } line = br.readLine(); } } } catch (Exception e) { logger.error("Error when loading infrastructure definition file : " + fileName, e); } return mapping; }

Target:
public Map<String, List<String>> getInfrasToPoliciesMapping() { Map<String, List<String>> mapping = new HashMap<>(); String fileName = null; try { fileName = PAResourceManagerProperties.RM_NODESOURCE_INFRA_POLICY_MAPPING.getValueAsString(); if (!(new File(fileName).isAbsolute())) { fileName = PAResourceManagerProperties.RM_HOME.getValueAsString() + File.separator + fileName; } mapping = Files.readAllLines(Paths.get(fileName)) .stream() .map(line -> line.split(",")) .filter(array -> array.length > 1) .map(Arrays::asList) .collect(Collectors.toMap(list -> list.get(0).trim(), list -> list.subList(1, list.size()) .stream() .map(String::trim) .collect(Collectors.toList()))); } catch (Exception e) { logger.error("Error when loading infrastructure definition file : " + fileName, e); } return mapping; }
Source:
public ApplePayDecrypter(ConnectorConfiguration configuration, ObjectMapper objectMapper) { this.objectMapper = objectMapper; ApplePayConfig applePayConfig = configuration.getWorldpayConfig().getApplePayConfig(); try { privateKey = generatePrivateKey(BASE64_DECODER.decode(applePayConfig.getPrivateKey())); certificate = generateCertificate(BASE64_DECODER.decode(applePayConfig.getPublicCertificate())); } catch (Exception e) { throw new RuntimeException(e); } long daysToExpiry = TimeUnit.MILLISECONDS.toDays(certificate.getNotAfter().getTime() - new Date().getTime()); LOGGER.info("The Apple Pay payment processing cert will expire in days", daysToExpiry); }

Target:
public ApplePayDecrypter(ConnectorConfiguration configuration, ObjectMapper objectMapper) { this.objectMapper = objectMapper; ApplePayConfig applePayConfig = configuration.getWorldpayConfig().getApplePayConfig(); try { privateKey = generatePrivateKey(BASE64_DECODER.decode(applePayConfig.getPrivateKey())); certificate = generateCertificate(BASE64_DECODER.decode(applePayConfig.getPublicCertificate())); } catch (Exception e) { throw new RuntimeException(e); } long daysToExpiry = DAYS.between(Instant.now(), certificate.getNotAfter().toInstant()); LOGGER.info("The Apple Pay payment processing cert will expire in days", daysToExpiry); }
Source:
public static <T> T createProxy( Optional<TrustContext> trustContext, String uri, Class<T> type, AuxiliaryRemotingParameters parameters) { return Suppliers.memoizeWithExpiration( () -> ConjureJavaRuntimeTargetFactory.DEFAULT.createProxy(trustContext, uri, type, parameters) .instance(), Duration.ofMinutes(10).toMinutes(), TimeUnit.MINUTES).get(); }

Target:
public static <T> T createProxy( Optional<TrustContext> trustContext, String uri, Class<T> type, AuxiliaryRemotingParameters parameters) { return Suppliers.memoizeWithExpiration( () -> ConjureJavaRuntimeTargetFactory.DEFAULT.createProxy(trustContext, uri, type, parameters) .instance(), Duration.ofMinutes(30).toMinutes(), TimeUnit.MINUTES).get(); }
Source:
private void listen() { try { socket = new ServerSocket(PORT); logger.info("Started Language Server Protocol (LSP) service on port {}", PORT); while (!socket.isClosed()) { logger.debug("Going to wait for a client to connect"); try { Socket client = socket.accept(); new Thread(() -> { handleConnection(client); }, "Client " + client.getRemoteSocketAddress()).start(); } catch (IOException e) { logger.debug("Error accepting the client connection: {}", e.getMessage()); } } } catch (IOException e) { logger.error("Error starting the Language Server", e); } }

Target:
private void listen() { try { socket = new ServerSocket(PORT); logger.info("Started Language Server Protocol (LSP) service on port {}", PORT); while (!socket.isClosed()) { logger.debug("Going to wait for a client to connect"); try { Socket client = socket.accept(); new Thread(() -> { handleConnection(client); }, "Client " + client.getRemoteSocketAddress()).start(); } catch (IOException e) { if (!socket.isClosed()) { logger.error("Error accepting client connection: {}", e.getMessage()); } } } } catch (IOException e) { logger.error("Error starting the Language Server", e); } }
Source:
public String getLargestImage(int minImageWidth) { if (!mContentContainsImages) { return null; } String currentImageUrl = null; int currentMaxWidth = minImageWidth; Matcher imgMatcher = IMG_TAG_PATTERN.matcher(mContent); while (imgMatcher.find()) { String imageTag = imgMatcher.group(0); String imageUrl = imgMatcher.group(1); int width = Math.max(ReaderHtmlUtils.getWidthAttrValue(imageTag), ReaderHtmlUtils.getIntQueryParam(imageUrl, "w")); if (width > currentMaxWidth) { currentImageUrl = imageUrl; currentMaxWidth = width; } else { currentImageUrl = ReaderHtmlUtils.getSrcsetImageForTag(imageTag, minImageWidth); if (currentImageUrl == null && hasSuitableClassForFeaturedImage(imageTag)) { currentImageUrl = imageUrl; } if (currentImageUrl == null) { currentImageUrl = ReaderHtmlUtils.getLargeFileAttr(imageTag); } } } return currentImageUrl; }

Target:
public String getLargestImage(int minImageWidth) { if (!mContentContainsImages) { return null; } String currentImageUrl = null; int currentMaxWidth = minImageWidth; Matcher imgMatcher = IMG_TAG_PATTERN.matcher(mContent); while (imgMatcher.find()) { String imageTag = imgMatcher.group(0); String imageUrl = imgMatcher.group(1); int width = Math.max(ReaderHtmlUtils.getWidthAttrValue(imageTag), ReaderHtmlUtils.getIntQueryParam(imageUrl, "w")); if (width > currentMaxWidth) { currentImageUrl = imageUrl; currentMaxWidth = width; } SrcsetImage bestFromSrcset = ReaderHtmlUtils.getLargestSrcsetImageForTag(imageTag); if (bestFromSrcset != null && bestFromSrcset.getWidth() > currentMaxWidth) { currentMaxWidth = bestFromSrcset.getWidth(); currentImageUrl = bestFromSrcset.getUrl(); } if (currentImageUrl == null && hasSuitableClassForFeaturedImage(imageTag)) { currentImageUrl = imageUrl; } if (currentImageUrl == null) { currentImageUrl = ReaderHtmlUtils.getLargeFileAttr(imageTag); } } return currentImageUrl; }
Source:
Depgraph withNonrootsAsRoots() { Depgraph res = new Depgraph(); res.roots.addAll(roots); res.roots.addAll(nonroots); res.rootExterns.addAll(rootExterns); res.nonrootExterns.addAll(nonrootExterns); return res; }

Target:
Depgraph withNonrootsAsRoots() { Depgraph res = new Depgraph(); res.roots.addAll(roots); res.roots.addAll(nonroots); res.rootExterns.addAll(rootExterns); res.rootExterns.addAll(nonrootExterns); return res; }
Source:
private void setBlindTrustSSLContext() { try { TrustStrategy acceptingTrustStrategy = (cert, authType) -> true; sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); } catch (KeyStoreException | KeyManagementException | NoSuchAlgorithmException e) { e.printStackTrace(); } }

Target:
private void setBlindTrustSSLContext() { try { TrustStrategy acceptingTrustStrategy = (cert, authType) -> true; sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); } catch (KeyStoreException | KeyManagementException | NoSuchAlgorithmException e) { throw new RuntimeException(e.getMessage(), e); } }
Source:
public String execute(CommandContext commandContext) { AuthorizationManager authorizationManager = commandContext.getAuthorizationManager(); authorizationManager.checkCamundaAdmin(); ResourceEntity licenseResource = commandContext.getResourceManager().findLicenseKeyResource(); if (licenseResource != null) { return new String(licenseResource.getBytes()); } PropertyEntity licenseProperty = commandContext.getPropertyManager().findPropertyById(LICENSE_KEY_PROPERTY_NAME); if (licenseProperty != null) { return licenseProperty.getValue(); } return null; }

Target:
public String execute(CommandContext commandContext) { AuthorizationManager authorizationManager = commandContext.getAuthorizationManager(); authorizationManager.checkCamundaAdmin(); ResourceEntity licenseResource = commandContext.getResourceManager().findLicenseKeyResource(); if (licenseResource != null) { return new String(licenseResource.getBytes(), StandardCharsets.UTF_8); } PropertyEntity licenseProperty = commandContext.getPropertyManager().findPropertyById(LICENSE_KEY_PROPERTY_NAME); if (licenseProperty != null) { return licenseProperty.getValue(); } return null; }
Source:
public void testAttemptsToStopStartedServicesOnInitFailure() { Service s1 = new ParentTestService(); FancyCacheProvider s2 = new FancyCacheProvider(); ServiceLocator locator = new ServiceLocator(s1, s2); try { locator.startAllServices(); } catch (Exception e) { } assertThat(s2.startStopCounter, is(0)); }

Target:
public void testAttemptsToStopStartedServicesOnInitFailure() { Service s1 = new ParentTestService(); FancyCacheProvider s2 = new FancyCacheProvider(); ServiceLocator locator = new ServiceLocator(s1, s2); try { locator.startAllServices(); fail(); } catch (Exception e) { assertThat(e, instanceOf(RuntimeException.class)); assertThat(e.getMessage(), is("Implement me!")); } assertThat(s2.startStopCounter, is(0)); }
Source:
public void notifyClusterListeners(Collection<? extends Event> events, UUID uuid) { for (Event event : events) { if (event.isPre()) { throw new IllegalArgumentException("Events for cluster listener should never be pre change"); } switch (event.getType()) { case CACHE_ENTRY_MODIFIED: for (ListenerInvocation listener : cacheEntryModifiedListeners) { if (listener.clustered && uuid.equals(clusterListenerIDs.get(listener.target))) { listener.invoke(event, true, true); } } break; case CACHE_ENTRY_CREATED: for (ListenerInvocation listener : cacheEntryCreatedListeners) { if (listener.clustered && uuid.equals(clusterListenerIDs.get(listener.target))) { listener.invoke(event, true, true); } } break; case CACHE_ENTRY_REMOVED: for (ListenerInvocation listener : cacheEntryRemovedListeners) { if (listener.clustered && uuid.equals(clusterListenerIDs.get(listener.target))) { listener.invoke(event, true, true); } } break; default: throw new IllegalArgumentException("Unexpected event type encountered!"); } } }

Target:
public void notifyClusterListeners(Collection<? extends Event> events, UUID uuid) { for (Event event : events) { if (event.isPre()) { throw new IllegalArgumentException("Events for cluster listener should never be pre change"); } switch (event.getType()) { case CACHE_ENTRY_MODIFIED: for (ListenerInvocation listener : cacheEntryModifiedListeners) { if (listener.clustered && uuid.equals(listener.generatedId)) { listener.invoke(event, true, true); } } break; case CACHE_ENTRY_CREATED: for (ListenerInvocation listener : cacheEntryCreatedListeners) { if (listener.clustered && uuid.equals(listener.generatedId)) { listener.invoke(event, true, true); } } break; case CACHE_ENTRY_REMOVED: for (ListenerInvocation listener : cacheEntryRemovedListeners) { if (listener.clustered && uuid.equals(listener.generatedId)) { listener.invoke(event, true, true); } } break; default: throw new IllegalArgumentException("Unexpected event type encountered!"); } } }