auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected String createPayload(LoadBalancer.Request.DeregisterPayload payload) { requestBuilder.append("<ws:deregisterServersOnLoadBalancer>") .append("<request>"); for (String s : payload.serverIds()) { requestBuilder.append(format("<serverIds>%s</serverIds>", s)); } requestBuilder.append(format("<loadBalancerId>%s</loadBalancerId>", payload.id())) .append("</request>") .append("</ws:deregisterServersOnLoadBalancer>"); START return requestBuilder.toString().replaceAll("\\s+", ""); END } Is this really needed?

Target:
protected String createPayload(LoadBalancer.Request.DeregisterPayload payload) { requestBuilder.append("<ws:deregisterServersOnLoadBalancer>") .append("<request>"); for (String s : payload.serverIds()) { requestBuilder.append(format("<serverIds>%s</serverIds>", s)); } requestBuilder.append(format("<loadBalancerId>%s</loadBalancerId>", payload.id())) .append("</request>") .append("</ws:deregisterServersOnLoadBalancer>"); return requestBuilder.toString(); }
Source:
START protected LoadBalancerListResponseHandler(DateCodecFactory dateCodec, ServerListResponseHandler balancedServerResponseHandler, FirewallListResponseHandler firewallListResponseHandler) { END super(dateCodec, balancedServerResponseHandler, firewallListResponseHandler); this.loadBalancers = Lists.newArrayList(); } Make this package private.

Target:
LoadBalancerListResponseHandler(DateCodecFactory dateCodec, ServerListResponseHandler balancedServerResponseHandler, FirewallListResponseHandler firewallListResponseHandler) { super(dateCodec, balancedServerResponseHandler, firewallListResponseHandler); this.loadBalancers = Lists.newArrayList(); }
Source:
public void testGetAllLoadBalancers() { List<LoadBalancer> loadBalancers = api.loadBalancerApi().getAllLoadBalancers(); START assertNotNull(loadBalancers); END assertFalse(loadBalancers.isEmpty()); } The API should never return null lists. Remove this. Also, should this be executed after creating the load balancer?

Target:
public void testGetAllLoadBalancers() { List<LoadBalancer> loadBalancers = api.loadBalancerApi().getAllLoadBalancers(); assertFalse(loadBalancers.isEmpty()); }
Source:
public void testGetLoadBalancer() { LoadBalancer loadBalancer = api.loadBalancerApi().getLoadBalancer(loadBalancerID); START System.out.println(loadBalancer); END assertNotNull(loadBalancer); } Remove this

Target:
public void testGetLoadBalancer() { LoadBalancer loadBalancer = api.loadBalancerApi().getLoadBalancer(loadBalancerID); assertNotNull(loadBalancer); }
Source:
protected void checkPortRange() { checkArgument((portRangeEnd == null && portRangeStart == null) START || (portRangeEnd != null && portRangeStart != null), "Port range must be both present or null"); END if (portRangeEnd != null) { checkArgument(protocol == Protocol.TCP || protocol == Protocol.UDP, "Port range can only be set for TCP or UDP"); checkArgument(portRangeEnd > portRangeStart, "portRangeEnd must be greater than portRangeStart"); checkArgument(portRangeEnd >= 1 && portRangeEnd <= 65534, "Port range end must be 1 to 65534"); checkArgument(portRangeStart >= 1 && portRangeStart <= 65534, "Port range start must be 1 to 65534"); } } [nit] This can be more concise: ``` java checkArgument(!(portRangeEnd == null ^ portRangeStart == null), "Port range must be both present or null"); ```

Target:
protected void checkPortRange() { checkArgument(!(portRangeEnd == null ^ portRangeStart == null), "Port range must be both present or null"); if (portRangeEnd != null) { checkArgument(protocol == Protocol.TCP || protocol == Protocol.UDP, "Port range can only be set for TCP or UDP"); checkArgument(portRangeEnd > portRangeStart, "portRangeEnd must be greater than portRangeStart"); checkArgument(portRangeEnd >= 1 && portRangeEnd <= 65534, "Port range end must be 1 to 65534"); checkArgument(portRangeStart >= 1 && portRangeStart <= 65534, "Port range start must be 1 to 65534"); } }
Source:
public static Properties defaultProperties() { Properties properties = BaseHttpApiMetadata.defaultProperties(); properties.setProperty(Constants.PROPERTY_MAX_RETRIES, "5"); START properties.setProperty(ShipyardProperties.SHIPYARD_CREDENTIAL, "<remote-service-key-given-by-shipyard-cli>"); END return properties; } Is this a _good_ value for this property? Will the Api work if users don't override it? Should this value be passed as the credential?

Target:
public static Properties defaultProperties() { return BaseHttpApiMetadata.defaultProperties(); }
Source:
START public ServiceKeyAuthentication(@Provider Supplier<Credentials> creds) { END this.creds = checkNotNull(creds, "creds"); } Make the constructor package protected. This way you make sure it is only used by the Guice injector, which will already enforce the parameters to be present. Then you can also remove the `checkNotNull` check.

Target:
ServiceKeyAuthentication(@Provider Supplier<Credentials> creds) { this.creds = creds; }
Source:
START public String parseMessage(HttpResponse response) { END if (response.getPayload() == null) return null; try { return Strings2.toStringAndClose(response.getPayload().openStream()); } catch (IOException e) { throw Throwables.propagate(e); } } Make this method private

Target:
private String parseMessage(HttpResponse response) { if (response.getPayload() == null) return null; try { return Strings2.toStringAndClose(response.getPayload().openStream()); } catch (IOException e) { throw Throwables.propagate(e); } }
Source:
public Builder securityOpts(List<String> securityOpts) { START this.securityOpts = ImmutableList.copyOf(checkNotNull(securityOpts, "securityOpts")); END return this; } weird indent. also this class is inconsistent on safe copies. as auto will likely generate builders and these won't do safe copies, better to just not do it, and ensure whoever is calling this safe copies in.

Target:
public Builder securityOpts(List<String> securityOpts) { this.securityOpts = securityOpts; return this; }
Source:
public void testList() { List<CloudService> response = api().list(); START for (CloudService cloudService : api().list()) { END checkHostedService(cloudService); } if (!response.isEmpty()) { CloudService cloudService = response.iterator().next(); assertEquals(api().get(cloudService.name()), cloudService); } } [minor] `for (CS cloudService : response)`?

Target:
public void testList() { List<CloudService> response = api().list(); for (CloudService cloudService : response) { checkHostedService(cloudService); } if (!response.isEmpty()) { CloudService cloudService = response.iterator().next(); assertEquals(api().get(cloudService.name()), cloudService); } }
Source:
public String toString() { START return MoreObjects.toStringHelper(this).omitNullValues().add("code", code).add("message", message).toString(); END } [minor] The new implementations elsewhere seem to remove `omitNullValues`. Intentionally left here? What does `@AutoValue` do?

Target:
public String toString() { return toStringHelper(this).add("code", code).add("message", message).toString(); }
Source:
START public BaseDataCenterResponseHandler(DateCodecFactory dateCodecFactory) { END super(dateCodecFactory); this.builder = DataCenter.builder(); } Guice best practices: make this constructor visible only at package level.

Target:
BaseDataCenterResponseHandler(DateCodecFactory dateCodecFactory) { super(dateCodecFactory); this.builder = DataCenter.builder(); }
Source:
START public DataCenterListResponseHandler(DateCodecFactory dateCodec) { END super(dateCodec); this.dataCenters = Lists.newArrayList(); } Injected constructor should be package private.

Target:
DataCenterListResponseHandler(DateCodecFactory dateCodec) { super(dateCodec); this.dataCenters = Lists.newArrayList(); }
Source:
START public BaseProfitBricksRequestBinder(String paramName) { END this.paramName = checkNotNull(paramName, "Initialize 'paramName' in constructor"); } This should be only created by the Guice injector. Make the constructor `protected`.

Target:
protected BaseProfitBricksRequestBinder(String paramName) { this.paramName = checkNotNull(paramName, "Initialize 'paramName' in constructor"); }
Source:
START public CreateDataCenterRequestBinder() { END super("dataCenter"); this.requestBuilder = new StringBuilder(128); } This constructor should be only called by the Guice injector. Make it package private by removing the `public` modifier.

Target:
CreateDataCenterRequestBinder() { super("dataCenter"); this.requestBuilder = new StringBuilder(128); }
Source:
public void testCreateDataCenterWithIllegalArguments() throws Exception { String[] names = {"JCl@ouds", "JC|ouds", "^clouds", ""}; for (String name : names) try { DataCenter.Request.CreatePayload.create(name, Location.US_LAS); fail("Should have failed for name: ".concat(name)); } catch (Exception ex) { START assertTrue(ex instanceof IllegalArgumentException); END } } Why not just catching the `IllegalArgumentException`?

Target:
public void testCreateDataCenterWithIllegalArguments() throws Exception { String[] names = {"JCl@ouds", "JC|ouds", "^clouds", ""}; for (String name : names) { try { DataCenter.Request.CreatePayload.create(name, Location.US_LAS); fail("Should have failed for name: ".concat(name)); } catch (IllegalArgumentException ex) { // expected exception } } }
Source:
public Volume apply(ServerDrive serverDrive) { VolumeBuilder builder = new VolumeBuilder(); DriveInfo driveInfo = api.getDriveInfo(serverDrive.getDriveUuid()); builder.id(driveInfo.getUuid()); builder.size(driveInfo.getSize().floatValue()); builder.durable(true); builder.type(Volume.Type.NAS); START builder.bootDevice(serverDrive.getBootOrder() > 0); END return builder.build(); } Just checking...boot order _greater_ than zero means this is a boot device?

Target:
public Volume apply(ServerDrive serverDrive) { VolumeBuilder builder = new VolumeBuilder(); DriveInfo driveInfo = api.getDriveInfo(serverDrive.getDriveUuid()); builder.id(driveInfo.getUuid()); builder.size(driveInfo.getSize().floatValue()); builder.durable(true); builder.type(Volume.Type.NAS); builder.bootDevice(serverDrive.getBootOrder() != null); return builder.build(); }
Source:
private Function<String, OsFamily> osFamily() { return new Function<String, OsFamily>() { START OsFamily osFamily = OsFamily.UNRECOGNIZED; END @Override public OsFamily apply(final String description) { if (description != null) { if (description.contains(CENTOS)) osFamily = OsFamily.CENTOS; else if (description.contains(UBUNTU)) osFamily = OsFamily.UBUNTU; } logger.debug("os family for item: %s is %s", description, osFamily); return osFamily; } }; } There is no need for this local variable. Just return directly the detected os family.

Target:
private Function<String, OsFamily> osFamily() { return new Function<String, OsFamily>() { @Override public OsFamily apply(final String description) { if (description != null) { if (description.contains(CENTOS)) return OsFamily.CENTOS; else if (description.contains(UBUNTU)) return OsFamily.UBUNTU; } return OsFamily.UNRECOGNIZED; } }; }
Source:
public static Properties defaultProperties() { Properties properties = BaseHttpApiMetadata.defaultProperties(); properties.setProperty(Constants.PROPERTY_MAX_RETRIES, "15"); properties.setProperty("jclouds.ssh.retry-auth", "true"); properties.setProperty(Constants.PROPERTY_CONNECTION_TIMEOUT, "1200000"); // 15 minutes START properties.setProperty("image.login-user", "root"); END properties.setProperty(ComputeServiceProperties.IMAGE_LOGIN_USER, "root:password"); properties.setProperty(TEMPLATE, "osFamily=UBUNTU,os64Bit=true,osVersionMatches=1[012].[01][04]"); return properties; } Where is this property (without the jclouds prefix) used?

Target:
public static Properties defaultProperties() { Properties properties = BaseHttpApiMetadata.defaultProperties(); properties.setProperty(Constants.PROPERTY_MAX_RETRIES, "15"); properties.setProperty("jclouds.ssh.retry-auth", "true"); properties.setProperty(Constants.PROPERTY_CONNECTION_TIMEOUT, "1200000"); // 15 minutes properties.setProperty(ComputeServiceProperties.IMAGE_LOGIN_USER, "root:password"); properties.setProperty(TEMPLATE, "osFamily=UBUNTU,os64Bit=true,osVersionMatches=1[012].[01][04]"); return properties; }
Source:
public String parseMessage(HttpResponse response) { if (response.getPayload() == null) return null; try { return Strings2.toString(response.getPayload()); } catch (IOException e) { throw Throwables.propagate(e); } finally { try { START response.getPayload().getInput().close(); END } catch (IOException e) { throw Throwables.propagate(e); } } } The payload itself is already closeable. Close the payload to avoid the deprecation warning?

Target:
public String parseMessage(HttpResponse response) { if (response.getPayload() == null) return null; try { return Strings2.toString(response.getPayload()); } catch (IOException e) { throw Throwables.propagate(e); } finally { try { response.getPayload().close(); } catch (IOException e) { throw Throwables.propagate(e); } } }
Source:
public void write(JsonWriter out, PublicKey value) throws IOException { checkArgument(value instanceof RSAPublicKey || value instanceof DSAPublicKey, "Only RSA and DSA keys are supported"); if (value instanceof RSAPublicKey) { out.value(SshKeys.encodeAsOpenSSH((RSAPublicKey) value)); } else { out.value(DSAKeys.encodeAsOpenSSH((DSAPublicKey) value)); START } END } Could save one check like this, but up to you: ``` if (value instanceof RSAPublicKey) { .. } else if (value instanceof DSAPublicKey) { .. } else { throw new ... } ```

Target:
public void write(JsonWriter out, PublicKey value) throws IOException { if (value instanceof RSAPublicKey) { out.value(SshKeys.encodeAsOpenSSH((RSAPublicKey) value)); } else if (value instanceof DSAPublicKey) { out.value(DSAKeys.encodeAsOpenSSH((DSAPublicKey) value)); } else { throw new IllegalArgumentException("Only RSA and DSA keys are supported"); } }
Source:
public static Distribution fromValue(String value) { START return tryFind(asList(Distribution.values()), hasValue(value)).or(UNRECOGNIZED); END } Make a static variable for `asList(Distribution.values()`?

Target:
public static Distribution fromValue(String value) { return tryFind(values, hasValue(value)).or(UNRECOGNIZED); }
Source:
public ImageTemplate buildImageTemplateFromNode(String name, String id) { Droplet droplet = null; try { droplet = api.getDropletApi().get(Integer.valueOf(id)); START } catch (Exception ex) { END throw new NoSuchElementException("Cannot find droplet with id: " + id); } if (droplet == null) { throw new NoSuchElementException("Cannot find droplet with id: " + id); } return new ImageTemplateBuilder.CloneImageTemplateBuilder().nodeId(id).name(name).build(); } That catch should be removed. It was just a guard, before the provider had properly implemented the error/retry handlers.

Target:
public ImageTemplate buildImageTemplateFromNode(String name, String id) { Droplet droplet = api.getDropletApi().get(Integer.valueOf(id)); if (droplet == null) { throw new NoSuchElementException("Cannot find droplet with id: " + id); } return new ImageTemplateBuilder.CloneImageTemplateBuilder().nodeId(id).name(name).build(); }
Source:
public CalcSubscription build() { return new CalcSubscription(amount, discountAmount, discountPercent, endTime, period, price, resource START , startTime); END } Formatting: move `,` to the end of the previous line?

Target:
public CalcSubscription build() { return new CalcSubscription(amount, discountAmount, discountPercent, period, price, resource, startTime, endTime); }
Source:
protected Function<Object, IterableWithMarker<Discount>> markerToNextForArgs(List<Object> args) { return new Function<Object, IterableWithMarker<Discount>>() { @Override START public IterableWithMarker<Discount> apply(@Nullable Object input) { END PaginationOptions paginationOptions = PaginationOptions.class.cast(input); return api.listDiscounts(paginationOptions); } }; } This function will only be called when the marker is present, so in practice the `input` parameter won't be null. Remove the `@Nullable` annotation (apply this to all parser classes).

Target:
protected Function<Object, IterableWithMarker<Discount>> markerToNextForArgs(List<Object> args) { return new Function<Object, IterableWithMarker<Discount>>() { @Override public IterableWithMarker<Discount> apply(Object input) { PaginationOptions paginationOptions = PaginationOptions.class.cast(input); return api.listDiscounts(paginationOptions); } }; }
Source:
START VLANs(Iterable<VLANInfo> objects, PaginationOptions paginationOptions) { END super(objects, paginationOptions); } Why is this constructor package protected?

Target:
public VLANs(Iterable<VLANInfo> objects, PaginationOptions paginationOptions) { super(objects, paginationOptions); }
Source:
public UserOptions build() { UserOptions options = new UserOptions(); if ( limit != null ) { options.queryParameters.put("numResults", String.valueOf(limit)); // Remove the "limit" parameter: it has been replaced by "numResults" limit = null; } if ( page != null ) { options.queryParameters.put("page", String.valueOf(page)); START } END return addFilterOptions(options); } You could avoid the `if` statements by simply declaring the `UserOptions` instance in the builder directly, and modifying that: ``` public Builder { private final UserOptions options = new UserOptions(); public Builder page(int page) { options.queryParameters.put("page", String.valueOf(page)); return this; } ... public UserOptions build() { return addFilterOptions(options); } } ```

Target:
public UserOptions build() { return addFilterOptions(this.options); }
Source:
protected Image(String id, Date creationTimestamp, URI selfLink, String name, String description, String sourceType, URI preferredKernel, RawDisk rawDisk, Deprecated deprecated) { super(Kind.IMAGE, id, creationTimestamp, selfLink, name, description); this.sourceType = checkNotNull(sourceType, "sourceType of %s", name); this.preferredKernel = fromNullable(preferredKernel); this.rawDisk = checkNotNull(rawDisk, "rawDisk of %s", name); this.deprecated = fromNullable(deprecated); START ; END } Remove?

Target:
protected Image(String id, Date creationTimestamp, URI selfLink, String name, String description, String sourceType, URI preferredKernel, RawDisk rawDisk, Deprecated deprecated) { super(Kind.IMAGE, id, creationTimestamp, selfLink, name, description); this.sourceType = checkNotNull(sourceType, "sourceType of %s", name); this.preferredKernel = fromNullable(preferredKernel); this.rawDisk = checkNotNull(rawDisk, "rawDisk of %s", name); this.deprecated = fromNullable(deprecated); }
Source:
public void deleteTempFileAndFolder() { try { if ( aliasingIsActive() ) { FileObject srcFile = KettleVFS.getFileObject( temporaryFilePath, variableSpace ); srcFile.getParent().deleteAll(); } } catch ( FileSystemException | KettleFileException e ) { START log.logError( e.getMessage() ); END } } Can you add the exception as the second parameter? Otherwise we won't be able to tell where the error happened from just the message.

Target:
public void deleteTempFileAndFolder() { try { if ( aliasingIsActive() ) { FileObject srcFile = KettleVFS.getFileObject( temporaryFilePath, variableSpace ); srcFile.getParent().deleteAll(); } } catch ( FileSystemException | KettleFileException e ) { log.logError( e.getMessage(), e ); } }
Source:
public Builder addMember(MemberRef member) { START this.members.add(member); END return this; } You can omit the `this.`.

Target:
public Builder addMember(MemberRef member) { members.add(member); return this; }
Source:
public void onEntityPathfind(EntityPathfindEvent event) { this.event = event; Entity entity = event.getEntity(); Entity target = event.getTargetEntity(); this.entity = new EntityTag(entity); this.target = target != null ? new EntityTag(target) : null; EntityTag.rememberEntity(entity); START EntityTag.rememberEntity(target); END fire(event); EntityTag.forgetEntity(entity); EntityTag.forgetEntity(target); } These remember/forgets shouldn't be here.

Target:
public void onEntityPathfind(EntityPathfindEvent event) { this.event = event; this.entity = new EntityTag(event.getEntity()); Entity target = event.getTargetEntity(); this.target = target != null ? new EntityTag(target) : null; fire(event); }
Source:
public static void registerTags() { // <--[tag] // @attribute <MaterialTag.leaf_size> // @returns ElementTag // @mechanism MaterialTag.leaf_size // @group properties // @description // Returns the size of the leaves for this bamboo block. // Output is SMALL, LARGE, or NONE. // --> PropertyParser.<MaterialBamboo>registerTag("leaf_size", (attribute, material) -> { START return new ElementTag(String.valueOf(material.getBamboo().getLeaves())); END }); } `.name()` to stringify an enum.

Target:
public static void registerTags() { // <--[tag] // @attribute <MaterialTag.leaf_size> // @returns ElementTag // @mechanism MaterialTag.leaf_size // @group properties // @description // Returns the size of the leaves for this bamboo block. // Output is SMALL, LARGE, or NONE. // --> PropertyParser.<MaterialBamboo>registerTag("leaf_size", (attribute, material) -> { return new ElementTag(material.getBamboo().getLeaves().name()); }); }
Source:
public int getMax() { if (isCake()) { return getCake().getMaximumBites(); } START if (isSnow()) { END return getSnow().getMaximumLayers(); } else if (isHive()) { return getMaxHoneyLevel(); } return getLevelled().getMaximumLevel(); } This should be an `else`

Target:
public int getMax() { if (isCake()) { return getCake().getMaximumBites(); } else if (isSnow()) { return getSnow().getMaximumLayers(); } else if (isHive()) { return getMaxHoneyLevel(); } return getLevelled().getMaximumLevel(); }
Source:
public static void init() { Debug.log("Loading Paper support module..."); // Events ScriptEvent.registerScriptEvent(new PlayerEquipsArmorScriptEvent()); ScriptEvent.registerScriptEvent(new PlayerJumpsPaperScriptEventImpl()); ScriptEvent.registerScriptEvent(new PlayerSpectatesEntityScriptEvent()); START ScriptEvent.registerScriptEvent(new EntityKnocksbackEntityScriptEvent()); END ScriptEvent.registerScriptEvent(new PlayerStopsSpectatingScriptEvent()); ScriptEvent.registerScriptEvent(new ProjectileCollideScriptEvent()); ScriptEvent.registerScriptEvent(new TNTPrimesScriptEvent()); // Properties PropertyParser.registerProperty(EntityCanTick.class, EntityTag.class); } This list should be alphabetized (just look at the order of events in your IntelliJ class listing)

Target:
public static void init() { Debug.log("Loading Paper support module..."); // Events ScriptEvent.registerScriptEvent(new EntityKnocksbackEntityScriptEvent()); ScriptEvent.registerScriptEvent(new PlayerEquipsArmorScriptEvent()); ScriptEvent.registerScriptEvent(new PlayerJumpsPaperScriptEventImpl()); ScriptEvent.registerScriptEvent(new PlayerSpectatesEntityScriptEvent()); ScriptEvent.registerScriptEvent(new PlayerStopsSpectatingScriptEvent()); ScriptEvent.registerScriptEvent(new ProjectileCollideScriptEvent()); ScriptEvent.registerScriptEvent(new TNTPrimesScriptEvent()); // Properties PropertyParser.registerProperty(EntityCanTick.class, EntityTag.class); }
Source:
public ScriptEntryData getScriptEntryData() { START return new BukkitScriptEntryData(event != null ? EntityTag.getPlayerFrom(event.getPlayer()) : null, null); END } What's with the null check?

Target:
public ScriptEntryData getScriptEntryData() { return new BukkitScriptEntryData(EntityTag.getPlayerFrom(event.getPlayer()), null); }
Source:
public String getPropertyString() { START return entity.getBukkitEntity() instanceof Creeper ? ((Creeper) entity.getBukkitEntity()).getMaxFuseTicks() + "" : null; END } Unneeded tern (it's always a creeper if it's reading this line)

Target:
public String getPropertyString() { return String.valueOf(((Creeper) entity.getBukkitEntity()).getMaxFuseTicks()); }
Source:
public void adjust(Mechanism mechanism) { // <--[mechanism] // @object dEntity // @name max_fuse_ticks // @input Element(Integer) // @description // Sets the number of fuse ticks a creeper will default to when not triggered // @tags // <e@entity.max_fuse_ticks> // --> START if (mechanism.matches("max_fuse_ticks") && entity.getBukkitEntity() instanceof Creeper && mechanism.requireInteger()) { END ((Creeper) entity.getBukkitEntity()).setMaxFuseTicks(mechanism.getValue().asInt()); } } unneeded instanceof check for same reason as above

Target:
public void adjust(Mechanism mechanism) { // <--[mechanism] // @object dEntity // @name max_fuse_ticks // @input Element(Number) // @description // Sets the default number of ticks until the creeper explodes when primed (NOT the time remaining if already primed). // @tags // <e@entity.max_fuse_ticks> // --> if (mechanism.matches("max_fuse_ticks") && mechanism.requireInteger()) { ((Creeper) entity.getBukkitEntity()).setMaxFuseTicks(mechanism.getValue().asInt()); } }
Source:
public String getAttribute(Attribute attribute) { if (attribute == null) { return null; } // <--[tag] // @attribute <e@entity.max_fuse_ticks> // @returns Element(Integer) // @mechanism dEntity.max_fuse_ticks // @group properties // @description // Returns the number of fuse ticks a creeper will default to when not triggered. // --> START if (attribute.startsWith("max_fuse_ticks") && entity.getBukkitEntity() instanceof Creeper) { END return new Element(((Creeper) entity.getBukkitEntity()).getMaxFuseTicks()) .getAttribute(attribute.fulfill(1)); } return null; } unneeded check

Target:
public String getAttribute(Attribute attribute) { if (attribute == null) { return null; } // <--[tag] // @attribute <e@entity.max_fuse_ticks> // @returns Element(Number) // @mechanism dEntity.max_fuse_ticks // @group properties // @description // Returns the default number of ticks until the creeper explodes when primed (NOT the time remaining if already primed). // --> if (attribute.startsWith("max_fuse_ticks")) { return new Element(((Creeper) entity.getBukkitEntity()).getMaxFuseTicks()) .getAttribute(attribute.fulfill(1)); } return null; }
Source:
public void adjust(Mechanism mechanism) { CoreUtilities.autoPropertyMechanism(this, mechanism); if (!mechanism.fulfilled()) { START mechanism.reportInvalid(); END } } remove that bit^

Target:
public void adjust(Mechanism mechanism) { CoreUtilities.autoPropertyMechanism(this, mechanism); }
Source:
public Boolean getUserPropertyAsBoolean(String propertyKey) { String userProperty = this.getUserProperty(propertyKey); START if(userProperty != null && "1".equals(userProperty)) { END return true; } else { return false; } } Mixed tabs and spaces. Also `return userProperty != null && "1".equals(userProperty);` :P

Target:
public Boolean getUserPropertyAsBoolean(String propertyKey) { String userProperty = this.getUserProperty(propertyKey); return userProperty != null && "1".equals(userProperty); }
Source:
public synchronized void onSchoolDataWorkspaceUserDiscoveredEvent(@Observes SchoolDataWorkspaceUserDiscoveredEvent event) { //kun kurssille pelmahtaa uusi opiskelija START UserEntity userEntity = userEntityController.findUserEntityByDataSourceAndIdentifier(event.getUserDataSource(), event.getUserIdentifier()); END String userIdentifier = userEntity.getDefaultIdentifier(); String userDataSource = userEntity.getDefaultSchoolDataSource().getIdentifier(); SchoolDataIdentifier user = new SchoolDataIdentifier(userIdentifier, userDataSource); chatSyncController.syncStudent(user); } Riittäisikö tässäkin käyttää event.getUserDataSource() ja event.getUserIdentifier() sen sijaan, että haetaan userEntity ja käytetään sen default identifieriä?

Target:
public synchronized void onSchoolDataWorkspaceUserDiscoveredEvent(@Observes SchoolDataWorkspaceUserDiscoveredEvent event) { //kun kurssille pelmahtaa uusi opiskelija String userIdentifier = event.getUserIdentifier(); String userDataSource = event.getUserDataSource(); SchoolDataIdentifier user = new SchoolDataIdentifier(userIdentifier, userDataSource); chatSyncController.syncStudent(user); }
Source:
public static boolean isNullOrBlank(String string) { if (string == null) { return true; } int length = string.length(); if (length > 0) { for (int i = 0; i < length; i++) { if (!Character.isWhitespace(string.charAt(i))) { return false; } } } START return true; END } Could we move this to a util class that's clearly marked as non-public api?

Target:
private static boolean isNullOrBlank(String string) { if (string == null) { return true; } int length = string.length(); if (length > 0) { for (int i = 0; i < length; i++) { if (!Character.isWhitespace(string.charAt(i))) { return false; } } } return true; }
Source:
private boolean isDepositRecord(Resource bxc3Resc) { START PIDs.get(bxc3Resc.toString().toLowerCase()); END return bxc3Resc.hasProperty(FedoraProperty.hasModel.getProperty(), ContentModel.DEPOSIT_RECORD.getResource()); } this line can be removed

Target:
private boolean isDepositRecord(Resource bxc3Resc) { return bxc3Resc.hasProperty(FedoraProperty.hasModel.getProperty(), ContentModel.DEPOSIT_RECORD.getResource()); }
Source:
public PID getTransformedPid(PID originalPid) { return generateIds ? pidMinter.mintDepositRecordPid() : PIDs.get(DEPOSIT_RECORD_BASE, START originalPid.getUUID().toLowerCase()); END } For the sake of consistency, use `getId()` instead of `getUUID()`, since you are doing that for the other lowercase calls.

Target:
public PID getTransformedPid(PID originalPid) { return generateIds ? pidMinter.mintDepositRecordPid() : PIDs.get(DEPOSIT_RECORD_BASE, originalPid.getId().toLowerCase()); }
Source:
private boolean hasAccess(PID pid, String datastream) { // Defaults to jp2 surrogate START if (datastream.equals("IMAGE_JP2000") || datastream == null) { END datastream = JP2_ACCESS_COPY.getId(); } Permission permission = DatastreamPermissionUtil.getPermissionForDatastream(datastream); AgentPrincipals agent = AgentPrincipals.createFromThread(); LOG.debug("Checking if user has access to belonging to object {}.", agent.getUsername(), datastream, pid); return accessControlService.hasAccess(pid, agent.getPrincipals(), permission); } hmm, IMAGE_JP2000 is the boxc3 name for the datastream. Might be better to update `JP2Viewer.js` to request datastreams `jp2` (I think that's the current datastream name). Its kind of funny that `hasAccess` has this default datastream behavior but the actual controller methods both require the datastream name in the path.

Target:
private boolean hasAccess(PID pid, String datastream) { // Defaults to jp2 surrogate if (datastream == null) { datastream = JP2_ACCESS_COPY.getId(); } Permission permission = DatastreamPermissionUtil.getPermissionForDatastream(datastream); AgentPrincipals agent = AgentPrincipals.createFromThread(); LOG.debug("Checking if user has access to belonging to object {}.", agent.getUsername(), datastream, pid); return accessControlService.hasAccess(pid, agent.getPrincipals(), permission); }
Source:
START byte[] textStream() { END return "I am not an image".getBytes(); } make method private

Target:
private byte[] textStream() { return "I am not an image".getBytes(); }
Source:
private void setStaffOnly(Resource resc, Model model) { Map<String, String> depositStatus = getDepositStatus(); String staffOnly = depositStatus.get(DepositField.staffOnly.name()); START if (Boolean.parseBoolean(staffOnly)) { END model.add(resc, CdrAcl.none, PUBLIC_PRINC); model.add(resc, CdrAcl.none, AUTHENTICATED_PRINC); } } You only need to make the determination that the deposit is staff only once, i'd suggest checking this before line 54 `Model model = getWritableModel();` and doing an early return if not staff only. Alternatively, you could remove the check since the check is (trying to) happen in the DepositSupervisor.

Target:
private void setStaffOnly(Resource resc, Model model) { model.add(resc, CdrAcl.none, PUBLIC_PRINC); model.add(resc, CdrAcl.none, AUTHENTICATED_PRINC); }
Source:
private Boolean hasExistingTitle(Element mods) { START Boolean hasOldTitle; END try { Element title = mods.getChild("titleInfo", MODS_V3_NS).getChild("title", MODS_V3_NS); hasOldTitle = true; } catch (NullPointerException e) { hasOldTitle = false; } return hasOldTitle; } you can skip going through a variable and immediately return true or false (its fine to return in the `catch` block). Also, the return type probably doesn't need to be a `Boolean` in this case, the primative `boolean` should be fine.

Target:
private boolean hasExistingTitle(Element mods) { boolean hasOldTitle; try { Element title = mods.getChild("titleInfo", MODS_V3_NS).getChild("title", MODS_V3_NS); hasOldTitle = true; } catch (NullPointerException e) { hasOldTitle = false; } return hasOldTitle; }
Source:
public static synchronized RegistryService getInstance() { RegistryService local = instance; START if (local == null) { END local = new RegistryService(); instance = local; // associates a reporter with the current registry ReporterFactory.getOrCreateReporter(); } return local; } Why not test and assign `instance` directly rather than passing it through `local`?

Target:
public static synchronized RegistryService getInstance() { if (instance == null) { instance = new RegistryService(); // associates a reporter with the current registry ReporterFactory.getOrCreateReporter(); } return instance; }
Source:
START protected BinaryMetadataProcessor(String baseBinaryPath) { END this.baseBinaryPath = baseBinaryPath; if (!baseBinaryPath.endsWith("/")) { this.baseBinaryPath += "/"; } } should this constructor really have protected access? other processors look like they have public constructors

Target:
public BinaryMetadataProcessor(String baseBinaryPath) { this.baseBinaryPath = baseBinaryPath; if (!baseBinaryPath.endsWith("/")) { this.baseBinaryPath += "/"; } }
Source:
public BinaryObject replaceOriginalFile(InputStream contentStream, String filename, String mimetype, String sha1Checksum, String md5Checksum) { // Construct the path to where the original file will be created String objectPath = constructOriginalFilePath(); // Add the OriginalFile use type START Model fileModel = ModelFactory.createDefaultModel(); END Resource resc = fileModel.createResource(objectPath); resc.addProperty(RDF.type, PcdmUse.OriginalFile); return repoObjFactory.updateBinary(fileSetUri, ORIGINAL_FILE, contentStream, filename, mimetype, sha1Checksum, md5Checksum, fileModel); } After thinking about it some, I don't think replaceOriginalFile needs to be providing a model. Nothing is changing about its properties, so this is pretty much refreshing them. If we need to replace its properties at a later point there are other ways to do that.

Target:
public BinaryObject replaceOriginalFile(InputStream contentStream, String filename, String mimetype, String sha1Checksum, String md5Checksum) { return repoObjFactory.updateBinary(fileSetUri, ORIGINAL_FILE, contentStream, filename, mimetype, sha1Checksum, md5Checksum, null); }
Source:
public void testMODSGetsUpdated() throws Exception { populateFedora("uuid:ae0091e0-192d-46f9-a8ad-8b0dc82f33ad"); InputStream originalMods = workObj.getMODS().getBinaryStream(); assertModsNotUpdated(originalMods); importFile = createTempImportFile("src/test/resources/mods/update-work-mods.xml"); createJob(); job.run(); verify(mailSender).send(any(MimeMessage.class)); START InputStream updatedMods = objLoader.getWorkObject(workObj.getPid()).getMODS().getBinaryStream(); END assertModsUpdated(updatedMods); } Mainly wondering, but if you just called `workObj.getMODS()` would that reflect the updated MODS? I don't think its caching that.

Target:
public void testMODSGetsUpdated() throws Exception { populateFedora("uuid:ae0091e0-192d-46f9-a8ad-8b0dc82f33ad"); InputStream originalMods = workObj.getMODS().getBinaryStream(); assertModsNotUpdated(originalMods); importFile = createTempImportFile("src/test/resources/mods/update-work-mods.xml"); createJob(); job.run(); verify(mailSender).send(any(MimeMessage.class)); InputStream updatedMods = workObj.getMODS().getBinaryStream(); assertModsUpdated(updatedMods); }
Source:
private void moveObject(PID objPid) { aclService.assertHasAccess("Agent " + agent.getUsername() + " does not have permission to move object " + objPid, objPid, agent.getPrincipals(), Permission.move); RepositoryObject moveObj = repositoryObjectLoader.getRepositoryObject(objPid); START ContentObject moveContent = (ContentObject) moveObj; END destroyProxy(objPid); destContainer.addMember(moveContent); } can't lines 149-150 be combined?

Target:
private void moveObject(PID objPid) { aclService.assertHasAccess("Agent " + agent.getUsername() + " does not have permission to move object " + objPid, objPid, agent.getPrincipals(), Permission.move); ContentObject moveContent = (ContentObject) repositoryObjectLoader.getRepositoryObject(objPid); destroyProxy(objPid); destContainer.addMember(moveContent); }
Source:
public void init() throws Exception { createBaseContainer(RepositoryPathConstants.CONTENT_BASE); START repoObjLoader.init(); END } I'd suggest calling this `init` method from the context file instead

Target:
public void init() throws Exception { createBaseContainer(RepositoryPathConstants.CONTENT_BASE); }
Source:
private List<PID> makePidList(int numPids) { START List<PID> pids = new ArrayList<PID>(); END int i = 0; while(i < numPids) { PID pidMock = mock(PID.class); when(pidMock.getId()).thenReturn("uuid:" + UUID.randomUUID().toString()); pids.add(pidMock); i++; } return pids; } Change to `new ArrayList<>();`

Target:
private List<PID> makePidList(int numPids) { List<PID> pids = new ArrayList<>(); int i = 0; while(i < numPids) { PID pidMock = mock(PID.class); when(pidMock.getId()).thenReturn("uuid:" + UUID.randomUUID().toString()); pids.add(pidMock); i++; } return pids; }
Source:
public void testBadReplicationLocations() throws Exception { START processor = new ReplicationProcessor(repository, badReplicationLocations, maxRetries, retryDelay); END try { processor.process(exchange); } finally { verify(processor).equals(ReplicationDestinationUnavailableException.class); } } This method ends on this line. It would be clearer to remove the rest of the method

Target:
public void testBadReplicationLocations() throws Exception { processor = new ReplicationProcessor(repository, badReplicationLocations, maxRetries, retryDelay); }
Source:
public void testEventTypeFilter() throws Exception { getMockEndpoint("mock:direct:fulltext.filter").expectedMessageCount(0); createContext(ENHANCEMENT_ROUTE); Map<String, Object> headers = createEvent(FILE_ID, EVENT_TYPES); START headers.put(EVENT_TYPE, "ResourceDeletion"); END template.sendBodyAndHeaders("", headers); assertMockEndpointsSatisfied(); } Might as well just pass this event type to `createEvent` instead of `EVENT_TYPES`. Also, shouldn't the event type begin with `EVENT_NS`?

Target:
public void testEventTypeFilter() throws Exception { getMockEndpoint("mock:direct:fulltext.filter").expectedMessageCount(0); createContext(ENHANCEMENT_ROUTE); Map<String, Object> headers = createEvent(FILE_ID); headers.put(EVENT_TYPE, "ResourceDeletion"); template.sendBodyAndHeaders("", headers); assertMockEndpointsSatisfied(); }
Source:
public void addWorkMemberTest() { unit.addMember(workChildObj); ArgumentCaptor<ContentObject> captor = ArgumentCaptor.forClass(ContentObject.class); START verify(repository).addMember(eq(unit), captor.capture()); END ContentObject child = captor.getValue(); assertFalse("Should not be able to add Work to AdminUnit", child instanceof WorkObject); } What is actually returned here? Isn't it supposed to throw an exception for an invalid member type?

Target:
public void addWorkMemberTest() { unit.addMember(workChildObj); }
Source:
private URI createContentRoot(URI contentUri) { String contentRootString = URIUtil.join( contentUri, RepositoryPathConstants.CONTENT_ROOT_ID); URI contentRootUri = URI.create(contentRootString); // Don't initialize the object if it is already present. if (objectExists(contentRootUri)) { START return contentUri; END } Model model = ModelFactory.createDefaultModel(); Resource resc = model.createResource(contentRootString); resc.addProperty(DC.title, "Content Collections Root"); objFactory.createContentRootObject(contentRootUri, model); return contentRootUri; } Should this return contentRootUri?

Target:
private URI createContentRoot(URI contentUri) { String contentRootString = URIUtil.join( contentUri, RepositoryPathConstants.CONTENT_ROOT_ID); URI contentRootUri = URI.create(contentRootString); // Don't initialize the object if it is already present. if (objectExists(contentRootUri)) { return contentRootUri; } Model model = ModelFactory.createDefaultModel(); Resource resc = model.createResource(contentRootString); resc.addProperty(DC.title, "Content Collections Root"); objFactory.createContentRootObject(contentRootUri, model); return contentRootUri; }
Source:
public FileObject getDescription() { START Resource sourceMd = this.getResource(); END Statement s = sourceMd.getProperty(PcdmModels.hasRelatedObject); if (s != null) { PID fileObjPid = PIDs.get(s.getResource().getURI()); return repository.getFileObject(fileObjPid); } else { return null; } } I'd suggest renaming this variable since sourceMd implies source metadata in this context, but its actually just the resource for the current contentObject.

Target:
public FileObject getDescription() { Resource res = this.getResource(); Statement s = res.getProperty(PcdmModels.hasRelatedObject); if (s != null) { PID fileObjPid = PIDs.get(s.getResource().getURI()); return repository.getFileObject(fileObjPid); } else { return null; } }
Source:
public void addCollectionObjectMemberTest() { CollectionObject childObj = new CollectionObject(workChildPid, repository, dataLoader); START when(repository.createCollectionObject(any(PID.class), any(Model.class))) END .thenReturn(childObj); collection.addMember(childObj); } I can't run the test at the moment, but I don't think this line is doing anything in this test since repository.createCollectionObject is not used in collection.addMember. The repository create methods would only get called from the CollectionObject class if we had addFolder and addWork methods like with FolderObject, but I'm not clear yet on if we need those, so I'm okay that you left them out of CollectionObject.

Target:
public void addCollectionObjectMemberTest() { CollectionObject childObj = new CollectionObject(workChildPid, repository, dataLoader); collection.addMember(childObj); }
Source:
START public RepositoryObject setModel(Model model) { END this.model = model; return this; } Out of curiosity, why is the return type of this setter not void?

Target:
public void setModel(Model model) { this.model = model; }
Source:
public PremisEventBuilder addSoftwareAgent(String agent) { Model modelAgent = ModelFactory.createDefaultModel(); START Resource softwareAgent = modelAgent.createResource("http://id.loc.gov/vocabulary/preservation/agentType/sof"); END addAgent(Premis.hasEventRelatedAgentExecutor, softwareAgent, "#softwareAgent", agent); return this; } Use Premis.hasEventRelatedAgentAuthorizor

Target:
public PremisEventBuilder addSoftwareAgent(String agent) { Model modelAgent = ModelFactory.createDefaultModel(); Resource softwareAgent = modelAgent.createResource(Premis.hasEventRelatedAgentExecutor); addAgent(Premis.hasEventRelatedAgentExecutor, softwareAgent, "#softwareAgent", agent); return this; }
Source:
public PremisEventBuilder(String eventId, Resource eventType, Date date, PremisLogger premisLogger) { this.eventId = eventId; this.eventType = eventType; START this.date = date; END this.premisLogger = premisLogger; addEvent(); } Doesn't seem like there is a reason to hold date and eventType as instance variables on the PremisEventBuilder class, they don't need to live long enough for the call to addEvent, so maybe just pass them in as parameters?

Target:
public PremisEventBuilder(String eventId, Resource eventType, Date date, PremisLogger premisLogger) { this.eventId = eventId; this.premisLogger = premisLogger; addEvent(eventType, date); }
Source:
public PremisLogger getPremisLogger(PID pid) { File file = new File(depositDirectory, DepositConstants.EVENTS_DIR + "/" + pid.getUUID() + ".ttl"); try { PremisLogger premisLogger; if (!file.exists()) { file.getParentFile().mkdirs(); } START premisLogger = createNewEventsFile(pid, file); END return premisLogger; } catch (IOException e) { failJob(e, "Unexpected problem with deposit events file {}.", file.getAbsoluteFile()); } return null; } I think we can drop createNewEventsFile, all the method is doing is calling the constructor of PremisLogger which is doing the actual file creation

Target:
public PremisLogger getPremisLogger(PID pid) { File file = new File(depositDirectory, DepositConstants.EVENTS_DIR + "/" + pid.getUUID() + ".ttl"); try { if (!file.exists()) { file.getParentFile().mkdirs(); } return new PremisLogger(pid, file); } catch (Exception e) { failJob(e, "Unexpected problem with deposit events file {}.", file.getAbsoluteFile()); } return null; }
Source:
public void stop() throws Exception { LOG.info("Stopping the services worker daemon"); Map<String, WorkerPool> workerPools = appContext.getBeansOfType(WorkerPool.class); for (WorkerPool workerPool : workerPools.values()) { workerPool.end(true); START appContext.stop(); END } } Move this line outside the loop?

Target:
public void stop() throws Exception { LOG.info("Stopping the services worker daemon"); Map<String, WorkerPool> workerPools = appContext.getBeansOfType(WorkerPool.class); for (WorkerPool workerPool : workerPools.values()) { workerPool.end(true); } appContext.stop(); }
Source:
protected String getStagingLocation() { String result = null; @SuppressWarnings("rawtypes") Iterator i = mets.getDescendants(new ElementFilter("stagingLocation", JDOMNamespaceUtil.SIMPLE_METS_PROFILE_NS)); while(i.hasNext()) { Element e = (Element)i.next(); String loc = e.getTextTrim(); START if(loc.length() > 0) result = loc; END } return result; } Any reason to return the last staging location rather than the first one?

Target:
protected String getStagingLocation() { String result = null; @SuppressWarnings("rawtypes") Iterator i = mets.getDescendants(new ElementFilter("stagingLocation", JDOMNamespaceUtil.SIMPLE_METS_PROFILE_NS)); while(i.hasNext()) { Element e = (Element)i.next(); String loc = e.getTextTrim(); if(loc.length() > 0) { result = loc; break; } } return result; }
Source:
private static Caching create(String name, int ttl, List<CachingRule> rules) { START return builder().name(name).ttl(ttl).rules(rules).build(); END } To enforce immutability also in lists use `ImmutableList.copyOf` when the list is not null.

Target:
static Caching create(String name, int ttl, List<CachingRule> rules) { return builder().name(name).ttl(ttl).rules(rules).build(); }
Source:
public org.jclouds.openstack.ceilometer.v2.CeilometerApiMetadata build() { START return new org.jclouds.openstack.ceilometer.v2.CeilometerApiMetadata(this); END } The full package names are not necessary. `CeilometerApiMetadata` should suffice on the previous 2 lines.

Target:
public CeilometerApiMetadata build() { return new CeilometerApiMetadata(this); }
Source:
public AsyncBlobStore getAsyncBlobStore(String regionId) { checkRegionId(regionId); START return new org.jclouds.openstack.swift.v1.blobstore.internal.SubmissionAsyncBlobStore( END blobStoreInRegion(regionId), executor); } Just curious...any reason for the fully-qualified name here?

Target:
public AsyncBlobStore getAsyncBlobStore(String regionId) { checkRegionId(regionId); return new SubmissionAsyncBlobStore(blobStoreInRegion(regionId), executor); }
Source:
protected Account(long containerCount, long objectCount, long bytesUsed, Map<String, String> metadata, Multimap<String, String> headers) { this.containerCount = containerCount; this.objectCount = objectCount; this.bytesUsed = bytesUsed; this.metadata = metadata == null ? ImmutableMap.<String, String> of() : checkNotNull(metadata, "metadata"); START this.headers = headers == null ? ImmutableMultimap.<String, String> of() : checkNotNull(headers, "headers"); END } Don't need the `checkNotNull` at the end there (for both of these)? ;-)

Target:
protected Account(long containerCount, long objectCount, long bytesUsed, Map<String, String> metadata, Multimap<String, String> headers) { this.containerCount = containerCount; this.objectCount = objectCount; this.bytesUsed = bytesUsed; this.metadata = metadata == null ? ImmutableMap.<String, String> of() : metadata; this.headers = headers == null ? ImmutableMultimap.<String, String> of() : headers; }
Source:
public CreateContainerOptions headers(Multimap<String, String> headers) { START if (!headers.isEmpty()) { END this.headers.putAll(headers); } return this; } Optimization? `putAll` should not be expensive if there's nothing to put...

Target:
public CreateContainerOptions headers(Multimap<String, String> headers) { this.headers.putAll(headers); return this; }