auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void run() { appendMsgToCustomLog("Started NodeRecycleThread to restart the node once all the sessions are completed."); while (getTotalUsed() > 1) { try { Thread.sleep(1000); } catch (InterruptedException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } appendMsgToCustomLog("All sessions are completed and restarting the node."); shutdownNode(); }

Target:
public void run() { appendMsgToCustomLog("Started NodeRecycleThread to restart the node once all the sessions are completed."); while (getTotalUsed() > 0) { try { Thread.sleep(1000); } catch (InterruptedException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } appendMsgToCustomLog("All sessions are completed and restarting the node."); shutdownNode(); }
Source:
public void initialize() { logger.debug("Initializing hue light handler."); final String configLightId = (String) getConfig().get(LIGHT_ID); if (configLightId != null) { lightId = configLightId; if (getHueBridgeHandler() != null) { ThingStatusInfo statusInfo = getBridge().getStatusInfo(); updateStatus(statusInfo.getStatus(), statusInfo.getStatusDetail(), statusInfo.getDescription()); FullLight fullLight = getLight(); if (fullLight != null) { updateProperty(Thing.PROPERTY_FIRMWARE_VERSION, fullLight.getSoftwareVersion()); String thingUID = HueBindingConstants.THING_TYPE_PAR16_50_TW.getId(); if (thingUID.equals("PAR16_50_TW")) { isOsramPar16 = true; } } } } }

Target:
public void initialize() { logger.debug("Initializing hue light handler."); final String configLightId = (String) getConfig().get(LIGHT_ID); if (configLightId != null) { lightId = configLightId; if (getHueBridgeHandler() != null) { ThingStatusInfo statusInfo = getBridge().getStatusInfo(); updateStatus(statusInfo.getStatus(), statusInfo.getStatusDetail(), statusInfo.getDescription()); FullLight fullLight = getLight(); if (fullLight != null) { updateProperty(Thing.PROPERTY_FIRMWARE_VERSION, fullLight.getSoftwareVersion()); String thingTypeId = HueBindingConstants.THING_TYPE_PAR16_50_TW.getId(); if (thingTypeId.equals("PAR16_50_TW")) { isOsramPar16 = true; } } } } }
Source:
JoinType(int val) { assert (this.ordinal() == val) : "Enum element " + this.name() + " in position " + this.ordinal() + " instead of position " + val; m_val = val; }

Target:
JoinType(int val) { assert (this.ordinal() == val) : "Enum element " + this.name() + " in position " + this.ordinal() + " instead of position " + val; }
Source:
public DelegatingResourceDescription getRepresentationDescription(Representation rep) { DelegatingResourceDescription description = null; if (rep instanceof RefRepresentation) { description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("display"); description.addSelfLink(); } if (rep instanceof DefaultRepresentation || rep instanceof FullRepresentation) { description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("identifierType"); description.addProperty("location"); description.addProperty("source"); description.addProperty("manualEntryEnabled"); description.addProperty("automaticGenerationEnabled"); description.addSelfLink(); if (rep instanceof DefaultRepresentation) { description.addLink("full", ".?v=" + RestConstants.REPRESENTATION_FULL); } } return description; }

Target:
public DelegatingResourceDescription getRepresentationDescription(Representation rep) { DelegatingResourceDescription description = null; if (rep instanceof RefRepresentation) { description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("display"); description.addSelfLink(); } else if (rep instanceof DefaultRepresentation) { description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("identifierType"); description.addProperty("location"); description.addProperty("source"); description.addProperty("manualEntryEnabled"); description.addProperty("automaticGenerationEnabled"); description.addSelfLink(); description.addLink("full", ".?v=" + RestConstants.REPRESENTATION_FULL); } else if (rep instanceof FullRepresentation) { description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("identifierType"); description.addProperty("location"); description.addProperty("source"); description.addProperty("manualEntryEnabled"); description.addProperty("automaticGenerationEnabled"); description.addSelfLink(); } return description; }
Source:
private <T> T callWithTimeLimit(Callable<T> callable, LockRequestSpecification specification) throws InterruptedException { try { return timeLimiter.callWithTimeout(callable, blockingTimeLimitMillis, TimeUnit.MILLISECONDS, true); } catch (InterruptedException e) { log.warn("Lock service was interrupted when servicing for client \"{}\"; request was {}", specification.method(), specification.client(), specification.lockRequest(), e); throw e; } catch (UncheckedTimeoutException e) { String errorMessage = String.format( "Lock service timed out after %s milliseconds when servicing %s for client \"%s\"; request was %s", blockingTimeLimitMillis, specification.method(), specification.client(), specification.lockRequest()); log.warn(errorMessage, e); throw new BlockingTimeoutException(errorMessage); } catch (Exception e) { throw Throwables.propagate(e); } }

Target:
private <T> T callWithTimeLimit(Callable<T> callable, LockRequestSpecification specification) throws InterruptedException { try { return timeLimiter.callWithTimeout(callable, blockingTimeLimitMillis, TimeUnit.MILLISECONDS, true); } catch (InterruptedException e) { log.info("Lock service was interrupted when servicing for client \"{}\"; request was {}", specification.method(), specification.client(), specification.lockRequest(), e); throw e; } catch (UncheckedTimeoutException e) { String message = String.format( "Lock service timed out after %s milliseconds when servicing %s for client \"%s\"; request was %s", blockingTimeLimitMillis, specification.method(), specification.client(), specification.lockRequest()); log.info(message, e); throw new BlockingTimeoutException(message); } catch (Exception e) { throw Throwables.propagate(e); } }
Source:
LocalSymbolTableImports(SymbolTable defaultSystemSymtab, SymbolTable... imports) { assert defaultSystemSymtab.isSystemTable() : "defaultSystemSymtab isn't a system symtab"; if (imports != null && imports.length > 0) { if (imports[0].isSystemTable()) { myImports = new SymbolTable[imports.length]; System.arraycopy(imports, 0, myImports, 0, imports.length); } else { myImports = new SymbolTable[imports.length + 1]; myImports[0] = defaultSystemSymtab; System.arraycopy(imports, 0, myImports, 1, imports.length); } } else { myImports = new SymbolTable[] { defaultSystemSymtab }; } myBaseSids = new int[myImports.length]; myMaxId = prepBaseSids(myBaseSids, myImports); }

Target:
LocalSymbolTableImports(SymbolTable defaultSystemSymtab, SymbolTable... imports) { assert defaultSystemSymtab.isSystemTable() : "defaultSystemSymtab isn't a system symtab"; if (imports != null && imports.length > 0) { if (imports[0].isSystemTable()) { myImports = imports.clone(); } else { myImports = new SymbolTable[imports.length + 1]; myImports[0] = defaultSystemSymtab; System.arraycopy(imports, 0, myImports, 1, imports.length); } } else { myImports = new SymbolTable[] { defaultSystemSymtab }; } myBaseSids = new int[myImports.length]; myMaxId = prepBaseSids(myBaseSids, myImports); }
Source:
private void recordImmutableTimestamp(long immutableTs) { long recentTs = recentImmutableTs.get(); while (recentTs < immutableTs) { if (recentImmutableTs.compareAndSet(recentTs, immutableTs)) { break; } else { recentTs = recentImmutableTs.get(); } } }

Target:
private void recordImmutableTimestamp(long immutableTs) { recentImmutableTs.updateAndGet(current -> Math.max(current, immutableTs)); }
Source:
private boolean importTraces() { boolean success = false; IOverwriteQuery overwriteQuery = new IOverwriteQuery() { @Override public String queryOverwrite(String file) { return fOverwrite ? IOverwriteQuery.ALL : IOverwriteQuery.NO_ALL; } }; FileSystemStructureProvider fileSystemStructureProvider = FileSystemStructureProvider.INSTANCE; for (FileAndName traceToImport : fTraces) { try { if (fLinked) { createLink(fTargetFolder, Path.fromOSString(traceToImport.getFile().getAbsolutePath()), traceToImport.getName()); setTraceType(traceToImport); success = true; } else { List<File> subList = new ArrayList<File>(); subList.add(traceToImport.getFile()); ImportOperation operation = new ImportOperation(getContainerFullPath().append(traceToImport.getName()), traceToImport.getFile().getParentFile(), fileSystemStructureProvider, overwriteQuery, subList); operation.setContext(getShell()); operation.setCreateLinks(fLinked); if (executeImportOperation(operation)) { setTraceType(traceToImport); success = true; } } } catch (Exception e) { e.printStackTrace(); } } return success; }

Target:
private boolean importTraces() { boolean success = false; IOverwriteQuery overwriteQuery = new IOverwriteQuery() { @Override public String queryOverwrite(String file) { return fOverwrite ? IOverwriteQuery.ALL : IOverwriteQuery.NO_ALL; } }; FileSystemStructureProvider fileSystemStructureProvider = FileSystemStructureProvider.INSTANCE; for (FileAndName traceToImport : fTraces) { try { if (fLinked) { createLink(fTargetFolder, Path.fromOSString(traceToImport.getFile().getAbsolutePath()), traceToImport.getName()); setTraceType(traceToImport); success = true; } else { List<File> subList = new ArrayList<File>(); subList.add(traceToImport.getFile()); ImportOperation operation = new ImportOperation(getContainerFullPath().append(traceToImport.getName()), traceToImport.getFile().getParentFile(), fileSystemStructureProvider, overwriteQuery, subList); operation.setContext(getShell()); operation.setCreateLinks(fLinked); if (executeImportOperation(operation)) { setTraceType(traceToImport); success = true; } } } catch (Exception e) { } } return success; }
Source:
private Object processPreStoredProcQuery(InternalParamCollection params, int queryLevel) throws DataServiceFault { boolean isError = false; CallableStatement stmt = null; ResultSet rs = null; try { Connection conn = this.createConnection(queryLevel); stmt = (CallableStatement) this.createProcessedPreparedStatement( SQLQuery.DS_QUERY_TYPE_STORED_PROC, params, conn); if (this.isJDBCFirstBatchRequest()) { this.setBatchPreparedStatement(stmt); BatchDataServiceRequest.addParticipant(this); } if (!this.hasResult() || (this.hasResult() && this.isReturnGeneratedKeys()) || (this.hasResult() && this.isReturnUpdatedRowCount())) { if (this.isJDBCBatchRequest()) { if (this.isJDBCLastBatchRequest()) { stmt.executeBatch(); } } else { stmt.executeUpdate(); } } else { if (this.isResultOnlyOutParams()) { stmt.execute(); if (this.hasRefCursor()) { rs = (ResultSet) stmt.getObject(getCurrentRefCursorOrdinal()); } } else { rs = this.getFirstRSOfStoredProc(stmt); } } return new QueryResultInfo(stmt, rs); } catch (Exception e) { log.error(e.getMessage(), e); isError = true; throw new DataServiceFault(e, FaultCodes.DATABASE_ERROR, "Error in 'SQLQuery.processStoredProcQuery': " + e.getMessage()); } finally { if (log.isDebugEnabled()){ log.debug("Stopping DB calls. ThreadID:" + Thread.currentThread().getId()); } if (isError) { this.releaseResources(rs, this.isStatementClosable(isError) ? stmt : null); } } }

Target:
private Object processPreStoredProcQuery(InternalParamCollection params, int queryLevel) throws DataServiceFault { boolean isError = false; CallableStatement stmt = null; ResultSet rs = null; try { Connection conn = this.createConnection(queryLevel); stmt = (CallableStatement) this.createProcessedPreparedStatement( SQLQuery.DS_QUERY_TYPE_STORED_PROC, params, conn); if (this.isJDBCFirstBatchRequest()) { this.setBatchPreparedStatement(stmt); BatchDataServiceRequest.addParticipant(this); } if (!this.hasResult() || (this.hasResult() && this.isReturnGeneratedKeys()) || (this.hasResult() && this.isReturnUpdatedRowCount())) { if (this.isJDBCBatchRequest()) { if (this.isJDBCLastBatchRequest()) { stmt.executeBatch(); } } else { stmt.executeUpdate(); } } else { if (this.isResultOnlyOutParams()) { stmt.execute(); if (this.hasRefCursor()) { rs = (ResultSet) stmt.getObject(getCurrentRefCursorOrdinal()); } } else { rs = this.getFirstRSOfStoredProc(stmt); } } return new QueryResultInfo(stmt, rs); } catch (Exception e) { log.error(e.getMessage(), e); isError = true; throw new DataServiceFault(e, FaultCodes.DATABASE_ERROR, "Error in 'SQLQuery.processStoredProcQuery': " + e.getMessage()); } finally { if (log.isDebugEnabled()) { log.debug("Stopping DB calls: ThreadID - " + Thread.currentThread().getId()); } if (isError) { this.releaseResources(rs, this.isStatementClosable(isError) ? stmt : null); } } }
Source:
public void flush(FlushMode mode) { for (ConnectionListener cl : listeners) { if (FlushMode.ALL == mode) { destroyAndRemoveConnectionListener(cl); } if (FlushMode.INVALID == mode && cl.getState() != DESTROY && cl.getState() != DESTROYED) { int previousState = cl.getState(); cl.changeState(previousState, VALIDATION); validateConnectionListener(cl, previousState); } if (FlushMode.IDLE == mode && (cl.getState() == FREE || cl.getState() == TO_POOL) || cl.getState() == DESTROY) { destroyAndRemoveConnectionListener(cl); } } prefill(); }

Target:
public void flush(FlushMode mode) { for (ConnectionListener cl : listeners) { switch (mode) { case ALL: { destroyAndRemoveConnectionListener(cl, listeners); break; } case INVALID: { if (cl.changeState(FREE, VALIDATION)) { validateConnectionListener(listeners, cl, FREE); } break; } case IDLE: { if (cl.changeState(FREE, FLUSH)) { destroyAndRemoveConnectionListener(cl, listeners); } break; } case GRACEFULLY: { if (cl.changeState(FREE, FLUSH)) { destroyAndRemoveConnectionListener(cl, listeners); } else if (cl.getState() == IN_USE || cl.getState() == TO_POOL || cl.getState() == VALIDATION) { cl.setState(DESTROY); } break; } } } prefill(); }
Source:
public void execute(IAction action) { boolean performAction = MessageDialog.openConfirm(getShell(), UIText.DiscardChangesAction_confirmActionTitle, UIText.DiscardChangesAction_confirmActionMessage); if (!performAction) return; String jobname = UIText.DiscardChangesAction_discardChanges; Job job = new Job(jobname) { @Override protected IStatus run(IProgressMonitor monitor) { try { new DiscardChangesOperation(getSelectedResources()) .execute(monitor); } catch (CoreException e) { return Activator.createErrorStatus( e.getStatus().getMessage(), e); } return Status.OK_STATUS; } }; job.setUser(true); job.schedule(); }

Target:
public void execute(IAction action) { boolean performAction = MessageDialog.openConfirm(getShell(), UIText.DiscardChangesAction_confirmActionTitle, UIText.DiscardChangesAction_confirmActionMessage); if (!performAction) return; final DiscardChangesOperation operation = new DiscardChangesOperation( getSelectedResources()); String jobname = UIText.DiscardChangesAction_discardChanges; Job job = new Job(jobname) { @Override protected IStatus run(IProgressMonitor monitor) { try { operation.execute(monitor); } catch (CoreException e) { return Activator.createErrorStatus(e.getStatus() .getMessage(), e); } return Status.OK_STATUS; } }; job.setUser(true); job.setRule(operation.getSchedulingRule()); job.schedule(); }
Source:
public static FileReaderWriterFactory createFileReaderWriterFactory(String className) throws Exception { Class<?> clazz = Class.forName(className); if (!FileReaderWriterFactory.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException(String.format("The class '%s' is not assignable to '%s'.", className, FileReaderWriterFactory.class.getName())); } return (FileReaderWriterFactory) clazz.newInstance(); }

Target:
private static FileReaderWriterFactory createFileReaderWriterFactory(String className) throws Exception { Class<?> clazz = Class.forName(className); if (!FileReaderWriterFactory.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException(String.format("The class '%s' is not assignable to '%s'.", className, FileReaderWriterFactory.class.getName())); } return (FileReaderWriterFactory) clazz.newInstance(); }
Source:
private void start(boolean daemon) { if (daemon == Thread.currentThread().isDaemon()) { server.start(); } else { FutureTask<Void> startTask = new FutureTask<Void>(new Runnable() { @Override public void run() { server.start(); } }, null); CustomThreadFactory.defaultThreadFactory(daemon).newThread(startTask).start(); try { startTask.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (ExecutionException e) { Throwable cause = e.getCause(); if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } else if (cause instanceof Error) { throw (Error)cause; } else throw new RuntimeException("Unexpected exception on starting HttpSever", cause); } } }

Target:
private void start(boolean daemon) { if (daemon == Thread.currentThread().isDaemon()) { server.start(); } else { FutureTask<Void> startTask = new FutureTask<Void>(new Runnable() { @Override public void run() { server.start(); } }, null); DaemonThreadFactory.defaultThreadFactory(daemon).newThread(startTask).start(); try { startTask.get(); } catch (ExecutionException e) { throw new RuntimeException("Unexpected exception on starting HTTPSever", e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }
Source:
public int compareTo(GpxImageEntry image) { MapillaryAbstractImage img = (MapillaryAbstractImage) image; if (this.getSequence() == img.getSequence()) { MapillarySequence seq = this.getSequence(); return compare(seq.getImages().indexOf(this), seq.getImages().indexOf(image)); } int compareSeq = compare(this.getSequence().getCapturedAt(), img.getSequence().getCapturedAt()); if (compareSeq == 0) { int compareTime = super.compareTo(image); if (compareTime == 0) { return hashCode() - image.hashCode(); } return compareTime; } return compareSeq; }

Target:
public int compareTo(GpxImageEntry image) { if(image instanceof MapillaryAbstractImage) { MapillaryAbstractImage img = (MapillaryAbstractImage) image; if (this.getSequence() == img.getSequence()) { MapillarySequence seq = this.getSequence(); return compare(seq.getImages().indexOf(this), seq.getImages().indexOf(image)); } int compareSeq = compare(this.getSequence().getCapturedAt(), img.getSequence().getCapturedAt()); if (compareSeq != 0) { return compareSeq; } } int compareTime = super.compareTo(image); if (compareTime == 0) { return hashCode() - image.hashCode(); } return compareTime; }
Source:
public static long estimatedSizeInBytes(Object object) { if (object == null) { return 1; } Class<?> javaType = object.getClass(); if (javaType == Long.class) { return Long.BYTES; } else if (javaType == Double.class) { return Double.BYTES; } else if (javaType == Boolean.class) { return 1; } else if (object instanceof Block) { return ((Block) object).getSizeInBytes(); } else if (object instanceof Slice) { return ((Slice) object).getRetainedSize(); } return Integer.MAX_VALUE; }

Target:
public static long estimatedSizeInBytes(Object object) { if (object == null) { return 1; } Class<?> javaType = object.getClass(); if (javaType == Long.class) { return Long.BYTES; } else if (javaType == Double.class) { return Double.BYTES; } else if (javaType == Boolean.class) { return 1; } else if (object instanceof Block) { return ((Block) object).getSizeInBytes(); } else if (object instanceof Slice) { return ((Slice) object).length(); } return Integer.MAX_VALUE; }
Source:
public Map<VdcParameter, Object> getParamsMap() { Map<VdcParameter, Object> copy = new HashMap<VdcParameter, Object>(); for (Entry<VdcParameter, Object> entry : paramsMap.entrySet()) { copy.put(entry.getKey(), entry.getValue()); } return copy; }

Target:
public Map<VdcParameter, Object> getParamsMap() { return (Map<VdcParameter, Object>) ((HashMap)paramsMap).clone(); }
Source:
public int addResourceToAllServices(GrillSessionHandle sessionid, String type, String path) { int numAdded = 0; boolean error = false; for (GrillService service : GrillServices.get().getGrillServices()) { try { service.addResource(sessionid, type, path); numAdded++; } catch (GrillException e) { LOG.error("Failed to add resource in service:" + service, e); error = true; break; } } if (!error) { getSession(sessionid).addResource(type, path); } return numAdded; }

Target:
public int addResourceToAllServices(GrillSessionHandle sessionid, String type, String path) { int numAdded = 0; boolean error = false; for (GrillService service : GrillServices.get().getGrillServices()) { try { service.addResource(sessionid, type, path); numAdded++; } catch (GrillException e) { LOG.error("Failed to add resource type:" + type + " path:" + path + " in service:" + service, e); error = true; break; } } if (!error) { getSession(sessionid).addResource(type, path); } return numAdded; }
Source:
@Override public boolean canHandleRequest(@NonNull Request data) { final Uri uri = data.uri; if (uri == null) { return false; } return (SCHEME_CONTENT.equals(uri.getScheme()) && ContactsContract.Contacts.CONTENT_URI.getHost().equals(uri.getHost()) && matcher.match(data.uri) != UriMatcher.NO_MATCH); }

Target:
@Override public boolean canHandleRequest(@NonNull Request data) { final Uri uri = data.uri; return uri != null && SCHEME_CONTENT.equals(uri.getScheme()) && ContactsContract.Contacts.CONTENT_URI.getHost().equals(uri.getHost()) && matcher.match(data.uri) != UriMatcher.NO_MATCH; }
Source:
public String getAttributeValue(String name) { for (int i = 0; i < reader.getAttributeCount(); i++) { String attrName = reader.getAttributeLocalName(i); if (attrName.equals(name)) { return reader.getAttributeValue(i); } } return null; }

Target:
public String getAttributeValue(String name) { return reader.getAttributeValue(null, name); }
Source:
private ListenableFuture<Duration> announce() { final ListenableFuture<Duration> future = announcementClient.announce(ImmutableSet.copyOf(announcements.values())); Futures.addCallback(future, new FutureCallback<Duration>() { @Override public void onSuccess(Duration duration) { errorBackOff.success(); failed.set(null); nextAnnouncementTime.set(System.nanoTime() + duration.roundTo(NANOSECONDS)); duration = new Duration(duration.toMillis() * 0.8, MILLISECONDS); scheduleNextAnnouncement(duration); } @Override public void onFailure(Throwable t) { Duration duration = errorBackOff.failed(t); failed.set(t); scheduleNextAnnouncement(duration); } }, executor); return future; }

Target:
private ListenableFuture<Duration> announce() { final ListenableFuture<Duration> future = announcementClient.announce(getServiceAnnouncements()); Futures.addCallback(future, new FutureCallback<Duration>() { @Override public void onSuccess(Duration duration) { errorBackOff.success(); failed.set(null); nextAnnouncementTime.set(System.nanoTime() + duration.roundTo(NANOSECONDS)); duration = new Duration(duration.toMillis() * 0.8, MILLISECONDS); scheduleNextAnnouncement(duration); } @Override public void onFailure(Throwable t) { Duration duration = errorBackOff.failed(t); failed.set(t); scheduleNextAnnouncement(duration); } }, executor); return future; }
Source:
public void theRequestForAFirmwareUpgradeIsReceived() throws Throwable { PROPERTIES_MAP.put(Keys.KEY_DEVICE_IDENTIFICATION_E_LABEL, this.deviceId.getDeviceIdE()); PROPERTIES_MAP.put(Keys.KEY_ORGANIZATION_IDENTIFICATION, this.organisationId.getOrganisationId()); PROPERTIES_MAP.put(ENDPOINT_LABEL, this.serviceEndpoint.getServiceEndpoint()); this.requestRunner(TestStepStatus.OK, PROPERTIES_MAP, TEST_CASE_NAME_REQUEST, TEST_CASE_XML, TEST_SUITE_XML); }

Target:
public void theRequestForAFirmwareUpgradeIsReceived() throws Throwable { PROPERTIES_MAP.put(Keys.KEY_DEVICE_IDENTIFICATION_E_LABEL, this.deviceId.getDeviceIdE()); PROPERTIES_MAP.put(Keys.KEY_ORGANIZATION_IDENTIFICATION, this.organisationId.getOrganisationId()); this.requestRunner(TestStepStatus.OK, PROPERTIES_MAP, TEST_CASE_NAME_REQUEST, TEST_CASE_XML, TEST_SUITE_XML); }
Source:
public static QuestionCoreProcessor create(final QuestionResponseReadDAO questionResponseReadDAO, final QuestionResponseDAO questionResponseDAO) { final List<Question> allQuestions = questionResponseReadDAO.getAllQuestions(); if (allQuestions.isEmpty()) { try { throw new Exception("getAllQuestions failed: please check postgres"); } catch (Exception e) { e.printStackTrace(); } } final Map<Integer, Question> allQuestionIdMap = new HashMap<>(); final List<Question> onboardingQuestions = Lists.newArrayList(); final List<Question> anomalyQuestions = Lists.newArrayList(); final List<Question> dailyQuestions = Lists.newArrayList(); final List<Question> demoQuestions = Lists.newArrayList(); final List<Question> surveyQuestions = Lists.newArrayList(); for (final Question question : allQuestions) { allQuestionIdMap.put(question.id, question); if (question.category == QuestionCategory.ONBOARDING) { onboardingQuestions.add(question); } if (question.category == QuestionCategory.ANOMALY_LIGHT) { anomalyQuestions.add(question); } if (question.category == QuestionCategory.DAILY) { dailyQuestions.add(question); } if (question.category == QuestionCategory.DEMO) { demoQuestions.add(question); } if (question.category == QuestionCategory.SURVEY) { surveyQuestions.add(question); } } if (dailyQuestions.size() < 2) { try { throw new Exception("less than 2 daily questions avail: please check postgres"); } catch (Exception e) { e.printStackTrace(); } } return new QuestionCoreProcessor(questionResponseReadDAO, questionResponseDAO, allQuestionIdMap, onboardingQuestions, anomalyQuestions, dailyQuestions, demoQuestions, surveyQuestions); }

Target:
public static QuestionCoreProcessor create(final QuestionResponseReadDAO questionResponseReadDAO, final QuestionResponseDAO questionResponseDAO) { final List<Question> allQuestions = questionResponseReadDAO.getAllQuestions(); if (allQuestions.isEmpty()) { LOGGER.error("error=no-questions source=postgres"); } final Map<Integer, Question> allQuestionIdMap = new HashMap<>(); final List<Question> onboardingQuestions = Lists.newArrayList(); final List<Question> anomalyQuestions = Lists.newArrayList(); final List<Question> dailyQuestions = Lists.newArrayList(); final List<Question> demoQuestions = Lists.newArrayList(); final List<Question> surveyQuestions = Lists.newArrayList(); for (final Question question : allQuestions) { allQuestionIdMap.put(question.id, question); if (question.category == QuestionCategory.ONBOARDING) { onboardingQuestions.add(question); } if (question.category == QuestionCategory.ANOMALY_LIGHT) { anomalyQuestions.add(question); } if (question.category == QuestionCategory.DAILY) { dailyQuestions.add(question); } if (question.category == QuestionCategory.DEMO) { demoQuestions.add(question); } if (question.category == QuestionCategory.SURVEY) { surveyQuestions.add(question); } } if (dailyQuestions.size() < 2) { LOGGER.error("error=dailyQuestions source=postgres"); } return new QuestionCoreProcessor(questionResponseReadDAO, questionResponseDAO, allQuestionIdMap, onboardingQuestions, anomalyQuestions, dailyQuestions, demoQuestions, surveyQuestions); }
Source:
public void describe(StreamApplicationDescriptor appDescriptor) { KafkaSystemDescriptor kafkaSystemDescriptor = new KafkaSystemDescriptor("kafka").withConsumerZkConnect(KAFKA_CONSUMER_ZK_CONNECT) .withProducerBootstrapServers(KAFKA_PRODUCER_BOOTSTRAP_SERVERS) .withDefaultStreamConfigs(KAFKA_DEFAULT_STREAM_CONFIGS); KafkaInputDescriptor<PageView> pageViewInputDescriptor = kafkaSystemDescriptor.getInputDescriptor(INPUT_PAGEVIEW_STREAM_ID, new JsonSerdeV2<>(PageView.class)); GenericSystemDescriptor azureBlobSystemDescriptor = new GenericSystemDescriptor(OUTPUT_SYSTEM, "org.apache.samza.system.azureblob.AzureBlobSystemFactory"); GenericOutputDescriptor<PageViewAvroRecord> azureBlobOuputDescriptor = azureBlobSystemDescriptor.getOutputDescriptor(OUTPUT_STREAM, new NoOpSerde<>()); appDescriptor.withDefaultSystem(kafkaSystemDescriptor); MessageStream<PageView> pageViewInput = appDescriptor.getInputStream(pageViewInputDescriptor); OutputStream<PageViewAvroRecord> pageViewAvroRecordOutputStream = appDescriptor.getOutputStream(azureBlobOuputDescriptor); pageViewInput .map((message) -> { System.out.println("Sending: "); System.out.println("Received PageViewEvent with pageId: " + message.pageId); return PageViewAvroRecord.buildPageViewRecord(message); }) .sendTo(pageViewAvroRecordOutputStream); }

Target:
public void describe(StreamApplicationDescriptor appDescriptor) { KafkaSystemDescriptor kafkaSystemDescriptor = new KafkaSystemDescriptor("kafka").withConsumerZkConnect(KAFKA_CONSUMER_ZK_CONNECT) .withProducerBootstrapServers(KAFKA_PRODUCER_BOOTSTRAP_SERVERS) .withDefaultStreamConfigs(KAFKA_DEFAULT_STREAM_CONFIGS); KafkaInputDescriptor<PageView> pageViewInputDescriptor = kafkaSystemDescriptor.getInputDescriptor(INPUT_PAGEVIEW_STREAM_ID, new JsonSerdeV2<>(PageView.class)); GenericSystemDescriptor azureBlobSystemDescriptor = new GenericSystemDescriptor(OUTPUT_SYSTEM, "org.apache.samza.system.azureblob.AzureBlobSystemFactory"); GenericOutputDescriptor<PageViewAvroRecord> azureBlobOuputDescriptor = azureBlobSystemDescriptor.getOutputDescriptor(OUTPUT_STREAM, new NoOpSerde<>()); appDescriptor.withDefaultSystem(kafkaSystemDescriptor); MessageStream<PageView> pageViewInput = appDescriptor.getInputStream(pageViewInputDescriptor); OutputStream<PageViewAvroRecord> pageViewAvroRecordOutputStream = appDescriptor.getOutputStream(azureBlobOuputDescriptor); pageViewInput .map((message) -> { LOG.info("Sending: Received PageViewEvent with pageId: " + message.pageId); return PageViewAvroRecord.buildPageViewRecord(message); }) .sendTo(pageViewAvroRecordOutputStream); }
Source:
public void testSpecificBuildSelector() throws Exception { FreeStyleProject other = createArtifactProject(), p = rule.createFreeStyleProject(); ParameterDefinition paramDef = new StringParameterDefinition("FOO","foo"); ParametersDefinitionProperty paramsDef = new ParametersDefinitionProperty(paramDef); other.addProperty(paramsDef); CopyArtifactPermissionProperty cpp=new CopyArtifactPermissionProperty("/"+p.getName()); other.addProperty(cpp); SpecificBuildSelector sbs = new SpecificBuildSelector("1"); assertEquals("1", sbs.getBuildNumber()); p.getBuildersList().add(CopyArtifactUtil.createCopyArtifact(other.getName(), null, sbs, "*.txt", "", false, false, true)); rule.assertBuildStatusSuccess(other.scheduleBuild2(0, new UserCause(), new ParametersAction(new StringParameterValue("FOO", "buildone"))).get()); rule.assertBuildStatusSuccess(other.scheduleBuild2(0, new UserCause())); FreeStyleBuild b = p.scheduleBuild2(0, new UserCause()).get(); rule.assertBuildStatusSuccess(b); assertFile(true, "foo.txt", b); assertFile(true, "buildone.txt", b); assertFile(false, "subdir/subfoo.txt", b); }

Target:
public void testSpecificBuildSelector() throws Exception { FreeStyleProject other = createArtifactProject(), p = rule.createFreeStyleProject(); ParameterDefinition paramDef = new StringParameterDefinition("FOO", "foo"); ParametersDefinitionProperty paramsDef = new ParametersDefinitionProperty(paramDef); other.addProperty(paramsDef); SpecificBuildSelector sbs = new SpecificBuildSelector("1"); assertEquals("1", sbs.getBuildNumber()); p.getBuildersList().add(CopyArtifactUtil.createCopyArtifact(other.getName(), null, sbs, "*.txt", "", false, false, true)); rule.assertBuildStatusSuccess(other.scheduleBuild2(0, new UserCause(), new ParametersAction(new StringParameterValue("FOO", "buildone"))).get()); rule.assertBuildStatusSuccess(other.scheduleBuild2(0, new UserCause())); FreeStyleBuild b = p.scheduleBuild2(0, new UserCause()).get(); rule.assertBuildStatusSuccess(b); assertFile(true, "foo.txt", b); assertFile(true, "buildone.txt", b); assertFile(false, "subdir/subfoo.txt", b); }
Source:
public void onAllRequiredCapabilitiesAvailable() { DataHolder.getInstance().getBundleContext().registerService(WebSocketServerSC.class, this, null); LOGGER.info("All required capabilities are available"); }

Target:
public void onAllRequiredCapabilitiesAvailable() { DataHolder.getInstance().getBundleContext().registerService(WebSocketServerSC.class, this, null); log.info("All required capabilities are available"); }
Source:
public void removeIf(Predicate<T> predicate) { for (int i = start; i < start + size; i++) { T a = (T) data[i]; if (predicate.test(a)) { toRemove.remove(a); dataAsSet.remove(a); data[i] = data[start + --size]; i--; } } }

Target:
public void removeIf(Predicate<T> predicate) { for (int i = start; i < start + size; i++) { T a = (T) data[i]; if (predicate.test(a)) { toRemove.add(a); } } }
Source:
public Set<String> getStoredReposWithAlias() { return repoIO.getStoredRepos().stream().map(repoId -> { RepoAliasMap repoAliasMap = RepoAliasMap.getInstance(); if (repoAliasMap.hasAlias(repoId)) { return repoAliasMap.getAlias(repoId); } else { return repoId; } }).collect(Collectors.toSet()); }

Target:
public Set<String> getStoredReposWithAlias() { return repoIO.getStoredRepos().stream().map(repoId -> { RepoConfig repoConfig = prefs.getRepoConfig(); return repoConfig.hasRepoAlias(repoId) ? repoConfig.getRepoAlias(repoId) : repoId; }).collect(Collectors.toSet()); }
Source:
public String getTitle() { final HitPolicy hitPolicy = hitPolicySupplier.get(); final BuiltinAggregator builtinAggregator = builtinAggregatorSupplier.get(); final StringBuilder sb = new StringBuilder(hitPolicy.value().substring(0, 1).toUpperCase()); if (HitPolicy.COLLECT == hitPolicy) { if (builtinAggregator != null) { switch (builtinAggregator) { case COUNT: sb.append("#"); break; case MAX: sb.append(">"); break; case MIN: sb.append("<"); break; case SUM: sb.append("+"); } } } return sb.toString(); }

Target:
public String getTitle() { final HitPolicy hitPolicy = hitPolicySupplier.get(); final BuiltinAggregator builtinAggregator = builtinAggregatorSupplier.get(); final StringBuilder sb = new StringBuilder(hitPolicy.value().substring(0, 1).toUpperCase()); if (HitPolicy.COLLECT == hitPolicy) { if (builtinAggregator != null) { sb.append(builtinAggregator.getCode()); } } return sb.toString(); }
Source:
protected List<String> getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { List<String> options = new ArrayList<>(); if (args.length == 1 && user.isAuthorized("essentials.kit.reset")) { return getPlayers(server, user); } else if (args.length == 2) { for (String kitName : ess.getKits().getKits().getKeys(false)) { if (!user.isAuthorized("essentials.kits." + kitName)) { continue; } options.add(kitName); } return options; } return Collections.emptyList(); }

Target:
protected List<String> getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { List<String> options = new ArrayList<>(); if (args.length == 1 && user.isAuthorized("essentials.kit.reset")) { return getPlayers(server, user); } else if (args.length == 2 && user.isAuthorized("essentials.kit.reset")) { for (String kitName : ess.getKits().getKits().getKeys(false)) { if (!user.isAuthorized("essentials.kits." + kitName)) { continue; } options.add(kitName); } return options; } return options; }
Source:
private String readXMLDecl(Reader input) throws IOException { BufferedReader reader = new BufferedReader(input); String xmlDecl = new String(); String line = null; StringBuilder stringBuilder = new StringBuilder(); while (xmlDecl.length() < 100 && ((line = reader.readLine()) != null)) { stringBuilder.append(line); if (line.indexOf(XML_DECL_END) != -1) { return stringBuilder.toString().substring(0, xmlDecl.indexOf(XML_DECL_END) + XML_DECL_END.length()); } } return xmlDecl; }

Target:
private String readXMLDecl(Reader input) throws IOException { BufferedReader reader = new BufferedReader(input); String line = null; StringBuilder stringBuilder = new StringBuilder(100); while (stringBuilder.length() < 100 && ((line = reader.readLine()) != null)) { stringBuilder.append(line); if (line.indexOf(XML_DECL_END) != -1) { String resultString = stringBuilder.toString(); return resultString.substring(0, resultString.indexOf(XML_DECL_END) + XML_DECL_END.length()); } } return stringBuilder.toString(); }
Source:
public ValidationResult supportedFirewallTypeForClusterVersion() { return ValidationResult .failWith( EngineMessage.UNSUPPORTED_FIREWALL_TYPE_FOR_CLUSTER_VERSION, ReplacementUtils.createSetVariableString("$clusterVersion", cluster.getCompatibilityVersion()), ReplacementUtils.createSetVariableString("$firewallType", cluster.getFirewallType()) ) .when(cluster.getCompatibilityVersion().lessOrEquals(Version.v3_6) && FirewallType.FIREWALLD.equals(cluster.getFirewallType())); }

Target:
public ValidationResult supportedFirewallTypeForClusterVersion() { return ValidationResult .failWith( EngineMessage.UNSUPPORTED_FIREWALL_TYPE_FOR_CLUSTER_VERSION, ReplacementUtils.createSetVariableString("clusterVersion", cluster.getCompatibilityVersion()), ReplacementUtils.createSetVariableString("firewallType", cluster.getFirewallType()) ) .when(cluster.getCompatibilityVersion().lessOrEquals(Version.v3_6) && FirewallType.FIREWALLD.equals(cluster.getFirewallType())); }
Source:
protected void run(String[] args) throws Exception { LOG.info("Running 'run' command."); final Options commandOptions = CliFrontendParser.getRunCommandOptions(); final CommandLine commandLine = getCommandLine(commandOptions, args, true); final ProgramOptions programOptions = ProgramOptions.create(commandLine); if (commandLine.hasOption(HELP_OPTION.getOpt())) { CliFrontendParser.printHelpForRun(customCommandLines); return; } programOptions.validate(); final PackagedProgram program; try { LOG.info("Building program from JAR file"); program = buildProgram(programOptions); } catch (FileNotFoundException e) { throw new CliArgsException("Could not build the program from JAR file: " + e.getMessage(), e); } final List<URL> jobJars = program.getJobJarAndDependencies(); final Configuration effectiveConfiguration = getEffectiveConfiguration(commandLine, programOptions, jobJars); LOG.debug("Effective executor configuration: {}", effectiveConfiguration); try { executeProgram(effectiveConfiguration, program); } finally { program.deleteExtractedLibraries(); } }

Target:
protected void run(String[] args) throws Exception { LOG.info("Running 'run' command."); final Options commandOptions = CliFrontendParser.getRunCommandOptions(); final CommandLine commandLine = getCommandLine(commandOptions, args, true); final ProgramOptions programOptions = ProgramOptions.create(commandLine); if (commandLine.hasOption(HELP_OPTION.getOpt())) { CliFrontendParser.printHelpForRun(customCommandLines); return; } final PackagedProgram program; try { LOG.info("Building program from JAR file"); program = buildProgram(programOptions); } catch (FileNotFoundException e) { throw new CliArgsException("Could not build the program from JAR file: " + e.getMessage(), e); } final List<URL> jobJars = program.getJobJarAndDependencies(); final Configuration effectiveConfiguration = getEffectiveConfiguration(commandLine, programOptions, jobJars); LOG.debug("Effective executor configuration: {}", effectiveConfiguration); try { executeProgram(effectiveConfiguration, program); } finally { program.deleteExtractedLibraries(); } }
Source:
public RecordReader<NullWritable, NullWritable> getRecordReader(InputSplit inputSplit, JobConf jobConf, Reporter reporter) { return null; }

Target:
public RecordReader<NullWritable, NullWritable> getRecordReader(InputSplit inputSplit, JobConf jobConf, Reporter reporter) { throw new UnsupportedOperationException(); }
Source:
public boolean beginTrackingIfPossible(Application application) { if (mAutomaticTracker == null) { AutomaticTracker automaticTracker = AutomaticTracker.newInstance(application, this ); if (automaticTracker != null) { automaticTracker.register(); mAutomaticTracker = automaticTracker; return true; } } return false; }

Target:
public boolean beginTrackingIfPossible(Application application) { if (mAutomaticTracker == null) { AutomaticTracker automaticTracker = AutomaticTracker.newInstanceIfPossible(application, this ); if (automaticTracker != null) { automaticTracker.register(); mAutomaticTracker = automaticTracker; return true; } } return false; }
Source:
protected final void processAnnotationOnClass(MethodMetadata data, Class<?> targetType) { if (Arrays.stream(targetType.getAnnotations()) .anyMatch(annotation -> classAnnotationProcessors.stream() .anyMatch(processor -> processor.test(annotation)))) { Arrays.stream(targetType.getAnnotations()) .forEach(annotation -> classAnnotationProcessors.stream() .filter(processor -> processor.test(annotation)) .forEach(processor -> processor.process(annotation, data))); } else { if (targetType.getAnnotations().length == 0) { data.addWarning(String.format( "Class %s has no annotations, it may affect contract %s", targetType.getSimpleName(), getClass().getSimpleName())); } else { data.addWarning(String.format( "Class %s has annotations %s that are not used by contract %s", targetType.getSimpleName(), Arrays.stream(targetType.getAnnotations()) .map(annotation -> annotation.annotationType() .getSimpleName()) .collect(Collectors.toList()), getClass().getSimpleName())); } } }

Target:
protected final void processAnnotationOnClass(MethodMetadata data, Class<?> targetType) { final List<GuardedAnnotationProcessor> processors = Arrays.stream(targetType.getAnnotations()) .flatMap(annotation -> classAnnotationProcessors.stream() .filter(processor -> processor.test(annotation))) .collect(Collectors.toList()); if (!processors.isEmpty()) { Arrays.stream(targetType.getAnnotations()) .forEach(annotation -> processors.stream() .filter(processor -> processor.test(annotation)) .forEach(processor -> processor.process(annotation, data))); } else { if (targetType.getAnnotations().length == 0) { data.addWarning(String.format( "Class %s has no annotations, it may affect contract %s", targetType.getSimpleName(), getClass().getSimpleName())); } else { data.addWarning(String.format( "Class %s has annotations %s that are not used by contract %s", targetType.getSimpleName(), Arrays.stream(targetType.getAnnotations()) .map(annotation -> annotation.annotationType() .getSimpleName()) .collect(Collectors.toList()), getClass().getSimpleName())); } } }
Source:
public void testMismatch() throws Exception { ConstructorBean bean = db.getSharedHandle().createQuery("SELECT i, '7' FROM bean").mapTo(ConstructorBean.class).findOnly(); assertEquals("3", bean.s); assertEquals(2, bean.i); }

Target:
public void testMismatch() throws Exception { db.getSharedHandle().createQuery("SELECT i, '7' FROM bean").mapTo(ConstructorBean.class).findOnly(); }
Source:
public void loginRegisterTestWithMultipleAccounts() throws Exception { TokensApi unAuthenticatedTokensApi = new TokensApi(getWebClient(false, "n/a")); createAccount1(unAuthenticatedTokensApi); createAccount2(unAuthenticatedTokensApi); registerAndLinkUnavailableTokens(unAuthenticatedTokensApi); UsersApi mainUsersApi = new UsersApi(getWebClient(true, GOOGLE_ACCOUNT_USERNAME1)); io.swagger.client.model.User user = mainUsersApi.changeUsername(CUSTOM_USERNAME2); Assert.assertEquals(CUSTOM_USERNAME2, user.getUsername()); registerAndLinkUnavailableTokens(unAuthenticatedTokensApi); mockGitHub(CUSTOM_USERNAME1); mockGoogleHelper(GOOGLE_ACCOUNT_USERNAME1); io.swagger.client.model.Token token = unAuthenticatedTokensApi.addGoogleToken(satellizerJSON); Assert.assertEquals(100l, (long)token.getUserId()); io.swagger.client.model.Token fakeGitHubCode = unAuthenticatedTokensApi.addToken(satellizerJSON); Assert.assertEquals(100l, (long)fakeGitHubCode.getUserId()); }

Target:
public void loginRegisterTestWithMultipleAccounts() throws Exception { TokensApi unAuthenticatedTokensApi = new TokensApi(getWebClient(false, "n/a")); createAccount1(unAuthenticatedTokensApi); createAccount2(unAuthenticatedTokensApi); registerAndLinkUnavailableTokens(unAuthenticatedTokensApi); UsersApi mainUsersApi = new UsersApi(getWebClient(true, GOOGLE_ACCOUNT_USERNAME1)); io.swagger.client.model.User user = mainUsersApi.changeUsername(CUSTOM_USERNAME2); Assert.assertEquals(CUSTOM_USERNAME2, user.getUsername()); registerAndLinkUnavailableTokens(unAuthenticatedTokensApi); mockGitHub(CUSTOM_USERNAME1); mockGoogleHelper(GOOGLE_ACCOUNT_USERNAME1); io.swagger.client.model.Token token = unAuthenticatedTokensApi.addGoogleToken(satellizerJSON); Assert.assertEquals(CUSTOM_USERNAME2, token.getUsername()); Assert.assertEquals(TokenType.DOCKSTORE.toString(), token.getTokenSource()); io.swagger.client.model.Token fakeGitHubCode = unAuthenticatedTokensApi.addToken(satellizerJSON); Assert.assertEquals(CUSTOM_USERNAME2, fakeGitHubCode.getUsername()); Assert.assertEquals(TokenType.DOCKSTORE.toString(), fakeGitHubCode.getTokenSource()); }
Source:
public int hashCode() { return name.hashCode() ^ parameterType.hashCode(); }

Target:
public int hashCode() { return Objects.hashCode(getName(), getParameterType(), getTypeModifier(), getParameterPointerType(), isRequired()); }
Source:
public Set<Variable> variables() { final Set<Variable> result = new HashSet<Variable>(); this.accept(new AbstractVisitor<Void, Void>(null) { @Override public Void visit(Variable node, Void _) { result.add(node); return null; } }); return result; }

Target:
public Set<Variable> variables() { final Set<Variable> result = new HashSet<Variable>(); new BasicVisitor(null) { @Override public Void visit(Variable node, Void _) { result.add(node); return null; } }.visitNode(this); return result; }
Source:
private List<MetacardType> getFilteredMetacardTypes() { if (!whitelistedMetacardTypes.isEmpty()) { return metacardTypes .stream() .filter(metacardType -> whitelistedMetacardTypes.contains(metacardType.getName())) .collect(Collectors.toList()); } return metacardTypes; }

Target:
private List<MetacardType> getFilteredMetacardTypes() { if (!whiteListedMetacardTypes.isEmpty()) { return metacardTypes .stream() .filter(metacardType -> whiteListedMetacardTypes.contains(metacardType.getName())) .collect(Collectors.toList()); } return metacardTypes; }
Source:
public void setUp() { MockitoAnnotations.initMocks(this); TmcSettingsHolder.set(settings); langs = spy(new TaskExecutorImpl()); TmcLangsHolder.set(langs); TmcSettingsHolder.set(settings); Exercise ex = new Exercise("Osa02_01.WilliamLovelace", "Example"); command = new SubmitAdaptiveExerciseToSkillifier(mockObserver, ex, factory); arithFuncsTempDir = TestUtils.getProject(this.getClass(), "arith_funcs"); when(mockExercise.getExerciseDirectory(any(Path.class))).thenReturn(arithFuncsTempDir); when(settings.getLocale()).thenReturn(new Locale("FI")); Optional<String> mockToken = Optional.of("testToken"); settings.setToken(mockToken); when(factory.getSkillifierUrl(anyString())).thenReturn(URI.create("www.someurl.com")); }

Target:
public void setUp() { MockitoAnnotations.initMocks(this); TmcSettingsHolder.set(settings); langs = spy(new TaskExecutorImpl()); TmcLangsHolder.set(langs); TmcSettingsHolder.set(settings); Exercise ex = new Exercise("Osa02_01.WilliamLovelace", "Example"); command = new SubmitAdaptiveExerciseToSkillifier(mockObserver, ex, factory); arithFuncsTempDir = TestUtils.getProject(this.getClass(), "arith_funcs"); when(mockExercise.getExerciseDirectory(any(Path.class))).thenReturn(arithFuncsTempDir); when(settings.getLocale()).thenReturn(new Locale("FI")); Optional<String> mockToken = Optional.of("testToken"); settings.setToken(mockToken); when(factory.getSkillifierUrl(anyString())).thenReturn(URI.create("www.example.com")); }
Source:
protected void onInit() throws ServletException { Saver<AuthenticationResult> authenticationResultSaver = getConfig().getInstance(AUTHENTICATION_RESULT_SAVER); MessageSource messageSource = getConfig().getInstance(MESSAGE_SOURCE); LoginController controller = new LoginController( getConfig().getLoginControllerConfig(), getConfig().getForgotPasswordControllerConfig().getUri(), getConfig().getVerifyControllerConfig().getUri(), getConfig().getRegisterControllerConfig().getUri(), getConfig().getLogoutControllerConfig().getUri(), getConfig().getVerifyControllerConfig().isEnable(), authenticationResultSaver, new LoginErrorModelFactory(messageSource)); setController(controller); super.onInit(); }

Target:
protected void onInit() throws ServletException { MessageSource messageSource = getConfig().getInstance(MESSAGE_SOURCE); LoginController controller = new LoginController(getConfig(), new LoginErrorModelFactory(messageSource)); setController(controller); super.onInit(); }