auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected boolean checkValidVersion(Set<SourceFile> sourceFiles, Tool entry) { boolean isValidCWL = false; String cwlPrimaryDescriptorPath = "/Dockstore.cwl"; <START> Optional<SourceFile> cwlPrimaryDescriptor = sourceFiles.stream().filter(sf -> Objects.equals(sf.getPath(), cwlPrimaryDescriptorPath)).findFirst(); <END> if (cwlPrimaryDescriptor.isPresent()) { isValidCWL = true; } boolean isValidWDL = false; String wdlPrimaryDescriptorPath = "/Dockstore.wdl"; Optional<SourceFile> wdlPrimaryDescriptor = sourceFiles.stream().filter(sf -> Objects.equals(sf.getPath(), wdlPrimaryDescriptorPath)).findFirst(); if (wdlPrimaryDescriptor.isPresent()) { isValidWDL = true; } boolean hasDockerfile = false; String dockerfilePath = "/Dockerfile"; Optional<SourceFile> dockerfile = sourceFiles.stream().filter(sf -> Objects.equals(sf.getPath(), dockerfilePath)).findFirst(); if (dockerfile.isPresent()) { hasDockerfile = true; } return (isValidCWL || isValidWDL) && hasDockerfile; }</code><technical_language>anyMatch more suitable filter+findFirst</technical_language>

Target:
protected boolean checkValidVersion(Set<SourceFile> sourceFiles, Tool entry) { boolean isValidCWL = sourceFiles.stream().anyMatch(sf -> Objects.equals(sf.getPath(), "/Dockstore.cwl")); boolean isValidWDL = sourceFiles.stream().anyMatch(sf -> Objects.equals(sf.getPath(), "/Dockstore.wdl")); boolean hasDockerfile = sourceFiles.stream().anyMatch(sf -> Objects.equals(sf.getPath(), "/Dockerfile")); return (isValidCWL || isValidWDL) && hasDockerfile; }
Source:
<code>protected <T> HandlerHolder<T> addRegistration(String address, HandlerRegistration<T> registration, boolean replyHandler, boolean localOnly) { Objects.requireNonNull(registration.getHandler(), "handler"); LocalRegistrationResult result = addLocalRegistration(address, registration, replyHandler, localOnly); addRegistration(result.newAddress, address, replyHandler, localOnly, registration::setResult); <START> return result.holder; <END> }</code><technical_language>seize opportunity rename this method. is confusing is name current method purpose is provide a hook for clustered event bus propagate registration</technical_language>

Target:
protected <T> HandlerHolder<T> addRegistration(String address, HandlerRegistration<T> registration, boolean replyHandler, boolean localOnly) { Objects.requireNonNull(registration.getHandler(), "handler"); LocalRegistrationResult<T> result = addLocalRegistration(address, registration, replyHandler, localOnly); addRegistration(result.newAddress, address, replyHandler, localOnly, registration::setResult); return result.holder; }
Source:
<code>protected Hardware findHardwareWithId(Set<? extends Hardware> hardwaresToSearch) { try { return super.findHardwareWithId(hardwaresToSearch); <START> } catch (Exception NoSuchElementException) { <END> if (isAutomaticId(hardwareId)) { AutomaticHardwareIdSpec spec = parseId(hardwareId); return automaticHardwareForCpuAndRam(spec.getCores(), spec.getRam()); } else{ throw throwNoSuchElementExceptionAfterLoggingHardwareIds("Invalid hardwareId", hardwaresToSearch); } } }</code><technical_language>Variable names start in case</technical_language>

Target:
protected Hardware findHardwareWithId(Set<? extends Hardware> hardwaresToSearch) { try { return super.findHardwareWithId(hardwaresToSearch); } catch (NoSuchElementException ex) { if (isAutomaticId(hardwareId)) { AutomaticHardwareIdSpec spec = parseId(hardwareId); return automaticHardwareForCpuAndRam(spec.getCores(), spec.getRam()); } else { throw ex; } } }
Source:
<code>protected void processCapabilityRequirement(OperationContext context, Resource resource, String attributeName, boolean remove, String... attributeValues) { RuntimeCapability cap = getDependentCapability(context); String dependentName = getDependentName(cap, context); for (String attributeValue : attributeValues) { <START> if (attributeValue != null || !cap.getDynamicOptionalRequirements().contains(baseRequirementName)) { <END> String requirementName = getRequirementName(context, resource, attributeValue); if (remove) { context.deregisterCapabilityRequirement(requirementName, dependentName); } else { context.registerAdditionalCapabilityRequirement(requirementName, dependentName, attributeName); } } } }</code><technical_language>null a useful here? If AD allows undefined, populates RuntimeCap's dynamic optional requirements, this result in registering a strange requirement</technical_language>

Target:
protected void processCapabilityRequirement(OperationContext context, Resource resource, String attributeName, boolean remove, String... attributeValues) { RuntimeCapability cap = getDependentCapability(context); String dependentName = getDependentName(cap, context); for (String attributeValue : attributeValues) { if (attributeValue != null) { String requirementName = getRequirementName(context, resource, attributeValue); if (remove) { context.deregisterCapabilityRequirement(requirementName, dependentName); } else { context.registerAdditionalCapabilityRequirement(requirementName, dependentName, attributeName); } } } }
Source:
<code>private ChannelPipelineFactory initChannelPipelineFactory() { ChannelPipelineFactory pipelineFactory; boolean enableCompression = compressionType.equalsIgnoreCase("deflate"); if (enableCompression || enableSsl || enableIpFilter) { pipelineFactory = new AdvancedChannelPipelineFactory( enableCompression, enableSsl, keystore, keystorePassword, keystoreType, enableIpFilter, patternRuleConfigDefinition); } else { <START> pipelineFactory = () -> Channels.pipeline(); <END> } return pipelineFactory; }</code><technical_language>This replaced method reference, i.e. pipelineFactory = Channels::pipeline</technical_language>

Target:
private ChannelPipelineFactory initChannelPipelineFactory() { ChannelPipelineFactory pipelineFactory; boolean enableCompression = compressionType.equalsIgnoreCase("deflate"); if (enableCompression || enableSsl || enableIpFilter) { pipelineFactory = new AdvancedChannelPipelineFactory( enableCompression, enableSsl, keystore, keystorePassword, keystoreType, enableIpFilter, patternRuleConfigDefinition); } else { pipelineFactory = Channels::pipeline; } return pipelineFactory; }
Source:
<code>public void connectionsToRemovedMember_shouldBeClosed() { Config config = new Config() <START> .setProperty(GroupProperty.MAX_NO_HEARTBEAT_SECONDS.getName(), "20") <END> .setProperty(GroupProperty.HEARTBEAT_INTERVAL_SECONDS.getName(), "1"); HazelcastInstance hz1 = factory.newHazelcastInstance(config); HazelcastInstance hz2 = factory.newHazelcastInstance(config); HazelcastInstance hz3 = factory.newHazelcastInstance(config); assertClusterSizeEventually(3, hz1, hz2, hz3); final Address target = getAddress(hz3); ConnectionRemovedListener connListener1 = new ConnectionRemovedListener(target); getEndpointManager(hz1).addConnectionListener(connListener1); ConnectionRemovedListener connListener2 = new ConnectionRemovedListener(target); getEndpointManager(hz2).addConnectionListener(connListener2); dropOperationsBetween(hz3, hz1, F_ID, singletonList(HEARTBEAT)); assertClusterSizeEventually(2, hz1, hz2); connListener1.assertConnectionRemoved(); connListener2.assertConnectionRemoved(); }</code><technical_language>This prolong time test takes in normal execution, rely heartbeat timeout detect missing member (see assertClusterSizeEventually in line 873 below). test failure in #15710 failed in assert of cluster size (line 862 - waiting for a cluster of 3 members formed test setup). If is evidence of long hiccups in test failure logs, I close issue merging change test itself</technical_language>

Target:
public void connectionsToRemovedMember_shouldBeClosed() { Config config = new Config(); HazelcastInstance hz1 = factory.newHazelcastInstance(config); HazelcastInstance hz2 = factory.newHazelcastInstance(config); HazelcastInstance hz3 = factory.newHazelcastInstance(config); assertClusterSizeEventually(3, hz1, hz2, hz3); final Address target = getAddress(hz3); ConnectionRemovedListener connListener1 = new ConnectionRemovedListener(target); getEndpointManager(hz1).addConnectionListener(connListener1); ConnectionRemovedListener connListener2 = new ConnectionRemovedListener(target); getEndpointManager(hz2).addConnectionListener(connListener2); dropOperationsBetween(hz3, hz1, F_ID, singletonList(HEARTBEAT)); suspectMember(hz1, hz3); assertClusterSizeEventually(2, hz1, hz2); connListener1.assertConnectionRemoved(); connListener2.assertConnectionRemoved(); }
Source:
<code><START> private void sendOnOpenMessage(ChannelHandlerContext ctx, boolean isSecured, String uri) throws URISyntaxException { <END> cMsg = new StatusCarbonMessage(org.wso2.carbon.messaging.Constants.STATUS_OPEN, 0, null); Session session = new WebSocketSessionImpl(ctx, isSecured, uri, channelId); setupCarbonMessage(ctx); cMsg.setProperty(Constants.CONNECTION, Constants.UPGRADE); cMsg.setProperty(Constants.UPGRADE, Constants.WEBSOCKET_UPGRADE); publishToMessageProcessor(cMsg); }</code><technical_language>Do need session variable anymore</technical_language>

Target:
private void sendOnOpenMessage(ChannelHandlerContext ctx, boolean isSecured, String uri) throws URISyntaxException { cMsg = new StatusCarbonMessage(org.wso2.carbon.messaging.Constants.STATUS_OPEN, 0, null); setupCarbonMessage(ctx); cMsg.setProperty(Constants.CONNECTION, Constants.UPGRADE); cMsg.setProperty(Constants.UPGRADE, Constants.WEBSOCKET_UPGRADE); publishToMessageProcessor(cMsg); }
Source:
<code>protected Operation prepareOperation() { MapEntries mapEntries = new MapEntries(parameters.entries); MapOperationProvider operationProvider = getMapOperationProvider(parameters.name); <START> return operationProvider.createPutAllOperation(parameters.name, mapEntries, parameters.triggerMapLoader); <END> }</code><technical_language>regenerate codec correct version. extra field parameters.isTriggerMapLoaderExists this if client is aware of new field not. if isTriggerMapLoaderExists is true field options did. if is false then, fall behavior pass a true triggerMapLoader parameter of operation</technical_language>

Target:
protected Operation prepareOperation() { MapEntries mapEntries = new MapEntries(parameters.entries); MapOperationProvider operationProvider = getMapOperationProvider(parameters.name); return operationProvider.createPutAllOperation(parameters.name, mapEntries, !parameters.isTriggerMapLoaderExists || parameters.triggerMapLoader); }
Source:
<code>protected Map<String, String> getExclusiveLocks() { if (getVdsGroup().supportsGlusterService() && !isInternalExecution()) { return Collections.singletonMap(getVdsGroupId().toString(), LockingGroup.GLUSTER.name()); <START> } <END> return super.getExclusiveLocks(); }</code><technical_language>need call super method</technical_language>

Target:
protected Map<String, String> getExclusiveLocks() { if (getVdsGroup().supportsGlusterService() && !isInternalExecution()) { return Collections.singletonMap(getVdsGroupId().toString(), LockingGroup.GLUSTER.name()); } return null; }
Source:
<code>public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (operatingSystemMXBean == null) chain.doFilter(request, response); assert HttpServletRequest.class.isAssignableFrom(request.getClass()); HttpServletRequest httpRequest = (HttpServletRequest) request; assert HttpServletResponse.class.isAssignableFrom(response.getClass()); HttpServletResponse httpResponse = (HttpServletResponse) response; if (shouldBypassThrottling(httpRequest)) chain.doFilter(request, response); double systemLoad = operatingSystemMXBean.getSystemLoadAverage(); <START> if (systemLoad > systemLoadLimit) notifyOverloaded(httpResponse, systemLoad); <END> else chain.doFilter(request, response); }</code><technical_language>I preferable randomly drop some requests instead of them. e.g. find a formula translate load a % of requests drop</technical_language>

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (operatingSystemMXBean == null) chain.doFilter(request, response); assert HttpServletRequest.class.isAssignableFrom(request.getClass()); HttpServletRequest httpRequest = (HttpServletRequest) request; assert HttpServletResponse.class.isAssignableFrom(response.getClass()); HttpServletResponse httpResponse = (HttpServletResponse) response; if (shouldBypassThrottling(httpRequest)) { chain.doFilter(request, response); return; } if (shouldDropRequest(ratioOfRequestsToDrop())) notifyOverloaded(httpResponse); else chain.doFilter(request, response); }
Source:
<code>public void testGetVmBootActiveSharedDisk() { Disk bootDiskVm1 = dao.getVmBootActiveDisk(FixturesTool.VM_VM1_SHARED_BOOTABLE_DISK); Disk bootDiskVm2 = dao.getVmBootActiveDisk(FixturesTool.VM_VM2_SHARED_NONBOOTABLE_DISK); assertNull(bootDiskVm2, "VM2 should not have a <START> boot disk <END> attached"); assertNotNull(bootDiskVm1, "VM1 should have a boot disk attached"); assertEquals(FixturesTool.BOOTABLE_SHARED_DISK_ID, bootDiskVm1.getId(), "Wrong boot disk for VM"); }</code><technical_language>'bootable' nicer, IMO</technical_language>

Target:
public void testGetVmBootActiveSharedDisk() { Disk bootDiskVm1 = dao.getVmBootActiveDisk(FixturesTool.VM_VM1_SHARED_BOOTABLE_DISK); Disk bootDiskVm2 = dao.getVmBootActiveDisk(FixturesTool.VM_VM2_SHARED_NONBOOTABLE_DISK); assertNull(bootDiskVm2, "VM2 should not have a bootable disk attached"); assertNotNull(bootDiskVm1, "VM1 should have a bootable disk attached"); assertEquals(FixturesTool.BOOTABLE_SHARED_DISK_ID, bootDiskVm1.getId(), "Wrong boot disk for VM"); }
Source:
<code>public void testTransformMetacard() throws CatalogTransformerException, IOException { RtfQueryResponseAndMetacardTransformer transformer = createTransformer(); assertThat("Transformer cannot be null", transformer, notNullValue()); Metacard mockMetacard = createMockMetacard("Test Metacard Title"); <START> BinaryContent content = transformer.transform(mockMetacard, new HashMap<>()); <END> assertThat("Transformed content cannot be null", content, notNullValue()); assertThat( "Content mime type must be 'application/rtf'", content.getMimeType().toString(), equalTo("application/rtf")); assertThat("Content must not be empty", content.getByteArray().length, greaterThan(0)); }</code><technical_language>Collections.emptyMap()</technical_language>

Target:
public void testTransformMetacard() throws CatalogTransformerException, IOException, MimeTypeParseException { RtfQueryResponseAndMetacardTransformer transformer = createTransformer(); Metacard mockMetacard = createMockMetacard("Test Metacard Title"); BinaryContent content = transformer.transform(mockMetacard, Collections.emptyMap()); assertThat("Transformed content cannot be null", content, notNullValue()); assertThat( "Content mime type must be 'application/rtf'", content.getMimeType().toString(), equalTo("application/rtf")); String rtfResult = inputStreamToString(content.getInputStream()); assertThat("Content must not be empty", rtfResult, is(not(isEmptyOrNullString()))); String referenceRtf = getReferenceMetacardRtfFile(); assertThat("Produced RTF document must match reference", rtfResult, equalTo(referenceRtf)); }
Source:
<code>public List<RecordedEvent> deserializeRecordedEvents(String path) { List<RecordedEvent> events = new ArrayList<>(); JsonObject jsonObject; try { JsonParser parser = new JsonParser(); JsonElement jsonElement = parser.parse(new FileReader(path)); jsonObject = jsonElement.getAsJsonObject(); JsonArray jsonEvents = jsonObject.getAsJsonArray("events"); String clazz; long refId; long timestamp; long position; Event event; for (JsonElement element : jsonEvents) { jsonObject = element.getAsJsonObject(); clazz = jsonObject.get("event_class").getAsString(); refId = jsonObject.get("entityRef_ID").getAsLong(); position = jsonObject.get("position").getAsLong(); timestamp = jsonObject.get("timestamp").getAsLong(); event = deserializeSpecificEventData(jsonObject.get("event_data").getAsJsonObject(), clazz); RecordedEvent re = new RecordedEvent(refId, event, timestamp, position); events.add(re); } } catch (Exception e) { <START> logger.error(e.getMessage()); <END> } return events; }</code><technical_language>log full exception</technical_language>

Target:
List<RecordedEvent> deserializeRecordedEvents(String path) { List<RecordedEvent> events = new ArrayList<>(); JsonObject jsonObject; try { JsonParser parser = new JsonParser(); JsonElement jsonElement = parser.parse(new FileReader(path)); jsonObject = jsonElement.getAsJsonObject(); JsonArray jsonEvents = jsonObject.getAsJsonArray("events"); for (JsonElement element : jsonEvents) { jsonObject = element.getAsJsonObject(); String clazz = jsonObject.get("event_class").getAsString(); long refId = jsonObject.get("entityRef_ID").getAsLong(); long position = jsonObject.get("position").getAsLong(); long timestamp = jsonObject.get("timestamp").getAsLong(); Event event = deserializeSpecificEventData(jsonObject.get("event_data").getAsJsonObject(), clazz); RecordedEvent re = new RecordedEvent(refId, event, timestamp, position); events.add(re); } } catch (Exception e) { logger.error("Error while deserializing event:", e); } return events; }
Source:
<code>public static WSResponse startJob(String conf_id, String url, String record_id) { Configuration runConfig = getConfigurationFromDb(conf_id); <START> List<TextAnnotation> correctInstances = getInstancesFromDb(runConfig); <END> List<TextAnnotation> cleanseInstances = getInstancesFromDb(runConfig); System.out.println(url); LearnerInterface learner = new LearnerInterface(url); String jsonInfo = learner.getInfo(); if (jsonInfo.equals("err")) { System.out.println("Could not connect to server"); return null; } cleanseInstances(cleanseInstances, jsonInfo); if (cleanseInstances == null) { System.out.println("Error in cleanser"); return null; } Job newJob = new Job(learner, cleanseInstances); WSResponse solverResponse = newJob.sendAndReceiveRequestsFromSolver(); List<TextAnnotation> solvedInstances = newJob.getSolverInstances(); List<Boolean> skip = newJob.getSkip(); EvaluationRecord eval = evaluate(runConfig, correctInstances, solvedInstances, skip); storeEvaluationIntoDb(eval, record_id); System.out.println(solverResponse); return solverResponse; }</code><technical_language>Create issue fix this hack</technical_language>

Target:
public static WSResponse startJob(String conf_id, String url, String record_id) { Configuration runConfig = getConfigurationFromDb(conf_id); List<TextAnnotation> correctInstances = getInstancesFromDb(runConfig); List<TextAnnotation> cleansedInstances = getInstancesFromDb(runConfig); System.out.println(url); LearnerInterface learner = new LearnerInterface(url); String jsonInfo = learner.getInfo(); if (jsonInfo.equals("err")) { System.out.println("Could not connect to server"); return null; } cleanseInstances(cleansedInstances, jsonInfo); if (cleansedInstances == null) { System.out.println("Error in cleanser"); return null; } Job newJob = new Job(learner, cleansedInstances); WSResponse solverResponse = newJob.sendAndReceiveRequestsFromSolver(); List<TextAnnotation> solvedInstances = newJob.getSolverInstances(); List<Boolean> skip = newJob.getSkip(); EvaluationRecord eval = evaluate(runConfig, correctInstances, solvedInstances, skip); storeEvaluationIntoDb(eval, record_id); System.out.println(solverResponse); return solverResponse; }
Source:
<code>protected void executeVmCommand() { boolean <START> isPlugged = <END> getParameters().getAction() == PlugAction.PLUG; if (isPlugged){ clearAddressIfPciSlotIsDuplicated(vmDevice); } if (hotPlugVmNicRequired(getVm().getStatus())) { boolean externalNetworkIsPlugged = isPlugged && getNetwork() != null && getNetwork().isExternal(); if (externalNetworkIsPlugged) { plugToExternalNetwork(); } try { runVdsCommand(getParameters().getAction().getCommandType(), new VmNicDeviceVDSParameters(getVdsId(), getVm(), getParameters().getNic(), vmDevice)); } catch (EngineException e) { if (externalNetworkIsPlugged && getParameters().isNewNic()) { unplugFromExternalNetwork(); } throw e; } } TransactionSupport.executeInNewTransaction(updateDevice()); setSucceeded(true); }</code><technical_language>is isPlugged? parameter action mean, is plugged plugged? ..</technical_language>

Target:
protected void executeVmCommand() { boolean isNicToBePlugged = getParameters().getAction() == PlugAction.PLUG; if (isNicToBePlugged){ clearAddressIfPciSlotIsDuplicated(vmDevice); } if (hotPlugVmNicRequired(getVm().getStatus())) { boolean externalNetworkIsPlugged = isNicToBePlugged && getNetwork() != null && getNetwork().isExternal(); if (externalNetworkIsPlugged) { plugToExternalNetwork(); } try { runVdsCommand(getParameters().getAction().getCommandType(), new VmNicDeviceVDSParameters(getVdsId(), getVm(), getParameters().getNic(), vmDevice)); } catch (EngineException e) { if (externalNetworkIsPlugged && getParameters().isNewNic()) { unplugFromExternalNetwork(); } throw e; } } TransactionSupport.executeInNewTransaction(updateDevice()); setSucceeded(true); }
Source:
<code>public static <T> FactorComparator<T> create(String factorName, int weight, Comparator<T> comparator){ if (null == factorName || factorName == "" || weight < 0 || null == comparator){ logger.error("failed to create instance of FactorComparator, at least one of the input paramters are invalid"); <START> return null; <END> } return new FactorComparator<T>(factorName,weight,comparator); }</code><technical_language>throw exception</technical_language>

Target:
public static <T> FactorComparator<T> create(String factorName, int weight, Comparator<T> comparator){ if (null == factorName || factorName.length() == 0 || weight < 0 || null == comparator){ logger.error("failed to create instance of FactorComparator, at least one of the input paramters are invalid"); return null; } return new FactorComparator<T>(factorName,weight,comparator); }
Source:
<code>public SpongeBreakableData(Set<BlockType> breakable) { <START> super(BreakableData.class, breakable, Keys.BREAKABLE_BLOCK_TYPES); <END> }</code><technical_language>making a defensive copy of Set</technical_language>

Target:
public SpongeBreakableData(Set<BlockType> breakable) { super(BreakableData.class, Sets.newHashSet(breakable), Keys.BREAKABLE_BLOCK_TYPES, ImmutableSpongeBreakableData.class); }
Source:
<code>public Block getPositions(int[] positions, int offset, int length) { checkValidPositions(positions, offset, length, positionCount); int[] newIds = new int[length]; boolean isCompact = isCompact() && length >= dictionary.getPositionCount(); boolean[] seen = null; if (isCompact) { <START> seen = new boolean[dictionary.getPositionCount()]; <END> } for (int i = 0; i < length; i++) { newIds[i] = getId(positions[offset + i]); if (isCompact) { seen[newIds[i]] = true; } } for (int i = 0; i < dictionary.getPositionCount() && isCompact; i++) { isCompact &= seen[i]; } return new DictionaryBlock(newIds.length, getDictionary(), newIds, isCompact, getDictionarySourceId()); }</code><technical_language>nit: for (int i = offset; i < offset + length; ++i)</technical_language>

Target:
public Block getPositions(int[] positions, int offset, int length) { checkArrayRange(positions, offset, length); int[] newIds = new int[length]; boolean isCompact = isCompact() && length >= dictionary.getPositionCount(); boolean[] seen = null; if (isCompact) { seen = new boolean[dictionary.getPositionCount()]; } for (int i = 0; i < length; i++) { newIds[i] = getId(positions[offset + i]); if (isCompact) { seen[newIds[i]] = true; } } for (int i = 0; i < dictionary.getPositionCount() && isCompact; i++) { isCompact &= seen[i]; } return new DictionaryBlock(newIds.length, getDictionary(), newIds, isCompact, getDictionarySourceId()); }
Source:
<code>private static void testLinkStatus(SWTBotTreeItem traceItem, boolean isLinked) { <START> SWTBotView viewBot = fBot.viewByTitle("Properties"); <END> viewBot.setFocus(); fBot.waitUntil(ConditionHelpers.viewIsOpened(viewBot)); traceItem.select(); SWTBotTree tree = viewBot.bot().tree(); fBot.waitUntil(ConditionHelpers.IsTreeNodeAvailable(RESOURCE_PROPERTIES_ITEM_NAME, tree)); SWTBotTreeItem resourcePropertiesItem = tree.getTreeItem(RESOURCE_PROPERTIES_ITEM_NAME); fBot.waitUntil(ConditionHelpers.IsTreeChildNodeAvailable(LINKED_ITEM_NAME, resourcePropertiesItem)); SWTBotTreeItem linkedNode = resourcePropertiesItem.getNode(LINKED_ITEM_NAME); String linkedValue = linkedNode.cell(1); assertEquals(Boolean.toString(isLinked), linkedValue); }</code><technical_language>viewBot.show() selecting tree item enough? this point is view is created (it a view reference for a background tab)</technical_language>

Target:
private static void testLinkStatus(SWTBotTreeItem traceItem, boolean isLinked) { SWTBotView viewBot = fBot.viewByTitle("Properties"); viewBot.show(); fBot.waitUntil(ConditionHelpers.viewIsOpened(viewBot)); traceItem.select(); SWTBotTree tree = viewBot.bot().tree(); SWTBotTreeItem resourcePropertiesItem = tree.getTreeItem(RESOURCE_PROPERTIES_ITEM_NAME); fBot.waitUntil(ConditionHelpers.IsTreeChildNodeAvailable(LINKED_ITEM_NAME, resourcePropertiesItem)); SWTBotTreeItem linkedNode = resourcePropertiesItem.getNode(LINKED_ITEM_NAME); String linkedValue = linkedNode.cell(1); assertEquals(Boolean.toString(isLinked), linkedValue); }
Source:
<code>private String generateDisplayName(Map<String, String> surveyInstanceResponses) { StringBuilder displayName = new StringBuilder(); <START> for (int i = 0; i < displayNameQuestionIds.size(); i++) { <END> Long questionId = displayNameQuestionIds.get(i); displayName.append(surveyInstanceResponses.get(questionId.toString())); if (i < displayNameQuestionIds.size() - 1) { displayName.append(" - "); } } return displayName.toString(); }</code><technical_language>a _style_ change. This rewritten as: java for (String displayName: displayNameQuestionIds) { // do } need track of indices etc. conversation @ichinaski this loop is "too much". loop verify if element. IMHO, "simpler" remove trailing - end building string</technical_language>

Target:
private String generateDisplayName(Map<String, String> surveyInstanceResponses) { StringBuilder displayName = new StringBuilder(); for (Long questionId : displayNameQuestionIds) { displayName.append(surveyInstanceResponses.get(questionId.toString())).append(" - "); } int length = displayName.length(); displayName.delete(length - 3, length); return displayName.toString(); }
Source:
<code>public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Optional<User> user = userFetcher.userFor(request); if (authenticationIsRequired(request) && !user.isPresent()) { ResponseWriter writer = writerResolver.writerFor(request, response); ErrorSummary summary = ErrorSummary.forException(new NotAuthorizedException()); new ErrorResultWriter().write(summary, writer, request, response); return false; } if (user.isPresent() && !user.get().isProfileComplete() && requiresCompleteProfile(request, user.get())) { ResponseWriter writer = writerResolver.writerFor(request, response); ErrorSummary summary = ErrorSummary.forException(new UserProfileIncompleteException()); <START> new ErrorResultWriter().write(summary, writer, request, response); <END> return false; } return true; }</code><technical_language>refactor this avoid code duplication in two, similar, conditions</technical_language>

Target:
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Optional<User> user = userFetcher.userFor(request); String uri = request.getRequestURI(); if (!authorized(user, uri)) { writeError(request, response, new NotAuthorizedException()); return false; } else if (user.isPresent() && !hasProfile(user.get()) && needsProfile(uri, user.get())) { writeError(request, response, new UserProfileIncompleteException()); return false; } return true; }
Source:
<code>protected String getPrimaryKeySelection() { <START> return COL_LAST_USED + " = ?"; <END> }</code><technical_language>this COL_SUMMARY</technical_language>

Target:
protected String getPrimaryKeySelection() { return COL_SUMMARY + " = ?"; }
Source:
<code>private void handleResponse(MessageContext msgContext, HttpMethodBase method) throws IOException { int statusCode = method.getStatusCode(); <START> HTTPStatusCodeFamily family = getHTTPStatusCodeFamily(statusCode); <END> log.trace("Handling response - " + statusCode); Set<Integer> errorCodes = new HashSet<Integer>(); String strRetryErrorCodes = (String) msgContext.getProperty(HTTPConstants.ERROR_HTTP_STATUS_CODES); if (strRetryErrorCodes != null && !strRetryErrorCodes.trim().equals("")) { for (String strRetryErrorCode : strRetryErrorCodes.split(",")) { try { errorCodes.add(Integer.valueOf(strRetryErrorCode)); } catch (NumberFormatException e) { log.warn(strRetryErrorCode + " is not a valid status code"); } } } if (!errorCodes.contains(statusCode)) { msgContext.setProperty(HTTPConstants.HTTP_METHOD, method); processResponse(method, msgContext); } else { method.releaseConnection(); msgContext.setProperty(HTTPConstants.MC_HTTP_STATUS_CODE, method.getStatusCode()); AxisFault axisFault = new AxisFault( Messages.getMessage("transportError", String.valueOf(statusCode), method.getStatusText()), msgContext); axisFault.setFaultCode(String.valueOf(method.getStatusCode())); throw axisFault; } }</code><technical_language>do need this anymore ? method getHTTPStatusCodeFamily</technical_language>

Target:
private void handleResponse(MessageContext msgContext, HttpMethodBase method) throws IOException { int statusCode = method.getStatusCode(); log.trace("Handling response - " + statusCode); Set<Integer> errorCodes = new HashSet<Integer>(); String strRetryErrorCodes = (String) msgContext.getProperty(HTTPConstants.ERROR_HTTP_STATUS_CODES); if (strRetryErrorCodes != null && !strRetryErrorCodes.trim().equals("")) { for (String strRetryErrorCode : strRetryErrorCodes.split(",")) { try { errorCodes.add(Integer.valueOf(strRetryErrorCode)); } catch (NumberFormatException e) { log.warn(strRetryErrorCode + " is not a valid status code"); } } } if (!errorCodes.contains(statusCode)) { msgContext.setProperty(HTTPConstants.HTTP_METHOD, method); processResponse(method, msgContext); } else { method.releaseConnection(); msgContext.setProperty(HTTPConstants.MC_HTTP_STATUS_CODE, method.getStatusCode()); AxisFault axisFault = new AxisFault( Messages.getMessage("transportError", String.valueOf(statusCode), method.getStatusText()), msgContext); axisFault.setFaultCode(String.valueOf(method.getStatusCode())); throw axisFault; } }
Source:
<code>public void testNonExistingHomeFolder() throws Exception { <START> System.setProperty("user.home", "/?"); <END> final Object result = invokeGetHistory(); assertNotNull(result, "result is null"); final MemoryHistory history = (MemoryHistory) result; history.add("foo foo"); assertFalse(history instanceof PersistentHistory, "must not be PersistentHistory"); }</code><technical_language>is this affect other tests run JVM</technical_language>

Target:
public void testNonExistingHomeFolder() throws Exception { final File historyFile = new File("/?", ".history"); assertFalse(historyFile.canRead(), "shouldn't read invalid location"); assertFalse(historyFile.canWrite(), "shouldn't write invalid location"); MemoryHistory result = Console.getHistory(historyFile); assertNotNull(result, "result is null"); result.add("foo foo"); assertFalse(result instanceof PersistentHistory, "must not be PersistentHistory"); }
Source:
<code>private ResultSet getNextResultSet() { closeCurrentResultSet(); if (!tableIds.hasNext()) { return null; } Long tableId = tableIds.next(); Long columnId = metadataDao.getTemporalColumnId(tableId); String minColumn = "null"; String maxColumn = "null"; if (columnId != null) { Type columnType = metadataDao.getTableColumn(tableId, columnId).getDataType(); <START> checkState(columnType.equals(DATE) || columnType.equals(TIMESTAMP), "Temporal column must be of type timestamp or date: " + columnType); <END> if (columnType.equals(DATE)) { minColumn = convertDaysToMidnightTimestamp(minColumn(columnId)); maxColumn = convertDaysToMidnightTimestamp(maxColumn(columnId)); } else { minColumn = minColumn(columnId); maxColumn = maxColumn(columnId); } } List<String> columnNames = getMappedColumnNames(minColumn, maxColumn); try { connection = dbi.open().getConnection(); statement = PreparedStatementBuilder.create( connection, constructSqlTemplate(columnNames, tableId), columnNames, TYPES, ImmutableSet.of(getColumnIndex(SHARD_METADATA, SHARD_UUID)), tupleDomain); return statement.executeQuery(); } catch (SQLException | DBIException e) { close(); throw metadataError(e); } }</code><technical_language>"%s" substitution</technical_language>

Target:
private ResultSet getNextResultSet() { closeCurrentResultSet(); if (!tableIds.hasNext()) { return null; } Long tableId = tableIds.next(); Long columnId = metadataDao.getTemporalColumnId(tableId); String minColumn = "null"; String maxColumn = "null"; if (columnId != null) { Type columnType = metadataDao.getTableColumn(tableId, columnId).getDataType(); checkState(columnType.equals(DATE) || columnType.equals(TIMESTAMP), "Temporal column must be of type timestamp or date: %s", columnType); if (columnType.equals(DATE)) { minColumn = convertDaysToMidnightTimestamp(minColumn(columnId)); maxColumn = convertDaysToMidnightTimestamp(maxColumn(columnId)); } else { minColumn = minColumn(columnId); maxColumn = maxColumn(columnId); } } List<String> columnNames = getMappedColumnNames(minColumn, maxColumn); try { connection = dbi.open().getConnection(); statement = PreparedStatementBuilder.create( connection, constructSqlTemplate(columnNames, tableId), columnNames, TYPES, ImmutableSet.of(getColumnIndex(SHARD_METADATA, SHARD_UUID)), tupleDomain); return statement.executeQuery(); } catch (SQLException | DBIException e) { close(); throw metadataError(e); } }
Source:
<code>public void testCorruptedFrameExceptionInFinish() { EmbeddedChannel channel = new EmbeddedChannel(new Utf8FrameValidator()); try { channel.writeInbound(new TextWebSocketFrame(Unpooled.copiedBuffer(new byte[]{-50}))); Assert.fail(); } catch (CorruptedFrameException e) { <START> } <END> }</code><technical_language>@riyafa call channel.finish() assert return</technical_language>

Target:
public void testCorruptedFrameExceptionInFinish() { assertCorruptedFrameExceptionHandling(new byte[]{-50}); }
Source:
<code><START> public void testStateChangeWithTransitiveState() throws InterruptedException { <END> AgentMessageProcessor processor = (AgentMessageProcessor) this.agent.getMessagingClient().getMessageProcessor(); TestApplicationTemplate app = new TestApplicationTemplate(); processor.scopedInstance = app.getMySqlVm(); for( InstanceStatus status : InstanceStatus.values()) { if( status.isStable()) continue; app.getMySql().setStatus( status ); processor.processMessage( new MsgCmdChangeInstanceState( app.getMySql(), InstanceStatus.DEPLOYED_STARTED )); Assert.assertEquals( status, app.getMySql().getStatus()); } }</code><technical_language>No, this method throw interrupted exceptions</technical_language>

Target:
public void testStateChangeWithTransitiveState() { AgentMessageProcessor processor = (AgentMessageProcessor) this.agent.getMessagingClient().getMessageProcessor(); TestApplicationTemplate app = new TestApplicationTemplate(); processor.scopedInstance = app.getMySqlVm(); for( InstanceStatus status : InstanceStatus.values()) { if( status.isStable()) continue; app.getMySql().setStatus( status ); processor.processMessage( new MsgCmdChangeInstanceState( app.getMySql(), InstanceStatus.DEPLOYED_STARTED )); Assert.assertEquals( status, app.getMySql().getStatus()); } }
Source:
<code>private static String requestPath(final Ds3Request ds3Request) { final StringBuilder builder = new StringBuilder(); if (ds3Request.getClassification() == Classification.amazons3) { builder.append("\"/\""); if (ds3Request.getBucketRequirement() == Requirement.REQUIRED) { builder.append(" + this.bucketName"); if (ds3Request.getObjectRequirement() == Requirement.REQUIRED) { builder.append(" + \"/\" + this.objectName"); } } } else { <START> if (ds3Request.getResource() == Resource.BUCKET) { <END> builder.append("\"/_rest_/bucket/\""); if (!queryParamsContain(ds3Request.getRequiredQueryParams(), "Name")) { builder.append(" + this.bucketName"); } } else { builder.append("\"/_rest_/\""); } } return builder.toString(); }</code><technical_language>add this kind of logic for resource type. this is ask jason</technical_language>

Target:
private static String requestPath(final Ds3Request ds3Request) { final StringBuilder builder = new StringBuilder(); if (ds3Request.getClassification() == Classification.amazons3) { builder.append("\"/\""); if (ds3Request.getBucketRequirement() == Requirement.REQUIRED) { builder.append(" + this.bucketName"); if (ds3Request.getObjectRequirement() == Requirement.REQUIRED) { builder.append(" + \"/\" + this.objectName"); } } } else { if (ds3Request.getResource() != null) { builder.append("\"/_rest_/" + ds3Request.getResource().toString().toLowerCase() + "/\""); if (!queryParamsContain(ds3Request.getRequiredQueryParams(), "Name")) { builder.append(" + this.bucketName"); } } else { builder.append("\"/_rest_/\""); } } return builder.toString(); }
Source:
<code>public void takeThreadDump() throws FileNotFoundException, UnsupportedEncodingException { long iota = System.currentTimeMillis(); final SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd-HHmmss.SSS"); File file = threadDumps.file(format.format("threadDump-" + new Date(iota)) + ".txt"); threadDumps.add(file); PrintWriter writer; try { writer = new PrintWriter(file, "UTF-8"); } catch (FileNotFoundException e) { throw e; } catch (UnsupportedEncodingException e) { throw e; <START> } <END> ThreadMXBean mbean = ManagementFactory.getThreadMXBean(); ThreadInfo[] threads; try { threads = mbean.dumpAllThreads(mbean.isObjectMonitorUsageSupported(), mbean.isSynchronizerUsageSupported()); } catch (UnsupportedOperationException x) { x.printStackTrace(writer); threads = new ThreadInfo[0]; } for (int ti = threads.length - 1; ti >= 0; ti--) { printThreadInfo(writer, threads[ti], mbean); } long[] deadLocks; try { deadLocks = mbean.findDeadlockedThreads(); } catch (UnsupportedOperationException x) { x.printStackTrace(writer); deadLocks = null; } if (deadLocks != null && deadLocks.length != 0) { writer.println(" Deadlock Found "); ThreadInfo[] deadLockThreads = mbean.getThreadInfo(deadLocks); for (ThreadInfo threadInfo : deadLockThreads) { StackTraceElement[] elements = threadInfo.getStackTrace(); for (StackTraceElement element : elements) { writer.println(element.toString()); } } } writer.println(); writer.flush(); writer.close(); }</code><technical_language>I missing something. Is try/catch block useful</technical_language>

Target:
public void takeThreadDump() throws FileNotFoundException, UnsupportedEncodingException { long iota = System.currentTimeMillis(); final SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd-HHmmss.SSS"); File file = threadDumps.file(format.format("threadDump-" + new Date(iota)) + ".txt"); threadDumps.add(file); PrintWriter writer; writer = new PrintWriter(file, "UTF-8"); ThreadMXBean mbean = ManagementFactory.getThreadMXBean(); ThreadInfo[] threads; try { threads = mbean.dumpAllThreads(mbean.isObjectMonitorUsageSupported(), mbean.isSynchronizerUsageSupported()); } catch (UnsupportedOperationException x) { x.printStackTrace(writer); threads = new ThreadInfo[0]; } for (int ti = threads.length - 1; ti >= 0; ti--) { printThreadInfo(writer, threads[ti], mbean); } long[] deadLocks; try { deadLocks = mbean.findDeadlockedThreads(); if (deadLocks != null && deadLocks.length != 0) { writer.println(" Deadlock Found "); ThreadInfo[] deadLockThreads = mbean.getThreadInfo(deadLocks); for (ThreadInfo threadInfo : deadLockThreads) { StackTraceElement[] elements = threadInfo.getStackTrace(); for (StackTraceElement element : elements) { writer.println(element.toString()); } } } } catch (UnsupportedOperationException e) { e.printStackTrace(writer); } finally { writer.println(); writer.flush(); writer.close(); } }
Source:
<code>private void addDescriptorToLookups( SchemaDescriptor schema ) { if ( schema.entityType() == EntityType.NODE ) { <START> if ( schema.getEntityTokenIds().length == 0 ) <END> { descriptorsForAllLabels.add( schema ); } for ( int entityTokenId : schema.getEntityTokenIds() ) { addToLookup( entityTokenId, schema, descriptorsByLabel ); } for ( int propertyId : schema.getPropertyIds() ) { addToLookup( propertyId, schema, descriptorsByProperty ); } } else if ( schema.entityType() == EntityType.RELATIONSHIP ) { if ( schema.getEntityTokenIds().length == 0 ) { descriptorsForAllReltypes.add( schema ); } for ( int entityTokenId : schema.getEntityTokenIds() ) { addToLookup( entityTokenId, schema, descriptorsByReltype ); } for ( int propertyId : schema.getPropertyIds() ) { addToLookup( propertyId, schema, relationshipDescriptorsByProperty ); } } }</code><technical_language>this ANY_ENTITY_TOKEN</technical_language>

Target:
private void addDescriptorToLookups( SchemaDescriptor schema ) { if ( schema.entityType() == EntityType.NODE ) { if ( SchemaDescriptor.isAnyEntityTokenSchema( schema ) ) { descriptorsForAllLabels.add( schema ); } for ( int entityTokenId : schema.getEntityTokenIds() ) { addToLookup( entityTokenId, schema, descriptorsByLabel ); } for ( int propertyId : schema.getPropertyIds() ) { addToLookup( propertyId, schema, nodeDescriptorsByProperty ); } } else if ( schema.entityType() == EntityType.RELATIONSHIP ) { if ( SchemaDescriptor.isAnyEntityTokenSchema( schema ) ) { descriptorsForAllReltypes.add( schema ); } for ( int entityTokenId : schema.getEntityTokenIds() ) { addToLookup( entityTokenId, schema, descriptorsByReltype ); } for ( int propertyId : schema.getPropertyIds() ) { addToLookup( propertyId, schema, relationshipDescriptorsByProperty ); } } }
Source:
<code>public String apply(String text, String format) { final byte[] value; switch (Format.valueOf(format.toUpperCase(Locale.ROOT))) { case BASE64: value = Base64.getDecoder().decode(text.getBytes(StandardCharsets.UTF_8)); break; case HEX: <START> return String.format(Locale.ROOT, "%s%s", Hex.HEX_FLAG, Hex.validateHex(text)); <END> case ESCAPE: value = Octal.decode(text); break; default: throw new RuntimeException(); } assert value != null; return String.format(Locale.ROOT, "%s%s", Hex.HEX_FLAG, Hex.encodeHexString(value)); }</code><technical_language>I string concatenation is faster cheaper string format</technical_language>

Target:
public String apply(String text, String format) { final Format fmt; try { fmt = Format.valueOf(format.toUpperCase(Locale.ROOT)); } catch (IllegalArgumentException e) { throw new IllegalArgumentException( String.format(Locale.ENGLISH, "Encoding format '%s' is not supported", format) ); } return fmt.decode(text); }
Source:
<code><START> public static <T> DataType<T> dataType(String insertType, Type prestoResultType) <END> { return new DataType<>(insertType, prestoResultType, Object::toString, Function.identity()); }</code><technical_language>this method is good assumptions (that is: toString() produces good SQL literal), private</technical_language>

Target:
private static <T> DataType<T> dataType(String insertType, Type prestoResultType) { return new DataType<>(insertType, prestoResultType, Object::toString, Function.identity()); }
Source:
<code>public void populateRightPanel(final RightPanelView.Presenter rightPanelPresenter, final ScenarioGridModel scenarioGridModel) { String dmnFilePath = model.getSimulation().getSimulationDescriptor().getDmnFilePath(); if(factModelTreeHolder.getFactModelTuple() != null) { getSuccessCallback(rightPanelPresenter, scenarioGridModel).callback(factModelTreeHolder.getFactModelTuple()); } else { try { dmnTypeService.call(getSuccessCallback(rightPanelPresenter, scenarioGridModel), getErrorCallback(rightPanelPresenter)) .retrieveFactModelTuple(currentPath, dmnFilePath); <START> } catch (Exception e) { <END> eventBus.fireEvent(new ScenarioNotificationEvent("Failed to parse DMN", NotificationEvent.NotificationType.ERROR)); } } }</code><technical_language>This is a remote method call, I exception is fired. I expect wrapped invoked getErrorCallback in case of error</technical_language>

Target:
public void populateRightPanel(final RightPanelView.Presenter rightPanelPresenter, final ScenarioGridModel scenarioGridModel) { String dmnFilePath = model.getSimulation().getSimulationDescriptor().getDmnFilePath(); if (factModelTreeHolder.getFactModelTuple() != null) { getSuccessCallback(rightPanelPresenter, scenarioGridModel).callback(factModelTreeHolder.getFactModelTuple()); } else { dmnTypeService.call(getSuccessCallback(rightPanelPresenter, scenarioGridModel), getErrorCallback(rightPanelPresenter)) .retrieveFactModelTuple(currentPath, dmnFilePath); } }
Source:
<code><START> static ResourceResult getResources(Context context, Request data) throws FileNotFoundException { <END> Resources res; int id; if (data.resourceId != 0 || data.uri == null) { res = context.getResources(); id = data.resourceId; return new ResourceResult(res, id); } String pkg = data.uri.getAuthority(); if (pkg == null) throw new FileNotFoundException("No package provided: " + data.uri); try { PackageManager pm = context.getPackageManager(); res = pm.getResourcesForApplication(pkg); } catch (PackageManager.NameNotFoundException e) { throw new FileNotFoundException("Unable to obtain resources for package: " + data.uri); } List<String> segments = data.uri.getPathSegments(); if (segments == null || segments.isEmpty()) { throw new FileNotFoundException("No path segments: " + data.uri); } else if (segments.size() == 1) { try { id = Integer.parseInt(segments.get(0)); } catch (NumberFormatException e) { throw new FileNotFoundException("Last path segment is not a resource ID: " + data.uri); } } else if (segments.size() == 2) { String type = segments.get(0); String name = segments.get(1); id = res.getIdentifier(name, type, pkg); } else { throw new FileNotFoundException("More than two path segments: " + data.uri); } return new ResourceResult(res, id); }</code><technical_language>Method name getResourceResult</technical_language>

Target:
static Resources getResources(Context context, Request data) throws FileNotFoundException { if (data.resourceId != 0 || data.uri == null) { return context.getResources(); } String pkg = data.uri.getAuthority(); if (pkg == null) throw new FileNotFoundException("No package provided: " + data.uri); try { PackageManager pm = context.getPackageManager(); return pm.getResourcesForApplication(pkg); } catch (PackageManager.NameNotFoundException e) { throw new FileNotFoundException("Unable to obtain resources for package: " + data.uri); } }
Source:
<code>public void testWikiExample() { final CacheManager cacheManager = newCacheManagerBuilder() .withCache("preConfigured", newCacheConfigurationBuilder().buildConfig(Long.class, String.class)) .build(); final Cache<Long, String> preConfigured = cacheManager.getCache("preConfigured", Long.class, String.class); final Cache<Long, String> myCache = cacheManager.createCache("myCache", newCacheConfigurationBuilder().buildConfig(Long.class, String.class)); myCache.put(1L, "da one!"); final String value = myCache.get(1L); cacheManager.removeCache("preConfigured"); <START> final StandaloneCache<Long, String> standaloneCache = newCacheBuilder(Long.class, String.class, LoggerFactory.getLogger(Ehcache.class+"GettingStarted")) <END> .build(); standaloneCache.init(); cacheManager.close(); standaloneCache.close(); }</code><technical_language>Misses separator</technical_language>

Target:
public void testWikiExample() { final CacheManager cacheManager = newCacheManagerBuilder() .withCache("preConfigured", newCacheConfigurationBuilder().buildConfig(Long.class, String.class)) .build(); final Cache<Long, String> preConfigured = cacheManager.getCache("preConfigured", Long.class, String.class); final Cache<Long, String> myCache = cacheManager.createCache("myCache", newCacheConfigurationBuilder().buildConfig(Long.class, String.class)); myCache.put(1L, "da one!"); final String value = myCache.get(1L); cacheManager.removeCache("preConfigured"); final StandaloneCache<Long, String> standaloneCache = newCacheBuilder(Long.class, String.class, LoggerFactory.getLogger(Ehcache.class + "-" + "GettingStarted")) .build(); standaloneCache.init(); cacheManager.close(); standaloneCache.close(); }