auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void initAccessor() { RegionShortcut shortcut = getRegionShortCut(); if (shortcut.isPersistent()) { if (shortcut == RegionShortcut.PARTITION_PERSISTENT) { shortcut = RegionShortcut.PARTITION; } else if (shortcut == RegionShortcut.PARTITION_PERSISTENT_OVERFLOW) { shortcut = RegionShortcut.PARTITION_OVERFLOW; } else if (shortcut == RegionShortcut.PARTITION_REDUNDANT_PERSISTENT) { shortcut = RegionShortcut.PARTITION_REDUNDANT; } else if (shortcut == RegionShortcut.PARTITION_REDUNDANT_PERSISTENT_OVERFLOW) { shortcut = RegionShortcut.PARTITION_REDUNDANT_OVERFLOW; } else { fail("Wrong region type:" + shortcut); } } getCache().createRegionFactory(shortcut) .setPartitionAttributes( new PartitionAttributesFactory().setTotalNumBuckets(10).setLocalMaxMemory(0).create()) .addCacheListener(new CountingCacheListener()) .create(REGION_NAME); }

Target:
private void initAccessor() { RegionShortcut shortcut = getRegionShortCut(); if (shortcut.isPersistent()) { if (shortcut == RegionShortcut.PARTITION_PERSISTENT) { shortcut = RegionShortcut.PARTITION; } else if (shortcut == RegionShortcut.PARTITION_PERSISTENT_OVERFLOW) { shortcut = RegionShortcut.PARTITION_OVERFLOW; } else if (shortcut == RegionShortcut.PARTITION_REDUNDANT_PERSISTENT) { shortcut = RegionShortcut.PARTITION_REDUNDANT; } else if (shortcut == RegionShortcut.PARTITION_REDUNDANT_PERSISTENT_OVERFLOW) { shortcut = RegionShortcut.PARTITION_REDUNDANT_OVERFLOW; } } getCache().createRegionFactory(shortcut) .setPartitionAttributes( new PartitionAttributesFactory().setTotalNumBuckets(10).setLocalMaxMemory(0).create()) .addCacheListener(new CountingCacheListener()) .create(REGION_NAME); }
Source:
private void publishUpdate(){ posePub.publish(new GPSPoseMessage(new Date(), buggyFrameGpsY, buggyFrameGpsX, buggyFrameRotZ)); }

Target:
private void publishUpdate(){ posePub.publish(new GPSPoseMessage(new Date(), buggyFrameGpsLat, buggyFrameGpsLon, buggyFrameRotZ)); }
Source:
public void handleEvent(ZWaveBindingProvider provider, String itemName, ZWaveCommandClassValueEvent event) { ZWaveBindingConfig bindingConfiguration = provider.getZwaveBindingConfig(itemName); Item item = provider.getItem(itemName); String commandClassName = bindingConfiguration.getArguments().get("command"); boolean respondToBasic = "true".equalsIgnoreCase(bindingConfiguration.getArguments().get("respond_to_basic")); logger.trace("Getting converter for item = {}, command class = {}, item command class = {}", itemName, event.getCommandClass().getLabel(), commandClassName); if (item == null) { return; } if (commandClassName != null && !commandClassName.equalsIgnoreCase(event.getCommandClass().getLabel().toLowerCase()) && !(respondToBasic && event.getCommandClass() == CommandClass.BASIC)) { logger.warn("Not matching command class for item = {}, command class = {}, item command class = {}, ignoring event.", itemName, event.getCommandClass().getLabel(), commandClassName); if (event.getCommandClass() == CommandClass.BASIC && !respondToBasic) { logger.debug("Command class is BASIC, maybe you want to define respond_to_basic=true ?"); } return; } ZWaveCommandClassConverter<?> converter = this.getConverter(event.getCommandClass()); if (converter == null) { logger.warn("No converter found for command class = {}, ignoring event.", event.getCommandClass().toString()); return; } converter.handleEvent(event, item, bindingConfiguration.getArguments()); }

Target:
public void handleEvent(ZWaveBindingProvider provider, String itemName, ZWaveCommandClassValueEvent event) { ZWaveBindingConfig bindingConfiguration = provider.getZwaveBindingConfig(itemName); Item item = provider.getItem(itemName); String commandClassName = bindingConfiguration.getArguments().get("command"); boolean respondToBasic = "true".equalsIgnoreCase(bindingConfiguration.getArguments().get("respond_to_basic")); logger.trace("Getting converter for item = {}, command class = {}, item command class = {}", itemName, event.getCommandClass().getLabel(), commandClassName); if (item == null) { return; } if (commandClassName != null && !commandClassName.equalsIgnoreCase(event.getCommandClass().getLabel().toLowerCase()) && !(respondToBasic && event.getCommandClass() == CommandClass.BASIC)) { return; } ZWaveCommandClassConverter<?> converter = this.getConverter(event.getCommandClass()); if (converter == null) { logger.warn("No converter found for command class = {}, ignoring event.", event.getCommandClass().toString()); return; } converter.handleEvent(event, item, bindingConfiguration.getArguments()); }
Source:
private void scrollToSeeFMR(String slotName, AdsBaseObject page) { page.triggerComments(); page.scrollToPosition("#ArticleMidSection.mw-headline"); page.waitForSlotExpanded(page.wait.forElementVisible(By.id(slotName))); }

Target:
private void scrollToSeeFMR(String slotName, AdsBaseObject page) { page.triggerComments(); page.scrollToPosition(ARTICLE_MIDDLE_SECTION_SELECTOR); page.waitForSlotExpanded(page.wait.forElementVisible(By.id(slotName))); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!getIntent().getBooleanExtra("forceMainMenu", false)) { String lastRoom = SharedPrefsHelper.getSharedPrefs(this) .getString("lastRoom", "hi, jeff"); if (!lastRoom.equals("hi, jeff")) { Intent intent = new Intent(this, MachineActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } } setContentView(R.layout.activity_location); ButterKnife.bind(this); initRecyclerView(); initToolbar(); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!getIntent().getBooleanExtra("forceMainMenu", false)) { String lastRoom = SharedPrefsHelper.getSharedPrefs(this) .getString("lastRoom", null); if (!(lastRoom == null)) { Intent intent = new Intent(this, MachineActivity.class); startActivity(intent); } } setContentView(R.layout.activity_location); ButterKnife.bind(this); initRecyclerView(); initToolbar(); }
Source:
private XML(String identifier) { this.identifier = identifier; }

Target:
XML(String identifier) { this.identifier = identifier; }
Source:
public Filter(@JsonProperty("expression") final String expression) { this.expression = expression; }

Target:
public Filter(@JsonProperty("expression") final String expression) { this.expression = notEmpty(expression, "expression"); }
Source:
public void testWebAppUserStoreOperations() throws Exception { UserManagementClient userMgtClient = new UserManagementClient(backendURL, sessionCookie); userMgtClient.addUser(user1, "passWord1@", null, "default"); userMgtClient.addUser(user2, "passWord2@", null, "default"); userMgtClient.addRole("umRole1", new String[]{user1, user2}, new String[]{"login"}, false); userMgtClient.addRole("umRole2", new String[]{user1}, new String[]{"login"}, false); log.info("Users and Roles Added Successfully "); String webAppContext = "/TenantServlet?user=UserStoreTestUser1"; String finalURL = webAppUrl + webAppContext; URL url = new URL(finalURL); URLConnection connection = url.openConnection(); connection.setDoOutput(true); BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); char[] buffer = new char[Integer.parseInt(connection.getHeaderField("Content-Length"))]; int count = buffer.length; String value = null; while ((count = br.read(buffer)) > 0) { value = new String(buffer, 0, count); } JSONArray arr = new JSONArray(new String(value)); ArrayList<String> stringArray = new ArrayList<String>(); for (int i = 0; i < arr.length(); i++) { stringArray.add(arr.getString(i)); } assertFalse(stringArray.contains("Java Security Manager Exception"), "User Store Operations Cannot be Invoked with Java Security Manager"); }

Target:
public void testWebAppUserStoreOperations() throws Exception { UserManagementClient userMgtClient = new UserManagementClient(backendURL, sessionCookie); RemoteAuthorizationManagerServiceClient authorizationClient = new RemoteAuthorizationManagerServiceClient (backendURL, sessionCookie); userMgtClient.addUser(user1, user1Password, null, defaultProfileName); userMgtClient.addUser(user2, user2Password, null, defaultProfileName); userMgtClient.addRole(role1, new String[]{user1, user2}, new String[]{loginPermission}, false); userMgtClient.addRole(role2, new String[]{user1}, new String[]{loginPermission}, false); log.info("Users and Roles Added Successfully "); assertTrue(authorizationClient.isUserAuthorized(user1, loginPermission, "ui.execute"),"Security Enabled " + "Authorization Failed"); String webAppContext = "/TenantServlet?user=UserStoreTestUser1"; String finalURL = webAppUrl + webAppContext; URL url = new URL(finalURL); URLConnection connection = url.openConnection(); connection.setDoOutput(true); BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); char[] buffer = new char[Integer.parseInt(connection.getHeaderField("Content-Length"))]; int count = buffer.length; String value = null; while ((count = br.read(buffer)) > 0) { value = new String(buffer, 0, count); } JSONArray arr = new JSONArray(new String(value)); List<String> stringArray = new ArrayList<String>(); for (int i = 0; i < arr.length(); i++) { stringArray.add(arr.getString(i)); } assertFalse(stringArray.contains("Java Security Manager Exception"), "User Store Operations Cannot be Invoked with Java Security Manager"); }
Source:
public ModelAndView activityCenter(@PathVariable long activityId){ ModelAndView modelAndView = new ModelAndView("/activity-center-edit"); ActivityModel activityModel = activityService.findById(activityId); ActivityDto activityDto = new ActivityDto(activityModel); modelAndView.addObject("sources", Lists.newArrayList(Source.values())); modelAndView.addObject("dto",activityDto); return modelAndView; }

Target:
public ModelAndView activityCenter(@PathVariable long activityId){ ModelAndView modelAndView = new ModelAndView("/activity-center-edit"); ActivityDto activityDto = activityService.findActivityDtoById(activityId); modelAndView.addObject("sources", Lists.newArrayList(Source.values())); modelAndView.addObject("dto",activityDto); return modelAndView; }
Source:
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { TikaConfiguration tikaConfiguration = new TikaConfiguration(); setProperties(tikaConfiguration, parameters); TikaConfig config = resolveAndRemoveReferenceParameter(parameters, TIKA_CONFIG, TikaConfig.class); if (config != null) { tikaConfiguration.setTikaConfig(config); } tikaConfiguration.setOperation(new URI(uri).getHost()); return createEndpoint(uri, tikaConfiguration); }

Target:
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { TikaConfiguration tikaConfiguration = new TikaConfiguration(); TikaConfig config = resolveAndRemoveReferenceParameter(parameters, TIKA_CONFIG, TikaConfig.class); if (config != null) { tikaConfiguration.setTikaConfig(config); } tikaConfiguration.setOperation(new URI(uri).getHost()); TikaEndpoint endpoint = createEndpoint(uri, tikaConfiguration); setProperties(endpoint, parameters); return endpoint; }
Source:
public TenantProfileServiceHandler() { this.tenantProfileRepository = new TenantProfileRepository(Gateway.class, GatewayEntity.class); try { logger.debug("Initializing TenantProfileServiceHandler"); GenericObjectPool.Config poolConfig = new GenericObjectPool.Config(); poolConfig.maxActive = 100; poolConfig.minIdle = 5; poolConfig.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK; poolConfig.testOnBorrow = true; poolConfig.testWhileIdle = true; poolConfig.numTestsPerEvictionRun = 10; poolConfig.maxWait = 3000; csClientPool = new ThriftClientPool<>( tProtocol -> new CredentialStoreService.Client(tProtocol), poolConfig, ServerSettings.getCredentialStoreServerHost(), Integer.parseInt(ServerSettings.getCredentialStoreServerPort())); }catch (ApplicationSettingsException e) { logger.error("Error occured while reading airavata-server properties..", e); } }

Target:
public TenantProfileServiceHandler() throws Exception { this.tenantProfileRepository = new TenantProfileRepository(Gateway.class, GatewayEntity.class); try { logger.debug("Initializing TenantProfileServiceHandler"); GenericObjectPool.Config poolConfig = new GenericObjectPool.Config(); poolConfig.maxActive = 100; poolConfig.minIdle = 5; poolConfig.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK; poolConfig.testOnBorrow = true; poolConfig.testWhileIdle = true; poolConfig.numTestsPerEvictionRun = 10; poolConfig.maxWait = 3000; csClientPool = new ThriftClientPool<>( tProtocol -> new CredentialStoreService.Client(tProtocol), poolConfig, ServerSettings.getCredentialStoreServerHost(), Integer.parseInt(ServerSettings.getCredentialStoreServerPort())); } catch (ApplicationSettingsException e) { logger.error("Error occured while reading airavata-server properties..", e); throw new Exception(e); } }
Source:
protected boolean verifyChildrenSpecific(N parent, int index, N child) { return (parent.getChildStart(index) != child.getNodeStart() && parent.getChildEnd(index) != child.getNodeEnd()); }

Target:
protected boolean verifyChildrenSpecific(N parent, int index, N child) { return (parent.getChildStart(index) == child.getNodeStart() && parent.getChildEnd(index) == child.getNodeEnd()); }
Source:
private boolean doTruncateInvalidTxBefore(long time) throws InvalidTruncateTimeException { LOG.info("Removing tx ids before from invalid list", time); long truncateWp = TimeUnit.SECONDS.toMillis(time) * TxConstants.MAX_TX_PER_MS; if (inProgress.lowerKey(truncateWp) != null) { throw new InvalidTruncateTimeException("Transactions started earlier than " + time + " are in-progress"); } Set<Long> toTruncate = Sets.newHashSet(); for (long wp : invalid) { if (wp >= truncateWp) { break; } toTruncate.add(wp); } return doTruncateInvalidTx(toTruncate); }

Target:
private boolean doTruncateInvalidTxBefore(long time) throws InvalidTruncateTimeException { LOG.info("Removing tx ids before from invalid list", time); long truncateWp = time * TxConstants.MAX_TX_PER_MS; if (inProgress.lowerKey(truncateWp) != null) { throw new InvalidTruncateTimeException("Transactions started earlier than " + time + " are in-progress"); } Set<Long> toTruncate = Sets.newHashSet(); for (long wp : invalid) { if (wp >= truncateWp) { break; } toTruncate.add(wp); } return doTruncateInvalidTx(toTruncate); }
Source:
private void startApp(String appName, String appLocation) { try { if (StringUtils.isNotEmpty(appLocation)) { appService.addApplication(new URI(appLocation)); } executeAsSystem( () -> { appService.startApplication(appName); return true; }); } catch (ApplicationServiceException ase) { LOGGER.warn("Could not start " + appName, ase); } catch (URISyntaxException use) { LOGGER.warn("Could not install application, location is not a valid URI " + appLocation, use); } }

Target:
private void startApp(String appName, String appLocation) { try { if (!appLocation.isEmpty()) { appService.addApplication(new URI(appLocation)); } executeAsSystem( () -> { appService.startApplication(appName); return true; }); } catch (ApplicationServiceException ase) { LOGGER.warn("Could not start {}", appName, ase); } catch (URISyntaxException use) { LOGGER.warn( "Could not install application, location is not a valid URI {}", appLocation, use); } }
Source:
private static void from12(ChainedTransformationDescriptionBuilder chainedBuilder) { ResourceTransformationDescriptionBuilder builder = chainedBuilder.createBuilder(ELYTRON_12_0_0, ELYTRON_11_0_0); builder.addChildResource(PathElement.pathElement(ElytronDescriptionConstants.SERVER_SSL_CONTEXT)) .getAttributeBuilder() .addRejectCheck(new RejectAttributeChecker.SimpleAcceptListAttributeChecker(new ModelNode(ElytronDescriptionConstants.SSL_V2HELLO)), ElytronDescriptionConstants.PROTOCOLS) .end(); builder.addChildResource(PathElement.pathElement(ElytronDescriptionConstants.CLIENT_SSL_CONTEXT)) .getAttributeBuilder() .addRejectCheck(new RejectAttributeChecker.SimpleAcceptListAttributeChecker(new ModelNode(ElytronDescriptionConstants.SSL_V2HELLO)), ElytronDescriptionConstants.PROTOCOLS) .end(); }

Target:
private static void from12(ChainedTransformationDescriptionBuilder chainedBuilder) { ResourceTransformationDescriptionBuilder builder = chainedBuilder.createBuilder(ELYTRON_12_0_0, ELYTRON_11_0_0); builder.addChildResource(PathElement.pathElement(ElytronDescriptionConstants.KEY_MANAGER)) .getAttributeBuilder() .addRejectCheck(RejectAttributeChecker.DEFINED, ElytronDescriptionConstants.GENERATE_SELF_SIGNED_CERTIFICATE_HOST) .setDiscard(DiscardAttributeChecker.UNDEFINED, SSLDefinitions.GENERATE_SELF_SIGNED_CERTIFICATE_HOST) .end(); builder.rejectChildResource(PathElement.pathElement(ElytronDescriptionConstants.CASE_PRINCIPAL_TRANSFORMER)); }
Source:
private SqlTask newSqlTask() { TaskId taskId = new TaskId("query", 0, idGeneator.incrementAndGet()); URI location = URI.create("fake://task/" + taskId); return new SqlTask( taskId, location, "fake", new DefaultQueryContext(new QueryId("query"), new DataSize(1, MEGABYTE), new DataSize(2, MEGABYTE), memoryPool, new TestingGcMonitor(), executor, scheduledExecutor, new DataSize(1, GIGABYTE), spillSpaceTracker), sqlTaskExecutionFactory, executor, Functions.identity(), new DataSize(32, MEGABYTE), failedTasks); }

Target:
private SqlTask newSqlTask() { TaskId taskId = new TaskId("query", 0, idGeneator.incrementAndGet()); URI location = URI.create("fake://task/" + taskId); return new SqlTask( taskId, location, "fake", new DefaultQueryContext(new QueryId("query"), new DataSize(1, MEGABYTE), new DataSize(2, MEGABYTE), memoryPool, new TestingGcMonitor(), executor, scheduledExecutor, new DataSize(1, GIGABYTE), spillSpaceTracker), sqlTaskExecutionFactory, executor, Functions.identity(), new DataSize(32, MEGABYTE), new CounterStat()); }
Source:
protected String formatCommand(Command command, String format, ValueFormatter valueFormatter, String... keys) { String result = String.format(format, (Object[]) keys); Set<String> missingKeys = new HashSet<>(Arrays.asList(keys)); result = result.replaceAll("\\{" + Command.KEY_UNIQUE_ID + "}", getUniqueId(command.getDeviceId())); for (Map.Entry<String, Object> entry : command.getAttributes().entrySet()) { String value = null; if (valueFormatter != null) { value = valueFormatter.formatValue(entry.getKey(), entry.getValue()); } if (value == null) { value = entry.getValue().toString(); } result = result.replaceAll("\\{" + entry.getKey() + "}", value); missingKeys.remove(entry.getKey()); } for (String key : missingKeys) { result = result.replaceAll("\\{" + key + "}", ""); } return result; }

Target:
protected String formatCommand(Command command, String format, ValueFormatter valueFormatter, String... keys) { Object[] values = new String[keys.length]; for (int i = 0; i < keys.length; i++) { String value = null; if (keys[i].equals(Command.KEY_UNIQUE_ID)) { value = getUniqueId(command.getDeviceId()); } else { Object object = command.getAttributes().get(keys[i]); if (valueFormatter != null) { value = valueFormatter.formatValue(keys[i], object); } if (value == null && object != null) { value = object.toString(); } if (value == null) { value = ""; } } values[i] = value; } return String.format(format, values); }
Source:
private void printErrorStatus(CommandInterpreter interpreter, IStatus status) { interpreter.print("--Error status "); interpreter.print("message=" + status.getMessage()); interpreter.print(",code=" + status.getCode()); String severityString = null; switch (status.getSeverity()) { case IStatus.INFO: severityString = "INFO"; break; case IStatus.CANCEL: severityString = "CANCEL"; break; case IStatus.WARNING: severityString = "WARNING"; break; case IStatus.ERROR: severityString = "ERROR"; break; } interpreter.print(",severity=" + severityString); interpreter.print(",bundle=" + status.getPlugin()); interpreter.println("--"); Throwable t = status.getException(); if (t != null) interpreter.printStackTrace(t); IStatus[] children = status.getChildren(); if (children != null && children.length > 0) { interpreter.println("Error status children:"); for (IStatus children1 : children) { printErrorStatus(interpreter, children1); } } interpreter.println("--End Error Status--"); }

Target:
private void printErrorStatus(CommandInterpreter interpreter, IStatus status) { interpreter.print("--Error status "); interpreter.print("message=" + status.getMessage()); interpreter.print(",code=" + status.getCode()); String severityString = null; switch (status.getSeverity()) { case IStatus.INFO: severityString = "INFO"; break; case IStatus.CANCEL: severityString = "CANCEL"; break; case IStatus.WARNING: severityString = "WARNING"; break; case IStatus.ERROR: severityString = "ERROR"; break; } interpreter.print(",severity=" + severityString); interpreter.print(",bundle=" + status.getPlugin()); interpreter.println("--"); Throwable t = status.getException(); if (t != null) interpreter.printStackTrace(t); IStatus[] children = status.getChildren(); if (children != null && children.length > 0) { interpreter.println("Error status children:"); for (IStatus child : children) { printErrorStatus(interpreter, child); } } interpreter.println("--End Error Status--"); }
Source:
public void testList() throws UnauthorizedException, GeneralException { final ContactList contactResponseList = TestUtil.createContactList(); MessageBirdService messageBirdServiceMock = mock(MessageBirdService.class); MessageBirdClient messageBirdClientInjectMock = new MessageBirdClient(messageBirdServiceMock); when(messageBirdServiceMock.requestList(Mockito.eq(CONTACTPATH), Mockito.eq(0), Mockito.eq(20), Mockito.eq(ContactList.class))) .thenReturn(contactResponseList); final ContactList response = messageBirdClientInjectMock.listContacts(); verify(messageBirdServiceMock, times(1)) .requestList(Mockito.eq(CONTACTPATH), Mockito.eq(0), Mockito.eq(20), Mockito.eq(ContactList.class)); assertEquals(response.getItems().get(0).getFirstName(), contactResponseList.getItems().get(0).getFirstName()); assertEquals(response.getItems().get(0).getLastName(), contactResponseList.getItems().get(0).getLastName()); assertEquals(response.getItems().get(0).getId(), contactResponseList.getItems().get(0).getId()); assertEquals(response.getItems().get(0).getCreatedDatetime(), contactResponseList.getItems().get(0).getCreatedDatetime()); assertEquals(response.getItems().get(0).getMsisdn(), contactResponseList.getItems().get(0).getMsisdn()); assertEquals(response.getItems().get(0).getCustomDetails().getCustom1(), contactResponseList.getItems().get(0).getCustomDetails().getCustom1()); assertEquals(response.getItems().get(0).getMessages().getHREF(), contactResponseList.getItems().get(0).getMessages().getHREF()); assertEquals(response.getItems().get(0).getMessages().getTotalCount(), contactResponseList.getItems().get(0).getMessages().getTotalCount()); assertEquals(response.getItems().get(0).getHref(), contactResponseList.getItems().get(0).getHref()); assertEquals(response.getItems().get(0).getGroups().getHREF(), contactResponseList.getItems().get(0).getGroups().getHREF()); assertEquals(response.getItems().get(0).getGroups().getTotalCount(), contactResponseList.getItems().get(0).getGroups().getTotalCount()); assertNotNull(response.getItems().get(0).getCreatedDatetime()); assertNotNull(response.getItems().get(0).getUpdatedDatetime()); }

Target:
public void testList() throws UnauthorizedException, GeneralException { final ContactList contactResponseList = TestUtil.createContactList(); MessageBirdService messageBirdServiceMock = mock(MessageBirdService.class); MessageBirdClient messageBirdClientInjectMock = new MessageBirdClient(messageBirdServiceMock); when(messageBirdServiceMock.requestList(Mockito.eq(CONTACTPATH), Mockito.eq(0), Mockito.eq(20), Mockito.eq(ContactList.class))) .thenReturn(contactResponseList); final ContactList response = messageBirdClientInjectMock.listContacts(); verify(messageBirdServiceMock, times(1)) .requestList(Mockito.eq(CONTACTPATH), Mockito.eq(0), Mockito.eq(20), Mockito.eq(ContactList.class)); assertReflectionEquals(response.getItems().get(0),contactResponseList.getItems().get(0)); }
Source:
private static String getCompleteKey(String[] keys, int start, int end) { StringBuilder sb = new StringBuilder(1024); for (int i = start; i < end; ++i) { if (i > start) { sb.append(KEY_SEPARATOR); } sb.append(keys[i]); } return sb.toString(); }

Target:
private static String getCompleteKey(String[] keys, int start, int end) { int length = 0; for (int keyIndex = 0; keyIndex < keys.length; keyIndex++) { length += keys[keyIndex].length(); } StringBuilder sb = new StringBuilder(length); for (int i = start; i < end; ++i) { if (i > start) { sb.append(KEY_SEPARATOR); } sb.append(keys[i]); } return sb.toString(); }
Source:
private Symbol addFlowFromLearnedAssociations(ExplodedGraph.Edge edge, ImmutableList.Builder<JavaFileScannerContext.Location> flowBuilder) { Symbol newTrackSymbol = trackSymbol; if (newTrackSymbol == null) { return null; } ExplodedGraph.Node parent = edge.parent; Optional<LearnedAssociation> learnedAssociation = edge.learnedAssociations().stream() .filter(la -> la.symbol().equals(trackSymbol)) .findFirst(); if (learnedAssociation.isPresent()) { LearnedAssociation la = learnedAssociation.get(); for (Class<? extends Constraint> domain : domains) { Constraint constraint = parent.programState.getConstraint(la.symbolicValue(), domain); if(constraint != null) { flowBuilder.add(location(parent, String.format("'%s' is assigned %s.", la.symbol().name(), constraint.valueAsString()))); } } return parent.programState.getLastEvaluated(); } return newTrackSymbol; }

Target:
private Symbol addFlowFromLearnedAssociations(ExplodedGraph.Edge edge, ImmutableList.Builder<JavaFileScannerContext.Location> flowBuilder) { if (trackSymbol == null) { return null; } ExplodedGraph.Node parent = edge.parent; Optional<LearnedAssociation> learnedAssociation = edge.learnedAssociations().stream() .filter(la -> la.symbol().equals(trackSymbol)) .findFirst(); if (learnedAssociation.isPresent()) { LearnedAssociation la = learnedAssociation.get(); for (Class<? extends Constraint> domain : domains) { Constraint constraint = parent.programState.getConstraint(la.symbolicValue(), domain); if (constraint != null) { flowBuilder.add(location(parent, String.format("'%s' is assigned %s.", la.symbol().name(), constraint.valueAsString()))); } } return parent.programState.getLastEvaluated(); } return trackSymbol; }
Source:
public void testTimestampWithDelay() throws Exception { expectInitializeNoOffsets(Arrays.asList(SINGLE_TABLE_PARTITION)); PowerMock.replayAll(); db.createTable(SINGLE_TABLE_NAME, "modified", "TIMESTAMP NOT NULL", "id", "INT"); db.insert(SINGLE_TABLE_NAME, "modified", JdbcUtils.formatUTC(new Timestamp(10L)), "id", 1); startTask("modified", null, null, 4L); verifyTimestampFirstPoll(TOPIC_PREFIX + SINGLE_TABLE_NAME); Long currentTime = new Date().getTime(); db.insert(SINGLE_TABLE_NAME, "modified", JdbcUtils.formatUTC(new Timestamp(currentTime)), "id", 2); db.insert(SINGLE_TABLE_NAME, "modified", JdbcUtils.formatUTC(new Timestamp(currentTime+1L)), "id", 3); db.insert(SINGLE_TABLE_NAME, "modified", JdbcUtils.formatUTC(new Timestamp(currentTime+500L)), "id", 4); db.insert(SINGLE_TABLE_NAME, "modified", JdbcUtils.formatUTC(new Timestamp(currentTime+501L)), "id", 5); verifyPoll(2, "id", Arrays.asList(2, 3), true, false, TOPIC_PREFIX + SINGLE_TABLE_NAME); Thread.sleep(500); verifyPoll(2, "id", Arrays.asList(4, 5), true, false, TOPIC_PREFIX + SINGLE_TABLE_NAME); PowerMock.verifyAll(); }

Target:
public void testTimestampWithDelay() throws Exception { expectInitializeNoOffsets(Arrays.asList(SINGLE_TABLE_PARTITION)); PowerMock.replayAll(); db.createTable(SINGLE_TABLE_NAME, "modified", "TIMESTAMP NOT NULL", "id", "INT"); db.insert(SINGLE_TABLE_NAME, "modified", JdbcUtils.formatUTC(new Timestamp(10L)), "id", 1); startTask("modified", null, null, 4L); verifyTimestampFirstPoll(TOPIC_PREFIX + SINGLE_TABLE_NAME); Long currentTime = new Date().getTime(); db.insert(SINGLE_TABLE_NAME, "modified", new Timestamp(currentTime).toString(), "id", 2); db.insert(SINGLE_TABLE_NAME, "modified", new Timestamp(currentTime+1L).toString(), "id", 3); db.insert(SINGLE_TABLE_NAME, "modified", new Timestamp(currentTime+500L).toString(), "id", 4); db.insert(SINGLE_TABLE_NAME, "modified", new Timestamp(currentTime+501L).toString(), "id", 5); verifyPoll(2, "id", Arrays.asList(2, 3), true, false, TOPIC_PREFIX + SINGLE_TABLE_NAME); Thread.sleep(500); verifyPoll(2, "id", Arrays.asList(4, 5), true, false, TOPIC_PREFIX + SINGLE_TABLE_NAME); PowerMock.verifyAll(); }
Source:
protected void executeCommand() { setVds(null); if (getVds() == null) { setCommandShouldBeLogged(false); log.infoFormat("Host {0}({1}) not fenced since it doesn't exist anymore.", getVdsName(), getVdsId()); getReturnValue().setSucceeded(false); return; } VdsValidator validator = new VdsValidator(getVds()); boolean shouldBeFenced = validator.shouldVdsBeFenced(); if (shouldBeFenced) { getParameters().setParentCommand(VdcActionType.VdsNotRespondingTreatment); ExecutionContext ec = (ExecutionContext) ObjectUtils.clone(this.getExecutionContext()); if (ec != null) ec.setJob(this.getExecutionContext().getJob()); super.executeCommand(); if (ec != null) this.setExecutionContext(ec); } else { setCommandShouldBeLogged(false); log.infoFormat("Host {0}({1}) not fenced since it's status is ok, or it doesn't exist anymore.", getVdsName(), getVdsId()); } getReturnValue().setSucceeded(shouldBeFenced); }

Target:
protected void executeCommand() { setVds(null); if (getVds() == null) { setCommandShouldBeLogged(false); log.infoFormat("Host {0}({1}) not fenced since it doesn't exist anymore.", getVdsName(), getVdsId()); getReturnValue().setSucceeded(false); return; } VdsValidator validator = new VdsValidator(getVds()); boolean shouldBeFenced = validator.shouldVdsBeFenced(); if (shouldBeFenced) { getParameters().setParentCommand(VdcActionType.VdsNotRespondingTreatment); ExecutionContext ec = (ExecutionContext) ObjectUtils.clone(this.getExecutionContext()); if (ec != null) { ec.setJob(this.getExecutionContext().getJob()); } super.executeCommand(); if (ec != null) { this.setExecutionContext(ec); } } else { setCommandShouldBeLogged(false); log.infoFormat("Host {0}({1}) not fenced since it's status is ok, or it doesn't exist anymore.", getVdsName(), getVdsId()); } getReturnValue().setSucceeded(shouldBeFenced); }
Source:
public Queue<Selectable> createFlowTriggerEventQueue(RepairEvent event) { Set<String> terminatedOrRemovedInstanceIdsSet = new HashSet<>(event.getInstanceIds()); terminatedOrRemovedInstanceIdsSet.addAll(event.getAdditionalTermiantedInstanceIds()); List<String> terminatedOrRemovedInstanceId = terminatedOrRemovedInstanceIdsSet.stream().collect(Collectors.toList()); Queue<Selectable> flowEventChain = new ConcurrentLinkedQueue<>(); flowEventChain.add(new DownscaleEvent(DownscaleFlowEvent.DOWNSCALE_EVENT.event(), event.getResourceId(), terminatedOrRemovedInstanceId, event.getInstanceCountByGroup(), Boolean.TRUE, event.getOperationId(), event.accepted())); flowEventChain.add(new UpscaleEvent(UpscaleFlowEvent.UPSCALE_EVENT.event(), event.getResourceId(), event.getInstanceCountByGroup(), Boolean.TRUE, event.getOperationId())); return flowEventChain; }

Target:
public Queue<Selectable> createFlowTriggerEventQueue(RepairEvent event) { Set<String> terminatedOrRemovedInstanceIdsSet = new HashSet<>(event.getInstanceIds()); terminatedOrRemovedInstanceIdsSet.addAll(event.getAdditionalTermiantedInstanceIds()); List<String> terminatedOrRemovedInstanceIds = terminatedOrRemovedInstanceIdsSet.stream().collect(Collectors.toList()); Queue<Selectable> flowEventChain = new ConcurrentLinkedQueue<>(); flowEventChain.add(new DownscaleEvent(DownscaleFlowEvent.DOWNSCALE_EVENT.event(), event.getResourceId(), terminatedOrRemovedInstanceIds, event.getInstanceCountByGroup(), Boolean.TRUE, event.getOperationId(), event.accepted())); flowEventChain.add(new UpscaleEvent(UpscaleFlowEvent.UPSCALE_EVENT.event(), event.getResourceId(), event.getInstanceCountByGroup(), Boolean.TRUE, event.getOperationId())); return flowEventChain; }
Source:
protected void startup(BundleContext bundleContext) { final IConfigurationElement[] controls = Platform.getExtensionRegistry().getConfigurationElementsFor( "org.eclipse.emf.ecp.view.template"); if (controls.length == 0) { return; } if (controls.length > 1) { if (ViewModelUtil.isDebugMode()) { throw new IllegalArgumentException("Multiple templae models found. Only one is supported."); } reportService.report(new AbstractReport( "Multiple template models have been found. Only one of them will be used. Fix your project setup.")); } final IConfigurationElement e = controls[0]; final String xmiResource = e.getAttribute("xmi"); final Resource resource = loadResource(URI.createURI("platform:/plugin/" + e.getContributor().getName() + "/" + xmiResource)); if (resource == null) { return; } if (resource.getContents().size() != 1) { return; } registeredTemplate = (VTViewTemplate) resource.getContents().get(0); }

Target:
protected void startup(BundleContext bundleContext) { final IConfigurationElement[] controls = Platform.getExtensionRegistry().getConfigurationElementsFor( "org.eclipse.emf.ecp.view.template"); if (controls.length == 0) { return; } if (controls.length > 1) { if (ViewModelUtil.isDebugMode()) { throw new IllegalArgumentException("Multiple template models found. Only one is supported."); } reportService.report(new AbstractReport( "Multiple template models have been found. Only one of them will be used. Fix your project setup.")); } final IConfigurationElement e = controls[0]; final String xmiResource = e.getAttribute("xmi"); final Resource resource = loadResource(URI.createURI("platform:/plugin/" + e.getContributor().getName() + "/" + xmiResource)); if (resource == null) { return; } if (resource.getContents().size() != 1) { return; } registeredTemplate = (VTViewTemplate) resource.getContents().get(0); }
Source:
public JSONSerialization withCallback(final String callbackName) { return new GsonJSONSerialization(response, extractor, initializer, builder, serializee) { @Override protected SerializerBuilder getSerializer() { try { return new GsonSerializer(builder, response.getWriter(), extractor, initializer, serializee) { @Override protected void write(Writer writer, String json) throws IOException { writer.write(callbackName + "(" + json + ")"); } }; } catch (IOException e) { throw new ResultException("Unable to serialize data", e); } } }; }

Target:
public JSONSerialization withCallback(final String callbackName) { return new GsonJSONSerialization(response, extractor, initializer, builder, serializee) { @Override protected SerializerBuilder getSerializer() { try { return new GsonSerializer(builder, response.getWriter(), extractor, initializer, serializee) { @Override public void serialize() { try { response.getWriter().append(callbackName).append("("); super.serialize(); response.getWriter().append(")"); response.getWriter().flush(); } catch (IOException e) { throw new ResultException("Unable to serialize data", e); } } }; } catch (IOException e) { throw new ResultException("Unable to serialize data", e); } } }; }
Source:
private long resolveWallTime(String configuredWalltime, String errorMessage) { String confallTime = configuredWalltime; if (confallTime == null || confallTime.isEmpty() || confallTime.trim().equals("0")) { return 0; } long resolvedWallTime = Tools.formatDate(confallTime); if (resolvedWallTime == 0) { logger.warn(getId(), errorMessage); return 0; } return resolvedWallTime; }

Target:
private long resolveWallTime(String configuredWalltime, String errorMessage) { if (configuredWalltime == null || configuredWalltime.isEmpty() || configuredWalltime.trim().equals("0")) { return 0; } long resolvedWalltime = Tools.formatDate(configuredWalltime); if (resolvedWalltime == 0) { logger.warn(getId(), errorMessage); return 0; } return resolvedWalltime; }
Source:
@Test public void testReportSample() { Policy p; ArrayList<Notice> notices = new ArrayList<>(); p = parseWithNotices("default-src 'report-sample'", notices); assertEquals(1, p.getDirectives().size()); assertEquals(0, notices.size()); notices.clear(); p = parseWithNotices("script-src 'report-sample' 'report-sample'", notices); assertEquals(1, p.getDirectives().size()); assertEquals("script-src 'report-sample'", p.getDirectiveByType(ScriptSrcDirective.class).show()); assertEquals(0, notices.size()); notices.clear(); p = parseWithNotices("style-src 'report-sample' 'unsafe-hashed-attributes' 'report-sample' 'nonce-123'", notices); assertEquals(1, p.getDirectives().size()); assertEquals(2, notices.size()); assertEquals("Invalid base64-value (should be multiple of 4 bytes: 3).", notices.get(0).message); notices.clear(); p = parseWithNotices("default-src 'strict-dynamic' 'report-sample'", notices); assertEquals(1, p.getDirectives().size()); assertEquals(0, notices.size()); notices.clear(); p = parseWithNotices("img-src 'report-sample'", notices); assertEquals(1, p.getDirectives().size()); assertEquals(0, notices.size()); }

Target:
@Test public void testReportSample() { Policy p; ArrayList<Notice> notices = new ArrayList<>(); p = parseWithNotices("default-src 'report-sample'", notices); assertEquals(1, p.getDirectives().size()); assertEquals(0, notices.size()); notices.clear(); p = parseWithNotices("script-src 'report-sample' 'report-sample'", notices); assertEquals(1, p.getDirectives().size()); assertEquals("script-src 'report-sample'", p.getDirectiveByType(ScriptSrcDirective.class).show()); assertEquals(0, notices.size()); notices.clear(); p = parseWithNotices("default-src 'strict-dynamic' 'report-sample'", notices); assertEquals(1, p.getDirectives().size()); assertEquals(0, notices.size()); notices.clear(); p = parseWithNotices("img-src 'report-sample'", notices); assertEquals(1, p.getDirectives().size()); assertEquals(0, notices.size()); }
Source:
public Outer.Validator deserialize( JsonElement jsonElement, Type type, JsonDeserializationContext context) { JsonObject object = jsonElement.getAsJsonObject(); String validatorName = context.deserialize(object.get(VALIDATOR_PROPERTY), String.class); Outer.Validator result = null; JsonElement validators = object.get(VALIDATORS_PROPERTY); if (validators != null) { result = new Outer.ValidatorCollection( validatorName, context.deserialize( validators, new TypeToken<List<Outer.Validator>>() {}.getType())); } if (result == null) { result = new Outer.Validator( validatorName, context.deserialize(object.get("arguments"), List.class)); } return result; }

Target:
public Outer.Validator deserialize( JsonElement jsonElement, Type type, JsonDeserializationContext context) { JsonObject object = jsonElement.getAsJsonObject(); String validatorName = context.deserialize(object.get(SINGLE_VALIDATOR_PROPERTY), String.class); Outer.Validator result = null; JsonElement validators = object.get(VALIDATORS_PROPERTY); if (validators != null) { result = new Outer.ValidatorCollection( validatorName, context.deserialize(validators, OUTER_VALIDATOR_TYPE)); } if (result == null) { result = new Outer.Validator( validatorName, context.deserialize(object.get("arguments"), LIST_STRING)); } return result; }
Source:
private static Integer getNumberOfShards(Properties properties) { String nShards = properties.getProperty(NUMBER_OF_SHARDS_PROP); if (nShards == null) { nShards = properties.getProperty(SHARDING_STRATEGY_PROP + "." + NUMBER_OF_SHARDS_PROP); } return nShards != null ? Integer.valueOf(nShards) : null; }

Target:
private static int getNumberOfShards(Properties properties) { String nShards = properties.getProperty(NUMBER_OF_SHARDS_PROP); if (nShards != null) return Integer.valueOf(nShards); String value = properties.getProperty(SHARDING_STRATEGY_PROP + "." + NUMBER_OF_SHARDS_PROP); return value != null ? Integer.valueOf(value) : DEFAULT_NUMBER_SHARDS; }
Source:
public boolean isSrmResource() { return resource.getContents().stream().filter(DRepresentation.class::isInstance).findFirst().isPresent(); }

Target:
public boolean isSrmResource() { return Optional.ofNullable(resource.getContents().get(0)).filter(DRepresentation.class::isInstance).isPresent(); }
Source:
public DatabaseRow poll() throws SQLException { if (!_initialized) { throw new DatastreamRuntimeException("call start before calling poll for records"); } if (_queryResultSet == null) { executeFirstChunkedQuery(); _queryStmt = _connection.prepareStatement(_chunkedQuery); _queryStmt.setFetchSize(_fetchSize); _queryStmt.setQueryTimeout(_queryTimeoutSecs); } DatabaseRow row = null; while (row == null) { if (!_queryResultSet.next()) { if (numRowsInResult < _chunkSize) { return null; } numRowsInResult = 0; prepareChunkedQuery(); executeChunkedQuery(); if (!_queryResultSet.next()) { return null; } } row = getNextRow(); } return row; }

Target:
public DatabaseRow poll() throws SQLException { if (!_initialized) { throw new DatastreamRuntimeException("call start before calling poll for records"); } if (_queryResultSet == null) { executeFirstChunkedQuery(); _queryStmt = _connection.prepareStatement(_chunkedQuery); _queryStmt.setFetchSize(_fetchSize); _queryStmt.setQueryTimeout(_queryTimeoutSecs); } DatabaseRow row = null; while (row == null) { if (!_queryResultSet.next()) { if (_numRowsInResult < _rowCountLimit) { return null; } _numRowsInResult = 0; prepareChunkedQuery(); executeChunkedQuery(_queryStmt); if (!_queryResultSet.next()) { return null; } } row = getNextRow(); } return row; }
Source:
void account_credentials_are_invalid_for_a_live_gateway_account(String type) { var gatewayAccount = aGatewayAccountEntity().withType(GatewayAccountEntity.Type.fromString(type)).build(); var flexCredentials = new Worldpay3dsFlexCredentials("53f0917f101a4428b69d5fb0", "57992a087a0c4849895ab8a2","4cabd5d2-0133-4e82-b0e5-2024dbeddaa9"); when(response.getStatus()).thenReturn(HttpStatus.SC_BAD_REQUEST); when(client.target(threeDsFlexDdcUrls.get(type))).thenReturn(webTarget); when(worldpay3dsFlexJwtService.generateDdcToken(eq(GatewayAccount.valueOf(gatewayAccount)), eq(flexCredentials), any(ZonedDateTime.class))).thenReturn(DDC_TOKEN); var expectedFormData = new MultivaluedHashMap<String, String>(){{add("JWT", DDC_TOKEN);}}; when(invocationBuilder.post(argThat(new EntityMatcher(Entity.form(expectedFormData))))).thenReturn(response); assertFalse(service.validateCredentials(gatewayAccount, flexCredentials)); }

Target:
void account_credentials_are_invalid_for_a_live_gateway_account(String type) { var gatewayAccount = aGatewayAccountEntity().withType(GatewayAccountEntity.Type.fromString(type)).build(); var invalidIssuer = "54i0917n10va4428b69l5id0"; var invalidOrgUnitId = "57992i087n0v4849895alid2"; var invalidJwtMacKey = "4inva5l2-0133-4i82-d0e5-2024dbeddaa9"; var flexCredentials = new Worldpay3dsFlexCredentials(invalidIssuer, invalidOrgUnitId, invalidJwtMacKey); when(response.getStatus()).thenReturn(HttpStatus.SC_BAD_REQUEST); when(client.target(threeDsFlexDdcUrls.get(type))).thenReturn(webTarget); when(worldpay3dsFlexJwtService.generateDdcToken(eq(GatewayAccount.valueOf(gatewayAccount)), eq(flexCredentials), any(ZonedDateTime.class))).thenReturn(DDC_TOKEN); var expectedFormData = new MultivaluedHashMap<String, String>(){{add("JWT", DDC_TOKEN);}}; when(invocationBuilder.post(argThat(new EntityMatcher(Entity.form(expectedFormData))))).thenReturn(response); assertFalse(service.validateCredentials(gatewayAccount, flexCredentials)); }
Source:
public Multimap<String, String> openRevisions(int start, int end) { Misc.checkArgument(start >= 0, "Start position must be greater or equal to zero."); Misc.checkArgument(end > start, "End position must be greater than start."); Misc.checkArgument(end <= this.size(), "End position must be smaller than changes feed size."); Multimap<String, String> openRevisions = HashMultimap.create(); for(int i = start; i < end ; i ++) { ChangesResult.Row row = this.getResults().get(i); List<ChangesResult.Row.Rev> revisions = row.getChanges(); Set<String> openRevs = new HashSet<String>(revisions.size()); for(ChangesResult.Row.Rev rev : revisions) { openRevs.add(rev.getRev()); } openRevisions.putAll(row.getId(), openRevs); } return openRevisions; }

Target:
public Multimap<String, String> openRevisions(int start, int end) { Misc.checkArgument(start >= 0, "Start position must be greater or equal to zero."); Misc.checkArgument(end > start, "End position must be greater than start."); Misc.checkArgument(end <= this.size(), "End position must be less than or equal to the " + "changes feed size."); Multimap<String, String> openRevisions = HashMultimap.create(); for(int i = start; i < end ; i ++) { ChangesResult.Row row = this.getResults().get(i); List<ChangesResult.Row.Rev> revisions = row.getChanges(); Set<String> openRevs = new HashSet<String>(revisions.size()); for(ChangesResult.Row.Rev rev : revisions) { openRevs.add(rev.getRev()); } openRevisions.putAll(row.getId(), openRevs); } return openRevisions; }
Source:
public PriceSelectionBuilder plusLocaleProjection(@Nullable final String localeProjection) { this.localeProjection = new ArrayList<>(); this.localeProjection.add(localeProjection); return this; }

Target:
public PriceSelectionBuilder plusLocaleProjection(@Nullable final String localeProjection) { if (this.localeProjection == null) { this.localeProjection = new ArrayList<>(); } this.localeProjection.add(localeProjection); return this; }
Source:
public void testSpecificBuildSelector() throws Exception { WorkflowJob copier = createWorkflow( "copier", "step(copyArtifacts(projectName: 'copiee', selector: specific(\"${build('copiee').number}\")));" + "echo readFile('artifact.txt');" ); createWorkflow( "copiee", "writeFile text: 'foobar', file: 'artifact.txt';" + "archive includes: 'artifact.txt';" ); jenkinsRule.assertLogContains("foobar", jenkinsRule.assertBuildStatusSuccess(copier.scheduleBuild2(0))); }

Target:
public void testSpecificBuildSelector() throws Exception { WorkflowJob copier = jenkinsRule.createWorkflow( "copier", "copyArtifacts(projectName: 'copiee', selector: specific(\"${build('copiee').number}\"));" + "echo readFile('artifact.txt');" ); jenkinsRule.createWorkflow( "copiee", "writeFile text: 'foobar', file: 'artifact.txt';" + "archive includes: 'artifact.txt';" ); jenkinsRule.assertLogContains("foobar", jenkinsRule.assertBuildStatusSuccess(copier.scheduleBuild2(0))); }
Source:
public List<MCLivingEntity.MCEffect> potions(CArray ea, Target t) { List<MCLivingEntity.MCEffect> ret = new ArrayList<MCLivingEntity.MCEffect>(); for (String key : ea.stringKeySet()) { if (ea.get(key, t) instanceof CArray) { CArray effect = (CArray) ea.get(key, t); int potionID = 0, strength = 0, seconds = 30; boolean ambient = false; boolean particles = true; if (effect.containsKey("id")) { potionID = Static.getInt32(effect.get("id", t), t); } else { throw new Exceptions.FormatException("No potion ID was given at index " + key, t); } if (effect.containsKey("strength")) { strength = Static.getInt32(effect.get("strength", t), t); } if (effect.containsKey("seconds")) { seconds = Static.getInt32(effect.get("seconds", t), t); } if (effect.containsKey("ambient")) { ambient = Static.getBoolean(effect.get("ambient", t)); } if (effect.containsKey("particles")) { particles = Static.getBoolean(effect.get("particles", t)); } if (particles) { ret.add(new MCLivingEntity.MCEffect(potionID, strength, seconds, ambient)); } else { ret.add(new MCLivingEntity.MCEffect(potionID, strength, seconds, ambient, particles)); } } else { throw new Exceptions.FormatException("Expected a potion array at index" + key, t); } } return ret; }

Target:
public List<MCLivingEntity.MCEffect> potions(CArray ea, Target t) { List<MCLivingEntity.MCEffect> ret = new ArrayList<MCLivingEntity.MCEffect>(); for (String key : ea.stringKeySet()) { if (ea.get(key, t) instanceof CArray) { CArray effect = (CArray) ea.get(key, t); int potionID = 0, strength = 0, seconds = 30; boolean ambient = false; boolean particles = true; if (effect.containsKey("id")) { potionID = Static.getInt32(effect.get("id", t), t); } else { throw new Exceptions.FormatException("No potion ID was given at index " + key, t); } if (effect.containsKey("strength")) { strength = Static.getInt32(effect.get("strength", t), t); } if (effect.containsKey("seconds")) { seconds = Static.getInt32(effect.get("seconds", t), t); } if (effect.containsKey("ambient")) { ambient = Static.getBoolean(effect.get("ambient", t)); } if (effect.containsKey("particles")) { particles = Static.getBoolean(effect.get("particles", t)); } ret.add(new MCLivingEntity.MCEffect(potionID, strength, seconds, ambient, particles)); } else { throw new Exceptions.FormatException("Expected a potion array at index" + key, t); } } return ret; }