auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void build() { Flyway flyway = new Flyway(); flyway.setDataSource(properties.getProperty("databaseUrl"), properties.getProperty("databaseUrl") ,properties.getProperty("databaseUrl")); flyway.setInitVersion("0"); flyway.setTarget(MigrationVersion.fromVersion("0.3")); flyway.clean(); flyway.init(); flyway.migrate(); }

Target:
public void build() { Flyway flyway = new Flyway(); flyway.setDataSource(properties.getProperty("databaseUrl"), properties.getProperty("databaseUsername") ,properties.getProperty("databasePassword")); flyway.setInitVersion("0"); flyway.setTarget(MigrationVersion.fromVersion("0.3")); flyway.clean(); flyway.init(); flyway.migrate(); }
Source:
private static char[] getManifestContents(IPath jarPath) throws CoreException, IOException { if (JavaIndex.isEnabled()) { JavaIndex index = JavaIndex.getIndex(); String location = JavaModelManager.getLocalFile(jarPath).getAbsolutePath(); try (IReader reader = index.getNd().acquireReadLock()) { NdResourceFile resourceFile = index.getResourceFile(location.toCharArray()); if (index.isUpToDate(resourceFile)) { char[] manifestContent = resourceFile.getManifestContent().getChars(); if (manifestContent.length == 0) { return null; } return manifestContent; } } } ZipFile zip = null; InputStream inputStream = null; JavaModelManager manager = JavaModelManager.getJavaModelManager(); try { zip = manager.getZipFile(jarPath); ZipEntry manifest = zip.getEntry("META-INF/MANIFEST.MF"); if (manifest == null) { return null; } inputStream = zip.getInputStream(manifest); char[] chars = org.eclipse.jdt.internal.compiler.util.Util.getInputStreamAsCharArray(inputStream, -1, org.eclipse.jdt.internal.compiler.util.Util.UTF_8); return chars; } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } manager.closeZipFile(zip); } }

Target:
private static char[] getManifestContents(IPath jarPath) throws CoreException, IOException { if (JavaIndex.isEnabled()) { JavaIndex index = JavaIndex.getIndex(); String location = JavaModelManager.getLocalFile(jarPath).getAbsolutePath(); try (IReader reader = index.getNd().acquireReadLock()) { NdResourceFile resourceFile = index.getResourceFile(location.toCharArray()); if (index.isUpToDate(resourceFile)) { char[] manifestContent = resourceFile.getManifestContent().getChars(); if (manifestContent.length == 0) { return null; } return manifestContent; } } } ZipFile zip = null; InputStream inputStream = null; JavaModelManager manager = JavaModelManager.getJavaModelManager(); try { zip = manager.getZipFile(jarPath); ZipEntry manifest = zip.getEntry("META-INF/MANIFEST.MF"); if (manifest == null) { return null; } inputStream = zip.getInputStream(manifest); char[] chars = getInputStreamAsCharArray(inputStream, -1, UTF_8); return chars; } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } manager.closeZipFile(zip); } }
Source:
int scan(BinaryDeque.BinaryDequeScanner scanner) throws IOException { SegmentReader reader = openForRead(SCANNER_CURSOR); try { validateHeader(); int initialEntryCount = getNumEntries(); if (initialEntryCount == 0) { return 0; } long lastReadId = -1; while (true) { DBBPool.BBContainer cont = null; try { cont = reader.poll(PersistentBinaryDeque.UNSAFE_CONTAINER_FACTORY, true); } catch(IOException e) { reader.truncateToCurrentReadIndex(lastReadId); } if (cont == null) { break; } try { lastReadId = scanner.scan(cont); assert(m_startId == -1 || lastReadId != -1); } finally { cont.discard(); } } int entriesScanned = reader.readIndex(); int entriesTruncated = initialEntryCount - entriesScanned; if (!m_isActive && !isFinal() && entriesTruncated == 0) { finalize(false); } return entriesTruncated; } finally { reader.close(); } }

Target:
int scan(BinaryDeque.BinaryDequeScanner scanner) throws IOException { SegmentReader reader = openForRead(SCANNER_CURSOR); try { validateHeader(); int initialEntryCount = getNumEntries(); if (initialEntryCount == 0) { return 0; } long lastReadId = -1; while (true) { DBBPool.BBContainer cont = null; try { cont = reader.poll(PersistentBinaryDeque.UNSAFE_CONTAINER_FACTORY, true); } catch(IOException e) { m_usageSpecificLog.warn("Truncating segment file to the last safe point due to error", e); reader.truncateToCurrentReadIndex(lastReadId); } if (cont == null) { break; } try { lastReadId = scanner.scan(cont); assert(m_startId == -1 || lastReadId != -1); } finally { cont.discard(); } } int entriesScanned = reader.readIndex(); int entriesTruncated = initialEntryCount - entriesScanned; if (!m_isActive && !isFinal() && entriesTruncated == 0) { finalize(false); } return entriesTruncated; } finally { reader.close(); } }
Source:
public Configuration getConfiguration() { return new ConfigurationImpl(srvCtx.getConfiguration()); }

Target:
public Configuration getConfiguration() { return conf; }
Source:
public TiffRasterData readRasterData(Rectangle subImage) throws ImageReadException, IOException { int xRaster; int yRaster; int rasterWidth; int rasterHeight; if (subImage != null) { xRaster = subImage.x; yRaster = subImage.y; rasterWidth = subImage.width; rasterHeight = subImage.height; } else { xRaster = 0; yRaster = 0; rasterWidth = width; rasterHeight = height; } float[] rasterData = new float[rasterWidth * rasterHeight]; final int strip0 = yRaster / rowsPerStrip; final int strip1 = (yRaster + rasterHeight - 1) / rowsPerStrip; for (int strip = strip0; strip <= strip1; strip++) { int yStrip = strip * rowsPerStrip; int rowsRemaining = height - yStrip; int rowsInThisStrip = rowsRemaining > rowsPerStrip ? rowsPerStrip : rowsRemaining; int bytesPerRow = (bitsPerPixel * width + 7) / 8; int bytesPerStrip = rowsInThisStrip * bytesPerRow; final byte[] compressed = imageData.getImageData(strip).getData(); final byte[] decompressed = decompress(compressed, compression, bytesPerStrip, width, rowsInThisStrip); int[] blockData = unpackFloatingPointSamples( width, (int) rowsInThisStrip, width, decompressed, predictor, bitsPerPixel, byteOrder); transferBlockToRaster(0, yStrip, width, (int) rowsInThisStrip, blockData, xRaster, yRaster, rasterWidth, rasterHeight, rasterData); } return new TiffRasterData(rasterWidth, rasterHeight, rasterData); }

Target:
public TiffRasterData readRasterData(Rectangle subImage) throws ImageReadException, IOException { int xRaster; int yRaster; int rasterWidth; int rasterHeight; if (subImage != null) { xRaster = subImage.x; yRaster = subImage.y; rasterWidth = subImage.width; rasterHeight = subImage.height; } else { xRaster = 0; yRaster = 0; rasterWidth = width; rasterHeight = height; } float[] rasterData = new float[rasterWidth * rasterHeight]; final int strip0 = yRaster / rowsPerStrip; final int strip1 = (yRaster + rasterHeight - 1) / rowsPerStrip; for (int strip = strip0; strip <= strip1; strip++) { int yStrip = strip * rowsPerStrip; int rowsRemaining = height - yStrip; int rowsInThisStrip = Math.min(rowsRemaining, rowsPerStrip); int bytesPerRow = (bitsPerPixel * width + 7) / 8; int bytesPerStrip = rowsInThisStrip * bytesPerRow; final byte[] compressed = imageData.getImageData(strip).getData(); final byte[] decompressed = decompress(compressed, compression, bytesPerStrip, width, rowsInThisStrip); int[] blockData = unpackFloatingPointSamples( width, (int) rowsInThisStrip, width, decompressed, predictor, bitsPerPixel, byteOrder); transferBlockToRaster(0, yStrip, width, (int) rowsInThisStrip, blockData, xRaster, yRaster, rasterWidth, rasterHeight, rasterData); } return new TiffRasterData(rasterWidth, rasterHeight, rasterData); }
Source:
public WSAuthorizationManager(String serverUrl, String cookie, ConfigurationContext configCtxt) throws UserStoreException { try { stub = new RemoteAuthorizationManagerServiceStub(configCtxt, serverUrl + SERVICE_NAME); ServiceClient client = stub._getServiceClient(); Options option = client.getOptions(); option.setManageSession(true); option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie); } catch (AxisFault e) { if (log.isDebugEnabled()) { log.debug(CONNECTION_ERROR_MESSAGE, e); } throw new UserStoreException(); } }

Target:
public WSAuthorizationManager(String serverUrl, String cookie, ConfigurationContext configCtxt) throws UserStoreException { try { stub = new RemoteAuthorizationManagerServiceStub(configCtxt, serverUrl + SERVICE_NAME); ServiceClient client = stub._getServiceClient(); Options option = client.getOptions(); option.setManageSession(true); option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie); } catch (AxisFault e) { throw new UserStoreException("Axis error occurred while creating service client stub", e); } }
Source:
public final void createsKey() throws Exception { final PublicKeys keys = this.keys(); final PublicKey key = keys.create("rsa", "rsa sh"); MatcherAssert.assertThat( keys.iterate().iterator().next(), Matchers.equalTo(key) ); MatcherAssert.assertThat( key.user(), Matchers.equalTo( keys.user() ) ); keys.remove( key.number() ); MatcherAssert.assertThat( keys.iterate(), Matchers.not(Matchers.hasItem(key)) ); }

Target:
public final void createsKey() throws Exception { final PublicKeys keys = this.keys(); final PublicKey key = keys.create("rsa", "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDS+TF7+bae4UKj6nec1oipiP9Ysc6mBPszB80z13tMZBlsPCOiLVAMO2ER/wpnKHd/VylmYr5c6wc3kSj88846VHUhQDN7fLd/km06KTdW4+9db7HBfvr0063eDdi1lg8jlnccegeeqKsG39+iVQban7ugcPyJtjQE9k7JjYBT+SOgupWkYPVO+5Z3xF6VJL8gUTIMgoovgTabFx60t5h5UPtNaGbdcSlHhLOlWn8I7tHvwbYdhZVqlCC450rieXo8PpjndG3crcuHPZPDVSSXyqRpguIxVEVjXd3B/0vrhXJQJC4u0ukOOytLNL6Gzz3oK7SIB0mqWJ4Mo0Wp+zeX jac.wshmstr@gmail.com"); try { MatcherAssert.assertThat( keys.iterate(), Matchers.hasItem(key) ); MatcherAssert.assertThat( key.user(), Matchers.equalTo( keys.user() ) ); } finally { keys.remove(key.number()); } MatcherAssert.assertThat( keys.iterate(), Matchers.not(Matchers.hasItem(key)) ); }
Source:
public static PinotDataBitSetV2 createBitSet(PinotDataBuffer pinotDataBuffer, int numBitsPerValue) { switch (numBitsPerValue) { case 2: return new Bit2Encoded(pinotDataBuffer, numBitsPerValue); case 4: return new Bit4Encoded(pinotDataBuffer, numBitsPerValue); case 8: return new Bit8Encoded(pinotDataBuffer, numBitsPerValue); case 16: return new Bit16Encoded(pinotDataBuffer, numBitsPerValue); case 32: return new RawInt(pinotDataBuffer, numBitsPerValue); default: throw new UnsupportedOperationException(numBitsPerValue + "not supported by PinotDataBitSetV2"); } }

Target:
public static PinotDataBitSetV2 createBitSet(PinotDataBuffer pinotDataBuffer, int numBitsPerValue) { switch (numBitsPerValue) { case 1: return new Bit1Encoded(pinotDataBuffer, numBitsPerValue); case 2: return new Bit2Encoded(pinotDataBuffer, numBitsPerValue); case 4: return new Bit4Encoded(pinotDataBuffer, numBitsPerValue); case 8: return new Bit8Encoded(pinotDataBuffer, numBitsPerValue); case 16: return new Bit16Encoded(pinotDataBuffer, numBitsPerValue); case 32: return new RawInt(pinotDataBuffer, numBitsPerValue); default: throw new UnsupportedOperationException(numBitsPerValue + "not supported by PinotDataBitSetV2"); } }
Source:
public synchronized CtfTmfEvent getCurrentEvent() { final StreamInputReader top = super.getPrio().peek(); if (top != null) { if (fCurLocation.hashCode() != fPreviousHashCode) { fPreviousHashCode = fCurLocation.hashCode(); fPreviousCurEvent = CtfTmfEventFactory.createEvent(top.getCurrentEvent(), top.getFilename(), fTrace); } return fPreviousCurEvent; } return null; }

Target:
public synchronized CtfTmfEvent getCurrentEvent() { final StreamInputReader top = super.getPrio().peek(); if (top != null) { if (!fCurLocation.equals(fPreviousLocation)) { fPreviousLocation = fCurLocation; fPreviousEvent = CtfTmfEventFactory.createEvent(top.getCurrentEvent(), top.getFilename(), fTrace); } return fPreviousEvent; } return null; }
Source:
public void putTokenInfo(final UUID tokenUUID, final Map<String, Object> tokenInfo, final ByteBuffer principalKeyBuffer, final int ttl){ Preconditions.checkNotNull(tokenUUID, "tokenUUID is required"); Preconditions.checkNotNull(tokenUUID, "tokenInfo is required"); Preconditions.checkNotNull(ttl, "ttl is required"); logger.trace("putTokenInfo, token UUID: {}, tokenInfo: {}, ttl: {}", tokenUUID, tokenInfo, ttl); final BatchStatement batchStatement = new BatchStatement(); final Using usingTTL = QueryBuilder.ttl(ttl); tokenInfo.forEach((key, value) -> { ByteBuffer valueBuffer; if(key.equalsIgnoreCase(TOKEN_STATE)){ valueBuffer = toByteBuffer(value); }else{ valueBuffer = DataType.serializeValue(value, ProtocolVersion.NEWEST_SUPPORTED); } batchStatement.add( QueryBuilder.insertInto(TOKENS_TABLE) .value("key", DataType.serializeValue(tokenUUID, ProtocolVersion.NEWEST_SUPPORTED)) .value("column1", DataType.serializeValue(key, ProtocolVersion.NEWEST_SUPPORTED)) .value("value", valueBuffer) .using(usingTTL)); }); if(principalKeyBuffer != null){ batchStatement.add( QueryBuilder.insertInto(PRINCIPAL_TOKENS_TABLE) .value("key", principalKeyBuffer) .value("column1", DataType.serializeValue(tokenUUID, ProtocolVersion.NEWEST_SUPPORTED)) .value("value", ByteBuffer.wrap( new byte[] { 0 } )) .using(usingTTL)); } session.execute(batchStatement); }

Target:
public void putTokenInfo(final UUID tokenUUID, final Map<String, Object> tokenInfo, final ByteBuffer principalKeyBuffer, final int ttl){ Preconditions.checkNotNull(tokenUUID, "tokenUUID is required"); Preconditions.checkNotNull(tokenUUID, "tokenInfo is required"); Preconditions.checkArgument(ttl > -1 , "ttl is required to be positive"); logger.trace("putTokenInfo, token UUID: {}, tokenInfo: {}, ttl: {}", tokenUUID, tokenInfo, ttl); final BatchStatement batchStatement = new BatchStatement(); final Using usingTTL = QueryBuilder.ttl(ttl); tokenInfo.forEach((key, value) -> { ByteBuffer valueBuffer; if(key.equalsIgnoreCase(TOKEN_STATE)){ valueBuffer = toByteBuffer(value); }else{ valueBuffer = DataType.serializeValue(value, ProtocolVersion.NEWEST_SUPPORTED); } batchStatement.add( QueryBuilder.insertInto(TOKENS_TABLE) .value("key", DataType.serializeValue(tokenUUID, ProtocolVersion.NEWEST_SUPPORTED)) .value("column1", DataType.serializeValue(key, ProtocolVersion.NEWEST_SUPPORTED)) .value("value", valueBuffer) .using(usingTTL)); }); if(principalKeyBuffer != null){ batchStatement.add( QueryBuilder.insertInto(PRINCIPAL_TOKENS_TABLE) .value("key", principalKeyBuffer) .value("column1", DataType.serializeValue(tokenUUID, ProtocolVersion.NEWEST_SUPPORTED)) .value("value", ByteBuffer.wrap( new byte[] { 0 } )) .using(usingTTL)); } session.execute(batchStatement); }
Source:
public synchronized void flush() throws IOException { checkpoint(Checkpoint.MAX); }

Target:
public void flush() throws IOException { checkpoint(Checkpoint.MAX); }
Source:
public ExecutionResult execute(Project project) { setProject(project); IRepositoryService service = (IRepositoryService) GlobalServiceRegister.getDefault().getService(IRepositoryService.class); IProxyRepositoryFactory factory = service.getProxyRepositoryFactory(); ExecutionResult executeFinal = null; List<IRepositoryViewObject> list = new ArrayList<IRepositoryViewObject>(); try { for (ERepositoryObjectType curTyp : getAllTypes()) { if (curTyp != null && curTyp.isResourceItem()) { list.addAll(factory.getAll(project, curTyp, true, true)); } } if (list.isEmpty()) { return ExecutionResult.NOTHING_TO_DO; } for (IRepositoryViewObject object : list) { ExecutionResult execute = null; if ((object.getProperty().eResource() == null || object.getProperty().getItem().eResource() == null) && (object instanceof RepositoryObject)) { Property updatedProperty = factory.reload(object.getProperty()); ((RepositoryObject) object).setProperty(updatedProperty); } execute = this.migrateProjectSettings(project); if (execute == ExecutionResult.FAILURE) { return ExecutionResult.FAILURE; } Item item = object.getProperty().getItem(); execute = execute(item); unloadObject(object); if (execute == ExecutionResult.FAILURE) { executeFinal = ExecutionResult.FAILURE; } if (executeFinal != ExecutionResult.FAILURE) { executeFinal = execute; } } return executeFinal; } catch (PersistenceException e) { ExceptionHandler.process(e); return ExecutionResult.FAILURE; } }

Target:
public ExecutionResult execute(Project project) { ExecutionResult result = super.execute(project); if (result == ExecutionResult.FAILURE) { return result; } result = this.migrateProjectSettings(project); return result; }
Source:
public DoubleColumnSelector makeDoubleColumnSelector(String columnName) { DoubleColumnSelector existing = doubleColumnSelectorMap.get(columnName); if (existing != null) { return existing; } else { DoubleColumnSelector newSelector = delegate.makeDoubleColumnSelector(columnName); DoubleColumnSelector prev = doubleColumnSelectorMap.putIfAbsent( columnName, newSelector ); return prev != null ? prev : newSelector; } }

Target:
public DoubleColumnSelector makeDoubleColumnSelector(String columnName) { final DoubleColumnSelector existing = doubleColumnSelectorMap.get(columnName); if (existing != null) { return existing; } return doubleColumnSelectorMap.computeIfAbsent(columnName, delegate::makeDoubleColumnSelector); }
Source:
private String summary(String functionName, List<String> paramNames) { Deque<List<String>> paramLines = wrap(functionName, paramNames, 80); List<String> paramLinks = paramLines .stream() .map(params -> params .stream() .map(param -> String.format("<a href=\"#%s-%s\">%s</a>", functionName, param, param)) .collect(Collectors.joining(", "))) .collect(Collectors.toList()); return String.format( "%s(%s)", functionName, Joiner.on(String.format(",\n%s", Strings.repeat(" ", functionName != null ? functionName.length() + 1 : 0))) .join(paramLinks) ); }

Target:
private String summary(String functionName, List<String> paramNames) { List<List<String>> paramLines = wrap(functionName, paramNames, MAX_LINE_LENGTH); List<String> paramLinksLines = new ArrayList<>(); for (List<String> params : paramLines) { String paramLinksLine = params .stream() .map(param -> String.format("<a href=\"#%s-%s\">%s</a>", functionName, param, param)) .collect(Collectors.joining(", ")); paramLinksLines.add(paramLinksLine); } String paramList = Joiner .on(String.format(",\n%s", Strings.repeat(" ", functionName.length() + 1))) .join(paramLinksLines); return String.format("%s(%s)", functionName, paramList); }
Source:
public void testCreatePerson() { BufferedMockRequest mockRequest =new BufferedMockRequest(tester.getApplication(), tester.getHttpSession(), tester.getServletContext(), "POST"); String jsonObj = gson.toJson(new PersonPojo("James", "Smith", "changeit")); mockRequest.setTextAsRequestBody(jsonObj); tester.setRequest(mockRequest); tester.executeUrl("./personsmanager/persons"); tester.getRequest().setMethod("GET"); tester.executeUrl("./personsmanager/persons"); assertTrue(tester.getLastResponseAsString().contains(jsonObj)); }

Target:
public void testCreatePerson() { BufferedMockRequest mockRequest =new BufferedMockRequest(tester.getApplication(), tester.getHttpSession(), tester.getServletContext(), "POST"); String jsonObj = gson.toJson(new PersonPojo("James", "Smith", "changeit")); mockRequest.setTextAsRequestBody(jsonObj); tester.setRequest(mockRequest); tester.executeUrl("./personsmanager/persons"); assertEquals(jsonObj, tester.getLastResponseAsString()); tester.getRequest().setMethod("GET"); tester.executeUrl("./personsmanager/persons"); assertTrue(tester.getLastResponseAsString().contains(jsonObj)); }
Source:
public void queries(@HttpQueryParameter("queries") String queries, EntityManager entityManager, ObjectResponse<World[]> response) { ThreadLocalRandom random = ThreadLocalRandom.current(); int count = getQueryCount(queries); World[] worlds = new World[count]; for (int i = 0; i < worlds.length; i++) { worlds[i] = entityManager.find(World.class, random.nextInt(1, 10000)); } response.send(worlds); }

Target:
public void queries(@HttpQueryParameter("queries") String queries, EntityManager entityManager, ObjectResponse<World[]> response) { ThreadLocalRandom random = ThreadLocalRandom.current(); int count = getQueryCount(queries); World[] worlds = new World[count]; for (int i = 0; i < worlds.length; i++) { worlds[i] = entityManager.find(World.class, random.nextInt(1, 10001)); } response.send(worlds); }
Source:
private void initEditMode(ChangeInfo info) { if (Gerrit.isSignedIn() && info.status().isOpen()) { RevisionInfo rev = info.revision(revision); if (isEditModeEnabled(info, rev)) { editMode.setVisible(fileTableMode == FileTable.Mode.REVIEW); addFile.setVisible(!editMode.isVisible()); reviewMode.setVisible(!editMode.isVisible()); addFileAction = new AddFileAction( changeId, info.revision(revision), style, addFile); } else { editMode.setVisible(false); addFile.setVisible(false); reviewMode.setVisible(false); } boolean hasEdit = info.has_edit() && info.current_revision().equals(info.edit().name()); reply.setVisible(!hasEdit); quickApprove.setVisible(!hasEdit); if (hasEdit) { NativeMap<ActionInfo> actions = info.edit().has_actions() ? info.edit().actions() : NativeMap.<ActionInfo> create(); actions.copyKeysIntoChildren("id"); if (actions.containsKey("publish")) { publishEdit.setVisible(true); publishEdit.setTitle(actions.get("publish").title()); } if (actions.containsKey("/")) { deleteEdit.setVisible(true); deleteEdit.setTitle(actions.get("/").title()); } } } }

Target:
private void initEditMode(ChangeInfo info) { if (Gerrit.isSignedIn() && info.status().isOpen()) { RevisionInfo rev = info.revision(revision); if (isEditModeEnabled(info, rev)) { editMode.setVisible(fileTableMode == FileTable.Mode.REVIEW); addFile.setVisible(!editMode.isVisible()); reviewMode.setVisible(!editMode.isVisible()); addFileAction = new AddFileAction( changeId, info.revision(revision), style, addFile); } else { editMode.setVisible(false); addFile.setVisible(false); reviewMode.setVisible(false); } if (rev.is_edit()) { reply.setVisible(false); quickApprove.setVisible(false); NativeMap<ActionInfo> actions = info.edit().has_actions() ? info.edit().actions() : NativeMap.<ActionInfo> create(); actions.copyKeysIntoChildren("id"); if (actions.containsKey("publish")) { publishEdit.setVisible(true); publishEdit.setTitle(actions.get("publish").title()); } if (actions.containsKey("/")) { deleteEdit.setVisible(true); deleteEdit.setTitle(actions.get("/").title()); } } } }
Source:
public static void checkExisting(Datastream datastream) { checkNew(datastream); Objects.requireNonNull(datastream.getDestination(), "invalid datastream destination"); Objects.requireNonNull(datastream.getDestination().getConnectionString(), "invalid destination connection"); Objects.requireNonNull(datastream.getDestination().getPartitions(), "invalid destination partitions"); if (datastream.getDestination().getPartitions() <= 0) { throw new IllegalArgumentException("invalid Kafka topic partition count."); } }

Target:
public static void checkExisting(Datastream datastream) { checkNew(datastream); Objects.requireNonNull(datastream.getDestination(), "invalid datastream destination"); Objects.requireNonNull(datastream.getDestination().getConnectionString(), "invalid destination connection"); Objects.requireNonNull(datastream.getDestination().getPartitions(), "invalid destination partitions"); if (datastream.getDestination().getPartitions() <= 0) { throw new IllegalArgumentException("invalid destination partition count."); } }
Source:
URL getDatasetsUrl(String projectId, String datasetName, boolean fetchResults, Map<String, ?> queryParams) throws KeenQueryClientException { try { StringBuilder url = new StringBuilder(String.format(Locale.US, "%s/%s/projects/%s/%s", this.baseUrl, this.apiVersion, projectId, KeenQueryConstants.DATASETS )); if (datasetName != null) { url.append("/").append(datasetName); if (fetchResults) { url.append("/results"); } } if (queryParams != null && !queryParams.isEmpty()) { StringBuilder query = new StringBuilder(); for (Map.Entry<String, ?> entry : queryParams.entrySet()) { query.append(String.format("%s=", URLEncoder.encode(entry.getKey(), "UTF-8"))); query.append(String.format("%s&", URLEncoder.encode(entry.getValue().toString(), "UTF-8"))); } url.append("?").append(query.toString().replaceFirst("&$", "")); } return new URL(url.toString()); } catch (IOException ex) { Logger.getLogger(RequestUrlBuilder.class.getName()) .log(Level.SEVERE, "Failed to format dataset URL.", ex); throw new KeenQueryClientException("Failed to format dataset URL.", ex); } }

Target:
URL getDatasetsUrl(String projectId, String datasetName, boolean fetchResults, Map<String, ?> queryParams) throws KeenQueryClientException { try { StringBuilder url = createBaseDatasetsUrl(projectId); if (datasetName != null) { appendDatasetName(url, datasetName); if (fetchResults) { appendFetchResults(url); } } if (queryParams != null && !queryParams.isEmpty()) { appendQueryParams(url, queryParams); } return new URL(url.toString()); } catch (IOException ex) { Logger.getLogger(RequestUrlBuilder.class.getName()) .log(Level.SEVERE, "Failed to format dataset URL.", ex); throw new KeenQueryClientException("Failed to format dataset URL.", ex); } }
Source:
public Object execute(JobExecutionContext context) throws JobExecutionException { try { final JobArguments arguments = context.getJobArguments(); final String ownerKey = arguments.getAsString(OWNER_KEY); Owner owner = ownerCurator.getByKey(ownerKey); if (owner.isAutobindDisabled() || owner.isContentAccessEnabled()) { String caMessage = owner.isContentAccessEnabled() ? " because of the content access mode setting" : ""; throw new BadRequestException( i18n.tr("Auto-attach is disabled for owner {0}{1}.", owner.getKey(), caMessage)); } final Date entitleDate = arguments.getAs(ENTITLE_DATE_KEY, Date.class); final StringBuilder result = new StringBuilder(); for (String uuid : ownerCurator.getConsumerUuids(owner).list()) { try { Consumer consumer = consumerCurator.getConsumer(uuid); healSingleConsumer(consumer, owner, entitleDate); result.append("Healing event sent for consumer: ").append(uuid).append("\n"); } catch (Exception e) { log.debug("Healing failed for UUID \"{}\" with message: {}", uuid, e.getMessage()); result.append("Healing failed for UUID: ").append(uuid).append("\n"); } } return result; } catch (Exception e) { log.error("EntitlerJob encountered a problem.", e); throw new JobExecutionException(e.getMessage(), e, false); } }

Target:
public Object execute(JobExecutionContext context) throws JobExecutionException { try { final JobArguments arguments = context.getJobArguments(); final String ownerKey = arguments.getAsString(OWNER_KEY); Owner owner = ownerCurator.getByKey(ownerKey); if (owner.isAutobindDisabled() || owner.isContentAccessEnabled()) { String caMessage = owner.isContentAccessEnabled() ? " because of the content access mode setting" : ""; throw new BadRequestException( i18n.tr("Auto-attach is disabled for owner {0}{1}.", owner.getKey(), caMessage)); } final Date entitleDate = arguments.getAs(ENTITLE_DATE_KEY, Date.class); final StringBuilder result = new StringBuilder(); for (String uuid : ownerCurator.getConsumerUuids(owner).list()) { try { Consumer consumer = consumerCurator.getConsumer(uuid); healSingleConsumer(consumer, owner, entitleDate); result.append("Successfully healed consumer with UUID: ").append(uuid).append("\n"); } catch (Exception e) { log.debug("Healing failed for UUID \"{}\" with message: {}", uuid, e.getMessage()); result.append("Healing failed for UUID: ").append(uuid).append("\n"); } } return result; } catch (Exception e) { log.error("HealEntireOrgJob encountered a problem.", e); throw new JobExecutionException(e.getMessage(), e, false); } }
Source:
public void testNXQuery() throws ErrnoException { for (Network network : getTestableNetworks()) { CountDownLatch latch = new CountDownLatch(1); final int TIMEOUT_MS = 12_000; final String dname = "test1-nx.metric.gstatic.com"; mDns.query(network, dname, FLAG_NO_CACHE_LOOKUP, mHandler, answerList -> { if (answerList.size() == 0) { latch.countDown(); } } ); String msg = "InetAddress query " + dname + " got unexpected answer"; try { assertTrue(msg, latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS)); } catch (InterruptedException e) { } } }

Target:
public void testNXQuery() throws ErrnoException { for (Network network : getTestableNetworks()) { CountDownLatch latch = new CountDownLatch(1); final int TIMEOUT_MS = 12_000; final String dname = "test1-nx.metric.gstatic.com"; String msg = "InetAddress query " + dname; mDns.query(network, dname, FLAG_NO_CACHE_LOOKUP, mHandler, answerList -> { if (answerList.size() == 0) { latch.countDown(); return; } fail(msg + " but get valid answers"); } ); try { assertTrue(msg + " but no answer after " + TIMEOUT_MS + "ms.", latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS)); } catch (InterruptedException e) { } } }
Source:
public AggStats build(){ checkNotNull(accountId, "accountId cannot be null"); checkNotNull(dateLocal, "dateLocal cannot be null"); checkNotNull(externalDeviceId, "externalDeviceId cannot be null"); return new AggStats( this.accountId, this.dateLocal, this.externalDeviceId, this.deviceDataLength, this.trackerMotionLength, this.avgDailyTemp, this.maxDailyTemp, this.minDailyTemp, this.avgDailyHumidity, this.avgDailyDustDensity, this.sumLengthMicroLuxHourMap); }

Target:
public AggStats build(){ checkNotNull(accountId, "accountId cannot be null"); checkNotNull(dateLocal, "dateLocal cannot be null"); checkNotNull(externalDeviceId, "externalDeviceId cannot be null"); return new AggStats( this.accountId, this.dateLocal, this.externalDeviceId, this.deviceDataCount, this.trackerMotionCount, this.avgDailyTemp, this.maxDailyTemp, this.minDailyTemp, this.avgDailyHumidity, this.avgDailyDustDensity, this.sumCountMicroLuxHourMap); }
Source:
public int findAndSelect(int widgetOffset, String findString, boolean searchForward, boolean caseSensitive, boolean wholeWord) { int matchIndex = 0; String searchString = text.getText(); if (widgetOffset < 0) { widgetOffset = searchForward ? 0 : searchString.length(); } if (!caseSensitive) { searchString = searchString.toLowerCase(); findString = findString.toLowerCase(); } if (searchForward) { matchIndex = searchString.indexOf(findString, widgetOffset); } else { matchIndex = searchString.lastIndexOf(findString, widgetOffset); } if (matchIndex != -1) { text.setSelection(matchIndex, matchIndex + findString.length()); } return matchIndex; }

Target:
public int findAndSelect(int widgetOffset, String findString, boolean searchForward, boolean caseSensitive, boolean wholeWord) { int matchIndex = -1; String searchString = text.getText(); String findRegex = findString; if (widgetOffset < 0) { widgetOffset = searchForward ? 0 : searchString.length(); } if (wholeWord) { findRegex = WORD_BOUNDARY + findRegex + WORD_BOUNDARY; } int caseFlag = caseSensitive ? 0 : Pattern.CASE_INSENSITIVE; Pattern pattern = Pattern.compile(findRegex, caseFlag); Matcher matcher = pattern.matcher(searchString); if (searchForward) { matchIndex = matcher.find(widgetOffset) ? matcher.start() : -1; } else { matcher.region(0, widgetOffset); while (matcher.find()) { matchIndex = matcher.start(); } } if (matchIndex != -1) { text.setSelection(matchIndex, matchIndex + findString.length()); } return matchIndex; }
Source:
private void push(Path location) { String remoteBranch = view.getRemoteBranch(); String remote = remoteBranch.split("/")[0]; String branch = remoteBranch.split("/")[1]; service .push(location, singletonList(branch), remote, false) .then( result -> { notificationManager.notify(constant.pushSuccess(remote), SUCCESS, FLOAT_MODE); }) .catchError( error -> { final String providerName = GitUtil.getProviderNameFromError(error); if (!StringUtils.isNullOrEmpty(providerName)) { pushAuthenticated(location, branch, remote, providerName); return; } notificationManager.notify(constant.pushFail(), FAIL, FLOAT_MODE); }); }

Target:
private void push(Path location) { String remoteBranch = view.getRemoteBranch(); String remote = remoteBranch.split("/")[0]; String branch = remoteBranch.split("/")[1]; performOperationWithTokenRequestIfNeeded( new RemoteGitOperation<PushResponse>() { @Override public Promise<PushResponse> perform(Credentials credentials) { return service.push(location, singletonList(branch), remote, false, credentials); } }) .then( result -> { notificationManager.notify(locale.pushSuccess(remote), SUCCESS, FLOAT_MODE); }) .catchError( error -> { notificationManager.notify(locale.pushFail(), FAIL, FLOAT_MODE); }); }
Source:
public BranchMergeOperation exclude(Iterable<String> ids) { this.exclusions = Sets.newHashSet(ids); return this; }

Target:
public BranchMergeOperation exclude(Iterable<String> ids) { this.exclusions = ImmutableSet.copyOf(ids); return this; }
Source:
public static void input(MethodHandle methodHandle, NullableDoubleState state, double value) { if (state.isNull()) { state.setNull(false); state.setDouble(value); return; } try { if ((boolean) methodHandle.invokeExact(value, state.getDouble())) { state.setDouble(value); } } catch (Throwable t) { throwIfInstanceOf(t, Error.class); throwIfInstanceOf(t, PrestoException.class); throw new PrestoException(GENERIC_INTERNAL_ERROR, t); } }

Target:
public static void input(MethodHandle methodHandle, NullableDoubleState state, double value) { if (state.isNull()) { state.setNull(false); state.setDouble(value); return; } try { if ((boolean) methodHandle.invokeExact(value, state.getDouble())) { state.setDouble(value); } } catch (Throwable t) { throw internalError(t); } }
Source:
@Override public ServiceContextImpl serviceContext(String name) { if (!enterBusy()) return null; try { Collection<ServiceContextImpl> ctxs = serviceContexts(name); if (F.isEmpty(ctxs)) return null; synchronized (ctxs) { for (ServiceContextImpl ctx : ctxs) { if (ctx.service() != null) return ctx; } } return null; } finally { leaveBusy(); } }

Target:
@Override public ServiceContextImpl serviceContext(String name) { if (!enterBusy()) return null; try { Collection<ServiceContextImpl> ctxs = serviceContexts(name); if (ctxs == null) return null; synchronized (ctxs) { if (F.isEmpty(ctxs)) return null; for (ServiceContextImpl ctx : ctxs) { if (ctx.service() != null) return ctx; } } return null; } finally { leaveBusy(); } }
Source:
public RiakHll extractDatatype(RiakDatatype element) { return element.getAsHLL(); }

Target:
public RiakHll extractDatatype(RiakDatatype element) { return element.getAsHll(); }
Source:
public void onEvent(CacheEvent<K, V> event) { ExecutorService executor; if (storeEventSource.isEventOrdering()) { executor= orderedExecutor; } else { executor = unOrderedExectuor; } Future<?> future = null; if (!syncListenersList.isEmpty()) { future = executor.submit(new EventDispatchTask<K, V>(event, syncListenersList)); } if (!aSyncListenersList.isEmpty()) { executor.submit(new EventDispatchTask<K, V>(event, aSyncListenersList)); } if (future != null) { try { future.get(); } catch (Exception e) { LOGGER.error("Cache Event Listener failed for event type due to ", event.getType(), e); } } }

Target:
public void onEvent(CacheEvent<K, V> event) { ExecutorService executor; if (storeEventSource.isEventOrdering()) { executor= orderedExecutor; } else { executor = unOrderedExectuor; } if (!aSyncListenersList.isEmpty()) { executor.submit(new EventDispatchTask<K, V>(event, aSyncListenersList)); } if (!syncListenersList.isEmpty()) { Future<?> future = executor.submit(new EventDispatchTask<K, V>(event, syncListenersList)); try { future.get(); } catch (Exception e) { LOGGER.error("Exception received as result from synchronous listeners", e); } } }
Source:
public void process(GeneratingRegion region) { SurfaceHeightFacet facet = region.getRegionFacet(SurfaceHeightFacet.class); PlayAreaFacet playAreaFacet = region.getRegionFacet(PlayAreaFacet.class); float mountainHeight = 40; float hillHeight = 10; Rect2i processRegion = facet.getWorldRegion(); for (BaseVector2i position : processRegion.contents()) { float additiveMountainHeight = mountainNoise.noise(position.x(), position.y()) * mountainHeight; additiveMountainHeight = TeraMath.clamp(additiveMountainHeight, 0, mountainHeight); if (!playAreaFacet.getWorld((Vector2i) position)) { facet.setWorld(position, facet.getWorld(position) + additiveMountainHeight + 10); } } }

Target:
public void process(GeneratingRegion region) { SurfaceHeightFacet facet = region.getRegionFacet(SurfaceHeightFacet.class); PlayAreaFacet playAreaFacet = region.getRegionFacet(PlayAreaFacet.class); float mountainHeight = 40; Rect2i processRegion = facet.getWorldRegion(); for (BaseVector2i position : processRegion.contents()) { float additiveMountainHeight = mountainNoise.noise(position.x(), position.y()) * mountainHeight; additiveMountainHeight = TeraMath.clamp(additiveMountainHeight, 0, mountainHeight); if (!playAreaFacet.getWorld((Vector2i) position)) { facet.setWorld(position, facet.getWorld(position) + additiveMountainHeight + 10); } } }
Source:
private static String toLuceneDateTime(Date date) { try { SimpleDateFormat df = new SimpleDateFormat(LUCENE_DATE_TIME_FORMAT); String returnValue = df.format(date); return returnValue; } catch (Exception ex) { Logger.error(ESContentFactoryImpl.class, ex.toString()); return ERROR_DATE; } }

Target:
private static String toLuceneDateTime(Date date) { try { String returnValue = LUCENE_DATE_TIME_FORMAT.format(date); return returnValue; } catch (Exception ex) { Logger.error(ESContentFactoryImpl.class, ex.toString()); return ERROR_DATE; } }
Source:
public Selector parseRawSelector(String selector) { if (tokenPattern.matcher(selector).matches()) { SelectorBuilder builder = createEmptyBuilder().type(SelectorTypes.valueOf(selector.substring(1, 2)).get()); String argString = selector.substring(selector.indexOf('[') + 1, selector.lastIndexOf(']')); for (String argument : argString.split(",")) { int index = argument.indexOf('='); builder.addArgument(argument.substring(0, index), argument.substring(index) + 1); } return builder.build(); } return null; }

Target:
public Selector parseRawSelector(String selector) { checkArgument(tokenPattern.matcher(selector).matches()); SelectorBuilder builder = createEmptyBuilder().type(SelectorTypes.valueOf(selector.substring(1, 2)).get()); setArguments(builder, selector.substring(selector.indexOf('[') + 1, selector.lastIndexOf(']'))); return builder.build(); }
Source:
public void isNotAuthorizedWithInvalidCredentials() throws Exception { assertThat(BASIC_AUTH.isAuthorized("Basic wrong:password")).isFalse(); }

Target:
public void isNotAuthorizedWithInvalidCredentials() throws Exception { assertThat(BASIC_AUTH.isAuthorized("Basic " + encode("username:wrong"))).isFalse(); }
Source:
public static <T> Merger<T> getMerger(Class<T> returnType) { if (returnType == null) { throw new IllegalArgumentException("returnType is null"); } Merger result; if (returnType.isArray()) { Class type = returnType.getComponentType(); result = mergerCache.get(type); if (result == null) { loadMergers(); result = mergerCache.get(type); } if (result == null && !type.isPrimitive()) { result = ArrayMerger.INSTANCE; } } else { result = mergerCache.get(returnType); if (result == null) { loadMergers(); result = mergerCache.get(returnType); } } if (result == null) { throw new IllegalArgumentException(returnType.getName() + " is not supported"); } return result; }

Target:
public static <T> Merger<T> getMerger(Class<T> returnType) { if (returnType == null) { throw new IllegalArgumentException("returnType is null"); } Merger result; if (returnType.isArray()) { Class type = returnType.getComponentType(); result = mergerCache.get(type); if (result == null) { loadMergers(); result = mergerCache.get(type); } if (result == null && !type.isPrimitive()) { result = ArrayMerger.INSTANCE; } } else { result = mergerCache.get(returnType); if (result == null) { loadMergers(); result = mergerCache.get(returnType); } } return result; }
Source:
public void highlightNode(JsonRpcPeer peer, JSONObject params) { HighlightNodeRequest request = mObjectMapper.convertValue(params, HighlightNodeRequest.class); if (request.nodeId != null) { Object element = getElementForNodeId(request.nodeId); mDOMProvider.highlightElement(element); } }

Target:
public void highlightNode(JsonRpcPeer peer, JSONObject params) { HighlightNodeRequest request = mObjectMapper.convertValue(params, HighlightNodeRequest.class); if (request.nodeId == null) { LogUtil.w("highlightNode was not given a nodeId; JS objectId is not supported"); } else { Object element = mObjectIdMapper.getObjectForId(request.nodeId); mDOMProvider.highlightElement( element, request.highlightConfig.contentColor.getColor(), request.highlightConfig.paddingColor.getColor(), request.highlightConfig.borderColor.getColor(), request.highlightConfig.marginColor.getColor()); } }
Source:
static <E> Gen<E> choose(E[] values) { if(values.length == 0) return Gen.fail("Emtpy array"); else return random -> Gen.choose(0, values.length - 1).map(i -> values[i]).apply(random); }

Target:
static <E> Gen<E> choose(E[] values) { Objects.requireNonNull(values, "values is null"); if(values.length == 0) return Gen.fail("Empty array"); else return random -> Gen.choose(0, values.length - 1).map(i -> values[i]).apply(random); }
Source:
public void start() { synchronized (stateChangeLock) { Preconditions.checkState(!started, "already started"); Preconditions.checkState(!exec.isShutdown(), "already stopped"); try { consumer = getKafkaConsumer(); exec.submit( new Runnable() { @Override public void run() { try { while (!Thread.currentThread().isInterrupted()) { final Notice notice = notices.take(); try { notice.handle(); } catch (Exception e) { log.makeAlert(e, "KafkaSupervisor[%s] failed to handle notice", dataSource) .addData("noticeClass", notice.getClass().getSimpleName()) .emit(); } } } catch (InterruptedException e) { log.info("KafkaSupervisor[%s] interrupted, exiting", dataSource); } } } ); } catch (Exception e) { consumer.close(); log.makeAlert(e, "Exception starting KafkaSupervisor[%s]", dataSource) .emit(); throw Throwables.propagate(e); } firstRunTime = DateTime.now().plus(ioConfig.getStartDelay()); scheduledExec.scheduleAtFixedRate( buildRunTask(), ioConfig.getStartDelay().getMillis(), Math.max(ioConfig.getPeriod().getMillis(), MAX_RUN_FREQUENCY_MILLIS), TimeUnit.MILLISECONDS ); started = true; log.info("Started KafkaSupervisor[%s], first run in [%s]", dataSource, ioConfig.getStartDelay()); } }

Target:
public void start() { synchronized (stateChangeLock) { Preconditions.checkState(!started, "already started"); Preconditions.checkState(!exec.isShutdown(), "already stopped"); try { consumer = getKafkaConsumer(); exec.submit( new Runnable() { @Override public void run() { try { while (!Thread.currentThread().isInterrupted()) { final Notice notice = notices.take(); try { notice.handle(); } catch (Exception e) { log.makeAlert(e, "KafkaSupervisor[%s] failed to handle notice", dataSource) .addData("noticeClass", notice.getClass().getSimpleName()) .emit(); } } } catch (InterruptedException e) { log.info("KafkaSupervisor[%s] interrupted, exiting", dataSource); } } } ); firstRunTime = DateTime.now().plus(ioConfig.getStartDelay()); scheduledExec.scheduleAtFixedRate( buildRunTask(), ioConfig.getStartDelay().getMillis(), Math.max(ioConfig.getPeriod().getMillis(), MAX_RUN_FREQUENCY_MILLIS), TimeUnit.MILLISECONDS ); started = true; log.info( "Started KafkaSupervisor[%s], first run in [%s], with spec: [%s]", dataSource, ioConfig.getStartDelay(), spec.toString() ); } catch (Exception e) { if (consumer != null) { consumer.close(); } log.makeAlert(e, "Exception starting KafkaSupervisor[%s]", dataSource) .emit(); throw Throwables.propagate(e); } } }
Source:
public void testAsyncBulkActionWithPP() throws IOException { Document root = (Document) session.newRequest(FetchDocument.ID).set("value", "/").execute(); Document folder = (Document) session.newRequest(CreateDocument.ID) .setInput(root) .set("type", "Folder") .set("name", "test") .execute(); Document file = (Document) session.newRequest(CreateDocument.ID) .setInput(folder) .set("type", "File") .set("name", "file") .execute(); HashMap<String, Serializable> automationParams = new HashMap<>(); automationParams.put("properties", "dc:title=foo"); HashMap<String, Serializable> actionParams = new HashMap<>(); actionParams.put(AutomationBulkAction.OPERATION_ID, "Document.Update"); actionParams.put(AutomationBulkAction.OPERATION_PARAMETERS, automationParams); Object r = async.newRequest(BulkRunAction.ID) .set("action", AutomationBulkAction.ACTION_NAME) .set("providerName", "PageProvider") .set("quickFilters", "FileOnly") .set("bucketSize", "10") .set("batchSize", "5") .set("parameters", (new ObjectMapper()).writeValueAsString(actionParams)) .execute(); assertNotNull(r); txFeature.nextTransaction(); folder = (Document) session.newRequest(FetchDocument.ID).set("value", "/test").execute(); file = (Document) session.newRequest(FetchDocument.ID).set("value", "/test/file").execute(); assertEquals("test", folder.getTitle()); assertEquals("foo", file.getTitle()); }

Target:
public void testAsyncBulkActionWithPP() throws IOException { Document root = (Document) session.newRequest(FetchDocument.ID).set("value", "/").execute(); Document folder = (Document) session.newRequest(CreateDocument.ID) .setInput(root) .set("type", "Folder") .set("name", "test") .execute(); Document file = (Document) session.newRequest(CreateDocument.ID) .setInput(folder) .set("type", "File") .set("name", "file") .execute(); Map<String, Serializable> automationParams = new HashMap<>(); automationParams.put("properties", "dc:title=foo"); Map<String, Serializable> actionParams = new HashMap<>(); actionParams.put(AutomationBulkAction.OPERATION_ID, "Document.Update"); actionParams.put(AutomationBulkAction.OPERATION_PARAMETERS, (Serializable) automationParams); Object r = async.newRequest(BulkRunAction.ID) .set("action", AutomationBulkAction.ACTION_NAME) .set("providerName", "PageProvider") .set("quickFilters", "FileOnly") .set("bucketSize", "10") .set("batchSize", "5") .set("parameters", (new ObjectMapper()).writeValueAsString(actionParams)) .execute(); assertNotNull(r); txFeature.nextTransaction(); folder = (Document) session.newRequest(FetchDocument.ID).set("value", "/test").execute(); file = (Document) session.newRequest(FetchDocument.ID).set("value", "/test/file").execute(); assertEquals("test", folder.getTitle()); assertEquals("foo", file.getTitle()); }
Source:
public JSON getPedigree(String id) { Family family = null; Patient patient = this.patientRepository.getPatientById(id); if (patient != null) { family = this.familyRepository.getFamilyForPatient(patient); } else { family = this.familyRepository.getFamilyById(id); } if (family != null) { Pedigree pedigree = family.getPedigree(); if (pedigree != null && !pedigree.isEmpty()) { return pedigree.getData(); } } return new JSONObject(true); }

Target:
public Pedigree getPedigree(String id) { Family family = null; Patient patient = this.patientRepository.getPatientById(id); if (patient != null) { if (!this.authorizationService.hasAccess(Right.VIEW, patient.getDocument())) { return null; } family = this.familyRepository.getFamilyForPatient(patient); } else { family = this.familyRepository.getFamilyById(id); } if (family != null) { if (!this.authorizationService.hasAccess(Right.VIEW, family.getDocumentReference())) { return null; } Pedigree pedigree = family.getPedigree(); if (pedigree != null && !pedigree.isEmpty()) { if (patient != null) { pedigree.highlightProband(patient); } return pedigree; } } return null; }