auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public <T> T getObjectFromPropertyDefinition(PropertyDefinition propertyDefinition) throws ServiceLocalException { ServiceLocalException serviceException = null; OutParam<ServiceLocalException> serviceExceptionOut = new OutParam<ServiceLocalException>(); Object propertyValue = this.getPropertyValueOrException( propertyDefinition, serviceExceptionOut); serviceException = serviceExceptionOut.getParam(); if (serviceException == null) { return (T) propertyValue; } else { throw serviceException; } }

Target:
public <T> T getObjectFromPropertyDefinition(PropertyDefinition propertyDefinition) throws ServiceLocalException { OutParam<ServiceLocalException> serviceExceptionOut = new OutParam<ServiceLocalException>(); T propertyValue = getPropertyValueOrException(propertyDefinition, serviceExceptionOut); ServiceLocalException serviceException = serviceExceptionOut.getParam(); if (serviceException != null) { throw serviceException; } return propertyValue; }
Source:
protected void removeInlineDeployments() { runtime.getComponentManager().reset(); runtime.getComponentManager().start(); }

Target:
protected void removeInlineDeployments() throws Exception { runtime.getComponentManager().reset(); runtime.getComponentManager().start(); postSetUp(); }
Source:
private void decorateText(IDecoration decoration, IDecoratableResource resource) { String format = ""; switch (resource.getType()) { case IResource.FILE: format = store .getString(UIPreferences.DECORATOR_FILETEXT_DECORATION); break; case IResource.FOLDER: case DecoratableResourceMapping.RESOURCE_MAPPING: if (resource.isWorkingTreeRoot()) { format = store.getString( UIPreferences.DECORATOR_PROJECTTEXT_DECORATION); } else { format = store .getString(UIPreferences.DECORATOR_FOLDERTEXT_DECORATION); } break; case DecoratableResourceMapping.WORKING_SET: if (resource.getRepositoryName() != null && resource.getBranch() != null) format = store .getString(UIPreferences.DECORATOR_PROJECTTEXT_DECORATION); else format = store .getString(UIPreferences.DECORATOR_FOLDERTEXT_DECORATION); break; case IResource.PROJECT: format = store .getString(UIPreferences.DECORATOR_PROJECTTEXT_DECORATION); break; } Map<String, String> bindings = new HashMap<String, String>(); bindings.put(BINDING_RESOURCE_NAME, resource.getName()); bindings.put(BINDING_REPOSITORY_NAME, resource.getRepositoryName()); bindings.put(BINDING_BRANCH_NAME, resource.getBranch()); bindings.put(BINDING_BRANCH_STATUS, resource.getBranchStatus()); bindings.put(BINDING_DIRTY_FLAG, resource.isDirty() ? ">" : null); bindings.put(BINDING_STAGED_FLAG, resource.isStaged() ? "*" : null); decorate(decoration, format, bindings); }

Target:
private void decorateText(IDecoration decoration, IDecoratableResource resource) { String format = ""; switch (resource.getType()) { case IResource.FILE: format = store .getString(UIPreferences.DECORATOR_FILETEXT_DECORATION); break; case IResource.FOLDER: case DecoratableResourceMapping.RESOURCE_MAPPING: if (resource.isWorkingTreeRoot()) { format = store.getString( UIPreferences.DECORATOR_SUBMODULETEXT_DECORATION); } else { format = store.getString( UIPreferences.DECORATOR_FOLDERTEXT_DECORATION); } break; case DecoratableResourceMapping.WORKING_SET: if (resource.getRepositoryName() != null && resource.getBranch() != null) format = store .getString(UIPreferences.DECORATOR_PROJECTTEXT_DECORATION); else format = store .getString(UIPreferences.DECORATOR_FOLDERTEXT_DECORATION); break; case IResource.PROJECT: format = store .getString(UIPreferences.DECORATOR_PROJECTTEXT_DECORATION); break; } Map<String, String> bindings = new HashMap<String, String>(); bindings.put(BINDING_RESOURCE_NAME, resource.getName()); bindings.put(BINDING_REPOSITORY_NAME, resource.getRepositoryName()); bindings.put(BINDING_BRANCH_NAME, resource.getBranch()); bindings.put(BINDING_BRANCH_STATUS, resource.getBranchStatus()); bindings.put(BINDING_DIRTY_FLAG, resource.isDirty() ? ">" : null); bindings.put(BINDING_STAGED_FLAG, resource.isStaged() ? "*" : null); bindings.put(BINDING_SHORT_MESSAGE, resource.getCommitMessage()); decorate(decoration, format, bindings); }
Source:
public void testForceRefreshWithoutAutoRefresh() throws Exception { changeSiriusPreference(SiriusPreferencesKeys.PREF_AUTO_REFRESH.name(), false); assertTrue("Diagram should be empty", firstDiag.getOwnedDiagramElements().isEmpty()); assertTrue("Diagram should be empty", secondDiag.getOwnedDiagramElements().isEmpty()); applyNodeCreationTool("createPackageWithRefresh", secondDiag, secondDiag); assertEquals("Force refresh diagram has not been refreshed.", 1, secondDiag.getOwnedDiagramElements().size()); assertTrue("The non 'force refresh' diagram has been refreshed whereas 'automatic refresh' is false.", firstDiag.getOwnedDiagramElements().isEmpty()); }

Target:
public void testForceRefreshWithoutAutoRefresh() throws Exception { changeSiriusPreference(SiriusPreferencesKeys.PREF_AUTO_REFRESH.name(), false); assertTrue("Diagram should be empty", firstDiag.getOwnedDiagramElements().isEmpty()); assertTrue("Diagram should be empty", secondDiag.getOwnedDiagramElements().isEmpty()); applyNodeCreationTool("createPackageWithRefresh", secondDiag, secondDiag); assertEquals("Force refresh diagram has not been refreshed. Bad diagram elements number in diagram " + secondDiag.getName(), 1, secondDiag.getOwnedDiagramElements().size()); assertTrue("The non 'force refresh' diagram has been refreshed whereas 'automatic refresh' is false.", firstDiag.getOwnedDiagramElements().isEmpty()); }
Source:
private void getContainerStorageManagers() { Clock clock = SystemClock.instance(); StreamMetadataCache streamMetadataCache = new StreamMetadataCache(systemAdmins, 5000, clock); Map<String, SystemFactory> systemFactories = new JavaSystemConfig(jobConfig).getSystemFactories(); for (ContainerModel containerModel : containers.values()) { ContainerContext containerContext = new ContainerContextImpl(containerModel, new MetricsRegistryMap()); ContainerStorageManager containerStorageManager = new ContainerStorageManager(containerModel, streamMetadataCache, systemAdmins, changeLogSystemStreams, storageEngineFactories, systemFactories, this.getSerdes(), jobConfig, new HashMap<>(), new SamzaContainerMetrics(containerModel.getId(), new MetricsRegistryMap()), JobContextImpl.fromConfigWithDefaults(jobConfig), containerContext, new HashMap<>(), Optional.of(storeBaseDir), Optional.of(storeBaseDir), maxPartitionNumber, new SystemClock()); this.containerStorageManagers.put(containerModel.getId(), containerStorageManager); } }

Target:
private void getContainerStorageManagers() { Clock clock = SystemClock.instance(); StreamMetadataCache streamMetadataCache = new StreamMetadataCache(systemAdmins, 5000, clock); Map<String, SystemFactory> systemFactories = new JavaSystemConfig(jobConfig).getSystemFactories(); for (ContainerModel containerModel : containers.values()) { ContainerContext containerContext = new ContainerContextImpl(containerModel, new MetricsRegistryMap()); ContainerStorageManager containerStorageManager = new ContainerStorageManager(containerModel, streamMetadataCache, systemAdmins, changeLogSystemStreams, storageEngineFactories, systemFactories, this.getSerdes(), jobConfig, new HashMap<>(), new SamzaContainerMetrics(containerModel.getId(), new MetricsRegistryMap()), JobContextImpl.fromConfigWithDefaults(jobConfig), containerContext, new HashMap<>(), storeBaseDir, storeBaseDir, maxPartitionNumber, new SystemClock()); this.containerStorageManagers.put(containerModel.getId(), containerStorageManager); } }
Source:
public void testFourthToSixthVerses() { String expectedVersesFourToSix - "On the fourth day of Chrsitmas my true love gave to me, " + "four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n\n" + "On the fifth day of Christmas my true love gave to me, five Gold Rings, four Calling Birds, " + "three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n\n" + "On the sixth day of Christmas my true love gave to me, six Geese-a-Laying, five Gold Rings, " + "four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n" assertEquals(expectedVersesFourToSix, twelveDays.verses(4, 6)); }

Target:
public void testFourthToSixthVerses() { String expectedVersesFourToSix = "On the fourth day of Christmas my true love gave to me, " + "four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n\n" + "On the fifth day of Christmas my true love gave to me, five Gold Rings, four Calling Birds, " + "three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n\n" + "On the sixth day of Christmas my true love gave to me, six Geese-a-Laying, five Gold Rings, " + "four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n"; assertEquals(expectedVersesFourToSix, twelveDays.verses(4, 6)); }
Source:
public void init() { get( "/forms/query", (req, res) -> MAPPER.toJson( util.getMetacardsByFilter(FormAttributes.Query.TAG) .entrySet() .stream() .map(Map.Entry::getValue) .map(Result::getMetacard) .map(this::toFormTemplate) .filter(Objects::nonNull) .collect(Collectors.toList()))); get( "/forms/result", (req, res) -> MAPPER.toJson( util.getMetacardsByFilter(FormAttributes.Result.TAG) .entrySet() .stream() .map(Map.Entry::getValue) .map(Result::getMetacard) .map(this::toFieldFilter) .filter(Objects::nonNull) .collect(Collectors.toList()))); }

Target:
public void init() { get( "/forms/query", (req, res) -> util.getMetacardsByFilter(QUERY_TEMPLATE_TAG) .values() .stream() .map(Result::getMetacard) .filter(Objects::nonNull) .map(transformer::toFormTemplate) .filter(Objects::nonNull) .collect(Collectors.toList()), MAPPER::toJson); get( "/forms/result", (req, res) -> util.getMetacardsByFilter(ATTRIBUTE_GROUP_TAG) .values() .stream() .map(Result::getMetacard) .filter(Objects::nonNull) .map(transformer::toFieldFilter) .filter(Objects::nonNull) .collect(Collectors.toList()), MAPPER::toJson); }
Source:
public void patchNetId() throws Exception { context.turnOffAuthorisationSystem(); EPerson ePerson = EPersonBuilder.createEPerson(context) .withNameInMetadata("John", "Doe") .withEmail("Johndoe@fake-email.com") .build(); List<Operation> ops = new ArrayList<Operation>(); ReplaceOperation replaceOperation = new ReplaceOperation("/netid", "newNetId"); ops.add(replaceOperation); String patchBody = getPatchContent(ops); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(patch("/api/eperson/epersons/" + ePerson.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.netid", Matchers.is("newNetId"))); }

Target:
public void patchNetId() throws Exception { context.turnOffAuthorisationSystem(); EPerson ePerson = EPersonBuilder.createEPerson(context) .withNameInMetadata("John", "Doe") .withEmail("Johndoe@fake-email.com") .withNetId("testId") .build(); List<Operation> ops = new ArrayList<Operation>(); ReplaceOperation replaceOperation = new ReplaceOperation("/netid", "newNetId"); ops.add(replaceOperation); String patchBody = getPatchContent(ops); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(patch("/api/eperson/epersons/" + ePerson.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.netid", Matchers.is("newNetId"))) .andExpect(jsonPath("$.email", Matchers.is("johndoe@fake-email.com"))) .andExpect(jsonPath("$.canLogIn", Matchers.is(false))); }
Source:
public EventReceiverFirehoseFactory( @JsonProperty("serviceName") String serviceName, @JsonProperty("firehoseId") String firehoseId, @JsonProperty("bufferSize") Integer bufferSize, @JsonProperty("parser") MapInputRowParser parser, @JacksonInject ChatHandlerProvider chatHandlerProvider, @JacksonInject EventReceiverFirehoseFactoryConfig config ) { if (serviceName == null) { serviceName = String.format("%s:%s", config.getFirehoseIdPrefix(), Preconditions.checkNotNull(firehoseId, "firehoseId") ); } this.serviceName = Preconditions.checkNotNull(serviceName, "serviceName"); this.bufferSize = bufferSize == null || bufferSize <= 0 ? DEFAULT_BUFFER_SIZE : bufferSize; this.parser = Preconditions.checkNotNull(parser, "parser"); this.chatHandlerProvider = Optional.fromNullable(chatHandlerProvider); }

Target:
public EventReceiverFirehoseFactory( @JsonProperty("serviceName") String serviceName, @JsonProperty("firehoseId") String firehoseId, @JsonProperty("bufferSize") Integer bufferSize, @JsonProperty("parser") MapInputRowParser parser, @JacksonInject ChatHandlerProvider chatHandlerProvider, @JacksonInject EventReceiverFirehoseFactoryConfig config ) { if (serviceName == null) { this.serviceName = String.format( "%s:%s", config.getFirehoseIdPrefix(), Preconditions.checkNotNull(firehoseId, "firehoseId") ); } else { this.serviceName = Preconditions.checkNotNull(serviceName, "serviceName"); } this.config = config; this.bufferSize = bufferSize == null || bufferSize <= 0 ? DEFAULT_BUFFER_SIZE : bufferSize; this.parser = Preconditions.checkNotNull(parser, "parser"); this.chatHandlerProvider = Optional.fromNullable(chatHandlerProvider); }
Source:
public EntitleByProductsJobConfig() { this.setJobKey(JOB_KEY) .setJobName(JOB_NAME) .addConstraint(JobConstraints.uniqueByArguments(OWNER_KEY)); }

Target:
public EntitleByProductsJobConfig() { this.setJobKey(JOB_KEY) .setJobName(JOB_NAME); }
Source:
public DelegatingResourceDescription getCreatableProperties() { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addProperty("allergyId"); description.addProperty("allergen"); description.addProperty("severity"); description.addProperty("comment"); description.addProperty("reactions"); return description; }

Target:
public DelegatingResourceDescription getCreatableProperties() { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addRequiredProperty("allergen"); description.addProperty("severity"); description.addProperty("comment"); description.addProperty("reactions"); return description; }
Source:
public void setMethodInfo(ICPPASTFunctionDefinition functionDefinition, ICPPMethod classMethod) { method = classMethod; returnNoConstRef = false; IASTPointerOperator[] ptr = functionDefinition.getDeclarator().getPointerOperators(); if (ptr.length > 0 && ptr[0] instanceof ICPPASTReferenceOperator) { returnNoConstRef = !functionDefinition.getDeclSpecifier().isConst(); } isOverloadedOperator = isOverloadedOperator(classMethod.getName()); if (method.isStatic()) { checkerMode = CheckerMode.MODE_STATIC; } else if (method.getType().isConst()) { checkerMode = CheckerMode.MODE_CONST; } else { checkerMode = CheckerMode.MODE_NON_CONST; } classMembersAreUsed = false; classMembersAreWritten = false; hasProblems = false; isVirtual = null; }

Target:
public void setMethodInfo(ICPPASTFunctionDefinition functionDefinition, ICPPMethod classMethod) { method = classMethod; returnNoConstRef = false; IType retTyoe = SemanticUtil.getNestedType(method.getType().getReturnType(), SemanticUtil.TDEF); if (retTyoe instanceof ICPPReferenceType && !SemanticUtil.isConst(retTyoe)) { returnNoConstRef = true; } isOverloadedOperator = isOverloadedOperator(classMethod.getName()); if (method.isStatic()) { checkerMode = CheckerMode.MODE_STATIC; } else if (method.getType().isConst()) { checkerMode = CheckerMode.MODE_CONST; } else { checkerMode = CheckerMode.MODE_NON_CONST; } classMembersAreUsed = false; classMembersAreWritten = false; hasProblems = false; isVirtual = null; }
Source:
protected ObjectId commit(final Merger m, final CommitBuilder mergeCommit) throws IOException, UnsupportedEncodingException { ObjectInserter oi = m.getObjectInserter(); try { ObjectId id = oi.insert(mergeCommit); oi.flush(); return id; } finally { oi.release(); } }

Target:
protected final ObjectId commit(final Merger m, final CommitBuilder mergeCommit) throws IOException, UnsupportedEncodingException { ObjectInserter oi = m.getObjectInserter(); try { ObjectId id = oi.insert(mergeCommit); oi.flush(); return id; } finally { oi.release(); } }
Source:
public static StarlarkInt subtract(StarlarkInt x, StarlarkInt y) { if (x instanceof Int32 && y instanceof Int32) { long xl = ((Int32) x).v; long yl = ((Int32) y).v; return StarlarkInt.of(xl - yl); } try { long xl = x.toLongFast(); long yl = y.toLongFast(); long r = xl - yl; boolean overflow = ((xl >= 0) != (yl >= 0)) && ((yl >= 0) == (r >= 0)); if (!overflow) { return StarlarkInt.of(r); } } catch (OverflowException ignore) { } BigInteger xbig = x.toBigInteger(); BigInteger ybig = y.toBigInteger(); BigInteger zbig = xbig.subtract(ybig); return StarlarkInt.of(zbig); }

Target:
public static StarlarkInt subtract(StarlarkInt x, StarlarkInt y) { if (x instanceof Int32 && y instanceof Int32) { long xl = ((Int32) x).v; long yl = ((Int32) y).v; return StarlarkInt.of(xl - yl); } try { long xl = x.toLongFast(); long yl = y.toLongFast(); long zl = xl - yl; boolean overflow = ((xl ^ yl) & (xl ^ zl)) < 0; if (!overflow) { return StarlarkInt.of(zl); } } catch (Overflow unused) { } BigInteger xbig = x.toBigInteger(); BigInteger ybig = y.toBigInteger(); BigInteger zbig = xbig.subtract(ybig); return StarlarkInt.of(zbig); }
Source:
public void includeResource(Resource resource) { if (resourcesToInclude != null) { for (Resource res : resourcesToInclude) { if (res.getProviderName().equals(resource.getProviderName()) && res.getResourcePath().equals(resource.getResourcePath())) { throw new UiFrameworkException("Resource '"+ resource.getResourcePath() +"' Already Included in PageContext"); } } resourcesToInclude.add(resource); } else { resourcesToInclude.add(resource); } }

Target:
public void includeResource(Resource resource) { Iterator<Resource> iterator = resourcesToInclude.iterator(); while (iterator.hasNext()) { Resource res = iterator.next(); if (res.getProviderName().equals(resource.getProviderName()) && res.getResourcePath().equals(resource.getResourcePath())) { if (res.getPriority() < resource.getPriority()) { iterator.remove(); resourcesToInclude.add(resource); } return; } } resourcesToInclude.add(resource); }
Source:
public static Set<String> findCaches(Properties properties) { Set<String> caches = new HashSet<>(); caches.add(properties.getProperty(ENTITY_CACHE_RESOURCE_PROP, DEF_ENTITY_RESOURCE)); caches.add(properties.getProperty(COLLECTION_CACHE_RESOURCE_PROP, DEF_ENTITY_RESOURCE)); caches.add(properties.getProperty(COLLECTION_CACHE_RESOURCE_PROP, DEF_ENTITY_RESOURCE)); caches.add(properties.getProperty(NATURAL_ID_CACHE_RESOURCE_PROP, DEF_ENTITY_RESOURCE)); if (Boolean.parseBoolean(properties.getProperty(AvailableSettings.USE_QUERY_CACHE))) { caches.add(properties.getProperty(QUERY_CACHE_RESOURCE_PROP, DEF_QUERY_RESOURCE)); caches.add(properties.getProperty(TIMESTAMPS_CACHE_RESOURCE_PROP, DEF_QUERY_RESOURCE)); } int length = INFINISPAN_CONFIG_RESOURCE_PROP.length(); String customRegionPrefix = INFINISPAN_CONFIG_RESOURCE_PROP.substring(0, length - 3) + properties.getProperty(AvailableSettings.CACHE_REGION_PREFIX, ""); String customRegionSuffix = INFINISPAN_CONFIG_RESOURCE_PROP.substring(length - 4, length); for (String propertyName : properties.stringPropertyNames()) { if (propertyName.startsWith(customRegionPrefix) && propertyName.endsWith(customRegionSuffix)) { caches.add(properties.getProperty(propertyName)); } } return caches; }

Target:
public static Set<String> findCaches(Properties properties) { Set<String> caches = new HashSet<>(); caches.add(properties.getProperty(ENTITY_CACHE_RESOURCE_PROP, DEF_ENTITY_RESOURCE)); caches.add(properties.getProperty(COLLECTION_CACHE_RESOURCE_PROP, DEF_ENTITY_RESOURCE)); caches.add(properties.getProperty(NATURAL_ID_CACHE_RESOURCE_PROP, DEF_ENTITY_RESOURCE)); if (Boolean.parseBoolean(properties.getProperty(AvailableSettings.USE_QUERY_CACHE))) { caches.add(properties.getProperty(QUERY_CACHE_RESOURCE_PROP, DEF_QUERY_RESOURCE)); caches.add(properties.getProperty(TIMESTAMPS_CACHE_RESOURCE_PROP, DEF_QUERY_RESOURCE)); } int length = INFINISPAN_CONFIG_RESOURCE_PROP.length(); String customRegionPrefix = INFINISPAN_CONFIG_RESOURCE_PROP.substring(0, length - 3) + properties.getProperty(AvailableSettings.CACHE_REGION_PREFIX, ""); String customRegionSuffix = INFINISPAN_CONFIG_RESOURCE_PROP.substring(length - 4, length); for (String propertyName : properties.stringPropertyNames()) { if (propertyName.startsWith(customRegionPrefix) && propertyName.endsWith(customRegionSuffix)) { caches.add(properties.getProperty(propertyName)); } } return caches; }
Source:
public void stop() { masterGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); port = Optional.empty(); ip = Optional.empty(); }

Target:
public void stop() { CompletableFuture<?> masterGroupShutdown = wrapShutdownFuture(masterGroup.shutdownGracefully()); CompletableFuture<?> workerGroupShutdown = wrapShutdownFuture(workerGroup.shutdownGracefully()); try { CompletableFuture.allOf(masterGroupShutdown, workerGroupShutdown).get(); } catch (Exception e) { logger.errorWhileShuttingDown(e); } port = Optional.empty(); ip = Optional.empty(); }
Source:
public void testSimulatePackfileReplacement() throws Exception { File f1 = createFile("file"); File f2 = createFile("fool"); waitNextSec(f1); waitNextSec(f1); FileTime timestamp = Files.getLastModifiedTime(f1.toPath()); FileSnapshot save = FileSnapshot.save(f1); Files.move(f2.toPath(), f1.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); Files.setLastModifiedTime(f1.toPath(), timestamp); assertTrue(save.isModified(f1)); }

Target:
public void testSimulatePackfileReplacement() throws Exception { File f1 = createFile("file"); File f2 = createFile("fool"); waitNextSec(f2); waitNextSec(f2); FileTime timestamp = Files.getLastModifiedTime(f1.toPath()); FileSnapshot save = FileSnapshot.save(f1); Files.move(f2.toPath(), f1.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); Files.setLastModifiedTime(f1.toPath(), timestamp); assertTrue(save.isModified(f1)); }
Source:
public boolean incrementToken() throws IOException { if (input.incrementToken()) { final int newlen = STEMMER.stem(termAtt.buffer(), termAtt.length()); termAtt.setLength(newlen); return true; } else { return false; } }

Target:
public boolean incrementToken() throws IOException { if (input.incrementToken()) { int newlen = STEMMER.stem(termAtt.buffer(), termAtt.length()); termAtt.setLength(newlen); return true; } return false; }
Source:
public String build(final Path directory, final String name, final ProgressHandler handler, final BuildParameter... params) throws DockerException, InterruptedException, IOException { checkNotNull(handler, "handler"); WebTarget resource = resource().path("build"); for (final BuildParameter param : params) { resource = resource.queryParam(param.queryParam, String.valueOf(param.value)); } if (name != null) { resource = resource.queryParam("t", name); } log.debug("Auth Config {}", authConfig); AuthRegistryConfig registryConfig = null; if (authConfig == null) { registryConfig = new AuthRegistryConfig("", "", "", "", "", ""); } else { registryConfig = new AuthRegistryConfig(authConfig.serverAddress(), authConfig.username(), authConfig.password(), "", authConfig.email(), authConfig.serverAddress()); } log.debug("Registry Config {}", registryConfig.toConfig()); log.debug("Registry Encoded Set {}", Base64.encodeAsString(registryConfig.toConfig())); try (final CompressedDirectory compressedDirectory = CompressedDirectory.create(directory); final InputStream fileStream = Files.newInputStream(compressedDirectory.file()); final ProgressStream build = request(POST, ProgressStream.class, resource, resource.request(APPLICATION_JSON_TYPE) .header("X-Registry-Config", Base64.encodeAsString(registryConfig.toConfig())), Entity.entity(fileStream, "application/tar"))) { String imageId = null; while (build.hasNextMessage(POST, resource.getUri())) { final ProgressMessage message = build.nextMessage(POST, resource.getUri()); final String id = message.buildImageId(); if (id != null) { imageId = id; } handler.progress(message); } return imageId; } }

Target:
public String build(final Path directory, final String name, final ProgressHandler handler, final BuildParameter... params) throws DockerException, InterruptedException, IOException { checkNotNull(handler, "handler"); WebTarget resource = resource().path("build"); for (final BuildParameter param : params) { resource = resource.queryParam(param.queryParam, String.valueOf(param.value)); } if (name != null) { resource = resource.queryParam("t", name); } log.debug("Auth Config {}", authConfig); AuthRegistryConfig authRegistryConfig = null; if (authConfig == null) { authRegistryConfig = AuthRegistryConfig.EMPTY; } else { authRegistryConfig = new AuthRegistryConfig(authConfig.serverAddress(), authConfig.username(), authConfig.password(), authConfig.email(), authConfig.serverAddress()); } try (final CompressedDirectory compressedDirectory = CompressedDirectory.create(directory); final InputStream fileStream = Files.newInputStream(compressedDirectory.file()); final ProgressStream build = request(POST, ProgressStream.class, resource, resource.request(APPLICATION_JSON_TYPE) .header("X-Registry-Config", authRegistryHeader(authRegistryConfig)), Entity.entity(fileStream, "application/tar"))) { String imageId = null; while (build.hasNextMessage(POST, resource.getUri())) { final ProgressMessage message = build.nextMessage(POST, resource.getUri()); final String id = message.buildImageId(); if (id != null) { imageId = id; } handler.progress(message); } return imageId; } }
Source:
public void update(Command command) throws IllegalArgumentException { if (command instanceof UpDownType) { throw new IllegalStateException("Cannot call update() with UpDownType"); } else if (command instanceof StopMoveType) { throw new IllegalStateException("Cannot call update() with StopMoveType"); } else if (command instanceof PercentType) { state = (PercentType) command; } else { throw new IllegalStateException("Cannot call update() with custom stop/move/up/down"); } }

Target:
public void update(Command command) throws IllegalArgumentException { if (command instanceof StopMoveType) { throw new IllegalStateException("Cannot call update() with StopMoveType"); } else if (command instanceof PercentType) { state = (PercentType) command; } else { throw new IllegalStateException("Cannot call update() with custom stop/move/up/down"); } }
Source:
void method2(java.util.HashSet<String> set) { java.util.Map<String, String> map1 = new java.util.LinkedHashMap<String, String>() {{ put("Hello", "World"); put("first", "second"); put("polygene", "lubricants"); put("alpha", "betical");} }; java.util.Map<String, String> map2 = new java.util.LinkedHashMap<String, String>() {{ put("Hello", "World"); put("first", "second"); put("polygene", "lubricants"); put("alpha", "betical"); }}; java.util.Map<String, String> map3 = new java.util.LinkedHashMap<String, String>() {{ put("Hello", "World"); put("first", "second"); put("polygene", "lubricants"); }{}; }; }

Target:
void method2(java.util.HashSet<String> set) { java.util.Map<String, String> map1 = new java.util.LinkedHashMap<String, String>() {{ put("Hello", "World"); put("first", "second"); put("polygene", "lubricants"); put("alpha", "betical");} }; java.util.Map<String, String> map2 = new java.util.LinkedHashMap<String, String>() {{ put("Hello", "World"); put("first", "second"); put("polygene", "lubricants"); put("alpha", "betical"); }}; }
Source:
public String toString() { StringBuilder builder = new StringBuilder(); builder.append(getName()).append(" {"); Iterator<Entry<String, Object>> attributes = constructSerializationAttributes().entrySet().iterator(); builder.append(attributes.next()); while (attributes.hasNext()) { builder.append(", ").append(attributes.next()); } builder.append("}"); return builder.toString(); }

Target:
public String toString() { StringBuilder builder = new StringBuilder(); builder.append(getName()).append(" {"); Map<String, Object> attributes = constructSerializationAttributes(); if (attributes != null && !attributes.isEmpty()) { Iterator<Entry<String, Object>> i = attributes.entrySet().iterator(); builder.append(i.next()); while (i.hasNext()) { builder.append(", ").append(i.next()); } } builder.append("}"); return builder.toString(); }
Source:
public void testConstructorPrice() { assertEquals(animals.getItemPrice(), 30); assertEquals(radioactive.getItemPrice(), 0); assertEquals(duckTales.getItemPrice(), 20); assertEquals(mario.getItemPrice(), 100); assertEquals(nyanCat.getItemPrice(), 90); assertEquals(shakeItOff.getItemPrice(), 70); }

Target:
public void testConstructorPrice() { assertEquals(animals.getItemPrice(), ANIMALS_PRCICE); assertEquals(radioactive.getItemPrice(), RADIOACTIVE_PRICE); assertEquals(duckTales.getItemPrice(), DUCKTALES_PRICE); assertEquals(mario.getItemPrice(), MARIO_PRICE); assertEquals(nyanCat.getItemPrice(), NYANCAT_PRICE); assertEquals(shakeItOff.getItemPrice(), SHAKEITOFF_PRICE); }
Source:
public static void main(String[] args) throws Exception { HashMap<String, ClientCommand> commands = new HashMap<String, ClientCommand>(); HelpCommand help = new HelpCommand(commands); commands.put("help", help); commands.put("launch", new LaunchCommand()); commands.put("stopNimbus", new StopNimbusCommand()); String commandName = null; String[] commandArgs = null; if (args.length < 1) { commandName = "help"; commandArgs = new String[0]; } else { commandName = args[0]; commandArgs = Arrays.copyOfRange(args, 1, args.length); } ClientCommand command = commands.get(commandName); if(command == null) { System.err.println("ERROR: " + commandName + " is not a supported command."); help.printHelpFor(null); System.exit(1); } Options opts = command.getOpts(); if(!opts.hasOption("h")) { opts.addOption("h", "help", false, "print out a help message"); } CommandLine cl = new GnuParser().parse(command.getOpts(), commandArgs); if(cl.hasOption("help")) { help.printHelpFor(Arrays.asList(commandName)); } else { @SuppressWarnings("rawtypes") List remaining_args = cl.getArgList(); String config_file = null; if (!remaining_args.isEmpty()) config_file = (String)remaining_args.get(0); Map storm_conf = Config.readStormConfig(config_file); command.process(cl, storm_conf); } }

Target:
public static void main(String[] args) throws Exception { HashMap<String, ClientCommand> commands = new HashMap<String, ClientCommand>(); HelpCommand help = new HelpCommand(commands); commands.put("help", help); commands.put("launch", new LaunchCommand()); commands.put("stopNimbus", new StopNimbusCommand()); String commandName = null; String[] commandArgs = null; if (args.length < 1) { commandName = "help"; commandArgs = new String[0]; } else { commandName = args[0]; commandArgs = Arrays.copyOfRange(args, 1, args.length); } ClientCommand command = commands.get(commandName); if(command == null) { System.err.println("ERROR: " + commandName + " is not a supported command."); help.printHelpFor(null); System.exit(1); } Options opts = command.getOpts(); if(!opts.hasOption("h")) { opts.addOption("h", "help", false, "print out a help message"); } CommandLine cl = new GnuParser().parse(command.getOpts(), commandArgs); if(cl.hasOption("help")) { help.printHelpFor(Arrays.asList(commandName)); } else { String config_file = null; if (commandName.equals("launch") || commandName.equals("stopNimbus")) { List remaining_args = cl.getArgList(); if (remaining_args!=null) config_file = (String)remaining_args.get(0); } Map storm_conf = Config.readStormConfig(config_file); command.process(cl, storm_conf); } }
Source:
public void destroy() { Integer max = 0; String key = null; for(Map.Entry<String, Integer> elem : matchingWords.entrySet()) { if (elem.getValue() > max) { max = elem.getValue(); key = elem.getKey(); } } FileWriter writer = null; try { writer = new FileWriter(new File(MATCHING_WORDS_FILE_PATH)); writer.write(key); } catch(Exception ex) { ex.printStackTrace(); } finally { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } }

Target:
public void destroy() { findAndStoreTheMostUsedWord(); }
Source:
private Response resetOption(Action action, String optionName, String optionValue, boolean force) { return doAction(ActionType.ResetGlusterVolumeOptions, new ResetGlusterVolumeOptionsParameters(guid, new GlusterVolumeOptionEntity(guid, optionName, optionValue), force), action); }

Target:
private Response resetOption(Action action, String optionName, String optionValue, boolean force) { return doAction(ActionType.ResetGlusterVolumeOptions, new ResetGlusterVolumeOptionsParameters(guid, optionName == null ? null : new GlusterVolumeOptionEntity(guid, optionName, optionValue), force), action); }
Source:
public void shouldUpdatePatientIdentifiers() throws InterruptedException { Patient testPatient = patientAdapter.getPatientByMotechId(DEFAULT_CONFIG_NAME, patient.getMotechId()); String newOldIdentificationNumber = "612"; testPatient.getIdentifiers().get(0).setIdentifier(newOldIdentificationNumber); synchronized (lock) { patientAdapter.updatePatientIdentifiers(DEFAULT_CONFIG_NAME, testPatient); lock.wait(60000); } Patient updated = patientAdapter.getPatientByUuid(DEFAULT_CONFIG_NAME, testPatient.getUuid()); assertEquals("Old Identification Number", updated.getIdentifiers().get(0).getIdentifierType().getDisplay()); assertEquals(newOldIdentificationNumber, updated.getIdentifiers().get(0).getIdentifier()); }

Target:
public void shouldUpdatePatientIdentifiers() throws InterruptedException { Patient testPatient = patientAdapter.getPatientByMotechId(DEFAULT_CONFIG_NAME, patient.getMotechId()); String newIdentifiactionNumber = "612"; testPatient.getIdentifiers().get(0).setIdentifier(newIdentifiactionNumber); synchronized (lock) { patientAdapter.updatePatientIdentifiers(DEFAULT_CONFIG_NAME, testPatient); lock.wait(60000); } Patient updated = patientAdapter.getPatientByUuid(DEFAULT_CONFIG_NAME, testPatient.getUuid()); assertEquals("Old Identification Number", updated.getIdentifiers().get(0).getIdentifierType().getName()); assertEquals(newIdentifiactionNumber, updated.getIdentifiers().get(0).getIdentifier()); }
Source:
public void destroyTicketGrantingTicket(final WebContext context, final HttpTGTProfile profile) { HttpURLConnection connection = null; try { final URL endpointURL = new URL(getAuthenticator().getCasRestUrl()); final URL deleteURL = new URL(endpointURL, endpointURL.getPath() + "/" + profile.getTicketGrantingTicketId()); connection = HttpUtils.openPostConnection(deleteURL); final int responseCode = connection.getResponseCode(); if (responseCode != HttpStatus.SC_OK) { throw new TechnicalException("TGT delete request for `" + profile + "` failed: " + HttpUtils.buildHttpErrorMessage(connection)); } } catch (final IOException e) { throw new TechnicalException(e); } finally { HttpUtils.closeConnection(connection); } }

Target:
public void destroyTicketGrantingTicket(final WebContext context, final HttpTGTProfile profile) { HttpURLConnection connection = null; try { final URL endpointURL = new URL(getAuthenticator().getCasRestUrl()); final URL deleteURL = new URL(endpointURL, endpointURL.getPath() + "/" + profile.getTicketGrantingTicketId()); connection = HttpUtils.openDeleteConnection(deleteURL); final int responseCode = connection.getResponseCode(); if (responseCode != HttpStatus.SC_OK) { throw new TechnicalException("TGT delete request for `" + profile + "` failed: " + HttpUtils.buildHttpErrorMessage(connection)); } } catch (final IOException e) { throw new TechnicalException(e); } finally { HttpUtils.closeConnection(connection); } }
Source:
private void createMissingActivityRecord(String runningWsId, long idleTimeout) throws ServerException { LOG.warn( "Found a running workspace without any activity record. This shouldn't really happen" + " but is being rectified by adding a new activity record for it.", runningWsId); try { Workspace workspace = workspaceManager.getWorkspace(runningWsId); long createdTime = Long.parseLong(workspace.getAttributes().get(Constants.CREATED_ATTRIBUTE_NAME)); WorkspaceActivity activity = new WorkspaceActivity(); activity.setWorkspaceId(runningWsId); activity.setCreated(createdTime); activity.setStatus(WorkspaceStatus.RUNNING); activity.setLastRunning(clock.millis()); if (idleTimeout > 0) { activity.setExpiration(clock.millis() + idleTimeout); } activityDao.createActivity(activity); } catch (NotFoundException e) { LOG.error( "Detected a running workspace but could not find" + " its record.", runningWsId, e); } catch (ConflictException e) { LOG.debug( "Activity record created while we were trying to rectify its absence for a running" + " workspace {}.", runningWsId); } }

Target:
private void createMissingActivityRecord(String runningWsId, long idleTimeout) throws ServerException { LOG.warn( "Found a running workspace '{}' without any activity record. This shouldn't really happen" + " but is being rectified by adding a new activity record for it.", runningWsId); try { Workspace workspace = workspaceManager.getWorkspace(runningWsId); long createdTime; try { createdTime = Long.parseLong(workspace.getAttributes().get(Constants.CREATED_ATTRIBUTE_NAME)); } catch (NumberFormatException e) { LOG.error( "Failed to read the created time of the workspace '{}' from its attributes. Using the" + " current time.", runningWsId, e); createdTime = clock.millis(); } WorkspaceActivity activity = new WorkspaceActivity(); activity.setWorkspaceId(runningWsId); activity.setCreated(createdTime); activity.setStatus(WorkspaceStatus.RUNNING); activity.setLastRunning(clock.millis()); if (idleTimeout > 0) { activity.setExpiration(clock.millis() + idleTimeout); } activityDao.createActivity(activity); } catch (NotFoundException e) { LOG.error("Detected a running workspace '{}' but could not find its record.", runningWsId, e); } catch (ConflictException e) { LOG.debug( "Activity record created while we were trying to rectify its absence for a running" + " workspace '{}'.", runningWsId); } }
Source:
private XMLReader createReader() { try { JAXBContext context; context = JAXBContext.newInstance("org.atlasapi.remotesite.pa.features.bindings"); Unmarshaller unmarshaller = context.createUnmarshaller(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); XMLReader reader = factory.newSAXParser().getXMLReader(); reader.setContentHandler(unmarshaller.getUnmarshallerHandler()); unmarshaller.setListener(featuresProcessingListener()); return reader; } catch (Exception e) { throw new RuntimeException(e); } }

Target:
private XMLReader createReader() { try { JAXBContext context = JAXBContext.newInstance("org.atlasapi.remotesite.pa.features.bindings"); Unmarshaller unmarshaller = context.createUnmarshaller(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); XMLReader reader = factory.newSAXParser().getXMLReader(); reader.setContentHandler(unmarshaller.getUnmarshallerHandler()); unmarshaller.setListener(featuresProcessingListener()); return reader; } catch (Exception e) { throw new RuntimeException(e); } }
Source:
public void flushTo(Consumer<Page> consumer) { checkState(!pages.isEmpty(), "page buffer is empty"); long[] addresses = pageSorter.sort(types, pages, sortFields, sortOrders, rowCount); int[] pageIndex = new int[addresses.length]; int[] positionIndex = new int[addresses.length]; for (int i = 0; i < addresses.length; i++) { pageIndex[i] = pageSorter.decodePageIndex(addresses[i]); positionIndex[i] = pageSorter.decodePositionIndex(addresses[i]); } for (int i = 0; i < pageIndex.length; i++) { Page page = pages.get(pageIndex[i]); int position = positionIndex[i]; appendPositionTo(page, position, pageBuilder); if (pageBuilder.isFull()) { consumer.accept(pageBuilder.build()); pageBuilder.reset(); } } if (!pageBuilder.isEmpty()) { consumer.accept(pageBuilder.build()); pageBuilder.reset(); } pages.clear(); rowCount = 0; usedMemoryBytes = 0; }

Target:
public void flushTo(Consumer<Page> consumer) { checkState(!pages.isEmpty(), "page buffer is empty"); long[] addresses = pageSorter.sort(types, pages, sortFields, sortOrders, rowCount); int[] pageIndex = new int[addresses.length]; int[] positionIndex = new int[addresses.length]; for (int i = 0; i < addresses.length; i++) { pageIndex[i] = pageSorter.decodePageIndex(addresses[i]); positionIndex[i] = pageSorter.decodePositionIndex(addresses[i]); } verify(pageBuilder.isEmpty()); for (int i = 0; i < pageIndex.length; i++) { Page page = pages.get(pageIndex[i]); int position = positionIndex[i]; appendPositionTo(page, position, pageBuilder); if (pageBuilder.isFull()) { consumer.accept(pageBuilder.build()); pageBuilder.reset(); } } if (!pageBuilder.isEmpty()) { consumer.accept(pageBuilder.build()); pageBuilder.reset(); } pages.clear(); rowCount = 0; usedMemoryBytes = 0; }
Source:
public byte[] serialize() { final ElasticData elasticData = (ElasticData) getCore(); final int payloadSize = getElasticDataLength(); if (payload != null) { payload.setParent(this); } int headerLength = 14 + (vlanIDs.size() * 4) + 20 + 8; int length = headerLength + payloadSize; if (pad && length < 60) { length = 60; } byte[] data = new byte[length]; ByteBuffer bb = ByteBuffer.wrap(data); bb.put(cachedFlowStateEthernetHeader); if (elasticData.getLength() > 0) { putElasticData(bb, elasticData); } if (pad) { Arrays.fill(data, bb.position(), data.length, (byte) 0x0); } return data; }

Target:
public byte[] serialize() { final ElasticData elasticData = getCore(); final int payloadSize = getElasticDataLength(); if (payload != null) { payload.setParent(this); } int headerLength = 14 + (vlanIDs.size() * 4) + 20 + 8; int length = headerLength + payloadSize; if (pad && length < 60) { length = 60; } byte[] data = new byte[length]; ByteBuffer bb = ByteBuffer.wrap(data); bb.put(cachedFlowStateEthernetHeader); if (elasticData.getLength() > 0) { putElasticData(bb, 0, elasticData); } if (pad) { Arrays.fill(data, bb.position(), data.length, (byte) 0x0); } return data; }
Source:
BinaryData(byte[] data) { this.data = data; }

Target:
BinaryData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); this.data = Arrays.copyOf(data, data.length); }
Source:
private void setErrorDetailsForTaskExecution(DelegateExecution execution, String errorMessage, RESTResponse response) { if (httpStatusVariable != null && response != null) { execution.setVariable(httpStatusVariable.getValue(execution).toString(), response.getHttpStatus()); } if (errorMessageVariable != null) { execution.setVariable(errorMessageVariable.getValue(execution).toString(), errorMessage); } }

Target:
private void setErrorDetailsForTaskExecution(DelegateExecution execution, String errorMessage, RESTResponse response) { if (httpStatusVariable != null && response != null) { execution.setVariable(httpStatusVariable.getValue(execution).toString(), response.getHttpStatus()); } else if (response != null) { execution.setVariable(REST_INVOKE_ERROR_CODE, response.getHttpStatus()); } if (errorMessageVariable != null) { execution.setVariable(errorMessageVariable.getValue(execution).toString(), errorMessage); } else { execution.setVariable(REST_INVOKE_ERROR_MESSAGE, errorMessage); } }
Source:
protected void finalize() throws Throwable { ((ClassDiagramPattern) comboSelection).setPatternConfiguration(false, false); super.finalize(); }

Target:
protected void finalize() throws Throwable { if (comboSelection instanceof ClassDiagramPattern) ((ClassDiagramPattern) comboSelection).setPatternConfiguration(false, false); super.finalize(); }
Source:
public View getChildView(final int group, final int child, final boolean isLastChild, View convertView, final ViewGroup viewGroup) { final WeaponUnlock unlock = getChild(group, child).getUnlock(); final int completion = unlock.getCriteria().getCompletion(); while (convertView == null) { convertView = layoutInflater.inflate(R.layout.list_item_unlocks, viewGroup, false); } setText(convertView, R.id.title, WeaponStringSlugMap.get(unlock.getSlug())); setText(convertView, R.id.subtitle, resolveCriteriaLabel(unlock.getCriteria())); setProgress(convertView, R.id.progress, completion, 100); if (unlock.getCriteria().isCompleted()) { setText(convertView, R.id.completion, R.string.done); convertView.setAlpha(0.5f); } else { setText(convertView, R.id.completion, completion + "%"); convertView.setAlpha(1.0f); } return convertView; }

Target:
public View getChildView(final int group, final int child, final boolean isLastChild, View convertView, final ViewGroup viewGroup) { final WeaponUnlock unlock = getChild(group, child).getUnlock(); final int completion = unlock.getCriteria().getCompletion(); while (convertView == null) { convertView = layoutInflater.inflate(R.layout.list_item_unlocks, viewGroup, false); } setText(convertView, R.id.title, WeaponStringSlugMap.get(unlock.getSlug())); setText(convertView, R.id.subtitle, resolveCriteriaLabel(unlock.getCriteria())); setProgress(convertView, R.id.progress, completion, 100); convertView.setAlpha(unlock.getCriteria().isCompleted() ? OPACITY_FADED : OPACITY_NORMAL); return convertView; }
Source:
public void importFileStorageAddDomain(ArrayList<StorageDomain> domains) { StorageDomain sdToAdd = Linq.firstOrDefault(domains); StorageDomainStatic sdsToAdd = sdToAdd.getStorageStaticData(); StorageDomainManagementParameter params = new StorageDomainManagementParameter(sdsToAdd); params.setVdsId(hostId); Frontend.getInstance().runAction(VdcActionType.AddExistingFileStorageDomain, params, new IFrontendActionAsyncCallback() { @Override public void executed(FrontendActionAsyncResult result) { Object[] array = (Object[]) result.getState(); StorageListModel storageListModel = (StorageListModel) array[0]; StorageDomain sdToAdd1 = (StorageDomain) array[1]; VdcReturnValueBase returnVal = result.getReturnValue(); boolean success = returnVal != null && returnVal.getSucceeded(); if (success) { StorageModel model = (StorageModel) storageListModel.getWindow(); StoragePool dataCenter = model.getDataCenter().getSelectedItem(); if (!dataCenter.getId().equals(StorageModel.UnassignedDataCenterId)) { storageListModel.attachStorageToDataCenter(sdToAdd1.getId(), dataCenter.getId(), model.getActivateDomain().getEntity()); onFinish(storageListModel.context, true, storageListModel.storageModel, null); } else { postImportFileStorage(storageListModel.context, true, storageListModel.storageModel, null); } } else { postImportFileStorage(storageListModel.context, false, storageListModel.storageModel, ""); storageListModel.cleanConnection(fileConnection, hostId); } } }, new Object[] {this, sdToAdd}); }

Target:
public void importFileStorageAddDomain(ArrayList<StorageDomain> domains) { StorageDomain sdToAdd = Linq.firstOrDefault(domains); StorageDomainStatic sdsToAdd = sdToAdd.getStorageStaticData(); StorageDomainManagementParameter params = new StorageDomainManagementParameter(sdsToAdd); params.setVdsId(hostId); Frontend.getInstance().runAction(VdcActionType.AddExistingFileStorageDomain, params, new IFrontendActionAsyncCallback() { @Override public void executed(FrontendActionAsyncResult result) { Object[] array = (Object[]) result.getState(); StorageListModel storageListModel = (StorageListModel) array[0]; StorageDomain sdToAdd1 = (StorageDomain) array[1]; VdcReturnValueBase returnVal = result.getReturnValue(); boolean success = returnVal != null && returnVal.getSucceeded(); if (success) { StorageModel model = (StorageModel) storageListModel.getWindow(); StoragePool dataCenter = model.getDataCenter().getSelectedItem(); if (!dataCenter.getId().equals(StorageModel.UnassignedDataCenterId)) { storageListModel.attachStorageToDataCenter(sdToAdd1.getId(), dataCenter.getId(), model.getActivateDomain().getEntity()); onFinish(storageListModel.context, true, storageListModel.storageModel, null); } else { postImportFileStorage(storageListModel.context, true, storageListModel.storageModel, null); } } else { postImportFileStorage(storageListModel.context, false, storageListModel.storageModel, ""); cleanConnection(fileConnection, hostId); } } }, new Object[] {this, sdToAdd}); }