auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static synchronized void loadProperties() { if (errorStrings == null) { <START> try (InputStream fileInputStream = EventHubErrorCodeStrings.class.getClassLoader().getResource((ERROR_STRINGS_FILE_NAME)).openStream()) { <END> errorStrings = new Properties(); errorStrings.load(fileInputStream); } catch (IOException ex) { ex.printStackTrace(); } } }</code><technical_language>suggestion try (InputStream fileInputStream = EventHubErrorCodeStrings.class.getClassLoader().getResource(ERROR_STRINGS_FILE_NAME).openStream()) {</technical_language>

Target:
private static synchronized void loadProperties() { if (errorStrings == null) { try (InputStream fileInputStream = EventHubErrorCodeStrings.class.getClassLoader() .getResource(ERROR_STRINGS_FILE_NAME).openStream()) { errorStrings = new Properties(); errorStrings.load(fileInputStream); } catch (IOException ex) { ex.printStackTrace(); } } }
Source:
<code>public void testExceptionHandlingINFO() throws Exception { TestAppender appender = new TestAppender(); Logger logger = LogUtil.getRootLogger(); logger.setLevel(Level.DEBUG); logger.addAppender(appender); boolean makeSureNoExceptionIsThrown = false; try { mockDatabase(true); appConstants.put("configurations."+getConfigurationName()+".reportLevel", "INFO"); ClassLoaderManager manager = new ClassLoaderManager(ibisContext); ClassLoader config = manager.get(getConfigurationName()); makeSureNoExceptionIsThrown = true; assertNull(config); } finally { logger.removeAppender(appender); } assertTrue(makeSureNoExceptionIsThrown); List<LoggingEvent> log = appender.getLog(); LoggingEvent firstLogEntry = log.get(log.size()-1); assertEquals(IbisContext.class.getCanonicalName(), firstLogEntry.getLoggerName()); assertEquals(Level.INFO, firstLogEntry.getLevel()); String msg = (String) firstLogEntry.getMessage(); <START> assertTrue(msg.contains("error configuring ClassLoader for configuration [")); END> assertTrue(msg.endsWith("]")); }</code><technical_language>Dit kan je mooier doen als: import org.hamcrest.core.StringEndsWith; assertThat(msg,StringEndsWith.endsWith(...))</technical_language>

Target:
public void testExceptionHandlingINFO() throws Exception { TestAppender appender = new TestAppender(); Logger logger = LogUtil.getRootLogger(); logger.setLevel(Level.DEBUG); logger.addAppender(appender); boolean makeSureNoExceptionIsThrown = false; try { mockDatabase(true); appConstants.put("configurations."+getConfigurationName()+".reportLevel", "INFO"); ClassLoaderManager manager = new ClassLoaderManager(ibisContext); ClassLoader config = manager.get(getConfigurationName()); makeSureNoExceptionIsThrown = true; assertNull(config); } finally { logger.removeAppender(appender); } assertTrue(makeSureNoExceptionIsThrown); List<LoggingEvent> log = appender.getLog(); LoggingEvent firstLogEntry = log.get(log.size()-1); assertEquals(IbisContext.class.getCanonicalName(), firstLogEntry.getLoggerName()); assertEquals(Level.INFO, firstLogEntry.getLevel()); String msg = (String) firstLogEntry.getMessage(); assertThat(msg, StringContains.containsString(ERROR_PREFIX)); assertThat(msg, Matchers.endsWith(ERROR_SUFFIX)); }
Source:
<code>private void commonSectionFetchOnCatch(Throwable caught) { tocDrawer.setSlidingEnabled(false); <START> searchArticlesFragment.setTocEnabled(false); <END> if (caught instanceof SectionsFetchException) { if (((SectionsFetchException) caught).getCode().equals("missingtitle") || ((SectionsFetchException) caught).getCode().equals("invalidtitle")) { searchArticlesFragment.setTocHidden(true); ViewAnimations.crossFade(loadProgress, pageDoesNotExistError); } } else if (Utils.throwableContainsSpecificType(caught, SSLException.class)) { if (WikipediaApp.getInstance().incSslFailCount() < 2) { WikipediaApp.getInstance().setSslFallback(true); showNetworkError(); try { connectionIssueFunnel.logConnectionIssue("mdot", "commonSectionFetchOnCatch"); } catch (Exception e) { } } else { showNetworkError(); try { connectionIssueFunnel.logConnectionIssue("desktop", "commonSectionFetchOnCatch"); } catch (Exception e) { } } } else if (caught instanceof ApiException) { showNetworkError(); } else { throw new RuntimeException(caught); } }</code><technical_language>do setTocHidden here, instead of there? hidden for kind of error</technical_language>

Target:
private void commonSectionFetchOnCatch(Throwable caught) { tocDrawer.setSlidingEnabled(false); searchArticlesFragment.setTocEnabled(false); searchArticlesFragment.setTocHidden(true); if (caught instanceof SectionsFetchException) { if (((SectionsFetchException) caught).getCode().equals("missingtitle") || ((SectionsFetchException) caught).getCode().equals("invalidtitle")) { ViewAnimations.crossFade(loadProgress, pageDoesNotExistError); } } else if (Utils.throwableContainsSpecificType(caught, SSLException.class)) { if (WikipediaApp.getInstance().incSslFailCount() < 2) { WikipediaApp.getInstance().setSslFallback(true); showNetworkError(); try { connectionIssueFunnel.logConnectionIssue("mdot", "commonSectionFetchOnCatch"); } catch (Exception e) { } } else { showNetworkError(); try { connectionIssueFunnel.logConnectionIssue("desktop", "commonSectionFetchOnCatch"); } catch (Exception e) { } } } else if (caught instanceof ApiException) { showNetworkError(); } else { throw new RuntimeException(caught); } }
Source:
<code>public void setCacheContainer(BasicCacheContainer cacheContainer) { this.cacheContainer = cacheContainer; this.setCacheFromComponent = true; <START> System.out.println("===========<created"); <END> }</code><technical_language>Remove</technical_language>

Target:
public void setCacheContainer(BasicCacheContainer cacheContainer) { this.cacheContainer = cacheContainer; this.setCacheFromComponent = true; }
Source:
<code><START> public void executeCommand(Command command, ExecutionHandlerContext context) { <END> List<ByteArrayWrapper> commandElems = command.getProcessedCommandWrappers(); ByteArrayWrapper key = command.getKey(); ByteArrayWrapper newKey = commandElems.get(2); RedisKeyCommands redisKeyCommands = getRedisKeyCommands(context); if (key.equals(newKey)) { command.setResponse(Coder.getSimpleStringResponse(context.getByteBufAllocator(), "OK")); return; } if (!redisKeyCommands.rename(key, newKey)) { command.setResponse( Coder.getErrorResponse(context.getByteBufAllocator(), RedisConstants.ERROR_NO_SUCH_KEY)); return; } command.setResponse(Coder.getSimpleStringResponse(context.getByteBufAllocator(), "OK")); }</code><technical_language>changes incorrect merge perhaps</technical_language>

Target:
public RedisResponse executeCommand(Command command, ExecutionHandlerContext context) { List<ByteArrayWrapper> commandElems = command.getProcessedCommandWrappers(); ByteArrayWrapper key = command.getKey(); ByteArrayWrapper newKey = commandElems.get(2); RedisKeyCommands redisKeyCommands = getRedisKeyCommands(context); if (key.equals(newKey)) { return RedisResponse.string("OK"); } if (!redisKeyCommands.rename(key, newKey)) { return RedisResponse.error(ERROR_NO_SUCH_KEY); } return RedisResponse.string("OK"); }
Source:
<code>private long determineCanonicalizedLength(InputStream raw) throws IOException { long length = 0; <START> final EolCanonicalizingInputStream is = new EolCanonicalizingInputStream( <END> raw); for (int read = 0; read != -1; read = is.read(contentReadBuffer)) { length += read; } return length; }</code><technical_language>Style-nit: I if drop final keyword this fit line. final declaration in a short method</technical_language>

Target:
private long determineCanonicalizedLength(InputStream raw) throws IOException { long length = 0; final InputStream is = new EolCanonicalizingInputStream(raw); for (;;) { int r = is.read(contentReadBuffer); if (r <= 0) break; length += r; } return length; }
Source:
<code>public ActionResult execute() { String frontendUrl = getRequestParamValue("frontendUrl"); if (frontendUrl == null) { frontendUrl = ""; } AuthInfo output; if (userInfo == null) { output = new AuthInfo( gateKeeper.getLoginUrl(frontendUrl + Const.WebPageURIs.STUDENT_HOME_PAGE), gateKeeper.getLoginUrl(frontendUrl + Const.WebPageURIs.INSTRUCTOR_HOME_PAGE), gateKeeper.getLoginUrl(frontendUrl + Const.WebPageURIs.ADMIN_HOME_PAGE) ); } else { String googleId = userInfo.getId(); AccountAttributes accountInfo = logic.getAccount(googleId); String institute = null; if (accountInfo != null) { institute = accountInfo.getInstitute(); } output = new AuthInfo(userInfo, institute, authType == AuthType.MASQUERADE); } String csrfToken = StringHelper.encrypt(req.getSession().getId()); String existingCsrfToken = HttpRequestHelper.getCookieValueFromRequest(req, Const.CsrfConfig.TOKEN_COOKIE_NAME); if (!csrfToken.equals(existingCsrfToken)) { Cookie csrfTokenCookie = new Cookie(Const.CsrfConfig.TOKEN_COOKIE_NAME, csrfToken); csrfTokenCookie.setSecure(!Config.isDevServer()); csrfTokenCookie.setPath("/"); resp.addCookie(csrfTokenCookie); ArrayList<Cookie> cookieLst = new ArrayList<>(); cookieLst.add(csrfTokenCookie); <START> return new JsonResult(output, cookieLst); <END> } return new JsonResult(output); }</code><technical_language>is a faster method create list guava Arrays</technical_language>

Target:
public ActionResult execute() { String frontendUrl = getRequestParamValue("frontendUrl"); if (frontendUrl == null) { frontendUrl = ""; } AuthInfo output; if (userInfo == null) { output = new AuthInfo( gateKeeper.getLoginUrl(frontendUrl + Const.WebPageURIs.STUDENT_HOME_PAGE), gateKeeper.getLoginUrl(frontendUrl + Const.WebPageURIs.INSTRUCTOR_HOME_PAGE), gateKeeper.getLoginUrl(frontendUrl + Const.WebPageURIs.ADMIN_HOME_PAGE) ); } else { String googleId = userInfo.getId(); AccountAttributes accountInfo = logic.getAccount(googleId); String institute = null; if (accountInfo != null) { institute = accountInfo.getInstitute(); } output = new AuthInfo(userInfo, institute, authType == AuthType.MASQUERADE); } String csrfToken = StringHelper.encrypt(req.getSession().getId()); String existingCsrfToken = HttpRequestHelper.getCookieValueFromRequest(req, Const.CsrfConfig.TOKEN_COOKIE_NAME); if (!csrfToken.equals(existingCsrfToken)) { Cookie csrfTokenCookie = new Cookie(Const.CsrfConfig.TOKEN_COOKIE_NAME, csrfToken); csrfTokenCookie.setSecure(!Config.isDevServer()); csrfTokenCookie.setPath("/"); List<Cookie> cookieList = Arrays.asList(csrfTokenCookie); return new JsonResult(output, cookieList); } return new JsonResult(output); }
Source:
<code>private void checkRoleIsAssumableWithoutExternalId(CredentialVerificationContext credentialVerificationContext, AwsCredentialView awsCredential) { if (credentialVerificationContext.getCreationVerification()) { String roleArn = awsCredential.getRoleArn(); try { credentialClient.retrieveSessionCredentialsWithoutExternalId(awsCredential); <START> String message = String.format("CDP Control Pane is able to perform 'sts:AssumeRole' on '%s' role without external id. " + <END> "The role is vulnerable and could be exploited by confused deputy attacks. " + "Please update the role's trust relationship to have a condition on external id " + "or re-create the role with external id configured in the create role wizard.", roleArn); LOGGER.warn(message); throw new AwsPossibleConfusedDeputyException(message); } catch (AmazonClientException ae) { if (ae.getMessage().contains(ROLE_IS_NOT_ASSUMABLE_ERROR_MESSAGE_INDICATOR)) { String msg = String.format("Consider the specified role as secured. " + "CDP Control Pane is not authorized to perform sts:AssumeRole on '%s' role without external Id.", roleArn); LOGGER.info(msg); } else { throw ae; } } } }</code><technical_language>I show is external id is missing ? I guess lets check</technical_language>

Target:
private void checkRoleIsAssumableWithoutExternalId(CredentialVerificationContext credentialVerificationContext, AwsCredentialView awsCredential) { if (credentialVerificationContext.getCreationVerification()) { String roleArn = awsCredential.getRoleArn(); try { credentialClient.retrieveSessionCredentialsWithoutExternalId(awsCredential); String message = String.format("CDP Control Pane is able to perform 'sts:AssumeRole' on '%s' role without external id. " + "The role is vulnerable and could be exploited by confused deputy attacks. " + "Please update the role's trust relationship to have a condition on external id " + "or re-create the role with external id configured in the create role wizard.", roleArn); LOGGER.warn(message); throw new AwsConfusedDeputyException(message); } catch (AmazonClientException ae) { if (ae.getMessage().contains(ROLE_IS_NOT_ASSUMABLE_ERROR_MESSAGE_INDICATOR)) { String msg = String.format("Consider the specified role as secured. " + "CDP Control Pane is not authorized to perform sts:AssumeRole on '%s' role without external Id.", roleArn); LOGGER.info(msg); } else { throw ae; } } } }
Source:
<code>public static Optional<InsightCard> getInsights(final Long accountId, final DeviceId deviceId, final DeviceDataInsightQueryDAO deviceDataDAO, final SleepStatsDAODynamoDB sleepStatsDAODynamoDB) { final Optional<Integer> timeZoneOffsetOptional = sleepStatsDAODynamoDB.getTimeZoneOffset(accountId); if (!timeZoneOffsetOptional.isPresent()) { <START> LOGGER.debug("action=insight_absent-insight=bed_light_duration-reason=timezoneoffset_absent-account_id={}", accountId); <END> return Optional.absent(); } final Integer timeZoneOffset = timeZoneOffsetOptional.get(); final List<DeviceData> deviceDatas = getDeviceData(accountId, deviceId, deviceDataDAO, timeZoneOffset); if (deviceDatas.isEmpty()) { LOGGER.debug("action=insight_absent-insight=bed_light_duration-reason=device_datas_empty-account_id={}", accountId); return Optional.absent(); } final Integer avgLightOn = getInsightsHelper(deviceDatas, accountId); return scoreCardBedLightDuration(avgLightOn, accountId); }</code><technical_language>Format? action=insight-absent insight=bed-light-duration reason=timezone-offset-absent account_id={}</technical_language>

Target:
public static Optional<InsightCard> getInsights(final Long accountId, final DeviceId deviceId, final DeviceDataInsightQueryDAO deviceDataDAO, final SleepStatsDAODynamoDB sleepStatsDAODynamoDB) { final Optional<Integer> timeZoneOffsetOptional = sleepStatsDAODynamoDB.getTimeZoneOffset(accountId); if (!timeZoneOffsetOptional.isPresent()) { LOGGER.debug("action=insight_absent insight=bed_light_duration reason=timezoneoffset_absent account_id={}", accountId); return Optional.absent(); } final Integer timeZoneOffset = timeZoneOffsetOptional.get(); final List<DeviceData> deviceDatas = getDeviceData(accountId, deviceId, deviceDataDAO, timeZoneOffset); if (deviceDatas.isEmpty()) { LOGGER.debug("action=insight_absent insight=bed_light_duration reason=device_datas_empty account_id={}", accountId); return Optional.absent(); } final Integer avgLightOn = getInsightsHelper(deviceDatas, accountId); return scoreCardBedLightDuration(avgLightOn, accountId); }
Source:
<code>private void configureFetchSpec(CloneOperation op, GitRepositoryInfo gitRepositoryInfo, String remoteName) { <START> for (String fetchRefSpec : gitRepositoryInfo.getFetchRefSpecs()) { <END> op.addPostCloneTask(new ConfigureFetchAfterCloneTask(remoteName, fetchRefSpec)); } }</code><technical_language>style nit: curly braces single line blocks</technical_language>

Target:
private void configureFetchSpec(CloneOperation op, GitRepositoryInfo gitRepositoryInfo, String remoteName) { for (String fetchRefSpec : gitRepositoryInfo.getFetchRefSpecs()) op.addPostCloneTask(new ConfigureFetchAfterCloneTask(remoteName, fetchRefSpec)); }
Source:
<code>default void checkTimeoutPrecision(Duration duration, String timeoutName) { checkArgument(duration.minusMillis(duration.toMillis()).isZero(), <START> "Timeout should be a multiple of milliseconds", <END> SafeArg.of("timeoutName", timeoutName), SafeArg.of("duration", duration), UnsafeArg.of("uris", uris())); }</code><technical_language>Timeouts sub-millisecond precision supported</technical_language>

Target:
default void checkTimeoutPrecision(Duration duration, String timeoutName) { checkArgument(duration.minusMillis(duration.toMillis()).isZero(), "Timeouts with sub-millisecond precision are not supported", SafeArg.of("timeoutName", timeoutName), SafeArg.of("duration", duration), UnsafeArg.of("uris", uris())); }
Source:
<code>void onEditMessage(ClickEvent e) { if (Gerrit.isSignedIn()) { editCommitMessageAction.onEdit(); } else { <START> Gerrit.doSignIn(getToken()); <END> } }</code><technical_language>Unreachable code. button is visible if user is signed in action is defined</technical_language>

Target:
void onEditMessage(ClickEvent e) { editMessageAction.onEdit(); }
Source:
<code>protected void doGetText(HttpServletRequest req, HttpServletResponse res) throws IOException { GitilesView view = ViewFilter.getView(req); Repository repo = ServletUtils.getRepository(req); RevWalk walk = new RevWalk(repo); try { RevObject obj = walk.parseAny(view.getRevision().getId()); switch (obj.getType()) { case OBJ_COMMIT: try (Writer writer = startRenderText(req, res); OutputStream out = BaseEncoding.base64().encodingStream(writer)) { <START> out.write(((RevCommit)obj).getRawBuffer()); <END> } break; default: res.setStatus(SC_NOT_FOUND); break; } } finally { walk.release(); } }</code><technical_language>This materializes object, do that. Open ObjectId ObjectReader, open a stream ObjectLoader, copy output ByteStreams.copy similar</technical_language>

Target:
protected void doGetText(HttpServletRequest req, HttpServletResponse res) throws IOException { GitilesView view = ViewFilter.getView(req); Repository repo = ServletUtils.getRepository(req); ObjectReader reader = repo.newObjectReader(); ObjectLoader loader = reader.open(view.getRevision().getId(), OBJ_COMMIT); if (loader.getType() != OBJ_COMMIT) { res.setStatus(SC_NOT_FOUND); } else { try (Writer writer = startRenderText(req, res); OutputStream out = BaseEncoding.base64().encodingStream(writer)) { loader.copyTo(out); } } }
Source:
<code>public void drawItems(Rectangle bounds, ITimeDataProvider timeProvider, Item[] items, int topIndex, int nameSpace, GC gc) { <START> int bottomIndex = fTopIndex + countPerPage(); <END> for (int i = topIndex; i < bottomIndex; i++) { Item item = items[i]; drawItem(item, bounds, timeProvider, i, nameSpace, gc); } }</code><technical_language>verify: I countPerPage() count partially visible item bottom of control, this prevent drawn. Also, bottomIndex possibly >= items.length</technical_language>

Target:
public void drawItems(Rectangle bounds, ITimeDataProvider timeProvider, Item[] items, int topIndex, int nameSpace, GC gc) { int bottomIndex = Integer.min(topIndex + countPerPage(), items.length); for (int i = topIndex; i < bottomIndex; i++) { Item item = items[i]; drawItem(item, bounds, timeProvider, i, nameSpace, gc); } }
Source:
<code>protected Object doReceive() { Assert.state(this.running.get(), getComponentName() + " is not running"); AbstractFileInfo<F> file = poll(); if (file != null) { try { String remotePath = remotePath(file); Session<?> session = this.remoteFileTemplate.getSession(); try { return getMessageBuilderFactory() .withPayload(session.readRaw(remotePath)) .setHeader(IntegrationMessageHeaderAccessor.CLOSEABLE_RESOURCE, session) .setHeader(FileHeaders.REMOTE_DIRECTORY, file.getRemoteDirectory()) .setHeader(FileHeaders.REMOTE_FILE, file.getFilename()) .setHeader(FileHeaders.REMOTE_FILE_INFO, this.fileInfoJson ? file.toJson() : file); } catch (IOException e) { <START> throw new MessagingException("IOException when retrieving " + remotePath, e); <END> } } catch (RuntimeException e) { resetFilterIfnecessary(file); throw e; } } return null; }</code><technical_language>change this UncheckedIOException instead? is do messaging..</technical_language>

Target:
protected Object doReceive() { Assert.state(this.running.get(), () -> getComponentName() + " is not running"); AbstractFileInfo<F> file = poll(); if (file != null) { try { String remotePath = remotePath(file); Session<?> session = this.remoteFileTemplate.getSession(); try { return getMessageBuilderFactory() .withPayload(session.readRaw(remotePath)) .setHeader(IntegrationMessageHeaderAccessor.CLOSEABLE_RESOURCE, session) .setHeader(FileHeaders.REMOTE_DIRECTORY, file.getRemoteDirectory()) .setHeader(FileHeaders.REMOTE_FILE, file.getFilename()) .setHeader(FileHeaders.REMOTE_FILE_INFO, this.fileInfoJson ? file.toJson() : file); } catch (IOException e) { throw new UncheckedIOException("IOException when retrieving " + remotePath, e); } } catch (RuntimeException e) { resetFilterIfNecessary(file); throw e; } } return null; }
Source:
<code>private static void assertGeometryEquals(OGCGeometry actual, OGCGeometry expected) { <START> if (expected.isEmpty()) { <END> assertTrue(actual.isEmpty()); } else { actual.setSpatialReference(null); expected.setSpatialReference(null); assertEquals(actual, expected); } }</code><technical_language>earlier commits enhanced serialization avoid losing multi-types this if removed</technical_language>

Target:
private static void assertGeometryEquals(OGCGeometry actual, OGCGeometry expected) { actual.setSpatialReference(null); expected.setSpatialReference(null); ensureEnvelopeLoaded(actual); ensureEnvelopeLoaded(expected); assertEquals(actual, expected); }
Source:
<code><START> protected Boolean visitInListExpression(InListExpression actual, Node expected) <END> { if (!(expected instanceof InListExpression)) { return false; } InListExpression expectedInList = (InListExpression) expected; if (actual.getValues().size() == expectedInList.getValues().size()) { boolean verified = true; for (int i = 0; i < actual.getValues().size(); i++) { verified &= process(actual.getValues().get(i), expectedInList.getValues().get(i)); } return verified; } return false; }</code><technical_language>please extract separate commit</technical_language>

Target:
protected Boolean visitInListExpression(InListExpression actual, Node expected) { if (!(expected instanceof InListExpression)) { return false; } InListExpression expectedInList = (InListExpression) expected; return process(actual.getValues(), expectedInList.getValues()); }
Source:
<code>protected void doTestTrashCheckedInDocument(boolean expectCheckedIn) { DocumentModel folder = session.createDocumentModel("/", "folder", "Folder"); folder = session.createDocument(folder); <START> DocumentModel doc = session.createDocumentModel(folder.getPathAsString(), "doc", "File"); <END> doc = session.createDocument(doc); doc.checkIn(VersioningOption.MAJOR, null); assertFalse(doc.isCheckedOut()); session.save(); trashService.trashDocument(doc); doc = session.getDocument(new IdRef(doc.getId())); assertTrue(doc.isTrashed()); if (expectCheckedIn) { assertFalse(doc.isCheckedOut()); } else { assertTrue(doc.isCheckedOut()); } trashService.untrashDocument(doc); doc = session.getDocument(new IdRef(doc.getId())); assertFalse(doc.isTrashed()); if (expectCheckedIn) { assertFalse(doc.isCheckedOut()); } else { assertTrue(doc.isCheckedOut()); } DocumentModel doc2 = session.createDocumentModel("/folder", "doc2", "File"); doc2 = session.createDocument(doc2); doc2.checkIn(VersioningOption.MAJOR, null); session.save(); session.followTransition(doc2, "approve"); doc2 = session.getDocument(new IdRef(doc2.getId())); assertEquals("approved", doc2.getCurrentLifeCycleState()); assertTrue(doc2.isCheckedOut()); }</code><technical_language>(detail) needed, a constant is shorter more explicit</technical_language>

Target:
protected void doTestTrashCheckedInDocument(boolean expectCheckedIn) { DocumentModel folder = session.createDocumentModel("/", "folder", "Folder"); folder = session.createDocument(folder); DocumentModel doc = session.createDocumentModel("/folder", "doc", "File"); doc = session.createDocument(doc); doc.checkIn(VersioningOption.MAJOR, null); assertFalse(doc.isCheckedOut()); session.save(); trashService.trashDocument(doc); doc = session.getDocument(new IdRef(doc.getId())); assertTrue(doc.isTrashed()); if (expectCheckedIn) { assertFalse(doc.isCheckedOut()); } else { assertTrue(doc.isCheckedOut()); } trashService.untrashDocument(doc); doc = session.getDocument(new IdRef(doc.getId())); assertFalse(doc.isTrashed()); if (expectCheckedIn) { assertFalse(doc.isCheckedOut()); } else { assertTrue(doc.isCheckedOut()); } DocumentModel doc2 = session.createDocumentModel("/folder", "doc2", "File"); doc2 = session.createDocument(doc2); doc2.checkIn(VersioningOption.MAJOR, null); session.save(); session.followTransition(doc2, "approve"); doc2 = session.getDocument(new IdRef(doc2.getId())); assertEquals("approved", doc2.getCurrentLifeCycleState()); assertTrue(doc2.isCheckedOut()); }
Source:
<code>public static String generateJsonDiskDescription(Disk disk) throws IOException { String diskAlias = disk.getDiskAlias(); <START> String diskDescription = disk.getDiskDescription() != null ? disk.getDiskDescription() : ""; <END> int diskDescriptionMetadataPotentialLength = METADATA_DESCRIPTION_VALUE_MAX_LENGTH - DESCRIPTION_METADATA_OVERHEAD_LENGTH; if (diskAlias.length() <= diskDescriptionMetadataPotentialLength) { diskDescriptionMetadataPotentialLength -= diskAlias.length(); if (diskDescription.length() > diskDescriptionMetadataPotentialLength) { diskDescription = diskDescription.substring(0, diskDescriptionMetadataPotentialLength); log.warn("Can't store full disk description since it's too long. " + "Truncating and storing {}={}.", disk.getId(), DISK_DESCRIPTION, diskDescription); } } else { diskAlias = diskAlias.substring(0, diskDescriptionMetadataPotentialLength); diskDescription = StringUtils.EMPTY; log.warn("Can't store full disk alias since it's too long. " + "Truncating and storing {}={}.", disk.getId(), DISK_ALIAS, diskAlias); log.warn("Can't store disk description since the alias is too long. " + "The description will be stored as an empty string.", disk.getId()); } Map<String, Object> description = new TreeMap<>(); description.put(DISK_ALIAS, diskAlias); description.put(DISK_DESCRIPTION, diskDescription); return JsonHelper.mapToJson(description, false); }</code><technical_language>shorter temporary variables - "alias" "description" get nicer code. In context of this method, is confused variables (e.g. this else's alias)</technical_language>

Target:
public String generateJsonDiskDescription(Disk disk) throws IOException { Map<String, Object> description = new TreeMap<>(); description.put(DISK_ALIAS, disk.getDiskAlias()); description.put(DISK_DESCRIPTION, StringUtils.defaultString(disk.getDiskDescription())); return JsonHelper.mapToJson(generateJsonDiskDescription(description, DESCRIPTION_FIELDS_PRIORITY), false); }
Source:
<code>protected void beforeTest() { beforeTestSetup(); <START> client = clientSetup(pipeline -> new KeyClientBuilder() .pipeline(pipeline) .vaultUrl(getEndpoint()) .buildAsyncClient()); <END> }</code><technical_language>This deleted</technical_language>

Target:
protected void beforeTest() { beforeTestSetup(); }
Source:
<code>public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) { switch (n.getToken()) { case SCRIPT: enterModule(n, t.getInput().getPath()); break; case IMPORT: case EXPORT: visitImportOrExport(t, n); break; case CALL: if (n.isCall() && n.getFirstChild().matchesQualifiedName("goog.loadModule")) { loadModuleCall = n; enterModule(n, null); } break; case MODULE_BODY: currentModule.hasModuleBody = true; break; case DYNAMIC_IMPORT: <START> visitDynamicImport(t, n); <END> default: break; } return true; }</code><technical_language>Actually, this is break is missing</technical_language>

Target:
public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) { switch (n.getToken()) { case SCRIPT: enterModule(t, n, t.getInput().getPath()); break; case IMPORT: case EXPORT: visitImportOrExport(t, n); break; case CALL: if (n.isCall() && n.getFirstChild().matchesQualifiedName("goog.loadModule")) { loadModuleCall = n; enterModule(t, n, null); } break; case MODULE_BODY: currentModule.hasModuleBody = true; break; case DYNAMIC_IMPORT: visitDynamicImport(n); break; default: break; } return true; }
Source:
<code>public static LoggingConfigWatchdog configureAndWatch(long delay) { <START> final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); <END> URL url = contextClassLoader.getResource("log4j.xml"); if (url == null) { return null; } try { return Log4jWatchdog.watch(url.getFile(), delay); } catch (LinkageError cause) { return null; } }</code><technical_language>final for local variables parameters needed</technical_language>

Target:
public static Log4jWatchdogHandle configureAndWatch(long delay) { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); URL url = contextClassLoader.getResource("log4j.xml"); if (url == null) { return null; } try { return Log4jWatchdog.watch(url.getFile(), delay); } catch (LinkageError cause) { return null; } }
Source:
<code>public Optional<Context> getModelClass() { final Context context = new Context(); <START> return Optional.of(context); <END> }</code><technical_language>shorten line return Optional.of(new Context());</technical_language>

Target:
public Optional<Context> getModelClass() { return Optional.of(new Context()); }
Source:
<code>private void glusterHostRemove(Guid sourceClusterId) { VDSReturnValue returnValue = runVdsCommand( VDSCommandType.GlusterHostRemove, new GlusterHostRemoveVDSParameters((getClusterUtils().getUpServer(sourceClusterId)).getId(), getVds().gethost_name(), false)); <START> setSucceeded(returnValue.getSucceeded()); <END> if (!getSucceeded()) { handleVdsError(returnValue); errorType = AuditLogType.GLUSTER_HOST_REMOVE_FAILED; return; } }</code><technical_language>setting command succeeded? if error occur execution? instead, this method return boolean for success status</technical_language>

Target:
private boolean glusterHostRemove(Guid sourceClusterId) { String hostName = (getVds().gethost_name().isEmpty()) ? getVds().getManagmentIp() : getVds().gethost_name(); VDSReturnValue returnValue = runVdsCommand( VDSCommandType.GlusterHostRemove, new GlusterHostRemoveVDSParameters((getClusterUtils().getUpServer(sourceClusterId)).getId(), hostName, false)); if (getSucceeded()) { return true; } else { handleVdsError(returnValue); errorType = AuditLogType.GLUSTER_HOST_REMOVE_FAILED; return false; } }
Source:
<code>private void copyData(VmBase source, VmBase dest) { for (Field srcFld : VmBase.class.getDeclaredFields()) { try { if (srcFld.getAnnotation(CopyOnNewVersion.class) != null) { srcFld.setAccessible(true); Field dstFld = VmBase.class.getDeclaredField(srcFld.getName()); dstFld.setAccessible(true); dstFld.set(dest, srcFld.get(source)); } } catch (Exception exp) { log.errorFormat("Failed to copy field {0} of new version to VM {1} ({2}), error: {3}", srcFld.getName(), source.getName(), source.getId(), <START> exp.getMessage()); <END> } } }</code><technical_language>if fail a stale VM version in hand. roleback</technical_language>

Target:
private boolean copyData(VmBase source, VmBase dest) { for (Field srcFld : VmBase.class.getDeclaredFields()) { try { if (srcFld.getAnnotation(CopyOnNewVersion.class) != null) { srcFld.setAccessible(true); Field dstFld = VmBase.class.getDeclaredField(srcFld.getName()); dstFld.setAccessible(true); dstFld.set(dest, srcFld.get(source)); } } catch (Exception exp) { log.errorFormat("Failed to copy field {0} of new version to VM {1} ({2}), error: {3}", srcFld.getName(), source.getName(), source.getId(), exp.getMessage()); return false; } } return true; }
Source:
<code>public int read() throws IOException { if (mPosition == mLength) { return -1; } RetryPolicy retry = mRetryPolicySupplier.get(); IOException lastException = null; while (retry.attempt()) { try { updateStream(); int result = mBlockInStream.read(); if (result != -1) { mPosition++; } if (mBlockInStream.remaining() == 0) { closeBlockInStream(mBlockInStream); <START> mBlockInStream = null; <END> } return result; } catch (IOException e) { lastException = e; if (mBlockInStream != null) { handleRetryableException(mBlockInStream, e); mBlockInStream = null; } } } throw lastException; }</code><technical_language>setting of mBlockInStream = null is handled in closeBlockInStream</technical_language>

Target:
public int read() throws IOException { if (mPosition == mLength) { return -1; } RetryPolicy retry = mRetryPolicySupplier.get(); IOException lastException = null; while (retry.attempt()) { try { updateStream(); int result = mBlockInStream.read(); if (result != -1) { mPosition++; } if (mBlockInStream.remaining() == 0) { closeBlockInStream(mBlockInStream); } return result; } catch (IOException e) { lastException = e; if (mBlockInStream != null) { handleRetryableException(mBlockInStream, e); mBlockInStream = null; } } } throw lastException; }
Source:
<code><START> public String getImage() { <END> return getText(); }</code><technical_language>image attribute is supposed text of node. separate (the previous @Text attribute fine). A practical reason for is in future, other languages a get text of node, in case fetched getImage, for compatibility, a getText method, getSourceCode in #1728. *may* deprecate put getImage out of soon 7.0, contract is super loose</technical_language>

Target:
public String getImage() { return null; }
Source:
<code>public BluetoothDevice getDevice(BluetoothAddress address) { if (devices.containsKey(address.toString())) { return devices.get(address.toString()); } else { synchronized (devices) { if (devices.containsKey(address.toString())) { return devices.get(address.toString()); <START> } else { <END> BluetoothDevice device = new BlueZBluetoothDevice(this, address, ""); devices.put(address.toString(), device); return device; } } } }</code><technical_language>sense Read/Write locks instead of this "I'm feeling lucky try safe side" approach</technical_language>

Target:
public BluetoothDevice getDevice(BluetoothAddress address) { if (devices.containsKey(address.toString())) { return devices.get(address.toString()); } else { synchronized (devices) { if (devices.containsKey(address.toString())) { return devices.get(address.toString()); } else { BlueZBluetoothDevice device = new BlueZBluetoothDevice(this, address, ""); device.initialize(); devices.put(address.toString(), device); return device; } } } }
Source:
<code>public Long saveOrUpdate(ChannelDTO channel) { Assert.notNull(channel); Assert.notNull(channel.getName()); ChannelEntity channelEntity = this.channelRepository.findByName(channel.getName()); if (channelEntity == null) { channelEntity = this.converterService.convert(channel, ChannelEntity.class); } else if (channelEntity.isDeleted() != null && channelEntity.isDeleted()) { channelEntity.setDeleted(false); } else { throw new DuplicateChannelException(channel.getName()); } ChannelEntity savedEntity = this.channelRepository.saveAndFlush(channelEntity); try { return savedEntity.getId(); } catch (NullPointerException ex) { <START> return -1L; <END> } }</code><technical_language>For a black magic. this method return -1 if null pointer exception is occurred? In opinion is more readable if throw illegal argument exception if a validation fails return null if savedEntity is null, I prefer option. more question: please describe a situation savedEntity null</technical_language>

Target:
public Long saveOrUpdate(ChannelDTO channel) { Assert.notNull(channel); Assert.notNull(channel.getName()); ChannelEntity channelEntity = this.channelRepository.findByName(channel.getName()); if (channelEntity == null) { channelEntity = this.converterService.convert(channel, ChannelEntity.class); } else if (channelEntity.isDeleted() != null && channelEntity.isDeleted()) { channelEntity.setDeleted(false); } else { throw new DuplicateChannelException(channel.getName()); } this.channelRepository.saveAndFlush(channelEntity); return channelEntity.getId(); }
Source:
<code>public Hardware apply(VMHardware from) { final HardwareBuilder builder = new HardwareBuilder() .name(from.name) <START> .providerId("azurecompute-arm") <END> .id(from.name) .processors(ImmutableList.of(new Processor(from.numberOfCores, 2))) .ram(from.memoryInMB) .location(from.globallyAvailable ? null : FluentIterable.from(locations.get()) .firstMatch(LocationPredicates.idEquals(from.location)) .get()); if (from.resourceDiskSizeInMB != null) { builder.volume(new VolumeBuilder() .size(Float.valueOf(from.resourceDiskSizeInMB)) .type(Volume.Type.LOCAL) .build()); } if (from.osDiskSizeInMB != null) { builder.volume(new VolumeBuilder() .size(Float.valueOf(from.osDiskSizeInMB)) .type(Volume.Type.LOCAL) .build()); } ImmutableMap.Builder<String, String> metadata = ImmutableMap.builder(); metadata.put("maxDataDiskCount", String.valueOf(from.maxDataDiskCount)); builder.userMetadata(metadata.build()); return builder.build(); }</code><technical_language>This is id of provider. This is "real" id of hardware profile in provider; "backend id". Some providers AWS encode region information in IDs, "us-east-1/ami-0001", etc. +real\* id in provider is "ami-0001". id field is free providers encode information need in order able properly implement "getById" methods in adapter. providerId is meant hold real id of object in backend provider</technical_language>

Target:
public Hardware apply(VMHardware from) { final HardwareBuilder builder = new HardwareBuilder() .name(from.name()) .providerId(from.name()) .id(from.name()) .processors(ImmutableList.of(new Processor(from.numberOfCores(), 2))) .ram(from.memoryInMB()) .location(from.globallyAvailable() ? null : FluentIterable.from(locations.get()) .firstMatch(LocationPredicates.idEquals(from.location())) .get()); if (from.resourceDiskSizeInMB() != null) { builder.volume(new VolumeBuilder() .size(Float.valueOf(from.resourceDiskSizeInMB())) .type(Volume.Type.LOCAL) .build()); } if (from.osDiskSizeInMB() != null) { builder.volume(new VolumeBuilder() .size(Float.valueOf(from.osDiskSizeInMB())) .type(Volume.Type.LOCAL) .build()); } ImmutableMap.Builder<String, String> metadata = ImmutableMap.builder(); metadata.put("maxDataDiskCount", String.valueOf(from.maxDataDiskCount())); builder.userMetadata(metadata.build()); return builder.build(); }
Source:
<code>public void deleteElementOnComputeFunctionReturningNull() { LocalMap<String, String> map = sharedData.getLocalMap("foo"); map.put("hello", "world"); map.computeIfPresent("hello", (key, oldValue) -> null); <START> assertNull(map.get("hello")); <END> map.compute("hello", (key, oldValue) -> null); assertNull(map.get("hello")); map.put("hello", "world"); map.merge("hello", "world!!!!!!", (key, oldValue) -> null); assertNull(map.get("hello")); map.computeIfAbsent("hello", key -> null); assertNull(map.get("hello")); }</code><technical_language>need instead contains get</technical_language>

Target:
public void deleteElementOnComputeFunctionReturningNull() { LocalMap<String, String> map = sharedData.getLocalMap("foo"); map.put("hello", "world"); map.computeIfPresent("hello", (key, oldValue) -> null); assertFalse(map.containsKey("hello")); map.compute("hello", (key, oldValue) -> null); assertFalse(map.containsKey("hello")); map.put("hello", "world"); map.merge("hello", "world!!!!!!", (key, oldValue) -> null); assertFalse(map.containsKey("hello")); map.computeIfAbsent("hello", key -> null); assertFalse(map.containsKey("hello")); }
Source:
<code>public void configure(Binder binder) { binder.disableCircularProxies(); jaxrsBinder(binder).bindInjectionProvider(ClientInfo.class).to(ClientInfoSupplier.class); jaxrsBinder(binder).bindAdmin(ParsingExceptionMapper.class); jaxrsBinder(binder).bindAdmin(QueryParamExceptionMapper.class); jaxrsBinder(binder).bindAdmin(OverrideMethodFilter.class); jaxrsBinder(binder).bindAdmin(ThreadDumpResource.class); <START> bindConfig(binder).bind(JaxrsConfig.class); <END> newSetBinder(binder, Object.class, JaxrsResource.class).permitDuplicates(); newSetBinder(binder, JaxrsBinding.class, JaxrsResource.class).permitDuplicates(); newMapBinder(binder, new TypeLiteral<Class<?>>() {}, new TypeLiteral<Supplier<?>>() {}, JaxrsInjectionProvider.class); }</code><technical_language>I prefer unconditionally removing OverrideMethodFilter admin port. a case for there. pull other options admin-only module split options classes</technical_language>

Target:
public void configure(Binder binder) { binder.disableCircularProxies(); jaxrsBinder(binder).bindInjectionProvider(ClientInfo.class).to(ClientInfoSupplier.class); jaxrsBinder(binder).bindAdmin(ParsingExceptionMapper.class); jaxrsBinder(binder).bindAdmin(QueryParamExceptionMapper.class); jaxrsBinder(binder).bindAdmin(ThreadDumpResource.class); newSetBinder(binder, Object.class, JaxrsResource.class).permitDuplicates(); newSetBinder(binder, JaxrsBinding.class, JaxrsResource.class).permitDuplicates(); newMapBinder(binder, new TypeLiteral<Class<?>>() { }, new TypeLiteral<Supplier<?>>() { }, JaxrsInjectionProvider.class); }
Source:
<code>MethodHandle superMethodHandle(Method method) throws Exception { try { Class<?> declaringClass = method.getDeclaringClass(); return MethodHandles.lookup().findSpecial(declaringClass, method.getName(), MethodType.methodType(method.getReturnType(), method.getParameterTypes()), <START> declaringClass); <END> } catch (Exception e) { SUPER_METHOD_LOOKUP = PRIVATE_LOOKUP; return PRIVATE_LOOKUP.superMethodHandle(method); } }</code><technical_language>OOC, in ways findSpecial differ unreflectSpecial? functionally equivalent (ignoring JDK bugs), stards reflect data (Method) other a signature (MethodType)? if so, is worthwhile simplifying this _just_ findSpecial? also: this change impact calculus of access? if types (args return) private, package-private protected, unreflectSpecial|findSpecial fail reflected approach succeeded, explicitly set modes access levels</technical_language>

Target:
MethodHandle superMethodHandle(Method method) throws Exception { try { return MethodHandles.lookup().unreflectSpecial(method, method.getDeclaringClass()); } catch (Exception e) { SUPER_METHOD_LOOKUP = FIND_SPECIAL; return FIND_SPECIAL.superMethodHandle(method); } }
Source:
<code>protected void applyValidation() { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { if <START> (getControls().values().iterator().next().isDisposed()) <END> { return; } Label validationIcon = null; switch (getControls().size()) { case 3: validationIcon = Label.class.cast(getControls().get( new SWTGridCell(0, 1, CustomControlSWTRenderer.this))); break; default: break; } if (validationIcon != null && !validationIcon.isDisposed()) { validationIcon.setImage(getValidationIcon(getVElement().getDiagnostic().getHighestSeverity())); validationIcon.setToolTipText(getVElement().getDiagnostic().getMessage()); } if (swtCustomControl != null) { swtCustomControl.applyValidation(); } } }); }</code><technical_language>controls is empty? iterator fails</technical_language>

Target:
protected void applyValidation() { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { if (getControls().size() == 0 || getControls().values().iterator().next().isDisposed()) { return; } Label validationIcon = null; switch (getControls().size()) { case 3: validationIcon = Label.class.cast(getControls().get( new SWTGridCell(0, 1, CustomControlSWTRenderer.this))); break; default: break; } if (validationIcon != null && !validationIcon.isDisposed()) { validationIcon.setImage(getValidationIcon(getVElement().getDiagnostic().getHighestSeverity())); validationIcon.setToolTipText(getVElement().getDiagnostic().getMessage()); } if (swtCustomControl != null) { swtCustomControl.applyValidation(); } } }); }
Source:
<code>@Test public void platformTypeThrows() throws IOException { Moshi moshi = new Moshi.Builder().build(); try { <START> moshi.adapter(File.class); <END> } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Platform class java.io.File annotated requires explicit JsonAdapter to be registered"); } }</code><technical_language>Missing fail() in try block</technical_language>

Target:
@Test public void platformTypeThrows() throws IOException { Moshi moshi = new Moshi.Builder().build(); try { moshi.adapter(File.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Platform class java.io.File annotated requires explicit JsonAdapter to be registered"); } try { moshi.adapter(KeyGenerator.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Platform class javax.crypto.KeyGenerator annotated requires explicit JsonAdapter to be registered"); } try { moshi.adapter(Pair.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( "Platform class android.util.Pair annotated requires explicit JsonAdapter to be registered"); } }
Source:
<code>public void setNoMorePagesForLifespan(Lifespan lifespan) { <START> noMorePagesForLifespan.add(lifespan); <END> }</code><technical_language>Add requireNonNull for lifespan. This add call throw a NPE in case</technical_language>

Target:
public void setNoMorePagesForLifespan(Lifespan lifespan) { requireNonNull(lifespan, "lifespan is null"); noMorePagesForLifespan.add(lifespan); }
Source:
<code>protected Object executeScript( final ScriptableObject scriptable, final Scriptable scope, final String script, final Context cx ) throws Exception { ScriptableObject.defineClass( scope, JavaScriptResultSet.class ); @SuppressWarnings( "unchecked" ) Set<String> inputNames = getInputNames(); Iterator<String> inputNamesIterator = inputNames.iterator(); String inputName; Object inputValue; while ( inputNamesIterator.hasNext() ) { inputName = (String) inputNamesIterator.next(); if ( inputName.indexOf( '-' ) >= 0 ) { throw new IllegalArgumentException( Messages.getInstance().getErrorString( "JSRULE.ERROR_0006_INVALID_JS_VARIABLE", inputName ) ); } inputValue = getInputValue( inputName ); Object wrapper; if ( inputValue instanceof IPentahoResultSet ) { JavaScriptResultSet results = new JavaScriptResultSet(); results.setPrototype( scriptable ); results.setResultSet( (IPentahoResultSet) inputValue ); wrapper = Context.javaToJS( inputValue, results ); } else { <START> inputValue = Encode.forHtml( Context.toString( inputValue ) ); <END> wrapper = Context.javaToJS( inputValue, scope ); } ScriptableObject.putProperty( scope, inputName, wrapper ); } Object wrappedOut = Context.javaToJS( System.out, scope ); Object wrappedThis = Context.javaToJS( this, scope ); ScriptableObject.putProperty( scope, "out", wrappedOut ); ScriptableObject.putProperty( scope, "rule", wrappedThis ); return cx.evaluateString( scope, script, "<cmd>", 1, null ); }</code><technical_language>I encoding for html issues here. Suggest killing encode I demonstrate ability subvert Javascript system based bind variables. Suggest encode in success message calling a day</technical_language>

Target:
protected Object executeScript( final ScriptableObject scriptable, final Scriptable scope, final String script, final Context cx ) throws Exception { ScriptableObject.defineClass( scope, JavaScriptResultSet.class ); @SuppressWarnings( "unchecked" ) Set<String> inputNames = getInputNames(); Iterator<String> inputNamesIterator = inputNames.iterator(); String inputName; Object inputValue; while ( inputNamesIterator.hasNext() ) { inputName = (String) inputNamesIterator.next(); if ( inputName.indexOf( '-' ) >= 0 ) { throw new IllegalArgumentException( Messages.getInstance().getErrorString( "JSRULE.ERROR_0006_INVALID_JS_VARIABLE", inputName ) ); } inputValue = getInputValue( inputName ); Object wrapper; if ( inputValue instanceof IPentahoResultSet ) { JavaScriptResultSet results = new JavaScriptResultSet(); results.setPrototype( scriptable ); results.setResultSet( (IPentahoResultSet) inputValue ); wrapper = Context.javaToJS( inputValue, results ); } else { wrapper = Context.javaToJS( inputValue, scope ); } ScriptableObject.putProperty( scope, inputName, wrapper ); } Object wrappedOut = Context.javaToJS( System.out, scope ); Object wrappedThis = Context.javaToJS( this, scope ); ScriptableObject.putProperty( scope, "out", wrappedOut ); ScriptableObject.putProperty( scope, "rule", wrappedThis ); return cx.evaluateString( scope, script, "<cmd>", 1, null ); }