auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static long parseSizeInBytes(String string) { String digits = string; if (digits.length() == 0) { throw new NumberFormatException("Invalid empty string"); } char unit = digits.charAt(digits.length() - 1); if (unit == 'b' || unit == 'B') { digits = digits.substring(0, digits.length() - 1); if (digits.length() == 0) { throw new NumberFormatException(string); } unit = digits.charAt(digits.length() - 1); } long mul; switch (unit) { case 'k': case 'K': mul = KB; break; case 'm': case 'M': mul = MB; break; case 'g': case 'G': mul = GB; break; case 't': case 'T': mul = TB; break; default: if (!Character.isDigit(unit)) { throw new NumberFormatException(string); } mul = 1; } if (mul != 1) { digits = digits.substring(0, digits.length() - 1); if (digits.length() == 0) { throw new NumberFormatException(string); } } try { return Long.parseLong(digits.trim()) * mul; } catch (NumberFormatException e) { throw new NumberFormatException(string); } }

Target:
public static long parseSizeInBytes(String string) throws NumberFormatException { String digits = string; if (digits.length() == 0) { throw new NumberFormatException("Invalid empty string"); } char unit = digits.charAt(digits.length() - 1); if (unit == 'b' || unit == 'B') { digits = digits.substring(0, digits.length() - 1); if (digits.length() == 0) { throw new NumberFormatException(string); } unit = digits.charAt(digits.length() - 1); } long mul; switch (unit) { case 'k': case 'K': mul = KB; break; case 'm': case 'M': mul = MB; break; case 'g': case 'G': mul = GB; break; case 't': case 'T': mul = TB; break; default: if (!Character.isDigit(unit)) { throw new NumberFormatException(string); } mul = 1; } if (mul != 1) { digits = digits.substring(0, digits.length() - 1); if (digits.length() == 0) { throw new NumberFormatException(string); } } try { return Long.parseLong(digits.trim()) * mul; } catch (NumberFormatException e) { throw new NumberFormatException(string); } }
Source:
public final Optional<Argument> find(String name, StatementContext ctx) { if (name.startsWith(prefix)) { String actualName = name.substring(prefix.length()); int separator = actualName.indexOf('.'); if (separator != -1) { String parentName = actualName.substring(0, separator); String childName = actualName.substring(separator + 1); return childArgumentFinders .computeIfAbsent(parentName.endsWith("?") ? parentName.substring(0, parentName.length() - 1) : parentName, pn -> getValue(pn, ctx).map(v -> { if (Objects.nonNull(v.value)) { return getNestedArgumentFinder(v.value); } if (parentName.endsWith("?")) { return new NullArgumentFinder(); } throw new NullPointerException(); })) .flatMap(arg -> arg.find(childName, ctx)); } if (actualName.endsWith("?")) { actualName = actualName.substring(0, actualName.length() - 1); } return getValue(actualName, ctx) .map(tv -> ctx.findArgumentFor(tv.type, tv.value) .orElseThrow(() -> new UnableToCreateStatementException( String.format("No argument factory registered for type [%s] for element [%s] on [%s]", tv.type, name, object), ctx))); } return Optional.empty(); }

Target:
public final Optional<Argument> find(String name, StatementContext ctx) { if (name.startsWith(prefix)) { final String actualName = name.substring(prefix.length()); int separator = actualName.indexOf('.'); if (separator != -1) { String parentName = actualName.substring(0, separator); String childName = actualName.substring(separator + 1); return childArgumentFinders .computeIfAbsent(parentName.endsWith("?") ? parentName.substring(0, parentName.length() - 1) : parentName, pn -> getValue(pn, ctx).map(typedValue -> getValueNested(typedValue, parentName, childName))) .flatMap(arg -> arg.find(childName, ctx)); } return getValue(actualName, ctx) .map(tv -> ctx.findArgumentFor(tv.type, tv.value) .orElseThrow(() -> new UnableToCreateStatementException( String.format("No argument factory registered for type [%s] for element [%s] on [%s]", tv.type, name, object), ctx))); } return Optional.empty(); }
Source:
private HttpRequestEndPoint getEndPointCourseStructure(final String courseId) { return new HttpRequestEndPoint() { public String getUrl() { try { PrefManager pref = new PrefManager(MainApplication.instance(), PrefManager.Pref.LOGIN); String username = URLEncoder.encode(pref.getCurrentUserProfile().username, "UTF-8"); String block_counts = URLEncoder.encode("video", "UTF-8"); String requested_fields = URLEncoder.encode("graded,format,student_view_multi_device", "UTF-8"); String student_view_data = URLEncoder.encode("discussion,video", "UTF-8"); String cId = URLEncoder.encode(courseId, "UTF-8"); String url = config.getApiHostURL() + "/api/courses/v1/blocks/?course_id=" + cId + "&username=" + username + "&depth=all&requested_fields=" + requested_fields + "&student_view_data=" + student_view_data + "&block_counts=" + block_counts + "&nav_depth=3"; logger.debug("GET url for enrolling in a Course: " + url); return url; } catch (UnsupportedEncodingException e) { logger.error(e); } return ""; } public String getCacheKey() { return config.getApiHostURL() + "/api/courses/v1/blocks/?course_id=" + courseId; } public Map<String, String> getParameters() { return null; } }; }

Target:
private HttpRequestEndPoint getEndPointCourseStructure(final String courseId) { return new HttpRequestEndPoint() { public String getUrl() { PrefManager pref = new PrefManager(MainApplication.instance(), PrefManager.Pref.LOGIN); String url = Uri.parse(config.getApiHostURL() + "/api/courses/v1/blocks/?") .buildUpon() .appendQueryParameter("course_id", courseId) .appendQueryParameter("username", pref.getCurrentUserProfile().username) .appendQueryParameter("depth", "all") .appendQueryParameter("requested_fields", "graded,format,student_view_multi_device") .appendQueryParameter("student_view_data", "video,discussion") .appendQueryParameter("block_counts", "video") .appendQueryParameter("nav_depth", "3") .toString(); logger.debug("GET url for enrolling in a Course: " + url); return url; } public String getCacheKey() { return config.getApiHostURL() + "/api/courses/v1/blocks/?course_id=" + courseId; } public Map<String, String> getParameters() { return null; } }; }
Source:
public synchronized void addChangeListener(MemoryPoolId poolId, Consumer<MemoryPoolInfo> listener) { verify(memoryPoolExists(poolId), format("Memory pool doesn't exist: %s", poolId)); changeListeners.computeIfAbsent(poolId, id -> new ArrayList<>()).add(listener); }

Target:
public synchronized void addChangeListener(MemoryPoolId poolId, Consumer<MemoryPoolInfo> listener) { verify(memoryPoolExists(poolId), "Memory pool does not exist: %s", poolId); changeListeners.computeIfAbsent(poolId, id -> new ArrayList<>()).add(listener); }
Source:
public Optional<Errors> validatePatchRequest(JsonNode payload){ if(payload != null && payload.has(FIELD_OPERATION_PATH) && payload.findValue(FIELD_OPERATION_PATH).asText().equals("notify_settings")) { return validateNotifySettingsRequest(payload).map(Errors::from); } throw new UnsupportedOperationException("Not supported"); }

Target:
public Optional<Errors> validatePatchRequest(JsonNode payload){ Optional<List<String>> pathCheck = requestValidator.checkIfExistsOrEmpty(payload, FIELD_OPERATION, FIELD_OPERATION_PATH); if(pathCheck.isPresent()){ return pathCheck.map(Errors::from); } if(!payload.findValue(FIELD_OPERATION_PATH).asText().equals(FIELD_NOTIFY_SETTINGS)) { return Optional.of(Errors.from(format("Operation [%s] not supported for path [%s]", FIELD_OPERATION, payload.findValue(FIELD_OPERATION_PATH).asText()))); } return validateNotifySettingsRequest(payload).map(Errors::from); }
Source:
private void testGetVariantsByRegionHelper(String testString, int expectedSize) throws URISyntaxException { Response response = given().param("species", "mmusculus_grcm38").get(new URI("/v1/segments/" + testString + "/variants")); response.then().statusCode(200); List queryResponse = JsonPath.from(response.asString()).getList("response"); List<Map> result = JsonPath.from(response.asString()).getJsonObject("response[0].result"); for (Map m : result) { assertFalse(m.containsKey("")); String missingField = String.format("%s required field missing", m.get("name")); assertTrue(missingField, m.containsKey("id")); assertTrue(missingField, m.containsKey("chromosome")); assertTrue(missingField, m.containsKey("start")); assertTrue(missingField, m.containsKey("end")); } }

Target:
private void testGetVariantsByRegionHelper(String testString, int expectedSize) throws URISyntaxException { Response response = given().param("species", "mmusculus_grcm38").get(new URI("/v1/segments/" + testString + "/variants")); response.then().statusCode(200); List queryResponse = JsonPath.from(response.asString()).getList("response"); List<Map> result = JsonPath.from(response.asString()).getJsonObject("response[0].result"); for (Map m : result) { String missingField = String.format("%s required field missing", m.get("name")); assertTrue(missingField, m.containsKey("id")); assertTrue(missingField, m.containsKey("chromosome")); assertTrue(missingField, m.containsKey("start")); assertTrue(missingField, m.containsKey("end")); } }
Source:
public void visitNewClass(NewClassTree tree) { super.visitNewClass(tree); ClassTree classBody = tree.classBody(); if (classBody != null) { TypeTree identifier = tree.identifier(); if (!useThisIdentifier(classBody) && !enumConstants.contains(identifier) && isSAM(classBody)) { Tree member = classBody.members().get(0); if (member.is(Tree.Kind.METHOD) && multipleMethodsDefaultSameSignature(((JavaSymbol.MethodJavaSymbol) ((MethodTree) member).symbol()))) { context.reportIssue(this, identifier, "Make this anonymous inner class a lambda" + context.getJavaVersion().java8CompatibilityMessage()); } } } }

Target:
public void visitNewClass(NewClassTree tree) { super.visitNewClass(tree); ClassTree classBody = tree.classBody(); if (classBody != null) { TypeTree identifier = tree.identifier(); if (!useThisIdentifier(classBody) && !enumConstants.contains(identifier) && isSAM(classBody)) { context.reportIssue(this, identifier, "Make this anonymous inner class a lambda" + context.getJavaVersion().java8CompatibilityMessage()); } } }
Source:
protected void handleMessageInRunContext(final Message jmsRequest, final String replyId) throws JMSException { final JmsMessageReader<REQUEST> messageReader = JmsMessageReader.newInstance(jmsRequest, m_marshaller); final IMessage<REQUEST> request = messageReader.readMessage(); final Destination replyTopic = messageReader.readReplyTo(); final String correlationId = messageReader.readCorrelationId(); createRunContext() .withCorrelationId(correlationId) .withThreadLocal(IMessage.CURRENT, request) .run(new IRunnable() { @Override public void run() throws Exception { try { handleRequest(jmsRequest, request, replyId, replyTopic); } catch (Exception e) { throw BEANS.get(PlatformExceptionTranslator.class).translate(e) .withContextInfo("JMSCorrelationID", correlationId); } } }); }

Target:
protected void handleMessageInRunContext(final Message jmsRequest, final String replyId) throws JMSException { final JmsMessageReader<REQUEST> messageReader = JmsMessageReader.newInstance(jmsRequest, m_marshaller); final IMessage<REQUEST> request = messageReader.readMessage(); final Destination replyTopic = messageReader.readReplyTo(); final String correlationId = messageReader.readCorrelationId(); createRunContext() .withCorrelationId(correlationId) .withThreadLocal(IMessage.CURRENT, request) .run(new IRunnable() { @Override public void run() throws Exception { try { handleRequest(jmsRequest, request, replyId, replyTopic); } catch (Exception e) { throw BEANS.get(PlatformExceptionTranslator.class).translate(e) .withContextInfo("correlationId", correlationId); } } }); }
Source:
public int compareTo(@Nullable ISegment o) { if (o == null) { throw new IllegalArgumentException(); } Comparator<ISegment> comparator = Ordering .from(SegmentComparators.INTERVAL_START_COMPARATOR) .compound(SegmentComparators.INTERVAL_END_COMPARATOR); return comparator.compare(this, o); }

Target:
public int compareTo(@Nullable ISegment o) { if (o == null) { throw new IllegalArgumentException(); } return COMPARATOR.compare(this, o); }
Source:
public KafkaFuture<ListOffsetsResultInfo> partitionResult(final TopicPartition partition) { if (!futures.containsKey(partition)) { final KafkaFutureImpl<ListOffsetsResultInfo> result = new KafkaFutureImpl<>(); result.completeExceptionally(new IllegalArgumentException( "List Offsets for partition \"" + partition + "\" was not attempted")); return result; } return futures.get(partition); }

Target:
public KafkaFuture<ListOffsetsResultInfo> partitionResult(final TopicPartition partition) { KafkaFuture<ListOffsetsResultInfo> future = futures.get(partition); if (future == null) { throw new IllegalArgumentException( "List Offsets for partition \"" + partition + "\" was not attempted"); } return future; }
Source:
protected Result check() throws Exception { Connection connection = null; try { connection = DriverManager.getConnection( configuration.getDataSourceFactory().getUrl(), configuration.getDataSourceFactory().getUser(), configuration.getDataSourceFactory().getPassword()); connection.setReadOnly(true); Statement statement = connection.createStatement(); statement.execute("select * from pg_stat_database where datname='connector';"); ResultSet resultSet = statement.getResultSet(); resultSet.next(); numBackends = resultSet.getInt("numbackends"); xactCommit = resultSet.getInt("xact_commit"); return connection.isValid(2) ? Result.healthy() : Result.unhealthy("Could not validate the DB connection."); } catch (Exception e) { return Result.unhealthy(e.getMessage()); } finally { if (connection !=null) { connection.close(); } } }

Target:
protected Result check() throws Exception { Connection connection = null; try { connection = DriverManager.getConnection( configuration.getDataSourceFactory().getUrl(), configuration.getDataSourceFactory().getUser(), configuration.getDataSourceFactory().getPassword()); connection.setReadOnly(true); updateMetricData(connection); return connection.isValid(2) ? Result.healthy() : Result.unhealthy("Could not validate the DB connection."); } catch (Exception e) { return Result.unhealthy(e.getMessage()); } finally { if (connection != null) { connection.close(); } } }
Source:
public void getSetMembers_shouldReturnConceptSetMembersSortedWithRetiredLast() throws Exception { Concept c = new Concept(); Concept retiredConcept = new Concept(3); retiredConcept.setRetired(true); retiredConcept.setRetireReason("TEST"); retiredConcept.setRetiredBy(new User()); Concept retiredConcept2 = new Concept(0); retiredConcept2.setRetired(true); retiredConcept2.setRetireReason("TEST"); retiredConcept2.setRetiredBy(new User()); Concept retiredConcept3 = new Concept(0); retiredConcept3.setRetired(true); retiredConcept3.setRetireReason("TEST"); retiredConcept3.setRetiredBy(new User()); ConceptSet set0 = new ConceptSet(retiredConcept, 3.0); ConceptSet set1 = new ConceptSet(new Concept(1), 2.0); ConceptSet set2 = new ConceptSet(new Concept(2), 1.0); ConceptSet set3 = new ConceptSet(retiredConcept2, 0.0); ConceptSet set4 = new ConceptSet(); set4.setConcept(new Concept(3)); ConceptSet set5 = new ConceptSet(); set5.setConcept(retiredConcept3); List<ConceptSet> sets = new ArrayList<ConceptSet>(); sets.add(set0); sets.add(set1); sets.add(set2); sets.add(set3); sets.add(set4); sets.add(set5); c.setConceptSets(sets); List<Concept> setMembers = c.getSetMembers(); Assert.assertEquals(set4.getConcept().getConceptId(), setMembers.get(0).getConceptId()); Assert.assertEquals(set2.getConcept().getConceptId(), setMembers.get(1).getConceptId()); Assert.assertEquals(set1.getConcept().getConceptId(), setMembers.get(2).getConceptId()); Assert.assertEquals(set5.getConcept().getConceptId(), setMembers.get(3).getConceptId()); Assert.assertEquals(set3.getConcept().getConceptId(), setMembers.get(4).getConceptId()); Assert.assertEquals(set0.getConcept().getConceptId(), setMembers.get(5).getConceptId()); }

Target:
public void getSetMembers_shouldReturnConceptSetMembersSortedWithRetiredLast() throws Exception { Concept c = new Concept(); Concept retiredConcept = new Concept(3); retiredConcept.setRetired(true); Concept retiredConcept2 = new Concept(0); retiredConcept2.setRetired(true); Concept retiredConcept3 = new Concept(0); retiredConcept3.setRetired(true); ConceptSet set0 = new ConceptSet(retiredConcept, 3.0); ConceptSet set1 = new ConceptSet(new Concept(1), 2.0); ConceptSet set2 = new ConceptSet(new Concept(2), 1.0); ConceptSet set3 = new ConceptSet(retiredConcept2, 0.0); ConceptSet set4 = new ConceptSet(); set4.setConcept(new Concept(3)); ConceptSet set5 = new ConceptSet(); set5.setConcept(retiredConcept3); List<ConceptSet> sets = new ArrayList<ConceptSet>(); sets.add(set0); sets.add(set1); sets.add(set2); sets.add(set3); sets.add(set4); sets.add(set5); c.setConceptSets(sets); List<Concept> setMembers = c.getSetMembers(); Assert.assertEquals(set4.getConcept().getConceptId(), setMembers.get(0).getConceptId()); Assert.assertEquals(set2.getConcept().getConceptId(), setMembers.get(1).getConceptId()); Assert.assertEquals(set1.getConcept().getConceptId(), setMembers.get(2).getConceptId()); Assert.assertEquals(set5.getConcept().getConceptId(), setMembers.get(3).getConceptId()); Assert.assertEquals(set3.getConcept().getConceptId(), setMembers.get(4).getConceptId()); Assert.assertEquals(set0.getConcept().getConceptId(), setMembers.get(5).getConceptId()); }
Source:
public void hydrateAndCompileModelConfigs(ElideDynamicInMemoryCompiler compiler) throws Exception { HandlebarsHydrator hydrator = new HandlebarsHydrator(staticModelDetails); Map<String, String> tableClasses = hydrator.hydrateTableTemplate(this.elideTableConfig); Map<String, String> securityClasses = hydrator.hydrateSecurityTemplate(this.elideSecurityConfig); compiler.useParentClassLoader(getClass().getClassLoader()); for (Map.Entry<String, String> tablePojo : tableClasses.entrySet()) { log.debug("key: " + tablePojo.getKey() + ", value: " + tablePojo.getValue()); compiler.addSource(MODEL_PACKAGE_NAME + tablePojo.getKey(), tablePojo.getValue()); } for (Map.Entry<String, String> secPojo : securityClasses.entrySet()) { log.debug("key: " + secPojo.getKey() + ", value: " + secPojo.getValue()); compiler.addSource(SECURITY_PACKAGE_NAME + secPojo.getKey(), secPojo.getValue()); } compiledObjects = compiler.compileAll(); Set<Class<?>> compiledTableClasses = new HashSet<Class<?>>(); compiledObjects.values().forEach(cls -> { if (cls.getAnnotation(SecurityCheck.class) != null) { dictionary.addSecurityCheck(cls); } else { compiledTableClasses.add(cls); } }); compiledTableClasses.forEach(dictionary::bindEntity); }

Target:
public void hydrateAndCompileModelConfigs(ElideDynamicInMemoryCompiler compiler) throws Exception { HandlebarsHydrator hydrator = new HandlebarsHydrator(staticModelDetails); Map<String, String> tableClasses = hydrator.hydrateTableTemplate(this.elideTableConfig); Map<String, String> securityClasses = hydrator.hydrateSecurityTemplate(this.elideSecurityConfig); for (Map.Entry<String, String> tablePojo : tableClasses.entrySet()) { log.debug("key: " + tablePojo.getKey() + ", value: " + tablePojo.getValue()); compiler.addSource(MODEL_PACKAGE_NAME + tablePojo.getKey(), tablePojo.getValue()); } for (Map.Entry<String, String> secPojo : securityClasses.entrySet()) { log.debug("key: " + secPojo.getKey() + ", value: " + secPojo.getValue()); compiler.addSource(SECURITY_PACKAGE_NAME + secPojo.getKey(), secPojo.getValue()); } compiledObjects = compiler.compileAll(); Set<Class<?>> compiledTableClasses = new HashSet<Class<?>>(); compiledObjects.values().forEach(cls -> { if (cls.getAnnotation(SecurityCheck.class) != null) { dictionary.addSecurityCheck(cls); } else { compiledTableClasses.add(cls); } }); compiledTableClasses.forEach(dictionary::bindEntity); }
Source:
private void copyTestFileToWorkingDirectory(String filename) throws IOException { String destRoot = System.getProperty("java.io.tmpdir"); if(!(destRoot.endsWith("/") || destRoot.endsWith("\\"))){ destRoot += destRoot.contains("/")? "/" : "\\"; } String dest = destRoot + filename; String src = "org/biojava/nbio/core/sequence/GenbankProxySequenceReader/" + filename; File d = new File(dest); d.delete(); FileOutputStream destination = new FileOutputStream(new File(dest)); InputStream source = this.getClass().getClassLoader().getResourceAsStream(src); int read; byte[] buffer = new byte[1024]; while((read = source.read(buffer)) > 0){ destination.write(buffer, 0, read); } destination.flush(); destination.close(); source.close(); }

Target:
private void copyTestFileToWorkingDirectory(String filename) throws IOException { String destRoot = System.getProperty("java.io.tmpdir"); if(!(destRoot.endsWith("/") || destRoot.endsWith("\\"))){ destRoot += destRoot.contains("/")? "/" : "\\"; } String dest = destRoot + filename; String src = "org/biojava/nbio/core/sequence/loader/" + filename; File d = new File(dest); d.delete(); try(FileOutputStream destination = new FileOutputStream(d); InputStream is = this.getClass().getClassLoader().getResourceAsStream(src); ReadableByteChannel source = Channels.newChannel(is)) { destination.getChannel().transferFrom(source, 0, Long.MAX_VALUE); } }
Source:
FeatureId addFeature(final SimpleFeature feature, FeatureWriter<SimpleFeatureType, SimpleFeature> writer) throws IOException { final SimpleFeature toWrite = writer.next(); for ( int i = 0; i < toWrite.getType().getAttributeCount(); i++ ) { String name = toWrite.getType().getDescriptor(i).getLocalName(); toWrite.setAttribute( name, feature.getAttribute(name)); } toWrite.getUserData().putAll(feature.getUserData()); boolean useExisting = Boolean.TRUE.equals(feature.getUserData().get(Hints.USE_PROVIDED_FID)); if(getQueryCapabilities().isUseProvidedFIDSupported() && useExisting) { ((FeatureIdImpl) toWrite.getIdentifier()).setID(feature.getID()); } toWrite.getUserData().put("_original_", feature); writer.write(); feature.getUserData().putAll( toWrite.getUserData() ); feature.getUserData().remove("_original_"); return toWrite.getIdentifier(); }

Target:
FeatureId addFeature(final SimpleFeature feature, FeatureWriter<SimpleFeatureType, SimpleFeature> writer) throws IOException { final SimpleFeature toWrite = writer.next(); for ( int i = 0; i < toWrite.getType().getAttributeCount(); i++ ) { String name = toWrite.getType().getDescriptor(i).getLocalName(); toWrite.setAttribute( name, feature.getAttribute(name)); } toWrite.getUserData().putAll(feature.getUserData()); boolean useExisting = Boolean.TRUE.equals(feature.getUserData().get(Hints.USE_PROVIDED_FID)); if(getQueryCapabilities().isUseProvidedFIDSupported() && useExisting) { ((FeatureIdImpl) toWrite.getIdentifier()).setID(feature.getID()); } toWrite.getUserData().put(ORIGINAL_FEATURE_KEY, feature); writer.write(); feature.getUserData().putAll( toWrite.getUserData() ); feature.getUserData().remove(ORIGINAL_FEATURE_KEY); return toWrite.getIdentifier(); }
Source:
private Map<String, String> initDriveData() { Map<String, String> drive = new HashMap<String, String>(); DiskImage diskImage = getParameters().getDiskImage(); VmDevice vmDevice = getParameters().getVmDevice(); drive.put("type", "disk"); drive.put("format", diskImage.getvolume_format().toString().toLowerCase()); drive.put("bootOrder", String.valueOf(vmDevice.getBootOrder())); drive.put("propagateErrors", diskImage.getpropagate_errors().toString().toLowerCase()); drive.put("iface", "virtio"); drive.put("shared", Boolean.FALSE.toString()); drive.put("optional", Boolean.FALSE.toString()); drive.put("readonly", String.valueOf(vmDevice.getIsReadOnly())); drive.put("domainID", diskImage.getstorage_id().toString()); drive.put("poolID", diskImage.getstorage_pool_id().toString()); drive.put("volumeID", diskImage.getId().toString()); drive.put("imageID", diskImage.getimage_group_id().toString()); return drive; }

Target:
private Map<String, String> initDriveData() { Map<String, String> drive = new HashMap<String, String>(); DiskImage diskImage = getParameters().getDiskImage(); VmDevice vmDevice = getParameters().getVmDevice(); drive.put("type", "disk"); drive.put("format", diskImage.getvolume_format().toString().toLowerCase()); drive.put("bootOrder", String.valueOf(vmDevice.getBootOrder())); drive.put("propagateErrors", diskImage.getpropagate_errors().toString().toLowerCase()); drive.put("iface", diskImage.getdisk_interface().toString().toLowerCase()); drive.put("shared", Boolean.FALSE.toString()); drive.put("optional", Boolean.FALSE.toString()); drive.put("readonly", String.valueOf(vmDevice.getIsReadOnly())); drive.put("domainID", diskImage.getstorage_id().toString()); drive.put("poolID", diskImage.getstorage_pool_id().toString()); drive.put("volumeID", diskImage.getId().toString()); drive.put("imageID", diskImage.getimage_group_id().toString()); return drive; }
Source:
private Object transformPayloadForInputChannel(Object payload, String contentType, Collection<MediaType> to) { Object result = null; if (MediaType.APPLICATION_JSON_VALUE.equals(contentType) || XD_JSON_OCTET_STREAM_VALUE.equals(contentType)) { result = transformInputWithTypedJsonMapper(payload, contentType, to); } if (payload instanceof byte[]) if (result != null) { if (to.contains(MediaType.ALL)) { return result; } MediaType toObjectType = findJavaObjectType(to); if (toObjectType != null) { if (toObjectType.getParameter("type") == null) { return result; } String resultClass = result.getClass().getName(); if (resultClass.equals(toObjectType.getParameter("type"))) { return result; } return transformPayloadForInputChannel(result, contentType, Collections.singletonList(toObjectType)); } else if (XD_OCTET_STREAM_VALUE.equals(contentType)) { try { return new String((byte[]) payload, "UTF-8"); } catch (UnsupportedEncodingException e) { logger.error("Could not convert bytes to String", e); } } else if (XD_OCTET_STREAM_VALUE.equals(contentType)) { return payload; } } if (to.contains(MediaType.ALL)) { if (XD_TEXT_PLAIN_UTF8_VALUE.equals(contentType) && payload instanceof byte[]) { try { return new String((byte[]) payload, "UTF-8"); } catch (UnsupportedEncodingException e) { logger.error("Could not convert String to bytes", e); } } return payload; } return convert(payload, to); }

Target:
private Object transformPayloadForInputChannel(Object payload, String contentType, Collection<MediaType> to) { Object result = null; if (MediaType.APPLICATION_JSON_VALUE.equals(contentType) || XD_JSON_OCTET_STREAM_VALUE.equals(contentType) || XD_JSON_TEXT_VALUE.equals(contentType)) { if (!to.contains(MediaType.ALL) || XD_JSON_OCTET_STREAM_VALUE.equals(contentType)) { result = transformInputWithTypedJsonMapper(payload, contentType, to); } else if (XD_JSON_TEXT_VALUE.equals(contentType)) { result = convertBytesToUTF8String((byte[]) payload); } } if (payload instanceof byte[]) if (result != null) { if (to.contains(MediaType.ALL)) { return result; } MediaType toObjectType = findJavaObjectType(to); if (toObjectType != null) { if (toObjectType.getParameter("type") == null) { return result; } String resultClass = result.getClass().getName(); if (resultClass.equals(toObjectType.getParameter("type"))) { return result; } return transformPayloadForInputChannel(result, contentType, Collections.singletonList(toObjectType)); } else if (XD_OCTET_STREAM_VALUE.equals(contentType)) { try { return new String((byte[]) payload, "UTF-8"); } catch (UnsupportedEncodingException e) { logger.error("Could not convert bytes to String", e); } } else if (XD_OCTET_STREAM_VALUE.equals(contentType)) { return payload; } } if (to.contains(MediaType.ALL)) { if (XD_TEXT_PLAIN_UTF8_VALUE.equals(contentType) && payload instanceof byte[]) { return convertBytesToUTF8String((byte[]) payload); } return payload; } return convert(payload, to); }
Source:
private void configureBot(BotClient botClient, BotForce botForce) { try { int retries = 50; while (retries-- > 0 && null == botClient.getLocalPlayer()) { sleep(50); } if (null == botClient.getLocalPlayer()) { MekHQ.getLogger().log(getClass(), "configureBot", LogLevel.ERROR, "Could not configure bot " + botClient.getName()); } else { for (Entity entity : botForce.getEntityList()) { if (null == entity) { continue; } entity.setOwner(botClient.getLocalPlayer()); botClient.sendAddEntity(entity); Thread.sleep(campaign.getCampaignOptions().getStartGameDelay()); } botClient.getLocalPlayer().setTeam(botForce.getTeam()); botClient.getLocalPlayer().setStartingPos(botForce.getStart()); if (botForce.getCamoCategory() == Player.NO_CAMO) { if (botForce.getColorIndex() >= 0) { botClient.getLocalPlayer().setColorIndex(botForce.getColorIndex()); } } else { botClient.getLocalPlayer().setCamoCategory(botForce.getCamoCategory()); botClient.getLocalPlayer().setCamoFileName(botForce.getCamoFileName()); } botClient.sendPlayerInfo(); } } catch (Exception e) { MekHQ.getLogger().error(getClass(), "configureBot", e); } }

Target:
private void configureBot(BotClient botClient, BotForce botForce) { try { int retries = 50; while (retries-- > 0 && null == botClient.getLocalPlayer()) { sleep(50); } if (null == botClient.getLocalPlayer()) { MekHQ.getLogger().log(getClass(), "configureBot", LogLevel.ERROR, "Could not configure bot " + botClient.getName()); } else { for (Entity entity : botForce.getEntityList()) { if (null == entity) { continue; } entity.setOwner(botClient.getLocalPlayer()); botClient.sendAddEntity(entity); Thread.sleep(campaign.getCampaignOptions().getStartGameDelay()); } botClient.getLocalPlayer().setTeam(botForce.getTeam()); botClient.getLocalPlayer().setStartingPos(botForce.getStart()); if (botForce.getCamoCategory().equals(Player.NO_CAMO)) { if (botForce.getColorIndex() >= 0) { botClient.getLocalPlayer().setColorIndex(botForce.getColorIndex()); } } else { botClient.getLocalPlayer().setCamoCategory(botForce.getCamoCategory()); botClient.getLocalPlayer().setCamoFileName(botForce.getCamoFileName()); } botClient.sendPlayerInfo(); } } catch (Exception e) { MekHQ.getLogger().error(getClass(), "configureBot", e); } }
Source:
private static Gist gist() throws Exception { final String key = System.getProperty("failsafe.github.key"); Assume.assumeThat(key, Matchers.notNullValue()); return new RtGithub(key).gists().iterate().iterator().next(); }

Target:
private static Gist gist() throws Exception { final String key = System.getProperty("failsafe.github.key"); Assume.assumeThat(key, Matchers.notNullValue()); return new RtGithub(key) .gists() .create(Collections.singletonMap("file.txt", "file content")); }
Source:
public void emitTuples() { String query = queryToRetrieveData(); logger.debug("select statement: {}", query); SimpleStatement stmt = new SimpleStatement(query); stmt.setFetchSize(limit); try { if (nextPageState != null) { stmt.setPagingState(nextPageState); } ResultSet result = store.getSession().execute(stmt); nextPageState = result.getExecutionInfo().getPagingState(); int remaining = result.getAvailableWithoutFetching(); if (!result.isExhausted()) { for (Row row : result) { T tuple = getTuple(row); emit(tuple); if (--remaining == 0) { break; } } } else { Thread.sleep(waitForDataTimeout); } } catch (Exception ex) { store.disconnect(); DTThrowable.rethrow(ex); } }

Target:
public void emitTuples() { String query = queryToRetrieveData(); logger.debug("select statement: {}", query); SimpleStatement stmt = new SimpleStatement(query); stmt.setFetchSize(fetchSize); try { if (nextPageState != null) { stmt.setPagingState(nextPageState); } ResultSet result = store.getSession().execute(stmt); nextPageState = result.getExecutionInfo().getPagingState(); if (!result.isExhausted()) { for (Row row : result) { T tuple = getTuple(row); emit(tuple); } } else { Thread.sleep(waitForDataTimeout); } } catch (Exception ex) { store.disconnect(); DTThrowable.rethrow(ex); } }
Source:
public static Set<ColumnStatisticType> getSupportedStatistics(Type type) { if (type.equals(BOOLEAN)) { return ImmutableSet.of(NUMBER_OF_NON_NULL_VALUES, NUMBER_OF_TRUE); } else if (type.equals(BIGINT) || type.equals(INTEGER) || type.equals(SMALLINT) || type.equals(TINYINT)) { return ImmutableSet.of(NUMBER_OF_NON_NULL_VALUES, MIN, MAX, NUMBER_OF_DISTINCT_VALUES); } else if (type.equals(DOUBLE) || type.equals(REAL)) { return ImmutableSet.of(NUMBER_OF_NON_NULL_VALUES, MIN, MAX, NUMBER_OF_DISTINCT_VALUES); } else if (isVarcharType(type)) { return ImmutableSet.of(NUMBER_OF_NON_NULL_VALUES, NUMBER_OF_DISTINCT_VALUES, MAX_VALUE_SIZE_IN_BYTES, AVERAGE_VALUE_SIZE_IN_BYTES); } else if (isCharType(type)) { return ImmutableSet.of(NUMBER_OF_NON_NULL_VALUES, NUMBER_OF_DISTINCT_VALUES); } else if (type.equals(VARBINARY)) { return ImmutableSet.of(NUMBER_OF_NON_NULL_VALUES, MAX_VALUE_SIZE_IN_BYTES, AVERAGE_VALUE_SIZE_IN_BYTES); } else if (type.equals(DATE) || type.equals(TIMESTAMP)) { return ImmutableSet.of(NUMBER_OF_NON_NULL_VALUES, MIN, MAX, NUMBER_OF_DISTINCT_VALUES); } else if (type instanceof DecimalType) { return ImmutableSet.of(NUMBER_OF_NON_NULL_VALUES, MIN, MAX, NUMBER_OF_DISTINCT_VALUES); } else { return ImmutableSet.of(); } }

Target:
public static Set<ColumnStatisticType> getSupportedStatistics(Type type) { if (type.equals(BOOLEAN)) { return ImmutableSet.of(NUMBER_OF_NON_NULL_VALUES, NUMBER_OF_TRUE_VALUES); } else if (type.equals(BIGINT) || type.equals(INTEGER) || type.equals(SMALLINT) || type.equals(TINYINT)) { return ImmutableSet.of(NUMBER_OF_NON_NULL_VALUES, MIN, MAX, NUMBER_OF_DISTINCT_VALUES); } else if (type.equals(DOUBLE) || type.equals(REAL)) { return ImmutableSet.of(NUMBER_OF_NON_NULL_VALUES, MIN, MAX, NUMBER_OF_DISTINCT_VALUES); } else if (isVarcharType(type)) { return ImmutableSet.of(NUMBER_OF_NON_NULL_VALUES, NUMBER_OF_DISTINCT_VALUES, MAX_VALUE_SIZE_IN_BYTES, AVERAGE_VALUE_SIZE_IN_BYTES); } else if (isCharType(type)) { return ImmutableSet.of(NUMBER_OF_NON_NULL_VALUES, NUMBER_OF_DISTINCT_VALUES); } else if (type.equals(VARBINARY)) { return ImmutableSet.of(NUMBER_OF_NON_NULL_VALUES, MAX_VALUE_SIZE_IN_BYTES, AVERAGE_VALUE_SIZE_IN_BYTES); } else if (type.equals(DATE) || type.equals(TIMESTAMP)) { return ImmutableSet.of(NUMBER_OF_NON_NULL_VALUES, MIN, MAX, NUMBER_OF_DISTINCT_VALUES); } else if (type instanceof DecimalType) { return ImmutableSet.of(NUMBER_OF_NON_NULL_VALUES, MIN, MAX, NUMBER_OF_DISTINCT_VALUES); } else { return ImmutableSet.of(); } }
Source:
public IndexGeneratorTask( @JsonProperty("id") String id, @JsonProperty("groupId") String groupId, @JsonProperty("interval") Interval interval, @JsonProperty("firehose") FirehoseFactory firehoseFactory, @JsonProperty("schema") Schema schema, @JsonProperty("rowFlushBoundary") int rowFlushBoundary ) { super( id != null ? id : makeTaskId(groupId, interval.getStart(), interval.getEnd(), schema.getShardSpec().getPartitionNum()), groupId, makeTaskId(groupId, interval.getStart(), interval.getEnd(), schema.getShardSpec().getPartitionNum()), schema.getDataSource(), Preconditions.checkNotNull(interval, "interval") ); this.firehoseFactory = firehoseFactory; this.schema = schema; this.rowFlushBoundary = rowFlushBoundary; }

Target:
public IndexGeneratorTask( @JsonProperty("id") String id, @JsonProperty("groupId") String groupId, @JsonProperty("interval") Interval interval, @JsonProperty("firehose") FirehoseFactory firehoseFactory, @JsonProperty("schema") Schema schema, @JsonProperty("rowFlushBoundary") int rowFlushBoundary ) { super( id != null ? id : String.format( "%s_generator_%s_%s_%s", groupId, interval.getStart(), interval.getEnd(), schema.getShardSpec().getPartitionNum() ), groupId, schema.getDataSource(), Preconditions.checkNotNull(interval, "interval") ); this.firehoseFactory = firehoseFactory; this.schema = schema; this.rowFlushBoundary = rowFlushBoundary; }
Source:
public void onLoginSuccessful(User user) { PrefManager.setUserId(user.getUserId()); PrefManager.saveToken("Basic " + user.getBase64EncodedAuthenticationKey()); PrefManager.saveUser(user); FancyToast.makeText(this, getString(R.string.toast_welcome) + " " + user.getUsername(), FancyToast.LENGTH_SHORT, FancyToast.SUCCESS,false).show(); if (PrefManager.getPassCodeStatus()) { startActivity(new Intent(this, DashboardActivity.class)); } else { Intent intent = new Intent(this, PassCodeActivity.class); intent.putExtra(Constants.INTIAL_LOGIN, true); startActivity(intent); } finish(); }

Target:
public void onLoginSuccessful(User user) { PrefManager.setUserId(user.getUserId()); PrefManager.saveToken("Basic " + user.getBase64EncodedAuthenticationKey()); PrefManager.saveUser(user); Toast.makeText(this, getString(R.string.toast_welcome) + " " + user.getUsername(), Toast.LENGTH_SHORT).show(); if (PrefManager.getPassCodeStatus()) { startActivity(new Intent(this, DashboardActivity.class)); } else { Intent intent = new Intent(this, PassCodeActivity.class); intent.putExtra(Constants.INTIAL_LOGIN, true); startActivity(intent); } finish(); }
Source:
public BasicRasterTarget(WorldProvider worldProvider,Rect2i area, BlockTheme blockTheme) { this.worldProvider = worldProvider; this.affectedArea = area; this.blockTheme = blockTheme; Vector3i min = new Vector3i(affectedArea.minX(), -255, affectedArea.minY()); Vector3i max = new Vector3i(affectedArea.maxX(), 255, affectedArea.maxY()); this.affectedRegion = new BlockRegion(min, max); }

Target:
public BasicRasterTarget(WorldProvider worldProvider,Rect2i area, BlockTheme blockTheme) { this.worldProvider = worldProvider; this.affectedArea = area; this.blockTheme = blockTheme; this.affectedRegion = new BlockRegion(affectedArea.minX(), -255, affectedArea.minY(), affectedArea.maxX(), 255, affectedArea.maxY()); }
Source:
public static boolean isTravelRequestURI(String URI) { if (StringUtils.isNotBlank(URI) && URI.contains(ConcurConstants.TRAVEL_REQUEST_URI_INDICATOR)) { return true; } return false; }

Target:
public static boolean isTravelRequestURI(String URI) { return StringUtils.isNotBlank(URI) && URI.contains(ConcurConstants.TRAVEL_REQUEST_URI_INDICATOR); }
Source:
public void testSanitizeForSaving() { String googleId = "\t\tvalid.goo gleId \t\n"; String courseId = "\t\n co urseId"; String name = "\t\t\tna me<><>"; String email = "\n e 'm'a'i'l@google.com"; String roleName = Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_COOWNER; String displayedName = Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_COOWNER; InstructorPrivileges privileges = new InstructorPrivileges(Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_COOWNER); InstructorAttributes instructor = InstructorAttributes.builder(googleId, courseId, name, email) .withRole(roleName) .withDisplayedName(displayedName).withPrivileges(privileges) .build(); instructor.sanitizeForSaving(); assertEquals(privileges, instructor.privileges); assertEquals(SanitizationHelper.sanitizeGoogleId(googleId), instructor.googleId); assertEquals(SanitizationHelper.sanitizeTitle(courseId), instructor.courseId); assertEquals(SanitizationHelper.sanitizeName(name), instructor.name); assertEquals(SanitizationHelper.sanitizeEmail(email), instructor.email); instructor.role = null; instructor.displayedName = null; instructor.privileges = null; instructor.sanitizeForSaving(); assertEquals(privileges, instructor.privileges); }

Target:
public void testSanitizeForSaving() { String googleId = "\t\tvalid.goo gleId \t\n"; String courseId = "\t\n co urseId"; String name = "\t\t\tna me<><>"; String email = "\n my'email@google.com"; String roleName = Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_COOWNER; String displayedName = Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_COOWNER; InstructorPrivileges privileges = new InstructorPrivileges(Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_COOWNER); InstructorAttributes instructor = InstructorAttributes.builder(googleId, courseId, name, email) .withRole(roleName) .withDisplayedName(displayedName).withPrivileges(privileges) .build(); instructor.sanitizeForSaving(); assertEquals(privileges, instructor.privileges); assertEquals(SanitizationHelper.sanitizeGoogleId(googleId), instructor.googleId); assertEquals(SanitizationHelper.sanitizeTitle(courseId), instructor.courseId); assertEquals(SanitizationHelper.sanitizeName(name), instructor.name); assertEquals(SanitizationHelper.sanitizeEmail(email), instructor.email); instructor.role = null; instructor.displayedName = null; instructor.privileges = null; instructor.sanitizeForSaving(); assertEquals(privileges, instructor.privileges); }
Source:
public Optional<PackingPlan.InstancePlan> removeAnyInstanceOfComponent(String component) { Optional<PackingPlan.InstancePlan> instancePlan = getAnyInstanceOfComponent(component); if (instancePlan.isPresent()) { PackingPlan.InstancePlan plan = instancePlan.get(); this.instances.remove(plan); return Optional.of(plan); } return Optional.absent(); }

Target:
public Optional<PackingPlan.InstancePlan> removeAnyInstanceOfComponent(String component) { Optional<PackingPlan.InstancePlan> instancePlan = getAnyInstanceOfComponent(component); if (instancePlan.isPresent()) { PackingPlan.InstancePlan plan = instancePlan.get(); this.instances.remove(plan); return instancePlan; } return Optional.absent(); }
Source:
private static void assertAttributesEquals(final Map<String, Object> actual, Map<String, Object> expected) { final Set<String> expectedKeys = new HashSet<String>(expected.keySet()); for ( final Map.Entry<String, Object> act : actual.entrySet() ) { final Object actualValue = act.getValue(); if ( expected.containsKey(act.getKey()) && expected.get(act.getKey()) != null ) { final Object expectedValue = expected.get(act.getKey()); if ( expectedValue instanceof List ) { final List<Object> expectedList = (List<Object>)expectedValue; Assert.assertTrue(actualValue instanceof List, act.getKey() + " should be a list but isn't"); final List<Object> actualList = (List<Object>)actualValue; Assert.assertEquals(actualList.size(), expectedList.size(), act.getKey() + " size"); for ( int i = 0; i < expectedList.size(); i++ ) { assertAttributeEquals(act.getKey(), actualList.get(i), expectedList.get(i)); } } else { assertAttributeEquals(act.getKey(), actualValue, expectedValue); } } else { Assert.assertNull(actualValue, act.getKey() + " present in one but not in the other"); } expectedKeys.remove(act.getKey()); } for ( final String missingExpected : expectedKeys ) { final Object value = expected.get(missingExpected); Assert.assertTrue(isMissing(value), "Attribute " + missingExpected + " missing in one but not in other" ); } }

Target:
private static void assertAttributesEquals(final Map<String, Object> actual, Map<String, Object> expected) { final Set<String> expectedKeys = new HashSet<String>(expected.keySet()); for ( final Map.Entry<String, Object> act : actual.entrySet() ) { final Object actualValue = act.getValue(); if ( expected.containsKey(act.getKey()) && expected.get(act.getKey()) != null ) { final Object expectedValue = expected.get(act.getKey()); if ( expectedValue instanceof List ) { final List<Object> expectedList = (List<Object>)expectedValue; Assert.assertTrue(actualValue instanceof List, act.getKey() + " should be a list but isn't"); final List<Object> actualList = (List<Object>)actualValue; Assert.assertEquals(actualList.size(), expectedList.size(), act.getKey() + " size"); for ( int i = 0; i < expectedList.size(); i++ ) { assertAttributeEquals(act.getKey(), actualList.get(i), expectedList.get(i)); } } else { assertAttributeEquals(act.getKey(), actualValue, expectedValue); } } else { Assert.assertNull(actualValue, act.getKey() + " present in one but not in the other"); } expectedKeys.remove(act.getKey()); } for ( final String missingExpected : expectedKeys ) { final Object value = expected.get(missingExpected); Assert.assertTrue(isMissingAttribute(value), "Attribute " + missingExpected + " missing in one but not in other" ); } }
Source:
public Context getSelectedContext() { JTree treeContext = getTreeContext(); SiteNode node = (SiteNode) treeContext.getLastSelectedPathComponent(); if (node == null) { return null; } Target target = (Target)node.getUserObject(); if (target != null) { return target.getContext(); } return null; }

Target:
public Context getSelectedContext() { SiteNode node = (SiteNode) treeContext.getLastSelectedPathComponent(); if (node == null || node.isRoot()) { return null; } Target target = (Target) node.getUserObject(); if (target != null) { return target.getContext(); } return null; }
Source:
public void testHiveCoercionAvro() throws SQLException { HiveTableDefinition tableDefinition = HIVE_COERCION_AVRO; String tableName = mutableTableInstanceOf(tableDefinition).getNameInDatabase(); executeHiveQuery(format("INSERT INTO TABLE %s " + "PARTITION (id=1) " + "VALUES" + "(2323, 0.5)," + "(-2323, -1.5)", tableName)); avroAlterTableColumnTypes(tableName); avroAssertProperAlteredTableSchema(tableName); QueryResult queryResult = query(format("SELECT * FROM %s", tableName)); avroAssertColumnTypes(queryResult); assertThat(queryResult).containsOnly( row( 2323L, 0.5, 1), row( -2323L, -1.5, 1)); }

Target:
public void testHiveCoercionAvro() throws SQLException { HiveTableDefinition tableDefinition = HIVE_COERCION_AVRO; String tableName = mutableTableInstanceOf(tableDefinition).getNameInDatabase(); executeHiveQuery(format("INSERT INTO TABLE %s " + "PARTITION (id=1) " + "VALUES" + "(2323, 0.5)," + "(-2323, -1.5)", tableName)); executeHiveQuery(format("ALTER TABLE %s CHANGE COLUMN int_to_bigint int_to_bigint bigint", tableName)); executeHiveQuery(format("ALTER TABLE %s CHANGE COLUMN float_to_double float_to_double double", tableName)); assertThat(query("SHOW COLUMNS FROM " + tableName).project(1, 2)).containsExactly( row("int_to_bigint", "bigint"), row("float_to_double", "double"), row("id", "bigint")); QueryResult queryResult = query(format("SELECT * FROM " + tableName)); assertThat(queryResult).hasColumns(BIGINT, DOUBLE, BIGINT); assertThat(queryResult).containsOnly( row(2323L, 0.5, 1), row(-2323L, -1.5, 1)); }
Source:
public void test_eviction_with_specific_eviction_prioritizer() throws Exception { StandaloneCache<Number, String> cache = StandaloneCacheBuilder.newCacheBuilder(Number.class, String.class, LoggerFactory.getLogger(Ehcache.class + "StandaloneCacheEvictionTest")) .withCapacity(1L) .prioritizeEviction(Eviction.Prioritizer.LRU) .build(); cache.init(); assertThat(cache.getRuntimeConfiguration().getCapacityConstraint(), equalTo((Comparable<Long>)1L)); for (int i = 0; i < 3; i++) { cache.putIfAbsent(i, "" + i); } int nullValuesFound = 0; for (int i = 0; i < 3; i++) { String retrievedValue = cache.get(i); if (retrievedValue == null) { nullValuesFound ++; } } assertThat("The capacity of the store is 1, and we found more than 1 non empty value in it !", nullValuesFound, is(2)); }

Target:
public void test_eviction_with_specific_eviction_prioritizer() throws Exception { StandaloneCache<Number, String> cache = StandaloneCacheBuilder.newCacheBuilder(Number.class, String.class, LoggerFactory.getLogger(Ehcache.class + "-" + "StandaloneCacheEvictionTest")) .withCapacity(1L) .prioritizeEviction(Eviction.Prioritizer.LRU) .build(); cache.init(); assertThat(cache.getRuntimeConfiguration().getCapacityConstraint(), equalTo((Comparable<Long>)1L)); for (int i = 0; i < 3; i++) { cache.putIfAbsent(i, "" + i); } int nullValuesFound = 0; for (int i = 0; i < 3; i++) { String retrievedValue = cache.get(i); if (retrievedValue == null) { nullValuesFound ++; } } assertThat("The capacity of the store is 1, and we found more than 1 non empty value in it !", nullValuesFound, is(2)); }