working on it ...

Filters

Explore Public Snippets

Sort by

Found 4,525 snippets matching: spring

    public by lauhin  5381  3  7  1

    Count chars in a String in Java

    Count chars in Strings or letters in words in Java using the Spring framework
    import org.springframework.util.StringUtils;
    
    int occurance = StringUtils.countOccurrencesOf("012405802569015014", "0"); //returns 5
    int occurance = StringUtils.countOccurrencesOf("hello world", "l"); //returns 3

    public by lbottaro  3326  1  5  0

    How to create a Grid view in java spring

    Aligns the first rows * cols components of parent in a grid. Each component is as big as the maximum preferred width and height of the components. The parent is made just big enough to fit them all. @param rows number of rows @param cols number of columns @param initialX x location to start the grid at @param initialY y location to start t
    public static void makeGrid(Container parent,
                                int rows, int cols,
                                int initialX, int initialY,
                                int xPad, int yPad) {
        SpringLayout layout;
        try {
            layout = (SpringLayout)parent.getLayout();
        } catch (ClassCastException exc) {
            System.err.println("The first argument to makeGrid must use SpringLayout.");
            return;
        }
    
        Spring xPadSpring = Spring.constant(xPad);
        Spring yPadSpring = Spring.constant(yPad);
        Spring initialXSpring = Spring.constant(initialX);
        Spring initialYSpring = Spring.constant(initialY);
        int max = rows * cols;
    
        //Calculate Springs that are the max of the width/height so that all
        //cells have the same size.
        Spring maxWidthSpring = layout.getConstraints(parent.getComponent(0)).
                                    getWidth();
        Spring maxHeightSpring = layout.getConstraints(parent.getComponent(0)).
                                    getWidth();
        for (int i = 1; i < max; i++) {
            SpringLayout.Constraints cons = layout.getConstraints(
                                            parent.getComponent(i));
    
            maxWidthSpring = Spring.max(maxWidthSpring, cons.getWidth());
            maxHeightSpring = Spring.max(maxHeightSpring, cons.getHeight());
        }
    
        //Apply the new width/height Spring. This forces all the
        //components to have the same size.
        for (int i = 0; i < max; i++) {
            SpringLayout.Constraints cons = layout.getConstraints(
                                            parent.getComponent(i));
    
            cons.setWidth(maxWidthSpring);
            cons.setHeight(maxHeightSpring);
        }
    
        //Then adjust the x/y constraints of all the cells so that they
        //are aligned in a grid.
        SpringLayout.Constraints lastCons = null;
        SpringLayout.Constraints lastRowCons = null;
        for (int i = 0; i < max; i++) {
            SpringLayout.Constraints cons = layout.getConstraints(
                                                 parent.getComponent(i));
            if (i % cols == 0) { //start of new row
                lastRowCons = lastCons;
                cons.setX(initialXSpring);
            } else { //x position depends on previous component
                cons.setX(Spring.sum(lastCons.getConstraint(SpringLayout.EAST),
                                     xPadSpring));
            }
    
            if (i / cols == 0) { //first row
                cons.setY(initialYSpring);
            } else { //y position depends on previous row
                cons.setY(Spring.sum(lastRowCons.getConstraint(SpringLayout.SOUTH),
                                     yPadSpring));
            }
            lastCons = cons;
        }
    
        //Set the parent's size.
        SpringLayout.Constraints pCons = layout.getConstraints(parent);
        pCons.setConstraint(SpringLayout.SOUTH,
                            Spring.sum(
                                Spring.constant(yPad),
                                lastCons.getConstraint(SpringLayout.SOUTH)));
        pCons.setConstraint(SpringLayout.EAST,
                            Spring.sum(
                                Spring.constant(xPad),
                                lastCons.getConstraint(SpringLayout.EAST)));
    }
    

    public by xiongtec  3186  1  6  0

    @transactional rollback

    You shouldn't call Rollback programmatically. The best way, as recommended by the docs, is to use declarative approach. To do so, you need to annotate which exceptions will trigger a Rollback.
    
    In your case, something like this
    
    @Transactional(rollbackFor={MyException.class, AnotherException.class})
    public SomeResult doSomething(){
       ...
    }
    Take a look at the @Transaction API and the docs about rolling back a transaction.
    
    If, despite the docs recommendation, you want to make a programmatic rollback, then you need to call it from TransactionAspectSupport as already suggested. This is from the docs:
    
    public void resolvePosition() {
      try {
        // some business logic...
      } catch (NoProductInStockException ex) {
        // trigger rollback programmatically
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      }
    }
    There may be a architecture mistake though. If your method fails and you need to throw an exception, you shouldn't expect it to return anything. Maybe you're giving too much responsibilities to this method and should create a separated one that only model data, and throws an exception if something goes wrong, rolling back the transaction. Anyway, read the docs.

    public by AnghelLeonard  1608  0  5  0

    SpringBoot H2 in file

    SpringBoot H2 in file
    spring.datasource.url = jdbc:h2:~/foo;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
    spring.datasource.username = sa
    spring.datasource.password =

    external by jonikarppinen  5864914  623  5  0

    Example of replacing Spring Boot "whitelabel" error page with custom error responses

    Example of replacing Spring Boot "whitelabel" error page with custom error responses: CustomErrorController.java
    package com.company.project.controllers;
    
    import com.company.project.model.api.Error;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.autoconfigure.web.ErrorAttributes;
    import org.springframework.boot.autoconfigure.web.ErrorController;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.context.request.RequestAttributes;
    import org.springframework.web.context.request.ServletRequestAttributes;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.util.Map;
    
    /**
     * Based on the helpful answer at http://stackoverflow.com/q/25356781/56285,
     * with error details in response body added.
     * 
     * @author Joni Karppinen
     * @since 20.2.2015
     */
    @RestController
    public class CustomErrorController implements ErrorController {
    
        private static final String PATH = "/error";
    
        @Value("${debug}")
        private boolean debug;
    
        @Autowired
        private ErrorAttributes errorAttributes;
    
        @RequestMapping(value = PATH)
        Error error(HttpServletRequest request, HttpServletResponse response) {
            // Appropriate HTTP response code (e.g. 404 or 500) is automatically set by Spring. 
            // Here we just define response body.
            return new Error(response.getStatus(), getErrorAttributes(request, debug));
        }
    
        @Override
        public String getErrorPath() {
            return PATH;
        }
    
        private Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) {
            RequestAttributes requestAttributes = new ServletRequestAttributes(request);
            return errorAttributes.getErrorAttributes(requestAttributes, includeStackTrace);
        }
    
    }
    
    
    

    external by mismatch  1148581  58  5  0

    Spring Boot. Multiple datasources configuration example

    Spring Boot. Multiple datasources configuration example: DatabasesConfig.java
    import javax.sql.DataSource;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    @EnableConfigurationProperties({
    	DatabasesConfig.DataSourceOneProperties.class,
    	DatabasesConfig.DataSourceTwoProperties.class})
    public class DatabasesConfig {
    	@Autowired
    	DataSourceOneProperties dsOneProperties;
    	@Autowired
    	DataSourceTwoProperties dsTwoProperties;
    	
    	@Bean @Qualifier("ds_one")
    	public DataSource dataSourceOne() {
    		return createDataSource(dsOneProperties);
    	}
    	
    	@Bean @Qualifier("ds_two")
    	public DataSource dataSourceTwo() {
    		return createDataSource(dsTwoProperties);
    	}
    
    	private DataSource createDataSource(BaseDataSourceProperties properties) {
    		DataSourceBuilder factory = DataSourceBuilder
    				.create(properties.getClassLoader())
    				.driverClassName(properties.getDriverClassName())
    				.url(properties.getUrl())
    				.username(properties.getUsername())
    				.password(properties.getPassword());
    		return factory.build();
    	}
    	
    	@ConfigurationProperties(prefix = "appName.dbOne.datasource")
    	static class DataSourceOneProperties extends BaseDataSourceProperties {}
    	
    	@ConfigurationProperties(prefix = "appName.dbTwo.datasource")
    	static class DataSourceTwoProperties extends BaseDataSourceProperties {}
    	
    }
    
    

    external by fernandomantoan  294723  112  4  0

    Schema for PostgreSQL to use with JdbcTokenStore (Spring Security OAuth2)

    Schema for PostgreSQL to use with JdbcTokenStore (Spring Security OAuth2): schema.sql
    SQL
    create table oauth_client_details (
      client_id VARCHAR(256) PRIMARY KEY,
      resource_ids VARCHAR(256),
      client_secret VARCHAR(256),
      scope VARCHAR(256),
      authorized_grant_types VARCHAR(256),
      web_server_redirect_uri VARCHAR(256),
      authorities VARCHAR(256),
      access_token_validity INTEGER,
      refresh_token_validity INTEGER,
      additional_information VARCHAR(4096),
      autoapprove VARCHAR(256)
    );
    
    create table oauth_client_token (
      token_id VARCHAR(256),
      token bytea,
      authentication_id VARCHAR(256),
      user_name VARCHAR(256),
      client_id VARCHAR(256)
    );
    
    create table oauth_access_token (
      token_id VARCHAR(256),
      token bytea,
      authentication_id VARCHAR(256),
      user_name VARCHAR(256),
      client_id VARCHAR(256),
      authentication bytea,
      refresh_token VARCHAR(256)
    );
    
    create table oauth_refresh_token (
      token_id VARCHAR(256),
      token bytea,
      authentication bytea
    );
    
    create table oauth_code (
      code VARCHAR(256), authentication bytea
    );
    
    create table oauth_approvals (
      userId VARCHAR(256),
      clientId VARCHAR(256),
      scope VARCHAR(256),
      status VARCHAR(10),
      expiresAt TIMESTAMP,
      lastModifiedAt TIMESTAMP
    );
    
    

    external by Carsten  117429  2  4  0

    Embedded Apache DS LDAP and Spring Security

    Embedded Apache DS LDAP and Spring Security: apache-ds-tutorial.ldif LdapRouteTest-context.xml LdapRouteTest.java pom.xml
    # Sample LDIF data for the ApacheDS v1.0 Basic User's Guide
    #
    # Some sailors and their ships
    # userpassword for all persons is "pass"
    #
    version: 1
    
    dn: ou=people,o=sevenSeas
    objectclass: organizationalUnit
    objectclass: top
    description: Contains entries which describe persons (seamen)
    ou: people
    
    #dn: ou=groups,o=sevenSeas
    #objectclass: organizationalUnit
    #objectclass: top
    #description: Contains entries which describe groups (crews, for instance)
    #ou: groups
    #
    #dn: ou=crews,ou=groups,o=sevenSeas
    #objectclass: organizationalUnit
    #objectclass: top
    #description: Contains entries which describe ship crews
    #ou: crews
    #
    #dn: ou=ranks,ou=groups,o=sevenSeas
    #objectclass: organizationalUnit
    #objectclass: top
    #description: Contains entries which describe naval ranks (e.g. captain)
    #ou: ranks
    
    # HMS Lydia Crew
    # --------------
    
    dn: cn=Horatio Hornblower,ou=people,o=sevenSeas
    objectclass: person
    objectclass: organizationalPerson
    objectclass: inetOrgPerson
    objectclass: top
    cn: Horatio Hornblower
    description: Capt. Horatio Hornblower, R.N
    givenname: Horatio
    sn: Hornblower
    uid: hhornblo
    mail: hhornblo@royalnavy.mod.uk
    userpassword: {SHA}nU4eI71bcnBGqeO0t9tXvY1u5oQ=
    
    dn: cn=William Bush,ou=people,o=sevenSeas
    objectclass: person
    objectclass: organizationalPerson
    objectclass: inetOrgPerson
    objectclass: top
    cn: William Bush
    description: Lt. William Bush
    givenname: William
    manager: cn=Horatio Hornblower,ou=people,o=sevenSeas
    sn: Bush
    uid: wbush
    mail: wbush@royalnavy.mod.uk
    userpassword: {SHA}nU4eI71bcnBGqeO0t9tXvY1u5oQ=
    
    dn: cn=Thomas Quist,ou=people,o=sevenSeas
    objectclass: person
    objectclass: organizationalPerson
    objectclass: inetOrgPerson
    objectclass: top
    cn: Thomas Quist
    description: Seaman Quist
    givenname: Thomas
    manager: cn=Horatio Hornblower,ou=people,o=sevenSeas
    sn: Quist
    uid: tquist
    mail: tquist@royalnavy.mod.uk
    userpassword: {SHA}nU4eI71bcnBGqeO0t9tXvY1u5oQ=
    
    dn: cn=Moultrie Crystal,ou=people,o=sevenSeas
    objectclass: person
    objectclass: organizationalPerson
    objectclass: inetOrgPerson
    objectclass: top
    cn: Moultrie Crystal
    description: Lt. Crystal
    givenname: Moultrie
    manager: cn=Horatio Hornblower,ou=people,o=sevenSeas
    sn: Crystal
    uid: mchrysta
    mail: mchrysta@royalnavy.mod.uk
    userpassword: {SHA}nU4eI71bcnBGqeO0t9tXvY1u5oQ=
    
    #dn: cn=HMS Lydia,ou=crews,ou=groups,o=sevenSeas
    #objectclass: groupOfUniqueNames
    #objectclass: top
    #cn: HMS Lydia
    #uniquemember: cn=Horatio Hornblower,ou=people,o=sevenSeas
    #uniquemember: cn=William Bush,ou=people,o=sevenSeas
    #uniquemember: cn=Thomas Quist,ou=people,o=sevenSeas
    #uniquemember: cn=Moultrie Crystal,ou=people,o=sevenSeas
    
    
    <?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:camel="http://camel.apache.org/schema/spring"
    	xmlns:cxf="http://camel.apache.org/schema/cxf" xmlns:jaxws="http://cxf.apache.org/jaxws"
    	xmlns:security="http://www.springframework.org/schema/security"
    	xmlns:context="http://www.springframework.org/schema/context"
    	xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd
           http://camel.apache.org/schema/spring
           http://camel.apache.org/schema/spring/camel-spring.xsd
           http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security.xsd
           http://camel.apache.org/schema/cxf
           http://camel.apache.org/schema/cxf/camel-cxf.xsd">
    
    	<!-- ldap settings -->
    	<security:ldap-server root="ou=people,o=sevenseas" ldif="classpath:apache-ds-tutorial.ldif" />
    	<bean id="ldapserver" class="javax.naming.directory.InitialDirContext"
    		scope="prototype">
    		<constructor-arg>
    			<props>
    				<prop key="java.naming.factory.initial">com.sun.jndi.ldap.LdapCtxFactory</prop>
    				<prop key="java.naming.provider.url">ldap://127.0.0.1:33389</prop>
    				<prop key="java.naming.security.authentication">none</prop>
    			</props>
    		</constructor-arg>
    	</bean>
    
    	<camelContext xmlns="http://camel.apache.org/schema/spring">
    		<route>
    			<from uri="direct:start" />
    			<to uri="ldap:ldapserver?base=ou=people,o=sevenseas" />
    			<to uri="mock:result" />
    		</route>
    	</camelContext>
    </beans>
    
    
    import java.util.List;
    
    import org.apache.camel.CamelContext;
    import org.apache.camel.EndpointInject;
    import org.apache.camel.Exchange;
    import org.apache.camel.Produce;
    import org.apache.camel.ProducerTemplate;
    import org.apache.camel.component.mock.MockEndpoint;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration
    public class LdapRouteTest {
    	@Autowired
    	protected CamelContext camelContext;
    
    	@Produce(uri = "direct:start")
    	protected ProducerTemplate template;
    
    	@EndpointInject(uri = "mock:result")
    	protected MockEndpoint resultEndpoint;
    
    	@Test
    	public void testGetUserFromLdap() throws Exception {
    		// TODO what to expect
    		resultEndpoint.expectedBodiesReceived("(uid=admin,ou=system)");
    
    		template.sendBody("(&(objectClass=*)(uid=hhornblo))");
    
    		List<Exchange> exchanges = resultEndpoint.getExchanges();
    		for (Exchange msg : exchanges) {
    			System.out.println(">>> " + msg.getOut());
    		}
    
    		resultEndpoint.assertIsSatisfied();
    	}
    }
    
    
    ...
    
      <properties>
    		<cxf-version>2.7.4</cxf-version>
    		<camel-version>2.11.0</camel-version>
    		<junit-version>4.11</junit-version>
    		<log4j-version>1.2.17</log4j-version>
    		<slf4j-version>1.7.5</slf4j-version>
    		<spring-version>3.1.4.RELEASE</spring-version>
    		<apacheds-version>1.5.5</apacheds-version>
    		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    		<checkstyle.suppressions>/suppression.xml</checkstyle.suppressions>
    		<checkstyle.ruleset>/checkstyle.xml</checkstyle.ruleset>
    	</properties>
    
      <dependencies>
    
      	<dependency>
    			<groupId>org.apache.camel</groupId>
    			<artifactId>camel-core</artifactId>
    			<version>${camel-version}</version>
    		</dependency>
    		<dependency>
    			<groupId>org.apache.camel</groupId>
    			<artifactId>camel-spring</artifactId>
    			<version>${camel-version}</version>
    		</dependency>
    		<dependency>
    			<groupId>org.apache.camel</groupId>
    			<artifactId>camel-cxf</artifactId>
    			<version>${camel-version}</version>
    		</dependency>
    		<dependency>
    			<groupId>org.apache.camel</groupId>
    			<artifactId>camel-servlet</artifactId>
    			<version>${camel-version}</version>
    		</dependency>
    		<dependency>
    			<groupId>org.apache.camel</groupId>
    			<artifactId>camel-spring-ws</artifactId>
    			<version>${camel-version}</version>
    		</dependency>
    		<dependency>
    			<groupId>org.apache.camel</groupId>
    			<artifactId>camel-ldap</artifactId>
    			<version>${camel-version}</version>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-core</artifactId>
    			<version>${spring-version}</version>
    		</dependency>
    
    		<!-- cxf -->
    		<!-- regular http transport -->
    		<dependency>
    			<groupId>org.apache.cxf</groupId>
    			<artifactId>cxf-rt-transports-http</artifactId>
    			<version>${cxf-version}</version>
    		</dependency>
    
    		<!-- logging -->
    		<dependency>
    			<groupId>log4j</groupId>
    			<artifactId>log4j</artifactId>
    			<version>${log4j-version}</version>
    		</dependency>
    		<dependency>
    			<groupId>org.slf4j</groupId>
    			<artifactId>slf4j-log4j12</artifactId>
    			<version>${slf4j-version}</version>
    		</dependency>
    
    		<!-- cxf web container for unit testing -->
    		<dependency>
    			<groupId>org.apache.cxf</groupId>
    			<artifactId>cxf-rt-transports-http-jetty</artifactId>
    			<version>${cxf-version}</version>
    		</dependency>
    
    		<!-- spring security for ldap testing -->
    		<dependency>
    			<groupId>org.springframework.security</groupId>
    			<artifactId>spring-security-config</artifactId>
    			<version>${spring-version}</version>
    			<scope>test</scope>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework.security</groupId>
    			<artifactId>spring-security-ldap</artifactId>
    			<version>${spring-version}</version>
    			<scope>test</scope>
    		</dependency>
    		<dependency>
    			<groupId>org.apache.directory.server</groupId>
    			<artifactId>apacheds-all</artifactId>
    			<version>${apacheds-version}</version>
    			<scope>test</scope>
    		</dependency>
    
    		<!-- camel junit -->
    		<dependency>
    			<groupId>junit</groupId>
    			<artifactId>junit</artifactId>
    			<version>${junit-version}</version>
    			<scope>test</scope>
    		</dependency>
    		<dependency>
    			<groupId>org.apache.camel</groupId>
    			<artifactId>camel-test-spring</artifactId>
    			<version>${camel-version}</version>
    			<scope>test</scope>
    		</dependency>
      </dependencies>
    
    ...
    
    

    external by Github  92  0  1  0

    Spring Security configuration generated by http://www.glenware.com/spring-security-generator/ or https://github.com/farrelmr/spring-security-generator

    Spring Security configuration generated by http://www.glenware.com/spring-security-generator/ or https://github.com/farrelmr/spring-security-generator: SecurityConfig.java
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    	@Autowired
    	public void configureGlobal(AuthenticationManagerBuilder auth)
    			throws Exception {
    		auth.
    			inMemoryAuthentication()
                         ;
                         // YOU MUST SUPPLY USERNAMES AND ROLES 
    	}
    
    	
    }
    
    
    

    external by Github  57  0  1  0

    Spring Security configuration generated by http://www.glenware.com/spring-security-generator or https://github.com/farrelmr/spring-security-generator

    Spring Security configuration generated by http://www.glenware.com/spring-security-generator or https://github.com/farrelmr/spring-security-generator: SecurityConfig.java
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    	@Autowired
    	public void configureGlobal(AuthenticationManagerBuilder auth)
    			throws Exception {
    		auth.
    			inMemoryAuthentication()
                         ;
                         // YOU MUST SUPPLY USERNAMES AND ROLES 
    	}
    
    	
    }
    
    
    
    • Public Snippets
    • Channels Snippets