auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void prepare(Map stormConf, TopologyContext context, final OutputCollector collector) { _rand = new Random(); _collector = collector; Number subpid = _process.launch(stormConf, context); LOG.info("Launched subprocess with pid " + subpid); _readerThread = new Thread(new Runnable() { public void run() { while (_running) { try { Emission emission = _process.readEmission(); String command = emission.getCommand(); if(command.equals("ack")) { handleAck(emission.getId()); } else if (command.equals("fail")) { handleFail(emission.getId()); } else if (command.equals("error")) { handleError(emission.getMsg()); } else if (command.equals("log")) { String msg = emission.getMsg(); LOG.info("Shell msg: " + msg); } else if (command.equals("emit")) { handleEmit(emission); } } catch (InterruptedException e) { } catch (Throwable t) { die(t); } } } }); _readerThread.start(); _writerThread = new Thread(new Runnable() { public void run() { while (_running) { try { Object write = _pendingWrites.poll(1, SECONDS); if (write instanceof Immission) { _process.writeImmission((Immission)write); } else if (write instanceof List<?>) { } } catch (InterruptedException e) { } catch (Throwable t) { die(t); } } } }); _writerThread.start(); }

Target:
public void prepare(Map stormConf, TopologyContext context, final OutputCollector collector) { Object maxPending = stormConf.get(Config.TOPOLOGY_SHELLBOLT_MAX_PENDING); if (maxPending != null) { this._pendingWrites = new LinkedBlockingQueue(((Number)maxPending).intValue()); } _rand = new Random(); _collector = collector; _process = new ShellProcess(_command); Number subpid = _process.launch(stormConf, context); LOG.info("Launched subprocess with pid " + subpid); _readerThread = new Thread(new Runnable() { public void run() { while (_running) { try { ShellMsg shellMsg = _process.readShellMsg(); String command = shellMsg.getCommand(); if(command.equals("ack")) { handleAck(shellMsg.getId()); } else if (command.equals("fail")) { handleFail(shellMsg.getId()); } else if (command.equals("error")) { handleError(shellMsg.getMsg()); } else if (command.equals("log")) { String msg = shellMsg.getMsg(); LOG.info("Shell msg: " + msg); } else if (command.equals("emit")) { handleEmit(shellMsg); } } catch (InterruptedException e) { } catch (Throwable t) { die(t); } } } }); _readerThread.start(); _writerThread = new Thread(new Runnable() { public void run() { while (_running) { try { Object write = _pendingWrites.poll(1, SECONDS); if (write instanceof BoltMsg) { _process.writeBoltMsg((BoltMsg)write); } else if (write instanceof List<?>) { _process.writeTaskIds((List<Integer>)write); } else if (write != null) { throw new RuntimeException("Unknown class type to write: " + write.getClass().getName()); } } catch (InterruptedException e) { } catch (Throwable t) { die(t); } } } }); _writerThread.start(); }
Source:
private void checkForPreConditions() throws Exception { assumeFalse(compatibleClientVersion.contains(MetaDataProtocol.CURRENT_CLIENT_VERSION)); org.apache.hadoop.hbase.client.Connection conn = ConnectionFactory.createConnection(conf); Admin admin = conn.getAdmin(); assertFalse(admin.tableExists(TableName.valueOf(QueryConstants.SYSTEM_SCHEMA_NAME, PhoenixDatabaseMetaData.SYSTEM_CATALOG_TABLE))); }

Target:
private void checkForPreConditions() throws Exception { assumeFalse(compatibleClientVersion.contains(MetaDataProtocol.CURRENT_CLIENT_VERSION)); try (org.apache.hadoop.hbase.client.Connection conn = ConnectionFactory.createConnection(conf)) { Admin admin = conn.getAdmin(); assertFalse(admin.tableExists(TableName.valueOf(QueryConstants.SYSTEM_SCHEMA_NAME, PhoenixDatabaseMetaData.SYSTEM_CATALOG_TABLE))); } }
Source:
public static MediaFile fromMediaModel(MediaModel media) { if (media == null) { return null; } MediaFile mediaFile = new MediaFile(); mediaFile.setBlogId(String.valueOf(media.getLocalSiteId())); mediaFile.setMediaId(String.valueOf(media.getMediaId())); mediaFile.setId(media.getId()); mediaFile.setFileName(media.getFileName()); mediaFile.setFilePath(media.getFilePath()); mediaFile.setMimeType(media.getMimeType()); mediaFile.setThumbnailURL(media.getThumbnailUrl()); mediaFile.setFileURL(media.getUrl()); mediaFile.setTitle(media.getTitle()); mediaFile.setDescription(media.getDescription()); mediaFile.setCaption(media.getCaption()); mediaFile.setUploadState(media.getUploadState()); mediaFile.setVideo(media.getMimeType().startsWith("video")); mediaFile.setVideoPressShortCode(ShortcodeUtils.getVideoPressShortcodeFromId(media.getVideoPressGuid())); return mediaFile; }

Target:
public static MediaFile fromMediaModel(MediaModel media) { if (media == null) { return null; } MediaFile mediaFile = new MediaFile(); mediaFile.setBlogId(String.valueOf(media.getLocalSiteId())); mediaFile.setMediaId(String.valueOf(media.getMediaId())); mediaFile.setId(media.getId()); mediaFile.setFileName(media.getFileName()); mediaFile.setFilePath(media.getFilePath()); mediaFile.setMimeType(media.getMimeType()); mediaFile.setThumbnailURL(media.getThumbnailUrl()); mediaFile.setFileURL(media.getUrl()); mediaFile.setTitle(media.getTitle()); mediaFile.setDescription(media.getDescription()); mediaFile.setCaption(media.getCaption()); mediaFile.setUploadState(media.getUploadState()); mediaFile.setVideo(org.wordpress.android.fluxc.utils.MediaUtils.isVideoMimeType(media.getMimeType())); mediaFile.setVideoPressShortCode(ShortcodeUtils.getVideoPressShortcodeFromId(media.getVideoPressGuid())); return mediaFile; }
Source:
public CommentInfo get() throws RestApiException { try { return CommentInfoMapper.INSTANCE.apply(getDraft.apply(draft)); } catch (OrmException e) { throw new RestApiException("Cannot update draft", e); } }

Target:
public CommentInfo get() throws RestApiException { try { return CommentInfoMapper.INSTANCE.apply(getDraft.apply(draft)); } catch (OrmException e) { throw new RestApiException("Cannot retrieve draft", e); } }
Source:
public static <K, V, C> Function<CacheEntry<K, V>, CacheEntry<K, C>> converterToFunction(KeyValueFilterConverter<? super K, ? super V, C> filterConverter) { return new FilterConverterAsCacheEntryFunction<K, V, C>(filterConverter); }

Target:
public static <K, V, C> Function<CacheEntry<K, V>, CacheEntry<K, C>> converterToFunction(KeyValueFilterConverter<? super K, ? super V, C> filterConverter) { return new FilterConverterAsCacheEntryFunction<>(filterConverter); }
Source:
protected void dataCenter_SelectedItemChanged() { AsyncDataProvider.getStorageDomainList(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { MoveOrCopyDiskModel diskModel = (MoveOrCopyDiskModel) target; @SuppressWarnings("unchecked") ArrayList<StorageDomain> storageDomains = (ArrayList<StorageDomain>) returnValue; diskModel.onInitStorageDomains(storageDomains); } }), ((StoragePool) getDataCenter().getSelectedItem()).getId()); }

Target:
protected void dataCenter_SelectedItemChanged() { initStorageDomains(); }
Source:
protected AbstractBeanDefinition doParse(Element element, ParserContext parserContext, String channelName) { BeanDefinitionBuilder builder = ReactorNamespaceUtils.createBeanDefitionBuilder(SyslogInboundChannelAdapter.class, element); String s = element.getAttribute("port"); int port = 5140; if (StringUtils.hasText(s)) { port = Integer.parseInt(s); } builder.addConstructorArgValue(port); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "channel", "outputChannel"); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "error-channel", "errorChannel"); return builder.getBeanDefinition(); }

Target:
protected AbstractBeanDefinition doParse(Element element, ParserContext parserContext, String channelName) { BeanDefinitionBuilder builder = ReactorNamespaceUtils.createBeanDefinitionBuilder(SyslogInboundChannelAdapter.class, element); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "host", "host"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "port", "port"); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "error-channel", "errorChannel"); return builder.getBeanDefinition(); }
Source:
public void setTableId(Table.ID tId) { if (tId == null) throw new IllegalArgumentException("null table id not allowed"); this.tableId = tId; hashCode = 0; }

Target:
public void setTableId(Table.ID tId) { Objects.requireNonNull(tId, "null table id not allowed"); this.tableId = tId; hashCode = 0; }
Source:
public Map<String, Integer> getPartitionCountWithPendingState(String resourceStateModel, String state) { Map<String, Integer> pendingPartitionCount = new HashMap<String, Integer>(); for (String resource : _pendingStateMap.keySet()) { String stateModel = _resourceStateModelMap.get(resource); if (stateModel != null && stateModel.equals(resourceStateModel) || stateModel == null && resourceStateModel == null) { for (Partition partition : _pendingStateMap.get(resource).keySet()) { Map<String, Message> partitionMessage = _pendingStateMap.get(resource).get(partition); for (Map.Entry<String, Message> participantMap : partitionMessage.entrySet()) { String participant = participantMap.getKey(); if (!pendingPartitionCount.containsKey(participant)) { pendingPartitionCount.put(participant, 0); } String toState = participantMap.getValue().getToState(); if (toState != null && toState.equals(state) || toState == null && state == null) { pendingPartitionCount.put(participant, pendingPartitionCount.get(participant) + 1); } } } } } return pendingPartitionCount; }

Target:
public Map<String, Integer> getPartitionCountWithPendingState(String resourceStateModel, String state) { return getPartitionCountWithState(resourceStateModel, state, (Map) _pendingStateMap); }
Source:
public static String descramble(String scrambled) { if(scrambled==null) return null; try { return new String(Base64.getDecoder().decode(scrambled.getBytes(StandardCharsets.UTF_8)),StandardCharsets.UTF_8); } catch (IllegalArgumentException e) { return ""; } }

Target:
public static String descramble(String scrambled) { if(scrambled==null) return null; try { return new String(Base64.getDecoder().decode(scrambled.getBytes(StandardCharsets.UTF_8)),StandardCharsets.UTF_8); } catch (IllegalArgumentException e) { LOGGER.log(Level.WARNING,"Corrupted data", e); return ""; } }
Source:
public static final int[] getSubWordMatchingRegions(String pattern, String name) { if (name == null) return null; if (pattern == null) { return EMPTY_REGIONS; } int segmentStart = 0; int[] segments = EMPTY_REGIONS; char[] nameChars = name.toCharArray(); int iName = -1; for (int iPattern = 0; iPattern < pattern.length(); iPattern++) { iName++; if (iName == nameChars.length){ return null; } char patternChar = pattern.charAt(iPattern); char nameChar = nameChars[iName]; if (patternChar == nameChar) { continue; } if (ScannerHelper.toLowerCase(nameChar) == patternChar) { continue; } if (iName > segmentStart) { segments = Arrays.copyOf(segments, segments.length + 2); segments[segments.length - 2] = segmentStart; segments[segments.length - 1] = iName - segmentStart; } int wordStart = indexOfWordStart(nameChars, iName, patternChar); if (wordStart < 0) { return null; } segmentStart = wordStart; iName = wordStart; } segments = Arrays.copyOf(segments, segments.length + 2); segments[segments.length - 2] = segmentStart; segments[segments.length - 1] = iName - segmentStart + 1; return segments; }

Target:
public static final int[] getSubWordMatchingRegions(String pattern, String name) { if (name == null) return null; if (pattern == null) { return EMPTY_REGIONS; } int segmentStart = 0; int[] segments = EMPTY_REGIONS; char[] nameChars = name.toCharArray(); int iName = -1; for (int iPattern = 0; iPattern < pattern.length(); iPattern++) { iName++; if (iName == nameChars.length){ return null; } char patternChar = pattern.charAt(iPattern); char nameChar = nameChars[iName]; if (patternChar == nameChar) { continue; } if (ScannerHelper.toLowerCase(nameChar) == patternChar) { continue; } if (iName > segmentStart) { segments = Arrays.copyOf(segments, segments.length + 2); segments[segments.length - 2] = segmentStart; segments[segments.length - 1] = iName - segmentStart; } int wordStart = CharOperation.indexOfWordStart(nameChars, iName, patternChar); if (wordStart < 0) { return null; } segmentStart = wordStart; iName = wordStart; } segments = Arrays.copyOf(segments, segments.length + 2); segments[segments.length - 2] = segmentStart; segments[segments.length - 1] = iName - segmentStart + 1; return segments; }
Source:
protected void configure(HttpSecurity http) throws Exception { if(environment.acceptsProfiles("!"+Initializer.PROFILE_DEV)) { http.requiresChannel().antMatchers("/healthz").requiresInsecure() .and() .requiresChannel().mvcMatchers(" additional-field", ADMIN_API + "/event promo-code", ADMIN_API + "/reservation/event email/", ADMIN_API + "/event pending-payments", ADMIN_API + "/events sponsor-scan/export", ADMIN_API + "/events */audit" }; configurer.csrfTokenRepository(getCsrfTokenRepository()) .and() .authorizeRequests() .antMatchers(ADMIN_API + "/configuration new", ADMIN_API + "/reservation/event */notify", ADMIN_API + "/reservation/event performPayment").hasAnyRole(ADMIN, OWNER, SUPERVISOR) .antMatchers(ADMIN_API + " export/**").hasAnyRole(ADMIN, OWNER) .antMatchers("/admin/**").hasAnyRole(ADMIN, OWNER, SUPERVISOR) .antMatchers("/api/attendees/**").denyAll() .antMatchers("/**").permitAll() .and() .formLogin() .loginPage("/authentication") .loginProcessingUrl("/authenticate") .failureUrl("/authentication?failed") .and().logout().permitAll(); http.addFilterBefore(new RecaptchaLoginFilter(recaptchaService, "/authenticate", "/authentication?recaptchaFailed", configurationManager), UsernamePasswordAuthenticationFilter.class); if(environment.acceptsProfiles(Initializer.PROFILE_DEMO)) { http.addFilterAfter(new UserCreatorBeforeLoginFilter(userManager, "/authenticate"), RecaptchaLoginFilter.class); } }

Target:
protected void configure(HttpSecurity http) throws Exception { if(environment.acceptsProfiles("!"+Initializer.PROFILE_DEV)) { http.requiresChannel().antMatchers("/healthz").requiresInsecure() .and() .requiresChannel().mvcMatchers(" additional-field", ADMIN_API + "/event promo-code", ADMIN_API + "/reservation/event email/", ADMIN_API + "/event pending-payments", ADMIN_API + "/events sponsor-scan/export", ADMIN_API + "/events */audit" }; configurer.csrfTokenRepository(getCsrfTokenRepository()) .and() .authorizeRequests() .antMatchers(ADMIN_API + "/configuration new", ADMIN_API + "/reservation/event */notify", ADMIN_API + "/reservation/event confirm").hasAnyRole(ADMIN, OWNER, SUPERVISOR) .antMatchers(ADMIN_API + " export/**").hasAnyRole(ADMIN, OWNER) .antMatchers("/admin/**").hasAnyRole(ADMIN, OWNER, SUPERVISOR) .antMatchers("/api/attendees/**").denyAll() .antMatchers("/**").permitAll() .and() .formLogin() .loginPage("/authentication") .loginProcessingUrl("/authenticate") .failureUrl("/authentication?failed") .and().logout().permitAll(); http.addFilterBefore(new RecaptchaLoginFilter(recaptchaService, "/authenticate", "/authentication?recaptchaFailed", configurationManager), UsernamePasswordAuthenticationFilter.class); if(environment.acceptsProfiles(Initializer.PROFILE_DEMO)) { http.addFilterAfter(new UserCreatorBeforeLoginFilter(userManager, "/authenticate"), RecaptchaLoginFilter.class); } }
Source:
private void setCurrentRepo(Repository newRepo) { Repository old = getCurrentRepo(); this.currentRepo = newRepo; if(old == null) { if (newRepo == null) return; } else { if (old.equals(newRepo)) return; } this.firePropertyChange(this, P_REPOSITORY, old, newRepo); }

Target:
private void setCurrentRepo(Repository newRepo) { Repository old = getCurrentRepo(); this.currentRepo = newRepo; if (!Objects.equals(old, newRepo)) { this.firePropertyChange(this, P_REPOSITORY, old, newRepo); } }
Source:
private void readDataSource() { tableModel = new DataSourceTableModel(tableEditableElement); table.setModel(tableModel); table.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF); autoResizeColWidth(Math.min(5, tableModel.getRowCount()), new HashMap<String, Integer>(), new HashMap<String, TableCellRenderer>()); tableSorter = new DataSourceRowSorter(tableModel); tableSorter.addRowSorterListener( EventHandler.create(RowSorterListener.class,this, "onShownRowsChanged")); table.setRowSorter(tableSorter); tableRowHeader = new TableRowHeader(table); tableScrollPane.setRowHeaderView(tableRowHeader); setRowSelection((IntegerUnion)tableEditableElement.getSelection()); table.getSelectionModel().addListSelectionListener( EventHandler.create(ListSelectionListener.class,this, "onTableSelectionChange","")); add(makeFilterManager(),BorderLayout.SOUTH); dockingPanelParameters.addPropertyChangeListener( DockingPanelParameters.PROP_VISIBLE, EventHandler.create(PropertyChangeListener.class, this,"onChangeVisibility","newValue")); updateTitle(); tableEditableElement.addPropertyChangeListener(TableEditableElement.PROP_SELECTION, editableSelectionListener); }

Target:
private void readDataSource() { tableModel = new DataSourceTableModel(tableEditableElement); table.setModel(tableModel); table.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF); quickAutoResize(); tableSorter = new DataSourceRowSorter(tableModel); tableSorter.addRowSorterListener( EventHandler.create(RowSorterListener.class,this, "onShownRowsChanged")); table.setRowSorter(tableSorter); tableRowHeader = new TableRowHeader(table); tableScrollPane.setRowHeaderView(tableRowHeader); setRowSelection((IntegerUnion)tableEditableElement.getSelection()); table.getSelectionModel().addListSelectionListener( EventHandler.create(ListSelectionListener.class,this, "onTableSelectionChange","")); add(makeFilterManager(),BorderLayout.SOUTH); dockingPanelParameters.addPropertyChangeListener( DockingPanelParameters.PROP_VISIBLE, EventHandler.create(PropertyChangeListener.class, this,"onChangeVisibility","newValue")); updateTitle(); tableEditableElement.addPropertyChangeListener(TableEditableElement.PROP_SELECTION, editableSelectionListener); }
Source:
protected String buildTooltipText() { String tooltipText = null; StringBuilder sb = new StringBuilder(); if (!getCommand().getExecuteProhibitionReasons().isEmpty()) { for (String reason : getCommand().getExecuteProhibitionReasons()) { sb.append(reason).append(", "); } tooltipText = sb.toString(); if (tooltipText.length() != 0) { tooltipText = tooltipText.substring(0, tooltipText.length() -2); } } return tooltipText; }

Target:
protected String buildTooltipText() { String tooltipText = null; if (!getCommand().getExecuteProhibitionReasons().isEmpty()) { tooltipText = ""; for (String reason: getCommand().getExecuteProhibitionReasons()) { if (!tooltipText.isEmpty()) { tooltipText += ", "; } tooltipText += reason; } } return tooltipText; }
Source:
private RecordCursorFactory generateSelectDistinct(QueryModel model, SqlExecutionContext executionContext) throws SqlException { final RecordCursorFactory factory = generateSubQuery(model, executionContext); try { if (model.getColumns().size() == 1 && model.getNestedModel() != null && model.getNestedModel().getNestedModel() != null && model.getNestedModel().getNestedModel().getTableName() != null) { ExpressionNode tableName = model.getNestedModel().getNestedModel().getTableName(); TableReader reader = engine.getReader(executionContext.getCairoSecurityContext(), tableName.token); CharSequence columnName = model.getColumnNames().get(0); int columnIndex = reader.getMetadata().getColumnIndex(columnName); int columnType = reader.getMetadata().getColumnType(columnIndex); if (columnType == ColumnType.SYMBOL) { return new DistinctSymbolRecordCursorFactory( factory, entityColumnFilter, reader, columnName ); } } return new DistinctRecordCursorFactory( configuration, factory, entityColumnFilter, asm ); } catch (CairoException e) { factory.close(); throw e; } }

Target:
private RecordCursorFactory generateSelectDistinct(QueryModel model, SqlExecutionContext executionContext) throws SqlException { if (model.getColumns().size() == 1 && model.getNestedModel() != null && model.getNestedModel().getNestedModel() != null && model.getNestedModel().getNestedModel().getTableName() != null) { ExpressionNode tableNameExpressionNode = model.getNestedModel().getNestedModel().getTableName(); CharSequence tableName = tableNameExpressionNode.token; try (TableReader reader = engine.getReader(executionContext.getCairoSecurityContext(), tableName);) { CharSequence columnName = model.getColumnNames().get(0); TableReaderMetadata readerMetadata = (TableReaderMetadata) reader.getMetadata(); int columnIndex = readerMetadata.getColumnIndex(columnName); int columnType = readerMetadata.getColumnType(columnIndex); if (readerMetadata.getVersion() >= 416 && columnType == ColumnType.SYMBOL) { final GenericRecordMetadata distinctSymbolMetadata = new GenericRecordMetadata(); long tableVersion = reader.getVersion(); distinctSymbolMetadata.add( new TableColumnMetadata( Chars.toString(columnName), readerMetadata.getColumnType(columnIndex), readerMetadata.isColumnIndexed(columnIndex), readerMetadata.getIndexValueBlockCapacity(columnIndex), readerMetadata.isSymbolTableStatic(columnIndex) ) ); return new DistinctSymbolRecordCursorFactory( engine, distinctSymbolMetadata, Chars.toString(tableName), columnIndex, tableVersion ); } } } final RecordCursorFactory factory = generateSubQuery(model, executionContext); try { return new DistinctRecordCursorFactory( configuration, factory, entityColumnFilter, asm ); } catch (CairoException e) { factory.close(); throw e; } }
Source:
public void testGenerateSessionFromRequirements() { IPath sessionFolderPath = Activator.getDefault().getStateLocation(); IPath sessionFilePath = sessionFolderPath.addTrailingSeparator().append(SESSION_FILENAME).addFileExtension(SessionConfigStrings.DEFAULT_SESSION_CONFIG_FILE_EXTENSION); IStatus invalidStatusA = SessionConfigXML.generateSessionConfigFromRequirements(sessionFilePath, fInvalidRequirementsA); assertTrue(invalidStatusA.getSeverity() == IStatus.ERROR); IStatus invalidStatusB = SessionConfigXML.generateSessionConfigFromRequirements(sessionFilePath, fInvalidRequirementsB); assertTrue(invalidStatusB.getSeverity() == IStatus.ERROR); IStatus invalidStatusC = SessionConfigXML.generateSessionConfigFromRequirements(sessionFilePath, fInvalidRequirementsC); assertTrue(invalidStatusC.getSeverity() == IStatus.ERROR); IStatus validStatus = SessionConfigXML.generateSessionConfigFromRequirements(sessionFilePath, fValidRequirements); assertTrue(validStatus.isOK()); File sessionXMLFile = sessionFilePath.toFile(); URL url = SessionConfigXMLTest.class.getResource(SESSION_XSD_FILENAME); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Source xmlSource = new StreamSource(sessionXMLFile); try { Schema schema = schemaFactory.newSchema(url); Validator validator = schema.newValidator(); validator.validate(xmlSource); } catch (Exception e) { fail("The validation of the session configuration file has failed: " + e.getMessage()); } }

Target:
public void testGenerateSessionFromRequirements() { IPath sessionFolderPath = Activator.getDefault().getStateLocation(); IPath sessionFilePath = sessionFolderPath.addTrailingSeparator().append(SESSION_FILENAME).addFileExtension(SessionConfigStrings.DEFAULT_SESSION_CONFIG_FILE_EXTENSION); final List<TmfAnalysisRequirement> invalidRequirements = new ArrayList<>(); invalidRequirements.add(fInvalidRequirementType); IStatus invalidStatusA = SessionConfigXML.generateSessionConfigFromRequirements(sessionFilePath, invalidRequirements); assertTrue(invalidStatusA.getSeverity() == IStatus.ERROR); invalidRequirements.clear(); invalidRequirements.add(fValidRequirementEventA); invalidRequirements.add(fValidRequirementEventB); IStatus invalidStatusB = SessionConfigXML.generateSessionConfigFromRequirements(sessionFilePath, invalidRequirements); assertTrue(invalidStatusB.getSeverity() == IStatus.ERROR); invalidRequirements.clear(); invalidRequirements.add(fValidRequirementDomain); IStatus invalidStatusC = SessionConfigXML.generateSessionConfigFromRequirements(sessionFilePath, invalidRequirements); assertTrue(invalidStatusC.getSeverity() == IStatus.ERROR); IStatus validStatus = SessionConfigXML.generateSessionConfigFromRequirements(sessionFilePath, fValidRequirements); assertTrue(validStatus.isOK()); File sessionXMLFile = sessionFilePath.toFile(); assertTrue(SessionConfigXML.sessionValidate(sessionXMLFile).isOK()); }
Source:
public double modify(double inputSpeed) { currentSpeed = calculate(inputSpeed); LogKitten.w("AccelerationCap outputed: " + currentSpeed); return currentSpeed; }

Target:
public double modify(double inputSpeed) { currentSpeed = calculate(inputSpeed); LogKitten.d("AccelerationCap outputed: " + currentSpeed); return currentSpeed; }
Source:
public ECGDataQuality(DataStreams datastreams, double qualityThreshold) { DataPointStream ecg = datastreams.getDataPointStream(StreamConstants.ORG_MD2K_CSTRESS_DATA_ECG); DataPointStream ecgQuality = datastreams.getDataPointStream(StreamConstants.ORG_MD2K_CSTRESS_DATA_ECG_QUALITY); this.acceptableOutlierPercent = AUTOSENSE.QUALITY_acceptableOutlierPercent; this.outlierThresholdHigh = AUTOSENSE.QUALITY_outlierThresholdHigh; this.outlierThresholdLow = AUTOSENSE.QUALITY_outlierThresholdLow; this.ecgThresholdBandLoose = AUTOSENSE.QUALITY_ecgThresholdBandLoose; this.bufferLength = AUTOSENSE.QUALITY_bufferLength; envelBuff = new int[bufferLength]; classBuff = new int[bufferLength]; for (int i = 0; i < bufferLength; i++) { envelBuff[i] = 2 * ecgThresholdBandLoose; classBuff[i] = 0; } envelHead = 0; classHead = 0; List<DataPoint> quality = computeQuality(ecg.data, AUTOSENSE.QUALITY_windowSize); double count = 0; for (DataPoint dp : quality) { ecgQuality.add(dp); if (dp.value == AUTOSENSE.QUALITY_GOOD) { count++; } } DataPointStream ecgWindowQuality = datastreams.getDataPointStream(StreamConstants.ORG_MD2K_CSTRESS_DATA_ECG_WINDOW_QUALITY); if ((count / quality.size()) > qualityThreshold) ecgWindowQuality.add(new DataPoint(quality.get(0).timestamp, AUTOSENSE.QUALITY_GOOD)); else ecgWindowQuality.add(new DataPoint(quality.get(0).timestamp, AUTOSENSE.QUALITY_BAD)); }

Target:
public ECGDataQuality(DataStreams datastreams, double qualityThreshold) { this(datastreams, qualityThreshold, AUTOSENSE.QUALITY_acceptableOutlierPercent, AUTOSENSE.QUALITY_outlierThresholdHigh, AUTOSENSE.QUALITY_outlierThresholdLow, AUTOSENSE.QUALITY_ecgThresholdBandLoose, AUTOSENSE.QUALITY_bufferLength, AUTOSENSE.QUALITY_windowSizeEcg); }
Source:
public void stop(IMethodEnvironmentData data){ try { CamelContext context = getOrMakeContextByRid(getDocument().getIdentity().toString(),data.getCurrentWidget()); try { context.stop(); } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } }

Target:
public void stop(IMethodEnvironmentData data){ CamelContext context = getOrMakeContextByRid(getDocument().getIdentity().toString(),data.getCurrentWidget()); try { context.stop(); } catch (Exception e) { LOG.error("Cannot stop Camel Context",e); } waitingRefresh(context); }
Source:
public void populateDatastreamDestination(List<Datastream> datastreams) { HashMap<String, String> sourceDestinationMapping = new HashMap<>(); datastreams.stream().filter(d -> !d.getDestination().isEmpty()) .forEach(d -> sourceDestinationMapping.put(d.getSource(), d.getDestination())); datastreams.stream().filter(d -> d.getDestination().isEmpty() && sourceDestinationMapping.containsKey(d.getSource())) .forEach(d -> d.setDestination(sourceDestinationMapping.get(d.getSource()))); datastreams.stream().filter(d -> d.getDestination().isEmpty()) .forEach(d -> { if (sourceDestinationMapping.containsKey(d.getSource())) { d.setDestination(sourceDestinationMapping.get(d.getSource())); } else { String destination = createTopic(d); sourceDestinationMapping.put(d.getSource(), destination); d.setDestination(destination); } }); }

Target:
public void populateDatastreamDestination(List<Datastream> datastreams) { Objects.requireNonNull(datastreams, "Datastream should not be null"); HashMap<String, String> sourceDestinationMapping = new HashMap<>(); datastreams.stream().filter(d -> !d.getDestination().isEmpty()) .forEach(d -> sourceDestinationMapping.put(d.getSource(), d.getDestination())); LOG.debug("Datastream Source -> Destination mapping before populating new datastream destinations", sourceDestinationMapping); for (Datastream datastream : datastreams) { if (!datastream.getDestination().isEmpty()) { continue; } if (sourceDestinationMapping.containsKey(datastream.getSource())) { String destination = sourceDestinationMapping.get(datastream.getSource()); LOG.info(String.format("Datastream %s has same source as existing datastream, Setting the destination %s", datastream.getName(), destination)); datastream.setDestination(destination); } else { String destination = createTopic(datastream); LOG.info(String .format("Datastream %s has an unique source, Creating a new destination topic %s", datastream.getName(), destination)); sourceDestinationMapping.put(datastream.getSource(), destination); datastream.setDestination(destination); } } LOG.debug("Datastream Source -> Destination mapping after the populating new datastream destinations", sourceDestinationMapping); }
Source:
public HttpClient get() { KerberosConfig kerberosConfig = injector.getInstance(KerberosConfig.class); HttpClientConfig config = injector.getInstance(Key.get(HttpClientConfig.class, annotation)); Set<HttpRequestFilter> filters = ImmutableSet.<HttpRequestFilter>builder() .addAll(injector.getInstance(Key.get(new TypeLiteral<Set<HttpRequestFilter>>() {}, GlobalFilter.class))) .addAll(injector.getInstance(Key.get(new TypeLiteral<Set<HttpRequestFilter>>() {}, annotation))) .build(); verify(injector.getExistingBinding(Key.get(JettyIoPoolManager.class, annotation)) != null, "binding should exist"); JettyIoPoolManager ioPoolProvider = injector.getInstance(Key.get(JettyIoPoolManager.class, annotation)); JettyHttpClient client = new JettyHttpClient(config, kerberosConfig, Optional.of(ioPoolProvider.get()), ImmutableList.copyOf(filters)); ioPoolProvider.addClient(client); return client; }

Target:
public HttpClient get() { KerberosConfig kerberosConfig = injector.getInstance(KerberosConfig.class); HttpClientConfig config = injector.getInstance(Key.get(HttpClientConfig.class, annotation)); Set<HttpRequestFilter> filters = ImmutableSet.<HttpRequestFilter>builder() .addAll(injector.getInstance(Key.get(new TypeLiteral<Set<HttpRequestFilter>>() {}, GlobalFilter.class))) .addAll(injector.getInstance(Key.get(new TypeLiteral<Set<HttpRequestFilter>>() {}, annotation))) .build(); JettyIoPoolManager ioPoolProvider = injector.getInstance(Key.get(JettyIoPoolManager.class, annotation)); JettyHttpClient client = new JettyHttpClient(config, kerberosConfig, Optional.of(ioPoolProvider.get()), ImmutableList.copyOf(filters)); ioPoolProvider.setClient(client); return client; }
Source:
public void testFailedRun() { final MockExecutorLoader loader = new MockExecutorLoader(); final EventCollectorListener eventCollector = new EventCollectorListener(); final JobRunner runner = createJobRunner(1, "testJob", 0, true, loader, eventCollector); final ExecutableNode node = runner.getNode(); Assert.assertTrue(runner.getStatus() != Status.SUCCEEDED || runner.getStatus() != Status.FAILED); runner.run(); Assert.assertTrue(runner.getStatus() == node.getStatus()); Assert.assertTrue(node.getStatus() == Status.FAILED); Assert.assertTrue(node.getStartTime() > 0 && node.getEndTime() >= 0); Assert.assertTrue(node.getEndTime() - node.getStartTime() >= 0); final File logFile = new File(runner.getLogFilePath()); final Props outputProps = runner.getNode().getOutputProps(); Assert.assertTrue(outputProps.toProperties().isEmpty()); Assert.assertTrue(logFile.exists()); Assert.assertTrue(eventCollector.checkOrdering()); Assert.assertTrue(!runner.isKilled()); Assert.assertTrue(loader.getNodeUpdateCount(node.getId()) == 3); eventCollector .assertEvents(EventType.JOB_STARTED, EventType.JOB_STATUS_CHANGED, EventType.JOB_FINISHED); }

Target:
public void testFailedRun() { final MockExecutorLoader loader = new MockExecutorLoader(); final EventCollectorListener eventCollector = new EventCollectorListener(); final JobRunner runner = createJobRunner(1, "testJob", 0, true, loader, eventCollector); final ExecutableNode node = runner.getNode(); Assert.assertTrue(runner.getStatus() != Status.SUCCEEDED || runner.getStatus() != Status.FAILED); runner.run(); Assert.assertTrue(runner.getStatus() == node.getStatus()); Assert.assertTrue(node.getStatus() == Status.FAILED); Assert.assertTrue(node.getStartTime() > 0 && node.getEndTime() >= 0); final File logFile = new File(runner.getLogFilePath()); final Props outputProps = runner.getNode().getOutputProps(); Assert.assertEquals(0, outputProps.size()); Assert.assertTrue(logFile.exists()); Assert.assertTrue(eventCollector.checkOrdering()); Assert.assertTrue(!runner.isKilled()); Assert.assertTrue(loader.getNodeUpdateCount(node.getId()) == 3); eventCollector .assertEvents(EventType.JOB_STARTED, EventType.JOB_STATUS_CHANGED, EventType.JOB_FINISHED); }
Source:
private static String fetchLatestStableChromeDriverVersion() { String version = null; try { URL url = new URL(CHROME_DRIVER_LATEST_RELEASE_URL); URLConnection urlConnection = url.openConnection(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); StringBuilder content = new StringBuilder(); content.append(bufferedReader.readLine()); bufferedReader.close(); version = content.toString(); logger.info("Latest Chrome Driver Release found: " + version); } catch(Exception exception){ logger.error("Failed to fetch latest Chrome Driver Release"); } return version; }

Target:
private static String fetchLatestStableChromeDriverVersion() { String version = ""; try { URL url = new URL(CHROME_DRIVER_LATEST_RELEASE_URL); URLConnection urlConnection = url.openConnection(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); StringBuilder content = new StringBuilder(); content.append(bufferedReader.readLine()); bufferedReader.close(); version = content.toString(); logger.info("Latest Chrome Driver Release found: " + version); } catch (MalformedURLException exception) { logger.error("URL for fetching Chrome Release is malformed."); } catch (IOException exception) { logger.error("Failed to fetch latest Chrome Driver Release"); } return version; }
Source:
public static List<DiffEntry> scan(TreeWalk walk, boolean includeTrees) throws IOException { if (includeTrees && walk.isRecursive()) throw new IllegalAccessError( JGitText.get().cannotBeRecursiveWhenTreesAreIncluded); List<DiffEntry> r = new ArrayList<DiffEntry>(); MutableObjectId idBuf = new MutableObjectId(); while (walk.next()) { DiffEntry entry = new DiffEntry(); walk.getObjectId(idBuf, 0); entry.oldId = AbbreviatedObjectId.fromObjectId(idBuf); walk.getObjectId(idBuf, 1); entry.newId = AbbreviatedObjectId.fromObjectId(idBuf); entry.oldMode = walk.getFileMode(0); entry.newMode = walk.getFileMode(1); entry.newPath = entry.oldPath = walk.getPathString(); if (entry.oldMode == FileMode.MISSING) { entry.oldPath = DiffEntry.DEV_NULL; entry.changeType = ChangeType.ADD; r.add(entry); } else if (entry.newMode == FileMode.MISSING) { entry.newPath = DiffEntry.DEV_NULL; entry.changeType = ChangeType.DELETE; r.add(entry); } else { entry.changeType = ChangeType.MODIFY; if (RenameDetector.sameType(entry.oldMode, entry.newMode)) r.add(entry); else r.addAll(breakModify(entry)); } if (includeTrees && walk.isSubtree()) walk.enterSubtree(); } return r; }

Target:
public static List<DiffEntry> scan(TreeWalk walk, boolean includeTrees) throws IOException { if (includeTrees && walk.isRecursive()) throw new IllegalArgumentException( JGitText.get().cannotBeRecursiveWhenTreesAreIncluded); List<DiffEntry> r = new ArrayList<DiffEntry>(); MutableObjectId idBuf = new MutableObjectId(); while (walk.next()) { DiffEntry entry = new DiffEntry(); walk.getObjectId(idBuf, 0); entry.oldId = AbbreviatedObjectId.fromObjectId(idBuf); walk.getObjectId(idBuf, 1); entry.newId = AbbreviatedObjectId.fromObjectId(idBuf); entry.oldMode = walk.getFileMode(0); entry.newMode = walk.getFileMode(1); entry.newPath = entry.oldPath = walk.getPathString(); if (entry.oldMode == FileMode.MISSING) { entry.oldPath = DiffEntry.DEV_NULL; entry.changeType = ChangeType.ADD; r.add(entry); } else if (entry.newMode == FileMode.MISSING) { entry.newPath = DiffEntry.DEV_NULL; entry.changeType = ChangeType.DELETE; r.add(entry); } else { entry.changeType = ChangeType.MODIFY; if (RenameDetector.sameType(entry.oldMode, entry.newMode)) r.add(entry); else r.addAll(breakModify(entry)); } if (includeTrees && walk.isSubtree()) walk.enterSubtree(); } return r; }
Source:
public void onPartitionsRevoked(Collection<TopicPartition> topicPartitions) { _logger.info("Partition ownership revoked for {}, checkpointing.", topicPartitions); if (!_shutdown && !topicPartitions.isEmpty()) { try { maybeCommitOffsets(_consumer, true); } catch (Exception e) { _logger.warn("Caught exception while trying to commit offsets in onPartitionsRevoked with partitions {}.", topicPartitions, e); } } synchronized (_consumerAssignment) { _consumerAssignment.clear(); _consumerAssignment.addAll(_consumer.assignment()); } _logger.info("Current assignment is {}", _consumerAssignment); _kafkaPositionTrackerTask.retainAll(_consumerAssignment); _taskUpdates.add(DatastreamConstants.UpdateType.PAUSE_RESUME_PARTITIONS); }

Target:
public void onPartitionsRevoked(Collection<TopicPartition> topicPartitions) { _logger.info("Partition ownership revoked for {}, checkpointing.", topicPartitions); if (!_shutdown && !topicPartitions.isEmpty()) { try { maybeCommitOffsets(_consumer, true); } catch (Exception e) { _logger.warn("Caught exception while trying to commit offsets in onPartitionsRevoked with partitions {}.", topicPartitions, e); } } _consumerAssignment.clear(); _consumerAssignment.addAll(_consumer.assignment()); _logger.info("Current assignment is {}", _consumerAssignment); _kafkaPositionTracker.retainAll(_consumerAssignment); _taskUpdates.add(DatastreamConstants.UpdateType.PAUSE_RESUME_PARTITIONS); }
Source:
private List<Pair<Guid, Boolean>> disconnectOrConnectHostsInUpToDomainStorageServer(ActionType actionType) { List<VDS> hostsInStatusUp = getAllRunningVdssInPool(); List<Callable<Pair<Guid, Boolean>>> callables = new LinkedList<>(); for (final VDS vds : hostsInStatusUp) { callables.add(() -> { Pair<Guid, Boolean> toReturn = new Pair<>(vds.getId(), Boolean.FALSE); try { boolean connectResult = false; switch (actionType) { case CONNECT: connectResult = StorageHelperDirector.getInstance().getItem(getStorageDomain().getStorageType()) .connectStorageToDomainByVdsId(getStorageDomain(), vds.getId()); break; case DISCONNECT: connectResult = StorageHelperDirector.getInstance().getItem(getStorageDomain().getStorageType()) .disconnectStorageFromDomainByVdsId(getStorageDomain(), vds.getId()); } toReturn.setSecond(connectResult); } catch (RuntimeException e) { log.error("Failed to host '{}' to storage domain (name '{}', id '{}'): {}", actionType.actionDescription, vds.getName(), getStorageDomain().getName(), getStorageDomain().getId(), e.getMessage()); log.debug("Exception", e); } return toReturn; }); } return ThreadPoolUtil.invokeAll(callables); }

Target:
private List<Pair<Guid, Boolean>> disconnectOrConnectHostsInUpToDomainStorageServer(ActionType actionType) { List<VDS> hostsInStatusUp = getAllRunningVdssInPool(); List<Callable<Pair<Guid, Boolean>>> callables = new LinkedList<>(); for (final VDS vds : hostsInStatusUp) { callables.add(() -> { Pair<Guid, Boolean> toReturn = new Pair<>(vds.getId(), Boolean.FALSE); try { boolean connectResult = false; switch (actionType) { case CONNECT: connectResult = StorageHelperDirector.getInstance().getItem(getStorageDomain().getStorageType()) .connectStorageToDomainByVdsId(getStorageDomain(), vds.getId()); break; case DISCONNECT: connectResult = StorageHelperDirector.getInstance().getItem(getStorageDomain().getStorageType()) .disconnectStorageFromDomainByVdsId(getStorageDomain(), vds.getId()); break; } toReturn.setSecond(connectResult); } catch (RuntimeException e) { log.error("Failed to host '{}' to storage domain (name '{}', id '{}'): {}", actionType.actionDescription, vds.getName(), getStorageDomain().getName(), getStorageDomain().getId(), e.getMessage()); log.debug("Exception", e); } return toReturn; }); } return ThreadPoolUtil.invokeAll(callables); }
Source:
private void DiskInterface_SelectedItemChanged() { boolean isLunDisk = getDiskStorageType().getEntity() == DiskStorageType.LUN; DiskInterface diskInterface = getDiskInterface().getSelectedItem(); getIsSgIoUnfiltered().setIsAvailable(isLunDisk && DiskInterface.VirtIO_SCSI.equals(diskInterface)); getIsScsiPassthrough().setIsAvailable(isLunDisk && DiskInterface.VirtIO_SCSI.equals(diskInterface)); getIsUsingScsiReservation().setIsAvailable(isLunDisk && DiskInterface.VirtIO_SCSI.equals(diskInterface)); updateScsiPassthroguhChangeability(); changeScsiReservationChangeability(); updateReadOnlyChangeability(); updatePlugChangeability(); }

Target:
private void DiskInterface_SelectedItemChanged() { boolean isLunDisk = getDiskStorageType().getEntity() == DiskStorageType.LUN; DiskInterface diskInterface = getDiskInterface().getSelectedItem(); getIsSgIoUnfiltered().setIsAvailable(isLunDisk && DiskInterface.VirtIO_SCSI.equals(diskInterface)); getIsScsiPassthrough().setIsAvailable(isLunDisk && DiskInterface.VirtIO_SCSI.equals(diskInterface)); getIsUsingScsiReservation().setIsAvailable(isLunDisk && DiskInterface.VirtIO_SCSI.equals(diskInterface)); updateScsiPassthroguhChangeability(); updateScsiReservationChangeability(); updateReadOnlyChangeability(); updatePlugChangeability(); }
Source:
public double pidGet() { switch (pidSource) { case kRate: return getRate(); case kDisplacement: default: return getDistance(); } }

Target:
public double pidGet() { if (pidSource == PIDSourceType.kDisplacement) { return getDistance(); } return getRate(); }
Source:
private void getImageChildren(Guid snapshot, List<DiskImage> children) { List<DiskImage> snapshots = diskImageDao.getAllSnapshotsForParent(snapshot).stream() .collect(Collectors.toList()); children.addAll(snapshots); snapshots.forEach(s -> getImageChildren(s.getId(), children)); }

Target:
private void getImageChildren(Guid snapshot, List<DiskImage> children) { List<DiskImage> snapshots = diskImageDao.getAllSnapshotsForParent(snapshot); children.addAll(snapshots); snapshots.forEach(s -> getImageChildren(s.getId(), children)); }
Source:
private void applyHttp1xConnectionOptions(ChannelPipeline pipeline) { if (options.getIdleTimeout() > 0) { pipeline.addLast("idle", new IdleStateHandler(0, 0, options.getIdleTimeout(), options.getIdleTimeoutUnit())); } if (options.getLogActivity()) { pipeline.addLast("logging", new LoggingHandler()); } pipeline.addLast("codec", new HttpClientCodec( options.getMaxInitialLineLength(), options.getMaxHeaderSize(), options.getMaxChunkSize(), false, false, options.getDecoderInitialBufferSize())); if (options.isTryUseCompression()) { pipeline.addLast("inflater", new HttpContentDecompressor()); } }

Target:
private void applyHttp1xConnectionOptions(ChannelPipeline pipeline) { if (options.getIdleTimeout() > 0) { pipeline.addLast("idle", new IdleStateHandler(0, 0, options.getIdleTimeout(), options.getIdleTimeoutUnit())); } if (options.getLogActivity()) { pipeline.addLast("logging", new LoggingHandler()); } pipeline.addLast("codec", new HttpClientCodec( options.getMaxInitialLineLength(), options.getMaxHeaderSize(), options.getMaxChunkSize(), false, false, options.getDecoderInitialBufferSize())); if (options.isTryUseCompression()) { pipeline.addLast("inflater", new HttpContentDecompressor(false)); } }
Source:
public void channelRead0(ChannelHandlerContext ctx, Batch batch) throws Exception { if(logger.isDebugEnabled()) { logger.debug(format("XXXXXXXReceived a new payload")); } ctx.channel().attr(PROCESSING_BATCH).set(true); for(Message message : batch.getMessages()) { if(logger.isDebugEnabled()) { logger.debug(format("Sending a new message for the listener, sequence: " + message.getSequence())); } messageListener.onNewMessage(ctx, message); if(needAck(message)) { ack(ctx, message); } } ctx.flush(); ctx.channel().attr(PROCESSING_BATCH).set(false); }

Target:
public void channelRead0(ChannelHandlerContext ctx, Batch batch) throws Exception { if(logger.isDebugEnabled()) { logger.debug(format("Received a new payload")); } ctx.channel().attr(PROCESSING_BATCH).set(true); for(Message message : batch.getMessages()) { if(logger.isDebugEnabled()) { logger.debug(format("Sending a new message for the listener, sequence: " + message.getSequence())); } messageListener.onNewMessage(ctx, message); if(needAck(message)) { ack(ctx, message); } } ctx.flush(); ctx.channel().attr(PROCESSING_BATCH).set(false); }
Source:
private static GoStructType getLiteralStructType(@Nullable GoLiteralValue literalValue) { GoCompositeLit parentLit = GoPsiTreeUtil.getDirectParentOfType(literalValue, GoCompositeLit.class); if (parentLit != null && !isStructLit(parentLit)) return null; GoStructType litType = ObjectUtils.tryCast(GoPsiImplUtil.getLiteralType(literalValue, parentLit == null), GoStructType.class); String definitionName = getFieldDefinitionName(GoPsiTreeUtil.getDirectParentOfType(literalValue, GoValue.class)); return definitionName != null && litType != null ? getFieldDefinitionType(litType, definitionName) : litType; }

Target:
private static GoStructType getLiteralStructType(@Nullable GoLiteralValue literalValue) { GoCompositeLit parentLit = GoPsiTreeUtil.getDirectParentOfType(literalValue, GoCompositeLit.class); if (parentLit != null && !isStructLit(parentLit)) return null; GoStructType litType = ObjectUtils.tryCast(GoPsiImplUtil.getLiteralType(literalValue, parentLit == null), GoStructType.class); GoNamedElement definition = getFieldDefinition(GoPsiTreeUtil.getDirectParentOfType(literalValue, GoValue.class)); return definition != null && litType != null ? getUnderlyingStructType(definition.getGoType(null)) : litType; }
Source:
public void setDeviceLifecycleStatus(final String organisationIdentification, final String deviceIdentification, final String correlationUid, final DeviceLifecycleStatus deviceLifecycleStatus) throws FunctionalException { LOGGER.debug( "SetDeviceLifecycleStatus called with organisation {}, deviceLifecycleStatus and deviceIdentification {}", organisationIdentification, deviceLifecycleStatus.name(), deviceIdentification); this.findOrganisation(organisationIdentification); final Device device = this.deviceDomainService.searchDevice(deviceIdentification); device.setDeviceLifecycleStatus(deviceLifecycleStatus); this.deviceDomainService.saveDevice(device); final ResponseMessageResultType result = ResponseMessageResultType.OK; this.webServiceResponseMessageSender.send(ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(correlationUid).withOrganisationIdentification(organisationIdentification) .withDeviceIdentification(deviceIdentification).withResult(result).build()); }

Target:
public void setDeviceLifecycleStatus(final String organisationIdentification, final String deviceIdentification, final String correlationUid, final DeviceLifecycleStatus deviceLifecycleStatus) throws FunctionalException { LOGGER.debug( "SetDeviceLifecycleStatus called with organisation {}, deviceLifecycleStatus and deviceIdentification {}", organisationIdentification, deviceLifecycleStatus.name(), deviceIdentification); this.findOrganisation(organisationIdentification); final Device device = this.deviceDomainService.searchDevice(deviceIdentification); device.setDeviceLifecycleStatus(deviceLifecycleStatus); this.deviceDomainService.saveDevice(device); final ResponseMessageResultType result = ResponseMessageResultType.OK; ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(correlationUid).withOrganisationIdentification(organisationIdentification) .withDeviceIdentification(deviceIdentification).withResult(result).build(); this.webServiceResponseMessageSender.send(responseMessage); }