auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
void display(final ProjectDetail result) { final Project project = result.project; final Project.NameKey wildKey = Gerrit.getConfig().getWildProject(); final boolean isWild = wildKey.equals(project.getNameKey()); Project.NameKey parent = project.getParent(); if (parent == null) { parent = wildKey; } parentPanel.setVisible(!isWild); parentName.setTargetHistoryToken(Dispatcher.toProjectAdmin(parent, ProjectAdminScreen.ACCESS_TAB)); parentName.setText(parent.get()); rights.display(result.groups, result.rights, !result.canModifyData); }

Target:
void display(final ProjectDetail result) { final Project project = result.project; final Project.NameKey wildKey = Gerrit.getConfig().getWildProject(); final boolean isWild = wildKey.equals(project.getNameKey()); Project.NameKey parent = project.getParent(); if (parent == null) { parent = wildKey; } parentPanel.setVisible(!isWild); parentName.setTargetHistoryToken(Dispatcher.toProjectAdmin(parent, ProjectAdminScreen.ACCESS_TAB)); parentName.setText(parent.get()); rights.display(result.groups, result.rights); addPanel.setVisible(result.canModifyAccess); delRight.setVisible(rights.getCanDelete()); }
Source:
public String getExpectedFailureValue() { return content.substring(5, content.length()-1); }

Target:
public String getExpectedFailureValue() { return content.substring(INEQUALITY_START_TOKEN.length(), content.length()-INEQUALITY_END_TOKEN.length()); }
Source:
private static HiveTableDefinition.HiveTableDefinitionBuilder tableDefinitionBuilder(String fileFormat, Optional<String> recommendTableName, Optional<String> rowFormat) { String tableName = format("%s_hive_coercion", recommendTableName.orElse(fileFormat).toLowerCase(Locale.ENGLISH)); String floatToDoubleType = fileFormat.toLowerCase(Locale.ENGLISH).contains("parquet") ? "DOUBLE" : "FLOAT"; return HiveTableDefinition.builder(tableName) .setCreateTableDDLTemplate("" + "CREATE TABLE %NAME%(" + " tinyint_to_smallint TINYINT," + " tinyint_to_int TINYINT," + " tinyint_to_bigint TINYINT," + " smallint_to_int SMALLINT," + " smallint_to_bigint SMALLINT," + " int_to_bigint INT," + " bigint_to_varchar BIGINT," + " float_to_double " + floatToDoubleType + "," + " row_to_row STRUCT<keep: STRING, ti2si: TINYINT, si2int: SMALLINT, int2bi: INT, bi2vc: BIGINT>," + " list_to_list ARRAY<STRUCT<ti2int: TINYINT, si2bi: SMALLINT, bi2vc: BIGINT, remove: STRING>>," + " map_to_map MAP<TINYINT, STRUCT<ti2bi: TINYINT, int2bi: INT, float2double: " + floatToDoubleType + ">>" + ") " + "PARTITIONED BY (id BIGINT) " + rowFormat.map(s -> "ROW FORMAT " + s + " ").orElse(" ") + "STORED AS " + fileFormat); }

Target:
private static HiveTableDefinition.HiveTableDefinitionBuilder tableDefinitionBuilder(String fileFormat, Optional<String> recommendTableName, Optional<String> rowFormat) { String tableName = format("%s_hive_coercion", recommendTableName.orElse(fileFormat).toLowerCase(Locale.ENGLISH)); String floatToDoubleType = fileFormat.toLowerCase(Locale.ENGLISH).contains("parquet") ? "DOUBLE" : "FLOAT"; return HiveTableDefinition.builder(tableName) .setCreateTableDDLTemplate("" + "CREATE TABLE %NAME%(" + " tinyint_to_smallint TINYINT," + " tinyint_to_int TINYINT," + " tinyint_to_bigint TINYINT," + " smallint_to_int SMALLINT," + " smallint_to_bigint SMALLINT," + " int_to_bigint INT," + " bigint_to_varchar BIGINT," + " float_to_double " + floatToDoubleType + "," + " row_to_row STRUCT<keep: STRING, ti2si: TINYINT, si2int: SMALLINT, int2bi: INT, bi2vc: BIGINT>," + " list_to_list ARRAY<STRUCT<ti2int: TINYINT, si2bi: SMALLINT, bi2vc: BIGINT, remove: STRING>>," + " map_to_map MAP<TINYINT, STRUCT<ti2bi: TINYINT, int2bi: INT, float2double: " + floatToDoubleType + ">>" + ") " + "PARTITIONED BY (id BIGINT) " + rowFormat.map(s -> format("ROW FORMAT %s ", s)).orElse("") + "STORED AS " + fileFormat); }
Source:
public void builderWithThreshold() { Registry r = newRegistry(); PercentileDistributionSummary t = PercentileDistributionSummary.builder(r) .withName("test") .withThreshold(100_000) .build(); checkPercentiles(t, 25); }

Target:
public void builderWithThreshold() { Registry r = newRegistry(); PercentileDistributionSummary t = PercentileDistributionSummary.builder(r) .withName("test") .withRange(25_000, 100_000) .build(); checkPercentiles(t, 25); }
Source:
BuilderExecutionSettings() { myEmbeddedGradleDaemonEnabled = SystemProperties.getBooleanProperty(BuildProcessJvmArgs.USE_EMBEDDED_GRADLE_DAEMON, false); myGradleDaemonMaxIdleTimeInMs = SystemProperties.getIntProperty(BuildProcessJvmArgs.GRADLE_DAEMON_MAX_IDLE_TIME_IN_MS, -1); myGradleDaemonVmOptions = getJvmOptions(); myGradleHomeDir = findDir(BuildProcessJvmArgs.GRADLE_HOME_DIR_PATH, "Gradle home"); myGradleServiceDir = findDir(BuildProcessJvmArgs.GRADLE_SERVICE_DIR_PATH, "Gradle service"); myJavaHomeDir = findDir(BuildProcessJvmArgs.GRADLE_JAVA_HOME_DIR_PATH, "Java home"); myProjectDir = findProjectRootDir(); String buildActionName = System.getProperty(BuildProcessJvmArgs.BUILD_ACTION); myBuildAction = BuildAction.valueOf(buildActionName); myVerboseLoggingEnabled = SystemProperties.getBooleanProperty(BuildProcessJvmArgs.USE_GRADLE_VERBOSE_LOGGING, false); myParallelBuild = SystemProperties.getBooleanProperty(GlobalOptions.COMPILE_PARALLEL_OPTION, false); }

Target:
BuilderExecutionSettings() { myEmbeddedGradleDaemonEnabled = SystemProperties.getBooleanProperty(BuildProcessJvmArgs.USE_EMBEDDED_GRADLE_DAEMON, false); myGradleDaemonMaxIdleTimeInMs = SystemProperties.getIntProperty(BuildProcessJvmArgs.GRADLE_DAEMON_MAX_IDLE_TIME_IN_MS, -1); myGradleDaemonVmOptions = getJvmOptions(); myGradleHomeDir = findDir(BuildProcessJvmArgs.GRADLE_HOME_DIR_PATH, "Gradle home"); myGradleServiceDir = findDir(BuildProcessJvmArgs.GRADLE_SERVICE_DIR_PATH, "Gradle service"); myJavaHomeDir = findDir(BuildProcessJvmArgs.GRADLE_JAVA_HOME_DIR_PATH, "Java home"); myProjectDir = findProjectRootDir(); String buildActionName = System.getProperty(BuildProcessJvmArgs.BUILD_ACTION); myBuildMode = Strings.isNullOrEmpty(buildActionName) ? BuildMode.DEFAULT_BUILD_MODE : BuildMode.valueOf(buildActionName); myVerboseLoggingEnabled = SystemProperties.getBooleanProperty(BuildProcessJvmArgs.USE_GRADLE_VERBOSE_LOGGING, false); myParallelBuild = SystemProperties.getBooleanProperty(GlobalOptions.COMPILE_PARALLEL_OPTION, false); }
Source:
protected void copyAttachments(SQLDatabase db, long parentSequence, long newSequence) throws AttachmentException { Cursor c = null; try { c = db.rawQuery(SQL_ATTACHMENTS_SELECT_ALL, new String[]{String.valueOf(parentSequence)}); copyCursorValuesToNewSequence(db, c, newSequence); } catch (SQLException e){ throw new AttachmentException("Failed to copy attachments",e); }finally { DatabaseUtils.closeCursorQuietly(c); } }

Target:
protected void copyAttachments(SQLDatabase db, long parentSequence, long newSequence) throws DatastoreException { Cursor c = null; try { c = db.rawQuery(SQL_ATTACHMENTS_SELECT_ALL, new String[]{String.valueOf(parentSequence)}); copyCursorValuesToNewSequence(db, c, newSequence); } catch (SQLException e){ throw new DatastoreException("Failed to copy attachments", e); }finally { DatabaseUtils.closeCursorQuietly(c); } }
Source:
public void updateTest() { String preupdateString = "preupdate"; String user0 = "user0"; String user1 = "user1"; String user2 = "user2"; OPartitionedDatabasePool pool = orientDBClient.getDatabasePool(); ODatabaseDocumentTx db = pool.acquire(); try { for (String key : Arrays.asList(user0, user1, user2)) { ODocument doc = new ODocument(CLASS); for (int i = 0; i < NUM_FIELDS; i++) { doc.field(FIELD_PREFIX + i, preupdateString); } doc.save(); ODictionary<ORecord> dictionary = db.getDictionary(); dictionary.put(key, doc); } } finally { db.close(); } HashMap<String, ByteIterator> updateMap = new HashMap<>(); for (int i = 0; i < NUM_FIELDS; i++) { updateMap.put(FIELD_PREFIX + i, new StringByteIterator(buildDeterministicValue(user1, FIELD_PREFIX + i))); } orientDBClient.update(CLASS, user1, updateMap); db = pool.acquire(); try { ODictionary<ORecord> dictionary = db.getDictionary(); ODocument result = dictionary.get(user0); for (int i = 0; i < NUM_FIELDS; i++) { assertEquals("Assert first row fields contain preupdateString", result.field(FIELD_PREFIX + i), preupdateString); } result = dictionary.get(user1); for (int i = 0; i < NUM_FIELDS; i++) { assertEquals("Assert updated row fields are correct", result.field(FIELD_PREFIX + i), updateMap.get(FIELD_PREFIX + i).toString()); } result = dictionary.get(user2); for (int i = 0; i < NUM_FIELDS; i++) { assertEquals("Assert third row fields contain preupdateString", result.field(FIELD_PREFIX + i), preupdateString); } } finally { db.close(); } }

Target:
public void updateTest() { String preupdateString = "preupdate"; String user0 = "user0"; String user1 = "user1"; String user2 = "user2"; OPartitionedDatabasePool pool = orientDBClient.getDatabasePool(); try(ODatabaseDocumentTx db = pool.acquire()) { for (String key : Arrays.asList(user0, user1, user2)) { ODocument doc = new ODocument(CLASS); for (int i = 0; i < NUM_FIELDS; i++) { doc.field(FIELD_PREFIX + i, preupdateString); } doc.save(); ODictionary<ORecord> dictionary = db.getDictionary(); dictionary.put(key, doc); } } HashMap<String, ByteIterator> updateMap = new HashMap<>(); for (int i = 0; i < NUM_FIELDS; i++) { updateMap.put(FIELD_PREFIX + i, new StringByteIterator(buildDeterministicValue(user1, FIELD_PREFIX + i))); } orientDBClient.update(CLASS, user1, updateMap); try(ODatabaseDocumentTx db = pool.acquire()) { ODictionary<ORecord> dictionary = db.getDictionary(); ODocument result = dictionary.get(user0); for (int i = 0; i < NUM_FIELDS; i++) { assertEquals("Assert first row fields contain preupdateString", result.field(FIELD_PREFIX + i), preupdateString); } result = dictionary.get(user1); for (int i = 0; i < NUM_FIELDS; i++) { assertEquals("Assert updated row fields are correct", result.field(FIELD_PREFIX + i), updateMap.get(FIELD_PREFIX + i).toString()); } result = dictionary.get(user2); for (int i = 0; i < NUM_FIELDS; i++) { assertEquals("Assert third row fields contain preupdateString", result.field(FIELD_PREFIX + i), preupdateString); } } }
Source:
public static By getFindElementType(String locator) { logger.entering(locator); String tempLocator = locator; Preconditions.checkArgument(StringUtils.isNotBlank(tempLocator), INVALID_LOCATOR_ERR_MSG); By valueToReturn = null; tempLocator = tempLocator.trim(); int typeDelimiterIndex = tempLocator.indexOf('='); String locatorType = typeDelimiterIndex != -1 ? tempLocator.substring(0, typeDelimiterIndex) : tempLocator; switch (locatorType) { case "id": valueToReturn = By.id(tempLocator.substring(typeDelimiterIndex + 1)); break; case "name": valueToReturn = By.name(tempLocator.substring(typeDelimiterIndex + 1)); break; case "link": valueToReturn = By.linkText(tempLocator.substring(typeDelimiterIndex + 1)); break; case "xpath": valueToReturn = By.xpath(tempLocator.substring(typeDelimiterIndex + 1)); break; case "css": valueToReturn = By.cssSelector(tempLocator.substring(typeDelimiterIndex + 1)); break; case "classname": valueToReturn = By.className(tempLocator.substring(typeDelimiterIndex + 1)); break; default: if (tempLocator.startsWith("/") || tempLocator.startsWith("./")) { valueToReturn = By.xpath(tempLocator); break; } valueToReturn = new ByIdOrName(tempLocator); } if (logger.isLoggable(Level.FINE)) { String msg = valueToReturn.getClass().getSimpleName() + " will be the location strategy that will be used for locating " + tempLocator; logger.log(Level.FINE, msg); } logger.exiting(valueToReturn); return valueToReturn; }

Target:
public static By getFindElementType(String locator) { logger.entering(locator); Preconditions.checkArgument(StringUtils.isNotBlank(locator), INVALID_LOCATOR_ERR_MSG); By valueToReturn = null; String seleniumLocator = locator.trim(); int typeDelimiterIndex = seleniumLocator.indexOf('='); String locatorType = typeDelimiterIndex != -1 ? seleniumLocator.substring(0, typeDelimiterIndex) : seleniumLocator; switch (locatorType) { case "id": valueToReturn = By.id(seleniumLocator.substring(typeDelimiterIndex + 1)); break; case "name": valueToReturn = By.name(seleniumLocator.substring(typeDelimiterIndex + 1)); break; case "link": valueToReturn = By.linkText(seleniumLocator.substring(typeDelimiterIndex + 1)); break; case "xpath": valueToReturn = By.xpath(seleniumLocator.substring(typeDelimiterIndex + 1)); break; case "css": valueToReturn = By.cssSelector(seleniumLocator.substring(typeDelimiterIndex + 1)); break; case "classname": valueToReturn = By.className(seleniumLocator.substring(typeDelimiterIndex + 1)); break; default: if (seleniumLocator.startsWith("/") || seleniumLocator.startsWith("./")) { valueToReturn = By.xpath(seleniumLocator); break; } valueToReturn = new ByIdOrName(seleniumLocator); } if (logger.isLoggable(Level.FINE)) { String msg = valueToReturn.getClass().getSimpleName() + " will be the location strategy that will be used for locating " + seleniumLocator; logger.log(Level.FINE, msg); } logger.exiting(valueToReturn); return valueToReturn; }
Source:
public Response removeCustomizedStateAggregationConfig(@PathParam("clusterId") String clusterId) { HelixZkClient zkClient = getHelixZkClient(); if (!ZKUtil.isClusterSetup(clusterId, zkClient)) { return notFound("Cluster is not properly setup!"); } HelixAdmin admin = getHelixAdmin(); try { admin.removeCustomizedStateAggregationConfig(clusterId); } catch (HelixException ex) { _logger.error("Error in removing CustomizedStateAggregationConfig to cluster: " + clusterId, ex); return badRequest(ex.getMessage()); } catch (Exception ex) { _logger.error("Cannot remove CustomizedStateAggregationConfig to cluster: " + clusterId, ex); return serverError(ex); } return OK(); }

Target:
public Response removeCustomizedStateAggregationConfig(@PathParam("clusterId") String clusterId) { if (!doesClusterExist(clusterId)) { return notFound(String.format("Cluster %s does not exist", clusterId)); } HelixAdmin admin = getHelixAdmin(); try { admin.removeCustomizedStateAggregationConfig(clusterId); } catch (Exception ex) { _logger.error( "Cannot remove CustomizedStateAggregationConfig from cluster: {}, Exception: {}", clusterId, ex); return serverError(ex); } return OK(); }
Source:
public void createConsole(String additionalInitialComands) { Display.getDefault().syncExec(new Runnable() { public void run() { IConsoleManager manager = ConsolePlugin.getDefault().getConsoleManager(); boolean continueWithNewConsole = true; if (manager.getConsoles().length >= 1 && Consoles.showDialog) { continueWithNewConsole = MessageDialog.openQuestion(Display.getDefault().getActiveShell(), "Duplicate console", "Scripting console already Exists\nDo you still want to proceed with a new one?"); } if (continueWithNewConsole) { try { createConsole(createGeniePydevInterpreter(), additionalInitialComands); } catch (Exception e) { LOG.error(e); } } } }); Job.getJobManager().addJobChangeListener(JOB_CHANGE_LISTENER); }

Target:
public void createConsole(String additionalInitialComands) { Display.getDefault().syncExec(new Runnable() { public void run() { IConsoleManager manager = ConsolePlugin.getDefault().getConsoleManager(); boolean continueWithNewConsole = true; if (manager.getConsoles().length >= 1) { continueWithNewConsole = MessageDialog.openQuestion(Display.getDefault().getActiveShell(), "Duplicate console", "Scripting Console already exists. New Console will open on top of the current one. " + "Scripts running on current console will still run in the background.\n\n" + "You can switch between consoles using \"Display Selected Console\"" + " button. To terminate a console please click on the red icon from the menu bar.\n\n" + "Do you still want to proceed with a new Console?"); } if (continueWithNewConsole) { try { createConsole(createGeniePydevInterpreter(), additionalInitialComands); } catch (Exception e) { LOG.error(e); } } } }); Job.getJobManager().addJobChangeListener(JOB_CHANGE_LISTENER); }
Source:
public FormField findFormField(String fieldName) { return fields.stream() .filter(field -> field.getFieldName().equals(fieldName) || fieldName.equals(field.getFieldBinding())) .findFirst() .orElse(null); }

Target:
public FormField findFormField(String fieldName) { return fields.stream() .filter(field -> Objects.equals(field.getFieldName(), fieldName) || Objects.equals(fieldName, field.getFieldBinding())) .findFirst() .orElse(null); }
Source:
public static IStatus exportXmlFile(String from, String to) { File fromFile = getXmlFilesPath().addTrailingSeparator().append(from + XML_EXTENSION).toFile(); if (!fromFile.exists()) { Activator.logError("Failed to find XML analysis file " + fromFile.getName()); return Status.CANCEL_STATUS; } File toFile = new File(to); try { if (!toFile.exists()) { toFile.createNewFile(); } } catch (IOException e) { String error = Messages.XmlUtils_ErrorCopyingFile; Activator.logError(error, e); return new Status(IStatus.ERROR, Activator.PLUGIN_ID, error, e); } try (FileInputStream fis = new FileInputStream(fromFile); FileOutputStream fos = new FileOutputStream(toFile); FileChannel source = fis.getChannel(); FileChannel destination = fos.getChannel();) { destination.transferFrom(source, 0, source.size()); } catch (IOException e) { String error = Messages.XmlUtils_ErrorCopyingFile; Activator.logError(error, e); return new Status(IStatus.ERROR, Activator.PLUGIN_ID, error, e); } return Status.OK_STATUS; }

Target:
public static IStatus exportXmlFile(String from, String to) { File fromFile = getXmlFilesPath().addTrailingSeparator().append(from).toFile(); if (!fromFile.exists()) { Activator.logError("Failed to find XML analysis file " + fromFile.getName()); return Status.CANCEL_STATUS; } File toFile = new File(to); return copyXmlFile(fromFile, toFile); }
Source:
public String toString() { return "{" + "\"customerId\":" + customerId + ",\"name\":\"" + name + "\"" + ",\"age\":" + age + ",\"address\":\"" + address + "\"" + '}'; }

Target:
public String toString() { return "CustomerInfo{" + "customerId=" + customerId + ", name='" + name + '\'' + ", age=" + age + ", address='" + address + '\'' + '}'; }
Source:
public void execute() throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { CallContext.current().setEventDetails("Router Id: " + this._uuidMgr.getUuid(VirtualMachine.class, getId())); VirtualRouter router = _routerService.findRouter(getId()); Map<String, String> result = null; if (router == null || router.getRole() != VirtualRouter.Role.VIRTUAL_ROUTER) { throw new InvalidParameterValueException("Can't find router by id"); } else { result = _routerService.getRouterHealthCheckResults(getId(), shouldPerformFreshChecks()); } if (result != null) { DomainRouterHealthCheckResultsResponse routerResponse = _responseGenerator.createHealthCheckResponse(router, result); routerResponse.setResponseName(getCommandName()); setResponseObject(routerResponse); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to start router"); } }

Target:
public void execute() throws ResourceUnavailableException, InvalidParameterValueException, ServerApiException { CallContext.current().setEventDetails("Router Id: " + this._uuidMgr.getUuid(VirtualMachine.class, getRouterId())); VirtualRouter router = _routerService.findRouter(getRouterId()); if (router == null || router.getRole() != VirtualRouter.Role.VIRTUAL_ROUTER) { throw new InvalidParameterValueException("Can't find router by routerId"); } try { List<RouterHealthCheckResultResponse> healthChecks = _queryService.listRouterHealthChecks(this); RouterHealthCheckResultsListResponse routerResponse = new RouterHealthCheckResultsListResponse(); routerResponse.setRouterId(router.getUuid()); routerResponse.setHealthChecks(healthChecks); routerResponse.setObjectName("routerhealthchecks"); routerResponse.setResponseName(getCommandName()); setResponseObject(routerResponse); } catch (CloudRuntimeException ex){ ex.printStackTrace(); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to execute command due to exception: " + ex.getLocalizedMessage()); } }
Source:
Set<Status> ignoredStates() { return EnumSet.of( Status.REQUESTED, Status.CREATE_IN_PROGRESS, Status.UPDATE_IN_PROGRESS, Status.UPDATE_REQUESTED, Status.STOP_REQUESTED, Status.START_REQUESTED, Status.STOP_IN_PROGRESS, Status.START_IN_PROGRESS, Status.WAIT_FOR_SYNC, Status.MAINTENANCE_MODE_ENABLED, Status.EXTERNAL_DATABASE_CREATION_IN_PROGRESS, Status.BACKUP_IN_PROGRESS, Status.BACKUP_FINISHED, Status.BACKUP_FAILED, Status.RESTORE_IN_PROGRESS, Status.RESTORE_FINISHED, Status.RESTORE_FAILED ); }

Target:
Set<Status> ignoredStates() { return EnumSet.of( Status.REQUESTED, Status.CREATE_IN_PROGRESS, Status.UPDATE_IN_PROGRESS, Status.UPDATE_REQUESTED, Status.STOP_REQUESTED, Status.START_REQUESTED, Status.STOP_IN_PROGRESS, Status.START_IN_PROGRESS, Status.WAIT_FOR_SYNC, Status.MAINTENANCE_MODE_ENABLED, Status.EXTERNAL_DATABASE_CREATION_IN_PROGRESS, Status.BACKUP_IN_PROGRESS, Status.BACKUP_FAILED, Status.RESTORE_IN_PROGRESS, Status.RESTORE_FAILED ); }
Source:
private static void getLatency(Long latency) { Long innerLatency; if (latency != (long) minimum) { innerLatency = latency; } else { innerLatency = getDelayFromXml(); } try { TimeUnit.MILLISECONDS.sleep(innerLatency); } catch (InterruptedException e) { log.error("failed to to run getLatency error is:{}", e); } }

Target:
private static void getLatency(Long latency) { Long innerLatency; if (latency != minimum) { innerLatency = latency; } else { innerLatency = getDelayFromXml(); } try { TimeUnit.MILLISECONDS.sleep(innerLatency); } catch (InterruptedException e) { log.error("failed to to run getLatency error is:{}", e); } }
Source:
public static FakePlayer getFakePlayer(World world){ val dimId = world.provider.getDimension(); if(fakePlayers.containsKey(dimId)) return fakePlayers.get(dimId); if(world instanceof WorldServer){ FakePlayerLP fp = new FakePlayerLP((WorldServer) world); fakePlayers.put(dimId, fp); return fp; } if(world instanceof WorldClient){ FakePlayerLP fp = new FakePlayerLP(FMLCommonHandler.instance().getMinecraftServerInstance().getWorld(dimId)); fakePlayers.put(dimId, fp); return fp; } return null; }

Target:
public static FakePlayer getFakePlayer(World world) { int dimId = world.provider.getDimension(); if (fakePlayers.containsKey(dimId)) return fakePlayers.get(dimId); if (world instanceof WorldServer) { FakePlayerLP fp = new FakePlayerLP((WorldServer) world); fakePlayers.put(dimId, fp); return fp; } if (world instanceof WorldClient) { FakePlayerLP fp = new FakePlayerLP(FMLCommonHandler.instance().getMinecraftServerInstance().getWorld(dimId)); fakePlayers.put(dimId, fp); return fp; } return null; }
Source:
public void configurePersister(XStreamPersister persister, XStreamMessageConverter converter) { persister.setCallback(new XStreamPersister.Callback() { @Override protected Class<LayerGroupInfo> getObjectClass() { return LayerGroupInfo.class; } @Override protected CatalogInfo getCatalogObject() { Map<String, String> uriTemplateVars = (Map<String, String>) RequestContextHolder.getRequestAttributes().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST); String workspace = uriTemplateVars.get("workspaceName"); String layerGroup = uriTemplateVars.get("layerGroupName"); if (layerGroup == null) { return null; } return catalog.getLayerGroupByName(workspace, layerGroup); } @Override protected void postEncodeReference(Object obj, String ref, String prefix, HierarchicalStreamWriter writer, MarshallingContext context) { if ( obj instanceof StyleInfo ) { StringBuilder link = new StringBuilder(); if (prefix != null) { link.append("/workspaces/").append(converter.encode(prefix)); } link.append("/styles/").append(converter.encode(ref)); converter.encodeLink(link.toString(), writer); } if ( obj instanceof LayerInfo ) { converter.encodeLink("/layers/" + converter.encode(ref), writer); } else if ( obj instanceof LayerGroupInfo) { converter.encodeLink("/layergroups/" + converter.encode(ref), writer); } } }); }

Target:
public void configurePersister(XStreamPersister persister, XStreamMessageConverter converter) { persister.setCallback(new XStreamPersister.Callback() { @Override protected Class<LayerGroupInfo> getObjectClass() { return LayerGroupInfo.class; } @Override protected CatalogInfo getCatalogObject() { Map<String, String> uriTemplateVars = (Map<String, String>) RequestContextHolder.getRequestAttributes().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST); String workspace = uriTemplateVars.get("workspaceName"); String layerGroup = uriTemplateVars.get("layerGroupName"); if (layerGroup == null) { return null; } return catalog.getLayerGroupByName(workspace, layerGroup); } @Override protected void postEncodeReference(Object obj, String ref, String prefix, HierarchicalStreamWriter writer, MarshallingContext context) { if ( obj instanceof StyleInfo ) { StringBuilder link = new StringBuilder(); if (prefix != null) { link.append("/workspaces/").append(converter.encode(prefix)); } link.append("/styles/").append(converter.encode(ref)); converter.encodeLink(link.toString(), writer); } if ( obj instanceof LayerInfo ) { converter.encodeLink("/layers/" + converter.encode(ref), writer); } else if ( obj instanceof LayerGroupInfo) { LayerGroupInfo lg = (LayerGroupInfo) obj; if (lg.getWorkspace() != null) { converter.encodeLink("/workspaces/"+lg.getWorkspace().getName()+"/layergroups/" + converter.encode(ref), writer); } else { converter.encodeLink("/layergroups/" + converter.encode(ref), writer); } } } }); }
Source:
private File createWindowsSshAskpass(SSHUserPrivateKey sshUser) throws IOException { File ssh = File.createTempFile("pass", ".bat"); PrintWriter w = null; try { w = new PrintWriter(ssh); w.println("@echo off"); w.println("echo " + Secret.toString(sshUser.getPassphrase())); w.flush(); } finally { if (w != null) { w.close(); } } ssh.setExecutable(true); return ssh; }

Target:
private File createWindowsSshAskpass(SSHUserPrivateKey sshUser) throws IOException { File ssh = File.createTempFile("pass", ".bat"); try (PrintWriter w = new PrintWriter(ssh, Charset.defaultCharset().toString())) { w.println("@echo off"); w.println("echo " + Secret.toString(sshUser.getPassphrase())); w.flush(); } ssh.setExecutable(true); return ssh; }
Source:
void setState(ParseObject.State newState) { State.Builder builder = new State.Builder(getState()); builder.apply(newState); super.setState(builder.build()); }

Target:
void setState(ParseObject.State newState) { if (isCurrentUser() && getSessionToken() != null && newState.get("sessionToken") == null) { newState = newState.newBuilder().put("sessionToken", getSessionToken()).build(); } super.setState(newState); }
Source:
public static MultiMap<Type, TypedClassOperation> readOperations(@Nullable Path file) throws OperationParseException { return readOperations(file, true); }

Target:
public static MultiMap<Type, TypedClassOperation> readOperations(@Nullable Path file) throws OperationParseException { return readOperations(file, false); }
Source:
public ITmfTrace getTrace() { for (ITmfTrace trace : TmfTraceManager.getInstance().getOpenedTraces()) { for (ITmfTrace t : TmfTraceManager.getTraceSetWithExperiment(trace)) { if (getResource().equals(t.getResource()) && (t instanceof TmfExperiment)) { return t; } } } return null; }

Target:
public ITmfTrace getTrace() { for (ITmfTrace trace : TmfTraceManager.getInstance().getOpenedTraces()) { if (getResource().equals(trace.getResource()) && (trace instanceof TmfExperiment)) { return trace; } } return null; }
Source:
private ArrayList<Element> readXML() { try { Document templatesXML = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(getClass().getResourceAsStream("/latexstudio/editor/resources/templates.xml")); Element rootElement = templatesXML.getDocumentElement(); NodeList templatesNodeList = rootElement.getChildNodes(); ArrayList<Element> templates = new ArrayList<Element>(); for (int i = 0; i < templatesNodeList.getLength(); i++) { Node node = templatesNodeList.item(i); if (node instanceof Element) { templates.add((Element) node); } } return templates; } catch (IOException e) { } catch (SAXException e) { } catch (ParserConfigurationException e) { } return null; }

Target:
private ArrayList<Element> readXML() { try { Document templatesXML = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(getClass().getResourceAsStream(ApplicationUtils.pathToTemplatesFile)); Element rootElement = templatesXML.getDocumentElement(); NodeList templatesNodeList = rootElement.getChildNodes(); ArrayList<Element> templates = new ArrayList<Element>(); for (int i = 0; i < templatesNodeList.getLength(); i++) { Node node = templatesNodeList.item(i); if (node instanceof Element) { templates.add((Element) node); } } return templates; } catch (IOException | SAXException | ParserConfigurationException e) { LOGGER.log("Templates data couldn't be read."); e.printStackTrace(); } return null; }
Source:
private static String readLine(BufferedReader in) { String result = null; try { result = in.readLine(); } catch (Exception e) { logger.error("Can't read from " + testingFile + ": " + e); System.exit(1); } return result; }

Target:
private static String readLine(BufferedReader in) { String result = null; try { result = in.readLine(); } catch (Exception e) { System.err.println("Can't read from " + testingFile + ": " + e); System.exit(1); } return result; }
Source:
protected String tryLock(String key) { log.debug("Trying to lock '{}'", key); long deadline = System.nanoTime() + duration.toNanos(); long ttl = duration.multipliedBy(TTL_MULTIPLIER).toSeconds(); do { String lockInfo = "node=" + nodeId + " time=" + Instant.now(); if (kvStore.compareAndSet(key, null, lockInfo, ttl)) { log.debug("Lock '{}' acquired after {}ms", () -> key, () -> (System.nanoTime() - (deadline - duration.toNanos())) / 1_000_000); return lockInfo; } log.debug(" Sleeping on busy lock '{}' for {}ms", () -> key, () -> pollDelay.toMillis()); try { Thread.sleep(pollDelay.toMillis()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeServiceException(e); } } while (System.nanoTime() < deadline); log.debug("Failed to acquire lock '{}' after {}s", () -> key, () -> duration.toSeconds()); return null; }

Target:
protected String tryLock(String key) { log.debug("Trying to lock '{}'", key); long deadline = System.nanoTime() + duration.toNanos(); long ttl = duration.multipliedBy(TTL_MULTIPLIER).toSeconds(); do { String lockInfo = "node=" + nodeId + " time=" + Instant.now(); if (kvStore.compareAndSet(key, null, lockInfo, ttl)) { log.debug("Lock '{}' acquired after {}ms", () -> key, () -> (System.nanoTime() - (deadline - duration.toNanos())) / 1_000_000); return lockInfo; } log.debug(" Sleeping on busy lock '{}' for {}ms", () -> key, pollDelay::toMillis); try { Thread.sleep(pollDelay.toMillis()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeServiceException(e); } } while (System.nanoTime() < deadline); log.debug("Failed to acquire lock '{}' after {}s", () -> key, duration::toSeconds); return null; }
Source:
public void setCpuMaxDeviation(final Double maxCpuUsagePercentage, final Double totalCpuUsedPercentage, final Long totalHosts) { if (maxCpuUsagePercentage != null && totalCpuUsedPercentage != null && totalHosts != null && totalHosts != 0) { final Double averageCpuUsagePercentage = totalCpuUsedPercentage / totalHosts; this.cpuMaxDeviation = String.format("%.2f%%", (maxCpuUsagePercentage - averageCpuUsagePercentage) * 1.0 / averageCpuUsagePercentage); } }

Target:
public void setCpuMaxDeviation(final Double maxCpuUsagePercentage, final Double totalCpuUsedPercentage, final Long totalHosts) { if (maxCpuUsagePercentage != null && totalCpuUsedPercentage != null && totalHosts != null && totalHosts != 0) { final Double averageCpuUsagePercentage = totalCpuUsedPercentage / totalHosts; this.cpuMaxDeviation = String.format("%.2f%%", (maxCpuUsagePercentage - averageCpuUsagePercentage) / averageCpuUsagePercentage); } }
Source:
private void respawnPlayer(EntityRef clientEntity) { ClientComponent client = clientEntity.getComponent(ClientComponent.class); EntityRef playerCharacter = client.character; LocationComponent location = clientEntity.getComponent(LocationComponent.class); PlayerFactory playerFactory = new PlayerFactory(entityManager, worldProvider); Vector3f spawnPosition = playerFactory.findSpawnPositionFromLocationComponent(location); location.setWorldPosition(spawnPosition); clientEntity.saveComponent(location); AliveCharacterComponent aliveCharacterComponent = new AliveCharacterComponent(); playerCharacter.addComponent(aliveCharacterComponent); playerCharacter.send(new CharacterTeleportEvent(spawnPosition)); logger.debug("Re-spawing player at: {}", spawnPosition); Client clientListener = networkSystem.getOwner(clientEntity); Vector3i distance = clientListener.getViewDistance().getChunkDistance(); updateRelevanceEntity(clientEntity, distance); playerCharacter.send(new OnPlayerRespawnedEvent()); }

Target:
private void respawnPlayer(EntityRef clientEntity) { ClientComponent client = clientEntity.getComponent(ClientComponent.class); EntityRef playerCharacter = client.character; LocationComponent location = clientEntity.getComponent(LocationComponent.class); PlayerFactory playerFactory = new PlayerFactory(entityManager, worldProvider); Vector3f spawnPosition = playerFactory.findSpawnPositionFromLocationComponent(location); location.setWorldPosition(spawnPosition); clientEntity.saveComponent(location); playerCharacter.addComponent(new AliveCharacterComponent()); playerCharacter.send(new CharacterTeleportEvent(spawnPosition)); logger.debug("Re-spawing player at: {}", spawnPosition); Client clientListener = networkSystem.getOwner(clientEntity); Vector3i distance = clientListener.getViewDistance().getChunkDistance(); updateRelevanceEntity(clientEntity, distance); playerCharacter.send(new OnPlayerRespawnedEvent()); }
Source:
public ClientIOTaskResult aggregate(Iterable<TaskResult> results) throws Exception { Iterator<TaskResult> it = results.iterator(); if (it.hasNext()) { TaskResult taskResult = it.next(); if (!(taskResult instanceof ClientIOTaskResult)) { throw new IOException( "TaskResult is not of type ClientIOTaskResult. class: " + taskResult.getClass() .getName()); } return (ClientIOTaskResult) taskResult; } return new ClientIOTaskResult(); }

Target:
public ClientIOTaskResult aggregate(Iterable<TaskResult> results) throws Exception { Iterator<TaskResult> it = results.iterator(); if (it.hasNext()) { TaskResult taskResult = it.next(); if (it.hasNext()) { throw new IOException( "ClientIO is a single node test, so multiple task results cannot be aggregated."); } if (!(taskResult instanceof ClientIOTaskResult)) { throw new IOException( "TaskResult is not of type ClientIOTaskResult. class: " + taskResult.getClass() .getName()); } return (ClientIOTaskResult) taskResult; } return new ClientIOTaskResult(); }
Source:
@Override public boolean isLocked() throws IgniteException { try { if (sync.reentrantCount.get() > 0) return true; if (sync.isGloballyLocked) return true; GridCacheLockState2Base<LockOwner> state = sync.forceGet(); if (state == null) return false; ArrayDeque<LockOwner> nodes = state.owners; return !(nodes == null || nodes.isEmpty() || (sync.nodeId.equals(nodes.getFirst().nodeId) && nodes.size() == 1) ); } catch (IgniteCheckedException e) { throw U.convertException(e); } }

Target:
@Override public boolean isLocked() throws IgniteException { ctx.kernalContext().gateway().readLock(); try { if (sync.reentrantCnt.get() > 0 || sync.isGloballyLocked) return true; GridCacheLockState2Base<LockOwner> state = sync.forceGet(); if (state == null) return false; ArrayDeque<LockOwner> nodes = state.owners; return !(nodes == null || nodes.isEmpty() || (sync.nodeId.equals(nodes.getFirst().nodeId()) && nodes.size() == 1) ); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { ctx.kernalContext().gateway().readUnlock(); } }
Source:
public void run(Timeout timeout) { DefaultFuture future = DefaultFuture.getFuture(requestID); if (future.isDone()) { return; } if (future.getExecutor() != null) { future.getExecutor().execute(() -> { Response timeoutResponse = new Response(future.getId()); timeoutResponse.setStatus(future.isSent() ? Response.SERVER_TIMEOUT : Response.CLIENT_TIMEOUT); timeoutResponse.setErrorMessage(future.getTimeoutMessage(true)); DefaultFuture.received(future.getChannel(), timeoutResponse, true); }); } }

Target:
public void run(Timeout timeout) { DefaultFuture future = DefaultFuture.getFuture(requestID); if (future == null || future.isDone()) { return; } if (future.getExecutor() != null) { future.getExecutor().execute(() -> { Response timeoutResponse = new Response(future.getId()); timeoutResponse.setStatus(future.isSent() ? Response.SERVER_TIMEOUT : Response.CLIENT_TIMEOUT); timeoutResponse.setErrorMessage(future.getTimeoutMessage(true)); DefaultFuture.received(future.getChannel(), timeoutResponse, true); }); } }
Source:
private static long saturatedMult(long left, long right) { long retVal = left * right; if (left != 0 && (Long.MAX_VALUE / left < right)) { return Long.MAX_VALUE; } return retVal; }

Target:
private static long saturatedMult(long left, long right) { long retVal = left * right; if ((left != 0) && ((retVal / left) != right)) { return (sameSign(left, right) ? Long.MAX_VALUE : Long.MIN_VALUE); } return retVal; }
Source:
public ContractsGrantsCollectionActivityDocument() { super(); invoiceDetails = new ArrayList<ContractsGrantsCollectionActivityInvoiceDetail>(); collectionEvents = new ArrayList<CollectionEvent>(); }

Target:
public ContractsGrantsCollectionActivityDocument() { super(); invoiceDetails = new ArrayList<ContractsGrantsCollectionActivityInvoiceDetail>(); }
Source:
public void bulkAbort(List<ProcessInstanceSummary> processInstances) { if (processInstances == null || processInstances.isEmpty()) { return; } final Map<String, List<Long>> containerInstances = new HashMap<>(); for (ProcessInstanceSummary selected : processInstances) { if (selected.getState() != ProcessInstance.STATE_ACTIVE) { view.displayNotification(constants.Aborting_Process_Instance_Not_Allowed(selected.getId())); continue; } containerInstances.computeIfAbsent(selected.getDeploymentId(), key -> new ArrayList<>()); containerInstances.get(selected.getDeploymentId()).add(selected.getProcessInstanceId()); view.displayNotification(constants.Aborting_Process_Instance(selected.getId())); } if (containerInstances.size() > 0) { abortProcessInstances(containerInstances); } }

Target:
public void bulkAbort(List<ProcessInstanceSummary> processInstances) { if (processInstances == null || processInstances.isEmpty()) { return; } final Map<String, List<Long>> containerInstances = new HashMap<>(); for (ProcessInstanceSummary selected : processInstances) { if (selected.getState() != ProcessInstance.STATE_ACTIVE) { view.displayNotification(constants.Aborting_Process_Instance_Not_Allowed(selected.getId())); continue; } containerInstances.computeIfAbsent(selected.getDeploymentId(), key -> new ArrayList<>()).add(selected.getProcessInstanceId()); view.displayNotification(constants.Aborting_Process_Instance(selected.getId())); } if (containerInstances.size() > 0) { abortProcessInstances(containerInstances); } }
Source:
public boolean visit(@Nonnull JMethodCall call) { Collection<JMethod> targets = call.getMethodId().getMethods(); if (targets.size() != 1) { return false; } JMethod target = targets.iterator().next(); if (target.isAbstract() || target.isNative()) { return false; } boolean foundForceInline = false; for (JAnnotation annotation : target.getAnnotations()) { if (formatter.getName(annotation.getType()).equals(FORCE_INLINE_ANNOTATION)) { foundForceInline = true; break; } } if (foundForceInline) { call.addMarker(new InlineMarker(target)); } return true; }

Target:
public boolean visit(@Nonnull JMethodCall call) { Collection<JMethod> targets = call.getMethodId().getMethods(); if (targets.size() != 1) { return false; } JMethod target = targets.iterator().next(); if (target.isAbstract() || target.isNative()) { return false; } for (JAnnotation annotation : target.getAnnotations()) { if (formatter.getName(annotation.getType()).equals(FORCE_INLINE_ANNOTATION)) { JNameValuePair removeAfterValuePair = annotation.getNameValuePair(REMOVE_AFTER_ANNOTATION); if (removeAfterValuePair != null && removeAfterValuePair.getValue() instanceof JBooleanLiteral && ((JBooleanLiteral) removeAfterValuePair.getValue()).getValue() && target.getMarker(RemoveInlinedMarker.class) == null) { target.addMarker(new RemoveInlinedMarker()); } call.addMarker(new InlineMarker(target)); break; } } return true; }
Source:
public void refresh() { super.refresh(); Object value = this.target.eGet(this.eReference); if (value instanceof EObject) { Adapter adapter = this.composedAdapterFactory.adapt((EObject) value, IItemLabelProvider.class); if (adapter instanceof IItemLabelProvider) { IItemLabelProvider labelProvider = (IItemLabelProvider) adapter; this.text.setText(labelProvider.getText(value)); this.image.setImage(ExtendedImageRegistry.INSTANCE.getImage(labelProvider.getImage(value))); getOnClickExpression().ifPresent(expression -> { this.setStyle(); }); } } else if (value == null) { this.image.setImage(null); this.text.setText(Messages.SingleReference_noValue); } }

Target:
public void refresh() { super.refresh(); Object value = this.target.eGet(this.eReference); if (value instanceof EObject) { Adapter adapter = this.composedAdapterFactory.adapt((EObject) value, IItemLabelProvider.class); if (adapter instanceof IItemLabelProvider) { IItemLabelProvider labelProvider = (IItemLabelProvider) adapter; this.text.setText(labelProvider.getText(value)); this.text.setUnderlined(false); this.image.setImage(ExtendedImageRegistry.INSTANCE.getImage(labelProvider.getImage(value))); String onClickExpression = Optional.ofNullable(this.description.getOnClickExpression()).orElse(""); if (!onClickExpression.isEmpty()) { this.text.setUnderlined(true); } } } else if (value == null) { this.image.setImage(null); this.text.setText(Messages.SingleReference_noValue); } }
Source:
public void createPartControl(Composite parent) { String name = getViewSite().getSecondaryId(); if (name != null) { name = TmfViewFactory.getBaseSecId(name); } if (name != null) { fViewInfo.setName(name); } fPresentationProvider = new XmlPresentationProvider(name); super.createPartControl(parent); }

Target:
public void createPartControl(Composite parent) { String name = getViewSite().getSecondaryId(); if (name != null) { name = TmfViewFactory.getBaseSecId(name); } if (name != null) { fViewInfo.setName(name); } fPresentationProvider = new XmlPresentationProvider(name); TimeGraphViewer timeGraphViewer = getTimeGraphViewer(); timeGraphViewer.getTimeGraphControl().colorSettingsChanged(timeGraphViewer.getTimeGraphProvider().getStateTable()); super.createPartControl(parent); }
Source:
public CalDavConfig(String key, String username, String password, String url, int reloadMinutes, int historicLoadMinutes) { super(); this.key = key; this.username = username; this.password = password; this.url = url; this.reloadMinutes = reloadMinutes; this.historicLoadMinutes = historicLoadMinutes; }

Target:
public CalDavConfig(String key, String username, String password, String url, int reloadMinutes, int historicLoadMinutes) { this.key = key; this.username = username; this.password = password; this.url = url; this.reloadMinutes = reloadMinutes; this.historicLoadMinutes = historicLoadMinutes; }
Source:
public void search( @RequestParam("q") String query, @RequestParam(value = "type", required = false) Set<String> types, HttpServletRequest request, HttpServletResponse response) throws IOException { final Map<String, List<?>> searchResults = new TreeMap<>(); if (logger.isDebugEnabled()) { logger.debug( "Searching with q={}, type={}", query, ArrayUtils.toString(types.toArray())); } for (ISearchStrategy strategy : searchStrategies) { if (types == null || types.isEmpty() || types.contains("") || types.contains(strategy.getResultTypeName())) { searchResults.put(strategy.getResultTypeName(), strategy.search(query, request)); } } if (searchResults.isEmpty()) { logger.debug("Nothing found for query string: {}", query); response.setStatus(HttpServletResponse.SC_NOT_FOUND); } else { response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); jsonMapper.writeValue(response.getOutputStream(), searchResults); } }

Target:
public void search( @RequestParam("q") String query, @RequestParam(value = "type", required = false) Set<String> types, HttpServletRequest request, HttpServletResponse response) throws IOException { logger.debug("Searching with q={}, type={}", query, types); final Map<String, List<?>> searchResults = new TreeMap<>(); for (ISearchStrategy strategy : searchStrategies) { if (types == null || types.isEmpty() || types.contains("") || types.contains(strategy.getResultTypeName())) { searchResults.put(strategy.getResultTypeName(), strategy.search(query, request)); } } if (searchResults.isEmpty()) { logger.debug("Nothing found for query string: {}", query); response.setStatus(HttpServletResponse.SC_NOT_FOUND); } else { response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); jsonMapper.writeValue(response.getOutputStream(), searchResults); } }
Source:
public int setCloseTime(int childSequenceNumber, long endTime) { for (int i = 0; i < nbChildren; i++) { if (childSequenceNumber == this.children[i]) { childEnd[i] = endTime; return i; } } return -1; }

Target:
public int setCloseTime(int childSequenceNumber, long endTime) { for (int i = 0; i < nbChildren; i++) { if (childSequenceNumber == children[i]) { childEnd[i] = endTime; return i; } } return -1; }
Source:
private void join(EntityBareJid mucJid) throws SmackException.NotConnectedException, SmackException.NoResponseException, InterruptedException, XMPPException.XMPPErrorException, MultiUserChatException.MucAlreadyJoinedException, MultiUserChatException.NotAMucServiceException { lastPresenceSent = null; if (muc != null) { muc.removePresenceInterceptor(presenceInterceptor); logger.info("Leaving a MUC we already occupy."); muc.leave(); } MultiUserChatManager mucManager = MultiUserChatManager.getInstanceFor(xmppConnection); muc = mucManager.getMultiUserChat(mucJid); if (presenceInterceptor != null) { muc.addPresenceInterceptor(presenceInterceptor); } muc.createOrJoin(mucNickname); logger.info("Joined MUC: " + mucJid); setPresenceExtensions(mucClientManager.getPresenceExtensions()); }

Target:
private void join(EntityBareJid mucJid) throws SmackException.NotConnectedException, SmackException.NoResponseException, InterruptedException, XMPPException.XMPPErrorException, MultiUserChatException.MucAlreadyJoinedException, MultiUserChatException.NotAMucServiceException { resetLastPresenceSent(); if (muc != null) { muc.removePresenceInterceptor(presenceInterceptor); logger.info("Leaving a MUC we already occupy."); muc.leave(); } MultiUserChatManager mucManager = MultiUserChatManager.getInstanceFor(xmppConnection); muc = mucManager.getMultiUserChat(mucJid); if (presenceInterceptor != null) { muc.addPresenceInterceptor(presenceInterceptor); } muc.createOrJoin(mucNickname); logger.info("Joined MUC: " + mucJid); setPresenceExtensions(mucClientManager.getPresenceExtensions()); }