auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void main(String[] args) { WriteDataOptions options = PipelineOptionsFactory.fromArgs(args).withValidation().as(WriteDataOptions.class); Pipeline p = Pipeline.create(options); CloudBigtableTableConfiguration bigtableTableConfig = new CloudBigtableTableConfiguration.Builder() .withProjectId(options.getBigtableProjectId()) .withInstanceId(options.getBigtableInstanceId()) .withTableId(options.getBigtableTableId()) .build(); long rowSize = options.getMegabytesPerRow() * ONE_MB; final long max = (Math.round((options.getGigabytesWritten() * ONE_GB)) / rowSize); p.apply(GenerateSequence.from(0).to(max)) .apply( ParDo.of( new DoFn<Long, Mutation>() { @ProcessElement public void processElement(@Element Long rowkey, OutputReceiver<Mutation> out) { int maxLength = ("" + max).length(); String paddedRowkey = String.format("%0" + maxLength + "d", rowkey); String reversedRowkey = new StringBuilder(paddedRowkey).reverse().toString(); Put row = new Put(Bytes.toBytes(reversedRowkey)); byte[] b = new byte[(int) rowSize]; new Random().nextBytes(b); long timestamp = System.currentTimeMillis(); row.addColumn(Bytes.toBytes(COLUMN_FAMILY), Bytes.toBytes("C"), timestamp, b); out.output(row); } })) .apply(CloudBigtableIO.writeToTable(bigtableTableConfig)); p.run().waitUntilFinish(); }

Target:
public static void main(String[] args) { WriteDataOptions options = PipelineOptionsFactory.fromArgs(args).withValidation().as(WriteDataOptions.class); Pipeline p = Pipeline.create(options); CloudBigtableTableConfiguration bigtableTableConfig = new CloudBigtableTableConfiguration.Builder() .withProjectId(options.getBigtableProjectId()) .withInstanceId(options.getBigtableInstanceId()) .withTableId(options.getBigtableTableId()) .build(); long rowSize = options.getMegabytesPerRow() * ONE_MB; final long max = (Math.round((options.getGigabytesWritten() * ONE_GB)) / rowSize); int maxLength = ("" + max).length(); String numberFormat = "%0" + maxLength + "d"; p.apply(GenerateSequence.from(0).to(max)) .apply( ParDo.of( new DoFn<Long, Mutation>() { @ProcessElement public void processElement(@Element Long rowkey, OutputReceiver<Mutation> out) { String paddedRowkey = String.format(numberFormat, rowkey); String reversedRowkey = new StringBuilder(paddedRowkey).reverse().toString(); Put row = new Put(Bytes.toBytes(reversedRowkey)); byte[] b = new byte[(int) rowSize]; new Random().nextBytes(b); long timestamp = System.currentTimeMillis(); row.addColumn(Bytes.toBytes(COLUMN_FAMILY), Bytes.toBytes("C"), timestamp, b); out.output(row); } })) .apply(CloudBigtableIO.writeToTable(bigtableTableConfig)); p.run().waitUntilFinish(); }
Source:
private Span getSpan(Context context) { final Optional<Object> spanOptional = context.getData(PARENT_SPAN_KEY); if (!spanOptional.isPresent()) { logger.warning("Failed to find span in the context."); return null; } final Object value = spanOptional.get(); if (!(value instanceof Span)) { logger.warning("Could not extract span. Data in is not of type Span. Actual class: {}", PARENT_SPAN_KEY, value.getClass()); return null; } return (Span) value; }

Target:
private Span getSpan(Context context) { final Object value = getOptionalObject(context, PARENT_SPAN_KEY); if (!(value instanceof Span)) { logger.warning("Could not extract span. Data in context for key is not of type Span.", PARENT_SPAN_KEY); return null; } return (Span) value; }
Source:
JSONArray getPlatformPluginList() { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); JSONArray initialPluginList = null; updateSiteList: for (UpdateSite updateSite : Jenkins.getInstance().getUpdateCenter().getSiteList()) { String updateCenterJsonUrl = updateSite.getUrl(); String suggestedPluginUrl = updateCenterJsonUrl.replace("/update-center.json", "/platform-plugins.json"); try { URLConnection connection; try { connection = ProxyConfiguration.openAllowsRedirection(new URL(suggestedPluginUrl)); String initialPluginJson = IOUtils.toString(connection.getInputStream(), "utf-8"); initialPluginList = JSONArray.fromObject(initialPluginJson); break updateSiteList; } catch(IOException e) { throw new IOException("Invalid response code from URL: " + suggestedPluginUrl); } catch(Exception e) { LOGGER.log(Level.FINE, e.getMessage(), e); continue updateSiteList; } } catch(Exception e) { LOGGER.log(Level.FINE, e.getMessage(), e); } } if (initialPluginList == null) { try { ClassLoader cl = getClass().getClassLoader(); URL localPluginData = cl.getResource("jenkins/install/platform-plugins.json"); String initialPluginJson = IOUtils.toString(localPluginData.openStream(), "utf-8"); initialPluginList = JSONArray.fromObject(initialPluginJson); } catch (Exception e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } return initialPluginList; }

Target:
JSONArray getPlatformPluginList() { Jenkins.get().checkPermission(Jenkins.ADMINISTER); JSONArray initialPluginList = null; updateSiteList: for (UpdateSite updateSite : Jenkins.get().getUpdateCenter().getSiteList()) { String updateCenterJsonUrl = updateSite.getUrl(); String suggestedPluginUrl = updateCenterJsonUrl.replace("/update-center.json", "/platform-plugins.json"); try { URLConnection connection; try { connection = ProxyConfiguration.openURLAllowingCrossProtocolRedirects(new URL(suggestedPluginUrl)); String initialPluginJson = IOUtils.toString(connection.getInputStream(), "utf-8"); initialPluginList = JSONArray.fromObject(initialPluginJson); break updateSiteList; } catch(IOException e) { throw new IOException("Invalid response code from URL: " + suggestedPluginUrl, e); } catch(Exception e) { LOGGER.log(Level.FINE, e.getMessage(), e); continue updateSiteList; } } catch(Exception e) { LOGGER.log(Level.FINE, e.getMessage(), e); } } if (initialPluginList == null) { try { ClassLoader cl = getClass().getClassLoader(); URL localPluginData = cl.getResource("jenkins/install/platform-plugins.json"); String initialPluginJson = IOUtils.toString(localPluginData.openStream(), "utf-8"); initialPluginList = JSONArray.fromObject(initialPluginJson); } catch (Exception e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } return initialPluginList; }
Source:
public SMSMessage(String phoneNumber, String data) { if (phoneNumber == null) throw new NullPointerException("Phone number cannot be null."); if (data == null) throw new NullPointerException("Data cannot be null."); this.phoneNumber = phoneNumber; this.data = data; }

Target:
public SMSMessage(String phoneNumber, String data) { if (phoneNumber == null) throw new NullPointerException("Phone number cannot be null."); if (data == null) throw new NullPointerException("Data cannot be null."); if (!Pattern.matches(PHONE_NUMBER_PATTERN, phoneNumber)) throw new IllegalArgumentException("Invalid phone number."); this.phoneNumber = phoneNumber; this.data = data; }
Source:
public void testInvoicingSubscription() throws StripeException { Plan plan = Plan.create(getUniquePlanParams()); defaultCustomerParams.put("email", "test@stripe.com"); Customer customer = Customer.create(defaultCustomerParams); Map<String, Object> subscriptionParams = new HashMap<String, Object>(); subscriptionParams.put("plan", plan.getId()); subscriptionParams.put("billing", "send_invoice"); subscriptionParams.put("days_until_due", 30); subscriptionParams.put("customer", customer.getId()); Subscription sub = Subscription.create(subscriptionParams); assertEquals(sub.getPlan().getId(), plan.getId()); assertEquals(sub.getBilling(), "send_invoice"); assertEquals(sub.getDaysUntilDue(), (Integer) 30); Map<String, Object> updateParams = new HashMap<String, Object>(); updateParams.put("days_until_due", 10); Subscription subUpdated = sub.update(updateParams); assertEquals(subUpdated.getDaysUntilDue(), (Integer) 10); }

Target:
public void testInvoicingSubscription() throws StripeException { Plan plan = Plan.create(getUniquePlanParams()); defaultCustomerParams.put("email", "test@stripe.com"); Customer customer = Customer.create(defaultCustomerParams); Map<String, Object> subscriptionParams = new HashMap<String, Object>(); subscriptionParams.put("plan", plan.getId()); subscriptionParams.put("billing", "send_invoice"); subscriptionParams.put("days_until_due", 30); subscriptionParams.put("customer", customer.getId()); Subscription sub = Subscription.create(subscriptionParams); assertEquals(plan.getId(), sub.getPlan().getId()); assertEquals("send_invoice", sub.getBilling()); assertEquals((Integer) 30, sub.getDaysUntilDue()); Map<String, Object> updateParams = new HashMap<String, Object>(); updateParams.put("days_until_due", 10); Subscription subUpdated = sub.update(updateParams); assertEquals((Integer) 10, subUpdated.getDaysUntilDue()); }
Source:
private String mapQueryPropertyToFeatureProperty( final String queryProperty, final Predicate<String> isWfsFeatureProperty) { final String featurePropertyName = Optional.ofNullable(metacardMapper.getFeatureProperty(queryProperty)).orElse(queryProperty); if (isWfsFeatureProperty.test(featurePropertyName)) { final FeatureAttributeDescriptor featureAttributeDescriptor = (FeatureAttributeDescriptor) featureMetacardType.getAttributeDescriptor(featurePropertyName); if (featureAttributeDescriptor.isIndexed()) { return featureAttributeDescriptor.getPropertyName(); } else { throw new IllegalArgumentException( String.format(PROPERTY_NOT_QUERYABLE, featurePropertyName)); } } LOGGER.debug( "The property '{}' could not be mapped to a feature property of feature type '{}'.", featurePropertyName, featureMetacardType.getFeatureType()); return null; }

Target:
private String mapQueryPropertyToFeatureProperty( final String queryProperty, final Predicate<String> isWfsFeatureProperty) { final String featurePropertyName = Optional.ofNullable(metacardMapper.getFeatureProperty(queryProperty)).orElse(queryProperty); if (!isWfsFeatureProperty.test(featurePropertyName)) { throw new IllegalArgumentException( String.format( "'%s' was mapped to '%s', which is not a feature property of '%s'", queryProperty, featurePropertyName, featureMetacardType.getFeatureType())); } final FeatureAttributeDescriptor featureAttributeDescriptor = (FeatureAttributeDescriptor) featureMetacardType.getAttributeDescriptor(featurePropertyName); if (!featureAttributeDescriptor.isIndexed()) { throw new IllegalArgumentException( String.format(PROPERTY_NOT_QUERYABLE, featurePropertyName)); } return featureAttributeDescriptor.getPropertyName(); }
Source:
public void unregistered(SelectionKey key) { logger.debug("Unregistering server"); for (LogicalNode ln : subscriberGroups.values()) { ln.boot(); } eventloop.submit(new Runnable() { @Override public void run() { serverHelperExecutor.shutdown(); storageHelperExecutor.shutdown(); try { serverHelperExecutor.awaitTermination(5000, TimeUnit.MILLISECONDS); storageHelperExecutor.awaitTermination(5000, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.debug("Executor Termination", ex); } logger.info("Server stopped listening at {}", getServerAddress()); latch.countDown(); latch = null; } }); }

Target:
public void unregistered(SelectionKey key) { logger.debug("Unregistered {}", this); for (LogicalNode ln : subscriberGroups.values()) { ln.boot(); } super.unregistered(key); eventloop.submit(new Runnable() { @Override public void run() { serverHelperExecutor.shutdown(); storageHelperExecutor.shutdown(); try { serverHelperExecutor.awaitTermination(5000, TimeUnit.MILLISECONDS); storageHelperExecutor.awaitTermination(5000, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.debug("Executor Termination", ex); } logger.info("Server stopped listening at {}", getServerAddress()); latch.countDown(); latch = null; } }); }
Source:
protected boolean transitionRun(final Context context) { State state; State newState; do { state = _stateRef.get(); if (state.getType() != StateType.INIT) { if (!ParSeqGlobalConfiguration.isAllowCrossPlanSharingEnabled() && _startPlanId != null && !_startPlanId.equals(context.getPlanId())) { throw new IllegalStateException(this.toString() + " should not be shared across plans!!"); } return false; } newState = state.transitionRun(); } while (!_stateRef.compareAndSet(state, newState)); _startPlanId = context.getPlanId(); _traceBuilder = context.getTraceBuilder(); context.getTraceBuilder().addShallowTrace(_shallowTraceBuilder); return true; }

Target:
protected boolean transitionRun(final Context context) throws CrossPlanTaskSharingException { State state; State newState; do { state = _stateRef.get(); if (state.getType() != StateType.INIT) { if (!ParSeqGlobalConfiguration.allowCrossPlanTaskSharing() && state.getStartPlanId() != null && !state.getStartPlanId().equals(context.getPlanId())) { throw new CrossPlanTaskSharingException(this.toString() + " should not be shared across two plans!"); } return false; } newState = state.transitionRun(context.getPlanId()); } while (!_stateRef.compareAndSet(state, newState)); _traceBuilder = context.getTraceBuilder(); context.getTraceBuilder().addShallowTrace(_shallowTraceBuilder); return true; }
Source:
private boolean updateIsUsingScsiReservationRequested(LunDisk lunDisk) { return getVmDeviceForVm().isUsingScsiReservation() != lunDisk.isUsingScsiReservation(); }

Target:
private boolean updateIsUsingScsiReservationRequested(LunDisk lunDisk) { return getVmDeviceForVm().isUsingScsiReservation() != Boolean.TRUE.equals(lunDisk.isUsingScsiReservation()); }
Source:
public Query createReplacementQuery(EntityResolver resolver) { Object root; if (persistentType != null) { root = persistentType; } else if (dataMapName != null) { DataMap map = resolver.getDataMap(dataMapName); if (map == null) { throw new CayenneRuntimeException("Invalid dataMapName '%s'", dataMapName); } root = map; } else { root = null; } SQLTemplate template = new SQLTemplate(); template.setFetchingDataRows(isFetchingDataRows()); template.setRoot(root); template.setDefaultTemplate(getSql()); template.setCacheGroup(cacheGroup); template.setCacheStrategy(cacheStrategy); template.addPrefetch(prefetches); if (positionalParams != null) { template.setParamsList(positionalParams); } else { template.setParams(params); } template.setColumnNamesCapitalization(columnNameCaps); template.setFetchLimit(limit); template.setFetchOffset(offset); template.setPageSize(pageSize); template.setStatementFetchSize(statementFetchSize); if (isFetchingScalars()) { SQLResult resultMap = new SQLResult(); resultMap.addColumnResult("x"); template.setResult(resultMap); } return template; }

Target:
public Query createReplacementQuery(EntityResolver resolver) { Object root; if (persistentType != null) { root = persistentType; } else if (dataMapName != null) { DataMap map = resolver.getDataMap(dataMapName); if (map == null) { throw new CayenneRuntimeException("Invalid dataMapName '%s'", dataMapName); } root = map; } else { root = null; } SQLTemplate template = new SQLTemplate(); template.setFetchingDataRows(isFetchingDataRows()); template.setRoot(root); template.setDefaultTemplate(getSql()); template.setCacheGroup(cacheGroup); template.setCacheStrategy(cacheStrategy); if (prefetches != null) { template.addPrefetch(prefetches); } if (positionalParams != null) { template.setParamsList(positionalParams); } else { template.setParams(params); } template.setColumnNamesCapitalization(columnNameCaps); template.setFetchLimit(limit); template.setFetchOffset(offset); template.setPageSize(pageSize); template.setStatementFetchSize(statementFetchSize); if (isFetchingScalars()) { SQLResult resultMap = new SQLResult(); resultMap.addColumnResult("x"); template.setResult(resultMap); } return template; }
Source:
public void sendPullReplyMsg(final String destId, final K key, final V value, final int requestId, final long processingTime, @Nullable final TraceInfo traceInfo) { Span detached = null; try (final TraceScope sendPullReplyScope = Trace.startSpan("send_pull_reply." + " key: " + key + ", request_id: " + requestId, traceInfo)) { final PullReplyMsg pullReplyMsg = PullReplyMsg.newBuilder() .setKey(ByteBuffer.wrap(keyCodec.encode(key))) .setValue(ByteBuffer.wrap(valueCodec.encode(value))) .setRequestId(requestId) .setServerProcessingTime(processingTime) .build(); detached = sendPullReplyScope.detach(); send(destId, AvroPSMsg.newBuilder() .setType(Type.PullReplyMsg) .setPullReplyMsg(pullReplyMsg) .setTraceInfo(HTraceUtils.toAvro(TraceInfo.fromSpan(detached))) .build()); } finally { Trace.continueSpan(detached).close(); } }

Target:
public void sendPullReplyMsg(final String destId, final K key, final V value, final int requestId, final long processingTime, @Nullable final TraceInfo traceInfo) { Span detached = null; try (final TraceScope sendPullReplyScope = Trace.startSpan( String.format("send_pull_reply. key: %s, request_id: %d", key, requestId), traceInfo)) { final PullReplyMsg pullReplyMsg = PullReplyMsg.newBuilder() .setKey(ByteBuffer.wrap(keyCodec.encode(key))) .setValue(ByteBuffer.wrap(valueCodec.encode(value))) .setRequestId(requestId) .setServerProcessingTime(processingTime) .build(); detached = sendPullReplyScope.detach(); send(destId, AvroPSMsg.newBuilder() .setType(Type.PullReplyMsg) .setPullReplyMsg(pullReplyMsg) .setTraceInfo(HTraceUtils.toAvro(TraceInfo.fromSpan(detached))) .build()); } finally { Trace.continueSpan(detached).close(); } }
Source:
public void writeBlock(BlockEncodingSerde blockEncodingSerde, SliceOutput sliceOutput, Block block) { SingleMapBlock singleMapBlock = (SingleMapBlock) block; TypeSerde.writeType(sliceOutput, singleMapBlock.keyType); int offset = singleMapBlock.getOffset(); int positionCount = singleMapBlock.getPositionCount(); blockEncodingSerde.writeBlock(sliceOutput, singleMapBlock.getKeyBlock().getRegion(offset / 2, positionCount / 2)); blockEncodingSerde.writeBlock(sliceOutput, singleMapBlock.getValueBlock().getRegion(offset / 2, positionCount / 2)); int[] hashTable = singleMapBlock.getHashTable(); sliceOutput.appendInt(positionCount / 2 * HASH_MULTIPLIER); sliceOutput.writeBytes(wrappedIntArray(hashTable, offset / 2 * HASH_MULTIPLIER, positionCount / 2 * HASH_MULTIPLIER)); }

Target:
public void writeBlock(BlockEncodingSerde blockEncodingSerde, SliceOutput sliceOutput, Block block) { SingleMapBlock singleMapBlock = (SingleMapBlock) block; TypeSerde.writeType(sliceOutput, singleMapBlock.keyType); int offset = singleMapBlock.getOffset(); int positionCount = singleMapBlock.getPositionCount(); blockEncodingSerde.writeBlock(sliceOutput, singleMapBlock.getRawKeyBlock().getRegion(offset / 2, positionCount / 2)); blockEncodingSerde.writeBlock(sliceOutput, singleMapBlock.getRawValueBlock().getRegion(offset / 2, positionCount / 2)); int[] hashTable = singleMapBlock.getHashTable(); sliceOutput.appendInt(positionCount / 2 * HASH_MULTIPLIER); sliceOutput.writeBytes(wrappedIntArray(hashTable, offset / 2 * HASH_MULTIPLIER, positionCount / 2 * HASH_MULTIPLIER)); }
Source:
private ProjectNode project(String id, PlanNode source, VariableReferenceExpression variable, Expression expression) { return new ProjectNode( new PlanNodeId(id), source, Assignments.of(variable, expression)); }

Target:
private PlanNode project(String id, PlanNode source, VariableReferenceExpression variable, Expression expression) { return new ProjectNode( new PlanNodeId(id), source, assignment(variable, expression)); }
Source:
public void tearDown() { if (applicationContext != null) { applicationContext.close(); } }

Target:
public void tearDown() { if (applicationContext != null && applicationContext.isActive() ) { applicationContext.close(); } }
Source:
public void addToOrderBook(Order order) { if (order instanceof BuyOrder) { if (buyOrders.get(order.getStockSymbol()) != null) { stockArray = buyOrders.get(order.getStockSymbol()); stockArray.add(order); } else { stockArray = new ArrayList<Order>(); stockArray.add(order); } buyOrders.put(order.getStockSymbol(), stockArray); } else { if (sellOrders.get(order.getStockSymbol()) != null) { stockArray = sellOrders.get(order.getStockSymbol()); stockArray.add(order); } else { stockArray = new ArrayList<Order>(); stockArray.add(order); } sellOrders.put(order.getStockSymbol(), stockArray); } }

Target:
public void addToOrderBook(Order order) { if (order instanceof BuyOrder) { buyOrders.put(order.getStockSymbol(), addBuyOrder()); } else { sellOrders.put(order.getStockSymbol(), addSellOrder()); } }
Source:
public void saveLastId(String id) { logger.log(OneSignal.LOG_LEVEL.DEBUG, "OneSignal OSChannelTracker for: " + getIdTag() + " saveLastId: " + id); if (id == null || id.isEmpty()) return; JSONArray lastChannelObjectReceived = getLastChannelObjectsReceivedByNewId(id); logger.log(OneSignal.LOG_LEVEL.DEBUG, "OneSignal OSChannelTracker for: " + getIdTag() + " saveLastId with lastChannelObjectReceived: " + lastChannelObjectReceived); try { JSONObject newInfluenceId = new JSONObject() .put(getIdTag(), id) .put(TIME, System.currentTimeMillis()); lastChannelObjectReceived.put(newInfluenceId); } catch (JSONException exception) { logger.log(OneSignal.LOG_LEVEL.ERROR, "Generating tracker newInfluenceId JSONObject ", exception); return; } int channelLimit = getChannelLimit(); JSONArray channelObjectToSave = lastChannelObjectReceived; if (lastChannelObjectReceived.length() > channelLimit) { int lengthDifference = lastChannelObjectReceived.length() - channelLimit; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { for (int i = 0; i < lengthDifference; i++) { lastChannelObjectReceived.remove(i); } } else { channelObjectToSave = new JSONArray(); for (int i = lengthDifference; i < lastChannelObjectReceived.length(); i++) { try { channelObjectToSave.put(lastChannelObjectReceived.get(i)); } catch (JSONException exception) { logger.log(OneSignal.LOG_LEVEL.ERROR, "Before KITKAT API, Generating tracker lastChannelObjectReceived get JSONObject ", exception); } } } } logger.log(OneSignal.LOG_LEVEL.DEBUG, "OneSignal OSChannelTracker for: " + getIdTag() + " with channelObjectToSave: " + channelObjectToSave); saveChannelObjects(channelObjectToSave); }

Target:
public void saveLastId(String id) { logger.debug("OneSignal OSChannelTracker for: " + getIdTag() + " saveLastId: " + id); if (id == null || id.isEmpty()) return; JSONArray lastChannelObjectsReceived = getLastChannelObjectsReceivedByNewId(id); logger.debug("OneSignal OSChannelTracker for: " + getIdTag() + " saveLastId with lastChannelObjectsReceived: " + lastChannelObjectsReceived); try { JSONObject newInfluenceId = new JSONObject() .put(getIdTag(), id) .put(TIME, System.currentTimeMillis()); lastChannelObjectsReceived.put(newInfluenceId); } catch (JSONException exception) { logger.error("Generating tracker newInfluenceId JSONObject ", exception); return; } int channelLimit = getChannelLimit(); JSONArray channelObjectToSave = lastChannelObjectsReceived; if (lastChannelObjectsReceived.length() > channelLimit) { int lengthDifference = lastChannelObjectsReceived.length() - channelLimit; channelObjectToSave = new JSONArray(); for (int i = lengthDifference; i < lastChannelObjectsReceived.length(); i++) { try { channelObjectToSave.put(lastChannelObjectsReceived.get(i)); } catch (JSONException exception) { logger.error("Before KITKAT API, Generating tracker lastChannelObjectsReceived get JSONObject ", exception); } } } logger.debug("OneSignal OSChannelTracker for: " + getIdTag() + " with channelObjectToSave: " + channelObjectToSave); saveChannelObjects(channelObjectToSave); }
Source:
private void listFirmwares(Console console, String[] args) { if (args.length != 2) { console.println("Specify thing type id to get its available firmwares: firmware list <thingTypeUID>"); return; } ThingTypeUID thingTypeUID = new ThingTypeUID(args[1]); Collection<Firmware> firmwares = firmwareRegistry.getFirmwares(thingTypeUID); if (firmwares.isEmpty()) { console.println("No firmwares found."); } for (Firmware firmware : firmwares) { console.println(firmware.toString()); } }

Target:
private void listFirmwares(Console console, String[] args) { if (args.length != 2) { console.println("Specify the thing type id to get its available firmwares: firmware list <thingTypeUID>"); return; } ThingTypeUID thingTypeUID = new ThingTypeUID(args[1]); Collection<Firmware> firmwares = firmwareRegistry.getFirmwares(thingTypeUID); if (firmwares.isEmpty()) { console.println("No firmwares found."); } for (Firmware firmware : firmwares) { console.println(firmware.toString()); } }
Source:
public void clear(String tenantId) { String index = client.getIndex(tenantId); boolean indexExists = client.getClient() .admin() .indices() .prepareExists(index) .execute().actionGet().isExists(); if (indexExists) { client.getClient() .admin() .indices() .prepareDelete(index).execute().actionGet(); client.clear(tenantId); } }

Target:
public void clear(String tenantId) { String index = client.getIndex(tenantId); IndicesAdminClient indices = client.getClient().admin().indices(); boolean indexExists = indices.prepareExists(index) .execute() .actionGet() .isExists(); if (indexExists) { indices.prepareDelete(index) .execute() .actionGet(); client.clear(tenantId); } }
Source:
public BinaryObject getMODS() { Resource mods = this.getResource(); Statement s = mods.getProperty(Cdr.hasMods); if (s != null) { PID binPid = PIDs.get(s.getResource().getURI()); return repository.getBinary(binPid); } else { return null; } }

Target:
public BinaryObject getMODS() { Resource res = this.getResource(); Statement s = res.getProperty(Cdr.hasMods); if (s != null) { PID binPid = PIDs.get(s.getResource().getURI()); return repository.getBinary(binPid); } else { return null; } }
Source:
private List<Integer> calculateLastColumnsForPages(float[] relativeWidths) { List<Integer> lastColumnsForPages = new LinkedList<>(); lastColumnsForPages.add(1); float totalColumnsWidth = 0; for (int i = 1; i < relativeWidths.length; i++) { if (totalColumnsWidth + relativeWidths[i] > PAGE_WIDTH - relativeWidths[0]) { lastColumnsForPages.add(i); totalColumnsWidth = 0; } totalColumnsWidth += relativeWidths[i]; } lastColumnsForPages.add(-1); return lastColumnsForPages; }

Target:
private List<Integer> calculateLastColumnsForPages(float[] relativeWidths) { List<Integer> lastColumnsForPages = new ArrayList<>(); lastColumnsForPages.add(1); float totalColumnsWidth = 0; for (int i = 1; i < relativeWidths.length; i++) { if (totalColumnsWidth + relativeWidths[i] > PAGE_WIDTH - relativeWidths[0]) { lastColumnsForPages.add(i); totalColumnsWidth = 0; } totalColumnsWidth += relativeWidths[i]; } lastColumnsForPages.add(-1); return lastColumnsForPages; }
Source:
private ClassModifierShouldBe(Class<?> actual, boolean positive, String modifier) { super("%nExpecting:%n <%s>%n" + (positive ? "to" : "not to") + " be a %s class.", actual, modifier); }

Target:
private ClassModifierShouldBe(Class<?> actual, boolean positive, String modifier) { super("%nExpecting:%n <%s>%n" + (positive ? "to" : "not to") + " be a %s class but was %s.", actual, modifier, Modifier.toString(actual.getModifiers())); }
Source:
public boolean mediate(MessageContext synCtx) { List<PropertyMediator> propGroupList = this.getPropGroupList(); for (PropertyMediator propertyMediator : propGroupList) { propertyMediator.mediate(synCtx); } return true; }

Target:
public boolean mediate(MessageContext synCtx) { for (PropertyMediator propertyMediator : propGroupList) { propertyMediator.mediate(synCtx); } return true; }
Source:
public void destroy() throws Exception { restAPIStore.deleteApplication(tokenTestApiAppId, user.getUserDomain()); restAPIStore.deleteApplication(tokenTestAppId, user.getUserDomain()); restAPIStore.deleteApplication(oauthTokenTestApiId, user.getUserDomain()); restAPIPublisher.deleteAPI(apiId); restAPIPublisher.deleteAPI(apiIdForOauth); super.cleanUp(); }

Target:
public void destroy() throws Exception { restAPIStore.deleteApplication(tokenTestApiAppId); restAPIStore.deleteApplication(tokenTestAppId); restAPIStore.deleteApplication(oauthTokenTestApiId); restAPIPublisher.deleteAPI(apiId); restAPIPublisher.deleteAPI(apiIdForOauth); }
Source:
protected boolean processOperator(Mutable<ILogicalOperator> opRef, IOptimizationContext context) throws AlgebricksException { VXQueryOptimizationContext vxqOptCtx = (VXQueryOptimizationContext) context; IMetadataProvider iProvider = (IMetadataProvider) vxqOptCtx.getMetadataProvider(); VXQueryMetadataProvider vxqProvider = (VXQueryMetadataProvider) iProvider; dCtx = vxqProvider.getStaticContext(); AbstractLogicalOperator op1 = (AbstractLogicalOperator) opRef.getValue(); if (op1.getOperatorTag() != LogicalOperatorTag.UNNEST) { return false; } UnnestOperator unnest = (UnnestOperator) op1; AbstractLogicalOperator op2 = (AbstractLogicalOperator) unnest.getInputs().get(0).getValue(); if (op2.getOperatorTag() != LogicalOperatorTag.DATASOURCESCAN) { return false; } DataSourceScanOperator datascan = (DataSourceScanOperator) op2; if (!usedVariables.contains(datascan.getVariables())) { VXQueryCollectionDataSource ds = (VXQueryCollectionDataSource) datascan.getDataSource(); if (!updateDataSource(ds, unnest.getExpressionRef())) { return false; } Mutable<ILogicalExpression> varExp = ExpressionToolbox.findVariableExpression(unnest.getExpressionRef(), datascan.getVariables().get(0)); AssignOperator noOp = new AssignOperator(unnest.getVariable(), varExp); noOp.getInputs().addAll(unnest.getInputs()); opRef.setValue(noOp); return true; } return false; }

Target:
protected boolean processOperator(Mutable<ILogicalOperator> opRef, IOptimizationContext context) throws AlgebricksException { IMetadataProvider iProvider = ((VXQueryOptimizationContext) context).getMetadataProvider(); dCtx = ((VXQueryMetadataProvider) iProvider).getStaticContext(); AbstractLogicalOperator op1 = (AbstractLogicalOperator) opRef.getValue(); if (op1.getOperatorTag() != LogicalOperatorTag.UNNEST) { return false; } UnnestOperator unnest = (UnnestOperator) op1; AbstractLogicalOperator op2 = (AbstractLogicalOperator) unnest.getInputs().get(0).getValue(); if (op2.getOperatorTag() != LogicalOperatorTag.DATASOURCESCAN) { return false; } DataSourceScanOperator datascan = (DataSourceScanOperator) op2; if (!usedVariables.contains(datascan.getVariables())) { VXQueryCollectionDataSource ds = (VXQueryCollectionDataSource) datascan.getDataSource(); if (!updateDataSource(ds, unnest.getExpressionRef())) { return false; } Mutable<ILogicalExpression> varExp = ExpressionToolbox.findVariableExpression(unnest.getExpressionRef(), datascan.getVariables().get(0)); AssignOperator noOp = new AssignOperator(unnest.getVariable(), varExp); noOp.getInputs().addAll(unnest.getInputs()); opRef.setValue(noOp); return true; } return false; }
Source:
public Response toResponse(Throwable exception) { if (exception instanceof WebApplicationException) { WebApplicationException wae = (WebApplicationException) exception; return wae.getResponse(); } if (exception instanceof ClassCastException) { return Response.status(Status.BAD_REQUEST) .type(MediaType.APPLICATION_JSON) .entity(new ApiError(exception.getMessage())) .build(); } LOG.info("No exception mapping for " + exception.getClass() + ", responding 500", exception); return Response.status(Status.INTERNAL_SERVER_ERROR) .type(MediaType.APPLICATION_JSON) .entity(new ApiError(exception.getMessage())) .build(); }

Target:
public Response toResponse(Throwable exception) { if (exception instanceof WebApplicationException) { WebApplicationException wae = (WebApplicationException) exception; return wae.getResponse(); } if (exception instanceof ClassCastException) { return Response.status(Status.BAD_REQUEST) .type(MediaType.APPLICATION_JSON) .entity(new ApiError(exception.getMessage())) .build(); } LOG.info("No exception mapping for " + exception.getClass() + ", responding 500", exception); String message = Optional.fromNullable(exception.getMessage()) .or("Internal error. Check server logs for details."); return Response.status(Status.INTERNAL_SERVER_ERROR) .type(MediaType.APPLICATION_JSON) .entity(new ApiError(message)) .build(); }
Source:
void doCommonSPICompleteActions() { m_txnState.setDone(); if (m_txnDoneNotification != null) { m_txnDoneNotification.transactionDone(m_txnState.m_spHandle); } if (m_queue != null) { m_queue.flush(getTxnId()); } }

Target:
void doCommonSPICompleteActions() { m_txnState.setDone(); if (m_queue != null) { m_queue.flush(getTxnId()); } }
Source:
private String composeProxyClause() throws IOException { String proxyClause = "proxy"; final String proxyHost = System.getProperty(HTTP_PROXY_HOST); final String proxyporttxt = System.getProperty(HTTP_PROXY_PORT); if (StringUtils.isNotBlank(proxyHost) && StringUtils.isNotBlank(proxyporttxt)) { int proxyPort = 0; try { proxyPort = Integer.parseInt(proxyporttxt); } catch (final NumberFormatException exception) { Logger.error( this, Joiner.on(" ").join( "Can't parse proxy port", proxyporttxt ) ); } if (proxyPort > 0) { proxyClause = Joiner.on("").join( "http-proxy=", proxyHost, ":", proxyPort ); } } return proxyClause; }

Target:
private String composeProxyClause() throws IOException { String clause = "proxy"; final String host = System.getProperty(HTTP_PROXY_HOST); final String porttxt = System.getProperty(HTTP_PROXY_PORT); if (StringUtils.isNotBlank(host)) { int proxyPort = 80; try { proxyPort = Integer.parseInt(porttxt); } catch (final NumberFormatException exception) { final String message = Joiner.on(" ").join( "Can't parse proxy port", porttxt ); Logger.error( this, message ); throw new IllegalStateException(message); } if (proxyPort > 0) { clause = Joiner.on("").join( "http-proxy=", host, ":", proxyPort ); } } return clause; }
Source:
public String getNextIndexName(String aliasName, String oldIndexName) { if (oldIndexName == null || oldIndexName.isEmpty()) { return aliasName + SEP + "0000"; } int i = oldIndexName.lastIndexOf(SEP); if (i < 0) { throw new IllegalArgumentException("Invalid index name: " + oldIndexName); } int index = Integer.parseInt(oldIndexName.substring(i + 1)) + 1; return String.format("%s%s%04d", aliasName, SEP, index); }

Target:
public String getNextIndexName(String aliasName, String oldIndexName) { if (StringUtils.isEmpty(oldIndexName)) { return aliasName + SEP + "0000"; } int i = oldIndexName.lastIndexOf(SEP); if (i < 0) { throw new IllegalArgumentException("Invalid index name: " + oldIndexName); } int index = Integer.parseInt(oldIndexName.substring(i + 1)) + 1; return String.format("%s%s%04d", aliasName, SEP, index); }
Source:
public DefaultQuestionView(@NonNull final View view) { this.view = view; titleTextView = (TextView) view.findViewById(R.id.amp_title_text_view); if (titleTextView == null) { throw new IllegalArgumentException("You must supply a layout that includes a TextView with id amp_title_text_view"); } positiveButton = view.findViewById(R.id.amp_positive_button); if (positiveButton == null) { throw new IllegalArgumentException("You must supply a layout that includes a Button with id amp_positive_button"); } negativeButton = view.findViewById(R.id.amp_negative_button); if (negativeButton == null) { throw new IllegalArgumentException("You must supply a layout that includes a Button with id amp_negative_button"); } }

Target:
public DefaultQuestionView(@NonNull final View view) { this.view = view; titleTextView = (TextView) view.findViewById(R.id.amp_title_text_view); questionTextView = (TextView) view.findViewById(R.id.amp_question_text_view); if (questionTextView == null) { throw new IllegalArgumentException("You must supply a layout that includes a TextView with id amp_question_text_view"); } positiveButton = view.findViewById(R.id.amp_positive_button); if (positiveButton == null) { throw new IllegalArgumentException("You must supply a layout that includes a View with id amp_positive_button"); } negativeButton = view.findViewById(R.id.amp_negative_button); if (negativeButton == null) { throw new IllegalArgumentException("You must supply a layout that includes a View with id amp_negative_button"); } }
Source:
public boolean addReaction(String emojiName) { return slackService.addReaction(channelId, ts, emojiName); }

Target:
public boolean addReaction(String emojiName) { if (slackService == null) { return false; } return slackService.addReaction(channelId, ts, emojiName); }
Source:
public void updateRelationTupleCount(final RelationKey relation, final long count) throws CatalogException { Objects.requireNonNull(relation, "relation"); if (isClosed) { throw new CatalogException("Catalog is closed."); } try { queue.execute(new SQLiteJob<Void>() { @Override protected Void job(final SQLiteConnection sqliteConnection) throws CatalogException, SQLiteException { try { SQLiteStatement statement = sqliteConnection .prepare("UPDATE relations SET num_tuples=? WHERE user_name=? AND program_name=? AND relation_name=? and tombstone=0;"); statement.bind(1, count); statement.bind(2, relation.getUserName()); statement.bind(3, relation.getProgramName()); statement.bind(4, relation.getRelationName()); statement.stepThrough(); statement.dispose(); statement = null; } catch (final SQLiteException e) { throw new CatalogException(e); } return null; } }).get(); } catch (InterruptedException | ExecutionException e) { throw new CatalogException(e); } }

Target:
public void updateRelationTupleCount(final RelationKey relation, final long count) throws CatalogException { Objects.requireNonNull(relation, "relation"); if (isClosed) { throw new CatalogException("Catalog is closed."); } if (isDeletedRelation(relation)) { LOGGER.warn("Relation has already been deleted"); } try { queue.execute(new SQLiteJob<Void>() { @Override protected Void job(final SQLiteConnection sqliteConnection) throws CatalogException, SQLiteException { try { SQLiteStatement statement = sqliteConnection .prepare("UPDATE relations SET num_tuples=? WHERE user_name=? AND program_name=? AND relation_name=? and is_deleted=0;"); statement.bind(1, count); statement.bind(2, relation.getUserName()); statement.bind(3, relation.getProgramName()); statement.bind(4, relation.getRelationName()); statement.stepThrough(); statement.dispose(); statement = null; } catch (final SQLiteException e) { throw new CatalogException(e); } return null; } }).get(); } catch (InterruptedException | ExecutionException e) { throw new CatalogException(e); } }
Source:
private String getPrettyMessage(LogEvent event) { String payload = event.getPayload(); StringWriter swriter = new StringWriter(estimatePrettySize(payload)); XMLStreamWriter xwriter = new PrettyPrintXMLStreamWriter(StaxUtils.createXMLStreamWriter(swriter), 2); XMLStreamReader xreader = StaxUtils.createXMLStreamReader(new StringReader(payload)); try { StaxUtils.copy(xreader, xwriter); xwriter.flush(); } catch (XMLStreamException | WstxLazyException e) { if (!event.isTruncated()) { LOG.debug("Error while pretty printing cxf message, returning raw message.", e); return payload; } flush(xwriter); return swriter.toString(); } finally { close(xwriter); close(xreader); } return swriter.toString(); }

Target:
private String getPrettyMessage(LogEvent event) { String payload = event.getPayload(); StringWriter swriter = new StringWriter(estimatePrettySize(payload)); XMLStreamWriter xwriter = new PrettyPrintXMLStreamWriter(StaxUtils.createXMLStreamWriter(swriter), 2); XMLStreamReader xreader = StaxUtils.createXMLStreamReader(new StringReader(payload)); try { StaxUtils.copy(xreader, xwriter); xwriter.flush(); } catch (XMLStreamException xse) { return getPrettyMessageAfterExceptionHandling(xse, event, payload, swriter, xwriter); } catch (RuntimeException ex) { if (!(ex.getCause() instanceof XMLStreamException)) { throw ex; } XMLStreamException xse = (XMLStreamException) ex.getCause(); return getPrettyMessageAfterExceptionHandling(xse, event, payload, swriter, xwriter); } finally { close(xwriter); close(xreader); } return swriter.toString(); }
Source:
FilePerformanceStatisticsReader(PerformanceStatisticsHandler... handlers) { A.ensure(handlers != null, "At least one handler expected."); A.ensure(handlers.length > 0, "At least one handler expected."); this.handlers = handlers; }

Target:
public FilePerformanceStatisticsReader(PerformanceStatisticsHandler... handlers) { this(DFLT_READ_BUFFER_SIZE, handlers); }
Source:
public void testWithoutInterval() throws Exception { runTestWithoutIntervalTask(); final Interval interval = Intervals.of("2017-12-24/P1D"); final List<DataSegment> oldSegments = getStorageCoordinator().getUsedSegmentsForInterval("dataSource", interval); Assert.assertEquals(1, oldSegments.size()); runTestWithoutIntervalTask(); final List<DataSegment> newSegments = getStorageCoordinator().getUsedSegmentsForInterval("dataSource", interval); Assert.assertEquals(1, newSegments.size()); Assert.assertNotEquals(oldSegments.get(0).getVersion(), newSegments.get(0).getVersion()); }

Target:
public void testWithoutInterval() throws Exception { runTestWithoutIntervalTask(); final Interval interval = Intervals.of("2017-12-24/P1D"); final List<DataSegment> oldSegments = getStorageCoordinator().getUsedSegmentsForInterval("dataSource", interval); Assert.assertEquals(1, oldSegments.size()); runTestWithoutIntervalTask(); final List<DataSegment> newSegments = getStorageCoordinator().getUsedSegmentsForInterval("dataSource", interval); Assert.assertEquals(1, newSegments.size()); Assert.assertTrue(oldSegments.get(0).getVersion().compareTo(newSegments.get(0).getVersion()) < 0); }
Source:
public List<AbstractLayer> setLayersForMap (Integer mapModuleId, List<Integer> abstractLayerIds) throws Exception{ E module = this.findById(mapModuleId); List<AbstractLayer> layers = new ArrayList<AbstractLayer>(); if(module instanceof Map) { Map mapModule = (Map) module; for (Integer id : abstractLayerIds) { PersistentObject entity = this.abstractLayerService.findById(id); if(entity instanceof AbstractLayer){ AbstractLayer layer = (AbstractLayer) entity; if(layer != null){ layers.add(layer); } } } mapModule.setMapLayers(layers); this.saveOrUpdate((E) mapModule); return layers; } else { throw new Exception("Layer of with given Id is not a LayerGroup."); } }

Target:
public List<AbstractLayer> setLayersForMap (Integer mapModuleId, List<Integer> abstractLayerIds) throws Exception{ E module = this.findById(mapModuleId); List<AbstractLayer> layers = new ArrayList<AbstractLayer>(); if(module instanceof Map) { Map mapModule = (Map) module; for (Integer id : abstractLayerIds) { PersistentObject entity = this.abstractLayerService.findById(id); if(entity instanceof AbstractLayer){ AbstractLayer layer = (AbstractLayer) entity; if(layer != null){ layers.add(layer); } } } mapModule.setMapLayers(layers); this.saveOrUpdate((E) mapModule); return layers; } else { throw new Exception("Can't find mapModule with id " + mapModuleId.toString()); } }
Source:
public Action<?, ?> databaseBackupFinished() { return new AbstractDatabaseBackupAction<>(DatabaseBackupSuccess.class) { @Override protected BackupRestoreContext createFlowContext(FlowParameters flowParameters, StateContext<FlowState, FlowEvent> stateContext, DatabaseBackupSuccess payload) { return BackupRestoreContext.from(flowParameters, payload, null, null); } @Override protected void doExecute(BackupRestoreContext context, DatabaseBackupSuccess payload, Map<Object, Object> variables) { backupRestoreStatusService.backupDatabaseFinished(context.getStackId()); sendEvent(context); } @Override protected Selectable createRequest(BackupRestoreContext context) { return new StackEvent(DatabaseBackupEvent.DATABASE_BACKUP_FINALIZED_EVENT.event(), context.getStackId()); } @Override protected Object getFailurePayload(DatabaseBackupSuccess payload, Optional<BackupRestoreContext> flowContext, Exception ex) { return null; } }; }

Target:
public Action<?, ?> databaseBackupFinished() { return new AbstractBackupRestoreActions<>(DatabaseBackupSuccess.class) { @Override protected void doExecute(BackupRestoreContext context, DatabaseBackupSuccess payload, Map<Object, Object> variables) { backupRestoreStatusService.backupDatabaseFinished(context.getStackId()); sendEvent(context); } @Override protected Selectable createRequest(BackupRestoreContext context) { return new StackEvent(DatabaseBackupEvent.DATABASE_BACKUP_FINALIZED_EVENT.event(), context.getStackId()); } }; }
Source:
public SendToClientFunction getSendToClientFunction() { if (sendToClientFunction == null) { sendToClientFunction = (name, values) -> { String scriptTag = "<script type=\"text/javascript\">var " + Handlebars.Utils.escapeExpression(name) + "=" + GSON.toJson(values[0]) + ";</script>"; api.getRequestLookup().addToPlaceholder( (values.length == 2 && "headJs".equalsIgnoreCase((String) values[1])) ? Placeholder.headJs : Placeholder.js, scriptTag); }; } return sendToClientFunction; }

Target:
public SendToClientFunction getSendToClientFunction() { if (sendToClientFunction == null) { sendToClientFunction = (name, values) -> { String scriptTag = "<script type=\"text/javascript\">var " + Handlebars.Utils.escapeExpression(name) + "=" + GSON.toJson(values[0]) + ";</script>"; api.getRequestLookup().addToPlaceholder( (values.length == 2 && Placeholder.headJs.name().equalsIgnoreCase((String) values[1])) ? Placeholder.headJs : Placeholder.js, scriptTag); }; } return sendToClientFunction; }
Source:
public String insertCourseProblem(final String userId, final SrlProblem problem) throws AuthenticationException, DatabaseAccessException { final String resultId = CourseProblemManager.mongoInsertCourseProblem(auth, database, userId, problem); if (problem.hasProblemBankId()) { putCourseInBankProblem(problem.getCourseId(), problem.getProblemBankId(), userId, null); } try { updater.createNewItem(School.ItemType.COURSE_PROBLEM, resultId, problem.getAssignmentId(), userId, null); } catch (AuthenticationException e) { throw new AuthenticationException("Faild to create auth data while inserting course problem", e); } return resultId; }

Target:
public String insertCourseProblem(final String userId, final SrlProblem problem) throws AuthenticationException, DatabaseAccessException { final String resultId = CourseProblemManager.mongoInsertCourseProblem(auth, database, userId, problem); if (problem.hasProblemBankId()) { putCourseInBankProblem(problem.getCourseId(), problem.getProblemBankId(), userId, null); } try { updater.createNewItem(School.ItemType.COURSE_PROBLEM, resultId, problem.getAssignmentId(), userId, null); } catch (AuthenticationException e) { throw new AuthenticationException("Failed to create auth data while inserting course problem", e); } return resultId; }
Source:
public void testQueueQueryOnAutoCreatedQueueWithFQQN() throws Exception { SimpleString addressName = SimpleString.toSimpleString(UUID.randomUUID().toString()); SimpleString queueName = SimpleString.toSimpleString(UUID.randomUUID().toString()); SimpleString fqqn = addressName.concat("::").concat(queueName); try (JMSContext c = new ActiveMQConnectionFactory("vm://0").createContext()) { c.createProducer().send(c.createQueue(fqqn.toString()), c.createMessage()); assertTrue(Wait.waitFor(() -> server.locateQueue(queueName).getMessageCount() == 1, 2000, 100)); QueueQueryResult queueQueryResult = server.queueQuery(fqqn); assertEquals(queueName, queueQueryResult.getName()); assertEquals(addressName, queueQueryResult.getAddress()); assertEquals(1, queueQueryResult.getMessageCount()); queueQueryResult = server.queueQuery(queueName); assertEquals(queueName, queueQueryResult.getName()); assertEquals(addressName, queueQueryResult.getAddress()); assertEquals(1, queueQueryResult.getMessageCount()); c.createProducer().send(c.createQueue(addressName.toString()), c.createMessage()); assertTrue(Wait.waitFor(() -> server.locateQueue(queueName).getMessageCount() == 2, 2000, 100)); assertEquals(2, server.queueQuery(fqqn).getMessageCount()); assertEquals(2, server.queueQuery(queueName).getMessageCount()); } }

Target:
public void testQueueQueryOnAutoCreatedQueueWithFQQN() throws Exception { SimpleString addressName = SimpleString.toSimpleString(UUID.randomUUID().toString()); SimpleString queueName = SimpleString.toSimpleString(UUID.randomUUID().toString()); SimpleString fqqn = addressName.concat("::").concat(queueName); try (JMSContext c = new ActiveMQConnectionFactory("vm://0").createContext()) { c.createProducer().send(c.createQueue(fqqn.toString()), c.createMessage()); QueueQueryResult queueQueryResult = server.queueQuery(fqqn); assertEquals(queueName, queueQueryResult.getName()); assertEquals(addressName, queueQueryResult.getAddress()); Wait.assertEquals(1, () -> server.queueQuery(fqqn).getMessageCount()); queueQueryResult = server.queueQuery(queueName); assertEquals(queueName, queueQueryResult.getName()); assertEquals(addressName, queueQueryResult.getAddress()); assertEquals(1, queueQueryResult.getMessageCount()); c.createProducer().send(c.createQueue(addressName.toString()), c.createMessage()); Wait.assertEquals(2, () -> server.queueQuery(fqqn).getMessageCount()); Wait.assertEquals(2, () -> server.queueQuery(queueName).getMessageCount()); } }