auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>void addOccurances(ConcretizationInfo cfg, KLabel cell, KVariable var, List<K> items) { this.var = var; if (parentCell == null) { parentCell = cell; } else if (!parentCell.equals(cell)) { <START> throw new IllegalArgumentException("Cell variable used under two cells, " <END> + parentCell + " and " + cell); } if (remainingCells == null) { remainingCells = new HashSet<>(cfg.getChildren(cell)); } for (K item : items) { if (item instanceof KApply) { KApply kApply = (KApply) item; Sort s = cfg.getCellSort(kApply.klabel()); if (cfg.getMultiplicity(s) != ConfigurationInfo.Multiplicity.STAR) { remainingCells.remove(s); } } } }</code><technical_language>another source of IllegalArgumentException</technical_language>

Target:
void addOccurances(ConcretizationInfo cfg, KLabel cell, KVariable var, List<K> items) { this.var = var; if (parentCell == null) { parentCell = cell; } else if (!parentCell.equals(cell)) { throw KExceptionManager.criticalError("Cell variable used under two cells, " + parentCell + " and " + cell); } if (remainingCells == null) { remainingCells = new HashSet<>(cfg.getChildren(cell)); } for (K item : items) { if (item instanceof KApply) { KApply kApply = (KApply) item; Sort s = cfg.getCellSort(kApply.klabel()); if (cfg.getMultiplicity(s) != ConfigurationInfo.Multiplicity.STAR) { remainingCells.remove(s); } } } }
Source:
<code>public ConfigFileParser(File configFile, KTestOptions cmdArgs) throws IOException, SAXException, ParserConfigurationException, TransformerException { this.cmdArgs = cmdArgs; Source schemaFile = new StreamSource(new File(getSchema())); Source xmlFile = new StreamSource(configFile); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(schemaFile); Validator validator = schema.newValidator(); try { validator.validate(xmlFile); <START> } catch (SAXException e) { <END> String formatDoc = "<LINK_0>"; String pre = "Invalid config file formatting. "; String post = " (see " + formatDoc + " for config file formatting)"; throw new SAXException(pre + e.getMessage() + post); } DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer nullTransformer = transformerFactory.newTransformer(); DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder(); doc = docBuilder.newDocument(); DOMResult domResult = new DOMResult(doc); XMLReader xmlReader = XMLReaderFactory.createXMLReader(); ConfigPreProcessor locationAnnotator = new ConfigPreProcessor(xmlReader, doc); String systemId = configFile.getAbsolutePath(); InputSource inputSource = new InputSource(systemId); SAXSource saxSource = new SAXSource(locationAnnotator, inputSource); nullTransformer.transform(saxSource, domResult); }</code><technical_language>again, is this a SAX exception recaught it? Also, this is a good error Message. link fragile time, forget this is here. "refer manual" instead</technical_language>

Target:
public ConfigFileParser(File configFile, KTestOptions cmdArgs) throws IOException, SAXException, ParserConfigurationException, TransformerException { this.cmdArgs = cmdArgs; Source schemaFile = new StreamSource(new File(getSchema())); Source xmlFile = new StreamSource(configFile); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(schemaFile); Validator validator = schema.newValidator(); try { validator.validate(xmlFile); } catch (SAXException e) { GlobalSettings.kem.registerCriticalError( "Invalid config file formatting. Refer to the K manual for details. " + e.getMessage()); } DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer nullTransformer = transformerFactory.newTransformer(); DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder(); doc = docBuilder.newDocument(); DOMResult domResult = new DOMResult(doc); XMLReader xmlReader = XMLReaderFactory.createXMLReader(); ConfigPreProcessor locationAnnotator = new ConfigPreProcessor(xmlReader, doc); String systemId = configFile.getAbsolutePath(); InputSource inputSource = new InputSource(systemId); SAXSource saxSource = new SAXSource(locationAnnotator, inputSource); nullTransformer.transform(saxSource, domResult); }
Source:
<code>public void testShouldAnonymizeCharactersAfterSkippingCharactersUsingDigitals(){ String from = "3551085"; String digitals = "1234567890"; partialCharacterAnonymizer.NUMBER_OF_SKIPPED_CHARACTERS = 3; Map<String, String> m = new HashMap<>(); m.put(PartialCharacterAnonymizer.PARAMETER, digitals); Synonym synonym = partialCharacterAnonymizer.anonymize(from, 5, false, m); String to = (String) synonym.getTo(); System.out.println(from); System.out.println(to); <START> } <END></code><technical_language>I noted separate tests for cases, I overlooked that. I understand is good test separate concerns in separate tests, simpler combine a here</technical_language>

Target:
public void testShouldAnonymizeCharactersAfterSkippingCharactersUsingDigitals(){ String from = "3551085"; String CHARS = "1234567890"; partialCharacterAnonymizer.NUMBER_OF_SKIPPED_CHARACTERS = 3; Map<String, String> m = new HashMap<>(); m.put(PartialCharacterAnonymizer.PARAMETER, CHARS); Synonym synonym = partialCharacterAnonymizer.anonymize(from, 5, false, m); String to = (String) synonym.getTo(); Assert.assertNotSame(to.substring(3) +" is not different than " + from.substring(3), to.substring(3) ,from.substring(3)); }
Source:
<code>public ValidationResult bondNotUpdatedAndRemovedSimultaneously() { List<CreateOrUpdateBond> <START> duplicateBonds = <END> params.getCreateOrUpdateBonds() .stream() .filter(bond -> params.getRemovedBonds().contains(bond.getId())).collect(Collectors.toList()); if (CollectionUtils.isNotEmpty(duplicateBonds)) { EngineMessage engineMessage = EngineMessage.BOND_UPDATED_AND_REMOVED_SIMULTANEOUSLY; return new ValidationResult(engineMessage, ReplacementUtils.getListVariableAssignmentString(engineMessage, duplicateBonds.stream().map(CreateOrUpdateBond::getName).collect(Collectors.toList()))); } return ValidationResult.VALID; }</code><technical_language>1. please move .map(CreateOrUpdateBond::getName) this stream processing. faster more readable. (if filter returns empty collection, .map costs nothing). 2. This name is informative. 1), have: "namesOfBondsBeingRemovedAndPersisted". If better/shorter name, one</technical_language>

Target:
public ValidationResult bondNotUpdatedAndRemovedSimultaneously() { List<String> bondsUpdatedAndRemovedSimultaneously = params.getCreateOrUpdateBonds() .stream() .filter(bond -> params.getRemovedBonds().contains(bond.getId())) .map(CreateOrUpdateBond::getName) .collect(Collectors.toList()); if (CollectionUtils.isNotEmpty(bondsUpdatedAndRemovedSimultaneously)) { EngineMessage engineMessage = EngineMessage.BONDS_UPDATED_AND_REMOVED_SIMULTANEOUSLY; return new ValidationResult(engineMessage, ReplacementUtils.getListVariableAssignmentString(engineMessage, bondsUpdatedAndRemovedSimultaneously)); } return ValidationResult.VALID; }
Source:
<code><START> public DescribeInternetGatewaysResponseHandler(InternetGatewayHandler gatewayHandler) { <END> this.gatewayHandler = gatewayHandler; }</code><technical_language>Reduce injection constructor visibility removing public modifier</technical_language>

Target:
DescribeInternetGatewaysResponseHandler(InternetGatewayHandler gatewayHandler) { this.gatewayHandler = gatewayHandler; }
Source:
<code>public List<Footer> getFooters(JobContext jobContext) throws IOException { if (footers == null) { List<FileStatus> statuses = listStatus(jobContext); fileStatuses.clear(); for (FileStatus status : statuses) { fileStatuses.put(status.getPath(), status); <START> } <END> footers = getFooters(ContextUtil.getConfiguration(jobContext), statuses); } return footers; }</code><technical_language>great find a reuse statuses side effects</technical_language>

Target:
public List<Footer> getFooters(JobContext jobContext) throws IOException { List<FootersCacheValue> cacheFooters= getCachedFooters(jobContext); List<Footer> footers = new ArrayList<Footer>(cacheFooters.size()); for (FootersCacheValue cachedFooter: cacheFooters) { footers.add(cachedFooter.footer); } return footers; }
Source:
<code>ParameterizedTypeName(ClassName rawType, List<TypeName> typeArguments, List<AnnotationSpec> annotations) { this( rawType, <START> rawType.enclosingClassName() != null ? rawType.enclosingClassName() : rawType, <END> rawType.enclosingClassName() != null ? rawType.simpleName() : null, typeArguments, annotations); }</code><technical_language>This field definition strange. interchangeable</technical_language>

Target:
ParameterizedTypeName(ClassName rawType, List<TypeName> typeArguments, List<AnnotationSpec> annotations) { this(rawType, null, typeArguments, annotations); }
Source:
<code>public void quit() { if (browserComponent != null) { browserComponent.onAppQuit(); } if (!TestController.isTestMode() || TestController.isTestGlobalConfig()) { panels.saveSession(); prefs.saveGlobalConfig(); } if (!TestController.isTestMode() || TestController.isCloseOnQuit()) { Platform.exit(); System.exit(0); } provider.reset(); <START> provider.stop(); <END> }</code><technical_language>if this part execute? hotkey process persist? Reason is if System.exit is called, this is unreachable. put top of method. put this in method, clear does</technical_language>

Target:
public void quit() { globalHotkey.quit(); if (browserComponent != null) { browserComponent.onAppQuit(); } if (!TestController.isTestMode() || TestController.isTestGlobalConfig()) { panels.saveSession(); prefs.saveGlobalConfig(); } if (!TestController.isTestMode() || TestController.isCloseOnQuit()) { Platform.exit(); System.exit(0); } }
Source:
<code>public Response serve(IHTTPSession session) { Map<String, List<String>> parms = session.getParameters(); if (filePath == null) { return newFixedLengthResponse(Response.Status.FORBIDDEN, "", ""); } FileInputStream fis = null; try { fis = new FileInputStream(filePath); } catch (FileNotFoundException e) { <START> e.printStackTrace(); <END> return newFixedLengthResponse(Response.Status.FORBIDDEN, "", ""); } String mimeType = this.mimeType; return newChunkedResponse(Response.Status.OK, mimeType, fis); }</code><technical_language>Please LogUtils.LOGW</technical_language>

Target:
public Response serve(IHTTPSession session) { Map<String, List<String>> params = session.getParameters(); if (localFileLocationList == null) { return newFixedLengthResponse(Response.Status.FORBIDDEN, "", ""); } if (!params.containsKey("number")) { return null; } int file_number = Integer.parseInt(params.get("number").get(0)); FileInputStream fis = null; LocalFileLocation localFileLocation = localFileLocationList.get(file_number); try { fis = new FileInputStream(localFileLocation.fullPath); } catch (FileNotFoundException e) { LogUtils.LOGW(LogUtils.makeLogTag(HttpApp.class), e.toString()); return newFixedLengthResponse(Response.Status.FORBIDDEN, "", ""); } String mimeType = localFileLocation.getMimeType(); return newChunkedResponse(Response.Status.OK, mimeType, fis); }
Source:
<code>public void onManagementBecomingMaster() { if (setChangeListener != null) { log.warn("{} becoming master twice", this); return; } setChangeListener = new MyEntitySetChangeListener(); ((ManagementContextInternal) getManagementContext()).addEntitySetListener(setChangeListener); Task<Object> rescan = Tasks.builder().name("rescan entities").body( new Runnable() { @Override public void run() { try { rescanEntities(); } catch (Exception e) { <START> log.warn("Error rescanning entities when rebinding; may be a group set against an unknown entity: "+e); <END> log.debug("Trace for rescan entities error", e); Exceptions.propagateIfFatal(e); } } }).build(); getExecutionContext().submit(rescan); }</code><technical_language>This is called rebind - called entity is created+managed well. a message "Error rescanning for members of "+DynamicGroupImpl.this+"; a ..."</technical_language>

Target:
public void onManagementBecomingMaster() { if (setChangeListener != null) { log.warn("{} becoming master twice", this); return; } setChangeListener = new MyEntitySetChangeListener(); ((ManagementContextInternal) getManagementContext()).addEntitySetListener(setChangeListener); Task<Object> rescan = Tasks.builder().name("rescan entities").body( new Runnable() { @Override public void run() { try { rescanEntities(); } catch (Exception e) { log.warn("Error rescanning entities on management of "+DynamicGroupImpl.this+"; may be a group set against an unknown entity: "+e); log.debug("Trace for rescan entities error", e); Exceptions.propagateIfFatal(e); } } }).build(); getExecutionContext().submit(rescan); }
Source:
<code>public byte[] getTagsArray() { <START> return new byte[0]; <END> }</code><technical_language>return HConstants.EMPTY_BYTE_ARRAY;</technical_language>

Target:
public byte[] getTagsArray() { return HConstants.EMPTY_BYTE_ARRAY; }
Source:
<code><START> public ArrayList<Attachment> createAttachmentList() { <END> ArrayList<Attachment> result = new ArrayList<>(); for (Attachment attachment : attachments.values()) { int resizeCircumference; int resizeQuality; if (account.isResizeImageEnabled() && !attachment.resizeImageOverrideDefault && ImageResizer.isImage(context, attachment.uri)) { resizeCircumference = account.getResizeImageCircumference(); resizeQuality = account.getResizeImageQuality(); } else if (attachment.resizeImageOverrideDefault && ImageResizer.isImage(context, attachment.uri)) { resizeCircumference = attachment.resizeImageCircumference; resizeQuality = attachment.resizeImageQuality; } else { resizeCircumference = 0; resizeQuality = 0; } if (resizeCircumference != 0) { try { String newFilename = imageResizer.getResizedImageFile(context, attachment.uri, resizeCircumference, resizeQuality); long size = (new File(newFilename)).length(); Attachment newAttachment = attachment.createResizedCopy(newFilename, size); result.add(newAttachment); return result; } catch (IOException ioe) { Timber.i("image resizing failed for " + attachment.uri + " circumference=" + resizeCircumference + ", quality=" + resizeQuality); } } result.add(attachment); } return result; }</code><technical_language>This method needs a more descriptive name</technical_language>

Target:
public ArrayList<Attachment> createAttachmentList() { return new ArrayList<>(attachments.values()); }
Source:
<code>public void start() { try { <START> cache.getListenable().addListener(this); <END> cache.start(); } catch (Exception ex) { throw Throwables.propagate(ex); } }</code><technical_language>I nicer register anonymous class instead of this expose PathChildrenCacheListener interface. of objects getter above, able register Curator</technical_language>

Target:
public void start() { try { cache.getListenable().addListener( (client, event) -> handleChildEvent(client, event) ); cache.start(); } catch (Exception ex) { throw Throwables.propagate(ex); } }
Source:
<code>private void finish() { if (running) { AncientAltarOutputEvent ancientAltarOutputEvent = new AncientAltarOutputEvent(output, altar); <START> Bukkit.getPluginManager().callEvent(ancientAltarOutputEvent); <END> if (!ancientAltarOutputEvent.isCancelled()) { dropLocation.getWorld().playSound(dropLocation, Sound.ENTITY_ZOMBIE_VILLAGER_CURE, 1F, 1F); dropLocation.getWorld().playEffect(dropLocation, Effect.STEP_SOUND, Material.EMERALD_BLOCK); dropLocation.getWorld().dropItemNaturally(dropLocation.add(0, -0.5, 0), output); } pedestals.forEach(b -> listener.getAltarsInUse().remove(b.getLocation())); listener.getAltarsInUse().remove(altar.getLocation()); listener.getAltars().remove(altar); } else { dropLocation.getWorld().playSound(dropLocation, Sound.ENTITY_ZOMBIE_BREAK_WOODEN_DOOR, 1F, 1F); } }</code><technical_language>Hmm. a pre post event something. I this running anything. Hmm</technical_language>

Target:
private void finish() { if (running) { AncientAltarCraftEvent event = new AncientAltarCraftEvent(output, altar, player); Bukkit.getPluginManager().callEvent(event); if (!event.isCancelled()) { dropLocation.getWorld().playSound(dropLocation, Sound.ENTITY_ZOMBIE_VILLAGER_CURE, 1F, 1F); dropLocation.getWorld().playEffect(dropLocation, Effect.STEP_SOUND, Material.EMERALD_BLOCK); dropLocation.getWorld().dropItemNaturally(dropLocation.add(0, -0.5, 0), event.getItem()); } pedestals.forEach(b -> listener.getAltarsInUse().remove(b.getLocation())); listener.getAltarsInUse().remove(altar.getLocation()); listener.getAltars().remove(altar); } else { dropLocation.getWorld().playSound(dropLocation, Sound.ENTITY_ZOMBIE_BREAK_WOODEN_DOOR, 1F, 1F); } }
Source:
<code>private static void validateInode(INodesInPath srcIIP) throws IOException { String errorPrefix = "DIR* FSDirectory.swapBlockList: "; String error = "Swap Block List input "; <START> final INode srcInode = srcIIP.getLastINode(); if (srcInode == null) { error += srcIIP.getPath() + " is not found."; NameNode.stateChangeLog.warn(errorPrefix + error); throw new FileNotFoundException(error); } <END> if (!srcInode.isFile()) { error += srcIIP.getPath() + " is not a file."; NameNode.stateChangeLog.warn(errorPrefix + error); throw new IOException(error); } INodeFile iNodeFile = (INodeFile) srcIIP.getLastINode(); if (iNodeFile.isUnderConstruction()) { error += srcIIP.getPath() + " is under construction."; NameNode.stateChangeLog.warn(errorPrefix + error); throw new IOException(error); } if (srcIIP.getLatestSnapshotId() != Snapshot.CURRENT_STATE_ID) { error += srcIIP.getPath() + " is in a snapshot directory."; NameNode.stateChangeLog.warn(errorPrefix + error); throw new IOException(error); } }</code><technical_language>FsDirectory.resolveLastINode()</technical_language>

Target:
private static void validateInode(INodesInPath srcIIP) throws IOException { String errorPrefix = "DIR* FSDirectory.swapBlockList: "; String error = "Swap Block List input "; INode srcInode = FSDirectory.resolveLastINode(srcIIP); if (!srcInode.isFile()) { error += srcIIP.getPath() + " is not a file."; NameNode.stateChangeLog.warn(errorPrefix + error); throw new IOException(error); } INodeFile iNodeFile = (INodeFile) srcIIP.getLastINode(); if (iNodeFile.isUnderConstruction()) { error += srcIIP.getPath() + " is under construction."; NameNode.stateChangeLog.warn(errorPrefix + error); throw new IOException(error); } if (srcIIP.getLatestSnapshotId() != Snapshot.CURRENT_STATE_ID) { error += srcIIP.getPath() + " is in a snapshot directory."; NameNode.stateChangeLog.warn(errorPrefix + error); throw new IOException(error); } }
Source:
<code>private void searchAndRemoveGraphicalSynapseCongif(IProject project) { try { if (project.hasNature("org.wso2.developerstudio.eclipse.esb.project.nature")) { deleteGraphicalSynapseConfigDir(project); <START> } else if (project.hasNature("org.wso2.developerstudio.eclipse.general.project.nature")){ <END> deleteGraphicalSynapseConfigFiles(project); } } catch (CoreException e) { log.error("Error while deleting graphical-synapse-config directory in " + project); } }</code><technical_language>defined constants for project natures org.wso2.developerstudio.eclipse.platform.core.utils.Constants class</technical_language>

Target:
private void searchAndRemoveGraphicalSynapseCongif(IProject project) { try { if (project.hasNature(Constants.ESB_PROJECT_NATURE)) { deleteGraphicalSynapseConfigDir(project); } else if (project.hasNature(Constants.GENERAL_PROJECT_NATURE)) { deleteGraphicalSynapseConfigFiles(project); } } catch (CoreException e) { log.error("Error while deleting graphical-synapse-config directory in " + project); } }
Source:
<code>public void persistQueueOnCrash() { j.addStepWithDirtyShutdown(new Statement() { @Override public void evaluate() throws Throwable { Queue.Saver.DELAY_SECONDS = 0; scheduleSomeBuild(); assertBuildIsScheduled(); assertTrue("queue.xml does not exist", j.j.jenkins.getQueue().getXMLQueueFile().exists()); } }); j.addStep(new Statement() { @Override public void evaluate() { <START> assertBuildIsScheduled(); <END> } }); }</code><technical_language>this potentially hit race conditions flake, a Timer thread is triggering save here? need check for thread completed -- track next/last scheduled save is/was</technical_language>

Target:
public void persistQueueOnCrash() { j.addStepWithDirtyShutdown(new Statement() { @Override public void evaluate() throws Throwable { Queue.Saver.DELAY_SECONDS = 0; scheduleSomeBuild(); assertBuildIsScheduled(); ExtensionList.lookup(Queue.Saver.class).get(0).getNextSave().get(3, TimeUnit.SECONDS); assertTrue("queue.xml does not exist", j.j.jenkins.getQueue().getXMLQueueFile().exists()); } }); j.addStep(new Statement() { @Override public void evaluate() { assertBuildIsScheduled(); } }); }
Source:
<code>public void writeHeadersWhenWhiteList() { <START> WhiteListedAllowFromStrategy whitelist = new WhiteListedAllowFromStrategy(Collections.singletonList("example.com")); <END> XFrameOptionsHeaderWriter writer = new XFrameOptionsHeaderWriter(whitelist); writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderValue(XFrameOptionsHeaderWriter.XFRAME_OPTIONS_HEADER)).isEqualTo("DENY"); }</code><technical_language>Is this change necessary for this PR? I Collections.singletonList in test, recommend bringing other tests conformance in a PR. (For example, change tests refer member variables this., purpose of this PR)</technical_language>

Target:
public void writeHeadersWhenWhiteList() { WhiteListedAllowFromStrategy whitelist = new WhiteListedAllowFromStrategy(Arrays.asList("example.com")); XFrameOptionsHeaderWriter writer = new XFrameOptionsHeaderWriter(whitelist); writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderValue(XFrameOptionsHeaderWriter.XFRAME_OPTIONS_HEADER)).isEqualTo("DENY"); }
Source:
<code>private static void resetBytesMessageProperties( Message message, List<Object> out ) { <START> if (out.isEmpty()) { <END> return; } try { BytesMessage bytesMessage = (BytesMessage) message; byte[] body = new byte[(int) bytesMessage.getBodyLength()]; bytesMessage.reset(); bytesMessage.readBytes(body); message.clearBody(); resetProperties(message, out); bytesMessage.writeBytes(body); bytesMessage.reset(); } catch (JMSException e) { propagateIfFatal(e); log(e, "unable to reset BytesMessage body {0}", message, e); } }</code><technical_language>this condition effect previous if (disjoint) return;. remove need properties reset</technical_language>

Target:
private static void resetBytesMessageProperties( Message message, List<Object> out ) { try { BytesMessage bytesMessage = (BytesMessage) message; byte[] body = new byte[(int) bytesMessage.getBodyLength()]; bytesMessage.reset(); bytesMessage.readBytes(body); message.clearBody(); resetProperties(message, out); bytesMessage.writeBytes(body); } catch (JMSException e) { propagateIfFatal(e); log(e, "unable to reset BytesMessage body {0}", message, e); } }
Source:
<code>public E[] get() { if (result == null) { synchronized (this) { if (result == null) { if (acc == null){ result = loadServices(service, classLoader); <START> } else { <END> result = AccessController.doPrivileged((PrivilegedAction<E[]>) () -> loadServices(service, classLoader), acc); } } } } return result.clone(); }</code><technical_language>security manager check ported here</technical_language>

Target:
public E[] get() { if (result == null) { synchronized (this) { if (result == null) { if (WildFlySecurityManager.isChecking()) { result = AccessController.doPrivileged((PrivilegedAction<E[]>) () -> loadServices(service, classLoader), acc); } else { result = loadServices(service, classLoader); } } } } return result.clone(); }
Source:
<code>public void rollback() { for (Path file : tempFiles) { try { if (fileSystem.exists(file) && !fileSystem.delete(file, false)) { throw new IOException("Delete failed"); } } catch (IOException e) { log.warn(e, "Failed to delete temporary file: " + file); } <START> } <END> outputWriter.rollback(); }</code><technical_language>If this in reverse order, prevent races... blindly delete check if exists</technical_language>

Target:
public void rollback() { for (Path file : tempFiles) { try { fileSystem.delete(file, false); if (fileSystem.exists(file)) { throw new IOException("Delete failed"); } } catch (IOException e) { log.warn(e, "Failed to delete temporary file: " + file); } } outputWriter.rollback(); }
Source:
<code>public void testVFE3() { try { T_iget_13 t = new T_iget_13(); <START> t.run(); <END> fail("expected a NoSuchFieldError exception"); } catch (NoSuchFieldError e) { } }</code><technical_language>a big deal, style in other tests e.g. 'new T_iget_13().run();' a good idea similar possible. of minor</technical_language>

Target:
public void testVFE3() { try { new T_iget_13().run(); fail("expected a NoSuchFieldError exception"); } catch (NoSuchFieldError e) { } }
Source:
<code>public void open(IndexWriterParams params) throws IOException { host = params.get(KafkaConstants.HOST); port = params.getInt(KafkaConstants.PORT, 9092); keySerializer = params.get(KafkaConstants.KEY_SERIALIZER, "org.apache.kafka.common.serialization.ByteArraySerializer"); <START> valueSerializer = params.get(KafkaConstants.VALUE_SERIALIZER, <END> "org.apache.kafka.connect.json.JsonSerializer"); topic = params.get(KafkaConstants.TOPIC); if (StringUtils.isBlank(host)) { String message = "Missing host. It should be set in index-writers.xml"; message += "\n" + describe(); LOG.error(message); throw new RuntimeException(message); } Properties configProperties = new Properties(); configProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, host + ":" + port); configProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, keySerializer); configProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, valueSerializer); producer = new KafkaProducer<String, JsonNode>(configProperties); }</code><technical_language>parameters (keySerializer valueSerializer) index-writers.xml file other parameters. Otherwise, coder read code for finding options configurable parameters</technical_language>

Target:
public void open(IndexWriterParams params) throws IOException { host = params.get(KafkaConstants.HOST); port = params.getInt(KafkaConstants.PORT, 9092); keySerializer = params.get(KafkaConstants.KEY_SERIALIZER, "org.apache.kafka.common.serialization.ByteArraySerializer"); valueSerializer = params.get(KafkaConstants.VALUE_SERIALIZER, "org.apache.kafka.connect.json.JsonSerializer"); topic = params.get(KafkaConstants.TOPIC); maxDocCount = params.getInt(KafkaConstants.MAX_DOC_COUNT, 100); inputDocs = new ArrayList<ProducerRecord<String, JsonNode>>(maxDocCount); if (StringUtils.isBlank(host)) { String message = "Missing host. It should be set in index-writers.xml"; message += "\n" + describe(); LOG.error(message); throw new RuntimeException(message); } Properties configProperties = new Properties(); configProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, host + ":" + port); configProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, keySerializer); configProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, valueSerializer); Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); producer = new KafkaProducer<String, JsonNode>(configProperties); }
Source:
<code>public static void addEventLogger(Map<String, Object> conf, StormTopology topology) { Integer numExecutors = ObjectReader.getInt(conf.get(Config.TOPOLOGY_EVENTLOGGER_EXECUTORS), ObjectReader.getInt(conf.get(Config.TOPOLOGY_WORKERS))); <START> if(numExecutors==null || numExecutors==0) <END> return; HashMap<String, Object> componentConf = new HashMap<>(); componentConf.put(Config.TOPOLOGY_TASKS, numExecutors); componentConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, ObjectReader.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS))); Bolt eventLoggerBolt = Thrift.prepareSerializedBoltDetails( eventLoggerInputs(topology), new EventLoggerBolt(), null, numExecutors, componentConf); for (Object component : allComponents(topology).values()) { ComponentCommon common = getComponentCommon(component); common.put_to_streams(EVENTLOGGER_STREAM_ID, Thrift.outputFields(eventLoggerBoltFields())); } topology.put_to_bolts(EVENTLOGGER_COMPONENT_ID, eventLoggerBolt); }</code><technical_language>fix style a space if '{' '}'</technical_language>

Target:
public static void addEventLogger(Map<String, Object> conf, StormTopology topology) { Integer numExecutors = ObjectReader.getInt(conf.get(Config.TOPOLOGY_EVENTLOGGER_EXECUTORS), ObjectReader.getInt(conf.get(Config.TOPOLOGY_WORKERS))); if (numExecutors==null || numExecutors==0) { return; } HashMap<String, Object> componentConf = new HashMap<>(); componentConf.put(Config.TOPOLOGY_TASKS, numExecutors); componentConf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, ObjectReader.getInt(conf.get(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS))); Bolt eventLoggerBolt = Thrift.prepareSerializedBoltDetails( eventLoggerInputs(topology), new EventLoggerBolt(), null, numExecutors, componentConf); for (Object component : allComponents(topology).values()) { ComponentCommon common = getComponentCommon(component); common.put_to_streams(EVENTLOGGER_STREAM_ID, Thrift.outputFields(eventLoggerBoltFields())); } topology.put_to_bolts(EVENTLOGGER_COMPONENT_ID, eventLoggerBolt); }
Source:
<code>public ServiceBuilder<?> build(ServiceTarget target) { String containerName = this.configuration.getContainerName(); ServiceName deploymentUnitServiceName = this.context.getDeploymentUnitServiceName(); ServiceBuilder<?> builder = target.addService(this.getServiceName()); Consumer<BeanManagerFactory<I, T, TransactionBatch>> factory = builder.provides(this.getServiceName()); this.cache = builder.requires(InfinispanCacheRequirement.CACHE.getServiceName(this.support, containerName, InfinispanBeanManagerFactoryServiceConfiguratorFactory.getCacheName(deploymentUnitServiceName))); this.affinityFactory = builder.requires(InfinispanRequirement.KEY_AFFINITY_FACTORY.getServiceName(this.support, containerName)); this.repository = builder.requires(deploymentUnitServiceName.append("marshalling")); <START> this.scheduler = builder.requires(deploymentUnitServiceName.append(this.name, "expiration")); <END> this.dispatcherFactory = builder.requires(ClusteringRequirement.COMMAND_DISPATCHER_FACTORY.getServiceName(this.support, containerName)); this.registry = builder.requires(ClusteringCacheRequirement.REGISTRY.getServiceName(this.support, containerName, BeanManagerFactoryServiceConfiguratorConfiguration.CLIENT_MAPPINGS_CACHE_NAME)); this.group = builder.requires(ClusteringCacheRequirement.GROUP.getServiceName(this.support, containerName, BeanManagerFactoryServiceConfiguratorConfiguration.CLIENT_MAPPINGS_CACHE_NAME)); Service service = Service.newInstance(factory, new InfinispanBeanManagerFactory<>(this)); return builder.setInstance(service).setInitialMode(ServiceController.Mode.ON_DEMAND); }</code><technical_language>FYI (and I need change this patch of this) intent of separating service instance out of addService call dependency Supplier dependent Consumer instances set final fields service is constructed. start method construct value(s) based dependency values, "outject" consumers</technical_language>

Target:
public ServiceBuilder<?> build(ServiceTarget target) { ServiceBuilder<?> builder = target.addService(this.getServiceName()); new CompositeDependency(this.cache, this.affinityFactory, this.repository, this.scheduler, this.group, this.registry, this.dispatcherFactory).register(builder); Consumer<BeanManagerFactory<I, T, TransactionBatch>> factory = builder.provides(this.getServiceName()); Service service = Service.newInstance(factory, new InfinispanBeanManagerFactory<>(this)); return builder.setInstance(service).setInitialMode(ServiceController.Mode.ON_DEMAND); }
Source:
<code>public static TissuePieceType to(@Nonnull TissuePieceTypeDto from) { TissuePieceType to = new TissuePieceType(); if (from.getId() != null) to.setId(from.getId()); setString(to::setName, from.getName()); setString(to::setAbbreviation, from.getAbbreviation()); <START> setBoolean(to::setArchived, from.isArchived(), true); <END> return to; }</code><technical_language>parameter false (TissuePieceType#archived nullable)</technical_language>

Target:
public static TissuePieceType to(@Nonnull TissuePieceTypeDto from) { TissuePieceType to = new TissuePieceType(); if (from.getId() != null) to.setId(from.getId()); setString(to::setName, from.getName()); setString(to::setAbbreviation, from.getAbbreviation()); setBoolean(to::setArchived, from.isArchived(), false); return to; }
Source:
<code>public Builder<RelayConfiguration> configure(OperationContext context, ModelNode model) throws OperationFailedException { this.siteName = SITE.resolveModelAttribute(context, model).asString(); PathAddress address = context.getCurrentAddress(); Resource resource = context.readResource(PathAddress.EMPTY_ADDRESS); <START> List<ValueDependency<RemoteSiteConfiguration>> list = new ArrayList<>(); <END> for (Resource.ResourceEntry entry : resource.getChildren(RemoteSiteResourceDefinition.WILDCARD_PATH.getKey())) { InjectedValueDependency<RemoteSiteConfiguration> remoteSiteConfigurationInjectedValueDependency = new InjectedValueDependency<>(new RemoteSiteServiceNameProvider(address, entry.getPathElement()), RemoteSiteConfiguration.class); list.add(remoteSiteConfigurationInjectedValueDependency); } this.sites = list; return super.configure(context, model); }</code><technical_language>ArrayList constructed fixed capacity</technical_language>

Target:
public Builder<RelayConfiguration> configure(OperationContext context, ModelNode model) throws OperationFailedException { this.siteName = SITE.resolveModelAttribute(context, model).asString(); PathAddress address = context.getCurrentAddress(); Resource resource = context.readResource(PathAddress.EMPTY_ADDRESS); final Set<Resource.ResourceEntry> set = resource.getChildren(RemoteSiteResourceDefinition.WILDCARD_PATH.getKey()); List<ValueDependency<RemoteSiteConfiguration>> list = new ArrayList<>(set.size()); for (Resource.ResourceEntry entry : set) { list.add(new InjectedValueDependency<>(new RemoteSiteServiceNameProvider(address, entry.getPathElement()), RemoteSiteConfiguration.class)); } this.sites = list; return super.configure(context, model); }
Source:
<code>private BlobId getBlobIdFromString(String blobIdString) throws CoordinatorException { if (blobIdString == null || blobIdString.length() == 0) { logger.error("BlobIdString argument is null or zero length: {}", blobIdString); throw new CoordinatorException("BlobId is empty.", CoordinatorError.InvalidBlobId); } BlobId blobId; try { blobId = new BlobId(blobIdString, clusterMap); } catch (IOException e) { <START> logger.error("Caller passed in invalid BlobId " + blobIdString); <END> throw new CoordinatorException("BlobId is invalid.", CoordinatorError.InvalidBlobId); } catch (IllegalArgumentException e) { logger.error("Caller passed in invalid BlobId " + blobIdString); throw new CoordinatorException("BlobId is invalid. ", CoordinatorError.InvalidBlobId); } return blobId; }</code><technical_language>IOException means invalid blobid</technical_language>

Target:
private BlobId getBlobIdFromString(String blobIdString) throws CoordinatorException { if (blobIdString == null || blobIdString.length() == 0) { logger.error("BlobIdString argument is null or zero length: {}", blobIdString); throw new CoordinatorException("BlobId is empty.", CoordinatorError.InvalidBlobId); } BlobId blobId; try { blobId = new BlobId(blobIdString, clusterMap); } catch (Exception e) { logger.error("Caller passed in invalid BlobId " + blobIdString); throw new CoordinatorException("BlobId is invalid " + blobIdString, CoordinatorError.InvalidBlobId); } return blobId; }
Source:
<code>public void onBlockBreak(BlockBreakEvent e) { <START> if (SlimefunTag.CAVEMAN_TALISMAN_TRIGGERS.isTagged(e.getBlock().getType())) { Talisman.tryActivate(e, SlimefunItems.TALISMAN_WISE); <END> } }</code><technical_language>CAVEMAN = WISE</technical_language>

Target:
public void onBlockBreak(BlockBreakEvent e) { if (SlimefunTag.CAVEMAN_TALISMAN_TRIGGERS.isTagged(e.getBlock().getType())) { Talisman.tryActivate(e, SlimefunItems.TALISMAN_CAVEMAN); } }
Source:
<code>public void onTickEnd(TickEvent.WorldTickEvent event) { if(event.phase == TickEvent.Phase.END) { int dim = event.world.provider.dimensionId; if(blockSwappers.containsKey(dim)) { List<BlockSwapper> swappers = blockSwappers.get(dim); Iterator<BlockSwapper> iter = swappers.listIterator(); while(iter.hasNext()) { BlockSwapper next = iter.next(); if(!next.tick()) <START> iter.remove(); <END> } } } }</code><technical_language>why</technical_language>

Target:
public void onTickEnd(TickEvent.WorldTickEvent event) { if(event.phase == Phase.END) { int dim = event.world.provider.dimensionId; if(blockSwappers.containsKey(dim)) { List<BlockSwapper> swappers = blockSwappers.get(dim); Iterator<BlockSwapper> iter = swappers.listIterator(); while(iter.hasNext()) { BlockSwapper next = iter.next(); if(!next.tick()) iter.remove(); } } } }
Source:
<code>public List<CommentAttributes> getCommentsForReceiverVisibleToInstructor( String courseId, CommentParticipantType recipientType, String receiverEmail, String instructorEmail) throws EntityDoesNotExistException { verifyIsCoursePresent(courseId, "get"); verifyIsInstructorOfCourse(courseId, instructorEmail); List<CommentAttributes> commentsFromLogic = commentsDb.getCommentsForReceiver(courseId, recipientType, receiverEmail); Iterator<CommentAttributes> iterator = commentsFromLogic.iterator(); List<CommentAttributes> comments = new LinkedList<CommentAttributes>(); <START> HashSet<String> commentsVisitedSet = new HashSet<String>(); <END> while (iterator.hasNext()) { CommentAttributes c = iterator.next(); if (c.giverEmail.equals(instructorEmail)) { comments.add(c); preventAppendingThisCommentAgain(commentsVisitedSet, c); iterator.remove(); } } removeNonVisibleCommentsForInstructor(commentsFromLogic, commentsVisitedSet, comments); return comments; }</code><technical_language>Change type Set<String></technical_language>

Target:
public List<CommentAttributes> getCommentsForReceiverVisibleToInstructor( String courseId, CommentParticipantType recipientType, String receiverEmail, String instructorEmail) throws EntityDoesNotExistException { verifyIsCoursePresent(courseId, "get"); verifyIsInstructorOfCourse(courseId, instructorEmail); List<CommentAttributes> commentsFromDb = commentsDb.getCommentsForReceiver(courseId, recipientType, receiverEmail); Iterator<CommentAttributes> iterator = commentsFromDb.iterator(); List<CommentAttributes> comments = new LinkedList<CommentAttributes>(); HashSet<String> commentsVisitedSet = new HashSet<String>(); boolean canViewCommentsFromOthers = canViewCommentsFromOthers(courseId, recipientType, receiverEmail, instructorEmail); while (iterator.hasNext()) { CommentAttributes c = iterator.next(); if (c.giverEmail.equals(instructorEmail)) { comments.add(c); preventAppendingThisCommentAgain(commentsVisitedSet, c); iterator.remove(); } else if (!canViewCommentsFromOthers) { iterator.remove(); } } removeNonVisibleCommentsForInstructor(commentsFromDb, commentsVisitedSet, comments); iterator = comments.iterator(); while (iterator.hasNext()) { CommentAttributes c = iterator.next(); String firstRecipient = null; if (!c.recipients.isEmpty()) { firstRecipient = c.recipients.iterator().next(); } if (firstRecipient == null || Const.DISPLAYED_NAME_FOR_ANONYMOUS_COMMENT_PARTICIPANT.equals(firstRecipient)) { iterator.remove(); } } return comments; }
Source:
<code>public void awaitAllFutures() { Future<?> future = null; while ((future = futures.poll()) != null) { try { future.get(); } catch (InterruptedException | ExecutionException e) { <START> log.error("Encountered an error while awaiting an errant record future's " + "completition."); <END> throw new ConnectException(e); } } }</code><technical_language>Nit: new line is unnecessary, a misspelling: suggestion log.error("Encountered error while awaiting errant record future's completion.");</technical_language>

Target:
public void awaitAllFutures() { Future<?> future; while ((future = futures.poll()) != null) { try { future.get(); } catch (InterruptedException | ExecutionException e) { log.error("Encountered an error while awaiting an errant record future's completion."); throw new ConnectException(e); } } }
Source:
<code>public void testBytes() { assertQueryUsingH2Cte("SELECT ship_day FROM lineitem_ex"); assertQueryUsingH2Cte("SELECT ship_day FROM lineitem_ex WHERE ship_day < 15"); assertQueryUsingH2Cte("SELECT count(*) FROM lineitem_ex WHERE ship_day > 15"); assertQueryUsingH2Cte("SELECT count(*) FROM lineitem_ex WHERE ship_day is null"); assertQueryUsingH2Cte("SELECT ship_day, ship_month FROM lineitem_ex"); assertQueryUsingH2Cte("SELECT ship_day, ship_month FROM lineitem_ex WHERE ship_month = 1"); assertQueryUsingH2Cte("SELECT ship_day, ship_month FROM lineitem_ex WHERE ship_day = 1 AND ship_month = 1"); assertQueryUsingH2Cte("SELECT COUNT(*) FROM lineitem_ex WHERE ship_month is null"); assertQueryUsingH2Cte("SELECT COUNT(*) FROM lineitem_ex WHERE ship_day is not null AND ship_month = 1"); assertQueryUsingH2Cte("SELECT ship_day, ship_month FROM lineitem_ex WHERE ship_day > 15 AND ship_month < 5 AND (ship_day + ship_month) < 20"); assertQueryUsingH2Cte("SELECT count(*) FROM lineitem_ex WHERE ship_day_month[2] = 12"); <START> assertQueryUsingH2Cte("SELECT ship_day_month_nulls FROM lineitem_ex WHERE ship_day_month_nulls[1] is NOT NULL AND ship_day_month[1] > 3"); <END> }</code><technical_language>I expect this query fail ship_day_month_nulls column exist</technical_language>

Target:
public void testBytes() { assertQueryUsingH2Cte("SELECT ship_day FROM lineitem_ex"); assertQueryUsingH2Cte("SELECT ship_day FROM lineitem_ex WHERE ship_day < 15"); assertQueryUsingH2Cte("SELECT count(*) FROM lineitem_ex WHERE ship_day > 15"); assertQueryUsingH2Cte("SELECT count(*) FROM lineitem_ex WHERE ship_day is null"); assertQueryUsingH2Cte("SELECT ship_day, ship_month FROM lineitem_ex"); assertQueryUsingH2Cte("SELECT ship_day, ship_month FROM lineitem_ex WHERE ship_month = 1"); assertQueryUsingH2Cte("SELECT ship_day, ship_month FROM lineitem_ex WHERE ship_day = 1 AND ship_month = 1"); assertQueryUsingH2Cte("SELECT COUNT(*) FROM lineitem_ex WHERE ship_month is null"); assertQueryUsingH2Cte("SELECT COUNT(*) FROM lineitem_ex WHERE ship_day is not null AND ship_month = 1"); assertQueryUsingH2Cte("SELECT ship_day, ship_month FROM lineitem_ex WHERE ship_day > 15 AND ship_month < 5 AND (ship_day + ship_month) < 20"); assertQueryUsingH2Cte("SELECT count(*) FROM lineitem_ex WHERE ship_day_month[2] = 12"); }
Source:
<code>public ParametersBuilder addPersistedWithoutHibernate(int yearWhenPersistedWithoutHibernate, int monthWhenPersistedWithoutHibernate, int dayWhenPersistedWithoutHibernate, int hour, int minute, int second, int nanosecond, ZoneId defaultTimeZone) { if ( isNanosecondPrecisionSupported() ) { <START> nanosecond = 0; <END> } return add( defaultTimeZone, hour, minute, second, nanosecond, yearWhenPersistedWithoutHibernate, monthWhenPersistedWithoutHibernate, dayWhenPersistedWithoutHibernate ); }</code><technical_language>if condition be: if ( !isNanosecondPrecisionSupported() )</technical_language>

Target:
public ParametersBuilder addPersistedWithoutHibernate(int yearWhenPersistedWithoutHibernate, int monthWhenPersistedWithoutHibernate, int dayWhenPersistedWithoutHibernate, int hour, int minute, int second, int nanosecond, ZoneId defaultTimeZone) { if ( !isNanosecondPrecisionSupported() ) { nanosecond = 0; } return add( defaultTimeZone, hour, minute, second, nanosecond, yearWhenPersistedWithoutHibernate, monthWhenPersistedWithoutHibernate, dayWhenPersistedWithoutHibernate ); }
Source:
<code>public void switchFromDashboardIframeToIde(int timeout) { new WebDriverWait(this, timeout) <START> .until(visibilityOfElementLocated(By.id("ide-application-iframe"))); <END> new WebDriverWait(this, ATTACHING_ELEM_TO_DOM_SEC) .until( (ExpectedCondition<Boolean>) driver -> (((JavascriptExecutor) driver) .executeScript("return angular.element('body').scope().showIDE")) .toString() .equals("true")); new WebDriverWait(this, timeout) .until(frameToBeAvailableAndSwitchToIt(By.id("ide-application-iframe"))); }</code><technical_language>is method wait(timeout) in class. simplify code</technical_language>

Target:
public void switchFromDashboardIframeToIde(int timeout) { wait(timeout).until(visibilityOfElementLocated(By.id("ide-application-iframe"))); wait(ATTACHING_ELEM_TO_DOM_SEC) .until( (ExpectedCondition<Boolean>) driver -> (((JavascriptExecutor) driver) .executeScript("return angular.element('body').scope().showIDE")) .toString() .equals("true")); wait(timeout).until(frameToBeAvailableAndSwitchToIt(By.id("ide-application-iframe"))); }
Source:
<code>private static void minimizeTestSuite( CompilationUnit cu, String packageName, File file, String classpath, Map<String, String> expectedOutput, int timeoutLimit, boolean verboseOutput) { for (TypeDeclaration type : cu.getTypes()) { for (BodyDeclaration member : type.getMembers()) { if (member instanceof MethodDeclaration) { MethodDeclaration method = (MethodDeclaration) member; for (AnnotationExpr annotationExpr : method.getAnnotations()) { <START> if (annotationExpr.toString().equals("@Test")) { <END> minimizeMethod( method, cu, packageName, file, classpath, expectedOutput, timeoutLimit); if (verboseOutput) { System.out.println("Minimized method " + method.getName() + "."); } break; } } } } } }</code><technical_language>more natural abstract this out a routine, isTestMethod. drop for loop break statement, code easier read</technical_language>

Target:
private static void minimizeTestSuite( CompilationUnit cu, String packageName, File file, String classpath, Map<String, String> expectedOutput, int timeoutLimit, boolean verboseOutput) { for (TypeDeclaration type : cu.getTypes()) { for (BodyDeclaration member : type.getMembers()) { if (member instanceof MethodDeclaration) { MethodDeclaration method = (MethodDeclaration) member; if (isTestMethod(method)) { minimizeMethod(method, cu, packageName, file, classpath, expectedOutput, timeoutLimit); if (verboseOutput) { System.out.println("Minimized method " + method.getName() + "."); } } } } } }
Source:
<code>protected boolean canDoAction() { if (getDisk() == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_NOT_EXIST); } <START> if (getDiskType() == DiskStorageType.IMAGE) { <END> if (((DiskImage) getDisk()).getImageStatus() == ImageStatus.LOCKED) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISKS_LOCKED); } else if (((DiskImage) getDisk()).getImageStatus() != ImageStatus.OK) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISKS_ILLEGAL); } } if (getVm() == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_IS_NOT_VM_DISK); } if (isImageExclusiveLockNeeded() && getVm().isRunningOrPaused()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_RUNNING); } if (getVdsIdInPool() == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_NO_VDS_IN_POOL); } if (!validate(new StoragePoolValidator(getStoragePoolDao().get(getStoragePoolId())).isUp())) { return false; } return true; }</code><technical_language>DiskImageValidator encapsulate this logic/messages</technical_language>

Target:
protected boolean canDoAction() { if (getDisk() == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_NOT_EXIST); } if (getDiskType() == DiskStorageType.IMAGE) { DiskImagesValidator diskImagesValidator = new DiskImagesValidator(Arrays.asList((DiskImage) getDisk())); if (!validate(diskImagesValidator.diskImagesNotLocked()) || !validate(diskImagesValidator.diskImagesNotIllegal())) { return false; } } if (getVm() == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_IS_NOT_VM_DISK); } if (isImageExclusiveLockNeeded() && getVm().isRunningOrPaused()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_RUNNING); } if (getVdsIdInPool() == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_NO_VDS_IN_POOL); } if (!validate(new StoragePoolValidator(getStoragePoolDao().get(getStoragePoolId())).isUp())) { return false; } return true; }