auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void setInizialStateWithLastCallScenes() { if (sceneMan != null) { JsonObject response = connMan.getDigitalSTROMAPI().query2(connMan.getSessionToken(), LAST_CALL_SCENE_QUERY); if (response.isJsonObject()) { for (Entry<String, JsonElement> entry : response.entrySet()) { if (entry.getValue().isJsonObject()) { JsonObject zone = entry.getValue().getAsJsonObject(); int zoneID = -1; short groupID = -1; short sceneID = -1; if (zone.get(JSONApiResponseKeysEnum.ZONE_ID.getKey()) != null) { zoneID = zone.get(JSONApiResponseKeysEnum.ZONE_ID.getKey()).getAsInt(); } for (Entry<String, JsonElement> groupEntry : zone.entrySet()) { if (groupEntry.getKey().startsWith("group") && groupEntry.getValue().isJsonObject()) { JsonObject group = groupEntry.getValue().getAsJsonObject(); if (group.get(JSONApiResponseKeysEnum.DEVICES.getKey()) != null) { if (group.get(JSONApiResponseKeysEnum.GROUP.getKey()) != null) { groupID = group.get(JSONApiResponseKeysEnum.GROUP.getKey()).getAsShort(); } if (group.get(JSONApiResponseKeysEnum.LAST_CALL_SCENE.getKey()) != null) { sceneID = group.get(JSONApiResponseKeysEnum.LAST_CALL_SCENE.getKey()) .getAsShort(); } if (zoneID > -1 && groupID > -1 && sceneID > -1) { logger.debug( "inizial state, call scene " + zoneID + "-" + groupID + "-" + sceneID); sceneMan.callInternalSceneWithoutDiscovery(zoneID, groupID, sceneID); } } } } } } } } }

Target:
private void setInizialStateWithLastCallScenes() { if (sceneMan == null) { return; } JsonObject response = connMan.getDigitalSTROMAPI().query2(connMan.getSessionToken(), LAST_CALL_SCENE_QUERY); if (!response.isJsonObject()) { return; } for (Entry<String, JsonElement> entry : response.entrySet()) { if (!entry.getValue().isJsonObject()) { continue; } JsonObject zone = entry.getValue().getAsJsonObject(); int zoneID = -1; short groupID = -1; short sceneID = -1; if (zone.get(JSONApiResponseKeysEnum.ZONE_ID.getKey()) != null) { zoneID = zone.get(JSONApiResponseKeysEnum.ZONE_ID.getKey()).getAsInt(); } for (Entry<String, JsonElement> groupEntry : zone.entrySet()) { if (groupEntry.getKey().startsWith("group") && groupEntry.getValue().isJsonObject()) { JsonObject group = groupEntry.getValue().getAsJsonObject(); if (group.get(JSONApiResponseKeysEnum.DEVICES.getKey()) != null) { if (group.get(JSONApiResponseKeysEnum.GROUP.getKey()) != null) { groupID = group.get(JSONApiResponseKeysEnum.GROUP.getKey()).getAsShort(); } if (group.get(JSONApiResponseKeysEnum.LAST_CALL_SCENE.getKey()) != null) { sceneID = group.get(JSONApiResponseKeysEnum.LAST_CALL_SCENE.getKey()).getAsShort(); } if (zoneID > -1 && groupID > -1 && sceneID > -1) { logger.debug("initial state, call scene {}-{}-{}", zoneID, groupID, sceneID); sceneMan.callInternalSceneWithoutDiscovery(zoneID, groupID, sceneID); } } } } } }
Source:
public List<Action> getActionLinks(BusinessObjectBase businessObject, Person user) { BatchFile batchFile = (BatchFile) businessObject; List<Action> actionLinks = new LinkedList<>(); if (canCreateDoneFile(batchFile, user)) { actionLinks.add(new Action("Create Done", "GET", getCreateDoneUrl(batchFile))); } return actionLinks; }

Target:
public List<Action> getActionLinks(BusinessObjectBase businessObject, Person user) { BatchFile batchFile = (BatchFile) businessObject; List<Action> actionLinks = new LinkedList<>(); if (canCreateDoneFile(batchFile, user)) { actionLinks.add(new Action("Create Done", "GET", KRAD_URL_PREFIX + getCreateDoneUrl(batchFile))); } return actionLinks; }
Source:
public void saveOrder_shouldPassForADiscontinuationOrderWithNoPreviousOrder() { String fulfillerComment ="Some example comment"; TestOrder dcOrder = new TestOrder(); dcOrder.setAction(Action.DISCONTINUE); dcOrder.setPatient(patientService.getPatient(2)); dcOrder.setCareSetting(orderService.getCareSetting(2)); dcOrder.setConcept(conceptService.getConcept(5089)); dcOrder.setEncounter(encounterService.getEncounter(6)); dcOrder.setOrderer(providerService.getProvider(1)); dcOrder.setFulfillerStatus(Order.FulfillerStatus.RECEIVED); dcOrder.setFulfillerComment(fulfillerComment); int order_id = orderService.saveOrder(dcOrder, null).getId(); Order savedOrder = orderService.getOrder(order_id); assertEquals(savedOrder.getFulfillerStatus(), Order.FulfillerStatus.RECEIVED); assertEquals(savedOrder.getFulfillerComment(), fulfillerComment); }

Target:
public void saveOrder_shouldPassForADiscontinuationOrderWithNoPreviousOrder() { TestOrder dcOrder = new TestOrder(); dcOrder.setAction(Action.DISCONTINUE); dcOrder.setPatient(patientService.getPatient(2)); dcOrder.setCareSetting(orderService.getCareSetting(2)); dcOrder.setConcept(conceptService.getConcept(5089)); dcOrder.setEncounter(encounterService.getEncounter(6)); dcOrder.setOrderer(providerService.getProvider(1)); orderService.saveOrder(dcOrder, null); }
Source:
private void onCtrlMsgIdRange(final AvroElasticMemoryMessage msg, final TraceScope parentTraceInfo) { final String operationId = msg.getOperationId().toString(); final CtrlMsg ctrlMsg = msg.getCtrlMsg(); final String dataType = ctrlMsg.getDataType().toString(); final Codec codec = serializer.getCodec(dataType); final Set<Map<Long, Object>> idObjectMapSet = new HashSet<>(); int numObject = 0; for (final AvroLongRange avroLongRange : ctrlMsg.getIdRange()) { final Map<Long, Object> idObjectMap = memoryStore.getElasticStore().getRange(dataType, avroLongRange.getMin(), avroLongRange.getMax()); numObject += idObjectMap.size(); idObjectMapSet.add(idObjectMap); } final Set<Long> ids = new HashSet<>(); final List<UnitIdPair> unitIdPairList = new ArrayList<>(numObject); for (final Map<Long, Object> idObjectMap : idObjectMapSet) { for (final Map.Entry<Long, Object> idObject : idObjectMap.entrySet()) { final long id = idObject.getKey(); final UnitIdPair unitIdPair = UnitIdPair.newBuilder() .setUnit(ByteBuffer.wrap(codec.encode(idObject.getValue()))) .setId(id) .build(); unitIdPairList.add(unitIdPair); ids.add(id); } } pendingUpdates.put(operationId, new RemoveInfo(dataType, ids)); sender.get().sendDataMsg(msg.getDestId().toString(), ctrlMsg.getDataType().toString(), unitIdPairList, operationId, TraceInfo.fromSpan(parentTraceInfo.getSpan())); }

Target:
private void onCtrlMsgIdRange(final AvroElasticMemoryMessage msg, final TraceScope parentTraceInfo) { final String operationId = msg.getOperationId().toString(); final CtrlMsg ctrlMsg = msg.getCtrlMsg(); final String dataType = ctrlMsg.getDataType().toString(); final Codec codec = serializer.getCodec(dataType); final List<UnitIdPair> unitIdPairList = new ArrayList<>(); final SortedSet<Long> ids = new TreeSet<>(); for (final AvroLongRange avroLongRange : ctrlMsg.getIdRange()) { final Map<Long, Object> idObjectMap = memoryStore.getElasticStore().getRange(dataType, avroLongRange.getMin(), avroLongRange.getMax()); for (final Map.Entry<Long, Object> idObject : idObjectMap.entrySet()) { final long id = idObject.getKey(); if (!isMoving(id)) { final UnitIdPair unitIdPair = UnitIdPair.newBuilder() .setUnit(ByteBuffer.wrap(codec.encode(idObject.getValue()))) .setId(id) .build(); unitIdPairList.add(unitIdPair); ids.add(id); } } } if (ids.size() == 0) { final String myId = msg.getDestId().toString(); final String reason = new StringBuilder() .append("No data is movable in ").append(myId) .append(" of type ").append(dataType) .append(". Requested ranges: ").append(Arrays.toString(ctrlMsg.getIdRange().toArray())) .toString(); sender.get().sendFailureMsg(operationId, reason, TraceInfo.fromSpan(parentTraceInfo.getSpan())); return; } final Set<LongRange> ranges = LongRangeUtils.generateDenseLongRanges(ids); pendingUpdates.put(operationId, new Remove(dataType, ranges)); movingRanges.addAll(ranges); sender.get().sendDataMsg(msg.getDestId().toString(), ctrlMsg.getDataType().toString(), unitIdPairList, operationId, TraceInfo.fromSpan(parentTraceInfo.getSpan())); }
Source:
public static AlluxioURI findLowestCommonAncestor(Collection<AlluxioURI> paths) { if (paths == null || paths.isEmpty()) { return null; } List<String> matchedComponents = null; int matchedLen = 0; for (AlluxioURI path : paths) { String[] pathComp = path.getPath().split(AlluxioURI.SEPARATOR); if (matchedComponents == null) { matchedComponents = new ArrayList<>(Arrays.asList(pathComp)); matchedLen = pathComp.length; } for (int i = 0; i < pathComp.length && i < matchedLen; ++i) { if (!matchedComponents.get(i).equals(pathComp[i])) { matchedLen = i; break; } } } AlluxioURI lca = new AlluxioURI(AlluxioURI.SEPARATOR); return new AlluxioURI( PathUtils.concatPath(lca, matchedComponents.subList(0, matchedLen).toArray())); }

Target:
public static AlluxioURI findLowestCommonAncestor(Collection<AlluxioURI> paths) { if (paths == null || paths.isEmpty()) { return null; } List<String> matchedComponents = null; int matchedLen = 0; for (AlluxioURI path : paths) { String[] pathComp = path.getPath().split(AlluxioURI.SEPARATOR); if (matchedComponents == null) { matchedComponents = new ArrayList<>(Arrays.asList(pathComp)); matchedLen = pathComp.length; } for (int i = 0; i < pathComp.length && i < matchedLen; ++i) { if (!matchedComponents.get(i).equals(pathComp[i])) { matchedLen = i; break; } } } return new AlluxioURI(PathUtils.concatPath(AlluxioURI.SEPARATOR, matchedComponents.subList(0, matchedLen).toArray())); }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CommentImpl comment = (CommentImpl) o; return Objects.equals(id, comment.id) && Objects.equals(parentId, comment.parentId) && Objects.equals(ancestorIds, comment.ancestorIds) && Objects.equals(author, comment.author) && Objects.equals(text, comment.text) && Objects.equals(creationDate, comment.creationDate) && Objects.equals(modificationDate, comment.modificationDate) && Objects.equals(entityId, comment.entityId) && Objects.equals(origin, comment.origin) && Objects.equals(entity, comment.entity); }

Target:
public boolean equals(Object o) { return EqualsBuilder.reflectionEquals(this, o); }
Source:
public Map<NodeRef<Expression>, Type> getTypes() { return types; }

Target:
public Map<NodeRef<Expression>, Type> getTypes() { return unmodifiableMap(types); }
Source:
protected Iterable<Text> getLines(int page) throws CommandException { if (this.pages.size() == 0) { return ImmutableList.of(); } else if (page < 1) { throw new CommandException(t("Page %s does not exist!", page)); } else if (page > this.pages.size()) { throw new CommandException(t("Page %s is too high!", page)); } return this.pages.get(page - 1); }

Target:
protected Iterable<Text> getLines(int page) throws CommandException { final int size = this.pages.size(); if (size == 0) { return ImmutableList.of(); } else if (page < 1) { throw new CommandException(t("Page %s does not exist!", page)); } else if (page > size) { throw new CommandException(t("Page %s is greater than the max of %s!", page, size)); } return this.pages.get(page - 1); }
Source:
private boolean validateRemovePipelines(CruiseConfig preprocessedConfig) { EnvironmentConfig preprocessedEnvironmentConfig = preprocessedConfig.getEnvironments().find(environmentConfig.name()); if(preprocessedEnvironmentConfig instanceof MergeEnvironmentConfig){ for (String pipelineToRemove : pipelinesToRemove) { if(preprocessedEnvironmentConfig.containsPipelineRemotely(new CaseInsensitiveString(pipelineToRemove))){ String message = String.format("Can not remove pipeline '%s'. As it is defined remotely in environment '%s'", pipelineToRemove, environmentConfig.name()); result.badRequest(actionFailed.addParam(message)); return false; } } } EnvironmentConfig environmentConfig = this.environmentConfig; for (String pipelineToRemove : pipelinesToRemove) { if(!environmentConfig.containsPipeline(new CaseInsensitiveString(pipelineToRemove))){ String message = String.format("Pipeline '%s' does not exist in environment '%s'", pipelineToRemove, environmentConfig.name()); result.badRequest(actionFailed.addParam(message)); return false; } } return true; }

Target:
private boolean validateRemovePipelines(CruiseConfig preprocessedConfig) { EnvironmentConfig preprocessedEnvironmentConfig = preprocessedConfig.getEnvironments().find(environmentConfig.name()); if(preprocessedEnvironmentConfig instanceof MergeEnvironmentConfig){ for (String pipelineToRemove : pipelinesToRemove) { if(preprocessedEnvironmentConfig.containsPipelineRemotely(new CaseInsensitiveString(pipelineToRemove))){ String origin = ((MergeEnvironmentConfig) preprocessedEnvironmentConfig).getOriginForPipeline(new CaseInsensitiveString(pipelineToRemove)).displayName(); String message = String.format("Pipeline '%s' cannot be removed from environment '%s' as the association has been defined remotely in [%s]", pipelineToRemove, environmentConfig.name(), origin); result.badRequest(actionFailed.addParam(message)); return false; } } } EnvironmentConfig environmentConfig = this.environmentConfig; for (String pipelineToRemove : pipelinesToRemove) { if(!environmentConfig.containsPipeline(new CaseInsensitiveString(pipelineToRemove))){ String message = String.format("Pipeline '%s' does not exist in environment '%s'", pipelineToRemove, environmentConfig.name()); result.badRequest(actionFailed.addParam(message)); return false; } } return true; }
Source:
public T readFrom(final Class<T> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { if (entityStream.markSupported()) { entityStream.mark(1); if (entityStream.read() == -1) { throw new NoContentException("Johnzon cannot parse empty input stream"); } entityStream.reset(); } else { final PushbackInputStream buffer = new PushbackInputStream(entityStream); int firstByte = buffer.read(); if (firstByte == -1) { throw new NoContentException("Johnzon cannot parse empty input stream"); } buffer.unread(firstByte); entityStream = buffer; } return getJsonb(type).fromJson(entityStream, genericType); }

Target:
public T readFrom(final Class<T> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { try { return getJsonb(type).fromJson(entityStream, genericType); } catch (final NothingToRead e) { throw new NoContentException(e); } }
Source:
public void setRefiningChanges(Diff extension, DifferenceKind extensionKind, Diff refiningDiff) { MultiplicityElementChange refChange = (MultiplicityElementChange)extension; DifferenceSource differenceSource = refChange.getSource(); if (differenceSource == refiningDiff.getSource()) { if (refiningDiff.getRefines().isEmpty()) { refChange.getRefinedBy().add(refiningDiff); } else { refChange.getRefinedBy().addAll( Collections2.filter(refiningDiff.getRefines(), not(equalTo((Diff)refChange)))); } updateReferenceKind(refChange, refiningDiff); collectAndAddOtherRefiningDiffs(refChange, refiningDiff); } }

Target:
public void setRefiningChanges(Diff extension, DifferenceKind extensionKind, Diff refiningDiff) { if (refiningDiff.getSource() == extension.getSource()) { addRefiningDiffAndDependencies(extension, refiningDiff); for (Diff otherRefiningDiff : getRefiningDiffsOnSameSide(refiningDiff)) { addRefiningDiffAndDependencies(extension, otherRefiningDiff); } } }
Source:
public void propagateGeometryPathCommandsToPathPoints(Force force, AbstractProperty prop, JSONArray commands) { int lastIndex = commands.size()-1; JSONObject lastCommand = (JSONObject) commands.get(lastIndex); String commandName = (String) lastCommand.get("name"); if (commandName.equalsIgnoreCase("SetVisible")){ lastCommand.put("type", "SetValueCommandMuscle"); } else { JSONObject pathpointCommand = (JSONObject) lastCommand.clone(); GeometryPath gPath = GeometryPath.safeDownCast(force.getPropertyByName("GeometryPath").getValueAsObject()); pathpointCommand.put("objectUuid", getFirstPathPointUUID4GeometryPath(gPath).toString()); commands.add(pathpointCommand); } }

Target:
public void propagateGeometryPathCommandsToPathPoints(Force force, AbstractProperty prop, JSONArray commands) { int lastIndex = commands.size()-1; JSONObject lastCommand = (JSONObject) commands.get(lastIndex); String commandName = (String) lastCommand.get("name"); if (commandName.equalsIgnoreCase("SetVisible")){ lastCommand.put("type", "SetValueCommandMuscle"); } else { JSONObject pathpointCommand = (JSONObject) lastCommand.clone(); if (force.hasGeometryPath()){ GeometryPath gPath = GeometryPath.safeDownCast(force.getPropertyByName("GeometryPath").getValueAsObject()); pathpointCommand.put("objectUuid", getFirstPathPointUUID4GeometryPath(gPath).toString()); commands.add(pathpointCommand); } else { throw new UnsupportedOperationException("Trying to update GeometryPath of Force that has no GeometryPath:"+force.getName()); } } }
Source:
private void removePlacemarks(HashMap<? extends Feature, Object> placemarks) { super.removeFeatures((HashMap<Feature, Object>) placemarks); }

Target:
private void removePlacemarks(HashMap<? extends Feature, Object> placemarks) { removeFeatures((HashMap<Feature, Object>) placemarks); }
Source:
public SentryClient createSentryClient(Dsn dsn) { if (!checkPermission(Manifest.permission.INTERNET)) { Log.e(TAG, Manifest.permission.INTERNET + " is required to connect to the Sentry server," + " please add it to your AndroidManifest.xml"); } Log.d(TAG, "Sentry init with ctx='" + this.ctx.toString() + "'"); String protocol = dsn.getProtocol(); if (protocol.equalsIgnoreCase("noop")) { Log.w(TAG, "*** Couldn't find a suitable DSN, Sentry operations will do nothing!" + " See documentation: <LINK_0> ***"); } else if (!(protocol.equalsIgnoreCase("http") || protocol.equalsIgnoreCase("https"))) { String async = Lookup.lookup(DefaultSentryClientFactory.ASYNC_OPTION, dsn); if (async != null && async.equalsIgnoreCase("false")) { throw new IllegalArgumentException("Sentry Android cannot use synchronous connections, remove '" + DefaultSentryClientFactory.ASYNC_OPTION + "=false' from your options."); } throw new IllegalArgumentException("Only 'http' or 'https' connections are supported in" + " Sentry Android, but received: " + protocol); } SentryClient sentryClient = super.createSentryClient(dsn); sentryClient.addBuilderHelper(new AndroidEventBuilderHelper(this.ctx)); return sentryClient; }

Target:
public SentryClient createSentryClient(Dsn dsn) { if (!checkPermission(Manifest.permission.INTERNET)) { Log.e(TAG, Manifest.permission.INTERNET + " is required to connect to the Sentry server," + " please add it to your AndroidManifest.xml"); } Log.d(TAG, "Sentry init with ctx='" + ctx.toString() + "'"); String protocol = dsn.getProtocol(); if (protocol.equalsIgnoreCase("noop")) { Log.w(TAG, "*** Couldn't find a suitable DSN, Sentry operations will do nothing!" + " See documentation: <LINK_0> ***"); } else if (!(protocol.equalsIgnoreCase("http") || protocol.equalsIgnoreCase("https"))) { String async = Lookup.lookup(DefaultSentryClientFactory.ASYNC_OPTION, dsn); if (async != null && async.equalsIgnoreCase("false")) { throw new IllegalArgumentException("Sentry Android cannot use synchronous connections, remove '" + DefaultSentryClientFactory.ASYNC_OPTION + "=false' from your options."); } throw new IllegalArgumentException("Only 'http' or 'https' connections are supported in" + " Sentry Android, but received: " + protocol); } SentryClient sentryClient = super.createSentryClient(dsn); sentryClient.addBuilderHelper(new AndroidEventBuilderHelper(ctx)); return sentryClient; }
Source:
private void writeSingleElement(IndentingWriter writer, String name, String text) { if (text != null) { writer.print(String.format("<%s>", name)); writer.print(StringEscapeUtils.escapeXml10(text)); writer.println(String.format("</%s>", name)); } }

Target:
private void writeSingleElement(IndentingWriter writer, String name, String text) { if (text != null) { writer.print(String.format("<%s>", name)); writer.print(escapeString(text)); writer.println(String.format("</%s>", name)); } }
Source:
private void build() { Tessellator tess = Tessellator.getInstance(); BufferBuilder buffer = tess.getBuffer(); if (OpenGlHelper.useVbo()) vbo = new net.minecraft.client.renderer.vertex.VertexBuffer(FORMAT); else GlStateManager.glNewList(displayList = GLAllocation.generateDisplayLists(1), GL11.GL_COMPILE); vertices(buffer); if (OpenGlHelper.useVbo()) { buffer.finishDrawing(); buffer.reset(); vbo.bufferData(buffer.getByteBuffer()); } else { tess.draw(); GlStateManager.glEndList(); } }

Target:
private void build() { Tessellator tess = Tessellator.getInstance(); BufferBuilder buffer = tess.getBuffer(); if (OpenGlHelper.useVbo()) vbo = new VertexBuffer(FORMAT); else GlStateManager.glNewList(displayList = GLAllocation.generateDisplayLists(1), GL11.GL_COMPILE); vertices(buffer); if (OpenGlHelper.useVbo()) { buffer.finishDrawing(); buffer.reset(); vbo.bufferData(buffer.getByteBuffer()); } else { tess.draw(); GlStateManager.glEndList(); } }
Source:
private CmisServiceFactory createServiceFactory() { String className = "nl.nn.adapterframework.extensions.cmis.server.RepositoryConnectorFactory"; Object object = null; try { object = ClassLoaderUtil.loadClass(className).newInstance(); } catch (Exception e) { log.warn("Could not create a services factory instance: "+ e.toString(), e); return null; } if (!(object instanceof CmisServiceFactory)) { log.warn("The provided class is not an instance of CmisServiceFactory!"); } return (CmisServiceFactory) object; }

Target:
private CmisServiceFactory createServiceFactory() { String className = "nl.nn.adapterframework.extensions.cmis.server.RepositoryConnectorFactory"; Object object = null; try { object = ClassLoaderUtil.loadClass(className).newInstance(); } catch (Exception e) { log.warn("Could not create a services factory instance", e); return null; } if (!(object instanceof CmisServiceFactory)) { log.warn("The provided class is not an instance of CmisServiceFactory!"); } return (CmisServiceFactory) object; }
Source:
private File getPath(DataSegment segment) throws SegmentLoadingException { return new File(MapUtils.getString(segment.getLoadSpec(), "path")); }

Target:
private File getPath(DataSegment segment) throws SegmentLoadingException { return new File(MapUtils.getString(segment.getLoadSpec(), PATH_KEY)); }
Source:
public String getCurrentDatabaseVersion(PerunSession sess) throws InternalErrorException, PrivilegeException { Utils.checkPerunSession(sess); if (!AuthzResolver.isAuthorized(sess, Role.SELF) && !AuthzResolver.isAuthorized(sess, Role.PERUNOBSERVER)) throw new PrivilegeException(sess, "getCurrentDatabaseVersion"); return getDatabaseManagerBl().getCurrentDatabaseVersion(); }

Target:
public String getCurrentDatabaseVersion(PerunSession sess) throws InternalErrorException, PrivilegeException { Utils.checkPerunSession(sess); if (!AuthzResolver.isAuthorized(sess, Role.SELF)) throw new PrivilegeException(sess, "getCurrentDatabaseVersion"); return getDatabaseManagerBl().getCurrentDatabaseVersion(); }
Source:
public void testDefaultProperties() throws IOException { DocumentModel root = session.getDocument(new PathRef("/")); PageProvider<?> pp = pps.getPageProvider("DOCUMENT_HISTORY_PROVIDER", null, Long.valueOf(20), Long.valueOf(0), new HashMap<>(), root); @SuppressWarnings("unchecked") List<LogEntry> entries = (List<LogEntry>) pp.getCurrentPage(); RenderingContext renderingCtx = RenderingContext.CtxBuilder.get(); for (LogEntry entry : entries) { CSVAssert csv = csvAssert(entry, renderingCtx); csv.has("id"); csv.has("category"); csv.has("principalName"); csv.has("comment"); csv.has("docLifeCycle"); csv.has("docPath"); csv.has("docType"); csv.has("docUUID"); csv.has("eventId"); csv.has("repositoryId"); csv.has("eventDate"); csv.has("logDate"); } }

Target:
public void testDefaultProperties() throws IOException { RenderingContext renderingCtx = RenderingContext.CtxBuilder.get(); for (LogEntry entry : getLogEntries()) { CSVAssert csv = csvAssert(entry, renderingCtx); csv.has("id"); csv.has("category").isEquals("eventDocumentCategory"); csv.has("principalName").isEquals("Administrator"); csv.has("comment").isEquals(""); csv.has("docLifeCycle").isEquals("project"); csv.has("docPath").isEquals("/myFile"); csv.has("docType").isEquals("File"); csv.has("docUUID").isEquals(file.getId()); csv.has("eventId").isEquals(DocumentEventTypes.DOCUMENT_CREATED); csv.has("repositoryId").isEquals("test"); csv.has("eventDate"); csv.has("logDate"); } }
Source:
public List findPublishedSchemaById(long id) { Tool tool = findPublishedById(id); List schemaObjects = new ArrayList(); if (tool != null) { String defaultVersion = tool.getDefaultVersion(); String descriptorJson = getDescriptorJson(tool, defaultVersion); String schemaVariable = getSchemaVariable(descriptorJson); if (!schemaVariable.isEmpty()) { Map<String, Object> map = new HashMap(); map = cwlJson2Map(descriptorJson, schemaVariable); map = addContext(map, schemaVariable); map = stripNamespace(map, schemaVariable); schemaObjects = getSchemaObjectsList(map); } } return schemaObjects; }

Target:
public List findPublishedSchemaById(long id) { Tool tool = findPublishedById(id); return JsonLdRetriever.getSchema(tool); }
Source:
private void handleInvokedMethodException(Throwable cause) throws KeeperException, InterruptedException { if (cause instanceof KeeperException.UnimplementedException) { LOG.warn("Paginated getChildren is unimplemented in ZK server! " + "Falling back to non-paginated getChildren"); lookupNonPaginatedGetChildren(); throw KeeperException.create(KeeperException.Code.CONNECTIONLOSS); } else if (cause instanceof KeeperException) { throw KeeperException.create(((KeeperException) cause).code()); } else if (cause instanceof InterruptedException) { throw new InterruptedException(cause.getMessage()); } else { throw ExceptionUtil.convertToRuntimeException(cause); } }

Target:
private void handleInvokedMethodException(Throwable cause) throws KeeperException, InterruptedException { if (cause instanceof KeeperException.UnimplementedException) { LOG.warn("Paginated getChildren is unimplemented in ZK server! " + "Falling back to non-paginated getChildren"); _getChildrenMethod = lookupNonPaginatedGetChildren(); throw KeeperException.create(KeeperException.Code.CONNECTIONLOSS); } else if (cause instanceof KeeperException) { throw KeeperException.create(((KeeperException) cause).code()); } else if (cause instanceof InterruptedException) { throw new InterruptedException(cause.getMessage()); } else { throw ExceptionUtil.convertToRuntimeException(cause); } }
Source:
public void encode(final SAMSequenceDictionary dictionary) { dictionary.getSequences().forEach(this::encodeSQLine); }

Target:
public void encode(final SAMSequenceDictionary dictionary) { codec.encodeHeaderLine(false); dictionary.getSequences().forEach(this::encodeSequenceRecord); }
Source:
public String idFromValue(Object o) { String id = super.idFromValue(o); if (relacementIds.containsKey(id)) { id = relacementIds.get(id); } return id; }

Target:
public String idFromValue(Object o) { String id = super.idFromValue(o); return relacementIds.getOrDefault(id, id); }
Source:
protected Long nullUnsafeScalar(Year value) { return value.atDay( 1 ).atStartOfDay().atZone( ZoneOffset.UTC ).toInstant().toEpochMilli(); }

Target:
protected Long nullUnsafeScalar(Year value) { return value.atDay( 1 ).atStartOfDay().toInstant( ZoneOffset.UTC ).toEpochMilli(); }
Source:
public void testPushTimeInThePast() { ParsePush.State.Builder builder = new ParsePush.State.Builder(); ParsePush.State state = builder .pushTime(System.currentTimeMillis() - 1000) .data(new JSONObject()) .build(); }

Target:
public void testPushTimeInThePast() { ParsePush.State.Builder builder = new ParsePush.State.Builder(); ParsePush.State state = builder .pushTime(System.currentTimeMillis() / 1000 - 1000) .data(new JSONObject()) .build(); }
Source:
public float getFloat() { throw new UnsupportedOperationException("not implemented"); }

Target:
public float getFloat() { throw new UnsupportedOperationException("Casting to float type is not supported"); }
Source:
private static boolean isFormatChange(AttributeChange input) { for (EAttribute attribute : NotationPackage.Literals.FONT_STYLE.getEAllAttributes()) { if (input.getAttribute() == attribute) { return true; } } for (EAttribute attribute : NotationPackage.Literals.FILL_STYLE.getEAllAttributes()) { if (input.getAttribute() == attribute) { return true; } } for (EAttribute attribute : NotationPackage.Literals.LINE_STYLE.getEAllAttributes()) { if (input.getAttribute() == attribute) { return true; } } return false; }

Target:
private static boolean isFormatChange(AttributeChange input) { EAttribute attribute = input.getAttribute(); if (attribute != null) { return Arrays.asList(FONT_STYLE, FILL_STYLE, LINE_STYLE) .contains(attribute.getEContainingClass()); } return false; }
Source:
private String applyPartitioningStrategy(final EventType eventType, final JSONObject eventAsJson) throws InvalidOrderingKeyFieldsException { String partitionId; if (!eventType.getOrderingKeyFields().isEmpty()) { partitionId = orderingKeyFieldsPartitioningStrategy.calculatePartition(eventType, eventAsJson, 8); } else { partitionId = "1"; } return partitionId; }

Target:
private String applyPartitioningStrategy(final EventType eventType, final JSONObject eventAsJson) throws InvalidOrderingKeyFieldsException, NakadiException { String partitionId; final String[] partitions = topicRepository.listPartitionNames(eventType.getName()); if (!eventType.getOrderingKeyFields().isEmpty()) { partitionId = orderingKeyFieldsPartitioningStrategy.calculatePartition(eventType, eventAsJson, partitions); } else { partitionId = "0"; } return partitionId; }
Source:
public int compareTo(final ITmfTimestamp ts) { long value = getValue(); int scale = getScale(); if (BIG_BANG.equals(ts)) { return 1; } if (BIG_CRUNCH.equals(ts)) { return -1; } if (this == ts || isIdentical(this, ts)) { return 0; } if (scale == ts.getScale()) { if(ts.getValue() == Long.MIN_VALUE){ return 1; } final long delta = saturatedAdd(getValue(), -ts.getValue()); return Long.compare(delta, 0); } final ITmfTimestamp largerScale = (scale > ts.getScale()) ? this : ts; final ITmfTimestamp smallerScale = (scale < ts.getScale()) ? this : ts; final ITmfTimestamp nts = largerScale.normalize(0, smallerScale.getScale()); if (hasSaturated(largerScale, nts)) { if (smallerScale.getScale() == scale) { return Long.compare(0, nts.getValue()); } return Long.compare(nts.getValue(), 0); } if (smallerScale.getScale() == scale) { if(nts.getValue()==Long.MIN_VALUE){ return 1; } final long delta = saturatedAdd(value, - nts.getValue()); return Long.compare(delta, 0); } if (smallerScale.getValue() == Long.MIN_VALUE) { return 1; } final long delta = saturatedAdd(-smallerScale.getValue(), nts.getValue()); return Long.compare(delta, 0); }

Target:
public int compareTo(final ITmfTimestamp ts) { long value = getValue(); int scale = getScale(); if (BIG_BANG.equals(ts)) { return 1; } if (BIG_CRUNCH.equals(ts)) { return -1; } if (this == ts || isIdentical(this, ts)) { return 0; } if (scale == ts.getScale()) { if (ts.getValue() == Long.MIN_VALUE) { return 1; } final long delta = saturatedAdd(getValue(), -ts.getValue()); return Long.compare(delta, 0); } final ITmfTimestamp largerScale = (scale > ts.getScale()) ? this : ts; final ITmfTimestamp smallerScale = (scale < ts.getScale()) ? this : ts; final ITmfTimestamp nts = largerScale.normalize(0, smallerScale.getScale()); if (hasSaturated(largerScale, nts)) { if (smallerScale.getScale() == scale) { return Long.compare(0, nts.getValue()); } return Long.compare(nts.getValue(), 0); } if (smallerScale.getScale() == scale) { return Long.compare(value, nts.getValue()); } return Long.compare(nts.getValue(), smallerScale.getValue()); }
Source:
public DPXReader(SeekableByteChannel ch) throws IOException { this.readBuf = allocate(READ_BUFFER_SIZE); readBuf.order(ByteOrder.BIG_ENDIAN); initialRead(ch); this.magic = readBuf.getInt(); if (magic != SPDX) { readBuf.order(ByteOrder.LITTLE_ENDIAN); } }

Target:
public DPXReader(SeekableByteChannel ch) throws IOException { this.readBuf = allocate(READ_BUFFER_SIZE); initialRead(ch); this.magic = readBuf.getInt(); if (magic == SDPX) { readBuf.order(ByteOrder.BIG_ENDIAN); } else { readBuf.order(ByteOrder.LITTLE_ENDIAN); } }
Source:
public void runAutomated(AutomatedInstallData idata, IXMLElement panelRoot) throws InstallerException { IXMLElement locations = panelRoot.getFirstChildNamed(LOCATIONS_NODE_NAME); if (locations != null && locations.getContent() != null) { idata.setVariable(Unpacker.INSTALL_RT_LOCATIONS_VAR, locations.getContent()); } String installPath = idata.getVariable("INSTALL_PATH"); File folder = new File(installPath, P2DirectorStarterListener.DEVSTUDIO_LOCATION); Properties servers = (Properties) idata.getAttribute("AS_SERVERS"); if (servers == null || servers.isEmpty()) { servers = new Properties(); File runtimesFolder = new File (installPath, "runtimes"); RuntimePath runtimesPath = new RuntimePath(runtimesFolder.getAbsolutePath(), true); servers.put("server1", runtimesPath.toString()); } if (!folder.exists()) folder.mkdirs(); File file = new File(folder, "runtime_locations.properties"); FileOutputStream stream = null; try { stream = new FileOutputStream(file); servers.store(stream, null); stream.flush(); stream.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (stream != null) { try { stream.close(); } catch (IOException e1) { Debug.trace(e1); } } } }

Target:
public void runAutomated(AutomatedInstallData idata, IXMLElement panelRoot) throws InstallerException { IXMLElement locations = panelRoot.getFirstChildNamed(LOCATIONS_NODE_NAME); if (locations != null && locations.getContent() != null) { idata.setVariable(Unpacker.INSTALL_RT_LOCATIONS_VAR, locations.getContent()); } }
Source:
public MixedOperation<Route, RouteList, Resource<RouteRoute>> routes() { return new RouteOperationsImpl(this.getHttpClient(), this.getConfiguration()); }

Target:
public MixedOperation<Route, RouteList, Resource<Route>> routes() { return new RouteOperationsImpl(this.getHttpClient(), this.getConfiguration()); }
Source:
public boolean compile(File dir) { try { if (dir.equals(sourceDirectory)) { log.info("Running maven-compiler-plugin:compile"); runMojo("org.apache.maven.plugins:maven-compiler-plugin", "compile", null, null); log.info("Running maven-compiler-plugin:resources"); runMojo("org.apache.maven.plugins:maven-resources-plugin", "resources", null, null); } if (dir.equals(testSourceDirectory)) { log.info("Running maven-compiler-plugin:testCompile"); runMojo("org.apache.maven.plugins:maven-compiler-plugin", "testCompile", null, null); log.info("Running maven-compiler-plugin:testResources"); runMojo("org.apache.maven.plugins:maven-resources-plugin", "testResources", null, null); } return true; } catch (Exception e) { log.debug("Unable to compile", e); return false; } }

Target:
public boolean compile(File dir) { try { if (dir.equals(sourceDirectory)) { log.info("Running maven-compiler-plugin:compile"); runMojo("org.apache.maven.plugins:maven-compiler-plugin", "compile", null, null); log.info("Running maven-compiler-plugin:resources"); runMojo("org.apache.maven.plugins:maven-resources-plugin", "resources", null, null); } if (dir.equals(testSourceDirectory)) { log.info("Running maven-compiler-plugin:testCompile"); runMojo("org.apache.maven.plugins:maven-compiler-plugin", "testCompile", null, null); log.info("Running maven-compiler-plugin:testResources"); runMojo("org.apache.maven.plugins:maven-resources-plugin", "testResources", null, null); } return true; } catch (MojoExecutionException e) { log.error("Unable to compile", e); return false; } }
Source:
protected void firePropertyChange(int propertyId) { if (multiEditorManager instanceof AbstractMultiPageSashEditor) ((AbstractMultiPageSashEditor) multiEditorManager).handlePropertyChange(propertyId); }

Target:
protected void firePropertyChange(int propertyId) { for(Object obj : propertyListeners.getListeners()) ((IPropertyListener)obj).handlePropertyChange(this, propertyId); }
Source:
public Window<PublisherPush> getStream() { return pushStreamIterator; }

Target:
public PublisherStream.Window getStream() { return pushStreamIterator; }
Source:
public void testListStatusThrowsExceptionForUnreadableDir() throws Exception { assumePermissionsSupported(); Path testRootDir = getTestRootPath(fSys, "test/hadoop/dir"); Path obscuredDir = new Path(testRootDir, "foo"); Path subDir = new Path(obscuredDir, "bar"); fSys.mkdirs(subDir); fSys.setPermission(obscuredDir, new FsPermission((short)0)); try { intercept(IOException.class, () -> fSys.listStatus(obscuredDir)); } finally { fSys.setPermission(obscuredDir, new FsPermission((short)0755)); } }

Target:
public void testListStatusThrowsExceptionForUnreadableDir() throws Exception { assumePermissionsSupported(); Path testRootDir = getTestRootPath(fSys, "test/hadoop/dir"); Path obscuredDir = new Path(testRootDir, "foo"); Path subDir = new Path(obscuredDir, "bar"); fSys.mkdirs(subDir); fSys.setPermission(obscuredDir, new FsPermission((short)0)); try { fSys.listStatus(obscuredDir); Assert.fail("Should throw IOException"); } catch (IOException ioe) { } finally { fSys.setPermission(obscuredDir, new FsPermission((short)0755)); } }
Source:
public void setUp() { HttpServletRequest request = mock(HttpServletRequest.class); Map<String, String[]> params = new HashMap<String, String[]>(); params.put("account", new String[]{"Acme Co"}); params.put("name", new String[]{"Bill"}); when(request.getParameterMap()).thenReturn(params); when(request.getMethod()).thenReturn("PATCH"); when(request.getRequestURL()).thenReturn(new StringBuffer("/foo/bar")); when(request.getRequestURI()).thenReturn("/foo/bar"); when(request.getRemoteAddr()).thenReturn("12.0.4.57"); Enumeration<String> headers = new Vector<String>( Arrays.asList("Content-Type", "Content-Length", "X-Custom-Header")).elements(); when(request.getHeaderNames()).thenReturn(headers); when(request.getHeaders("Content-Type")).thenReturn( new Vector<String>(Collections.singletonList("application/json")).elements()); when(request.getHeaders("Content-Length")).thenReturn( new Vector<String>(Collections.singletonList("54")).elements()); when(request.getHeaders("X-Custom-Header")).thenReturn( new Vector<String>(Arrays.asList("some-data-1", "some-data-2")).elements()); ServletContext context = mock(ServletContext.class); BugsnagServletRequestListener listener = new BugsnagServletRequestListener(); listener.requestInitialized(new ServletRequestEvent(context, request)); }

Target:
public void setUp() { HttpServletRequest request = mock(HttpServletRequest.class); Map<String, String[]> params = new HashMap<String, String[]>(); params.put("account", new String[]{"Acme Co"}); params.put("name", new String[]{"Bill"}); when(request.getParameterMap()).thenReturn(params); when(request.getMethod()).thenReturn("PATCH"); when(request.getRequestURL()).thenReturn(new StringBuffer("/foo/bar")); when(request.getRequestURI()).thenReturn("/foo/bar"); when(request.getRemoteAddr()).thenReturn("12.0.4.57"); when(request.getHeaderNames()).thenReturn( stringsToEnumeration( "Content-Type", "Content-Length", "X-Custom-Header", "Authorization")); when(request.getHeaders("Content-Type")).thenReturn( stringsToEnumeration("application/json")); when(request.getHeaders("Content-Length")).thenReturn( stringsToEnumeration("54")); when(request.getHeaders("X-Custom-Header")).thenReturn( stringsToEnumeration("some-data-1", "some-data-2")); when(request.getHeaders("Authorization")).thenReturn( stringsToEnumeration("Basic ABC123")); ServletContext context = mock(ServletContext.class); BugsnagServletRequestListener listener = new BugsnagServletRequestListener(); listener.requestInitialized(new ServletRequestEvent(context, request)); }
Source:
@Override public OutputStream decorateLogger(AbstractBuild _ignore, final OutputStream logger) throws IOException, InterruptedException { final Pattern p = Pattern.compile(pattern.getPlainText()); return new LineTransformationOutputStream() { @Override protected void eol(byte[] b, int len) throws IOException { Matcher m = p.matcher(new String(b, 0, len, Charsets.UTF_8)); if (m.find()) { logger.write(m.replaceAll("****").getBytes(Charsets.UTF_8)); } else { logger.write(b, 0, len); } } }; }

Target:
@Override public OutputStream decorateLogger(AbstractBuild _ignore, final OutputStream logger) throws IOException, InterruptedException { final Pattern p = Pattern.compile(pattern.getPlainText()); return new LineTransformationOutputStream() { @Override protected void eol(byte[] b, int len) throws IOException { Matcher m = p.matcher(new String(b, 0, len, charsetName)); if (m.find()) { logger.write(m.replaceAll("****").getBytes(charsetName)); } else { logger.write(b, 0, len); } } }; }
Source:
public void run() { long startTime = System.currentTimeMillis(); try { mimeMsg = mailSender.createMimeMessage(); msg = new MimeMessageHelper(mimeMsg, MimeMessageHelper.MULTIPART_MODE_MIXED); } catch (MessagingException e) { log.error("Failed to send email to " + userEmail + " for update " + importFile.getAbsolutePath(), e); } try { initializeXMLReader(); try { getNextUpdate(); log.info("Finished metadata import for objects in {}ms for user {}", new Object[] {objectCount, System.currentTimeMillis() - startTime, username}); sendCompletedEmail(updated, failed); } catch (XMLStreamException e) { log.info("Errors reading XML during update " + username, e); failed.put(importFile.getAbsolutePath(), "The import file contains XML errors"); sendValidationFailureEmail(failed); } } catch (UpdateException e) { failed.put(importFile.getAbsolutePath(), "Failed to read metadata update package for " + username); sendValidationFailureEmail(failed); } finally { close(); cleanup(); } }

Target:
public void run() { long startTime = System.currentTimeMillis(); try { mimeMsg = mailSender.createMimeMessage(); msg = new MimeMessageHelper(mimeMsg, MimeMessageHelper.MULTIPART_MODE_MIXED); } catch (MessagingException e) { log.error("Failed to send email to " + userEmail + " for update " + importFile.getAbsolutePath(), e); } try { initializeXMLReader(); processUpdates(); log.info("Finished metadata import for objects in {}ms for user {}", new Object[] {objectCount, System.currentTimeMillis() - startTime, username}); sendCompletedEmail(updated, failed); } catch (UpdateException | XMLStreamException e) { log.info("Errors reading XML during update " + username, e); failed.put(importFile.getAbsolutePath(), "The import file contains XML errors"); sendValidationFailureEmail(failed); } finally { close(); cleanup(); } }
Source:
private static String renderAxiomWithImpact( List<OWLAxiom> axioms, int impact, OWLObjectRenderer renderer, Map<OWLAxiom, Set<String>> associatedOntologyIds) { StringBuilder builder = new StringBuilder(); builder.append("## Axioms used " + impact + " times" + "\n"); for (OWLAxiom ax : axioms) { builder.append( "- " + renderer.render(ax) + " [" + String.join(",", associatedOntologyIds.get(ax)) + "]\n"); } builder.append("\n"); return builder.toString(); }

Target:
private static String renderAxiomWithImpact( List<OWLAxiom> axioms, int impact, OWLObjectRenderer renderer, Map<OWLAxiom, Set<String>> associatedOntologyIds) { StringBuilder builder = new StringBuilder(); builder.append("## Axioms used ").append(impact).append(" times").append("\n"); for (OWLAxiom ax : axioms) { builder.append("- ").append(renderer.render(ax)).append(" [").append(String.join(",", associatedOntologyIds.get(ax))).append("]\n"); } builder.append("\n"); return builder.toString(); }
Source:
private static PlanFragment createTableScanPlanFragment(String name) { Symbol symbol = new Symbol("column"); PlanNode planNode = new TableScanNode( new PlanNodeId(name), new TableHandle( new ConnectorId("test"), new TestingTableHandle(), TestingTransactionHandle.create(), Optional.of(TestingHandle.INSTANCE)), ImmutableList.of(symbol), ImmutableMap.of(symbol, new TestingColumnHandle("column"))); return createFragment(planNode); }

Target:
private static PlanFragment createTableScanPlanFragment(String name) { Symbol symbol = new Symbol("column"); PlanNode planNode = new TableScanNode( new PlanNodeId(name), new TableHandle( new ConnectorId("test"), new TestingTableHandle(), TestingTransactionHandle.create(), Optional.empty()), ImmutableList.of(symbol), ImmutableMap.of(symbol, new TestingColumnHandle("column"))); return createFragment(planNode); }
Source:
public void onDamaged(OnDamagedEvent event, EntityRef entity) { Prefab particleEffectPrefab = prefabManager.getPrefab("LightAndShadowResources:cardParticleEffect"); for (Component c : particleEffectPrefab.iterateComponents()) { entity.addComponent(c); } audioManager.playSound(Assets.getSound("engine:Dig").get(), 1.0f); }

Target:
public void onDamaged(OnDamagedEvent event, EntityRef entity) { ParticleEmitterComponent emitter = entity.getComponent(ParticleEmitterComponent.class); emitter.particleSpawnsLeft = emitter.maxParticles; entity.saveComponent(emitter); audioManager.playSound(Assets.getSound("engine:Dig").get(), 1.0f); logger.info("current health: {}", entity.getComponent(HealthComponent.class).currentHealth); }
Source:
public void transform(KeyValue<LongWritable, Object> input, Emitter<StructuredRecord> emitter) throws Exception { Map<String, String> xmlRecord = (Map<String, String>) input.getValue(); String fileName = ""; String record = ""; for (String key : xmlRecord.keySet()) { fileName = key; record = xmlRecord.get(key); } StructuredRecord output = StructuredRecord.builder(DEFAULT_XML_SCHEMA) .set("offset", input.getKey().get()) .set("fileName", fileName) .set("record", record) .build(); emitter.emit(output); }

Target:
public void transform(KeyValue<LongWritable, Object> input, Emitter<StructuredRecord> emitter) throws Exception { Map<String, String> xmlRecord = (Map<String, String>) input.getValue(); Set<String> keySet = xmlRecord.keySet(); Iterator<String> itr = keySet.iterator(); String fileName = Iterators.getOnlyElement(itr); String record = xmlRecord.get(fileName); StructuredRecord output = StructuredRecord.builder(DEFAULT_XML_SCHEMA) .set("offset", input.getKey().get()) .set("filename", fileName) .set("record", record) .build(); emitter.emit(output); }
Source:
private synchronized void createGroupIfNecessary(SelectionContext<C> context, Executor executor) { ResourceGroupId id = context.getResourceGroupId(); if (!groups.containsKey(id)) { InternalResourceGroup group; if (id.getParent().isPresent()) { createGroupIfNecessary(new SelectionContext<>(id.getParent().get(), context.getContext()), executor); InternalResourceGroup parent = groups.get(id.getParent().get()); requireNonNull(parent, "parent is null"); int subGroupSegmentIndex = parent.getId().getSegments().size(); group = parent.getOrCreateSubGroup(id.getLastSegment(), (context.getFirstDynamicSegmentPosition().equals(OptionalInt.of(subGroupSegmentIndex)))); } else { RootInternalResourceGroup root = new RootInternalResourceGroup(id.getSegments().get(0), this::exportGroup, executor); group = root; rootGroups.add(root); } configurationManager.get().configure(group, context); checkState(groups.put(id, group) == null, "Unexpected existing resource group"); } }

Target:
private synchronized void createGroupIfNecessary(SelectionContext<C> context, Executor executor) { ResourceGroupId id = context.getResourceGroupId(); if (!groups.containsKey(id)) { InternalResourceGroup group; if (id.getParent().isPresent()) { createGroupIfNecessary(new SelectionContext<>(id.getParent().get(), context.getContext()), executor); InternalResourceGroup parent = groups.get(id.getParent().get()); requireNonNull(parent, "parent is null"); int subGroupSegmentIndex = parent.getId().getSegments().size(); group = parent.getOrCreateSubGroup(id.getLastSegment(), !context.getFirstDynamicSegmentPosition().equals(OptionalInt.of(subGroupSegmentIndex))); } else { RootInternalResourceGroup root = new RootInternalResourceGroup(id.getSegments().get(0), this::exportGroup, executor); group = root; rootGroups.add(root); } configurationManager.get().configure(group, context); checkState(groups.put(id, group) == null, "Unexpected existing resource group"); } }