Skip to main content

Home/ SoftwareEngineering/ Group items tagged equals

Rss Feed Group items tagged

kuni katsuya

Equals and HashCode | Hibernate | JBoss Community - 0 views

  • best strategies for implementation of equals() and hashcode() in your persistent classes
  • The general contract is: if you want to store an object in a List, Map or a Set then it is an requirement that equals and hashCode are implemented so they obey the standard contract as specified in the  documentation
  • Why are equals() and hashcode() importantNormally, most Java objects provide a built-in equals() and hashCode() based on the object's identity; so each new() object will be different from all others.
  • ...8 more annotations...
  • Separating object id and business key
  • recommend using the "semi"-unique attributes of your persistent class to implement equals() (and hashCode()
  • The database identifier property should only be an object identifier, and basically should be used by Hibernate only
  • Instead of using the database identifier for the equality comparison, you should use a set of properties for equals() that identify your individual objects
  • "name" String and "created" Date, I can use both to implement a good equals() method
  • Workaround by forcing a save/flush
  • work around by forcing a save() / flush() after object creation and before insertion into the set
  • Note that it's highly inefficient and thus not recommended
kuni katsuya

8. Bean Validation (JSR-303) - Confluence - 0 views

  • "Bean Validation" specification (aka JSR-303) standardizes an annotation-based validation framework for Java
  • Flex doesn't provide by itself such framework. The standard way of processing validation is to use Validator subclasses and to bind each validator to each user input (see Validating data). This method is at least time consuming for the developer, source of inconsistancies between the client-side and the server-side validation processes, and source of redundancies in your MXML code.
  • GraniteDS introduces an ActionsScript3 implementation of the Bean Validation specification and provides code generation tools integration so that your Java constraint annotations are reproduced in your AS3 beans
  • ...16 more annotations...
  • GraniteDS validation framework provides a set of standard constraints
  • Constraint Description AssertFalse The annotated element must be false AssertTrue The annotated element must be true DecimalMax The annotated element must be a number whose value must be lower or equal to the specified maximum DecimalMin The annotated element must be a number whose value must be greater or equal to the specified minimum Digits The annotated element must be a number whithin accepted range Future The annotated element must be a date in the future Max The annotated element must be a number whose value must be lower or equal to the specified maximum Min The annotated element must be a number whose value must be greater or equal to the specified minimum NotNull The annotated element must not be null Null The annotated element must be null Past The annotated element must be a date in the past Pattern The annotated String must match the supplied regular expression Size The annotated element size must be between the specified boundaries (included)
  • Constraint annotations must be placed on public properties, either public variables or public accessors
  • -keep-as3-metadata+=AssertFalse,AssertTrue,DecimalMax,DecimalMin, Digits,Future,Max,Min,NotNull,Null,Past,Pattern,Size
  • must use
  • keep the constraint annotations in your compiled code
  • Error Messages and Localization
  • {name.notnull}
  • {name.minsize}
  • use the built-in ResourceBundle support offered by Flex:
  • to add support for different locales
  • follow the same principle:
  • create a ValidationMessages.properties for the new locale
  • translate all default error messages and add new ones for your customized message keys
  • Note that the bundle name must always be set to "ValidationMessages".
  • Using the FormValidator Class
kuni katsuya

equalsverifier - EqualsVerifier can be used in Java unit tests to verify whether the co... - 0 views

  • EqualsVerifierEqualsVerifier can be used in Java unit tests to verify whether the contract for the equals and hashCode methods in a class is met. The contracts are described in the Javadoc comments for the java.lang.Object class.
kuni katsuya

3 ways to serialize Java Enums | Vineet Manohar's blog - 0 views

  • Mapping enum to database column using JPA/Hibernate You can use any of the 3 approaches discussed above. Map the enum to an integer column. The persistence implementation should automatically convert enum to ordinal() and back for you. Map the enum to a String column. The persistence implementation should automatically convert the enum value to String value via the name() function. Map the enum using a business value. You should mark the enum field as @Transient, and create another String field which you can map to a String column in your database table. Here’s an example code snippet. view plaincopy to clipboardprint?@Entity  public class Product {   @Column   private String colorValue;     @Transient   public Color getColor() {    return Color.fromValue(colorValue);   }     public void setColor(Color color) {    this.colorValue = color.toValue();   }  }  
  • Approach 3: Using a user defined business value – Recommended approach! This approach involves assigning a an explicit user defined value to each enum constant and defining a toValue() and fromValue() methods on the enum to do the serialization and deserialization.
  • public enum Color {   RED("RED"), GREEN("GREEN"), BLUE("BLUE"), UNKNOWN("UNKNOWN");     private final String value;     Color(String value) {     this.value = value;   }     public static Color fromValue(String value) {     if (value != null) {       for (Color color : values()) {         if (color.value.equals(value)) {           return color;         }       }     }       // you may return a default value     return getDefault();     // or throw an exception     // throw new IllegalArgumentException("Invalid color: " + value);   }     public String toValue() {     return value;   }     public static Color getDefault() {     return UNKNOWN;   }  }  public enum Color { RED("RED"), GREEN("GREEN"), BLUE("BLUE"), UNKNOWN("UNKNOWN"); private final String value; Color(String value) { this.value = value; } public static Color fromValue(String value) { if (value != null) { for (Color color : values()) { if (color.value.equals(value)) { return color; } } } // you may return a default value return getDefault(); // or throw an exception // throw new IllegalArgumentException("Invalid color: " + value); } public String toValue() { return value; } public static Color getDefault() { return UNKNOWN; } } This approach is better than approach 1 and approach 2 above. It neither depends on the order in which the enum constants are declared nor on the constant names.
kuni katsuya

Permissions | Apache Shiro - 0 views

  • Permission as a statement that defines an explicit behavior or action
  • lowest-level constructs in security polices
  • explicitly define only "what" the application can do
  • ...69 more annotations...
  • do not at all describe "who" is able to perform the action(s)
  • Multiple Parts
  • Wildcard Permissions support the concept of multiple levels or parts. For example, you could restructure the previous simple example by granting a user the permission printer:query
  • Multiple Values Each part can contain multiple values. So instead of granting the user both the "printer:print" and "printer:query" permissions, you could simply grant them one: printer:print,query
  • All Values What if you wanted to grant a user all values in a particular part? It would be more convenient to do this than to have to manually list every value. Again, based on the wildcard character, we can do this. If the printer domain had 3 possible actions (query, print, and manage), this: printer:query,print,manage
  • simply becomes this: printer:*
  • Using the wildcard in this way scales better than explicitly listing actions since, if you added a new action to the application later, you don't need to update the permissions that use the wildcard character in that part.
  • Finally, it is also possible to use the wildcard token in any part of a wildcard permission string. For example, if you wanted to grant a user the "view" action across all domains (not just printers), you could grant this: *:view Then any permission check for "foo:view" would return true
  • Instance-Level Access Control
  • instance-level Access Control Lists
  • Checking Permissions
  • SecurityUtils.getSubject().isPermitted("printer:print:lp7200")
  • printer:*:*
  • all actions on a single printer
  • printer:*:lp7200
    • kuni katsuya
       
      note: wildcard * usage for 'actions' part
  • missing parts imply that the user has access to all values corresponding to that part
  • printer:print is equivalent to printer:print:*
  • Missing Parts
  • rule of thumb is to
  • use the most specific permission string possible
  • when performing permission checks
  • first part is the
  • domain
    • kuni katsuya
       
      aka 'resource'
  • that is being operated on (printer)
  • second part is the
  • action
  • (query) being performed
  • There is no limit to the number of parts that can be used
  • three parts - the first is the
  • domain
  • the second is the
  • action(s)
  • third is the
  • instance(s)
  • allow access to
  • all actions
  • all printers
  • can only leave off parts from the end of the string
  • Performance Considerations
  • runtime implication logic must execute for
  • each assigned Permission
  • implicitly using Shiro's default
  • WildcardPermission
  • which executes the necessary implication logic
  • When using permission strings like the ones shown above, you're
  • Shiro's default behavior for Realm
  • for every permission check
  • all of the permissions assigned to that user
  • need to be checked individually for implication
  • as the number of permissions assigned to a user or their roles or groups increase, the time to perform the check will necessarily increase
  • If a Realm implementor has a
  • more efficient way of checking permissions and performing this implication logic
  • Realm isPermitted* method implementations
  • should implement that as part of their
  • implies
  • user:*:12345
  • user:update:12345
  • printer
  • implies
  • printer:print
  • Implication, not Equality
  • permission
  • checks
  • are evaluated by
  • implication
  • logic - not equality checks
  • the former implies the latter
  • superset of functionality
  • implication logic can be executed at runtime
kuni katsuya

TH01-EP03-US004 - Property Mgmt, Edit Location & Directions, Content Mgmt - Projects - ... - 0 views

  • Property Mgmt
  • Property Mgmt
  • Property Mgmt
  • ...18 more annotations...
  • Property Mgmt
  • Property Mgmt
  • Property Mgmt
  • As a user
    • kuni katsuya
       
      with what granted roles? from which organization?
  • ability to see
    • kuni katsuya
       
      permissions required: retrieve these resource types
  • Location Type
  • Description
  • Airports
  • belonging to other organizations
    • kuni katsuya
       
      content (license) owned by organization different than user's
  • clone this information
    • kuni katsuya
       
      clone = retrieve, then create ie. required permissions: {retrieve,create:}
  • have the rights
    • kuni katsuya
       
      generally speaking, there can be a few independent but overlapping mechanism that will control who is allowed to do what with content: 1. any subject's access to the content itself can be controlled via authorization rules (ie. required vs granted permissions) enforced via system-wide resource-based access control 2. content licensors (~content owners) can restrict the usage of their content by: * whom - ie. content licensee (legally/commercially represented by an organization) * how - eg. reuse as unmodified, create derivatives, composite, redistribute, etc * where - ie. distribution channels their content can be used (eg. only on hotel's vbrochure site, but not in any ids/gds channels) * when - temporal restrictions may limit scope of content license grant by: start, end, duration, season, etc 3. content licensees can further filter or funnel content available to them (resulting from a combination of license granted to them and access control) based on their own criteria (eg. generate a templated hotel presentation only if: at least 1 textual description, 5 photos and 1 video for a hotel is available with a license to combine them (composite content)
  • see how other organizations describe the property
    • kuni katsuya
       
      permission required: retrieve hotel descriptive content(?) owned by independent organization
  • Property Mgmt
  • which textual information
  • displayed
    • kuni katsuya
       
      displayed where? on specific channels?
  • ECM will ask user to confirm that the user has rights to use that content
    • kuni katsuya
       
      if ecm/vfml is to manage content licensing as a third party between organizations (content licensors & licensees) shouldn't ecm *know* if the user('s organization) has rights to use the content in question? is this question posed to the user (with required explicit acknowledgement) purely to absolve vfml from liability issues that may result from licensing disagreements?
  • property’s
    • kuni katsuya
       
      this being the user's (organization's) 'version'or 'view'of the hotel, since this user normally wouldn't/shouldn't be granted permissions to replace content for a hotel on a different organization's 'view'or 'version' of the same hotel
  • to see the user’s original content
    • kuni katsuya
       
      this implies that *at least* one version of such (temporarily) replaceable content needs to be managed/maintaned to allow reverting what if, deliberately, ignorantly or maliciously, a user replaces the same piece of--textual or any type, really--content for this hotel n times? will all n versions be required to be managed as an undo history? the user's ''original content'' might have been version 1, but equally might have been 1 mean: - previous version of the content, regardless of which user - initial version of that content attached to the hotel regardless of which user created/updated it and ignoring which organization owns it?, or, -
kuni katsuya

Stephen Colebourne's blog: Javadoc coding standards - 0 views

  • Javadoc coding standards
  • explain some of the rationale for some of my choices
  • this is more about the formatting of Javadoc, than the content of Javadoc
  • ...63 more annotations...
  • Each of the guidelines below consists of a short description of the rule and an explanation
  • Write Javadoc to be read as source code
  • Making Javadoc readable as source code
  • Public and protected
  • All public and protected methods should be fully defined with Javadoc
  • Package and private methods do not have to be, but may
  • benefit from it.
    • kuni katsuya
       
      think of it as internal design documentation when you revisit this code 8 months from now: - based on nothing but your well-chosen ;) package/class/method/variable names, will you recall all of your current design intentions and rationale? likely not - when you hand-off this code to another software engineer, how easy will it be to mostly rtfm? will you have to waste time preparing design/implementation notes specifically for the hand-off? if this is the case because the code is unreadable and not self-guiding and there's not already at least high level design notes in a wiki, you're doing it wrong!
  • If a method is overridden in a subclass, Javadoc should only be present if it says something distinct to the original definition of the method
    • kuni katsuya
       
      ie. don't just copy-paste the javadoc from the superclass. that's mindless and pointless monkey work
  • Use the standard style for the Javadoc comment
  • Do not use '**/' at the end of the Javadoc
  • Use simple HTML tags, not valid XHTML
  • XHTML adds many extra tags that make the Javadoc harder to read as source code
  • Use a single <p> tag between paragraphs
  • Place a single <p> tag on the blank line between paragraphs:
    • kuni katsuya
       
      this at least makes the paragraph breaks wysiwygísh and somewhat easier to read
  • Use a single <li> tag for items in a list
  • place a single <li> tag at the start of the line and no closing tag
  • Define a punchy first sentence
  • it has the responsibility of summing up the method or class to readers scanning the class or package
  • the first sentence should be
  • clear and punchy, and generally short
  • use the third person form at the start
  • Avoid the second person form, such as "Get the foo"
  • Use "this" to refer to an instance of the class
  • When referring to an instance of the class being documented, use "this" to reference it.
  • Aim for short single line sentences
  • Wherever possible, make Javadoc sentences fit on a single line
  • favouring between 80 and 120 characters
  • Use @link and @code wisely
  • @link feature creates a visible hyperlink in generated Javadoc to the target
  • @code feature provides a section of fixed-width font, ideal for references to methods and class names
  • Only use @link on the first reference to a specific class or method
  • Use @code for subsequent references.
  • This avoids excessive hyperlinks cluttering up the Javadoc
  • Never use @link in the first sentence
  • Always use @code in the first sentence if necessary
  • Adding a hyperlink in that first sentence makes the higher level documentation more confusing
  • Do not use @code for null, true or false
  • Adding @code for every occurrence is a burden to both the reader and writer of the Javadoc and adds no real value.
  • Use @param, @return and @throws
  • @param entries should be specified in the same order as the parameters
  • @return should be after the @param entries
  • followed by @throws.
  • Use @param for generics
  • correct approach is an @param tag with the parameter name of <T> where T is the type parameter name.
  • Use one blank line before @param
  • This aids readability in source code.
  • Treat @param and @return as a phrase
  • They should start with a lower case letter, typically using the word "the". They should not end with a dot. This aids readability in source code and when generated.
  • treated as phrases rather than complete sentences
  • Treat @throws as an if clause
  • phrase describing the condition
  • Define null-handling for all parameters and return types
    • kuni katsuya
       
      ideally, if the method in question has any specified/required pre and/or post conditions, they should be noted in the javadoc, not *just* null handling also, there are cleaner ways to design around this type of old school null handling hackage
  • methods should define their null-tolerance in the @param or @return
  • standard forms expressing this
  • "not null"
  • "may be null"
  • "null treated as xxx"
    • kuni katsuya
       
      DO NOT DO THIS this is just bad design
  • "null returns xxx"
    • kuni katsuya
       
      this might also stink of poor design ymmv
  • In general the behaviour of the passed in null should be defined
  • Specifications require implementation notes
  • Avoid @author
  • source control system is in a much better position to record authors
  • This wastes everyone's time and decreases the overall value of the documentation. When you have nothing useful to say, say nothing!
    • kuni katsuya
       
      likewise with javadoc on things like default constructors /**  * Creates an instance of SomeClass  */ public SomeClass() {} is equally useless and unnecessarily clutters up the source code
kuni katsuya

WildcardPermission (Apache Shiro 1.2.1 API) - 0 views

  • first token is the
  • domain
  • second token is the
  • ...7 more annotations...
  • action b
  • eing performed
  • boolean implies(Permission p)
  • Returns true if this current instance
  • implies all the functionality and/or resource access described by the specified Permission argument
  • false otherwise
  • current instance must be exactly equal to or a superset of the functionalty and/or resource access described by the given Permission argument
  •  
    "first token is the"
kuni katsuya

Access control - Wikipedia, the free encyclopedia - 0 views

  • Computer security
  • authentication, authorization and audit
  • In any access control model, the entities that can perform actions in the system are called subjects, and the entities representing resources to which access may need to be controlled are called objects
  • ...39 more annotations...
  • Principle of least privilege
  • object-capability model, any software entity can potentially act as both a subject and object
  • Access control models used by current systems tend to fall into one of two classes:
  • those based on capabilities
  • those based on access control lists (ACLs)
  • Both capability-based and ACL-based models have mechanisms to allow access rights to be granted to all members of a group of subjects (often the group is itself modeled as a subject)
  • identification and authentication determine who can log on to a system, and the association of users with the software subjects that they are able to control as a result of logging in; authorization determines what a subject can do; accountability identifies what a subject (or all subjects associated with a user) did.
  • Authorization determines what a subject can do on the system
  • Authorization
  • Access control models
  • categorized as either discretionary or non-discretionary
  • three most widely recognized models are
  • Discretionary Access Control (DAC)
  • Mandatory Access Control (MAC)
  • Role Based Access Control (RBAC)
  • Attribute-based access control
  • Discretionary access control
  • Discretionary access control (DAC) is a policy determined by the owner of an object. The owner decides who is allowed to access the object and what privileges they have.
  • Every object in the system has an owner
  • access policy for an object is determined by its owner
  • DAC systems, each object's initial owner is the subject that caused it to be created
  • Mandatory access control
  • Mandatory access control refers to allowing access to a resource
  • if and only if rules exist
  • that allow a given user to access the resource
  • Management is often simplified (over what can be required) if the information can be protected using
  • hierarchical access control
  • or by implementing sensitivity labels.
  • Sensitivity labels
  • A subject's sensitivity label specifies its
  • level of trust
  • level of trust required for access
  • subject must have a sensitivity level equal to or higher than the requested object
  • Role-based access control
  • Role-based access control (RBAC) is an
  • access policy
  • determined by the system
  • not the owner
  • Access control
kuni katsuya

Pro JPA 2: Mastering the Java™ Persistence API > Advanced Topics > SQL Querie... - 0 views

  • queries are also known as native queries
  • SQL Queries
  • reasons why a developer using JP QL might want to integrate SQL queries into their application
  • ...32 more annotations...
  • JPA 2.0, still contains only a subset of the features supported by many database vendors
  • features not supported in JP QL.
  • performance required by an application is to replace the JP QL query with a hand-optimized SQL version. This may be a simple restructuring of the query that the persistence provider was generating, or it may be a vendor-specific version that leverages query hints and features specific to a particular database.
  • recommend avoiding SQL initially if possible and then introducing it only when necessary
  • benefits of SQL query support is that it uses the same Query interface used for JP QL queries. With some small exceptions that will be described later, all the Query interface operations discussed in previous chapters apply equally to both JP QL and SQL queries.
  • keep application code consistent because it needs to concern itself only with the EntityManager and Query interfaces.
  • An unfortunate result of adding the TypedQuery interface in JPA 2.0 is that the createNativeQuery() method was already defined in JPA 1.0 to accept a SQL string and a result class and return an untyped Query interface
  • consequence is that when the createNativeQuery() method is called with a result class argument one might mistakenly think it will produce a TypedQuery, like createQuery() and createNamedQuery() do when a result class is passed in.
  • @NamedNativeQuery
  • resultClass=Employee.class
  • The fact that the named query was defined using SQL instead of JP QL is not important to the caller
  • SQL Result Set Mapping
  • JPA provides SQL result set mappings to handle these scenarios
  • A SQL result set mapping is defined using the @SqlResultSetMapping annotation. It may be placed on an entity class and consists of a name (unique within the persistence unit) and one or more entity and column mappings.
  • entities=@EntityResult(entityClass=Employee.class)
  • @SqlResultSetMapping
  • Multiple Result Mappings
  • A query may return more than one entity at a time
  • The SQL result set mapping to return both the Employee and Address entities out of this query
  • emp_id, name, salary, manager_id, dept_id
  • address_id, id, street, city, state, zip
  • order in which the entities are listed is not important
  • ntities={@EntityResult(entityClass=Employee.class), @EntityResult(entityClass=Address.class)}
  • expected result type and therefore received an instance of TypedQuery that is bound to the expected type. By qualifying the result type in this way, the getResultList() and getSingleResult() methods return the correct types without the need for casting.
  • Defining a Class for Use in a Constructor Expression
  • public EmpMenu(String employeeName, String departmentName)
  • List<EmpMenu>
  • NEW example.EmpMenu(" + "e.name, e.department.name)
  • EmpMenu.class
  • createNamedQuery() can return a TypedQuery whereas the createNativeQuery() method returns an untyped Query
  • List<Employee>
  • createNamedQuery("orgStructureReportingTo", Employee.class)
kuni katsuya

Chapter 15. Data Management - 1 views

  •  abstractEntity.uid();
    • kuni katsuya
       
      sets the uid before persist
  •  UUID.randomUUID().toString();
  • AbstractEntity 
  • ...70 more annotations...
  • @MappedSuperclass
  • Important things on ID/UID
  • entity lives in three layers:
  • Flex client
  • JPA persistence context
  • database
  • When updating existing entities coming from the database
  • id is defined and is maintained in the three layers during the different serialization/persistence operations
  • when a new entity is being created in any of the two upper layers (Flex/JPA)
  • new entity has no id until it has been persisted to the database
  • most common solution is to
  • have a second persisted id, the uid
  • which is created by the client and persisted along with the entity
  • recommended approach to avoid any kind of subtle problems is to have a real uid property which will be persisted in the database but is not a primary key for efficiency concerns
  • You can now ask Tide to
  • limit the object graph before sending it
  • Flex with the following API :
  • EntityGraphUnintializer
  • uninitializeEntityGraph
  • Person object will be uninitialized
  • uperson contains
  • only the minimum of data
  • to correctly merge your changes in the server persistence context
  • Tide uses the
  • client data tracking
  • to determine which parts of the graph need to be sent
  • Calling the EntityGraphUninitializer manually is a bit tedious and ugly, so there is a cleaner possibility when you are using generated typesafe service proxies
  • annotate your service method arguments with @org.granite.tide.data.Lazy :
  • @Lazy
  • take care that you have added the [Lazy] annotation to your Flex metadata compilation configuration
  • in the Flex application, register the UninitializeArgumentPreprocessor component in Tide as follows :
  • [UninitializeArgumentPreprocessor]
  • all calls to PersonService.save() will
  • automatically use a properly uninitialized version
  • of the person argument.
  • 15.4. Dirty Checking and Conflict Handling
  • simplify the handling of data between Flex and Java EE
  • Chapter 15. Data Management
  • Tide maintains a client-side cache of entity instances and ensures that every instance is unique in the Flex client context
  •  uid().hashCode();
  • Tide currently only supports Integer or Long version fields, not timestamps and that the field must be nullable
  • in a multi-tier environment (@Version annotation)
  • highly recommended to use
  • JPA optimistic locking
  • highly recommended to add a
  • persistent uid field
  • AbstractEntity
  • in general this identifier will be
  • initialized from Flex
  • @Column(name="ENTITY_UID", unique=true, nullable=false, updatable=false, length=36)     private String uid;
  • @Version     private Integer version;
  • uid().equals(((AbstractEntity)o).uid())
  • consistent identifier through all application layers
  • @PrePersist
  • 15.3. Reverse Lazy Loading
  • 15.4. Dirty Checking and Conflict Handling
  • 15.4. Dirty Checking and Conflict Handling
  • 15.4. Dirty Checking and Conflict Handling
  • Dirty Checking and Conflict Handling
  • entity instance can be in two states :
  • Stable
  • Dirty
  • property meta_dirty is
  • bindable
  • could be used
  • to enable/disable a Save button
  • correct way of knowing if any object has been changed in the context, is to use the property meta_dirty of the Tide context
  • tideContext.meta_dirty
  • reliable when using optimistic locking
  • check that its @Version field has been incremented
1 - 12 of 12
Showing 20 items per page