auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected DatastreamRuntimeException generateSendFailure(Exception exception) { _dynamicMetricsManager.createOrUpdateMeter(_metricsNamesPrefix, AGGREGATE, PRODUCER_ERROR, 1); if (exception instanceof IllegalStateException) { _log.warn("sent failure transiently, exception: ", exception); return new DatastreamTransientException(exception); } else { _log.warn("sent failure, restart producer, exception: ", exception); shutdownProducer(); return new DatastreamRuntimeException(exception); } }

Target:
DatastreamRuntimeException generateSendFailure(Exception exception) { _dynamicMetricsManager.createOrUpdateMeter(_metricsNamesPrefix, AGGREGATE, PRODUCER_ERROR, 1); if (exception instanceof IllegalStateException) { _log.warn("sent failure transiently, exception: ", exception); return new DatastreamTransientException(exception); } else { _log.warn("sent failure, restart producer, exception: ", exception); shutdownProducer(); return new DatastreamRuntimeException(exception); } }
Source:
public void setupTopologyConfigId(long topologyConfigId) { CorfuStoreMetadata.Timestamp timestamp = corfuStore.getTimestamp(); long persistedTopologyConfigId = query(timestamp, LogReplicationMetadataType.TOPOLOGY_CONFIG_ID); if (topologyConfigId <= persistedTopologyConfigId) { log.warn("Skip setupTopologyConfigId. the current topologyConfigId is not larger than the persistedTopologyConfigID {}", topologyConfigId, persistedTopologyConfigId); return; } TxBuilder txBuilder = corfuStore.tx(NAMESPACE, IsolationLevel.snapshot(timestamp)); for (LogReplicationMetadataType type : LogReplicationMetadataType.values()) { long val = Address.NON_ADDRESS; if (type == LogReplicationMetadataType.TOPOLOGY_CONFIG_ID) { val = topologyConfigId; } appendUpdate(txBuilder, type, val); } txBuilder.commit(); log.info("Update topologyConfigId, new metadata {}", this); }

Target:
public void setupTopologyConfigId(long topologyConfigId) { CorfuStoreMetadata.Timestamp timestamp = corfuStore.getTimestamp(); long persistedTopologyConfigId = query(timestamp, LogReplicationMetadataType.TOPOLOGY_CONFIG_ID); if (topologyConfigId <= persistedTopologyConfigId) { log.warn("Skip setupTopologyConfigId. the current topologyConfigId is not larger than the persistedTopologyConfigID {}", topologyConfigId, persistedTopologyConfigId); return; } TxBuilder txBuilder = corfuStore.tx(NAMESPACE); for (LogReplicationMetadataType type : LogReplicationMetadataType.values()) { long val = Address.NON_ADDRESS; if (type == LogReplicationMetadataType.TOPOLOGY_CONFIG_ID) { val = topologyConfigId; } appendUpdate(txBuilder, type, val); } txBuilder.commit(timestamp); log.info("Update topologyConfigId, new metadata {}", this); }
Source:
public void testNoCaching() throws Throwable { MetadataManager metadata = METADATA_MANAGER; ExpressionCompiler compiler = new ExpressionCompiler(metadata, new PageFunctionCompiler(metadata, false)); ImmutableList.Builder<RowExpression> projectionsBuilder = ImmutableList.builder(); ArrayType arrayType = new ArrayType(VARCHAR); Signature signature = new Signature("concat", SCALAR, arrayType.getTypeSignature(), arrayType.getTypeSignature(), arrayType.getTypeSignature()); projectionsBuilder.add(new CallExpression(signature, arrayType, ImmutableList.of(field(0, arrayType), field(1, arrayType)))); ImmutableList<RowExpression> projections = projectionsBuilder.build(); PageProcessor pageProcessor = compiler.compilePageProcessor(Optional.empty(), projections).get(); PageProcessor pageProcessor2 = compiler.compilePageProcessor(Optional.empty(), projections).get(); assertTrue(pageProcessor != pageProcessor2); }

Target:
public void testNoCaching() throws Throwable { ImmutableList.Builder<RowExpression> projectionsBuilder = ImmutableList.builder(); ArrayType arrayType = new ArrayType(VARCHAR); Signature signature = new Signature("concat", SCALAR, arrayType.getTypeSignature(), arrayType.getTypeSignature(), arrayType.getTypeSignature()); projectionsBuilder.add(new CallExpression(signature, arrayType, ImmutableList.of(field(0, arrayType), field(1, arrayType)))); ImmutableList<RowExpression> projections = projectionsBuilder.build(); PageProcessor pageProcessor = compiler.compilePageProcessor(Optional.empty(), projections).get(); PageProcessor pageProcessor2 = compiler.compilePageProcessor(Optional.empty(), projections).get(); assertTrue(pageProcessor != pageProcessor2); }
Source:
private RequestLog createRequestLog() { final Slf4jRequestLog requestLog = new Slf4jRequestLog(); requestLog.setExtended(true); requestLog.setLogTimeZone("GMT"); requestLog.setLogLatency(true); return requestLog; }

Target:
private RequestLog createRequestLog() { final Slf4jRequestLog requestLog = new Slf4jRequestLog(); requestLog.setExtended(true); requestLog.setLogTimeZone(ZoneId.systemDefault().getId()); requestLog.setLogLatency(true); return requestLog; }
Source:
public void testToExecuteNotInstalledCommand_shouldThrowException() throws Exception { CommandProcessor cp = getOsgiService(CommandProcessor.class); CommandSession cs = cp.createSession(System.in, System.out, System.err); cs.execute("failing-command"); fail("Exception should be thrown that the command does not exist"); cs.close(); }

Target:
public void testToExecuteNotInstalledCommand_shouldThrowException() throws Exception { CommandProcessor cp = getOsgiService(CommandProcessor.class); CommandSession cs = cp.createSession(System.in, System.out, System.err); cs.execute("failing-command"); cs.close(); fail("Exception should be thrown that the command does not exist"); }
Source:
public RedisResponse executeCommand(Command command, ExecutionHandlerContext executionHandlerContext) { parameterRequirements.checkParameters(command, executionHandlerContext); if (executor instanceof ResponseExecutor) { return ((ResponseExecutor) executor).executeCommandWithResponse(command, executionHandlerContext); } executor.executeCommand(command, executionHandlerContext); return null; }

Target:
public RedisResponse executeCommand(Command command, ExecutionHandlerContext executionHandlerContext) { parameterRequirements.checkParameters(command, executionHandlerContext); return executor.executeCommandWithResponse(command, executionHandlerContext); }
Source:
protected List<org.junit.rules.MethodRule> rules(Object target) { List<org.junit.rules.MethodRule> rules = getTestClass().getAnnotatedFieldValues(target, Rule.class, org.junit.rules.MethodRule.class); rules.addAll(getTestClass().getAnnotatedMethodValues(target, Rule.class, org.junit.rules.MethodRule.class)); return rules; }

Target:
protected List<MethodRule> rules(Object target) { List<MethodRule> rules = getTestClass().getAnnotatedMethodValues(target, Rule.class, MethodRule.class); rules.addAll(getTestClass().getAnnotatedFieldValues(target, Rule.class, MethodRule.class)); return rules; }
Source:
public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof File, "this binder is only valid for File!"); checkNotNull(request, "request"); File dockerFile = (File) input; File tmpDir = Files.createTempDir(); final File targetFile = new File(tmpDir + File.separator + "Dockerfile"); try { Files.copy(dockerFile, targetFile); File archive = Archives.tar(tmpDir, File.createTempFile("archive", ".tar")); FileInputStream data = new FileInputStream(archive); Payload payload = Payloads.newInputStreamPayload(data); payload.getContentMetadata().setContentLength(data.getChannel().size()); payload.getContentMetadata().setContentType(MediaType.TEXT_PLAIN); request.setPayload(payload); } catch (IOException e) { e.printStackTrace(); } return request; }

Target:
public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof File, "this binder is only valid for File!"); checkNotNull(request, "request"); File dockerFile = (File) input; File tmpDir = Files.createTempDir(); final File targetFile = new File(tmpDir + File.separator + "Dockerfile"); try { Files.copy(dockerFile, targetFile); File archive = Archives.tar(tmpDir, File.createTempFile("archive", ".tar")); FileInputStream data = new FileInputStream(archive); Payload payload = Payloads.newInputStreamPayload(data); payload.getContentMetadata().setContentLength(data.getChannel().size()); payload.getContentMetadata().setContentType("application/tar"); request.setPayload(payload); } catch (IOException e) { logger.error(e, "Couldn't create a tarball for %s", targetFile); throw Throwables.propagate(e); } return request; }
Source:
private static LinkedHashMap<Integer, String> getPlaceholders(@Nullable GoExpression argument) { if (argument == null) return null; String placeholderText = resolve(argument); if (placeholderText == null) return null; int placeholderTextLength = placeholderText.length(); int placeholderStart = 0; LinkedHashMap<Integer, String> placeholders = new LinkedHashMap<Integer, String>(); while (placeholderStart < placeholderTextLength) { ProgressManager.checkCanceled(); if (PLACEHOLDER_START_CHAR != placeholderText.charAt(placeholderStart)) { placeholderStart++; continue; } int placeholderEnd = placeholderStart + 1; while (placeholderEnd < placeholderTextLength && PLACEHOLDER_ALLOWED_CHARS.indexOf(placeholderText.charAt(placeholderEnd)) != -1 && PLACEHOLDER_END_CHARS.indexOf(placeholderText.charAt(placeholderEnd)) == -1) { placeholderEnd++; } if (placeholderEnd >= placeholderTextLength) break; if (PLACEHOLDER_ALLOWED_CHARS.indexOf(placeholderText.charAt(placeholderEnd)) == -1 && PLACEHOLDER_END_CHARS.indexOf(placeholderText.charAt(placeholderEnd)) == -1) { placeholderStart = placeholderEnd; placeholderStart++; continue; } String placeholder = placeholderText.substring(placeholderStart, placeholderEnd + 1); if (!isValidPlaceholder(placeholder)) { placeholders.put(placeholderStart, placeholder); } placeholderStart = placeholderEnd; placeholderStart++; } return placeholders; }

Target:
private static LinkedHashMap<Integer, String> getPlaceholders(@Nullable GoExpression argument) { LinkedHashMap<Integer, String> placeholders = new LinkedHashMap<Integer, String>(); if (argument == null) return placeholders; String placeholderText = resolve(argument); if (placeholderText == null) return placeholders; if (StringUtil.countChars(placeholderText, '%') < 2) return placeholders; if (StringUtil.countChars(placeholderText, '%') == 2 && placeholderText.contains("%%")) return placeholders; int placeholderTextLength = placeholderText.length(); int placeholderStart = 0; String PLACEHOLDER_ALLOWED_CHARS = " *#.[]+-0123456789"; String PLACEHOLDER_END_CHARS = "%vTtbcdoqxXUbeEfFgGsqxXp"; while (placeholderStart < placeholderTextLength) { ProgressManager.checkCanceled(); char PLACEHOLDER_START_CHAR = '%'; if (PLACEHOLDER_START_CHAR != placeholderText.charAt(placeholderStart)) { placeholderStart++; continue; } int placeholderEnd = placeholderStart + 1; while (placeholderEnd < placeholderTextLength && StringUtil.containsChar(PLACEHOLDER_ALLOWED_CHARS, placeholderText.charAt(placeholderEnd)) && StringUtil.containsChar(PLACEHOLDER_END_CHARS, placeholderText.charAt(placeholderEnd))) { placeholderEnd++; } if (placeholderEnd >= placeholderTextLength) break; if (PLACEHOLDER_ALLOWED_CHARS.indexOf(placeholderText.charAt(placeholderEnd)) == -1 && PLACEHOLDER_END_CHARS.indexOf(placeholderText.charAt(placeholderEnd)) == -1) { placeholderStart = placeholderEnd; placeholderStart++; continue; } String placeholder = placeholderText.substring(placeholderStart, placeholderEnd + 1); if (!"%%".equals(placeholder)) { placeholders.put(placeholderStart, placeholder); } placeholderStart = placeholderEnd; placeholderStart++; } return placeholders; }
Source:
protected String getSqlType(String schemaName, Schema.Type type) { final String sqlType; if (schemaName != null && logicalNameToSqlTypeMap.containsKey(schemaName)) { sqlType = logicalNameToSqlTypeMap.get(schemaName); } else { sqlType = schemaTypeToSqlTypeMap.get(type); } if (sqlType == null) { throw new ConnectException(String.format("%s type doesn't have a mapping to the SQL database column type", type)); } return sqlType; }

Target:
protected String getSqlType(String schemaName, Schema.Type type) { String sqlType = null; if (schemaName != null) { sqlType = logicalNameToSqlTypeMap.get(schemaName); } if (sqlType == null) { sqlType = schemaTypeToSqlTypeMap.get(type); } if (sqlType == null) { throw new ConnectException(String.format("%s type doesn't have a mapping to the SQL database column type", type)); } return sqlType; }
Source:
public void simpleIntegrationTestNeg() throws Exception { TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, "localhost", "TestDB", 1, 4, 1, 1, "MasterSlave", true); ConfigAccessor configAccessor = new ConfigAccessor(_gZkClient); ClusterConfig clusterConfig = configAccessor.getClusterConfig(clusterName); clusterConfig.getRecord() .setListField(ClusterConfig.ClusterConfigProperty.INSTANCE_CAPACITY_KEYS.name(), new ArrayList<>()); clusterConfig.setTopologyAwareEnabled(true); clusterConfig.setTopology("/Rack/Sub-Rack/Host/Instance"); clusterConfig.setFaultZoneType("Host"); configAccessor.setClusterConfig(clusterName, clusterConfig); String instanceName = "localhost_12918"; HelixManager participant = new ZKHelixManager(clusterName, instanceName , InstanceType.PARTICIPANT, ZK_ADDR); participant.getStateMachineEngine().registerStateModelFactory("MasterSlave", new MockMSModelFactory()); try { participant.connect(); } catch (IllegalArgumentException expected) { Assert.assertEquals(expected.getMessage(), "Domain for instance localhost_12918 is not set, fail the topology-aware placement!"); } ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient)); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); Assert.assertNull(accessor.getProperty(keyBuilder.liveInstance("localhost_12918"))); Assert.assertNull(accessor.getProperty(keyBuilder.controllerLeader())); }

Target:
public void simpleIntegrationTestNeg() throws Exception { TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, "localhost", "TestDB", 1, 4, 1, 1, "MasterSlave", true); ConfigAccessor configAccessor = new ConfigAccessor(_gZkClient); ClusterConfig clusterConfig = configAccessor.getClusterConfig(clusterName); clusterConfig.getRecord() .setListField(ClusterConfig.ClusterConfigProperty.INSTANCE_CAPACITY_KEYS.name(), new ArrayList<>()); clusterConfig.setTopologyAwareEnabled(true); clusterConfig.setTopology("/Rack/Sub-Rack/Host/Instance"); clusterConfig.setFaultZoneType("Host"); configAccessor.setClusterConfig(clusterName, clusterConfig); String instanceName = "localhost_12918"; HelixManager participant = new ZKHelixManager(clusterName, instanceName , InstanceType.PARTICIPANT, ZK_ADDR); participant.getStateMachineEngine().registerStateModelFactory("MasterSlave", new MockMSModelFactory()); try { participant.connect(); Assert.fail(); } catch (IllegalArgumentException expected) { Assert.assertEquals(expected.getMessage(), "Domain for instance localhost_12918 is not set, fail the topology-aware placement!"); } ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient)); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); Assert.assertNull(accessor.getProperty(keyBuilder.liveInstance("localhost_12918"))); Assert.assertNull(accessor.getProperty(keyBuilder.controllerLeader())); }
Source:
public Builder withInteractive(Boolean interactive) { this.interactive = interactive; return this; }

Target:
public Builder withInteractive(Boolean interactive) { this.interactive = checkNotNull(interactive); return this; }
Source:
public void execute(Tuple input) { try { final Object tupleField = input.getValueByField(StreamlineEvent.STREAMLINE_EVENT); if (tupleField instanceof StreamlineEvent) { String genId = Long.toString(rand.nextLong()); StreamlineEvent event = (StreamlineEvent) tupleField; StreamlineEvent eventWithStream = getStreamlineEventWithStream((StreamlineEvent) event, input, genId); for (Result result : processorRuntime.process(eventWithStream)) { for (StreamlineEvent e : result.events) { collector.emit(result.stream, input, new Values(e)); } } } else { LOG.debug("Invalid tuple received. Tuple disregarded and rules not evaluated.\n\tTuple [{}]." + "\n\tStreamlineEvent [{}].", input, tupleField); collector.ack(input); } } catch (Exception e) { collector.fail(input); collector.reportError(e); LOG.debug("", e); } }

Target:
public void execute(Tuple input) { try { final Object tupleField = input.getValueByField(StreamlineEvent.STREAMLINE_EVENT); if (tupleField instanceof StreamlineEvent) { String genId = Long.toString(rand.nextLong()); StreamlineEvent event = (StreamlineEvent) tupleField; StreamlineEvent eventWithStream = getStreamlineEventWithStream(event, input, genId); for (Result result : processorRuntime.process(eventWithStream)) { for (StreamlineEvent e : result.events) { collector.emit(result.stream, input, new Values(e)); } } } else { LOG.debug("Invalid tuple received. Tuple disregarded and rules not evaluated.\n\tTuple [{}]." + "\n\tStreamlineEvent [{}].", input, tupleField); } collector.ack(input); } catch (Exception e) { collector.fail(input); collector.reportError(e); LOG.debug("", e); } }
Source:
public void testInfo() throws Exception { String url = String.format("http://localhost:%d/rest/v2/cache-managers/default/", restServer().getPort()); ContentResponse response = client.newRequest(url).send(); ResponseAssertion.assertThat(response).isOk(); String json = response.getContentAsString(); JsonNode cmInfo = mapper.readTree(json); assertFalse(cmInfo.get("version").asText().isEmpty()); assertEquals(2, cmInfo.get("cluster_members").size()); assertEquals(2, cmInfo.get("cluster_members_physical_addresses").size()); assertTrue(cmInfo.get("local_site").isNull()); }

Target:
public void testInfo() throws Exception { String url = String.format("http://localhost:%d/rest/v2/cache-managers/default/", restServer().getPort()); ContentResponse response = client.newRequest(url).send(); ResponseAssertion.assertThat(response).isOk(); String json = response.getContentAsString(); JsonNode cmInfo = mapper.readTree(json); assertFalse(cmInfo.get("version").asText().isEmpty()); assertEquals(2, cmInfo.get("cluster_members").size()); assertEquals(2, cmInfo.get("cluster_members_physical_addresses").size()); assertEquals("LON-1", cmInfo.get("local_site").asText()); }
Source:
public ModuleDefinition findDefinition(String name, ModuleType moduleType) { try { for (String ext : SUFFIXES) { String location = String.format("%s/%s/%s%s", root, moduleType.name(), name, ext); Resource[] resources = resolver.getResources(location); for (Resource resource : resources) { ModuleDefinition candidate = fromResource(resource); if (candidate != null) { return candidate; } } } } catch (IOException e) { throw new RuntimeIOException("An error occurred trying to locate modules", e); } return null; }

Target:
public ModuleDefinition findDefinition(String name, ModuleType moduleType) { List<ModuleDefinition> result = new ArrayList<ModuleDefinition>(); try { for (String ext : SUFFIXES) { String location = String.format("%s/%s/%s%s", root, moduleType.name(), name, ext); Resource[] resources = resolver.getResources(location); for (Resource resource : resources) { fromResource(resource, result); } } } catch (IOException e) { throw new RuntimeIOException(String.format("An error occurred trying to locate module '%s:%s'", moduleType, name), e); } return result.size() == 1 ? result.iterator().next() : null; }
Source:
public Task importTask(String json) throws IOException { LOGGER.info("Importing the task from json"); ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(json); removeIgnoredFields(node); Task task = mapper.readValue(node, Task.class); List<DataSource> sources = task.getTaskConfig().getDataSources(); for (DataSource ds : sources) { TaskDataProvider provider = findProviderByName(ds); if (null != provider) { Long oldId = ds.getProviderId(); Long newId = provider.getId(); if (!oldId.equals(newId)) { replaceProviderId(task, oldId, newId); ds.setProviderId(newId); } } } save(task); return task; }

Target:
public Task importTask(String json) throws IOException { LOGGER.info("Importing a task from json"); LOGGER.trace("The json file: {}", json); ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(json); removeIgnoredFields(node); Task task = mapper.readValue(node, Task.class); List<DataSource> sources = task.getTaskConfig().getDataSources(); for (DataSource ds : sources) { TaskDataProvider provider = findProviderByName(ds); if (null != provider) { Long oldId = ds.getProviderId(); Long newId = provider.getId(); if (!oldId.equals(newId)) { replaceProviderId(task, oldId, newId); ds.setProviderId(newId); } } } save(task); return task; }
Source:
public static boolean callSpawnEntitySpawner(final List<Entity> entities, final PhaseContext<?> context) { try (final CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { frame.addContext(EventContextKeys.SPAWN_TYPE, SpawnTypes.WORLD_SPAWNER); final SpawnEntityEvent event = SpongeEventFactory.createSpawnEntityEventSpawner(frame.getCurrentCause(), entities); if (ShouldFire.SPAWN_ENTITY_EVENT_SPAWNER) { SpongeImpl.postEvent(event); } if (!event.isCancelled() && event.getEntities().size() > 0) { return EntityUtil.processEntitySpawnsFromEvent(context, event); } return false; } }

Target:
public static boolean callSpawnEntitySpawner(final List<Entity> entities, final PhaseContext<?> context) { try (final CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { frame.addContext(EventContextKeys.SPAWN_TYPE, SpawnTypes.WORLD_SPAWNER); final SpawnEntityEvent event = SpongeEventFactory.createSpawnEntityEventSpawner(frame.getCurrentCause(), entities); SpongeImpl.postEvent(event); if (!event.isCancelled() && event.getEntities().size() > 0) { return EntityUtil.processEntitySpawnsFromEvent(context, event); } return false; } }
Source:
public String getProcessorName() { return RefactoringCoreMessages.RenameResourceProcessor_processor_name; }

Target:
public String getProcessorName() { return RefactoringCoreMessages.MoveRenameResourceProcessor_processor_name; }
Source:
public ConcurrentGrouper( final ByteBuffer buffer, final KeySerdeFactory<KeyType> keySerdeFactory, final ColumnSelectorFactory columnSelectorFactory, final AggregatorFactory[] aggregatorFactories, final int bufferGrouperMaxSize, final float bufferGrouperMaxLoadFactor, final int bufferGrouperInitialBuckets, final LimitedTemporaryStorage temporaryStorage, final ObjectMapper spillMapper, final int concurrencyHint ) { Preconditions.checkArgument(concurrencyHint > 0, "concurrencyHint > 0"); this.groupers = new ArrayList<>(concurrencyHint); this.threadLocalGrouper = new ThreadLocal<SpillingGrouper<KeyType>>() { @Override protected SpillingGrouper<KeyType> initialValue() { return groupers.get(threadNumber.getAndIncrement()); } }; final int sliceSize = (buffer.capacity() / concurrencyHint); for (int i = 0; i < concurrencyHint; i++) { final ByteBuffer slice = buffer.duplicate(); slice.position(sliceSize * i); slice.limit(slice.position() + sliceSize); groupers.add( new SpillingGrouper<>( slice.slice(), keySerdeFactory, columnSelectorFactory, aggregatorFactories, bufferGrouperMaxSize, bufferGrouperMaxLoadFactor, bufferGrouperInitialBuckets, temporaryStorage, spillMapper, false ) ); } this.entryComparator = keySerdeFactory.factorize().entryComparator(); }

Target:
public ConcurrentGrouper( final ByteBuffer buffer, final KeySerdeFactory<KeyType> keySerdeFactory, final ColumnSelectorFactory columnSelectorFactory, final AggregatorFactory[] aggregatorFactories, final int bufferGrouperMaxSize, final float bufferGrouperMaxLoadFactor, final int bufferGrouperInitialBuckets, final LimitedTemporaryStorage temporaryStorage, final ObjectMapper spillMapper, final int concurrencyHint ) { Preconditions.checkArgument(concurrencyHint > 0, "concurrencyHint > 0"); this.groupers = new ArrayList<>(concurrencyHint); this.threadLocalGrouper = new ThreadLocal<SpillingGrouper<KeyType>>() { @Override protected SpillingGrouper<KeyType> initialValue() { return groupers.get(threadNumber.getAndIncrement()); } }; final int sliceSize = (buffer.capacity() / concurrencyHint); for (int i = 0; i < concurrencyHint; i++) { final ByteBuffer slice = buffer.duplicate(); slice.position(sliceSize * i); slice.limit(slice.position() + sliceSize); groupers.add( new SpillingGrouper<>( slice.slice(), keySerdeFactory, columnSelectorFactory, aggregatorFactories, bufferGrouperMaxSize, bufferGrouperMaxLoadFactor, bufferGrouperInitialBuckets, temporaryStorage, spillMapper, false ) ); } this.keyObjComparator = keySerdeFactory.objectComparator(); }
Source:
public void testExecute() throws Exception { InstructorAttributes instructor1OfCourse1 = typicalBundle.instructors.get("instructor1OfCourse1"); String instructorId = instructor1OfCourse1.googleId; String courseId = instructor1OfCourse1.courseId; ______TS("Typical case, delete a soft-deleted course in Recycle Bin"); String[] submissionParams = new String[] { Const.ParamsNames.INSTRUCTOR_ID, instructorId, Const.ParamsNames.COURSE_ID, courseId, }; loginAsInstructor(instructorId); CoursesLogic.inst().moveCourseToRecycleBin(courseId); assertEquals(courseId, CoursesLogic.inst().getSoftDeletedCourseForInstructor(instructor1OfCourse1).getId()); DeleteCourseAction action = getAction(submissionParams); JsonResult result = getJsonResult(action); MessageOutput message = (MessageOutput) result.getOutput(); assertEquals(HttpStatus.SC_OK, result.getStatusCode()); assertEquals("The course " + courseId + " has been permanently deleted.", message.getMessage()); }

Target:
public void testExecute() throws Exception { ______TS("Not enough parameters"); verifyHttpParameterFailure(); InstructorAttributes instructor1OfCourse1 = typicalBundle.instructors.get("instructor1OfCourse1"); String instructorId = instructor1OfCourse1.googleId; String courseId = instructor1OfCourse1.courseId; ______TS("Typical case, delete a soft-deleted course in Recycle Bin"); String[] submissionParams = new String[] { Const.ParamsNames.COURSE_ID, courseId, }; CourseAttributes courseToBeDeleted = logic.getCourse(courseId); loginAsInstructor(instructorId); logic.moveCourseToRecycleBin(courseToBeDeleted.getId()); assertEquals(courseId, logic.getSoftDeletedCourseForInstructor(instructor1OfCourse1).getId()); DeleteCourseAction deleteCourseAction = getAction(submissionParams); JsonResult result = getJsonResult(deleteCourseAction); MessageOutput messageOutput = (MessageOutput) result.getOutput(); assertEquals(HttpStatus.SC_OK, result.getStatusCode()); assertEquals("OK", messageOutput.getMessage()); assertNull(logic.getCourse(instructor1OfCourse1.courseId)); }
Source:
private byte[] createContentAccessDataPayload(Owner owner, Environment environment) throws IOException { Set<Product> containerSet = new HashSet<Product>(); List<Content> ownerContent = (List<Content>) ownerContentCurator.getContentByOwner(owner); Set<String> entitledProductIds = new HashSet<String>(); List<org.candlepin.model.dto.Product> productModels = new ArrayList<org.candlepin.model.dto.Product>(); Map<String, EnvironmentContent> promotedContent = getPromotedContent(environment); String contentPrefix = getContentPrefix(owner, environment); Product container = new Product(); Entitlement emptyEnt = new Entitlement(); Pool emptyPool = new Pool(); Product skuProduct = new Product(); Consumer emptyConsumer = new Consumer(); containerSet.add(container); container.setId("content_access"); container.setName("Golden Ticket"); for (Content c : ownerContent) { container.addContent(c, false); } emptyConsumer.setEnvironment(environment); emptyEnt.setPool(emptyPool); emptyEnt.setConsumer(emptyConsumer); emptyPool.setProduct(skuProduct); emptyPool.setStartDate(new Date()); emptyPool.setEndDate(new Date()); skuProduct.setName("Golden Ticket"); skuProduct.setId("content_access"); entitledProductIds.add("content-access"); org.candlepin.model.dto.Product productModel = v3extensionUtil.mapProduct(container, skuProduct, contentPrefix, promotedContent, emptyConsumer, emptyEnt, entitledProductIds); productModels.add(productModel); return v3extensionUtil.createEntitlementDataPayload(skuProduct, productModels, emptyEnt, contentPrefix, promotedContent); }

Target:
private byte[] createContentAccessDataPayload(Owner owner, Environment environment) throws IOException { Set<Product> containerSet = new HashSet<Product>(); CandlepinQuery<Content> ownerContent = ownerContentCurator.getContentByOwner(owner); Set<String> entitledProductIds = new HashSet<String>(); List<org.candlepin.model.dto.Product> productModels = new ArrayList<org.candlepin.model.dto.Product>(); Map<String, EnvironmentContent> promotedContent = getPromotedContent(environment); String contentPrefix = getContentPrefix(owner, environment); Product container = new Product(); Entitlement emptyEnt = new Entitlement(); Pool emptyPool = new Pool(); Product skuProduct = new Product(); Consumer emptyConsumer = new Consumer(); containerSet.add(container); container.setId("content_access"); container.setName(" Content Access"); for (Content c : ownerContent) { container.addContent(c, false); } emptyConsumer.setEnvironment(environment); emptyEnt.setPool(emptyPool); emptyEnt.setConsumer(emptyConsumer); emptyPool.setProduct(skuProduct); emptyPool.setStartDate(new Date()); emptyPool.setEndDate(new Date()); skuProduct.setName("Content Access"); skuProduct.setId("content_access"); entitledProductIds.add("content-access"); org.candlepin.model.dto.Product productModel = v3extensionUtil.mapProduct(container, skuProduct, contentPrefix, promotedContent, emptyConsumer, emptyEnt, entitledProductIds); productModels.add(productModel); return v3extensionUtil.createEntitlementDataPayload(skuProduct, productModels, emptyEnt, contentPrefix, promotedContent); }
Source:
private int getReadBarcodeValue(final SAMRecord record, final String tag) { if (null == READ_ONE_BARCODE_TAG) return 0; final String attr = record.getStringAttribute(tag); if (null == attr) return 0; else return attr.hashCode(); }

Target:
public static int getReadBarcodeValue(final SAMRecord record, final String tag) { if (null == tag) return 0; final String attr = record.getStringAttribute(tag); if (null == attr) return 0; else return attr.hashCode(); }
Source:
private String getDefaultTextValue(FormField field) { Map<String, String> fieldAttributes = new HashMap<String, String>(); fieldAttributes.putAll(field.getFormControl().getAttributesMap()); fieldAttributes.put("Control Type", field.getFormControl().getFormControlType().name()); return this.valueGenerator.getValue(null, null, fieldAttributes); }

Target:
private List<String> getDefaultTextValue(FormField field) { String fieldId = field.getName(); Map<String, String> fieldAttributes = new HashMap<String, String>(); List<String> definedValues = new ArrayList<String>(); fieldAttributes.putAll(field.getFormControl().getAttributesMap()); fieldAttributes.put("Control Type", field.getFormControl().getFormControlType().name()); if (field.getFormControl().getFormControlType().isSubmit()) { List<String> submitFields = new ArrayList<String>(); for (String value : field.getPredefinedValues()){ String finalValue = this.valueGenerator.getValue(uri, url, fieldId, value, definedValues, envAttributes, fieldAttributes); submitFields.add(finalValue); } return submitFields; } List<String> values = field.getValues(); String defaultValue; if(field.getFormControl().getAttributesMap().containsKey("value")){ defaultValue = field.getFormControl().getAttributesMap().get("value"); } if (log.isDebugEnabled()) { log.debug("Existing values: " + values); } if (values.isEmpty() || (values.size() == 1 && values.get(0).isEmpty())) { defaultValue = DEFAULT_EMPTY_VALUE; Collection<String> predefValues = field.getPredefinedValues(); if (!predefValues.isEmpty()) { definedValues.addAll(predefValues); Iterator<String> iterator = predefValues.iterator(); defaultValue = iterator.next(); if (iterator.hasNext()) { defaultValue = iterator.next(); } } } else { defaultValue = values.get(0); } String finalValue = this.valueGenerator.getValue(uri, url, fieldId, defaultValue, definedValues, envAttributes, fieldAttributes); log.debug("Generated: " + finalValue + "For field " + field.getName()); values = new ArrayList<>(1); values.add(finalValue); return values; }
Source:
private static void applyArtifactInNormalFilter(final M2FiltersArgumentCollection MTFAC, final VariantContext vc, final Collection<String> filters) { if (!vc.hasAttribute(SomaticGenotypingEngine.NORMAL_ARTIFACT_LOD_ATTRIBUTE)) { return; } final double normalArtifactLod = MathUtils.arrayMax(GATKProtectedVariantContextUtils.getAttributeAsDoubleArray(vc, SomaticGenotypingEngine.NORMAL_ARTIFACT_LOD_ATTRIBUTE, () -> null, -1)); if (normalArtifactLod > MTFAC.NORMAL_ARTIFACT_LOD_THRESHOLD) { filters.add(ARTIFACT_IN_NORMAL_FILTER_NAME); } }

Target:
private static void applyArtifactInNormalFilter(final M2FiltersArgumentCollection MTFAC, final VariantContext vc, final Collection<String> filters) { if (!( vc.hasAttribute(SomaticGenotypingEngine.NORMAL_ARTIFACT_LOD_ATTRIBUTE) && vc.hasAttribute(GATKVCFConstants.TUMOR_LOD_KEY))) { return; } final double[] normalArtifactLods = getArrayAttribute(vc, SomaticGenotypingEngine.NORMAL_ARTIFACT_LOD_ATTRIBUTE); final double[] tumorLods = getArrayAttribute(vc, GATKVCFConstants.TUMOR_LOD_KEY); final int indexOfMaxTumorLod = MathUtils.maxElementIndex(tumorLods); if (normalArtifactLods[indexOfMaxTumorLod] > MTFAC.NORMAL_ARTIFACT_LOD_THRESHOLD) { filters.add(ARTIFACT_IN_NORMAL_FILTER_NAME); } }
Source:
public Secret getId() { properties.getId(); return this; }

Target:
public String getId() { return properties.getId(); }
Source:
public SearchResult query(final SearchQuery query) { final String input = query.getInput(); final CriteriaBuilder builder = new CriteriaBuilder(OnmsMonitoringLocation.class) .ilike("locationName", QueryUtils.ilike(input)) .orderBy("locationName") .distinct(); final int totalCount = monitoringLocationDao.countMatching(builder.toCriteria()); final Criteria criteria = builder.limit(query.getMaxResults()).toCriteria(); final List<OnmsMonitoringLocation> matchingResult = monitoringLocationDao.findMatching(criteria); final List<SearchResultItem> searchResultItems = matchingResult.stream().map(monitoringLocation -> { final SearchResultItem searchResultItem = new SearchResultItem(); searchResultItem.setIdentifier(monitoringLocation.getLocationName()); searchResultItem.setLabel("Show nodes in location '" + monitoringLocation.getLocationName() + "'"); searchResultItem.setUrl("element/nodeList.htm?monitoringLocation=" + monitoringLocation.getLocationName()); return searchResultItem; }).collect(Collectors.toList()); final SearchResult searchResult = new SearchResult(Contexts.Action).withMore(totalCount > searchResultItems.size()).withResults(searchResultItems); return searchResult; }

Target:
public SearchResult query(final SearchQuery query) { final String input = query.getInput(); final CriteriaBuilder builder = new CriteriaBuilder(OnmsMonitoringLocation.class) .ilike("locationName", QueryUtils.ilike(input)) .orderBy("locationName") .distinct(); final int totalCount = monitoringLocationDao.countMatching(builder.toCriteria()); final Criteria criteria = builder.limit(query.getMaxResults()).toCriteria(); final List<OnmsMonitoringLocation> matchingResult = monitoringLocationDao.findMatching(criteria); final List<SearchResultItem> searchResultItems = matchingResult.stream().map(monitoringLocation -> { final SearchResultItem searchResultItem = new SearchResultItem(); searchResultItem.setIdentifier(monitoringLocation.getLocationName()); searchResultItem.setLabel("Show nodes in location '" + monitoringLocation.getLocationName() + "'"); searchResultItem.setUrl("element/nodeList.htm?monitoringLocation=" + UrlUtils.encode(monitoringLocation.getLocationName())); return searchResultItem; }).collect(Collectors.toList()); final SearchResult searchResult = new SearchResult(Contexts.Action).withMore(totalCount > searchResultItems.size()).withResults(searchResultItems); return searchResult; }
Source:
protected void verifyOutput(UserDTO source, User dest, boolean childrenGenerated) { if (source != null) { assertEquals(source.getId(), dest.getId()); assertEquals(source.getUsername(), dest.getUsername()); assertEquals(source.getSuperAdmin(), dest.isSuperAdmin()); assertNotNull(source.getPassword()); assertNotNull(dest.getPassword()); } else { assertNull(dest); } }

Target:
protected void verifyOutput(UserDTO source, User dest, boolean childrenGenerated) { if (source != null) { assertEquals(source.getUsername(), dest.getUsername()); assertEquals(source.getSuperAdmin(), dest.isSuperAdmin()); assertEquals(Util.hash(source.getPassword()), dest.getHashedPassword()); } else { assertNull(dest); } }
Source:
private void requestState() { new Thread(new Runnable() { @Override public void run() { for (String cmd : Arrays.asList("PW?", "MS?", "MV?", "ZM?", "MU?", "SI?", "Z2?", "Z2MU?", "Z3", "Z3MU?", "NSE")) { internSendCommandTelnet(cmd); try { Thread.sleep(300); } catch (InterruptedException e) { logger.trace("Interrupted while requesting state", e); } } } }).start(); }

Target:
private void requestState() { executor.execute(new Runnable() { @Override public void run() { for (String cmd : Arrays.asList("PW?", "MS?", "MV?", "ZM?", "MU?", "SI?", "Z2?", "Z2MU?", "Z3", "Z3MU?", "NSE")) { internSendCommandTelnet(cmd); try { Thread.sleep(300); } catch (InterruptedException e) { logger.trace("Interrupted while requesting state", e); } } } }); }
Source:
private IWindowComponent wrapActivity(final Activity activity) { if (activity == null) { throw new IllegalArgumentException("activity"); } return new IWindowComponent() { Activity mRefActivity = activity; @Override public void startActivityForResult(Intent intent, int requestCode) { if (mRefActivity != null) { mRefActivity.startActivityForResult(intent, requestCode); } } }; }

Target:
private IWindowComponent wrapActivity(final Activity activity) { if (activity == null) { throw new IllegalArgumentException("activity"); } return new IWindowComponent() { private Activity mRefActivity = activity; @Override public void startActivityForResult(Intent intent, int requestCode) { if (mRefActivity != null) { mRefActivity.startActivityForResult(intent, requestCode); } } }; }
Source:
public void display(final ChangeDetail detail, final PatchSet.Id diffBaseId) { clear(); final PatchSet currps = detail.getCurrentPatchSet(); currentPatchSetId = currps.getId(); patchSets = new ArrayList<PatchSet>(); for (PatchSet ps : detail.getPatchSets()) { if (!ps.isDraft() || (Gerrit.isSignedIn() && detail.hasDraftAccess(Gerrit.getUserAccount().getId()))) { patchSets.add(ps); } else if (currentPatchSetId == ps.getId()) { currentPatchSetId = null; } } if (currentPatchSetId == null) { if (!patchSets.isEmpty()) { currentPatchSetId = patchSets.get(patchSets.size() - 1).getId(); } else { currentPatchSetId = currps.getId(); } } if (Gerrit.isSignedIn()) { final AccountGeneralPreferences p = Gerrit.getUserAccount().getGeneralPreferences(); if (p.isDisplayPatchSetsInReverseOrder()) { Collections.reverse(patchSets); } } patchSetPanelsList = new ArrayList<PatchSetComplexDisclosurePanel>(); for (final PatchSet ps : patchSets) { final PatchSetComplexDisclosurePanel p; if (ps == currps) { p = new PatchSetComplexDisclosurePanel(parent, detail, detail .getCurrentPatchSetDetail()); if (diffBaseId != null) { p.setDiffBaseId(diffBaseId); p.refresh(); } } else { p = new PatchSetComplexDisclosurePanel(parent, detail, ps); if (diffBaseId != null) { p.setDiffBaseId(diffBaseId); } if (ps.getId() == currentPatchSetId){ p.setOpen(true); } } add(p); patchSetPanelsList.add(p); } }

Target:
public void display(final ChangeDetail detail, final PatchSet.Id diffBaseId) { clear(); final PatchSet currps = detail.getCurrentPatchSet(); currentPatchSetId = currps.getId(); patchSets = detail.getPatchSets(); final List<PatchSet.Id> changePatchSets = new ArrayList<PatchSet.Id>(); for (final PatchSet ps : patchSets) { changePatchSets.add(ps.getId()); } if (Gerrit.isSignedIn()) { final AccountGeneralPreferences p = Gerrit.getUserAccount().getGeneralPreferences(); if (p.isDisplayPatchSetsInReverseOrder()) { Collections.reverse(patchSets); } } patchSetPanelsList = new ArrayList<PatchSetComplexDisclosurePanel>(); for (final PatchSet ps : patchSets) { final PatchSetComplexDisclosurePanel p; if (ps == currps) { p = new PatchSetComplexDisclosurePanel(parent, detail, detail .getCurrentPatchSetDetail()); if (diffBaseId != null) { p.setDiffBaseId(diffBaseId); p.refresh(); } } else { p = new PatchSetComplexDisclosurePanel(parent, detail, ps); if (diffBaseId != null) { p.setDiffBaseId(diffBaseId); } } add(p); patchSetPanelsList.add(p); } }
Source:
public String[] getPlantsOfStudent(String student) { String[] plants = new String[PARTITION_SIZE_WIDTH * 2]; int studentPlantsIndex = Arrays.binarySearch(students, student) * PARTITION_SIZE_WIDTH; for (int i = 0; i < PARTITION_SIZE_WIDTH; i++) { plants[i] = getPlantName(garden.charAt(studentPlantsIndex + i)); } int newRowLocation = garden.indexOf('\n'); for (int i = PARTITION_SIZE_WIDTH; i < PARTITION_SIZE_WIDTH * 2; i++) { plants[i] = getPlantName(garden.charAt(newRowLocation - 1 + studentPlantsIndex + i)); } return plants; }

Target:
public List<Plant> getPlantsOfStudent(String student) { List<Plant> plants = new ArrayList<Plant>(); int studentPlantsIndex = Arrays.binarySearch(students, student) * PLANTS_PER_STUDENT_PER_ROW; for (int i = studentPlantsIndex; i < studentPlantsIndex + PLANTS_PER_STUDENT_PER_ROW; i++) { plants.add(Plant.getPlant(garden.charAt(i))); } for (int i = newRowLocation + studentPlantsIndex; i < newRowLocation + studentPlantsIndex + PLANTS_PER_STUDENT_PER_ROW; i++) { plants.add(Plant.getPlant(garden.charAt(i))); } return plants; }
Source:
protected int index(String urlFormat, String bulkString) throws IOException { String tempUrl = String.format(urlFormat, getBaseUrl()); HttpEntity entity = new NStringEntity(bulkString, ContentType.APPLICATION_JSON); int statusCode = 0; Queue<String> callQ = new LinkedList<>(); callQ.add(tempUrl); int callCount = 0; while(!callQ.isEmpty() && callCount < MAX_CALL_COUNT) { callCount++; String url = callQ.remove(); logger.info("Using url [{}]", url); HttpPost httpPost = new HttpPost(url); httpPost.setHeaders(getHeaders()); httpPost.setEntity(entity); CloseableHttpResponse response = null; try { response = closeableHttpClient.execute(httpPost); statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED) { logger.error("index method failed with status code: and error: {}", response.getStatusLine().getStatusCode(), EntityUtils.toString(response.getEntity())); } } catch (Exception e) { if(response == null){ logger.error("index method failed with message: {}", e.getMessage()); url = String.format(urlFormat, getBaseUrl()); callQ.add(url); } else { logger.error("index method failed with status code: and exception message: {}", response.getStatusLine().getStatusCode(), e.getMessage()); } } finally { if(response != null) { response.close(); } } } return statusCode; }

Target:
public int index(String urlFormat, String bulkString) throws IOException { String tempUrl = String.format(urlFormat, getBaseUrl()); HttpEntity entity = new NStringEntity(bulkString, ContentType.APPLICATION_JSON); int statusCode = 0; Queue<String> callQ = new LinkedList<>(); callQ.add(tempUrl); int callCount = 0; while(!callQ.isEmpty() && callCount < MAX_CALL_COUNT) { callCount++; String url = callQ.remove(); logger.info("Using url [{}]", url); HttpPost httpPost = new HttpPost(url); httpPost.setHeaders(getHeaders()); httpPost.setEntity(entity); CloseableHttpResponse response = null; try { response = closeableHttpClient.execute(httpPost); statusCode = response.getStatusLine().getStatusCode(); String str = EntityUtils.toString(response.getEntity()); EntityUtils.consume(response.getEntity()); if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED) { logger.error("index method failed with status code: and error: {}", statusCode, str); } } catch (Exception e) { if(response == null){ logger.error("index method failed with message: {}", e.getMessage()); url = String.format(urlFormat, getBaseUrl()); callQ.add(url); } else { logger.error("index method failed with status code: and exception message: {}", statusCode, e.getMessage()); } } finally { if(response != null) { response.close(); } } } return statusCode; }
Source:
private ClusterConfig getClusterConfig(ServicesConfig servicesConfig) { if (servicesConfig != null && !servicesConfig.services().isEmpty()) { Map<String, String> metadata = clusterConfig.metadata(); if (metadata.isEmpty()) { metadata = new HashMap<>(); } metadata.putAll(Microservices.metadata(servicesConfig)); clusterConfig.metadata(metadata); } return clusterConfig.build(); }

Target:
private ClusterConfig getClusterConfig(ServicesConfig servicesConfig) { if (servicesConfig != null && !servicesConfig.services().isEmpty()) { Map<String, String> metadata = new HashMap<>(); metadata.putAll(clusterConfig.metadata()); metadata.putAll(Microservices.metadata(servicesConfig)); clusterConfig.metadata(metadata); } return clusterConfig.build(); }
Source:
public Document getDocumentById( String id ) { File file = fileFor(id); if (isExcluded(file) || !file.exists()) { return null; } boolean isRoot = isRoot(id); boolean isResource = isContentNode(id); DocumentWriter writer = null; File parentFile = file.getParentFile(); if (isResource) { writer = newDocument(id); BinaryValue binaryValue = binaryFor(file); writer.setPrimaryType(NT_RESOURCE); writer.addProperty(JCR_DATA, binaryValue); if (addMimeTypeMixin) { String mimeType = null; String encoding = null; try { mimeType = binaryValue.getMimeType(); } catch (Throwable e) { getLogger().error(e, JcrI18n.couldNotGetMimeType, getSourceName(), id, e.getMessage()); } writer.addProperty(JCR_ENCODING, encoding); writer.addProperty(JCR_MIME_TYPE, mimeType); } writer.addProperty(JCR_LAST_MODIFIED, factories().getDateFactory().create(file.lastModified())); writer.addProperty(JCR_LAST_MODIFIED_BY, null); writer.setNotQueryable(); parentFile = file; } else if (file.isFile()) { writer = newDocument(id); writer.setPrimaryType(NT_FILE); writer.addProperty(JCR_CREATED, factories().getDateFactory().create(file.lastModified())); writer.addProperty(JCR_CREATED_BY, null); String childId = isRoot ? JCR_CONTENT_SUFFIX : id + JCR_CONTENT_SUFFIX; writer.addChild(childId, JCR_CONTENT); } else { writer = newFolderWriter(id, file, 0); } if (!isRoot) { String parentId = idFor(parentFile); writer.setParents(parentId); } writer.addProperties(extraPropertiesStore().getProperties(id)); if (addMimeTypeMixin) { writer.addMixinType(MIX_MIME_TYPE); } return writer.document(); }

Target:
public Document getDocumentById( String id ) { File file = fileFor(id); if (isExcluded(file) || !file.exists()) return null; boolean isRoot = isRoot(id); boolean isResource = isContentNode(id); DocumentWriter writer = null; File parentFile = file.getParentFile(); if (isResource) { writer = newDocument(id); BinaryValue binaryValue = binaryFor(file); writer.setPrimaryType(NT_RESOURCE); writer.addProperty(JCR_DATA, binaryValue); if (addMimeTypeMixin) { String mimeType = null; String encoding = null; try { mimeType = binaryValue.getMimeType(); } catch (Throwable e) { getLogger().error(e, JcrI18n.couldNotGetMimeType, getSourceName(), id, e.getMessage()); } writer.addProperty(JCR_ENCODING, encoding); writer.addProperty(JCR_MIME_TYPE, mimeType); } writer.addProperty(JCR_LAST_MODIFIED, factories().getDateFactory().create(file.lastModified())); writer.addProperty(JCR_LAST_MODIFIED_BY, null); writer.setNotQueryable(); parentFile = file; } else if (file.isFile()) { writer = newDocument(id); writer.setPrimaryType(NT_FILE); writer.addProperty(JCR_CREATED, factories().getDateFactory().create(file.lastModified())); writer.addProperty(JCR_CREATED_BY, null); String childId = isRoot ? JCR_CONTENT_SUFFIX : id + JCR_CONTENT_SUFFIX; writer.addChild(childId, JCR_CONTENT); } else { writer = newFolderWriter(id, file, 0); } if (!isRoot) { String parentId = idFor(parentFile); writer.setParents(parentId); } writer.addProperties(extraPropertiesStore().getProperties(id)); if (addMimeTypeMixin) { writer.addMixinType(MIX_MIME_TYPE); } return writer.document(); }