auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void rollback() throws SQLException { checkClosed(); if (autoCommit) { throw new PSQLException(GT.tr("Cannot rollback when autoCommit is enabled."), PSQLState.NO_ACTIVE_SQL_TRANSACTION); } if (queryExecutor.getTransactionState() != TransactionState.IDLE) { executeTransactionCommand(rollbackQuery); } else { LOGGER.log(Level.WARNING, "Rollback requested but no transaction in progress"); } }

Target:
public void rollback() throws SQLException { checkClosed(); if (autoCommit) { throw new PSQLException(GT.tr("Cannot rollback when autoCommit is enabled."), PSQLState.NO_ACTIVE_SQL_TRANSACTION); } if (queryExecutor.getTransactionState() != TransactionState.IDLE) { executeTransactionCommand(rollbackQuery); } else { LOGGER.log(Level.FINE, "Rollback requested but no transaction in progress"); } }
Source:
public void shouldParseUberConfirmationSegment() { String routingResponse = "{\"booking\":" + "{\"confirmation\":{\"provider\":{\"title\":\"John\",\"subtitle\":\"4.9\",\"imageURL\":\"<LINK_2>\"}," + "\"vehicle\":{\"title\":\"Prius Toyota\",\"subtitle\":\"UBER-PLATE\",\"imageURL\":\"<LINK_0>\"}," + "\"status\":{\"title\":\"Accepted\",\"subtitle\":\"Your request has been accepted by a driver and is 'en route' to the start location.\",\"value\":\"accepted\"}," + "\"purchase\":{\"price\":8.0,\"currency\":\"AUD\",\"productName\":\"uberX\",\"productType\":\"ps_tnc\",\"id\":\"2d1d002b-d4d0-4411-98e1-673b244878b2\"}," + "\"actions\":[{\"title\":\"Cancel Ride\",\"type\":\"CANCEL\",\"internalURL\":\"<LINK_1>\",\"isDestructive\":true}," + "{\"title\":\"Call Driver\",\"type\":\"CALL\",\"externalURL\":\"tel:(555)555-5555\",\"isDestructive\":false}]},\"title\":\"Accepted\"}," + "\"endTime\":1476477040,\"realTime\":true,\"segmentTemplateHashCode\":105079429,\"startTime\":1476476663}"; TripSegment segment = bookingGson().fromJson(routingResponse, TripSegment.class); assertThat(segment.getBooking()).isNotNull(); assertThat(segment.getBooking().getConfirmation()).isNotNull(); }

Target:
public void shouldParseUberConfirmationSegment() throws IOException { String routingResponse = IOUtils.toString(getClass().getResourceAsStream("/booking-uber.json")); TripSegment segment = bookingGson().fromJson(routingResponse, TripSegment.class); assertThat(segment.getBooking()).isNotNull(); assertThat(segment.getBooking().getConfirmation()).isNotNull(); }
Source:
void loadWhenBindingToConstructorParametersWithCustomDataUnitShouldBind() { MutablePropertySources sources = this.context.getEnvironment().getPropertySources(); Map<String, Object> source = new HashMap<>(); source.put("test.duration", "12"); source.put("test.size", "13"); source.put("test.period", "14"); source.put("test.formattedDuration", "15d"); source.put("test.formattedPeriod", "16y"); sources.addLast(new MapPropertySource("test", source)); load(ConstructorParameterWithUnitConfiguration.class); ConstructorParameterWithUnitProperties bean = this.context .getBean(ConstructorParameterWithUnitProperties.class); assertThat(bean.getDuration()).isEqualTo(Duration.ofDays(12)); assertThat(bean.getSize()).isEqualTo(DataSize.ofMegabytes(13)); assertThat(bean.getFormattedDuration()).isEqualTo(Duration.ofDays(15)); assertThat(bean.getFormattedPeriod()).isEqualTo(Period.ofYears(16)); }

Target:
void loadWhenBindingToConstructorParametersWithCustomDataUnitShouldBind() { MutablePropertySources sources = this.context.getEnvironment().getPropertySources(); Map<String, Object> source = new HashMap<>(); source.put("test.duration", "12"); source.put("test.size", "13"); source.put("test.period", "14"); sources.addLast(new MapPropertySource("test", source)); load(ConstructorParameterWithUnitConfiguration.class); ConstructorParameterWithUnitProperties bean = this.context .getBean(ConstructorParameterWithUnitProperties.class); assertThat(bean.getDuration()).isEqualTo(Duration.ofDays(12)); assertThat(bean.getSize()).isEqualTo(DataSize.ofMegabytes(13)); assertThat(bean.getPeriod()).isEqualTo(Period.ofYears(14)); }
Source:
private ResultAndError<PullTaskResult> handleBadLocalState(AndroidTransactionParserFactory factory) { Pair<Integer, String> returnCodeAndMessageFromRecovery = recover(requestor, factory); int returnCode = returnCodeAndMessageFromRecovery.first; String failureReason = returnCodeAndMessageFromRecovery.second; if (returnCode == PROGRESS_DONE) { onSuccessfulSync(); return new ResultAndError<>(PullTaskResult.DOWNLOAD_SUCCESS); } else if (returnCode == PROGRESS_RECOVERY_FAIL_SAFE || returnCode == PROGRESS_RECOVERY_FAIL_BAD) { wipeLoginIfItOccurred(); this.publishProgress(PROGRESS_DONE); return new ResultAndError<>(PullTaskResult.UNKNOWN_FAILURE, failureReason); } else { wipeLoginIfItOccurred(); return null; } }

Target:
private ResultAndError<PullTaskResult> handleBadLocalState(AndroidTransactionParserFactory factory) throws UnknownSyncError { Pair<Integer, String> returnCodeAndMessageFromRecovery = recover(requestor, factory); int returnCode = returnCodeAndMessageFromRecovery.first; String failureReason = returnCodeAndMessageFromRecovery.second; if (returnCode == PROGRESS_DONE) { onSuccessfulSync(); return new ResultAndError<>(PullTaskResult.DOWNLOAD_SUCCESS); } else if (returnCode == PROGRESS_RECOVERY_FAIL_SAFE || returnCode == PROGRESS_RECOVERY_FAIL_BAD) { wipeLoginIfItOccurred(); this.publishProgress(PROGRESS_DONE); return new ResultAndError<>(PullTaskResult.UNKNOWN_FAILURE, failureReason); } else { throw new UnknownSyncError(); } }
Source:
public Arguments setUntypedNullArgument(Argument untypedNullArgument) { if (untypedNullArgument == null) { throw new IllegalArgumentException("the Argument itself may not be null"); } this.untypedNullArgument = untypedNullArgument; return this; }

Target:
public void setUntypedNullArgument(Argument untypedNullArgument) { if (untypedNullArgument == null) { throw new IllegalArgumentException("the Argument itself may not be null"); } this.untypedNullArgument = untypedNullArgument; }
Source:
public void run_gradle_script_messages_initialized() { final String gradleInstallationName = "Default"; GradleInstallation.installGradle(jenkins, gradleInstallationName, GradleInstallation.LATEST_VERSION); final FreeStyleJob job = jenkins.jobs.create(); job.copyResource(resource("/gradle_plugin/script.gradle"), "build.gradle"); final GradleStep step = job.addBuildStep(GradleStep.class); step.setVersion(gradleInstallationName); step.setTasks("hello"); job.save(); final Build build = job.startBuild(); build.shouldSucceed(); assertThat(build.getConsole(), containsString("Invoke Gradle script")); }

Target:
public void run_gradle_script_messages_initialized() { GradleInstallation.installLatestGradleVersion(jenkins); final FreeStyleJob job = jenkins.jobs.create(); job.copyResource(resource("/gradle_plugin/script.gradle"), "build.gradle"); final GradleStep step = job.addBuildStep(GradleStep.class); step.setVersion(GradleInstallation.DEFAULT_VERSION_NAME); step.setTasks("hello"); job.save(); final Build build = job.startBuild(); build.shouldSucceed(); assertThat(build.getConsole(), containsString("Invoke Gradle script")); }
Source:
public ImmutableList<Artifact> getSources() { return ImmutableList.copyOf(Iterables.transform(importPathSourcePair, p -> p.first)); }

Target:
public ImmutableList<ProtoSource> getSources() { return sources; }
Source:
public MapSqlParameterMapper<GlusterBrickEntity> getBatchMapper() { throw new RuntimeException("Unsupported operation"); }

Target:
public MapSqlParameterMapper<GlusterBrickEntity> getBatchMapper() { throw new NotImplementedException("Unsupported operation"); }
Source:
public void setUp() throws Exception { jobState = new JobState() { private static final long serialVersionUID = 1L; @Override public ArrayList<TaskState> getTasks() { ArrayList<TaskState> list = new ArrayList<TaskState>(); for (int i = 0; i < 10; i++) { list.add(mock(TaskState.class)); } return list; } @Override public void update(TaskInfo info) { } @Override public void update(JobInfo jobInfo) { } @Override public JobInfo getJobInfo() { return null; } @Override public Map<TaskId, TaskState> getHMTasks() { return null; } @Override public String getOwner() { return null; } @Override public JobType getType() { return null; } }; }

Target:
public void setUp() throws Exception { jobState = new JobState() { private static final long serialVersionUID = 1L; @Override public ArrayList<TaskState> getTasks() { ArrayList<TaskState> list = new ArrayList<TaskState>(10); for (int i = 0; i < 10; i++) { list.add(mock(TaskState.class)); } return list; } @Override public void update(TaskInfo info) { } @Override public void update(JobInfo jobInfo) { } @Override public JobInfo getJobInfo() { return null; } @Override public Map<TaskId, TaskState> getHMTasks() { return null; } @Override public String getOwner() { return null; } @Override public JobType getType() { return null; } }; }
Source:
public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException { if (arguments.length != 1) { throw new UDFArgumentLengthException("The GeocodedDataUDF takes an array with only 1 element as argument"); } ObjectInspector arg1 = arguments[0]; if (arg1.getCategory() != Category.PRIMITIVE) { throw new UDFArgumentTypeException(0, "A string argument was expected but an argument of type " + arg1.getTypeName() + " was given."); } PrimitiveCategory primitiveCategory = ((PrimitiveObjectInspector) arg1).getPrimitiveCategory(); if (primitiveCategory != PrimitiveCategory.STRING) { throw new UDFArgumentTypeException(0, "A string argument was expected but an argument of type " + arg1.getTypeName() + " was given."); } argumentOI = arg1; if (geocode == null) { try { geocode = new Geocode(currentPath); } catch (IOException ex) { LOG.error(ex); throw new RuntimeException(ex); } } ArrayList fieldNames = new ArrayList(); ArrayList fieldObjectInspectors = new ArrayList(); for (String field : Geocode.getFields()) { fieldNames.add(field); if (field.equalsIgnoreCase("latitude") || field.equalsIgnoreCase("longitude")) fieldObjectInspectors.add(PrimitiveObjectInspectorFactory.javaDoubleObjectInspector); else fieldObjectInspectors.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector); } result = new HashMap<String, String>(); return ObjectInspectorFactory.getStandardMapObjectInspector( PrimitiveObjectInspectorFactory.javaStringObjectInspector, PrimitiveObjectInspectorFactory.javaStringObjectInspector); }

Target:
public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException { if (arguments.length != 1) { throw new UDFArgumentLengthException("The GeocodedDataUDF takes an array with only 1 element as argument"); } ObjectInspector arg1 = arguments[0]; if (arg1.getCategory() != Category.PRIMITIVE) { throw new UDFArgumentTypeException(0, "A string argument was expected but an argument of type " + arg1.getTypeName() + " was given."); } PrimitiveCategory primitiveCategory = ((PrimitiveObjectInspector) arg1).getPrimitiveCategory(); if (primitiveCategory != PrimitiveCategory.STRING) { throw new UDFArgumentTypeException(0, "A string argument was expected but an argument of type " + arg1.getTypeName() + " was given."); } argumentOI = arg1; if (geocode == null) { try { geocode = new Geocode(); } catch (IOException ex) { LOG.error(ex); throw new RuntimeException(ex); } } result = new HashMap<String, String>(); return ObjectInspectorFactory.getStandardMapObjectInspector( PrimitiveObjectInspectorFactory.javaStringObjectInspector, PrimitiveObjectInspectorFactory.javaStringObjectInspector); }
Source:
private void createTableEnvironment( EnvironmentSettings settings, TableConfig config, CatalogManager catalogManager, ModuleManager moduleManager, FunctionCatalog functionCatalog) { config.addConfiguration(flinkConfig); if (environment.getExecution().isStreamingPlanner()) { streamExecEnv = createStreamExecutionEnvironment(); execEnv = null; final Map<String, String> executorProperties = settings.toExecutorProperties(); executor = lookupExecutor(executorProperties, streamExecEnv); tableEnv = createStreamTableEnvironment( streamExecEnv, settings, config, executor, catalogManager, moduleManager, functionCatalog); } else if (environment.getExecution().isBatchPlanner()) { streamExecEnv = null; execEnv = createExecutionEnvironment(); executor = null; tableEnv = new BatchTableEnvironmentImpl( execEnv, config, catalogManager, moduleManager); } else { throw new SqlExecutionException("Unsupported execution type specified."); } }

Target:
private void createTableEnvironment( EnvironmentSettings settings, TableConfig config, CatalogManager catalogManager, ModuleManager moduleManager, FunctionCatalog functionCatalog) { if (environment.getExecution().isStreamingPlanner()) { streamExecEnv = createStreamExecutionEnvironment(); execEnv = null; final Map<String, String> executorProperties = settings.toExecutorProperties(); executor = lookupExecutor(executorProperties, streamExecEnv); tableEnv = createStreamTableEnvironment( streamExecEnv, settings, config, executor, catalogManager, moduleManager, functionCatalog); } else if (environment.getExecution().isBatchPlanner()) { streamExecEnv = null; execEnv = createExecutionEnvironment(); executor = null; tableEnv = new BatchTableEnvironmentImpl( execEnv, config, catalogManager, moduleManager); } else { throw new SqlExecutionException("Unsupported execution type specified."); } }
Source:
protected void addMemberCheckNull(Object member, boolean addSeparator) { IfStatement ifStatement= fAst.newIfStatement(); ifStatement.setExpression(createInfixExpression(createMemberAccessExpression(member, true, true), Operator.NOT_EQUALS, fAst.newNullLiteral())); Block thenBlock= fAst.newBlock(); flushBuffer(null); for (String a : getContext().getTemplateParser().getBody()) { addElement(processElement(a, member), thenBlock); } if (addSeparator) addElement(getContext().getTemplateParser().getSeparator(), thenBlock); flushBuffer(thenBlock); if (thenBlock.statements().size() == 1 && !getContext().isForceBlocks()) { ifStatement.setThenStatement((Statement)ASTNode.copySubtree(fAst, (ASTNode)thenBlock.statements().get(0))); } else { ifStatement.setThenStatement(thenBlock); } toStringMethod.getBody().statements().add(ifStatement); }

Target:
protected void addMemberCheckNull(Object member, boolean addSeparator) { IfStatement ifStatement= fAst.newIfStatement(); ifStatement.setExpression(createInfixExpression(createMemberAccessExpression(member, true, true), Operator.NOT_EQUALS, fAst.newNullLiteral())); Block thenBlock= fAst.newBlock(); flushBuffer(null); for (String s : getContext().getTemplateParser().getBody()) { addElement(processElement(s, member), thenBlock); } if (addSeparator) addElement(getContext().getTemplateParser().getSeparator(), thenBlock); flushBuffer(thenBlock); if (thenBlock.statements().size() == 1 && !getContext().isForceBlocks()) { ifStatement.setThenStatement((Statement)ASTNode.copySubtree(fAst, (ASTNode)thenBlock.statements().get(0))); } else { ifStatement.setThenStatement(thenBlock); } toStringMethod.getBody().statements().add(ifStatement); }
Source:
public synchronized void unsubscribe() { if (dispatcher == null) { LOGGER.warn("attempted to unsubscribe with a null internal " + "subscription - possibly unsubscribing more than once - subject: " + subject); return; } try { dispatcher.unsubscribe(getFormattedSubject()); } catch (IllegalStateException e) { LOGGER.warn("could not unsubscribe from subscription. " + e.getMessage()); } dispatcher = null; }

Target:
public synchronized void unsubscribe() { if (dispatcher == null) { LOGGER.warn("attempted to unsubscribe with a null internal " + "subscription - possibly unsubscribing more than once - subject: " + subject); return; } try { dispatcher.unsubscribe(getFormattedSubject()); } catch (IllegalStateException e) { LOGGER.warn("could not unsubscribe from subscription. " + e.getMessage()); } conn.closeDispatcher(dispatcher); dispatcher = null; }
Source:
public Repo<Master> call(long tid, Master master) throws Exception { Utils.idLock.lock(); try { tableInfo.tableId = Utils.getNextId(tableInfo.tableName, master.getInstance(), Table.ID::of); if (tableInfo.props.containsKey(Property.TABLE_OFFLINE_OPTS + "create.initial.splits") && this.splitFile != null) { storeSplitFileNameInZooKeeper(); } return new SetupPermissions(tableInfo); } finally { Utils.idLock.unlock(); } }

Target:
public Repo<Master> call(long tid, Master master) throws Exception { Utils.idLock.lock(); try { tableInfo.tableId = Utils.getNextId(tableInfo.tableName, master.getContext(), Table.ID::of); return new SetupPermissions(tableInfo); } finally { Utils.idLock.unlock(); } }
Source:
public void define(WebService.NewController context) { WebService.NewAction action = context.createAction(ACTION) .setPost(true) .setDescription("Update a custom metric.<br /> Requires 'Administer System' permission.") .setSince("5.2") .setHandler(this); action.createParam(PARAM_ID) .setRequired(true) .setDescription("Id of the custom metric to update") .setExampleValue("42"); action.createParam(PARAM_KEY) .setDescription("Key") .setMaximumLength(MAX_KEY_LENGTH) .setDescription("Key") .setExampleValue("team_size"); action.createParam(PARAM_NAME) .setMaximumLength(MAX_NAME_LENGTH) .setDescription("Name") .setExampleValue("Team Size"); action.createParam(PARAM_TYPE) .setDescription("Metric type key") .setPossibleValues(Metric.ValueType.names()) .setExampleValue(Metric.ValueType.INT.name()); action.createParam(PARAM_DESCRIPTION) .setDescription("Description") .setMaximumLength(MAX_DESCRIPTION_LENGTH) .setExampleValue("Size of the team"); action.createParam(PARAM_DOMAIN) .setMaximumLength(MAX_DOMAIN_LENGTH) .setDescription("Domain") .setExampleValue("Tests"); }

Target:
public void define(WebService.NewController context) { WebService.NewAction action = context.createAction(ACTION) .setPost(true) .setDescription("Update a custom metric.<br /> Requires 'Administer System' permission.") .setSince("5.2") .setHandler(this); action.createParam(PARAM_ID) .setRequired(true) .setDescription("Id of the custom metric to update") .setExampleValue("42"); action.createParam(PARAM_KEY) .setDescription("Key") .setMaximumLength(MAX_KEY_LENGTH) .setDescription("Key") .setExampleValue("team_size"); action.createParam(PARAM_NAME) .setMaximumLength(MAX_NAME_LENGTH) .setDescription("Name"); action.createParam(PARAM_TYPE) .setDescription("Metric type key") .setPossibleValues(Metric.ValueType.names()) .setExampleValue(Metric.ValueType.INT.name()); action.createParam(PARAM_DESCRIPTION) .setDescription("Description") .setMaximumLength(MAX_DESCRIPTION_LENGTH) .setExampleValue("Size of the team"); action.createParam(PARAM_DOMAIN) .setMaximumLength(MAX_DOMAIN_LENGTH) .setDescription("Domain") .setExampleValue("Tests"); }
Source:
public long getMinReplicatedIndex(PipelineID pipelineID) throws IOException { Long minIndex = null; Iterator<RaftGroup> raftGroupIterator = getServer().getGroups().iterator(); while (raftGroupIterator.hasNext()) { RaftGroup group = raftGroupIterator.next(); if (group.getGroupId().getUuid().equals(pipelineID.getId())) { GroupInfoReply reply = getServer() .getGroupInfo(createGroupInfoRequest(pipelineID.getProtobuf())); minIndex = RatisHelper.getMinReplicatedIndex(reply.getCommitInfos()); } } return minIndex == null ? 0 : minIndex.longValue(); }

Target:
public long getMinReplicatedIndex(PipelineID pipelineID) throws IOException { Long minIndex; GroupInfoReply reply = getServer() .getGroupInfo(createGroupInfoRequest(pipelineID.getProtobuf())); minIndex = RatisHelper.getMinReplicatedIndex(reply.getCommitInfos()); return minIndex == null ? -1 : minIndex.longValue(); }
Source:
private void initWsWorkUnitsSoapProxy(String baseURL, String user, String pass) { wsWorkunitsServiceSoapProxy = new WsWorkunitsServiceSoapProxy(baseURL); fallBackWorkunitsServiceSoapProxy = new org.hpccsystems.ws.client.gen.wsworkunits.v1_56.WsWorkunitsServiceSoapProxy(baseURL); if (wsWorkunitsServiceSoapProxy != null) { WsWorkunitsServiceSoap wsWorkunitsServiceSoap = wsWorkunitsServiceSoapProxy.getWsWorkunitsServiceSoap(); if (user != null && pass != null) Connection.initStub((Stub) wsWorkunitsServiceSoap, user, pass); } if (fallBackWorkunitsServiceSoapProxy != null) { org.hpccsystems.ws.client.gen.wsworkunits.v1_56.WsWorkunitsServiceSoap fallBackWorkunitsServiceSoap = fallBackWorkunitsServiceSoapProxy.getWsWorkunitsServiceSoap(); if (user != null && pass != null) Connection.initStub((Stub) fallBackWorkunitsServiceSoap, user, pass); } }

Target:
private void initWsWorkUnitsSoapProxy(String baseURL, String user, String pass) { wsWorkunitsServiceSoapProxy = new WsWorkunitsServiceSoapProxy(baseURL); if (wsWorkunitsServiceSoapProxy != null) { WsWorkunitsServiceSoap wsWorkunitsServiceSoap = wsWorkunitsServiceSoapProxy.getWsWorkunitsServiceSoap(); if (user != null && pass != null) Connection.initStub((Stub) wsWorkunitsServiceSoap, user, pass); } fallBackWorkunitsServiceSoapProxy = new org.hpccsystems.ws.client.gen.wsworkunits.v1_56.WsWorkunitsServiceSoapProxy( baseURL); if (fallBackWorkunitsServiceSoapProxy != null) { org.hpccsystems.ws.client.gen.wsworkunits.v1_56.WsWorkunitsServiceSoap fallBackWorkunitsServiceSoap = fallBackWorkunitsServiceSoapProxy .getWsWorkunitsServiceSoap(); if (user != null && pass != null) Connection.initStub((Stub) fallBackWorkunitsServiceSoap, user, pass); } }
Source:
public void testGetCalendarSettings() throws Exception { Calendar cal = new Calendar() ; cal.setName("myCal") ; cal.setCalendarOwner("root"); JsonGeneratorImpl generatorImpl = new JsonGeneratorImpl(); JsonValue json = generatorImpl.createJsonObject(new CalendarResource(cal, CAL_BASE_URI + "/")); byte[] data = json.toString().getBytes("UTF-8"); headers.putSingle("content-type", "application/json"); headers.putSingle("content-length", "" + data.length); login("root"); ByteArrayContainerResponseWriter writer = new ByteArrayContainerResponseWriter(); ContainerResponse response = service(HTTPMethods.GET, CAL_BASE_URI + "/getCalendarSettings", baseURI, headers, data, writer); assertEquals(HTTPStatus.OK, response.getStatus()); }

Target:
public void testGetCalendarSettings() throws Exception { Calendar cal = new Calendar() ; cal.setName("myCal") ; cal.setCalendarOwner("root"); JsonGeneratorImpl generatorImpl = new JsonGeneratorImpl(); CalendarSetting calendarSetting = calendarService.getCalendarSetting("root"); JsonValue json = generatorImpl.createJsonObject(calendarSetting); byte[] data = json.toString().getBytes("UTF-8"); headers.putSingle("content-type", "application/json"); headers.putSingle("content-length", "" + data.length); login("root"); ByteArrayContainerResponseWriter writer = new ByteArrayContainerResponseWriter(); ContainerResponse response = service(HTTPMethods.GET, CAL_BASE_URI + "/getCalendarSettings", baseURI, headers, data, writer); assertEquals(HTTPStatus.OK, response.getStatus()); assertEquals("MM/dd/yyyy", calendarSetting.getDateFormat()); }
Source:
private UidFetchCommand createUidFetchCommand(int maximumAutoDownloadMessageSize, Long uid, Item... items) { FetchProfile fetchProfile = new FetchProfile(); Collections.addAll(fetchProfile, items); return new UidFetchCommand.Builder() .maximumAutoDownloadMessageSize(maximumAutoDownloadMessageSize) .idSet(Collections.singletonList(uid)) .messageParams(fetchProfile, new HashMap<>(Collections.singletonMap(String.valueOf(uid), (Message) createImapMessage(String.valueOf(uid))))) .build(); }

Target:
private UidFetchCommand createUidFetchCommand(int maximumAutoDownloadMessageSize, Long uid, Item... items) { FetchProfile fetchProfile = new FetchProfile(); Collections.addAll(fetchProfile, items); Map<String, Message> messageMap = Collections.singletonMap(String.valueOf(uid), (Message) createImapMessage(String.valueOf(uid))); return UidFetchCommand.createWithMessageParams(Collections.singleton(uid), maximumAutoDownloadMessageSize, messageMap, fetchProfile, null); }
Source:
private void confirmNotAlreadyJoinedAsInstructor(InstructorAttributes instructorForKey, String googleId, String institute) throws JoinCourseException { if(instructorForKey.googleId ==null || !instructorForKey.googleId.equals(googleId)){ return; } AccountAttributes existingAccount = accountsDb.getAccount(googleId); if (existingAccount != null && existingAccount.isInstructor){ String errorMsg = ""; if (institute != null) { errorMsg = "You have already verified the account"; } else { errorMsg = googleId + " has already joined this course"; } throw new JoinCourseException(Const.StatusCodes.ALREADY_JOINED, errorMsg); } }

Target:
private void confirmNotAlreadyJoinedAsInstructor(InstructorAttributes instructorForKey, String googleId, String institute) throws JoinCourseException { if(instructorForKey.googleId ==null || !instructorForKey.googleId.equals(googleId)){ return; } AccountAttributes existingAccount = accountsDb.getAccount(googleId); if (existingAccount != null && existingAccount.isInstructor){ throw new JoinCourseException(Const.StatusCodes.ALREADY_JOINED, googleId + " has already joined this course"); } }
Source:
public void compactOnLaunch_shouldCompact() throws IOException { Pair<Long, Long> results = populateTestRealmAndCompactOnLaunch(new CompactOnLaunchCallback() { @Override public boolean shouldCompact(long totalBytes, long usedBytes) { assertTrue(totalBytes > usedBytes); return true; } }); assertTrue(results.first.compareTo(results.second) > 0); }

Target:
public void compactOnLaunch_shouldCompact() throws IOException { Pair<Long, Long> results = populateTestRealmAndCompactOnLaunch(new CompactOnLaunchCallback() { @Override public boolean shouldCompact(long totalBytes, long usedBytes) { assertTrue(totalBytes > usedBytes); return true; } }); assertTrue(results.first > results.second); }
Source:
public static File download(File targetDir, URL from) { if (targetDir == null) { targetDir = new File(DRONE_TARGET_DOWNLOADED_DIRECTORY); } String fromUrl = from.toString(); String fileName = fromUrl.substring(fromUrl.lastIndexOf("/") + 1); File target = new File(targetDir + File.separator + fileName); File downloaded = null; synchronized (log) { if (target.exists() && target.isFile()) { downloaded = target; } else if (!targetDir.exists()) { targetDir.mkdirs(); } if (downloaded == null) { for (int i = 0; i < 3; i++) { try { downloaded = runDownloadExecution(from, target.getAbsolutePath(), fileName).await(); } catch (ExecutionException ee) { System.err.print("ERROR: the downloading has failed. "); if (2 - i > 0) { System.err.println("Trying again - number of remaining attempts: " + (2 - i)); continue; } else { System.err.println("For more information see the stacktrace of an exception"); throw ee; } } break; } } } return downloaded; }

Target:
public static File download(File targetDir, URL from) { if (targetDir == null) { targetDir = new File(DRONE_TARGET_DOWNLOADED_DIRECTORY); } String fromUrl = from.toString(); String fileName = fromUrl.substring(fromUrl.lastIndexOf("/") + 1); File target = new File(targetDir + File.separator + fileName); File downloaded = null; synchronized (log) { if (target.exists() && target.isFile()) { downloaded = target; } else if (!targetDir.exists()) { targetDir.mkdirs(); } if (downloaded == null) { for (int i = 2; i >= 0; i--) { try { downloaded = runDownloadExecution(from, target.getAbsolutePath(), fileName).await(); } catch (ExecutionException ee) { System.err.print("ERROR: the downloading has failed. "); if (i != 0) { System.err.println("Trying again - number of remaining attempts: " + i); continue; } else { System.err.println("For more information see the stacktrace of an exception"); throw ee; } } break; } } } return downloaded; }
Source:
private void analyseData(final List<InstanceData> allData) { totalInstances = allData.size(); for (InstanceData instance : allData) { SurveyInstanceDto sid = instance.surveyInstanceDto; if (sid.getApprovedFlag() != null && sid.getApprovedFlag().equalsIgnoreCase("true")) { approvedInstances++; } Date cd = sid.getCollectionDate(); if (firstSubmission == null || cd.before(firstSubmission)) { firstSubmission = cd; } if (lastSubmission == null || cd.after(lastSubmission)) { lastSubmission = cd; } String u = sid.getSubmitterName(); if (instancesByUser.containsKey(u)) { instancesByUser.put(u, instancesByUser.get(u) + 1); } else { instancesByUser.put(u, Integer.valueOf(1)); } String dev = sid.getDeviceIdentifier(); if (instancesByDevice.containsKey(dev)) { instancesByDevice.put(dev, instancesByDevice.get(dev) + 1); } else { instancesByDevice.put(dev, Integer.valueOf(1)); } Long dur = sid.getSurveyalTime(); if (dur != null) { totalDuration += dur; maxDuration = Long.max(maxDuration, dur); minDuration = Long.min(minDuration, dur); } } }

Target:
private void analyseData(final List<InstanceData> allData) { totalInstances = allData.size(); for (InstanceData instance : allData) { SurveyInstanceDto sid = instance.surveyInstanceDto; if (sid.getApprovedFlag() != null && sid.getApprovedFlag().equalsIgnoreCase("true")) { approvedInstances++; } Date cd = sid.getCollectionDate(); if (firstSubmission == null || cd.before(firstSubmission)) { firstSubmission = cd; } if (lastSubmission == null || cd.after(lastSubmission)) { lastSubmission = cd; } String u = sid.getSubmitterName(); if (instancesByUser.containsKey(u)) { instancesByUser.put(u, instancesByUser.get(u) + 1); } else { instancesByUser.put(u, Integer.valueOf(1)); } String dev = sid.getDeviceIdentifier(); if (instancesByDevice.containsKey(dev)) { instancesByDevice.put(dev, instancesByDevice.get(dev) + 1); } else { instancesByDevice.put(dev, Integer.valueOf(1)); } Long durationSeconds = sid.getSurveyalTime(); if (durationSeconds != null) { totalDuration += durationSeconds; maxDuration = Long.max(maxDuration, durationSeconds); minDuration = Long.min(minDuration, durationSeconds); } } }
Source:
public PeriodicQueryStorageMetadata(String sparql, VariableOrder varOrder) { Preconditions.checkNotNull(sparql); Preconditions.checkNotNull(varOrder); this.sparql = sparql; this.varOrder = varOrder; }

Target:
public PeriodicQueryStorageMetadata(String sparql, VariableOrder varOrder) { this.sparql = Preconditions.checkNotNull(sparql); this.varOrder = Preconditions.checkNotNull(varOrder); }
Source:
public Users list() { if (isFiltered()) { return mapDbUserCollection(getBackendCollection(VdcQueryType.GetDbUserByUserId, new GetDbUserByUserIdParameters(getCurrent().get(VdcUser.class).getUserId()))); } else { return mapDbUserCollection(getBackendCollection(SearchType.DBUser, getSearchPattern())); } }

Target:
public Users list() { if (isFiltered()) { return mapDbUserCollection(getBackendCollection(VdcQueryType.GetAllDbUsers, new VdcQueryParametersBase())); } else { return mapDbUserCollection(getBackendCollection(SearchType.DBUser, getSearchPattern())); } }
Source:
public List<AmbryReplica> getReplicaIds() { return clusterManagerCallback.getReplicaIdsForPartition(this) .stream() .map(r -> (AmbryReplica) r) .collect(Collectors.toList()); }

Target:
public List<AmbryReplica> getReplicaIds() { return clusterManagerCallback.getReplicaIdsForPartition(this); }
Source:
private Set<PathFilterSet> findAssetPaths(final ResourceResolver resourceResolver, final String pagePath) { final Set<PathFilterSet> filters = new LinkedHashSet<>(); final Resource parentResource = resourceResolver.resolve(pagePath); if (isExcluded(this.pageExclusionPatterns, pagePath)) { if (pagePath.endsWith("/" + NameConstants.NN_CONTENT)) { return filters; } final PageManager pageManager = resourceResolver.adaptTo(PageManager.class); Page page = pageManager.getContainingPage(parentResource); excludedPages.add(page.getPath()); return filters; } final ValueMap parentResourceProperties = parentResource.getValueMap(); for (String key : parentResourceProperties.keySet()) { final Object value = parentResourceProperties.get(key); if (value instanceof String) { addFilter(filters, (String) value, resourceResolver); } else if (value instanceof String[]) { final String[] arrayValue = (String[]) value; for (String stringValue : arrayValue) { addFilter(filters, stringValue, resourceResolver); } } } final Iterator<Resource> children = parentResource.listChildren(); while (children.hasNext()) { final Resource child = children.next(); filters.addAll(findAssetPaths(resourceResolver, child.getPath())); } return filters; }

Target:
private Set<PathFilterSet> findAssetPaths(final ResourceResolver resourceResolver, final String pagePath) { final Set<PathFilterSet> filters = new LinkedHashSet<>(); final Resource parentResource = resourceResolver.resolve(pagePath); if (isExcluded(this.pageExclusionPatterns, pagePath)) { if (pagePath.endsWith("/" + NameConstants.NN_CONTENT)) { return filters; } final PageManager pageManager = resourceResolver.adaptTo(PageManager.class); Page page = pageManager.getContainingPage(parentResource); if (page != null) { excludedPages.add(page.getPath()); } else { excludedPages.add(parentResource.getPath()); } return filters; } final ValueMap parentResourceProperties = parentResource.getValueMap(); for (String key : parentResourceProperties.keySet()) { final Object value = parentResourceProperties.get(key); if (value instanceof String) { addFilter(filters, (String) value, resourceResolver); } else if (value instanceof String[]) { final String[] arrayValue = (String[]) value; for (String stringValue : arrayValue) { addFilter(filters, stringValue, resourceResolver); } } } final Iterator<Resource> children = parentResource.listChildren(); while (children.hasNext()) { final Resource child = children.next(); filters.addAll(findAssetPaths(resourceResolver, child.getPath())); } return filters; }
Source:
public void testFilledListEventMapping() { final DateTime timestamp = new DateTime(); final Integer eventCode = new Integer(10); final Integer eventCounter = new Integer(1); final Event event = new Event(timestamp, eventCode, eventCounter); final List<Event> listOriginal = new ArrayList<>(); listOriginal.add(event); final List<com.alliander.osgp.adapter.ws.schema.smartmetering.management.Event> listMapped = this.managementMapper .mapAsList(listOriginal, com.alliander.osgp.adapter.ws.schema.smartmetering.management.Event.class); assertNotNull(listMapped); assertNotNull(listMapped.get(0)); assertNotNull(listMapped.get(0).getEventCounter()); assertNotNull(listMapped.get(0).getEventType()); assertNotNull(listMapped.get(0).getTimestamp()); assertEquals(timestamp.getYear(), listMapped.get(0).getTimestamp().getYear()); assertEquals(timestamp.getMonthOfYear(), listMapped.get(0).getTimestamp().getMonth()); assertEquals(timestamp.getDayOfMonth(), listMapped.get(0).getTimestamp().getDay()); assertEquals(timestamp.getHourOfDay(), listMapped.get(0).getTimestamp().getHour()); assertEquals(timestamp.getMinuteOfHour(), listMapped.get(0).getTimestamp().getMinute()); assertEquals(timestamp.getSecondOfMinute(), listMapped.get(0).getTimestamp().getSecond()); assertEquals((int) eventCode, listMapped.get(0).getEventType().ordinal()); assertEquals(eventCounter, listMapped.get(0).getEventCounter()); }

Target:
public void testFilledListEventMapping() { final DateTime timestamp = new DateTime(); final Event event = new Event(timestamp, EVENTCODE, EVENTCOUNTER); final List<Event> listOriginal = new ArrayList<>(); listOriginal.add(event); final List<com.alliander.osgp.adapter.ws.schema.smartmetering.management.Event> listMapped = this.managementMapper .mapAsList(listOriginal, com.alliander.osgp.adapter.ws.schema.smartmetering.management.Event.class); assertNotNull(listMapped); assertNotNull(listMapped.get(0)); assertNotNull(listMapped.get(0).getEventCounter()); assertNotNull(listMapped.get(0).getEventType()); assertNotNull(listMapped.get(0).getTimestamp()); assertEquals(timestamp.getYear(), listMapped.get(0).getTimestamp().getYear()); assertEquals(timestamp.getMonthOfYear(), listMapped.get(0).getTimestamp().getMonth()); assertEquals(timestamp.getDayOfMonth(), listMapped.get(0).getTimestamp().getDay()); assertEquals(timestamp.getHourOfDay(), listMapped.get(0).getTimestamp().getHour()); assertEquals(timestamp.getMinuteOfHour(), listMapped.get(0).getTimestamp().getMinute()); assertEquals(timestamp.getSecondOfMinute(), listMapped.get(0).getTimestamp().getSecond()); assertEquals((int) EVENTCODE, listMapped.get(0).getEventType().ordinal()); assertEquals(EVENTCOUNTER, listMapped.get(0).getEventCounter()); }
Source:
private Long getRssUsageFrom(Process process) { Long rssUsage; try (InputStream inputStream = process.getInputStream(); Reader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) { rssUsage = Long.valueOf(bufferedReader.readLine()); } catch (Exception e) { throw new IllegalStateException("Error in JMX memory stats retrieval", e); } return rssUsage; }

Target:
private Long getRssUsageFrom(Process process) { Long rssUsage; try (InputStream inputStream = process.getInputStream(); Reader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) { rssUsage = Long.valueOf(bufferedReader.readLine()); } catch (Exception e) { throw new IllegalStateException("Error in rss stats retrieval", e); } return rssUsage; }
Source:
public void checkSearchingReferenceSetsReturnsWellFormed() throws AvroRemoteException { final SearchReferenceSetsRequest req = SearchReferenceSetsRequest.newBuilder().build(); final SearchReferenceSetsResponse resp = client.references.searchReferenceSets(req); final List<ReferenceSet> sets = resp.getReferenceSets(); sets.stream().forEach(rs -> assertThat(rs.getId()).isNotNull()); sets.stream().forEach(rs -> assertThat(rs.getMd5checksum()).isNotNull()); sets.stream().forEach(rs -> assertThat(rs.getSourceAccessions()).isNotNull()); }

Target:
public void checkSearchingReferenceSetsReturnsWellFormed() throws AvroRemoteException { final SearchReferenceSetsRequest req = SearchReferenceSetsRequest.newBuilder().build(); final SearchReferenceSetsResponse resp = client.references.searchReferenceSets(req); final List<ReferenceSet> sets = resp.getReferenceSets(); sets.stream().forEach(this::checkRefSetConstants); }
Source:
public void onFailure(Throwable caught) { close(); status.setContents("Monitoring is unavailable on this node. Maybe node was started with --disableMonitoring option.<br>"+ "Error message: "+ JSONUtils.getJsonErrorMessage(caught)); }

Target:
public void onFailure(Throwable caught) { close(); status.setContents("Monitoring is unavailable on this node. <br>" + "Either monitoring was disabled with the disableMonitoring option or an error occurred. <br>" + "More information are available inside the node logs."); }
Source:
protected void onConstructorFound(NewClassTree newClassTree) { Tree mTree = findParentMethod(newClassTree); if (mTree.is(Tree.Kind.METHOD)) { Optional<StatementTree> secureRandomOptional = findSecureRandomInMethod((MethodTree) mTree, returnSymbolOfArgument(newClassTree.arguments().get(0))); if (!secureRandomOptional.isPresent()) { reportIssue(newClassTree, "Use a dynamically-generated, random IV."); } } }

Target:
protected void onConstructorFound(NewClassTree newClassTree) { Tree mTree = findEnclosingMethod(newClassTree); if (mTree != null) { MethodInvocationVisitor mitVisit = new MethodInvocationVisitor(newClassTree); mTree.accept(mitVisit); if (!mitVisit.secureRandomFound) { reportIssue(newClassTree, "Use a dynamically-generated, random IV."); } } }
Source:
private List<SelectItem> populateDocumentTypes() { List<SelectItem> localDocumentTypeList = new ArrayList<SelectItem>(); try { Properties localDocumentTypeProperties = PropertyAccessor.getInstance().getProperties(NhincConstants.DOCUMET_TYPE_PROPERTY_FILE); for (Iterator<Entry<Object, Object>> it = localDocumentTypeProperties.entrySet().iterator(); it.hasNext();) { Entry<Object, Object> property = it.next(); localDocumentTypeList.add(new SelectItem((String) property.getKey(), (String) property.getValue())); } } catch (PropertyAccessException ex) { LOG.error("Not able to load the document types from the property file:" + ex.getMessage()); } return localDocumentTypeList; }

Target:
private List<SelectItem> populateDocumentTypes() { List<SelectItem> localDocumentTypeList = new ArrayList<SelectItem>(); try { Properties localDocumentTypeProperties = PropertyAccessor.getInstance().getProperties(NhincConstants.DOCUMENT_TYPE_PROPERTY_FILE); Iterator<Entry<Object, Object>> it = localDocumentTypeProperties.entrySet().iterator(); while (it.hasNext()) { Entry<Object, Object> property = it.next(); localDocumentTypeList.add(new SelectItem((String) property.getKey(), (String) property.getValue())); } } catch (PropertyAccessException ex) { LOG.error("Not able to load the document types from the property file:" + ex.getMessage()); } return localDocumentTypeList; }
Source:
public void execute(final OperationParams params) throws Exception { if (downloadDirectory == null) { final String homeDirectory = System.getProperty("geowave.home", "."); final Path path = Paths.get(homeDirectory, DEFAULT_DOWNLOAD_DIR); InstallGdal.main(new String[] {path.toString()}); } else { InstallGdal.main(new String[] {downloadDirectory}); } }

Target:
public void execute(final OperationParams params) throws Exception { if (downloadDirectory == null) { final String homeDirectory = System.getProperty("geowave.home", "."); final Path path = Paths.get(homeDirectory, DEFAULT_DOWNLOAD_DIR); downloadDirectory = path.toString(); } InstallGdal.main(new String[] {downloadDirectory}); }
Source:
void handleNoFollowsFlag(ByteBuf frame, SynchronousSink<ByteBuf> sink, int streamId) { ByteBuf header = removeHeader(streamId); if (header != null) { int maxReassemblySize = this.maxReassemblySize; if (maxReassemblySize != Integer.MAX_VALUE) { int currentPayloadSize = getMetadataSize(streamId) + getDataSize(streamId); if (currentPayloadSize + frame.readableBytes() - FrameHeaderCodec.size() > maxReassemblySize) { header.release(); frame.release(); cancelAssemble(streamId); throw new IllegalStateException("Reassembled payload went out of allowed size"); } } if (FrameHeaderCodec.hasMetadata(header)) { ByteBuf assembledFrame = assembleFrameWithMetadata(frame, streamId, header); sink.next(assembledFrame); } else { ByteBuf data = assembleData(frame, streamId); ByteBuf assembledFrame = FragmentationCodec.encode(allocator, header, data); sink.next(assembledFrame); } frame.release(); } else { sink.next(frame); } }

Target:
void handleNoFollowsFlag(ByteBuf frame, SynchronousSink<ByteBuf> sink, int streamId) { ByteBuf header = removeHeader(streamId); if (header != null) { int maxReassemblySize = this.maxInboundPayloadSize; if (maxReassemblySize != Integer.MAX_VALUE) { int currentPayloadSize = getMetadataSize(streamId) + getDataSize(streamId); if (currentPayloadSize + frame.readableBytes() - FrameHeaderCodec.size() > maxReassemblySize) { frame.release(); throw new IllegalStateException("Reassembled payload went out of allowed size"); } } if (FrameHeaderCodec.hasMetadata(header)) { ByteBuf assembledFrame = assembleFrameWithMetadata(frame, streamId, header); sink.next(assembledFrame); } else { ByteBuf data = assembleData(frame, streamId); ByteBuf assembledFrame = FragmentationCodec.encode(allocator, header, data); sink.next(assembledFrame); } frame.release(); } else { sink.next(frame); } }
Source:
public MockBoundedByteBufferReceive send(Send send) throws IOException { if (!shouldRespond) { return null; } ServerErrorCode serverError = hardError != null ? hardError : serverErrors.size() > 0 ? serverErrors.poll() : ServerErrorCode.No_Error; RequestOrResponseType type = ((RequestOrResponse) send).getRequestType(); RequestOrResponse response; switch (type) { case PutRequest: response = makePutResponse((PutRequest) send, serverError); break; case GetRequest: response = makeGetResponse((GetRequest) send, serverError); break; case DeleteRequest: response = makeDeleteResponse((DeleteRequest) send, serverError); break; default: throw new IOException("Unknown request type received"); } ByteBufferChannel channel = new ByteBufferChannel(ByteBuffer.allocate((int) response.sizeInBytes())); response.writeTo(channel); ByteBuffer payload = channel.getBuffer(); payload.flip(); payload.getLong(); return new MockBoundedByteBufferReceive(payload); }

Target:
public BoundedByteBufferReceive send(Send send) throws IOException { if (!shouldRespond) { return null; } ServerErrorCode serverError = hardError != null ? hardError : serverErrors.size() > 0 ? serverErrors.poll() : ServerErrorCode.No_Error; RequestOrResponseType type = ((RequestOrResponse) send).getRequestType(); RequestOrResponse response; switch (type) { case PutRequest: response = makePutResponse((PutRequest) send, serverError); break; case GetRequest: response = makeGetResponse((GetRequest) send, serverError); break; case DeleteRequest: response = makeDeleteResponse((DeleteRequest) send, serverError); break; default: throw new IOException("Unknown request type received"); } ByteBufferChannel channel = new ByteBufferChannel(ByteBuffer.allocate((int) response.sizeInBytes())); response.writeTo(channel); ByteBuffer payload = channel.getBuffer(); payload.flip(); BoundedByteBufferReceive boundedByteBufferReceive = new BoundedByteBufferReceive(); boundedByteBufferReceive.readFrom(Channels.newChannel(new ByteBufferInputStream(payload))); return boundedByteBufferReceive; }
Source:
public void testRequestFilters() throws Exception { TestReplicationListener listener = new TestReplicationListener(); PullReplication pullReplication = createPullReplication(); pullReplication.requestFilters.add(new InvalidJSONFilter()); Replicator replicator = ReplicatorFactory.oneway(pullReplication); replicator.getEventBus().register(listener); replicator.start(); while(replicator.getState() != Replicator.State.COMPLETE && replicator.getState() != Replicator.State.ERROR) { Thread.sleep(1000); } Assert.assertEquals(Replicator.State.ERROR, replicator.getState()); Assert.assertFalse(listener.finishCalled); Assert.assertTrue(listener.errorCalled); Assert.assertTrue(listener.exception instanceof CouchException); CouchException couchException = (CouchException) listener.exception; Assert.assertTrue(couchException.getStatusCode() == 400); Assert.assertEquals(couchException.getReason(), "invalid_json"); }

Target:
public void testRequestFilters() throws Exception { FilterCallCounter filterCallCounter = new FilterCallCounter(); PullReplication pullReplication = createPullReplication(); pullReplication.requestFilters.add(filterCallCounter); runReplicationUntilComplete(pullReplication); Assert.assertTrue(filterCallCounter.filterRequestTimesCalled >= 1); }
Source:
private Promise<UsersWorkspaceDto> getWorkspaceToStart() { final WorkspaceConfigDto workspaceConfigDto = factory.getWorkspace(); final String create = factory.getPolicies() == null ? "perClick" : factory.getPolicies().getCreate(); switch (create) { case "perUser": return getWorkspaceByConditionOrCreateNew(workspaceConfigDto, new Function<UsersWorkspaceDto, Boolean>() { @Override public Boolean apply(UsersWorkspaceDto existWs) throws FunctionException { return factory.getId().equals(existWs.getAttributes().get(FACTORY_ID_ATTRIBUTE)); } }); case "perAccount": return getWorkspaceByConditionOrCreateNew(workspaceConfigDto, new Function<UsersWorkspaceDto, Boolean>() { @Override public Boolean apply(UsersWorkspaceDto arg) throws FunctionException { return workspaceConfigDto.getName().equals(arg.getName()); } }); case "perClick": default: return getWorkspaceByConditionOrCreateNew(workspaceConfigDto, new Function<UsersWorkspaceDto, Boolean>() { @Override public Boolean apply(UsersWorkspaceDto arg) throws FunctionException { return false; } }); } }

Target:
private Promise<UsersWorkspaceDto> getWorkspaceToStart() { final WorkspaceConfigDto workspaceConfigDto = factory.getWorkspace(); final String policy = factory.getPolicies() == null ? "perClick" : factory.getPolicies().getCreate(); switch (policy) { case "perUser": return getWorkspaceByConditionOrCreateNew(workspaceConfigDto, new Function<UsersWorkspaceDto, Boolean>() { @Override public Boolean apply(UsersWorkspaceDto existWs) throws FunctionException { return factory.getId().equals(existWs.getAttributes().get(FACTORY_ID_ATTRIBUTE)); } }); case "perAccount": return getWorkspaceByConditionOrCreateNew(workspaceConfigDto, new Function<UsersWorkspaceDto, Boolean>() { @Override public Boolean apply(UsersWorkspaceDto arg) throws FunctionException { return workspaceConfigDto.getName().equals(arg.getName()); } }); case "perClick": default: return getWorkspaceByConditionOrCreateNew(workspaceConfigDto, new Function<UsersWorkspaceDto, Boolean>() { @Override public Boolean apply(UsersWorkspaceDto arg) throws FunctionException { return false; } }); } }