auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean bind(final ClientEndpoint endpoint) { if (!clientSelector.select(endpoint)) { return false; } if (endpointManager.registerEndpoint(endpoint)) { Connection conn = endpoint.getConnection(); <START> if (conn instanceof TcpIpConnection) { <END> InetSocketAddress socketAddress = conn.getRemoteSocketAddress(); if (socketAddress != null) { Address address = new Address(socketAddress); ((TcpIpConnection) conn).setEndPoint(address); } } } else { return true; } if (!clientSelector.select(endpoint)) { endpointManager.removeEndpoint(endpoint); return false; } return true; }</code><technical_language>minor: this more readable if move this condition like; java if (!endpointManager.registerEndpoint(endpoint)) { // connection exists reauthenticated promote owner connection return true; }</technical_language>

Target:
public boolean bind(final ClientEndpoint endpoint) { if (!clientSelector.select(endpoint)) { return false; } if (!endpointManager.registerEndpoint(endpoint)) { return true; } Connection conn = endpoint.getConnection(); if (conn instanceof TcpIpConnection) { InetSocketAddress socketAddress = conn.getRemoteSocketAddress(); if (socketAddress != null) { Address address = new Address(socketAddress); ((TcpIpConnection) conn).setEndPoint(address); } } if (!clientSelector.select(endpoint)) { endpointManager.removeEndpoint(endpoint); return false; } return true; }
Source:
<code>public void update(Observable o, Object arg) { clear(); <START> createProfiles(); <END> }</code><technical_language>sync, please create profiles replace volatile reference</technical_language>

Target:
public void update(Observable o, Object arg) { profiles = createProfiles(); }
Source:
<code>public boolean equals(Object o) { if (o instanceof WorkItemDefinition) { WorkItemDefinition other = (WorkItemDefinition) o; return super.equals(other) && name.equals(other.name) && ((null != category) ? category.equals(other.category) : null == other.category) && ((null != description) ? description.equals(other.description) : null == other.description) && ((null != displayName) ? displayName.equals(other.displayName) : null == other.displayName) && ((null != documentation) ? documentation.equals(other.documentation) : null == other.documentation) && <START> ((null != iconDefinition) ? iconDefinition.equals(other.iconDefinition) : null == other.iconDefinition) && <END> ((null != defaultHandler) ? defaultHandler.equals(other.defaultHandler) : null == other.defaultHandler) && ((null != parameters) ? parameters.equals(other.parameters) : null == other.parameters) && ((null != results) ? results.equals(other.results) : null == other.results) && ((null != dependencies) ? dependencies.equals(other.dependencies) : null == other.dependencies); } return false; }</code><technical_language>This is simplified Objects.equals(iconDefinition, other.iconDefinition); for other cases in this class</technical_language>

Target:
public boolean equals(Object o) { if (o instanceof WorkItemDefinition) { WorkItemDefinition other = (WorkItemDefinition) o; return super.equals(other) && name.equals(other.name) && Objects.equals(category, other.category) && Objects.equals(description, other.description) && Objects.equals(displayName, other.displayName) && Objects.equals(documentation, other.documentation) && Objects.equals(iconDefinition, other.iconDefinition) && Objects.equals(defaultHandler, other.defaultHandler) && Objects.equals(parameters, other.parameters) && Objects.equals(results, other.results) && Objects.equals(dependencies, other.dependencies); } return false; }
Source:
<code>public void start() { onPingRequestSubscriber = Subscribers.create(new OnPingRequestAction()); transport.listen().observeOn(scheduler) .filter(PING_FILTER) <START> .filter(targetFilter()) <END> .subscribe(onPingRequestSubscriber); onAskToPingRequestSubscriber = Subscribers.create(new OnAskToPingRequestAction()); transport.listen().observeOn(scheduler) .filter(PING_REQ_FILTER) .subscribe(onAskToPingRequestSubscriber); onTransitAckRequestSubscriber = Subscribers.create(new OnTransitAckRequestAction()); transport.listen().observeOn(scheduler) .filter(ACK_FILTER) .filter(ORIGINAL_ISSUER_FILTER) .subscribe(onTransitAckRequestSubscriber); int pingTime = config.getPingTime(); pingTask = executor.scheduleWithFixedDelay(new PingTask(), pingTime, pingTime, TimeUnit.MILLISECONDS); }</code><technical_language>I this targetFilter is useless overall. Algorithm send Ping you. basically filtering out this case valid</technical_language>

Target:
public void start() { onPingRequestSubscriber = Subscribers.create(new OnPingRequestAction()); transport.listen().observeOn(scheduler) .filter(PING_FILTER) .filter(targetFilter()) .subscribe(onPingRequestSubscriber); onAskToPingRequestSubscriber = Subscribers.create(new OnAskToPingRequestAction()); transport.listen().observeOn(scheduler) .filter(PING_REQ_FILTER) .subscribe(onAskToPingRequestSubscriber); onTransitAckRequestSubscriber = Subscribers.create(new OnTransitAckRequestAction()); transport.listen().observeOn(scheduler) .filter(ACK_FILTER) .filter(ORIGINAL_ISSUER_FILTER) .subscribe(onTransitAckRequestSubscriber); int pingTime = config.getPingTime(); pingTask = executor.scheduleWithFixedDelay(this::doPing, pingTime, pingTime, TimeUnit.MILLISECONDS); }
Source:
<code>public ContainerSpec(ContainerSpec other) { super(other.getId(), other.getContainerName(), other.getServerTemplateKey()); this.releasedId = other.releasedId; this.status = other.status; <START> this.configs = other.getConfigs().isEmpty() ? Collections.emptyMap() : new EnumMap<>(other.getConfigs()); <END> }</code><technical_language>Please change line 38 EnumMap<> for consistency</technical_language>

Target:
public ContainerSpec(ContainerSpec other) { super(other.getId(), other.getContainerName(), other.getServerTemplateKey()); this.releasedId = other.releasedId; this.status = other.status; this.configs = other.getConfigs().isEmpty() ? new EnumMap<>(Capability.class) : new EnumMap<>(other.getConfigs()); }
Source:
<code>private void waitForQueryToBeKilled(DistributedQueryRunner queryRunner) throws InterruptedException { boolean queryDone = false; while (!queryDone) { for (BasicQueryInfo info : queryRunner.getCoordinator().getQueryManager().getQueries()) { if (info.getState().isDone()) { assertNotNull(info.getErrorCode()); assertEquals(info.getErrorCode().getCode(), CLUSTER_OUT_OF_MEMORY.toErrorCode().getCode()); queryDone = true; <START> break; <END> } } MILLISECONDS.sleep(10); } }</code><technical_language>I return</technical_language>

Target:
private void waitForQueryToBeKilled(DistributedQueryRunner queryRunner) throws InterruptedException { while (true) { for (BasicQueryInfo info : queryRunner.getCoordinator().getQueryManager().getQueries()) { if (info.getState().isDone()) { assertNotNull(info.getErrorCode()); assertEquals(info.getErrorCode().getCode(), CLUSTER_OUT_OF_MEMORY.toErrorCode().getCode()); return; } } MILLISECONDS.sleep(10); } }
Source:
<code>public PageInfo evict() { PageId victim = mEvictor.evict(); if (victim == null) { return null; } <START> return mPageMap.get(victim); <END> }</code><technical_language>If this is null, do need do update evictor state</technical_language>

Target:
public PageInfo evict() { PageId victim = mEvictor.evict(); if (victim == null) { return null; } PageInfo victimInfo = mPageMap.get(victim); if (victimInfo == null) { LOG.error("Invalid result returned by evictor: page not available", victim); mEvictor.updateOnDelete(victim); return null; } return victimInfo; }
Source:
<code>public ActivityImpl parseReceiveTask(Element receiveTaskElement, ScopeImpl scope) { ActivityImpl activity = createActivityOnScope(receiveTaskElement, scope); activity.setActivityBehavior(new ReceiveTaskActivityBehavior()); parseAsynchronousContinuationForActivity(receiveTaskElement, activity); parseExecutionListenersOnScope(receiveTaskElement, activity); if (receiveTaskElement.attribute("messageRef") != null) { activity.setScope(true); activity.setEventScope(activity); <START> EventSubscriptionDeclaration declaration = parseMessageEventDefinition(receiveTaskElement, null); <END> declaration.setActivityId(activity.getActivityId()); declaration.setEventScopeActivityId(activity.getActivityId()); addEventSubscriptionDeclaration(declaration, activity, receiveTaskElement); } for (BpmnParseListener parseListener : parseListeners) { parseListener.parseReceiveTask(receiveTaskElement, scope, activity); } return activity; }</code><technical_language>pass receive task id here</technical_language>

Target:
public ActivityImpl parseReceiveTask(Element receiveTaskElement, ScopeImpl scope) { ActivityImpl activity = createActivityOnScope(receiveTaskElement, scope); activity.setActivityBehavior(new ReceiveTaskActivityBehavior()); parseAsynchronousContinuationForActivity(receiveTaskElement, activity); parseExecutionListenersOnScope(receiveTaskElement, activity); if (receiveTaskElement.attribute("messageRef") != null) { activity.setScope(true); activity.setEventScope(activity); EventSubscriptionDeclaration declaration = parseMessageEventDefinition(receiveTaskElement, activity.getId()); declaration.setActivityId(activity.getActivityId()); declaration.setEventScopeActivityId(activity.getActivityId()); addEventSubscriptionDeclaration(declaration, activity, receiveTaskElement); } for (BpmnParseListener parseListener : parseListeners) { parseListener.parseReceiveTask(receiveTaskElement, scope, activity); } return activity; }
Source:
<code><START> public DataRecord getRecord(DataIdentifier identifier) throws DataStoreException { <END> return null; }</code><technical_language>Need implement</technical_language>

Target:
public DataRecord getRecord(DataIdentifier identifier) throws DataStoreException { DataRecord result = getRecordIfStored(identifier); if (null == result) { throw new DataStoreException(String.format("No matching record for identifier %s", identifier.toString())); } return result; }
Source:
<code>public DataSet< V> intersect(DataSet< V> dataSet, String name, OperationContext context, boolean pushScope, String scopeDetail) { pushScopeIfNeeded(context, pushScope, scopeDetail); try { Dataset<Row> that = SpliceSpark.getSession() .createDataFrame( rdd.map( new LocatedRowToRowFunction()), context.getOperation() .getExecRowDefinition() .schema()); Dataset<Row> other = SpliceSpark.getSession() .createDataFrame( ((SparkDataSet)dataSet).rdd .map(new LocatedRowToRowFunction()), context.getOperation() .getExecRowDefinition() .schema()); <START> Dataset<Row> result = that.intersect(other); <END> return new SparkDataSet( result.javaRDD() .map(new RowToLocatedRowFunction(context))); } catch (Exception se){ throw new RuntimeException(se); }finally { if (pushScope) context.popScope(); } }</code><technical_language>dataset names left right instead of other</technical_language>

Target:
public DataSet< V> intersect(DataSet< V> dataSet, String name, OperationContext context, boolean pushScope, String scopeDetail) { pushScopeIfNeeded(context, pushScope, scopeDetail); try { Dataset<Row> left = SpliceSpark.getSession() .createDataFrame( rdd.map( new LocatedRowToRowFunction()), context.getOperation() .getExecRowDefinition() .schema()); Dataset<Row> right = SpliceSpark.getSession() .createDataFrame( ((SparkDataSet)dataSet).rdd .map(new LocatedRowToRowFunction()), context.getOperation() .getExecRowDefinition() .schema()); Dataset<Row> result = left.intersect(right); return toSpliceLocatedRow(result,context); } catch (Exception se){ throw new RuntimeException(se); }finally { if (pushScope) context.popScope(); } }
Source:
<code>public ChemComp getChemComp(String recordName) { String name = recordName.toUpperCase().trim(); try { <START> try(InputStream inStream = this.getClass().getResourceAsStream("/chemcomp/"+name + ".cif.gz")) { <END> logger.debug("Reading chemcomp/"+name+".cif.gz"); if ( inStream == null){ logger.debug("Getting empty chem comp for {}",name); ChemComp cc = ChemComp.getEmptyChemComp(); cc.setId(name); return cc; } MMcifParser parser = new SimpleMMcifParser(); ChemCompConsumer consumer = new ChemCompConsumer(); parser.addMMcifConsumer(consumer); parser.parse(new BufferedReader(new InputStreamReader(new GZIPInputStream(inStream)))); ChemicalComponentDictionary dict = consumer.getDictionary(); ChemComp chemComp = dict.getChemComp(name); return chemComp; } } catch (IOException e){ logger.error("IOException caught while reading chem comp {}.",name,e); } logger.warn("Problem when loading chem comp {}, will use an empty chem comp for it", name); ChemComp cc = ChemComp.getEmptyChemComp(); cc.setId(name); return cc; }</code><technical_language>try-with try? try is redundant, it</technical_language>

Target:
public ChemComp getChemComp(String recordName) { String name = recordName.toUpperCase().trim(); try(InputStream inStream = this.getClass().getResourceAsStream("/chemcomp/"+name + ".cif.gz")) { logger.debug("Reading chemcomp/"+name+".cif.gz"); if ( inStream == null){ logger.debug("Getting empty chem comp for {}",name); ChemComp cc = ChemComp.getEmptyChemComp(); cc.setId(name); return cc; } MMcifParser parser = new SimpleMMcifParser(); ChemCompConsumer consumer = new ChemCompConsumer(); parser.addMMcifConsumer(consumer); parser.parse(new BufferedReader(new InputStreamReader(new GZIPInputStream(inStream)))); ChemicalComponentDictionary dict = consumer.getDictionary(); ChemComp chemComp = dict.getChemComp(name); return chemComp; } catch (IOException e){ logger.error("IOException caught while reading chem comp {}.",name,e); } logger.warn("Problem when loading chem comp {}, will use an empty chem comp for it", name); ChemComp cc = ChemComp.getEmptyChemComp(); cc.setId(name); return cc; }
Source:
<code>private void registerAbnormalStopHandler() throws InfrastructureException { project .pods() .watch( (action, pod) -> { if (pod.getStatus() != null && "Failed".equals(pod.getStatus().getPhase())) { try { internalStop(emptyMap()); final String podName = pod.getMetadata().getName(); eventService.publish( DtoFactory.newDto(RuntimeStatusEvent.class) .withIdentity(DtoConverter.asDto(getContext().getIdentity())) .withStatus("STOPPED") <START> .withPrevStatus("RUNNING") <END> .withFailed(true) .withError(format("Pod '%s' was abnormally stopped", podName))); } catch (InfrastructureException ex) { LOG.error("OpenShift environment stop failed cause '{}'", ex.getMessage()); } } }); }</code><technical_language>move hard coded values constants</technical_language>

Target:
private void registerAbnormalStopHandler() throws InfrastructureException { project .pods() .watch( (action, pod) -> { if (pod.getStatus() != null && POD_FAILED_STATUS.equals(pod.getStatus().getPhase())) { try { internalStop(emptyMap()); } catch (InfrastructureException ex) { LOG.error("OpenShift environment stop failed cause '{}'", ex.getMessage()); } finally { sendRuntimeStoppedEvent( format("Pod '%s' was abnormally stopped", pod.getMetadata().getName())); } } }); }
Source:
<code>public static final HTInterval readFrom(ByteBuffer buffer) throws IOException { HTInterval interval; long intervalStart, intervalEnd; int attribute; TmfStateValue value; byte valueType; byte array[]; int posStart = buffer.position(); intervalStart = buffer.getLong(); <START> intervalEnd = buffer.getLong() + intervalStart; <END> attribute = buffer.getInt(); valueType = buffer.get(); switch (valueType) { case TYPE_NULL: value = TmfStateValue.nullValue(); break; case TYPE_INTEGER: value = TmfStateValue.newValueInt(buffer.getInt()); break; case TYPE_STRING: int valueSize = buffer.get(); array = new byte[valueSize]; buffer.get(array); value = TmfStateValue.newValueString(new String(array)); byte res = buffer.get(); if (res != 0) { throw new IOException(errMsg); } break; case TYPE_LONG: value = TmfStateValue.newValueLong(buffer.getLong()); break; case TYPE_DOUBLE: value = TmfStateValue.newValueDouble(buffer.getDouble()); break; default: throw new IOException(errMsg); } try { interval = new HTInterval(intervalStart, intervalEnd, attribute, value, buffer.position() - posStart); } catch (TimeRangeException e) { throw new IOException(errMsg); } return interval; }</code><technical_language>I do this separately, below. Tbh gain reading/writing 8 bytes</technical_language>

Target:
public static final HTInterval readFrom(ByteBuffer buffer) throws IOException { HTInterval interval; long intervalStart, intervalEnd; int attribute; TmfStateValue value; byte valueType; byte array[]; int posStart = buffer.position(); intervalStart = buffer.getLong(); intervalEnd = buffer.getLong(); attribute = buffer.getInt(); valueType = buffer.get(); switch (valueType) { case TYPE_NULL: value = TmfStateValue.nullValue(); break; case TYPE_INTEGER: value = TmfStateValue.newValueInt(buffer.getInt()); break; case TYPE_STRING: int valueSize = buffer.get(); array = new byte[valueSize]; buffer.get(array); value = TmfStateValue.newValueString(new String(array)); byte res = buffer.get(); if (res != 0) { throw new IOException(errMsg); } break; case TYPE_LONG: value = TmfStateValue.newValueLong(buffer.getLong()); break; case TYPE_DOUBLE: value = TmfStateValue.newValueDouble(buffer.getDouble()); break; default: throw new IOException(errMsg); } try { interval = new HTInterval(intervalStart, intervalEnd, attribute, value, buffer.position() - posStart); } catch (TimeRangeException e) { throw new IOException(errMsg); } return interval; }
Source:
<code>public Rule JsonObject() { return FirstOf( Sequence( ZeroOrMore( WhiteSpace() ).skipNode(), "{ ", FirstOf( Sequence( Pair(), ZeroOrMore( Sequence( ", ", Pair() ) ) ), Optional( Pair() ) ).suppressNode(), "} " ), <START> Sequence( ZeroOrMore( ANY ), builder.setInvalidJsonInPrefix( match() ), ACTION( false ) ) <END> ); }</code><technical_language>OK, I missed this change review. a good idea needs some more love. I plan be: * JsonObject is. this a clear meaning of is. * add a rule named JsonObjectParameter contains new stuff wraps JsonObject rule * rename invalidJsonInPrefix invalidJsonParameter (the property method)</technical_language>

Target:
public Rule JsonObject() { return Sequence( ZeroOrMore( WhiteSpace() ).skipNode(), "{ ", FirstOf( Sequence( Pair(), ZeroOrMore( Sequence( ", ", Pair() ) ) ), Optional( Pair() ) ).suppressNode(), "} " ); }
Source:
<code>public static void request(final String host, final int port, final FullHttpRequest request, final Consumer<FullHttpResponse> consumer, final Long timeoutSeconds) throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(1); EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); Channel channel = new Bootstrap() .group(eventLoopGroup) .channel(NioSocketChannel.class) .remoteAddress(host, port) .handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(final Channel ch) throws Exception { ch.pipeline() .addLast(new HttpClientCodec()) .addLast(new HttpObjectAggregator(1024 * 1024)) .addLast(new SimpleChannelInboundHandler<FullHttpResponse>() { @Override protected void channelRead0(final ChannelHandlerContext ctx, final FullHttpResponse httpResponse) throws Exception { try { consumer.accept(httpResponse); } finally { <START> countDownLatch.countDown(); <END> } } }); } }).connect() .sync().channel(); channel.writeAndFlush(request); countDownLatch.await(timeoutSeconds, TimeUnit.SECONDS); channel.close().sync(); }</code><technical_language>need CountDownLatch? I clone branch for deeply reviewing</technical_language>

Target:
public static void request(final String host, final int port, final FullHttpRequest request, final Consumer<FullHttpResponse> consumer, final Long timeoutSeconds) { CountDownLatch countDownLatch = new CountDownLatch(1); EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); Channel channel = new Bootstrap() .group(eventLoopGroup) .channel(NioSocketChannel.class) .remoteAddress(host, port) .handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(final Channel ch) throws Exception { ch.pipeline() .addLast(new HttpClientCodec()) .addLast(new HttpObjectAggregator(1024 * 1024)) .addLast(new SimpleChannelInboundHandler<FullHttpResponse>() { @Override protected void channelRead0(final ChannelHandlerContext ctx, final FullHttpResponse httpResponse) throws Exception { try { consumer.accept(httpResponse); } finally { countDownLatch.countDown(); } } }); } }).connect() .sync().channel(); channel.writeAndFlush(request); countDownLatch.await(timeoutSeconds, TimeUnit.SECONDS); channel.close().sync(); }
Source:
<code>public void handlePut() { if (resource.getType() == Type.DIRECTORY) { throw new RestletException("Attempting to write data to a directory.", Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } else { try { boolean isNew = resource.getType() == Type.UNDEFINED; <START> if (operation == Operation.COPY || operation == Operation.MOVE) { <END> try (InputStream is = getRequest().getEntity().getStream()) { Resource source = store.get(IOUtils.toString(is, "UTF-8")); if (source.getType() == Type.UNDEFINED) { throw new RestletException("Undefined source path.", Status.CLIENT_ERROR_NOT_FOUND); } try { if (operation == Operation.MOVE) { if (!source.renameTo(resource)) { throw new RestletException("Rename operation failed.", Status.SERVER_ERROR_INTERNAL); } } else { if (source.getType() == Type.DIRECTORY) { throw new RestletException("Cannot copy directory.", Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } IOUtils.copyStream(source.in(), resource.out(), true, true); } } catch (IllegalStateException e) { throw new RestletException("I/O Error", Status.SERVER_ERROR_INTERNAL, e); } } } else { IOUtils.copyStream(getRequest().getEntity().getStream(), resource.out(), true, true); } if (isNew) { getResponse().setStatus(Status.SUCCESS_CREATED); } } catch (IOException e) { throw new RestletException("I/O Error", Status.SERVER_ERROR_INTERNAL, e); } } }</code><technical_language>@NielsCharlier, is loads of trailing whitespace in this file. Adding a new file is a great opportunity Eclipse formatter</technical_language>

Target:
public void handlePut() { if (resource.getType() == Type.DIRECTORY) { throw new RestletException("Attempting to write data to a directory.", Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } else { try { boolean isNew = resource.getType() == Type.UNDEFINED; if (operation == Operation.COPY || operation == Operation.MOVE) { try (InputStream is = getRequest().getEntity().getStream()) { Resource source = store.get(IOUtils.toString(is)); if (source.getType() == Type.UNDEFINED) { throw new RestletException("Undefined source path.", Status.CLIENT_ERROR_NOT_FOUND); } try { if (operation == Operation.MOVE) { if (!source.renameTo(resource)) { throw new RestletException("Rename operation failed.", Status.SERVER_ERROR_INTERNAL); } } else { if (source.getType() == Type.DIRECTORY) { throw new RestletException("Cannot copy directory.", Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } IOUtils.copyStream(source.in(), resource.out(), true, true); } } catch (IllegalStateException e) { throw new RestletException("I/O Error", Status.SERVER_ERROR_INTERNAL, e); } } } else { IOUtils.copyStream(getRequest().getEntity().getStream(), resource.out(), true, true); } if (isNew) { getResponse().setStatus(Status.SUCCESS_CREATED); } } catch (IOException e) { throw new RestletException("I/O Error", Status.SERVER_ERROR_INTERNAL, e); } } }
Source:
<code>private SharingPhysicalSlotRequestBulk createBulk(Map<ExecutionSlotSharingGroup, List<ExecutionVertexID>> executions) { Map<ExecutionSlotSharingGroup, ResourceProfile> pendingRequests = executions .keySet() .stream() .collect(Collectors.toMap( group -> group, group -> sharedSlots.get(group).getPhysicalSlotResourceProfile() )); Map<ExecutionSlotSharingGroup, AllocationID> fulfilledRequests = new HashMap<>(); SharingPhysicalSlotRequestBulk bulk = new SharingPhysicalSlotRequestBulk( executions, pendingRequests, fulfilledRequests, (executionVertexId, cause) -> { ExecutionSlotSharingGroup group = slotSharingStrategy.getExecutionSlotSharingGroup(executionVertexId); <START> sharedSlots.get(group).cancelLogicalSlotRequest(executionVertexId, cause); <END> }); registerPhysicalSlotRequestBulkCallbacks(executions.keySet(), bulk); return bulk; }</code><technical_language>I suggest add a check state sharedSlots.get(group) contains item</technical_language>

Target:
private SharingPhysicalSlotRequestBulk createBulk(Map<ExecutionSlotSharingGroup, List<ExecutionVertexID>> executions) { Map<ExecutionSlotSharingGroup, ResourceProfile> pendingRequests = executions .keySet() .stream() .collect(Collectors.toMap( group -> group, group -> sharedSlots.get(group).getPhysicalSlotResourceProfile() )); SharingPhysicalSlotRequestBulk bulk = new SharingPhysicalSlotRequestBulk( executions, pendingRequests, this::cancelLogicalSlotRequest); registerPhysicalSlotRequestBulkCallbacks(executions.keySet(), bulk); return bulk; }
Source:
<code>private List<Partition> getPartitions(String databaseName, String tableName, String expression) { try { List<Partition> partitions = new ArrayList<>(); String nextToken = null; do { GetPartitionsResult result = glueClient.getPartitions(new GetPartitionsRequest() .withDatabaseName(databaseName) .withTableName(tableName) .withExpression(expression) .withNextToken(nextToken)); result.getPartitions().stream() .forEach(p -> partitions.add(GlueToPrestoConverter.convertPartition(p))); nextToken = result.getNextToken(); } while (nextToken != null); return partitions; } catch (AmazonServiceException e) { <START> throw new PrestoException(HIVE_METASTORE_ERROR, e); <END> } }</code><technical_language>getPartitionNamesByParts() is supposed a fast list partition names is query planning. fetch full partition metadata in a pipelined manner query executes. Fetching partition metadata slow expensive (especially traditional Hive metastore). if metastore is fast, tables millions of partitions. (Though Glue limits 20k partitions table. nice.) appears Glue API fetch names, this do. downside is fetch partition metadata twice, caching. (HiveMetadataFactory CachingHiveMetastore.memoizeMetastore() creates SemiTransactionalHiveMetastore, full partition objects discarded this method.)</technical_language>

Target:
private List<Partition> getPartitions(String databaseName, String tableName, String expression) { try { List<Partition> partitions = new ArrayList<>(); String nextToken = null; do { GetPartitionsResult result = glueClient.getPartitions(new GetPartitionsRequest() .withDatabaseName(databaseName) .withTableName(tableName) .withExpression(expression) .withNextToken(nextToken)); result.getPartitions().stream() .forEach(partition -> partitions.add(GlueToPrestoConverter.convertPartition(partition))); nextToken = result.getNextToken(); } while (nextToken != null); return partitions; } catch (AmazonServiceException e) { throw new PrestoException(HIVE_METASTORE_ERROR, e); } }
Source:
<code>public void retry() { synchronized (workerThread) { final Map<K, PullRequest> pendingPullRequests = workerThread.pendingPullRequests; final PullRequest pullRequest = pendingPullRequests.get(encodedKey.getKey()); if (checkPullRequest(pullRequest, requestId)) { final int retryCount = pullRequest.getAndIncrementRetryCount(); if (retryCount >= MAX_PULL_RETRY_COUNT) { throw new RuntimeException("Fail to load a value for pull"); } LOG.log(Level.WARNING, "Retry pull request for key {0}. This is {1}-th retry", new Object[]{encodedKey.getKey(), retryCount + 1}); sendPullMsg(encodedKey, requestId); } else { <START> LOG.log(Level.INFO, "Could not find corresponding pullRequest for key: {0}, requestId: {1}", <END> new Object[]{encodedKey.getKey(), requestId}); } } }</code><technical_language>WARNING.</technical_language>

Target:
public void retry() { synchronized (workerThread) { final Map<K, PullRequest> pendingPullRequests = workerThread.pendingPullRequests; final PullRequest pullRequest = pendingPullRequests.get(encodedKey.getKey()); if (pendingPullRequestExists(pullRequest, requestId)) { pullRequest.processRetry(); } else { LOG.log(Level.INFO, "Could not find corresponding pullRequest for key: {0}, requestId: {1}", new Object[]{encodedKey.getKey(), requestId}); } } }
Source:
<code>private static void populateSchemaFields(Schema schema, Set<BoundField> fields) { for (BoundField field: schema.fields()) { fields.add(field); <START> if (field.def.type.arrayElementType().isPresent()) { <END> Type innerType = field.def.type.arrayElementType().get(); if (innerType instanceof Schema) populateSchemaFields((Schema) innerType, fields); } else if (field.def.type instanceof Schema) populateSchemaFields((Schema) field.def.type, fields); } }</code><technical_language>nit: field.def.type.isArray() some of other patterns</technical_language>

Target:
private static void populateSchemaFields(Schema schema, Set<BoundField> fields) { for (BoundField field: schema.fields()) { fields.add(field); if (field.def.type.isArray()) { Type innerType = field.def.type.arrayElementType().get(); if (innerType instanceof Schema) populateSchemaFields((Schema) innerType, fields); } else if (field.def.type instanceof Schema) populateSchemaFields((Schema) field.def.type, fields); } }
Source:
<code>private void checkIdent(DetailAST ast) { final Deque<String> currentVariables = getCurrentVariables(); <START> if (currentVariables != null && !getCurrentVariables().isEmpty()) { <END> final DetailAST identAST = ast.getFirstChild(); if (identAST != null && identAST.getType() == TokenTypes.IDENT && getCurrentVariables().contains(identAST.getText())) { log(ast.getLineNo(), ast.getColumnNo(), MSG_KEY, identAST.getText()); } } }</code><technical_language>getCurrentVariables() => currentVariables</technical_language>

Target:
private void checkIdent(DetailAST ast) { if (!getCurrentVariables().isEmpty()) { final DetailAST identAST = ast.getFirstChild(); if (identAST != null && identAST.getType() == TokenTypes.IDENT && getCurrentVariables().contains(identAST.getText())) { log(ast.getLineNo(), ast.getColumnNo(), MSG_KEY, identAST.getText()); } } }
Source:
<code>public void setPassword(String password) { Preconditions.checkArgument(!Strings.isNullOrEmpty(password)); synchronized(random) { <START> this.salt = SHA512(new BigInteger(130, random).toString(32)); <END> } this.password = SHA512(SHA512(password).concat(this.salt)); }</code><technical_language>If want store user passwords (which a fan of) for [BCrypt](<LINK_0> instead. SHA MD5 algorithms designed for speed allowing attackers brute-force passwords. BCrypt algorithm is designed slow, instructed slow further, if required. find BCrypt in this dependency: xml <dependency> <groupId>org.mindrot</groupId> <artifactId>jbcrypt</artifactId> <version>0.3m</version> </dependency></technical_language>

Target:
public void setPassword(String password) { Preconditions.checkArgument(!Strings.isNullOrEmpty(password)); this.password = BCrypt.hashpw(password, BCrypt.gensalt()); }
Source:
<code>public void handleSuccess(List<Media> collection) { presenter.addItemsToQueryList(collection); if (gridAdapter == null) { setAdapter(collection); } else { if (gridAdapter.containsAll(collection)) { return; } gridAdapter.addItems(collection); try { ((WikidataItemDetailsActivity) getContext()).viewPagerNotifyDataSetChanged(); } catch (Exception e) { e.printStackTrace(); } } progressBar.setVisibility(GONE); isLoading = false; statusTextView.setVisibility(GONE); for (Media m : collection) { <START> presenter.replaceTitlesWithCaptions("M"+m.getPageId(), mediaSize++); <END> } }</code><technical_language>prefix M is places. extracted out a constant</technical_language>

Target:
public void handleSuccess(List<Media> collection) { presenter.addItemsToQueryList(collection); if (gridAdapter == null) { setAdapter(collection); } else { if (gridAdapter.containsAll(collection)) { return; } gridAdapter.addItems(collection); try { ((WikidataItemDetailsActivity) getContext()).viewPagerNotifyDataSetChanged(); } catch (RuntimeException e) { Timber.e(e); } } progressBar.setVisibility(GONE); isLoading = false; statusTextView.setVisibility(GONE); for (Media media : collection) { final String pageId = media.getPageId(); if (pageId != null) { presenter.replaceTitlesWithCaptions(PAGE_ID_PREFIX + pageId, mediaSize++); } } }
Source:
<code>public void addMember(PerunSession sess, Group group, Member member) throws InternalErrorException, MemberNotExistsException, PrivilegeException, AlreadyMemberException, GroupNotExistsException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException, AttributeNotExistsException, ExternallyManagedException { Utils.checkPerunSession(sess); getGroupsManagerBl().checkGroupExists(sess, group); getPerunBl().getMembersManagerBl().checkMemberExists(sess, member); if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, group) && !AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, group)) { throw new PrivilegeException(sess, "addMember"); } if (member.getVoId() != (group.getVoId())) { throw new MembershipMismatchException("Member and group are form the different VO"); } Attribute attrSynchronizeEnabled = getPerunBl().getAttributesManagerBl().getAttribute(sess, group, GROUPSYNCHROENABLED_ATTRNAME); <START> if (Objects.equals("true", (String) attrSynchronizeEnabled.getValue()) || getGroupsManagerBl().isGroupInStructureSynchronizationTree(sess, group)) { <END> throw new ExternallyManagedException("Adding of member is not allowed. Group is externally managed."); } getGroupsManagerBl().addMember(sess, group, member); }</code><technical_language>suggestion if ("true".equals(attrSynchronizeEnabled.getValue()) || getGroupsManagerBl().isGroupInStructureSynchronizationTree(sess, group)) {</technical_language>

Target:
public void addMember(PerunSession sess, Group group, Member member) throws InternalErrorException, MemberNotExistsException, PrivilegeException, AlreadyMemberException, GroupNotExistsException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException, AttributeNotExistsException, ExternallyManagedException { Utils.checkPerunSession(sess); getGroupsManagerBl().checkGroupExists(sess, group); getPerunBl().getMembersManagerBl().checkMemberExists(sess, member); if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, group) && !AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, group)) { throw new PrivilegeException(sess, "addMember"); } if (member.getVoId() != (group.getVoId())) { throw new MembershipMismatchException("Member and group are form the different VO"); } Attribute attrSynchronizeEnabled = getPerunBl().getAttributesManagerBl().getAttribute(sess, group, GROUPSYNCHROENABLED_ATTRNAME); if ("true".equals(attrSynchronizeEnabled.getValue()) || getGroupsManagerBl().isGroupInStructureSynchronizationTree(sess, group)) { throw new ExternallyManagedException("Adding of member is not allowed. Group is externally managed."); } getGroupsManagerBl().addMember(sess, group, member); }
Source:
<code>public void testEvaluateRightFunc() throws Exception { Literal<Object> value = Literal.of(DataTypes.STRING, "crate.io"); assertEvaluate("right(name, 10)", null, Literal.of((String) null)); assertEvaluate("right(name, null)", null, value); assertEvaluate("right(name, 0)", "", value); assertEvaluate("right(name, 100)", "", Literal.of("")); assertEvaluate("right('crate.io', 2)","io", value); <START> assertEvaluate("right('crate.io', -6)","io", value); <END> }</code><technical_language>a string literal instead of column name intend</technical_language>

Target:
public void testEvaluateRightFunc() throws Exception { Literal<Object> value = Literal.of(DataTypes.STRING, "crate.io"); assertEvaluate("right(name, 10)", null, Literal.of((String) null)); assertEvaluate("right(name, null)", null, value); assertEvaluate("right(name, 0)", "", value); assertEvaluate("right(name, 100)", "", Literal.of("")); assertEvaluate("right(name, 2)","io", value); assertEvaluate("right(name, -6)","io", value); assertEvaluate("right('crate.io', age)","io", Literal.of(2)); assertEvaluate("right('crate.io', age)","io", Literal.of(-6)); }
Source:
<code>public void testSeekStatistics() throws IOException { describe("Testing the values of statistics from seek operations in " + "AbfsInputStream"); AzureBlobFileSystem fs = getFileSystem(); AzureBlobFileSystemStore abfss = fs.getAbfsStore(); Path seekStatPath = path(getMethodName()); AbfsOutputStream out = null; AbfsInputStream in = null; try { out = createAbfsOutputStreamWithFlushEnabled(fs, seekStatPath); out.write(defBuffer); out.hflush(); in = abfss.openFileForRead(seekStatPath, fs.getFsStatistics()); int result = in.read(defBuffer, 0, ONE_MB); LOG.info("Result of read : {}", result); for (int i = 0; i < OPERATIONS; i++) { in.seek(0); in.seek(ONE_MB); } AbfsInputStreamStatisticsImpl stats = (AbfsInputStreamStatisticsImpl) in.getStreamStatistics(); assertEquals("Mismatch in seekOps value", 2 * OPERATIONS, stats.getSeekOperations()); assertEquals("Mismatch in backwardSeekOps value", OPERATIONS, stats.getBackwardSeekOperations()); assertEquals("Mismatch in forwardSeekOps value", OPERATIONS, stats.getForwardSeekOperations()); assertEquals("Mismatch in bytesBackwardsOnSeek value", -1 * OPERATIONS * ONE_MB, stats.getBytesBackwardsOnSeek()); assertEquals("Mismatch in bytesSkippedOnSeek value", 0, stats.getBytesSkippedOnSeek()); assertEquals("Mismatch in seekInBuffer value", 2 * OPERATIONS, stats.getSeekInBuffer()); <START> <END> } finally { IOUtils.cleanupWithLogger(LOG, out, in); } }</code><technical_language>1. close() stream ask for stats again, verify readable 2. call toString opened closed streams</technical_language>

Target:
public void testSeekStatistics() throws IOException { describe("Testing the values of statistics from seek operations in " + "AbfsInputStream"); AzureBlobFileSystem fs = getFileSystem(); AzureBlobFileSystemStore abfss = fs.getAbfsStore(); Path seekStatPath = path(getMethodName()); AbfsOutputStream out = null; AbfsInputStream in = null; try { out = createAbfsOutputStreamWithFlushEnabled(fs, seekStatPath); out.write(defBuffer); out.hflush(); in = abfss.openFileForRead(seekStatPath, fs.getFsStatistics()); int result = in.read(defBuffer, 0, ONE_MB); LOG.info("Result of read : {}", result); for (int i = 0; i < OPERATIONS; i++) { in.seek(0); in.seek(ONE_MB); } AbfsInputStreamStatisticsImpl stats = (AbfsInputStreamStatisticsImpl) in.getStreamStatistics(); LOG.info("STATISTICS: {}", stats.toString()); assertEquals("Mismatch in seekOps value", 2 * OPERATIONS, stats.getSeekOperations()); assertEquals("Mismatch in backwardSeekOps value", OPERATIONS, stats.getBackwardSeekOperations()); assertEquals("Mismatch in forwardSeekOps value", OPERATIONS, stats.getForwardSeekOperations()); assertEquals("Mismatch in bytesBackwardsOnSeek value", -1 * OPERATIONS * ONE_MB, stats.getBytesBackwardsOnSeek()); assertEquals("Mismatch in bytesSkippedOnSeek value", 0, stats.getBytesSkippedOnSeek()); assertEquals("Mismatch in seekInBuffer value", 2 * OPERATIONS, stats.getSeekInBuffer()); in.close(); LOG.info("STATISTICS after closing: {}", stats.toString()); } finally { IOUtils.cleanupWithLogger(LOG, out, in); } }
Source:
<code>public void testNoAuthentication() { <START> assertNull(this.action.createCredentials(requestContext, getCredentials(), "usrPsw")); <END> }</code><technical_language>This return null, wrap assertNull</technical_language>

Target:
public void testNoAuthentication() { this.action.createCredentials(requestContext, getCredentials(), "usrPsw"); }
Source:
<code>public Long getId() { <START> return base + counter.getAndIncrement(); <END> }</code><technical_language>Oh, I missed thing. getId() throw IdGenerationException if counter exceeds range of integer(2^32)? Creating more 2^32 ids conflicts ids created other IdFactory</technical_language>

Target:
public Long getId() throws IdGenerationException { if (counter.get() == 0x100000000L) { throw new IdGenerationException("No more id available"); } return base + counter.getAndIncrement(); }
Source:
<code><START> public Sha256Hash hashForSignature( <END> int inputIndex, Script redeemScript, SigHash type, boolean anyoneCanPay) { return hashForSignature(inputIndex, redeemScript.getProgram(), type, anyoneCanPay); }</code><technical_language>Please reformat this method signature (and 5 above)</technical_language>

Target:
public Sha256Hash hashForSignature(int inputIndex, Script redeemScript, SigHash type, boolean anyoneCanPay) { int sigHash = TransactionSignature.calcSigHashValue(type, anyoneCanPay); return hashForSignature(inputIndex, redeemScript.getProgram(), (byte) sigHash); }
Source:
<code>public void handleGetSpecificAttributeValueResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType deviceResult, final OsgpException exception, final String resultData) { LOGGER.debug("handleGetSpecificAttributeValueResponse for MessageType: {}", deviceMessageMetadata.getMessageType()); ResponseMessageResultType result = deviceResult; if (exception != null) { LOGGER.error(DEVICE_RESPONSE_NOT_OK_UNEXPECTED_EXCEPTION, exception); result = ResponseMessageResultType.NOT_OK; } <START> this.webServiceResponseMessageSender.send( <END> ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception).withDataObject(resultData) .withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(), deviceMessageMetadata.getMessageType()); }</code><technical_language>Extract building of ResponseMessage variable (in eclipse, select text, right-click > refactor > extract local variable / select code + shift+alt+L). This code a bit more readable, especially passing in other besides ResponseMessage</technical_language>

Target:
public void handleGetSpecificAttributeValueResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType deviceResult, final OsgpException exception, final String resultData) { LOGGER.debug("handleGetSpecificAttributeValueResponse for MessageType: {}", deviceMessageMetadata.getMessageType()); ResponseMessageResultType result = deviceResult; if (exception != null) { LOGGER.error(DEVICE_RESPONSE_NOT_OK_UNEXPECTED_EXCEPTION, exception); result = ResponseMessageResultType.NOT_OK; } ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception).withDataObject(resultData) .withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(); this.webServiceResponseMessageSender.send( responseMessage, deviceMessageMetadata.getMessageType()); }
Source:
<code><START> public Set<String> getPluginsThatSupportsWebBasedAuthentication() { <END> return getPluginsThatSupports(SupportedAuthType.Web); }</code><technical_language>I thought it, getPluginsThatSupports returned a Set<String>, I left it. this changed</technical_language>

Target:
public Set<AuthorizationPluginInfo> getPluginsThatSupportsWebBasedAuthentication() { return getPluginsThatSupports(SupportedAuthType.Web); }
Source:
<code>public int getWeight(EStructuralFeature feature) { if (irrelevant(feature)) { return 0; } Integer found = weights.get(feature); if (found == null) { found = Integer.valueOf(SMALL); if ("name".equals(feature.getName()) || "id".equals(feature.getName())) { found = Integer.valueOf(SIGNIFICANT); } <START> if (feature instanceof EReference && ((EReference)feature).isContainment()) { <END> found = Integer.valueOf(NORMAL); } if (feature instanceof EReference) { found = Integer.valueOf(referenceChangeCoef * found.intValue()); } else { found = Integer.valueOf(attributeChangeCoef * found.intValue()); } weights.put(feature, found); } return found.intValue(); }</code><technical_language>this happen a containment reference is stated irrelevant that</technical_language>

Target:
public int getWeight(EStructuralFeature feature) { if (irrelevant(feature)) { return 0; } Integer found = weights.get(feature); if (found == null) { found = Integer.valueOf(SMALL); if ("name".equals(feature.getName()) || "id".equals(feature.getName())) { found = Integer.valueOf(SIGNIFICANT); } if (feature instanceof EReference) { found = Integer.valueOf(referenceChangeCoef * found.intValue()); } else { found = Integer.valueOf(attributeChangeCoef * found.intValue()); } weights.put(feature, found); } return found.intValue(); }
Source:
<code><START> public void testWithoutCustomPrefix() { <END> mockPrefix(null); ninjaGraphite.start(); Mockito.verify(builder, Mockito.times(1)).prefixedWith(TEST_HOSTNAME); }</code><technical_language>Nice testcase! done :)</technical_language>

Target:
public void testWithoutCustomPrefix() { Mockito.when(ninjaProperties.get(Mockito.eq("metrics.graphite.prefix"))).thenReturn(null); ninjaGraphite.start(); Mockito.verify(builder, Mockito.times(1)).prefixedWith(TEST_HOSTNAME); }
Source:
<code>public void addReply(String reply){ waitForElementByElement(replyCommentButton); String url = driver.getCurrentUrl(); <START> executeScript("document.querySelectorAll('.cmnRpl')[0].click()"); <END> verifyURL(url + modal); replyInputArea.sendKeys(reply); replyInputArea.submit(); verifyURL(url + modal); verifyAddedReplyOnCommentPage(reply); PageObjectLogging.log("addReply", "reply "+reply+" added", true, driver); }</code><technical_language>jQueryClick BasePageObject</technical_language>

Target:
public void addReply(String reply){ waitForElementByElement(replyCommentButton); String url = driver.getCurrentUrl(); replyCommentButton.click(); verifyURL(url + modal); replyInputArea.sendKeys(reply); replyInputArea.submit(); verifyURL(url + modal); verifyAddedReplyOnCommentPage(reply); PageObjectLogging.log("addReply", "reply "+reply+" added", true, driver); }
Source:
<code>public void clear() { checkForParentModification(); final List<IonValue> toRemove = new ArrayList<IonValue>(size); for(int i = 0; i < size; i++) { <START> toRemove.add(get(i)); <END> } parent.removeAll(toRemove); size = 0; this.structuralModificationCount = IonSequenceLite.this.structuralModificationCount; }</code><technical_language>simpler call remove(i)? build toRemove first..</technical_language>

Target:
public void clear() { checkForParentModification(); int parentIndex = toParentIndex(0); for (int i = 0; i < size; i++) { IonSequenceLite.this.remove(parentIndex); } size = 0; this.structuralModificationCount = IonSequenceLite.this.structuralModificationCount; }
Source:
<code><START> public Config(Map<String, String> properties) { <END> this.properties.putAll(properties); }</code><technical_language>more method file location of properties good</technical_language>

Target:
public Config(Map<String, String> properties) { super(properties); }
Source:
<code>private static boolean isExistingDomain(String domain, int tenantId, Connection connection) throws UserStoreException { Connection dbConnection = null; PreparedStatement prepStmt = null; ResultSet rs = null; boolean isExisting = false; try { <START> dbConnection = connection; <END> prepStmt = dbConnection.prepareStatement(JDBCRealmConstants.IS_DOMAIN_EXISTING_SQL); if (domain != null) { domain = domain.toUpperCase(); } prepStmt.setString(1, domain); prepStmt.setInt(2, tenantId); rs = prepStmt.executeQuery(); if (rs.next()) { isExisting = true; } return isExisting; } catch (SQLException e) { String errorMessage = "DB error occurred while checking is existing domain : " + domain + " & tenant id : " + tenantId; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } }</code><technical_language>I usage of dbConnection variable</technical_language>

Target:
private static boolean isExistingDomain(String domain, int tenantId, Connection connection) throws UserStoreException { PreparedStatement prepStmt = null; ResultSet rs = null; boolean isExisting = false; try { prepStmt = connection.prepareStatement(JDBCRealmConstants.IS_DOMAIN_EXISTING_SQL); if (domain != null) { domain = domain.toUpperCase(); } prepStmt.setString(1, domain); prepStmt.setInt(2, tenantId); rs = prepStmt.executeQuery(); if (rs.next()) { isExisting = true; } return isExisting; } catch (SQLException e) { String errorMessage = "DB error occurred while checking is existing domain : " + domain + " & tenant id : " + tenantId; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { DatabaseUtil.closeAllConnections( null, rs, prepStmt ); } }