
- Type about:config in Firefox address bar.
- If it displays a warning, confirm you know what you're doing.
- Find this property (you can use the filter): browser.display.focus_ring_width
- Set its value to 0 (zero).
Java, JEE, Spring, photography blog.
sudo dkms install virtualbox/4.1.2 sudo modprobe vboxdrv
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerHmm... How can I use a JBoss AS7 module as a dependency? The solution is to add the org.slf4j entry as a MANIFEST.MF dependency. The MANIFEST.MF file looks then like that:
Manifest-Version: 1.0 Archiver-Version: Plexus Archiver Created-By: Apache Maven Built-By: M1key Build-Jdk: 1.6.0_27 Dependencies: org.slf4jMaven can do it for you automatically.
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <configuration> <archive> <manifestEntries> <Dependencies>org.slf4j</Dependencies> </manifestEntries> </archive> </configuration> </plugin>I guess I should have RTFM... More about class loading in AS7.
@Controller @RequestMapping("/personRegistration") @SessionAttributes("personTo") public class PersonRegistrationController {Now, let's take a look at initialisation code. The controller expects an appropriate validator to be passed during construction time. The validator is, in our case, a Spring bean, so we can have it autowired.
@Autowired public PersonRegistrationController(PersonRegistrationValidator validator) { super(); this.validator = validator; } @InitBinder public void initBinder(WebDataBinder binder) { binder.registerCustomEditor(Gender.class, new GenderEditor()); }Next, look at the method that handles GET requests. This method resets the potentially submitted data by creating a new PersonTo object and storing it in session. It requests the registration name form to be displayed. (The forms code will soon follow)
@RequestMapping(method = RequestMethod.GET) public String setupForm(Model model) { PersonTo personTo = new PersonTo(); model.addAttribute(PERSON_TO, personTo); return REGISTRATION_NAME_FORM; }And now the big thing. The method that handles POST requests which are those where the user actually submitted data.
@RequestMapping(method = RequestMethod.POST) public String submitForm(HttpServletRequest request, HttpServletResponse response, @ModelAttribute(PERSON_TO) PersonTo personTo, BindingResult result, SessionStatus status, @RequestParam("_page") int currentPage, Model model) { Map<Integer, String> pageForms = new HashMap<Integer, String>(); pageForms.put(0, REGISTRATION_NAME_FORM); pageForms.put(1, REGISTRATION_GENDER_FORM); if (userClickedCancel(request)) { status.setComplete(); return REDIRECT_TO_HOMEPAGE; } else if (userIsFinished(request)) { validator.validate(personTo, result); if (result.hasErrors()) { return pageForms.get(currentPage); } else { log.info("Registration finished for person [{}: {}].", personTo.getGender(), personTo.getName()); personTo.setRegistrationComplete(true); return REDIRECT_TO_SUCCESS_PAGE; } } else { int targetPage = WebUtils.getTargetPage(request, "_target", currentPage); if (userClickedPrevious(currentPage, targetPage)) { return pageForms.get(targetPage); } else { switch (currentPage) { case 0: validator.validateName(personTo, result); break; } case 1: validator.validateGender(personTo, result); break; } if (result.hasErrors()) { return pageForms.get(currentPage); } else { return pageForms.get(targetPage); } } } }
<form method="post" modelAttribute="personTo"> <table> <tr> <td>Your name:</td> <td>#springFormInput("personTo.name" "") </td> <td>#springShowErrors("" "") </td> </tr> <tr> <td colspan="3"> <input type="submit" value="Next" name="_target1"> <input type="submit" value="Cancel" name="_cancel"> <input type="hidden" value="0" name="_page"> </td> </tr> </table> </form>And the gender selection page. Note we are using a drop down list here.
<form method="post" modelAttribute="personTo"> <table> <tr> <td>Your gender:</td> <td>#springFormSingleSelect("personTo.gender" $genders "") </td> <td>#springShowErrors("" "") </td> </tr> <tr> <td colspan="3"> <input type="submit" value="Previous" name="_target0"> <input type="submit" value="Finish" name="_finish"> <input type="submit" value="Cancel" name="_cancel"> <input type="hidden" value="1" name="_page"> </td> </tr> </table> </form>
public class GenderEditor extends PropertyEditorSupport { @Override public String getAsText() { if (getValue() == null) { return null; } else { Gender gender = (Gender) getValue(); return gender.toString(); } } @Override public void setAsText(String text) throws IllegalArgumentException { if (StringUtils.isEmpty(text)) { setValue(""); } else if (text.equalsIgnoreCase("m")) { setValue(Gender.MALE); } else if (text.equalsIgnoreCase("f")) { setValue(Gender.FEMALE); } else if (text.equalsIgnoreCase("o")) { setValue(Gender.OTHER); } } }We need the getAsText() method for validation purposes. That makes sure that if an unknown value is passed from the view, the resulting value is null (as opposed to the String "null").
import javax.ejb.Local; import javax.ejb.Singleton; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import me.m1key.audiolicious.domain.entities.Song; import me.m1key.audiolicious.services.SongRepository; @Singleton @Local(SongRepository.class) public class JpaSongRepository implements SongRepository { @PersistenceContext private EntityManager entityManager; @Override public void save(Song song) { entityManager.persist(song); } }As you can see, it does not do a lot - but it is an EJB and it uses @PersistenceContext. I did not expose any way to set the entityManager because I don't like having to change production code just so that tests can run. So, that would be rather hard to mock. But we don't have to mock, we are going to run the test on the server.
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.util.Date; import javax.inject.Inject; // Certain imports omitted for brevity. import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ArchivePaths; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.DependencyResolvers; import org.jboss.shrinkwrap.resolver.api.maven.MavenDependencyResolver; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(Arquillian.class) public class JpaSongRepositoryIT { // Stuff omitted for brevity. private Date albumDateAdded = new Date(); private Date albumDateModified = new Date(); private Date albumDateSkipped = new Date(); @Inject private SongRepository jpaSongRepository; @Inject private RepositoriesTestHelperBean testHelperBean; @Deployment public static WebArchive createTestArchive() throws IllegalArgumentException, IOException { return ShrinkWrap .create(WebArchive.class, JpaSongRepositoryIT.class.getSimpleName() + ".war") .addAsWebInfResource(EmptyAsset.INSTANCE, ArchivePaths.create("beans.xml")) .addAsResource("log4j.xml", "log4j.xml") .addAsResource("META-INF/persistence.xml", "META-INF/persistence.xml") .addClasses(Album.class, Artist.class, JpaSongRepository.class, NullAlbum.class, NullArtist.class, NullEntitiesFactory.class, Rating.class, RatingTo.class, Song.class, SongRepository.class, SongTo.class, RepositoriesTestHelperBean.class, TrackTo.class) .addAsLibraries( DependencyResolvers .use(MavenDependencyResolver.class) .artifacts("org.slf4j:slf4j-api:1.6.1", "org.slf4j:slf4j-log4j12:1.6.1", "commons-lang:commons-lang:2.6") .resolveAsFiles()); } @Test public void shouldCreateAndRetrieveSong() { assertEquals("There should be no songs before any are created.", Long.valueOf(0), testHelperBean.totalSongs()); Artist artist = testHelperBean.createArtist(ARTIST_NAME); Album album = testHelperBean.createAlbum(ALBUM_NAME, artist, new Rating(80)); Song song = new Song(SONG_1_NAME, ARTIST_NAME, album, 1988, "Zakk Wylde/Bob Daisley/Ozzy Osbourne", "Rock", albumDateAdded, albumDateModified, new Rating(80), 9, albumDateSkipped, 0, false, 0, 0, false); jpaSongRepository.save(song); assertNotNull("Saved song should not be null.", testHelperBean.getSongByUuid(song.getUuid())); } // Other tests omitted for brevity. }Let's take a closer look. First, the test is annotated with @RunWith(Arquillian.class). That is because we need Arquillian to orchestrate the entire test. Arquillian will handle our @Deployment. This is where, using ShrinkWrap, we create the WAR file with our test and what we want to test with all its dependencies, also the external ones, from our pom.xml. This WAR file will be deployed to JBoss 7 when you run the test with Maven or from within your IDE. I must admit that getting the dependencies right (i.e. giving it exactly what it needs and not too much) can be a bit tiresome and frustrating.
<dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.jboss.spec</groupId> <artifactId>jboss-javaee-web-6.0</artifactId> <type>pom</type> <scope>provided</scope> </dependency> <dependency> <groupId>org.jboss.as</groupId> <artifactId>jboss-as-arquillian-container-managed</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.jboss.shrinkwrap</groupId> <artifactId>shrinkwrap-api</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.jboss.shrinkwrap.resolver</groupId> <artifactId>shrinkwrap-resolver-impl-maven</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.jboss.arquillian.junit</groupId> <artifactId>arquillian-junit-container</artifactId> <scope>test</scope> </dependency>
<?xml version="1.0" encoding="UTF-8"?> <arquillian xmlns="http://jboss.org/schema/arquillian" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jboss.org/schema/arquillian http://jboss.org/schema/arquillian/arquillian_1_0.xsd"> <!-- Uncomment to have test archives exported to the file system for inspection --> <engine> <property name="deploymentExportPath">target/</property> </engine> <container qualifier="jboss" default="true"> <protocol type="jmx-as7"> <property name="executionType">REMOTE</property> </protocol> </container> </arquillian>When the test is running, it's running on a remote instance of JBoss. That means you have to download JBoss 7 yourself. You can hardcode its location in this file, but it's not a good idea if you're sharing the project with other people. Instead, you can set your JBOSS_HOME system variable to something like e:\Servers\jboss-as-web-7.0.0.Final.
<form method="post" action=""> <table> <tr> <td>Your name:</td> <td>#springFormInput("reservation.userName" "") </td> <td>#springShowErrors("" "") </td> </tr>This will create an input field with an ID userName.
<link type="text/css" href="../css/humanity/jquery-ui-1.8.16.custom.css" rel="stylesheet" /> <link type="text/css" href="../css/basic.css" rel="stylesheet" /> <script type="text/javascript" src="../js/jquery-1.6.2.min.js"></script> <script type="text/javascript" src="../js/jquery-ui-1.8.16.custom.min.js"></script> <script> $(function() { $( "input:submit" ).button(); }); </script> <style> .ui-autocomplete-loading { background: white url('../images/ui-anim_basic_16x16.gif') right center no-repeat; } </style> <script type="text/javascript" src="../js/autocomplete.js"></script>Only the last line is non-standard. That's my custom JS file.
$(function() { $("#userName").autocomplete( { source : function(request, response) { $.ajax({ url : "names", dataType : "json", data : { term : request.term }, success : function(data) { response($.map(data.names, function(item) { return { label : item.label, value : item.label } })); } }); }, minLength : 1 }); });Let's explain it step by step. On windows load, the nameless function will run. Using jQuery selector I'm selecting the HTML element with ID userName. Then I'm calling the autocomplete() function on it that will turn it into an autocomplete input. It accepts many parameters; here I only use source and minLength because they are sufficient.
{"names":[{"label":"Michael","value":"1"},{"label":"Mike","value":"2"},{"label":"Mikey","value":"3"}]}This bit:
$.map(data.names, function(item)… selects the names field from the response. Then, we have to select the label and value. Label is what will be displayed in the suggestion box. Value is what will be ultimately selected. In my case I chose to ignore the returned value (which is a number, as you can see) and just use the label field.
@Controller @RequestMapping("/names") public class NamesController { private static final Logger log = LoggerFactory .getLogger(NamesController.class); @RequestMapping(method = RequestMethod.GET) public String getNames(Model model, @RequestParam(required = false) String term) { log.debug("getNames(\"{}\")", term); model.addAttribute("names", Arrays.asList(names)); return "jsonNames"; } private LabelValueTo[] names = new LabelValueTo[] { new LabelValueTo("Michael", "1"), new LabelValueTo("Mike", "2"), new LabelValueTo("Mikey", "3") }; }I have already written a bit about Spring and JSON so I will not comment that in great detail. Notice that I'm returning a view called jsonNames. What happens with it next?
<bean class="org.springframework.web.servlet.view.XmlViewResolver"> <property name="order" value="0" /> <property name="location" value="/WEB-INF/views.xml" /> </bean> <bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver"> <property name="order" value="1" /> <property name="cache" value="true" /> <property name="prefix" value="/WEB-INF/vm/" /> <property name="suffix" value=".vm" /> <property name="exposeSpringMacroHelpers" value="true" /> </bean>And the referenced view.xml file:
<bean name="jsonNames" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
<h2>Crane fly</h2> <div class="photo"> <div class="title"> <strong>Crane fly</strong> </div> <div class="aroundImage" style="height: 534px;"> <div class="warning"> <a href="javascript:void(0)">Click here to view this image.</a> </div> <img src="images/macro03.jpg" alt="Crane fly - Macro Work" class="hidden" /> </div> <div class="description"> This is a <em>tipula oleracea</em>. Its wingspan can reach 6cm! </div> </div>What that does is it displays a black square where the photo should be, with a warning. It has the height put in explicitly to reflect the size of the picture. If the user clicks anywhere on the black square (not necessarily the warning message), the photo will appear. Now, the interesting bit, the jQuery bit.
$(function() { // This will run on windows onload. $('div.warning a').bind('click', function(event) { var $aroundImage = $(event.target).closest('div.aroundImage').click(); }); $('div.aroundImage').bind('click', function(event) { var $aroundImage = $(event.target); var $hiddenImage = $aroundImage.children('img'); var $warningMessage = $aroundImage.children('div.warning'); $hiddenImage.show(); $warningMessage.hide(); $aroundImage.css('cursor', 'default'); }); });OK, let's describe it step by step. The whole thing is wrapped in this:
$(function() { // This will run on windows onload. // ... });The dollar sign ($) is obviously jQuery. By passing it a function like that we make sure that the function will run when the HTML document is loaded, i.e. when all page elements are available. What is worth mentioning, you can make the call many times and all of the given functions will run when body is loaded in the order they are declared.
$(function() {/* ... */}); $(function() {/* ... */}); $(function() {/* ... */});Let's now take a look at this.
$('div.aroundImage').bind('click', function(event) { var $aroundImage = $(event.target); var $hiddenImage = $aroundImage.children('img'); var $warningMessage = $aroundImage.children('div.warning'); $hiddenImage.show(); $warningMessage.hide(); $aroundImage.css('cursor', 'default'); });Here we use jQuery bind function to bind an event, which is a jQuery preferred way of event handling free from browser inconsistencies. We then obtain the hidden image to show it and the warning message to hide it. We also change the cursor to the default one (from pointer) because there is nothing else to click on. Here we redirect warning message onclick event to the div onclick event to avoid duplicating code.
$('div.warning a').bind('click', function(event) { var $aroundImage = $(event.target).closest('div.aroundImage').click(); });What is good about this jQuery code is that it doesn't care how many hidden images you have on the page. And the images don't need to have unique IDs or anything like that.
the virtualbox kernel modules do not match this version rtr3init failed with rc 1912 rc 1912 ubuntu '/etc/init.d/vboxdrv setup'
sudo apt-get install linux-headers-$(uname -r) sudo /etc/init.d/vboxdrv setupIt helped.
EntityManagerFactory entityManagerFactory = Persistence .createEntityManagerFactory("testPu"); entityManager = entityManagerFactory.createEntityManager();
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"> <property name="persistenceUnitName" value="Dogs" /> </bean> <bean id="dogsDao" class="me.m1key.springtx.dao.DogsDaoImpl" /> <bean id="dogsBean" class="me.m1key.springtx.beans.DogsBean" scope="singleton"> <property name="dogsDao" ref="dogsDao" /> </bean> <tx:annotation-driven transaction-manager="myTransactionManager" /> <tx:jta-transaction-manager /> <bean id="myTransactionManager" class="org.springframework.transaction.jta.JtaTransactionManager" /> <bean class=" org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor " />Look closely, notice the jta-transaction-manager annotation and JtaTransactionManager.
… <persistence-unit name="Dogs" transaction-type="JTA"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <jta-data-source>java:/DogsDS</jta-data-source> <class>me.m1key.springtx.entities.Dog</class> <properties> <property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.JBossTransactionManagerLookup" /> <property name="hibernate.show_sql" value="true" /> <property name="hibernate.format_sql" value="true" /> <property name="hibernate.hbm2ddl.auto" value="create" /> </properties> </persistence-unit> …Notice the transaction-type attribute. It's JTA as opposed to RESOURCE_LOCAL in the case of non-JTA. You must also specify transaction manager lookup class which is server dependent.
@PersistenceContext private EntityManager em; @SuppressWarnings("unchecked") @Transactional(readOnly = true) public List<Dog> retrieveAllDogs() { return em.createQuery("from Dog").getResultList(); }
<dependencies> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>3.6.0.Final</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-commons-annotations</artifactId> <version>3.2.0.Final</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.0-api</artifactId> <version>1.0.0.Final</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>3.6.0.Final</version> <type>jar</type> <scope>provided</scope> </dependency> <dependency> <groupId>hsqldb</groupId> <artifactId>hsqldb</artifactId> <version>1.8.0.7</version> <type>jar</type> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>3.0.3.RELEASE</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>3.0.3.RELEASE</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>3.0.3.RELEASE</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.5.8</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.5.8</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.1</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>3.0.3.RELEASE</version> <type>jar</type> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.1</version> <type>jar</type> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.0.3.RELEASE</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>3.0.3.RELEASE</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.jboss.spec.javax.servlet</groupId> <artifactId>jboss-servlet-api_3.0_spec</artifactId> <version>1.0.0.Final</version> <scope>provided</scope> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2</version> </dependency> </dependencies> <repositories> <repository> <id>r.j.o-groups-public</id> <url>https://repository.jboss.org/nexus/content/groups/public/</url> </repository> </repositories>
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"> <property name="persistenceUnitName" value="Dogs" /> </bean> <bean id="dogsDao" class="me.m1key.springtx.dao.DogsDaoImpl" /> <bean id="dogsBean" class="me.m1key.springtx.beans.DogsBean" scope="singleton"> <property name="dogsDao" ref="dogsDao" /> </bean> <tx:annotation-driven transaction-manager="myTransactionManager" /> <bean id="myTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /> </beans>What's worth noting is the transaction manager. Because we are not using JTA, we must explicitly provide the transaction manager for the application to use.
… <persistence-unit name="Dogs" transaction-type="RESOURCE_LOCAL"> <non-jta-data-source>java:/DogsDS</non-jta-data-source> <class>me.m1key.springtx.entities.Dog</class> <properties> <property name="hibernate.show_sql" value="true" /> <property name="hibernate.format_sql" value="true" /> <property name="hibernate.hbm2ddl.auto" value="create" /> </properties> </persistence-unit> ...What we have here is a persistence unit called Dogs. The transaction type is RESOURCE_LOCAL - that tells the container not to use JTA. Below we specify JNDI data source name, entity classes and some properties. Note I don't have to specify typical data source properties (user name, password, url) - that's because they don't belong here. We define data source properties in JBoss.
<?xml version="1.0" encoding="UTF-8"?> <datasources> <local-tx-datasource> <jndi-name>DogsDS</jndi-name> <connection-url>jdbc:hsqldb:hsql://localhost/dogsdb</connection-url> <driver-class>org.hsqldb.jdbcDriver</driver-class> <user-name>sa</user-name> <password></password> <min-pool-size>5</min-pool-size> <max-pool-size>20</max-pool-size> <idle-timeout-minutes>0</idle-timeout-minutes> <track-statements /> <prepared-statement-cache-size>32</prepared-statement-cache-size> <metadata> <type-mapping>Hypersonic SQL</type-mapping> </metadata> </local-tx-datasource> </datasources>Nice and simple.
@PersistenceContext private EntityManager em; @SuppressWarnings("unchecked") @Transactional(readOnly = true) public List<Dog> retrieveAllDogs() { return em.createQuery("from Dog").getResultList(); }
git diff master..branch
git diff --name-status master..branch
git diff --color master..my251
git diff branch..master
WARN [com.mchange.v2.async.ThreadPoolAsynchronousRunner] (Timer-1) com.mchange.v2.async.ThreadPoolAsynchronousRunner $DeadlockDetector@26d6221b -- APPARENT DEADLOCK!!!(line breaks added for readability)
<property name="hibernate.c3p0.max_size" value="100" /> ...
git format-patch commit_id^..commit_id
@Log private static Logger log;
package me.m1key.test; import java.lang.reflect.Field; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public aspect LogInjectAspect { pointcut loggerAccessed(Object a): get(@Log Logger me.m1key.test.*.*) && this(a); before(Object objectWithLog): loggerAccessed(objectWithLog) { for (Field field : objectWithLog.getClass().getDeclaredFields()) { field.setAccessible(true); if (field.getName().equals(thisJoinPoint.getSignature().getName())) { try { if (field.get(null) == null) { System.out.println("OMG I'm setting the value."); field.set(objectWithLog, LoggerFactory.getLogger(objectWithLog.getClass())); } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } } } } }
duplicate key: interface javax.validation.constraints.Size
<rich:accordion switchType="client"> <rich:accordionItem header="#{msg['index.accordion.tab1.heading']}"> <h:outputText value="#{msg['index.accordion.tab1.text']}" /> </rich:accordionItem> <rich:accordionItem header="#{msg['index.accordion.tab2.heading']}"> <h:outputText value="#{msg['index.accordion.tab2.text']}" /> </rich:accordionItem> </rich:accordion>
<rich:popupPanel id="popup" modal="true" resizeable="false" onmaskclick="#{rich:component('popup')}.hide()"> <f:facet name="header"> <h:outputText value="#{msg['index.info.header']}" /> </f:facet> <f:facet name="controls"> <h:outputLink value="#" onclick="#{rich:component('popup')}.hide(); return false;"> X </h:outputLink> </f:facet> <p> <h:outputText value="#{msg['index.info.text']}" /> </p> <p> <h:outputLink value="#" onclick="#{rich:component('popup')}.hide(); return false;"> <h:outputText value="#{msg['index.info.close']}" /> </h:outputLink> </p> </rich:popupPanel>
<h:form id="dogForm"> <rich:messages /> <rich:dataTable value="#{dogsBean.allDogs}" var="dog" id="table" rows="30"> <f:facet name="noData"> <h:outputText value="#{msg['index.table.noData']}" /> </f:facet> <rich:column filterValue="#{dogsFilteringBean.nameFilter}" filterExpression="#{fn:containsIgnoreCase(dog.name,dogsFilteringBean.nameFilter)}"> <f:facet name="header"> <h:panelGroup> <h:outputText value="#{msg['index.table.column.name']}" /> <h:inputText value="#{dogsFilteringBean.nameFilter}" onkeypress="if (event.keyCode == 13) {return false;} else {return true;}"> <a4j:ajax event="blur" render="table" execute="@this" /> </h:inputText> </h:panelGroup> </f:facet> <h:outputText value="#{dog.name}" /> </rich:column> </rich:dataTable> </h:form>
<?xml version="1.0" encoding="UTF-8"?> <faces-config xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd" version="2.0"> <application> <locale-config> <default-locale>en</default-locale> </locale-config> <resource-bundle> <base-name>messages.messages</base-name> <var>msg</var> </resource-bundle> </application> </faces-config>
registration.title = Register registration.h1 = Register registration.email = Email: registration.name = Name: ...
<h:outputText value="#{msg['registration.h1']}" />
<h:form rendered="#{!sessionTracker.loggedIn}"> <rich:panel> <h:panelGrid columns="3"> <h:outputText value="#{msg['registration.email']}" /> <h:inputText id="email" value="#{registrationBean.email}"> <rich:validator /> </h:inputText> <rich:message for="email" /> <h:outputText value="#{msg['registration.name']}" /> <h:inputText id="name" value="#{registrationBean.name}" status="nameStatus"> <rich:validator status="nameStatus" /> </h:inputText> <h:panelGroup> <a4j:status name="nameStatus" startText="#{msg['registration.checkingName']}" startStyle="background-color: FFA500" /> <rich:message for="name" /> </h:panelGroup> <h:commandButton value="#{msg['registration.register']}" action="#{registrationBean.register}" /> </h:panelGrid> </rich:panel> </h:form>
@NotNull(message = "{rf.name.notNull}") @Size(min = 2, message = "{rf.name.size}") @ValidUserName public String getName() { return name; }
import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ValidUserNameValidator implements ConstraintValidator<ValidUserName, String> { private Logger log = LoggerFactory.getLogger(ValidUserNameValidator.class); private String[] forbiddenNames = { "Michal", "Mikey", "Mickey", "M1key", "M1ckey" }; @Override public void initialize(ValidUserName firstUpper) { // See JSR 303 Section 2.4.1 for sample implementation. } @Override public boolean isValid(String value, ConstraintValidatorContext context) { log.debug("Validating."); if (value == null || value.length() == 0) { return true; } // Let's simulate a costly operation. try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return isNotForbidden(value); }
<h:form> <rich:panel> <h:panelGrid columns="3"> <h:outputText value="Email:" /> <h:inputText id="email" value="#{registration.email}"> <rich:validator /> </h:inputText> <rich:message for="email" /> <h:outputText value="Name:" /> <h:inputText id="name" value="#{registration.name}"> <rich:validator /> </h:inputText> <rich:message for="name" /> <a4j:commandButton value="Register" action="#{registration.register}" render="length" /> </h:panelGrid> </rich:panel> </h:form>
package me.m1key.rf; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.inject.Inject; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; @ManagedBean @RequestScoped public class Registration { @Inject private SessionTracker sessionTracker; private String email; private String name; @NotNull(message = "{rf.email.notNull}") @Pattern(message = "{rf.email.pattern}", regexp = "...") public String getEmail() { return email; } @NotNull(message = "{rf.name.notNull}") @Size(min = 2, message = "{rf.name.size}") public String getName() { return name; }I spared you the regular expression for email validation. What’s cool about it? This gives you both automatic client-side and server side (in case someone turned off their JavaScript, for instance) validation.
@ValidUserName public String getName() { return name; }
@Documented @Constraint(validatedBy = ValidUserNameValidator.class) @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER }) @Retention(RetentionPolicy.RUNTIME) public @interface ValidUserName { String message() default "{rf.validUserName}"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
public class ValidUserNameValidator implements ConstraintValidator<ValidUserName, String> { private Logger log = LoggerFactory.getLogger(ValidUserNameValidator.class); private String[] forbiddenNames = { "Michal", "Mikey", "Mickey", "M1key", "M1ckey" }; @Override public void initialize(ValidUserName firstUpper) { // See JSR 303 Section 2.4.1 for sample implementation. } @Override public boolean isValid(String value, ConstraintValidatorContext context) { log.info("Validating"); if (value == null || value.length() == 0) { return true; } return isNotForbidden(value); } private boolean isNotForbidden(String name) { return !isForbidden(name); } private boolean isForbidden(String name) { for (String forbiddenName : forbiddenNames) { if (name.equals(forbiddenName)) { return true; } } return false; } }