auphong2707/dl4se-code-review-dataset huggingface dataset:
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> // --> if (mechanism.matches("max_fuse_ticks") && entity.getBukkitEntity() instanceof Creeper && mechanism.requireInteger()) { ((Creeper) entity.getBukkitEntity()).setMaxFuseTicks(mechanism.getValue().asInt()); } }

Target:
unneeded instanceof check for same reason as above
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. // --> if (attribute.startsWith("max_fuse_ticks") && entity.getBukkitEntity() instanceof Creeper) { return new Element(((Creeper) entity.getBukkitEntity()).getMaxFuseTicks()) .getAttribute(attribute.fulfill(1)); } return null; }

Target:
unneeded check
Source:
public void adjust(Mechanism mechanism) { CoreUtilities.autoPropertyMechanism(this, mechanism); if (!mechanism.fulfilled()) { mechanism.reportInvalid(); } }

Target:
remove that bit^
Source:
public Boolean getUserPropertyAsBoolean(String propertyKey) { String userProperty = this.getUserProperty(propertyKey); if(userProperty != null && "1".equals(userProperty)) { return true; } else { return false; } }

Target:
Mixed tabs and spaces. Also `return userProperty != null && "1".equals(userProperty);` :P
Source:
public synchronized void onSchoolDataWorkspaceUserDiscoveredEvent(@Observes SchoolDataWorkspaceUserDiscoveredEvent event) { //kun kurssille pelmahtaa uusi opiskelija UserEntity userEntity = userEntityController.findUserEntityByDataSourceAndIdentifier(event.getUserDataSource(), event.getUserIdentifier()); String userIdentifier = userEntity.getDefaultIdentifier(); String userDataSource = userEntity.getDefaultSchoolDataSource().getIdentifier(); SchoolDataIdentifier user = new SchoolDataIdentifier(userIdentifier, userDataSource); chatSyncController.syncStudent(user); }

Target:
Riittäisikö tässäkin käyttää event.getUserDataSource() ja event.getUserIdentifier() sen sijaan, että haetaan userEntity ja käytetään sen default identifieriä?
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; } } } return true; }

Target:
Could we move this to a util class that's clearly marked as non-public api?
Source:
private boolean isDepositRecord(Resource bxc3Resc) { PIDs.get(bxc3Resc.toString().toLowerCase()); return bxc3Resc.hasProperty(FedoraProperty.hasModel.getProperty(), ContentModel.DEPOSIT_RECORD.getResource()); }

Target:
this line can be removed
Source:
public PID getTransformedPid(PID originalPid) { return generateIds ? pidMinter.mintDepositRecordPid() : PIDs.get(DEPOSIT_RECORD_BASE, originalPid.getUUID().toLowerCase()); }

Target:
For the sake of consistency, use `getId()` instead of `getUUID()`, since you are doing that for the other lowercase calls.
Source:
private boolean hasAccess(PID pid, String datastream) { // Defaults to jp2 surrogate if (datastream.equals("IMAGE_JP2000") || 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); }

Target:
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.
Source:
byte[] textStream() { return "I am not an image".getBytes(); }

Target:
make method private
Source:
private void setStaffOnly(Resource resc, Model model) { Map<String, String> depositStatus = getDepositStatus(); String staffOnly = depositStatus.get(DepositField.staffOnly.name()); if (Boolean.parseBoolean(staffOnly)) { model.add(resc, CdrAcl.none, PUBLIC_PRINC); model.add(resc, CdrAcl.none, AUTHENTICATED_PRINC); } }

Target:
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.
Source:
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; }

Target:
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.
Source:
public static synchronized RegistryService getInstance() { RegistryService local = instance; if (local == null) { local = new RegistryService(); instance = local; // associates a reporter with the current registry ReporterFactory.getOrCreateReporter(); } return local; }

Target:
Why not test and assign `instance` directly rather than passing it through `local`?
Source:
protected BinaryMetadataProcessor(String baseBinaryPath) { this.baseBinaryPath = baseBinaryPath; if (!baseBinaryPath.endsWith("/")) { this.baseBinaryPath += "/"; } }

Target:
should this constructor really have protected access? other processors look like they have public constructors
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 Model fileModel = ModelFactory.createDefaultModel(); Resource resc = fileModel.createResource(objectPath); resc.addProperty(RDF.type, PcdmUse.OriginalFile); return repoObjFactory.updateBinary(fileSetUri, ORIGINAL_FILE, contentStream, filename, mimetype, sha1Checksum, md5Checksum, fileModel); }

Target:
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.
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)); InputStream updatedMods = objLoader.getWorkObject(workObj.getPid()).getMODS().getBinaryStream(); assertModsUpdated(updatedMods); }

Target:
Mainly wondering, but if you just called `workObj.getMODS()` would that reflect the updated MODS? I don't think its caching that.
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); ContentObject moveContent = (ContentObject) moveObj; destroyProxy(objPid); destContainer.addMember(moveContent); }

Target:
can't lines 149-150 be combined?
Source:
public void init() throws Exception { createBaseContainer(RepositoryPathConstants.CONTENT_BASE); repoObjLoader.init(); }

Target:
I'd suggest calling this `init` method from the context file instead
Source:
private List<PID> makePidList(int numPids) { List<PID> pids = new ArrayList<PID>(); 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; }

Target:
Change to `new ArrayList<>();`
Source:
public void testBadReplicationLocations() throws Exception { processor = new ReplicationProcessor(repository, badReplicationLocations, maxRetries, retryDelay); try { processor.process(exchange); } finally { verify(processor).equals(ReplicationDestinationUnavailableException.class); } }

Target:
This method ends on this line. It would be clearer to remove the rest of the method
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); headers.put(EVENT_TYPE, "ResourceDeletion"); template.sendBodyAndHeaders("", headers); assertMockEndpointsSatisfied(); }

Target:
Might as well just pass this event type to `createEvent` instead of `EVENT_TYPES`. Also, shouldn't the event type begin with `EVENT_NS`?
Source:
public void addWorkMemberTest() { unit.addMember(workChildObj); ArgumentCaptor<ContentObject> captor = ArgumentCaptor.forClass(ContentObject.class); verify(repository).addMember(eq(unit), captor.capture()); ContentObject child = captor.getValue(); assertFalse("Should not be able to add Work to AdminUnit", child instanceof WorkObject); }

Target:
What is actually returned here? Isn't it supposed to throw an exception for an invalid member type?
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)) { return contentUri; } Model model = ModelFactory.createDefaultModel(); Resource resc = model.createResource(contentRootString); resc.addProperty(DC.title, "Content Collections Root"); objFactory.createContentRootObject(contentRootUri, model); return contentRootUri; }

Target:
Should this return contentRootUri?
Source:
public FileObject getDescription() { Resource sourceMd = this.getResource(); Statement s = sourceMd.getProperty(PcdmModels.hasRelatedObject); if (s != null) { PID fileObjPid = PIDs.get(s.getResource().getURI()); return repository.getFileObject(fileObjPid); } else { return null; } }

Target:
I'd suggest renaming this variable since sourceMd implies source metadata in this context, but its actually just the resource for the current contentObject.
Source:
public void addCollectionObjectMemberTest() { CollectionObject childObj = new CollectionObject(workChildPid, repository, dataLoader); when(repository.createCollectionObject(any(PID.class), any(Model.class))) .thenReturn(childObj); collection.addMember(childObj); }

Target:
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.
Source:
public RepositoryObject setModel(Model model) { this.model = model; return this; }

Target:
Out of curiosity, why is the return type of this setter not void?
Source:
public PremisEventBuilder addSoftwareAgent(String agent) { Model modelAgent = ModelFactory.createDefaultModel(); Resource softwareAgent = modelAgent.createResource("http://id.loc.gov/vocabulary/preservation/agentType/sof"); addAgent(Premis.hasEventRelatedAgentExecutor, softwareAgent, "#softwareAgent", agent); return this; }

Target:
Use Premis.hasEventRelatedAgentAuthorizor
Source:
public PremisEventBuilder(String eventId, Resource eventType, Date date, PremisLogger premisLogger) { this.eventId = eventId; this.eventType = eventType; this.date = date; this.premisLogger = premisLogger; addEvent(); }

Target:
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?
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(); } premisLogger = createNewEventsFile(pid, file); return premisLogger; } catch (IOException e) { failJob(e, "Unexpected problem with deposit events file {}.", file.getAbsoluteFile()); } return null; }

Target:
I think we can drop createNewEventsFile, all the method is doing is calling the constructor of PremisLogger which is doing the actual file creation
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); appContext.stop(); } }

Target:
Move this line outside the loop?
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(); if(loc.length() > 0) result = loc; } return result; }

Target:
Any reason to return the last staging location rather than the first one?
Source:
private static Caching create(String name, int ttl, List<CachingRule> rules) { return builder().name(name).ttl(ttl).rules(rules).build(); }

Target:
To enforce immutability also in lists use `ImmutableList.copyOf` when the list is not null.
Source:
public org.jclouds.openstack.ceilometer.v2.CeilometerApiMetadata build() { return new org.jclouds.openstack.ceilometer.v2.CeilometerApiMetadata(this); }

Target:
The full package names are not necessary. `CeilometerApiMetadata` should suffice on the previous 2 lines.
Source:
public AsyncBlobStore getAsyncBlobStore(String regionId) { checkRegionId(regionId); return new org.jclouds.openstack.swift.v1.blobstore.internal.SubmissionAsyncBlobStore( blobStoreInRegion(regionId), executor); }

Target:
Just curious...any reason for the fully-qualified name here?
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"); this.headers = headers == null ? ImmutableMultimap.<String, String> of() : checkNotNull(headers, "headers"); }

Target:
Don't need the `checkNotNull` at the end there (for both of these)? ;-)
Source:
public CreateContainerOptions headers(Multimap<String, String> headers) { if (!headers.isEmpty()) { this.headers.putAll(headers); } return this; }

Target:
Optimization? `putAll` should not be expensive if there's nothing to put...
Source:
public void testPutHeaders() { PutOptions options = new PutOptions().headers(ImmutableMultimap.of(OBJECT_DELETE_AT, "123456789")); assertEquals(ImmutableList.of("123456789"), options.buildRequestHeaders().get(OBJECT_DELETE_AT)); }

Target:
As above, assertions the wrong way around?
Source:
public void testStaticWebsiteListingsCSS() { Multimap<String, String> headers = ImmutableMultimap.of(STATIC_WEB_LISTINGS_CSS, "listings.css"); UpdateContainerOptions options = new UpdateContainerOptions().headers(headers); assertEquals(ImmutableList.of("listings.css"), options.buildRequestHeaders().get(STATIC_WEB_LISTINGS_CSS)); }

Target:
As above, assertions the wrong way around?
Source:
public void testList() throws Exception { for (String regionId : regions) { ObjectApi objectApi = api.objectApiInRegionForContainer(regionId, containerName); ObjectList response = objectApi.list(); assertEquals(response.getContainer(), api.containerApiInRegion(regionId).get(containerName)); assertNotNull(response); for (SwiftObject object : response) { checkObject(object); } } }

Target:
Don't need this assertion?
Source:
public void testNonExistentVersion() throws Exception { // The referenced resource only an endpoint for v999.999 of the GlanceApi HttpResponse localVersionNegotiationResponse = HttpResponse.builder().statusCode(300).message("HTTP/1.1 300 Multiple Choices").payload( payloadFromResourceWithContentType("/glanceVersionResponseVersionUnavailable.json", "application/json")).build(); GlanceApi apiWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, versionNegotiationRequest, localVersionNegotiationResponse); try { apiWhenExist.getImageApiForZone("az-1.region-a.geo-1").list(); } catch (UncheckedExecutionException e) { if (e.getCause().getClass() == HttpException.class) return; } fail("Did not throw expected HttpException"); }

Target:
Instead of the `try...catch...fail`, can we use `@Test(expected = HttpException)` here?
Source:
public Builder metadata(Map<String, Object> metadata) { if (metadata == null) { this.metadata = ImmutableMap.of(); } else { this.metadata = ImmutableMap.copyOf(metadata); } return this; }

Target:
The constructor already does this logic. Could this just be `this.metadata = metadata`?
Source:
public static NetworkType fromValue(String value) { if (value == null) return null; return NetworkType.valueOf(value.toUpperCase()); }

Target:
Is `null` a valid input value here at all?
Source:
public static Properties defaultProperties() { System.setProperty(TTL_MIN_IN_SEC, "60"); System.setProperty(TTL_MAX_IN_SEC, "1209600"); System.setProperty(MESSAGE_MAX, "20"); System.setProperty(MESSAGE_BODY_MAX_IN_BYTES, "262144"); Properties properties = BaseHttpApiMetadata.defaultProperties(); properties.setProperty(SERVICE_TYPE, ServiceType.QUEUES); properties.setProperty(CREDENTIAL_TYPE, CredentialTypes.PASSWORD_CREDENTIALS); return properties; }

Target:
Do we do this anywhere else? Any reason why these are in System?
Source:
public Builder ttl(int ttl) { checkArgument(ttl >= getInteger(TTL_MIN_IN_SEC), "ttl must be >= %s", getInteger(TTL_MIN_IN_SEC)); checkArgument(ttl <= getInteger(TTL_MAX_IN_SEC), "ttl must be <= %s", getInteger(TTL_MAX_IN_SEC)); this.ttl = ttl; return self(); }

Target:
See above. In fact, combine these into one check: "ttl must be between X and Y (inclusive) but was Z"?
Source:
protected static String getMessageId(String rawMessageHref) { // strip off everything but the message id return rawMessageHref.substring(rawMessageHref.lastIndexOf('/')+1); }

Target:
Make an injectable "hrefToMessageId" function?
Source:
protected void configure() { bind(DateAdapter.class).to(Iso8601DateAdapter.class); super.configure(); }

Target:
This binding is redundant if the `AutoscaleParserModule` already adds it. Remove it from here?
Source:
public int compareTo(SwiftResource that) { if (that == null) return 1; if (this == that) return 0; return this.getTransactionId().compareTo(that.getTransactionId()); }

Target:
Better to throw NullPointerException?
Source:
public HttpRequest filter(HttpRequest request) throws HttpException { String endpoint = request.getEndpoint().toString(); Pattern pattern = Pattern.compile("/[^/]*$"); // From last / to the end of the line Matcher matcher = pattern.matcher(endpoint); matcher.find(); String encodable = matcher.group(); String encoded = encodable.replace(".", "%2e"); String newEndpoint = matcher.replaceFirst(encoded); return request.toBuilder().endpoint(newEndpoint).build(); }

Target:
Extract as a constant?
Source:
public CmdLineParser(Object bean, ParserProperties parserProperties) { // A 'return' in the constructor just skips the rest of the implementation // and returns the new object directly. if (bean==null) return; // Parse the metadata and create the setters new ClassParser().parse(bean,this); if (parserProperties.shouldSortOptions()) { // for display purposes, keep the arguments in argument order, but sort the options in alphabetical order Collections.sort(options, new Comparator<OptionHandler>() { public int compare(OptionHandler o1, OptionHandler o2) { return o1.option.toString().compareTo(o2.option.toString()); } }); } setUsageWidth(parserProperties.getUsageWidth()); }

Target:
I think it's better to store the reference for future enhancements instead of just copying the content. I love the idea of a configuration object :+1:
Source:
public ParserProperties withUsageWidth(int usageWidth) { if (usageWidth < 0) throw new IllegalArgumentException("Usage width is negative"); if (this.usageWidth == usageWidth) return this; return new ParserProperties(usageWidth, this.shouldSortOptions); }

Target:
This looks like a builder pattern in combination with fluent interface and some kind of immutable class pattern. The immutable class makes it much more complicated when the class grows. Every setter will be a big constructor call. Is it really necessary?
Source:
public static List<Class<?>> getSuperInterfaces(Class clazz) { ArrayList<Class<?>> result = new ArrayList<Class<?>>(); addImplementedSuperInterfaces(clazz, result); return result; }

Target:
You should be able to use the diamond operator here, i.e. new ArrayList<>()
Source:
public static void onUpgrade(Context context, SQLiteDatabase db, int oldVersion, int newVersion) { if (newVersion <= 2) { db.execSQL(QUERY_TABLE_DROP); onCreate(context, db); } else if (newVersion >= 3) { final String ALTER_TBL = "ALTER TABLE " + TABLENAME + " ADD COLUMN " + COLUMN_IS_PAID_ACCOUNT + " integer default 0;"; db.execSQL(ALTER_TBL); } }

Target:
In this case you're going to alter the table for every new version. it must be newVersion == 3 && oldVersion <= 2
Source:
public void testRetrieveKeyAndValueNull() { // setup target JdbcCodeList jdbcCodeList = new JdbcCodeList(); // setup parameters\ jdbcCodeList.setDataSource(dataSource); jdbcCodeList.setLabelColumn("valueColumn"); jdbcCodeList.setValueColumn("labelColumn"); jdbcCodeList.setQuerySql("Select code_id, code_name from codelist"); Map<String, String> mapOutput = jdbcCodeList.retrieveMap(); // assert assertThat(mapOutput.size(), is(0)); assertNull(mapOutput.get("valueColumn")); assertNull(mapOutput.get("labelColumn")); }

Target:
- [x] Follows are unnecessary, because `mapOutput.size` is zero. ``` assertNull(mapOutput.get("valueColumn")); assertNull(mapOutput.get("labelColumn")); ``` --- It was removed. 059df0362e3fc35b1ec81490950162cfbd065425
Source:
private void postConstruct() throws IOException { LOGGER.debug("Fedora staging: {}", fedoraOcflStaging); LOGGER.debug("Fedora OCFL root: {}", ocflRepoRoot); LOGGER.debug("Fedora OCFL temp: {}", ocflTemp); Files.createDirectories(fedoraOcflStaging); Files.createDirectories(ocflRepoRoot); Files.createDirectories(ocflTemp); }

Target:
Normally I do not like the logs to be too chatty... but these three messages are important to see at startup. Can you change them to `LOGGER.info()`?
Source:
public DefaultOCFLObjectSessionFactory( @Value("#{ocflPropsConfig.fedoraOcflStaging}") final Path ocflStagingDir) { LOGGER.info("Fedora OCFL persistence staging directory:\n- {}", ocflStagingDir); try { this.ocflStagingDir = Files.createDirectories(ocflStagingDir); } catch (IOException e) { throw new UncheckedIOException(e); } }

Target:
Maybe reduce this logging to `debug`, in favor of the cleaner output of `OcflPropsConfig`.
Source:
private String encode(final String value) throws Exception { return URLEncoder.encode(value, StandardCharsets.UTF_8); }

Target:
Can remove `throws` clause.
Source:
public static final Operator fromString(final String str) { for (Operator o : Operator.values()) { if (o.value.equals(str)) { return o; } } throw new IllegalArgumentException("Value " + str + " not recognized."); }

Target:
Can remove `final`... as this method is `static`.
Source:
public Condition(final Field field, final Operator operator, final String object) { this.field = field; this.operator = operator; this.object = object; }

Target:
Just a thought, but you could push the expression parse logic down into this class. I could see `Condition` having the following `public static` methods: * `public static Condition fromExpression(final String conditionExpression);` * `public static Condition fromStrings(final String field, final String operator, final String object);` * `public static Condition fromEnums(final Field field, final Operator operator, final String object);` Or something along those lines.
Source:
public void stop(BundleContext context) throws Exception { Preferences.getInstance().dispose(); super.stop(context); }

Target:
It doesn't feel right. Why it is required?
Source:
protected Object doReadObject(final boolean unshared) throws ClassNotFoundException, IOException { final Object obj = objectPreResolver.readResolve(doReadObject(readUnsignedByte(), unshared)); if (depth == 0) { final SortedSet<Validator> validators = this.validators; if (validators != null) { this.validators = null; validatorSeq = 0; for (Validator validator : validators) { validator.getValidation().validateObject(); } } } return obj; }

Target:
I think this placement might be a problem, because there are a number of call sites which call doReadObject(int, boolean) which would essentially bypass this resolution. I think you may have to either edit the main doReadObject method, capturing every return statement, or else wrap the whole method with a method that does the substitution (though this will reduce the maximum stack depth that can be achieved).
Source:
protected RemoteCallback<List<String>> getRemoteCallback(Consumer<List<KieAssetsDropdownItem>> assetListConsumer) { return response -> { List<KieAssetsDropdownItem> toAccept = response.stream() .map(this::getKieAssetsDropdownItem) .filter(this::filterTargetDirectory) .sorted(Comparator.comparing(KieAssetsDropdownItem::getText, String.CASE_INSENSITIVE_ORDER)) .collect(Collectors.toList()); assetListConsumer.accept(toAccept); }; }

Target:
Could you please tell me why dont we use an Optional for for "toAccept"? Isnt that possible that user would have some leftovers in target but removed all dmn files in the project?
Source:
protected void resetDocks() { abstractScenarioSimulationDocksHandler.getSettingsPresenter().ifPresent(SubDockView.Presenter::reset); abstractScenarioSimulationDocksHandler.getCheatSheetPresenter().ifPresent(SubDockView.Presenter::reset); abstractScenarioSimulationDocksHandler.getTestToolsPresenter().ifPresent(SubDockView.Presenter::reset); scenarioSimulationEditorWrapper.resetAdditionalDocks(); }

Target:
Is it possible to uniform this code and not have two different approaches?
Source:
protected double getColumnWidth(String expressionIdentifierName) { ExpressionIdentifier.NAME expressionName; try { expressionName = ExpressionIdentifier.NAME.valueOf(expressionIdentifierName); } catch (IllegalArgumentException e) { expressionName = ExpressionIdentifier.NAME.Other; } switch (expressionName) { case Index: return 70; case Description: return 300; default: return 114; } }

Target:
I remember a similar (the same?) code somewhere else. Am I wrong?
Source:
private boolean isTypeGuvnorEnum() { return conditionColumn != null && conditionColumn.getValueList() != null && conditionColumn.getValueList().split(",").length > 1; }

Target:
Shouldn't we handle case when single enum is specified? ```java private boolean isTypeGuvnorEnum() { if (conditionColumn != null && conditionColumn.getValueList() != null) { if (conditionColumn.getValueList().split(",").length > 1) { return true; } else { return conditionColumn.getValueList().trim().length() > 0; } } else { return false; } } ```
Source:
protected static JSIScenarioType getScenario(Scenario source) { JSIScenarioType toReturn = new JSIScenarioType(); JSIFactMappingValuesType factMappingValuesType = new JSIFactMappingValuesType(); toReturn.setFactMappingValues(factMappingValuesType); final List<FactMappingValue> unmodifiableFactMappingValues = source.getUnmodifiableFactMappingValues(); List<JSIFactMappingValueType> toSet = new ArrayList<>(); populateJSIFactMappingValuesType(toSet, unmodifiableFactMappingValues); factMappingValuesType.setFactMappingValue(toSet); return toReturn; }

Target:
We should either make `populateJSIFactMappingValuesType` private or move the `toSet` variable inside of `populateJSIFactMappingValuesType` because currently we do not do any check in `populateJSIFactMappingValuesType` if `toSet` is not null.
Source:
protected static Imports getImports(JSIImportsType source) { Imports toReturn = new Imports(); if (source != null) { final JSIWrappedImportsType imports = source.getImports(); if (imports != null) { imports.getImport().forEach(importsType -> toReturn.addImport(getImport(importsType))); } } return toReturn; }

Target:
This variant is a little bit shorter and still well readable, what do you think? ```java if (source != null && source.getImports() != null) { final JSIWrappedImportsType imports = source.getImports(); imports.getImport().forEach(importsType -> toReturn.addImport(getImport(importsType))); } ```
Source:
public void getItems(Consumer<List<KieAssetsDropdownItem>> assetListConsumer) { List<KieAssetsDropdownItem> toAccept = new ArrayList<>(); assetListConsumer.accept(toAccept); }

Target:
Can't be just `assetListConsumer.accept(Collections.emptyList())`?
Source:
private String parseActualValue(final String value) { if (value != null && value.indexOf("=") > 1) { return value.substring(0, value.indexOf("=")); } else { return value; } }

Target:
I think this should be `> 0` since a value list item of `1=One` does not work.
Source:
public void setGridWidgetBACKGROUND() { testToolsPresenterSpy.setGridWidget(GridWidget.BACKGROUND); verify(testToolsPresenterSpy, times(1)).onDisableEditorTab(); verify(testToolsPresenterSpy, times(1)).hideInstances(); verify(testToolsPresenterSpy, never()).showInstanceListContainerSeparator(eq(true)); }

Target:
@yesamer This can be removed, I think
Source:
public void onBackgroundTabSelected() { setItemMenuEnabled(true); runScenarioMenuItem.setEnabled(false); scenarioBackgroundGridWidget.clearSelections(); scenarioBackgroundGridWidget.select(); scenarioMainGridWidget.deselect(); populateRightDocks(TestToolsPresenter.IDENTIFIER); }

Target:
Please enable run button in background tab
Source:
protected void checkExpressionSyntax() { String value = getValue(); if (!value.startsWith(EXPRESSION_VALUE_PREFIX)) { if (value.startsWith(MVEL_ESCAPE_SYMBOL)) { widget.setValue(value.replaceFirst(MVEL_ESCAPE_SYMBOL, EXPRESSION_VALUE_PREFIX)); } else if (value.startsWith(" ")) { widget.setValue(value.replaceFirst(" ", EXPRESSION_VALUE_PREFIX)); } else { widget.setValue(EXPRESSION_VALUE_PREFIX + value); } } }

Target:
could be final
Source:
protected FactModelTree createTopLevelFactModelTree(String factName, DMNType type, SortedMap<String, FactModelTree> hiddenFacts, FactModelTree.Type fmType) throws WrongDMNTypeException { return isToBeManagedAsCollection((BaseDMNTypeImpl) type) ? createFactModelTreeForCollection(new HashMap<>(), factName, type, hiddenFacts, fmType, new ArrayList<>()) : createFactModelTreeForNoCollection(new HashMap<>(), factName, factName, type.getName(), type, hiddenFacts, fmType, new ArrayList<>()); }

Target:
@danielezonca Since it is always cast, is it not possible to directly set _BaseDMNTypeImpl_ for "type" instead of _DMNType_ ?
Source:
public void onSaveButton(String scenarioType) { if (saveCommand != null) { simulationDescriptor.setSkipFromBuild(view.getSkipFromBuild().isChecked()); switch (ScenarioSimulationModel.Type.valueOf(scenarioType)) { case RULE: saveRuleSettings(); break; case DMN: saveDMNSettings(); break; } saveCommand.execute(); } }

Target:
Just a small suggestion to add a default with new IlligalStateException in case if we would add some new scenario type.
Source:
public void onDownload(final Supplier<Path> pathSupplier) { final String downloadURL = getFileDownloadURL(pathSupplier); open(downloadURL); }

Target:
@yesamer Why those have been changed to _public_ ? Just to understand
Source:
public void isExecutable_HeaderCellSelected() { when(scenarioGridModelMock.getSelectedCells()).thenReturn(Collections.emptyList()); when(scenarioGridModelMock.getSelectedHeaderCells()).thenReturn(Lists.create(selectedCell, selectedCell2)); assertTrue(handler.isExecutable(scenarioGridMock)); }

Target:
just one cell should be here
Source:
private boolean hasEntryPoint(final Pattern52 pattern) { return pattern.getEntryPointName() != null && !pattern.getEntryPointName().trim().isEmpty(); }

Target:
We could use `org.drools.core.util.StringUtils` for the implementation.
Source:
protected boolean isToSkip(FactMapping factMapping) { return OTHER.equals(factMapping.getExpressionIdentifier().getType()) || EMPTY.equals(factMapping.getFactIdentifier()) || factMapping.getExpressionElements().size() == 0; }

Target:
Just for the sake of short codebase `.size() == 0` could be replaced by `.isEmpty()`
Source:
public void deleteColumn(int columnIndex) { checkSimulation(); final GridColumn<?> toDelete = getColumns().get(columnIndex); deleteColumn(toDelete); simulation.removeFactMappingByIndex(columnIndex); synchronizeFactMappingsWidths(); }

Target:
@yesamer I think that's to be removed. `synchronizeFactMappingsWidths` put the current columns widht inside factmappings, but we decided it should happen **only** when the user saves the scenario - otherwise rely on the "status" implementation to manage them
Source:
public void onImport(String fileContents) { GWT.log(this.toString() + "onImport(" + fileContents + ")"); scenarioSimulationEditorWrapper.onImport(fileContents, getImportCallBack(), getImportErrorCallback(), context.getStatus().getSimulation()); }

Target:
Is this log necessary?
Source:
public void onEvent(AppendColumnEvent event) { context.getStatus().setColumnId(String.valueOf(new Date().getTime())); context.getStatus().setColumnGroup(event.getColumnGroup()); commonExecution(context, new AppendColumnCommand()); context.getScenarioGridPanel().setFocus(true); }

Target:
@jomarko If there is nothing preventing this, move all those "context.getScenarioGridPanel().setFocus(true);" inside commonExecution
Source:
public String getType(final Optional<String> operatorFromCell) throws ValueResolveException { try { Logger.add("Getting type from utils"); if (operatorFromCell.isPresent()) { return conditionColumn.getFieldType(); } final String type = utils.getType(conditionColumn, columnIndex); Logger.add("Resolver type from utils: " + type); return type; } catch (final Exception e) { throw new ValueResolveException("Failed to get type for " + ToString.toString(conditionColumn) + " columnIndex: " + columnIndex, e); } }

Target:
Do we want to keep the logging in this class. Asking because we do not log what type was resolved if operator was in the cell.
Source:
protected FactModelTree getSimpleClassFactModelTree(Class clazz) { String key = clazz.getSimpleName(); Map<String, String> simpleProperties = new HashMap<>(); String fullName = clazz.getCanonicalName(); simpleProperties.put("value", fullName); String packageName = fullName.substring(0, fullName.lastIndexOf(".")); return new FactModelTree(key, packageName, simpleProperties); }

Target:
This seems to me as util method that could be used by **delegation** instead of **inheritance**. Is the inheritance used because of the testeability?
Source:
public ScenarioGridColumn build() { List<GridColumn.HeaderMetaData> headerMetaDataList = headerBuilder.build(); ScenarioGridColumnRenderer actualScenarioGridColumnRenderer = scenarioGridColumnRenderer != null ? scenarioGridColumnRenderer : new ScenarioGridColumnRenderer(); ScenarioGridColumn scenarioGridColumn = new ScenarioGridColumn(headerMetaDataList, actualScenarioGridColumnRenderer, width, isMovable, factoryCell, placeHolder ); // by default scenario columns should be auto to have auto resize scenarioGridColumn.setColumnWidthMode(GridColumn.ColumnWidthMode.auto); scenarioGridColumn.setMinimumWidth(width); return scenarioGridColumn; }

Target:
If these are the defaults for ScenarioGridColumn, should we set them inside the ScenarioGridColumn constructor?
Source:
public void removeFactMapping(FactMapping toRemove) { factMappings.remove(toRemove); }

Target:
I prefer to move these methods to `Simulation` (or better create also two methods there and change these to package private) so they can remove also existing related `FactMappingValue` from the `Scenario`s before to remove them from the header. Otherwise it is easy to forget to cleanup `Scenario`s and have inconsistent data
Source:
public IndexBuilder fillIndexBuilder(final Path path) throws Exception { InputStream inputStream = null; try { inputStream = ioService.newInputStream(path, StandardOpenOption.READ); final String drl = DecisionTableFactory.loadFromInputStream(inputStream, null); return fillDrlIndexBuilder(path, drl); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { // no-op } } } }

Target:
Worth to use try with resources: ```java try (final InputStream inputStream = ioService.newInputStream(path, StandardOpenOption.READ)) { final String drl = DecisionTableFactory.loadFromInputStream(inputStream, null); return fillDrlIndexBuilder(path, drl); } ```
Source:
public ScenarioSimulationEditorPresenter(final Caller<ScenarioSimulationService> service, final ScenarioSimulationResourceType type, final ImportsWidgetPresenter importsWidget, final AsyncPackageDataModelOracleFactory oracleFactory) { super(); this.baseView = newScenarioSimulationView(); // Indirection added for test-purpose this.service = service; this.type = type; this.importsWidget = importsWidget; this.oracleFactory = oracleFactory; }

Target:
You should use the super(baseView) to provide the view for base and then set the view for this class so that you don't need to later cast for the actual view.
Source:
void submit() { view.submit(versionRecordManager.getCurrentPath()); versionRecordManager.restoreToCurrentVersion(); concurrentUpdateSessionInfo = null; }

Target:
Are you sure this is the correct method!? From what I can see (from the code) that will show a popup to restore the file to the current version. Other editors use ```versionRecordManager.reloadVersions(path);``` in their "save success callbacks". You might also want to check the XLS Score Card Editor and the "Upload file" Editor for similar problems. I'll compile this PR and _see_ what it's doing; in case my code review is misguided.
Source:
public DeleteColumnManagementAnchorWidget() { super(); setText(GuidedDecisionTableConstants.INSTANCE.Delete()); setTitle(GuidedDecisionTableConstants.INSTANCE.DeleteThisColumn()); addClickHandler((clickEvent) -> { deletePopUpPresenter.getToggleCommentPresenter().getViewElement().setAttribute("hidden", "true"); deletePopUpPresenter.show((comment) -> afterDeleteConfirmedCommand.execute()); }); }

Target:
@jomarko I don't think it's going to be quite so easy :-( IMO this is really an abuse of the ```DeletePopupPresenter``` as we should not be tweaking it's visual appearance from outside the class (adding a ```enableComment(boolean)``` is probably quite acceptable)... but that also brings me onto...
Source:
public CEPOperatorsDropdown getNewOperatorDropdown(String[] operators, SingleFieldConstraint constraint) { return new CEPOperatorsDropdown(operators, constraint); }

Target:
Did you want this to ideally be package protected?
Source:
public static void assertDoesNotContain(final String notExpected, final Set<Issue> result, final int rowNumber) { assertFalse("Found " + notExpected, result.stream() .filter(issue -> titleEquals(issue, notExpected) && rowNumberContains(issue, new HashSet<Integer>() {{ add(rowNumber); }})) .count() > 0); }

Target:
`Collections.singletonSet(rowNumber)`
Source:
public void init(final AdditionalInfoPage page) { this.page = page; clear(); setup(); }

Target:
This could be considered a strange implementation of MVP; as your P is calling ```V.init(..)``` which then calls ```V.setup()``` which then calls the P to call the V to setup some UI elements. Why not have P call perform the complete setup rather than have the V call the P to call the V to complete setup? Or did I miss something?
Source:
private void setupFieldList() { final String selectField = translate(GuidedDecisionTableErraiConstants.FieldPageView_SelectField); fieldsList.clear(); fieldsList.addItem("-- " + selectField + " --", ""); page.forEachFactField(fieldName -> fieldsList.addItem(fieldName)); fieldsList.setSelectedIndex(getCurrentIndexFromList(getCurrentValue(), fieldsList)); }

Target:
It took a little "unwinding" but I followed the code OK!
Source:
public int hashCode() { int result = severity != null ? severity.hashCode() : 0; result = 31 * result + (rowNumbers != null ? rowNumbers.hashCode() : 0); result = 31 * result + (checkType != null ? checkType.hashCode() : 0); result = 31 * result + (debugMessage != null ? debugMessage.hashCode() : 0); return result; }

Target:
GWT Client side and hashCode tend to cause trouble, the workaround is to use ~~ Like this: https://github.com/kiegroup/drools-wb/blob/1fabbdea01b75ac325e97df72d58d87a65d3955d/drools-wb-services/drools-wb-verifier/drools-wb-verifier-api/src/main/java/org/drools/workbench/services/verifier/api/client/index/FieldBase.java#L100-L105
Source:
public int hashCode() { int result = factType.hashCode(); result = 31 * result + name.hashCode(); return result; }

Target:
I'm still scared something stupid not using `result = ~~result` in your `hashCode` implementations.. but if you're happy.. then.... you'll be the one scratching your head _if_ the JIRAs start rolling in about V&V going crazy after a while..
Source:
protected String[] getDuplicates() { System.out.println("getting duplicates"); return duplicates; }

Target:
Sorry, @zkrejcov I missed this the first time round.. it'd be best to remove this type of logging (which I assume you added to help debug your tests, or the like)
Source:
public int hashCode() { return 37 * pattern.hashCode() + factField.hashCode(); }

Target:
If you find your analysis panel starts going a bit loopy (IIRC you said it does), you might want to check your `hashCode` implementations - you should try to use `result = ~~result` type construct.. I can dig out the original email if you like?
Source:
void initialiseLockManager() { lockManager.init( new LockTarget( currentPath, parent.getView().asWidget(), placeRequest, new LockTarget.TitleProvider() { @Override public String getTitle() { return currentPath.getFileName() + " - " + resourceType.getDescription(); } }, new Runnable() { @Override public void run() { //Nothing to do } } ), parent ); }

Target:
last two parameters to LockTarget constructor could be lambda expressions to make this statement shorter.
Source:
private boolean isSelfSigned(X509Certificate[] chain) { if(chain[0].getIssuerX500Principal().getName().equals(chain[0].getSubjectX500Principal().getName())){ return true; } else { return false; } }

Target:
Perhaps replace by: `return chain[0].getIssuerX500Principal().getName().equals(chain[0].getSubjectX500Principal().getName())` (there's no need for the if/else)?
Source:
private int asLit(SetVar var, DecisionOperator<SetVar> op, int val) { int l; if (op == DecisionOperatorFactory.makeSetForce()) { l = SatSolver.negated(png.Literal(var, val, true)); } else if (op == DecisionOperatorFactory.makeSetRemove()) { l = png.Literal(var, val, true); } else { throw new UnsupportedOperationException("Cannot deal with such operator: " + op); } return l; }

Target:
Method `equals()` should be used instead of `==`.
Source:
public int getPropagationConditions(int idx) { if (fast) { return IntEventType.instantiation(); } return IntEventType.boundAndInst(); }

Target:
remove fast attribute?
Source:
private void findSingletons(BitSet restriction) { for (int i = restriction.nextSetBit(0); i >= 0; i = restriction.nextSetBit(i + 1)) { if (graph.getPredOf(i).size() * graph.getSuccOf(i).size() == 0) { nodeSCC[i] = nbSCC; sccFirstNode[nbSCC++] = i; restriction.clear(i); } } }

Target:
I suggest: `if (graph.getPredOf(i).size() == 0 || graph.getSuccOf(i).size() == 0) {`
Source:
public static void free(ByteBuffer buffer) { try { if (buffer.isDirect()) { clean((DirectBuffer) buffer); } } catch (Exception e) { throw Throwables.propagate(e); } }

Target:
Is try-catch needed here?
Source:
public static Boolean isZip(String fName) { if (Strings.isNullOrEmpty(fName)) { return false; } return fName.endsWith(ZIP_SUFFIX); // Technically a file named `.zip` would be fine }

Target:
why Boolean, and not boolean?
Source:
public static Boolean isGz(String fName) { if (Strings.isNullOrEmpty(fName)) { return false; } return fName.endsWith(GZ_SUFFIX) && fName.length() > GZ_SUFFIX.length(); }

Target:
why is this logic different than for .zip?
Source:
private void addSizedFiles(Collection<File> files) { if (files == null || files.isEmpty()) { return; } long size = 0l; for (File file : files) { size += file.length(); } this.files.addAll(files); this.size += size; }

Target:
Why is this private, when addFiles does the same thing and is public?
Source:
public static void copyToFileAndClose(InputStream is, File file) throws IOException { OutputStream os = null; try { file.getParentFile().mkdirs(); os = new BufferedOutputStream(new FileOutputStream(file)); ByteStreams.copy(is, os); } finally { CloseQuietly.close(is); CloseQuietly.close(os); } }

Target:
try with resources might be better here?
Source:
public void setFieldNames(String header) throws FormattedException { try { setFieldNames(splitter.split(header)); } catch (Exception e) { Throwables.propagateIfInstanceOf(e, FormattedException.class); throw new FormattedException.Builder() .withErrorCode(FormattedException.ErrorCode.UNPARSABLE_HEADER) .withMessage(e.getMessage()) .build(); } }

Target:
FormattedException is a runtime exception, so you don't need to declare it.
Source:
public Optional<Collection<VirtualGatewayInterface>> getGatewayInterfaces(VirtualGatewayInstance gateway) { return l3manager.getGatewayInterfaces(gateway); }

Target:
You want to avoid returning an optional collection. Just return an empty collection
Source:
public void enableFirewall(boolean enabled) { if(this.enabled != enabled) { logger.info("Setting firewall to {}", enabled); this.enabled = enabled; List<Masked<U64>> changes = new ArrayList<Masked<U64>>(); changes.add(Masked.of(DEFAULT_COOKIE, AppCookie.getAppFieldMask())); // Add announcement that all firewall decisions changed routingService.handleRoutingDecisionChange(changes); } }

Target:
Can we use an ImmutableSet instead? And is list necessary instead of set?
Source:
public void destroyNode(String id) { // stop it first try { suspendNode(id); // wait until fully stopped serverStopped.apply(id); } catch (Exception e) { // ignore e.printStackTrace(); } api.getVirtualServerApi().destroy(id); // wait until fully destroyed String systemId = toSystemId.apply(id); systemNormal.apply(systemId); }

Target:
You'd better use a logger here to ignore the exception or propagate the exception using Throwables.propagate
Source:
public synchronized void manage(ManagedBean mBean, String name) { if (mBeanServer != null) { ManagementUtils.register(mBeanServer, mBean, mBean.getType(), name); } mbeans.put(new Key(mBean, name), mBean); }

Target:
[curiosity] Is it expected that beans are registered when an `mBeanServer` is not set yet?
Source:
public LocalizedString getDisplayNames() { if (displayName == null) { String simple = context.getState().getLabel(); if (simple != null) { displayName = resolveExpression(simple); } else if (context.getId() != null) { Map<Locale, Described.State> descriptions = navigation.loadDescriptions(context.getId()); displayName = ObjectFactory.createLocalizedString(descriptions); } } return displayName; }

Target:
There will be slight perf cost now that you are going to look through all resource bundles and resolve all languages when someone calls getDisplayNames(). Again I'm not sure about the use case as to why this should be done. getDisplayName() properly resolves the label.