auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean isChimericReadPair(final QuerySortedReadPairIteratorUtil.ReadPair readPair, final int minimumMappingQuality) { return (!readPair.read1.getReadUnmappedFlag() && !readPair.read2.getReadUnmappedFlag() && readPair.read1.getMappingQuality() >= minimumMappingQuality && readPair.read2.getMappingQuality() >= minimumMappingQuality && (Math.abs(readPair.read1.getInferredInsertSize()) > MAX_INSERT_SIZE || !readPair.read1.getReferenceIndex().equals(readPair.read2.getReferenceIndex()) || SamPairUtil.getPairOrientation(readPair.read1) != SamPairUtil.PairOrientation.FR || readPair.read1.getAttribute("SA") != null)); }

Target:
private boolean isChimericReadPair(final QuerySortedReadPairIteratorUtil.ReadPair readPair, final int minimumMappingQuality) { return (readPair.read1.getMappingQuality() >= minimumMappingQuality && readPair.read2.getMappingQuality() >= minimumMappingQuality && ChimeraUtil.isChimeric(readPair.read1, readPair.read2, ChimeraUtil.DEFAULT_INSERT_SIZE_LIMIT, ChimeraUtil.DEFAULT_EXPECTED_ORIENTATIONS)); }
Source:
public static void cleanUp() throws IOException, SQLException { logger.info("Running with Hibernate " + org.hibernate.Version.getVersionString()); TestsUtil.clearSchema(); ScriptsBase sb = new ScriptsBase(); sb.executeScriptRunner(DB_DDL_SCRIPTS_RESOURCE_PATH, false); }

Target:
public static void cleanUp() throws IOException, SQLException { logger.info("Running with Hibernate " + org.hibernate.Version.getVersionString()); TestsUtil.clearSchema(); executeScriptRunner(DB_DDL_SCRIPTS_RESOURCE_PATH, false); }
Source:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); connectionServiceLocator = new ServiceLocator<ConnectionService>( this.getActivity(), ConnectionService.class, ConnectionServiceBinder.class); connectionServiceLocator.setOnBindListener(new ServiceLocator.IOnBindListener() { @Override public void onServiceBound() { setDisconnectDisbandVisibility(); } }); NetworkFragment.this.adapter = new UserListAdapter(getActivity(), new UserList(), false ); userListServiceLocator = new ServiceLocator<UserListService>( this.getActivity(), UserListService.class, UserListServiceBinder.class); userListServiceLocator.setOnBindListener(new ServiceLocator.IOnBindListener() { @Override public void onServiceBound() { NetworkFragment.this.adapter.updateUsers(getUserListFromService()); } }); registerReceivers(); }

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); connectionServiceLocator = new ServiceLocator<ConnectionService>( this.getActivity(), ConnectionService.class, ConnectionServiceBinder.class); connectionServiceLocator.setOnBindListener(new ServiceLocator.IOnBindListener() { @Override public void onServiceBound() { setDisconnectDisbandVisibility(); } }); adapter = new UserListAdapter(getActivity(), new UserList(), false); userListServiceLocator = new ServiceLocator<UserListService>( this.getActivity(), UserListService.class, UserListServiceBinder.class); userListServiceLocator.setOnBindListener(new ServiceLocator.IOnBindListener() { @Override public void onServiceBound() { NetworkFragment.this.adapter.updateUsers(getUserListFromService()); } }); registerReceivers(); }
Source:
public static String getIp() { if (null != cachedIpAddress) { return cachedIpAddress; } NetworkInterface networkInterface = findNetworkInterface(); if (networkInterface != null) { Enumeration<InetAddress> ipAddresses = networkInterface.getInetAddresses(); while (ipAddresses.hasMoreElements()) { InetAddress ipAddress = ipAddresses.nextElement(); if (isValidAddress(ipAddress)) { cachedIpAddress = ipAddress.getHostAddress(); return cachedIpAddress; } } } return null; }

Target:
public static String getIp() { if (null != cachedIpAddress) { return cachedIpAddress; } NetworkInterface networkInterface = findNetworkInterface(); if (null != networkInterface) { Enumeration<InetAddress> ipAddresses = networkInterface.getInetAddresses(); while (ipAddresses.hasMoreElements()) { InetAddress ipAddress = ipAddresses.nextElement(); if (isValidAddress(ipAddress)) { cachedIpAddress = ipAddress.getHostAddress(); return cachedIpAddress; } } } throw new HostException("ip is null"); }
Source:
private Geometry onlyPolygon(Geometry result) { if ((result instanceof Polygon) || (result instanceof MultiPolygon)) return result; List polys = com.vividsolutions.jts.geom.util.PolygonExtracter.getPolygons(result); if (polys.size() == 0) return null; if (polys.size() == 1) return (Polygon) polys.get(0); return new MultiPolygon((Polygon[]) polys.toArray(new Polygon[polys.size()]), result.getFactory()); }

Target:
private Geometry onlyPolygon(Geometry result) { if ((result instanceof Polygon) || (result instanceof MultiPolygon)) { return result; } List polys = com.vividsolutions.jts.geom.util.PolygonExtracter.getPolygons(result); if (polys.size() == 0) { return null; } if (polys.size() == 1) { return (Polygon) polys.get(0); } return new MultiPolygon((Polygon[]) polys.toArray(new Polygon[polys.size()]), result.getFactory()); }
Source:
public boolean deleteEntityInTable(String tableName, ODataEntry entity) { String keyValue = entity.getValue(DOCUMENT_ID); WriteResult delete = jongo.getCollection(tableName).remove(new ObjectId(keyValue)); return delete.wasAcknowledged(); }

Target:
public boolean deleteEntityInTable(String tableName, ODataEntry entity) throws ODataServiceFault { String documentId = entity.getValue(DOCUMENT_ID); WriteResult delete = jongo.getCollection(tableName).remove(new ObjectId(documentId)); int wasDeleted = delete.getN(); if (wasDeleted == 1) { return delete.wasAcknowledged(); } else { throw new ODataServiceFault("Document ID: " + documentId + " does not exist in " + "collection: " + tableName + "."); } }
Source:
protected String getServiceEventActionCodeResponder() { return DocSubmissionAuditTransformsConstants.EVENT_ACTION_CODE_RECIPIENT; }

Target:
protected String getServiceEventActionCodeResponder() { return DocSubmissionAuditTransformsConstants.EVENT_ACTION_CODE_SOURCE; }
Source:
public void close() throws IOException { if (s3Object != null) { s3Object.close(); } }

Target:
public void close() throws IOException { super.close(); if (s3Object != null) { s3Object.close(); } }
Source:
public void testCreateWithBlockDeviceMapping() { String serverId = null; String flavorRef = "performance1-2"; String imageRef = "3ab30cc6-c503-41d3-8a37-106fda7848a7"; for (String regionId : regions) { ServerApi serverApi = api.getServerApi(regionId); try { BlockDeviceMapping blockDeviceMappings = BlockDeviceMapping.builder() .uuid(imageRef).sourceType("image").destinationType("volume") .volumeSize(100).bootIndex(0).build(); CreateServerOptions options = CreateServerOptions.Builder .blockDeviceMappings(ImmutableSet.of(blockDeviceMappings)); ServerCreated server = serverApi.create(hostName, "", flavorRef, options); serverId = server.getId(); awaitActive(serverApi).apply(server.getId()); Server serverCheck = serverApi.get(serverId); assertEquals(serverCheck.getStatus(), ACTIVE); } finally { if (serverId != null) { serverApi.delete(serverId); } } } }

Target:
public void testCreateWithBlockDeviceMapping() { String serverId = null; String flavorRef = "performance1-2"; String imageRef = "3ab30cc6-c503-41d3-8a37-106fda7848a7"; for (String regionId : regions) { ServerApi serverApi = api.getServerApi(regionId); ExtensionApi extensionApi = api.getExtensionApi(regionId); if (extensionApi.get("os-block-device-mapping-v2-boot") != null) { try { BlockDeviceMapping blockDeviceMappings = BlockDeviceMapping.builder() .uuid(imageRef).sourceType("image").destinationType("volume") .volumeSize(100).bootIndex(0).build(); CreateServerOptions options = CreateServerOptions.Builder .blockDeviceMappings(ImmutableSet.of(blockDeviceMappings)); ServerCreated server = serverApi.create(hostName, "", flavorRef, options); serverId = server.getId(); awaitActive(serverApi).apply(server.getId()); Server serverCheck = serverApi.get(serverId); assertEquals(serverCheck.getStatus(), ACTIVE); } finally { if (serverId != null) { serverApi.delete(serverId); } } } } }
Source:
protected Control createContents(Composite parent) { Composite displayArea = new Composite(parent, SWT.NONE); GridLayoutFactory.fillDefaults().applyTo(displayArea); GridDataFactory.fillDefaults().applyTo(displayArea); final Repository repo = (Repository) getElement() .getAdapter(Repository.class); if (repo == null) return displayArea; StoredConfig config = repo.getConfig(); if (config instanceof FileBasedConfig) { File configFile = ((FileBasedConfig) config).getFile(); config = new FileBasedConfig(configFile, repo.getFS()); config.addChangeListener(new ConfigChangedListener() { public void onConfigChanged(ConfigChangedEvent event) { repo.getListenerList().dispatch(new ConfigChangedEvent()); } }); } else { config = repo.getConfig(); } editor = new ConfigurationEditorComponent(displayArea, config, true, false) { @Override protected void setErrorMessage(String message) { RepositoryPropertyPage.this.setErrorMessage(message); } }; editor.createContents(); return displayArea; }

Target:
protected Control createContents(Composite parent) { Composite displayArea = new Composite(parent, SWT.NONE); GridLayoutFactory.fillDefaults().applyTo(displayArea); GridDataFactory.fillDefaults().applyTo(displayArea); final Repository repo = (Repository) getElement() .getAdapter(Repository.class); if (repo == null) return displayArea; StoredConfig config = repo.getConfig(); if (config instanceof FileBasedConfig) { File configFile = ((FileBasedConfig) config).getFile(); config = new FileBasedConfig(configFile, repo.getFS()); config.addChangeListener(new ConfigChangedListener() { public void onConfigChanged(ConfigChangedEvent event) { repo.fireEvent(new ConfigChangedEvent()); } }); } editor = new ConfigurationEditorComponent(displayArea, config, true, false) { @Override protected void setErrorMessage(String message) { RepositoryPropertyPage.this.setErrorMessage(message); } }; editor.createContents(); return displayArea; }
Source:
public final String getSecurityUncompressed() throws NitfFormatException { if (getSecurityFieldCompression().equals("GZIP")) { byte[] security = getSecurity(); StringBuilder sb = new StringBuilder(); try (ByteArrayInputStream bis = new ByteArrayInputStream(security); GZIPInputStream gis = new GZIPInputStream(bis); BufferedReader br = new BufferedReader(new InputStreamReader(gis, StandardCharsets.ISO_8859_1))) { String line; while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { throw new NitfFormatException("Could not uncompress SECURITY field." + e.getLocalizedMessage()); } return sb.toString(); } return getFieldValue("SECURITY"); }

Target:
public final String getSecurityUncompressed() throws NitfFormatException { if (getSecurityFieldCompression().equals("GZIP")) { byte[] security = getSecurity(); StringBuilder sb = new StringBuilder(); try (ByteArrayInputStream bis = new ByteArrayInputStream(security); GZIPInputStream gis = new GZIPInputStream(bis); BufferedReader br = new BufferedReader(new InputStreamReader(gis, StandardCharsets.UTF_8))) { String line; while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { throw new NitfFormatException("Could not uncompress SECURITY field." + e.getLocalizedMessage()); } return sb.toString(); } return new String(getSecurity(), StandardCharsets.UTF_8); }
Source:
public void close() { coordinatorStreamStore.close(); }

Target:
public void close() { }
Source:
public Response register(Action action) { validateParameters(action, "cluster.id|name"); BackendVnicProfileHelper.validateVnicMappings(action, this); ImportVmTemplateFromConfParameters params = new ImportVmTemplateFromConfParameters(); ExternalRegistrationConfigurationMapper.mapFromModel(action.getRegistrationConfiguration(), params); params.setContainerId(guid); params.setStorageDomainId(parent.getStorageDomainId()); params.setClusterId(getClusterId(action)); params.setImagesExistOnTargetStorageDomain(true); params.setExternalVnicProfileMappings(ExternalVnicProfileMappingMapper.mapFromModel(action.getVnicProfileMappings())); if (action.isSetClone()) { params.setImportAsNewEntity(action.isClone()); if (action.isSetVm() && action.getTemplate().isSetName()) { params.getVmTemplate().setName(action.getTemplate().getName()); } } if (action.isSetAllowPartialImport()) { params.setAllowPartialImport(action.isAllowPartialImport()); } return doAction(ActionType.ImportVmTemplateFromConfiguration, params, action); }

Target:
public Response register(Action action) { BackendVnicProfileHelper.validateVnicMappings(action, this); ImportVmTemplateFromConfParameters params = new ImportVmTemplateFromConfParameters(); ExternalRegistrationConfigurationMapper.mapFromModel(action.getRegistrationConfiguration(), params); params.setContainerId(guid); params.setStorageDomainId(parent.getStorageDomainId()); if (action.isSetCluster()) { params.setClusterId(getClusterId(action)); } params.setImagesExistOnTargetStorageDomain(true); params.setExternalVnicProfileMappings(ExternalVnicProfileMappingMapper.mapFromModel(action.getVnicProfileMappings())); if (action.isSetClone()) { params.setImportAsNewEntity(action.isClone()); if (action.isSetVm() && action.getTemplate().isSetName()) { params.getVmTemplate().setName(action.getTemplate().getName()); } } if (action.isSetAllowPartialImport()) { params.setAllowPartialImport(action.isAllowPartialImport()); } return doAction(ActionType.ImportVmTemplateFromConfiguration, params, action); }
Source:
public void addPamAuthentication(UserEntity userEntity, String userName, boolean persist) throws AmbariException { addAuthentication(userEntity, UserAuthenticationType.PAM, userName, new Validator() { @Override public void validate(UserEntity userEntity, String key) throws AmbariException { List<UserAuthenticationEntity> authenticationEntities = userEntity.getAuthenticationEntities(); for (UserAuthenticationEntity entity : authenticationEntities) { if (entity.getAuthenticationType() == UserAuthenticationType.PAM) { throw new AmbariException("The authentication type already exists for this user"); } } } }, persist); }

Target:
public void addPamAuthentication(UserEntity userEntity, String userName, boolean persist) throws AmbariException { addAuthentication(userEntity, UserAuthenticationType.PAM, userName, (user, key) -> { List<UserAuthenticationEntity> authenticationEntities = user.getAuthenticationEntities(); for (UserAuthenticationEntity entity : authenticationEntities) { if (entity.getAuthenticationType() == UserAuthenticationType.PAM) { throw new AmbariException("The authentication type already exists for this user"); } } }, persist); }
Source:
public <R, X extends Exception> R withHandle(HandleCallback<R, X> callback) throws X { if (threadHandle.get() != null) { return callback.withHandle(threadHandle.get()); } try (Handle h = this.open()) { threadHandle.set(h); return callback.withHandle(h); } finally { threadHandle.remove(); } }

Target:
public <R, X extends Exception> R withHandle(HandleCallback<R, X> callback) throws X { if (threadHandleSupplier.get() != null) { return callback.withHandle(threadHandleSupplier.get().getHandle()); } try (Handle h = this.open()) { threadHandleSupplier.set(new ConstantHandleSupplier(h)); return callback.withHandle(h); } finally { threadHandleSupplier.remove(); } }
Source:
public void selectProduct(String nameToken) { String className = $("a[href=#" + nameToken + "]", productHead).attr("data-resource"); String productSelected; switch(className){ case "gwtp": productSelected = pageProductResources.style().gwtp(); break; case "jukito": productSelected = pageProductResources.style().jukito(); break; case "gae": default: productSelected = pageProductResources.style().gae(); break; } $(productHead).find("a").removeClass(pageProductResources.style().active()); $("a[href=#" + nameToken + "]", productHead).addClass(pageProductResources.style().active()); $(productHead).removeClass(); $(productHead).addClass(headClassNames); $(productHead).addClass(productSelected); }

Target:
public void selectProduct(String nameToken) { String className = $("a[href=#" + nameToken + "]", productHead).attr("data-style"); $(productHead).find("a").removeClass(pageProductResources.style().active()); $("a[href=#" + nameToken + "]", productHead).addClass(pageProductResources.style().active()); $(productHead).removeClass(); $(productHead).addClass(headClassNames); $(productHead).addClass(className); }
Source:
public ArrayList<Pair<String, QueryMetric>> getRunningQueries() { ArrayList<Pair<String, QueryMetric>> runningQueriesList = new ArrayList<Pair<String, QueryMetric>>(); lock.lock(); ArrayList<String> queryKeys = new ArrayList<String>(); queryKeys.addAll(runningQueries.keySet()); try { for (String key : queryKeys) { runningQueriesList.add(new Pair<String, QueryMetric>(key, runningQueries.get(key).getFirst())); } } finally { lock.unlock(); } return runningQueriesList; }

Target:
public ArrayList<Pair<String, QueryMetric>> getRunningQueries() { ArrayList<Pair<String, QueryMetric>> runningQueriesList = new ArrayList<Pair<String, QueryMetric>>(); lock.lock(); try { for (String key : runningQueries.keySet()) { runningQueriesList.add(new Pair<String, QueryMetric>(key, runningQueries.get(key).getFirst())); } } finally { lock.unlock(); } return runningQueriesList; }
Source:
public void read(CorfuPayloadMsg<ReadRequest> msg, ChannelHandlerContext ctx, IServerRouter r) { long address = msg.getPayload().getAddress(); boolean cacheable = msg.getPayload().isCacheReadResult(); log.trace("read: {}, cacheable: {}", msg.getPayload().getAddress(), cacheable); Lock lock = resetLock.readLock(); lock.lock(); try { if (msg.getEpoch() != serverContext.getServerEpoch()) { throw new WrongEpochException(serverContext.getServerEpoch()); } ReadResponse rr = new ReadResponse(); try { ILogData logData = dataCache.get(address, cacheable); if (logData == null) { rr.put(address, LogData.getEmpty(address)); } else { rr.put(address, (LogData) logData); } r.sendResponse(ctx, msg, CorfuMsgType.READ_RESPONSE.payloadMsg(rr)); } catch (DataCorruptionException e) { log.error("Data corruption exception while reading address {}", address, e); r.sendResponse(ctx, msg, CorfuMsgType.ERROR_DATA_CORRUPTION.payloadMsg(address)); } } finally { lock.unlock(); } }

Target:
public void read(CorfuPayloadMsg<ReadRequest> msg, ChannelHandlerContext ctx, IServerRouter r) { boolean cacheable = msg.getPayload().isCacheReadResult(); if (log.isTraceEnabled()) { log.trace("read: {}, cacheable: {}", msg.getPayload().getAddresses(), cacheable); } ReadResponse rr = new ReadResponse(); for (long address : msg.getPayload().getAddresses()) { try { ILogData logData = dataCache.get(address, cacheable); if (logData == null) { rr.put(address, LogData.getEmpty(address)); } else { rr.put(address, (LogData) logData); } } catch (DataCorruptionException e) { log.error( "Data corruption exception while reading addresses {}", msg.getPayload().getAddresses(), e); r.sendResponse(ctx, msg, CorfuMsgType.ERROR_DATA_CORRUPTION.payloadMsg(address)); return; } } r.sendResponse(ctx, msg, CorfuMsgType.READ_RESPONSE.payloadMsg(rr)); }
Source:
public @Nullable Integer resolve(ITmfEvent event) { Integer cpu = TmfTraceUtils.resolveIntEventAspectOfClassForEvent(event.getTrace(), TmfCpuAspect.class, event); if (cpu == null) { return null; } TidAnalysisModule analysis = TmfTraceUtils.getAnalysisModuleOfClass(event.getTrace(), TidAnalysisModule.class, TidAnalysisModule.ID); if (analysis == null) { return null; } Integer tid = analysis.getThreadOnCpuAtTime(cpu, event.getTimestamp().toNanos()); if (tid != null) { return tid; } return null; }

Target:
public @Nullable Integer resolve(ITmfEvent event) { Integer cpu = TmfTraceUtils.resolveIntEventAspectOfClassForEvent(event.getTrace(), TmfCpuAspect.class, event); if (cpu == null) { return null; } TidAnalysisModule analysis = TmfTraceUtils.getAnalysisModuleOfClass(event.getTrace(), TidAnalysisModule.class, TidAnalysisModule.ID); if (analysis == null) { return null; } return analysis.getThreadOnCpuAtTime(cpu, event.getTimestamp().toNanos()); }
Source:
public short undeleteBlob(BlobId blobId, short lifeVersion, CloudUpdateValidator cloudUpdateValidator) throws CloudStorageException { Map<String, Object> updateFields = new HashMap<>(); updateFields.put(CloudBlobMetadata.FIELD_LIFE_VERSION, lifeVersion); updateFields.put(CloudBlobMetadata.FIELD_DELETION_TIME, Utils.Infinite_Time); UpdateResponse updateResponse = updateBlobMetadata(blobId, updateFields, cloudUpdateValidator); return updateResponse.metadata.containsKey(CloudBlobMetadata.FIELD_LIFE_VERSION) ? Short.parseShort( updateResponse.metadata.get(CloudBlobMetadata.FIELD_LIFE_VERSION)) : 0; }

Target:
public short undeleteBlob(BlobId blobId, short lifeVersion, CloudUpdateValidator cloudUpdateValidator) throws CloudStorageException { Map<String, Object> updateFields = new HashMap<>(); updateFields.put(CloudBlobMetadata.FIELD_LIFE_VERSION, lifeVersion); updateFields.put(CloudBlobMetadata.FIELD_DELETION_TIME, Utils.Infinite_Time); UpdateResponse updateResponse = updateBlobMetadata(blobId, updateFields, cloudUpdateValidator); return Short.parseShort(updateResponse.metadata.getOrDefault(CloudBlobMetadata.FIELD_LIFE_VERSION, "0")); }
Source:
public Tuple getNext() throws IOException { try { if (!reader.nextKeyValue()) return null; List<Object> tuple = tuple0; if (readKey) { if (readValue) { tuple = tuple2; tuple.set(0, getCurrentKeyObject()); tuple.set(1, getCurrentValueObject()); } else { tuple = tuple1; tuple.set(0, getCurrentKeyObject()); } } else if (readValue) { tuple = tuple1; tuple.set(0, getCurrentValueObject()); } return tupleFactory.newTupleNoCopy(tuple); } catch (EOFException e) { if (valueArguments.hasOption(SKIP_EOF_ERRORS_PARAM)) { LOG.warn("EOFException encountered while reading input", e); counterHelper_.incrCounter(SequenceFileLoaderCounters.EOFError, 1L); } else { throw e; } } catch (InterruptedException e) { throw new ExecException("Error while reading input", 6018, PigException.REMOTE_ENVIRONMENT, e); } return null; }

Target:
public Tuple getNext() throws IOException { try { if (!reader.nextKeyValue()) return null; List<Object> tuple = tuple0; if (readKey) { if (readValue) { tuple = tuple2; tuple.set(0, getCurrentKeyObject()); tuple.set(1, getCurrentValueObject()); } else { tuple = tuple1; tuple.set(0, getCurrentKeyObject()); } } else if (readValue) { tuple = tuple1; tuple.set(0, getCurrentValueObject()); } return tupleFactory.newTupleNoCopy(tuple); } catch (EOFException e) { if (otherArguments.hasOption(SKIP_EOF_ERRORS_PARAM)) { LOG.warn("EOFException encountered while reading input", e); counterHelper_.incrCounter(SequenceFileLoaderCounters.EOFError, 1L); } else { throw e; } } catch (InterruptedException e) { throw new ExecException("Error while reading input", 6018, PigException.REMOTE_ENVIRONMENT, e); } return null; }
Source:
public MarshallableEntry next() { try { while (hasNext()) { if (file < 0) { file = iterator.next(); handle = fileProvider.getFile(file); } for (; ; ) { EntryHeader header = EntryRecord.readOldEntryHeader(handle, offset); if (header == null) { handle.close(); file = -1; break; } if (header.valueLength() > 0) { byte[] serializedKey = EntryRecord.readKey(handle, header, offset); byte[] serializedValue = EntryRecord.readValue(handle, header, offset); offset += header.totalLength(); if (EntryRecord.readOldEntryHeader(handle, offset) == null) { handle.close(); file = -1; } return entryFactory.create(new ByteBufferImpl(serializedKey), new ByteBufferImpl(serializedValue)); } offset += header.totalLength(); } } throw new NoSuchElementException(); } catch (Exception e) { throw new CacheException(e); } }

Target:
public MarshallableEntry next() { try { while (hasNext()) { if (file < 0) { file = iterator.next(); handle = fileProvider.getFile(file); } for (; ; ) { EntryHeader header = reader.read(handle, offset); if (header == null) { handle.close(); file = -1; break; } if (header.valueLength() > 0) { byte[] serializedKey = EntryRecord.readKey(handle, header, offset); byte[] serializedValue = EntryRecord.readValue(handle, header, offset); offset += header.totalLength(); if (reader.read(handle, offset) == null) { handle.close(); file = -1; } return entryFactory.create(ByteBufferImpl.create(serializedKey), ByteBufferImpl.create(serializedValue)); } offset += header.totalLength(); } } throw new NoSuchElementException(); } catch (Exception e) { throw new CacheException(e); } }
Source:
public static String generateHeaderFileName(String fileNameBase) { return StringUtils.safeFormat("%s_header", fileNameBase); }

Target:
public static String generateHeaderFileName(String fileNameBase) { return StringUtils.format("%s_header", fileNameBase); }
Source:
private Object doWithOutputStream(OutputStreamFunction f) { if (cacheOutputStream == null) { return null; } try { f.apply(cacheOutputStream); } catch (IOException t) { try { cacheOutputStream.close(); } catch (IOException e) { } cacheOutputStream = null; } return null; }

Target:
private Object doWithOutputStream(OutputStreamFunction f) { if (cacheOutputStream == null) { return null; } try { f.apply(cacheOutputStream); } catch (IOException t) { logger.error(String.format("Failed to operate with additional artifact stream: coordinates-[%s]", coordinates), t); try { cacheOutputStream.close(); } catch (IOException e) { } cacheOutputStream = null; } return null; }
Source:
private void populateAuthnReqDTO(HttpServletRequest req, SAMLSSOAuthnReqDTO authnReqDTO, SAMLSSOSessionDTO sessionDTO, AuthenticationResult authResult) throws UserStoreException, IdentityException { authnReqDTO.setAssertionConsumerURL(sessionDTO.getAssertionConsumerURL()); authnReqDTO.setId(sessionDTO.getRequestID()); authnReqDTO.setIssuer(sessionDTO.getIssuer()); authnReqDTO.setSubject(sessionDTO.getSubject()); authnReqDTO.setRpSessionId(sessionDTO.getRelyingPartySessionId()); authnReqDTO.setRequestMessageString(sessionDTO.getRequestMessageString()); authnReqDTO.setQueryString(sessionDTO.getHttpQueryString()); authnReqDTO.setDestination(sessionDTO.getDestination()); authnReqDTO.setUser(authResult.getSubject()); authnReqDTO.setIdPInitSSOEnabled(sessionDTO.isIdPInitSSO()); authnReqDTO.setClaimMapping(authResult.getClaimMapping()); authnReqDTO.setTenantDomain(sessionDTO.getTenantDomain()); authnReqDTO.setIdPInitSLOEnabled(sessionDTO.isIdPInitSLO()); if (StringUtils.isNotBlank(sessionDTO.getAttributeConsumingServiceIndex())) { authnReqDTO.setAttributeConsumingServiceIndex(Integer.parseInt(sessionDTO.getAttributeConsumingServiceIndex())); } SAMLSSOUtil.setIsSaaSApplication(authResult.isSaaSApp()); SAMLSSOUtil.setUserTenantDomain(authResult.getSubject().getTenantDomain()); }

Target:
private void populateAuthnReqDTO(HttpServletRequest req, SAMLSSOAuthnReqDTO authnReqDTO, SAMLSSOSessionDTO sessionDTO, AuthenticationResult authResult) throws UserStoreException, IdentityException { authnReqDTO.setAssertionConsumerURL(sessionDTO.getAssertionConsumerURL()); authnReqDTO.setId(sessionDTO.getRequestID()); authnReqDTO.setIssuer(sessionDTO.getIssuer()); authnReqDTO.setSubject(sessionDTO.getSubject()); authnReqDTO.setRpSessionId(sessionDTO.getRelyingPartySessionId()); authnReqDTO.setRequestMessageString(sessionDTO.getRequestMessageString()); authnReqDTO.setQueryString(sessionDTO.getHttpQueryString()); authnReqDTO.setDestination(sessionDTO.getDestination()); authnReqDTO.setUser(authResult.getSubject()); authnReqDTO.setIdPInitSSOEnabled(sessionDTO.isIdPInitSSO()); authnReqDTO.setClaimMapping(authResult.getClaimMapping()); authnReqDTO.setTenantDomain(sessionDTO.getTenantDomain()); authnReqDTO.setIdPInitSLOEnabled(sessionDTO.isIdPInitSLO()); if (!(sessionDTO.getAttributeConsumingServiceIndex() < 1)) { authnReqDTO.setAttributeConsumingServiceIndex(sessionDTO.getAttributeConsumingServiceIndex()); } SAMLSSOUtil.setIsSaaSApplication(authResult.isSaaSApp()); SAMLSSOUtil.setUserTenantDomain(authResult.getSubject().getTenantDomain()); }
Source:
public GroupForm getGroupForm(String key) { log.debug("Initializing group form for group key " + key); IEntityGroup group = GroupService.findGroup(key); GroupForm form = new GroupForm(); form.setKey(key); form.setName(group.getName()); form.setDescription(group.getDescription()); form.setCreatorId(group.getCreatorID()); form.setType(groupListHelper.getEntityType(group).toString()); Iterator<IGroupMember> groupIter = group.getChildren().iterator(); while (groupIter.hasNext()) { IGroupMember child = groupIter.next(); JsonEntityBean childBean = groupListHelper.getEntity(child); form.addMember(childBean); } return form; }

Target:
public GroupForm getGroupForm(String key) { log.debug("Initializing group form for group key " + key); IEntityGroup group = GroupService.findGroup(key); GroupForm form = new GroupForm(); form.setKey(key); form.setName(group.getName()); form.setDescription(group.getDescription()); form.setCreatorId(group.getCreatorID()); form.setType(groupListHelper.getEntityType(group).toString()); for (IGroupMember child : group.getChildren()) { JsonEntityBean childBean = groupListHelper.getEntity(child); form.addMember(childBean); } return form; }
Source:
public static String readFromURL(final URL url) throws IOException { final StringBuilder builder = new StringBuilder(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(url.openStream(), BackendFileSystemManager.UT8)); String line = null; while ((line = reader.readLine()) != null) { builder.append(line); builder.append("\n"); } return builder.toString(); } finally { if (null != reader) { reader.close(); } } }

Target:
public static String readFromURL(final URL url) throws IOException { final StringBuilder builder = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), BackendFileSystemManager.UT8))) { String line; while ((line = reader.readLine()) != null) { builder.append(line); builder.append("\n"); } return builder.toString(); } }
Source:
public NeedsPaging<PatientIdentifier> doGetAll(Patient parent, RequestContext context) throws ResponseException { List<PatientIdentifier> newPatientIdentifier; if (context.getIncludeAll()) { newPatientIdentifier = new ArrayList<PatientIdentifier>(parent.getIdentifiers()); } else { newPatientIdentifier = parent.getActiveIdentifiers(); } return new NeedsPaging<PatientIdentifier>(newPatientIdentifier, context); }

Target:
public NeedsPaging<PatientIdentifier> doGetAll(Patient parent, RequestContext context) throws ResponseException { List<PatientIdentifier> patientIdentifiers; if (context.getIncludeAll()) { patientIdentifiers = new ArrayList<PatientIdentifier>(parent.getIdentifiers()); } else { patientIdentifiers = parent.getActiveIdentifiers(); } return new NeedsPaging<PatientIdentifier>(patientIdentifiers, context); }
Source:
private HTableDescriptor[] getTableDescriptorsIgnoreFailure(TableName[] tableNames) { List<HTableDescriptor> descriptors = new ArrayList<>(); for (TableName tableName : tableNames) { try { descriptors.add(getTableDescriptor(tableName)); } catch (IOException ex) { LOG.warn( "Table name %s failed with %s with error message as %s", tableName.getNameAsString(), ex.getClass().getSimpleName(), ex.getMessage()); } } return descriptors.toArray(new HTableDescriptor[0]); }

Target:
private HTableDescriptor[] getTableDescriptorsIgnoreFailure(TableName[] tableNames) throws IOException { List<HTableDescriptor> descriptors = new ArrayList<>(); for (TableName tableName : tableNames) { try { descriptors.add(getTableDescriptor(tableName)); } catch (IOException ex) { if (ex instanceof TableNotFoundException || ex.getCause() instanceof FailedPreconditionException || Status.Code.FAILED_PRECONDITION == Status.fromThrowable(ex.getCause()).getCode()) { continue; } throw ex; } } return descriptors.toArray(new HTableDescriptor[0]); }
Source:
public void testGetWindowsPathHumanishName() throws IllegalArgumentException, URISyntaxException { String humanishName = new URIish("file:/ + File.separator + "b" + File.separator + "c.git/") .getHumanishName(); assertEquals("c", humanishName); }

Target:
public void testGetWindowsPathHumanishName() throws IllegalArgumentException, URISyntaxException { String humanishName = new URIish("file:/ .getHumanishName(); assertEquals("c", humanishName); }
Source:
public ValidationResult validate(EnvironmentDto environmentDto, ParametersDto parametersDto, ValidationResultBuilder validationResultBuilder) { AzureParametersDto azureParametersDto = parametersDto.azureParametersDto(); if (!azureSingleResourceGroupFeatureSwitch.isActive() || Objects.isNull(azureParametersDto)) { return validationResultBuilder.build(); } AzureResourceGroupDto azureResourceGroupDto = azureParametersDto.getAzureResourceGroupDto(); if (Objects.isNull(azureResourceGroupDto) || USE_MULTIPLE.equals(azureResourceGroupDto.getResourceGroupUsagePattern()) || !USE_EXISTING.equals(azureResourceGroupDto.getResourceGroupCreation())) { return validationResultBuilder.build(); } CloudCredential cloudCredential = credentialToCloudCredentialConverter.convert(environmentDto.getCredential()); AzureClient azureClient = azureClientService.getClient(cloudCredential); if (!azureClient.resourceGroupExists(azureResourceGroupDto.getName())) { validationResultBuilder.error(String.format("Resource group '%s' does not exist.", azureResourceGroupDto.getName())); } return validationResultBuilder.build(); }

Target:
public ValidationResult validate(EnvironmentDto environmentDto, ParametersDto parametersDto, ValidationResultBuilder validationResultBuilder) { LOGGER.debug("ParametersDto: {}, featureSwitch: {}", parametersDto, azureSingleResourceGroupFeatureSwitch.isActive()); AzureParametersDto azureParametersDto = parametersDto.azureParametersDto(); if (!azureSingleResourceGroupFeatureSwitch.isActive() || Objects.isNull(azureParametersDto)) { return validationResultBuilder.build(); } AzureResourceGroupDto azureResourceGroupDto = azureParametersDto.getAzureResourceGroupDto(); if (Objects.isNull(azureResourceGroupDto) || USE_MULTIPLE.equals(azureResourceGroupDto.getResourceGroupUsagePattern()) || !USE_EXISTING.equals(azureResourceGroupDto.getResourceGroupCreation())) { return validationResultBuilder.build(); } LOGGER.debug("Using single, existing resource group {}", azureResourceGroupDto.getName()); CloudCredential cloudCredential = credentialToCloudCredentialConverter.convert(environmentDto.getCredential()); AzureClient azureClient = azureClientService.getClient(cloudCredential); if (!azureClient.resourceGroupExists(azureResourceGroupDto.getName())) { validationResultBuilder.error(String.format("Resource group '%s' does not exist.", azureResourceGroupDto.getName())); } return validationResultBuilder.build(); }
Source:
public PackReverseIndex(final PackIndex packIndex) { index = packIndex; final long cnt = index.getObjectCount(); if (cnt > Integer.MAX_VALUE) throw new IllegalArgumentException( JGitText.get().hugeIndexesAreNotSupportedByJgitYet); if (cnt == 0) { bucketSize = Long.MAX_VALUE; offsetIndex = new int[1]; nth = new int[0]; return; } final long[] offsetsBySha1 = new long[(int) cnt]; long maxOffset = 0; int ith = 0; for (final MutableEntry me : index) { final long o = me.getOffset(); offsetsBySha1[ith++] = o; if (o > maxOffset) maxOffset = o; } bucketSize = maxOffset / cnt + 1; int[] bucketIndex = new int[(int) cnt]; int[] bucketValues = new int[(int) cnt + 1]; for (int oi = 0; oi < offsetsBySha1.length; oi++) { final long o = offsetsBySha1[oi]; final int bucket = (int) (o / bucketSize); final int bucketValuesPos = oi + 1; final int current = bucketIndex[bucket]; bucketIndex[bucket] = bucketValuesPos; bucketValues[bucketValuesPos] = current; } int nthByOffset = 0; nth = new int[offsetsBySha1.length]; offsetIndex = bucketIndex; for (int bi = 0; bi < bucketIndex.length; bi++) { final int start = nthByOffset; for (int vi = bucketIndex[bi]; vi > 0; vi = bucketValues[vi]) { final int nthBySha1 = vi - 1; final long o = offsetsBySha1[nthBySha1]; int insertion = nthByOffset++; for (; start < insertion; insertion--) { if (o > offsetsBySha1[nth[insertion - 1]]) break; nth[insertion] = nth[insertion - 1]; } nth[insertion] = nthBySha1; } offsetIndex[bi] = nthByOffset; } }

Target:
public PackReverseIndex(final PackIndex packIndex) { index = packIndex; final long cnt = index.getObjectCount(); if (cnt + 1 > Integer.MAX_VALUE) throw new IllegalArgumentException( JGitText.get().hugeIndexesAreNotSupportedByJgitYet); if (cnt == 0) { bucketSize = Long.MAX_VALUE; offsetIndex = new int[1]; nth = new int[0]; return; } final long[] offsetsBySha1 = new long[(int) cnt]; long maxOffset = 0; int ith = 0; for (final MutableEntry me : index) { final long o = me.getOffset(); offsetsBySha1[ith++] = o; if (o > maxOffset) maxOffset = o; } bucketSize = maxOffset / cnt + 1; int[] bucketIndex = new int[(int) cnt]; int[] bucketValues = new int[(int) cnt + 1]; for (int oi = 0; oi < offsetsBySha1.length; oi++) { final long o = offsetsBySha1[oi]; final int bucket = (int) (o / bucketSize); final int bucketValuesPos = oi + 1; final int current = bucketIndex[bucket]; bucketIndex[bucket] = bucketValuesPos; bucketValues[bucketValuesPos] = current; } int nthByOffset = 0; nth = new int[offsetsBySha1.length]; offsetIndex = bucketIndex; for (int bi = 0; bi < bucketIndex.length; bi++) { final int start = nthByOffset; for (int vi = bucketIndex[bi]; vi > 0; vi = bucketValues[vi]) { final int nthBySha1 = vi - 1; final long o = offsetsBySha1[nthBySha1]; int insertion = nthByOffset++; for (; start < insertion; insertion--) { if (o > offsetsBySha1[nth[insertion - 1]]) break; nth[insertion] = nth[insertion - 1]; } nth[insertion] = nthBySha1; } offsetIndex[bi] = nthByOffset; } }
Source:
public void testDefault() throws Exception { final String[] expected = { "27:31: " + getCheckMessage(MSG_WS_FOLLOWED, ";"), "43:32: " + getCheckMessage(MSG_WS_FOLLOWED, ";"), "55:11: " + getCheckMessage(MSG_WS_FOLLOWED, ";"), }; verify(checkConfig, getPath("InputForIteratorPad.java"), expected); }

Target:
public void testDefault() throws Exception { final String[] expected = { "27:31: " + getCheckMessage(MSG_WS_FOLLOWED, ";"), "43:32: " + getCheckMessage(MSG_WS_FOLLOWED, ";"), "55:11: " + getCheckMessage(MSG_WS_FOLLOWED, ";"), }; verify(checkConfig, getPath("InputEmptyForIteratorPad.java"), expected); }
Source:
public void run() { _logger.info("Starting the Kafka-based connector task for {}", _datastreamTask); boolean startingUp = true; long pollInterval = 0; _eventsProcessedCountLoggedTime = Instant.now(); try { _consumer = createKafkaConsumer(_consumerProps); consumerSubscribe(); ConsumerRecords<?, ?> records; while (!_shouldDie) { preConsumerPollHook(); records = pollRecords(pollInterval); if (startingUp) { pollInterval = _pollTimeoutMs; startingUp = false; _startedLatch.countDown(); } if (records != null && !records.isEmpty()) { Instant readTime = Instant.now(); processRecords(records, readTime); trackEventsProcessedProgress(records.count()); } } _logger.info("Flushing and committing offsets before task exits.", _taskName); maybeCommitOffsets(_consumer, true); } catch (WakeupException e) { if (!_shouldDie) { _logger.error("Got WakeupException while not in shutdown mode.", e); throw e; } else { _logger.info("Got WakeupException, shutting down task {}.", _taskName); } } catch (Exception e) { _logger.error("{} failed with exception.", _taskName, e); _datastreamTask.setStatus(DatastreamTaskStatus.error(e.toString() + ExceptionUtils.getFullStackTrace(e))); throw new DatastreamRuntimeException(e); } finally { _stoppedLatch.countDown(); _consumer.close(); _logger.info("{} stopped", _taskName); } }

Target:
public void run() { _logger.info("Starting the Kafka-based connector task for {}", _datastreamTask); boolean startingUp = true; long pollInterval = 0; _eventsProcessedCountLoggedTime = Instant.now(); try { _consumer = createKafkaConsumer(_consumerProps); consumerSubscribe(); ConsumerRecords<?, ?> records; while (!_shutdown) { preConsumerPollHook(); records = pollRecords(pollInterval); if (startingUp) { pollInterval = _pollTimeoutMs; startingUp = false; _startedLatch.countDown(); } if (records != null && !records.isEmpty()) { Instant readTime = Instant.now(); processRecords(records, readTime); trackEventsProcessedProgress(records.count()); } } _logger.info("Flushing and committing offsets before task exits.", _taskName); maybeCommitOffsets(_consumer, true); } catch (WakeupException e) { if (_shutdown) { _logger.info("Got WakeupException, shutting down task {}.", _taskName); maybeCommitOffsets(_consumer, true); } else { _logger.error("Got WakeupException while not in shutdown mode.", e); throw e; } } catch (Exception e) { _logger.error("{} failed with exception.", _taskName, e); _datastreamTask.setStatus(DatastreamTaskStatus.error(e.toString() + ExceptionUtils.getFullStackTrace(e))); throw new DatastreamRuntimeException(e); } finally { _stoppedLatch.countDown(); _consumer.close(); _logger.info("{} stopped", _taskName); } }
Source:
public static Object instantiateInstanceWithClientConfig(String className, IClientConfig clientConfig) throws InstantiationException, IllegalAccessException, ClassNotFoundException { Class clazz = Class.forName(className); if (IClientConfigAware.class.isAssignableFrom(clazz)) { IClientConfigAware obj = (IClientConfigAware) clazz.newInstance(); obj.initWithNiwsConfig(clientConfig); return obj; } else { try { if (clazz.getConstructor(IClientConfig.class) != null) { return clazz.getConstructor(IClientConfig.class).newInstance(clientConfig); } } catch (NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException ignore) { } } logger.warn("Class " + className + " neither implements IClientConfigAware nor provides a constructor with IClientConfig as the parameter. Only default constructor will be used."); return clazz.newInstance(); }

Target:
public static Object instantiateInstanceWithClientConfig(String className, IClientConfig clientConfig) throws InstantiationException, IllegalAccessException, ClassNotFoundException { Class clazz = Class.forName(className); if (IClientConfigAware.class.isAssignableFrom(clazz)) { IClientConfigAware obj = (IClientConfigAware) clazz.newInstance(); obj.initWithNiwsConfig(clientConfig); return obj; } else { try { if (clazz.getConstructor(IClientConfig.class) != null) { return clazz.getConstructor(IClientConfig.class).newInstance(clientConfig); } } catch (NoSuchMethodException ignored) { } catch (SecurityException | IllegalArgumentException | InvocationTargetException e) { logger.warn("Error getting/invoking IClientConfig constructor of {}", className, e); } } logger.warn("Class " + className + " neither implements IClientConfigAware nor provides a constructor with IClientConfig as the parameter. Only default constructor will be used."); return clazz.newInstance(); }
Source:
public synchronized int getNextSequenceNumber() { IMemoryLocalStorage memoryLocalStorage = cachedLocalStorage; if(memoryLocalStorage == null) { try { memoryLocalStorage = createCachedLocalStorage(); return getNextSequenceNumber(memoryLocalStorage); } catch (Exception e) { SwrveLogger.e(LOG_TAG, "Error getting getNextSequenceNumber", e); } finally { if (memoryLocalStorage != null) memoryLocalStorage.close(); } } return getNextSequenceNumber(memoryLocalStorage); }

Target:
public synchronized int getNextSequenceNumber() { MemoryCachedLocalStorage memoryCachedLocalStorage = cachedLocalStorage; if (memoryCachedLocalStorage == null) { try { memoryCachedLocalStorage = createCachedLocalStorage(); ILocalStorage sqliteLocalStorage = createLocalStorage(); memoryCachedLocalStorage.setSecondaryStorage(sqliteLocalStorage); return getNextSequenceNumber(memoryCachedLocalStorage); } catch (Exception e) { SwrveLogger.e(LOG_TAG, "Error getting getNextSequenceNumber", e); } finally { if (memoryCachedLocalStorage != null) memoryCachedLocalStorage.close(); } } return getNextSequenceNumber(memoryCachedLocalStorage); }
Source:
public DefaultManagementRegistryService(ManagementRegistryServiceConfiguration configuration) { if (configuration == null) { throw new NullPointerException(); } this.configuration = configuration; }

Target:
public DefaultManagementRegistryService(ManagementRegistryServiceConfiguration configuration) { this.configuration = configuration == null ? new DefaultManagementRegistryConfiguration() : configuration; }
Source:
public static String createRootVariable(Path<?> path, int suffix) { String variable = path.accept(ToStringVisitor.DEFAULT, TEMPLATES).replace('.', '_'); return variable + "_" + suffix; }

Target:
public static String createRootVariable(Path<?> path, int suffix) { String variable = path.accept(ToStringVisitor.DEFAULT, TEMPLATES); return variable + "_" + suffix; }
Source:
public void inflatedueDate() { mfDatePicker = MFDatePicker.newInsance(this); etChargeDueDate.setText(MFDatePicker.getDatePickedAsString()); etChargeDueDate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mfDatePicker.show(getActivity().getSupportFragmentManager(), FragmentConstants .DFRAG_DATE_PICKER); } }); }

Target:
public void inflatedueDate() { mfDatePicker = MFDatePicker.newInsance(this); etChargeDueDate.setText(MFDatePicker.getDatePickedAsString()); }
Source:
Optional<Work> lookup(String workId) { return allQueued.values().stream().map(queue -> queue.lookup(workId)).filter(work -> work != null).findAny(); }

Target:
Optional<Work> lookup(String workId) { return allQueued.values().stream().map(queue -> queue.lookup(workId)).filter(Objects::nonNull).findAny(); }
Source:
public void setUp() { random = new Random(); System.setProperty(MockLogger.LOG_KEY_PREFIX + LinkdTopologyProvider.class.getName(), "INFO"); }

Target:
public void setUp() { random = new Random(42); System.setProperty(MockLogger.LOG_KEY_PREFIX + LinkdTopologyProvider.class.getName(), "INFO"); MetricRegistry registry = Mockito.mock(MetricRegistry.class); provider = new LinkdTopologyProvider(registry); }
Source:
public AnalyzeTextOptions setTokenFilters(TokenFilterName... tokenFilters) { this.tokenFilters = Arrays.asList(tokenFilters); return this; }

Target:
public AnalyzeTextOptions setTokenFilters(TokenFilterName... tokenFilters) { this.tokenFilters = (tokenFilters == null) ? null : Arrays.asList(tokenFilters); return this; }
Source:
public void testMissingELDependencyThrowsExceptionDuringFactoryBootstrap() throws Exception { System.out.println("yo"); ClassLoader classLoader = new ELIgnoringClassLoader(); Class<?> clazz = classLoader.loadClass( Validation.class.getName() ); Object validation = clazz.newInstance(); Method m = clazz.getMethod( "buildDefaultValidatorFactory" ); try { m.invoke( validation ); fail( "An exception should have been thrown" ); } catch ( InvocationTargetException e ) { Exception exceptionInValidation = (Exception) e.getTargetException(); assertEquals( exceptionInValidation.getMessage(), "Unable to instantiate Configuration.", "Bootstrapping in Validation should throw an exception " ); Throwable rootCause = exceptionInValidation.getCause(); assertTrue( rootCause.getMessage().startsWith( "HV000183" ), "The root cause of the failure should be missing EL dependencies" ); } }

Target:
public void testMissingELDependencyThrowsExceptionDuringFactoryBootstrap() throws Exception { ClassLoader classLoader = new ELIgnoringClassLoader(); Class<?> clazz = classLoader.loadClass( Validation.class.getName() ); Object validation = clazz.newInstance(); Method m = clazz.getMethod( "buildDefaultValidatorFactory" ); Object validatorFactory = m.invoke( validation ); Method getValidatorMethod = validatorFactory.getClass().getMethod( "getValidator" ); try { getValidatorMethod.invoke( validatorFactory ); fail( "An exception should have been thrown" ); } catch ( InvocationTargetException e ) { Exception exceptionInValidation = (Exception) e.getTargetException(); assertEquals( exceptionInValidation.getMessage(), "HV000183: Unable to load 'javax.el.ExpressionFactory'. Check that you have the EL dependencies on the classpath, or use ParameterMessageInterpolator instead", "Bootstrapping in Validation should throw an exception " ); } }
Source:
@Nonnull @Override public Directive<DirectiveValue> construct(Set<DirectiveValue> newValues) { return new BlockAllMixedContentDirective(); }

Target:
@Nonnull @Override public Directive<DirectiveValue> construct(Set<DirectiveValue> newValues) { return this; }