- File -> Import -> Git -> Projects From Git > URI
- Enter the github repository URL.
You can get https URL from github repository page -> sidebar
- Select the branch you want to clone
- Select the local storage location for your new project
- Create a new groovy project. It will prompt you if you want to convert to grails project. Select yes.The location should be $ProjectRoot/src, the directroy that is the parent directory of grails-app!
Monday, November 25, 2013
Import Grails project from GitHub into Eclipse
Tuesday, May 28, 2013
How to change Eclipse to use spaces instead of tabs
For the default text editor:
- General > Editors > Text Editors > Insert spaces for tabs (check it)
For PHP:
- PHP > Code Style > Formatter > Tab policy (choose "spaces")
- PHP > Code Style > Formatter > Indentation size (set to 4)
For CSS:
- Web > CSS > Editor > Indent using spaces (select it)
- Web > CSS > Editor > Indentation size (set to 4)
For HTML:
- Web > HTML > Editor > Indent using spaces (select it)
- Web > HTML > Editor > Indentation size (set to 4)
For XML:
- XML > XML Files > Editor > Indent using spaces (select it)
- XML > XML Files > Editor > Indentation size (set to 4)
For Javascript:
- Javascript > Preferences > Code Style > Formatter > Edit > Indentation (choose "spaces only")
- Rename the formatter settings profile to save it
For Java:
- Java > Preferences > Code Style > Formatter > Edit > Indentation (choose "spaces only")
- Rename the formatter settings profile to save it
To search for all the tabs in eclipse.
Search > File > search for containing text "\t" and select Regular expression > Search
To replace tab with spaces
Search > File > search for containing text "\t" and select Regular expression > Replace > Enter 4 spaces.
Thursday, May 2, 2013
Wednesday, May 1, 2013
Regular Expression
Lookahead
- q(?=u) : quit
- q(?!u) : qtip not quit
LookBehind
- (?<=a)b : abc
- (?<!a)b : xbc not ab
- ^ matches at the start of the string
- $ matches at the end of the string
- \d matches a single character that is a digit
- \w matches a "word character" (alphanumeric characters plus underscore)
- \s matches a whitespace character
- The dot matches a single character, except line break characters. It is short for [^\n] (UNIX regex flavors) or[^\r\n] (Windows regex flavors).gr.y matches gray, grey, gr%y, etc.
Thursday, January 24, 2013
Spring 3.1 registering and using properties
Registering properties in Spring
Starting with Spring 3.1, the new Environment and PropertySource abstractions simplify working with properties. The default Spring Environment now contains two property sources: the System properties and the JVM properties, with the System properties having precedence.(1) Registering Properties via the XML namespace:
<context:property-placeholder location="classpath:config/${env:local}/**/*.properties" ignore-unresolvable="true"/>
(2) Registering Properties via Java Annotation:(2)
@PropertySource("classpath:config/${env:local}/environment.properties")
Spring 3.1 introduces the new @PropertySource annotation, as a convenient mechanism of adding property sources to the environment. But as opposed to using XML namespace element, the Java @PropertySource annotation does not automatically register a PropertySourcesPlaceholderConfigurer with Spring.
Instead, the bean must be explicitly defined in the configuration to get the property resolution mechanism working.
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
Note: Resource location wildcards (e.g. **/*.properties) are not permitted; each location must evaluate to exactly one
.properties
resource. So if you want to use wildcards in your propertySource, don't use Method 2).(3) Registering Properties via Java configuration:
static @Bean public PropertySourcesPlaceholderConfigurer myPropertySourcesPlaceholderConfigurer() throws IOException {
String envVar = System.getenv("env");
if (envVar == null)
envVar = "local";
PropertySourcesPlaceholderConfigurer p = new PropertySourcesPlaceholderConfigurer();
p.setLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath*:config/"+envVar+"/*.properties"));
p.setIgnoreUnresolvablePlaceholders(true);
return p;
}
Using properties in Spring
Both the older PropertyPlaceholderConfigurer and the new PropertySourcesPlaceholderConfigurer added in Spring 3.1 resolve ${…} placeholders within bean definition property values and @Value annotations.For example, to inject a property using the @Value annotation:
@Value( "${jdbc.url}" )
private String jdbcUrl;
Using properties in Spring XML configuration:
<bean id="dataSource">
<property name="url" value="${jdbc.url}" />
</bean>
And lastly, obtaining properties via the new Environment APIs:
@Autowired
private Environment env;
...
dataSource.setUrl(env.getProperty("jdbc.url"));
Friday, January 18, 2013
MongoDB
Default
<mongo:mongo write-concern="SAFE" />
<mongo:db-factory id="mongoDbFactory"
host="localhost"
port="27017"
dbname="database"
username="joe"
password="secret"/>
<bean id="mongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
</bean>
mongo = new Mongo();
mongoDbFactory = new SimpleMongoDbFactory(mongo, "dbname");
mongoTemplate = new MongoTemplate(mongoDbFactory());
Spring 3.2 Java Configuration For SpringMvc
@Configuration
@EnableWebMvc
@Import({DbConfig.class, LoggingConfig.class})
@ComponentScan(basePackages = {"org....", "org...."})
public class WebConfig extends WebMvcConfigurerAdapter {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}
The new @EnableWebMvc : The functionality of the annotation is equivalent to the XML version:
<mvc:annotation-driven />
<mvc:annotation-driven />
@RunWith(SpringJUnit4ClassRunner.class)
//defaults to "file:src/main/webapp"
@WebAppConfiguration
//detects "${classname}-context.xml" in same package or static nested @Configuration
//The default loader is AnnotationConfigWebContextLoader.class
@Configuration class
@ContextConfiguration(classes=WebConfig.class)
@Category(IntegrationTest.class)
public class WebIntegrationTest {
@Autowired
protected WebApplicationContext webApplicationContext;
protected MockMvc mockMvc;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public final void whenSpringContextIsInstantiated_thenNoExceptions(){
}
}
Friday, January 11, 2013
More Maven
Phases
Shortened plugin prefix is done automatically if the artifactId follows the convention of using ${prefix}-maven-plugin (or maven-${prefix}-plugin if the plugin is part of the Apache Maven project). For example maven-surefire-plugin, you can refer to it as mvn surefire:${goal}
To activate this, you would type this in command line
Goals
Goal are defined in each plugin.- From the packaging selected, goals are bind to phases by default.
- By Configure plugins in your project, you can bind goals to phases. These goals will be added to the goals already bound to the phases from the packaging selected.
Shortened plugin prefix is done automatically if the artifactId follows the convention of using ${prefix}-maven-plugin (or maven-${prefix}-plugin if the plugin is part of the Apache Maven project). For example maven-surefire-plugin, you can refer to it as mvn surefire:${goal}
Profiles
A profile can be triggered/activated in several ways:
- Explicitly
- Through Maven settings
- Based on environment variables
- OS settings
- Present or missing files
- To activate a profile based on environment variables
<profiles>
<profile>
<activation>
<property>
<name>environment</name>
<value>test</value>
</property>
</activation>
...
</profile>
</profiles>
To activate this, you would type this in command line
mvn groupId:artifactId:goal -Denvironment=test
- Profiles can be explicitly specified using the -P CLI option.
mvn groupId:artifactId:goal -P profile1
Thursday, January 10, 2013
Groovy Project - how to create project from existing source
- Install Eclipse Groovy Plugin. Follow how to install in this instruction http://groovy.codehaus.org/Eclipse+Plugin
- Create new Groovy project, unselect default location, point to existing project location. Click next. The wizard will not allow you to select project layout, It will automatically configure the JRE and the project layout based on the existing source. You can change it in next step.
- On second screen (Build Settings)
- Click add project .. to build path if you have source under project root.
- Change Default output folder from bin to target to in line with maven build so target folder can be ignored for checkin.
- For groovy script, right mouse click and select Run As-> Groovy Script.
Wednesday, January 9, 2013
More Git
FETCH_HEAD
is a short-lived ref, to keep track of what has just been
fetched from the remote repository.
FETCH_HEAD is a reference to the tip of the last
fetch, whether that fetch was initiated directly using the fetch command or as
part of a pull.
HEAD is the tip of current branch
git branch –a: shows all the branches git knows about
*master
remotes/origin/master
master is the branch in the local repository
remotes/origin/master is the a branch named master on the remote named origin. remotes/origin/master = origin/master
remotes/origin/master is the a branch named master on the remote named origin. remotes/origin/master = origin/master
Tuesday, January 8, 2013
Spring 3.0 MVC Validation and Exception Handling
Domain Class:
Define contraints in domain class. You can define your own constraints.
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Response {
private BigInteger id;
@NotNull
private BigInteger itemId;
@Size(min = 1, max = 14)
private String response;
}
Controller Class:
@Valid annotiation on incoming parameter to trigger validation.
@ExceptionHandler to handle different type of exceptions.
@Controller public class ResponseController { public @ResponseBody Response postResponse(
@Valid
@RequestBody ItemResponse itemResponse){ } @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(value = HttpStatus.BAD_REQUEST) @ResponseBody public String handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) { BindingResult bindingResult = ex.getBindingResult(); List
errors = bindingResult.getFieldErrors(); StringBuffer customMessage = new StringBuffer(); for (FieldError error : errors ) { customMessage.append(error.getObjectName() +"." + error.getField() +" "+ error.getDefaultMessage()+"\n"); } return customMessage.toString(); } @ExceptionHandler(IOException.class) @ResponseStatus(value = HttpStatus.BAD_REQUEST) public ModelAndView handleIOException(MethodArgumentNotValidException ex) { …. } }
Spring Configuration:
Following are example configuration for different types of Exception Handler.
<!-- Annotation Based ExceptionHandler -->
<beans:bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver">
<beans:property name="order" value="1" />
</beans:bean>
<!-- SimpleMapping ExceptionHandler -->
<beans:bean
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<beans:property name="exceptionMappings">
<beans:props>
<beans:prop
key="org.springframework.web.bind.MethodArgumentNotValidException">validationError</beans:prop>
<beans:prop key="java.lang.IOException">ioerror</beans:prop>
</beans:props>
</beans:property>
<beans:property name="statusCodes">
<beans:props>
<beans:prop key="ioerror">403</beans:prop>
<beans:prop key="validationError">406</beans:prop>
</beans:props>
</beans:property>
<beans:property name="defaultErrorView" value="error" />
<beans:property name="order" value="2" />
</beans:bean>
<!-- Default ExceptionHandler -->
<beans:bean
class="org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver">
<beans:property name="order" value="3" />
</beans:bean>
Subscribe to:
Posts (Atom)