auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static SpecificationCollection create(List<File> specificationFiles) { if (specificationFiles == null) { return null; } MultiMap<OperationSignature, Method> signatureMap = new MultiMap<>(); Map<AccessibleObject, OperationSpecification> specificationMap = new LinkedHashMap<>(); for (File specificationFile : specificationFiles) { List<OperationSpecification> specificationList; try { specificationList = readSpecifications(specificationFile); } catch (IOException e) { String msg = "Unable to read specifications from file"; if (Log.isLoggingOn()) { Log.logLine(msg + ": " + specificationFile); } throw new RandoopConditionError(msg, e); } catch (Throwable e) { throw new RandoopConditionError("Bad input", e); } for (OperationSpecification specification : specificationList) { OperationSignature operation = specification.getOperation(); if (operation == null) { continue; } if (specification.getIdentifiers().hasDuplicatedName()) { String msg = String.format( "Ignoring specification with identifier name conflict: %s", specification.getOperation().toString()); System.out.println(msg); if (Log.isLoggingOn()) { Log.logLine(msg); } continue; } AccessibleObject accessibleObject = getAccessibleObject(operation); specificationMap.put(accessibleObject, specification); if (accessibleObject instanceof Method) { OperationSignature signature = OperationSignature.of(accessibleObject); signatureMap.add(signature, (Method) accessibleObject); } } } Map<AccessibleObject, Set<Method>> parentMap = buildParentMap(signatureMap); return new SpecificationCollection(specificationMap, signatureMap, parentMap); }

Target:
public static SpecificationCollection create(List<File> specificationFiles) { if (specificationFiles == null) { return null; } MultiMap<OperationSignature, Method> signatureToMethods = new MultiMap<>(); Map<AccessibleObject, OperationSpecification> specificationMap = new LinkedHashMap<>(); for (File specificationFile : specificationFiles) { List<OperationSpecification> specificationList = readSpecificationFile(specificationFile); try { for (OperationSpecification specification : specificationList) { OperationSignature operation = specification.getOperation(); if (operation == null) { throw new Error("operation is null for specification " + specification); } if (specification.getIdentifiers().hasDuplicatedName()) { throw new RandoopConditionError( "Duplicate name in specification: " + specification.getOperation()); } AccessibleObject accessibleObject = getAccessibleObject(operation); specificationMap.put(accessibleObject, specification); if (accessibleObject instanceof Method) { OperationSignature signature = OperationSignature.of(accessibleObject); signatureToMethods.add(signature, (Method) accessibleObject); } } } catch (RandoopConditionError e) { e.setFile(specificationFile); throw e; } } Map<AccessibleObject, Set<Method>> overridden = buildOverridingMap(signatureToMethods); return new SpecificationCollection(specificationMap, signatureToMethods, overridden); }
Source:
public void setup() throws Exception { CanvasCommandManagerImpl commandManager = new CanvasCommandManagerImpl(); when(canvasHandler.getCanvas()).thenReturn(canvas); when(clientSessionManager.getCurrentSession()).thenReturn(editorSession); when(editorSession.getCanvasHandler()).thenReturn(canvasHandler); when(editorSession.getCommandRegistry()).thenReturn(commandRegistry); when(editorSession.getCommandManager()).thenReturn(commandManager); this.tested = new RequestCommandManager(clientSessionManager, commandRegisteredEvent); }

Target:
public void setup() throws Exception { CanvasCommandManagerImpl commandManager = new CanvasCommandManagerImpl(); when(canvasHandler.getCanvas()).thenReturn(canvas); when(clientSessionManager.getCurrentSession()).thenReturn(editorSession); when(editorSession.getCanvasHandler()).thenReturn(canvasHandler); when(editorSession.getCommandRegistry()).thenReturn(commandRegistry); when(editorSession.getCommandManager()).thenReturn(commandManager); this.tested = new RequestCommandManager(clientSessionManager); }
Source:
private Set<String> getTrashRemovedResourcesId(List<String> resourceIds, List<String> archivedResources) { Set<String> trashRemovedResources = null; Iterator<String> it = resourceIds.iterator(); String id = null; while (it.hasNext()) { id = (String)it.next(); ResourceInterface resourceInterfaceArchived = null; ResourceInterface resourceInterfaceTrashed = null; try { resourceInterfaceTrashed = this.getTrashedResourceManager().loadTrashedResource(id); resourceInterfaceArchived = this.getResourceManager().loadResource(id); if (!(null != resourceInterfaceArchived || null != resourceInterfaceTrashed)) { if (null == trashRemovedResources) { trashRemovedResources = new HashSet<String>(); } trashRemovedResources.add(id); } } catch (Throwable t) { logger.error("Errore in verifica risorsa rimossa definitivamente da cestino, id " + id, t); throw new RuntimeException("Errore in verifica risorsa rimossa definitivamente da cestino, id " + id, t); } } return trashRemovedResources; }

Target:
private Set<String> getTrashRemovedResourcesId(List<String> resourceIds, List<String> archivedResources) { Set<String> trashRemovedResources = null; Iterator<String> it = resourceIds.iterator(); String id = null; while (it.hasNext()) { id = (String)it.next(); ResourceInterface resourceInterfaceArchived = null; ResourceInterface resourceInterfaceTrashed = null; try { resourceInterfaceTrashed = this.getTrashedResourceManager().loadTrashedResource(id); resourceInterfaceArchived = this.getResourceManager().loadResource(id); if (!(null != resourceInterfaceArchived || null != resourceInterfaceTrashed)) { if (null == trashRemovedResources) { trashRemovedResources = new HashSet<String>(); } trashRemovedResources.add(id); } } catch (Throwable t) { logger.error("Error checking resource permanently removed, id " + id, t); throw new RuntimeException("Error checking resource permanently removed, id " + id, t); } } return trashRemovedResources; }
Source:
public static void switchToExistingOrCreateUserType(ITestDevice device) throws DeviceNotAvailableException, UserSwitchFailedException { try { UserUtil.switchToUserType(device, mUserToSwitchTo); } catch (UserUtil.SecondaryUserNotFoundException attemptCreate) { CLog.d("No secondary users exist, creating one."); UserUtil.createAndSwitchToSecondaryUser(device); } }

Target:
private void switchToExistingOrCreateUserType(ITestDevice device) throws DeviceNotAvailableException, UserSwitchFailedException { try { UserUtil.switchToUserType(device, mUserToSwitchTo); } catch (UserUtil.SecondaryUserNotFoundException attemptCreate) { CLog.d("No secondary users exist, creating one."); UserUtil.createAndSwitchToSecondaryUser(device); } }
Source:
public OperatorResponse execute(Operator operator, int operatorId, long windowId) throws IOException { logger.debug("Receieved slowdown operator operatorId windowId {}", operator, operatorId, windowId); if (operator instanceof RandomNumberGenerator) { RandomNumberGenerator generator = (RandomNumberGenerator)operator; generator.suspend(); } return new InputOperatorResponse(); }

Target:
public OperatorResponse execute(Operator operator, int operatorId, long windowId) throws IOException { logger.debug("Received slowdown operator operatorId windowId {}", operator, operatorId, windowId); if (operator instanceof RandomNumberGenerator) { RandomNumberGenerator generator = (RandomNumberGenerator)operator; generator.suspend(); } return new InputOperatorResponse(); }
Source:
public void startingVmCompleted(Guid vmId, String cause) { log.info("Startup of VM completed ({})", vmId, cause); startingVms.remove(vmId); }

Target:
public void startingVmCompleted(Guid vmId, String cause) { if (log.isDebugEnabled() && startingVms.contains(vmId)) { log.debug("Startup of VM completed ({})", vmId, cause); } startingVms.remove(vmId); }
Source:
private void setTypeRef(Configuration conf) { String className = conf.get(CLASS_CONF_KEY); if (className == null) { throw new RuntimeException(CLASS_CONF_KEY + " is not set"); } Class<?> clazz = null; try { clazz = conf.getClassByName(className); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } typeRef = new TypeRef<M>(clazz){}; }

Target:
private void setTypeRef(Configuration conf) { String className = conf.get(CLASS_CONF_KEY); if (className == null) { throw new RuntimeException(CLASS_CONF_KEY + " is not set"); } Class<?> clazz = null; try { clazz = conf.getClassByName(className); } catch (ClassNotFoundException e) { throw new RuntimeException("failed to instantiate class '" + className + "'", e); } typeRef = new TypeRef<M>(clazz){}; }
Source:
public Result[] searchFields(String q, String f, float boost, int k) throws IOException { IndexSearcher searcher = new IndexSearcher(reader); searcher.setSimilarity(similarity); Query queryContents = new BagOfWordsQueryGenerator().buildQuery(LuceneDocumentGenerator.FIELD_BODY, analyzer, q); Query queryField = new BagOfWordsQueryGenerator().buildQuery(f, analyzer, q); BooleanQuery query = new BooleanQuery.Builder() .add(queryContents, BooleanClause.Occur.SHOULD) .add(new BoostQuery(queryField, boost), BooleanClause.Occur.SHOULD).build(); List<String> queryTokens = AnalyzerUtils.tokenize(analyzer, q); SearchArgs searchArgs = new SearchArgs(); searchArgs.arbitraryScoreTieBreak = false; searchArgs.hits = k; searchArgs.searchtweets = searchtweets; TopDocs rs = new TopDocs(0, new ScoreDoc[]{}, Float.NaN); RerankerContext context; if (searchtweets) { throw new UnsupportedOperationException(); } else { rs = searcher.search(query, isRerank ? searchArgs.rerankcutoff : k, BREAK_SCORE_TIES_BY_DOCID, true, true); context = new RerankerContext<>(searcher, null, query, null, q, queryTokens, null, searchArgs); } ScoredDocuments hits = cascade.run(ScoredDocuments.fromTopDocs(rs, searcher), context); Result[] results = new Result[hits.ids.length]; for (int i = 0; i < hits.ids.length; i++) { Document doc = hits.documents[i]; String docid = doc.getField(LuceneDocumentGenerator.FIELD_ID).stringValue(); IndexableField field = doc.getField(LuceneDocumentGenerator.FIELD_RAW); String content = field == null ? null : field.stringValue(); results[i] = new Result(docid, hits.ids[i], hits.scores[i], content); } return results; }

Target:
public Result[] searchFields(String q, String f, float boost, int k) throws IOException { IndexSearcher searcher = new IndexSearcher(reader); searcher.setSimilarity(similarity); Query queryContents = new BagOfWordsQueryGenerator().buildQuery(LuceneDocumentGenerator.FIELD_BODY, analyzer, q); Query queryField = new BagOfWordsQueryGenerator().buildQuery(f, analyzer, q); BooleanQuery query = new BooleanQuery.Builder() .add(queryContents, BooleanClause.Occur.SHOULD) .add(new BoostQuery(queryField, boost), BooleanClause.Occur.SHOULD).build(); List<String> queryTokens = AnalyzerUtils.tokenize(analyzer, q); return search(query, queryTokens, q, k, -1); }
Source:
public void boot(final PlayerName playerName) { assertUserIsAdmin(); if (serverMessenger.getServerNode().getPlayerName().equals(playerName)) { throw new IllegalStateException("Cannot boot server node"); } final INode modNode = MessageContext.getSender(); serverMessenger.getNodes().stream() .filter(n -> n.getPlayerName().equals(playerName)) .findAny() .ifPresent( node -> { serverMessenger.removeConnection(node); database .getModeratorAuditHistoryDao() .addAuditRecord( ModeratorAuditHistoryDao.AuditArgs.builder() .moderatorUserId( database .getUserJdbiDao() .lookupUserIdByName(modNode.getName()) .orElseThrow( () -> new IllegalStateException( "Failed to find user: " + modNode.getName()))) .actionName(ModeratorAuditHistoryDao.AuditAction.BOOT_USER_FROM_LOBBY) .actionTarget(node.getPlayerName().getValue()) .build()); }); }

Target:
public void boot(final PlayerName playerName) { assertUserIsAdmin(); if (serverMessenger.getServerNode().getPlayerName().equals(playerName)) { throw new IllegalStateException("Cannot boot server node"); } final INode modNode = MessageContext.getSender(); findNodeByPlayerName(playerName) .ifPresent( node -> { serverMessenger.removeConnection(node); database .getModeratorAuditHistoryDao() .addAuditRecord( ModeratorAuditHistoryDao.AuditArgs.builder() .moderatorUserId( database .getUserJdbiDao() .lookupUserIdByName(modNode.getName()) .orElseThrow( () -> new IllegalStateException( "Failed to find user: " + modNode.getName()))) .actionName(ModeratorAuditHistoryDao.AuditAction.BOOT_USER_FROM_LOBBY) .actionTarget(node.getPlayerName().getValue()) .build()); }); }
Source:
void processRequest(CorfuMsg msg, ChannelHandlerContext ctx, IServerRouter r) { executor.submit(() -> getHandler().handle(msg, ctx, r)); }

Target:
protected void processRequest(CorfuMsg msg, ChannelHandlerContext ctx, IServerRouter r) { executor.submit(() -> getHandler().handle(msg, ctx, r)); }
Source:
public Collection<Object> getAppComponents(String extension, SupportedTransports type, Object... services) { if (!OWNER_EXTENSION.equals(extension)) { return Collections.emptyList(); } ScenarioSimulationService scenarioSimulationService = Arrays.stream(services) .filter(elem -> ScenarioSimulationService.class.isAssignableFrom(elem.getClass())) .map(ScenarioSimulationService.class::cast) .findFirst() .orElse(null); List<Object> components = new ArrayList<Object>(1); if (SupportedTransports.REST.equals(type)) { components.add(new ScenarioSimulationResource(scenarioSimulationService)); } return components; }

Target:
public Collection<Object> getAppComponents(String extension, SupportedTransports type, Object... services) { if (!Objects.equals(OWNER_EXTENSION, extension)) { return Collections.emptyList(); } Optional<ScenarioSimulationService> simulationService = Arrays.stream(services) .filter(elem -> ScenarioSimulationService.class.isAssignableFrom(elem.getClass())) .map(ScenarioSimulationService.class::cast) .findFirst(); List<Object> components = new ArrayList<>(1); if (SupportedTransports.REST.equals(type)) { if (simulationService.isPresent()) { components.add(new ScenarioSimulationResource(simulationService.get())); } else { logger.error("Impossible to load Test Scenario extension because of missing ScenarioSimulationService. " + "This should never happen if ScenarioSimulationKieServerExtension is properly deployed and activated"); } } return components; }
Source:
public void testRemoveReadingLists() { ContentResource cr = mock(ContentResource.class); files.put("IsCitation", cr); when(cr.getContentType()).thenReturn("org.sakaiproject.citation.impl.CitationList"); assertEquals(0, exportUtil.removeReadingLists(files).size()); }

Target:
public void testRemoveReadingLists() { ContentResource cr = mock(ContentResource.class); files.put("IsCitation", cr); when(cr.getResourceType()).thenReturn("org.sakaiproject.citation.impl.CitationList"); assertEquals(0, exportUtil.removeReadingLists(files).size()); }
Source:
public void setKeyName(String keyName) { if (keyName == null || keyName.isEmpty()) { throw new IllegalArgumentException("Argument cannot be null."); } if (keyName.length() > SecurityConstants.MAX_KEY_NAME_LENGTH) { throw new IllegalArgumentException("sasKeyName cannot be greater than " + SecurityConstants.MAX_KEY_NAME_LENGTH + " characters."); } this.keyName = keyName; }

Target:
public void setKeyName(String keyName) { if (keyName == null || keyName.isEmpty()) { throw new IllegalArgumentException("Argument cannot be null"); } if (keyName.length() > SecurityConstants.MAX_KEY_NAME_LENGTH) { throw new IllegalArgumentException("sasKeyName cannot be greater than " + SecurityConstants.MAX_KEY_NAME_LENGTH + " characters."); } this.keyName = keyName; }
Source:
public Item[] addItem(Item... slots) { List<Item> itemSlots = new ArrayList<>(); for (Item slot : slots) { if (slot.getId() != 0 && slot.getCount() > 0) { itemSlots.add(slot.clone()); } } List<Integer> emptySlots = new ArrayList<>(); for (int i = 0; i < this.getSize(); ++i) { Item item = this.getItem(i); if (item.getId() == Item.AIR || item.getCount() <= 0) { emptySlots.add(i); } for (Item slot : new ArrayList<>(itemSlots)) { if (slot.equals(item) && item.getCount() < item.getMaxStackSize() && slot.getDamage() == item.getDamage()) { int amount = Math.min(item.getMaxStackSize() - item.getCount(), slot.getCount()); amount = Math.min(amount, this.getMaxStackSize()); if (amount > 0) { slot.setCount(slot.getCount() - amount); item.setCount(item.getCount() + amount); this.setItem(i, item); if (slot.getCount() <= 0) { itemSlots.remove(slot); } } } } if (itemSlots.isEmpty()) { break; } } if (!itemSlots.isEmpty() && !emptySlots.isEmpty()) { for (int slotIndex : emptySlots) { if (!itemSlots.isEmpty()) { Item slot = itemSlots.get(0); int amount = Math.min(slot.getMaxStackSize(), slot.getCount()); amount = Math.min(amount, this.getMaxStackSize()); slot.setCount(slot.getCount() - amount); Item item = slot.clone(); item.setCount(amount); this.setItem(slotIndex, item); if (slot.getCount() <= 0) { itemSlots.remove(slot); } } } } return itemSlots.stream().toArray(Item[]::new); }

Target:
public Item[] addItem(Item... slots) { List<Item> itemSlots = new ArrayList<>(); for (Item slot : slots) { if (slot.getId() != 0 && slot.getCount() > 0) { itemSlots.add(slot.clone()); } } List<Integer> emptySlots = new ArrayList<>(); for (int i = 0; i < this.getSize(); ++i) { Item item = this.getItem(i); if (item.getId() == Item.AIR || item.getCount() <= 0) { emptySlots.add(i); } for (Item slot : new ArrayList<>(itemSlots)) { if (slot.equals(item) && item.getCount() < item.getMaxStackSize()) { int amount = Math.min(item.getMaxStackSize() - item.getCount(), slot.getCount()); amount = Math.min(amount, this.getMaxStackSize()); if (amount > 0) { slot.setCount(slot.getCount() - amount); item.setCount(item.getCount() + amount); this.setItem(i, item); if (slot.getCount() <= 0) { itemSlots.remove(slot); } } } } if (itemSlots.isEmpty()) { break; } } if (!itemSlots.isEmpty() && !emptySlots.isEmpty()) { for (int slotIndex : emptySlots) { if (!itemSlots.isEmpty()) { Item slot = itemSlots.get(0); int amount = Math.min(slot.getMaxStackSize(), slot.getCount()); amount = Math.min(amount, this.getMaxStackSize()); slot.setCount(slot.getCount() - amount); Item item = slot.clone(); item.setCount(amount); this.setItem(slotIndex, item); if (slot.getCount() <= 0) { itemSlots.remove(slot); } } } } return itemSlots.stream().toArray(Item[]::new); }
Source:
public synchronized void onMessageProcessingFinished(TcpDiscoveryAbstractMessage msg) { assert msg != null; Long startTs = msgsProcStartTs.remove(msg.id()); if (startTs == null) { long duration = U.currentTimeMillis() - startTs; int totalProcMsgs = totalProcessedMessages(); if (totalProcMsgs != 0) avgMsgProcTime = (avgMsgProcTime * (totalProcMsgs - 1) + duration) / totalProcMsgs; if (duration > maxMsgProcTime) maxMsgProcTime = duration; } }

Target:
public synchronized void onMessageProcessingFinished(TcpDiscoveryAbstractMessage msg) { assert msg != null; Long startTs = msgsProcStartTs.remove(msg.id()); if (startTs != null) { long duration = U.currentTimeMillis() - startTs; int totalProcMsgs = totalProcessedMessages(); if (totalProcMsgs != 0) avgMsgProcTime = (avgMsgProcTime * (totalProcMsgs - 1) + duration) / totalProcMsgs; if (duration > maxMsgProcTime) maxMsgProcTime = duration; } }
Source:
public void testCancelSubscriptionWithInvalidRequestedDate() throws SubscriptionBaseApiException { final String prod = "Shotgun"; final BillingPeriod term = BillingPeriod.MONTHLY; final String planSet = PriceListSet.DEFAULT_PRICELIST_NAME; final DefaultSubscriptionBase subscription = testUtil.createSubscription(bundle, prod, term, planSet); PlanPhase currentPhase = subscription.getCurrentPhase(); assertEquals(currentPhase.getPhaseType(), PhaseType.TRIAL); testListener.pushExpectedEvent(NextEvent.PHASE); final Interval it = new Interval(clock.getUTCNow(), clock.getUTCNow().plusDays(31)); clock.addDeltaFromReality(it.toDurationMillis()); assertListenerStatus(); currentPhase = subscription.getCurrentPhase(); assertEquals(currentPhase.getPhaseType(), PhaseType.EVERGREEN); final DateTime invalidDate = subscription.getBundleStartDate().minusDays(3); subscription.cancelWithDate(invalidDate, callContext); assertListenerStatus(); testListener.pushExpectedEvent(NextEvent.CANCEL); assertListenerStatus(); }

Target:
public void testCancelSubscriptionWithInvalidRequestedDate() throws SubscriptionBaseApiException { final String prod = "Shotgun"; final BillingPeriod term = BillingPeriod.MONTHLY; final String planSet = PriceListSet.DEFAULT_PRICELIST_NAME; final DefaultSubscriptionBase subscription = testUtil.createSubscription(bundle, prod, term, planSet); PlanPhase currentPhase = subscription.getCurrentPhase(); assertEquals(currentPhase.getPhaseType(), PhaseType.TRIAL); testListener.pushExpectedEvent(NextEvent.PHASE); final Interval it = new Interval(clock.getUTCNow(), clock.getUTCNow().plusDays(31)); clock.addDeltaFromReality(it.toDurationMillis()); assertListenerStatus(); currentPhase = subscription.getCurrentPhase(); assertEquals(currentPhase.getPhaseType(), PhaseType.EVERGREEN); final DateTime invalidDate = subscription.getBundleStartDate().minusDays(3); subscription.cancelWithDate(invalidDate, callContext); }
Source:
private String getSelectedFunctionString(String functionString) { functionString += " "; functionString = functionString.replace("(", "( "); functionString = functionString.replace(")", " )"); functionString = functionString.replace(",", " , "); return functionString; }

Target:
private String getSelectedFunctionString(String functionString) { return functionString.replace("(", "( ") .replace(")", " )") .replace(",", " , ") .concat(" "); }
Source:
protected void executeCommand() { if (noChangesDetected()) { log.info("No changes were detected in setup networks for host '{}' (ID: '{}')", getVdsName(), getVdsId()); setSucceeded(true); return; } fillInUnsetBondingOptions(); int timeout = getSetupNetworksTimeout(); FutureVDSCall<VDSReturnValue> setupNetworksTask = invokeSetupNetworksCommand(timeout); try { VDSReturnValue retVal = setupNetworksTask.get(timeout, TimeUnit.SECONDS); if (retVal != null) { if (!retVal.getSucceeded() && retVal.getVdsError() == null && getParameters().rollbackOnFailure()) { throw new EngineException(EngineError.SETUP_NETWORKS_ROLLBACK, retVal.getExceptionString()); } VdsHandler.handleVdsResult(retVal); if (retVal.getSucceeded()) { try (EngineLock monitoringLock = acquireMonitorLock()) { VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GetCapabilities, new VdsIdAndVdsVDSCommandParametersBase(getVds())); VDS updatedHost = (VDS) returnValue.getReturnValue(); persistNetworkChanges(updatedHost); } logMonitorLockReleased("Host setup networks"); setSucceeded(true); } } } catch (TimeoutException e) { log.debug("Host Setup networks command timed out for seconds", timeout); } }

Target:
protected void executeCommand() { if (noChangesDetected()) { log.info("No changes were detected in setup networks for host '{}' (ID: '{}')", getVdsName(), getVdsId()); setSucceeded(true); return; } int timeout = getSetupNetworksTimeout(); FutureVDSCall<VDSReturnValue> setupNetworksTask = invokeSetupNetworksCommand(timeout); try { VDSReturnValue retVal = setupNetworksTask.get(timeout, TimeUnit.SECONDS); if (retVal != null) { if (!retVal.getSucceeded() && retVal.getVdsError() == null && getParameters().rollbackOnFailure()) { throw new EngineException(EngineError.SETUP_NETWORKS_ROLLBACK, retVal.getExceptionString()); } VdsHandler.handleVdsResult(retVal); if (retVal.getSucceeded()) { try (EngineLock monitoringLock = acquireMonitorLock()) { VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GetCapabilities, new VdsIdAndVdsVDSCommandParametersBase(getVds())); VDS updatedHost = (VDS) returnValue.getReturnValue(); persistNetworkChanges(updatedHost); } logMonitorLockReleased("Host setup networks"); setSucceeded(true); } } } catch (TimeoutException e) { log.debug("Host Setup networks command timed out for seconds", timeout); } }
Source:
public void deployPartial(String name, Set<TargetExtensions> targetExtensions) throws Exception { Bundle bundle = new BundleImpl(osgi, lookupBundle(name), null); RuntimeContext ctx = new OSGiRuntimeContext(runtime, bundle); listBundleComponents(bundle).map(URLStreamRef::new).forEach(component -> { try { this.deployPartialComponent(ctx, targetExtensions, component); } catch (IOException e) { log.warn("PartialBundle: " + name + " failed to load: " + component, e); } }); }

Target:
public void deployPartial(String name, Set<TargetExtensions> targetExtensions) throws Exception { Bundle bundle = new BundleImpl(osgi, lookupBundle(name), null); RuntimeContext ctx = new OSGiRuntimeContext(runtime, bundle); listBundleComponents(bundle).map(URLStreamRef::new).forEach(component -> { try { this.deployPartialComponent(ctx, targetExtensions, component); } catch (IOException e) { log.error("PartialBundle: " + name + " failed to load: " + component, e); } }); }
Source:
private Deployment getDeploymentByName(String deploymentName) throws IOException { Deployment dc = openShiftClient .extensions().deployments() .inNamespace(this.cheOpenShiftProjectName) .withName(deploymentName) .get(); if (dc == null) { LOG.warn("No Deployment with name " + deploymentName + " could be found"); } return dc; }

Target:
private Deployment getDeploymentByName(String deploymentName) throws IOException { Deployment deployment = openShiftClient .extensions().deployments() .inNamespace(this.openShiftCheProjectName) .withName(deploymentName) .get(); if (deployment == null) { LOG.warn("No Deployment with name could be found", deploymentName); } return deployment; }
Source:
public String getUserName() { final User user = User.get(authenticationName, false, Collections.emptyMap()); return user != null ? user.getDisplayName() : authenticationName; }

Target:
public String getUserName() { final User user = User.getById(authenticationName, false); return user != null ? user.getDisplayName() : authenticationName; }
Source:
public static CosmosChangeFeedFindToken fromBytes(DataInputStream inputStream) throws IOException { CosmosChangeFeedFindToken cosmosChangeFeedFindToken; DataInputStream stream = new DataInputStream(inputStream); short version = stream.readShort(); switch (version) { case VERSION_0: FindTokenType type = FindTokenType.values()[stream.readShort()]; if (type != FindTokenType.CloudBased) { throw new IllegalArgumentException( String.format("Invalid token type %s found while deserialization. Expected %s.", type, FindTokenType.CloudBased)); } long bytesRead = stream.readLong(); String startContinuationToken = Utils.readIntString(inputStream); String endContinuationToken = Utils.readIntString(inputStream); int index = inputStream.readInt(); int totalItems = inputStream.readInt(); String cacheSessionId = Utils.readIntString(inputStream); cosmosChangeFeedFindToken = new CosmosChangeFeedFindToken(bytesRead, startContinuationToken, endContinuationToken, index, totalItems, cacheSessionId, version); break; default: throw new IllegalStateException("Unknown version of cloud token: " + version); } return cosmosChangeFeedFindToken; }

Target:
public static CosmosChangeFeedFindToken fromBytes(DataInputStream inputStream) throws IOException { DataInputStream stream = new DataInputStream(inputStream); short version = stream.readShort(); switch (version) { case VERSION_0: FindTokenType type = FindTokenType.values()[stream.readShort()]; if (type != FindTokenType.CloudBased) { throw new IllegalArgumentException( String.format("Invalid token type %s found while deserialization. Expected %s.", type, FindTokenType.CloudBased)); } long bytesRead = stream.readLong(); String startContinuationToken = readIntString(inputStream); String endContinuationToken = readIntString(inputStream); int index = inputStream.readInt(); int totalItems = inputStream.readInt(); String cacheSessionId = readIntString(inputStream); return new CosmosChangeFeedFindToken(bytesRead, startContinuationToken, endContinuationToken, index, totalItems, cacheSessionId, version); default: throw new IllegalStateException("Unknown version of cloud token: " + version); } }
Source:
public void testPutNextEntryUsingCurrentTime() throws IOException { long timeBeforeZipSeconds = System.currentTimeMillis() / 1000 * 1000; ByteArrayOutputStream bos = new ByteArrayOutputStream(); try (ZipOutputStream out = new ZipOutputStream(bos)) { out.putNextEntry(new ZipEntry("name")); out.closeEntry(); out.finish(); } long timeAfterZipSeconds = (System.currentTimeMillis() / 1000 + 1) * 1000; try (ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(bos.toByteArray()))) { ZipEntry entry = zis.getNextEntry(); assertEquals("name", entry.getName()); assertTrue(timeBeforeZipSeconds <= entry.getTime()); assertTrue(timeAfterZipSeconds >= entry.getTime()); } }

Target:
public void testPutNextEntryUsingCurrentTime() throws IOException { long timeBeforeZip = System.currentTimeMillis() / 1000 * 1000; ByteArrayOutputStream bos = new ByteArrayOutputStream(); try (ZipOutputStream out = new ZipOutputStream(bos)) { ZipEntry entryWithoutExplicitTime = new ZipEntry("name"); out.putNextEntry(entryWithoutExplicitTime); out.closeEntry(); out.finish(); } long timeAfterZip = (System.currentTimeMillis() / 1000 + 1) * 1000; try (ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(bos.toByteArray()))) { ZipEntry entry = zis.getNextEntry(); assertEquals("name", entry.getName()); assertTrue(timeBeforeZip <= entry.getTime()); assertTrue(timeAfterZip >= entry.getTime()); } }
Source:
public ImportNetworksModel(SearchableListModel sourceListModel) { this.sourceListModel = sourceListModel; setTitle(ConstantsManager.getInstance().getConstants().importNetworksTitle()); setHashName("import_networks"); UICommand tempVar = new UICommand(CMD_IMPORT, this); tempVar.setTitle(ConstantsManager.getInstance().getConstants().importNetworksButton()); tempVar.setIsDefault(true); getCommands().add(tempVar); UICommand tempVar2 = new UICommand(CMD_CANCEL, this); tempVar2.setTitle(ConstantsManager.getInstance().getConstants().cancel()); tempVar2.setIsCancel(true); getCommands().add(tempVar2); providers.getSelectedItemChangedEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { onProviderChosen(); } }); AsyncDataProvider.GetAllProviders(new AsyncQuery(this, new INewAsyncCallback() { @SuppressWarnings("unchecked") @Override public void onSuccess(Object model, Object returnValue) { List<Provider> providers = Linq.toList(Linq.filterNetworkProviders((Iterable<Provider>) returnValue)); providers.add(0, null); Provider selectedProvider = (Provider) getProviders().getSelectedItem(); getProviders().setItems(providers); getProviders().setSelectedItem(selectedProvider); } })); }

Target:
public ImportNetworksModel(SearchableListModel sourceListModel) { this.sourceListModel = sourceListModel; setTitle(ConstantsManager.getInstance().getConstants().importNetworksTitle()); setHashName("import_networks"); UICommand tempVar = new UICommand(CMD_IMPORT, this); tempVar.setTitle(ConstantsManager.getInstance().getConstants().importNetworksButton()); tempVar.setIsDefault(true); getCommands().add(tempVar); UICommand tempVar2 = new UICommand(CMD_CANCEL, this); tempVar2.setTitle(ConstantsManager.getInstance().getConstants().cancel()); tempVar2.setIsCancel(true); getCommands().add(tempVar2); providers.getSelectedItemChangedEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { onProviderChosen(); } }); initProviderList(); }
Source:
public void shouldAddNodeToExplicitIndex() throws Exception { long nodeId; try ( Transaction tx = session.beginTransaction() ) { nodeId = tx.dataWrite().nodeCreate(); ExplicitIndexWrite indexWrite = tx.indexWrite(); indexWrite.nodeAddToExplicitIndex( INDEX_NAME, nodeId, KEY, VALUE ); tx.success(); } try ( org.neo4j.graphdb.Transaction ctx = graphDb.beginTx() ) { IndexHits<Node> hits = graphDb.index().forNodes( INDEX_NAME ).get( KEY, "this is it" ); assertThat( hits.next().getId(), equalTo( nodeId ) ); hits.close(); ctx.success(); } }

Target:
public void shouldAddNodeToExplicitIndex() throws Exception { long nodeId; try ( Transaction tx = session.beginTransaction() ) { nodeId = tx.dataWrite().nodeCreate(); ExplicitIndexWrite indexWrite = tx.indexWrite(); indexWrite.nodeAddToExplicitIndex( INDEX_NAME, nodeId, KEY, VALUE ); tx.success(); } try ( org.neo4j.graphdb.Transaction ctx = graphDb.beginTx() ) { IndexHits<Node> hits = graphDb.index().forNodes( INDEX_NAME ).get( KEY, VALUE ); assertThat( hits.next().getId(), equalTo( nodeId ) ); hits.close(); ctx.success(); } }
Source:
public void getAmbryBlobStorageServiceTest() throws Exception { JSONObject jsonObject = new JSONObject().put("POST", "http://uploadUrl:15158").put("GET", "http://downloadUrl:15158"); Properties properties = new Properties(); properties.setProperty(FrontendConfig.URL_SIGNER_ENDPOINTS, jsonObject.toString()); properties.setProperty("clustermap.cluster.name", "CLuster-Name"); properties.setProperty("clustermap.datacenter.name", "Datacenter-Name"); properties.setProperty("clustermap.host.name", "localhost"); VerifiableProperties verifiableProperties = new VerifiableProperties(properties); AmbryBlobStorageServiceFactory ambryBlobStorageServiceFactory = new AmbryBlobStorageServiceFactory(verifiableProperties, new MockClusterMap(), new MockRestRequestResponseHandler(), new InMemoryRouter(verifiableProperties, new MockClusterMap()), new InMemAccountService(false, true)); BlobStorageService ambryBlobStorageService = ambryBlobStorageServiceFactory.getBlobStorageService(); assertNotNull("No BlobStorageService returned", ambryBlobStorageService); assertEquals("Did not receive an AmbryBlobStorageService instance", AmbryBlobStorageService.class.getCanonicalName(), ambryBlobStorageService.getClass().getCanonicalName()); }

Target:
public void getAmbryBlobStorageServiceTest() throws Exception { JSONObject jsonObject = new JSONObject().put("POST", "http://uploadUrl:15158").put("GET", "http://downloadUrl:15158"); Properties properties = new Properties(); CommonTestUtils.populateRequiredRouterProps(properties); properties.setProperty(FrontendConfig.URL_SIGNER_ENDPOINTS, jsonObject.toString()); properties.setProperty("clustermap.cluster.name", "Cluster-Name"); properties.setProperty("clustermap.datacenter.name", "Datacenter-Name"); properties.setProperty("clustermap.host.name", "localhost"); VerifiableProperties verifiableProperties = new VerifiableProperties(properties); AmbryBlobStorageServiceFactory ambryBlobStorageServiceFactory = new AmbryBlobStorageServiceFactory(verifiableProperties, new MockClusterMap(), new MockRestRequestResponseHandler(), new InMemoryRouter(verifiableProperties, new MockClusterMap()), new InMemAccountService(false, true)); BlobStorageService ambryBlobStorageService = ambryBlobStorageServiceFactory.getBlobStorageService(); assertNotNull("No BlobStorageService returned", ambryBlobStorageService); assertEquals("Did not receive an AmbryBlobStorageService instance", AmbryBlobStorageService.class.getCanonicalName(), ambryBlobStorageService.getClass().getCanonicalName()); }
Source:
public RecordIterator<T> readBatch() throws IOException { final ParquetReaderBatch<T> batch = getCachedEntry(); final long startingRowNum = rowsReturned; if (!nextBatch(batch)) { batch.recycle(); return null; } final RecordIterator<T> records = batch.convertAndGetIterator(startingRowNum); if (recordsToSkip > 0) { skipRecord(records); } return records; }

Target:
public RecordIterator<T> readBatch() throws IOException { final ParquetReaderBatch<T> batch = getCachedEntry(); final long rowsReturnedBefore = rowsReturned; if (!nextBatch(batch)) { batch.recycle(); return null; } final RecordIterator<T> records = batch.convertAndGetIterator(rowsReturnedBefore); skipRecord(records); return records; }
Source:
public Flux<FileRange> listRanges() { return azureFileStorageClient.files().getRangeListWithRestResponseAsync(shareName, filePath, shareSnapshot, null, null, Context.NONE) .flatMapMany(this::convertListRangesResponseToFileRangeInfo); }

Target:
public Flux<FileRange> listRanges() { return azureFileStorageClient.files().getRangeListWithRestResponseAsync(shareName, filePath, snapshot, null, null, Context.NONE) .flatMapMany(this::convertListRangesResponseToFileRangeInfo); }
Source:
public void addLogicalTypeConversion(Conversion<?> conversion) { conversions.put(conversion.getLogicalTypeName(), conversion); Class<?> type = conversion.getConvertedType(); if (conversionsByClass.containsKey(type)) { conversionsByClass.get(type).add(conversion); } else { List<Conversion<?>> conversions = new ArrayList<Conversion<?>>(1); conversions.add(conversion); conversionsByClass.put(type, conversions); } }

Target:
public void addLogicalTypeConversion(Conversion<?> conversion) { conversions.put(conversion.getLogicalTypeName(), conversion); Class<?> type = conversion.getConvertedType(); if (conversionsByClass.containsKey(type)) { conversionsByClass.get(type).put( conversion.getLogicalTypeName(), conversion); } else { Map<String, Conversion<?>> conversions = new LinkedHashMap<String, Conversion<?>>(); conversions.put(conversion.getLogicalTypeName(), conversion); conversionsByClass.put(type, conversions); } }
Source:
public ValidationResult update(Consumer consumer, Entitlement entitlement, Integer change) { ValidationResult result = new ValidationResult(); if (!consumer.getType().isManifest()) { Pool pool = entitlement.getPool(); if (!"yes".equalsIgnoreCase(pool.getProductAttributeValue(Pool.Attributes.MULTI_ENTITLEMENT)) && entitlement.getQuantity() + change > 1) { result.addError(new ValidationError(i18n.tr( EntitlementRulesTranslator.PoolErrorKeys.MULTI_ENTITLEMENT_UNSUPPORTED))); } if (!consumer.isGuest()) { String multiplier = pool.getProductAttributeValue(Product.Attributes.INSTANCE_MULTIPLIER); if (multiplier != null) { int instanceMultiplier = Integer.parseInt(multiplier); if ((entitlement.getQuantity() + change) % instanceMultiplier != 0) { result.addError(new ValidationError(i18n.tr( EntitlementRulesTranslator.PoolErrorKeys.QUANTITY_MISMATCH ))); } } } } finishValidation(result, entitlement.getPool(), change); return result; }

Target:
public ValidationResult update(Consumer consumer, Entitlement entitlement, Integer change) { ValidationResult result = new ValidationResult(); if (!consumer.getType().isManifest()) { Pool pool = entitlement.getPool(); if (!"yes".equalsIgnoreCase(pool.getProductAttributeValue(Pool.Attributes.MULTI_ENTITLEMENT)) && entitlement.getQuantity() + change > 1) { result.addError(new ValidationError( EntitlementRulesTranslator.PoolErrorKeys.MULTI_ENTITLEMENT_UNSUPPORTED)); } if (!consumer.isGuest()) { String multiplier = pool.getProductAttributeValue(Product.Attributes.INSTANCE_MULTIPLIER); if (multiplier != null) { int instanceMultiplier = Integer.parseInt(multiplier); if ((entitlement.getQuantity() + change) % instanceMultiplier != 0) { result.addError(new ValidationError( EntitlementRulesTranslator.PoolErrorKeys.QUANTITY_MISMATCH )); } } } } finishValidation(result, entitlement.getPool(), change); return result; }
Source:
public final Statement apply( final Statement base, final Description description ) { return new Statement() { @Override public void evaluate() throws Throwable { try { base.evaluate(); } catch (final IllegalStateException ex) { Logger.warn( base, String.format( "Test %s skipped due to IllegalStateException", description ) ); Assume.assumeTrue(false); } } }; }

Target:
public final Statement apply( final Statement base, final Description description ) { return new Statement() { @Override public void evaluate() throws Throwable { try { base.evaluate(); } catch (final BindException ignored) { Logger.warn( base, String.format( "Test %s skipped due to no available ports", description ) ); Assume.assumeTrue(false); } } }; }
Source:
public List<String> getValues() { return values.stream().map(String::new).collect(Collectors.toList()); }

Target:
public List<String> getValues() { return values.stream() .map(b -> new String(b, StandardCharsets.US_ASCII)) .collect(Collectors.toList()); }
Source:
public boolean execute(final CompileContext context) { Project project = context.getProject(); if (ErlangCompilerSettings.getInstance(project).isUseRebarCompilerEnabled()) { return true; } LOG.info("Prepare build order for project "+project.getName()); File projectSystemDirectory = BuildManager.getInstance().getProjectSystemDirectory(project); if (projectSystemDirectory == null) { addPrepareDependenciesFailedMessage(context); return true; } LOG.debug("Run action for preparing build order"); ErlangProjectBuildOrder projectBuildOrder = ApplicationManager.getApplication().runReadAction(new Computable<ErlangProjectBuildOrder>() { @Nullable @Override public ErlangProjectBuildOrder compute() { return getProjectBuildOrder(context); } }); if (projectBuildOrder == null) { return false; } try { LOG.debug("Serialize build order"); Document serializedDocument = new Document(XmlSerializer.serialize(projectBuildOrder, new SkipDefaultValuesSerializationFilters())); File file = new File(projectSystemDirectory, ErlangPrepareDependenciesBuilder.DEPENDENCIES_TREE_FILE_PATH); file.getParentFile().mkdirs(); LOG.debug("Write build order to "+file.getAbsolutePath()); JDOMUtil.writeDocument(serializedDocument, file, SystemProperties.getLineSeparator()); } catch (XmlSerializationException e) { LOG.warn("Can't serialize build order object."); LOG.debug(e); addPrepareDependenciesFailedMessage(context); return true; } catch (IOException e) { LOG.warn("Some I/O errors occurred while writing build orders to file"); LOG.debug(e); addPrepareDependenciesFailedMessage(context); return true; } return true; }

Target:
public boolean execute(final CompileContext context) { Project project = context.getProject(); if (ErlangCompilerSettings.getInstance(project).isUseRebarCompilerEnabled()) { return true; } LOG.info("Prepare build order for project " + project.getName()); File projectSystemDirectory = BuildManager.getInstance().getProjectSystemDirectory(project); if (projectSystemDirectory == null) { addPrepareDependenciesFailedMessage(context); return true; } ErlangProjectBuildOrder projectBuildOrder = ApplicationManager.getApplication().runReadAction(new Computable<ErlangProjectBuildOrder>() { @Nullable @Override public ErlangProjectBuildOrder compute() { return getProjectBuildOrder(context); } }); if (projectBuildOrder == null) { return false; } writeBuildOrder(context, projectSystemDirectory, projectBuildOrder); return true; }
Source:
protected void validateMetadata(BlobMetadata metadata) throws IOException { checkExtendedAttributesSupport(); super.validateMetadata(metadata); }

Target:
protected void validateMetadata(BlobMetadata metadata) throws IOException { if (!isMacOSX()) { super.validateMetadata(metadata); } }
Source:
public ToolUseHandler getItemHandler() { return (e, tool, fortune, drops) -> { if (SlimefunTag.SMELTERS_PICKAXE_BLOCKS.isTagged(e.getBlock().getType()) && !BlockStorage.hasBlockInfo(e.getBlock())) { Collection<ItemStack> blockDrops = e.getBlock().getDrops(getItem()); for (ItemStack drop : blockDrops) { if (drop != null && drop.getType() != Material.AIR) { smelt(e.getBlock(), drop, fortune); drops.add(drop); } } damageItem(e.getPlayer(), tool); } }; }

Target:
public ToolUseHandler getItemHandler() { return (e, tool, fortune, drops) -> { Block b = e.getBlock(); if (SlimefunTag.SMELTERS_PICKAXE_BLOCKS.isTagged(b.getType()) && !BlockStorage.hasBlockInfo(b)) { Collection<ItemStack> blockDrops = b.getDrops(getItem()); for (ItemStack drop : blockDrops) { if (drop != null && drop.getType() != Material.AIR) { smelt(b, drop, fortune); drops.add(drop); } } damageItem(e.getPlayer(), tool); } }; }
Source:
public int execute() { try { SamInputResource resource = initInputResource(); @Cleanup final SamReader reader = SamReaderFactory.makeDefault().open(resource); SAMFileHeader header = reader.getFileHeader(); QueryInterval[] intervals = QueryHandler.parseQueryStrings(header, query); String outputFileName = generateFileOutputName(); @Cleanup final SAMFileWriter writer = initFileWriter(header, outputFileName); if (!headerOnly) { SAMRecordIterator iterator = reader.query(intervals, containedOnly); while (iterator.hasNext()) { val record = iterator.next(); writer.addAlignment(record); } } } catch (IOException e) { throw new RuntimeException(e); } return SUCCESS_STATUS; }

Target:
public int execute() { try { SamInputResource resource = createInputResource(); @Cleanup val reader = SamReaderFactory.makeDefault().open(resource); SAMFileHeader header = reader.getFileHeader(); QueryInterval[] intervals = QueryHandler.parseQueryStrings(header, query); val outputFileName = generateFileOutputName(); @Cleanup val writer = createFileWriter(header, outputFileName); if (!headerOnly) { SAMRecordIterator iterator = reader.query(intervals, containedOnly); while (iterator.hasNext()) { val record = iterator.next(); writer.addAlignment(record); } } } catch (IOException e) { throw new RuntimeException(e); } return SUCCESS_STATUS; }
Source:
public void unsubscribe_synchronous() throws InterruptedException { SyncUser user = UserFactory.createUniqueUser(Constants.AUTH_URL); createServerData(user, Constants.SYNC_SERVER_URL); final SyncConfiguration partialSyncConfig = configurationFactory.createSyncConfigurationBuilder(user, Constants.SYNC_SERVER_URL) .name("partialSync") .initialData(r -> { r.where(PartialSyncObjectA.class).greaterThan("number", 5).subscribe("my-sub"); }) .waitForInitialRemoteData() .addModule(new PartialSyncModule()) .build(); Realm realm = Realm.getInstance(partialSyncConfig); looperThread.closeAfterTest(realm); realm.executeTransaction(r -> { Subscription sub = r.getSubscription("my-sub"); assertEquals(Subscription.State.ACTIVE, sub.getState()); sub.unsubscribe(); }); RealmResults<PartialSyncObjectA> results = realm.where(PartialSyncObjectA.class).findAll(); results.addChangeListener((objects, changeSet) -> { if (objects.isEmpty()) { looperThread.testComplete(); } }); }

Target:
public void unsubscribe_synchronous() throws InterruptedException { SyncUser user = UserFactory.createUniqueUser(Constants.AUTH_URL); createServerData(user, Constants.SYNC_SERVER_URL); final SyncConfiguration partialSyncConfig = configurationFactory.createSyncConfigurationBuilder(user, Constants.SYNC_SERVER_URL) .name("partialSync") .initialData(r -> { r.where(PartialSyncObjectA.class).greaterThan("number", 5).subscribe("my-sub"); }) .waitForInitialRemoteData() .addModule(new PartialSyncModule()) .build(); Realm realm = Realm.getInstance(partialSyncConfig); looperThread.closeAfterTest(realm); realm.executeTransaction(r -> { Subscription sub = r.getSubscription("my-sub"); assertEquals(Subscription.State.ACTIVE, sub.getState()); sub.unsubscribe(); assertEquals(Subscription.State.INVALIDATED, sub.getState()); }); RealmResults<PartialSyncObjectA> results = realm.where(PartialSyncObjectA.class).findAll(); results.addChangeListener((objects, changeSet) -> { if (objects.isEmpty()) { looperThread.testComplete(); } }); }
Source:
public void load() { ScenarioSimulationModel model = service.load(path); assertEquals(Type.DMN, model.getSimulation().getSimulationDescriptor().getType()); verify(dmnTypeServiceMock, times(1)).initializeNameAndNamespace(any(), any(), anyString()); when(dmnTypeServiceMock.initializeNameAndNamespace(any(), any(), anyString())).thenThrow(new ImpossibleToFindDMNException("")); try { service.load(path); } catch (Exception e) { fail(); } }

Target:
public void load() { ScenarioSimulationModel model = service.load(path); assertEquals(Type.DMN, model.getSimulation().getSimulationDescriptor().getType()); verify(dmnTypeServiceMock, times(1)).initializeNameAndNamespace(any(), any(), anyString()); doThrow(new ImpossibleToFindDMNException("")).when(dmnTypeServiceMock).initializeNameAndNamespace(any(), any(), anyString()); try { service.load(path); } catch (Exception e) { fail(); } }