auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static File locateExecutable() throws IngestModule.IngestModuleException, IOException { File exeFile = null; Path execName = null; String photorec_linux_directory = "/usr/bin"; if (PlatformUtil.isWindowsOS()) { execName = Paths.get(PHOTOREC_DIRECTORY, PHOTOREC_EXECUTABLE); exeFile = InstalledFileLocator.getDefault().locate(execName.toString(), PhotoRecCarverFileIngestModule.class.getPackage().getName(), false); } else { File usrBin = new File("/usr/bin/photorec"); File usrLocalBin = new File("/usr/local/bin/photorec"); if (usrBin.canExecute() && usrBin.exists() && !usrBin.isDirectory()) { photorec_linux_directory = "/usr/bin"; }else if(usrLocalBin.canExecute() && usrLocalBin.exists() && !usrLocalBin.isDirectory()){ photorec_linux_directory = "/usr/local/bin"; }else{ exeFile = null; } execName = Paths.get(photorec_linux_directory, PHOTOREC_LINUX_EXECUTABLE); exeFile = new File(execName.toString()); } if (null == exeFile) { throw new IngestModule.IngestModuleException(Bundle.missingExecutable_message()); } if (!exeFile.canExecute()) { throw new IngestModule.IngestModuleException(Bundle.cannotRunExecutable_message()); } return exeFile; }

Target:
public static File locateExecutable() throws IngestModule.IngestModuleException { File exeFile = null; Path execName = null; String photorec_linux_directory = "/usr/bin"; if (PlatformUtil.isWindowsOS()) { execName = Paths.get(PHOTOREC_DIRECTORY, PHOTOREC_EXECUTABLE); exeFile = InstalledFileLocator.getDefault().locate(execName.toString(), PhotoRecCarverFileIngestModule.class.getPackage().getName(), false); } else { File usrBin = new File("/usr/bin/photorec"); File usrLocalBin = new File("/usr/local/bin/photorec"); if (usrBin.canExecute() && usrBin.exists() && !usrBin.isDirectory()) { photorec_linux_directory = "/usr/bin"; }else if(usrLocalBin.canExecute() && usrLocalBin.exists() && !usrLocalBin.isDirectory()){ photorec_linux_directory = "/usr/local/bin"; }else{ throw new IngestModule.IngestModuleException("Photorec not found"); } execName = Paths.get(photorec_linux_directory, PHOTOREC_LINUX_EXECUTABLE); exeFile = new File(execName.toString()); } if (null == exeFile) { throw new IngestModule.IngestModuleException(Bundle.missingExecutable_message()); } if (!exeFile.canExecute()) { throw new IngestModule.IngestModuleException(Bundle.cannotRunExecutable_message()); } return exeFile; }
Source:
protected void addShards() { MongoDBRouter router = getParent().getAttribute(MongoDBShardedDeployment.ROUTER_CLUSTER).getAttribute(MongoDBRouterCluster.ANY_ROUTER); if (router == null) return; MongoDBClientSupport client; try { client = MongoDBClientSupport.forServer(router); } catch (UnknownHostException e) { throw Exceptions.propagate(e); } for (Entity member : this.getMembers()) { if (member.getAttribute(Startable.SERVICE_UP) && !addedMembers.contains(member)) { MongoDBServer primary = null; primary = member.getAttribute(MongoDBReplicaSet.PRIMARY_ENTITY); String replicaSetURL = ((MongoDBReplicaSet) member).getName() + "/" + Strings.removeFromStart(primary.getAttribute(MongoDBServer.MONGO_SERVER_ENDPOINT), "http://"); LOG.info("Using to add shard URL {}...", router, replicaSetURL); client.addShardToRouter(replicaSetURL); addedMembers.add(member); } } }

Target:
protected void addShards() { MongoDBRouter router = getParent().getAttribute(MongoDBShardedDeployment.ROUTER_CLUSTER).getAttribute(MongoDBRouterCluster.ANY_RUNNING_ROUTER); if (router == null) return; MongoDBClientSupport client; try { client = MongoDBClientSupport.forServer(router); } catch (UnknownHostException e) { throw Exceptions.propagate(e); } for (Entity member : this.getMembers()) { if (member.getAttribute(Startable.SERVICE_UP) && !addedMembers.contains(member)) { MongoDBServer primary = member.getAttribute(MongoDBReplicaSet.PRIMARY_ENTITY); String addr = Strings.removeFromStart(primary.getAttribute(MongoDBServer.MONGO_SERVER_ENDPOINT), "http://"); String replicaSetURL = ((MongoDBReplicaSet) member).getName() + "/" + addr; LOG.info("Using to add shard URL {}...", router, replicaSetURL); client.addShardToRouter(replicaSetURL); addedMembers.add(member); } } }
Source:
public void write(DataOutput out) throws IOException { out.writeFloat(this.l2reg); out.writeInt(this.in); out.writeInt(this.out); if(this.serializationType == SerializationType.WEIGHTS || this.serializationType == SerializationType.MODEL_SPEC) { SerializationUtil.write2DimFloatArray(out, this.weights, this.in, this.out); SerializationUtil.writeFloatArray(out, this.bias, this.out); } else if(this.serializationType == SerializationType.GRADIENTS) { SerializationUtil.write2DimFloatArray(out, this.wGrads, this.in, this.out); SerializationUtil.writeFloatArray(out, this.bGrads, this.out); } }

Target:
public void write(DataOutput out) throws IOException { out.writeFloat(this.l2reg); out.writeInt(this.in); out.writeInt(this.out); switch(this.serializationType) { case WEIGHTS: case MODEL_SPEC: SerializationUtil.write2DimFloatArray(out, this.weights, this.in, this.out); SerializationUtil.writeFloatArray(out, this.bias, this.out); break; case GRADIENTS: SerializationUtil.write2DimFloatArray(out, this.wGrads, this.in, this.out); SerializationUtil.writeFloatArray(out, this.bGrads, this.out); break; default: break; } }
Source:
public void testFailureOnAllPollThatSends() throws Exception { router = getNonBlockingRouter(); setOperationParams(chunkSize); String blobId = router.putBlob(putBlobProperties, putUserMetadata, putChannel).get(); try { mockSelectorState.set(MockSelectorState.ThrowExceptionOnSend); router.getBlobInfo(blobId).get(); Assert.fail("operation should have thrown"); } catch (ExecutionException e) { RouterException routerException = (RouterException) e.getCause(); Assert.assertEquals("Exception received should be router closed error", routerException.getErrorCode(), RouterErrorCode.RouterClosed); } }

Target:
public void testFailureOnAllPollThatSends() throws Exception { router = getNonBlockingRouter(); setOperationParams(chunkSize); String blobId = router.putBlob(putBlobProperties, putUserMetadata, putChannel).get(); mockSelectorState.set(MockSelectorState.ThrowExceptionOnSend); try { router.getBlobInfo(blobId).get(); Assert.fail("operation should have thrown"); } catch (ExecutionException e) { RouterException routerException = (RouterException) e.getCause(); Assert.assertEquals("Exception received should be router closed error", RouterErrorCode.RouterClosed, routerException.getErrorCode()); } }
Source:
public Set<String> getGroupsSet(String user) throws IOException { return null; }

Target:
public Set<String> getGroupsSet(String user) throws IOException { if (user.equals("root")) { return Sets.newHashSet("admin"); } else if (user.equals("nobody")) { return Sets.newHashSet("nobody"); } else { String[] groups = HadoopUsersConfTestHelper.getHadoopUserGroups(user); return (groups != null) ? Sets.newHashSet(groups) : Collections.emptySet(); } }
Source:
public int executeMethod(HttpMethod method) throws IOException, HttpException { try { boolean customRedirectionNeeded = false; try { method.setFollowRedirects(mFollowRedirects); } catch (Exception e) { customRedirectionNeeded = mFollowRedirects; } HttpParams params = method.getParams(); params.setParameter(HttpMethodParams.USER_AGENT, mUserAgent); Log_OC.d(TAG + " #" + mInstanceNumber, "REQUEST " + method.getName() + " " + method.getPath()); int status = super.executeMethod(method); if (customRedirectionNeeded) { status = patchRedirection(status, method); } return status; } catch (IOException e) { Log_OC.d(TAG + " #" + mInstanceNumber, "Exception occurred", e); throw e; } }

Target:
public int executeMethod(HttpMethod method) throws IOException, HttpException { try { boolean customRedirectionNeeded = false; try { method.setFollowRedirects(mFollowRedirects); } catch (Exception e) { customRedirectionNeeded = mFollowRedirects; } HttpParams params = method.getParams(); String userAgent = OwnCloudClientManagerFactory.getUserAgent(); params.setParameter(HttpMethodParams.USER_AGENT, userAgent); Log_OC.d(TAG + " #" + mInstanceNumber, "REQUEST " + method.getName() + " " + method.getPath()); int status = super.executeMethod(method); if (customRedirectionNeeded) { status = patchRedirection(status, method); } return status; } catch (IOException e) { Log_OC.d(TAG + " #" + mInstanceNumber, "Exception occurred", e); throw e; } }
Source:
public Session findSession(String id) throws IOException { log.debug("Datastore manager is loading session: " + id); Session session = null; try { session = this.getStore().load(id); } catch (ClassNotFoundException ex) { log.warn("An error occurred during session deserialization" + ex); } return session; }

Target:
public Session findSession(String id) throws IOException { log.debug("Datastore manager is loading session: " + id); Session session = null; try { session = this.getStore().load(id); } catch (ClassNotFoundException ex) { log.warn("An error occurred during session deserialization", ex); } return session; }
Source:
public Query existsQuery(QueryShardContext context) { if (hasDocValues()) { return new DocValuesFieldExistsQuery(name()); } else if (omitNorms()) { return new TermQuery(new Term(FieldNamesFieldMapper.NAME, name())); } else { return new NormsFieldExistsQuery(name()); } }

Target:
public Query existsQuery(QueryShardContext context) { if (hasDocValues()) { return new DocValuesFieldExistsQuery(name()); } else { return new TermQuery(new Term(FieldNamesFieldMapper.NAME, name())); } }
Source:
public @Nullable Long getClusterRegionId() { return regionId; }

Target:
public long getClusterRegionId() { return clusterRegionId; }
Source:
private void testGetCoOwnersForCourse() { ______TS("Verify co-owner status of generated co-owners list"); String courseId = "idOfTypicalCourse1"; List<InstructorAttributes> generatedCoOwners = instructorsLogic.getCoOwnersForCourse(courseId); for (InstructorAttributes generatedCoOwner : generatedCoOwners) { assertTrue(generatedCoOwner.hasCoownerPrivileges()); } ______TS("Verify all co-owners present in generated co-owners list"); List<InstructorAttributes> instructors = instructorsLogic.getInstructorsForCourse(courseId); List<InstructorAttributes> coOwners = new ArrayList<InstructorAttributes>(); for (InstructorAttributes instructor : instructors) { if (!instructor.hasCoownerPrivileges()) { continue; } coOwners.add(instructor); } assertTrue(coOwners.toString().equals(generatedCoOwners.toString())); }

Target:
private void testGetCoOwnersForCourse() { ______TS("Verify co-owner status of generated co-owners list"); String courseId = "idOfTypicalCourse1"; List<InstructorAttributes> generatedCoOwners = instructorsLogic.getCoOwnersForCourse(courseId); for (InstructorAttributes generatedCoOwner : generatedCoOwners) { assertTrue(generatedCoOwner.hasCoownerPrivileges()); } ______TS("Verify all co-owners present in generated co-owners list"); List<String> coOwnersEmailsFromDataBundle = new ArrayList<String>(); for (InstructorAttributes instructor : new ArrayList<InstructorAttributes>(dataBundle.instructors.values())) { if (!(instructor.getCourseId().equals(courseId) && instructor.hasCoownerPrivileges())) { continue; } coOwnersEmailsFromDataBundle.add(instructor.email); } List<String> generatedCoOwnersEmails = new ArrayList<String>(); for (InstructorAttributes generatedCoOwner : generatedCoOwners) { generatedCoOwnersEmails.add(generatedCoOwner.email); } assertTrue(coOwnersEmailsFromDataBundle.containsAll(generatedCoOwnersEmails) && generatedCoOwnersEmails.containsAll(coOwnersEmailsFromDataBundle)); }
Source:
public static int clearTempModelFiles() { int deleteCount = 0; for (File c : AnkiDroidApp.getInstance().getCacheDir().listFiles()) { if (c.getAbsolutePath().endsWith("json") && c.getAbsolutePath().contains("editedTemplate")) { if (!c.delete()) { Timber.w("Unable to delete temp file %s", c.getAbsolutePath()); } else { deleteCount++; Timber.d("Deleted temp model file %s", c.getAbsolutePath()); } } } return deleteCount; }

Target:
public static int clearTempModelFiles() { int deleteCount = 0; for (File c : AnkiDroidApp.getInstance().getCacheDir().listFiles()) { String absolutePath = c.getAbsolutePath(); if (absolutePath.contains("editedTemplate") && absolutePath.endsWith("json") ) { if (!c.delete()) { Timber.w("Unable to delete temp file %s", c.getAbsolutePath()); } else { deleteCount++; Timber.d("Deleted temp model file %s", c.getAbsolutePath()); } } } return deleteCount; }
Source:
public Distributor getDistributor() { String clazz = config.get(DISTRIBUTOR_SECTION, "implementation").orElse(DEFAULT_DISTRIBUTOR_SERVER); LOG.info("Creating distributor server: " + clazz); try { Class<?> busClazz = Class.forName(clazz); Method create = busClazz.getMethod("create", Config.class); if (!Modifier.isStatic(create.getModifiers())) { throw new IllegalArgumentException(String.format( "Distributor class %s's `create(Config)` method must be static", clazz)); } if (!Distributor.class.isAssignableFrom(create.getReturnType())) { throw new IllegalArgumentException(String.format( "Distributor class %s's `create(Config)` method must return a Distributor", clazz)); } return (Distributor) create.invoke(null, config); } catch (NoSuchMethodException e) { throw new IllegalArgumentException(String.format( "Distributor class %s must have a static `create(Config)` method", clazz)); } catch (ReflectiveOperationException e) { throw new IllegalArgumentException("Unable to find event bus class: " + clazz, e); } }

Target:
public Distributor getDistributor() { String clazz = config.get(DISTRIBUTOR_SECTION, "implementation").orElse(DEFAULT_DISTRIBUTOR_SERVER); LOG.info("Creating distributor server: " + clazz); try { Class<?> distributorClazz = Class.forName(clazz); Method create = distributorClazz.getMethod("create", Config.class); if (!Modifier.isStatic(create.getModifiers())) { throw new IllegalArgumentException(String.format( "Distributor class %s's `create(Config)` method must be static", clazz)); } if (!Distributor.class.isAssignableFrom(create.getReturnType())) { throw new IllegalArgumentException(String.format( "Distributor class %s's `create(Config)` method must return a Distributor", clazz)); } return (Distributor) create.invoke(null, config); } catch (NoSuchMethodException e) { throw new IllegalArgumentException(String.format( "Distributor class %s must have a static `create(Config)` method", clazz)); } catch (ReflectiveOperationException e) { throw new IllegalArgumentException("Unable to find distributor class: " + clazz, e); } }
Source:
public Result get(final UUID id) { final Organization organization; try { organization = _organizationRepository.get(request()); } catch (final NoSuchElementException e) { return internalServerError(); } try { final Optional<Report> report = _reportRepository.getReport(id, organization); return report.map(r -> ok(Json.toJson(models.view.reports.Report.fromInternal(r)))) .orElseGet(ReportController::notFound); } catch (final PersistenceException e) { LOGGER.error() .setMessage("Get report failed") .setThrowable(e) .log(); return internalServerError(); } }

Target:
public Result get(final UUID id) { final Organization organization; try { organization = _organizationRepository.get(request()); } catch (final NoSuchElementException e) { return internalServerError(); } final Optional<Report> report = _reportRepository.getReport(id, organization); return report .map(r -> ok(Json.toJson(models.view.reports.Report.fromInternal(r)))) .orElseGet(ReportController::notFound); }
Source:
private void storeRerunData(BranchId branch, String destSetId, HashMap<String, String> reruns) { StringBuilder sb = new StringBuilder(); for (Entry<String, String> entry : reruns.entrySet()) { sb = sb.append(DispoStrings.SCRIPT_ENTRY); sb = sb.append(String.format(DispoStrings.SCRIPT_NAME, entry.getKey())); sb = sb.append(String.format(DispoStrings.SCRIPT_PATH, entry.getValue())); sb = sb.append(DispoStrings.IS_RUNNABLE); sb = sb.append(DispoStrings.SCRIPT_ENTRY_END); } DispoSetData dispoSetData = new DispoSetData(); dispoSetData.setTime(new Date().toString()); dispoSetData.setRerunList(DispoStrings.BATCH_RERUN_LIST + sb.toString() + DispoStrings.BATCH_RERUN_LIST_END); ArtifactReadable author = getQuery().findUser(); storageProvider.get().updateDispoSet(author, branch, destSetId, dispoSetData); }

Target:
private void storeRerunData(BranchId branch, String destSetId, HashMap<String, String> reruns) { StringBuilder sb = new StringBuilder(); for (Entry<String, String> entry : reruns.entrySet()) { sb = sb.append(DispoStrings.SCRIPT_ENTRY); sb = sb.append(String.format(DispoStrings.SCRIPT_NAME, entry.getKey())); sb = sb.append(String.format(DispoStrings.SCRIPT_PATH, entry.getValue())); sb = sb.append(DispoStrings.IS_RUNNABLE); sb = sb.append(DispoStrings.SCRIPT_ENTRY_END); } DispoSetData dispoSetData = new DispoSetData(); dispoSetData.setTime(new Date()); dispoSetData.setRerunList(DispoStrings.BATCH_RERUN_LIST + sb.toString() + DispoStrings.BATCH_RERUN_LIST_END); ArtifactReadable author = getQuery().findUser(); storageProvider.get().updateDispoSet(author, branch, destSetId, dispoSetData); }
Source:
public OutputPlugin( final Optional<Filter> filter, final Batching batching ) { this.filter = filter; this.batching = batching; if (filter == null) { throw new RuntimeException("filter can't be null"); } if (batching == null) { throw new RuntimeException("batching can't be null"); } }

Target:
public OutputPlugin( final Optional<Filter> filter, final Batching batching ) { this.filter = filter; this.batching = batching; }
Source:
public void testCurrentServer() throws Exception { String sqlText = "values current server"; String sqlTextAlt = "values current_server"; String expected = "1 |\n" + "----------\n" + "splicedb |"; ResultSet rs = methodWatcher.executeQuery(sqlText); assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toString(rs)); rs.close(); rs = methodWatcher.executeQuery(sqlTextAlt); assertEquals("\n" + sqlTextAlt + "\n", expected, TestUtils.FormattedResult.ResultFactory.toString(rs)); }

Target:
public void testCurrentServer() throws Exception { String sqlText = "values current server"; String sqlTextAlt = "values current_server"; String expected = "1 |\n" + "----------\n" + "splicedb |"; try (ResultSet rs = methodWatcher.executeQuery(sqlText)) { assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toString(rs)); } try (ResultSet rs = methodWatcher.executeQuery(sqlTextAlt)) { assertEquals("\n" + sqlTextAlt + "\n", expected, TestUtils.FormattedResult.ResultFactory.toString(rs)); } }
Source:
public void testMigratoinCannotBeSetWhenVMUsesScsiReservation() { prepareVmToPassCanDoAction(); VmDevice device = createVmDevice(); doReturn(vmDeviceDAO).when(command).getVmDeviceDao(); when(vmDeviceDAO.getVmDeviceByVmIdAndType(vm.getId(), VmDeviceGeneralType.DISK)).thenReturn(Arrays.asList(device)); vm.setMigrationSupport(MigrationSupport.MIGRATABLE); CanDoActionTestUtils.runAndAssertCanDoActionFailure(command, VdcBllMessages.MIGRATION_SUPPORT_NOT_VALID_WHEN_VM_USES_SCSI_RESERVATION); }

Target:
public void testMigratoinCannotBeSetWhenVMUsesScsiReservation() { prepareVmToPassCanDoAction(); vm.setMigrationSupport(MigrationSupport.MIGRATABLE); VmDevice device = createVmDevice(); mockVmDevice(device); mockVmValidator(); CanDoActionTestUtils.runAndAssertCanDoActionFailure(command, VdcBllMessages.MIGRATION_SUPPORT_NOT_VALID_WHEN_VM_USES_SCSI_RESERVATION); }
Source:
private void displaySearchResult(GeocodeResult geocodeResult) { if (mMapView.getCallout() != null && mMapView.getCallout().isShowing()) { mMapView.getCallout().dismiss(); } mMapView.getGraphicsOverlays().clear(); mGraphicsOverlay.getGraphics().clear(); Point resultPoint = geocodeResult.getDisplayLocation(); Graphic resultLocGraphic = new Graphic(resultPoint, geocodeResult.getAttributes(), mPinSourceSymbol); mGraphicsOverlay.getGraphics().add(resultLocGraphic); mMapView.setViewpointAsync(new Viewpoint(geocodeResult.getExtent()), 3); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); }

Target:
private void displaySearchResult(GeocodeResult geocodeResult) { if (mMapView.getCallout() != null && mMapView.getCallout().isShowing()) { mMapView.getCallout().dismiss(); } mMapView.getGraphicsOverlays().clear(); mGraphicsOverlay.getGraphics().clear(); Point resultPoint = geocodeResult.getDisplayLocation(); Graphic resultLocGraphic = new Graphic(resultPoint, geocodeResult.getAttributes(), mPinSourceSymbol); mGraphicsOverlay.getGraphics().add(resultLocGraphic); mMapView.setViewpointAsync(new Viewpoint(geocodeResult.getExtent()), 3); mMapView.getGraphicsOverlays().add(mGraphicsOverlay); showCallout(resultLocGraphic); }
Source:
private boolean skipOnMatrixChildren(AbstractBuild build) { return notifier.isMatrixProject(build) && !notifier.getMatrixTriggerMode().forChild; }

Target:
private boolean skipOnMatrixChildren(AbstractBuild build) { if (notifier.isMatrixRun(build)) { MatrixTriggerMode matrixTriggerMode = notifier.getMatrixTriggerMode(); return !(matrixTriggerMode != null && matrixTriggerMode.forChild); } return false; }
Source:
public void shouldPublishAvroAndConsumeJsonMessageWithTraceId() throws IOException{ byte[] avroMessage = new AvroUser("John Doe", 44, "black").asBytes(); String jsonMessage = "{\"name\":\"John Doe\",\"age\":44,\"favoriteColor\":\"black\"}"; String traceId = UUID.randomUUID().toString(); Topic topic = operations.buildTopic(topic() .withName("publishAvroConsumeJsonWithTraceId.topic") .withValidation(true) .withMessageSchema(user.getSchemaAsString()) .withContentType(AVRO).build() ); operations.createSubscription(topic, "subscription", HTTP_ENDPOINT_URL); remoteService.expectMessages(jsonMessage); WebTarget client = ClientBuilder.newClient().target(FRONTEND_URL).path("topics").path(topic.getQualifiedName()); Response response = client .request() .header("Trace-Id", traceId) .post(Entity.entity(avroMessage, MediaType.valueOf("avro/binary"))); assertThat(response).hasStatus(Response.Status.CREATED); assertThat(remoteService.waitAndGetLastRequest()).hasHeaderValue("Trace-Id", traceId); }

Target:
public void shouldPublishAvroAndConsumeJsonMessageWithTraceId() throws IOException{ String traceId = UUID.randomUUID().toString(); Topic topic = operations.buildTopic(topic() .withName("publishAvroConsumeJsonWithTraceId.topic") .withValidation(true) .withMessageSchema(user.getSchemaAsString()) .withContentType(AVRO).build() ); operations.createSubscription(topic, "subscription", HTTP_ENDPOINT_URL); remoteService.expectMessages(user.asJson()); WebTarget client = ClientBuilder.newClient().target(FRONTEND_URL).path("topics").path(topic.getQualifiedName()); Response response = client .request() .header("Trace-Id", traceId) .post(Entity.entity(user.asBytes(), MediaType.valueOf("avro/binary"))); assertThat(response).hasStatus(Response.Status.CREATED); assertThat(remoteService.waitAndGetLastRequest()).hasHeaderValue("Trace-Id", traceId); }
Source:
public AuthenticationResult createEscalatedAuthenticationResult() { return new AuthenticationResult(internalClientPrincipal, authorizerName, "kerberos", null); }

Target:
public AuthenticationResult createEscalatedAuthenticationResult() { return new AuthenticationResult(internalClientPrincipal, authorizerName, null, null); }
Source:
private Boolean performPush(StackOperation op, SessionFrame matchingFrame, boolean isNewFrame, boolean currentFramePushed, SessionFrame onDeck, EvaluationContext ec) { if (op.isOperationTriggered(ec)) { if (matchingFrame == null) { matchingFrame = onDeck; } for (StackFrameStep step : op.getStackFrameSteps()) { matchingFrame.pushStep(step.defineStep(ec)); } return pushNewFrame(matchingFrame, isNewFrame, currentFramePushed); } return null; }

Target:
private boolean performPush(StackOperation op, SessionFrame matchingFrame, boolean isNewFrame, boolean currentFramePushed, SessionFrame onDeck, EvaluationContext ec) { if (op.isOperationTriggered(ec)) { if (matchingFrame == null) { matchingFrame = onDeck; } for (StackFrameStep step : op.getStackFrameSteps()) { matchingFrame.pushStep(step.defineStep(ec)); } return pushNewFrame(matchingFrame, isNewFrame, currentFramePushed); } return currentFramePushed; }
Source:
public void cancel(Locality locality) { for (I id: this.expirationTracker.getTrackedIds()) { if (Thread.currentThread().isInterrupted()) break; if (!locality.isLocal(id)) { this.cancel(id); } } }

Target:
public void cancel(Locality locality) { for (I id: this.evictionFutures.keySet()) { if (Thread.currentThread().isInterrupted()) break; if (!locality.isLocal(id)) { this.cancel(id); } } }
Source:
private void setVmTicket() { Frontend.RunAction(VdcActionType.SetVmTicket, new SetVmTicketParameters(getEntity().getId(), null, TICKET_VALIDITY_SECONDS), new IFrontendActionAsyncCallback() { @Override public void Executed(FrontendActionAsyncResult result) { VdcReturnValueBase ticketReturnValue = result.getReturnValue(); if (ticketReturnValue != null && ticketReturnValue.getActionReturnValue() != null) { otp64 = (String) ticketReturnValue.getActionReturnValue(); if (StringHelper.isNullOrEmpty(getEntity().getDisplayIp()) || StringHelper.stringsEqual(getEntity().getDisplayIp(), "0")) { AsyncQuery _asyncQuery = new AsyncQuery(); _asyncQuery.setModel(this); _asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void OnSuccess(Object model, Object ReturnValue) { VncConsoleModel consoleModel = (VncConsoleModel) model; VncConsoleModel.this.host = (String) ((VdcQueryReturnValue) ReturnValue).getReturnValue(); consoleModel.setAndInvokeClient(); } }; Frontend.RunQuery(VdcQueryType.GetManagementInterfaceAddressByVmId, new IdQueryParameters(getEntity().getId()), _asyncQuery); } else { VncConsoleModel.this.host = getEntity().getDisplayIp(); setAndInvokeClient(); } } } }); }

Target:
private void setVmTicket() { Frontend.RunAction(VdcActionType.SetVmTicket, new SetVmTicketParameters(getEntity().getId(), null, TICKET_VALIDITY_SECONDS), new IFrontendActionAsyncCallback() { @Override public void executed(FrontendActionAsyncResult result) { VdcReturnValueBase ticketReturnValue = result.getReturnValue(); if (ticketReturnValue != null && ticketReturnValue.getActionReturnValue() != null) { otp64 = (String) ticketReturnValue.getActionReturnValue(); if (StringHelper.isNullOrEmpty(getEntity().getDisplayIp()) || StringHelper.stringsEqual(getEntity().getDisplayIp(), "0")) { AsyncQuery _asyncQuery = new AsyncQuery(); _asyncQuery.setModel(this); _asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object ReturnValue) { VncConsoleModel consoleModel = (VncConsoleModel) model; VncConsoleModel.this.host = (String) ((VdcQueryReturnValue) ReturnValue).getReturnValue(); consoleModel.setAndInvokeClient(); } }; Frontend.RunQuery(VdcQueryType.GetManagementInterfaceAddressByVmId, new IdQueryParameters(getEntity().getId()), _asyncQuery); } else { VncConsoleModel.this.host = getEntity().getDisplayIp(); setAndInvokeClient(); } } } }); }
Source:
private void doProvisionVcsSshConfig( List<SshPairImpl> vcsSshPairs, KubernetesEnvironment k8sEnv, String wsId) { StringBuilder sshConfigData = new StringBuilder(); for (SshPair sshPair : vcsSshPairs) { sshConfigData.append(buildConfig(sshPair.getName())); } String sshConfigMapName = SSH_CONFIG_MAP_NAME; Map<String, String> sshConfig = new HashMap<>(); sshConfig.put(SSH_CONFIG, sshConfigData.toString()); ConfigMap configMap = new ConfigMapBuilder() .withNewMetadata() .withName(sshConfigMapName) .endMetadata() .withData(sshConfig) .build(); k8sEnv.getConfigMaps().put(configMap.getMetadata().getName(), configMap); k8sEnv .getPodsData() .values() .forEach( p -> mountConfigFile(p.getSpec(), sshConfigMapName, p.getRole() != PodRole.INJECTABLE)); }

Target:
private void doProvisionVcsSshConfig( List<SshPairImpl> vcsSshPairs, KubernetesEnvironment k8sEnv, String wsId) { StringBuilder sshConfigData = new StringBuilder(); for (SshPair sshPair : vcsSshPairs) { sshConfigData.append(buildConfig(sshPair.getName())); } Map<String, String> sshConfig = new HashMap<>(); sshConfig.put(SSH_CONFIG, sshConfigData.toString()); ConfigMap configMap = new ConfigMapBuilder() .withNewMetadata() .withName(SSH_CONFIG_MAP_NAME) .endMetadata() .withData(sshConfig) .build(); k8sEnv.getConfigMaps().put(configMap.getMetadata().getName(), configMap); k8sEnv .getPodsData() .values() .forEach( p -> mountConfigFile( p.getSpec(), SSH_CONFIG_MAP_NAME, p.getRole() != PodRole.INJECTABLE)); }
Source:
public static ClientConfiguration toClientConf(AccumuloConfiguration conf) { ClientConfiguration clientConf = ClientConfiguration.create(); final String serverPrincipal = conf.get(Property.GENERAL_KERBEROS_PRINCIPAL); final KerberosName krbName; try { krbName = new KerberosName(serverPrincipal); clientConf.setProperty(ClientConfiguration.ClientProperty.KERBEROS_SERVER_PRIMARY, krbName.getServiceName()); } catch (Exception e) { } HashSet<String> clientKeys = new HashSet<>(); for (ClientConfiguration.ClientProperty prop : ClientConfiguration.ClientProperty.values()) { clientKeys.add(prop.getKey()); } String key; for (Map.Entry<String,String> entry : conf) { key = entry.getKey(); if (clientKeys.contains(key)) { clientConf.setProperty(key, entry.getValue()); } } return clientConf; }

Target:
public static ClientConfiguration toClientConf(AccumuloConfiguration conf) { ClientConfiguration clientConf = ClientConfiguration.create(); final String serverPrincipal = conf.get(Property.GENERAL_KERBEROS_PRINCIPAL); final KerberosName krbName; if (serverPrincipal != null && !serverPrincipal.isEmpty()) { krbName = new KerberosName(serverPrincipal); clientConf.setProperty(KERBEROS_SERVER_PRIMARY, krbName.getServiceName()); } HashSet<String> clientKeys = new HashSet<>(); for (ClientConfiguration.ClientProperty prop : ClientConfiguration.ClientProperty.values()) { clientKeys.add(prop.getKey()); } String key; for (Map.Entry<String,String> entry : conf) { key = entry.getKey(); if (clientKeys.contains(key)) { clientConf.setProperty(key, entry.getValue()); } } return clientConf; }
Source:
public File getResource(String path) { if (path == null) { return null; } final String configurationDirectory = FilenameUtils .concat(OpenmrsUtil.getApplicationDataDirectory(), "configuration"); final File resourceFile; final File file = new File(path); if (file.isAbsolute()) { resourceFile = file; } else { resourceFile = new File(configurationDirectory, path); } try { if (!resourceFile.getCanonicalPath().startsWith(configurationDirectory)) { log.warn("Attempted to load invalid resource: {}", file); return null; } } catch (IOException e) { log.error("Error occurred while trying to load file: {}", path, e); return null; } return resourceFile.exists() ? resourceFile : null; }

Target:
public File getResource(String path) { if (path == null) { return null; } final String configurationDirectory; try { configurationDirectory = OpenmrsUtil.getDirectoryInApplicationDataDirectory("configuration") .getCanonicalPath(); } catch (IOException e) { throw new APIException("Could not determine canonical path for configuration directory", e); } final File resourceFile; final File file = new File(path); if (file.isAbsolute()) { resourceFile = file; } else { resourceFile = new File(configurationDirectory, path); } try { if (!resourceFile.getCanonicalPath().startsWith(configurationDirectory)) { log.warn("Attempted to load invalid resource: {}", file); return null; } } catch (IOException e) { log.error("Error occurred while trying to load file: {}", path, e); return null; } return resourceFile.exists() ? resourceFile : null; }
Source:
public void onUpdate() { superUpdate(); if(ticksExisted >= effectThreshhold) Botania.proxy.sparkleFX(worldObj, posX, posY, posZ, 0.3F, 0.09F, 1F, 4F, 1, true); if(ticksExisted >= length) this.setDead(); ticksExisted++; }

Target:
public void onUpdate() { superUpdate(); if(ticksExisted >= effectThreshhold && worldObj.isRemote) Botania.proxy.wispFX(worldObj, posX, posY, posZ, 0.3F, 0.09F, 1F, 1F, -0.1F, 0.18F); if(ticksExisted >= length) this.setDead(); ticksExisted++; if (!isDead) onUpdate(); }
Source:
public void waitForReady() throws InterruptedException { Thread t = Thread.currentThread(); String oldName = t.getName(); try { int retries = 0; while (true) { Thread.sleep(1000 * 10); try { URL url = toAgentListenerURL(first(jenkinsUrls)); retries++; t.setName(oldName + ": trying " + url + " for " + retries + " times"); HttpURLConnection con = (HttpURLConnection) openURLConnection(url, credentials, proxyCredentials, sslSocketFactory); con.setConnectTimeout(5000); con.setReadTimeout(5000); con.connect(); if (con.getResponseCode() == 200) { return; } LOGGER.info("Master isn't ready to talk to us. Will retry again: response code=" + con .getResponseCode()); } catch (IOException e) { LOGGER.log(INFO, "Failed to connect to the master. Will retry again", e); } } } finally { t.setName(oldName); } }

Target:
public void waitForReady() throws InterruptedException { Thread t = Thread.currentThread(); String oldName = t.getName(); try { int retries = 0; while (true) { Thread.sleep(1000 * 10); try { URL url = toAgentListenerURL(first(jenkinsUrls)); if (url == null) { return; } retries++; t.setName(oldName + ": trying " + url + " for " + retries + " times"); HttpURLConnection con = (HttpURLConnection) openURLConnection(url, credentials, proxyCredentials, sslSocketFactory); con.setConnectTimeout(5000); con.setReadTimeout(5000); con.connect(); if (con.getResponseCode() == 200) { return; } LOGGER.log(Level.INFO, "Master isn't ready to talk to us on {0}. Will retry again: response code={1}", new Object[]{url, con.getResponseCode()}); } catch (IOException e) { LOGGER.log(INFO, "Failed to connect to the master. Will retry again", e); } } } finally { t.setName(oldName); } }
Source:
public void afterPropertiesSet() { this.faWindowTitle = clientProperties.getForgedAlliance().getWindowTitle(); eventBus.register(this); }

Target:
public void afterPropertiesSet() { eventBus.register(this); }
Source:
public TmfModelResponse<ITmfXyModel> fetchXY(TimeQueryFilter filter, @Nullable IProgressMonitor monitor) { List<P> providers = getProviders(); boolean allCommon = Iterables.all(providers, p -> p instanceof ITmfCommonXAxisModel); if (allCommon) { return getCommonXResponse(filter, monitor, providers); } return getXyResponse(filter, monitor, providers); }

Target:
public TmfModelResponse<ITmfXyModel> fetchXY(TimeQueryFilter filter, @Nullable IProgressMonitor monitor) { List<P> providers = getProviders(); boolean allCommon = Iterables.all(providers, ITmfCommonXAxisModel.class::isInstance); if (allCommon) { return getCommonXResponse(filter, monitor, providers); } return getXyResponse(filter, monitor, providers); }
Source:
public ExtendedInMemoryUserDetailsManager myUserDetailsService() { ExtendedInMemoryUserDetailsManager extendedInMemoryUserDetailsManager = new ExtendedInMemoryUserDetailsManager(); List<GrantedAuthority> salaboyAuthorities = new ArrayList<>(); salaboyAuthorities.add(new SimpleGrantedAuthority("ROLE_ACTIVITI_USER")); salaboyAuthorities.add(new SimpleGrantedAuthority("GROUP_activitiTeam")); extendedInMemoryUserDetailsManager.createUser(new User("salaboy", "password", salaboyAuthorities)); List<GrantedAuthority> adminAuthorities = new ArrayList<>(); adminAuthorities.add(new SimpleGrantedAuthority("ROLE_ACTIVITI_ADMIN")); extendedInMemoryUserDetailsManager.createUser(new User("admin", "password", adminAuthorities)); List<GrantedAuthority> garthAuthorities = new ArrayList<>(); garthAuthorities.add(new SimpleGrantedAuthority("ROLE_ACTIVITI_USER")); garthAuthorities.add(new SimpleGrantedAuthority("GROUP_doctor")); extendedInMemoryUserDetailsManager.createUser(new User("garth", "password", garthAuthorities)); return extendedInMemoryUserDetailsManager; }

Target:
public UserDetails myUserDetailsService() { ExtendedInMemoryUserDetailsManager extendedInMemoryUserDetailsManager = new ExtendedInMemoryUserDetailsManager(); List<GrantedAuthority> salaboyAuthorities = new ArrayList<>(); salaboyAuthorities.add(new SimpleGrantedAuthority("ROLE_ACTIVITI_USER")); salaboyAuthorities.add(new SimpleGrantedAuthority("GROUP_activitiTeam")); extendedInMemoryUserDetailsManager.createUser(new User("salaboy", "password", salaboyAuthorities)); List<GrantedAuthority> adminAuthorities = new ArrayList<>(); adminAuthorities.add(new SimpleGrantedAuthority("ROLE_ACTIVITI_ADMIN")); extendedInMemoryUserDetailsManager.createUser(new User("admin", "password", adminAuthorities)); List<GrantedAuthority> garthAuthorities = new ArrayList<>(); garthAuthorities.add(new SimpleGrantedAuthority("ROLE_ACTIVITI_USER")); garthAuthorities.add(new SimpleGrantedAuthority("GROUP_doctor")); extendedInMemoryUserDetailsManager.createUser(new User("garth", "password", garthAuthorities)); return (UserDetails) extendedInMemoryUserDetailsManager; }
Source:
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; final String token = tokenExtractor.getToken(request); if (token == null) { send403(res, "Authorization token is missed"); return; } Jws<Claims> jwt; try { if (shouldSkipAuthentication(request, token)) { chain.doFilter(req, res); return; } jwt = jwtParser.parseClaimsJws(token); LOG.debug("JWT = ", jwt); } catch (ExpiredJwtException e) { send403(res, "The specified token is expired"); return; } catch (JwtException e) { send403(res, "Token validation failed: " + e.getMessage()); return; } request.setAttribute("token", jwt); chain.doFilter(req, res); }

Target:
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; final String token = tokenExtractor.getToken(request); if (token == null) { send401(res, "Authorization token is missed"); return; } Jws<Claims> jwt; try { if (shouldSkipAuthentication(request, token)) { chain.doFilter(req, res); return; } jwt = jwtParser.parseClaimsJws(token); LOG.debug("JWT = ", jwt); } catch (ExpiredJwtException e) { send401(res, "The specified token is expired"); return; } catch (JwtException e) { send401(res, "Token validation failed: " + e.getMessage()); return; } request.setAttribute("token", jwt); chain.doFilter(req, res); }
Source:
public void testRunMultipleQueries_ignored_failure_multiple() { ArrayList<VdcQueryType> queryTypeList = new ArrayList<VdcQueryType>(); queryTypeList.add(VdcQueryType.Search); queryTypeList.add(VdcQueryType.Search); ArrayList<VdcQueryParametersBase> queryParamsList = new ArrayList<VdcQueryParametersBase>(); queryParamsList.add(new SearchParameters("*win*", SearchType.VM)); queryParamsList.add(new SearchParameters("*lin*", SearchType.VM)); Frontend.RunMultipleQueries(queryTypeList, queryParamsList, mockMultipleQueryCallback, "test", mockService); verify(mockService).RunMultipleQueries(eq(queryTypeList), eq(queryParamsList), callbackMultipleQueries.capture()); StatusCodeException exception = new StatusCodeException(0, "0 status code"); callbackMultipleQueries.getValue().onFailure(exception); }

Target:
public void testRunMultipleQueries_ignored_failure_multiple() { ArrayList<VdcQueryType> queryTypeList = new ArrayList<VdcQueryType>(); queryTypeList.add(VdcQueryType.Search); queryTypeList.add(VdcQueryType.Search); ArrayList<VdcQueryParametersBase> queryParamsList = new ArrayList<VdcQueryParametersBase>(); queryParamsList.add(new SearchParameters("*win*", SearchType.VM)); queryParamsList.add(new SearchParameters("*lin*", SearchType.VM)); Frontend.RunMultipleQueries(queryTypeList, queryParamsList, mockMultipleQueryCallback, "test", mockService); verify(mockService).RunMultipleQueries(eq(queryTypeList), eq(queryParamsList), callbackMultipleQueries.capture()); StatusCodeException exception = new StatusCodeException(0, "0 status code"); callbackMultipleQueries.getValue().onFailure(exception); verify(mockFrontendFailureEvent, never()).raise(eq(Frontend.class), any(FrontendFailureEventArgs.class)); }
Source:
static void permitAll(HttpSecurityBuilder<? extends HttpSecurityBuilder<?>> http, RequestMatcher... requestMatchers) { ExpressionUrlAuthorizationConfigurer<?> configurer = http .getConfigurer(ExpressionUrlAuthorizationConfigurer.class); Assert.state(configurer != null, "permitAll only works with HttpSecurity.authorizeRequests()"); for (RequestMatcher matcher : requestMatchers) { if (matcher != null) { configurer.getRegistry().addMapping(0, new UrlMapping(matcher, SecurityConfig.createList(ExpressionUrlAuthorizationConfigurer.permitAll))); configurer.authorizationManagerBuilder.add(0, new RequestMatcherEntry<>(matcher, (a, o) -> AuthorizationDecision.GRANTED)); } } }

Target:
static void permitAll(HttpSecurityBuilder<? extends HttpSecurityBuilder<?>> http, RequestMatcher... requestMatchers) { ExpressionUrlAuthorizationConfigurer<?> configurer = http .getConfigurer(ExpressionUrlAuthorizationConfigurer.class); Assert.state(configurer != null, "permitAll only works with HttpSecurity.authorizeRequests()"); for (RequestMatcher matcher : requestMatchers) { if (matcher != null) { configurer.getRegistry().addMapping(0, new UrlMapping(matcher, SecurityConfig.createList(ExpressionUrlAuthorizationConfigurer.permitAll))); } } }
Source:
public void acceptRecord(final SAMRecord rec, final ReferenceSequence ref) { super.acceptRecord(rec, ref); }

Target:
public void acceptRecord(final SAMRecord rec, final ReferenceSequence ref) { if (!rec.getNotPrimaryAlignmentFlag()){ super.acceptRecord(rec, ref); } }
Source:
User getUser() { User user = null; HttpSession session = request.getSession(false); if (session != null) { user = (User) session.getAttribute(com.dotmarketing.util.WebKeys.CMS_USER); } return user; }

Target:
User getUser() { User user = null; final HttpSession session = request.getSession(false); if (session != null) { user = (User) session.getAttribute(com.dotmarketing.util.WebKeys.CMS_USER); } return user; }
Source:
Queue<ReplicaId> orderReplicaIds(String datacenterName, List<ReplicaId> replicaIds, boolean crossDCProxyCallEnabled) { Queue<ReplicaId> orderedReplicaIds = new ArrayDeque<ReplicaId>(replicaIdCount); Map<String, Deque<ReplicaId>> replicasPerDatacenter = new HashMap<String, Deque<ReplicaId>>(); Map<String, Integer> availableReplicaCountPerDatacenter = new HashMap<String, Integer>(); for (ReplicaId replicaId : replicaIds) { String dataCenter = replicaId.getDataNodeId().getDatacenterName(); if (!replicasPerDatacenter.containsKey(dataCenter)) { replicasPerDatacenter.put(dataCenter, new LinkedList<ReplicaId>()); availableReplicaCountPerDatacenter.put(dataCenter, 0); } } for (ReplicaId replicaId : replicaIds) { String dcName = replicaId.getDataNodeId().getDatacenterName(); if (dcName.equals(datacenterName)) { addReplicaToDataCenter(replicaId, dcName, replicasPerDatacenter, availableReplicaCountPerDatacenter); } else if (crossDCProxyCallEnabled) { addReplicaToDataCenter(replicaId, dcName, replicasPerDatacenter, availableReplicaCountPerDatacenter); } } dataCenterCount += replicasPerDatacenter.size() - 1; shuffleAndPopulate(replicasPerDatacenter, availableReplicaCountPerDatacenter, orderedReplicaIds); return orderedReplicaIds; }

Target:
Queue<ReplicaId> orderReplicaIds(String datacenterName, List<ReplicaId> replicaIds, boolean crossDCProxyCallEnabled) { Queue<ReplicaId> orderedReplicaIds = new ArrayDeque<ReplicaId>(replicaIdCount); List<ReplicaId> localReplicaIds = new ArrayList<ReplicaId>(replicaIdCount); List<ReplicaId> remoteReplicaIds = new ArrayList<ReplicaId>(replicaIdCount); List<ReplicaId> downReplicaIds = new ArrayList<ReplicaId>(replicaIdCount); for (ReplicaId replicaId : replicaIds) { if (replicaId.isDown()) { downReplicaIds.add(replicaId); } else if (replicaId.getDataNodeId().getDatacenterName().equals(datacenterName)) { localReplicaIds.add(replicaId); } else if (crossDCProxyCallEnabled) { remoteReplicaIds.add(replicaId); } } Collections.shuffle(localReplicaIds); orderedReplicaIds.addAll(localReplicaIds); Collections.shuffle(remoteReplicaIds); orderedReplicaIds.addAll(remoteReplicaIds); Collections.shuffle(downReplicaIds); orderedReplicaIds.addAll(downReplicaIds); return orderedReplicaIds; }
Source:
public void testToStockWithNewParents() throws IOException { SampleStockDto dto = new SampleStockDto(); dto.setRootSampleClassId(1L); dto.setParentSampleClassId(2L); dto.setSampleClassId(3L); dto.setExternalName("externalName"); dto.setTissueOriginId(4L); dto.setTissueTypeId(5L); Sample sample = Dtos.to(dto); assertNotNull(sample); assertTrue(LimsUtils.isStockSample(sample)); SampleStock analyte = (SampleStock) sample; assertNotNull(analyte.getSampleClass()); assertEquals(Long.valueOf(3L), analyte.getSampleClass().getId()); assertNotNull(analyte.getParent()); assertTrue(LimsUtils.isTissueSample(analyte.getParent())); SampleTissue tissue = (SampleTissue) analyte.getParent(); assertNotNull(tissue.getSampleClass()); assertEquals(Long.valueOf(2L), tissue.getSampleClass().getId()); assertNotNull(tissue.getTissueOrigin()); assertEquals(Long.valueOf(4L), tissue.getTissueOrigin().getId()); assertNotNull(tissue.getTissueType()); assertEquals(Long.valueOf(5L), tissue.getTissueType().getId()); assertNotNull(tissue.getParent()); assertTrue(LimsUtils.isIdentitySample(tissue.getParent())); Identity identity = (Identity) tissue.getParent(); assertEquals("externalName", identity.getExternalName()); }

Target:
public void testToStockWithNewParents() { SampleStockDto dto = new SampleStockDto(); dto.setRootSampleClassId(1L); dto.setParentTissueSampleClassId(2L); dto.setSampleClassId(3L); dto.setExternalName("externalName"); dto.setTissueOriginId(4L); dto.setTissueTypeId(5L); Sample sample = Dtos.to(dto); assertNotNull(sample); assertTrue(LimsUtils.isStockSample(sample)); SampleStock analyte = (SampleStock) sample; assertNotNull(analyte.getSampleClass()); assertEquals(Long.valueOf(3L), analyte.getSampleClass().getId()); assertNotNull(analyte.getParent()); assertTrue(LimsUtils.isTissueSample(analyte.getParent())); SampleTissue tissue = (SampleTissue) analyte.getParent(); assertNotNull(tissue.getSampleClass()); assertEquals(Long.valueOf(2L), tissue.getSampleClass().getId()); assertNotNull(tissue.getTissueOrigin()); assertEquals(Long.valueOf(4L), tissue.getTissueOrigin().getId()); assertNotNull(tissue.getTissueType()); assertEquals(Long.valueOf(5L), tissue.getTissueType().getId()); assertNotNull(tissue.getParent()); assertTrue(LimsUtils.isIdentitySample(tissue.getParent())); Identity identity = (Identity) tissue.getParent(); assertEquals("externalName", identity.getExternalName()); }
Source:
public String getTextToEdit(Object editedObject) { if (editedObject instanceof ValueSpecification) { return new UMLLabelProvider().getText(editedObject); } return "not a ValueSpecification"; }

Target:
public String getTextToEdit(Object editedObject) { if (editedObject instanceof ValueSpecification) { return new UMLLabelProvider().getText(editedObject); } return NOT_A_VALUE_SPECIFICATION; }