auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private synchronized CompletableFuture<Boolean> ensureUptodate(NetworkAccess network) { return network.retrieveEntryPoint(sharedDir) .thenCompose(sharedDirOpt -> { if (!sharedDirOpt.isPresent()) return CompletableFuture.completedFuture(true); return CapabilityStore.getReadOnlyCapabilityFileSize(sharedDirOpt.get(), network) .thenCompose(count -> { if (count == capCountReadOnly) { return addEditableCapabilities(sharedDirOpt, network); } else { return CapabilityStore.loadReadAccessSharingLinksFromIndex(homeDirSupplier, sharedDirOpt.get(), ownerName, network, random, hasher, capCountReadOnly, true) .thenCompose(newReadCaps -> { capCountReadOnly += newReadCaps.getBytesRead(); root = newReadCaps.getRetrievedCapabilities().stream() .reduce(root, (root, cap) -> root.put(trimOwner(cap.path), new EntryPoint(cap.cap, ownerName)), (a, b) -> a); return addEditableCapabilities(sharedDirOpt, network); }); } }); }); }

Target:
private synchronized CompletableFuture<Boolean> ensureUptodate(NetworkAccess network) { return network.retrieveEntryPoint(sharedDir) .thenCompose(sharedDirOpt -> { if (!sharedDirOpt.isPresent()) return CompletableFuture.completedFuture(true); return CapabilityStore.getReadOnlyCapabilityFileSize(sharedDirOpt.get(), network) .thenCompose(bytes -> { if (bytes == byteOffsetReadOnly) { return addEditableCapabilities(sharedDirOpt, network); } else { return CapabilityStore.loadReadAccessSharingLinksFromIndex(homeDirSupplier, sharedDirOpt.get(), ownerName, network, random, hasher, byteOffsetReadOnly, true) .thenCompose(newReadCaps -> { byteOffsetReadOnly += newReadCaps.getBytesRead(); root = newReadCaps.getRetrievedCapabilities().stream() .reduce(root, (root, cap) -> root.put(trimOwner(cap.path), new EntryPoint(cap.cap, ownerName)), (a, b) -> a); return addEditableCapabilities(sharedDirOpt, network); }); } }); }); }
Source:
public void testUnitPath() throws Exception { List<PID> pids = makePidList(1); when(pathFactory.getAncestorPids(pid)).thenReturn(pids); filter.filter(dip); verify(idb, never()).setParentUnit(anyString()); verify(idb, never()).setParentCollection(anyString()); }

Target:
public void testUnitPath() throws Exception { List<PID> pids = makePidList(1); when(pathFactory.getAncestorPids(pid)).thenReturn(pids); filter.filter(dip); verify(idb).setAncestorPath(listCaptor.capture()); List<String> ancestorPath = listCaptor.getValue(); ancestorPathCheck(ancestorPath, pids); assertEquals(1, ancestorPath.size()); verify(idb, never()).setParentUnit(anyString()); verify(idb, never()).setParentCollection(anyString()); }
Source:
public void prepareRun(StageSubmitterContext context) throws Exception { super.prepareRun(context); init(); if (fields != null) { FieldOperation operation = new FieldTransformOperation("CSV Parse", "Parsing the field.", Collections.singletonList(config.field), fields.stream().map(Schema.Field::getName) .collect(Collectors.toList())); context.record(Collections.singletonList(operation)); } }

Target:
public void prepareRun(StageSubmitterContext context) throws Exception { super.prepareRun(context); init(); if (fields != null) { FieldOperation operation = new FieldTransformOperation("Parse", "Parsed field", Collections.singletonList(config.field), fields.stream().map(Schema.Field::getName) .collect(Collectors.toList())); context.record(Collections.singletonList(operation)); } }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; State state = (State) o; if (!nt.equals(state.nt)) return false; if (!stateId.equals(state.stateId)) return false; return true; }

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; State state = (State) o; if (unique != state.unique) return false; return true; }
Source:
public static H2Config.Builder initial() { return new Builder() .setHeaderTableSize(INIT_HEADER_TABLE_SIZE) .setPushEnabled(INIT_ENABLE_PUSH) .setMaxConcurrentStreams(Integer.MAX_VALUE) .setMaxFrameSize(INIT_MAX_FRAME_SIZE) .setInitialWindowSize(INIT_WINDOW_SIZE); }

Target:
public static H2Config.Builder initial() { return new Builder() .setHeaderTableSize(INIT_HEADER_TABLE_SIZE) .setPushEnabled(INIT_ENABLE_PUSH) .setMaxConcurrentStreams(Integer.MAX_VALUE) .setMaxFrameSize(INIT_MAX_FRAME_SIZE) .setInitialWindowSize(INIT_WINDOW_SIZE) .setMaxHeaderListSize(Integer.MAX_VALUE); }
Source:
protected static void initialiseOutbound(Node n, long baseTime, CommunicationDetails cd, StringBuilder nodeId) { CommunicationDetails.Outbound ob = new CommunicationDetails.Outbound(); ob.getIds().add(nodeId.toString()); ob.setMultiConsumer(true); ob.setProducerOffset(TimeUnit.MILLISECONDS.convert((n.getBaseTime() - baseTime), TimeUnit.NANOSECONDS)); cd.getOutbound().add(ob); if (n.getClass() == Producer.class) { ob = new CommunicationDetails.Outbound(); for (int j = 0; j < ((Producer) n).getCorrelationIds().size(); j++) { CorrelationIdentifier ci = ((Producer) n).getCorrelationIds().get(j); if (ci.getScope() == Scope.Interaction || ci.getScope() == Scope.ControlFlow) { ob.getIds().add(ci.getValue()); } } if (!ob.getIds().isEmpty()) { ob.setMultiConsumer(((Producer) n).multipleConsumers()); ob.setProducerOffset(TimeUnit.MILLISECONDS.convert((n.getBaseTime() - baseTime), TimeUnit.NANOSECONDS)); cd.getOutbound().add(ob); } } else if (n.containerNode()) { for (int i = 0; i < ((ContainerNode)n).getNodes().size(); i++) { int len = nodeId.length(); nodeId.append(':'); nodeId.append(i); initialiseOutbound(((ContainerNode) n).getNodes().get(i), baseTime, cd, nodeId); nodeId.delete(len, nodeId.length()); } } }

Target:
protected static void initialiseOutbound(Node n, long baseTime, CommunicationDetails cd, StringBuilder nodeId) { CommunicationDetails.Outbound ob = new CommunicationDetails.Outbound(); ob.getIds().add(nodeId.toString()); ob.setMultiConsumer(true); ob.setProducerOffset(TimeUnit.MILLISECONDS.convert((n.getBaseTime() - baseTime), TimeUnit.NANOSECONDS)); cd.getOutbound().add(ob); if (n.getClass() == Producer.class) { ob = new CommunicationDetails.Outbound(); for (int j = 0; j < n.getCorrelationIds().size(); j++) { CorrelationIdentifier ci = n.getCorrelationIds().get(j); if (ci.getScope() == Scope.Interaction || ci.getScope() == Scope.ControlFlow) { ob.getIds().add(ci.getValue()); } } if (!ob.getIds().isEmpty()) { ob.setMultiConsumer(((Producer) n).multipleConsumers()); ob.setProducerOffset(TimeUnit.MILLISECONDS.convert((n.getBaseTime() - baseTime), TimeUnit.NANOSECONDS)); cd.getOutbound().add(ob); } } else if (n.containerNode()) { for (int i = 0; i < ((ContainerNode)n).getNodes().size(); i++) { int len = nodeId.length(); nodeId.append(':'); nodeId.append(i); initialiseOutbound(((ContainerNode) n).getNodes().get(i), baseTime, cd, nodeId); nodeId.delete(len, nodeId.length()); } } }
Source:
public static boolean isCompressionCodecSupported(InputFormat inputFormat, Path path) { if (inputFormat instanceof TextInputFormat) { try { CompressionCodec compressionCodec = HiveUtil.getCompressionCodec((TextInputFormat) inputFormat, path); if (compressionCodec == null || Arrays.stream(S3SelectSupportedCompressionCodecs.values()) .anyMatch(c -> c.codecClass.isInstance(compressionCodec))) { return true; } } catch (IllegalAccessException | NoSuchFieldException e) { log.error(e, "Failed to find compressionCodec for inputFormat: %s", inputFormat.getClass().getName()); return false; } } return false; }

Target:
public static boolean isCompressionCodecSupported(InputFormat inputFormat, Path path) { if (inputFormat instanceof TextInputFormat) { try { Optional<CompressionCodec> compressionCodec = getCompressionCodec((TextInputFormat) inputFormat, path); if (!compressionCodec.isPresent() || stream(S3SelectSupportedCompressionCodecs.values()) .anyMatch(codec -> codec.getCodecClass().isInstance(compressionCodec.get()))) { return true; } } catch (IllegalAccessException | NoSuchFieldException e) { LOG.error(e, "Failed to find compressionCodec for inputFormat: %s", inputFormat.getClass().getName()); return false; } } return false; }
Source:
private String getTSUIDForMetric(final String query_string, TSDB tsdb) { if (query_string == null || query_string.isEmpty()) { throw new BadRequestException("The query string was empty"); } HashMap<String, String> tags = new HashMap<String, String>(); String metric = null; try { metric = Tags.parseWithMetric(query_string, tags); } catch (IllegalArgumentException e) { throw new BadRequestException(e.getMessage()); } TreeMap<String, String> sortedTags = new TreeMap<String, String>(tags); ByteArrayOutputStream buf = new ByteArrayOutputStream(); buf.write(tsdb.getUID(UniqueIdType.METRIC, metric), 0, 3); for (Entry<String, String> e : sortedTags.entrySet()) { buf.write(tsdb.getUID(UniqueIdType.TAGK, e.getKey()), 0, 3); buf.write(tsdb.getUID(UniqueIdType.TAGV, e.getValue()), 0, 3); } String tsuid = UniqueId.uidToString(buf.toByteArray()); return tsuid; }

Target:
private String getTSUIDForMetric(final String query_string, TSDB tsdb) { if (query_string == null || query_string.isEmpty()) { throw new BadRequestException("The query string was empty"); } final HashMap<String, String> tags = new HashMap<String, String>(); String metric = null; try { metric = Tags.parseWithMetric(query_string, tags); } catch (IllegalArgumentException e) { throw new BadRequestException(e); } final TreeMap<String, String> sortedTags = new TreeMap<String, String>(tags); final ByteArrayOutputStream buf = new ByteArrayOutputStream( TSDB.metrics_width() + sortedTags.size() * (TSDB.tagk_width() + TSDB.tagv_width())); try { buf.write(tsdb.getUID(UniqueIdType.METRIC, metric)); for (Entry<String, String> e: sortedTags.entrySet()) { buf.write(tsdb.getUID(UniqueIdType.TAGK, e.getKey()), 0, 3); buf.write(tsdb.getUID(UniqueIdType.TAGV, e.getValue()), 0, 3); } } catch (IOException e) { throw new BadRequestException(e); } final String tsuid = UniqueId.uidToString(buf.toByteArray()); return tsuid; }
Source:
public void subscribeToTopic(final String topic, final AWSIotMqttQos qos, final AWSIotMqttSubscriptionStatusCallback subscriptionStatusCallback, final AWSIotMqttNewMessageCallback callback) { if (topic == null || topic.isEmpty()) { throw new IllegalArgumentException("topic is null or empty"); } if (qos == null) { throw new IllegalArgumentException("QoS cannot be null."); } if (null != mqttClient) { try { if (subscriptionStatusCallback != null) { mqttClient.subscribe(topic, qos.asInt(), null, new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { subscriptionStatusCallback.onSuccess(); } @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { subscriptionStatusCallback.onFailure(exception); } }); } else { mqttClient.subscribe(topic, qos.asInt()); } } catch (final MqttException e) { throw new AmazonClientException("Client error when subscribing.", e); } final AWSIotMqttTopic topicModel = new AWSIotMqttTopic(topic, qos, callback); topicListeners.put(topic, topicModel); } }

Target:
public void subscribeToTopic(final String topic, final AWSIotMqttQos qos, final AWSIotMqttSubscriptionStatusCallback subscriptionStatusCallback, final AWSIotMqttNewMessageCallback callback) { if (topic == null || topic.isEmpty()) { throw new IllegalArgumentException("topic is null or empty"); } if (qos == null) { throw new IllegalArgumentException("QoS cannot be null."); } if (null != mqttClient) { try { if (subscriptionStatusCallback != null) { mqttClient.subscribe(topic, qos.asInt(), null, new IMqttActionListener() { @Override public void onSuccess(IMqttToken asyncActionToken) { subscriptionStatusCallback.onSuccess(); } @Override public void onFailure(IMqttToken asyncActionToken, Throwable exception) { subscriptionStatusCallback.onFailure(exception); } }); } else { mqttClient.subscribe(topic, qos.asInt()); } } catch (final MqttException e) { if(subscriptionStatusCallback != null) { subscriptionStatusCallback.onFailure(e); } else { throw new AmazonClientException("Client error when subscribing.", e); } } final AWSIotMqttTopic topicModel = new AWSIotMqttTopic(topic, qos, callback); topicListeners.put(topic, topicModel); } }
Source:
protected void validateValuesSafeToInject(String command, String[] targetVars) { for (int i = 0; i < targetVars.length; i++) { String targetVar = targetVars[i]; if (isGrouped) { for (List<? extends RDFNode> group : groupedItems) { RDFNode item = group.get(i); validateSafeToInject(command, targetVar, item.asNode()); } } else { if (targetVars.length > 1) { if (items instanceof List) { List<? extends RDFNode> listItems = (List<? extends RDFNode>) items; RDFNode item = listItems.get(i); validateSafeToInject(command, targetVar, item.asNode()); } else { throw new ARQException("Multiple VALUES variables (" + String.join(", ", targetVars) + ") being used without an ordered list of items: " + items.toString()); } } else { for (RDFNode item : items) { validateSafeToInject(command, targetVar, item.asNode()); } } } } }

Target:
protected void validateValuesSafeToInject(String command, String[] targetVars) { if (targetVars.length == 1) { String targetVar = targetVars[0]; for (List<? extends RDFNode> row : rowItems) { for (RDFNode item : row) { validateSafeToInject(command, targetVar, item.asNode()); } } } else { for (int i = 0; i < targetVars.length; i++) { String targetVar = targetVars[i]; for (List<? extends RDFNode> row : rowItems) { if (targetVars.length == row.size()) { RDFNode item = row.get(i); validateSafeToInject(command, targetVar, item.asNode()); } else { String rowString = row.stream().map(RDFNode::toString).collect(Collectors.joining(",")); throw new ARQException("Number of VALUES variables (" + String.join(", ", targetVars) + ") does not equal replacement row (" + rowString + ")."); } } } } }
Source:
public TextSelectionActivity(User source, TextSelection selection, IFile file) { this(source, selection, false, file); }

Target:
public TextSelectionActivity(User source, TextSelection selection, IFile file) { super(source, file); if (file == null) throw new IllegalArgumentException("file must not be null"); TextPosition startPosition = selection.getStartPosition(); this.startLine = startPosition.getLineNumber(); this.startInLineOffset = startPosition.getInLineOffset(); TextPosition endPosition = selection.getEndPosition(); this.endLine = endPosition.getLineNumber(); this.endInLineOffset = endPosition.getInLineOffset(); this.isBackwardsSelection = selection.isBackwardsSelection(); }
Source:
public void close(Reporter reporter) throws IOException { log.debug("mutations written: " + mutCount + ", values written: " + valCount); if (simulate) return; try { mtbw.close(); } catch (MutationsRejectedException e) { if (!e.getSecurityErrorCodes().isEmpty()) { HashMap<String,Set<SecurityErrorCode>> tables = new HashMap<>(); for (var ke : e.getSecurityErrorCodes().entrySet()) { String tableId = ke.getKey().getTableId().toString(); Set<SecurityErrorCode> secCodes = tables.computeIfAbsent(tableId, k -> new HashSet<>()); secCodes.addAll(ke.getValue()); } log.error("Not authorized to write to tables : " + tables); } if (e.getConstraintViolationSummaries().size() > 0) { log.error("Constraint violations : " + e.getConstraintViolationSummaries().size()); } throw new IOException(e); } finally { client.close(); } }

Target:
public void close(Reporter reporter) throws IOException { log.debug("mutations written: " + mutCount + ", values written: " + valCount); if (simulate) return; try { mtbw.close(); } catch (MutationsRejectedException e) { if (!e.getSecurityErrorCodes().isEmpty()) { var tables = new HashMap<String,Set<SecurityErrorCode>>(); e.getSecurityErrorCodes().forEach((tabletId, secSet) -> { var tableId = tabletId.getTableId().toString(); tables.computeIfAbsent(tableId, p -> new HashSet<>()).addAll(secSet); }); log.error("Not authorized to write to tables : " + tables); } if (e.getConstraintViolationSummaries().size() > 0) { log.error("Constraint violations : " + e.getConstraintViolationSummaries().size()); } throw new IOException(e); } finally { client.close(); } }
Source:
public void changeDiscoveryMode(){ validationProvider = new BeansXmlValidationProviderCDI11(); prepareBeanXml("all", true); }

Target:
public void changeDiscoveryMode(){ validationProvider = new BeansXmlValidationProviderCDI20(); prepareBeanXml("all", true); }
Source:
public void addInput(Page page) { requireNonNull(page, "page is null"); checkState(needsInput(), "Operator does not need input"); Block[] blocks = new Block[columnChannels.size()]; for (int outputChannel = 0; outputChannel < columnChannels.size(); outputChannel++) { blocks[outputChannel] = page.getBlock(columnChannels.get(outputChannel)); } statisticAggregation.addInput(page); ListenableFuture<?> blockedOnAggregation = statisticAggregation.isBlocked(); CompletableFuture<?> future = pageSink.appendPage(new Page(blocks)); updateMemoryUsage(); ListenableFuture<?> blockedOnWrite = toListenableFuture(future); if (blockedOnWrite.isDone() && blockedOnAggregation.isDone()) { blocked = NOT_BLOCKED; } else { blocked = allAsList(blockedOnAggregation, blockedOnWrite); } rowCount += page.getPositionCount(); updateWrittenBytes(); }

Target:
public void addInput(Page page) { requireNonNull(page, "page is null"); checkState(needsInput(), "Operator does not need input"); Block[] blocks = new Block[columnChannels.size()]; for (int outputChannel = 0; outputChannel < columnChannels.size(); outputChannel++) { blocks[outputChannel] = page.getBlock(columnChannels.get(outputChannel)); } statisticAggregationOperator.addInput(page); ListenableFuture<?> blockedOnAggregation = statisticAggregationOperator.isBlocked(); CompletableFuture<?> future = pageSink.appendPage(new Page(blocks)); updateMemoryUsage(); ListenableFuture<?> blockedOnWrite = toListenableFuture(future); blocked = allAsList(blockedOnAggregation, blockedOnWrite); rowCount += page.getPositionCount(); updateWrittenBytes(); }
Source:
private void move() { ArrayList<DiskImage> disks = (ArrayList<DiskImage>) getSelectedItems(); if (disks == null) { return; } if (getWindow() != null) { return; } VM vm = getEntity(); MoveDiskModel model = new MoveDiskModel(); setWindow(model); if (vm.getStatus().isUpOrPaused()) { model.setWarningAvailable(true); model.setMessage(ConstantsManager.getInstance().getConstants().liveStorageMigrationWarning()); model.setMessage(ConstantsManager.getInstance().getConstants().liveStorageMigrationStorageFilteringNote()); } model.setTitle(ConstantsManager.getInstance().getConstants().moveDisksTitle()); model.setHelpTag(HelpTag.move_disk); model.setHashName("move_disk"); model.setIsSourceStorageDomainNameAvailable(true); model.setEntity(this); model.init(disks); model.startProgress(null); }

Target:
private void move() { ArrayList<DiskImage> disks = (ArrayList<DiskImage>) getSelectedItems(); if (disks == null) { return; } if (getWindow() != null) { return; } VM vm = getEntity(); MoveDiskModel model = new MoveDiskModel(); setWindow(model); if (vm.isRunningAndQualifyForDisksMigration()) { model.setWarningAvailable(true); model.setMessage(ConstantsManager.getInstance().getConstants().liveStorageMigrationWarning()); model.setMessage(ConstantsManager.getInstance().getConstants().liveStorageMigrationStorageFilteringNote()); } model.setTitle(ConstantsManager.getInstance().getConstants().moveDisksTitle()); model.setHelpTag(HelpTag.move_disk); model.setHashName("move_disk"); model.setIsSourceStorageDomainNameAvailable(true); model.setEntity(this); model.init(disks); model.startProgress(null); }
Source:
public static LocalLauncher create( final List<Entry<String, String>> roleMapping, final Predicate<String> isDisabled, final GameData gameData) { final Predicate<Entry<String, String>> enabledPredicate = entry -> !isDisabled.test(entry.getValue()); final PlayerListing playerListing = new PlayerListing( null, roleMapping.stream() .collect(Collectors.toUnmodifiableMap(Entry::getKey, enabledPredicate::test)), roleMapping.stream() .filter(enabledPredicate) .collect( Collectors.toUnmodifiableMap( Entry::getKey, entry -> PlayerType.fromLabel(entry.getValue()))), gameData.getGameVersion(), gameData.getGameName(), String.valueOf(gameData.getCurrentRound()), null, null); return new LocalLauncher( GameSelector.fromGameData(gameData), new PlainRandomSource(), playerListing, null, new HeadedLaunchAction(null)); }

Target:
public static LocalLauncher create( final List<Entry<String, String>> roleMapping, final Predicate<String> isDisabled, final GameData gameData) { final Predicate<Entry<String, String>> isPlayerEnabled = entry -> !isDisabled.test(entry.getValue()); final PlayerListing playerListing = new PlayerListing( roleMapping.stream() .collect(Collectors.toUnmodifiableMap(Entry::getKey, isPlayerEnabled::test)), roleMapping.stream() .filter(isPlayerEnabled) .collect( Collectors.toUnmodifiableMap( Entry::getKey, entry -> PlayerType.fromLabel(entry.getValue()))), gameData.getGameVersion(), gameData.getGameName(), String.valueOf(gameData.getCurrentRound())); return new LocalLauncher( GameSelector.fromGameData(gameData), new PlainRandomSource(), playerListing, null, new HeadedLaunchAction(null)); }
Source:
public void visitImportFrom(ImportFrom importFrom) { hasUnresolvedWildcardImport |= (importFrom.isWildcardImport() && importFrom.hasUnresolvedWildcardImport()); super.visitImportFrom(importFrom); }

Target:
public void visitImportFrom(ImportFrom importFrom) { hasUnresolvedWildcardImport |= importFrom.hasUnresolvedWildcardImport(); super.visitImportFrom(importFrom); }
Source:
public String toString() { final StringBuilder sb = new StringBuilder("User{"); sb.append("id='").append(id).append('\''); sb.append(", senderId='").append(fromUser).append('\''); sb.append(", api='").append(api).append('\''); sb.append(", application='").append(application).append('\''); sb.append(", subject='").append(subject).append('\''); sb.append(", content='").append(content).append('\''); sb.append(", createdAt='").append(createdAt).append('\''); sb.append('}'); return sb.toString(); }

Target:
public String toString() { final StringBuilder sb = new StringBuilder("User{"); sb.append("id='").append(id).append('\''); sb.append(", fromUser='").append(fromUser).append('\''); sb.append(", api='").append(api).append('\''); sb.append(", application='").append(application).append('\''); sb.append(", subject='").append(subject).append('\''); sb.append(", content='").append(content).append('\''); sb.append(", createdAt='").append(createdAt).append('\''); sb.append('}'); return sb.toString(); }
Source:
static Map<String, EntryValue> convertBeanToEntryMap(Object bean) { Map<String, Object> buildAttributeValueMap = BeanUtilsExtended.buildObjectAttributeMap(bean); return Maps.transformEntries(buildAttributeValueMap, new ObjectToEntryValueTransformer()); }

Target:
public static Map<String, EntryValue> convertBeanToEntryMap(Object bean) { Map<String, Object> buildAttributeValueMap = BeanUtilsExtended.buildObjectAttributeMap(bean); return Maps.transformEntries(buildAttributeValueMap, new ObjectToEntryValueTransformer()); }
Source:
public void addSubAttribute(Attribute newSubAttribute) { if (newSubAttribute == null || newSubAttribute.getName() == null || newSubAttribute.getName().equals(this.getName())) { throw new IllegalArgumentException(); } subAttributes.put(newSubAttribute.getName(), newSubAttribute); }

Target:
public void addSubAttribute(Attribute newSubAttribute) { if (newSubAttribute == null || newSubAttribute.getName() == null) { throw new IllegalArgumentException(); } subAttributes.put(newSubAttribute.getName(), newSubAttribute); }
Source:
private InputPort<Object> wsOutput(DAG dag, String operatorName) { String daemonAddress = dag.getValue(DAG.GATEWAY_CONNECT_ADDRESS); if (!StringUtils.isEmpty(daemonAddress)) { URI uri = URI.create((dag.getValue(DAG.GATEWAY_USE_SSL) ? "wss://" : "ws://") + daemonAddress + "/pubsub"); String appId = "appid"; String topic = "apps.logstream." + appId + "." + operatorName; PubSubWebSocketOutputOperator<Object> wsOut = dag.addOperator(operatorName, new PubSubWebSocketOutputOperator<Object>()); wsOut.setUri(uri); wsOut.setTopic(topic); return wsOut.input; } ConsoleOutputOperator operator = dag.addOperator(operatorName, new ConsoleOutputOperator()); operator.setStringFormat(operatorName + ": %s"); return operator.input; }

Target:
private InputPort<Object> wsOutput(DAG dag, String operatorName) { if (PubSubHelper.isGatewayConfigured(dag)) { String appId = "appid"; String topic = "apps.logstream." + appId + "." + operatorName; PubSubWebSocketOutputOperator<Object> wsOut = dag.addOperator(operatorName, new PubSubWebSocketOutputOperator<Object>()); wsOut.setUri(PubSubHelper.getURI(dag)); wsOut.setTopic(topic); return wsOut.input; } ConsoleOutputOperator operator = dag.addOperator(operatorName, new ConsoleOutputOperator()); operator.setStringFormat(operatorName + ": %s"); return operator.input; }
Source:
public void handleGetStatusResponse(final com.alliander.osgp.dto.valueobjects.DeviceStatusDto deviceStatusDto, final DomainType allowedDomainType, final String deviceIdentification, final String organisationIdentification, final String correlationUid, final String messageType, final ResponseMessageResultType deviceResult, final OsgpException exception) { LOGGER.info("handleResponse for MessageType: {}", messageType); final GetStatusResponse response = new GetStatusResponse(); response.setOsgpException(exception); response.setResult(deviceResult); if (deviceResult == ResponseMessageResultType.NOT_OK || exception != null) { LOGGER.error("Device Response not ok.", exception); } else { final DeviceStatus status = this.domainCoreMapper.map(deviceStatusDto, DeviceStatus.class); try { final Device dev = this.deviceDomainService.searchDevice(deviceIdentification); if (LightMeasurementDevice.LMD_TYPE.equals(dev.getDeviceType())) { this.handleLmd(status, response); } else { this.handleSsld(deviceIdentification, status, allowedDomainType, response); } } catch (final FunctionalException e) { LOGGER.error("Caught FunctionalException", e); } } this.webServiceResponseMessageSender.send(ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(correlationUid).withOrganisationIdentification(organisationIdentification) .withDeviceIdentification(deviceIdentification).withResult(response.getResult()) .withOsgpException(response.getOsgpException()).withDataObject(response.getDeviceStatusMapped()) .build()); }

Target:
public void handleGetStatusResponse(final com.alliander.osgp.dto.valueobjects.DeviceStatusDto deviceStatusDto, final DomainType allowedDomainType, final String deviceIdentification, final String organisationIdentification, final String correlationUid, final String messageType, final ResponseMessageResultType deviceResult, final OsgpException exception) { LOGGER.info("handleResponse for MessageType: {}", messageType); final GetStatusResponse response = new GetStatusResponse(); response.setOsgpException(exception); response.setResult(deviceResult); if (deviceResult == ResponseMessageResultType.NOT_OK || exception != null) { LOGGER.error("Device Response not ok.", exception); } else { final DeviceStatus status = this.domainCoreMapper.map(deviceStatusDto, DeviceStatus.class); try { final Device dev = this.deviceDomainService.searchDevice(deviceIdentification); if (LightMeasurementDevice.LMD_TYPE.equals(dev.getDeviceType())) { this.handleLmd(status, response); } else { this.handleSsld(deviceIdentification, status, allowedDomainType, response); } } catch (final FunctionalException e) { LOGGER.error("Caught FunctionalException", e); } } ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(correlationUid).withOrganisationIdentification(organisationIdentification) .withDeviceIdentification(deviceIdentification).withResult(response.getResult()) .withOsgpException(response.getOsgpException()).withDataObject(response.getDeviceStatusMapped()) .build(); this.webServiceResponseMessageSender.send(responseMessage); }
Source:
public void initializeDefaultPreferences() { IPreferenceStore store = Activator.getDefault().getPreferenceStore(); store.setDefault(PreferenceConstants.P_CHOICE, "clangd"); store.setDefault(PreferenceConstants.P_FLAGS, ""); }

Target:
public void initializeDefaultPreferences() { IPreferenceStore store = Activator.getDefault().getPreferenceStore(); store.setDefault(PreferenceConstants.P_SERVER_CHOICE, "clangd"); store.setDefault(PreferenceConstants.P_SERVER_OPTIONS, ""); }
Source:
final void setSessionCacheSize(int size) { if (size < 0) { throw new IllegalArgumentException(); } long oldSize = maximumCacheSize.getAndSet(size); if (oldSize < size) { freeSessions(); } }

Target:
final void setSessionCacheSize(int size) { long oldSize = maximumCacheSize.getAndSet(size); if (oldSize > size) { freeSessions(); } }
Source:
private Predicate<String> toPredicate(final List<String> regexList, final boolean defaultResult) { return regexList .stream() .map(r -> "^" + r + "$") .map(Pattern::compile) .map(Pattern::asPredicate) .reduce(Predicate::or).orElse(t -> defaultResult); }

Target:
private Predicate<String> toPredicate(final List<String> regexList, final boolean defaultResult) { return regexList .stream() .map(Pattern::compile) .map(Pattern::asPredicate) .reduce(Predicate::or).orElse(t -> defaultResult); }
Source:
private Message<?> enhanceScatterReplyMessage(Message<?> message) { MessageHeaders headers = message.getHeaders(); return getMessageBuilderFactory() .fromMessage(message) .setHeader(MessageHeaders.ERROR_CHANNEL, headers.get(GATHER_RESULT_CHANNEL)) .build(); }

Target:
private Message<?> enhanceScatterReplyMessage(Message<?> message) { MessageHeaders headers = message.getHeaders(); return getMessageBuilderFactory() .fromMessage(message) .setHeader(MessageHeaders.ERROR_CHANNEL, headers.get(ORIGINAL_ERROR_CHANNEL)) .removeHeaders(ORIGINAL_ERROR_CHANNEL) .build(); }
Source:
public static LibvirtSecret map(OpenstackVolumeAuthenticationKey model, LibvirtSecret template) { LibvirtSecret entity = template != null ? template : new LibvirtSecret(); if (model.isSetId()) { entity.setId(GuidUtils.asGuid(model.getId())); } if (model.isSetUuid()) { entity.setId(GuidUtils.asGuid(model.getUuid())); } if (model.isSetDescription()) { entity.setDescription(model.getDescription()); } if (model.isSetValue()) { entity.setValue(model.getValue()); } if (model.isSetUsageType()) { OpenstackVolumeAuthenticationKeyUsageType usageType = OpenstackVolumeAuthenticationKeyUsageType.fromValue(model.getUsageType()); if (usageType != null) { entity.setUsageType(map(usageType, null)); } } if (model.isSetOpenstackVolumeProvider()) { entity.setProviderId(GuidUtils.asGuid(model.getOpenstackVolumeProvider().getId())); } return entity; }

Target:
public static LibvirtSecret map(OpenstackVolumeAuthenticationKey model, LibvirtSecret template) { LibvirtSecret entity = template != null ? template : new LibvirtSecret(); if (model.isSetId()) { entity.setId(GuidUtils.asGuid(model.getId())); } if (model.isSetUuid()) { entity.setId(GuidUtils.asGuid(model.getUuid())); } if (model.isSetDescription()) { entity.setDescription(model.getDescription()); } if (model.isSetValue()) { entity.setValue(model.getValue()); } if (model.isSetUsageType()) { OpenstackVolumeAuthenticationKeyUsageType usageType = OpenstackVolumeAuthenticationKeyUsageType.fromValue(model.getUsageType()); if (usageType != null) { entity.setUsageType(map(usageType, null)); } } if (model.isSetOpenstackVolumeProvider() && model.getOpenstackVolumeProvider().isSetId()) { entity.setProviderId(GuidUtils.asGuid(model.getOpenstackVolumeProvider().getId())); } return entity; }
Source:
public DurationFormatter(Duration duration) { this.stringRepresentation = duration.toString(); }

Target:
public DurationFormatter(Duration duration) { if ( Duration.ZERO.equals( duration ) ) { this.stringRepresentation = "0"; } else { long seconds = duration.getSeconds(); long days = seconds / ( 24 * 3_600 ); long hours = seconds / 3_600 % 24; long minutes = seconds / 60 % 60; int millis = duration.getNano() / 1_000_000; int nanos = duration.getNano() % 1_000_000; StringBuilder formattedDuration = new StringBuilder(); appendTimeUnit( formattedDuration, days, "days", "day" ); appendTimeUnit( formattedDuration, hours, "hours", "hour" ); appendTimeUnit( formattedDuration, minutes, "minutes", "minute" ); appendTimeUnit( formattedDuration, seconds % 60, "seconds", "second" ); appendTimeUnit( formattedDuration, millis, "milliseconds", "millisecond" ); appendTimeUnit( formattedDuration, nanos, "nanoseconds", "nanosecond" ); this.stringRepresentation = formattedDuration.toString(); } }
Source:
private void addApproval(final PatchSetApproval.Key psaKey, final Short score, final Change c, final CmdOption co, final Transaction txn) throws OrmException, UnloggedFailure { PatchSetApproval psa = db.patchSetApprovals().get(psaKey); Boolean insert = false; if (psa == null) { insert = true; psa = new PatchSetApproval(psaKey, score); } final List<PatchSetApproval> approvals = Collections.emptyList(); final FunctionState fs = functionStateFactory.create(c, patchSetId, approvals); psa.setValue(score); fs.normalize( approvalTypes.getApprovalType(psa.getCategoryId()), psa); if (score != psa.getValue()) { throw new UnloggedFailure(CMD_ERR, co.name() + "=" + co.value() + " not permitted"); } psa.setGranted(); if (insert) { db.patchSetApprovals().insert(Collections.singleton(psa), txn); } else { db.patchSetApprovals().update(Collections.singleton(psa), txn); } }

Target:
private void addApproval(final PatchSetApproval.Key psaKey, final Short score, final Change c, final CmdOption co, final Transaction txn) throws OrmException, UnloggedFailure { PatchSetApproval psa = db.patchSetApprovals().get(psaKey); boolean insert = false; if (psa == null) { insert = true; psa = new PatchSetApproval(psaKey, score); } final List<PatchSetApproval> approvals = Collections.emptyList(); final FunctionState fs = functionStateFactory.create(c, patchSetId, approvals); psa.setValue(score); fs.normalize( approvalTypes.getApprovalType(psa.getCategoryId()), psa); if (score != psa.getValue()) { throw new UnloggedFailure(CMD_ERR, co.name() + "=" + co.value() + " not permitted"); } psa.setGranted(); if (insert) { db.patchSetApprovals().insert(Collections.singleton(psa), txn); } else { db.patchSetApprovals().update(Collections.singleton(psa), txn); } }
Source:
@Override public void processInStreamOutStream(int type, BinaryRawReaderEx reader, BinaryRawWriterEx writer) throws IgniteCheckedException { switch (type) { case OP_GET_META: { int typeId = reader.readInt(); platformCtx.writeMetadata(writer, typeId, false); break; } case OP_GET_META_WITH_SCHEMAS: { int typeId = reader.readInt(); platformCtx.writeMetadata(writer, typeId, true); break; } case OP_GET_SCHEMA: { int typeId = reader.readInt(); int schemaId = reader.readInt(); platformCtx.writeSchema(writer, typeId, schemaId); break; } case OP_GET_TYPE: { int typeId = reader.readInt(); ClassNotFoundException err = null; for (byte platformId : new byte[] {DOTNET_ID, JAVA_ID}) { try { String typeName = platformContext().kernalContext().marshallerContext() .getClassName(platformId, typeId); writer.writeString(typeName); err = null; break; } catch (ClassNotFoundException e) { if (err == null) err = e; } } if (err != null) throw new BinaryObjectException(err); break; } case OP_REGISTER_ENUM: { String name = reader.readString(); int cnt = reader.readInt(); Map<String, Integer> vals = new HashMap<>(cnt); for (int i = 0; i < cnt; i++) { vals.put(reader.readString(), reader.readInt()); } BinaryType binaryType = platformCtx.kernalContext().grid().binary().registerEnum(name, vals); platformCtx.writeMetadata(writer, binaryType.typeId(), false); break; } default: super.processInStreamOutStream(type, reader, writer); break; } }

Target:
@Override public void processInStreamOutStream(int type, BinaryRawReaderEx reader, BinaryRawWriterEx writer) throws IgniteCheckedException { switch (type) { case OP_GET_META: { int typeId = reader.readInt(); platformCtx.writeMetadata(writer, typeId, false); break; } case OP_GET_META_WITH_SCHEMAS: { int typeId = reader.readInt(); platformCtx.writeMetadata(writer, typeId, true); break; } case OP_GET_SCHEMA: { int typeId = reader.readInt(); int schemaId = reader.readInt(); platformCtx.writeSchema(writer, typeId, schemaId); break; } case OP_GET_TYPE: { int typeId = reader.readInt(); try { String typeName = platformContext().kernalContext().marshallerContext() .getClassName(MarshallerPlatformIds.DOTNET_ID, typeId); writer.writeString(typeName); } catch (ClassNotFoundException e) { throw new BinaryObjectException(e); } break; } case OP_REGISTER_ENUM: { String name = reader.readString(); int cnt = reader.readInt(); Map<String, Integer> vals = new HashMap<>(cnt); for (int i = 0; i < cnt; i++) { vals.put(reader.readString(), reader.readInt()); } BinaryType binaryType = platformCtx.kernalContext().grid().binary().registerEnum(name, vals); platformCtx.writeMetadata(writer, binaryType.typeId(), false); break; } default: super.processInStreamOutStream(type, reader, writer); break; } }
Source:
protected void assertEvaluationIsError() throws Exception { IValue value = getValue(); assertEquals(value, IntegralValue.ERROR); }

Target:
protected void assertEvaluationIsError() throws Exception { IValue value = getValue(); assertEquals(IntegralValue.ERROR, value); }
Source:
public void addPythonFile(String filePath) { Preconditions.checkNotNull(filePath); String fileKey = generateUniqueFileKey(PYTHON_FILE_PREFIX, filePath); registerCachedFileIfNotExist(filePath, fileKey); if (!internalConfig.contains(PYTHON_FILES)) { internalConfig.set(PYTHON_FILES, new HashMap<>()); } internalConfig.get(PYTHON_FILES).put(fileKey, new File(filePath).getName()); }

Target:
private void addPythonFile(String filePath) { Preconditions.checkNotNull(filePath); String fileKey = generateUniqueFileKey(PYTHON_FILE_PREFIX, filePath); registerCachedFileIfNotExist(filePath, fileKey); if (!internalConfig.contains(PYTHON_FILES)) { internalConfig.set(PYTHON_FILES, new HashMap<>()); } internalConfig.get(PYTHON_FILES).put(fileKey, new File(filePath).getName()); }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; IntegerCopyNumberState that = (IntegerCopyNumberState) o; return copyNumber == that.copyNumber; }

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; return copyNumber == ((IntegerCopyNumberState) o).copyNumber; }
Source:
public @NonNull TmfModelResponse<TmfTreeModel<TimeGraphEntryModel>> fetchTree(Map<String, Object> fetchParameters, @Nullable IProgressMonitor monitor) { fetchTreeIsComplete = true; long rootId = ENTRY_ID.getAndIncrement(); ITmfTrace trace = getTrace(); TraceEntryModel.Builder traceEntry = new TraceEntryModel.Builder(rootId, trace.getName(), trace.getStartTime().toNanos(), trace); entryList = new ArrayList<>(); moduleEntryModelList = new ArrayList<>(); long traceEnd = traceEntry.getStartTime(); for (ITmfAnalysisModuleWithStateSystems module : fModules) { synchronized (fStartedAnalysis) { if (monitor != null) { if (monitor.isCanceled()) { return new TmfModelResponse<>(null, Status.CANCELLED, CommonStatusMessage.TASK_CANCELLED); } } } waitForInitialization(getTrace(), module); long id = ENTRY_ID.getAndIncrement(); ModuleEntryModel.Builder moduleEntry = new ModuleEntryModel.Builder(id, module.getName(), traceEntry.getStartTime(), module); long moduleEnd = traceEntry.getStartTime(); for (ITmfStateSystem ss : module.getStateSystems()) { addStateSystem(ss, id); moduleEnd = Long.max(moduleEnd, ss.getCurrentEndTime()); } moduleEntry.setEndTime(moduleEnd); traceEnd = Long.max(traceEnd, moduleEnd); ModuleEntryModel finalModuleEntry = moduleEntry.build(rootId); entryList.add(finalModuleEntry); moduleEntryModelList.add(finalModuleEntry); } traceEntry.setEndTime(traceEnd); TraceEntryModel finalTraceEntry = traceEntry.build(-1); entryList.add(finalTraceEntry); Collections.reverse(entryList); Status status = fetchTreeIsComplete ? Status.COMPLETED : Status.RUNNING; String msg = fetchTreeIsComplete ? CommonStatusMessage.COMPLETED : CommonStatusMessage.RUNNING; return new TmfModelResponse<>(new TmfTreeModel<>(Collections.emptyList(), entryList), status, msg); }

Target:
public @NonNull TmfModelResponse<TmfTreeModel<TimeGraphEntryModel>> fetchTree(Map<String, Object> fetchParameters, @Nullable IProgressMonitor monitor) { List<TimeGraphEntryModel> EntryList = new ArrayList<>(fEntryBuilder.size()); moduleEntryModelList = new ArrayList<>(); Boolean fetchTreeIsComplete = true; synchronized (fEntryBuilder) { fetchTreeIsComplete &= addTrace(monitor, EntryList); if (monitor != null) { if (monitor.isCanceled()) { return new TmfModelResponse<>(null, Status.CANCELLED, CommonStatusMessage.TASK_CANCELLED); } } } Collections.reverse(EntryList); Status status = fetchTreeIsComplete ? Status.COMPLETED : Status.RUNNING; String msg = fetchTreeIsComplete ? CommonStatusMessage.COMPLETED : CommonStatusMessage.RUNNING; return new TmfModelResponse<>(new TmfTreeModel<>(Collections.emptyList(), EntryList), status, msg); }
Source:
public JaxRsClientFactoryImpl(ApplicationContext ctx) { provider = () -> null; boolean disableTLS = false; if (ctx != null) { provider = () -> { try { return ctx.getBean(TlsProvider.class); } catch (NoSuchBeanDefinitionException e) { return null; } }; disableTLS = Boolean.parseBoolean(ctx.getEnvironment().getProperty(KEY_DISABLE, "false")); } if (disableTLS) { this.factoryCustomizers.add(sslContextFactory -> { LOG.info("Disabling TLS 1.3"); sslContextFactory.setExcludeProtocols("TLSv1.3"); }); } }

Target:
public JaxRsClientFactoryImpl(ApplicationContext ctx) { provider = () -> null; if (ctx != null) { provider = () -> { try { return ctx.getBean(TlsProvider.class); } catch (NoSuchBeanDefinitionException e) { return null; } }; } }
Source:
protected void execute() { motor.set(speed); LogKitten.d("MotorSet executing with speed " + speed); }

Target:
public void execute() { motor.set(speed); LogKitten.d("MotorSet executing with speed " + speed); }
Source:
public void downloadZipComplex() throws IOException { final ApiClient ownerWebClient = getWebClient(USER_2_USERNAME, testingPostgres); WorkflowsApi ownerWorkflowApi = new WorkflowsApi(ownerWebClient); Workflow refresh = registerGatkSvWorkflow(ownerWorkflowApi); Long workflowId = refresh.getId(); Long versionId = refresh.getWorkflowVersions().get(0).getId(); ownerWorkflowApi.getWorkflowZip(workflowId, versionId); final io.dockstore.webservice.core.Workflow dockstoreWorkflow = workflowDAO.findById(workflowId); final Optional<io.dockstore.webservice.core.WorkflowVersion> version = dockstoreWorkflow.getWorkflowVersions().stream() .filter(wv -> wv.getId() == versionId).findFirst(); Assert.assertTrue(version.isPresent()); final File tempFile = File.createTempFile("dockstore-test", ".zip"); try { final FileOutputStream fos = new FileOutputStream(tempFile); final Set<io.dockstore.webservice.core.SourceFile> sourceFiles = version.get().getSourceFiles(); new EntryVersionHelperImpl().writeStreamAsZip(sourceFiles, fos, Paths.get("/GATKSVPipelineClinical.wdl")); final ZipFile zipFile = new ZipFile(tempFile); final long wdlCount = zipFile.stream().filter(e -> e.getName().endsWith(".wdl")).count(); Assert.assertEquals(sourceFiles.size(), wdlCount); zipFile.stream().filter(e -> e.getName().endsWith(".wdl")).forEach(e -> { final String name = "/" + e.getName(); Assert.assertTrue("expected " + name, sourceFiles.stream().anyMatch(sf -> sf.getAbsolutePath().equals(name))); }); zipFile.close(); } finally { FileUtils.deleteQuietly(tempFile); } }

Target:
public void downloadZipComplex() throws IOException { final ApiClient ownerWebClient = getWebClient(USER_2_USERNAME, testingPostgres); WorkflowsApi ownerWorkflowApi = new WorkflowsApi(ownerWebClient); Workflow refresh = registerGatkSvWorkflow(ownerWorkflowApi); Long workflowId = refresh.getId(); Long versionId = refresh.getWorkflowVersions().get(0).getId(); ownerWorkflowApi.getWorkflowZip(workflowId, versionId); final io.dockstore.webservice.core.Workflow dockstoreWorkflow = workflowDAO.findById(workflowId); final Optional<io.dockstore.webservice.core.WorkflowVersion> version = dockstoreWorkflow.getWorkflowVersions().stream() .filter(wv -> wv.getId() == versionId).findFirst(); Assert.assertTrue(version.isPresent()); final File tempFile = File.createTempFile("dockstore-test", ".zip"); try (FileOutputStream fos = new FileOutputStream(tempFile)) { final Set<io.dockstore.webservice.core.SourceFile> sourceFiles = version.get().getSourceFiles(); new EntryVersionHelperImpl().writeStreamAsZip(sourceFiles, fos, Paths.get("/GATKSVPipelineClinical.wdl")); final ZipFile zipFile = new ZipFile(tempFile); final long wdlCount = zipFile.stream().filter(e -> e.getName().endsWith(".wdl")).count(); Assert.assertEquals(sourceFiles.size(), wdlCount); zipFile.stream().filter(e -> e.getName().endsWith(".wdl")).forEach(e -> { final String name = "/" + e.getName(); Assert.assertTrue("expected " + name, sourceFiles.stream().anyMatch(sf -> sf.getAbsolutePath().equals(name))); }); zipFile.close(); } finally { FileUtils.deleteQuietly(tempFile); } }
Source:
private boolean onIsPotionActive(final LivingEntity entityIn, final Effect potion) { return false; }

Target:
private boolean impl$onIsPotionActive(final LivingEntity entityIn, final Effect potion) { return false; }
Source:
private void createPresenterViewUi() { RenderedTemplate renderedTemplate = null; if (presenterConfigModel.getNestedPresenter()) { renderedTemplate = createdNestedPresenterTemplates.getViewui(); } else if (presenterConfigModel.getPresenterWidget()) { renderedTemplate = createdPresenterWidgetTemplates.getViewui(); } else if (presenterConfigModel.getPopupPresenter()) { renderedTemplate = createdPopupPresenterTemplates.getViewui(); } String className = renderedTemplate.getNameAndNoExt(); String contents = renderedTemplate.getContents(); final PsiDirectory[] directoriesInPackage = createdPresenterPackage.getDirectories(); final PsiFile element = PsiFileFactory.getInstance(project).createFileFromText(className, XmlFileType.INSTANCE, contents); final CreatedPsiClass createdPsiClass = new CreatedPsiClass(); ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { PsiElement createdElement = directoriesInPackage[0].add(element); PsiJavaFile createdJavaFile = (PsiJavaFile) createdElement; PsiClass[] createdClasses = createdJavaFile.getClasses(); createdPsiClass.setPsiClass(createdClasses[0]); CodeStyleManager.getInstance(project).reformat(createdClasses[0]); } }); }

Target:
private void createPresenterViewUi() { RenderedTemplate renderedTemplate = null; if (presenterConfigModel.getNestedPresenter()) { renderedTemplate = createdNestedPresenterTemplates.getViewui(); } else if (presenterConfigModel.getPresenterWidget()) { renderedTemplate = createdPresenterWidgetTemplates.getViewui(); } else if (presenterConfigModel.getPopupPresenter()) { renderedTemplate = createdPopupPresenterTemplates.getViewui(); } final String className = renderedTemplate.getNameAndNoExt(); final String contents = renderedTemplate.getContents(); final PsiDirectoriesModel psiDirectoriesModel = new PsiDirectoriesModel(); ApplicationManager.getApplication().invokeAndWait(new Runnable() { @Override public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { PsiDirectory[] directoriesInPackage = createdPresenterPackage.getDirectories(); psiDirectoriesModel.set(directoriesInPackage); } }); } }, ModalityState.NON_MODAL); final PsiElementModel psiElementModel = new PsiElementModel(); ApplicationManager.getApplication().invokeAndWait(new Runnable() { @Override public void run() { ApplicationManager.getApplication().runReadAction(new Runnable() { @Override public void run() { PsiFile element = PsiFileFactory.getInstance(project).createFileFromText( className, XmlFileType.INSTANCE, contents); psiElementModel.set(element); } }); } }, ModalityState.NON_MODAL); ApplicationManager.getApplication().invokeAndWait(new Runnable() { @Override public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { PsiDirectory[] psiDirectories = psiDirectoriesModel.get(); psiDirectories[0].add(psiElementModel.get()); } }); } }, ModalityState.NON_MODAL); }