auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static File profileName( File file, long count ) { String name = file.getName(); File dir = file.getParentFile(); return new File( dir, "." + name + "." + Long.toHexString( count ) + SUFFIX_CACHEPROF ); }

Target:
private static File profileName( File file, long count ) { String name = file.getName(); File dir = new File( file.getParentFile(), PROFILE_DIR ); return new File( dir, name + "." + Long.toString( count ) + SUFFIX_CACHEPROF ); }
Source:
private void moveFirstAndLastNodes(final LGraph layeredGraph, final Layer firstLayer, final Layer lastLayer, final Layer firstLabelLayer, final Layer lastLabelLayer) { for (Layer layer : layeredGraph) { LNode nodes = LGraphUtil.toNodeArray(layer.getNodes()); for (LNode node : nodes) { switch (node.getProperty(LayeredOptions.LAYERING_LAYER_CONSTRAINT)) { case FIRST: node.setLayer(firstLayer); throwUpUnlessNoIncomingEdges(node); moveLabelsToLabelLayer(node, true, firstLabelLayer); break; case LAST: node.setLayer(lastLayer); throwUpUnlessNoOutgoingEdges(node); moveLabelsToLabelLayer(node, false, lastLabelLayer); break; } } } ListIterator<Layer> layerIter = layeredGraph.getLayers().listIterator(); while (layerIter.hasNext()) { if (layerIter.next().getNodes().isEmpty()) { layerIter.remove(); } } }

Target:
private void moveFirstAndLastNodes(final LGraph layeredGraph, final Layer firstLayer, final Layer lastLayer, final Layer firstLabelLayer, final Layer lastLabelLayer) { for (Layer layer : layeredGraph) { LNode[] nodes = LGraphUtil.toNodeArray(layer.getNodes()); for (LNode node : nodes) { switch (node.getProperty(LayeredOptions.LAYERING_LAYER_CONSTRAINT)) { case FIRST: throwUpUnlessNoIncomingEdges(node); node.setLayer(firstLayer); moveLabelsToLabelLayer(node, true, firstLabelLayer); break; case LAST: throwUpUnlessNoOutgoingEdges(node); node.setLayer(lastLayer); moveLabelsToLabelLayer(node, false, lastLabelLayer); break; } } } ListIterator<Layer> layerIter = layeredGraph.getLayers().listIterator(); while (layerIter.hasNext()) { if (layerIter.next().getNodes().isEmpty()) { layerIter.remove(); } } }
Source:
private Set<String> getUsageArguments(Properties properties) { SortedSet<String> args = new TreeSet<>(new Comparator<String>() { @Override public int compare(String o, String t1) { return o.compareTo(t1); } }); for (String argName : properties.stringPropertyNames()) { String[] param = argName.split("\\."); if (param.length < 3) { throw new IllegalArgumentException( String.format("Invalid option '%1$s'", argName) ); } args.add(param[1]); } return args; }

Target:
private Set<String[]> getUsageArguments(Properties properties) { SortedSet<String[]> args = new TreeSet<>(new Comparator<String[]>() { @Override public int compare(String[] o, String[] t1) { return o[2].compareTo(t1[2]); } }); for (String argName : properties.stringPropertyNames()) { String[] param = argName.split("\\."); if (param.length < 4) { throw new IllegalArgumentException( String.format("Invalid option '%1$s'", argName) ); } args.add(param); } return args; }
Source:
public TypeMapper() { try { final Ds3TypeMapperParser parser = new Ds3TypeMapperParserImpl(); final Ds3TypeMapper ds3TypeMapper = parser.getMap(); this.typeMapper = ds3TypeMapper.getTypeMapper(); } catch (final ParserException|IOException e) { LOG.error("Attempted to create Type Mapper", e); } }

Target:
private TypeMapper() throws IOException, ParserException { ds3TypeMapper = initTypeMapper(); }
Source:
public boolean isApplicable(MessageBeans beans, String msg) { int presentMask = beans.getPresentBeansMask(); return ((requiredBeans & presentMask) == requiredBeans && (requiredBeans | presentMask) == requiredBeans); }

Target:
public boolean isApplicable(MessageBeans beans, String msg) { int presentMask = beans.getPresentBeansMask(); return requiredBeans == presentMask; }
Source:
private static boolean isTransparencyAttestationUpdated(final DeveloperDTO original, final DeveloperDTO changed) { if ((original.getTransparencyAttestationMappings() != null && changed.getTransparencyAttestationMappings() == null) || (original.getTransparencyAttestationMappings() == null && changed.getTransparencyAttestationMappings() != null) || (original.getTransparencyAttestationMappings().size() != changed.getTransparencyAttestationMappings() .size())) { return true; } else { for (DeveloperACBMapDTO originalMapping : original.getTransparencyAttestationMappings()) { for (DeveloperACBMapDTO changedMapping : changed.getTransparencyAttestationMappings()) { if (!Objects.equals(originalMapping.getAcbName(), changedMapping.getAcbName()) || !Objects.equals(originalMapping.getTransparencyAttestation(), changedMapping.getTransparencyAttestation())) { return true; } } } } return false; }

Target:
private boolean isTransparencyAttestationUpdated(final DeveloperDTO original, final DeveloperDTO changed) { if ((original.getTransparencyAttestationMappings() != null && changed.getTransparencyAttestationMappings() == null) || (original.getTransparencyAttestationMappings() == null && changed.getTransparencyAttestationMappings() != null) || (original.getTransparencyAttestationMappings().size() != changed.getTransparencyAttestationMappings() .size())) { return true; } else { for (DeveloperACBMapDTO originalMapping : original.getTransparencyAttestationMappings()) { Optional<DeveloperACBMapDTO> matchingMapping = changed.getTransparencyAttestationMappings().stream() .filter(changedMapping -> StringUtils.equals(originalMapping.getAcbName(), changedMapping.getAcbName())) .findFirst(); if (!matchingMapping.isPresent() || !StringUtils.equals(originalMapping.getTransparencyAttestation(), matchingMapping.get().getTransparencyAttestation())) { return true; } } } return false; }
Source:
public void testGetNonExistingDataCenter() throws Exception { MockWebServer server = mockWebServer(); server.enqueue(new MockResponse().setResponseCode(500).setBody(payloadFromResource("/fault-404.xml"))); ProfitBricksApi pbApi = api(server.getUrl(rootUrl)); DataCenterApi api = pbApi.dataCenterApi(); String id = "random-non-existing-id"; try { DataCenter dataCenter = api.getDataCenter(id); assertRequestHasCommonProperties(server.takeRequest()); assertNull(dataCenter); } catch (Exception ex) { fail("Should've just thrown null"); } finally { pbApi.close(); server.shutdown(); } }

Target:
public void testGetNonExistingDataCenter() throws Exception { MockWebServer server = mockWebServer(); server.enqueue(new MockResponse().setResponseCode(500).setBody(payloadFromResource("/fault-404.xml"))); ProfitBricksApi pbApi = api(server.getUrl(rootUrl)); DataCenterApi api = pbApi.dataCenterApi(); String id = "random-non-existing-id"; try { DataCenter dataCenter = api.getDataCenter(id); assertRequestHasCommonProperties(server.takeRequest()); assertNull(dataCenter); } finally { pbApi.close(); server.shutdown(); } }
Source:
public void testTypeInfoTestCoverage() { Reflections reflections = new Reflections("org.apache.flink"); Set<Class<? extends TypeInformation>> typeInfos = reflections.getSubTypesOf(TypeInformation.class); Set<String> typeInfoTestNames = reflections.getSubTypesOf(TypeInformationTestBase.class) .stream().map(Class::getName).collect(Collectors.toSet()); for (Class<? extends TypeInformation> typeInfo : typeInfos) { if (Modifier.isAbstract(typeInfo.getModifiers()) || Modifier.isPrivate(typeInfo.getModifiers()) || typeInfo.getName().contains("test") || typeInfo.getName().contains("Test") || typeInfo.getName().contains("ITCase") || typeInfo.getName().contains("$") || typeInfo.getName().contains("scala") || typeInfo.getName().contains("queryablestate")) { continue; } final String testToFind = typeInfo.getName() + "Test"; if (!typeInfoTestNames.contains(testToFind)) { fail("Could not find test '" + testToFind + "' that covers '" + typeInfo.getName() + "'."); } } }

Target:
public void testTypeInfoTestCoverage() { Reflections reflections = new Reflections("org.apache.flink"); Set<Class<? extends TypeInformation>> typeInfos = reflections.getSubTypesOf(TypeInformation.class); Set<String> typeInfoTestNames = reflections.getSubTypesOf(TypeInformationTestBase.class) .stream().map(Class::getName).collect(Collectors.toSet()); for (Class<? extends TypeInformation> typeInfo : typeInfos) { if (Modifier.isAbstract(typeInfo.getModifiers()) || Modifier.isPrivate(typeInfo.getModifiers()) || typeInfo.getName().contains("Test$") || typeInfo.getName().contains("TestBase$") || typeInfo.getName().contains("ITCase$") || typeInfo.getName().contains("$$anon") || typeInfo.getName().contains("queryablestate")) { continue; } final String testToFind = typeInfo.getName() + "Test"; if (!typeInfoTestNames.contains(testToFind)) { fail("Could not find test '" + testToFind + "' that covers '" + typeInfo.getName() + "'."); } } }
Source:
private void visitRequireCall(NodeTraversal t, Node require, Node parent) { String requireName = getCommonJsImportPath(require); String moduleName = getImportedModuleName(t, require); Node moduleRef = NodeUtil.newQName(compiler, getBasePropertyImport(moduleName)) .useSourceInfoFromForTree(require); parent.replaceChild(require, moduleRef); t.reportCodeChange(); }

Target:
private void visitRequireCall(NodeTraversal t, Node require, Node parent) { String moduleName = getImportedModuleName(t, require); Node moduleRef = NodeUtil.newQName(compiler, getBasePropertyImport(moduleName)) .useSourceInfoFromForTree(require); parent.replaceChild(require, moduleRef); t.reportCodeChange(); }
Source:
public void initialize() { super.initialize(); userSearchTextField.textProperty().addListener((observable, oldValue, newValue) -> filterChatUsers(newValue)); channelTabScrollPaneVBox.setMinWidth(preferencesService.getPreferences().getChat().getChannelTabScrollPaneWidth()); channelTabScrollPaneVBox.setPrefWidth(preferencesService.getPreferences().getChat().getChannelTabScrollPaneWidth()); JavaFxUtil.addListener(preferencesService.getPreferences().getChat().chatColorModeProperty(), chatColorModeChangeListener); addUserFilterPopup(); chatUserListView.setItems(filteredChatUserList); chatUserListView.setCellFactory(param -> new ChatUserListCell(uiService)); autoCompletionHelper.bindTo(messageTextField()); splitPane.widthProperty().addListener((observable, oldValue, newValue) -> { splitPane.setDividerPositions((splitPane.widthProperty().doubleValue() - (double) USER_LIST_WIDTH_PX) / splitPane.widthProperty().doubleValue()); System.out.println((newValue.doubleValue() - (double) USER_LIST_WIDTH_PX) / newValue.doubleValue()); }); }

Target:
public void initialize() { super.initialize(); userSearchTextField.textProperty().addListener((observable, oldValue, newValue) -> filterChatUsers(newValue)); channelTabScrollPaneVBox.setMinWidth(preferencesService.getPreferences().getChat().getChannelTabScrollPaneWidth()); channelTabScrollPaneVBox.setPrefWidth(preferencesService.getPreferences().getChat().getChannelTabScrollPaneWidth()); JavaFxUtil.addListener(preferencesService.getPreferences().getChat().chatColorModeProperty(), chatColorModeChangeListener); addUserFilterPopup(); chatUserListView.setItems(filteredChatUserList); chatUserListView.setCellFactory(param -> new ChatUserListCell(uiService)); autoCompletionHelper.bindTo(messageTextField()); }
Source:
public void start(BundleContext bc) throws Exception { context = bc; logger.debug("Core bundle has been started."); DateExpression de = new DateExpression("2016-01-31T16:45:46+00:00"); logger.debug("stop"); }

Target:
public void start(BundleContext bc) throws Exception { context = bc; logger.debug("Core bundle has been started."); }
Source:
protected Pair<Boolean, VdcFault> runConnectionStorageToDomain(StorageDomain storageDomain, Guid vdsId, int type) { Provider provider = getProviderDao().get(Guid.createGuidFromString(storageDomain.getStorage())); VDS vds = getVdsDao().get(vdsId); List<LibvirtSecret> libvirtSecrets = getLibvirtSecretDao().getAllByProviderId(provider.getId()); if (!libvirtSecrets.isEmpty()) { VDSReturnValue returnValue = Backend.getInstance().getResourceManager().RunVdsCommand( VDSCommandType.RegisterLibvirtSecrets, new RegisterLibvirtSecretsVDSParameters(vdsId, libvirtSecrets)); if (!returnValue.getSucceeded()) { addMessageToAuditLog(AuditLogType.FAILED_TO_REGISTER_LIBVIRT_SECRET, storageDomain.getName(), vds.getName()); log.error("Failed to register libvirt secret for storage domain on vds {}.", storageDomain.getName(), vds.getName()); VdcFault vdcFault = new VdcFault(); vdcFault.setError(returnValue.getVdsError().getCode()); return new Pair<>(false, vdcFault); } } return new Pair<>(true, null); }

Target:
protected Pair<Boolean, VdcFault> runConnectionStorageToDomain(StorageDomain storageDomain, Guid vdsId, int type) { Provider provider = getProviderDao().get(Guid.createGuidFromString(storageDomain.getStorage())); VDS vds = getVdsDao().get(vdsId); List<LibvirtSecret> libvirtSecrets = getLibvirtSecretDao().getAllByProviderId(provider.getId()); VDSReturnValue returnValue; if (!libvirtSecrets.isEmpty()) { try { returnValue = Backend.getInstance().getResourceManager().RunVdsCommand( VDSCommandType.RegisterLibvirtSecrets, new RegisterLibvirtSecretsVDSParameters(vdsId, libvirtSecrets)); } catch (RuntimeException e) { log.error("Failed to register libvirt secret for storage domain on vds {}. Error: {}", storageDomain.getName(), vds.getName(), e.getMessage()); log.debug("Exception", e); return new Pair<>(false, null); } if (!returnValue.getSucceeded()) { addMessageToAuditLog(AuditLogType.FAILED_TO_REGISTER_LIBVIRT_SECRET, storageDomain.getName(), vds.getName()); log.error("Failed to register libvirt secret for storage domain on vds {}.", storageDomain.getName(), vds.getName()); VdcFault vdcFault = new VdcFault(); vdcFault.setError(returnValue.getVdsError().getCode()); return new Pair<>(false, vdcFault); } } return new Pair<>(true, null); }
Source:
private Criterion getCriterionForShortName(String name, boolean includeVoided) { if (includeVoided) { return Restrictions.disjunction().add(Restrictions.eq("name.givenName", name).ignoreCase()).add( Restrictions.eq("name.middleName", name).ignoreCase()).add( Restrictions.eq("name.familyName", name).ignoreCase()).add( Restrictions.eq("name.familyName2", name).ignoreCase()); } else { return Restrictions.conjunction().add(Restrictions.eq("name.voided", false)).add( Restrictions.disjunction().add(Restrictions.eq("name.givenName", name).ignoreCase()).add( Restrictions.eq("name.middleName", name).ignoreCase()).add( Restrictions.eq("name.familyName", name).ignoreCase()).add( Restrictions.eq("name.familyName2", name).ignoreCase())); } }

Target:
private Criterion getCriterionForShortName(String name, boolean includeVoided) { Criterion criterion = Restrictions.disjunction().add(Restrictions.eq("name.givenName", name).ignoreCase()).add( Restrictions.eq("name.middleName", name).ignoreCase()) .add(Restrictions.eq("name.familyName", name).ignoreCase()).add( Restrictions.eq("name.familyName2", name).ignoreCase()); if (!includeVoided) { return Restrictions.conjunction().add(Restrictions.eq("name.voided", false)).add(criterion); } return criterion; }
Source:
public IndexingResult index(DbSession dbSession, Collection<EsQueueDto> items) { if (items.isEmpty()) { return new IndexingResult(); } Set<String> logins = items .stream() .map(EsQueueDto::getDocId) .collect(toHashSet(items.size())); BulkIndexer bulkIndexer = newBulkIndexer(Size.REGULAR, new OneToOneResilientIndexingListener(dbClient, dbSession, items)); bulkIndexer.start(); logins.forEach(l -> bulkIndexer.addDeletion(INDEX_TYPE_VIEW, l)); return bulkIndexer.stop(); }

Target:
public IndexingResult index(DbSession dbSession, Collection<EsQueueDto> items) { if (items.isEmpty()) { return new IndexingResult(); } Set<String> views = items .stream() .map(EsQueueDto::getDocId) .collect(toHashSet(items.size())); BulkIndexer bulkIndexer = newBulkIndexer(Size.REGULAR, new OneToOneResilientIndexingListener(dbClient, dbSession, items)); bulkIndexer.start(); views.removeAll(dbClient.componentDao().selectExistingUuids(dbSession, views)); views.forEach(v -> bulkIndexer.addDeletion(INDEX_TYPE_VIEW, v)); return bulkIndexer.stop(); }
Source:
public static void deIdentifyTableWithFpe() throws IOException { String projectId = "your-project-id"; Table tableToDeIdentify = Table.newBuilder() .addHeaders(FieldId.newBuilder().setName("Employee ID").build()) .addHeaders(FieldId.newBuilder().setName("Date").build()) .addHeaders(FieldId.newBuilder().setName("Compensation").build()) .addRows(Row.newBuilder() .addValues(Value.newBuilder().setStringValue("11111").build()) .addValues(Value.newBuilder().setStringValue("2015").build()) .addValues(Value.newBuilder().setStringValue("$10").build()) .build()) .addRows(Row.newBuilder() .addValues(Value.newBuilder().setStringValue("11111").build()) .addValues(Value.newBuilder().setStringValue("2016").build()) .addValues(Value.newBuilder().setStringValue("$20").build()) .build()) .addRows(Row.newBuilder() .addValues(Value.newBuilder().setStringValue("22222").build()) .addValues(Value.newBuilder().setStringValue("2016").build()) .addValues(Value.newBuilder().setStringValue("$15").build()) .build()) .build(); String kmsKeyName = "projects/YOUR_PROJECT/" + "locations/YOUR_KEYRING_REGION/" + "keyRings/YOUR_KEYRING_NAME/" + "cryptoKeys/YOUR_KEY_NAME"; String wrappedAesKey = "YOUR_ENCRYPTED_AES_256_KEY"; deIdentifyTableWithFpe(projectId, tableToDeIdentify, kmsKeyName, wrappedAesKey); }

Target:
public static void deIdentifyTableWithFpe() throws IOException { String projectId = "your-project-id"; String kmsKeyName = "projects/YOUR_PROJECT/" + "locations/YOUR_KEYRING_REGION/" + "keyRings/YOUR_KEYRING_NAME/" + "cryptoKeys/YOUR_KEY_NAME"; String wrappedAesKey = "YOUR_ENCRYPTED_AES_256_KEY"; Table tableToDeIdentify = Table.newBuilder() .addHeaders(FieldId.newBuilder().setName("Employee ID").build()) .addHeaders(FieldId.newBuilder().setName("Date").build()) .addHeaders(FieldId.newBuilder().setName("Compensation").build()) .addRows(Row.newBuilder() .addValues(Value.newBuilder().setStringValue("11111").build()) .addValues(Value.newBuilder().setStringValue("2015").build()) .addValues(Value.newBuilder().setStringValue("$10").build()) .build()) .addRows(Row.newBuilder() .addValues(Value.newBuilder().setStringValue("11111").build()) .addValues(Value.newBuilder().setStringValue("2016").build()) .addValues(Value.newBuilder().setStringValue("$20").build()) .build()) .addRows(Row.newBuilder() .addValues(Value.newBuilder().setStringValue("22222").build()) .addValues(Value.newBuilder().setStringValue("2016").build()) .addValues(Value.newBuilder().setStringValue("$15").build()) .build()) .build(); deIdentifyTableWithFpe(projectId, tableToDeIdentify, kmsKeyName, wrappedAesKey); }
Source:
public <U> Vector<T> distinctBy(Function<? super T, ? extends U> keyExtractor) { Objects.requireNonNull(keyExtractor, "keyExtractor is null"); final Set<U> seen = new java.util.HashSet<>(); return filter(t -> seen.add(keyExtractor.apply(t))); }

Target:
public <U> Vector<T> distinctBy(Function<? super T, ? extends U> keyExtractor) { Objects.requireNonNull(keyExtractor, "keyExtractor is null"); final java.util.Set<U> seen = new java.util.HashSet<>(length()); return filter(t -> seen.add(keyExtractor.apply(t))); }
Source:
public boolean isSparse(){ return isSparse; }

Target:
public boolean isSparse() { return false; }
Source:
public CommandResult2(int resultCode, DataSourceDesc2 desc) { this(resultCode, desc, System.currentTimeMillis()); }

Target:
public CommandResult2(int resultCode, DataSourceDesc2 desc) { this(resultCode, desc, SystemClock.elapsedRealtime()); }
Source:
public Expression from(@NonNull String alias) { if(alias == null) { throw new IllegalArgumentException("alias is null"); } return new MetaExpression(this.keyPath, alias); }

Target:
public Expression from(@NonNull String alias) { if (alias == null) { throw new IllegalArgumentException("alias is null."); } return new MetaExpression(this.keyPath, alias); }
Source:
private int invalidateSmallestTxVersion() { ConflictTxStream firstEntry = cacheEntries.peek(); if (cacheEntries.size() == 0) { return 0; } int numEntries = 0; while (firstAddress() == firstEntry.txVersion) { if (log.isTraceEnabled()) { log.trace("evict items " + numEntries + " with address " + firstAddress()); } ConflictTxStream entry = cacheEntries.poll(); conflictKeys.remove(entry); numEntries++; } if (log.isTraceEnabled()) { log.trace("Evict entries", numEntries); } maxConflictWildcard = Math.max(maxConflictWildcard, firstEntry.txVersion); return numEntries; }

Target:
private int invalidateSmallestTxVersion() { ConflictTxStream firstEntry = cacheEntries.peek(); if (cacheEntries.size() == 0) { return 0; } int numEntries = 0; while (firstAddress() == firstEntry.txVersion) { if (log.isTraceEnabled()) { log.trace( "invalidateSmallestTxVersion: items evicted min address {}", numEntries, firstAddress()); } ConflictTxStream entry = cacheEntries.poll(); conflictKeys.remove(entry); numEntries++; } maxConflictWildcard = Math.max(maxConflictWildcard, firstEntry.txVersion); return numEntries; }
Source:
private static void serializePrimitive(Type type, BlockBuilder builder, Object object) { requireNonNull(builder, "parent builder is null"); if (object == null) { builder.appendNull(); return; } if (type.equals(BOOLEAN)) { type.writeBoolean(builder, (Boolean) object); return; } else if (type.equals(BIGINT)) { type.writeLong(builder, Long.valueOf(String.valueOf(object))); return; } else if (type.equals(DOUBLE)) { type.writeDouble(builder, (Double) object); return; } else if (type.equals(INTEGER)) { type.writeLong(builder, Long.valueOf(String.valueOf(object))); return; } else if (type.equals(VARCHAR)) { type.writeSlice(builder, utf8Slice(String.valueOf(object))); return; } else if (type.equals(VARBINARY)) { type.writeSlice(builder, utf8Slice(String.valueOf(object))); return; } throw new RuntimeException("Unknown primitive type: " + type.getDisplayName()); }

Target:
private static void serializePrimitive(Type type, BlockBuilder builder, Object object) { requireNonNull(builder, "builder is null"); if (object == null) { builder.appendNull(); return; } if (type.equals(BOOLEAN)) { type.writeBoolean(builder, (Boolean) object); } else if (type.equals(BIGINT)) { type.writeLong(builder, Long.valueOf(String.valueOf(object))); } else if (type.equals(DOUBLE)) { type.writeDouble(builder, (Double) object); } else if (type.equals(INTEGER)) { type.writeLong(builder, Long.valueOf(String.valueOf(object))); } else if (type.equals(VARCHAR)) { type.writeSlice(builder, utf8Slice(String.valueOf(object))); } else if (type.equals(VARBINARY)) { type.writeSlice(builder, utf8Slice(String.valueOf(object))); } else { throw new RuntimeException("Unknown primitive type: " + type.getDisplayName()); } }
Source:
private void handleBody(InputStream payload, MessageMetadata messageMetadata) throws IOException, MessageFormatException { if (!successfullyDeserialized) { ByteBuffer encryptionKey = messageMetadata == null ? null : messageMetadata.getEncryptionKey(); serverBlobProperties = MessageFormatRecord.deserializeBlobProperties(payload); serverUserMetadata = MessageFormatRecord.deserializeUserMetadata(payload); successfullyDeserialized = true; if (!serverBlobProperties.isEncrypted()) { state = State.Complete; if (operationResult == null) { operationResult = new GetBlobResultInternal( new GetBlobResult(new BlobInfo(serverBlobProperties, serverUserMetadata.array()), null), null); } } else { state = State.Decrypting; logger.trace("Moving the state to and submitting decrypt job for {}", State.Decrypting, blobId); cryptoJobHandler.submitJob( new DecryptJob(blobId, encryptionKey.duplicate(), null, serverUserMetadata, cryptoService, kms, (DecryptJob.DecryptJobResult result, Exception exception) -> { logger.trace("Handling decrypt job callback results for {}", blobId); decryptCallbackResultInfo.get().setResultAndException(result, exception); routerCallback.onPollReady(); })); } } else { } }

Target:
private void handleBody(InputStream payload, MessageMetadata messageMetadata) throws IOException, MessageFormatException { ByteBuffer encryptionKey = messageMetadata == null ? null : messageMetadata.getEncryptionKey(); serverBlobProperties = MessageFormatRecord.deserializeBlobProperties(payload); ByteBuffer userMetadata = MessageFormatRecord.deserializeUserMetadata(payload); if (encryptionKey == null) { operationResult = new GetBlobResultInternal(new GetBlobResult(new BlobInfo(serverBlobProperties, userMetadata.array()), null), null); } else { progressTracker.initializeDecryptionTracker(); logger.trace("Submitting decrypt job for {}", blobId); long startTimeMs = System.currentTimeMillis(); cryptoJobHandler.submitJob( new DecryptJob(blobId, encryptionKey.duplicate(), null, userMetadata, cryptoService, kms, (DecryptJob.DecryptJobResult result, Exception exception) -> { logger.trace("Handling decrypt job callback results for {}", blobId); routerMetrics.decryptTimeMs.update(System.currentTimeMillis() - startTimeMs); if (exception == null) { logger.trace("Successfully updating decrypt job callback results for {}", blobId); operationResult = new GetBlobResultInternal( new GetBlobResult(new BlobInfo(serverBlobProperties, result.getDecryptedUserMetadata().array()), null), null); progressTracker.setDecryptionSuccess(); } else { logger.trace("Exception thrown on decryption for {}", exception, blobId); setOperationException( new RouterException("Exception thrown on decrypting the content for " + blobId, exception, RouterErrorCode.UnexpectedInternalError)); progressTracker.setDecryptionFailed(); } routerCallback.onPollReady(); })); } }
Source:
public void doesNotLogIfOperationsAreFast() { makeOperationsTakeSpecifiedDuration(SHORT_DURATION); allowLogging(); profilingTimelockService.getFreshTimestamp(); profilingTimelockService.startIdentifiedAtlasDbTransaction(); verify(delegate).getFreshTimestamp(); verify(delegate).startIdentifiedAtlasDbTransaction(); verifyLoggerNeverInvoked(); }

Target:
public void doesNotLogIfOperationsAreFast() { flushLogsWithCall(SHORT_DURATION, profilingTimelockService::getFreshTimestamp); flushLogsWithCall(SHORT_DURATION, profilingTimelockService::startIdentifiedAtlasDbTransaction); verify(delegate).getFreshTimestamp(); verify(delegate).startIdentifiedAtlasDbTransaction(); verifyLoggerNeverInvoked(); }
Source:
private void addStreamProperties(IMediaStream stream, HashMap<String,Object> streamHash){ HashMap<String,Object> EncodersHash = new HashMap<>(); double videoBitrate = stream.getPublishBitrateVideo() / 1000; double audioBitrate = stream.getPublishBitrateAudio() / 1000; double totalBitrate = videoBitrate + audioBitrate; double framerate = stream.getPublishFramerateVideo(); EncodersHash.put("videoBitrate", videoBitrate); EncodersHash.put("audioBitrate", audioBitrate); EncodersHash.put("totalBitrate", totalBitrate); EncodersHash.put("frameRate", framerate); getMetaDataProperties(stream, EncodersHash); streamHash.put("Encoder", EncodersHash); logger.debug(httpSessionId+"[" + stream.getName() + "] Add the following params: videoBitrate "+ videoBitrate + ", audioBitrate " + audioBitrate + ", framerate "+ framerate); }

Target:
private void addStreamProperties(IMediaStream stream, HashMap<String,Object> streamHash){ HashMap<String,Object> EncodersHash = new HashMap<String,Object>(); double videoBitrate = stream.getPublishBitrateVideo() / 1000; double audioBitrate = stream.getPublishBitrateAudio() / 1000; double framerate = stream.getPublishFramerateVideo(); String audioCodec = FLVUtils.audioCodecToString(stream.getPublishAudioCodecId()); String videoCodec = FLVUtils.videoCodecToString(stream.getPublishVideoCodecId()); EncodersHash.put("videoCodec", videoCodec); EncodersHash.put("audioCodec", audioCodec); EncodersHash.put("videoBitrate", videoBitrate); EncodersHash.put("audioBitrate", audioBitrate); EncodersHash.put("frameRate", framerate); getMetaDataProperties(stream, EncodersHash); streamHash.put("Encoder", EncodersHash); logger.debug(httpSessionId+"[" + stream.getName() + "] Add the following params: videoBitrate "+ videoBitrate + ", audioBitrate " + audioBitrate + ", framerate "+ framerate); }
Source:
public void importButtonClicked() { ImportEntriesDialog dialog = new ImportEntriesDialog(databaseContext, BackgroundTask.wrap(() -> new ArrayList<>(resolverResult.getNewEntries()))); dialog.setTitle(Localization.lang("Import entries from LaTeX files")); dialog.showAndWait(); close.set(true); }

Target:
public void importButtonClicked() { ImportEntriesDialog dialog = new ImportEntriesDialog(databaseContext, BackgroundTask.wrap(() -> new ArrayList<>(resolverResult.getNewEntries()))); dialog.setTitle(Localization.lang("Import entries from LaTeX files")); dialog.showAndWait(); }
Source:
public void testUpdateToolForumUrl() throws ApiException { ContainersApi toolsApi = setupWebService(); DockstoreTool toolTest = toolsApi.getContainerByToolPath(DOCKERHUB_TOOL_PATH, null); toolsApi.refresh(toolTest.getId()); toolTest.setForumUrl("hello.com"); toolsApi.updateContainer(toolTest.getId(), toolTest); toolsApi.refresh(toolTest.getId()); final String updatedForumUrl = testingPostgres.runSelectStatement("select forumurl from tool where id = " + toolTest.getId(), String.class); assertEquals("the forumurl should be hello.com", "hello.com", updatedForumUrl); }

Target:
public void testUpdateToolForumUrl() throws ApiException { final String forumUrl = "hello.com"; ContainersApi toolsApi = setupWebService(); DockstoreTool toolTest = toolsApi.getContainerByToolPath(DOCKERHUB_TOOL_PATH, null); toolsApi.refresh(toolTest.getId()); toolTest.setForumUrl(forumUrl); toolsApi.updateContainer(toolTest.getId(), toolTest); toolsApi.refresh(toolTest.getId()); final String updatedForumUrl = testingPostgres.runSelectStatement("select forumurl from tool where id = " + toolTest.getId(), String.class); assertEquals("the forumurl should be hello.com", forumUrl, updatedForumUrl); }
Source:
public void testList() throws IOException, StripeException { final Customer customer = Customer.retrieve(CUSTOMER_ID); Map<String, Object> params = new HashMap<String, Object>(); params.put("object", "card"); Card stubbedCard = getCardFixture(customer); ExternalAccountCollection stubbedCollection = new ExternalAccountCollection(); List<ExternalAccount> stubbedData = new LinkedList<ExternalAccount>(); stubbedData.add(stubbedCard); stubbedCollection.setData(stubbedData); stubRequest( APIResource.RequestMethod.GET, String.format("/v1/customers/%s/sources", customer.getId()), params, ExternalAccountCollection.class, stubbedCollection.toJson() ); final ExternalAccountCollection externalAccounts = customer.getSources().list(params); assertNotNull(externalAccounts); assertEquals(1, externalAccounts.getData().size()); verifyRequest( APIResource.RequestMethod.GET, String.format("/v1/customers/%s/sources", customer.getId()) ); Card card = (Card) externalAccounts.getData().get(0); assertNotNull(card); }

Target:
public void testList() throws IOException, StripeException { final Customer customer = Customer.retrieve(CUSTOMER_ID); final Map<String, Object> params = new HashMap<String, Object>(); params.put("object", "card"); params.put("limit", 1); final Card stubbedCard = getCardFixture(customer); final ExternalAccountCollection stubbedCollection = new ExternalAccountCollection(); final List<ExternalAccount> stubbedData = new LinkedList<ExternalAccount>(); stubbedData.add(stubbedCard); stubbedCollection.setData(stubbedData); stubRequest( APIResource.RequestMethod.GET, String.format("/v1/customers/%s/sources", customer.getId()), params, ExternalAccountCollection.class, stubbedCollection.toJson() ); final ExternalAccountCollection externalAccounts = customer.getSources().list(params); assertNotNull(externalAccounts); assertEquals(1, externalAccounts.getData().size()); verifyRequest( APIResource.RequestMethod.GET, String.format("/v1/customers/%s/sources", customer.getId()) ); final Card card = (Card) externalAccounts.getData().get(0); assertNotNull(card); }
Source:
public void accept(ProbeResult probeResult) { String machineName = probeResult.getMachineName(); DockerMachine machine = startSynchronizer.getMachines().get(machineName); if (machine == null) { return; } String serverName = probeResult.getServerName(); ProbeStatus probeStatus = probeResult.getStatus(); Server server = machine.getServers().get(serverName); ServerStatus oldServerStatus = server.getStatus(); ServerStatus serverStatus; if (probeStatus == ProbeStatus.FAILED && oldServerStatus == ServerStatus.RUNNING) { serverStatus = ServerStatus.STOPPED; } else if (probeStatus == ProbeStatus.PASSED && (oldServerStatus == null || oldServerStatus == ServerStatus.UNKNOWN || oldServerStatus == ServerStatus.STOPPED)) { serverStatus = ServerStatus.RUNNING; } else { return; } machine.setServerStatus(serverName, serverStatus); sendServerStatusEvent(machineName, serverName, machine.getServers().get(serverName)); }

Target:
public void accept(ProbeResult probeResult) { String machineName = probeResult.getMachineName(); DockerMachine machine = startSynchronizer.getMachines().get(machineName); if (machine == null) { return; } String serverName = probeResult.getServerName(); ProbeStatus probeStatus = probeResult.getStatus(); Server server = machine.getServers().get(serverName); ServerStatus oldServerStatus = server.getStatus(); ServerStatus serverStatus; if (probeStatus == ProbeStatus.FAILED && oldServerStatus == ServerStatus.RUNNING) { serverStatus = ServerStatus.STOPPED; } else if (probeStatus == ProbeStatus.PASSED && (oldServerStatus != ServerStatus.RUNNING)) { serverStatus = ServerStatus.RUNNING; } else { return; } machine.setServerStatus(serverName, serverStatus); sendServerStatusEvent(machineName, serverName, machine.getServers().get(serverName)); }
Source:
public Snippet063ComboViewer(Shell shell) { GridLayoutFactory.fillDefaults().numColumns(2) .margins(LayoutConstants.getMargins()).generateLayout(shell); final Label l = new Label(shell, SWT.None); l.setText("Choose Item:"); final ComboViewer v = new ComboViewer(shell); v.setLabelProvider(new LabelProvider()); v.setContentProvider(new MyContentProvider()); v.setInput(createModel()); }

Target:
public Snippet063ComboViewer(Shell shell) { GridLayoutFactory.fillDefaults().numColumns(2) .margins(LayoutConstants.getMargins()).generateLayout(shell); final Label l = new Label(shell, SWT.None); l.setText("Choose Item:"); final ComboViewer v = new ComboViewer(shell); v.setLabelProvider(new LabelProvider()); v.setContentProvider(new MyContentProvider()); MyModel[] model = createModel(); v.setInput(model); if (model.length > 0) { v.setSelection(new StructuredSelection(model[0])); } }
Source:
public void importPackage(String name) { Package p = Package.getPackage(name); String rqpath = ServletRequestsAttr.getCurrentURL(); if (p == null) { ClassLoader cl = ClassUtil.getContextClassLoader(ImportHandler.class); String path = name.replace('.', '/'); URL url = cl.getResource(path); if (url == null) { throw new ELException(Util.message( null, "importHandler.invalidPackage", name)); } } List packageList = importPackages.get(rqpath); if (packageList == null) { packageList = new ArrayList<String>(Arrays.asList(JAVA_LANG_PACKAGE)); } if (!packageList.contains(name)) { packageList.add(name); } importPackages.put(rqpath , packageList); }

Target:
public void importPackage(String name) { String rqpath = ServletRequestsAttr.getCurrentURL(); List<String> packages = importPackages.get(rqpath); if (packages == null) { packages = new ArrayList(Arrays.asList(JAVA_LANG_PACKAGE)); } packages.add(name); importPackages.put(rqpath , packages); }
Source:
private String getKey() { if (this.key == null && this.rememberMeServices instanceof AbstractRememberMeServices) { this.key = ((AbstractRememberMeServices) rememberMeServices).getKey(); } if (this.key == null) { this.key = UUID.randomUUID().toString(); } return this.key; }

Target:
private String getKey() { if (this.key == null) { if (this.rememberMeServices instanceof AbstractRememberMeServices) { this.key = ((AbstractRememberMeServices) rememberMeServices).getKey(); } else { this.key = UUID.randomUUID().toString(); } } return this.key; }
Source:
protected boolean set(TileEntityFurnace container, Integer value) { container.setField(3, value); return true; }

Target:
protected boolean set(TileEntityFurnace container, Integer value) { if(container.getStackInSlot(0) == null || value > container.getField(3)){ return false; } container.setField(2, value); return true; }
Source:
public void testSetErrorInResponseWhenNoUserFoundForProvidedToken() throws Exception { when(userManagerMock.getById(anyString())).thenThrow(new NotFoundException("User not found")); machineLoginFilter.doFilter(getRequestMock(), responseMock, chainMock); verify(keyManagerMock, atLeastOnce()).getOrCreateKeyPair(eq(WORKSPACE_ID)); verify(userManagerMock).getById(anyString()); verify(responseMock) .sendError( 401, "Authentication with machine token failed cause: User for this token no longer exist."); }

Target:
public void testSetErrorInResponseWhenNoUserFoundForProvidedToken() throws Exception { when(userManagerMock.getById(anyString())).thenThrow(new NotFoundException("User not found")); machineLoginFilter.doFilter(getRequestMock(), responseMock, chainMock); verify(keyManagerMock, atLeastOnce()).getOrCreateKeyPair(eq(WORKSPACE_ID)); verify(userManagerMock).getById(anyString()); verify(responseMock) .sendError(401, "Machine token authentication failed: Corresponding user doesn't exist."); }
Source:
void verifyPartLinkFilesExist(List<String> theMultiPartLinkFiles, String theSinglePartLinkFile) { List<String> notFoundMulti = notFound(theMultiPartLinkFiles); List<String> notFoundSingle = notFound(Arrays.asList(theSinglePartLinkFile)); boolean multiPartFilesFound = notFoundMulti.isEmpty(); boolean singlePartFilesFound = notFoundSingle.isEmpty(); if (!LogicUtil.multiXor(multiPartFilesFound, singlePartFilesFound)) { String msg; if (!multiPartFilesFound && !singlePartFilesFound) { msg = "Could not find any of the PartLink files: " + notFoundMulti + " or " + notFoundSingle; } else { msg = "Found both the single PartLink file, " + theSinglePartLinkFile + ", and the split PartLink files: " + theMultiPartLinkFiles; } throw new UnprocessableEntityException(msg); } }

Target:
void verifyPartLinkFilesExist(List<String> theMultiPartLinkFiles, String theSinglePartLinkFile) { List<String> notFoundMulti = notFound(theMultiPartLinkFiles); List<String> notFoundSingle = notFound(Arrays.asList(theSinglePartLinkFile)); boolean multiPartFilesFound = notFoundMulti.isEmpty(); boolean singlePartFilesFound = notFoundSingle.isEmpty(); if (!LogicUtil.multiXor(multiPartFilesFound, singlePartFilesFound)) { String msg; if (!multiPartFilesFound && !singlePartFilesFound) { msg = "Could not find any of the PartLink files: " + notFoundMulti + " nor " + notFoundSingle; } else { msg = "Only either the single PartLink file or the split PartLink files can be present. Found both the single PartLink file, " + theSinglePartLinkFile + ", and the split PartLink files: " + theMultiPartLinkFiles; } throw new UnprocessableEntityException(msg); } }
Source:
@Override public GridCursor<Row> find(Row lower, Row upper, BPlusTree.TreeRowClosure<Row, Row> filterC) { return find(lower, upper); }

Target:
@Override public GridCursor<Row> find(Row lower, Row upper, BPlusTree.TreeRowClosure<Row, Row> filterC) { assert filterC == null; int firstCol = F.first(collation.getKeys()); if (ectx.rowHandler().get(firstCol, lower) != null && ectx.rowHandler().get(firstCol, upper) != null) return new Cursor(rows.subMap(lower, true, upper, true)); else if (ectx.rowHandler().get(firstCol, lower) == null && ectx.rowHandler().get(firstCol, upper) != null) return new Cursor(rows.headMap(upper, true)); else if (ectx.rowHandler().get(firstCol, lower) != null && ectx.rowHandler().get(firstCol, upper) == null) return new Cursor(rows.tailMap(lower, true)); else return new Cursor(rows); }
Source:
public EhcacheEntityResponse decode(byte[] payload) { ByteBuffer buffer = ByteBuffer.wrap(payload); byte opCode = buffer.get(); EhcacheEntityResponse.Type type = EhcacheEntityResponse.Type.responseType(opCode); byte[] payArr = new byte[buffer.remaining()]; buffer.get(payArr); switch (type) { case SUCCESS: return EhcacheEntityResponse.Success.INSTANCE; case FAILURE: Exception exception = (Exception)Util.unmarshall(payArr); return new EhcacheEntityResponse.Failure(exception); case GET_RESPONSE: return new EhcacheEntityResponse.GetResponse(ChainCodec.decode(payArr)); default: throw new UnsupportedOperationException("The operation is not supported with opCode : " + opCode); } }

Target:
public EhcacheEntityResponse decode(byte[] payload) { ByteBuffer buffer = ByteBuffer.wrap(payload); byte opCode = buffer.get(); EhcacheEntityResponse.Type type = EhcacheEntityResponse.Type.responseType(opCode); byte[] payArr = new byte[buffer.remaining()]; buffer.get(payArr); switch (type) { case SUCCESS: return EhcacheEntityResponse.Success.INSTANCE; case FAILURE: Exception exception = (Exception)Util.unmarshall(payArr); return new EhcacheEntityResponse.Failure(exception); case GET_RESPONSE: return new EhcacheEntityResponse.GetResponse(chainCodec.decode(payArr)); default: throw new UnsupportedOperationException("The operation is not supported with opCode : " + opCode); } }
Source:
private static String readCurrentNL() { FileInputStream fin = null; try { URL url = Platform.getConfigurationLocation().getURL(); Properties p = new Properties(); File iniFile = new File(url.getFile(), "config.ini"); fin = new FileInputStream(iniFile); p.load(fin); return p.getProperty(OSGI_NL); } catch (IOException ex) { LOG.error(ex.getMessage(), ex); return null; } finally { IOUtils.closeQuietly(fin); } }

Target:
private static String readCurrentNL() { FileInputStream fin = null; try { URL url = Platform.getConfigurationLocation().getURL(); Properties p = new Properties(); File iniFile = new File(url.getFile(), "config.ini"); fin = new FileInputStream(iniFile); p.load(fin); return p.getProperty(OSGI_NL); } catch (IOException ex) { LOG.error("Fail in reading config.ini file", ex); return null; } finally { IOUtils.closeQuietly(fin); } }
Source:
void dump(final IndentingPrintWriter pw) { pw.println("mPotentialConflictPrefixesMap:"); for (int i = 0; i < mPotentialConflictPrefixesMap.size(); i++) { pw.println(mPotentialConflictPrefixesMap.keyAt(i) + " - " + mPotentialConflictPrefixesMap.valueAt(i)); } pw.println("mDownstreamPrefixMap:"); for (int i = 0; i < mDownstreamPrefixMap.size(); i++) { pw.println(mDownstreamPrefixMap.keyAt(i) + " - " + mDownstreamPrefixMap.valueAt(i)); } }

Target:
void dump(final IndentingPrintWriter pw) { pw.println("mUpstreamPrefixMap:"); pw.increaseIndent(); for (int i = 0; i < mUpstreamPrefixMap.size(); i++) { pw.println(mUpstreamPrefixMap.keyAt(i) + " - " + mUpstreamPrefixMap.valueAt(i)); } pw.println("mDownstreamPrefixMap:"); for (int i = 0; i < mDownstreamPrefixMap.size(); i++) { pw.println(mDownstreamPrefixMap.keyAt(i) + " - " + mDownstreamPrefixMap.valueAt(i)); } pw.decreaseIndent(); }
Source:
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { Context context = ReactiveSecurityContextHolder.getContext() .filter(Objects::isNull) .switchIfEmpty(Mono.fromSupplier(() -> { SecurityContext securityContext = new SecurityContextImpl(); securityContext.setAuthentication(createAuthentication(exchange)); return securityContext; })) .as(ReactiveSecurityContextHolder::withSecurityContext); return Mono.subscriberContext() .subscriberContext(context) .then(chain.filter(exchange)); }

Target:
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { return ReactiveSecurityContextHolder.getContext() .switchIfEmpty(Mono.defer(() -> { SecurityContext securityContext = new SecurityContextImpl(); securityContext.setAuthentication(createAuthentication(exchange)); return chain.filter(exchange) .subscriberContext(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))) .then(Mono.empty()); })).flatMap(securityContext -> chain.filter(exchange)); }
Source:
public static PluginMessage fromString(String channel, String text) { ByteBuf buf = Unpooled.buffer(5 + text.length()); try { try { ByteBufUtils.writeUTF8(buf, text); } catch (NullPointerException e) { ByteBufUtils.writeUTF8(buf, "Glowstone"); } } catch (IOException e) { GlowServer.logger.log(Level.WARNING, "Error converting to PluginMessage: \"" + channel + "\", \"" + text + "\"", e); } byte[] array = buf.array(); buf.release(); return new PluginMessage(channel, array); }

Target:
public static PluginMessage fromString(String channel, String text) { ByteBuf buf = Unpooled.buffer(5 + text.length()); try { ByteBufUtils.writeUTF8(buf, text); } catch (IOException e) { GlowServer.logger.log(Level.WARNING, "Error converting to PluginMessage: \"" + channel + "\", \"" + text + "\"", e); } byte[] array = buf.array(); buf.release(); return new PluginMessage(channel, array); }
Source:
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { try { this.cordovaInterface.onRequestPermissionResult(requestCode, permissions, grantResults); } catch (JSONException ex) { LOG.d(TAG, "JSONException: Parameters fed into the method are not valid"); ex.printStackTrace(); } }

Target:
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { try { this.cordovaInterface.onRequestPermissionResult(requestCode, permissions, grantResults); } catch (JSONException ex) { LOG.d(TAG, "JSONException: Parameters fed into the method are not valid"); } }
Source:
boolean isProjectStyle() { if (myIsFrameworkStyle) { return false; } ProjectResourceRepository repository = ProjectResourceRepository.getProjectResources(myConfiguration.getModule(), true); assert repository != null : repository.getDisplayName(); return repository.hasResourceItem(ResourceType.STYLE, myStyleName); }

Target:
boolean isProjectStyle() { if (myIsFrameworkStyle) { return false; } ProjectResourceRepository repository = ProjectResourceRepository.getProjectResources(myConfiguration.getModule(), true); assert repository != null : myConfiguration.getModule().getName(); return repository.hasResourceItem(ResourceType.STYLE, myStyleName); }
Source:
protected Command getCommand(IEvaluationContext context) { TransactionalEditingDomain editingDomain = getEditingDomain(context); List<Diagram> diagrams = getSelectedDiagrams(); if (editingDomain != null && diagrams.size() == 1) { final Diagram diag = diagrams.get(0); final String diagramLabel = LabelInternationalization.getInstance().getDiagramLabelWithoutName(diag); if (null != diagramLabel && LabelInternationalizationPreferencesUtils.getInternationalizationPreference(diag)) { AbstractTransactionalCommand cmd = new RenameDiagramLabelCommand( editingDomain, "ChangeDiagramLabelCommand", diag, diagramLabel, "Rename diagram label...", "New label:"); return new GMFtoEMFCommandWrapper(cmd); } else { final String currentName = diag.getName(); if (currentName != null) { return new RenameElementCommand( editingDomain, "RenameDiagramCommand", diag, currentName, Messages.RenameDiagramHandler_RenameAnExistingDiagram, Messages.RenameDiagramHandler_NewName); } } } return UnexecutableCommand.INSTANCE; }

Target:
protected Command getCommand(IEvaluationContext context) { TransactionalEditingDomain editingDomain = getEditingDomain(context); List<Diagram> diagrams = getSelectedDiagrams(); if (editingDomain != null && diagrams.size() == 1) { final Diagram diag = diagrams.get(0); final String diagramLabel = LabelInternationalization.getInstance().getDiagramLabelWithoutName(diag); if (null != diagramLabel && LabelInternationalizationPreferencesUtils.getInternationalizationPreference(diag)) { AbstractTransactionalCommand cmd = new RenameDiagramLabelCommand(editingDomain, "ChangeDiagramLabelCommand", diag, diagramLabel, Messages.RenameDiagramHandler_Label_DialogTitle); return new GMFtoEMFCommandWrapper(cmd); } else { final String currentName = diag.getName(); if (currentName != null) { EStructuralFeature nameFeature = diag.eClass().getEStructuralFeature("name"); return new RenameElementCommand(editingDomain, "RenameDiagramCommand", diag, currentName, nameFeature, Messages.RenameDiagramHandler_RenameAnExistingDiagram, Messages.RenameDiagramHandler_NewName); } } } return UnexecutableCommand.INSTANCE; }