auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected boolean addVmImages() { if (getVmTemplate().getDiskMap().size() > 0) { if (getVm().getStatus() != VMStatus.Down) { log.error("Cannot add images. VM is not Down"); throw new VdcBLLException(VdcBllErrors.IRS_IMAGE_STATUS_ILLEGAL); } VmHandler.LockVm(getVmId()); for (DiskImage dit : getImagesToCheckDestinationStorageDomains()) { CreateSnapshotFromTemplateParameters tempVar = new CreateSnapshotFromTemplateParameters( dit.getImageId(), getParameters().getVmStaticData().getId()); tempVar.setDestStorageDomainId(diskInfoDestinationMap.get(dit.getId()).getStorageIds().get(0)); tempVar.setDiskAlias(diskInfoDestinationMap.get(dit.getId()).getDiskAlias()); tempVar.setStorageDomainId(dit.getStorageIds().get(0)); tempVar.setVmSnapshotId(getVmSnapshotId()); tempVar.setParentCommand(VdcActionType.AddVm); tempVar.setEntityInfo(getParameters().getEntityInfo()); tempVar.setParentParameters(getParameters()); tempVar.setQuotaId(diskInfoDestinationMap.get(dit.getId()).getQuotaId()); VdcReturnValueBase result = getBackend().runInternalAction(VdcActionType.CreateSnapshotFromTemplate, tempVar, ExecutionHandler.createDefaultContexForTasks(getExecutionContext())); if (!result.getSucceeded()) { throw new VdcBLLException(result.getFault().getError()); } else { getTaskIdList().addAll(result.getInternalVdsmTaskIdList()); DiskImage newImage = (DiskImage) result.getActionReturnValue(); srcDiskToTargetDiskMapping.put(dit.getId(), newImage.getId()); <START> newDiskImages.add(newImage); <END> } } } return true; }</code><technical_language>instead of keeping a map a list, combine a single map? E.g. 'id' 'disk' (to avoid maintaining data structures)</technical_language>

Target:
protected boolean addVmImages() { if (getVmTemplate().getDiskMap().size() > 0) { if (getVm().getStatus() != VMStatus.Down) { log.error("Cannot add images. VM is not Down"); throw new VdcBLLException(VdcBllErrors.IRS_IMAGE_STATUS_ILLEGAL); } VmHandler.LockVm(getVmId()); for (DiskImage dit : getImagesToCheckDestinationStorageDomains()) { CreateSnapshotFromTemplateParameters tempVar = new CreateSnapshotFromTemplateParameters( dit.getImageId(), getParameters().getVmStaticData().getId()); tempVar.setDestStorageDomainId(diskInfoDestinationMap.get(dit.getId()).getStorageIds().get(0)); tempVar.setDiskAlias(diskInfoDestinationMap.get(dit.getId()).getDiskAlias()); tempVar.setStorageDomainId(dit.getStorageIds().get(0)); tempVar.setVmSnapshotId(getVmSnapshotId()); tempVar.setParentCommand(VdcActionType.AddVm); tempVar.setEntityInfo(getParameters().getEntityInfo()); tempVar.setParentParameters(getParameters()); tempVar.setQuotaId(diskInfoDestinationMap.get(dit.getId()).getQuotaId()); VdcReturnValueBase result = getBackend().runInternalAction(VdcActionType.CreateSnapshotFromTemplate, tempVar, ExecutionHandler.createDefaultContexForTasks(getExecutionContext())); if (!result.getSucceeded()) { throw new VdcBLLException(result.getFault().getError()); } else { getTaskIdList().addAll(result.getInternalVdsmTaskIdList()); DiskImage newImage = (DiskImage) result.getActionReturnValue(); srcDiskIdToTargetDiskIdMapping.put(dit.getId(), newImage.getId()); } } } return true; }
Source:
<code>public void testGetCinderDiskByDiskAndImageIds() { <START> Guid cinderImageId = new Guid("42058975-3d5e-484a-80c1-01c31207f580"); <END> DiskImage result = dao.getDiskImageByDiskAndImageIds(FixturesTool.FLOATING_CINDER_DISK_ID, cinderImageId); assertNotNull(result); assertEquals(FixturesTool.FLOATING_CINDER_DISK_ID, result.getId()); assertEquals(cinderImageId, result.getImageId()); }</code><technical_language>extract this FixturesTool (possibly in another patch this one)</technical_language>

Target:
public void testGetCinderDiskByDiskAndImageIds() { DiskImage result = dao.getDiskImageByDiskAndImageIds( FixturesTool.FLOATING_CINDER_DISK_ID, FixturesTool.CINDER_IMAGE_ID); assertNotNull(result); assertEquals(FixturesTool.FLOATING_CINDER_DISK_ID, result.getId()); assertEquals(FixturesTool.CINDER_IMAGE_ID, result.getImageId()); }
Source:
<code>public void test_A_topology() throws Exception { Cluster cluster = consumer.readTopology(); String json = mapper.writeValueAsString(cluster.toMap()); System.out.println(json); <START> assertThat(json, equalTo(read("/topology.json"))); <END> }</code><technical_language>I fully understand this is simple write is brittle. For assertions topology, a do a number of rely identical text formats? For example, comparison of JSon in memory? else</technical_language>

Target:
public void test_A_topology() throws Exception { Cluster cluster = consumer.readTopology(); String json = mapper.writeValueAsString(cluster.toMap()); System.out.println(json); }
Source:
<code>public void testInsertPartitionedTableOverwriteExistingPartition() { for (TestingHiveStorageFormat storageFormat : getAllTestingHiveStorageFormat(immutablePartitionSession)) { <START> testInsertPartitionedTableOverwriteExistingPartition( <END> Session.builder(storageFormat.getSession()) .setCatalogSessionProperty(immutablePartitionSession.getCatalog().get(), "insert_overwrite_existing_partitions", "true") .build(), storageFormat.getFormat()); } }</code><technical_language>I necessity for this tests ran storage formats</technical_language>

Target:
public void testInsertPartitionedTableOverwriteExistingPartition() { testInsertPartitionedTableOverwriteExistingPartition( Session.builder(getSession()) .setCatalogSessionProperty(catalog, "insert_existing_partitions_behavior", "OVERWRITE") .build(), HiveStorageFormat.ORC); }
Source:
<code>public void visitReturnStatement(ReturnStatementTree tree) { <START> if(tree.expression()== null || !isIncrementOrDecrement(tree.expression())) { <END> scan(tree.expression()); } }</code><technical_language>a variable instead of calling 3 times tree.expression()</technical_language>

Target:
public void visitReturnStatement(ReturnStatementTree tree) { ExpressionTree expression = tree.expression(); if(expression == null || !isIncrementOrDecrement(expression)) { scan(expression); } }
Source:
<code>public Collection<Order> getOrder(OrderQueryParams... orderQueryParams) throws IOException { return Arrays.stream(orderQueryParams) .filter(oq -> oq instanceof OrderQueryParamCurrencyPair) .map(oq -> (OrderQueryParamCurrencyPair) oq) .flatMap( oq -> { try { return getBithumbOrderDetail(oq.getOrderId(), oq.getCurrencyPair()).getData() .stream() .map(detail -> BithumbAdapters.adaptOrderDetail(detail, oq.getOrderId())); } catch (IOException e) { <START> return null; <END> } catch (BithumbException e) { throw BithumbErrorAdapter.adapt(e); } }) .filter(Objects::nonNull) .collect(Collectors.toList()); }</code><technical_language>silent errors pure evil IOException thrown out</technical_language>

Target:
public Collection<Order> getOrder(OrderQueryParams... orderQueryParams) throws IOException { return Arrays.stream(orderQueryParams) .filter(oq -> oq instanceof OrderQueryParamCurrencyPair) .map(oq -> (OrderQueryParamCurrencyPair) oq) .map( oq -> { try { BithumbResponse<BithumbOrderDetail> r = getBithumbOrderDetail(oq.getOrderId(), oq.getCurrencyPair()); return BithumbAdapters.adaptOrderDetail(r.getData(), oq.getOrderId()); } catch (IOException e) { throw new RuntimeException(e); } catch (BithumbException e) { throw BithumbErrorAdapter.adapt(e); } }) .filter(Objects::nonNull) .collect(Collectors.toList()); }
Source:
<code>public String asSummaryString() { <START> return "Kafka 0.10 scan source"; <END> }</code><technical_language>"Kafka-0.10". others</technical_language>

Target:
public String asSummaryString() { return "Kafka-0.10"; }
Source:
<code>public void makeUnDiscoverablePatchUnauthorizedTest() throws Exception { context.turnOffAuthorisationSystem(); parentCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity) .withName("Sub Community") .build(); Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build(); Item item = ItemBuilder.createItem(context, col1) .withTitle("Public item 1") .withIssueDate("2017-10-17") .withAuthor("Smith, Donald").withAuthor("Doe, John") .withSubject("ExtraEntry") .build(); String token = getAuthToken(admin.getEmail(), password); List<Operation> ops = new ArrayList<Operation>(); <START> ReplaceOperation replaceOperation = new ReplaceOperation("/discoverable", "false"); <END> ops.add(replaceOperation); String patchBody = getPatchContent(ops); getClient().perform(patch("/api/core/items/" + item.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isUnauthorized()); getClient(token).perform(get("/api/core/items/" + item.getID())) .andExpect(status().isOk()) .andExpect(jsonPath("$.uuid", Matchers.is(item.getID().toString()))) .andExpect(jsonPath("$.discoverable", Matchers.is(true))); }</code><technical_language>official true instead "true"</technical_language>

Target:
public void makeUnDiscoverablePatchUnauthorizedTest() throws Exception { context.turnOffAuthorisationSystem(); parentCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity) .withName("Sub Community") .build(); Collection col1 = CollectionBuilder.createCollection(context, child1).withName("Collection 1").build(); Item item = ItemBuilder.createItem(context, col1) .withTitle("Public item 1") .withIssueDate("2017-10-17") .withAuthor("Smith, Donald").withAuthor("Doe, John") .withSubject("ExtraEntry") .build(); String token = getAuthToken(admin.getEmail(), password); List<Operation> ops = new ArrayList<Operation>(); ReplaceOperation replaceOperation = new ReplaceOperation("/discoverable", false); ops.add(replaceOperation); String patchBody = getPatchContent(ops); getClient().perform(patch("/api/core/items/" + item.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isUnauthorized()); getClient(token).perform(get("/api/core/items/" + item.getID())) .andExpect(status().isOk()) .andExpect(jsonPath("$.uuid", Matchers.is(item.getID().toString()))) .andExpect(jsonPath("$.discoverable", Matchers.is(true))); }
Source:
<code>public Note merge(Note base, Note ours, Note theirs, ObjectReader reader, ObjectInserter inserter) throws IOException { if (ours == null) { return theirs; } if (theirs == null) { return ours; } if (ours.getData().equals(theirs.getData())) { return ours; } ObjectLoader lo = reader.open(ours.getData()); byte[] sep = new byte[] {'\n'}; ObjectLoader lt = reader.open(theirs.getData()); try (UnionInputStream union = new UnionInputStream( lo.openStream(), <START> new ByteArrayInputStream(sep), <END> lt.openStream())) { ObjectId noteData = inserter.insert(Constants.OBJ_BLOB, lo.getSize() + sep.length + lt.getSize(), union); return new Note(ours, noteData); } }</code><technical_language>This assignment newly opened resource</technical_language>

Target:
public Note merge(Note base, Note ours, Note theirs, ObjectReader reader, ObjectInserter inserter) throws IOException { if (ours == null) { return theirs; } if (theirs == null) { return ours; } if (ours.getData().equals(theirs.getData())) { return ours; } ObjectLoader lo = reader.open(ours.getData()); byte[] sep = new byte[] {'\n'}; ObjectLoader lt = reader.open(theirs.getData()); try (ByteArrayInputStream b = new ByteArrayInputStream(sep); UnionInputStream union = new UnionInputStream( lo.openStream(), b, lt.openStream())) { ObjectId noteData = inserter.insert(Constants.OBJ_BLOB, lo.getSize() + sep.length + lt.getSize(), union); return new Note(ours, noteData); } }
Source:
<code>private Set<SupportedAdditionalClusterFeature> getSupportedAdditionalClusterFeatures(Boolean enabled) { SupportedAdditionalClusterFeature clusterFeature = new SupportedAdditionalClusterFeature(); AdditionalFeature feature = new <START> AdditionalFeature(Guid.newGuid(), "libgfapi_supported", Version.v4_1, <END> null, null); clusterFeature.setFeature(feature); clusterFeature.setEnabled(enabled); return Collections.singleton(clusterFeature); }</code><technical_language>.. here</technical_language>

Target:
private Set<SupportedAdditionalClusterFeature> getSupportedAdditionalClusterFeatures(Boolean enabled) { SupportedAdditionalClusterFeature clusterFeature = new SupportedAdditionalClusterFeature(); AdditionalFeature feature = new AdditionalFeature(Guid.newGuid(), VmInfoBuildUtils.VDSM_LIBGF_CAP_NAME, Version.v4_1, null, null); clusterFeature.setFeature(feature); clusterFeature.setEnabled(enabled); return Collections.singleton(clusterFeature); }
Source:
<code>public void remove() { <START> setDead(); <END> }</code><technical_language>Is this API call implementation (native) method call</technical_language>

Target:
public void remove() { this.setDead(); }
Source:
<code>static <A extends Annotation> A getAnnotationFromClass(Class<?> clazz, Class<A> a) { try { return clazz.getAnnotation(a); } catch (Throwable t) { String msg = "Encountered problems when parsing the annotation on class " + clazz.getCanonicalName() + ". "; msg += SUFFIX; throw new TypeNotPresentException(msg, t); <START> } <END> }</code><technical_language>check if a is null getAnnotation throw NPE is related types</technical_language>

Target:
static <A extends Annotation> A getAnnotationFromClass(Class<?> clazz, Class<A> a) { Objects.requireNonNull(clazz, "Cannot retrieve annotations from a null class."); Objects.requireNonNull(a, "Cannot work with a null annotation"); try { return clazz.getAnnotation(a); } catch (Throwable t) { String msg = "Encountered problems when parsing the annotation on class " + clazz.getCanonicalName() + ". "; msg += SUFFIX; throw new TypeNotPresentException(msg, t); } }
Source:
<code>protected void updateProvidedObjectsHolder(URL url, Set<E> providedObjects) { if (providedObjects != null && !providedObjects.isEmpty()) { List<String> uids = new ArrayList<String>(); for (E providedObject : providedObjects) { String uid = getUID(providedObject); <START> E oldProvidedObject = providedObjectsHolder.get(uid); <END> uids.add(uid); providedObjectsHolder.put(uid, providedObject); notifyListeners(oldProvidedObject, providedObject); } providerPortfolio.put(url, uids); } }</code><technical_language>put method of a map returns object. calling get in front of if notify listeners put call now? Java final String uid = getUID(providedObject); uids.add(uid); final E oldProvidedObject = providedObjectsHolder.put(uid, providedObject); notifyListeners(oldProvidedObject, providedObject);</technical_language>

Target:
protected void updateProvidedObjectsHolder(URL url, Set<E> providedObjects) { if (providedObjects != null && !providedObjects.isEmpty()) { List<String> uids = new ArrayList<String>(); for (E providedObject : providedObjects) { String uid = getUID(providedObject); uids.add(uid); E oldProvidedObject = providedObjectsHolder.put(uid, providedObject); notifyListeners(oldProvidedObject, providedObject); } providerPortfolio.put(url, uids); } }
Source:
<code>public void lineGetStyle(LineStyleEvent event) { <START> List<StyleRange> styles = new ArrayList<StyleRange>(); <END> int token; StyleRange lastStyle; if (inBlockComment(event.lineOffset, event.lineOffset + event.lineText.length())) { styles.add(new StyleRange(event.lineOffset, event.lineText.length(), getColor(COMMENT), null)); event.styles = styles.toArray(new StyleRange[styles.size()]); return; } Color defaultFgColor = ((Control)event.widget).getForeground(); scanner.setRange(event.lineText); token = scanner.nextToken(); while (token != EOF) { if (token == OTHER) { } else if (token != WHITE) { Color color = getColor(token); if ((!color.equals(defaultFgColor)) || (token == KEY)) { StyleRange style = new StyleRange(scanner.getStartOffset() + event.lineOffset, scanner.getLength(), color, null); if (token == KEY) { style.fontStyle = SWT.BOLD; } if (styles.isEmpty()) { styles.add(style); } else { lastStyle = styles.get(styles.size()-1); if (lastStyle.similarTo(style) && (lastStyle.start + lastStyle.length == style.start)) { lastStyle.length += style.length; } else { styles.add(style); } } } } else if ((!styles.isEmpty()) && ((lastStyle=styles.get(styles.size()-1)).fontStyle == SWT.BOLD)) { int start = scanner.getStartOffset() + event.lineOffset; lastStyle = styles.get(styles.size() - 1); if (lastStyle.start + lastStyle.length == start) { lastStyle.length += scanner.getLength(); } } token= scanner.nextToken(); } event.styles = styles.toArray(new StyleRange[styles.size()]); }</code><technical_language>need for type</technical_language>

Target:
public void lineGetStyle(LineStyleEvent event) { List<StyleRange> styles = new ArrayList<>(); int token; StyleRange lastStyle; if (inBlockComment(event.lineOffset, event.lineOffset + event.lineText.length())) { styles.add(new StyleRange(event.lineOffset, event.lineText.length(), getColor(COMMENT), null)); event.styles = styles.toArray(new StyleRange[styles.size()]); return; } Color defaultFgColor = ((Control)event.widget).getForeground(); scanner.setRange(event.lineText); token = scanner.nextToken(); while (token != EOF) { if (token == OTHER) { } else if (token != WHITE) { Color color = getColor(token); if ((!color.equals(defaultFgColor)) || (token == KEY)) { StyleRange style = new StyleRange(scanner.getStartOffset() + event.lineOffset, scanner.getLength(), color, null); if (token == KEY) { style.fontStyle = SWT.BOLD; } if (styles.isEmpty()) { styles.add(style); } else { lastStyle = styles.get(styles.size()-1); if (lastStyle.similarTo(style) && (lastStyle.start + lastStyle.length == style.start)) { lastStyle.length += style.length; } else { styles.add(style); } } } } else if ((!styles.isEmpty()) && ((lastStyle=styles.get(styles.size()-1)).fontStyle == SWT.BOLD)) { int start = scanner.getStartOffset() + event.lineOffset; lastStyle = styles.get(styles.size() - 1); if (lastStyle.start + lastStyle.length == start) { lastStyle.length += scanner.getLength(); } } token= scanner.nextToken(); } event.styles = styles.toArray(new StyleRange[styles.size()]); }
Source:
<code>private void increaseSize(int length) { length = Math.max(length + 1, 4 * p.length); <START> <END> int pn[] = new int[length]; int qn[] = new int[length]; System.arraycopy(p, 0, pn, 0, p.length); System.arraycopy(q, 0, qn, 0, q.length); p = pn; q = qn; }</code><technical_language>remove debug statements</technical_language>

Target:
private void increaseSize(int length) { length = Math.max(length + 1, 4 * p.length); Out.debug("increasing length to " + length); int pn[] = new int[length]; int qn[] = new int[length]; System.arraycopy(p, 0, pn, 0, p.length); System.arraycopy(q, 0, qn, 0, q.length); p = pn; q = qn; }
Source:
<code>private List<String> readServersFromFile(String filename) { List<String> servers = new ArrayList<>(); if (filename == null) { return servers; } else { try { Files.readAllLines(Paths.get(filename)).stream().map(String::trim) .filter(((Predicate<String>) String::isEmpty).negate()).map(String::toLowerCase) .forEach(servers::add); } catch (IOException e) { <START> LOG.warn("Exception while reading excludes file, continuing anyways", e); <END> } return servers; } }</code><technical_language>continue if file read fails right</technical_language>

Target:
private List<String> readServersFromFile(String filename) throws IOException { List<String> servers = new ArrayList<>(); if (filename != null) { try { Files.readAllLines(Paths.get(filename)).stream().map(String::trim) .filter(((Predicate<String>) String::isEmpty).negate()).map(String::toLowerCase) .forEach(servers::add); } catch (IOException e) { LOG.error("Exception while reading servers from file,", e); throw e; } } return servers; }
Source:
<code>default Collection<T> getItems(Predicate<T> pred) { <START> List<T> filteredItems = new ArrayList<>(); <END> for (T item : getItems()) { if (pred.test(item)) { filteredItems.add(item); } } return filteredItems; }</code><technical_language>important all, stream + predicate</technical_language>

Target:
default Collection<T> getItems(Predicate<T> pred) { return getItemsStream(pred) .collect(Collectors.toList()); }
Source:
<code>private static DetailAST getParent(DetailAST commentBlock) { DetailAST result = commentBlock.getParent(); if (result == null) { result = commentBlock.getNextSibling(); } <START> final List<Integer> typesArrayList = new ArrayList<>(Arrays.asList( <END> TokenTypes.TYPE, TokenTypes.MODIFIERS, TokenTypes.ANNOTATION, TokenTypes.ANNOTATIONS, TokenTypes.ARRAY_DECLARATOR, TokenTypes.TYPE_PARAMETERS, TokenTypes.DOT)); while (true) { final int type = result.getType(); if (typesArrayList.contains(type)) { result = result.getParent(); } else if (type == TokenTypes.SINGLE_LINE_COMMENT) { result = result.getNextSibling(); } else { break; } } return result; }</code><technical_language>If this is a hardcoded list changes, please move a static final field</technical_language>

Target:
private static DetailAST getParent(DetailAST commentBlock) { DetailAST result = commentBlock.getParent(); if (result == null) { result = commentBlock.getNextSibling(); } while (true) { final int type = result.getType(); if (TYPES_HASH_SET.contains(type)) { result = result.getParent(); } else if (type == TokenTypes.SINGLE_LINE_COMMENT) { result = result.getNextSibling(); } else { break; } } return result; }
Source:
<code>private void updateLabelList() { AsyncQuery getLabelsQuery = new AsyncQuery(); getLabelsQuery.asyncCallback = new INewAsyncCallback() { @SuppressWarnings("unchecked") @Override public void onSuccess(Object model, Object result) { final List<Label> allLabels = (List<Label>) result; boolean isAnyTemplateBehavior = getBehavior().isAnyTemplateBehavior() || getBehavior().isNewTemplateBehavior(); if (getIsNew() || isAnyTemplateBehavior) { labelList.setItems(allLabels); labelList.setSelectedItems(new ArrayList<Label>()); } else { AsyncQuery getLabelsByVmIdQuery = new AsyncQuery(); getLabelsByVmIdQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { List<Label> vmLabelsList = (List<Label>) returnValue; labelList.setItems(allLabels); labelList.setSelectedItems(vmLabelsList); } }; Guid vmId = <START> ((ExistingVmModelBehavior) getBehavior()).getVm().getId(); <END> AsyncDataProvider.getInstance().getLabelListByEntityId(getLabelsByVmIdQuery, vmId); } labelList.setIsChangeable(false); } }; AsyncDataProvider.getInstance().getLabelList(getLabelsQuery); }</code><technical_language>This CCE in case of editing pools instance types</technical_language>

Target:
private void updateLabelList() { AsyncQuery getLabelsQuery = new AsyncQuery(); getLabelsQuery.asyncCallback = new INewAsyncCallback() { @SuppressWarnings("unchecked") @Override public void onSuccess(Object model, Object result) { final List<Label> allLabels = (List<Label>) result; boolean isExistingVmBehavior = getBehavior() instanceof ExistingVmModelBehavior; if (isExistingVmBehavior) { AsyncQuery getLabelsByVmIdQuery = new AsyncQuery(); getLabelsByVmIdQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { List<Label> vmLabelsList = (List<Label>) returnValue; labelList.setItems(allLabels); labelList.setSelectedItems(vmLabelsList); } }; Guid vmId = ((ExistingVmModelBehavior) getBehavior()).getVm().getId(); AsyncDataProvider.getInstance().getLabelListByEntityId(getLabelsByVmIdQuery, vmId); } else { labelList.setItems(allLabels); labelList.setSelectedItems(new ArrayList<Label>()); } labelList.setIsChangeable(false); } }; AsyncDataProvider.getInstance().getLabelList(getLabelsQuery); }
Source:
<code>public void addRecords(Map<TopicPartition, List<KafkaMessage>> records) { log.debug("Adding records to stream"); for (Map.Entry<TopicPartition, List<KafkaMessage>> entry : records.entrySet()) { for (KafkaMessage message : entry.getValue()) { <START> BlockingQueue<KafkaMessage> queue = topicQueue.get(entry.getKey().topic()); <END> if (queue != null) { queue.add(message); } } } }</code><technical_language>Minor optimization: grabbing blocking queue for a topic done in higher loop queue != null check done earlier well</technical_language>

Target:
public void addRecords(Map<TopicPartition, List<KafkaMessage>> records) { log.debug("Adding records to stream"); for (Map.Entry<TopicPartition, List<KafkaMessage>> entry : records.entrySet()) { final String topic = entry.getKey().topic(); final BlockingQueue<KafkaMessage> queue = topicQueue.get(topic); if (queue != null) { for (KafkaMessage message : entry.getValue()) { queue.add(message); } } else { log.error("Tried to add records to non-existant topic '{}'; listing records...", topic); for (KafkaMessage message : entry.getValue()) { log.error("Missed adding message on topic '{}': {}", topic, message.getMsg()); } } } }
Source:
<code>private static void validateTextSearchArgument(Object textSearch) throws QueryException { if (!(textSearch instanceof String)) { <START> throw new QueryException("$search operator expects a String"); <END> } }</code><technical_language>"expects a String" -> "requires a String operand"</technical_language>

Target:
private static void validateTextSearchArgument(Object textSearch) throws QueryException { if (!(textSearch instanceof String)) { throw new QueryException("$search operator requires a String operand"); } }
Source:
<code>public synchronized void updateQuotaCache() { if (!isCacheUpdateNeeded()) { return; } log.debug("Updating Quota Cache..."); long timeStart = System.currentTimeMillis(); List<Quota> allQuotaIncludingConsumption = getQuotaDAO().getAllQuotaIncludingConsumption(); if (allQuotaIncludingConsumption.isEmpty()) { return; } lock.writeLock().lock(); try { for (Quota quota : allQuotaIncludingConsumption) { if (!storagePoolQuotaMap.containsKey(quota.getStoragePoolId())) { storagePoolQuotaMap.put(quota.getStoragePoolId(), new HashMap<Guid,Quota>()); } storagePoolQuotaMap.get(quota.getStoragePoolId()).put(quota.getId(), quota); <START> } <END> } finally { lock.writeLock().unlock(); } long timeEnd = System.currentTimeMillis(); log.debugFormat("Quota Cache updated. ({0} msec)", timeEnd-timeStart); }</code><technical_language>construct map lock</technical_language>

Target:
public synchronized void updateQuotaCache() { if (!isCacheUpdateNeeded()) { return; } log.debug("Updating Quota Cache..."); long timeStart = System.currentTimeMillis(); List<Quota> allQuotaIncludingConsumption = getQuotaDAO().getAllQuotaIncludingConsumption(); if (allQuotaIncludingConsumption.isEmpty()) { return; } HashMap<Guid, Map<Guid, Quota>> newStoragePoolQuotaMap = new HashMap<Guid, Map<Guid, Quota>>(); for (Quota quota : allQuotaIncludingConsumption) { if (!newStoragePoolQuotaMap.containsKey(quota.getStoragePoolId())) { newStoragePoolQuotaMap.put(quota.getStoragePoolId(), new HashMap<Guid,Quota>()); } newStoragePoolQuotaMap.get(quota.getStoragePoolId()).put(quota.getId(), quota); } lock.writeLock().lock(); try { storagePoolQuotaMap = newStoragePoolQuotaMap; } finally { lock.writeLock().unlock(); } long timeEnd = System.currentTimeMillis(); log.debugFormat("Quota Cache updated. ({0} msec)", timeEnd-timeStart); }
Source:
<code>private void createSampleBoard() { logger.info("Creating " + SAMPLE_BOARD); panelControl.closeAllPanels(); List<PanelInfo> panelData = new ArrayList<>(); panelData.add(new PanelInfo(FIRST_SAMPLE_PANEL_NAME, FIRST_SAMPLE_FILTER)); panelData.add(new PanelInfo(SECOND_SAMPLE_PANEL_NAME, SECOND_SAMPLE_FILTER)); panelData.add(new PanelInfo(THIRD_SAMPLE_PANEL_NAME, THIRD_SAMPLE_FILTER)); createBoard(panelData, SAMPLE_BOARD); panelControl.selectPanel(0); triggerBoardSaveEventSequence(SAMPLE_BOARD); DialogMessage.showInformationDialog("Auto-create Board - " + SAMPLE_BOARD, SAMPLE_BOARD + " has been created and loaded.\n\n" + <START> "It is saved under the name \"" + SAMPLE_BOARD + "\"."); <END> }</code><technical_language>here, format strings</technical_language>

Target:
private void createSampleBoard() { logger.info("Creating " + SAMPLE_BOARD); panelControl.closeAllPanels(); List<PanelInfo> panelData = new ArrayList<>(); for (int i = 0; i < SAMPLE_PANEL_NAMES.size(); i++) { panelData.add(new PanelInfo(SAMPLE_PANEL_NAMES.get(i), SAMPLE_PANEL_FILTERS.get(i))); } createBoard(panelData, SAMPLE_BOARD); panelControl.selectPanel(0); triggerBoardSaveEventSequence(SAMPLE_BOARD); DialogMessage.showInformationDialog("Auto-create Board - " + SAMPLE_BOARD, SAMPLE_BOARD_DIALOG); }
Source:
<code>public void delete( Context context, Request request, Response response ) throws ResourceException { String repoId = this.getRepositoryId( request ); try { getNexus().deleteRepository( repoId ); response.setStatus( Status.SUCCESS_NO_CONTENT ); } catch ( ConfigurationException e ) { getLogger().warn( e.getMessage() ); <START> <END> throw new ResourceException( Status.CLIENT_ERROR_BAD_REQUEST, e.getMessage(), e ); } catch ( NoSuchRepositoryAccessException e ) { getLogger().warn( "Repository access denied, id=" + repoId ); throw new ResourceException( Status.CLIENT_ERROR_FORBIDDEN, "Access Denied to Repository" ); } catch ( NoSuchRepositoryException e ) { getLogger().warn( "Repository not found, id=" + repoId ); throw new ResourceException( Status.CLIENT_ERROR_NOT_FOUND, "Repository Not Found" ); } catch ( IOException e ) { getLogger().warn( "Got IO Exception!", e ); throw new ResourceException( Status.SERVER_ERROR_INTERNAL ); } catch ( AccessDeniedException e ) { getLogger().warn( "Not allowed to delete repository '" + repoId + "'", e ); throw new ResourceException( Status.CLIENT_ERROR_BAD_REQUEST, "Not allowed to delete repository '" + repoId + "'" ); } }</code><technical_language>creating a more specific ConfigurationException in this case logged INFO</technical_language>

Target:
public void delete( Context context, Request request, Response response ) throws ResourceException { String repoId = this.getRepositoryId( request ); try { getNexus().deleteRepository( repoId ); response.setStatus( Status.SUCCESS_NO_CONTENT ); } catch ( RepositoryDependentException e ) { getLogger().info( e.getMessage() ); throw new ResourceException( Status.CLIENT_ERROR_BAD_REQUEST, e.getUIMessage(), e ); } catch ( ConfigurationException e ) { getLogger().warn( e.getMessage() ); throw new ResourceException( Status.CLIENT_ERROR_BAD_REQUEST, e.getMessage(), e ); } catch ( NoSuchRepositoryAccessException e ) { getLogger().warn( "Repository access denied, id=" + repoId ); throw new ResourceException( Status.CLIENT_ERROR_FORBIDDEN, "Access Denied to Repository" ); } catch ( NoSuchRepositoryException e ) { getLogger().warn( "Repository not found, id=" + repoId ); throw new ResourceException( Status.CLIENT_ERROR_NOT_FOUND, "Repository Not Found" ); } catch ( IOException e ) { getLogger().warn( "Got IO Exception!", e ); throw new ResourceException( Status.SERVER_ERROR_INTERNAL ); } catch ( AccessDeniedException e ) { getLogger().warn( "Not allowed to delete repository '" + repoId + "'", e ); throw new ResourceException( Status.CLIENT_ERROR_BAD_REQUEST, "Not allowed to delete repository '" + repoId + "'" ); } }
Source:
<code>public <S extends Message, T extends Message> void dispatch(SinkModule<S, T> module, String topic, T message) { try (MDCCloseable mdc = Logging.withPrefixCloseable(MessageConsumerManager.LOG_PREFIX)) { LOG.trace("dispatch({}): sending message {}", topic, message); String messageId = UUID.randomUUID().toString(); byte[] messageInBytes = wrapMessageToProto(messageId, module.marshal(message)); final ProducerRecord<String,byte[]> record = new ProducerRecord<>(topic, messageId, messageInBytes); while(true) { try { final Future<RecordMetadata> future = producer.send(record); future.get(); break; } catch (InterruptedException e) { LOG.warn("Interrupted while sending message to topic {}.", topic, e); Thread.currentThread().interrupt(); break; } catch (ExecutionException e) { if (e.getCause() != null && e.getCause() instanceof TimeoutException) { <START> LOG.warn("Timeout occured while sending message to topic {}, it will be attempted again.", topic, e); <END> } else { LOG.error("Exception occured while sending message to topic ", e); break; } } } } }</code><technical_language>remove stack trace logs here, a TimeoutException, if bound a lot of these. suggestion LOG.warn("Timeout occurred while sending message topic {}, attempted again.", topic);</technical_language>

Target:
public <S extends Message, T extends Message> void dispatch(SinkModule<S, T> module, String topic, T message) { try (MDCCloseable mdc = Logging.withPrefixCloseable(MessageConsumerManager.LOG_PREFIX)) { LOG.trace("dispatch({}): sending message {}", topic, message); String messageId = UUID.randomUUID().toString(); byte[] messageInBytes = wrapMessageToProto(messageId, module.marshal(message)); final ProducerRecord<String,byte[]> record = new ProducerRecord<>(topic, messageId, messageInBytes); while(true) { try { final Future<RecordMetadata> future = producer.send(record); future.get(); break; } catch (InterruptedException e) { LOG.warn("Interrupted while sending message to topic {}.", topic, e); Thread.currentThread().interrupt(); break; } catch (ExecutionException e) { if (e.getCause() != null && e.getCause() instanceof TimeoutException) { LOG.warn("Timeout occured while sending message to topic {}, it will be attempted again.", topic); } else { LOG.error("Exception occured while sending message to topic ", e); break; } } } } }
Source:
<code>private static int cnt(int max) { <START> return Stream.range(2, max + 1) <END> .flatMap(a -> Stream.range(2, max + 1) .map(b -> BigInteger.valueOf(a).pow(b))) .distinct() .length(); }</code><technical_language>Cool, fast. I goal of 99 coming nearer :) Instead of Stream.range(2, max + 1) please Stream.rangeInclusive(2, max). canonical use-case. Thx</technical_language>

Target:
private static int cnt(int max) { return Stream.rangeClosed(2, max) .map(BigInteger::valueOf) .flatMap(a -> Stream.rangeClosed(2, max).map(a::pow)) .distinct() .length(); }
Source:
<code>protected void initializeModelHandlers(final TagListModel model) { super.initializeModelHandlers(model); model.getResetRequestedEvent().addListener(new IEventListener<EventArgs>() { @Override public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { if (model.getItems() == null) { return; } Iterator<TagModel> iterator = model.getItems().iterator(); if (iterator.hasNext()) { TagModel root = model.cloneTagModel(iterator.next()); updateDataProvider(Arrays.asList(root)); } } }); model.getPropertyChangedEvent().addListener(new IEventListener<PropertyChangedEventArgs>() { @Override public void eventRaised(Event<? extends PropertyChangedEventArgs> ev, Object sender, PropertyChangedEventArgs args) { if ("SelectedItems".equals(args.propertyName)) { <START> if (getSelectionModel().getSelectedObject() != null) { <END> TagActivatedEvent.fire(TagModelProvider.this, findRootNode(getSelectionModel().getSelectedObject())); } } } private TagModel findRootNode(TagModel tagModel) { if (tagModel.getParent() != null) { return findRootNode(tagModel.getParent()); } return tagModel; } }); }</code><technical_language>this cover case a tag selected user un-selects it? add: private final List<TagModel> activeTags = new ArrayList<>(); field, code: model.getSelectedItemsChangedEvent().addListener(new IEventListener<EventArgs>() { @Override public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { List<TagModel> selectedItems = model.getSelectedItems(); if (!activeTags.equals(selectedItems)) { // fire TagActivationChange event } activeTags.clear(); activeTags.addAll(selectedItems) } });</technical_language>

Target:
protected void initializeModelHandlers(final TagListModel model) { super.initializeModelHandlers(model); model.getResetRequestedEvent().addListener(new IEventListener<EventArgs>() { @Override public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { if (model.getItems() == null) { return; } Iterator<TagModel> iterator = model.getItems().iterator(); if (iterator.hasNext()) { TagModel root = model.cloneTagModel(iterator.next()); updateDataProvider(Arrays.asList(root)); } } }); model.getPropertyChangedEvent().addListener(new IEventListener<PropertyChangedEventArgs>() { @Override public void eventRaised(Event<? extends PropertyChangedEventArgs> ev, Object sender, PropertyChangedEventArgs args) { if ("SelectedItems".equals(args.propertyName)) { if (getSelectionModel().getSelectedObject() != null) { TagActivationChangedEvent.fire(TagModelProvider.this, findRootNode(getSelectionModel().getSelectedObject())); } } } private TagModel findRootNode(TagModel tagModel) { if (tagModel.getParent() != null) { return findRootNode(tagModel.getParent()); } return tagModel; } }); }
Source:
<code>public SubmissionResult call() { logger.info("Submitting exercise {}", exercise.getName()); informObserver(0, "Submitting exercise to server"); URI submissionUrl = tmcServerCommunicationTaskFactory.getSkillifierUrl(exercise.getName() + "/submit?username=" + TmcSettingsHolder.get().getToken().get()); logger.info("submissionurl: {}", submissionUrl.toString()); String networkResult = ""; try { networkResult = tmcServerCommunicationTaskFactory.getSubmissionFetchTask(submissionUrl).call(); logger.info("network result: {}", networkResult); } catch (Exception e) { informObserver(1, "Error while waiting for response from server"); <START> logger.warn("Error while updating adaptive submission status from server, continuing", e); <END> } Gson gson = new GsonBuilder().create(); SubmissionResult result = gson.fromJson(networkResult, AdaptiveSubmissionResult.class).toSubmissionResult(); if (!"null".equals(result.getError())) { logger.warn("submission result error: " + result.getError()); } return result; }</code><technical_language>"Continuing" sounds a bit retrying process stop, for this resolve nicely. If exception call() line 50, surely networkResult empty string (As line 48). This gson.fromJson(...) return null line 58 method return null. Is some reason pre-empt processing return null right now? E: If reading code wrong, please do correct :)</technical_language>

Target:
public SubmissionResult call() { logger.info("Submitting exercise {}", exercise.getName()); informObserver(0, "Submitting exercise to server"); URI submissionUrl = tmcServerCommunicationTaskFactory.getSkillifierUrl(exercise.getName() + "/submit?username=" + TmcSettingsHolder.get().getToken().get()); logger.info("submissionurl: {}", submissionUrl.toString()); String networkResult = ""; try { networkResult = tmcServerCommunicationTaskFactory.getSubmissionFetchTask(submissionUrl).call(); logger.info("network result: {}", networkResult); } catch (Exception e) { informObserver(1, "Error while waiting for response from server"); logger.warn("Error while updating adaptive submission status from server.", e); } Gson gson = new GsonBuilder().create(); SubmissionResult result = gson.fromJson(networkResult, AdaptiveSubmissionResult.class).toSubmissionResult(); if (!"null".equals(result.getError())) { logger.warn("Submission result error: " + result.getError()); } return result; }
Source:
<code>protected void createPreparedStatement(Connection db) throws SQLException { String quoteString = JdbcUtils.getIdentifierQuoteString(db); <START> stmt = db.prepareStatement("SELECT * FROM " + quoteString + name + quoteString); <END> }</code><technical_language>this 100% work. Table name "mytable" in case quoting is fine, "myschema.mytable" is quoted "myschema"."mytable"</technical_language>

Target:
protected void createPreparedStatement(Connection db) throws SQLException { String quoteString = JdbcUtils.getIdentifierQuoteString(db); stmt = db.prepareStatement("SELECT * FROM " + JdbcUtils.quoteString(name, quoteString)); }
Source:
<code>public void testLargeGeometryToBingTiles() throws Exception { Path filePath = Paths.get(this.getClass().getClassLoader().getResource("large_polygon.txt").getPath()); <START> List<String> lines = Files.lines(filePath).collect(Collectors.toList()); <END> for (String line : lines) { String[] parts = line.split("\\|"); String wkt = parts[0]; int zoomLevel = Integer.parseInt(parts[1]); long tileCount = Long.parseLong(parts[2]); assertFunction("cardinality(geometry_to_bing_tiles(ST_GeometryFromText('" + wkt + "'), " + zoomLevel + "))", BIGINT, tileCount); } }</code><technical_language>List<String> lines = Files.readAllLines(filePath);</technical_language>

Target:
public void testLargeGeometryToBingTiles() throws Exception { Path filePath = Paths.get(this.getClass().getClassLoader().getResource("large_polygon.txt").getPath()); List<String> lines = Files.readAllLines(filePath); for (String line : lines) { String[] parts = line.split("\\|"); String wkt = parts[0]; int zoomLevel = Integer.parseInt(parts[1]); long tileCount = Long.parseLong(parts[2]); assertFunction("cardinality(geometry_to_bing_tiles(ST_GeometryFromText('" + wkt + "'), " + zoomLevel + "))", BIGINT, tileCount); } }
Source:
<code>protected boolean checkExistingStorageDomain() { if (DbFacade.getInstance().getStorageDomainStaticDao().get(getStorageDomain().getId()) != null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_NOT_EXIST); } <START> Pair<StorageDomainStatic, Guid> domainFromIrs = (Pair<StorageDomainStatic, Guid>) runVdsCommand( <END> VDSCommandType.HSMGetStorageDomainInfo, new HSMGetStorageDomainInfoVDSCommandParameters(getVdsId(), getStorageDomain().getId()) ).getReturnValue(); if (domainFromIrs == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_NOT_EXIST); } return concreteCheckExistingStorageDomain(domainFromIrs); }</code><technical_language>Please executeHSMGetStorageDomainInfo - added in place</technical_language>

Target:
protected boolean checkExistingStorageDomain() { if (DbFacade.getInstance().getStorageDomainStaticDao().get(getStorageDomain().getId()) != null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_NOT_EXIST); } Pair<StorageDomainStatic, Guid> domainFromIrs = executeHSMGetStorageDomainInfo(new HSMGetStorageDomainInfoVDSCommandParameters(getVdsId(), getStorageDomain().getId()); if (domainFromIrs == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_NOT_EXIST); } return concreteCheckExistingStorageDomain(domainFromIrs); }
Source:
<code>public static void setSerializationStrategy(SerializationStrategy serializationStrategy) { <START> if (serializationStrategy == null) { <END> throw new IllegalArgumentException("Serialization strategy can't be null"); } strategy = serializationStrategy; }</code><technical_language>Assert.notNull()</technical_language>

Target:
public static void setSerializationStrategy(SerializationStrategy serializationStrategy) { Assert.notNull(serializationStrategy, "Serialization strategy can't be null"); strategy = serializationStrategy; }
Source:
<code>beginRecognizeReceipts(Flux<ByteBuffer> receipt, long length, RecognizeOptions recognizeOptions) { try { Objects.requireNonNull(receipt, "'receipt' is required and cannot be null."); recognizeOptions = getRecognizeOptionsProperties(recognizeOptions); final boolean isIncludeFieldElements = recognizeOptions.isIncludeFieldElements(); return new PollerFlux<>( recognizeOptions.getPollInterval(), streamActivationOperation( (contentType -> service.analyzeReceiptAsyncWithResponseAsync( contentType, receipt, length, isIncludeFieldElements).map(response -> new OperationResult( parseModelId(response.getDeserializedHeaders().getOperationLocation())))), receipt, recognizeOptions.getContentType()), pollingOperation(service::getAnalyzeReceiptResultWithResponseAsync), (activationResponse, context) -> monoError(logger, new RuntimeException("Cancellation is not supported")), fetchingOperation(service::getAnalyzeReceiptResultWithResponseAsync) .andThen(after -> after.map(modelSimpleResponse -> { <START> throwIfAnalyzeStatusInvalid(modelSimpleResponse.getValue()); <END> return toRecognizedForm(modelSimpleResponse.getValue().getAnalyzeResult(), isIncludeFieldElements); }).onErrorMap(Utility::mapToHttpResponseExceptionIfExist))); } catch (RuntimeException ex) { return PollerFlux.error(ex); } }</code><technical_language>Throwing exception a map operator is odd. In this case, handle() operator sink.error() sink.next() depending response is error success</technical_language>

Target:
beginRecognizeReceipts(Flux<ByteBuffer> receipt, long length, RecognizeOptions recognizeOptions) { return beginRecognizeReceipts(receipt, length, recognizeOptions, Context.NONE); }
Source:
<code>public void setAnalysisCache(final AnalysisCache cache) { if (cache == null && isAnalysisCacheFunctional()) { analysisCache = new NoopAnalysisCache(); if (!isIgnoreIncrementalAnalysis() && LOG.isLoggable(Level.WARNING)) { final String version = PMDVersion.isUnknown() || PMDVersion.isSnapshot() ? "latest" : "pmd-" + PMDVersion.VERSION; <START> LOG.warning("This analysis could be faster, please consider using Incremental Analysis: " <END> + "<LINK_0>" + version + "/pmd_userdocs_getting_started.html#incremental-analysis"); } } else if (!isIgnoreIncrementalAnalysis()) { analysisCache = cache; } }</code><technical_language>I find unintuitive find this here... suggest moving log PMD.doPMD, is guaranteed run a more natural</technical_language>

Target:
public void setAnalysisCache(final AnalysisCache cache) { this.analysisCache = cache == null ? new NoopAnalysisCache() : cache; }
Source:
<code>public Response getPaymentEvents(@ApiParam(value = "accountId", hidden = true) @Auth Account account, @PathParam("paymentId") String paymentId) { logger.info("Payment events request - payment_id={}", paymentId); String url = account.getPaymentType().equals(DIRECT_DEBIT) ? connectorDDUrl : connectorUrl; UriBuilder builder = UriBuilder .fromPath(url) .path(format("/v1/api/accounts/%s/charges/%s/events", account.getAccountId(), paymentId)); <START> Collections.<Pair<String, String>>emptyList().stream().forEach(pair -> { <END> if (isNotBlank(pair.getRight())) { builder.queryParam(pair.getKey(), pair.getValue()); } }); Response connectorResponse = client .target(builder.toString()) .request() .get(); if (connectorResponse.getStatus() == SC_OK) { JsonNode payload = connectorResponse.readEntity(JsonNode.class); URI paymentEventsLink = publicApiUriGenerator.getPaymentEventsURI(baseUrl, payload.get("charge_id").asText()); URI paymentLink = publicApiUriGenerator.getPaymentURI(baseUrl, payload.get("charge_id").asText()); PaymentEvents response = PaymentEvents.createPaymentEventsResponse(payload, paymentLink.toString()) .withSelfLink(paymentEventsLink.toString()); logger.info("Payment events returned - [ ]", response); return Response.ok(response).build(); } throw new GetEventsException(connectorResponse); }</code><technical_language>streaming empty list</technical_language>

Target:
public Response getPaymentEvents(@ApiParam(value = "accountId", hidden = true) @Auth Account account, @PathParam("paymentId") String paymentId) { logger.info("Payment events request - payment_id={}", paymentId); Response connectorResponse = client .target(connectorUriGenerator.chargeEventsURI(account, paymentId)) .request() .get(); if (connectorResponse.getStatus() == SC_OK) { JsonNode payload = connectorResponse.readEntity(JsonNode.class); URI paymentEventsLink = publicApiUriGenerator.getPaymentEventsURI(payload.get("charge_id").asText()); URI paymentLink = publicApiUriGenerator.getPaymentURI(payload.get("charge_id").asText()); PaymentEvents response = PaymentEvents.createPaymentEventsResponse(payload, paymentLink.toString()) .withSelfLink(paymentEventsLink.toString()); logger.info("Payment events returned - [ ]", response); return Response.ok(response).build(); } throw new GetEventsException(connectorResponse); }