Search Results

Search found 356 results on 15 pages for 'getters'.

Page 11/15 | < Previous Page | 7 8 9 10 11 12 13 14 15  | Next Page >

  • web.xml - Java Servlet Filters and WebSphere - URL Pattern issues

    - by Ed
    Hi, So we are running a web application that has been tested on Tomcat, Glassfish, WebLogic and WebSphere. All run correctly except WebSphere. The issue is that filters are not processed for files under a certain directory. For example I have a filter that checks the user's lanuage from browser cookies and another that get the user's username, in the web.xml there are configured like so: <!-- ****************************** --> <!-- * Security context filtering * --> <!-- ****************************** --> <filter> <filter-name>SetSecurityContextFilter</filter-name> <filter-class> com.test.security.SecurityContextServletFilter </filter-class> </filter> <!-- ****************************** --> <!-- ** Locale context filtering ** --> <!-- ****************************** --> <filter> <filter-name>SetLocaleFilter</filter-name> <filter-class> com.test.locale.LocaleServletFilter </filter-class> </filter> <filter-mapping> <filter-name>SetSecurityContextFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>SetLocaleFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> Both filters set a static threadlocal variable which can be accessed from a static getter, but when the same file 'test.jsp' invokes the getters, under 'contextroot/js' they return the default values (as if unset) while under 'contextroot/pages' they are correct. Any ideas? Thanks in advance.

    Read the article

  • JPA merge fails due to duplicate key

    - by wobblycogs
    I have a simple entity, Code, that I need to persist to a MySQL database. public class Code implements Serializable { @Id private String key; private String description; ...getters and setters... } The user supplies a file full of key, description pairs which I read, convert to Code objects and then insert in a single transaction using em.merge(code). The file will generally have duplicate entries which I deal with by first adding them to a map keyed on the key field as I read them in. A problem arises though when keys differ only by case (for example: XYZ and XyZ). My map will, of course, contain both entries but during the merge process MySQL sees the two keys as being the same and the call to merge fails with a MySQLIntegrityConstraintViolationException. I could easily fix this by uppercasing the keys as I read them in but I'd like to understand exactly what is going wrong. The conclusion I have come to is that JPA considers XYZ and XyZ to be different keys but MySQL considers them to be the same. As such when JPA checks its list of known keys (or does whatever it does to determine whether it needs to perform an insert or update) it fails to find the previous insert and issuing another which then fails. Is this corrent? Is there anyway round this other than better filtering the client data? I haven't defined .equals or .hashCode on the Code class so perhaps this is the problem.

    Read the article

  • Enum "does not have a no-arg default constructor" with Jaxb and cxf

    - by Dave
    A client is having an issue running java2ws on some of their code, which uses & extends classes that are consumed from my SOAP web services. Confused yet? :) I'm exposing a SOAP web service (JBoss5, Java 6). Someone is consuming that web service with Axis1 and creating a jar out of it with the data types and client stubs. They are then defining their own type, which extends one of my types. My type contains an enumeration. class MyParent { private MyEnumType myEnum; // getters, settters for myEnum; } class TheirChild extends MyParent { ... } When they are running java2ws on their code (which extends my class), they get Caused by: com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions net.foo.bar.MyEnuMType does not have a no-arg default constructor. this problem is related to the following location: at net.foo.bar.MyEnumType at public net.foo.bar.MyEnumType net.foo.bar.MyParent.getMyEnum() The enum I've defined is below. This is now how it comes out after being consumed, but it's how I have it defined on the app server: @XmlType(name = "MyEnumType") @XmlEnum public enum MyEnumType { Val1("Val1"), Val2("Val2") private final String value; MyEnumType(String v) { value = v; } public String value() { return value; } public static MyEnumType fromValue(String v) { if (v == null || v.length() == 0) { return null; } if (v.equals("Val1")) { return MyEnumType.Val1; } if (v.equals("Val2")) { return MyEnumType.Val2; } return null; } } I've seen things online and other posts, like (this one) regarding Jaxb's inability to handle Lists or things like that, but I'm baffled about my enum. I'm pretty sure you can't have a default constructor for an enum (well, at least a public no-arg constructor, Java yells at me when I try), so I'm not sure what makes this error possible. Any ideas? Also, the "2 counts of IllegalAnnotationsExceptions" may be because my code actually has two enums that are written similarly, but I left them out of this example for brevity.

    Read the article

  • Best practices for class-mapping with SoapClient

    - by Foofy
    Using SoapClient's class mapping feature and it's pretty sweet. Unfortunately the SOAP service we're using has a bunch of read-only properties on some of the objects and will throw faults if the properties are passed back as anything but null. Need to filter out the properties before they're used in the SOAP call and am looking for advice on the best way to do it. So far the options are: Stick to a convention where I use getter and setter functions to manipulate the properties, and use property overloading to filter method access since only SoapClient would be doing that. E.g. developers would access properties like this: $obj->getAccountNumber() SoapClient would access properties like this: $obj->accountNumber I don't like this because the properties are still exposed and things could go wrong if developers don't stick to convention. Have a wrapper for SoapClient that sets a public property the mapped objects can check to see if the property is being accessed by SoapClient. I already have a wrapper that assigns a reference to itself to all the mapped objects. class SoapClientWrapper { public function __soapCall($method, $args) { $this->setSoapMode(true); $this->_soapClient->__soapCall($method, $args); $this->setSoapMode(false); } } class Invoice { function __get($val) { if($this->_soapClient->getSoapMode()) { return null; } else { return $this->$val; } } } This works but it doesn't feel right and seems a bit clunky. Do the mapping manually, and don't use SoapClient's mapping features. I'd just have a function on all the mapped objects that returns the safe-to-send properties. Also, nobody would have access to properties they shouldn't since I could enforce getters and setters. A lot more work, though.

    Read the article

  • Spring MVC parameter validation

    - by Don
    Hi, I've defined a controller, validator and command class for a Spring 2.5 MVC application like this: public class ResourceController extends AbstractCommandController { private MessageRetriever messageRetriever; protected ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { ResourceCommand resourceCommand = (ResourceCommand) command; // I NEED TO CHECK HERE IF COMMAND IS VALID? } public static class ResourceCommand { private String module; private String site; private String lang; // GETTERS AND SETTERS OMITTED } public static class ResourceValidator implements Validator { public boolean supports(Class clazz) { return ResourceCommand.class.isAssignableFrom(clazz); } public void validate(Object obj, Errors errors) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "module", "MODULE_REQUIRED"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "site", "SITE_REQUIRED"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lang", "LANG_REQUIRED"); } } } I have wired these all together in the application context: <bean id="resourceController" class="com.amadeus.jcp.ui.framework.localization.ResourceController"> <property name="commandClass" value="com.amadeus.jcp.ui.framework.localization.ResourceController.ResourceCommand"/> <property name="validator"> <bean class="com.amadeus.jcp.ui.framework.localization.ResourceController.ResourceValidator"/> </property> </bean> However, I can't figure out how to actually check whether the command is valid or not - I assume the framework calls the validator, but how do I get access to the result? Incidentally, I'm using Java 1.4, so can't use any solutions that require annotations or other Java 1.5 features. Thanks, Don

    Read the article

  • Spring-hibernate mapping problem

    - by James
    I have a spring-hibernate application which is failing to map an object properly: basically I have 2 domain objects, a Post and a User. The semantics are that every Post has 1 corresponding User. The Post domain object looks roughly as follows: class Post { private int pId; private String attribute; ... private User user; //getters and setters here } As you can see, Post contains a reference to User. When I load a Post object, I want to corresponding User object to be loaded (lazily - only when its needed). My mapping looks as follows: <class name="com...Post" table="post"> <id name="pId" column="PostId" /> <property name="attribute" column="Attribute" type="java.lang.String" /> <one-to-one name="User" fetch="join" class="com...User"></one-to-one> </class> And of course I have a basic mapping for User set up. As far as my table schema is concerned, I have a table called post with a foreign UserId which links to the user table. I thought this setup should work, BUT when I load a page that forces the lazy loading of the User object, I notice the following Hiberate query being generated: Select ... from post this_ left outer join user user2_ on this.PostId=user2_.UserId ... Obviously this is wrong: it should be joining UserId from post with UserId from user, but instead its incorrectly joining PostId from post (its primary key) with UserId from user. Any ideas? Thanks!

    Read the article

  • Java - Is this a bad design pattern?

    - by Walter White
    Hi all, In our application, I have seen code written like this: User.java (User entity) public class User { protected String firstName; protected String lastName; ... getters/setters (regular POJO) } UserSearchCommand { protected List<User> users; protected int currentPage; protected int sortColumnIndex; protected SortOder sortOrder; // the current user we're editing, if at all protected User user; public String getFirstName() {return(user.getFirstName());} public String getLastName() {return(user.getLastName());} } Now, from my experience, this pattern or anti-pattern looks bad to me. For one, we're mixing several concerns together. While they're all user-related, it deviates from typical POJO design. If we're going to go this route, then shouldn't we do this instead? UserSearchCommand { protected List<User> users; protected int currentPage; protected int sortColumnIndex; protected SortOder sortOrder; // the current user we're editing, if at all protected User user; public User getUser() {return(user);} } Simply return the user object, and then we can call whatever methods on it as we wish? Since this is quite different from typical bean development, JSR 303, bean validation doesn't work for this model and we have to write validators for every bean. Does anyone else see anything wrong with this design pattern or am I just being picky as a developer? Walter

    Read the article

  • How to ask BeanUtils to ignore null values

    - by Calm Storm
    Using Commons beanUtils I would like to know how to ask any converter say the Dateconverter to ignore null values and use null as default. As an example consider a public class, public class X { private Date date1; private String string1; //add public getters and setters } and my convertertest as, public class Apache { @Test public void testSimple() throws Exception { X x1 = new X(), x2 = new X(); x1.setString1("X"); x1.setDate1(null); org.apache.commons.beanutils.BeanUtils.copyProperties(x2, x1); //throws ConversionException System.out.println(x2.getString1()); System.out.println(x2.getDate1()); } } The above throws a NPE since the date happens to be null. This looks a very primitive scenario to me which should be handled by default (as in, I would expect x2 to have null value for date1). The doco tells me that I can ask the converter to do this. Can someone point me as to the best way for doing this ? I dont want to get hold of the Converter and isUseDefault() to be true because then I have to do it for all Date, Enum and many other converters !

    Read the article

  • ObjC: Alloc instance of Class and performing selectors on it leads to __CFRequireConcreteImplementat

    - by Arakyd
    Hi, I'm new to Objective-C and I'd like to abstract my database access using a model class like this: @interface LectureModel : NSMutableDictionary { } -(NSString*)title; -(NSDate*)begin; ... @end I use the dictionary methods setValue:forKey: to store attributes and return these in the getters. Now I want to read these models from a sqlite database by using the Class dynamically. + (NSArray*)findBySQL:(NSString*)sql intoModelClass:(Class)modelClass { NSMutableArray* models = [[[NSMutableArray alloc] init] autorelease]; sqlite3* db = sqlite3_open(...); sqlite3_stmt* result = NULL; sqlite3_prepare_v2(db, [sql UTF8String], -1, &result, NULL); while(sqlite3_step(result) == SQLITE_ROW) { id modelInstance = [[modelClass alloc] init]; for (int i = 0; i < sqlite3_column_count(result); ++i) { NSString* key = [NSString stringWithUTF8String:sqlite3_column_name(result, i)]; NSString* value = [NSString stringWithUTF8String:(const char*)sqlite3_column_text(result, i)]; if([modelInstance respondsToSelector:@selector(setValue:forKey:)]) [modelInstance setValue:value forKey:key]; } [models addObject:modelInstance]; } sqlite3_finalize(result); sqlite3_close(db); return models; } Funny thing is, the respondsToSelector: works, but if I try (in the debugger) to step over [modelInstance setValue:value forKey:key], it will throw an exception, and the stacktrace looks like: #0 0x302ac924 in ___TERMINATING_DUE_TO_UNCAUGHT_EXCEPTION___ #1 0x991d9509 in objc_exception_throw #2 0x302d6e4d in __CFRequireConcreteImplementation #3 0x00024d92 in +[DBManager findBySQL:intoModelClass:] at DBManager.m:114 #4 0x0001ea86 in -[FavoritesViewController initializeTableData:] at FavoritesViewController.m:423 #5 0x0001ee41 in -[FavoritesViewController initializeTableData] at FavoritesViewController.m:540 #6 0x305359da in __NSFireDelayedPerform #7 0x302454a0 in CFRunLoopRunSpecific #8 0x30244628 in CFRunLoopRunInMode #9 0x32044c31 in GSEventRunModal #10 0x32044cf6 in GSEventRun #11 0x309021ee in UIApplicationMain #12 0x00002988 in main at main.m:14 So, what's wrong with this? Presumably I'm doing something really stupid and just don't see it... Many thanks in advance for your answers, Arakyd :..

    Read the article

  • EJB3 Entity and Lazy Problem

    - by Stefano
    My Entity beAN have 2 list: @Entity @Table(name = "TABLE_INTERNAL") public class Internal implements java.io.Serializable { ...SOME GETTERS AND SETTERS... private List<Match> matchs; private List<Regional> regionals; } mapped one FetchType.LAZY and one FetchType.EAGER : @OneToMany(fetch = FetchType.LAZY,mappedBy = "internal") public List<Match> getMatchs() { return matchs; } public void setMatchs(List<Match> matchs) { this.matchs = matchs; } @ManyToMany(targetEntity = Regional.class, mappedBy = "internals", fetch =FetchType.EAGER) public List<Regional> getRegionals() { return regionals; } public void setRegionals(List<Regional> regionals) { this.regionals = regionals; } I need both lists full ! But I cant put two FetchType.EAGER beacuse it's an error. I try some test: List<Internal> out; out= em.createQuery("from Internal").getResultList(); out= em.createQuery("from Internal i JOIN FETCH i.regionals ").getResultList(); I'm not able to fill both lists...Help!!! Stefano

    Read the article

  • OpenCMS - Search field of custom bean

    - by Luigi 1982
    Hi at all... I make some beans with information from VFS of OpenCMS. I want to make searchable the data of my beans. I follow this step but without success: 1) Extends my bean class with CmsSearch and ovverride init method. After I make some stuff for the constructor of my bean: /* Some stuff for CMSSearch */ /** Constant for the fields we will search */ static final String[] DOC_QRY_FIELDS = new String[] {"oggettoDocumento","dataPubblicazione", "societa"}; /** The names of our search index files */ static final String OFFLINE_INDEX = "all_bacheca"; static final String ONLINE_INDEX = "all_bacheca"; public DocumentBean(){ super(); m_parameters.setSort(CmsSearchParameters.SORT_DEFAULT); m_parameters.setFields(Arrays.asList(DocumentBean.DOC_QRY_FIELDS)); m_parameters.setIndex(ONLINE_INDEX); m_parameters.setMatchesPerPage(20); } public void init(CmsObject cms) { super.init(cms); // set search index to offline or online based on current //user project if (cms.getRequestContext().currentProject().isOnlineProject()) { m_parameters.setIndex(ONLINE_INDEX); } else { m_parameters.setIndex(OFFLINE_INDEX); } } // getters and setters.. 2) Configure a new DocumentField with the new field 3) Adding code to my jsp: <input type="hidden" name="field" value="oggettoDocumento"/> But nothing... How can I perform the custom bean search? I can't find any document.. If anyone know some info, basic.. is good for me.. Thanks!

    Read the article

  • Getter and Setter vs. Builder strategy

    - by Extrakun
    I was reading a JavaWorld's article on Getter and Setter where the basic premise is that getters expose internal content of an object, hence tightening coupling, and go on to provide examples using builder objects. I was rather leery of abolishing getter/setter but on second reading of the article, see to quite like the idea. However, sometimes I just need one cruical element of an entity class, such as the user's id and writing one whole class just to extract that cruical element seems like overkill. It also implies that for different view, a different type of importer/exporter must be implemented (or the whole data of the class to be exported out, thus resulting in waste). Usually I tend towards filtering the result of a getter - for example, if I need to output the price of a product in different currency, I would code it as: return CurrencyOutput::convertTo($product->price(), 'USD'); This is with the understanding that the raw output of a getter is not necessary the final result to be pushed onto a screen or a database. Is getter/setter really as bad as it is protrayed to be? When should one adopt a builder strategy, or a 'get the result and filter it' approach? How do you avoid having a class needing to know about every other objects if you are not using getter/setter?

    Read the article

  • NetBeans Tips and Tricks

    - by cdmckay
    I just saw an Eclipse tips & tricks post and was wondering if anyone had any tips & tricks for my IDE of choice: NetBeans. Here's a few I know and find to be useful: Removing a package: After you remove a package in NetBeans, it sticks around as a grayed-out package in your Project view. To get rid of that, switch to Files view and delete the directory. Alt-Insert (in Windows) opens up a Generate submenu at your cursor. A nice shortcut for quickly generating getters/setters (among other things). Selecting a chunk of code, right-clicking and then clicking "Refactor Introduce Method" will have NetBeans introduce a method, complete with arguments and return value. Of course you have to make sure the chunk of code only has one return value. Sometimes when you run a build and it crashes, the Java window sticks around at the bottom. I used to just click X until Windows let me End Task, but there's a nicer way to get rid of them. Click "Run Stop Build/Run" and NetBeans will close the window for you. It'll even let you close multiple applications at once. These may seem obvious to grizzled NetBeans developers, but I thought they might be useful for NetBeans newbs like me. Anyone else have any tips/tricks to share? Here are some from the comments: NetBeans allows for code templates. You can even add yours on the Code Templates tab under the Editor settings on the Options window. Some examples: Type sout and hit the tab key as a shorcut for System.out.println("") Type psvm and hit the tab key as a shorcut for public static void main(String args[]) {} Ctrl Shift C: Comments out the selected block of code. Alt Shift F: Formats the selected block of code. Ctrl E: Deletes current line. Ctrl Shift I: Fixes your imports, handy if you've just written a piece of code that needs a lot of packages imported.

    Read the article

  • Object oriented design of game in Java: How to handle a party of NPCs?

    - by Arvanem
    Hi folks, I'm making a very simple 2D RPG in Java. My goal is to do this in as simple code as possible. Stripped down to basics, my class structure at the moment is like this: Physical objects have an x and y dimension. Roaming objects are physical objects that can move(). Humanoid objects are roaming objects that have inventories of GameItems. The Player is a singleton humanoid object that can hire up to 4 NPC Humanoids to join his or her party, and do other actions, such as fight non-humanoid objects. NPC Humanoids can be hired by the Player object to join his or her party, and once hired can fight for the Player. So far I have given the Player class a "party" ArrayList of NPC Humanoids, and the NPC Humanoids class a "hired" Boolean. However, my fight method is clunky, using an if to check the party size before implementing combat, e.g. public class Player extends Humanoids { private ArrayList<Humanoids> party; // GETTERS AND SETTERS for party here //... public void fightEnemy(Enemy eneObj) { if (this.getParty().size() == 0) // Do combat without party issues else if (this.getParty().size() == 1) // Do combat with party of 1 else if (this.getParty().size() == 2) // Do combat with party of 2 // etc. My question is, thinking in object oriented design, am I on the right track to do this in as simple code as possible? Is there a better way?

    Read the article

  • java Properties - to expose or not to expose?

    - by ring bearer
    This might be an age old problem and I am sure everyone has their own ways. Suppose I have some properties defined such as secret.user.id=user secret.password=password website.url=http://stackoverflow.com Suppose I have 100 different classes and places where I need to use these properties. Which one is good (1) I create a Util class that will load all properties and serve them using a key constant Such as : Util is a singleton that loads all properties and keeps up on getInstance() call. Util myUtil = Util.getInstance(); String user = myUtil.getConfigByKey(Constants.SECRET_USER_ID); String password = myUtil.getConfigByKey(Constants.SECRET_PASSWORD); .. //getConfigByKey() - inturns invokes properties.get(..) doSomething(user, password) So wherever I need these properties, I can do steps above. (2) I create a meaningful Class to represent these properties; say, ApplicationConfig and provide getters to get specific properties. So above code may look like: ApplicationConfig config = ApplicationConfig.getInstance(); doSomething(config.getSecretUserId(), config.getPassword()); //ApplicationConfig would have instance variables that are initialized during // getInstance() after loading from properties file. Note: The properties file as such will have only minor changes in the future. My personal choice is (2) - let me hear some comments?

    Read the article

  • Avoiding anemic domain model - a real example

    - by cbp
    I am trying to understand Anemic Domain Models and why they are supposedly an anti-pattern. Here is a real world example. I have an Employee class, which has a ton of properties - name, gender, username, etc public class Employee { public string Name { get; set; } public string Gender { get; set; } public string Username { get; set; } // Etc.. mostly getters and setters } Next we have a system that involves rotating incoming phone calls and website enquiries (known as 'leads') evenly amongst sales staff. This system is quite complex as it involves round-robining enquiries, checking for holidays, employee preferences etc. So this system is currently seperated out into a service: EmployeeLeadRotationService. public class EmployeeLeadRotationService : IEmployeeLeadRotationService { private IEmployeeRepository _employeeRepository; // ...plus lots of other injected repositories and services public void SelectEmployee(ILead lead) { // Etc. lots of complex logic } } Then on the backside of our website enquiry form we have code like this: public void SubmitForm() { var lead = CreateLeadFromFormInput(); var selectedEmployee = Kernel.Get<IEmployeeLeadRotationService>() .SelectEmployee(lead); Response.Write(employee.Name + " will handle your enquiry. Thanks."); } I don't really encounter many problems with this approach, but supposedly this is something that I should run screaming from because it is an Anemic Domain Model. But for me its not clear where the logic in the lead rotation service should go. Should it go in the lead? Should it go in the employee? What about all the injected repositories etc that the rotation service requires - how would they be injected into the employee, given that most of the time when dealing with an employee we don't need any of these repositories?

    Read the article

  • When to use "property" builtin: auxiliary functions and generators

    - by Seth Johnson
    I recently discovered Python's property built-in, which disguises class method getters and setters as a class's property. I'm now being tempted to use it in ways that I'm pretty sure are inappropriate. Using the property keyword is clearly the right thing to do if class A has a property _x whose allowable values you want to restrict; i.e., it would replace the getX() and setX() construction one might write in C++. But where else is it appropriate to make a function a property? For example, if you have class Vertex(object): def __init__(self): self.x = 0.0 self.y = 1.0 class Polygon(object): def __init__(self, list_of_vertices): self.vertices = list_of_vertices def get_vertex_positions(self): return zip( *( (v.x,v.y) for v in self.vertices ) ) is it appropriate to add vertex_positions = property( get_vertex_positions ) ? Is it ever ok to make a generator look like a property? Imagine if a change in our code meant that we no longer stored Polygon.vertices the same way. Would it then be ok to add this to Polygon? @property def vertices(self): for v in self._new_v_thing: yield v.calculate_equivalent_vertex()

    Read the article

  • What's the best way to read a UDT from a database with Java?

    - by Lukas Eder
    I thought I knew everything about UDTs and JDBC until someone on SO pointed out some details of the Javadoc of java.sql.SQLInput and java.sql.SQLData JavaDoc to me. The essence of that hint was (from SQLInput): An input stream that contains a stream of values representing an instance of an SQL structured type or an SQL distinct type. This interface, used only for custom mapping, is used by the driver behind the scenes, and a programmer never directly invokes SQLInput methods. This is quite the opposite of what I am used to do (which is also used and stable in productive systems, when used with the Oracle JDBC driver): Implement SQLData and provide this implementation in a custom mapping to ResultSet.getObject(int index, Map mapping) The JDBC driver will then call-back on my custom type using the SQLData.readSQL(SQLInput stream, String typeName) method. I implement this method and read each field from the SQLInput stream. In the end, getObject() will return a correctly initialised instance of my SQLData implementation holding all data from the UDT. To me, this seems like the perfect way to implement such a custom mapping. Good reasons for going this way: I can use the standard API, instead of using vendor-specific classes such as oracle.sql.STRUCT, etc. I can generate source code from my UDTs, with appropriate getters/setters and other properties My questions: What do you think about my approach, implementing SQLData? Is it viable, even if the Javadoc states otherwise? What other ways of reading UDT's in Java do you know of? E.g. what does Spring do? what does Hibernate do? What does JPA do? What do you do? Addendum: UDT support and integration with stored procedures is one of the major features of jOOQ. jOOQ aims at hiding the more complex "JDBC facts" from client code, without hiding the underlying database architecture. If you have similar questions like the above, jOOQ might provide an answer to you.

    Read the article

  • How to get error text in controller from BindingResult

    - by Mike
    I have an controller that returns JSON. It takes a form, which validates itself via spring annotations. I can get FieldError list from BindingResult, but they don't contain the text that a JSP would display in the tag. How can I get the error text to send back in JSON? @RequestMapping(method = RequestMethod.POST) public @ResponseBody JSONResponse submit(@Valid AnswerForm answerForm, BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response) { if (result.hasErrors()) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); JSONResponse r = new JSONResponse(); r.setStatus(JSONResponseStatus.ERROR); //HOW DO I GET ERROR MESSAGES OUT OF BindingResult??? } else { JSONResponse r = new JSONResponse(); r.setStatus(JSONResponseStatus.OK); return r; } } JSONREsponse class is just a POJO public class JSONResponse implements Serializable { private JSONResponseStatus status; private String error; private Map<String,String> errors; private Map<String,Object> data; ...getters and setters... } Calling BindingResult.getAllErrors() returns an array of FieldError objects, but it doesn't have the actual errors.

    Read the article

  • SpringMvc Annotations for DAO interface and DAO implementation

    - by dev_darin
    I would like to know if I am annotating these classes correctly, since I am new to the annotations: Country.java @Component public class Country { private int countryId; private String countryName; private String countryCode; /** * No args constructor */ public Country() { } /** * @param countryId * @param countryName * @param countryCode */ public Country(int countryId, String countryName, String countryCode) { this.countryId = countryId; this.countryName = countryName; this.countryCode = countryCode; } //getters and setters } CountryDAO.java @Repository public interface CountryDAO { public List<Country> getCountryList(); public void saveCountry(Country country); public void updateCountry(Country country); } JdbcCountryDAO.java @Component public class JdbcCountryDAO extends JdbcDaoSupport implements CountryDAO{ private final Logger logger = Logger.getLogger(getClass()); @Autowired public List<Country> getCountryList() { int countryId = 6; String countryCode = "AI"; logger.debug("In getCountryList()"); String sql = "SELECT * FROM TBLCOUNTRY WHERE countryId = ? AND countryCode = ?"; logger.debug("Executing getCountryList String "+sql); Object[] parameters = new Object[] {countryId, countryCode}; logger.info(sql); //List<Country> countryList = getJdbcTemplate().query(sql,new CountryMapper()); List<Country> countryList = getJdbcTemplate().query(sql, parameters,new CountryMapper()); return countryList; } CountryManagerIFace.java @Repository public interface CountryManagerIFace extends Serializable{ public void saveCountry(Country country); public List<Country> getCountries(); } CountryManager.java @Component public class CountryManager implements CountryManagerIFace{ @Autowired private CountryDAO countryDao; public void saveCountry(Country country) { countryDao.saveCountry(country); } public List<Country> getCountries() { return countryDao.getCountryList(); } public void setCountryDao(CountryDAO countryDao){ this.countryDao = countryDao; } }

    Read the article

  • How do I write test code to exercise a C# generic Pair<TKey, TValue> ?

    - by Scott Davies
    Hi, I am reading through Jon Skeet's "C# in Depth", first edition (which is a great book). I'm in section 3.3.3, page 84, "Implementing Generics". Generics always confuse me, so I wrote some code to exercise the sample. The code provided is: using System; using System.Collections.Generic; public sealed class Pair<TFirst, TSecond> : IEquatable<Pair<TFirst, TSecond>> { private readonly TFirst first; private readonly TSecond second; public Pair(TFirst first, TSecond second) { this.first = first; this.second = second; } ...property getters... public bool Equals(Pair<TFirst, TSecond> other) { if (other == null) { return false; } return EqualityComparer<TFirst>.Default.Equals(this.First, other.First) && EqualityComparer<TSecond>.Default.Equals(this.Second, other.Second); } My code is: class MyClass { public static void Main (string[] args) { // Create new pair. Pair thePair = new Pair(new String("1"), new String("1")); // Compare a new pair to previous pair by generating a second pair. if (thePair.Equals(new Pair(new string("1"), new string("1")))) System.Console.WriteLine("Equal"); else System.Console.WriteLine("Not equal"); } } The compiler complains: "Using the generic type 'ManningListing36.Paie' requires 2 type argument(s) CS0305" What am I doing wrong ? Thanks, Scott

    Read the article

  • Trouble passing JSP values to ActionForm (Struts)

    - by tacotime
    Hi, I am a newbie to Struts and have inherited a problem. I am trying to pass 3 values contained in the same table cell from a JSP to my ActionForm class. The first value (and others in the JSP) work fine, but for some reason the other two do not. I have the appropriate getters and setters, but only the first (newrecnum) shows up, the other two are null. Is there a limitation to only pass the first value? Or is there something else wrong? Here is the JSP code: <td> <html:text size="10" maxlength="10" property="newrecnum"/><br> <html:text size="5" maxlength="5" property="newrectime"/> <html:select property="newreccode" disabled="true"> <html:option value="YES">YES</html:option> <html:option value="NO">NO</html:option></html:select> </td> I can include the ActionForm code as well if needed. Thanks!

    Read the article

  • How to identify the type of socket data?

    - by Nitesh Panchal
    Hello, May be i am not able to express my doubt properly in this question but still i will try. Basically i created a simple socket based chat program and everything works fine. But i think i have made many patches in it from the design point of view. I have used ObjectInputStream and ObjectOutputStreams in my program. The question i want to ask is how do i identify the different type of data that i send across the network? say if it is simple String type object i directly add to List<String> chatMessages. Now if want to ban certain users i created an another class :- public class User{ private String name; private String id; //getters and setters } This User class means no importance to me till now but i only created it to properly identify the action. Thus if i receive an instanceOf User i can be sure that some user is to be banned. That way i dont have to hardcode strings. I mean first i thought of sending something like "Banned User :" + userName and then i used to check if string startsWith "Banned User :" then i take some action :p. I've created a User class but it means no importance to me in my program. I want to know whether directly sending strings is good way or create a class for every action that is good. If i am not clear please let me know. If i have hundreds of action do i have to create hundreds of classes so i can check via instanceOf? Say now if i plan to create a BUZZ like facility that is available in yahoo messenger. Should i again create an another class named BUZZ? so it can be identified easily?

    Read the article

  • Turning a JSON list into a POJO

    - by Josh L
    I'm having trouble getting this bit of JSON into a POJO. I'm using Jackson configured like this: protected ThreadLocal<ObjectMapper> jparser = new ThreadLocal<ObjectMapper>(); public void receive(Object object) { try { if (object instanceof String && ((String)object).length() != 0) { ObjectDefinition t = null ; if (parserChoice==0) { if (jparser.get()==null) { jparser.set(new ObjectMapper()); } t = jparser.get().readValue((String)object, ObjectDefinition.class); } Object key = t.getKey(); if (key == null) return; transaction.put(key,t); } } catch (Exception e) { e.printStackTrace(); } } Here's the JSON that needs to be turned into a POJO: { "id":"exampleID1", "entities":{ "tags":[ { "text":"textexample1", "indices":[ 2, 14 ] }, { "text":"textexample2", "indices":[ 31, 36 ] }, { "text":"textexample3", "indices":[ 37, 43 ] } ] } And lastly, here's what I currently have for the java class: protected Entities entities; @JsonIgnoreProperties(ignoreUnknown = true) protected class Entities { public Entities() {} protected Tags tags; @JsonIgnoreProperties(ignoreUnknown = true) protected class Tags { public Tags() {} protected String text; public String getText() { return text; } public void setText(String text) { this.text = text; } }; public Tags getTags() { return tags; } public void setTags(Tags tags) { this.tags = tags; } }; //Getters & Setters ... I've been able to translate the more simple objects into a POJO, but the list has me stumped. Any help is appreciated. Thanks!

    Read the article

  • templete class c++

    - by inna karpasas
    hi! i try to design a templete for my universty project. i wrote the follwing cod: #ifndef _LinkedList_H_ #define _LinkedList_H_ #include "Link.h" #include <ostream> template <class L>//error one class LinkedList { private: Link<L> *pm_head; Link<L> * pm_tail; int m_numOfElements; Link<L>* FindLink(L * dataToFind); public: LinkedList(); ~LinkedList(); int GetNumOfElements(){return m_numOfElements;} bool Add( L * data); L *FindData(L * data); template <class L> friend ostream & operator<<(ostream& os,const LinkedList<L> listToprint);//error two L* GetDataOnTop(); bool RemoveFromHead(); L* Remove(L * toRemove); this templete uses the link class templete #ifndef _Link_H_ #define _Link_H_ template <class T>//error 3 class Link { private: T* m_data; Link* m_next; Link* m_prev; public: Link(T* data); ~Link(void); bool Link::operator ==(const Link& other)const; /*getters*/ Link* GetNext()const {return m_next;} Link* GetPrev()const {return m_prev;} T* GetData()const {return m_data;} //setters void SetNext(Link* next) {m_next = next;} void SetPrev(Link* prev) {m_prev = prev;} void SetData(T* data) {m_data = data;} }; error one: shadows template parm class L' error two:declaration ofclass L' error three: shadows template parm `class T' i dont understand what is the problem. i can relly usr your help thank you :)

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15  | Next Page >