auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void flushFailedActions() { if (!failedActions.isEmpty()) { Iterator<Action> iterator = failedActions.values().iterator(); while (iterator.hasNext()) { Action action = iterator.next(); iterator.remove(); performSubmit(action); if (action.getPicasso().loggingEnabled) { log(OWNER_DISPATCHER, VERB_REPLAYED, action.getRequest().logId()); } } } }

Target:
private void flushFailedActions() { if (!failedActions.isEmpty()) { Iterator<Action> iterator = failedActions.values().iterator(); while (iterator.hasNext()) { Action action = iterator.next(); iterator.remove(); if (action.getPicasso().loggingEnabled) { log(OWNER_DISPATCHER, VERB_REPLAYING, action.getRequest().logId()); } performSubmit(action); } } }
Source:
public void handleContentRecovery(SPath path, byte[] content, String encoding, User source) { VirtualFile virtualFile = VirtualFileConverter.convertToVirtualFile(path); if (virtualFile == null) { return; } Document document = projectAPI.getDocument(virtualFile); if (document == null) { return; } int documentLength = document.getTextLength(); IFile file = path.getFile(); annotationManager.removeAnnotations(file); String text; try { text = new String(content, encoding); } catch (UnsupportedEncodingException e) { LOG.warn("Could not decode text using given encoding. Using default instead.", e); text = new String(content); } boolean wasReadOnly = !document.isWritable(); boolean wasDocumentListenerEnabled = manager.isDocumentListenerEnabled(); try { if (wasReadOnly) { document.setReadOnly(false); } if (wasDocumentListenerEnabled) { manager.disableDocumentListener(); } editorAPI.deleteText(document, 0, documentLength); editorAPI.insertText(document, 0, text); } finally { if (wasDocumentListenerEnabled) { manager.enableDocumentListener(); } if (wasReadOnly) { document.setReadOnly(true); } } Editor editor = null; if (projectAPI.isOpen(virtualFile)) { editor = projectAPI.openEditor(virtualFile, false); } annotationManager.addContributionAnnotation(source, file, 0, documentLength, editor); }

Target:
public void handleContentRecovery(SPath path, byte[] content, String encoding, User source) { VirtualFile virtualFile = VirtualFileConverter.convertToVirtualFile(path); if (virtualFile == null) { LOG.warn( "Could not recover file content of " + path + " as it could not be converted to a VirtualFile."); return; } Document document = projectAPI.getDocument(virtualFile); if (document == null) { LOG.warn( "Could not recover file content of " + path + " as no valid Document representation was returned by the IntelliJ API."); return; } int documentLength = document.getTextLength(); IFile file = path.getFile(); annotationManager.removeAnnotations(file); String text; try { text = new String(content, encoding); } catch (UnsupportedEncodingException e) { LOG.warn("Could not decode text using given encoding. Using default instead.", e); text = new String(content); NotificationPanel.showWarning( String.format( Messages.LocalEditorManipulator_incompatible_encoding_message, file.getLocation(), encoding, Charset.defaultCharset()), Messages.LocalEditorManipulator_incompatible_encoding_title); } boolean wasReadOnly = !document.isWritable(); boolean wasDocumentListenerEnabled = manager.isDocumentListenerEnabled(); try { if (wasReadOnly) { document.setReadOnly(false); } if (wasDocumentListenerEnabled) { manager.disableDocumentListener(); } editorAPI.deleteText(document, 0, documentLength); editorAPI.insertText(document, 0, text); } finally { if (wasDocumentListenerEnabled) { manager.enableDocumentListener(); } if (wasReadOnly) { document.setReadOnly(true); } } Editor editor = null; if (projectAPI.isOpen(virtualFile)) { editor = projectAPI.openEditor(virtualFile, false); } annotationManager.addContributionAnnotation(source, file, 0, documentLength, editor); }
Source:
static JiraRestClient createJiraClient() throws IOException { ConnectionInfo con = new ConnectionInfo(); final URI uri; try { uri = new URI(IrcBotConfig.JIRA_URL); } catch(URISyntaxException ex) { throw new IOException("Cannot create JIRA URI from string " + IrcBotConfig.JIRA_URL, ex); } JiraRestClient client = new AsynchronousJiraRestClientFactory().createWithBasicHttpAuthentication( uri, con.userName, con.password); return client; }

Target:
static JiraRestClient createJiraClient() throws IOException { ConnectionInfo con = new ConnectionInfo(); JiraRestClient client = new AsynchronousJiraRestClientFactory().createWithBasicHttpAuthentication( IrcBotConfig.JIRA_URI, con.userName, con.password); return client; }
Source:
private static String buildMessage(InetSocketAddress address, int queueSize) { return String.format("[%s] Pool is busy (no available connection and the queue has reached its max size %d", address.getAddress(), queueSize); }

Target:
private static String buildMessage(InetSocketAddress address, int queueSize) { return String.format("[%s] Pool is busy (no available connection and the queue has reached its max size %d)", address.getAddress(), queueSize); }
Source:
private String retrieveAuthToken(HttpClient client, String details) throws Exception { if(StringUtils.isNotBlank(details)) { Map<String, String> auth = parseAuthDetails(details); if(auth.containsKey(REALM)) { Request request = client.newRequest(StringUtils.strip(auth.get(REALM),"\"")); for (Entry<String, String> e: auth.entrySet()) { if(!REALM.equals(e.getKey())) { request.param(StringUtils.strip(e.getKey(),"\""), StringUtils.strip(e.getValue(),"\"")); } } LOG.debug("Auth request uri: " + request.getURI()); ContentResponse response = request.send(); LOG.debug("Auth response: " + response.toString()); if(response.getStatus() == STATUS_OK && response.getHeaders().contains(PROPERTY_CONTENT_TYPE,MEDIATYPE_APPLICATION_JSON)) { ModelNode tokenNode = ModelNode.fromJSONString(response.getContentAsString()); if(tokenNode.hasDefined("token")) { return tokenNode.get("token").asString(); }else { LOG.debug("No auth token was found on auth response: " + tokenNode.toJSONString(false)); } } else { LOG.info("Unable to retrieve authentication token from as response was not OK or unexpected content type"); } }else { LOG.info("Unable to retrieve authentication token - realm was not found in the authenticate header: " + auth.toString()); } } return null; }

Target:
private String retrieveAuthToken(HttpClient client, String details) throws Exception { if(StringUtils.isNotBlank(details)) { Map<String, String> auth = parseAuthDetails(details); if(auth.containsKey(REALM)) { Request request = createAuthRequest(client, auth); ContentResponse response = request.send(); LOG.debug("Auth response: " + response.toString()); if(response.getStatus() == STATUS_OK && response.getHeaders().contains(PROPERTY_CONTENT_TYPE, MEDIATYPE_APPLICATION_JSON)) { ModelNode tokenNode = ModelNode.fromJSONString(response.getContentAsString()); if(tokenNode.hasDefined(TOKEN)) { return tokenNode.get(TOKEN).asString(); }else { LOG.debug("No auth token was found on auth response: " + tokenNode.toJSONString(false)); } } else { LOG.info("Unable to retrieve authentication token as response was not OK and/or unexpected content type"); } }else { LOG.info("Unable to retrieve authentication token - 'realm' was not found in the authenticate header: " + auth.toString()); } } return null; }
Source:
public static <T> AnnotatedHandlerInspector<T> inspectType(Class<? extends T> handlerType, ParameterResolverFactory parameterResolverFactory) { return inspectType(handlerType, parameterResolverFactory, new ClasspathHandlerDefinition(Thread.currentThread().getContextClassLoader())); }

Target:
public static <T> AnnotatedHandlerInspector<T> inspectType(Class<? extends T> handlerType, ParameterResolverFactory parameterResolverFactory) { return inspectType(handlerType, parameterResolverFactory, ClasspathHandlerDefinition.forClass(handlerType)); }
Source:
private void setupTestsConfiguration() { System.setProperty(TestConfigurationFactory.TEST_CONFIGURATION_URI_KEY, options.getConfigFile()); System.setProperty(TestConfigurationFactory.LOCAL_TEST_CONFIGURATION_URI_KEY, options.getConfigFileLocal()); }

Target:
private void setupTestsConfiguration() { System.setProperty(TEST_CONFIGURATION_URI_KEY, options.getConfigFile()); System.setProperty(LOCAL_TEST_CONFIGURATION_URI_KEY, options.getConfigFileLocal()); }
Source:
public static Optional<MediaType> getMediaType(ExampleObject example) { if (example == null) { return Optional.empty(); } MediaType mediaType = new MediaType(); Example exampleObject = new Example(); exampleObject.setDescription(example.name()); exampleObject.setSummary(example.summary()); exampleObject.setExternalValue(example.externalValue()); exampleObject.setValue(example.value()); mediaType.addExamples(example.name(), exampleObject); return Optional.of(mediaType); }

Target:
public static Optional<MediaType> getMediaType(ExampleObject example) { if (example == null) { return Optional.empty(); } if (StringUtils.isNotBlank(example.name())) { MediaType mediaType = new MediaType(); Example exampleObject = new Example(); if (StringUtils.isNotBlank(example.name())) { exampleObject.setDescription(example.name()); } if (StringUtils.isNotBlank(example.summary())) { exampleObject.setSummary(example.summary()); } if (StringUtils.isNotBlank(example.externalValue())) { exampleObject.setExternalValue(example.externalValue()); } if (StringUtils.isNotBlank(example.value())) { exampleObject.setValue(example.value()); } mediaType.addExamples(example.name(), exampleObject); return Optional.of(mediaType); } return Optional.empty(); }
Source:
public void changesVisibility() throws IOException { final AwsAttributes attr = new AwsAttributes(); attr.show(true); MatcherAssert.assertThat(attr.visible(), Matchers.equalTo(true)); attr.show(false); MatcherAssert.assertThat(attr.visible(), Matchers.equalTo(false)); }

Target:
public void changesVisibility() throws Exception { final AwsAttributes attr = new AwsAttributes(); attr.show(true); MatcherAssert.assertThat(attr.visible(), Matchers.equalTo(true)); attr.show(false); MatcherAssert.assertThat(attr.visible(), Matchers.equalTo(false)); }
Source:
public void setBootSequence(BootSequence value) { ArrayList<BootSequence> items = new ArrayList<BootSequence>(); for (char a : value.toString().toCharArray()) { items.add(BootSequence.valueOf((Character.valueOf(a)).toString())); } Object firstBootDevice = null; for (Object item : getFirstBootDevice().getItems()) { EntityModel a = (EntityModel) item; if ((BootSequence) a.getEntity() == Linq.FirstOrDefault(items)) { firstBootDevice = a; } } getFirstBootDevice().setSelectedItem(firstBootDevice); ArrayList<EntityModel> secondDeviceOptions = Linq.<EntityModel> Cast(getSecondBootDevice().getItems()); if (items.size() > 1) { BootSequence last = items.get(items.size() - 1); for (EntityModel a : secondDeviceOptions) { if (a.getEntity() != null && (BootSequence) a.getEntity() == last) { getSecondBootDevice().setSelectedItem(a); break; } } } else { for (EntityModel a : secondDeviceOptions) { if (a.getEntity() == null) { getSecondBootDevice().setSelectedItem(a); break; } } } }

Target:
public void setBootSequence(BootSequence value) { ArrayList<BootSequence> items = new ArrayList<BootSequence>(); for (char a : value.toString().toCharArray()) { items.add(BootSequence.valueOf(String.valueOf(a))); } Object firstBootDevice = null; for (Object item : getFirstBootDevice().getItems()) { EntityModel a = (EntityModel) item; if ((BootSequence) a.getEntity() == Linq.FirstOrDefault(items)) { firstBootDevice = a; } } getFirstBootDevice().setSelectedItem(firstBootDevice); ArrayList<EntityModel> secondDeviceOptions = Linq.<EntityModel> Cast(getSecondBootDevice().getItems()); if (items.size() > 1) { BootSequence last = items.get(items.size() - 1); for (EntityModel a : secondDeviceOptions) { if (a.getEntity() != null && (BootSequence) a.getEntity() == last) { getSecondBootDevice().setSelectedItem(a); break; } } } else { for (EntityModel a : secondDeviceOptions) { if (a.getEntity() == null) { getSecondBootDevice().setSelectedItem(a); break; } } } }
Source:
private Map<Guid, BrickProperties> getBrickPropertiesMap(GlusterVolumeAdvancedDetails volumeDetails) { Map<Guid, BrickProperties> brickStatusMap = new HashMap<Guid, BrickProperties>(); for (BrickDetails brickDetails : volumeDetails.getBrickDetails()) { brickStatusMap.put(brickDetails.getBrickProperties().getBrickId(), brickDetails.getBrickProperties()); } return brickStatusMap; }

Target:
private Map<Guid, BrickProperties> getBrickPropertiesMap(GlusterVolumeAdvancedDetails volumeDetails) { Map<Guid, BrickProperties> brickStatusMap = new HashMap<Guid, BrickProperties>(); for (BrickDetails brickDetails : volumeDetails.getBrickDetails()) { if (brickDetails.getBrickProperties().getBrickId() != null) { brickStatusMap.put(brickDetails.getBrickProperties().getBrickId(), brickDetails.getBrickProperties()); } } return brickStatusMap; }
Source:
static void factorNormalize(final RealMatrix input, final double[] targetFactors) { Utils.nonNull(input, "Input matrix cannot be null."); Utils.nonNull(targetFactors, "Target factors cannot be null."); if (targetFactors.length != input.getRowDimension()) { throw new GATKException("Number of target factors does not correspond to the number of rows."); } input.walkInOptimizedOrder(new DefaultRealMatrixChangingVisitor() { @Override public double visit(final int row, final int column, final double value) { return value / targetFactors[row]; } }); }

Target:
static void factorNormalize(final RealMatrix input, final double[] targetFactors) { Utils.nonNull(input, "Input matrix cannot be null."); Utils.nonNull(targetFactors, "Target factors cannot be null."); Utils.validateArg(targetFactors.length == input.getRowDimension(), "Number of target factors does not correspond to the number of rows."); input.walkInOptimizedOrder(new DefaultRealMatrixChangingVisitor() { @Override public double visit(final int row, final int column, final double value) { return value / targetFactors[row]; } }); }
Source:
private void processUnclosedSymbolicValue(ExplodedGraph.Node node, SymbolicValue sv) { List<JavaFileScannerContext.Location> flow = SECheck.flow(node, sv); flow.stream() .filter(loc -> loc.syntaxNode.is(Tree.Kind.NEW_CLASS) || loc.syntaxNode.is(Tree.Kind.METHOD_INVOCATION)) .forEach(loc -> reportIssue(loc.syntaxNode, String.format("Close this \"%s\".", name(loc.syntaxNode)), ImmutableSet.of(flow))); }

Target:
private void processUnclosedSymbolicValue(ExplodedGraph.Node node, SymbolicValue sv) { List<JavaFileScannerContext.Location> flow = SECheck.flow(node, sv, constraint -> constraint instanceof ObjectConstraint && ((ObjectConstraint) constraint).hasStatus(Status.OPENED)); flow.stream() .filter(loc -> loc.syntaxNode.is(Tree.Kind.NEW_CLASS, Tree.Kind.METHOD_INVOCATION)) .forEach(loc -> reportIssue(loc.syntaxNode, String.format("Close this \"%s\".", name(loc.syntaxNode)), Collections.emptySet())); }
Source:
public void close() throws Exception { scheduledExecutorService.shutdown(); }

Target:
public void close() throws Exception { scheduledExecutorService.shutdown(); scheduledExecutorService.awaitTermination(6000, TimeUnit.MILLISECONDS); }
Source:
public void processSourceCode(Reader sourceCode, RuleSets ruleSets, RuleContext ctx) throws PMDException { determineLanguage(ctx); Initializer.initialize(); if (ruleSets.applies(ctx.getSourceCodeFile())) { if (!configuration.isAutoFixes() && isCacheUpToDate(ctx)) { for (final RuleViolation rv : getCachedViolationsForFile(ctx.getSourceCodeFile())) { ctx.getReport().addRuleViolation(rv); } return; } try { ruleSets.start(ctx); processSource(sourceCode, ruleSets, ctx); } catch (final ParseException pe) { configuration.getAnalysisCache().analysisFailed(ctx.getSourceCodeFile()); throw new PMDException("Error while parsing " + ctx.getSourceCodeFilename(), pe); } catch (final Exception e) { configuration.getAnalysisCache().analysisFailed(ctx.getSourceCodeFile()); throw new PMDException("Error while processing " + ctx.getSourceCodeFilename(), e); } finally { ruleSets.end(ctx); } } }

Target:
public void processSourceCode(Reader sourceCode, RuleSets ruleSets, RuleContext ctx) throws PMDException { determineLanguage(ctx); Initializer.initialize(); if (ruleSets.applies(ctx.getSourceCodeFile())) { if (!configuration.isAutoFixes() && configuration.getAnalysisCache().isUpToDate(ctx.getSourceCodeFile())) { for (final RuleViolation rv : configuration.getAnalysisCache().getCachedViolations(ctx.getSourceCodeFile())) { ctx.getReport().addRuleViolation(rv); } return; } try { ruleSets.start(ctx); processSource(sourceCode, ruleSets, ctx); } catch (final ParseException pe) { configuration.getAnalysisCache().analysisFailed(ctx.getSourceCodeFile()); throw new PMDException("Error while parsing " + ctx.getSourceCodeFilename(), pe); } catch (final Exception e) { configuration.getAnalysisCache().analysisFailed(ctx.getSourceCodeFile()); throw new PMDException("Error while processing " + ctx.getSourceCodeFilename(), e); } finally { ruleSets.end(ctx); } } }
Source:
public Boolean visitGroupingOperation(GroupingOperation node, Void context) { if (orderByScope.isPresent()) { node.getGroupingColumns().forEach(groupingColumn -> verifyNoOrderByReferencesToOutputColumns( groupingColumn, REFERENCE_TO_OUTPUT_ATTRIBUTE_WITHIN_ORDER_BY_GROUPING, "Invalid reference to output projection attribute from ORDER BY grouping" )); } Optional<Expression> argumentNotInGroupBy = node.getGroupingColumns().stream() .filter(argument -> !columnReferences.containsKey(argument) || !isGroupingKey(argument)) .findAny(); if (argumentNotInGroupBy.isPresent()) { throw new SemanticException( INVALID_PROCEDURE_ARGUMENTS, node, "The arguments to GROUPING() must be expressions referenced by the GROUP BY at the associated query level. Mismatch due to %s.", argumentNotInGroupBy.get() ); } return true; }

Target:
public Boolean visitGroupingOperation(GroupingOperation node, Void context) { if (orderByScope.isPresent()) { node.getGroupingColumns().forEach(groupingColumn -> verifyNoOrderByReferencesToOutputColumns( groupingColumn, REFERENCE_TO_OUTPUT_ATTRIBUTE_WITHIN_ORDER_BY_GROUPING, "Invalid reference to output of SELECT clause from grouping() expression in ORDER BY" )); } Optional<Expression> argumentNotInGroupBy = node.getGroupingColumns().stream() .filter(argument -> !columnReferences.containsKey(argument) || !isGroupingKey(argument)) .findAny(); if (argumentNotInGroupBy.isPresent()) { throw new SemanticException( INVALID_PROCEDURE_ARGUMENTS, node, "The arguments to GROUPING() must be expressions referenced by the GROUP BY at the associated query level. Mismatch due to %s.", argumentNotInGroupBy.get() ); } return true; }
Source:
public void obtain_LocalTime_using_hours_minutes_seconds_millis_nanos() { final int hours = 5; final int minutes = 31; final int seconds = 25; final int millis = 125; final long nanos = 2356L; final LocalTime localTime = LocalTimes.of(5, 31, 25, 125, 2356L); final Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR, hours); calendar.set(Calendar.MINUTE, minutes); calendar.set(Calendar.SECOND, seconds); calendar.set(Calendar.MILLISECOND, millis); assertEquals(calendar.get(Calendar.HOUR), localTime.getHours()); assertEquals(calendar.get(Calendar.MINUTE), localTime.getMinutes()); assertEquals(calendar.get(Calendar.SECOND), localTime.getSeconds()); assertEquals(calendar.get(Calendar.MILLISECOND), localTime.getMillis()); assertEquals(nanos, localTime.getNanos()); }

Target:
public void obtain_LocalTime_using_hours_minutes_seconds_millis_nanos() { final LocalTime localTime = LocalTimes.of(hours, minutes, seconds, millis, nanos); assertTrue(hours == localTime.getHours()); assertTrue(minutes == localTime.getMinutes()); assertTrue(seconds == localTime.getSeconds()); assertTrue(millis == localTime.getMillis()); assertTrue(nanos == localTime.getNanos()); }
Source:
public void testParseIntGarbage() throws EvaluationException { try { PARSE_INTEGER.evaluate(s("garbage")); } catch (EvaluationException e){ assertThat("parse_Integer(\"garbage\") throws", true, instanceOf(Boolean.class)); } }

Target:
public void testParseIntGarbage() throws EvaluationException { PARSE_INTEGER.evaluate(s("garbage")); }
Source:
public Analyzer getBean(Map<String, String> initProperties, String fullPrefix, SenseiPluginRegistry pluginRegistry) { Version matchVersion = Version.valueOf(MapUtils.getString(initProperties, "matchVersion", "LUCENE_35")); Pattern pattern = Pattern.compile(MapUtils.getString(initProperties, "pattern", " +")); boolean toLowerCase = MapUtils.getBoolean(initProperties, "toLowerCase", true); String stopWordsStr = MapUtils.getString(initProperties, "stopWords", ""); Set<String> stopWords = new HashSet<String>(Arrays.asList(stopWordsStr.split(" *, *"))); return new PatternAnalyzer(matchVersion, pattern, toLowerCase, stopWords); }

Target:
public Analyzer getBean(Map<String, String> initProperties, String fullPrefix, SenseiPluginRegistry pluginRegistry) { Version matchVersion = Version.valueOf(MapUtils.getString(initProperties, "matchVersion", "LUCENE_35")); Pattern pattern = Pattern.compile(MapUtils.getString(initProperties, "pattern", "\\s+")); boolean toLowerCase = MapUtils.getBoolean(initProperties, "toLowerCase", true); String stopWordsStr = MapUtils.getString(initProperties, "stopWords", ""); Set<String> stopWords = new HashSet<String>(Arrays.asList(stopWordsStr.split("\\s*,\\s*"))); return new PatternAnalyzer(matchVersion, pattern, toLowerCase, stopWords); }
Source:
public void testCloneNote() throws IOException, CloneNotSupportedException, InterruptedException, InterpreterException, SchedulerException, RepositoryException { Note note = notebook.createNote(null); factory.setInterpreters(note.getId(), factory.getDefaultInterpreterSettingList()); final Paragraph p = note.addParagraph(); p.setText("hello world"); note.runAll(); while(p.isTerminated()==false || p.getResult()==null) Thread.yield(); p.setStatus(Status.RUNNING); Note cloneNote = notebook.cloneNote(note.getId(), "clone note", null); Paragraph cp = cloneNote.paragraphs.get(0); assertEquals(cp.getStatus(), Status.READY); assertEquals(cp.getId(), p.getId()); assertEquals(cp.text, p.text); assertEquals(cp.getResult().message(), p.getResult().message()); AuthenticationInfo subject = new AuthenticationInfo("user1"); Note cloneNote2 = notebook.cloneNote(note.getId(), "clone note2", subject); Notebook notebook = new Notebook( conf, notebookRepo, schedulerFactory, new InterpreterFactory(conf, null, null, null, depResolver), this, null, notebookAuthorization, null); assertNotNull(notebook.getNotebookAuthorization().getOwners(cloneNote2.getId())); assertEquals(1, notebook.getNotebookAuthorization().getOwners(cloneNote2.getId()).size()); Set<String> owners = new HashSet<>(); owners.add("user1"); assertEquals(owners, notebook.getNotebookAuthorization().getOwners(cloneNote2.getId())); }

Target:
public void testCloneNote() throws IOException, CloneNotSupportedException, InterruptedException, InterpreterException, SchedulerException, RepositoryException { Note note = notebook.createNote(null); factory.setInterpreters(note.getId(), factory.getDefaultInterpreterSettingList()); final Paragraph p = note.addParagraph(); p.setText("hello world"); note.runAll(); while(p.isTerminated()==false || p.getResult()==null) Thread.yield(); p.setStatus(Status.RUNNING); Note cloneNote = notebook.cloneNote(note.getId(), "clone note", null); Paragraph cp = cloneNote.paragraphs.get(0); assertEquals(cp.getStatus(), Status.READY); assertEquals(cp.getId(), p.getId()); assertEquals(cp.text, p.text); assertEquals(cp.getResult().message(), p.getResult().message()); AuthenticationInfo subject = new AuthenticationInfo("user1"); Note cloneNote2 = notebook.cloneNote(note.getId(), "clone note2", subject); assertNotNull(notebook.getNotebookAuthorization().getOwners(cloneNote2.getId())); assertEquals(1, notebook.getNotebookAuthorization().getOwners(cloneNote2.getId()).size()); Set<String> owners = new HashSet<>(); owners.add("user1"); assertEquals(owners, notebook.getNotebookAuthorization().getOwners(cloneNote2.getId())); }
Source:
private DescribeConfigsResponse describeConfigsResponse(ApiError error, NewTopic... topics) { if (error == null) error = new ApiError(Errors.NONE, ""); List<DescribeConfigsResponseData.DescribeConfigsResult> results = new ArrayList<>(); for (NewTopic topic : topics) { results.add(new DescribeConfigsResponseData.DescribeConfigsResult() .setErrorCode(error.error().code()) .setErrorMessage(error.message()) .setResourceType(ConfigResource.Type.TOPIC.id()) .setResourceName(topic.name()) .setConfigs(topic.configs().entrySet().stream().map(e -> new DescribeConfigsResponseData.DescribeConfigsResourceResult() .setName(e.getKey()) .setValue(e.getValue())).collect(Collectors.toList()))); } return new DescribeConfigsResponse(new DescribeConfigsResponseData() .setThrottleTimeMs(1000) .setResults(results)); }

Target:
private DescribeConfigsResponse describeConfigsResponse(ApiError error, NewTopic... topics) { List<DescribeConfigsResponseData.DescribeConfigsResult> results = Stream.of(topics) .map(topic -> new DescribeConfigsResponseData.DescribeConfigsResult() .setErrorCode(error.error().code()) .setErrorMessage(error.message()) .setResourceType(ConfigResource.Type.TOPIC.id()) .setResourceName(topic.name()) .setConfigs(topic.configs().entrySet() .stream() .map(e -> new DescribeConfigsResponseData.DescribeConfigsResourceResult() .setName(e.getKey()) .setValue(e.getValue())) .collect(Collectors.toList()))) .collect(Collectors.toList()); return new DescribeConfigsResponse(new DescribeConfigsResponseData().setThrottleTimeMs(1000).setResults(results)); }
Source:
public ExtensionRuleConfig() { super(); initialize(); }

Target:
public ExtensionRuleConfig() { super(NAME); }
Source:
private SolrInputDocument toDoc(Question q) { List<String> tagNames = Lists.transform(q.getTags(), new Function<Tag, String>() { @Nullable @Override public String apply(@Nullable Tag tag) { return tag.getName(); } }); SolrInputDocument doc = new SolrInputDocument(); doc.addField("id", q.getId()); doc.addField("title", q.getTitle()); doc.addField("description", q.getMarkedDescription()); doc.addField("tags", tagNames.toString().replace("[", "").replace("]", "")); String answer = null; List<String> responses = new ArrayList<>(); for (Answer a : q.getAnswers()) { if (a.isSolution()) { answer = a.getDescription(); } else { responses.add(a.getDescription()); } } if (answer != null) { doc.addField("answer", answer); } if (responses.size() > 0) { doc.addField("responses", responses.toString().replace("[", "").replace("]", "")); } return doc; }

Target:
private SolrInputDocument toDoc(Question q) { List<String> tagNames = Lists.transform(q.getTags(), new Function<Tag, String>() { @Nullable @Override public String apply(@Nullable Tag tag) { return tag.getName(); } }); SolrInputDocument doc = new SolrInputDocument(); doc.addField("id", q.getId()); doc.addField("title", q.getTitle()); doc.addField("description", q.getMarkedDescription()); doc.addField("tags", join(tagNames)); String solution = null; List<String> answers = new ArrayList<>(); for (Answer a : q.getAnswers()) { if (a.isSolution()) { solution = a.getDescription(); } else { answers.add(a.getDescription()); } } if (solution != null) { doc.addField("solution", solution); } if (answers.size() > 0) { doc.addField("answers", join(answers)); } return doc; }
Source:
public static void setEnv(Map<String, String> newVariables) { Map<String, String> newenv = new HashMap<>(); newenv.putAll(System.getenv()); newenv.putAll(newVariables); try { Class<?> processEnvironmentClass = Class.forName(PROCESS_ENVIRONMENT); Field theEnvironmentField = processEnvironmentClass.getDeclaredField(THE_ENVIRONMENT_FILED); theEnvironmentField.setAccessible(true); Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null); env.putAll(newenv); Field theCaseInsensitiveEnvironmentField = processEnvironmentClass .getDeclaredField(THE_CASE_INSENSITIVE_ENVIRONMENT); theCaseInsensitiveEnvironmentField.setAccessible(true); Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null); cienv.putAll(newenv); } catch (NoSuchFieldException e) { try { Class[] classes = Collections.class.getDeclaredClasses(); Map<String, String> env = System.getenv(); for (Class cl : classes) { if (COLLECTIONS_UNMODIFIABLE_MAP.equals(cl.getName())) { Field field = cl.getDeclaredField(FIELD_M); field.setAccessible(true); Object obj = field.get(env); Map<String, String> map = (Map<String, String>) obj; map.clear(); map.putAll(newenv); } } } catch (IllegalAccessException | NoSuchFieldException ex) { logger.error("Unable to set environment variable via unmodifiable map", ex); } } catch (ClassNotFoundException | IllegalAccessException e) { logger.error("Unable to set environment variable", e); } }

Target:
public static void setEnv(Map<String, String> newVariables) { Map<String, String> newenv = new HashMap<>(); newenv.putAll(System.getenv()); newenv.putAll(newVariables); try { Class<?> processEnvironmentClass = Class.forName(PROCESS_ENVIRONMENT); Field theEnvironmentField = processEnvironmentClass.getDeclaredField(THE_ENVIRONMENT_FILED); theEnvironmentField.setAccessible(true); Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null); env.putAll(newenv); Field theCaseInsensitiveEnvironmentField = processEnvironmentClass .getDeclaredField(THE_CASE_INSENSITIVE_ENVIRONMENT); theCaseInsensitiveEnvironmentField.setAccessible(true); Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null); cienv.putAll(newenv); } catch (NoSuchFieldException e) { Class[] classes = Collections.class.getDeclaredClasses(); Map<String, String> env = System.getenv(); Arrays.asList(classes).stream().filter(cl -> COLLECTIONS_UNMODIFIABLE_MAP.equals(cl.getName())).forEach( (cl) -> { try { Field field = cl.getDeclaredField(FIELD_M); field.setAccessible(true); Object obj = field.get(env); Map<String, String> map = (Map<String, String>) obj; map.clear(); map.putAll(newenv); } catch (IllegalAccessException | NoSuchFieldException ex) { logger.error("Unable to set environment variable via unmodifiable map", ex); } } ); } catch (ClassNotFoundException | IllegalAccessException e) { logger.error("Unable to set environment variable", e); } }
Source:
private List<DatanodeInfo> filterNodes( NodeOperationalState opState, NodeState health) { if (opState != null && health != null) { return filterNodes(new NodeStatus(opState, health)); } if (opState == null && health == null) { return getAllDatanodeInfos(); } ArrayList<DatanodeInfo> nodes = new ArrayList<>(); try { lock.readLock().lock(); for(DatanodeInfo dn : nodeMap.values()) { if (opState != null && dn.getNodeStatus().getOperationalState() != opState) { continue; } if (health != null && dn.getNodeStatus().getHealth() != health) { continue; } nodes.add(dn); } } finally { lock.readLock().unlock(); } return nodes; }

Target:
private List<DatanodeInfo> filterNodes( NodeOperationalState opState, NodeState health) { if (opState != null && health != null) { return filterNodes(new NodeStatus(opState, health)); } if (opState == null && health == null) { return getAllDatanodeInfos(); } try { lock.readLock().lock(); return nodeMap.values().stream() .filter(n -> opState == null || n.getNodeStatus().getOperationalState() == opState) .filter(n -> health == null || n.getNodeStatus().getHealth() == health) .collect(Collectors.toList()); } finally { lock.readLock().unlock(); } }
Source:
protected ActiveMQDestination(final SimpleString address, final TYPE type, final ActiveMQSession session) { this(address, null, type, session); }

Target:
protected ActiveMQDestination(final SimpleString address, final TYPE type, final ActiveMQSession session) { this.simpleAddress = address; this.thetype = type; this.session = session; this.temporary = TYPE.isTemporary(type); this.queue = TYPE.isQueue(type); }
Source:
protected HttpMessage createHttpMessageWithRespBody(String responseBody, String contentType) throws HttpMalformedHeaderException, URIException { HttpRequestHeader requestHeader = new HttpRequestHeader(); requestHeader.setURI(new URI("<LINK_0>", false)); msg = new HttpMessage(); msg.setRequestHeader(requestHeader); msg.setResponseBody(responseBody); msg.setResponseHeader( "HTTP/1.1 200 OK\r\n" + "Server: Apache-Coyote/1.1\r\n" + "Content-Type: " + contentType + "\r\n" + "Content-Length: " + responseBody.length() + "\r\n"); return msg; }

Target:
protected HttpMessage createHttpMessageWithRespBody(String responseBody, String contentType) throws HttpMalformedHeaderException, URIException { HttpRequestHeader requestHeader = new HttpRequestHeader(); requestHeader.setURI(new URI("<LINK_0>", false)); HttpMessage msg = new HttpMessage(); msg.setRequestHeader(requestHeader); msg.setResponseBody(responseBody); msg.setResponseHeader( "HTTP/1.1 200 OK\r\n" + "Server: Apache-Coyote/1.1\r\n" + "Content-Type: " + contentType + "\r\n" + "Content-Length: " + responseBody.length() + "\r\n"); return msg; }
Source:
private boolean canRemoveVm() { if (getVm() == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_NOT_EXIST); } if (IsVmRunning(getVmId()) || (getVm().getStatus() == VMStatus.NotResponding)) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_RUNNING); } if (getVm().getStatus() == VMStatus.Suspended) { return failCanDoAction(VdcBllMessages.VM_CANNOT_REMOVE_VM_WHEN_STATUS_IS_NOT_DOWN); } if (isVmInPool(getVmId())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_ATTACHED_TO_POOL); } ValidationResult vmDuringSnapshotResult = new SnapshotsValidator().vmNotDuringSnapshot(getVm().getId()); if (!vmDuringSnapshotResult.isValid()) { addCanDoActionMessage(vmDuringSnapshotResult.getMessage().name()); return false; } VmHandler.updateDisksFromDb(getVm()); if (!ImagesHandler.PerformImagesChecks(getVm(), getReturnValue().getCanDoActionMessages(), getVm().getStoragePoolId(), Guid.Empty, false, !getParameters().getForce(), false, false, getParameters().getForce(), false, !getVm().getDiskMap().values().isEmpty(), true, getVm().getDiskMap().values())) { return false; } if (getParameters().getForce() && getVm().getStatus() == VMStatus.ImageLocked && AsyncTaskManager.getInstance().HasTasksByStoragePoolId(getVm().getStoragePoolId())) { return failCanDoAction(VdcBllMessages.VM_CANNOT_REMOVE_HAS_RUNNING_TASKS); } return true; }

Target:
private boolean canRemoveVm() { if (IsVmRunning(getVmId()) || (getVm().getStatus() == VMStatus.NotResponding)) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_RUNNING); } if (getVm().getStatus() == VMStatus.Suspended) { return failCanDoAction(VdcBllMessages.VM_CANNOT_REMOVE_VM_WHEN_STATUS_IS_NOT_DOWN); } if (isVmInPool(getVmId())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_ATTACHED_TO_POOL); } ValidationResult vmDuringSnapshotResult = new SnapshotsValidator().vmNotDuringSnapshot(getVm().getId()); if (!vmDuringSnapshotResult.isValid()) { addCanDoActionMessage(vmDuringSnapshotResult.getMessage().name()); return false; } VmHandler.updateDisksFromDb(getVm()); if (!ImagesHandler.PerformImagesChecks(getVm(), getReturnValue().getCanDoActionMessages(), getVm().getStoragePoolId(), Guid.Empty, false, !getParameters().getForce(), false, false, getParameters().getForce(), false, !getVm().getDiskMap().values().isEmpty(), true, getVm().getDiskMap().values())) { return false; } if (getParameters().getForce() && getVm().getStatus() == VMStatus.ImageLocked && AsyncTaskManager.getInstance().HasTasksByStoragePoolId(getVm().getStoragePoolId())) { return failCanDoAction(VdcBllMessages.VM_CANNOT_REMOVE_HAS_RUNNING_TASKS); } return true; }
Source:
public void handleGetMbusEncryptionKeyStatusResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType resultType, final OsgpException exception, final GetMbusEncryptionKeyStatusResponseDto getMbusEncryptionKeyStatusResponseDto) { LOGGER.info("handleGetMbusEncryptionKeyStatusResponse for MessageType: {}", deviceMessageMetadata.getMessageType()); final String mbusDeviceIdentification = getMbusEncryptionKeyStatusResponseDto.getMbusDeviceIdentification(); final EncryptionKeyStatusType encryptionKeyStatusType = EncryptionKeyStatusType .valueOf(getMbusEncryptionKeyStatusResponseDto.getEncryptionKeyStatus().name()); this.webServiceResponseMessageSender.send( ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(mbusDeviceIdentification).withResult(resultType) .withOsgpException(exception).withDataObject(encryptionKeyStatusType) .withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(), deviceMessageMetadata.getMessageType()); }

Target:
public void handleGetMbusEncryptionKeyStatusResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType resultType, final OsgpException exception, final GetMbusEncryptionKeyStatusResponseDto getMbusEncryptionKeyStatusResponseDto) { LOGGER.info("handleGetMbusEncryptionKeyStatusResponse for MessageType: {}", deviceMessageMetadata.getMessageType()); final String mbusDeviceIdentification = getMbusEncryptionKeyStatusResponseDto.getMbusDeviceIdentification(); final EncryptionKeyStatusType encryptionKeyStatusType = EncryptionKeyStatusType .valueOf(getMbusEncryptionKeyStatusResponseDto.getEncryptionKeyStatus().name()); ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(mbusDeviceIdentification).withResult(resultType) .withOsgpException(exception).withDataObject(encryptionKeyStatusType) .withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(); this.webServiceResponseMessageSender.send( responseMessage, deviceMessageMetadata.getMessageType()); }
Source:
public void testTimestamps() { assertQueryUsingH2Cte("SELECT ship_timestamp FROM lineitem_ex"); assertQueryUsingH2Cte("SELECT ship_timestamp FROM lineitem_ex WHERE ship_timestamp < TIMESTAMP '1993-01-01 01:00:00'"); assertQueryUsingH2Cte("SELECT count(*) FROM lineitem_ex WHERE ship_timestamp IS NOT NULL"); assertQueryUsingH2Cte("SELECT count(*) FROM lineitem_ex WHERE ship_timestamp = (TIMESTAMP '2012-08-08 01:00:00')"); assertQueryUsingH2Cte("SELECT commit_timestamp, ship_timestamp FROM lineitem_ex"); assertQueryUsingH2Cte("SELECT commit_timestamp, ship_timestamp FROM lineitem_ex WHERE ship_timestamp > (TIMESTAMP '1993-08-08 01:00:00') AND commit_timestamp < (TIMESTAMP '1993-08-08 01:00:00')"); assertQueryUsingH2Cte("SELECT commit_timestamp, ship_timestamp FROM lineitem_ex WHERE year(ship_timestamp) - year(commit_timestamp) > 1"); assertQueryUsingH2Cte("SELECT COUNT(*) FROM lineitem_ex WHERE commit_timestamp IS NULL"); assertQueryUsingH2Cte("SELECT commit_timestamp, ship_timestamp, orderkey FROM lineitem_ex WHERE year(commit_timestamp) > 1993 and year(ship_timestamp) > 1993 and year(ship_timestamp) - year(commit_timestamp) = 1"); }

Target:
public void testTimestamps() { assertQueryUsingH2Cte("SELECT ship_timestamp FROM lineitem_ex"); assertQueryUsingH2Cte("SELECT ship_timestamp FROM lineitem_ex WHERE ship_timestamp < TIMESTAMP '1993-01-01 01:00:00'"); assertQueryUsingH2Cte("SELECT count(*) FROM lineitem_ex WHERE ship_timestamp IS NOT NULL"); assertQueryUsingH2Cte("SELECT count(*) FROM lineitem_ex WHERE ship_timestamp = TIMESTAMP '2012-08-08 01:00:00'"); assertQueryUsingH2Cte("SELECT commit_timestamp, ship_timestamp FROM lineitem_ex"); assertQueryUsingH2Cte("SELECT commit_timestamp, ship_timestamp FROM lineitem_ex WHERE ship_timestamp > TIMESTAMP '1993-08-08 01:00:00' AND commit_timestamp < TIMESTAMP '1993-08-08 01:00:00'"); assertQueryReturnsEmptyResult("SELECT commit_timestamp, ship_timestamp FROM lineitem_ex WHERE year(ship_timestamp) - year(commit_timestamp) > 1"); assertQueryUsingH2Cte("SELECT commit_timestamp, ship_timestamp, orderkey FROM lineitem_ex WHERE year(commit_timestamp) > 1993 and year(ship_timestamp) > 1993 and year(ship_timestamp) - year(commit_timestamp) = 1"); }
Source:
private void handleCredentials(HttpServletRequest request, String user, String password) { UserProfile userProfile = translateUser(user); AuthenticationProfile profile = AuthenticationProfileRepository.getInstance().getProfile(userProfile.profile); if (profile == null) { log.error(String.format("Error in obtaining profile %1$s", userProfile.profile)); } else { ExtMap outputMap = profile.getAuthn().invoke(new ExtMap().mput( Base.InvokeKeys.COMMAND, Authn.InvokeCommands.AUTHENTICATE_CREDENTIALS ).mput( Authn.InvokeKeys.USER, userProfile.userName ).mput( Authn.InvokeKeys.CREDENTIALS, password ) ); if (outputMap.<Integer> get(Base.InvokeKeys.RESULT) == Base.InvokeResult.SUCCESS && outputMap.<Integer> get(Authn.InvokeKeys.RESULT) == Authn.AuthResult.SUCCESS) { request.setAttribute(FiltersHelper.Constants.REQUEST_AUTH_RECORD_KEY, outputMap.<ExtMap> get(Authn.InvokeKeys.AUTH_RECORD)); request.setAttribute(FiltersHelper.Constants.REQUEST_PROFILE_KEY, userProfile.profile); } else { log.error( String.format( "Failure in authentication to profile %1$s. Invocation Result code is %2$s. Authn result code is %3$s", userProfile.profile, outputMap.<Integer> get(Base.InvokeKeys.RESULT), outputMap.<Integer> get(Authn.InvokeKeys.RESULT) ) ); } } }

Target:
private void handleCredentials(HttpServletRequest request, String user, String password) { UserProfile userProfile = translateUser(user); if (userProfile == null || userProfile.profile == null) { log.error(String.format("Error in obtaining profile %1$s", userProfile.profile)); } else { ExtMap outputMap = userProfile.profile.getAuthn().invoke(new ExtMap().mput( Base.InvokeKeys.COMMAND, Authn.InvokeCommands.AUTHENTICATE_CREDENTIALS ).mput( Authn.InvokeKeys.USER, userProfile.userName ).mput( Authn.InvokeKeys.CREDENTIALS, password ) ); if (outputMap.<Integer> get(Base.InvokeKeys.RESULT) == Base.InvokeResult.SUCCESS && outputMap.<Integer> get(Authn.InvokeKeys.RESULT) == Authn.AuthResult.SUCCESS) { request.setAttribute(FiltersHelper.Constants.REQUEST_AUTH_RECORD_KEY, outputMap.<ExtMap> get(Authn.InvokeKeys.AUTH_RECORD)); request.setAttribute(FiltersHelper.Constants.REQUEST_PROFILE_KEY, userProfile.profile.getName()); } else { log.error( String.format( "Failure in authentication to profile %1$s. Invocation Result code is %2$s. Authn result code is %3$s", userProfile.profile, outputMap.<Integer> get(Base.InvokeKeys.RESULT), outputMap.<Integer> get(Authn.InvokeKeys.RESULT) ) ); } } }
Source:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String requestUri = request.getRequestURI(); logger.debug("Starting execution of proxy request for {}", requestUri); SiteContext siteContext = SiteContext.getCurrent(); if (siteContext == null) { throw new IllegalStateException("Can't resolve site context for current request"); } String siteName = siteContext.getSiteName(); logger.debug("Resolved site for proxy request {}", siteName, requestUri); String targetUrl = getTargetUrl(siteContext, requestUri); logger.debug("Resolved target url for proxy request {}", targetUrl, requestUri); if (request.getRequestURL().toString().contains(targetUrl)) { logger.debug("Resolved target url for request is local, will skip proxy", requestUri); throw new HttpProxyException("Local target url detected"); } request.setAttribute(ATTR_TARGET_URI, targetUrl); request.setAttribute(ATTR_TARGET_HOST, URIUtils.extractHost(URI.create(targetUrl))); super.service(request, response); }

Target:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String requestUri = request.getRequestURI(); logger.debug("Starting execution of proxy request for {}", requestUri); SiteContext siteContext = SiteContext.getCurrent(); if (siteContext == null) { throw new IllegalStateException("Can't resolve site context for current request"); } String siteName = siteContext.getSiteName(); logger.debug("Resolved site for proxy request {}", siteName, requestUri); String targetUrl = getTargetUrl(siteContext, requestUri); logger.debug("Resolved target url for proxy request {}", targetUrl, requestUri); if (request.getRequestURL().toString().contains(targetUrl)) { logger.debug("Resolved target url for request is local, will skip proxy", requestUri); throw new LocalTargetUrlProxyException("Local target url detected"); } request.setAttribute(ATTR_TARGET_URI, targetUrl); request.setAttribute(ATTR_TARGET_HOST, URIUtils.extractHost(URI.create(targetUrl))); super.service(request, response); }
Source:
public void serialize(XMLExtendedStreamWriter writer, JdbcBinaryStoreConfiguration configuration) throws XMLStreamException { writer.writeStartElement(Element.BINARY_KEYED_JDBC_STORE); writeJdbcStoreAttributes(writer, configuration); writeJDBCStoreTable(writer, Element.BINARY_KEYED_TABLE, configuration.table()); writeCommonStoreElements(writer, configuration); writer.writeEndElement(); }

Target:
public void serialize(XMLExtendedStreamWriter writer, JdbcBinaryStoreConfiguration configuration) throws XMLStreamException { writer.writeStartElement(Element.BINARY_KEYED_JDBC_STORE); writeJdbcStoreAttributes(writer, configuration); writeCommonStoreSubAttributes(writer, configuration); writeJDBCStoreTable(writer, Element.BINARY_KEYED_TABLE, configuration.table()); writeJDBCStoreConnection(writer, configuration); writeCommonStoreElements(writer, configuration); writer.writeEndElement(); }
Source:
private static GoNamedElement getFieldDefinition(@Nullable GoValue value) { GoKey key = PsiTreeUtil.getPrevSiblingOfType(value, GoKey.class); GoFieldName fieldName = key != null ? key.getFieldName() : null; PsiElement field = fieldName != null ? fieldName.resolve() : null; return field instanceof GoAnonymousFieldDefinition || field instanceof GoFieldDefinition ? ObjectUtils .tryCast(field, GoNamedElement.class) : null; }

Target:
private static GoNamedElement getFieldDefinition(@Nullable GoValue value) { GoKey key = PsiTreeUtil.getPrevSiblingOfType(value, GoKey.class); GoFieldName fieldName = key != null ? key.getFieldName() : null; PsiElement field = fieldName != null ? fieldName.resolve() : null; return GoPsiImplUtil.isFieldDefinition(field) ? ObjectUtils.tryCast(field, GoNamedElement.class) : null; }