auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected EnvVars buildEnv(AbstractProject<?, ?> job) { EnvVars env = new EnvVars(); for (EnvironmentContributor contributor : EnvironmentContributor.all()) { try { contributor.buildEnvironmentFor(job, env, TaskListener.NULL); <START> } catch (Throwable t) { <END> LOGGER.debug("{} failed to build env ({}), skipping", contributor.getClass(), t.getMessage(), t); } } return env; }</code><technical_language>discussions in other PRs agreed this approach is good, suppresses kinds of system <code>Error</code>s, supposed system failures</technical_language>

Target:
protected EnvVars buildEnv(AbstractProject<?, ?> job) { EnvVars env = new EnvVars(); for (EnvironmentContributor contributor : EnvironmentContributor.all()) { try { contributor.buildEnvironmentFor(job, env, TaskListener.NULL); } catch (Exception e) { LOGGER.debug("{} failed to build env ({}), skipping", contributor.getClass(), e.getMessage(), e); } } return env; }
Source:
<code>public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) { if (bridgeStatusInfo.getStatus() == ThingStatus.ONLINE && getThing().getStatusInfo().getStatusDetail() == ThingStatusDetail.BRIDGE_OFFLINE) { <START> updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE); <END> } else if (bridgeStatusInfo.getStatus() == ThingStatus.OFFLINE) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE); } }</code><technical_language>refactoring of OH2 bindings, this default implementation helpful. In cases, is simply expected ONLINE bridge is ONLINE. This means this method needs overwritten, question arises if super. bridgeStatusChanged() called if logic reimplemented. variants nice. I change this line ThingStatus.ONLINE this expected behavior in cases. needs else, override default impl. @sbussweiler WDYT</technical_language>

Target:
public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) { if (bridgeStatusInfo.getStatus() == ThingStatus.ONLINE && getThing().getStatusInfo().getStatusDetail() == ThingStatusDetail.BRIDGE_OFFLINE) { updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE); } else if (bridgeStatusInfo.getStatus() == ThingStatus.OFFLINE) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE); } }
Source:
<code>private void storeCache(final boolean move) { if (progress.isShowing()) { showToast(res.getString(R.string.err_detail_still_working)); return; } if (Settings.getChooseList()) { new StoredList.UserInterface(this).promptForListSelection(R.string.list_title, new Action1<Integer>() { @Override public void call(final Integer selectedListId) { storeCacheInList(selectedListId, move); } }, true, cache.getLists()); } else { <START> storeCacheInList(StoredList.TEMPORARY_LIST.id, move); <END> } }</code><technical_language>StoredList.STANDARD_LIST_ID, #5646</technical_language>

Target:
private void storeCache(final boolean move) { if (progress.isShowing()) { showToast(res.getString(R.string.err_detail_still_working)); return; } if (Settings.getChooseList()) { new StoredList.UserInterface(this).promptForListSelection(R.string.list_title, new Action1<Integer>() { @Override public void call(final Integer selectedListId) { storeCacheInList(selectedListId, move); } }, true, cache.getLists()); } else { storeCacheInList(StoredList.STANDARD_LIST_ID, move); } }
Source:
<code>public boolean getBoolean(String fieldName) { long columnIndex = proxyState.getRow$realm().getColumnIndex(fieldName); RealmFieldType columnType = proxyState.getRow$realm().getColumnType(columnIndex); if (columnType != RealmFieldType.BOOLEAN) { <START> throw new IllegalArgumentException(fieldName + " is not a boolean, but a " + columnType); <END> } return proxyState.getRow$realm().getBoolean(columnIndex); }</code><technical_language>quote 'boolean' 'columnType'</technical_language>

Target:
public boolean getBoolean(String fieldName) { long columnIndex = proxyState.getRow$realm().getColumnIndex(fieldName); checkFieldType(fieldName, columnIndex, RealmFieldType.BOOLEAN); return proxyState.getRow$realm().getBoolean(columnIndex); }
Source:
<code>public void testBadFutureType() throws Exception { ServerThread localServer = start(); Client client = ClientFactory.createClient(); client.createConnection("localhost"); ClientResponseImpl response = null; try { response = (ClientResponseImpl) client.callProcedure("TestNTProcs$NTProcWithBadTypeFuture"); } catch (ProcCallException e) { <START> response = (ClientResponseImpl) e.getClientResponse(); <END> } assertEquals(ClientResponse.GRACEFUL_FAILURE, response.getStatus()); System.out.println("Client got failure response"); System.out.println(response.toJSONString()); localServer.shutdown(); localServer.join(); }</code><technical_language>verify error message? This way, reader easily kind of error this test cases check</technical_language>

Target:
public void testBadFutureType() throws Exception { ServerThread localServer = start(); Client client = ClientFactory.createClient(); client.createConnection("localhost"); ClientResponseImpl response = null; try { response = (ClientResponseImpl) client.callProcedure("TestNTProcs$NTProcWithBadTypeFuture"); } catch (ProcCallException e) { response = (ClientResponseImpl) e.getClientResponse(); } assertEquals(ClientResponse.GRACEFUL_FAILURE, response.getStatus()); assertTrue(response.getStatusString().contains("was not an acceptible VoltDB return type")); System.out.println("Client got failure response"); System.out.println(response.toJSONString()); localServer.shutdown(); localServer.join(); }
Source:
<code>public boolean canDelete() { try { XWikiDocument doc = new XWikiDocument(); doc.setFullName(getFullName(), this.context); <START> if (!hasAccessLevel(ADMIN_RIGHT, getFullName()) && !hasAccessLevel("delete", getFullName())) { <END> return false; } String waitdays; if (hasAccessLevel(ADMIN_RIGHT, getFullName())) { waitdays = getXWikiContext().getWiki().Param("xwiki.store.recyclebin.adminWaitDays", "0"); } else { waitdays = getXWikiContext().getWiki().Param("xwiki.store.recyclebin.waitDays", "7"); } int seconds = (int) (Double.parseDouble(waitdays) * 24 * 60 * 60 + 0.5); Calendar cal = Calendar.getInstance(); cal.setTime(getDate()); cal.add(Calendar.SECOND, seconds); return cal.before(Calendar.getInstance()); } catch (Exception ex) { LOGGER.warn("Exception while checking if entry can be removed from the recycle bin", getId(), ex); return false; } }</code><technical_language>remove ADMIN right test imply DELETE anyway</technical_language>

Target:
public boolean canDelete() { try { XWikiDocument doc = new XWikiDocument(); doc.setFullName(getFullName(), this.context); if (!hasAccessLevel("delete", getFullName())) { return false; } String waitdays; if (hasAccessLevel(ADMIN_RIGHT, getFullName())) { waitdays = getXWikiContext().getWiki().Param("xwiki.store.recyclebin.adminWaitDays", "0"); } else { waitdays = getXWikiContext().getWiki().Param("xwiki.store.recyclebin.waitDays", "7"); } int seconds = (int) (Double.parseDouble(waitdays) * 24 * 60 * 60 + 0.5); Calendar cal = Calendar.getInstance(); cal.setTime(getDate()); cal.add(Calendar.SECOND, seconds); return cal.before(Calendar.getInstance()); } catch (Exception ex) { LOGGER.warn("Exception while checking if entry can be removed from the recycle bin", getId(), ex); return false; } }
Source:
<code>public JsonArray execJson() { <START> throw new NotImplementedException("JSON queries not implemented for remote calls") ; <END> }</code><technical_language>Minor: for worse, org.apache.jena.atlas.lib.NotImplemented</technical_language>

Target:
public JsonArray execJson() { throw new NotImplemented("JSON queries not implemented for remote calls") ; }
Source:
<code>private void assertGetResult(StorageDomain result) { assertNotNull(result); assertEquals(existingDomain, result); assertEquals("Wrong committed disk size", 8, result.getCommittedDiskSize()); assertEquals("Wrong actual disk size", 4, result.getActualImagesSize()); assertEquals("Wrong first metadata device", FixturesTool.LUN_ID_OF_DOMAIN_METADATA, result.getFirstMetadataDevice()); assertEquals("Wrong vg metadata device", FixturesTool.LUN_ID_OF_DOMAIN_VG_METADATA, result.getVgMetadataDevice()); assertEquals("Wrong shared status", StorageDomainSharedStatus.Active, result.getStorageDomainSharedStatus()); <START> assertEquals("Wrong backup flag status", false, result.isBackup()); <END> }</code><technical_language>set this true in fixtures.xml properly load a non-default value</technical_language>

Target:
private void assertGetResult(StorageDomain result) { assertNotNull(result); assertEquals(existingDomain, result); assertEquals("Wrong committed disk size", 8, result.getCommittedDiskSize()); assertEquals("Wrong actual disk size", 4, result.getActualImagesSize()); assertEquals("Wrong first metadata device", FixturesTool.LUN_ID_OF_DOMAIN_METADATA, result.getFirstMetadataDevice()); assertEquals("Wrong vg metadata device", FixturesTool.LUN_ID_OF_DOMAIN_VG_METADATA, result.getVgMetadataDevice()); assertEquals("Wrong shared status", StorageDomainSharedStatus.Active, result.getStorageDomainSharedStatus()); assertEquals("Wrong backup flag status", true, result.isBackup()); }
Source:
<code>private static FeedItem createFeedItem(Feed feed, DocumentFile file, Context context) { String uuid = UUID.randomUUID().toString(); MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever(); mediaMetadataRetriever.setDataSource(context, file.getUri()); String dateStr = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DATE); Date date = null; if (!TextUtils.isEmpty(dateStr)) { try { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.getDefault()); date = simpleDateFormat.parse(dateStr); <START> } catch (ParseException parseException) { <END> } } if (date == null) { date = new Date(file.lastModified()); } FeedItem item = new FeedItem(0, file.getName(), uuid, file.getName(), date, FeedItem.UNPLAYED, feed); item.setAutoDownload(false); String durationStr = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); String title = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE); if (!TextUtils.isEmpty(title)) { item.setTitle(title); } long duration = Long.parseLong(durationStr); long size = file.length(); FeedMedia media = new FeedMedia(0, item, (int) duration, 0, size, file.getType(), file.getUri().toString(), file.getUri().toString(), false, null, 0, 0); media.setHasEmbeddedPicture(mediaMetadataRetriever.getEmbeddedPicture() != null); item.setMedia(media); return item; }</code><technical_language>METADATA_KEY_DATE format is specified, I is good try falling DateUtils.parse here. if returns null either, I file modified date</technical_language>

Target:
private static FeedItem createFeedItem(Feed feed, DocumentFile file, Context context) { String uuid = UUID.randomUUID().toString(); MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever(); mediaMetadataRetriever.setDataSource(context, file.getUri()); String dateStr = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DATE); Date date = null; if (!TextUtils.isEmpty(dateStr)) { try { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.getDefault()); date = simpleDateFormat.parse(dateStr); } catch (ParseException parseException) { date = DateUtils.parse(dateStr); if (date == null) { date = new Date(file.lastModified()); } } } else { date = new Date(file.lastModified()); } FeedItem item = new FeedItem(0, file.getName(), uuid, file.getName(), date, FeedItem.UNPLAYED, feed); item.setAutoDownload(false); String durationStr = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); String title = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE); if (!TextUtils.isEmpty(title)) { item.setTitle(title); } long duration = Long.parseLong(durationStr); long size = file.length(); FeedMedia media = new FeedMedia(0, item, (int) duration, 0, size, file.getType(), file.getUri().toString(), file.getUri().toString(), false, null, 0, 0); media.setHasEmbeddedPicture(mediaMetadataRetriever.getEmbeddedPicture() != null); item.setMedia(media); return item; }
Source:
<code>public MockRestAdapter(String token, final String responseString, final HashMap<String, String> headers) { this.exceptionReference = new AtomicReference<>(); this.requestReference = new AtomicReference<>(); this.resultReference = new AtomicReference<>(); this.mockRestAdapter = new BitreserveRestAdapter(token); this.restAdapter = new RestAdapter.Builder().setEndpoint(GlobalConfigurations.API_SERVER_URL) .setRequestInterceptor(this.mockRestAdapter.getBitreserveRequestInterceptor(token)) .setClient(new Client() { @Override public Response execute(Request request) throws IOException { requestReference.set(request); return new Response("some/url", 200, "reason", new ArrayList<Header>() {{ if (headers != null) { for (Map.Entry<String, String> entry : headers.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); add(new retrofit.client.Header(key, value)); } } <START> }}, new TypedByteArray("application/json", TextUtils.isEmpty(responseString) ? new byte[0] : responseString.getBytes())); <END> } }).build(); this.mockRestAdapter.setAdapter(this.restAdapter); }</code><technical_language>is this needed? ask .getBytes() empty string</technical_language>

Target:
public MockRestAdapter(String token, final String responseString, final HashMap<String, String> headers) { this.exceptionReference = new AtomicReference<>(); this.requestReference = new AtomicReference<>(); this.resultReference = new AtomicReference<>(); this.mockRestAdapter = new BitreserveRestAdapter(token); this.restAdapter = new RestAdapter.Builder().setEndpoint(GlobalConfigurations.API_SERVER_URL) .setRequestInterceptor(this.mockRestAdapter.getBitreserveRequestInterceptor(token)) .setClient(new Client() { @Override public Response execute(Request request) throws IOException { requestReference.set(request); return new Response("some/url", 200, "reason", new ArrayList<Header>() {{ if (headers != null) { for (Map.Entry<String, String> entry : headers.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); add(new retrofit.client.Header(key, value)); } } }}, new TypedByteArray("application/json", responseString == null ? new byte[0] : responseString.getBytes())); } }).build(); this.mockRestAdapter.setAdapter(this.restAdapter); }
Source:
<code>protected void configure() { install(new XDocLoader.Module()); factory(XDocProjectConfig.Factory.class); DynamicMap.mapOf(binder(), Formatter.class); <START> bind(Formatter.class) .annotatedWith(Exports.named(AsciidocFormatter.NAME)) .to(AsciidocFormatter.class); <END> bind(Formatter.class) .annotatedWith(Exports.named(MarkdownFormatter.NAME)) .to(MarkdownFormatter.class); bind(Formatter.class) .annotatedWith(Exports.named(PlainTextFormatter.NAME)) .to(PlainTextFormatter.class); DynamicSet.bind(binder(), ProjectWebLink.class) .to(XDocWebLink.class); DynamicSet.bind(binder(), BranchWebLink.class) .to(XDocWebLink.class); DynamicSet.bind(binder(), FileWebLink.class) .to(XDocFileWebLink.class); DynamicSet.bind(binder(), TopMenu.class).toInstance(new TopMenu() { @Override public List<MenuEntry> getEntries() { StringBuilder url = new StringBuilder(); url.append("/plugins/"); url.append(pluginName); url.append(XDocServlet.PATH_PREFIX); url.append("${projectName}"); return Lists.newArrayList(new MenuEntry(GerritTopMenu.PROJECTS, Lists.newArrayList(new MenuItem("Readme", url.toString())))); } }); }</code><technical_language>Future improvement/optimization pluggable (plugin in plugin :). provide number of plugin packaged versions: all-in-one markdown version + pluggable optional formatter-modules added in addition gerrit_site/lib directory this work. similar scripting plugins javamelody-plugin, provide number of artifacts Buck driven build, e. g. want database introspection need another (optional) library: [1]. This allow add number of formatter dpendencies. Consumer of plugin need use. [1] <LINK_0></technical_language>

Target:
protected void configure() { install(new XDocLoader.Module()); factory(XDocProjectConfig.Factory.class); DynamicMap.mapOf(binder(), Formatter.class); bind(Formatter.class) .annotatedWith(Exports.named(AsciidoctorFormatter.NAME)) .to(AsciidoctorFormatter.class); bind(Formatter.class) .annotatedWith(Exports.named(MarkdownFormatter.NAME)) .to(MarkdownFormatter.class); bind(Formatter.class) .annotatedWith(Exports.named(PlainTextFormatter.NAME)) .to(PlainTextFormatter.class); DynamicSet.bind(binder(), ProjectWebLink.class) .to(XDocWebLink.class); DynamicSet.bind(binder(), BranchWebLink.class) .to(XDocWebLink.class); DynamicSet.bind(binder(), FileWebLink.class) .to(XDocFileWebLink.class); DynamicSet.bind(binder(), TopMenu.class).toInstance(new TopMenu() { @Override public List<MenuEntry> getEntries() { StringBuilder url = new StringBuilder(); url.append("/plugins/"); url.append(pluginName); url.append(XDocServlet.PATH_PREFIX); url.append("${projectName}"); return Lists.newArrayList(new MenuEntry(GerritTopMenu.PROJECTS, Lists.newArrayList(new MenuItem("Readme", url.toString())))); } }); }
Source:
<code>public void onError(Throwable e) { Disposable d = get(); if (d != DisposableHelper.DISPOSED && compareAndSet(d, DisposableHelper.DISPOSED)) { DisposableHelper.dispose(task); actual.onError(e); <START> } <END> }</code><technical_language>deliver error RxJavaPlugins.onError() in else block</technical_language>

Target:
public void onError(Throwable e) { Disposable d = get(); if (d != DisposableHelper.DISPOSED && compareAndSet(d, DisposableHelper.DISPOSED)) { DisposableHelper.dispose(task); actual.onError(e); } else { RxJavaPlugins.onError(e); } }
Source:
<code>private String calculateZone(String zoneFromRequest, FreeIpaAndClient freeIpaAndClient) throws FreeIpaClientException { Optional<String> optionalZone = Optional.ofNullable(zoneFromRequest); String zone = optionalZone.orElse(freeIpaAndClient.getFreeIpa().getDomain()); boolean providedZoneDifferentThanDefault = !freeIpaAndClient.getFreeIpa().getDomain().equals(StringUtils.removeEnd(zone, ".")); if (optionalZone.isPresent() && providedZoneDifferentThanDefault) { validateZoneExists(optionalZone.get(), freeIpaAndClient.getClient()); <START> } <END> return zone; }</code><technical_language>a log line nice</technical_language>

Target:
private String calculateZone(String zoneFromRequest, FreeIpaAndClient freeIpaAndClient) throws FreeIpaClientException { Optional<String> optionalZone = Optional.ofNullable(zoneFromRequest); String zone = optionalZone.orElse(freeIpaAndClient.getFreeIpa().getDomain()); boolean providedZoneDifferentThanDefault = !freeIpaAndClient.getFreeIpa().getDomain().equals(StringUtils.removeEnd(zone, ".")); if (optionalZone.isPresent() && providedZoneDifferentThanDefault) { LOGGER.debug("Zone is provided in the request and different from the default one [{}]", zone, freeIpaAndClient.getFreeIpa().getDomain()); validateZoneExists(optionalZone.get(), freeIpaAndClient.getClient()); } return zone; }
Source:
<code>Resource getTotalReserved() { Resource totalReserved = getReservedContainer() != null ? Resources.clone(getReservedContainer().getAllocatedResource()) : <START> Resource.newInstance(0, 0); <END> Resources.addTo(totalReserved, totalResourcesPreempted); return totalReserved; }</code><technical_language>Resources.clone(Resources.none()). way, do Resources.clone( getReservedContainer() != null ? getReservedContainer.getAllocatedResource() : Resources.none())</technical_language>

Target:
Resource getTotalReserved() { Resource totalReserved = Resources.clone(getReservedContainer() != null ? getReservedContainer().getAllocatedResource() : Resource.newInstance(0, 0)); Resources.addTo(totalReserved, totalResourcesPreempted); return totalReserved; }
Source:
<code>public byte[] getCacheKey() { byte[] delegateCacheKey = delegate.getCacheKey(); <START> return ByteBuffer.allocate(1 + delegateCacheKey.length) <END> .put(AggregatorUtil.SUPPRESSED_AGG_CACHE_TYPE_ID) .put(delegateCacheKey) .array(); }</code><technical_language>Please CacheKeyBuilder. AggregatorFactory is Cacheable, simply builder.appendCacheable()</technical_language>

Target:
public byte[] getCacheKey() { CacheKeyBuilder cacheKeyBuilder = new CacheKeyBuilder(AggregatorUtil.SUPPRESSED_AGG_CACHE_TYPE_ID); cacheKeyBuilder.appendCacheable(delegate); return cacheKeyBuilder.build(); }
Source:
<code>public String toStringSpecific() { <START> return NLS.bind("Core Node, {0} children {1}", END> nbChildren, Arrays.toString(Arrays.copyOf(children, nbChildren))); }</code><technical_language>NLS.bind is for externalized strings, {0}, {1}, etc. defined in external messages.properties files. get a similar result String.format(), Guava's Objects.toStringHelper(), is nice btw</technical_language>

Target:
public String toStringSpecific() { return String.format("Core Node, %d children %s", nbChildren, Arrays.toString(Arrays.copyOf(children, nbChildren))); }
Source:
<code>private void createSolrCore() throws IOException, SolrServerException { String url = HttpSolrClientFactory.getDefaultHttpsAddress(); final HttpClientBuilder builder = HttpClients.custom() .setDefaultCookieStore(new BasicCookieStore()) .setMaxConnTotal(128) <START> .setMaxConnPerRoute(32); <END> if (StringUtils.startsWithIgnoreCase(url, "https")) { builder.setSSLSocketFactory( new SSLConnectionSocketFactory( HttpSolrClientFactory.getSslContext(), HttpSolrClientFactory.getProtocols(), HttpSolrClientFactory.getCipherSuites(), SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER)); } final String solrDataDir = HttpSolrClientFactory.getSolrDataDir(); if (solrDataDir != null) { ConfigurationStore.getInstance().setDataDirectoryPath(solrDataDir); } HttpSolrClientFactory.createSolrCore(url, coreName, null, builder.build()); }</code><technical_language>log get full stack trace</technical_language>

Target:
private void createSolrCore() throws IOException, SolrServerException { httpBuilder = new org.codice.solr.factory.impl.HttpClientBuilder(encryptionService); String url = getBackupUrl(); final String solrDataDir = getSolrDataDir(); ConfigurationStore.getInstance().setDataDirectoryPath(solrDataDir); HttpSolrClientFactory.createSolrCore(url, coreName, null, httpBuilder.get().build()); }
Source:
<code>private ClassLoader buildCoreClassLoader() throws IOException { List<URL> urls = new ArrayList<>(); List<DependenciesTxt> overrides = new ArrayList<>(); DependenciesTxt core = new DependenciesTxt(getClass().getClassLoader().getResourceAsStream("dependencies.txt")); File[] plugins = new File(home, "plugins").listFiles(); if (plugins!=null) { for (File p : plugins) { String n = p.getName(); if (p.isFile() && (n.endsWith(".jpi") || n.endsWith(".hpi"))) { try { new Plugin(p).process(core, urls, overrides); } catch (IOException e) { <START> LOGGER.log(WARNING, "Skipping "+p, e); <END> } } } } Set<String> jars = context.getResourcePaths("/WEB-INF/jars"); if (jars==null || jars.isEmpty()) { throw new IllegalStateException("No WEB-INF/jars"); } OUTER: for (String jar : jars) { if (!jar.endsWith(".jar")) continue; String justName = jar.substring(jar.lastIndexOf('/')+1); Dependency d = core.fromFileName(justName); if (d==null) { LOGGER.log(INFO, "Allowing unexpected core jar file without override check: "+jar); } else { for (DependenciesTxt o : overrides) { if (o.contains(d.ga)) continue OUTER; } } urls.add(context.getResource(jar)); } return new URLClassLoader(urls.toArray(new URL[urls.size()]),Thread.currentThread().getContextClassLoader()); }</code><technical_language>", is a plugin". IMHO logging level is high folders disable flags in directory</technical_language>

Target:
private ClassLoader buildCoreClassLoader() throws IOException { List<URL> urls = new ArrayList<>(); DependenciesTxt core = new DependenciesTxt(getClass().getClassLoader().getResourceAsStream("dependencies.txt")); File[] plugins = new File(home, "plugins").listFiles(); if (plugins!=null) { for (File p : plugins) { String n = p.getName(); if (p.isFile() && (n.endsWith(".jpi") || n.endsWith(".hpi"))) { try { new Plugin(p).process(core, urls, overrides); } catch (IOException e) { LOGGER.log(WARNING, "Skipping "+p, e); } } } } Set<String> jars = context.getResourcePaths("/WEB-INF/jars"); if (jars==null || jars.isEmpty()) { throw new IllegalStateException("No WEB-INF/jars"); } for (String jar : jars) { if (!jar.endsWith(".jar")) continue; String justName = jar.substring(jar.lastIndexOf('/')+1); Dependency d = core.fromFileName(justName); if (d==null) { LOGGER.log(INFO, "Allowing unexpected core jar file without override check: "+jar); } else { if (overrides.isOverridden(d)) continue; } urls.add(context.getResource(jar)); } return new URLClassLoader(urls.toArray(new URL[urls.size()]),Thread.currentThread().getContextClassLoader()); }
Source:
<code>protected void run() throws Exception { org.eclipse.jgit.api.Status status = new Git(db).status().call(); Collection<String> added = status.getAdded(); Collection<String> changed = status.getChanged(); Collection<String> removed = status.getRemoved(); Collection<String> modified = status.getModified(); Collection<String> missing = status.getMissing(); <START> Collection<String> untracked = status.getUntracked(); <END> int nbToBeCommitted = added.size() + changed.size() + removed.size(); if (nbToBeCommitted > 0) { out.println("# " + CLIText.get().toBeCommitted); printList(CLIText.get().newFile, added); printList(CLIText.get().modified, changed); printList(CLIText.get().removed, removed); } int nbNotStagedForCommit = modified.size() + missing.size(); if (nbNotStagedForCommit > 0) { out.println("# " + CLIText.get().notStagedForCommit); printList(CLIText.get().modified, modified); printList(CLIText.get().removed, missing); } int nbUntracked = untracked.size(); if (showUntracked && nbUntracked > 0) { out.println("# " + CLIText.get().untrackedFiles); printList(CLIText.get().untracked, untracked); } out.println(MessageFormat.format(CLIText.get().summaryStatus, nbToBeCommitted, nbNotStagedForCommit, nbUntracked)); }</code><technical_language>add status.getConflicting() 'unmerged'</technical_language>

Target:
protected void run() throws Exception { final Ref head = db.getRef(Constants.HEAD); if (head != null && head.isSymbolic()) { String branch = Repository.shortenRefName(head.getLeaf().getName()); out.println(MessageFormat.format("# " + CLIText.get().onBranch, branch)); } else out.println("# " + CLIText.get().notOnAnyBranch); org.eclipse.jgit.api.Status status = new Git(db).status().call(); Collection<String> added = status.getAdded(); Collection<String> changed = status.getChanged(); Collection<String> removed = status.getRemoved(); Collection<String> modified = status.getModified(); Collection<String> missing = status.getMissing(); Collection<String> untracked = status.getUntracked(); Collection<String> unmerged = status.getConflicting(); int nbToBeCommitted = added.size() + changed.size() + removed.size(); if (nbToBeCommitted > 0) { out.println("# " + CLIText.get().toBeCommitted); printList(CLIText.get().newFile, added); printList(CLIText.get().modified, changed); printList(CLIText.get().removed, removed); } int nbNotStagedForCommit = modified.size() + missing.size(); if (nbNotStagedForCommit > 0) { out.println("# " + CLIText.get().notStagedForCommit); printList(CLIText.get().modified, modified); printList(CLIText.get().removed, missing); } int nbUnmerged = unmerged.size(); if (nbUnmerged > 0) { out.println("# " + CLIText.get().unmergedPaths); printList(unmerged); } int nbUntracked = untracked.size(); if (showUntracked && nbUntracked > 0) { out.println("# " + CLIText.get().untrackedFiles); printList(untracked); } out.println(MessageFormat.format(CLIText.get().summaryStatus, nbToBeCommitted, nbNotStagedForCommit, nbUnmerged, nbUntracked)); }
Source:
<code>public String toString() { final StringBuilder out = new StringBuilder(); out.append(this.argument.toString()); out.append(" -> "); out.append(this.result.toString()); <START> return out.toString(); <END> }</code><technical_language>String.format("%s -> %s", argument, result)</technical_language>

Target:
public String toString() { return String.format("%s -> %s", argument, result); }
Source:
<code>private String sendToZeppelinHub(HttpMethod method, String url, String json, boolean withResponse) throws IOException { <START> InputStreamResponseListener listener = new InputStreamResponseListener(); <END> Response response; String data; Request request = client.newRequest(url).method(method).header(ZEPPELIN_TOKEN_HEADER, token); if ((method.equals(HttpMethod.PUT) || method.equals(HttpMethod.POST)) && !StringUtils.isBlank(json)) { request.content(new StringContentProvider(json, "UTF-8"), "application/json;charset=UTF-8"); } return withResponse ? sendToZeppelinHub(request) : sendToZeppelinHubWithoutResponseBody(request); }</code><technical_language>delete unused listener, response, data variables</technical_language>

Target:
private String sendToZeppelinHub(HttpMethod method, String url, String json, boolean withResponse) throws IOException { Request request = client.newRequest(url).method(method).header(ZEPPELIN_TOKEN_HEADER, token); if ((method.equals(HttpMethod.PUT) || method.equals(HttpMethod.POST)) && !StringUtils.isBlank(json)) { request.content(new StringContentProvider(json, "UTF-8"), "application/json;charset=UTF-8"); } return withResponse ? sendToZeppelinHub(request) : sendToZeppelinHubWithoutResponseBody(request); }
Source:
<code>public Path convert(Path outputFile) throws GoGoDuckException { List<String> outputCommand = new ArrayList<String>(); String baseFilename = FilenameUtils.getBaseName(String.valueOf(outputFile)); String txtFilename = baseFilename + ".txt"; outputCommand.add(ncpdqPath + " -U " + outputFile.toString() + " tmp"); outputCommand.add("mv tmp " + outputFile.toString()); outputCommand.add(ncksPath + " --no_nm_prn -a " + outputFile.toString() + " > " + txtFilename); try { executeCommands(outputCommand, outputFile); String outputFileAsCsvString = parseNcks(txtFilename); Path tmpPath = Paths.get(txtFilename); Files.delete(tmpPath); <START> String csvFilename = baseFilename + "." + extension; <END> File csvFile = new File(csvFilename); FileUtils.writeStringToFile(csvFile, outputFileAsCsvString); return csvFile.toPath(); } catch (Exception e) { throw new GoGoDuckException(String.format("Could not convert output to csv: '%s'", e.getMessage())); } }</code><technical_language>String.format here</technical_language>

Target:
public Path convert(Path outputFile) throws GoGoDuckException { String baseFilename = FilenameUtils.getBaseName(String.valueOf(outputFile)); try { File unpackedNetCDF = unpackNetCDF(outputFile.toFile()); Path csvPath = executeNcksAndOutputToFile(baseFilename, unpackedNetCDF.toPath()); Files.delete(unpackedNetCDF.toPath()); return csvPath; } catch (Exception e) { throw new GoGoDuckException(String.format("Could not convert output to csv: '%s'", e.getMessage())); } }
Source:
<code>public void withPublicKeyWhenUsingCustomTypeHeaderThenSuccessfullyDecodes() throws Exception { RSAPublicKey publicKey = TestKeys.DEFAULT_PUBLIC_KEY; RSAPrivateKey privateKey = TestKeys.DEFAULT_PRIVATE_KEY; JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).type(new JOSEObjectType("JWS")).build(); JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() .expirationTime(Date.from(Instant.now().plusSeconds(60))) .build(); SignedJWT signedJwt = signedJwt(privateKey, header, claimsSet); NimbusJwtDecoder decoder = withPublicKey(publicKey) .signatureAlgorithm(SignatureAlgorithm.RS256) <START> .jwtProcessorCustomizer(p -> p.setJWSTypeVerifier((type, context) -> {})) <END> .build(); assertThat(decoder.decode(signedJwt.serialize()).containsClaim(JwtClaimNames.EXP)).isNotNull(); }</code><technical_language>recommend test follow allowlisting pattern Nimbus is using. For example, more secure do: java .jwtProcessorCustomizer(p -> p.setJWSTypeVerifier( new DefaultJOSEObjectTypeVerifier(new JOSEObjectType("JWS")) ) )</technical_language>

Target:
public void withPublicKeyWhenUsingCustomTypeHeaderThenSuccessfullyDecodes() throws Exception { RSAPublicKey publicKey = TestKeys.DEFAULT_PUBLIC_KEY; RSAPrivateKey privateKey = TestKeys.DEFAULT_PRIVATE_KEY; JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).type(new JOSEObjectType("JWS")).build(); JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() .expirationTime(Date.from(Instant.now().plusSeconds(60))) .build(); SignedJWT signedJwt = signedJwt(privateKey, header, claimsSet); NimbusJwtDecoder decoder = withPublicKey(publicKey) .signatureAlgorithm(SignatureAlgorithm.RS256) .jwtProcessorCustomizer(p -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS")))) .build(); assertThat(decoder.decode(signedJwt.serialize()).containsClaim(JwtClaimNames.EXP)).isNotNull(); }
Source:
<code>public View getViewForHighlighting(Object element) { if (getHost() instanceof AndroidDescriptorHost) { <START> final AndroidDescriptorHost host = (AndroidDescriptorHost) getHost(); <END> final Dialog dialog = (Dialog) element; return host.getHighlightingView(dialog.getWindow()); } return null; }</code><technical_language>nit: store result of getHost() re-use it</technical_language>

Target:
public View getViewForHighlighting(Object element) { final Descriptor.Host host = getHost(); if (host instanceof AndroidDescriptorHost) { final Dialog dialog = (Dialog) element; return ((AndroidDescriptorHost) host).getHighlightingView(dialog.getWindow()); } return null; }
Source:
<code>public void addNodeToken(String nodeUrl, String token) throws RMException { if (allNodes.containsKey(nodeUrl)) { RMNode rmNode = allNodes.get(nodeUrl); rmNode.addToken(token); } else { <START> throw new RMException("Unkonwn node " + nodeUrl); <END> } }</code><technical_language>Unkonwn => Unknown</technical_language>

Target:
public void addNodeToken(String nodeUrl, String token) throws RMException { if (allNodes.containsKey(nodeUrl)) { RMNode rmNode = allNodes.get(nodeUrl); checkNodeAdminPermission(rmNode, caller); rmNode.addToken(token); } else { throw new RMException("Unknown node " + nodeUrl); } }
Source:
<code>private CircuitBreakerMetrics(Seq<CircuitBreaker> circuitBreakers){ circuitBreakers.forEach(circuitBreaker -> { <START> metricRegistry.register(name("resilience4j.circuitbreaker", circuitBreaker.getName(), "successful"), <END> (Gauge<Integer>) () -> circuitBreaker.getMetrics().getNumberOfSuccessfulCalls()); metricRegistry.register(name("resilience4j.circuitbreaker", circuitBreaker.getName(), "failed"), (Gauge<Integer>) () -> circuitBreaker.getMetrics().getNumberOfFailedCalls()); metricRegistry.register(name("resilience4j.circuitbreaker", circuitBreaker.getName(), "not_permitted"), (Gauge<Long>) () -> circuitBreaker.getMetrics().getNumberOfNotPermittedCalls()); metricRegistry.register(name("resilience4j.circuitbreaker", circuitBreaker.getName(), "buffered"), (Gauge<Integer>) () -> circuitBreaker.getMetrics().getNumberOfBufferedCalls()); metricRegistry.register(name("resilience4j.circuitbreaker", circuitBreaker.getName(), "buffered_max"), (Gauge<Integer>) () -> circuitBreaker.getMetrics().getMaxNumberOfBufferedCalls()); } ); }</code><technical_language>move circuitBreaker.getMetrics() circuitBreaker.getName() separate variables start of lambda</technical_language>

Target:
private CircuitBreakerMetrics(Seq<CircuitBreaker> circuitBreakers){ circuitBreakers.forEach(circuitBreaker -> { String name = circuitBreaker.getName(); CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics(); metricRegistry.register(name("resilience4j.circuitbreaker", name, "successful"), (Gauge<Integer>) metrics::getNumberOfSuccessfulCalls); metricRegistry.register(name("resilience4j.circuitbreaker", name, "failed"), (Gauge<Integer>) metrics::getNumberOfFailedCalls); metricRegistry.register(name("resilience4j.circuitbreaker", name, "not_permitted"), (Gauge<Long>) metrics::getNumberOfNotPermittedCalls); metricRegistry.register(name("resilience4j.circuitbreaker", name, "buffered"), (Gauge<Integer>) metrics::getNumberOfBufferedCalls); metricRegistry.register(name("resilience4j.circuitbreaker", name, "buffered_max"), (Gauge<Integer>) metrics::getMaxNumberOfBufferedCalls); } ); }
Source:
<code>private void gtk_swt_set_border_color (GdkColor color) { GdkRGBA rgba = null; if (color != null) { rgba = new GdkRGBA (); <START> rgba = display.toGdkRGBA (color); <END> } String css_string = "* {\n"; if (rgba != null) { String css_color = gtk_rgba_to_css_string (rgba); css_string += "border-color: " + css_color + ";\n"; } css_string += "}\n"; long context = OS.gtk_widget_get_style_context (handle); gtk_css_provider_load_from_css (context, css_string); }</code><technical_language>display.toGdkRGBA returns null remove "rgba=new GdkRGBA()"</technical_language>

Target:
private void gtk_swt_set_border_color (GdkColor color) { GdkRGBA rgba = null; if (color != null) { rgba = display.toGdkRGBA (color); } String css_string = "* {\n"; if (rgba != null) { String css_color = gtk_rgba_to_css_string (rgba); css_string += "border-color: " + css_color + ";\n"; } css_string += "}\n"; long context = OS.gtk_widget_get_style_context (handle); gtk_css_provider_load_from_css (context, css_string); }
Source:
<code>protected Optional<UserVO> checkPassword(UserVO user, String password) { boolean validPassword = passwordService.checkPassword(password, user.getPasswordSalt(), user.getPasswordHash()); long loginTimeout = configurationService.getLong(Constants.LAST_LOGIN_TIMEOUT, Constants.LAST_LOGIN_TIMEOUT_DEFAULT); boolean mustUpdateLoginStatistic = user.getLoginAttempts() != 0 || user.getLastLogin() == null || timestampService.getTimestamp() - user.getLastLogin().getTime() > loginTimeout; if (validPassword && mustUpdateLoginStatistic) { UserVO user1 = updateStatisticOnSuccessfulLogin(user, loginTimeout); return of(user1); } else if (!validPassword) { user.setLoginAttempts(user.getLoginAttempts() + 1); if (user.getLoginAttempts() >= configurationService.getInt(Constants.MAX_LOGIN_ATTEMPTS, Constants.MAX_LOGIN_ATTEMPTS_DEFAULT)) { user.setStatus(UserStatus.LOCKED_OUT); <START> logger.info("User with id has been locked out after login attempts.", user.getId(), user.getLoginAttempts()); <END> user.setLoginAttempts(0); } userDao.merge(user); return empty(); } return of(user); }</code><technical_language>Change id login</technical_language>

Target:
protected Optional<UserVO> checkPassword(UserVO user, String password) { boolean validPassword = passwordService.checkPassword(password, user.getPasswordSalt(), user.getPasswordHash()); long loginTimeout = configurationService.getLong(Constants.LAST_LOGIN_TIMEOUT, Constants.LAST_LOGIN_TIMEOUT_DEFAULT); boolean mustUpdateLoginStatistic = user.getLoginAttempts() != 0 || user.getLastLogin() == null || timestampService.getTimestamp() - user.getLastLogin().getTime() > loginTimeout; if (validPassword && mustUpdateLoginStatistic) { UserVO user1 = updateStatisticOnSuccessfulLogin(user, loginTimeout); return of(user1); } else if (!validPassword) { user.setLoginAttempts(user.getLoginAttempts() + 1); if (user.getLoginAttempts() >= configurationService.getInt(Constants.MAX_LOGIN_ATTEMPTS, Constants.MAX_LOGIN_ATTEMPTS_DEFAULT)) { user.setStatus(UserStatus.LOCKED_OUT); logger.info("User with login has been locked out after login attempts.", user.getLogin(), user.getLoginAttempts()); user.setLoginAttempts(0); } userDao.merge(user); return empty(); } return of(user); }
Source:
<code>public T proceed() throws Throwable { InterruptTask interruptTask = new InterruptTask(Thread.currentThread()); ScheduledFuture<?> future = executor.schedule(interruptTask, timeout.getValue(), timeout.getUnit()); Throwable failure = null; T result = null; try { result = delegate.proceed(); } catch (Throwable t) { failure = t; } finally { future.cancel(true); if (interruptTask.executed) { <START> Thread.interrupted(); <END> failure = createTimeoutException(failure); } } if (failure != null) { throw failure; } return result; }</code><technical_language>I happen if throwable is blacklisted. IMO in situation thrown as-is if, for example, OOME, JVM crash gracefully. @marcphilipp Thoughts</technical_language>

Target:
public T proceed() throws Throwable { InterruptTask interruptTask = new InterruptTask(Thread.currentThread()); ScheduledFuture<?> future = executor.schedule(interruptTask, timeout.getValue(), timeout.getUnit()); Throwable failure = null; T result = null; try { result = delegate.proceed(); } catch (Throwable t) { BlacklistedExceptions.rethrowIfBlacklisted(t); failure = t; } finally { boolean cancelled = future.cancel(false); if (!cancelled) { future.get(); } if (interruptTask.executed) { Thread.interrupted(); failure = createTimeoutException(failure); } } if (failure != null) { throw failure; } return result; }
Source:
<code>public boolean isTaskExecutable(NodeSet selectedNodes, EligibleTaskDescriptor task) { logger.debug("Selected Nodes: " + selectedNodes); logger.debug("Analysing task: " + ((EligibleTaskDescriptorImpl) task).getInternal().getName()); final String requiredLicenses = ((EligibleTaskDescriptorImpl) task).getInternal() .getRuntimeGenericInformation() .get(REQUIRED_LICENSES); if (requiredLicenses != null) { <START> if (eligibleTasksDescriptorsLicenses == null) <END> eligibleTasksDescriptorsLicenses = new HashMap<String, FixedSizeArrayList>(); final Properties properties = LicenseConfiguration.getConfiguration().getProperties(); logger.debug("Need to check licenses with " + properties.toString()); final String[] requiredLicensesArray = requiredLicenses.split(","); for (int i = 0; i < requiredLicensesArray.length; i++) { final String currentRequiredLicense = requiredLicensesArray[i]; final int numberOfLicenses = Integer.parseInt(properties.getProperty(currentRequiredLicense)); if (!eligibleTasksDescriptorsLicenses.containsKey(currentRequiredLicense)) { eligibleTasksDescriptorsLicenses.put(currentRequiredLicense, new FixedSizeArrayList(numberOfLicenses)); } if (!canGetLicense(task, currentRequiredLicense, numberOfLicenses)) { logger.debug("License for " + currentRequiredLicense + " not available, returning false"); return false; } } for (int i = 0; i < requiredLicensesArray.length; i++) { eligibleTasksDescriptorsLicenses.get(requiredLicensesArray[i]).add(task); } logger.debug("All licenses are available, returning true"); return true; } else { return true; } }</code><technical_language>please add curly brackets</technical_language>

Target:
public boolean isTaskExecutable(NodeSet selectedNodes, EligibleTaskDescriptor task) { logger.debug("Selected Nodes: " + selectedNodes); logger.debug("Analysing task: " + ((EligibleTaskDescriptorImpl) task).getInternal().getName()); final String requiredLicenses = ((EligibleTaskDescriptorImpl) task).getInternal() .getRuntimeGenericInformation() .get(REQUIRED_LICENSES); if (requiredLicenses != null) { initialize(); logger.debug("Need to check licenses with " + properties.toString()); final String[] requiredLicensesArray = requiredLicenses.split(","); for (int i = 0; i < requiredLicensesArray.length; i++) { final String currentRequiredLicense = requiredLicensesArray[i]; if (!canGetLicense(currentRequiredLicense)) { logger.debug("License for " + currentRequiredLicense + " not available, keep task pending"); return false; } } for (int i = 0; i < requiredLicensesArray.length; i++) { eligibleTasksDescriptorsLicenses.get(requiredLicensesArray[i]).add(task); } logger.debug("All licenses are available, executing task"); return true; } else { return true; } }
Source:
<code>public ReadCache(ByteBufAllocator allocator, long maxCacheSize, int maxSegmentSize) { this.allocator = allocator; int segmentsCount = Math.max(2, (int) (maxCacheSize / maxSegmentSize)); segmentSize = (int) (maxCacheSize / segmentsCount); cacheSegments = new ArrayList<>(); cacheIndexes = new ArrayList<>(); for (int i = 0; i < segmentsCount; i++) { <START> cacheSegments.add(Unpooled.buffer(segmentSize, segmentSize)); <END> cacheIndexes.add(new ConcurrentLongLongPairHashMap(4096, 2 * Runtime.getRuntime().availableProcessors())); } }</code><technical_language>This is coming allocator. Rather, intention is get unpooled direct memory for read cache</technical_language>

Target:
public ReadCache(ByteBufAllocator allocator, long maxCacheSize, int maxSegmentSize) { this.allocator = allocator; int segmentsCount = Math.max(2, (int) (maxCacheSize / maxSegmentSize)); segmentSize = (int) (maxCacheSize / segmentsCount); cacheSegments = new ArrayList<>(); cacheIndexes = new ArrayList<>(); for (int i = 0; i < segmentsCount; i++) { cacheSegments.add(allocator.buffer(segmentSize, segmentSize)); cacheIndexes.add(new ConcurrentLongLongPairHashMap(4096, 2 * Runtime.getRuntime().availableProcessors())); } }
Source:
<code>public RAFLock lockOpen() throws IOException { RAFLock lock = new RAFLock() { @Override protected void innerUnlock() { PooledRandomAccessFileWrapper.this.unlock(); } }; synchronized(closables) { if(closed) throw new IOException("Already closed"); if(lockLevel > 0) { lockLevel++; return lock; } else { while(true) { if(OPEN_FDS < MAX_OPEN_FDS) break; PooledRandomAccessFileWrapper closable = closables.pollFirst(); if(closable != null) { closable.closeRAF(); continue; } try { closables.wait(); } catch (InterruptedException e) { } } <START> OPEN_FDS++; <END> lockLevel++; } if(raf != null) return lock; try { raf = new RandomAccessFile(file, mode); } catch (IOException e) { unlock(); throw e; } return lock; } }</code><technical_language>file descriptor open here? This statement wrong place</technical_language>

Target:
public RAFLock lockOpen() throws IOException { RAFLock lock = new RAFLock() { @Override protected void innerUnlock() { PooledRandomAccessFileWrapper.this.unlock(); } }; synchronized(closables) { while(true) { if(closed) throw new IOException("Already closed"); if(raf != null) { lockLevel++; return lock; } else if(OPEN_FDS < MAX_OPEN_FDS) { lockLevel++; OPEN_FDS++; try { raf = new RandomAccessFile(file, mode); } catch (IOException e) { lockLevel--; OPEN_FDS--; throw e; } return lock; } else { PooledRandomAccessFileWrapper closable = pollFirstClosable(); if(closable != null) { closable.closeRAF(); continue; } try { closables.wait(); } catch (InterruptedException e) { } } } } }
Source:
<code>private void saveProperty(String type, String name, String value) { <START> String payload = "UPDATE PROPERTIES SET TYPE='" + name + "', VALUE='" + type + "' WHERE NAME = '" + value + "'"; <END> Statement sta; try { sta = conn.createStatement(); int count = sta.executeUpdate(payload); if (count == 0) { payload = "INSERT INTO PROPERTIES VALUES ('" + name + "', '" + type + "', '" + value + "')"; Statement insert = conn.createStatement(); count = insert.executeUpdate(payload); } } catch (SQLException e) { log.warn("Unable to save property " + name + "!"); log.warn(e.toString()); e.printStackTrace(); } }</code><technical_language>A sanitization a lot of sense, if else '</technical_language>

Target:
private void saveProperty(String type, String name, String value) { try { PreparedStatement sta = conn.prepareStatement("UPDATE PROPERTIES SET TYPE= ?, VALUE= ? WHERE NAME = ?"); sta.setString(1, type); sta.setString(2, value); sta.setString(3, name); int count = sta.executeUpdate(); if (count == 0) { PreparedStatement insert = conn.prepareStatement("INSERT INTO PROPERTIES VALUES (?, ?, ?)"); insert.setString(1, name); insert.setString(2, value); insert.setString(3, value); count = insert.executeUpdate(); } } catch (SQLException e) { log.warn("Unable to save property " + name + "!"); log.warn(e.toString()); e.printStackTrace(); } }
Source:
<code>public int add(ComplexEventChunk<StreamEvent> addingEventChunk) { addingEventChunk.reset(); while (addingEventChunk.hasNext()) { ComplexEvent complexEvent = addingEventChunk.next(); StreamEvent streamEvent = tableStreamEventFactory.newInstance(); eventConverter.convertComplexEvent(complexEvent, streamEvent); this.add(streamEvent); } <START> return findEventChunkSize(addingEventChunk.getFirst()); <END> }</code><technical_language>This is a costly operation finding event size time, do other optimizations</technical_language>

Target:
public void add(ComplexEventChunk<StreamEvent> addingEventChunk) { addingEventChunk.reset(); while (addingEventChunk.hasNext()) { size++; ComplexEvent complexEvent = addingEventChunk.next(); StreamEvent streamEvent = tableStreamEventFactory.newInstance(); eventConverter.convertComplexEvent(complexEvent, streamEvent); this.add(streamEvent); } }